text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* Client-side (UI) code for the LIT tool. */ // tslint:disable:no-new-decorators import '@material/mwc-icon'; import {html} from 'lit'; import {customElement, property} from 'lit/decorators'; import {classMap} from 'lit/directives/class-map'; import {styleMap} from 'lit/directives/style-map'; import {observable} from 'mobx'; import {ReactiveElement} from '../lib/elements'; import {LitRenderConfig, LitTabGroupConfig, RenderConfig} from '../services/modules_service'; import {ModulesService} from '../services/services'; import {app} from './app'; import {LitModule} from './lit_module'; import {styles} from './modules.css'; import {LitWidget, MIN_GROUP_WIDTH_PX} from './widget_group'; // Width of a minimized widget group. From widget_group.css. const MINIMIZED_WIDTH_PX = 38 + 4; /* width + padding */ const COMPONENT_AREA_HPAD = 4; /* padding pixels */ // Contains for each section (main section, or a tab), a mapping of widget // groups to their calculated widths. interface LayoutWidths { [tabName: string]: number[]; } /** * The component responsible for rendering the selected and available lit * modules. This component does not extend from MobxLitElement, as we want * to explicitly control when it rerenders (via the setRenderModulesCallback). */ @customElement('lit-modules') export class LitModules extends ReactiveElement { private readonly modulesService = app.getService(ModulesService); @property({type: Number}) mainSectionHeight = this.modulesService.getSetting('mainHeight') || 45; @observable upperLayoutWidths: LayoutWidths = {}; @observable lowerLayoutWidths: LayoutWidths = {}; private resizeObserver!: ResizeObserver; static override get styles() { return styles; } override firstUpdated() { // We set up a callback in the modulesService to allow it to explicitly // trigger a rerender of this component when visible modules have been // updated by the user. Normally we'd do this in a reactive way, but we'd // like as fine-grain control over layout rendering as possible. this.modulesService.setRenderModulesCallback(() => { this.requestUpdate(); }); const container: HTMLElement = this.shadowRoot!.querySelector('.outer-container')!; this.resizeObserver = new ResizeObserver(() => { const renderLayout = this.modulesService.getRenderLayout(); this.calculateAllWidths(renderLayout); // Set offset for maximized modules. This module doesn't know which // toolbars are present, but we can just find the bounding area // explicitly. const bcr = container.getBoundingClientRect(); container.style.setProperty('--top-toolbar-offset', `${bcr.top}px`); container.style.setProperty('--modules-area-height', `${bcr.height}px`); }); this.resizeObserver.observe(container); this.reactImmediately( () => this.modulesService.getRenderLayout(), renderLayout => { this.calculateAllWidths(renderLayout); }); // Escape key to exit full-screen modules. document.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key === 'Escape') { for (const e of this.shadowRoot!.querySelectorAll( 'lit-widget-group[maximized]')) { e.removeAttribute('maximized'); } } }); } calculateAllWidths(renderLayout: LitRenderConfig) { this.calculateWidths(renderLayout.upper, this.upperLayoutWidths); this.calculateWidths(renderLayout.lower, this.lowerLayoutWidths); } // Calculate widths of all modules in all tabs of a group. calculateWidths(groupLayout: LitTabGroupConfig, layoutWidths: LayoutWidths) { for (const panelName of Object.keys(groupLayout)) { layoutWidths[panelName] = []; // TODO: make this function just return values? this.calculatePanelWidths( panelName, groupLayout[panelName], layoutWidths); } } // Calculate widths of all module groups in a single panel. calculatePanelWidths( panelName: string, panelConfig: RenderConfig[][], layoutWidths: LayoutWidths) { // Get the number of minimized widget groups to calculate the total width // available for non-minimized widgets. let numMinimized = 0; for (const configGroup of panelConfig) { if (this.modulesService.isModuleGroupHidden(configGroup[0])) { numMinimized +=1; } } const containerWidth = this.shadowRoot!.querySelector('.outer-container')! .getBoundingClientRect() .width; const widthAvailable = containerWidth - COMPONENT_AREA_HPAD - MINIMIZED_WIDTH_PX * numMinimized; // Get the total number of columns requested for the non-minimized widget // groups. let totalCols = 0; for (const configGroup of panelConfig) { if (this.modulesService.isModuleGroupHidden(configGroup[0])) { continue; } const numColsList = configGroup.map(config => config.moduleType.numCols); totalCols += Math.max(...numColsList); } // Set the width for each widget group based on the maximum number of // columns it's widgets have specified and the width available. for (let i = 0; i < panelConfig.length; i++) { const configGroup = panelConfig[i]; const numColsList = configGroup.map(config => config.moduleType.numCols); const width = Math.max(...numColsList) / totalCols * widthAvailable; layoutWidths[panelName][i] = width; } } override disconnectedCallback() { super.disconnectedCallback(); // We clear the callback if / when the lit-modules component is removed. this.modulesService.setRenderModulesCallback(() => {}); } override updated() { // Since the widget parent element is responsible for displaying the load // status of its child litModule, and we can't provide a callback to a // dynamically created template string component (in // this.renderModuleWidget), we need to imperatively set a callback on the // child litModule to allow it to set the loading state of its parent // widget. const widgetElements = this.shadowRoot!.querySelectorAll('lit-widget'); widgetElements.forEach(widgetElement => { // Currently, a widget can only contain one LitModule, so we just select // the first child and ensure it's a LitModule. const litModuleElement = widgetElement.children[0]; if (litModuleElement instanceof LitModule) { litModuleElement.setIsLoading = (isLoading: boolean) => { (widgetElement as LitWidget).isLoading = isLoading; }; } }); } override render() { const layout = this.modulesService.getRenderLayout(); const upperGroupNames = Object.keys(layout.upper); const lowerGroupNames = Object.keys(layout.lower); const containerClasses = classMap({ 'outer-container': true, 'outer-container-centered': Boolean(this.modulesService.getSetting('centerPage')), }); // By default, set the selected tab to the first tab. if (this.modulesService.selectedTabUpper === '') { this.modulesService.selectedTabUpper = upperGroupNames[0]; } if (this.modulesService.selectedTabLower === '') { this.modulesService.selectedTabLower = lowerGroupNames[0]; } // If the selected tab doesn't exist, then default to the first tab. const indexOfUpperTab = upperGroupNames.indexOf(this.modulesService.selectedTabUpper); const upperTabToSelect = indexOfUpperTab === -1 ? upperGroupNames[0] : upperGroupNames[indexOfUpperTab]; const indexOfLowerTab = lowerGroupNames.indexOf(this.modulesService.selectedTabLower); const lowerTabToSelect = indexOfLowerTab === -1 ? lowerGroupNames[0] : lowerGroupNames[indexOfLowerTab]; const setUpperTab = (name: string) => { this.modulesService.selectedTabUpper = name; }; const setLowerTab = (name: string) => { this.modulesService.selectedTabLower = name; }; const upperTabsVisible = Object.keys(layout.upper).length > 1; const renderUpperTabBar = () => { // clang-format on return html` <div class='tab-bar'> <div class='tabs-container'> ${this.renderTabs(upperGroupNames, upperTabToSelect, setUpperTab)} </div> </div> </div> `; // clang-format off }; const lowerSectionVisible = Object.keys(layout.lower).length > 0; const upperHeight = lowerSectionVisible ? `${this.mainSectionHeight}vh` : "100%"; const styles = styleMap({ '--upper-height': upperHeight, '--num-tab-bars': `${upperTabsVisible ? 2 : 1}`, }); // clang-format off return html` <div id='outer-container' class=${containerClasses} style=${styles}> ${upperTabsVisible ? renderUpperTabBar() : null} <div id='upper-group-area'> ${this.renderComponentGroups(layout.upper, upperTabToSelect, this.upperLayoutWidths)} </div> ${lowerSectionVisible ? html` <div class='tab-bar' id='center-bar'> <div class='tabs-container'> ${this.renderTabs(lowerGroupNames, lowerTabToSelect, setLowerTab)} </div> <div id='drag-container'> <mwc-icon class="drag-icon">drag_handle</mwc-icon> <div id='drag-handler' draggable='true' @drag=${(e: DragEvent) => {this.onBarDragged(e);}}> </div> </div> </div> <div id='lower-group-area'> ${this.renderComponentGroups(layout.lower, lowerTabToSelect, this.lowerLayoutWidths)} </div> ` : null} </div> `; // clang-format on } private onBarDragged(e: DragEvent) { // TODO(lit-dev): compute this relative to the container, rather than using // vh? const main = this.shadowRoot!.getElementById('upper-group-area')!; const mainTopPos = main.getBoundingClientRect().top; // Sometimes Chrome will fire bad drag events, either at (0,0) // or jumping around a few hundred pixels off from the drag handler. // Detect and ignore these so the UI doesn't get messed up. const handlerBCR = this.shadowRoot!.getElementById( 'drag-handler')!.getBoundingClientRect(); const yOffset = -10; if (e.clientY + yOffset < mainTopPos || e.clientY <= handlerBCR.top - 30 || e.clientY >= handlerBCR.bottom + 30) { console.log('Anomalous drag event; skipping resize', e); return; } this.mainSectionHeight = Math.floor( (e.clientY + yOffset - mainTopPos) / window.innerHeight * 100); } /** * Render the tabbed groups of components. * @param layout Layout to render * @param tabToSelect Tab to show as selected */ renderComponentGroups( layout: LitTabGroupConfig, tabToSelect: string, layoutWidths: LayoutWidths) { return Object.keys(layout).map(tabName => { const configs: RenderConfig[][] = layout[tabName]; const selected = tabToSelect === tabName; const classes = classMap({selected, 'components-group-holder': true}); return html` <div class=${classes}> ${this.renderWidgetGroups(configs, tabName, layoutWidths)} </div>`; }); } /** * Render the tabs of the selection groups at the bottom of the layout. * @param tabNames Names of the tabs to render * @param tabToSelect Tab to show as selected */ renderTabs( tabNames: string[], tabToSelect: string, setTabFn: (name: string) => void) { return tabNames.map((tabName) => { const onclick = (e: Event) => { setTabFn(tabName); e.preventDefault(); // Need to trigger a manual update, since this class does not // respond automatically to mobx observables. this.requestUpdate(); }; const selected = tabToSelect === tabName; const classes = classMap({selected, tab: true}); return html`<div class=${classes} @click=${onclick}>${tabName}</div>`; }); } renderWidgetGroups( configs: RenderConfig[][], section: string, layoutWidths: LayoutWidths) { // Calllback for widget isMinimized state changes. const onMin = (event: Event) => { // Recalculate the widget group widths in this section. this.calculatePanelWidths(section, configs, layoutWidths); }; return configs.map((configGroup, i) => { // Callback from widget width drag events. const onDrag = (event: Event) => { // tslint:disable-next-line:no-any const dragWidth = (event as any).detail.dragWidth; // If the dragged group isn't the right-most group, then balance the // delta in width with the widget directly to it's left (so if a widget // is expanded, then its adjacent widget is shrunk by the same amount). if (i < configs.length - 1) { const adjacentConfig = configs[i + 1]; if (!this.modulesService.isModuleGroupHidden(adjacentConfig[0])) { const widthChange = dragWidth - layoutWidths[section][i]; const oldAdjacentWidth = layoutWidths[section][i + 1]; layoutWidths[section][i + 1] = Math.max(MIN_GROUP_WIDTH_PX, oldAdjacentWidth - widthChange); } } // Set the width of the dragged widget group. layoutWidths[section][i] = dragWidth; this.requestUpdate(); }; const width = layoutWidths[section] ? layoutWidths[section][i] : 0; return html`<lit-widget-group .configGroup=${configGroup} @widget-group-minimized-changed=${onMin} @widget-group-drag=${onDrag} .width=${width}></lit-widget-group>`; }); } } declare global { interface HTMLElementTagNameMap { 'lit-modules': LitModules; } }
the_stack
import { Locale } from '../Locale'; // tslint:disable: no-magic-numbers const MAP: string[] = [ 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th' ]; const lc: Locale = { weekStartsOn: 0, firstWeekContainsDate: 4, am: 'am', pm: 'pm', formatLT: 'h:mm A', formatLTS: 'h:mm:ss A', formatL: 'MM/DD/Y', formatl: 'M/D/Y', formatLL: 'MMMM D, Y', formatll: 'MMM D, Y', formatLLL: 'MMMM D, Y h:mm A', formatlll: 'MMM D, Y h:mm A', formatLLLL: 'dddd, MMMM D, Y h:mm A', formatllll: 'ddd, MMM D, Y h:mm A', suffix: (value: number) => { const TH_SPECIAL_MIN = 11; const TH_SPECIAL_MAX = 13; const suffix = value >= TH_SPECIAL_MIN && value <= TH_SPECIAL_MAX ? 'th' : MAP[ value % MAP.length ]; return value + suffix; }, identifierTime: (short) => short ? 'lll' : 'LLL', identifierDay: (short) => short ? 'll' : 'LL', identifierWeek: (short) => 'wo [week of] Y', identifierMonth: (short) => short ? 'MMM Y' : 'MMMM Y', identifierQuarter: (short) => 'Qo [quarter] Y', identifierYear: (short) => 'Y', patternNone: (day) => 'Does not repeat', patternDaily: (day) => 'Daily', patternWeekly: (day) => 'Weekly on ' + day.format('dddd'), patternMonthlyWeek: (day) => 'Monthly on the ' + lc.suffix(day.weekspanOfMonth + 1) + ' ' + day.format('dddd'), patternAnnually: (day) => 'Annually on ' + day.format('MMMM Do'), patternAnnuallyMonthWeek: (day) => 'Annually on the ' + lc.suffix(day.weekspanOfMonth + 1) + ' ' + day.format('dddd') + ' of ' + day.format('MMMM'), patternWeekday: (day) => 'Every weekday (Monday to Friday)', patternMonthly: (day) => 'Monthly on the ' + day.format('Do') + ' day', patternLastDay: (day) => 'Last day of the month', patternLastDayOfMonth: (day) => 'Last day of ' + day.format('MMMM'), patternLastWeekday: (day) => 'Last ' + day.format('dddd') + ' in ' + day.format('MMMM'), patternCustom: (day) => 'Custom...', scheduleStartingOn: (start) => 'Starting on ' + start.format('MMMM Do, YYYY'), scheduleEndingOn: (end) => ' and ending on ' + end.format('MMMM Do, YYYY'), scheduleEndsOn: (end) => 'Up until ' + end.format('MMMM Do, YYYY'), scheduleThing: (thing, start) => start ? 'The ' + thing + ' will occur' : ' the ' + thing + ' will occur', scheduleAtTimes: ' at ', scheduleDuration: (duration, unit) => ' lasting ' + duration + ' ' + (unit ? unit + (duration !== 1 ? 's' : '') + ' ' : ''), scheduleExcludes: ' excluding ', scheduleIncludes: ' including ', scheduleCancels: ' with cancellations on ', ruleDayOfWeek: { // every 2nd day of the week every: (every) => `every ${lc.suffix(every)} day of the week`, // starting on the 5th day of the week offset: (offset) => `starting on the ${lc.suffix(offset)} day of the week`, // on the 1st, 2nd, and 4th day of the week oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} day of the week` }, ruleLastDayOfMonth: { // every 3rd last day of the month every: (every) => `every ${lc.suffix(every)} last day of the month`, // starting on the 2nd last day of the month offset: (offset) => `starting on the ${lc.suffix(offset)} last day of the month`, // on the 1st, 2nd, and 3rd last day of the month oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} last day of the month` }, ruleDayOfMonth: { // every 3rd day of the month every: (every) => `every ${lc.suffix(every)} day of the month`, // starting on the 2nd day of the month offset: (offset) => `starting on the ${lc.suffix(offset)} day of the month`, // on the 1st, 2nd, and 3rd day of the month oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} day of the month` }, ruleDayOfYear: { // every 3rd day of the year every: (every) => `every ${lc.suffix(every)} day of the year`, // starting on the 2nd day of the year offset: (offset) => `starting on the ${lc.suffix(offset + 1)} day of the year`, // on the 1st, 2nd, and 3rd day of the year oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} day of the year` }, ruleYear: { // every 3rd year every: (every) => `every ${lc.suffix(every)} year`, // starting in 2018 offset: (offset) => `starting in ${offset}`, // in 2019, 2020, and 2021 oneOf: (values) => `in ${lc.list(values.map(x => x.toString()))}` }, ruleMonth: { // every 3rd month every: (every) => `every ${lc.suffix(every)} month`, // starting in February offset: (offset) => `starting in ${lc.months[0][offset]}`, // in February, May, and June oneOf: (values) => `in ${lc.list(values.map(x => lc.months[0][x]))}` }, ruleDay: { // every 2nd day of the week every: (every) => `every ${lc.suffix(every)} day of the week`, // starting on Tuesday offset: (offset) => `starting on ${lc.weekdays[0][offset]}`, // on Monday, Wednesday, and Friday oneOf: (values) => `on ${lc.list(values.map(v => lc.weekdays[0][v]))}` }, ruleWeek: { // every 3rd week of the year every: (every) => `every ${lc.suffix(every)} week of the year`, // starting on the 2nd week of the year offset: (offset) => `starting on the ${lc.suffix(offset)} week of the year`, // on the 1st, 2nd, and 3rd week of the year oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} week of the year` }, ruleWeekOfYear: { // every 3rd week of the year every: (every) => `every ${lc.suffix(every)} week of the year`, // starting on the 2nd week of the year offset: (offset) => `starting on the ${lc.suffix(offset)} week of the year`, // on the 1st, 2nd, and 3rd week of the year oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} week of the year` }, ruleWeekspanOfYear: { // every 3rd weekspan of the year every: (every) => `every ${lc.suffix(every + 1)} weekspan of the year`, // starting on the 2nd weekspan of the year offset: (offset) => `starting on the ${lc.suffix(offset + 1)} weekspan of the year`, // on the 1st, 2nd, and 3rd weekspan of the year oneOf: (values) => `on the ${lc.list(values.map(x => lc.suffix(x + 1)))} weekspan of the year` }, ruleFullWeekOfYear: { // every 3rd full week of the year every: (every) => `every ${lc.suffix(every)} full week of the year`, // starting on the 2nd full week of the year offset: (offset) => `starting on the ${lc.suffix(offset)} full week of the year`, // on the 1st, 2nd, and 3rd full week of the year oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} full week of the year` }, ruleLastWeekspanOfYear: { // every 3rd last weekspan of the year every: (every) => `every ${lc.suffix(every + 1)} last weekspan of the year`, // starting on the 2nd last weekspan of the year offset: (offset) => `starting on the ${lc.suffix(offset + 1)} last weekspan of the year`, // on the 1st, 2nd, and 3rd last weekspan of the year oneOf: (values) => `on the ${lc.list(values.map(x => lc.suffix(x + 1)))} last weekspan of the year` }, ruleLastFullWeekOfYear: { // every 3rd last full week of the year every: (every) => `every ${lc.suffix(every)} last full week of the year`, // starting on the 2nd last full week of the year offset: (offset) => `starting on the ${lc.suffix(offset)} last full week of the year`, // on the 1st, 2nd, and 3rd last full week of the year oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} last full week of the year` }, ruleWeekOfMonth: { // every 3rd week of the month every: (every) => `every ${lc.suffix(every)} week of the month`, // starting on the 2nd week of the month offset: (offset) => `starting on the ${lc.suffix(offset)} week of the month`, // on the 1st, 2nd, and 3rd week of the month oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} week of the month` }, ruleFullWeekOfMonth: { // every 3rd full week of the month every: (every) => `every ${lc.suffix(every)} full week of the month`, // starting on the 2nd full week of the month offset: (offset) => `starting on the ${lc.suffix(offset)} full week of the month`, // on the 1st, 2nd, and 3rd full week of the month oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} full week of the month` }, ruleWeekspanOfMonth: { // every 3rd weekspan of the month every: (every) => `every ${lc.suffix(every + 1)} weekspan of the month`, // starting on the 2nd weekspan of the month offset: (offset) => `starting on the ${lc.suffix(offset + 1)} weekspan of the month`, // on the 1st, 2nd, and 3rd weekspan of the month oneOf: (values) => `on the ${lc.list(values.map(x => lc.suffix(x + 1)))} weekspan of the month` }, ruleLastFullWeekOfMonth: { // every 3rd last full week of the month every: (every) => `every ${lc.suffix(every)} last full week of the month`, // starting on the 2nd last full week of the month offset: (offset) => `starting on the ${lc.suffix(offset)} last full week of the month`, // on the 1st, 2nd, and 3rd full week of the month oneOf: (values) => `on the ${lc.list(values.map(lc.suffix))} last full week of the month` }, ruleLastWeekspanOfMonth: { // every 3rd last weekspan of the month every: (every) => `every ${lc.suffix(every + 1)} last weekspan of the month`, // starting on the 2nd last weekspan of the month offset: (offset) => `starting on the ${lc.suffix(offset + 1)} last weekspan of the month`, // on the 1st, 2nd, and 3rd last weekspan of the month oneOf: (values) => `on the ${lc.list(values.map(x => lc.suffix(x + 1)))} last weekspan of the month` }, summaryDay: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd, ' : 'dddd, ') : '') + (short ? 'MMM ' : 'MMMM ') + 'Do' + (year ? ' YYYY' : ''), summaryWeek: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd, ' : 'dddd, ') : '') + (short ? 'MMM ' : 'MMMM ') + 'Do' + (year ? ' YYYY' : ''), summaryMonth: (short, dayOfWeek, year) => (short ? 'MMM' : 'MMMM') + (year ? ' YYYY' : ''), summaryYear: (short, dayOfWeek, year) => (year ? 'YYYY' : ''), list: (items) => { const last: number = items.length - 1; let out: string = items[0]; for (let i = 1; i < last; i++) { out += ', ' + items[i]; } if (last > 0) { out += ' and ' + items[last]; } return out; }, months: [ ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], ['Ja', 'F', 'Mr', 'Ap', 'My', 'Je', 'Jl', 'Ag', 'S', 'O', 'N', 'D'] ], weekdays: [ ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Su', 'M', 'Tu', 'W', 'Th', 'F', 'Sa'], ], }; export default lc;
the_stack
import { CognitoJwtInvalidClientIdError, CognitoJwtInvalidGroupError, CognitoJwtInvalidTokenUseError, JwtInvalidClaimError, ParameterValidationError, } from "./error.js"; import { JwtRsaVerifierBase, JwtRsaVerifierProperties } from "./jwt-rsa.js"; import { JwksCache, Jwks, Jwk } from "./jwk.js"; import { JwtHeader, JwtPayload, CognitoIdOrAccessTokenPayload, } from "./jwt-model.js"; import { assertStringArrayContainsString, assertStringEquals, assertStringArraysOverlap, } from "./assert.js"; import { Properties } from "./typing-util.js"; export interface CognitoVerifyProperties { /** * The client ID that you expect to be present on the JWT * (In the ID token's aud claim, or the Access token's client_id claim). * If you provide a string array, that means at least one of those client IDs * must be present on the JWT. * Pass null explicitly to not check the JWT's client ID--if you know what you're doing */ clientId: string | string[] | null; /** * The token use that you expect to be present in the JWT's token_use claim. * Usually you are verifying either Access token (common) or ID token (less common). * Pass null explicitly to not check the JWT's token use--if you know what you're doing */ tokenUse: "id" | "access" | null; /** * The group that you expect to be present in the JWT's "cognito:groups" claim. * If you provide a string array, that means at least one of those groups * must be present in the JWT's "cognito:groups" claim. */ groups?: string | string[] | null; /** * The scope that you expect to be present in the JWT's scope claim. * If you provide a string array, that means at least one of those scopes * must be present in the JWT's scope claim. */ scope?: string | string[] | null; /** * The number of seconds after expiration (exp claim) or before not-before (nbf claim) that you will allow * (use this to account for clock differences between systems) */ graceSeconds?: number; /** * Your custom function with checks. It will be called, at the end of the verification, * after standard verifcation checks have all passed. * Throw an error in this function if you want to reject the JWT for whatever reason you deem fit. * Your function will be called with a properties object that contains: * - the decoded JWT header * - the decoded JWT payload * - the JWK that was used to verify the JWT's signature */ customJwtCheck?: (props: { header: JwtHeader; payload: JwtPayload; jwk: Jwk; }) => Promise<void> | void; /** * If you want to peek inside the invalid JWT when verification fails, set `includeRawJwtInErrors` to true. * Then, if an error is thrown during verification of the invalid JWT (e.g. the JWT is invalid because it is expired), * the Error object will include a property `rawJwt`, with the raw decoded contents of the **invalid** JWT. * The `rawJwt` will only be included in the Error object, if the JWT's signature can at least be verified. */ includeRawJwtInErrors?: boolean; } /** Type for Cognito JWT verifier properties, for a single User Pool */ export type CognitoJwtVerifierProperties = { /** The User Pool whose JWTs you want to verify */ userPoolId: string; } & Partial<CognitoVerifyProperties>; /** * Type for Cognito JWT verifier properties, when multiple User Pools are used in the verifier. * In this case, you should be explicit in mapping `clientId` to User Pool. */ export type CognitoJwtVerifierMultiProperties = { /** The User Pool whose JWTs you want to verify */ userPoolId: string; } & CognitoVerifyProperties; /** * Cognito JWT Verifier for a single user pool */ export type CognitoJwtVerifierSingleUserPool< T extends CognitoJwtVerifierProperties > = CognitoJwtVerifier< Properties<CognitoVerifyProperties, T>, T & JwtRsaVerifierProperties<CognitoVerifyProperties> & { userPoolId: string; audience: null; }, false >; /** * Cognito JWT Verifier for multiple user pools */ export type CognitoJwtVerifierMultiUserPool< T extends CognitoJwtVerifierMultiProperties > = CognitoJwtVerifier< Properties<CognitoVerifyProperties, T>, T & JwtRsaVerifierProperties<CognitoVerifyProperties> & { userPoolId: string; audience: null; }, true >; /** * Parameters used for verification of a JWT. * The first parameter is the JWT, which is (of course) mandatory. * The second parameter is an object with specific properties to use during verification. * The second parameter is only mandatory if its mandatory members (e.g. client_id) were not * yet provided at verifier level. In that case, they must now be provided. */ type CognitoVerifyParameters<SpecificVerifyProperties> = { [key: string]: never; } extends SpecificVerifyProperties ? [jwt: string, props?: SpecificVerifyProperties] : [jwt: string, props: SpecificVerifyProperties]; /** * Validate claims of a decoded Cognito JWT. * This function throws an error in case there's any validation issue. * * @param payload - The JSON parsed payload of the Cognito JWT * @param options - Validation options * @param options.groups - The cognito groups, of which at least one must be present in the JWT's cognito:groups claim * @param options.tokenUse - The required token use of the JWT: "id" or "access" * @param options.clientId - The required clientId of the JWT. May be an array of string, of which at least one must match * @returns void */ export function validateCognitoJwtFields( payload: JwtPayload, options: { groups?: string | string[] | null; tokenUse?: "id" | "access" | null; clientId?: string | string[] | null; } ): void { // Check groups if (options.groups != null) { assertStringArraysOverlap( "Cognito group", payload["cognito:groups"], options.groups, CognitoJwtInvalidGroupError ); } // Check token use assertStringArrayContainsString( "Token use", payload.token_use, ["id", "access"] as const, CognitoJwtInvalidTokenUseError ); if (options.tokenUse !== null) { if (options.tokenUse === undefined) { throw new ParameterValidationError( "tokenUse must be provided or set to null explicitly" ); } assertStringEquals( "Token use", payload.token_use, options.tokenUse, CognitoJwtInvalidTokenUseError ); } // Check clientId aka audience if (options.clientId !== null) { if (options.clientId === undefined) { throw new ParameterValidationError( "clientId must be provided or set to null explicitly" ); } if (payload.token_use === "id") { assertStringArrayContainsString( 'Client ID ("audience")', payload.aud, options.clientId, CognitoJwtInvalidClientIdError ); } else { assertStringArrayContainsString( "Client ID", payload.client_id, options.clientId, CognitoJwtInvalidClientIdError ); } } } /** * Class representing a verifier for JWTs signed by Amazon Cognito */ export class CognitoJwtVerifier< SpecificVerifyProperties extends Partial<CognitoVerifyProperties>, IssuerConfig extends JwtRsaVerifierProperties<SpecificVerifyProperties> & { userPoolId: string; audience: null; }, MultiIssuer extends boolean > extends JwtRsaVerifierBase< SpecificVerifyProperties, IssuerConfig, MultiIssuer > { private constructor( props: CognitoJwtVerifierProperties | CognitoJwtVerifierMultiProperties[], jwksCache?: JwksCache ) { const issuerConfig = Array.isArray(props) ? (props.map((p) => ({ ...p, ...CognitoJwtVerifier.parseUserPoolId(p.userPoolId), audience: null, // checked instead by validateCognitoJwtFields })) as IssuerConfig[]) : ({ ...props, ...CognitoJwtVerifier.parseUserPoolId(props.userPoolId), audience: null, // checked instead by validateCognitoJwtFields } as IssuerConfig); super(issuerConfig, jwksCache); } /** * Parse a User Pool ID, to extract the issuer and JWKS URI * * @param userPoolId The User Pool ID * @returns The issuer and JWKS URI for the User Pool */ public static parseUserPoolId(userPoolId: string): { issuer: string; jwksUri: string; } { // Disable safe regexp check as userPoolId is provided by developer, i.e. is not user input // eslint-disable-next-line security/detect-unsafe-regex const match = userPoolId.match(/^(?<region>(\w+-)?\w+-\w+-\d)+_\w+$/); if (!match) { throw new ParameterValidationError( `Invalid Cognito User Pool ID: ${userPoolId}` ); } const region = match.groups!.region; const issuer = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`; return { issuer, jwksUri: `${issuer}/.well-known/jwks.json`, }; } /** * Create a Cognito JWT verifier for a single User Pool * * @param verifyProperties The verification properties for your User Pool * @param additionalProperties Additional properties * @param additionalProperties.jwksCache Overriding JWKS cache that you want to use * @returns An Cognito JWT Verifier instance, that you can use to verify Cognito signed JWTs with */ static create<T extends CognitoJwtVerifierProperties>( verifyProperties: T & Partial<CognitoJwtVerifierProperties>, additionalProperties?: { jwksCache: JwksCache } ): CognitoJwtVerifierSingleUserPool<T>; /** * Create a Cognito JWT verifier for multiple User Pools * * @param verifyProperties An array of verification properties, one for each User Pool * @param additionalProperties Additional properties * @param additionalProperties.jwksCache Overriding JWKS cache that you want to use * @returns An Cognito JWT Verifier instance, that you can use to verify Cognito signed JWTs with */ static create<T extends CognitoJwtVerifierMultiProperties>( props: (T & Partial<CognitoJwtVerifierMultiProperties>)[], additionalProperties?: { jwksCache: JwksCache } ): CognitoJwtVerifierMultiUserPool<T>; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types static create( verifyProperties: | CognitoJwtVerifierProperties | CognitoJwtVerifierMultiProperties[], additionalProperties?: { jwksCache: JwksCache } ) { return new this(verifyProperties, additionalProperties?.jwksCache); } /** * Verify (synchronously) a JWT that is signed by Amazon Cognito. * * @param jwt The JWT, as string * @param props Verification properties * @returns The payload of the JWT––if the JWT is valid, otherwise an error is thrown */ public verifySync<T extends SpecificVerifyProperties>( ...[jwt, properties]: CognitoVerifyParameters<SpecificVerifyProperties> ): CognitoIdOrAccessTokenPayload<IssuerConfig, T> { const { decomposedJwt, jwksUri, verifyProperties } = this.getVerifyParameters(jwt, properties); this.verifyDecomposedJwtSync(decomposedJwt, jwksUri, verifyProperties); try { validateCognitoJwtFields(decomposedJwt.payload, verifyProperties); } catch (err) { if ( verifyProperties.includeRawJwtInErrors && err instanceof JwtInvalidClaimError ) { throw err.withRawJwt(decomposedJwt); } throw err; } return decomposedJwt.payload as CognitoIdOrAccessTokenPayload< IssuerConfig, T >; } /** * Verify (asynchronously) a JWT that is signed by Amazon Cognito. * This call is asynchronous, and the JWKS will be fetched from the JWKS uri, * in case it is not yet available in the cache. * * @param jwt The JWT, as string * @param props Verification properties * @returns Promise that resolves to the payload of the JWT––if the JWT is valid, otherwise the promise rejects */ public async verify<T extends SpecificVerifyProperties>( ...[jwt, properties]: CognitoVerifyParameters<SpecificVerifyProperties> ): Promise<CognitoIdOrAccessTokenPayload<IssuerConfig, T>> { const { decomposedJwt, jwksUri, verifyProperties } = this.getVerifyParameters(jwt, properties); await this.verifyDecomposedJwt(decomposedJwt, jwksUri, verifyProperties); try { validateCognitoJwtFields(decomposedJwt.payload, verifyProperties); } catch (err) { if ( verifyProperties.includeRawJwtInErrors && err instanceof JwtInvalidClaimError ) { throw err.withRawJwt(decomposedJwt); } throw err; } return decomposedJwt.payload as CognitoIdOrAccessTokenPayload< IssuerConfig, T >; } /** * This method loads a JWKS that you provide, into the JWKS cache, so that it is * available for JWT verification. Use this method to speed up the first JWT verification * (when the JWKS would otherwise have to be downloaded from the JWKS uri), or to provide the JWKS * in case the JwtVerifier does not have internet access to download the JWKS * * @param jwks The JWKS * @param userPoolId The userPoolId for which you want to cache the JWKS * Supply this field, if you instantiated the CognitoJwtVerifier with multiple userPoolIds * @returns void */ public cacheJwks( ...[jwks, userPoolId]: MultiIssuer extends false ? [jwks: Jwks, userPoolId?: string] : [jwks: Jwks, userPoolId: string] ): void { let issuer: string | undefined; if (userPoolId !== undefined) { issuer = CognitoJwtVerifier.parseUserPoolId(userPoolId).issuer; } else if (this.expectedIssuers.length > 1) { throw new ParameterValidationError("userPoolId must be provided"); } const issuerConfig = this.getIssuerConfig(issuer); super.cacheJwks(jwks, issuerConfig.issuer); } }
the_stack
import { jsx, css } from "@emotion/core"; import * as React from "react"; import { animated, useSpring, SpringConfig } from "react-spring"; import { useFocusElement } from "./Hooks/use-focus-trap"; import { Portal } from "./Portal"; import PropTypes from "prop-types"; import { RemoveScroll } from "react-remove-scroll"; import { useTheme } from "./Theme/Providers"; import { Theme } from "./Theme"; import { useMeasure, Bounds } from "./Hooks/use-measure"; import { usePrevious } from "./Hooks/previous"; import { useHideBody } from "./Hooks/hide-body"; import { useGestureResponder, StateType } from "react-gesture-responder"; export const RequestCloseContext = React.createContext(() => { }); const positions = (theme: Theme) => ({ left: css` top: 0; left: 0; bottom: 0; width: auto; max-width: 100vw; ${theme.mediaQueries.md} { max-width: 400px; } &::before { content: ""; position: fixed; width: 100vw; top: 0; background: ${theme.colors.background.layer}; bottom: 0; right: 100%; } `, right: css` top: 0; right: 0; bottom: 0; width: auto; max-width: 100vw; ${theme.mediaQueries.md} { max-width: 400px; } &::after { content: ""; position: fixed; width: 100vw; top: 0; left: 100%; background: ${theme.colors.background.layer}; bottom: 0; } `, bottom: css` bottom: 0; left: 0; right: 0; height: auto; width: 100%; padding: 0; box-sizing: border-box; ${theme.mediaQueries.md} { max-height: 400px; } & > div { border-top-right-radius: ${theme.radii.lg}; border-top-left-radius: ${theme.radii.lg}; padding-bottom: ${theme.spaces.lg}; padding-top: ${theme.spaces.xs}; } &::before { content: ""; position: fixed; height: 100vh; left: 0; right: 0; background: ${theme.colors.background.layer}; top: 100%; } `, top: css` top: 0; left: 0; right: 0; height: auto; width: 100%; padding: 0; box-sizing: border-box; ${theme.mediaQueries.md} { max-height: 400px; } & > div { border-bottom-right-radius: ${theme.radii.lg}; border-bottom-left-radius: ${theme.radii.lg}; padding-bottom: ${theme.spaces.xs}; padding-top: ${theme.spaces.md}; } &::before { content: ""; position: fixed; height: 100vh; left: 0; right: 0; background: ${theme.colors.background.layer}; transform: translateY(-100%); } ` }); export type SheetPositions = "left" | "top" | "bottom" | "right"; export interface SheetProps { /** Whether the sheet is visible */ isOpen: boolean; /** A callback to handle closing the sheet */ onRequestClose: () => void; role?: string; children: React.ReactNode; /** * The position of the sheet. * 'left' is typically used for navigation, * 'right' for additional information, * 'bottom' for responsive modal popovers. */ position: SheetPositions; /** spring animation configuration */ animationConfig?: SpringConfig; } /** * A sheet is useful for displaying app based navigation (typically on the left), * supplemental information (on the right), or menu options (typically * from the bottom on mobile devices). * * Sheets should not be tied to specific URLs. */ export const Sheet: React.FunctionComponent<SheetProps> = ({ isOpen, children, animationConfig = { mass: 0.8, tension: 185, friction: 24 }, position = "right", onRequestClose, ...props }) => { const theme = useTheme(); const [mounted, setMounted] = React.useState(false); const ref = React.useRef<HTMLDivElement | null>(null); useFocusElement(ref, isOpen); const { bounds } = useMeasure(ref); const previousBounds = usePrevious(bounds); const positionsStyle = React.useMemo(() => positions(theme), [theme]); const initialDirection = React.useRef<"vertical" | "horizontal" | null>(null); const { bind: bindHideBody } = useHideBody(isOpen); const startVelocity = React.useRef<number | null>(null); const [visible, setVisible] = React.useState(isOpen); const isOpenRef = React.useRef(isOpen); // this is a weird-ass hack to allow us to access isOpen // state within our onRest callback. Closures!! React.useEffect(() => { isOpenRef.current = isOpen; }, [isOpen]); // A spring which animates the sheet position const [{ xy }, setSpring] = useSpring(() => { const { x, y } = getDefaultPositions(isOpen, position); return { xy: [x, y], config: animationConfig, onStart: () => { setVisible(true); }, onRest: () => { if (!isOpenRef.current) { setVisible(false); } } }; }); // A spring which animates the overlay opacity const [{ opacity }, setOpacity] = useSpring(() => { return { opacity: isOpen ? 1 : 0, config: animationConfig }; }); /** * Handle gestures */ // our overlay pan responder const { bind: bindTouchable } = useGestureResponder({ onStartShouldSet: () => true, onRelease: ({ initial, xy }) => { // ignore swipes on release if (initial[0] === xy[0] && initial[1] === xy[1]) { setTimeout(() => onRequestClose(), 0); } } }); function onEnd(state: StateType) { const close = shouldCloseOnRelease(state, bounds, position); if (close) { onRequestClose(); return; } animateToPosition(); } // our main sheet pan responder const { bind } = useGestureResponder( { onStartShouldSet: () => { initialDirection.current = null; return false; }, onMoveShouldSet: ({ initial, xy }) => { // we lock in the direction when it's first provided const gestureDirection = initialDirection.current || getDirection(initial, xy); if (!initialDirection.current) { initialDirection.current = gestureDirection; } if ( gestureDirection === "horizontal" && (position === "left" || position === "right") ) { return true; } else if ( gestureDirection === "vertical" && (position === "top" || position === "bottom") ) { return true; } return false; }, onRelease: (state: StateType) => { startVelocity.current = state.velocity; onEnd(state); }, onTerminate: onEnd, onMove: state => { const { x, y } = getDragCoordinates(state, position); const opacity = getDragOpacity(state, bounds, position); setSpring({ xy: [x, y], immediate: true, config: animationConfig }); setOpacity({ opacity }); } }, { enableMouse: false } ); /** * Animate the sheet to open / close position * depending on position and state. * @param immediate */ const animateToPosition = React.useCallback( (immediate = false) => { // when the user makes the gesture to close we start // our animation with their last velocity const { width, height } = bounds; const velocity = startVelocity.current; startVelocity.current = null; const { x, y } = getDefaultPositions(isOpen, position, width, height); setSpring({ config: { ...animationConfig, velocity: velocity || 0 }, xy: [x, y], immediate }); setOpacity({ opacity: isOpen ? 1 : 0 }); }, [animationConfig, bounds, isOpen, position, setOpacity, setSpring] ); /** * Handle close / open non-gestured controls */ React.useEffect(() => { const { width } = bounds; // a bit of a hack to prevent the sheet from being // displayed at the wrong position before properly // measuring it. const hasMounted = previousBounds && previousBounds.width === 0 && width !== 0; if (hasMounted && !mounted) { setMounted(true); } animateToPosition(!mounted); }, [animateToPosition, position, mounted, bounds, previousBounds, isOpen]); /** * Convert our positions to translate3d */ const interpolate = (x: number, y: number) => { return `translate3d(${taper(x, position)}px, ${taper(y, position)}px, 0)`; }; return ( <Portal> <div {...bindHideBody} aria-hidden={!isOpen} {...bind} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); onRequestClose(); } }} css={{ bottom: 0, left: 0, overflow: "auto", width: "100vw", height: "100vh", pointerEvents: isOpen ? "auto" : "none", visible: visible ? "visible" : "hidden", zIndex: theme.zIndices.overlay, position: "fixed", content: "''", right: 0, top: 0, WebkitTapHighlightColor: "transparent" }} > <animated.div style={{ opacity }} {...bindTouchable} css={{ touchAction: "none", position: "absolute", willChange: "opacity", top: 0, left: 0, pointerEvents: isOpen ? "auto" : "none", right: 0, bottom: 0, background: theme.colors.background.overlay }} /> <animated.div tabIndex={-1} ref={ref} className="Sheet" onClick={e => { e.stopPropagation(); }} style={{ transform: xy.interpolate(interpolate as any) as any }} css={[ { willChange: "transform", visibility: visible ? "visible" : "hidden", outline: "none", zIndex: theme.zIndices.modal, opacity: 1, position: "fixed" }, positionsStyle[position] ]} {...props} > <RequestCloseContext.Provider value={onRequestClose}> <RemoveScroll enabled={isOpen} forwardProps> <div className="Sheet__container" css={{ background: theme.colors.background.layer, height: "100%" }} > {children} </div> </RemoveScroll> </RequestCloseContext.Provider> </animated.div> </div> </Portal> ); }; Sheet.propTypes = { isOpen: PropTypes.bool, onRequestClose: PropTypes.func, children: PropTypes.node, position: PropTypes.oneOf(["left", "top", "right", "bottom"]), animationConfig: PropTypes.shape({ tension: PropTypes.number, mass: PropTypes.number, friction: PropTypes.number }) }; /** * Determine the sheet location given * its position and the gesture input */ function getDragCoordinates({ delta }: StateType, position: SheetPositions) { const [dx, dy] = delta; switch (position) { case "left": case "right": return { x: dx, y: 0 }; case "top": case "bottom": return { y: dy, x: 0 }; } } /** * Determine if the sheet should close on * release given a position. */ function shouldCloseOnRelease( { delta, velocity, direction }: StateType, { width, height }: Bounds, position: SheetPositions ) { const [dx, dy] = delta; switch (position) { case "left": { // quick swipe if (velocity > 0.2 && direction[0] < 0) { return true; } if (dx < 0 && Math.abs(dx) > width / 2) { return true; } return false; } case "top": { if (velocity > 0.2 && direction[1] <= -1) { return true; } if (dy < 0 && Math.abs(dy) > height / 2) { return true; } return false; } case "right": { if (velocity > 0.2 && direction[0] >= 1) { return true; } if (dx > 0 && Math.abs(dx) > width / 2) { return true; } return false; } case "bottom": { if (velocity > 0.2 && direction[1] > 0) { return true; } if (dy > 0 && Math.abs(dy) > height / 2) { return true; } return false; } } } /** * Determine the overlay opacity */ function getDragOpacity( { delta }: StateType, { width, height }: Bounds, position: SheetPositions ) { const [dx, dy] = delta; switch (position) { case "left": { return dx < 0 ? 1 - Math.abs(dx) / width : 1; } case "top": { return dy < 0 ? 1 - Math.abs(dy) / height : 1; } case "right": { return dx > 0 ? 1 - Math.abs(dx) / width : 1; } case "bottom": { return dy > 0 ? 1 - Math.abs(dy) / height : 1; } } } /** * Determine the default x, y position * for the various positions */ function getDefaultPositions( isOpen: boolean, position: SheetPositions, width: number = 400, height: number = 400 ) { switch (position) { case "left": { return { x: isOpen ? 0 : -width, y: 0 }; } case "top": { return { x: 0, y: isOpen ? 0 : -height }; } case "right": { return { x: isOpen ? 0 : width, y: 0 }; } case "bottom": { return { x: 0, y: isOpen ? 0 : height }; } } } /** * Add friction to the sheet position if it's * moving inwards * @param x */ function taper(x: number, position: SheetPositions) { if (position === "left" || position === "top") { if (x <= 0) { return x; } return x * 0.4; } if (x >= 0) { return x; } return x * 0.4; } /** * Compare two positions and determine the direction * the gesture is moving (horizontal or vertical) * * If the difference is the same, return null. This happends * when only a click is registered. * * @param initial * @param xy */ export function getDirection(initial: [number, number], xy: [number, number]) { const xDiff = Math.abs(initial[0] - xy[0]); const yDiff = Math.abs(initial[1] - xy[1]); // just a regular click if (xDiff === yDiff) { return null; } if (xDiff > yDiff) { return "horizontal"; } return "vertical"; }
the_stack
import { RuntimeError } from './util'; import { Element } from './element'; import { Flow } from './flow'; import { RenderContext } from './rendercontext'; import { StaveNote } from './stavenote'; import { FontInfo } from './types/common'; export interface StaveLineNotes { first_note: StaveNote; first_indices: number[]; last_note: StaveNote; last_indices: number[]; } // Attribution: Arrow rendering implementations based off of // Patrick Horgan's article, "Drawing lines and arcs with // arrow heads on HTML5 Canvas" // // Draw an arrow head that connects between 3 coordinates. function drawArrowHead( ctx: RenderContext, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number ): void { // all cases do this. ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x0, y0); ctx.closePath(); ctx.fill(); } export class StaveLine extends Element { static get CATEGORY(): string { return 'StaveLine'; } // Text Positioning static readonly TextVerticalPosition = { TOP: 1, BOTTOM: 2, }; static readonly TextJustification = { LEFT: 1, CENTER: 2, RIGHT: 3, }; public render_options: { padding_left: number; padding_right: number; line_width: number; line_dash?: number[]; rounded_end: boolean; color?: string; draw_start_arrow: boolean; draw_end_arrow: boolean; arrowhead_length: number; arrowhead_angle: number; text_position_vertical: number; text_justification: number; }; protected text: string; protected font: FontInfo; // These five instance variables are all initialized by the constructor via this.setNotes(notes). protected notes!: StaveLineNotes; protected first_note!: StaveNote; protected first_indices!: number[]; protected last_note!: StaveNote; protected last_indices!: number[]; // Initialize the StaveLine with the given `notes`. // // `notes` is a struct that has: // // ``` // { // first_note: Note, // last_note: Note, // first_indices: [n1, n2, n3], // last_indices: [n1, n2, n3] // } // ``` constructor(notes: StaveLineNotes) { super(); this.setNotes(notes); this.text = ''; this.font = { family: 'Arial', size: 10, weight: '', }; this.render_options = { // Space to add to the left or the right padding_left: 4, padding_right: 3, // The width of the line in pixels line_width: 1, // An array of line/space lengths. (TODO/QUESTION: Is this supported in SVG?). line_dash: undefined, // Can draw rounded line end, instead of a square. (TODO/QUESTION: Is this supported in SVG?). rounded_end: true, // The color of the line and arrowheads color: undefined, // Flags to draw arrows on each end of the line draw_start_arrow: false, draw_end_arrow: false, // The length of the arrowhead sides arrowhead_length: 10, // The angle of the arrowhead arrowhead_angle: Math.PI / 8, // The position of the text text_position_vertical: StaveLine.TextVerticalPosition.TOP, text_justification: StaveLine.TextJustification.CENTER, }; } // Set the font for the `StaveLine` text setFont(font: FontInfo): this { this.font = font; return this; } // The the annotation for the `StaveLine` setText(text: string): this { this.text = text; return this; } // Set the notes for the `StaveLine` setNotes(notes: StaveLineNotes): this { if (!notes.first_note && !notes.last_note) { throw new RuntimeError('BadArguments', 'Notes needs to have either first_note or last_note set.'); } if (!notes.first_indices) notes.first_indices = [0]; if (!notes.last_indices) notes.last_indices = [0]; if (notes.first_indices.length !== notes.last_indices.length) { throw new RuntimeError('BadArguments', 'Connected notes must have same number of indices.'); } this.notes = notes; this.first_note = notes.first_note; this.first_indices = notes.first_indices; this.last_note = notes.last_note; this.last_indices = notes.last_indices; return this; } // Apply the style of the `StaveLine` to the context applyLineStyle(): void { const ctx = this.checkContext(); const render_options = this.render_options; if (render_options.line_dash) { ctx.setLineDash(render_options.line_dash); } if (render_options.line_width) { ctx.setLineWidth(render_options.line_width); } if (render_options.rounded_end) { ctx.setLineCap('round'); } else { ctx.setLineCap('square'); } } // Apply the text styling to the context applyFontStyle(): void { const ctx = this.checkContext(); if (this.font) { ctx.setFont(this.font.family, this.font.size, this.font.weight); } const render_options = this.render_options; const color = render_options.color; if (color) { ctx.setStrokeStyle(color); ctx.setFillStyle(color); } } // Helper function to draw a line with arrow heads protected drawArrowLine(ctx: RenderContext, pt1: { x: number; y: number }, pt2: { x: number; y: number }): void { const both_arrows = this.render_options.draw_start_arrow && this.render_options.draw_end_arrow; const x1 = pt1.x; const y1 = pt1.y; const x2 = pt2.x; const y2 = pt2.y; // For ends with arrow we actually want to stop before we get to the arrow // so that wide lines won't put a flat end on the arrow. const distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); const ratio = (distance - this.render_options.arrowhead_length / 3) / distance; let end_x; let end_y; let start_x; let start_y; if (this.render_options.draw_end_arrow || both_arrows) { end_x = Math.round(x1 + (x2 - x1) * ratio); end_y = Math.round(y1 + (y2 - y1) * ratio); } else { end_x = x2; end_y = y2; } if (this.render_options.draw_start_arrow || both_arrows) { start_x = x1 + (x2 - x1) * (1 - ratio); start_y = y1 + (y2 - y1) * (1 - ratio); } else { start_x = x1; start_y = y1; } if (this.render_options.color) { ctx.setStrokeStyle(this.render_options.color); ctx.setFillStyle(this.render_options.color); } // Draw the shaft of the arrow ctx.beginPath(); ctx.moveTo(start_x, start_y); ctx.lineTo(end_x, end_y); ctx.stroke(); ctx.closePath(); // calculate the angle of the line const line_angle = Math.atan2(y2 - y1, x2 - x1); // h is the line length of a side of the arrow head const h = Math.abs(this.render_options.arrowhead_length / Math.cos(this.render_options.arrowhead_angle)); let angle1; let angle2; let top_x; let top_y; let bottom_x; let bottom_y; if (this.render_options.draw_end_arrow || both_arrows) { angle1 = line_angle + Math.PI + this.render_options.arrowhead_angle; top_x = x2 + Math.cos(angle1) * h; top_y = y2 + Math.sin(angle1) * h; angle2 = line_angle + Math.PI - this.render_options.arrowhead_angle; bottom_x = x2 + Math.cos(angle2) * h; bottom_y = y2 + Math.sin(angle2) * h; drawArrowHead(ctx, top_x, top_y, x2, y2, bottom_x, bottom_y); } if (this.render_options.draw_start_arrow || both_arrows) { angle1 = line_angle + this.render_options.arrowhead_angle; top_x = x1 + Math.cos(angle1) * h; top_y = y1 + Math.sin(angle1) * h; angle2 = line_angle - this.render_options.arrowhead_angle; bottom_x = x1 + Math.cos(angle2) * h; bottom_y = y1 + Math.sin(angle2) * h; drawArrowHead(ctx, top_x, top_y, x1, y1, bottom_x, bottom_y); } } // Renders the `StaveLine` on the context draw(): this { const ctx = this.checkContext(); this.setRendered(); const first_note = this.first_note; const last_note = this.last_note; const render_options = this.render_options; ctx.save(); this.applyLineStyle(); // Cycle through each set of indices and draw lines let start_position = { x: 0, y: 0 }; let end_position = { x: 0, y: 0 }; this.first_indices.forEach((first_index, i) => { const last_index = this.last_indices[i]; // Get initial coordinates for the start/end of the line start_position = first_note.getModifierStartXY(2, first_index); end_position = last_note.getModifierStartXY(1, last_index); const upwards_slope = start_position.y > end_position.y; // Adjust `x` coordinates for modifiers start_position.x += first_note.getMetrics().modRightPx + render_options.padding_left; end_position.x -= last_note.getMetrics().modLeftPx + render_options.padding_right; // Adjust first `x` coordinates for displacements const notehead_width = first_note.getGlyph().getWidth(); const first_displaced = first_note.getKeyProps()[first_index].displaced; if (first_displaced && first_note.getStemDirection() === 1) { start_position.x += notehead_width + render_options.padding_left; } // Adjust last `x` coordinates for displacements const last_displaced = last_note.getKeyProps()[last_index].displaced; if (last_displaced && last_note.getStemDirection() === -1) { end_position.x -= notehead_width + render_options.padding_right; } // Adjust y position better if it's not coming from the center of the note start_position.y += upwards_slope ? -3 : 1; end_position.y += upwards_slope ? 2 : 0; this.drawArrowLine(ctx, start_position, end_position); }); ctx.restore(); // Determine the x coordinate where to start the text const text_width = ctx.measureText(this.text).width; const justification = render_options.text_justification; let x = 0; if (justification === StaveLine.TextJustification.LEFT) { x = start_position.x; } else if (justification === StaveLine.TextJustification.CENTER) { const delta_x = end_position.x - start_position.x; const center_x = delta_x / 2 + start_position.x; x = center_x - text_width / 2; } else if (justification === StaveLine.TextJustification.RIGHT) { x = end_position.x - text_width; } // Determine the y value to start the text let y = 0; const vertical_position = render_options.text_position_vertical; if (vertical_position === StaveLine.TextVerticalPosition.TOP) { y = first_note.checkStave().getYForTopText(); } else if (vertical_position === StaveLine.TextVerticalPosition.BOTTOM) { y = first_note.checkStave().getYForBottomText(Flow.TEXT_HEIGHT_OFFSET_HACK); } // Draw the text ctx.save(); this.applyFontStyle(); ctx.fillText(this.text, x, y); ctx.restore(); return this; } }
the_stack
import * as assert from "assert"; import * as model from "../../../preview/controller"; const floatCheckEpsilon = 1e-12; const testRecursionDepth = 7; const defaultNormalZoom = 2; function assertEqual(actual: number, expected: number): void { assert.equal(actual, expected); } function assertAlmostEqual(actual: number, expected: number): void { assert(Math.abs(actual - expected) < floatCheckEpsilon, `Actual: ${actual}, Expected: ${expected}.`); } class FakeView { private widthValue: number; private heightValue: number; private contentWidthValue: number; private contentHeightValue: number; private contentMarginValue: number; private contentXValue = -1; private contentYValue = -1; private zoomValue = -1; private zoomModeValue: model.ZoomMode = model.ZoomMode.Fixed; private controller: model.Controller; public constructor( width: number, height: number, contentWidth: number, contentHeight: number, contentMargin: number, public readonly zoomStep: number, public readonly offsetStep: number, zoomMode: model.ZoomMode ) { this.widthValue = width; this.heightValue = height; this.contentWidthValue = contentWidth; this.contentHeightValue = contentHeight; this.contentMarginValue = contentMargin; const viewEventListener = new class implements model.ViewEventListener { public constructor(private fakeView: FakeView) { } public onZoomModeChanged(zoomMode1: model.ZoomMode): void { this.fakeView.zoomModeValue = zoomMode1; } public onLayoutChanged(x: number, y: number, w: number, h: number, zoom: number): void { assertEqual(w, this.fakeView.contentWidth); assertEqual(h, this.fakeView.contentHeight); this.fakeView.contentXValue = x; this.fakeView.contentYValue = y; this.fakeView.zoomValue = zoom; } }(this); this.controller = model.Controller.create( width, height, contentWidth, contentHeight, contentMargin, viewEventListener, zoomStep, offsetStep, zoomMode ); } public get width(): number { return this.widthValue; } public get height(): number { return this.heightValue; } public get contentWidth(): number { return this.contentWidthValue; } public get contentHeight(): number { return this.contentHeightValue; } public get contentMargin(): number { return this.contentMarginValue; } public get contentX(): number { return this.contentXValue; } public get contentY(): number { return this.contentYValue; } public get zoom(): number { return this.zoomValue; } public get zoomMode(): model.ZoomMode { return this.zoomModeValue; } public beginDrag(x: number, y: number): (x: number, y: number) => void { return this.controller.beginDrag(x, y); } public resize(width: number, height: number): void { this.widthValue = width; this.heightValue = height; this.controller.resize(width, height); } public resizeContent(width: number, height: number): void { this.contentWidthValue = width; this.contentHeightValue = height; this.controller.resizeContent(width, height); } public setZoomMode(zoomMode: model.ZoomMode): void { this.controller.setZoomMode(zoomMode); } public toggleOverview(x: number, y: number): void { this.controller.toggleOverview(x, y); } public zoomIn(x: number, y: number): void { this.controller.zoomIn(x, y); } public zoomOut(x: number, y: number): void { this.controller.zoomOut(x, y); } public get hasEnoughSpace(): boolean { const contentMargin = this.contentMargin * 2; return this.contentWidth < this.width - contentMargin && this.contentHeight < this.height - contentMargin; } public hasEnoughSpaceWithSize(width: number, height: number): boolean { const contentMargin = this.contentMargin * 2; return this.contentWidth < width - contentMargin && this.contentHeight < height - contentMargin; } public hasEnoughSpaceWithContentSize(width: number, height: number): boolean { const contentMargin = this.contentMargin * 2; return width < this.width - contentMargin && height < this.height - contentMargin; } } function makeCreator(creator: () => FakeView, action: (fakeView: FakeView) => void): () => FakeView { return (): FakeView => { const fakeView = creator(); action(fakeView); return fakeView; }; } type SavedState = (creator: () => FakeView, recursionDepth: number) => void; function saveState( referenceViewCreator: () => FakeView, checker: (creator: () => FakeView, contentX: number, contentY: number, zoom: number, recursionDepth: number) => void ): SavedState { const referenceView = referenceViewCreator(); return (creator: () => FakeView, recursionDepth: number): void => { const fakeView = creator(); referenceView.resize(fakeView.width, fakeView.height); referenceView.resizeContent(fakeView.contentWidth, fakeView.contentHeight); checker(creator, referenceView.contentX, referenceView.contentY, referenceView.zoom, recursionDepth); }; } // Fixed Normal State. function checkFixedNormalState( creator: () => FakeView, expectedX: number, expectedY: number, expectedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.Fixed); assertAlmostEqual(fakeView.contentX, expectedX); assertAlmostEqual(fakeView.contentY, expectedY); assertAlmostEqual(fakeView.zoom, expectedZoom); // Drag. checkFixedNormalState( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, fakeView.zoom, recursionDepth ); // Resize. checkFixedNormalState( makeCreator(creator, (v) => v.resize(fakeView.width * 1.1, fakeView.height * 1.2)), fakeView.contentX + fakeView.width * 0.05, fakeView.contentY + fakeView.height * 0.1, fakeView.zoom, recursionDepth ); // Resize content. checkFixedNormalState( makeCreator(creator, (v) => v.resizeContent(fakeView.contentWidth * 1.1, fakeView.contentHeight * 1.2)), fakeView.contentX * 1.1 - fakeView.width * 0.05, fakeView.contentY * 1.2 - fakeView.height * 0.1, fakeView.zoom, recursionDepth ); const savedState = saveState(creator, (c, x, y, z, d) => checkFixedNormalState(c, x, y, z, d)); // Set Zoom Mode. { // Fixed. checkFixedNormalState( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), fakeView.contentX, fakeView.contentY, fakeView.zoom, recursionDepth ); // Fit. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedState, fakeView.zoom, recursionDepth ); // Auto Fit. { const checker = fakeView.hasEnoughSpace ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedState, fakeView.zoom, recursionDepth ); } } // Toggle overview. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoom), fakeView.contentY * (1.2 - 0.2 / fakeView.zoom), fakeView.zoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } // Fixed 100% State. function checkFixed100PercentStateWithSavedZoom( creator: () => FakeView, expectedX: number, expectedY: number, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.Fixed); assertAlmostEqual(fakeView.contentX, expectedX); assertAlmostEqual(fakeView.contentY, expectedY); assertAlmostEqual(fakeView.zoom, 1); // Drag. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, savedZoom, recursionDepth ); // Resize. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.resize(fakeView.width * 1.1, fakeView.height * 1.2)), fakeView.contentX + fakeView.width * 0.05, fakeView.contentY + fakeView.height * 0.1, savedZoom, recursionDepth ); // Resize content. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.resizeContent(fakeView.contentWidth * 1.1, fakeView.contentHeight * 1.2)), fakeView.contentX * 1.1 - fakeView.width * 0.05, fakeView.contentY * 1.2 - fakeView.height * 0.1, savedZoom, recursionDepth ); const savedState = saveState( creator, (c, x, y, _, d) => checkFixed100PercentStateWithSavedZoom(c, x, y, savedZoom, d) ); // Set Zoom Mode. { // Fixed. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), fakeView.contentX, fakeView.contentY, savedZoom, recursionDepth ); // Fit. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedState, savedZoom, recursionDepth ); // Auto Fit. { const checker = fakeView.hasEnoughSpace ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedState, savedZoom, recursionDepth ); } } // Toggle overview. checkFixedNormalState( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - savedZoom * 0.1), fakeView.contentY * (1.2 - savedZoom * 0.2), savedZoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), 1 / fakeView.zoomStep, recursionDepth ); } } function checkFit(fakeView: FakeView): void { const expectedZoom = Math.min( (fakeView.width - fakeView.contentMargin * 2) / fakeView.contentWidth, (fakeView.height - fakeView.contentMargin * 2) / fakeView.contentHeight ); const expectedX = (fakeView.width - fakeView.contentWidth * expectedZoom) / 2; const expectedY = (fakeView.height - fakeView.contentHeight * expectedZoom) / 2; assertAlmostEqual(fakeView.contentX, expectedX); assertAlmostEqual(fakeView.contentY, expectedY); assertAlmostEqual(fakeView.zoom, expectedZoom); } function checkInitialFixedState( creator: () => FakeView, fakeView: FakeView, savedZoom: number, recursionDepth: number ): void { if (fakeView.hasEnoughSpace) { checkFixed100PercentStateWithSavedZoom( creator, (fakeView.width - fakeView.contentWidth) / 2, (fakeView.height - fakeView.contentHeight) / 2, savedZoom, recursionDepth ); } else { const contentMargin = fakeView.contentMargin * 2; const zoom = Math.min( (fakeView.width - contentMargin) / fakeView.contentWidth, (fakeView.height - contentMargin) / fakeView.contentHeight ); checkFixedNormalState( creator, (fakeView.width - fakeView.contentWidth * zoom) / 2, (fakeView.height - fakeView.contentHeight * zoom) / 2, zoom, recursionDepth ); } } // Fit State. function checkFitStateWithSavedStateAndZoom( creator: () => FakeView, savedState: SavedState, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.Fit); checkFit(fakeView); // Drag. checkFixedNormalState( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, fakeView.zoom, recursionDepth ); // Resize. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.resize(fakeView.width * 1.1, fakeView.height * 1.2)), savedState, savedZoom, recursionDepth ); // Resize content. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.resizeContent(fakeView.contentWidth * 1.1, fakeView.contentHeight * 1.2)), savedState, savedZoom, recursionDepth ); // Set Zoom Mode. { // Fixed. savedState(makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), recursionDepth); // Fit. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedState, savedZoom, recursionDepth ); // Auto Fit. { const checker = fakeView.hasEnoughSpace ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedState, savedZoom, recursionDepth ); } } // Toggle overview. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoom), fakeView.contentY * (1.2 - 0.2 / fakeView.zoom), fakeView.zoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } function checkFitStateWithSavedZoom(creator: () => FakeView, savedZoom: number, recursionDepth: number): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.Fit); checkFit(fakeView); // Drag. checkFixedNormalState( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, fakeView.zoom, recursionDepth ); // Resize. checkFitStateWithSavedZoom( makeCreator(creator, (v) => v.resize(fakeView.width * 1.1, fakeView.height * 1.2)), savedZoom, recursionDepth ); // Resize content. checkFitStateWithSavedZoom( makeCreator(creator, (v) => v.resizeContent(fakeView.contentWidth * 1.1, fakeView.contentHeight * 1.2)), savedZoom, recursionDepth ); // Set Zoom Mode. { // Fixed. checkInitialFixedState( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), fakeView, fakeView.zoom, recursionDepth ); // Fit. checkFitStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedZoom, recursionDepth ); // Auto Fit. { const checker = fakeView.hasEnoughSpace ? checkAutoFit100PercentStateWithSavedZoom : checkAutoFitFitStateWithSavedZoom; checker(makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedZoom, recursionDepth); } } // Toggle overview. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoom), fakeView.contentY * (1.2 - 0.2 / fakeView.zoom), fakeView.zoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } function checkIdentityCenter(fakeView: FakeView): void { assertAlmostEqual(fakeView.contentX, (fakeView.width - fakeView.contentWidth) / 2); assertAlmostEqual(fakeView.contentY, (fakeView.height - fakeView.contentHeight) / 2); assertEqual(fakeView.zoom, 1); } // Auto Fit 100% State. function checkAutoFit100PercentStateWithSavedStateAndZoom( creator: () => FakeView, savedState: SavedState, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.AutoFit); checkIdentityCenter(fakeView); // Drag. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, savedZoom, recursionDepth ); // Resize. { const newWidth = fakeView.width / 1.1; const newHeight = fakeView.height / 1.2; const checker = fakeView.hasEnoughSpaceWithSize(newWidth, newHeight) ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker(makeCreator(creator, (v) => v.resize(newWidth, newHeight)), savedState, savedZoom, recursionDepth); } // Resize content. { const newContentWidth = fakeView.contentWidth * 1.1; const newContentHeight = fakeView.contentHeight * 1.2; const checker = fakeView.hasEnoughSpaceWithContentSize(newContentWidth, newContentHeight) ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker( makeCreator(creator, (v) => v.resizeContent(newContentWidth, newContentHeight)), savedState, savedZoom, recursionDepth ); } // Set Zoom Mode. { // Fixed. savedState(makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), recursionDepth); // Fit. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedState, savedZoom, recursionDepth ); // Auto Fit. { checkAutoFit100PercentStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedState, savedZoom, recursionDepth ); } } // Toggle overview. checkFixedNormalState( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - savedZoom * 0.1), fakeView.contentY * (1.2 - savedZoom * 0.2), savedZoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } function checkAutoFit100PercentStateWithSavedZoom( creator: () => FakeView, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.AutoFit); checkIdentityCenter(fakeView); // Drag. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, savedZoom, recursionDepth ); // Resize. { const newWidth = fakeView.width / 1.1; const newHeight = fakeView.height / 1.2; const checker = fakeView.hasEnoughSpaceWithSize(newWidth, newHeight) ? checkAutoFit100PercentStateWithSavedZoom : checkAutoFitFitStateWithSavedZoom; checker(makeCreator(creator, (v) => v.resize(newWidth, newHeight)), savedZoom, recursionDepth); } // Resize content. { const newContentWidth = fakeView.contentWidth * 1.1; const newContentHeight = fakeView.contentHeight * 1.2; const checker = fakeView.hasEnoughSpaceWithContentSize(newContentWidth, newContentHeight) ? checkAutoFit100PercentStateWithSavedZoom : checkAutoFitFitStateWithSavedZoom; checker( makeCreator(creator, (v) => v.resizeContent(newContentWidth, newContentHeight)), savedZoom, recursionDepth ); } // Set Zoom Mode. { // Fixed. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), fakeView.contentX, fakeView.contentY, savedZoom, recursionDepth ); // Fit. checkFitStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedZoom, recursionDepth ); // Auto Fit. { checkAutoFit100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedZoom, recursionDepth ); } } // Toggle overview. checkFixedNormalState( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - savedZoom * 0.1), fakeView.contentY * (1.2 - savedZoom * 0.2), savedZoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } // Auto Fit Fit State. function checkAutoFitFitStateWithSavedStateAndZoom( creator: () => FakeView, savedState: SavedState, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.AutoFit); checkFit(fakeView); // Drag. checkFixedNormalState( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, fakeView.zoom, recursionDepth ); // Resize. { const newWidth = fakeView.width * 1.1; const newHeight = fakeView.height * 1.2; const checker = fakeView.hasEnoughSpaceWithSize(newWidth, newHeight) ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker(makeCreator(creator, (v) => v.resize(newWidth, newHeight)), savedState, savedZoom, recursionDepth); } // Resize content. { const newContentWidth = fakeView.contentWidth / 1.1; const newContentHeight = fakeView.contentHeight / 1.2; const checker = fakeView.hasEnoughSpaceWithContentSize(newContentWidth, newContentHeight) ? checkAutoFit100PercentStateWithSavedStateAndZoom : checkAutoFitFitStateWithSavedStateAndZoom; checker( makeCreator(creator, (v) => v.resizeContent(newContentWidth, newContentHeight)), savedState, savedZoom, recursionDepth ); } // Set Zoom Mode. { // Fixed. savedState(makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), recursionDepth); // Fit. checkFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedState, savedZoom, recursionDepth ); // Auto Fit. { checkAutoFitFitStateWithSavedStateAndZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedState, savedZoom, recursionDepth ); } } // Toggle overview. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoom), fakeView.contentY * (1.2 - 0.2 / fakeView.zoom), fakeView.zoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } function checkAutoFitFitStateWithSavedZoom( creator: () => FakeView, savedZoom: number, recursionDepth: number ): void { if (recursionDepth > 0) { --recursionDepth; const fakeView = creator(); assertEqual(fakeView.zoomMode, model.ZoomMode.AutoFit); checkFit(fakeView); // Drag. checkFixedNormalState( makeCreator(creator, (v) => v.beginDrag(10, 20)(30, 50)), fakeView.contentX + 20, fakeView.contentY + 30, fakeView.zoom, recursionDepth ); // Resize. { const newWidth = fakeView.width * 1.1; const newHeight = fakeView.height * 1.2; const checker = fakeView.hasEnoughSpaceWithSize(newWidth, newHeight) ? checkAutoFit100PercentStateWithSavedZoom : checkAutoFitFitStateWithSavedZoom; checker(makeCreator(creator, (v) => v.resize(newWidth, newHeight)), savedZoom, recursionDepth); } // Resize content. { const newContentWidth = fakeView.contentWidth / 1.1; const newContentHeight = fakeView.contentHeight / 1.2; const checker = fakeView.hasEnoughSpaceWithContentSize(newContentWidth, newContentHeight) ? checkAutoFit100PercentStateWithSavedZoom : checkAutoFitFitStateWithSavedZoom; checker( makeCreator(creator, (v) => v.resizeContent(newContentWidth, newContentHeight)), savedZoom, recursionDepth ); } // Set Zoom Mode. { // Fixed. checkInitialFixedState( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fixed)), fakeView, fakeView.zoom, recursionDepth ); // Fit. checkFitStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.Fit)), savedZoom, recursionDepth ); // Auto Fit. { checkAutoFitFitStateWithSavedZoom( makeCreator(creator, (v) => v.setZoomMode(model.ZoomMode.AutoFit)), savedZoom, recursionDepth ); } } // Toggle overview. checkFixed100PercentStateWithSavedZoom( makeCreator(creator, (v) => v.toggleOverview(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoom), fakeView.contentY * (1.2 - 0.2 / fakeView.zoom), fakeView.zoom, recursionDepth ); // Zoom in. checkFixedNormalState( makeCreator(creator, (v) => v.zoomIn(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - fakeView.zoomStep * 0.1), fakeView.contentY * (1.2 - fakeView.zoomStep * 0.2), fakeView.zoom * fakeView.zoomStep, recursionDepth ); // Zoom out. checkFixedNormalState( makeCreator(creator, (v) => v.zoomOut(fakeView.contentX * 1.1, fakeView.contentY * 1.2)), fakeView.contentX * (1.1 - 0.1 / fakeView.zoomStep), fakeView.contentY * (1.2 - 0.2 / fakeView.zoomStep), fakeView.zoom / fakeView.zoomStep, recursionDepth ); } } suite("Model", function (): void { test("Fixed Controller - 100%", function (): void { checkFixed100PercentStateWithSavedZoom( () => new FakeView(600, 400, 300, 200, 10, 1.1, 10, model.ZoomMode.Fixed), 150, 100, defaultNormalZoom, testRecursionDepth ); }); test("Create Fixed Controller - Corner", function (): void { checkFixedNormalState( () => new FakeView(600, 400, 580, 380, 10, 1.1, 10, model.ZoomMode.Fixed), 10, 10, 1, testRecursionDepth ); }); test("Create Fixed Controller - Fit Horizontal", function (): void { checkFixedNormalState( () => new FakeView(600, 400, 581, 380, 10, 1.1, 10, model.ZoomMode.Fixed), 10, 6000 / 581, 580 / 581, testRecursionDepth ); }); test("Create Fixed Controller - Fit Vertical", function (): void { checkFixedNormalState( () => new FakeView(600, 400, 580, 381, 10, 1.1, 10, model.ZoomMode.Fixed), 4100 / 381, 10, 380 / 381, testRecursionDepth ); }); test("Create Fit Controller - Upscaling - Fit Horizontal", function (): void { const creator = (): FakeView => new FakeView(600, 400, 100, 10, 10, 1.1, 10, model.ZoomMode.Fit); checkFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); test("Create Fit Controller - Upscaling - Fit Vertical", function (): void { const creator = (): FakeView => new FakeView(600, 400, 10, 100, 10, 1.1, 10, model.ZoomMode.Fit); checkFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); test("Create Fit Controller - Downscaling - Fit Horizontal", function (): void { const creator = (): FakeView => new FakeView(600, 400, 1000, 100, 10, 1.1, 10, model.ZoomMode.Fit); checkFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); test("Create Fit Controller - Downscaling - Fit Vertical", function (): void { const creator = (): FakeView => new FakeView(600, 400, 100, 1000, 10, 1.1, 10, model.ZoomMode.Fit); checkFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); test("Create AutoFit Controller - 100%", function (): void { checkAutoFit100PercentStateWithSavedZoom( () => new FakeView(600, 400, 300, 200, 10, 1.1, 10, model.ZoomMode.AutoFit), defaultNormalZoom, testRecursionDepth ); }); test("Create AutoFit Controller - Corner", function (): void { checkAutoFitFitStateWithSavedZoom( () => new FakeView(600, 400, 580, 380, 10, 1.1, 10, model.ZoomMode.AutoFit), 1, testRecursionDepth ); }); test("Create AutoFit Controller - Fit Horizontal", function (): void { const creator = (): FakeView => new FakeView(600, 400, 581, 380, 10, 1.1, 10, model.ZoomMode.AutoFit); checkAutoFitFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); test("Create AutoFit Controller - Fit Vertical", function (): void { const creator = (): FakeView => new FakeView(600, 400, 580, 381, 10, 1.1, 10, model.ZoomMode.AutoFit); checkAutoFitFitStateWithSavedZoom(creator, creator().zoom, testRecursionDepth); }); });
the_stack
import type { Url } from 'url' import debugModule from 'debug' import minimatch from 'minimatch' import Forge from 'node-forge' import fs from 'fs-extra' import { clientCertificateStore } from './agent' const { pki, asn1, pkcs12, util } = Forge const debug = debugModule('cypress:network:client-certificates') export class ParsedUrl { constructor (url: string) { if (url === '*' || url === 'https://*') { this.host = '*' this.path = undefined this.port = undefined } else { let parsed = new URL(url) this.host = parsed.hostname this.port = !parsed.port ? undefined : parseInt(parsed.port) if (parsed.pathname.length === 0 || parsed.pathname === '/') { this.path = undefined } else if ( parsed.pathname.length > 0 && !parsed.pathname.endsWith('/') && !parsed.pathname.endsWith('*') ) { this.path = `${parsed.pathname}/` } else { this.path = parsed.pathname } } this.hostMatcher = new minimatch.Minimatch(this.host) this.pathMatcher = new minimatch.Minimatch(this.path ?? '') } path: string | undefined; host: string; port: number | undefined; hostMatcher: minimatch.IMinimatch; pathMatcher: minimatch.IMinimatch; } export class UrlMatcher { static buildMatcherRule (url: string): ParsedUrl { return new ParsedUrl(url) } static matchUrl (hostname: string | undefined | null, path: string | undefined | null, port: number | undefined | null, rule: ParsedUrl | undefined): boolean { if (!hostname || !rule) { return false } let ret = rule.hostMatcher.match(hostname) if (ret && rule.port) { ret = rule.port === port } if (ret && rule.path) { ret = rule.pathMatcher?.match(path ?? '') } return ret } } /** * Defines the certificates that should be used for the specified URL */ export class UrlClientCertificates { constructor (url: string) { this.subjects = '' this.url = url this.pathnameLength = new URL(url).pathname.length this.clientCertificates = new ClientCertificates() } clientCertificates: ClientCertificates; url: string; subjects: string; pathnameLength: number; matchRule: ParsedUrl | undefined; addSubject (subject: string) { if (!this.subjects) { this.subjects = subject } else { this.subjects = `${this.subjects} - ${subject}` } } } /** * Client certificates; this is in a data structure that is compatible with the NodeJS TLS API described * at https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options */ export class ClientCertificates { ca: Buffer[] = []; cert: Buffer[] = []; key: PemKey[] = []; pfx: PfxCertificate[] = []; } export class PemKey { constructor (pem: Buffer, passphrase: string | undefined) { this.pem = pem this.passphrase = passphrase } pem: Buffer; passphrase: string | undefined; } export class PfxCertificate { constructor (buf: Buffer, passphrase: string | undefined) { this.buf = buf this.passphrase = passphrase } buf: Buffer; passphrase: string | undefined; } export class ClientCertificateStore { private _urlClientCertificates: UrlClientCertificates[] = []; addClientCertificatesForUrl (cert: UrlClientCertificates) { debug( 'ClientCertificateStore::addClientCertificatesForUrl: "%s"', cert.url, ) const existing = this._urlClientCertificates.find((x) => x.url === cert.url) if (existing) { throw new Error(`ClientCertificateStore::addClientCertificatesForUrl: Url ${cert.url} already in store`) } cert.matchRule = UrlMatcher.buildMatcherRule(cert.url) this._urlClientCertificates.push(cert) } getClientCertificateAgentOptionsForUrl (requestUrl: Url): ClientCertificates | null { if ( !this._urlClientCertificates || this._urlClientCertificates.length === 0 ) { return null } const port = !requestUrl.port ? undefined : parseInt(requestUrl.port) const matchingCerts = this._urlClientCertificates.filter((cert) => { return UrlMatcher.matchUrl(requestUrl.hostname, requestUrl.path, port, cert.matchRule) }) switch (matchingCerts.length) { case 0: debug(`not using client certificate(s) for url '${requestUrl.href}'`) return null case 1: debug( `using client certificate(s) '${matchingCerts[0].subjects}' for url '${requestUrl.href}'`, ) return matchingCerts[0].clientCertificates default: matchingCerts.sort((a, b) => { return b.pathnameLength - a.pathnameLength }) debug( `using client certificate(s) '${matchingCerts[0].subjects}' for url '${requestUrl.href}'`, ) return matchingCerts[0].clientCertificates } } getCertCount (): Number { return !this._urlClientCertificates ? 0 : this._urlClientCertificates.length } clear (): void { this._urlClientCertificates = [] } } /** * Load and parse the client certificate configuration. The structure and content of this * has already been validated; this function reads cert content from file and adds it to the * network ClientCertificateStore * @param config */ export function loadClientCertificateConfig (config) { const { clientCertificates } = config let index = 0 try { clientCertificateStore.clear() // The basic validation of the certificate configuration has already been done by this point // within the 'isValidClientCertificatesSet' function within packages/server/lib/util/validation.js if (clientCertificates) { clientCertificates.forEach((item) => { debug(`loading client cert at index ${index}`) const urlClientCertificates = new UrlClientCertificates(item.url) if (item.ca) { item.ca.forEach((ca: string) => { if (ca) { debug(`loading CA cert from '${ca}'`) const caRaw = loadBinaryFromFile(ca) try { pki.certificateFromPem(caRaw) } catch (error) { throw new Error(`Cannot parse CA cert: ${error.message}`) } urlClientCertificates.clientCertificates.ca.push(caRaw) } }) } if (!item.certs || item.certs.length === 0) { throw new Error('Either PEM or PFX must be supplied') } item.certs.forEach((cert) => { if (!cert || (!cert.cert && !cert.pfx)) { throw new Error('Either PEM or PFX must be supplied') } if (cert.cert) { if (!cert.key) { throw new Error(`No PEM key defined for cert: ${cert.cert}`) } debug( `loading PEM cert information from '${JSON.stringify(cert)}'`, ) debug(`loading PEM cert from '${cert.cert}'`) const pemRaw = loadBinaryFromFile(cert.cert) let pemParsed = undefined try { pemParsed = pki.certificateFromPem(pemRaw) } catch (error) { throw new Error(`Cannot parse PEM cert: ${error.message}`) } urlClientCertificates.clientCertificates.cert.push(pemRaw) let passphrase: string | undefined = undefined if (cert.passphrase) { debug(`loading PEM passphrase from '${cert.passphrase}'`) passphrase = loadTextFromFile(cert.passphrase) } debug(`loading PEM key from '${cert.key}'`) const pemKeyRaw = loadBinaryFromFile(cert.key) try { if (passphrase) { if (!pki.decryptRsaPrivateKey(pemKeyRaw, passphrase)) { throw new Error( 'Cannot decrypt PEM key with supplied passphrase (check the passphrase file content and that it doesn\'t have unexpected whitespace at the end)', ) } } else { if (!pki.privateKeyFromPem(pemKeyRaw)) { throw new Error('Cannot load PEM key') } } } catch (error) { throw new Error(`Cannot parse PEM key: ${error.message}`) } urlClientCertificates.clientCertificates.key.push( new PemKey(pemKeyRaw, passphrase), ) const subject = extractSubjectFromPem(pemParsed) urlClientCertificates.addSubject(subject) debug( `loaded client PEM certificate: ${subject} for url: ${urlClientCertificates.url}`, ) } if (cert.pfx) { debug( `loading PFX cert information from '${JSON.stringify(cert)}'`, ) let passphrase: string | undefined = undefined if (cert.passphrase) { debug(`loading PFX passphrase from '${cert.passphrase}'`) passphrase = loadTextFromFile(cert.passphrase) } debug(`loading PFX cert from '${cert.pfx}'`) const pfxRaw = loadBinaryFromFile(cert.pfx) const pfxParsed = loadPfx(pfxRaw, passphrase) urlClientCertificates.clientCertificates.pfx.push( new PfxCertificate(pfxRaw, passphrase), ) const subject = extractSubjectFromPfx(pfxParsed) urlClientCertificates.addSubject(subject) debug( `loaded client PFX certificate: ${subject} for url: ${urlClientCertificates.url}`, ) } }) clientCertificateStore.addClientCertificatesForUrl(urlClientCertificates) index++ }) debug( `loaded client certificates for ${clientCertificateStore.getCertCount()} URL(s)`, ) } } catch (e) { debug( `Failed to load client certificate for clientCertificates[${index}]: ${e.message} ${e.stack}`, ) throw new Error( `Failed to load client certificates for clientCertificates[${index}]: ${e.message}. For more debug details run Cypress with DEBUG=cypress:server:client-certificates*`, ) } } function loadBinaryFromFile (filepath: string): Buffer { debug(`loadCertificateFile: ${filepath}`) return fs.readFileSync(filepath) } function loadTextFromFile (filepath: string): string { debug(`loadPassphraseFile: ${filepath}`) return fs.readFileSync(filepath, 'utf8').toString() } /** * Extract subject from supplied pem instance */ function extractSubjectFromPem (pem): string { try { return pem.subject.attributes .map((attr) => [attr.shortName, attr.value].join('=')) .join(', ') } catch (e) { throw new Error(`Unable to extract subject from PEM file: ${e.message}`) } } /** * Load PFX data from the supplied Buffer and passphrase */ function loadPfx (pfx: Buffer, passphrase: string | undefined) { try { const certDer = util.decode64(pfx.toString('base64')) const certAsn1 = asn1.fromDer(certDer) return pkcs12.pkcs12FromAsn1(certAsn1, passphrase) } catch (e) { debug(`loadPfx fail: ${e.message} ${e.stackTrace}`) throw new Error(`Unable to load PFX file: ${e.message}`) } } /** * Extract subject from supplied pfx instance */ function extractSubjectFromPfx (pfx) { try { const certs = pfx.getBags({ bagType: pki.oids.certBag })[pki.oids.certBag].map((item) => item.cert) return certs[0].subject.attributes.map((attr) => [attr.shortName, attr.value].join('=')).join(', ') } catch (e) { throw new Error(`Unable to extract subject from PFX file: ${e.message}`) } }
the_stack
import padEnd from "pad-end"; // For example: if two exponents are more than 17 apart, // consider adding them together pointless, just return the larger one const MAX_SIGNIFICANT_DIGITS = 17; // Highest value you can safely put here is Number.MAX_SAFE_INTEGER-MAX_SIGNIFICANT_DIGITS const EXP_LIMIT = 9e15; // The largest exponent that can appear in a Number, though not all mantissas are valid here. const NUMBER_EXP_MAX = 308; // The smallest exponent that can appear in a Number, though not all mantissas are valid here. const NUMBER_EXP_MIN = -324; // Tolerance which is used for Number conversion to compensate floating-point error. const ROUND_TOLERANCE = 1e-10; const powerOf10 = (() => { // We need this lookup table because Math.pow(10, exponent) // when exponent's absolute value is large is slightly inaccurate. // You can fix it with the power of math... or just make a lookup table. // Faster AND simpler const powersOf10: number[] = []; for (let i = NUMBER_EXP_MIN + 1; i <= NUMBER_EXP_MAX; i++) { powersOf10.push(Number("1e" + i)); } const indexOf0InPowersOf10 = 323; return (power: number) => powersOf10[power + indexOf0InPowersOf10]; })(); const D = (value: DecimalSource) => value instanceof Decimal ? value : new Decimal(value); const ME = (mantissa: number, exponent: number) => new Decimal().fromMantissaExponent(mantissa, exponent); const ME_NN = (mantissa: number, exponent: number) => new Decimal().fromMantissaExponent_noNormalize(mantissa, exponent); function affordGeometricSeries( resourcesAvailable: Decimal, priceStart: Decimal, priceRatio: Decimal, currentOwned: number | Decimal, ) { const actualStart = priceStart.mul(priceRatio.pow(currentOwned)); return Decimal.floor( resourcesAvailable.div(actualStart).mul(priceRatio.sub(1)).add(1).log10() / priceRatio.log10()); } function sumGeometricSeries( numItems: number | Decimal, priceStart: Decimal, priceRatio: Decimal, currentOwned: number | Decimal, ) { return priceStart .mul(priceRatio.pow(currentOwned)) .mul(Decimal.sub(1, priceRatio.pow(numItems))) .div(Decimal.sub(1, priceRatio)); } function affordArithmeticSeries( resourcesAvailable: Decimal, priceStart: Decimal, priceAdd: Decimal, currentOwned: Decimal, ) { // n = (-(a-d/2) + sqrt((a-d/2)^2+2dS))/d // where a is actualStart, d is priceAdd and S is resourcesAvailable // then floor it and you're done! const actualStart = priceStart.add(currentOwned.mul(priceAdd)); const b = actualStart.sub(priceAdd.div(2)); const b2 = b.pow(2); return b.neg() .add(b2.add(priceAdd.mul(resourcesAvailable).mul(2)).sqrt()) .div(priceAdd) .floor(); } function sumArithmeticSeries( numItems: Decimal, priceStart: Decimal, priceAdd: Decimal, currentOwned: Decimal, ) { const actualStart = priceStart.add(currentOwned.mul(priceAdd)); // (n/2)*(2*a+(n-1)*d) return numItems .div(2) .mul(actualStart.mul(2).plus(numItems.sub(1).mul(priceAdd))); } function efficiencyOfPurchase(cost: Decimal, currentRpS: Decimal, deltaRpS: Decimal) { return cost.div(currentRpS).add(cost.div(deltaRpS)); } export type DecimalSource = Decimal | number | string; /** * The Decimal's value is simply mantissa * 10^exponent. */ export default class Decimal { get m() { return this.mantissa; } set m(value) { this.mantissa = value; } get e() { return this.exponent; } set e(value) { this.exponent = value; } get s() { return this.sign(); } set s(value) { if (value === 0) { this.e = 0; this.m = 0; return; } if (this.sgn() !== value) { this.m = -this.m; } } public static fromMantissaExponent(mantissa: number, exponent: number) { return new Decimal().fromMantissaExponent(mantissa, exponent); } public static fromMantissaExponent_noNormalize(mantissa: number, exponent: number) { return new Decimal().fromMantissaExponent_noNormalize(mantissa, exponent); } public static fromDecimal(value: Decimal) { return new Decimal().fromDecimal(value); } public static fromNumber(value: number) { return new Decimal().fromNumber(value); } public static fromString(value: string) { return new Decimal().fromString(value); } public static fromValue(value: DecimalSource) { return new Decimal().fromValue(value); } public static fromValue_noAlloc(value: DecimalSource) { return value instanceof Decimal ? value : new Decimal(value); } public static abs(value: DecimalSource) { return D(value).abs(); } public static neg(value: DecimalSource) { return D(value).neg(); } public static negate(value: DecimalSource) { return D(value).neg(); } public static negated(value: DecimalSource) { return D(value).neg(); } public static sign(value: DecimalSource) { return D(value).sign(); } public static sgn(value: DecimalSource) { return D(value).sign(); } public static round(value: DecimalSource) { return D(value).round(); } public static floor(value: DecimalSource) { return D(value).floor(); } public static ceil(value: DecimalSource) { return D(value).ceil(); } public static trunc(value: DecimalSource) { return D(value).trunc(); } public static add(value: DecimalSource, other: DecimalSource) { return D(value).add(other); } public static plus(value: DecimalSource, other: DecimalSource) { return D(value).add(other); } public static sub(value: DecimalSource, other: DecimalSource) { return D(value).sub(other); } public static subtract(value: DecimalSource, other: DecimalSource) { return D(value).sub(other); } public static minus(value: DecimalSource, other: DecimalSource) { return D(value).sub(other); } public static mul(value: DecimalSource, other: DecimalSource) { return D(value).mul(other); } public static multiply(value: DecimalSource, other: DecimalSource) { return D(value).mul(other); } public static times(value: DecimalSource, other: DecimalSource) { return D(value).mul(other); } public static div(value: DecimalSource, other: DecimalSource) { return D(value).div(other); } public static divide(value: DecimalSource, other: DecimalSource) { return D(value).div(other); } public static recip(value: DecimalSource) { return D(value).recip(); } public static reciprocal(value: DecimalSource) { return D(value).recip(); } public static reciprocate(value: DecimalSource) { return D(value).reciprocate(); } public static cmp(value: DecimalSource, other: DecimalSource) { return D(value).cmp(other); } public static compare(value: DecimalSource, other: DecimalSource) { return D(value).cmp(other); } public static eq(value: DecimalSource, other: DecimalSource) { return D(value).eq(other); } public static equals(value: DecimalSource, other: DecimalSource) { return D(value).eq(other); } public static neq(value: DecimalSource, other: DecimalSource) { return D(value).neq(other); } public static notEquals(value: DecimalSource, other: DecimalSource) { return D(value).notEquals(other); } public static lt(value: DecimalSource, other: DecimalSource) { return D(value).lt(other); } public static lte(value: DecimalSource, other: DecimalSource) { return D(value).lte(other); } public static gt(value: DecimalSource, other: DecimalSource) { return D(value).gt(other); } public static gte(value: DecimalSource, other: DecimalSource) { return D(value).gte(other); } public static max(value: DecimalSource, other: DecimalSource) { return D(value).max(other); } public static min(value: DecimalSource, other: DecimalSource) { return D(value).min(other); } public static clamp(value: DecimalSource, min: DecimalSource, max: DecimalSource) { return D(value).clamp(min, max); } public static clampMin(value: DecimalSource, min: DecimalSource) { return D(value).clampMin(min); } public static clampMax(value: DecimalSource, max: DecimalSource) { return D(value).clampMax(max); } public static cmp_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).cmp_tolerance(other, tolerance); } public static compare_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).cmp_tolerance(other, tolerance); } public static eq_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).eq_tolerance(other, tolerance); } public static equals_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).eq_tolerance(other, tolerance); } public static neq_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).neq_tolerance(other, tolerance); } public static notEquals_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).notEquals_tolerance(other, tolerance); } public static lt_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).lt_tolerance(other, tolerance); } public static lte_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).lte_tolerance(other, tolerance); } public static gt_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).gt_tolerance(other, tolerance); } public static gte_tolerance(value: DecimalSource, other: DecimalSource, tolerance: DecimalSource) { return D(value).gte_tolerance(other, tolerance); } public static log10(value: DecimalSource) { return D(value).log10(); } public static absLog10(value: DecimalSource) { return D(value).absLog10(); } public static pLog10(value: DecimalSource) { return D(value).pLog10(); } public static log(value: DecimalSource, base: number) { return D(value).log(base); } public static log2(value: DecimalSource) { return D(value).log2(); } public static ln(value: DecimalSource) { return D(value).ln(); } public static logarithm(value: DecimalSource, base: number) { return D(value).logarithm(base); } public static pow10(value: number) { if (Number.isInteger(value)) { return ME_NN(1, value); } return ME(Math.pow(10, value % 1), Math.trunc(value)); } public static pow(value: DecimalSource, other: number | Decimal) { // Fast track: 10^integer if (typeof value === "number" && value === 10 && typeof other === "number" && Number.isInteger(other)) { return ME_NN(1, other); } return D(value).pow(other); } public static exp(value: DecimalSource) { return D(value).exp(); } public static sqr(value: DecimalSource) { return D(value).sqr(); } public static sqrt(value: DecimalSource) { return D(value).sqrt(); } public static cube(value: DecimalSource) { return D(value).cube(); } public static cbrt(value: DecimalSource) { return D(value).cbrt(); } public static dp(value: DecimalSource) { return D(value).dp(); } public static decimalPlaces(value: DecimalSource) { return D(value).dp(); } /** * If you're willing to spend 'resourcesAvailable' and want to buy something * with exponentially increasing cost each purchase (start at priceStart, * multiply by priceRatio, already own currentOwned), how much of it can you buy? * Adapted from Trimps source code. */ public static affordGeometricSeries( resourcesAvailable: DecimalSource, priceStart: DecimalSource, priceRatio: DecimalSource, currentOwned: number | Decimal) { return affordGeometricSeries( D(resourcesAvailable), D(priceStart), D(priceRatio), currentOwned, ); } /** * How much resource would it cost to buy (numItems) items if you already have currentOwned, * the initial price is priceStart and it multiplies by priceRatio each purchase? */ public static sumGeometricSeries( numItems: number | Decimal, priceStart: DecimalSource, priceRatio: DecimalSource, currentOwned: number | Decimal) { return sumGeometricSeries( numItems, D(priceStart), D(priceRatio), currentOwned, ); } /** * If you're willing to spend 'resourcesAvailable' and want to buy something with additively * increasing cost each purchase (start at priceStart, add by priceAdd, already own currentOwned), * how much of it can you buy? */ public static affordArithmeticSeries( resourcesAvailable: DecimalSource, priceStart: DecimalSource, priceAdd: DecimalSource, currentOwned: DecimalSource) { return affordArithmeticSeries( D(resourcesAvailable), D(priceStart), D(priceAdd), D(currentOwned), ); } /** * How much resource would it cost to buy (numItems) items if you already have currentOwned, * the initial price is priceStart and it adds priceAdd each purchase? * Adapted from http://www.mathwords.com/a/arithmetic_series.htm */ public static sumArithmeticSeries( numItems: DecimalSource, priceStart: DecimalSource, priceAdd: DecimalSource, currentOwned: DecimalSource) { return sumArithmeticSeries( D(numItems), D(priceStart), D(priceAdd), D(currentOwned), ); } /** * When comparing two purchases that cost (resource) and increase your resource/sec by (deltaRpS), * the lowest efficiency score is the better one to purchase. * From Frozen Cookies: * http://cookieclicker.wikia.com/wiki/Frozen_Cookies_(JavaScript_Add-on)#Efficiency.3F_What.27s_that.3F */ public static efficiencyOfPurchase(cost: DecimalSource, currentRpS: DecimalSource, deltaRpS: DecimalSource) { return efficiencyOfPurchase( D(cost), D(currentRpS), D(deltaRpS), ); } public static randomDecimalForTesting(absMaxExponent: number) { // NOTE: This doesn't follow any kind of sane random distribution, so use this for testing purposes only. // 5% of the time, have a mantissa of 0 if (Math.random() * 20 < 1) { return ME_NN(0, 0); } let mantissa = Math.random() * 10; // 10% of the time, have a simple mantissa if (Math.random() * 10 < 1) { mantissa = Math.round(mantissa); } mantissa *= Math.sign(Math.random() * 2 - 1); const exponent = Math.floor(Math.random() * absMaxExponent * 2) - absMaxExponent; return ME(mantissa, exponent); /* Examples: randomly test pow: var a = Decimal.randomDecimalForTesting(1000); var pow = Math.random()*20-10; if (Math.random()*2 < 1) { pow = Math.round(pow); } var result = Decimal.pow(a, pow); ["(" + a.toString() + ")^" + pow.toString(), result.toString()] randomly test add: var a = Decimal.randomDecimalForTesting(1000); var b = Decimal.randomDecimalForTesting(17); var c = a.mul(b); var result = a.add(c); [a.toString() + "+" + c.toString(), result.toString()] */ } /** * A number (double) with absolute value between [1, 10) OR exactly 0. * If mantissa is ever 10 or greater, it should be normalized * (divide by 10 and add 1 to exponent until it is less than 10, * or multiply by 10 and subtract 1 from exponent until it is 1 or greater). * Infinity/-Infinity/NaN will cause bad things to happen. */ public mantissa = NaN; /** * A number (integer) between -EXP_LIMIT and EXP_LIMIT. * Non-integral/out of bounds will cause bad things to happen. */ public exponent = NaN; constructor(value?: DecimalSource) { if (value === undefined) { this.m = 0; this.e = 0; } else if (value instanceof Decimal) { this.fromDecimal(value); } else if (typeof value === "number") { this.fromNumber(value); } else { this.fromString(value); } } /** * When mantissa is very denormalized, use this to normalize much faster. */ public normalize() { if (this.m >= 1 && this.m < 10) { return this; } // TODO: I'm worried about mantissa being negative 0 here which is why I set it again, but it may never matter if (this.m === 0) { this.m = 0; this.e = 0; return this; } const tempExponent = Math.floor(Math.log10(Math.abs(this.m))); this.m = tempExponent === NUMBER_EXP_MIN ? this.m * 10 / 1e-323 : this.m / powerOf10(tempExponent); this.e += tempExponent; return this; } public fromMantissaExponent(mantissa: number, exponent: number) { // SAFETY: don't let in non-numbers if (!isFinite(mantissa) || !isFinite(exponent)) { mantissa = Number.NaN; exponent = Number.NaN; return this; } this.m = mantissa; this.e = exponent; // Non-normalized mantissas can easily get here, so this is mandatory. this.normalize(); return this; } /** * Well, you know what you're doing! */ public fromMantissaExponent_noNormalize(mantissa: number, exponent: number) { this.m = mantissa; this.e = exponent; return this; } public fromDecimal(value: Decimal) { this.m = value.m; this.e = value.e; return this; } public fromNumber(value: number) { // SAFETY: Handle Infinity and NaN in a somewhat meaningful way. if (isNaN(value)) { this.m = Number.NaN; this.e = Number.NaN; } else if (value === Number.POSITIVE_INFINITY) { this.m = 1; this.e = EXP_LIMIT; } else if (value === Number.NEGATIVE_INFINITY) { this.m = -1; this.e = EXP_LIMIT; } else if (value === 0) { this.m = 0; this.e = 0; } else { this.e = Math.floor(Math.log10(Math.abs(value))); // SAFETY: handle 5e-324, -5e-324 separately this.m = this.e === NUMBER_EXP_MIN ? value * 10 / 1e-323 : value / powerOf10(this.e); // SAFETY: Prevent weirdness. this.normalize(); } return this; } public fromString(value: string) { if (value.indexOf("e") !== -1) { const parts = value.split("e"); this.m = parseFloat(parts[0]); this.e = parseFloat(parts[1]); // Non-normalized mantissas can easily get here, so this is mandatory. this.normalize(); } else if (value === "NaN") { this.m = Number.NaN; this.e = Number.NaN; } else { this.fromNumber(parseFloat(value)); if (isNaN(this.m)) { throw Error("[DecimalError] Invalid argument: " + value); } } return this; } public fromValue(value?: DecimalSource) { if (value instanceof Decimal) { return this.fromDecimal(value); } if (typeof value === "number") { return this.fromNumber(value); } if (typeof value === "string") { return this.fromString(value); } this.m = 0; this.e = 0; return this; } public toNumber() { // Problem: new Decimal(116).toNumber() returns 115.99999999999999. // TODO: How to fix in general case? It's clear that if toNumber() is // VERY close to an integer, we want exactly the integer. // But it's not clear how to specifically write that. // So I'll just settle with 'exponent >= 0 and difference between rounded // and not rounded < 1e-9' as a quick fix. // var result = this.m*Math.pow(10, this.e); if (!isFinite(this.e)) { return Number.NaN; } if (this.e > NUMBER_EXP_MAX) { return this.m > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } if (this.e < NUMBER_EXP_MIN) { return 0; } // SAFETY: again, handle 5e-324, -5e-324 separately if (this.e === NUMBER_EXP_MIN) { return this.m > 0 ? 5e-324 : -5e-324; } const result = this.m * powerOf10(this.e); if (!isFinite(result) || this.e < 0) { return result; } const resultRounded = Math.round(result); if (Math.abs(resultRounded - result) < ROUND_TOLERANCE) { return resultRounded; } return result; } public mantissaWithDecimalPlaces(places: number) { // https://stackoverflow.com/a/37425022 if (isNaN(this.m) || isNaN(this.e)) { return Number.NaN; } if (this.m === 0) { return 0; } const len = places + 1; const numDigits = Math.ceil(Math.log10(Math.abs(this.m))); const rounded = Math.round(this.m * Math.pow(10, len - numDigits)) * Math.pow(10, numDigits - len); return parseFloat(rounded.toFixed(Math.max(len - numDigits, 0))); } public toString() { if (isNaN(this.m) || isNaN(this.e)) { return "NaN"; } if (this.e >= EXP_LIMIT) { return this.m > 0 ? "Infinity" : "-Infinity"; } if (this.e <= -EXP_LIMIT || this.m === 0) { return "0"; } if (this.e < 21 && this.e > -7) { return this.toNumber().toString(); } return this.m + "e" + (this.e >= 0 ? "+" : "") + this.e; } public toExponential(places: number) { // https://stackoverflow.com/a/37425022 // TODO: Some unfixed cases: // new Decimal("1.2345e-999").toExponential() // "1.23450000000000015e-999" // new Decimal("1e-999").toExponential() // "1.000000000000000000e-999" // TBH I'm tempted to just say it's a feature. // If you're doing pretty formatting then why don't you know how many decimal places you want...? if (isNaN(this.m) || isNaN(this.e)) { return "NaN"; } if (this.e >= EXP_LIMIT) { return this.m > 0 ? "Infinity" : "-Infinity"; } if (this.e <= -EXP_LIMIT || this.m === 0) { return "0" + (places > 0 ? padEnd(".", places + 1, "0") : "") + "e+0"; } // two cases: // 1) exponent is < 308 and > -324: use basic toFixed // 2) everything else: we have to do it ourselves! if (this.e > NUMBER_EXP_MIN && this.e < NUMBER_EXP_MAX) { return this.toNumber().toExponential(places); } if (!isFinite(places)) { places = MAX_SIGNIFICANT_DIGITS; } const len = places + 1; const numDigits = Math.max(1, Math.ceil(Math.log10(Math.abs(this.m)))); const rounded = Math.round(this.m * Math.pow(10, len - numDigits)) * Math.pow(10, numDigits - len); return rounded.toFixed(Math.max(len - numDigits, 0)) + "e" + (this.e >= 0 ? "+" : "") + this.e; } public toFixed(places: number) { if (isNaN(this.m) || isNaN(this.e)) { return "NaN"; } if (this.e >= EXP_LIMIT) { return this.m > 0 ? "Infinity" : "-Infinity"; } if (this.e <= -EXP_LIMIT || this.m === 0) { return "0" + (places > 0 ? padEnd(".", places + 1, "0") : ""); } // two cases: // 1) exponent is 17 or greater: just print out mantissa with the appropriate number of zeroes after it // 2) exponent is 16 or less: use basic toFixed if (this.e >= MAX_SIGNIFICANT_DIGITS) { return this.m.toString() .replace(".", "") .padEnd(this.e + 1, "0") + (places > 0 ? padEnd(".", places + 1, "0") : ""); } return this.toNumber().toFixed(places); } public toPrecision(places: number) { if (this.e <= -7) { return this.toExponential(places - 1); } if (places > this.e) { return this.toFixed(places - this.e - 1); } return this.toExponential(places - 1); } public valueOf() { return this.toString(); } public toJSON() { return this.toString(); } public toStringWithDecimalPlaces(places: number) { return this.toExponential(places); } public abs() { return ME_NN(Math.abs(this.m), this.e); } public neg() { return ME_NN(-this.m, this.e); } public negate() { return this.neg(); } public negated() { return this.neg(); } public sign() { return Math.sign(this.m); } public sgn() { return this.sign(); } public round() { if (this.e < -1) { return new Decimal(0); } if (this.e < MAX_SIGNIFICANT_DIGITS) { return new Decimal(Math.round(this.toNumber())); } return this; } public floor() { if (this.e < -1) { return Math.sign(this.m) >= 0 ? new Decimal(0) : new Decimal(-1); } if (this.e < MAX_SIGNIFICANT_DIGITS) { return new Decimal(Math.floor(this.toNumber())); } return this; } public ceil() { if (this.e < -1) { return Math.sign(this.m) > 0 ? new Decimal(1) : new Decimal(0); } if (this.e < MAX_SIGNIFICANT_DIGITS) { return new Decimal(Math.ceil(this.toNumber())); } return this; } public trunc() { if (this.e < 0) { return new Decimal(0); } if (this.e < MAX_SIGNIFICANT_DIGITS) { return new Decimal(Math.trunc(this.toNumber())); } return this; } public add(value: DecimalSource) { // figure out which is bigger, shrink the mantissa of the smaller // by the difference in exponents, add mantissas, normalize and return // TODO: Optimizations and simplification may be possible, see https://github.com/Patashu/break_infinity.js/issues/8 const decimal = D(value); if (this.m === 0) { return decimal; } if (decimal.m === 0) { return this; } let biggerDecimal; let smallerDecimal; if (this.e >= decimal.e) { biggerDecimal = this; smallerDecimal = decimal; } else { biggerDecimal = decimal; smallerDecimal = this; } if (biggerDecimal.e - smallerDecimal.e > MAX_SIGNIFICANT_DIGITS) { return biggerDecimal; } // Have to do this because adding numbers that were once integers but scaled down is imprecise. // Example: 299 + 18 return ME(Math.round( 1e14 * biggerDecimal.m + 1e14 * smallerDecimal.m * powerOf10(smallerDecimal.e - biggerDecimal.e)), biggerDecimal.e - 14); } public plus(value: DecimalSource) { return this.add(value); } public sub(value: DecimalSource) { return this.add(D(value).neg()); } public subtract(value: DecimalSource) { return this.sub(value); } public minus(value: DecimalSource) { return this.sub(value); } public mul(value: DecimalSource) { // This version avoids an extra conversion to Decimal, if possible. Since the // mantissa is -10...10, any number short of MAX/10 can be safely multiplied in if (typeof value === "number") { if (value < 1e307 && value > -1e307) { return ME(this.m * value, this.e); } // If the value is larger than 1e307, we can divide that out of mantissa (since it's // greater than 1, it won't underflow) return ME(this.m * 1e-307 * value, this.e + 307); } const decimal = typeof value === "string" ? new Decimal(value) : value; return ME(this.m * decimal.m, this.e + decimal.e); } public multiply(value: DecimalSource) { return this.mul(value); } public times(value: DecimalSource) { return this.mul(value); } public div(value: DecimalSource) { return this.mul(D(value).recip()); } public divide(value: DecimalSource) { return this.div(value); } public divideBy(value: DecimalSource) { return this.div(value); } public dividedBy(value: DecimalSource) { return this.div(value); } public recip() { return ME(1 / this.m, -this.e); } public reciprocal() { return this.recip(); } public reciprocate() { return this.recip(); } /** * -1 for less than value, 0 for equals value, 1 for greater than value */ public cmp(value: DecimalSource) { const decimal = D(value); // TODO: sign(a-b) might be better? https://github.com/Patashu/break_infinity.js/issues/12 /* from smallest to largest: -3e100 -1e100 -3e99 -1e99 -3e0 -1e0 -3e-99 -1e-99 -3e-100 -1e-100 0 1e-100 3e-100 1e-99 3e-99 1e0 3e0 1e99 3e99 1e100 3e100 */ if (this.m === 0) { if (decimal.m === 0) { return 0; } if (decimal.m < 0) { return 1; } if (decimal.m > 0) { return -1; } } if (decimal.m === 0) { if (this.m < 0) { return -1; } if (this.m > 0) { return 1; } } if (this.m > 0) { if (decimal.m < 0) { return 1; } if (this.e > decimal.e) { return 1; } if (this.e < decimal.e) { return -1; } if (this.m > decimal.m) { return 1; } if (this.m < decimal.m) { return -1; } return 0; } if (this.m < 0) { if (decimal.m > 0) { return -1; } if (this.e > decimal.e) { return -1; } if (this.e < decimal.e) { return 1; } if (this.m > decimal.m) { return 1; } if (this.m < decimal.m) { return -1; } return 0; } throw Error("Unreachable code"); } public compare(value: DecimalSource) { return this.cmp(value); } public eq(value: DecimalSource) { const decimal = D(value); return this.e === decimal.e && this.m === decimal.m; } public equals(value: DecimalSource) { return this.eq(value); } public neq(value: DecimalSource) { return !this.eq(value); } public notEquals(value: DecimalSource) { return this.neq(value); } public lt(value: DecimalSource) { const decimal = D(value); if (this.m === 0) { return decimal.m > 0; } if (decimal.m === 0) { return this.m <= 0; } if (this.e === decimal.e) { return this.m < decimal.m; } if (this.m > 0) { return decimal.m > 0 && this.e < decimal.e; } return decimal.m > 0 || this.e > decimal.e; } public lte(value: DecimalSource) { return !this.gt(value); } public gt(value: DecimalSource) { const decimal = D(value); if (this.m === 0) { return decimal.m < 0; } if (decimal.m === 0) { return this.m > 0; } if (this.e === decimal.e) { return this.m > decimal.m; } if (this.m > 0) { return decimal.m < 0 || this.e > decimal.e; } return decimal.m < 0 && this.e < decimal.e; } public gte(value: DecimalSource) { return !this.lt(value); } public max(value: DecimalSource) { const decimal = D(value); return this.lt(decimal) ? decimal : this; } public min(value: DecimalSource) { const decimal = D(value); return this.gt(decimal) ? decimal : this; } public clamp(min: DecimalSource, max: DecimalSource) { return this.max(min).min(max); } public clampMin(min: DecimalSource) { return this.max(min); } public clampMax(max: DecimalSource) { return this.min(max); } public cmp_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); return this.eq_tolerance(decimal, tolerance) ? 0 : this.cmp(decimal); } public compare_tolerance(value: DecimalSource, tolerance: DecimalSource) { return this.cmp_tolerance(value, tolerance); } /** * Tolerance is a relative tolerance, multiplied by the greater of the magnitudes of the two arguments. * For example, if you put in 1e-9, then any number closer to the * larger number than (larger number)*1e-9 will be considered equal. */ public eq_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); // https://stackoverflow.com/a/33024979 // return abs(a-b) <= tolerance * max(abs(a), abs(b)) return Decimal.lte( this.sub(decimal).abs(), Decimal.max(this.abs(), decimal.abs()).mul(tolerance), ); } public equals_tolerance(value: DecimalSource, tolerance: DecimalSource) { return this.eq_tolerance(value, tolerance); } public neq_tolerance(value: DecimalSource, tolerance: DecimalSource) { return !this.eq_tolerance(value, tolerance); } public notEquals_tolerance(value: DecimalSource, tolerance: DecimalSource) { return this.neq_tolerance(value, tolerance); } public lt_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); return !this.eq_tolerance(decimal, tolerance) && this.lt(decimal); } public lte_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); return this.eq_tolerance(decimal, tolerance) || this.lt(decimal); } public gt_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); return !this.eq_tolerance(decimal, tolerance) && this.gt(decimal); } public gte_tolerance(value: DecimalSource, tolerance: DecimalSource) { const decimal = D(value); return this.eq_tolerance(decimal, tolerance) || this.gt(decimal); } public log10() { return this.e + Math.log10(this.m); } public absLog10() { return this.e + Math.log10(Math.abs(this.m)); } public pLog10() { return this.m <= 0 || this.e < 0 ? 0 : this.log10(); } public log(base: number) { // UN-SAFETY: Most incremental game cases are log(number := 1 or greater, base := 2 or greater). // We assume this to be true and thus only need to return a number, not a Decimal, // and don't do any other kind of error checking. return (Math.LN10 / Math.log(base)) * this.log10(); } public log2() { return 3.32192809488736234787 * this.log10(); } public ln() { return 2.30258509299404568402 * this.log10(); } public logarithm(base: number) { return this.log(base); } public pow(value: number | Decimal) { // UN-SAFETY: Accuracy not guaranteed beyond ~9~11 decimal places. // TODO: Decimal.pow(new Decimal(0.5), 0); or Decimal.pow(new Decimal(1), -1); // makes an exponent of -0! Is a negative zero ever a problem? const numberValue = value instanceof Decimal ? value.toNumber() : value; // TODO: Fast track seems about neutral for performance. // It might become faster if an integer pow is implemented, // or it might not be worth doing (see https://github.com/Patashu/break_infinity.js/issues/4 ) // Fast track: If (this.e*value) is an integer and mantissa^value // fits in a Number, we can do a very fast method. const temp = this.e * numberValue; let newMantissa; if (Number.isSafeInteger(temp)) { newMantissa = Math.pow(this.m, numberValue); if (isFinite(newMantissa) && newMantissa !== 0) { return ME(newMantissa, temp); } } // Same speed and usually more accurate. const newExponent = Math.trunc(temp); const residue = temp - newExponent; newMantissa = Math.pow(10, numberValue * Math.log10(this.m) + residue); if (isFinite(newMantissa) && newMantissa !== 0) { return ME(newMantissa, newExponent); } // return Decimal.exp(value*this.ln()); // UN-SAFETY: This should return NaN when mantissa is negative and value is non-integer. const result = Decimal.pow10(numberValue * this.absLog10()); // this is 2x faster and gives same values AFAIK if (this.sign() === -1 && Math.abs(numberValue % 2) === 1) { return result.neg(); } return result; } public pow_base(value: DecimalSource) { return D(value).pow(this); } public factorial() { // Using Stirling's Approximation. // https://en.wikipedia.org/wiki/Stirling%27s_approximation#Versions_suitable_for_calculators const n = this.toNumber() + 1; return Decimal.pow( (n / Math.E) * Math.sqrt(n * Math.sinh(1 / n) + 1 / (810 * Math.pow(n, 6))), n).mul(Math.sqrt(2 * Math.PI / n)); } public exp() { const x = this.toNumber(); // Fast track: if -706 < this < 709, we can use regular exp. if (-706 < x && x < 709) { return Decimal.fromNumber(Math.exp(x)); } return Decimal.pow(Math.E, x); } public sqr() { return ME(Math.pow(this.m, 2), this.e * 2); } public sqrt() { if (this.m < 0) { return new Decimal(Number.NaN); } if (this.e % 2 !== 0) { return ME(Math.sqrt(this.m) * 3.16227766016838, Math.floor(this.e / 2)); } // Mod of a negative number is negative, so != means '1 or -1' return ME(Math.sqrt(this.m), Math.floor(this.e / 2)); } public cube() { return ME(Math.pow(this.m, 3), this.e * 3); } public cbrt() { let sign = 1; let mantissa = this.m; if (mantissa < 0) { sign = -1; mantissa = -mantissa; } const newMantissa = sign * Math.pow(mantissa, 1 / 3); const mod = this.e % 3; if (mod === 1 || mod === -1) { return ME(newMantissa * 2.1544346900318837, Math.floor(this.e / 3)); } if (mod !== 0) { return ME(newMantissa * 4.6415888336127789, Math.floor(this.e / 3)); } // mod != 0 at this point means 'mod == 2 || mod == -2' return ME(newMantissa, Math.floor(this.e / 3)); } // Some hyperbolic trig functions that happen to be easy public sinh() { return this.exp().sub(this.negate().exp()).div(2); } public cosh() { return this.exp().add(this.negate().exp()).div(2); } public tanh() { return this.sinh().div(this.cosh()); } public asinh() { return Decimal.ln(this.add(this.sqr().add(1).sqrt())); } public acosh() { return Decimal.ln(this.add(this.sqr().sub(1).sqrt())); } public atanh() { if (this.abs().gte(1)) { return Number.NaN; } return Decimal.ln(this.add(1).div(new Decimal(1).sub(this))) / 2; } /** * Joke function from Realm Grinder */ public ascensionPenalty(ascensions: number) { if (ascensions === 0) { return this; } return this.pow(Math.pow(10, -ascensions)); } /** * Joke function from Cookie Clicker. It's 'egg' */ public egg() { return this.add(9); } public lessThanOrEqualTo(other: DecimalSource) { return this.cmp(other) < 1; } public lessThan(other: DecimalSource) { return this.cmp(other) < 0; } public greaterThanOrEqualTo(other: DecimalSource) { return this.cmp(other) > -1; } public greaterThan(other: DecimalSource) { return this.cmp(other) > 0; } public decimalPlaces() { return this.dp(); } public dp() { if (!isFinite(this.mantissa)) { return NaN; } if (this.exponent >= MAX_SIGNIFICANT_DIGITS) { return 0; } const mantissa = this.mantissa; let places = -this.exponent; let e = 1; while (Math.abs(Math.round(mantissa * e) / e - mantissa) > ROUND_TOLERANCE) { e *= 10; places++; } return places > 0 ? places : 0; } public static get MAX_VALUE() { return MAX_VALUE; } public static get MIN_VALUE() { return MIN_VALUE; } public static get NUMBER_MAX_VALUE() { return NUMBER_MAX_VALUE; } public static get NUMBER_MIN_VALUE() { return NUMBER_MIN_VALUE; } } const MAX_VALUE = ME_NN(1, EXP_LIMIT); const MIN_VALUE = ME_NN(1, -EXP_LIMIT); const NUMBER_MAX_VALUE = D(Number.MAX_VALUE); const NUMBER_MIN_VALUE = D(Number.MIN_VALUE);
the_stack
import styles from "./catalog.module.scss"; import React from "react"; import { disposeOnUnmount, observer } from "mobx-react"; import { ItemListLayout } from "../item-object-list"; import type { IComputedValue } from "mobx"; import { action, computed, makeObservable, observable, reaction, runInAction, when } from "mobx"; import type { CatalogEntityStore } from "./catalog-entity-store/catalog-entity.store"; import { MenuItem, MenuActions } from "../menu"; import type { CatalogEntityContextMenu } from "../../api/catalog-entity"; import type { CatalogCategory, CatalogCategoryRegistry, CatalogEntity } from "../../../common/catalog"; import { CatalogAddButton } from "./catalog-add-button"; import { Notifications } from "../notifications"; import { MainLayout } from "../layout/main-layout"; import type { StorageLayer } from "../../utils"; import { prevDefault } from "../../utils"; import { CatalogEntityDetails } from "./catalog-entity-details"; import { CatalogMenu } from "./catalog-menu"; import { RenderDelay } from "../render-delay/render-delay"; import { Icon } from "../icon"; import { HotbarToggleMenuItem } from "./hotbar-toggle-menu-item"; import { Avatar } from "../avatar"; import { withInjectables } from "@ogre-tools/injectable-react"; import catalogPreviousActiveTabStorageInjectable from "./catalog-previous-active-tab-storage/catalog-previous-active-tab-storage.injectable"; import catalogEntityStoreInjectable from "./catalog-entity-store/catalog-entity-store.injectable"; import type { GetCategoryColumnsParams, CategoryColumns } from "./columns/get.injectable"; import getCategoryColumnsInjectable from "./columns/get.injectable"; import type { RegisteredCustomCategoryViewDecl } from "./custom-views.injectable"; import customCategoryViewsInjectable from "./custom-views.injectable"; import type { CustomCategoryViewComponents } from "./custom-views"; import type { NavigateToCatalog } from "../../../common/front-end-routing/routes/catalog/navigate-to-catalog.injectable"; import navigateToCatalogInjectable from "../../../common/front-end-routing/routes/catalog/navigate-to-catalog.injectable"; import catalogRouteParametersInjectable from "./catalog-route-parameters.injectable"; import { browseCatalogTab } from "./catalog-browse-tab"; import type { AppEvent } from "../../../common/app-event-bus/event-bus"; import appEventBusInjectable from "../../../common/app-event-bus/app-event-bus.injectable"; import hotbarStoreInjectable from "../../../common/hotbars/store.injectable"; import type { HotbarStore } from "../../../common/hotbars/store"; import type { VisitEntityContextMenu } from "../../../common/catalog/visit-entity-context-menu.injectable"; import catalogCategoryRegistryInjectable from "../../../common/catalog/category-registry.injectable"; import visitEntityContextMenuInjectable from "../../../common/catalog/visit-entity-context-menu.injectable"; import type { Navigate } from "../../navigation/navigate.injectable"; import navigateInjectable from "../../navigation/navigate.injectable"; import type { NormalizeCatalogEntityContextMenu } from "../../catalog/normalize-menu-item.injectable"; import normalizeCatalogEntityContextMenuInjectable from "../../catalog/normalize-menu-item.injectable"; interface Dependencies { catalogPreviousActiveTabStorage: StorageLayer<string | null>; catalogEntityStore: CatalogEntityStore; getCategoryColumns: (params: GetCategoryColumnsParams) => CategoryColumns; customCategoryViews: IComputedValue<Map<string, Map<string, RegisteredCustomCategoryViewDecl>>>; emitEvent: (event: AppEvent) => void; routeParameters: { group: IComputedValue<string>; kind: IComputedValue<string>; }; navigateToCatalog: NavigateToCatalog; hotbarStore: HotbarStore; catalogCategoryRegistry: CatalogCategoryRegistry; visitEntityContextMenu: VisitEntityContextMenu; navigate: Navigate; normalizeMenuItem: NormalizeCatalogEntityContextMenu; } @observer class NonInjectedCatalog extends React.Component<Dependencies> { private readonly menuItems = observable.array<CatalogEntityContextMenu>(); @observable activeTab?: string; constructor(props: Dependencies) { super(props); makeObservable(this); } @computed get routeActiveTab(): string { const { group, kind } = this.props.routeParameters; const dereferencedGroup = group.get(); const dereferencedKind = kind.get(); if (dereferencedGroup && dereferencedKind) { return `${dereferencedGroup}/${dereferencedKind}`; } const previousTab = this.props.catalogPreviousActiveTabStorage.get(); if (previousTab) { return previousTab; } return browseCatalogTab; } async componentDidMount() { const { catalogEntityStore, catalogPreviousActiveTabStorage, catalogCategoryRegistry, } = this.props; disposeOnUnmount(this, [ catalogEntityStore.watch(), reaction(() => this.routeActiveTab, async (routeTab) => { catalogPreviousActiveTabStorage.set(this.routeActiveTab); try { await when(() => (routeTab === browseCatalogTab || !!catalogCategoryRegistry.filteredItems.find(i => i.getId() === routeTab)), { timeout: 5_000 }); // we need to wait because extensions might take a while to load const item = catalogCategoryRegistry.filteredItems.find(i => i.getId() === routeTab); runInAction(() => { this.activeTab = routeTab; catalogEntityStore.activeCategory.set(item); }); } catch (error) { console.error(error); Notifications.error(( <p> {"Unknown category: "} {routeTab} </p> )); } }, { fireImmediately: true }), // If active category is filtered out, automatically switch to the first category reaction(() => catalogCategoryRegistry.filteredItems, () => { if (!catalogCategoryRegistry.filteredItems.find(item => item.getId() === catalogEntityStore.activeCategory.get()?.getId())) { const item = catalogCategoryRegistry.filteredItems[0]; runInAction(() => { if (item) { this.activeTab = item.getId(); this.props.catalogEntityStore.activeCategory.set(item); } }); } }), ]); this.props.emitEvent({ name: "catalog", action: "open", }); } addToHotbar(entity: CatalogEntity): void { this.props.hotbarStore.addToHotbar(entity); } removeFromHotbar(entity: CatalogEntity): void { this.props.hotbarStore.removeFromHotbar(entity.getId()); } onDetails = (entity: CatalogEntity) => { if (this.props.catalogEntityStore.selectedItemId.get()) { this.props.catalogEntityStore.selectedItemId.set(undefined); } else { this.props.catalogEntityStore.onRun(entity); } }; get categories() { return this.props.catalogCategoryRegistry.items; } onTabChange = action((tabId: string | null) => { const activeCategory = this.categories.find(category => category.getId() === tabId); this.props.emitEvent({ name: "catalog", action: "change-category", params: { category: activeCategory ? activeCategory.getName() : "Browse", }, }); if (activeCategory) { this.props.catalogPreviousActiveTabStorage.set(`${activeCategory.spec.group}/${activeCategory.spec.names.kind}`); this.props.navigateToCatalog({ group: activeCategory.spec.group, kind: activeCategory.spec.names.kind }); } else { this.props.catalogPreviousActiveTabStorage.set(null); this.props.navigateToCatalog({ group: browseCatalogTab }); } }); renderItemMenu = (entity: CatalogEntity) => { const onOpen = () => { this.menuItems.clear(); this.props.visitEntityContextMenu(entity, { menuItems: this.menuItems, navigate: this.props.navigate, }); }; return ( <MenuActions onOpen={onOpen}> <MenuItem key="open-details" onClick={() => this.props.catalogEntityStore.selectedItemId.set(entity.getId())} > View Details </MenuItem> { this.menuItems .map(this.props.normalizeMenuItem) .map((menuItem, index) => ( <MenuItem key={index} onClick={menuItem.onClick}> {menuItem.title} </MenuItem> )) } <HotbarToggleMenuItem key="hotbar-toggle" entity={entity} addContent="Add to Hotbar" removeContent="Remove from Hotbar" /> </MenuActions> ); }; renderName(entity: CatalogEntity) { const isItemInHotbar = this.props.hotbarStore.isAddedToActive(entity); return ( <> <Avatar title={entity.getName()} colorHash={`${entity.getName()}-${entity.getSource()}`} src={entity.spec.icon?.src} background={entity.spec.icon?.background} className={styles.catalogAvatar} size={24} > {entity.spec.icon?.material && <Icon material={entity.spec.icon?.material} small/>} </Avatar> <span>{entity.getName()}</span> <Icon small className={styles.pinIcon} svg={isItemInHotbar ? "push_off" : "push_pin"} tooltip={isItemInHotbar ? "Remove from Hotbar" : "Add to Hotbar"} onClick={prevDefault(() => isItemInHotbar ? this.removeFromHotbar(entity) : this.addToHotbar(entity))} /> </> ); } renderViews = (activeCategory: CatalogCategory | undefined) => { if (!activeCategory) { return this.renderList(activeCategory); } const customViews = this.props.customCategoryViews.get() .get(activeCategory.spec.group) ?.get(activeCategory.spec.names.kind); const renderView = ({ View }: CustomCategoryViewComponents, index: number) => ( <View key={index} category={activeCategory} /> ); return ( <> {customViews?.before.map(renderView)} {this.renderList(activeCategory)} {customViews?.after.map(renderView)} </> ); }; renderList(activeCategory: CatalogCategory | undefined) { const { catalogEntityStore, getCategoryColumns } = this.props; const tableId = activeCategory ? `catalog-items-${activeCategory.metadata.name.replace(" ", "")}` : "catalog-items"; if (this.activeTab === undefined) { return null; } return ( <ItemListLayout<CatalogEntity, false> className={styles.Catalog} tableId={tableId} renderHeaderTitle={activeCategory?.metadata.name ?? "Browse All"} isSelectable={false} isConfigurable={true} preloadStores={false} store={catalogEntityStore} getItems={() => catalogEntityStore.entities.get()} customizeTableRowProps={entity => ({ disabled: !entity.isEnabled(), })} {...getCategoryColumns({ activeCategory })} onDetails={this.onDetails} renderItemMenu={this.renderItemMenu} /> ); } render() { if (!this.props.catalogEntityStore) { return null; } const activeCategory = this.props.catalogEntityStore.activeCategory.get(); const selectedItem = this.props.catalogEntityStore.selectedItem.get(); return ( <MainLayout sidebar={( <CatalogMenu activeTab={this.activeTab} onItemClick={this.onTabChange} /> )} > <div className={styles.views}> {this.renderViews(activeCategory)} </div> { selectedItem ? ( <CatalogEntityDetails entity={selectedItem} hideDetails={() => this.props.catalogEntityStore.selectedItemId.set(undefined)} onRun={() => this.props.catalogEntityStore.onRun(selectedItem)} /> ) : activeCategory ? ( <RenderDelay> <CatalogAddButton category={activeCategory} /> </RenderDelay> ) : null } </MainLayout> ); } } export const Catalog = withInjectables<Dependencies>(NonInjectedCatalog, { getProps: (di, props) => ({ ...props, catalogEntityStore: di.inject(catalogEntityStoreInjectable), catalogPreviousActiveTabStorage: di.inject(catalogPreviousActiveTabStorageInjectable), getCategoryColumns: di.inject(getCategoryColumnsInjectable), customCategoryViews: di.inject(customCategoryViewsInjectable), routeParameters: di.inject(catalogRouteParametersInjectable), navigateToCatalog: di.inject(navigateToCatalogInjectable), emitEvent: di.inject(appEventBusInjectable).emit, hotbarStore: di.inject(hotbarStoreInjectable), catalogCategoryRegistry: di.inject(catalogCategoryRegistryInjectable), visitEntityContextMenu: di.inject(visitEntityContextMenuInjectable), navigate: di.inject(navigateInjectable), normalizeMenuItem: di.inject(normalizeCatalogEntityContextMenuInjectable), }), });
the_stack
import * as vscode from 'vscode'; import * as fs from 'fs'; import { ext } from './extensionVariables'; import * as path from 'path'; import { JenkinsConnection } from './jenkinsConnection'; /** * Static class holding API query properties for jobs, builds, and nodes. */ export class QueryProperties { public static readonly job = [ 'name', 'fullName', 'url', 'buildable', 'inQueue', 'description' ].join(','); public static readonly jobMinimal = [ 'name', 'fullName', 'url', 'description' ].join(','); public static readonly build = [ 'number', 'result', 'description', 'url', 'duration', 'timestamp', 'building' ].join(','); public static readonly node = [ 'assignedLabels[name]', 'description', 'displayName', 'executors[idle,currentExecutable[displayName,timestamp,url]]', 'idle', 'offline', 'offlineCause', 'offlineCauseReason', 'temporarilyOffline' ].join(','); } function _sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Async sleep utility method. * @param ms Milliseconds to sleep. */ export async function sleep(ms: number) { await _sleep(ms); } export function getValidEditor() { let langIds = [ "groovy", "jenkinsfile", "java" ]; var editor = vscode.window.activeTextEditor; if (!editor || !langIds.includes(editor?.document.languageId)) { return undefined; } return editor; } export function timer() { let timeStart = new Date().getTime(); return { get seconds() { const seconds = Math.ceil((new Date().getTime() - timeStart) / 1000) + 's'; return seconds; }, get ms() { const ms = (new Date().getTime() - timeStart) + 'ms'; return ms; } }; } export async function withProgressOutput(title: string, func: () => Promise<string>): Promise<string> { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: title, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { vscode.window.showWarningMessage("User canceled command."); }); return await func(); }); } export async function withProgressOutputParallel(title: string, items: any[], func: (i: any) => Promise<string>) { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: title, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { vscode.window.showWarningMessage("User canceled command."); }); let results = await parallelTasks(items, func); return results.join(`\n${'-'.repeat(80)}\n`); }); } export async function showQuicPick(items: any[]): Promise<void> { let qp = vscode.window.createQuickPick(); qp.items = items; qp.title = ''; } export function filepath(...filenameParts: string[]): string { return ext.context.asAbsolutePath(path.join(...filenameParts)); } /** * Runs through logic that shores up backwards-compatibility issues found in settings.json. * NOTE: also for backwards compatibility for older host settings found in v0.0.* */ export async function applyBackwardsCompat() { let jenkinsConfig = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); // Applies default host or the legacy host connection info to the // list of jenkins hosts. let conns: any[] = (0 === jenkinsConfig.connections.length) ? [ { "name": "default", "uri": undefined === jenkinsConfig.uri ? 'http://127.0.0.1:8080' : jenkinsConfig.uri, "username": undefined === jenkinsConfig.username ? null : jenkinsConfig.username, "active": true } ] : jenkinsConfig.connections; // If any existing connections in settings.json have the "password" field, ask the user // if they would like to store them in the local-keystore for each connection. let connectionsWithPassword = jenkinsConfig.connections.filter((c: any) => null != c.password && '' != c.password); if (!connectionsWithPassword.length) { return; } let connectionsString = connectionsWithPassword.map((c: any) => c.name).join('\n'); let message = `Jenkins Jack: The latest version manages passwords from your system's key-store.\nWould you like to migrate your connection passwords in settings.json to the local key-store?\n\n${connectionsString}`; let result = await vscode.window.showInformationMessage(message, { modal: true }, { title: 'Yes' } ); if (undefined === result) { return undefined; } for (let c of connectionsWithPassword) { let conn = JenkinsConnection.fromJSON(c); await conn.setPassword(c.password); delete c.password; } vscode.window.showInformationMessage('Jenkins Jack: Passwords migrated successfully!'); await vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', conns, vscode.ConfigurationTarget.Global); } /** * Utility for parsing a json file and returning * its contents. * @param path The path to the json file. * @returns The parsed json. */ export function readjson(path: string): any { let raw: any = fs.readFileSync(path); let json: any; try { json = JSON.parse(raw); } catch (err) { err.message = `Could not parse parameter JSON from ${path}`; throw err; } return json; } /** * Writes the given json to disk. * @param path The the file path (file included) to write to. * @param json The json to write out. */ export function writejson(path: string, json: any) { try { let jsonString = JSON.stringify(json, null, 4); fs.writeFileSync(path, jsonString, 'utf8'); } catch (err) { err.message = `Could not write parameter JSON to ${path}`; throw err; } } /** * TODO: HACK * Returns some nasty hard-coded Jenkins Pipeline * XML as a Pipeline job config template. */ export function pipelineJobConfigXml() { return `<?xml version="1.0" encoding="UTF-8"?> <flow-definition plugin="workflow-job@2.10"> <description /> <keepDependencies>false</keepDependencies> <properties> <com.sonyericsson.rebuild.RebuildSettings plugin="rebuild@1.25"> <autoRebuild>false</autoRebuild> <rebuildDisabled>false</rebuildDisabled> </com.sonyericsson.rebuild.RebuildSettings> <com.synopsys.arc.jenkinsci.plugins.jobrestrictions.jobs.JobRestrictionProperty plugin="job-restrictions@0.4" /> <hudson.plugins.throttleconcurrents.ThrottleJobProperty plugin="throttle-concurrents@2.0"> <categories class="java.util.concurrent.CopyOnWriteArrayList" /> <throttleEnabled>false</throttleEnabled> <throttleOption>project</throttleOption> <limitOneJobWithMatchingParams>false</limitOneJobWithMatchingParams> <paramsToUseForLimit /> </hudson.plugins.throttleconcurrents.ThrottleJobProperty> <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty> <triggers /> </org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty> </properties> <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.29"> <script></script> <sandbox>false</sandbox> </definition> <triggers /> </flow-definition>`; } export function addeNodeLabelsScript(nodes: string[], labels: string[]): string { let labelsToken = ''; let nodesToken = ''; for (let l of labels) { labelsToken += ` "${l}",`; } for (let n of nodes) { nodesToken += ` "${n}",`; } return `import jenkins.model.*; import jenkins.model.Jenkins; // Labels you want to add def additionalLabels = [ <<LABELS>> ]; // Target machines to update def nodeNames = [ <<NODES>> ]; jenkins = Jenkins.instance; for (node in nodeNames) { println jenkins.getSlave(node); def node = jenkins.getNode(node); def labelsStr = node.labelString; validLabels = additionalLabels.findAll { l -> !labelsStr.contains(l) }; if (validLabels.isEmpty()) { continue; } def validLabels = validLabels.join(' '); jenkins.getNode(node).setLabelString(labelsStr + ' ' + validLabels); } jenkins.setNodes(jenkins.getNodes()); jenkins.save();`.replace('<<LABELS>>', labelsToken).replace('<<NODES>>', nodesToken); } export async function parallelTasks<T>(items: any, action: ((item: any) => Promise<T>)): Promise<T[]> { let tasks: Promise<T>[] = []; for (let item of items) { let t = new Promise<T>(async (resolve) => { return resolve(action(item)); }); tasks.push(t); } return await Promise.all<T>(tasks); } /** * Groovy script for updating labels on the provided list of in nodes. * @param nodes A list of node names as strings * @param labels A list of labels to update on the nodes * @returns A script for updating nodes on the Jenkins server. */ export function updateNodeLabelsScript(nodes: string[], labels: string[]): string { let labelsToken = ''; let nodesToken = ''; for (let l of labels) { labelsToken += ` "${l}",`; } for (let n of nodes) { nodesToken += ` "${n}",`; } return `import jenkins.model.*; import jenkins.model.Jenkins; // Labels you want to add def newLabels = [ <<LABELS>> ]; // Target machines to update def nodeNames = [ <<NODES>> ]; jenkins = Jenkins.instance; for (nodeName in nodeNames) { def node = jenkins.getNode(nodeName); def labelsStr = node.labelString; jenkins.getNode(nodeName).setLabelString(newLabels.join(' ')); } jenkins.setNodes(jenkins.getNodes()); jenkins.save();`.replace('<<LABELS>>', labelsToken).replace('<<NODES>>', nodesToken); } /** * Converts a standard folder path into a supported Jenkins uri folder path. * @param folderPath The folder path (e.g. folder1/folder2/folder3) * @returns A supported Jenkins uri folder path (/folder1/job/folder2/job/folder3) */ export function folderToUri(folderPath: string) { return folderPath.split('/').join('/job/'); } /** * Converts timestamp into a date/time string. * @param timestamp Timestamp in milliseconds * @returns A formatted date/time string */ export function toDateString(timestamp: number): string { return `${new Date(timestamp).toLocaleString(undefined, { month: '2-digit', day: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false})}` } /** * Converts milliseconds into HH:MM:SS.MS string. * Taken from: https://stackoverflow.com/a/19700358 * @param duration Time in milliseconds */ export function msToTime(duration: number): string { // @ts-ignore var milliseconds = Math.floor((duration % 1000) / 100), seconds = Math.floor((duration / 1000) % 60), minutes = Math.floor((duration / (1000 * 60)) % 60), hours = Math.floor((duration / (1000 * 60 * 60)) % 24); let hrs = (hours < 10) ? "0" + hours : hours; let mins = (minutes < 10) ? "0" + minutes : minutes; let secs = (seconds < 10) ? "0" + seconds : seconds; return "+" + hrs + ":" + mins + ":" + secs; // + "." + milliseconds; } export function addDetail(detail: string): string { return `[${detail}] `; }
the_stack
module android.widget { import Resources = android.content.res.Resources; import Canvas = android.graphics.Canvas; import Matrix = android.graphics.Matrix; import RectF = android.graphics.RectF; import Drawable = android.graphics.drawable.Drawable; import TextUtils = android.text.TextUtils; import Log = android.util.Log; import View = android.view.View; import Integer = java.lang.Integer; import System = java.lang.System; import NetDrawable = androidui.image.NetDrawable; import LayoutParams = android.view.ViewGroup.LayoutParams; import AttrBinder = androidui.attr.AttrBinder; /** * Displays an arbitrary image, such as an icon. The ImageView class * can load images from various sources (such as resources or content * providers), takes care of computing its measurement from the image so that * it can be used in any layout manager, and provides various display options * such as scaling and tinting. * * @attr ref android.R.styleable#ImageView_adjustViewBounds * @attr ref android.R.styleable#ImageView_src * @attr ref android.R.styleable#ImageView_maxWidth * @attr ref android.R.styleable#ImageView_maxHeight * @attr ref android.R.styleable#ImageView_tint * @attr ref android.R.styleable#ImageView_scaleType * @attr ref android.R.styleable#ImageView_cropToPadding */ export class ImageView extends View { // settable by the client private mUri:string; //private mResource:number = 0; private mMatrix:Matrix; private mScaleType:ImageView.ScaleType; private mHaveFrame:boolean = false; private mAdjustViewBounds:boolean = false; private mMaxWidth:number = Integer.MAX_VALUE; private mMaxHeight:number = Integer.MAX_VALUE; //// these are applied to the drawable //private mColorFilter:ColorFilter; // //private mXfermode:Xfermode; private mAlpha:number = 255; private mViewAlphaScale:number = 256; private mColorMod:boolean = false; private mDrawable:Drawable = null; private mState:number[] = null; private mMergeState:boolean = false; private mLevel:number = 0; private mDrawableWidth:number = 0; private mDrawableHeight:number = 0; private mDrawMatrix:Matrix = null; // Avoid allocations... private mTempSrc:RectF = new RectF(); private mTempDst:RectF = new RectF(); private mCropToPadding:boolean; private mBaseline:number = -1; private mBaselineAlignBottom:boolean = false; // AdjustViewBounds behavior will be in compatibility mode for older apps. private mAdjustViewBoundsCompat:boolean = false; //private static sScaleTypeArray:ImageView.ScaleType[] = [ ImageView.ScaleType.MATRIX, ImageView.ScaleType.FIT_XY, // ImageView.ScaleType.FIT_START, ImageView.ScaleType.FIT_CENTER, ImageView.ScaleType.FIT_END, ImageView.ScaleType.CENTER, // ImageView.ScaleType.CENTER_CROP, ImageView.ScaleType.CENTER_INSIDE ]; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>){ super(context, bindElement, defStyle); this.initImageView(); let a = context.obtainStyledAttributes(bindElement, defStyle); let d = a.getDrawable('src'); if (d != null) { this.setImageDrawable(d); } this.mBaselineAlignBottom = a.getBoolean('baselineAlignBottom', false); this.mBaseline = a.getDimensionPixelSize('baseline', -1); this.setAdjustViewBounds(a.getBoolean('adjustViewBounds', false)); this.setMaxWidth(a.getDimensionPixelSize('maxWidth', Integer.MAX_VALUE)); this.setMaxHeight(a.getDimensionPixelSize('maxHeight', Integer.MAX_VALUE)); let scaleType = ImageView.parseScaleType(a.getString('scaleType'), null); if (scaleType != null) { this.setScaleType(scaleType); } // AndroidUI ignore: not support now. // let tint = a.getInt('tint', 0); // if (tint != 0) { // this.setColorFilter(tint); // } let alpha = a.getInt('drawableAlpha', 255); if (alpha != 255) { this.setAlpha(alpha); } this.mCropToPadding = a.getBoolean('cropToPadding', false); a.recycle(); //need inflate syntax/reader for matrix } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder() .set('src', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { let d = attrBinder.parseDrawable(value); if (d) v.setImageDrawable(d); else v.setImageURI(value); }, getter(v: ImageView) { return v.mDrawable; } }).set('baselineAlignBottom', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { v.setBaselineAlignBottom(attrBinder.parseBoolean(value, v.mBaselineAlignBottom)); }, getter(v: ImageView) { return v.getBaselineAlignBottom(); } }).set('baseline', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { v.setBaseline(attrBinder.parseNumberPixelSize(value, v.mBaseline)); }, getter(v: ImageView) { return v.mBaseline; } }).set('adjustViewBounds', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { v.setAdjustViewBounds(attrBinder.parseBoolean(value, false)); }, getter(v: ImageView) { return v.getAdjustViewBounds(); } }).set('maxWidth', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { let baseValue = v.getParent() instanceof View ? (<View><any>v.getParent()).getWidth() : 0; v.setMaxWidth(attrBinder.parseNumberPixelSize(value, v.mMaxWidth, baseValue)); }, getter(v: ImageView) { return v.mMaxWidth; } }).set('maxHeight', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { let baseValue = v.getParent() instanceof View ? (<View><any>v.getParent()).getHeight() : 0; v.setMaxHeight(attrBinder.parseNumberPixelSize(value, v.mMaxHeight, baseValue)); }, getter(v: ImageView) { return v.mMaxHeight; } }).set('scaleType', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { if (typeof value === 'number') { v.setScaleType(value); } else { v.setScaleType(ImageView.parseScaleType(value, v.mScaleType)); } }, getter(v: ImageView) { return v.mScaleType; } }).set('drawableAlpha', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { v.setImageAlpha(attrBinder.parseInt(value, v.mAlpha)); }, getter(v: ImageView) { return v.mAlpha; } }).set('cropToPadding', { setter(v: ImageView, value: any, attrBinder:AttrBinder) { v.setCropToPadding(attrBinder.parseBoolean(value, false)); }, getter(v: ImageView) { return v.getCropToPadding(); } }); } private initImageView():void { this.mMatrix = new Matrix(); this.mScaleType = ImageView.ScaleType.FIT_CENTER; //this.mAdjustViewBoundsCompat = this.mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1; } protected verifyDrawable(dr:Drawable):boolean { return this.mDrawable == dr || super.verifyDrawable(dr); } jumpDrawablesToCurrentState():void { super.jumpDrawablesToCurrentState(); if (this.mDrawable != null) this.mDrawable.jumpToCurrentState(); } invalidateDrawable(dr:Drawable):void { if (dr == this.mDrawable) { /* we invalidate the whole view in this case because it's very * hard to know where the drawable actually is. This is made * complicated because of the offsets and transformations that * can be applied. In theory we could get the drawable's bounds * and run them through the transformation and offsets, but this * is probably not worth the effort. */ this.invalidate(); } else { super.invalidateDrawable(dr); } } drawableSizeChange(who : Drawable):void{ if (who == this.mDrawable) { this.resizeFromDrawable(); }else { super.drawableSizeChange(who); } } hasOverlappingRendering():boolean { return (this.getBackground() != null && this.getBackground().getCurrent() != null); } //onPopulateAccessibilityEvent(event:AccessibilityEvent):void { // super.onPopulateAccessibilityEvent(event); // let contentDescription:CharSequence = this.getContentDescription(); // if (!TextUtils.isEmpty(contentDescription)) { // event.getText().add(contentDescription); // } //} /** * True when ImageView is adjusting its bounds * to preserve the aspect ratio of its drawable * * @return whether to adjust the bounds of this view * to presrve the original aspect ratio of the drawable * * @see #setAdjustViewBounds(boolean) * * @attr ref android.R.styleable#ImageView_adjustViewBounds */ getAdjustViewBounds():boolean { return this.mAdjustViewBounds; } /** * Set this to true if you want the ImageView to adjust its bounds * to preserve the aspect ratio of its drawable. * * <p><strong>Note:</strong> If the application targets API level 17 or lower, * adjustViewBounds will allow the drawable to shrink the view bounds, but not grow * to fill available measured space in all cases. This is for compatibility with * legacy {@link android.view.View.MeasureSpec MeasureSpec} and * {@link android.widget.RelativeLayout RelativeLayout} behavior.</p> * * @param adjustViewBounds Whether to adjust the bounds of this view * to preserve the original aspect ratio of the drawable. * * @see #getAdjustViewBounds() * * @attr ref android.R.styleable#ImageView_adjustViewBounds */ setAdjustViewBounds(adjustViewBounds:boolean):void { this.mAdjustViewBounds = adjustViewBounds; if (adjustViewBounds) { this.setScaleType(ImageView.ScaleType.FIT_CENTER); } } /** * The maximum width of this view. * * @return The maximum width of this view * * @see #setMaxWidth(int) * * @attr ref android.R.styleable#ImageView_maxWidth */ getMaxWidth():number { return this.mMaxWidth; } /** * An optional argument to supply a maximum width for this view. Only valid if * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a maximum * of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width * layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original * image is small. To set an image to a fixed size, specify that size in the layout params and * then use {@link #setScaleType(android.widget.ImageView.ScaleType)} to determine how to fit * the image within the bounds. * </p> * * @param maxWidth maximum width for this view * * @see #getMaxWidth() * * @attr ref android.R.styleable#ImageView_maxWidth */ setMaxWidth(maxWidth:number):void { this.mMaxWidth = maxWidth; } /** * The maximum height of this view. * * @return The maximum height of this view * * @see #setMaxHeight(int) * * @attr ref android.R.styleable#ImageView_maxHeight */ getMaxHeight():number { return this.mMaxHeight; } /** * An optional argument to supply a maximum height for this view. Only valid if * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width * layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original * image is small. To set an image to a fixed size, specify that size in the layout params and * then use {@link #setScaleType(android.widget.ImageView.ScaleType)} to determine how to fit * the image within the bounds. * </p> * * @param maxHeight maximum height for this view * * @see #getMaxHeight() * * @attr ref android.R.styleable#ImageView_maxHeight */ setMaxHeight(maxHeight:number):void { this.mMaxHeight = maxHeight; } /** Return the view's drawable, or null if no drawable has been assigned. */ getDrawable():Drawable { return this.mDrawable; } ///** // * Sets a drawable as the content of this ImageView. // * // * <p class="note">This does Bitmap reading and decoding on the UI // * thread, which can cause a latency hiccup. If that's a concern, // * consider using {@link #setImageDrawable(android.graphics.drawable.Drawable)} or // * {@link #setImageBitmap(android.graphics.Bitmap)} and // * {@link android.graphics.BitmapFactory} instead.</p> // * // * @param resId the resource identifier of the drawable // * // * @attr ref android.R.styleable#ImageView_src // */ //setImageResource(resId:number):void { // if (this.mUri != null || this.mResource != resId) { // this.updateDrawable(null); // this.mResource = resId; // this.mUri = null; // const oldWidth:number = this.mDrawableWidth; // const oldHeight:number = this.mDrawableHeight; // this.resolveUri(); // if (oldWidth != this.mDrawableWidth || oldHeight != this.mDrawableHeight) { // this.requestLayout(); // } // this.invalidate(); // } //} /** * Sets the content of this ImageView to the specified Uri. * // * <p class="note">This does Bitmap reading and decoding on the UI // * thread, which can cause a latency hiccup. If that's a concern, // * consider using {@link #setImageDrawable(android.graphics.drawable.Drawable)} or // * {@link #setImageBitmap(android.graphics.Bitmap)} and // * {@link android.graphics.BitmapFactory} instead.</p> // * AndroidUI note: suggest to load net image use this method * * @param uri The Uri of an image */ setImageURI(uri:string):void { //if (this.mResource != 0 || (this.mUri != uri && (uri == null || this.mUri == null || !uri.equals(this.mUri)))) { if (this.mUri != uri) { if(this.mDrawable instanceof NetDrawable){//use same obj to load image this.mUri = uri; (<NetDrawable>this.mDrawable).setURL(uri); this.invalidate(); }else { this.updateDrawable(null); //this.mResource = 0; this.mUri = uri; const oldWidth:number = this.mDrawableWidth; const oldHeight:number = this.mDrawableHeight; this.resolveUri(); if (oldWidth != this.mDrawableWidth || oldHeight != this.mDrawableHeight) { this.requestLayout(); } this.invalidate(); } } } /** * Sets a drawable as the content of this ImageView. * * @param drawable The drawable to set */ setImageDrawable(drawable:Drawable):void { if (this.mDrawable != drawable) { //this.mResource = 0; this.mUri = null; const oldWidth:number = this.mDrawableWidth; const oldHeight:number = this.mDrawableHeight; this.updateDrawable(drawable); if (oldWidth != this.mDrawableWidth || oldHeight != this.mDrawableHeight) { this.requestLayout(); } this.invalidate(); } } ///** // * Sets a Bitmap as the content of this ImageView. // * // * @param bm The bitmap to set // */ //setImageBitmap(bm:Bitmap):void { // // if this is used frequently, may handle bitmaps explicitly // // to reduce the intermediate drawable object // this.setImageDrawable(new BitmapDrawable(this.mContext.getResources(), bm)); //} setImageState(state:number[], merge:boolean):void { this.mState = state; this.mMergeState = merge; if (this.mDrawable != null) { this.refreshDrawableState(); this.resizeFromDrawable(); } } setSelected(selected:boolean):void { super.setSelected(selected); this.resizeFromDrawable(); } /** * Sets the image level, when it is constructed from a * {@link android.graphics.drawable.LevelListDrawable}. * * @param level The new level for the image. */ setImageLevel(level:number):void { this.mLevel = level; if (this.mDrawable != null) { this.mDrawable.setLevel(level); this.resizeFromDrawable(); } } /** * Controls how the image should be resized or moved to match the size * of this ImageView. * * @param scaleType The desired scaling mode. * * @attr ref android.R.styleable#ImageView_scaleType */ setScaleType(scaleType:ImageView.ScaleType):void { if (scaleType == null) { throw Error(`new NullPointerException()`); } if (this.mScaleType != scaleType) { this.mScaleType = scaleType; this.setWillNotCacheDrawing(this.mScaleType == ImageView.ScaleType.CENTER); this.requestLayout(); this.invalidate(); } } /** * Return the current scale type in use by this ImageView. * * @see ImageView.ScaleType * * @attr ref android.R.styleable#ImageView_scaleType */ getScaleType():ImageView.ScaleType { return this.mScaleType; } /** Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this method will return an identity matrix. Do not change this matrix in place but make a copy. If you want a different matrix applied to the drawable, be sure to call setImageMatrix(). */ getImageMatrix():Matrix { if (this.mDrawMatrix == null) { return new Matrix(Matrix.IDENTITY_MATRIX); } return this.mDrawMatrix; } setImageMatrix(matrix:Matrix):void { // collaps null and identity to just null if (matrix != null && matrix.isIdentity()) { matrix = null; } // don't invalidate unless we're actually changing our matrix if (matrix == null && !this.mMatrix.isIdentity() || matrix != null && !this.mMatrix.equals(matrix)) { this.mMatrix.set(matrix); this.configureBounds(); this.invalidate(); } } /** * Return whether this ImageView crops to padding. * * @return whether this ImageView crops to padding * * @see #setCropToPadding(boolean) * * @attr ref android.R.styleable#ImageView_cropToPadding */ getCropToPadding():boolean { return this.mCropToPadding; } /** * Sets whether this ImageView will crop to padding. * * @param cropToPadding whether this ImageView will crop to padding * * @see #getCropToPadding() * * @attr ref android.R.styleable#ImageView_cropToPadding */ setCropToPadding(cropToPadding:boolean):void { if (this.mCropToPadding != cropToPadding) { this.mCropToPadding = cropToPadding; this.requestLayout(); this.invalidate(); } } private resolveUri():void { if (this.mDrawable != null) { return; } let d:Drawable = null; if (this.mUri != null) { d = new androidui.image.NetDrawable(this.mUri); } else { return; } this.updateDrawable(d); } onCreateDrawableState(extraSpace:number):number[] { if (this.mState == null) { return super.onCreateDrawableState(extraSpace); } else if (!this.mMergeState) { return this.mState; } else { return ImageView.mergeDrawableStates(super.onCreateDrawableState(extraSpace + this.mState.length), this.mState); } } private updateDrawable(d:Drawable):void { if (this.mDrawable != null) { this.mDrawable.setCallback(null); this.unscheduleDrawable(this.mDrawable); } this.mDrawable = d; if (d != null) { d.setCallback(this); if (d.isStateful()) { d.setState(this.getDrawableState()); } d.setLevel(this.mLevel); //d.setLayoutDirection(this.getLayoutDirection()); d.setVisible(this.getVisibility() == ImageView.VISIBLE, true); this.mDrawableWidth = d.getIntrinsicWidth(); this.mDrawableHeight = d.getIntrinsicHeight(); this.applyColorMod(); this.configureBounds(); } else { this.mDrawableWidth = this.mDrawableHeight = -1; } } protected resizeFromDrawable():boolean { let d:Drawable = this.mDrawable; if (d != null) { let w:number = d.getIntrinsicWidth(); if (w < 0) w = this.mDrawableWidth; let h:number = d.getIntrinsicHeight(); if (h < 0) h = this.mDrawableHeight; if (w != this.mDrawableWidth || h != this.mDrawableHeight) { this.mDrawableWidth = w; this.mDrawableHeight = h; if (this.mLayoutParams!=null && this.mLayoutParams.width != LayoutParams.WRAP_CONTENT && this.mLayoutParams.width != LayoutParams.MATCH_PARENT && this.mLayoutParams.height != LayoutParams.WRAP_CONTENT && this.mLayoutParams.height != LayoutParams.MATCH_PARENT) { // In a fixed-size view, no need requestLayout. this.configureBounds(); } else { this.requestLayout(); } this.invalidate(); return true; } } return false; } //onRtlPropertiesChanged(layoutDirection:number):void { // super.onRtlPropertiesChanged(layoutDirection); // if (this.mDrawable != null) { // this.mDrawable.setLayoutDirection(layoutDirection); // } //} private static sS2FArray:Matrix.ScaleToFit[] = [ Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END ]; private static scaleTypeToScaleToFit(st:ImageView.ScaleType):Matrix.ScaleToFit { // ScaleToFit enum to their corresponding Matrix.ScaleToFit values return ImageView.sS2FArray[st - 1]; } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { this.resolveUri(); let w:number; let h:number; // Desired aspect ratio of the view's contents (not including padding) let desiredAspect:number = 0.0; // We are allowed to change the view's width let resizeWidth:boolean = false; // We are allowed to change the view's height let resizeHeight:boolean = false; const widthSpecMode:number = View.MeasureSpec.getMode(widthMeasureSpec); const heightSpecMode:number = View.MeasureSpec.getMode(heightMeasureSpec); if (this.mDrawable == null) { // If no drawable, its intrinsic size is 0. this.mDrawableWidth = -1; this.mDrawableHeight = -1; w = h = 0; } else { w = this.mDrawableWidth; h = this.mDrawableHeight; if (w <= 0) w = 1; if (h <= 0) h = 1; // ratio of our drawable. See if that is possible. if (this.mAdjustViewBounds) { resizeWidth = widthSpecMode != View.MeasureSpec.EXACTLY; resizeHeight = heightSpecMode != View.MeasureSpec.EXACTLY; desiredAspect = <number> w / <number> h; } } let pleft:number = this.mPaddingLeft; let pright:number = this.mPaddingRight; let ptop:number = this.mPaddingTop; let pbottom:number = this.mPaddingBottom; let widthSize:number; let heightSize:number; if (resizeWidth || resizeHeight) { /* If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at least one dimension. */ // Get the max possible width given our constraints widthSize = this.resolveAdjustedSize(w + pleft + pright, this.mMaxWidth, widthMeasureSpec); // Get the max possible height given our constraints heightSize = this.resolveAdjustedSize(h + ptop + pbottom, this.mMaxHeight, heightMeasureSpec); if (desiredAspect != 0.0) { // See what our actual aspect ratio is let actualAspect:number = <number> (widthSize - pleft - pright) / (heightSize - ptop - pbottom); if (Math.abs(actualAspect - desiredAspect) > 0.0000001) { let done:boolean = false; // Try adjusting width to be proportional to height if (resizeWidth) { let newWidth:number = Math.floor((desiredAspect * (heightSize - ptop - pbottom))) + pleft + pright; // Allow the width to outgrow its original estimate if height is fixed. if (!resizeHeight && !this.mAdjustViewBoundsCompat) { widthSize = this.resolveAdjustedSize(newWidth, this.mMaxWidth, widthMeasureSpec); } if (newWidth <= widthSize) { widthSize = newWidth; done = true; } } // Try adjusting height to be proportional to width if (!done && resizeHeight) { let newHeight:number = Math.floor(((widthSize - pleft - pright) / desiredAspect)) + ptop + pbottom; // Allow the height to outgrow its original estimate if width is fixed. if (!resizeWidth && !this.mAdjustViewBoundsCompat) { heightSize = this.resolveAdjustedSize(newHeight, this.mMaxHeight, heightMeasureSpec); } if (newHeight <= heightSize) { heightSize = newHeight; } } } } } else { /* We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just measure in the normal way. */ w += pleft + pright; h += ptop + pbottom; w = Math.max(w, this.getSuggestedMinimumWidth()); h = Math.max(h, this.getSuggestedMinimumHeight()); widthSize = ImageView.resolveSizeAndState(w, widthMeasureSpec, 0); heightSize = ImageView.resolveSizeAndState(h, heightMeasureSpec, 0); } this.setMeasuredDimension(widthSize, heightSize); } private resolveAdjustedSize(desiredSize:number, maxSize:number, measureSpec:number):number { let result:number = desiredSize; let specMode:number = View.MeasureSpec.getMode(measureSpec); let specSize:number = View.MeasureSpec.getSize(measureSpec); switch(specMode) { case View.MeasureSpec.UNSPECIFIED: /* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves. */ result = Math.min(desiredSize, maxSize); break; case View.MeasureSpec.AT_MOST: // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min(Math.min(desiredSize, specSize), maxSize); break; case View.MeasureSpec.EXACTLY: // No choice. Do what we are told. result = specSize; break; } return result; } protected setFrame(l:number, t:number, r:number, b:number):boolean { let changed:boolean = super.setFrame(l, t, r, b); this.mHaveFrame = true; this.configureBounds(); return changed; } private configureBounds():void { if (this.mDrawable == null || !this.mHaveFrame) { return; } let dwidth:number = this.mDrawableWidth; let dheight:number = this.mDrawableHeight; let vwidth:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; let vheight:number = this.getHeight() - this.mPaddingTop - this.mPaddingBottom; let fits:boolean = (dwidth < 0 || vwidth == dwidth) && (dheight < 0 || vheight == dheight); if (dwidth <= 0 || dheight <= 0 || ImageView.ScaleType.FIT_XY == this.mScaleType) { /* If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view. */ this.mDrawable.setBounds(0, 0, vwidth, vheight); this.mDrawMatrix = null; } else { // We need to do the scaling ourself, so have the drawable // use its native size. this.mDrawable.setBounds(0, 0, dwidth, dheight); if (ImageView.ScaleType.MATRIX == this.mScaleType) { // Use the specified matrix as-is. if (this.mMatrix.isIdentity()) { this.mDrawMatrix = null; } else { this.mDrawMatrix = this.mMatrix; } } else if (fits) { // The bitmap fits exactly, no transform needed. this.mDrawMatrix = null; } else if (ImageView.ScaleType.CENTER == this.mScaleType) { // Center bitmap in view, no scaling. this.mDrawMatrix = this.mMatrix; this.mDrawMatrix.setTranslate(Math.floor(((vwidth - dwidth) * 0.5 + 0.5)), Math.floor(((vheight - dheight) * 0.5 + 0.5))); } else if (ImageView.ScaleType.CENTER_CROP == this.mScaleType) { this.mDrawMatrix = this.mMatrix; let scale:number; let dx:number = 0, dy:number = 0; if (dwidth * vheight > vwidth * dheight) { scale = <number> vheight / <number> dheight; dx = (vwidth - dwidth * scale) * 0.5; } else { scale = <number> vwidth / <number> dwidth; dy = (vheight - dheight * scale) * 0.5; } this.mDrawMatrix.setScale(scale, scale); this.mDrawMatrix.postTranslate(Math.floor((dx + 0.5)), Math.floor((dy + 0.5))); } else if (ImageView.ScaleType.CENTER_INSIDE == this.mScaleType) { this.mDrawMatrix = this.mMatrix; let scale:number; let dx:number; let dy:number; if (dwidth <= vwidth && dheight <= vheight) { scale = 1.0; } else { scale = Math.min(<number> vwidth / <number> dwidth, <number> vheight / <number> dheight); } dx = Math.floor(((vwidth - dwidth * scale) * 0.5 + 0.5)); dy = Math.floor(((vheight - dheight * scale) * 0.5 + 0.5)); this.mDrawMatrix.setScale(scale, scale); this.mDrawMatrix.postTranslate(dx, dy); } else { // Generate the required transform. this.mTempSrc.set(0, 0, dwidth, dheight); this.mTempDst.set(0, 0, vwidth, vheight); this.mDrawMatrix = this.mMatrix; this.mDrawMatrix.setRectToRect(this.mTempSrc, this.mTempDst, ImageView.scaleTypeToScaleToFit(this.mScaleType)); } } } protected drawableStateChanged():void { super.drawableStateChanged(); let d:Drawable = this.mDrawable; if (d != null && d.isStateful()) { d.setState(this.getDrawableState()); } } protected onDraw(canvas:Canvas):void { super.onDraw(canvas); if (this.mDrawable == null) { // couldn't resolve the URI return; } if (this.mDrawableWidth == 0 || this.mDrawableHeight == 0) { // nothing to draw (empty bounds) return; } if (this.mDrawMatrix == null && this.mPaddingTop == 0 && this.mPaddingLeft == 0) { this.mDrawable.draw(canvas); } else { let saveCount:number = canvas.getSaveCount(); canvas.save(); if (this.mCropToPadding) { const scrollX:number = this.mScrollX; const scrollY:number = this.mScrollY; canvas.clipRect(scrollX + this.mPaddingLeft, scrollY + this.mPaddingTop, scrollX + this.mRight - this.mLeft - this.mPaddingRight, scrollY + this.mBottom - this.mTop - this.mPaddingBottom); } canvas.translate(this.mPaddingLeft, this.mPaddingTop); if (this.mDrawMatrix != null) { canvas.concat(this.mDrawMatrix); } this.mDrawable.draw(canvas); canvas.restoreToCount(saveCount); } } /** * <p>Return the offset of the widget's text baseline from the widget's top * boundary. </p> * * @return the offset of the baseline within the widget's bounds or -1 * if baseline alignment is not supported. */ getBaseline():number { if (this.mBaselineAlignBottom) { return this.getMeasuredHeight(); } else { return this.mBaseline; } } /** * <p>Set the offset of the widget's text baseline from the widget's top * boundary. This value is overridden by the {@link #setBaselineAlignBottom(boolean)} * property.</p> * * @param baseline The baseline to use, or -1 if none is to be provided. * * @see #setBaseline(int) * @attr ref android.R.styleable#ImageView_baseline */ setBaseline(baseline:number):void { if (this.mBaseline != baseline) { this.mBaseline = baseline; this.requestLayout(); } } /** * Set whether to set the baseline of this view to the bottom of the view. * Setting this value overrides any calls to setBaseline. * * @param aligned If true, the image view will be baseline aligned with * based on its bottom edge. * * @attr ref android.R.styleable#ImageView_baselineAlignBottom */ setBaselineAlignBottom(aligned:boolean):void { if (this.mBaselineAlignBottom != aligned) { this.mBaselineAlignBottom = aligned; this.requestLayout(); } } /** * Return whether this view's baseline will be considered the bottom of the view. * * @see #setBaselineAlignBottom(boolean) */ getBaselineAlignBottom():boolean { return this.mBaselineAlignBottom; } ///** // * Set a tinting option for the image. // * // * @param color Color tint to apply. // * @param mode How to apply the color. The standard mode is // * {@link PorterDuff.Mode#SRC_ATOP} // * // * @attr ref android.R.styleable#ImageView_tint // */ //setColorFilter(color:number, mode:PorterDuff.Mode):void { // this.setColorFilter(new PorterDuffColorFilter(color, mode)); //} // ///** // * Set a tinting option for the image. Assumes // * {@link PorterDuff.Mode#SRC_ATOP} blending mode. // * // * @param color Color tint to apply. // * @attr ref android.R.styleable#ImageView_tint // */ //setColorFilter(color:number):void { // this.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); //} // //clearColorFilter():void { // this.setColorFilter(null); //} // ///** // * @hide Candidate for future API inclusion // */ //setXfermode(mode:Xfermode):void { // if (this.mXfermode != mode) { // this.mXfermode = mode; // this.mColorMod = true; // this.applyColorMod(); // this.invalidate(); // } //} // ///** // * Returns the active color filter for this ImageView. // * // * @return the active color filter for this ImageView // * // * @see #setColorFilter(android.graphics.ColorFilter) // */ //getColorFilter():ColorFilter { // return this.mColorFilter; //} // ///** // * Apply an arbitrary colorfilter to the image. // * // * @param cf the colorfilter to apply (may be null) // * // * @see #getColorFilter() // */ //setColorFilter(cf:ColorFilter):void { // if (this.mColorFilter != cf) { // this.mColorFilter = cf; // this.mColorMod = true; // this.applyColorMod(); // this.invalidate(); // } //} /** * Returns the alpha that will be applied to the drawable of this ImageView. * * @return the alpha that will be applied to the drawable of this ImageView * * @see #setImageAlpha(int) */ getImageAlpha():number { return this.mAlpha; } /** * Sets the alpha value that should be applied to the image. * * @param alpha the alpha value that should be applied to the image * * @see #getImageAlpha() */ setImageAlpha(alpha:number):void { // keep it legal alpha &= 0xFF; if (this.mAlpha != alpha) { this.mAlpha = alpha; this.mColorMod = true; this.applyColorMod(); this.invalidate(); } } ///** // * Sets the alpha value that should be applied to the image. // * // * @param alpha the alpha value that should be applied to the image // * // * @deprecated use #setImageAlpha(int) instead // */ //setAlpha(alpha:number):void { // // keep it legal // alpha &= 0xFF; // if (this.mAlpha != alpha) { // this.mAlpha = alpha; // this.mColorMod = true; // this.applyColorMod(); // this.invalidate(); // } //} private applyColorMod():void { // re-applied if the Drawable is changed. if (this.mDrawable != null && this.mColorMod) { this.mDrawable = this.mDrawable.mutate(); //this.mDrawable.setColorFilter(this.mColorFilter); //this.mDrawable.setXfermode(this.mXfermode); this.mDrawable.setAlpha(this.mAlpha * this.mViewAlphaScale >> 8); } } setVisibility(visibility:number):void { super.setVisibility(visibility); if (this.mDrawable != null) { this.mDrawable.setVisible(visibility == ImageView.VISIBLE, false); } } protected onAttachedToWindow():void { super.onAttachedToWindow(); if (this.mDrawable != null) { this.mDrawable.setVisible(this.getVisibility() == ImageView.VISIBLE, false); } } protected onDetachedFromWindow():void { super.onDetachedFromWindow(); if (this.mDrawable != null) { this.mDrawable.setVisible(false, false); } } //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(ImageView.class.getName()); //} // //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(ImageView.class.getName()); //} static parseScaleType(s:string, defaultType:ImageView.ScaleType):ImageView.ScaleType{ if(s==null) return defaultType; s = s.toLowerCase(); if(s === 'matrix'.toLowerCase()) return ImageView.ScaleType.MATRIX; if(s === 'fitXY'.toLowerCase()) return ImageView.ScaleType.FIT_XY; if(s === 'fitStart'.toLowerCase()) return ImageView.ScaleType.FIT_START; if(s === 'fitCenter'.toLowerCase()) return ImageView.ScaleType.FIT_CENTER; if(s === 'fitEnd'.toLowerCase()) return ImageView.ScaleType.FIT_END; if(s === 'center'.toLowerCase()) return ImageView.ScaleType.CENTER; if(s === 'centerCrop'.toLowerCase()) return ImageView.ScaleType.CENTER_CROP; if(s === 'centerInside'.toLowerCase()) return ImageView.ScaleType.CENTER_INSIDE; return defaultType; } } export module ImageView{ /** * Options for scaling the bounds of an image to the bounds of this view. */ export enum ScaleType { /** * Scale using the image matrix when drawing. The image matrix can be set using * {@link ImageView#setImageMatrix(Matrix)}. From XML, use this syntax: * <code>android:scaleType="matrix"</code>. */ MATRIX /*(0) { } */, /** * Scale the image using {@link Matrix.ScaleToFit#FILL}. * From XML, use this syntax: <code>android:scaleType="fitXY"</code>. */ FIT_XY /*(1) { } */, /** * Scale the image using {@link Matrix.ScaleToFit#START}. * From XML, use this syntax: <code>android:scaleType="fitStart"</code>. */ FIT_START /*(2) { } */, /** * Scale the image using {@link Matrix.ScaleToFit#CENTER}. * From XML, use this syntax: * <code>android:scaleType="fitCenter"</code>. */ FIT_CENTER /*(3) { } */, /** * Scale the image using {@link Matrix.ScaleToFit#END}. * From XML, use this syntax: <code>android:scaleType="fitEnd"</code>. */ FIT_END /*(4) { } */, /** * Center the image in the view, but perform no scaling. * From XML, use this syntax: <code>android:scaleType="center"</code>. */ CENTER /*(5) { } */, /** * Scale the image uniformly (maintain the image's aspect ratio) so * that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view * (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerCrop"</code>. */ CENTER_CROP /*(6) { } */, /** * Scale the image uniformly (maintain the image's aspect ratio) so * that both dimensions (width and height) of the image will be equal * to or less than the corresponding dimension of the view * (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerInside"</code>. */ CENTER_INSIDE /*(7) { } */ /*; constructor( ni:number) { nativeInt = ni; } nativeInt:number = 0; */}} }
the_stack
import isEqual from 'lodash-es/isEqual'; import FilterFilled from '@ant-design/icons-vue/FilterFilled'; import Button from '../../../button'; import Menu from '../../../menu'; import Checkbox from '../../../checkbox'; import Radio from '../../../radio'; import Dropdown from '../../../dropdown'; import Empty from '../../../empty'; import type { ColumnType, ColumnFilterItem, Key, TableLocale, GetPopupContainer, } from '../../interface'; import FilterDropdownMenuWrapper from './FilterWrapper'; import type { FilterState } from '.'; import { computed, defineComponent, onBeforeUnmount, ref, shallowRef, watch } from 'vue'; import classNames from '../../../_util/classNames'; import useConfigInject from '../../../_util/hooks/useConfigInject'; import { useInjectSlots } from '../../context'; const { SubMenu, Item: MenuItem } = Menu; function hasSubMenu(filters: ColumnFilterItem[]) { return filters.some(({ children }) => children && children.length > 0); } function renderFilterItems({ filters, prefixCls, filteredKeys, filterMultiple, locale, }: { filters: ColumnFilterItem[]; prefixCls: string; filteredKeys: Key[]; filterMultiple: boolean; locale: TableLocale; }) { if (filters.length === 0) { // wrapped with <div /> to avoid react warning // https://github.com/ant-design/ant-design/issues/25979 return ( <MenuItem key="empty"> <div style={{ margin: '16px 0', }} > <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={locale.filterEmptyText} imageStyle={{ height: 24, }} /> </div> </MenuItem> ); } return filters.map((filter, index) => { const key = String(filter.value); if (filter.children) { return ( <SubMenu key={key || index} title={filter.text} popupClassName={`${prefixCls}-dropdown-submenu`} > {renderFilterItems({ filters: filter.children, prefixCls, filteredKeys, filterMultiple, locale, })} </SubMenu> ); } const Component = filterMultiple ? Checkbox : Radio; return ( <MenuItem key={filter.value !== undefined ? key : index}> <Component checked={filteredKeys.includes(key)} /> <span>{filter.text}</span> </MenuItem> ); }); } export interface FilterDropdownProps<RecordType> { tablePrefixCls: string; prefixCls: string; dropdownPrefixCls: string; column: ColumnType<RecordType>; filterState?: FilterState<RecordType>; filterMultiple: boolean; columnKey: Key; triggerFilter: (filterState: FilterState<RecordType>) => void; locale: TableLocale; getPopupContainer?: GetPopupContainer; } export default defineComponent<FilterDropdownProps<any>>({ name: 'FilterDropdown', props: [ 'tablePrefixCls', 'prefixCls', 'dropdownPrefixCls', 'column', 'filterState', 'filterMultiple', 'columnKey', 'triggerFilter', 'locale', 'getPopupContainer', ] as any, setup(props, { slots }) { const contextSlots = useInjectSlots(); const filterDropdownVisible = computed(() => props.column.filterDropdownVisible); const visible = ref(false); const filtered = computed( () => !!( props.filterState && (props.filterState.filteredKeys?.length || props.filterState.forceFiltered) ), ); const filterDropdownRef = computed(() => { const { filterDropdown, slots = {}, customFilterDropdown } = props.column; return ( filterDropdown || (slots.filterDropdown && contextSlots.value[slots.filterDropdown]) || (customFilterDropdown && contextSlots.value.customFilterDropdown) ); }); const filterIconRef = computed(() => { const { filterIcon, slots = {} } = props.column; return ( filterIcon || (slots.filterIcon && contextSlots.value[slots.filterIcon]) || contextSlots.value.customFilterIcon ); }); const triggerVisible = (newVisible: boolean) => { visible.value = newVisible; props.column.onFilterDropdownVisibleChange?.(newVisible); }; const mergedVisible = computed(() => typeof filterDropdownVisible.value === 'boolean' ? filterDropdownVisible.value : visible.value, ); const propFilteredKeys = computed(() => props.filterState?.filteredKeys); const filteredKeys = shallowRef([]); const onSelectKeys = ({ selectedKeys }: { selectedKeys?: Key[] }) => { filteredKeys.value = selectedKeys; }; watch( propFilteredKeys, () => { onSelectKeys({ selectedKeys: propFilteredKeys.value || [] }); }, { immediate: true }, ); const openKeys = shallowRef([]); const openRef = ref(); const onOpenChange = (keys: string[]) => { openRef.value = window.setTimeout(() => { openKeys.value = keys; }); }; const onMenuClick = () => { window.clearTimeout(openRef.value); }; onBeforeUnmount(() => { window.clearTimeout(openRef.value); }); // ======================= Submit ======================== const internalTriggerFilter = (keys: Key[] | undefined | null) => { const { column, columnKey, filterState } = props; const mergedKeys = keys && keys.length ? keys : null; if (mergedKeys === null && (!filterState || !filterState.filteredKeys)) { return null; } if (isEqual(mergedKeys, filterState?.filteredKeys)) { return null; } props.triggerFilter({ column, key: columnKey, filteredKeys: mergedKeys, }); }; const onConfirm = () => { triggerVisible(false); internalTriggerFilter(filteredKeys.value); }; const onReset = () => { filteredKeys.value = []; triggerVisible(false); internalTriggerFilter([]); }; const doFilter = ({ closeDropdown } = { closeDropdown: true }) => { if (closeDropdown) { triggerVisible(false); } internalTriggerFilter(filteredKeys.value); }; const onVisibleChange = (newVisible: boolean) => { if (newVisible && propFilteredKeys.value !== undefined) { // Sync filteredKeys on appear in controlled mode (propFilteredKeys.value !== undefiend) filteredKeys.value = propFilteredKeys.value || []; } triggerVisible(newVisible); // Default will filter when closed if (!newVisible && !filterDropdownRef.value) { onConfirm(); } }; const { direction } = useConfigInject('', props); return () => { const { tablePrefixCls, prefixCls, column, dropdownPrefixCls, filterMultiple, locale, getPopupContainer, } = props; // ======================== Style ======================== const dropdownMenuClass = classNames({ [`${dropdownPrefixCls}-menu-without-submenu`]: !hasSubMenu(column.filters || []), }); let dropdownContent; if (typeof filterDropdownRef.value === 'function') { dropdownContent = filterDropdownRef.value({ prefixCls: `${dropdownPrefixCls}-custom`, setSelectedKeys: (selectedKeys: Key[]) => onSelectKeys({ selectedKeys }), selectedKeys: filteredKeys.value, confirm: doFilter, clearFilters: onReset, filters: column.filters, visible: mergedVisible.value, column: column.__originColumn__, }); } else if (filterDropdownRef.value) { dropdownContent = filterDropdownRef.value; } else { const selectedKeys = filteredKeys.value as any; dropdownContent = ( <> <Menu multiple={filterMultiple} prefixCls={`${dropdownPrefixCls}-menu`} class={dropdownMenuClass} onClick={onMenuClick} onSelect={onSelectKeys} onDeselect={onSelectKeys} selectedKeys={selectedKeys} getPopupContainer={getPopupContainer} openKeys={openKeys.value} onOpenChange={onOpenChange} v-slots={{ default: () => renderFilterItems({ filters: column.filters || [], prefixCls, filteredKeys: filteredKeys.value, filterMultiple, locale, }), }} ></Menu> <div class={`${prefixCls}-dropdown-btns`}> <Button type="link" size="small" disabled={selectedKeys.length === 0} onClick={onReset} > {locale.filterReset} </Button> <Button type="primary" size="small" onClick={onConfirm}> {locale.filterConfirm} </Button> </div> </> ); } const menu = ( <FilterDropdownMenuWrapper class={`${prefixCls}-dropdown`}> {dropdownContent} </FilterDropdownMenuWrapper> ); let filterIcon; if (typeof filterIconRef.value === 'function') { filterIcon = filterIconRef.value({ filtered: filtered.value, column: column.__originColumn__, }); } else if (filterIconRef.value) { filterIcon = filterIconRef.value; } else { filterIcon = <FilterFilled />; } return ( <div class={`${prefixCls}-column`}> <span class={`${tablePrefixCls}-column-title`}>{slots.default?.()}</span> <Dropdown overlay={menu} trigger={['click']} visible={mergedVisible.value} onVisibleChange={onVisibleChange} getPopupContainer={getPopupContainer} placement={direction.value === 'rtl' ? 'bottomLeft' : 'bottomRight'} > <span role="button" tabindex={-1} class={classNames(`${prefixCls}-trigger`, { active: filtered.value, })} onClick={e => { e.stopPropagation(); }} > {filterIcon} </span> </Dropdown> </div> ); }; }, });
the_stack
import * as express from 'express'; export type GenerateMessageMethod = () => string; export interface ErrorConstructor { new (...params: any[]): Error; } /** * Modifies an error's stack to include the current stack and logs it to * stderr. Useful for logging errors received by a callback. * * @param err any error or error message received from a callback * @param message any message you'd like to prepend * @returns err */ export function log(err: Error, message?: string): Error; export function logError(err: Error, cb: () => any): void; /** * Modifies an error's stack to include the current stack without logging * it. Useful for logging errors received by a callback. * * @param err any error or error message received from a callback * @returns err */ export function prependCurrentStack(err: Error): Error; export namespace helpers { /** * Simple interface for generating a new Error class type. * @param name The full name of the new Error class * @param options.extends The base class for the new Error * class. Default is Error. * @param options.globalize Boolean (default true) to store the * Error in global space so that the * Error is equivalent to others included * from other versions of the module. * @param options.args Array of names of values to accept and * store from the class constructor. * Default is ['message', 'inner_error']. * @param options.generateMessage A function for defining a custom error * message. */ function generateClass( name: string, options?: { extends?: Error | undefined, globalize?: boolean | undefined, args?: string[] | undefined, generateMessage?: GenerateMessageMethod | undefined } ): ErrorConstructor; } export namespace middleware { /** * Express middleware for preventing the web server from crashing when * an error is thrown from an asynchronous context. Any error that would * have caused a crash is logged to stderr. */ function crashProtector(errorHandler: (err: Error, req: express.Request, res: express.Response) => void): void; /** * Express middleware that translates common errors into HTTP status * codes and messages. */ function errorHandler(err: Error, req: express.Request, res: express.Response, next: express.NextFunction): void; } /** * This is roughly the same as the native Error class. It additionally * supports an inner_error attribute. * * @example throw new errors.Error("Please provide authentication.", err) */ export class Error extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(entityName: string, inner_error?: Error); } /** * Applicable when a resource is already in use, for example unique key * constraints like a username. * * @example throw new errors.AlreadyInUseError('user', 'username') */ export class AlreadyInUseError extends global.Error { /** * @param entityName the entity that owns the protected resource * @param args the fields or attributes that are already in use */ constructor(entityName: string, ...args: string[]); } /** * Applicable when there's a generic problem with an argument received by a * function call. * * @example throw new errors.ArgumentError('username', err) */ export class ArgumentError extends global.Error { /** * @param argumentName the name of the argument that has a problem * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(argumentName: string, inner_error?: Error); } /** * Applicable when an argument received by a function call is null/undefined * or empty. * * @example throw new errors.ArgumentNullError('username', err) */ export class ArgumentNullError extends ArgumentError { /** * @param argumentName the name of the argument that is null * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(argumentName: string, inner_error?: Error); } /** * Applicable when an operation requires authentication * * @example throw new errors.AuthenticationRequiredError("Please provide authentication.", err) */ export class AuthenticationRequiredError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs on a connection. * * @example throw new errors.ConnectionError('database connection no longer available', err) */ export class ConnectionError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Represents a message and a HTTP status code. * * @example throw new errors.HttpStatusError(404, "Not Found") * @example throw new errors.HttpStatusError(err, req) */ export class HttpStatusError extends global.Error { /** * Figure out a proper status code and message from a given error. To * change the mappings, modify HttpStatusError.message_map and * HttpStatusError.code_map * * @param status_code any HTTP status code integer * @param message any message */ constructor(status_code: number, message?: string); /** * @param err any instanceof Error * @param req the request object */ constructor(err: Error, req?: express.Request); /** * Status code for this error. */ statusCode: number; } /** * Applicable when an invalid operation occurs. * * @example throw new errors.InvalidOperationError('divide by zero', err) */ export class InvalidOperationError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs on a socket. * * @example throw new errors.SocketError('socket no longer available', err) */ export class SocketError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an attempt to retrieve data yielded no result. * * @example throw new errors.NotFoundError("User", err) */ export class NotFoundError extends global.Error { /** * @param entity_name a description for what was not found * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(entity_name: string, inner_error?: Error); } /** * Applicable when a requested method or operation is not implemented. * * @example throw new errors.NotImplementedError("Method is not yet implemented.", err) */ export class NotImplementedError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an operation is not permitted * * @example throw new errors.NotPermittedError("username cannot be changed once set.", err) */ export class NotPermittedError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when a certain condition is not supported by your application. * * @example throw new errors.NotSupportedError('Zero values', err) */ export class NotSupportedError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when there is not enough memory to continue the execution of a program. * * @example throw new errors.OutOfMemoryError('Maximum mem size exceeded.', err) */ export class OutOfMemoryError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Represents an error that occurs when a numeric variable or parameter is * outside of its valid range. This is roughly the same as the native * RangeError class. It additionally supports an inner_error attribute. * * @example throw new errors.RangeError("Value must be between " + MIN + " and " + MAX, err) */ export class RangeError extends global.RangeError { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Represents an error when a non-existent variable is referenced. This is * roughly the same as the native ReferenceError class. It additionally * supports an inner_error attribute. * * @example throw new errors.ReferenceError("x is not defined", err) */ export class ReferenceError extends global.ReferenceError { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when the execution stack overflows because it contains too * many nested method calls. * * @example throw new errors.StackOverflowError('Stack overflow detected.', err) */ export class StackOverflowError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Represents an error when trying to interpret syntactically invalid code. * This is roughly the same as the native SyntaxError class. It additionally * supports an inner_error attribute. * * @example throw new errors.SyntaxError("Unexpected token a", err) */ export class SyntaxError extends global.SyntaxError { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an operation takes longer than the alloted amount. * * @example throw new errors.TimeoutError('100ms', err) */ export class TimeoutError extends global.Error { /** * @param time a time duration * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(time: string, inner_error?: Error); } /** * Represents an error when a value is not of the expected type. This is * roughly the same as the native TypeError class. It additionally supports * an inner_error attribute. * * @example throw new errors.TypeError("number is not a function", err) */ export class TypeError extends global.TypeError { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Represents an error when a value is not of the expected type. This is * roughly the same as the native URIError class. It additionally supports * an inner_error attribute. * * @example throw new errors.URIError("URI malformed", err) */ export class URIError extends global.URIError { /** * @param message any message * @param inner_error the Error instance that caused the current error. * Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Useful for denoting a problem with a user-defined value. Generally, you * won't throw this error. It serializes to JSON, and it can also function * as an envelope for multiple errors. * * @example * function validateUsername(username) { * var errors = new errors.ValidationError() * if (username.length < 3) errors.addError(new errors.ValidationError("username must be at least two characters long", "VAL_MIN_USERNAME_LENGTH", "username")) * if(/-%$*&!/.test(username)) errors.addError(new errors.ValidationError("username may not contain special characters", "VAL_USERNAME_SPECIALCHARS", "username")) * return errors * } */ export class ValidationError extends global.Error { /** * @param message any message * @param code an optional error code * @param field an optional description of the data */ constructor(message: string, code?: string, field?: string); /** * add an error object to the errors array */ addError(error: Error): this; /** * append an array of error objects to the errors array */ addErrors(errors: Error[]): this; } export namespace data { /** * Applicable when an error occurs on or with an external data source. * * @example throw new errors.data.DataError('Too many rows returned from database', err) */ class DataError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs while using memcached. * * @example throw new errors.data.MemcachedError('Expected value not found', err) */ class MemcachedError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs while using MongoDB. * * @example throw new errors.data.MongoDBError('Retrieved value not in expected format', err) */ class MongoDBError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs while using redis. * * @example throw new errors.data.RedisError('expected value not found in redis', err) */ class RedisError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when a transaction was unexpectedly rolled back. * * @example throw new errors.data.RollbackError('database transaction was unexpectedly rolled back', err) */ class RollbackError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error occurs while using a SQL database. * * @example throw new errors.data.SQLError('foreign key constraint violated', err) */ class SQLError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when an error unexpectedly interrupts a transaction. * * @example throw new errors.data.TransactionError('transaction already complete', err) */ class TransactionError extends DataError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } } export namespace io { /** * Base class for Errors while accessing information using streams, * files and directories. * * @example throw new errors.io.IOError("Could not open file", err) */ class IOError extends global.Error { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when part of a file or directory cannot be found. * * @example throw new errors.io.DirectoryNotFoundError("/var/log", err) */ class DirectoryNotFoundError extends IOError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error) } /** * Applicable when trying to access a drive or share that is not * available. * * @example throw new errors.io.DriveNotFoundError("c", err) */ class DriveNotFoundError extends IOError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when reading is attempted past the end of a stream. * * @example throw new errors.io.EndOfStreamError("EOS while reading header", err) */ class EndOfStreamError extends IOError { /** * @param message any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(message: string, inner_error?: Error); } /** * Applicable when a file is found and read but cannot be loaded. * * @example throw new errors.io.FileLoadError("./package.json", err) */ class FileLoadError extends IOError { /** * @param file_name any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(file_name: string, inner_error?: Error); } /** * Applicable when an attempt to access a file that does not exist on * disk fails. * * @example throw new errors.io.FileNotFoundError("./package.json", err) */ class FileNotFoundError extends IOError { /** * @param file_name any message * @param inner_error the Error instance that caused the current * error. Stack trace will be appended. */ constructor(file_name: string, inner_error?: Error); } }
the_stack
// ReadLaterUI is a Mojo WebUI controller and therefore needs mojo defined to // finish running its tests. import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; import 'chrome://read-later.top-chrome/side_panel/bookmarks_list.js'; import {BookmarkFolderElement, FOLDER_OPEN_CHANGED_EVENT} from 'chrome://read-later.top-chrome/side_panel/bookmark_folder.js'; import {BookmarksApiProxyImpl} from 'chrome://read-later.top-chrome/side_panel/bookmarks_api_proxy.js'; import {BookmarksListElement, LOCAL_STORAGE_OPEN_FOLDERS_KEY} from 'chrome://read-later.top-chrome/side_panel/bookmarks_list.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/test_util.js'; import {TestBookmarksApiProxy} from './test_bookmarks_api_proxy.js'; suite('SidePanelBookmarksListTest', () => { let bookmarksList: BookmarksListElement; let bookmarksApi: TestBookmarksApiProxy; const folders: chrome.bookmarks.BookmarkTreeNode[] = [ { id: '0', parentId: 'root', title: 'Bookmarks bar', children: [ { id: '3', parentId: '0', title: 'Child bookmark', url: 'http://child/bookmark/', }, { id: '4', parentId: '0', title: 'Child folder', children: [ { id: '5', parentId: '4', title: 'Nested bookmark', url: 'http://nested/bookmark/', }, ], } ], }, { id: '1', parentId: 'root', title: 'Other bookmarks', children: [], }, { id: '2', title: 'Mobile bookmarks', children: [], }, ]; function getFolderElements(root: HTMLElement): BookmarkFolderElement[] { return Array.from(root.shadowRoot!.querySelectorAll('bookmark-folder')); } function getBookmarkElements(root: HTMLElement): HTMLElement[] { return Array.from(root.shadowRoot!.querySelectorAll('.bookmark')); } setup(async () => { window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY] = undefined; document.body.innerHTML = ''; bookmarksApi = new TestBookmarksApiProxy(); bookmarksApi.setFolders(JSON.parse(JSON.stringify(folders))); BookmarksApiProxyImpl.setInstance(bookmarksApi); bookmarksList = document.createElement('bookmarks-list'); document.body.appendChild(bookmarksList); await flushTasks(); }); test('GetsAndShowsFolders', () => { assertEquals(1, bookmarksApi.getCallCount('getFolders')); assertEquals(folders.length, getFolderElements(bookmarksList).length); }); test('UpdatesChangedBookmarks', () => { const rootFolderIndex = 0; const bookmarkIndex = 0; const changedBookmark = folders[rootFolderIndex]!.children![bookmarkIndex]!; bookmarksApi.callbackRouter.onChanged.callListeners(changedBookmark.id, { title: 'New title', url: 'http://new/url', }); const folderElement = getFolderElements(bookmarksList)[rootFolderIndex] as BookmarkFolderElement; const bookmarkElement = getBookmarkElements(folderElement)[bookmarkIndex]!; assertEquals('New title', bookmarkElement.textContent); }); test('UpdatesReorderedChildren', () => { // Reverse the children of Bookmarks bar. const children = folders[0]!.children!; const reverseOrder = children.map(child => child.id).reverse(); bookmarksApi.callbackRouter.onChildrenReordered.callListeners( folders[0]!.id, {childIds: reverseOrder}); flush(); const rootFolderElement = getFolderElements(bookmarksList)[0]!; const childFolder = getFolderElements(rootFolderElement)[0]!; const childBookmark = getBookmarkElements(rootFolderElement)[0]!; assertTrue( !!(childFolder.compareDocumentPosition(childBookmark) & Node.DOCUMENT_POSITION_FOLLOWING)); }); test('AddsCreatedBookmark', async () => { bookmarksApi.callbackRouter.onCreated.callListeners('999', { id: '999', title: 'New bookmark', index: 0, parentId: '4', url: '//new/bookmark', }); flush(); const rootFolderElement = getFolderElements(bookmarksList)[0]!; const childFolder = getFolderElements(rootFolderElement)[0]!; childFolder.shadowRoot!.querySelector<HTMLElement>( '.row')!.click(); // Open folder. await flushTasks(); const childFolderBookmarks = getBookmarkElements(childFolder); assertEquals(2, childFolderBookmarks.length); assertEquals('New bookmark', childFolderBookmarks[0]!.textContent); }); test('AddsCreatedBookmarkForNewFolder', () => { // Create a new folder without a children array. bookmarksApi.callbackRouter.onCreated.callListeners('1000', { id: '1000', title: 'New folder', index: 0, parentId: '0', }); flush(); // Create a new bookmark within that folder. bookmarksApi.callbackRouter.onCreated.callListeners('1001', { id: '1001', title: 'New bookmark in new folder', index: 0, parentId: '1000', url: 'http://google.com', }); flush(); const rootFolderElement = getFolderElements(bookmarksList)[0]!; const newFolder = getFolderElements(rootFolderElement)[0]!; assertEquals(1, newFolder.folder.children!.length); }); test('MovesBookmarks', () => { const movedBookmark = folders[0]!.children![1]!.children![0]!; bookmarksApi.callbackRouter.onMoved.callListeners(movedBookmark.id, { index: 0, parentId: folders[0]!.id, // Moving to bookmarks bar. oldParentId: folders[0]!.children![1]!.id, // Moving from child folder. oldIndex: 0, }); flush(); const bookmarksBarFolder = getFolderElements(bookmarksList)[0]!; const movedBookmarkElement = getBookmarkElements(bookmarksBarFolder)[0]!; assertEquals('Nested bookmark', movedBookmarkElement.textContent); const childFolder = getFolderElements(bookmarksBarFolder)[0]!; const childFolderBookmarks = getBookmarkElements(childFolder); assertEquals(0, childFolderBookmarks.length); }); test('MovesBookmarksIntoNewFolder', () => { // Create a new folder without a children array. bookmarksApi.callbackRouter.onCreated.callListeners('1000', { id: '1000', title: 'New folder', index: 0, parentId: '0', }); flush(); const movedBookmark = folders[0]!.children![1]!.children![0]!; bookmarksApi.callbackRouter.onMoved.callListeners(movedBookmark.id, { index: 0, parentId: '1000', oldParentId: folders[0]!.children![1]!.id, oldIndex: 0, }); flush(); const bookmarksBarFolder = getFolderElements(bookmarksList)[0]!; const newFolder = getFolderElements(bookmarksBarFolder)[0]!; assertEquals(1, newFolder.folder.children!.length); }); test('DefaultsToFirstFolderBeingOpen', () => { assertEquals( JSON.stringify([folders[0]!.id]), window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY]); }); test('UpdatesLocalStorageOnFolderOpenChanged', () => { bookmarksList.dispatchEvent(new CustomEvent(FOLDER_OPEN_CHANGED_EVENT, { bubbles: true, composed: true, detail: { id: folders[0]!.id, open: false, } })); assertEquals( JSON.stringify([]), window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY]); bookmarksList.dispatchEvent(new CustomEvent(FOLDER_OPEN_CHANGED_EVENT, { bubbles: true, composed: true, detail: { id: '5001', open: true, } })); assertEquals( JSON.stringify(['5001']), window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY]); }); test('MovesFocusBetweenFolders', () => { const folderElements = getFolderElements(bookmarksList); function dispatchArrowKey(key: string) { bookmarksList.dispatchEvent(new KeyboardEvent('keydown', {key})); } function assertActiveElement(index: number) { assertEquals( folderElements[index], bookmarksList.shadowRoot!.activeElement); } // Move focus to the first folder. folderElements[0]!.moveFocus(1); assertActiveElement(0); // One ArrowDown key should still keep focus in the first folder since the // folder has children. dispatchArrowKey('ArrowDown'); assertActiveElement(0); // Two ArrowsDown to eventually make it to the second folder. dispatchArrowKey('ArrowDown'); dispatchArrowKey('ArrowDown'); assertActiveElement(1); // One ArrowsDown to eventually make it to the third folder. dispatchArrowKey('ArrowDown'); assertActiveElement(2); // One ArrowsDown to loop back to the first folder. dispatchArrowKey('ArrowDown'); assertActiveElement(0); // One ArrowUp to loop back to the last folder. dispatchArrowKey('ArrowUp'); assertActiveElement(2); // One ArrowUp to loop back to the second folder. dispatchArrowKey('ArrowUp'); assertActiveElement(1); }); test('CutsCopyPastesBookmark', async () => { const folderElement = getFolderElements(bookmarksList)[0]!; const bookmarkElement = getBookmarkElements(folderElement)[0]!; bookmarkElement.dispatchEvent(new KeyboardEvent( 'keydown', {key: 'x', ctrlKey: true, bubbles: true, composed: true})); const cutId = await bookmarksApi.whenCalled('cutBookmark'); assertEquals('3', cutId); bookmarkElement.dispatchEvent(new KeyboardEvent( 'keydown', {key: 'c', ctrlKey: true, bubbles: true, composed: true})); const copiedId = await bookmarksApi.whenCalled('copyBookmark'); assertEquals('3', copiedId); bookmarkElement.dispatchEvent(new KeyboardEvent( 'keydown', {key: 'v', ctrlKey: true, bubbles: true, composed: true})); let [pastedId, pastedDestinationId] = await bookmarksApi.whenCalled('pasteToBookmark'); assertEquals('0', pastedId); assertEquals('3', pastedDestinationId); }); });
the_stack
import { expect } from 'chai'; import { backtest } from '../../lib/backtest'; import { DataFrame, IDataFrame } from 'data-forge'; import { IBar } from '../../lib/bar'; import { IStrategy, EnterPositionFn, IEntryRuleArgs, ExitPositionFn, IExitRuleArgs, TradeDirection } from '../../lib/strategy'; import * as moment from 'dayjs'; describe("backtest short", () => { function round(value: number) { return Math.round(value * 100) / 100; } function makeDate(dateStr: string, fmt?: string): Date { return moment(dateStr, fmt || "YYYY/MM/DD").toDate(); } function mockBar(): IBarDef { return { time: "2018/10/20", close: 2, }; } interface IBarDef { time: string; open?: number; high?: number; low?: number; close: number; volume?: number; } function makeBar(bar: IBarDef): IBar { return { time: makeDate(bar.time), open: bar.open !== undefined ? bar.open : bar.close, high: bar.high !== undefined ? bar.high : bar.close, low: bar.low !== undefined ? bar.low : bar.close, close: bar.close, volume: bar.volume !== undefined ? bar.volume : 1, }; } function makeDataSeries(bars: IBarDef[]): IDataFrame<number, IBar> { return new DataFrame<number, IBar>(bars.map(makeBar)); } const mockEntry = () => {}; const mockExit = () => {}; function mockStrategy(): IStrategy { return { entryRule: mockEntry, exitRule: mockExit, }; } function unconditionalShortEntry(enterPosition: EnterPositionFn, args: IEntryRuleArgs<IBar, {}>) { enterPosition({ direction: TradeDirection.Short }); // Unconditionally enter position at market price. }; function unconditionalShortExit(exitPosition: ExitPositionFn, args: IExitRuleArgs<IBar, {}>) { exitPosition(); // Unconditionally exit position at market price. }; const shortStrategyWithUnconditionalEntryAndExit: IStrategy = { entryRule: unconditionalShortEntry, exitRule: unconditionalShortExit, }; const simpleInputSeries = makeDataSeries([ { time: "2018/10/20", close: 1 }, { time: "2018/10/21", close: 2 }, { time: "2018/10/22", close: 3 }, ]); const longerDataSeries = makeDataSeries([ { time: "2018/10/20", close: 1 }, { time: "2018/10/21", close: 2 }, { time: "2018/10/22", close: 4 }, { time: "2018/10/23", close: 5 }, { time: "2018/10/24", close: 6 }, ]); it('going short makes a loss when the price rises', () => { const entryPrice = 3; const exitPrice = 7; const inputSeries = makeDataSeries([ { time: "2018/10/20", open: 1, close: 2 }, { time: "2018/10/21", open: entryPrice, close: 4 }, // Enter position at open on this day. { time: "2018/10/22", open: 5, close: 6 }, { time: "2018/10/23", open: exitPrice, close: 8 }, // Exit position at open on this day. ]); const trades = backtest(shortStrategyWithUnconditionalEntryAndExit, inputSeries); const singleTrade = trades[0]; expect(singleTrade.profit).to.be.lessThan(0); expect(singleTrade.profit).to.eql(entryPrice-exitPrice); }); it('going short makes a profit when the price drops', () => { const entryPrice = 6; const exitPrice = 2; const inputSeries = makeDataSeries([ { time: "2018/10/20", open: 8, close: 7 }, { time: "2018/10/21", open: entryPrice, close: 5 }, // Enter position at open on this day. { time: "2018/10/22", open: 4, close: 3 }, { time: "2018/10/23", open: exitPrice, close: 1 }, // Exit position at open on this day. ]); const trades = backtest(shortStrategyWithUnconditionalEntryAndExit, inputSeries); const singleTrade = trades[0]; expect(singleTrade.profit).to.be.greaterThan(0); expect(singleTrade.profit).to.eql(entryPrice-exitPrice); }); it("can exit short via stop loss", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 110 }, // Hold { time: "2018/10/23", close: 120 }, // Stop loss triggered. { time: "2018/10/24", close: 120 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.stopPrice).to.eql(120); expect(singleTrade.exitReason).to.eql("stop-loss"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23")); }); it("stop loss exits short based on intrabar high", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 110 }, // Hold { time: "2018/10/23", open: 110, high: 120, low: 100, close: 105 }, // Stop loss triggered. { time: "2018/10/24", close: 105 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitPrice).to.eql(120); }); it("stop loss is not triggered unless there is a significant rise", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day { time: "2018/10/22", close: 90 }, // Hold { time: "2018/10/23", close: 85 }, // Hold { time: "2018/10/24", close: 82 }, // Exit ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitReason).to.eql("finalize"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/24")); }); it("can exit short via profit target", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, profitTarget: args => args.entryPrice * (10/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 95 }, // Hold { time: "2018/10/23", close: 90 }, // Profit target triggered. { time: "2018/10/24", close: 90 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.profitTarget).to.eql(90); expect(singleTrade.exitReason).to.eql("profit-target"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23")); }); it("profit target exits short based on intrabar low", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, profitTarget: args => args.entryPrice * (10/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 95 }, // Hold { time: "2018/10/23", open: 95, high: 100, low: 90, close: 95 }, // Profit target triggered. { time: "2018/10/24", close: 95 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitPrice).to.eql(90); }); it("short exit is not triggered unless target profit is achieved", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, profitTarget: args => args.entryPrice * (30/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day { time: "2018/10/22", close: 100 }, // Hold { time: "2018/10/23", close: 110 }, // Hold { time: "2018/10/24", close: 120 }, // Exit ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitReason).to.eql("finalize"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/24")); }); it("can exit short via trailing stop loss", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, trailingStopLoss: args => args.bar.close * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 110 }, // Hold { time: "2018/10/23", close: 120 }, // Stop loss triggered. { time: "2018/10/24", close: 120 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitReason).to.eql("stop-loss"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23")); }); it("can exit short via decreasing trailing stop loss", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, trailingStopLoss: args => args.bar.close * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 60 }, // Hold { time: "2018/10/23", close: 72 }, // Stop loss triggered. { time: "2018/10/24", close: 72 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitReason).to.eql("stop-loss"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23")); }); it("trailing stop loss exits short based on intrabar high", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, trailingStopLoss: args => args.bar.close * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 110 }, // Hold { time: "2018/10/23", open: 110, high: 120, low: 100, close: 110 }, // Stop loss triggered. { time: "2018/10/24", close: 110 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitPrice).to.eql(120); }); it("trailing stop loss is not triggered unless there is a significant rise", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, trailingStopLoss: args => args.bar.close * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day { time: "2018/10/22", close: 110 }, // Hold { time: "2018/10/23", close: 115 }, // Hold { time: "2018/10/24", close: 112 }, // Exit ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.exitReason).to.eql("finalize"); expect(singleTrade.exitTime).to.eql(makeDate("2018/10/24")); }); it("can place intrabar conditional short order", () => { const strategy: IStrategy = { entryRule: (enterPosition, args) => { enterPosition({ direction: TradeDirection.Short, entryPrice: 6, // Enter position when price hits 6. }); }, exitRule: mockExit, }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 10 }, { time: "2018/10/21", close: 9 }, { time: "2018/10/22", close: 8 }, { time: "2018/10/23", close: 7, low: 6 }, // Intraday entry. { time: "2018/10/24", close: 5 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.entryTime).to.eql(makeDate("2018/10/23")); }); it("conditional short order is not executed if price doesn't reach target", () => { const strategy: IStrategy = { entryRule: (enterPosition, args) => { enterPosition({ direction: TradeDirection.Short, entryPrice: 6, // Enter position when price hits 6. }); }, exitRule: mockExit, }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 10 }, { time: "2018/10/21", close: 9 }, { time: "2018/10/22", close: 8 }, { time: "2018/10/23", close: 7 }, { time: "2018/10/24", close: 7 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(0); }); it("computes risk from initial stop", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 100 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.riskPct).to.eql(20); }); it("computes rmultiple from initial risk and profit", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 80 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.rmultiple).to.eql(1); }); it("computes rmultiple from initial risk and loss", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 120 }, ]); const trades = backtest(strategy, inputSeries); expect(trades.length).to.eql(1); const singleTrade = trades[0]; expect(singleTrade.rmultiple).to.eql(-1); }); it("current risk rises as profit increases", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, stopLoss: args => args.entryPrice * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 80 }, { time: "2018/10/23", close: 60 }, { time: "2018/10/24", close: 40 }, { time: "2018/10/25", close: 20 }, { time: "2018/10/26", close: 10 }, ]); const trades = backtest(strategy, inputSeries, { recordRisk: true }); expect(trades.length).to.eql(1); const singleTrade = trades[0]; const output = singleTrade.riskSeries!.map(risk => ({ time: risk.time, value: round(risk.value) })); expect(output).to.eql([ { time: makeDate("2018/10/21"), value: 20, }, { time: makeDate("2018/10/22"), value: 50, }, { time: makeDate("2018/10/23"), value: 100, }, { time: makeDate("2018/10/24"), value: 200, }, { time: makeDate("2018/10/25"), value: 500, }, { time: makeDate("2018/10/26"), value: 1100, }, ]); }); it("current risk remains low by trailing stop loss", () => { const strategy: IStrategy = { entryRule: unconditionalShortEntry, trailingStopLoss: args => args.bar.close * (20/100) }; const inputSeries = makeDataSeries([ { time: "2018/10/20", close: 100 }, { time: "2018/10/21", close: 100 }, // Entry day. { time: "2018/10/22", close: 80 }, { time: "2018/10/23", close: 60 }, { time: "2018/10/24", close: 40 }, { time: "2018/10/25", close: 20 }, { time: "2018/10/26", close: 10 }, ]); const trades = backtest(strategy, inputSeries, { recordRisk: true }); expect(trades.length).to.eql(1); const singleTrade = trades[0]; const output = singleTrade.riskSeries!.map(risk => ({ time: risk.time, value: round(risk.value) })); expect(output).to.eql([ { time: makeDate("2018/10/21"), value: 20, }, { time: makeDate("2018/10/22"), value: 20, }, { time: makeDate("2018/10/23"), value: 20, }, { time: makeDate("2018/10/24"), value: 20, }, { time: makeDate("2018/10/25"), value: 20, }, { time: makeDate("2018/10/26"), value: 20, }, ]); }); it('profit is computed for short trade finalized at end of the trading period', () => { const inputData = makeDataSeries([ { time: "2018/10/20", close: 10 }, { time: "2018/10/21", close: 10 }, { time: "2018/10/22", close: 5 }, ]); const trades = backtest(shortStrategyWithUnconditionalEntryAndExit, inputData); const singleTrade = trades[0]; expect(singleTrade.profit).to.eql(5); expect(singleTrade.profitPct).to.eql(50); expect(singleTrade.growth).to.eql(2); }); });
the_stack
import {assert} from 'chai'; import {activeElement, activeElementAccessibleName, activeElementTextContent, getBrowserAndPages, tabBackward, tabForward, waitForFunction} from '../../shared/helper.js'; import {describe, it} from '../../shared/mocha-extensions.js'; import {focusConsolePrompt, getConsoleMessages, getStructuredConsoleMessages, navigateToConsoleTab, showVerboseMessages, waitForLastConsoleMessageToHaveContent} from '../helpers/console-helpers.js'; /* eslint-disable no-console */ describe('The Console Tab', async () => { const tests = [ { description: 'produces console messages when a page logs using console.log', evaluate: () => console.log('log'), expectedMessages: [{ message: 'log', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:1', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }], }, { description: 'produces console messages when a page logs using console.debug', evaluate: () => console.debug('debug'), expectedMessages: [{ message: 'debug', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:1', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-verbose-level', }], }, { description: 'produces console messages when a page logs using console.warn', evaluate: () => console.warn('warn'), expectedMessages: [{ message: 'warn', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:1', stackPreview: '\n(anonymous) @ __puppeteer_evaluation_script__:1', wrapperClasses: 'console-message-wrapper console-from-api console-warning-level', }], }, { description: 'produces console messages when a page logs using console.error', evaluate: () => console.error('error'), expectedMessages: [{ message: 'error', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:1', stackPreview: '\n(anonymous) @ __puppeteer_evaluation_script__:1', wrapperClasses: 'console-message-wrapper console-from-api console-error-level', }], }, { description: 'produces a single console message when messages are repeated', evaluate: () => { for (let i = 0; i < 5; ++i) { console.log('repeated'); } }, expectedMessages: [{ message: 'repeated', messageClasses: 'console-message repeated-message', repeatCount: '5', source: '__puppeteer_evaluation_script__:3', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }], }, { description: 'counts how many time console.count has been called with the same message', evaluate: () => { for (let i = 0; i < 2; ++i) { console.count('count'); } }, expectedMessages: [ { message: 'count: 1', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:3', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'count: 2', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:3', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, ], }, { description: 'creates an empty group message using console.group/console.groupEnd', evaluate: () => { console.group('group'); console.groupEnd(); }, expectedMessages: [ { message: 'group', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:2', stackPreview: null, wrapperClasses: 'console-message-wrapper console-group-title console-from-api console-info-level', }, ], }, { description: 'logs multiple arguments using console.log', evaluate: () => { console.log('1', '2', '3'); }, expectedMessages: [ { message: '1 2 3', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:2', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, ], }, { description: 'creates a collapsed group using console.groupCollapsed with all messages in between hidden', evaluate: () => { console.groupCollapsed('groupCollapsed'); console.log({property: 'value'}); console.log(42); console.log(true); console.log(null); console.log(undefined); console.log(document); console.log(function() {}); console.log(function f() {}); console.log([1, 2, 3]); console.log(/regexp.*/); console.groupEnd(); }, expectedMessages: [ { message: 'groupCollapsed', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:2', stackPreview: null, wrapperClasses: 'console-message-wrapper console-group-title console-from-api console-info-level', }, ], }, { description: 'logs console.count messages with and without arguments', evaluate: () => { console.count(); console.count(); console.count(); console.count('title'); console.count('title'); console.count('title'); }, expectedMessages: [ { message: 'default: 1', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:2', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'default: 2', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:3', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'default: 3', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:4', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'title: 1', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:5', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'title: 2', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:6', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, { message: 'title: 3', messageClasses: 'console-message', repeatCount: null, source: '__puppeteer_evaluation_script__:7', stackPreview: null, wrapperClasses: 'console-message-wrapper console-from-api console-info-level', }, ], }, ]; for (const test of tests) { it(test.description, async () => { const {target} = getBrowserAndPages(); await navigateToConsoleTab(); await showVerboseMessages(); await target.evaluate(test.evaluate); const actualMessages = await waitForFunction(async () => { const messages = await getStructuredConsoleMessages(); return messages.length === test.expectedMessages.length ? messages : undefined; }); assert.deepEqual(actualMessages, test.expectedMessages, 'Console message does not match the expected message'); }); } describe('keyboard navigation', () => { it('can navigate between individual messages', async () => { const {frontend} = getBrowserAndPages(); await getConsoleMessages('focus-interaction'); await focusConsolePrompt(); await tabBackward(); assert.strictEqual(await activeElementTextContent(), 'focus-interaction.html:9'); await frontend.keyboard.press('ArrowUp'); assert.strictEqual(await activeElementTextContent(), 'focus-interaction.html:9 Third message'); await frontend.keyboard.press('ArrowUp'); assert.strictEqual(await activeElementTextContent(), 'focus-interaction.html:8'); await frontend.keyboard.press('ArrowDown'); assert.strictEqual(await activeElementTextContent(), 'focus-interaction.html:9 Third message'); await tabBackward(); // Focus should now be on the console settings, e.g. out of the list of console messages assert.strictEqual(await activeElementAccessibleName(), 'Console settings'); await tabForward(); // Focus is now back to the list, selecting the last message source URL assert.strictEqual(await activeElementTextContent(), 'focus-interaction.html:9'); await tabForward(); assert.strictEqual(await activeElementAccessibleName(), 'Console prompt'); }); it('should not lose focus on prompt when logging and scrolling', async () => { const {target, frontend} = getBrowserAndPages(); await getConsoleMessages('focus-interaction'); await focusConsolePrompt(); await target.evaluate(() => { console.log('New message'); }); await waitForLastConsoleMessageToHaveContent('New message'); assert.strictEqual(await activeElementAccessibleName(), 'Console prompt'); await target.evaluate(() => { for (let i = 0; i < 100; i++) { console.log(`Message ${i}`); } }); await waitForLastConsoleMessageToHaveContent('Message 99'); assert.strictEqual(await activeElementAccessibleName(), 'Console prompt'); const consolePrompt = await activeElement(); const wrappingBox = await consolePrompt.boundingBox(); if (!wrappingBox) { throw new Error('Can\'t compute bounding box of console prompt.'); } // +20 to move from the top left point so we are definitely scrolling // within the container await frontend.mouse.move(wrappingBox.x + 20, wrappingBox.y + 5); await frontend.mouse.wheel({deltaY: -500}); assert.strictEqual(await activeElementAccessibleName(), 'Console prompt'); }); }); });
the_stack
import * as React from 'react'; import styles from './TeamsCreator.module.scss'; import { ITeamsCreatorProps } from './ITeamsCreatorProps'; import { TextField, ITextField } from 'office-ui-fabric-react/lib/TextField'; import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { PrimaryButton, DefaultButton, ActionButton } from 'office-ui-fabric-react/lib/Button'; import { Spinner } from 'office-ui-fabric-react/lib/Spinner'; import { PeoplePicker, PrincipalType, IPeoplePickerUserItem } from "@pnp/spfx-controls-react/lib/PeoplePicker"; import * as strings from 'TeamsCreatorWebPartStrings'; import { MSGraphClient } from '@microsoft/sp-http'; /** * State of the component */ export enum CreationState { /** * Initial state - user input */ notStarted = 0, /** * creating all selected elements (group, team, channel, tab) */ creating = 1, /** * everything has been created */ created = 2, /** * error during creation */ error = 4 } /** * App definition returned from App Catalog */ export interface ITeamsApp { id: string; externalId?: string; displayName: string; version: string; distributionMethod: string; } /** * State */ export interface ITeamsCreatorState { /** * Selected team name. Also used as group name */ teamName?: string; /** * team description */ teamDescription?: string; /** * Group owners */ owners?: string[]; /** * group members */ members?: string[]; /** * Flag if channel should be created */ createChannel?: boolean; /** * channel name */ channelName?: string; /** * channel description */ channelDescription?: string; /** * flag if we need to add a tab */ addTab?: boolean; /** * tab name */ tabName?: string; /** * teams apps from app catalog */ apps?: ITeamsApp[]; /** * current state of the component */ creationState?: CreationState; /** * creation spinner text */ spinnerText?: string; /** * id of the selected app to be added as tab */ selectedAppId?: string; } export default class TeamsCreator extends React.Component<ITeamsCreatorProps, ITeamsCreatorState> { constructor(props: ITeamsCreatorProps) { super(props); this.state = { creationState: CreationState.notStarted }; this._onClearClick = this._onClearClick.bind(this); } public render(): React.ReactElement<ITeamsCreatorProps> { const { teamName, teamDescription, createChannel, channelName, channelDescription, addTab, tabName, apps, creationState, spinnerText, selectedAppId } = this.state; const appsDropdownOptions: IDropdownOption[] = apps ? apps.map(app => { return { key: app.id, text: app.displayName }; }) : []; return ( <div className={styles.teamsCreator}> <h2>{strings.Welcome}</h2> <div className={styles.container}> {{ 0: <div> <div className={styles.teamSection}> <TextField required={true} label={strings.TeamNameLabel} value={teamName} onChanged={this._onTeamNameChange.bind(this)}></TextField> <TextField label={strings.TeamDescriptionLabel} value={teamDescription} onChanged={this._onTeamDescriptionChange.bind(this)}></TextField> <PeoplePicker context={this.props.context} titleText={strings.Owners} personSelectionLimit={3} showHiddenInUI={false} principleTypes={[PrincipalType.User]} selectedItems={this._onOwnersSelected.bind(this)} isRequired={true} /> <PeoplePicker context={this.props.context} titleText={strings.Members} personSelectionLimit={3} showHiddenInUI={false} principleTypes={[PrincipalType.User]} selectedItems={this._onMembersSelected.bind(this)} /> </div> <Checkbox label={strings.CreateChannel} checked={createChannel} onChange={this._onCreateChannelChange.bind(this)} /> {createChannel && <div> <div className={styles.channelSection}> <TextField required={createChannel} label={strings.ChannelName} value={channelName} onChanged={this._onChannelNameChange.bind(this)}></TextField> <TextField label={strings.ChannelDescription} value={channelDescription} onChanged={this._onChannelDescriptionChange.bind(this)}></TextField> </div> <Checkbox label={strings.AddTab} checked={addTab} onChange={this._onAddTabChange.bind(this)} /> {addTab && <div> <TextField required={addTab} label={strings.TabName} value={tabName} onChanged={this._onTabNameChange.bind(this)}></TextField> <Dropdown required={addTab} label={strings.App} disabled={!this.state.apps} options={appsDropdownOptions} selectedKey={selectedAppId} onChanged={this._onAppSelected.bind(this)}></Dropdown> </div>} </div>} <div className={styles.buttons}> <PrimaryButton text={strings.Create} className={styles.button} onClick={this._onCreateClick.bind(this)} /> <DefaultButton text={strings.Clear} className={styles.button} onClick={this._onClearClick} /> </div> </div>, 1: <div> <Spinner label={spinnerText} /> </div>, 2: <div> <div>{strings.Success}</div> <PrimaryButton iconProps={{ iconName: 'TeamsLogo' }} href='https://aka.ms/mstfw' target='_blank'>{strings.OpenTeams}</PrimaryButton> <DefaultButton onClick={this._onClearClick}>{strings.StartOver}</DefaultButton> </div>, 4: <div> <div className={styles.error}>{strings.Error}</div> <DefaultButton onClick={this._onClearClick}>{strings.StartOver}</DefaultButton> </div> }[creationState]} </div> </div> ); } private _onTeamNameChange(value: string) { this.setState({ teamName: value }); } private _onTeamDescriptionChange(value: string) { this.setState({ teamDescription: value }); } private _onChannelNameChange(value: string) { this.setState({ channelName: value }); } private _onChannelDescriptionChange(value: string) { this.setState({ channelDescription: value }); } private _onTabNameChange(value: string) { this.setState({ tabName: value }); } private _onAppSelected(item: IDropdownOption) { this.setState({ selectedAppId: item.key as string }); } private _onCreateChannelChange(e: React.FormEvent<HTMLElement | HTMLInputElement>, checked: boolean) { this.setState({ createChannel: checked }); } private _onAddTabChange(e: React.FormEvent<HTMLElement | HTMLInputElement>, checked: boolean) { this.setState({ addTab: checked }); this._getAvailableApps(); } private _onMembersSelected(members: IPeoplePickerUserItem[]) { this.setState({ members: members.map(m => m.id) }); } private _onOwnersSelected(owners: IPeoplePickerUserItem[]) { this.setState({ owners: owners.map(o => o.id) }); } private async _onCreateClick() { this._processCreationRequest(); } private _onClearClick() { this._clearState(); } private _clearState() { this.setState({ teamName: '', teamDescription: '', members: [], owners: [], createChannel: false, channelName: '', channelDescription: '', addTab: false, tabName: '', selectedAppId: '', creationState: CreationState.notStarted, spinnerText: '' }); } private async _getAvailableApps(): Promise<void> { if (this.state.apps) { return; } const context = this.props.context; const graphClient = await context.msGraphClientFactory.getClient(); const appsResponse = await graphClient.api('appCatalogs/teamsApps').version('v1.0').get(); const apps = appsResponse.value as ITeamsApp[]; apps.sort((a, b) => { if (a.displayName < b.displayName) { return -1; } else if (a.displayName > b.displayName) { return 1; } return 0; }); this.setState({ apps: apps }); } /** * Main flow */ private async _processCreationRequest(): Promise<void> { const context = this.props.context; // initializing graph client to be used in all requests const graphClient = await context.msGraphClientFactory.getClient(); this.setState({ creationState: CreationState.creating, spinnerText: strings.CreatingGroup }); // // Create a group first // const groupId = await this._createGroup(graphClient); if (!groupId) { this._onError(); return; } this.setState({ spinnerText: strings.CreatingTeam }); // // Create team // const teamId = await this._createTeamWithAttempts(groupId, graphClient); if (!teamId) { this._onError(); return; } if (!this.state.createChannel) { this.setState({ creationState: CreationState.created }); return; } this.setState({ spinnerText: strings.CreatingChannel }); // // Create channel // const channelId = await this._createChannel(teamId, graphClient); if (!channelId) { this._onError(); return; } if (!this.state.addTab) { this.setState({ creationState: CreationState.created }); return; } this.setState({ spinnerText: strings.InstallingApp }); // // install app // const isInstalled = await this._installApp(teamId, graphClient); if (!isInstalled) { this._onError(); return; } this.setState({ spinnerText: strings.CreatingTab }); // // add tab // const isTabCreated = await this._addTab(teamId, channelId, graphClient); if (!isTabCreated) { this._onError(); } else { this.setState({ creationState: CreationState.created }); } } private _onError(message?: string): void { this.setState({ creationState: CreationState.error }); } /** * Installs the app to the team * @param teamId team Id * @param graphClient graph client */ private async _installApp(teamId: string, graphClient: MSGraphClient): Promise<boolean> { try { await graphClient.api(`teams/${teamId}/installedApps`).version('v1.0').post({ 'teamsApp@odata.bind': `https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/${this.state.selectedAppId}` }); } catch (error) { console.error(error); return false; } return true; } /** * Adds tab to the specified channel of the team * @param teamId team id * @param channelId channel id * @param graphClient graph client */ private async _addTab(teamId: string, channelId: string, graphClient: MSGraphClient): Promise<boolean> { try { await graphClient.api(`teams/${teamId}/channels/${channelId}/tabs`).version('v1.0').post({ displayName: this.state.tabName, 'teamsApp@odata.bind': `https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/${this.state.selectedAppId}` }); } catch (error) { console.error(error); return false; } return true; } /** * Creates channel in the team * @param teamId team id * @param graphClient graph client */ private async _createChannel(teamId: string, graphClient: MSGraphClient): Promise<string> { const { channelName, channelDescription } = this.state; try { const response = await graphClient.api(`teams/${teamId}/channels`).version('v1.0').post({ displayName: channelName, description: channelDescription }); return response.id; } catch (error) { console.error(error); return ''; } } /** * Creates O365 group * @param graphClient graph client */ private async _createGroup(graphClient: MSGraphClient): Promise<string> { const displayName = this.state.teamName; const mailNickname = this._generateMailNickname(displayName); let { owners, members } = this.state; const groupRequest = { displayName: displayName, description: this.state.teamDescription, groupTypes: [ 'Unified' ], mailEnabled: true, mailNickname: mailNickname, securityEnabled: false }; if (owners && owners.length) { groupRequest['owners@data.bind'] = owners.map(owner => { return `https://graph.microsoft.com/v1.0/users/${owner}`; }); } if (members && members.length) { groupRequest['members@data.bind'] = members.map(member => { return `https://graph.microsoft.com/v1.0/users/${member}`; }); } try { const response = await graphClient.api('groups').version('v1.0').post(groupRequest); return response.id; } catch (error) { console.error(error); return ''; } } /** * Creates team. as mentioned in the documentation - we need to make multiple attempts if team creation request errored * @param groupId group id * @param graphClient graph client */ private async _createTeamWithAttempts(groupId: string, graphClient: MSGraphClient): Promise<string> { let attemptsCount = 0; let teamId: string = ''; // // From the documentation: If the group was created less than 15 minutes ago, it's possible for the Create team call to fail with a 404 error code due to replication delays. // The recommended pattern is to retry the Create team call three times, with a 10 second delay between calls. // do { teamId = await this._createTeam(groupId, graphClient); if (teamId) { attemptsCount = 3; } else { attemptsCount++; } } while (attemptsCount < 3); return teamId; } /** * Waits 10 seconds and tries to create a team * @param groupId group id * @param graphClient graph client */ private async _createTeam(groupId: string, graphClient: MSGraphClient): Promise<string> { return new Promise<string>(resolve => { setTimeout(() => { graphClient.api(`groups/${groupId}/team`).version('v1.0').put({ memberSettings: { allowCreateUpdateChannels: true }, messagingSettings: { allowUserEditMessages: true, allowUserDeleteMessages: true }, funSettings: { allowGiphy: true, giphyContentRating: "strict" } }).then(response => { resolve(response.id); }, () => { resolve(''); }); }, 10000); }); } /** * Generates mail nick name by display name of the group * @param displayName group display name */ private _generateMailNickname(displayName: string): string { return displayName.toLowerCase().replace(/\s/gmi, '-'); } }
the_stack
import './cluster.js'; import './shared_style.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import 'chrome://resources/polymer/v3_0/iron-scroll-threshold/iron-scroll-threshold.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {Time} from 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import {IronScrollThresholdElement} from 'chrome://resources/polymer/v3_0/iron-scroll-threshold/iron-scroll-threshold.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BrowserProxyImpl} from './browser_proxy.js'; import {Cluster, PageCallbackRouter, PageHandlerRemote, QueryParams, QueryResult, URLVisit} from './history_clusters.mojom-webui.js'; import {ClusterAction, MetricsProxyImpl} from './metrics_proxy.js'; /** * @fileoverview This file provides a custom element that requests and shows * history clusters given a query. It handles loading more clusters using * infinite scrolling as well as deletion of visits within the clusters. */ declare global { interface HTMLElementTagNameMap { 'history-clusters': HistoryClustersElement, } interface Window { // https://github.com/microsoft/TypeScript/issues/40807 requestIdleCallback(callback: () => void): void; } } interface HistoryClustersElement { $: { clusters: IronListElement, confirmationDialog: CrLazyRenderElement<CrDialogElement>, confirmationToast: CrLazyRenderElement<CrToastElement>, scrollThreshold: IronScrollThresholdElement, }; } class HistoryClustersElement extends PolymerElement { static get is() { return 'history-clusters'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * The current query for which related clusters are requested and shown. */ query: { type: String, observer: 'onQueryChanged_', value: '', }, /** * The header text to show when the query and the results are non-empty. */ headerText_: { type: String, computed: `computeHeaderText_(result_.*)`, }, /** * The placeholder text to show when the results are empty. */ placeholderText_: { type: String, computed: `computePlaceholderText_(result_.*)`, }, /** * The browser response to a request for the freshest clusters related to * a given query until an optional given end time (or the present time). * Contains the clusters, the optional continuation end time to be used in * the follow-up request to load older clusters, and the original query. */ result_: Object, /** * The list of visits to be removed. A non-empty array indicates a pending * remove request to the browser. */ visitsToBeRemoved_: { type: Object, value: () => [], }, }; } //============================================================================ // Properties //============================================================================ query: string; private callbackRouter_: PageCallbackRouter; private onClustersQueryResultListenerId_: number|null = null; private onVisitsRemovedListenerId_: number|null = null; private pageHandler_: PageHandlerRemote; private result_: QueryResult; private visitsToBeRemoved_: Array<URLVisit>; //============================================================================ // Overridden methods //============================================================================ constructor() { super(); this.pageHandler_ = BrowserProxyImpl.getInstance().handler; this.callbackRouter_ = BrowserProxyImpl.getInstance().callbackRouter; } connectedCallback() { super.connectedCallback(); // Register a per-document singleton focus outline manager. Some of our // child elements depend on the CSS classes set by this singleton. FocusOutlineManager.forDocument(document); this.$.clusters.notifyResize(); this.$.clusters.scrollTarget = this; this.$.scrollThreshold.scrollTarget = this; this.onClustersQueryResultListenerId_ = this.callbackRouter_.onClustersQueryResult.addListener( this.onClustersQueryResult_.bind(this)); this.onVisitsRemovedListenerId_ = this.callbackRouter_.onVisitsRemoved.addListener( this.onVisitsRemoved_.bind(this)); } disconnectedCallback() { super.disconnectedCallback(); this.callbackRouter_.removeListener( assert(this.onClustersQueryResultListenerId_!)); this.onClustersQueryResultListenerId_ = null; this.callbackRouter_.removeListener( assert(this.onVisitsRemovedListenerId_!)); this.onVisitsRemovedListenerId_ = null; } //============================================================================ // Event handlers //============================================================================ private onCancelButtonClick_() { this.visitsToBeRemoved_ = []; this.$.confirmationDialog.get().close(); } private onConfirmationDialogCancel_() { this.visitsToBeRemoved_ = []; } private onLoadMoreButtonClick_() { if (this.result_ && this.result_.continuationEndTime) { this.queryClusters_({ query: this.result_.query, endTime: this.result_.continuationEndTime, }); } } private onRemoveButtonClick_() { this.pageHandler_.removeVisits(this.visitsToBeRemoved_) .then(({accepted}) => { if (!accepted) { this.visitsToBeRemoved_ = []; } }); this.$.confirmationDialog.get().close(); } /** * Called with `event` received from a cluster requesting to be removed from * the list when all its visits have been removed. Contains the cluster index. */ private onRemoveCluster_(event: CustomEvent<number>) { const index = event.detail; this.splice('result_.clusters', index, 1); MetricsProxyImpl.getInstance().recordClusterAction( ClusterAction.DELETED, index); } /** * Called with `event` received from a visit requesting to be removed. `event` * may contain the related visits of the said visit, if applicable. */ private onRemoveVisits_(event: CustomEvent<Array<URLVisit>>) { // Return early if there is a pending remove request. if (this.visitsToBeRemoved_.length) { return; } this.visitsToBeRemoved_ = event.detail; if (assert(this.visitsToBeRemoved_.length) > 1) { this.$.confirmationDialog.get().showModal(); } else { // Bypass the confirmation dialog if removing one visit only. this.onRemoveButtonClick_(); } } /** * Called when the value of the search field changes. */ private onSearchChanged_(event: CustomEvent<string>) { // Update the query based on the value of the search field, if necessary. if (event.detail !== this.query) { this.query = event.detail; } } /** * Called when the scrollable area has been scrolled nearly to the bottom. */ private onScrolledToBottom_() { this.$.scrollThreshold.clearTriggers(); if (this.shadowRoot!.querySelector(':focus-visible')) { // If some element of ours is keyboard-focused, don't automatically load // more clusters. It loses the user's position and messes up screen // readers. Let the user manually click the "Load More" button, if needed. // We use :focus-visible here, because :focus is triggered by mouse focus // too. And `FocusOutlineManager.visible()` is too primitive. It's true // on page load, and whenever the user is typing in the searchbox. return; } this.onLoadMoreButtonClick_(); } //============================================================================ // Helper methods //============================================================================ private computeHeaderText_(): string { return this.result_ && this.result_.query && this.result_.clusters.length ? loadTimeData.getStringF('headerText', this.result_.query) : ''; } private computePlaceholderText_(): string { if (!this.result_) { return ''; } return this.result_.clusters.length ? '' : loadTimeData.getString( this.result_.query ? 'noSearchResults' : 'noResults'); } /** * Returns true and hides the button unless we actually have more results to * load. Note we don't actually hide this button based on keyboard-focus * state. This is because if the user is using the mouse, more clusters are * loaded before the user ever gets a chance to see this button. */ private getLoadMoreButtonHidden_( _result: QueryResult, _result_clusters: Array<Cluster>, _result_continuation_time: Time): boolean { return !this.result_ || this.result_.clusters.length === 0 || !this.result_.continuationEndTime; } /** * Returns a promise that resolves when the browser is idle. */ private onBrowserIdle_(): Promise<void> { return new Promise(resolve => { window.requestIdleCallback(() => { resolve(); }); }); } private onClustersQueryResult_(result: QueryResult) { if (result.isContinuation) { // Do not replace the existing result when `result` contains a partial // set of clusters that should be appended to the existing ones. this.push('result_.clusters', ...result.clusters); this.set('result_.continuationEndTime', result.continuationEndTime); } else { // Scroll to the top when `result` contains a new set of clusters. this.scrollTop = 0; this.result_ = result; } // Handle the "tall monitor" edge case: if the returned results are are // shorter than the vertical viewport, the <history-clusters> element will // not have a scrollbar, and the user will never be able to trigger the // iron-scroll-threshold to request more results. Therefore, immediately // request more results if there is no scrollbar to fill the viewport. // // This should happen quite rarely in the queryless state since the backend // transparently tries to get at least ~100 visits to cluster. // // This is likely to happen very frequently in the search query state, since // many clusters will not match the search query and will be discarded. // // Do this on browser idle to avoid jank and to give the DOM a chance to be // updated with the results we just got. this.onBrowserIdle_().then(() => { if (this.scrollHeight <= this.clientHeight) { this.onLoadMoreButtonClick_(); } }); } private onQueryChanged_() { this.onBrowserIdle_().then(() => { this.queryClusters_({ query: this.query.trim(), endTime: undefined, }); }); } /** * Called when the last accepted request to browser to remove visits succeeds. */ private onVisitsRemoved_() { // Show the confirmation toast once done removing one visit only; since a // confirmation dialog was not shown prior to the action. if (assert(this.visitsToBeRemoved_.length) === 1) { this.$.confirmationToast.get().show(); } this.visitsToBeRemoved_ = []; } private queryClusters_(queryParams: QueryParams) { // Invalidate the existing `continuationEndTime`, if any, in order to // prevent sending additional requests while a request is in-flight. A new // `continuationEndTime` will be supplied with the new set of results. if (this.result_) { this.result_.continuationEndTime = undefined; } this.pageHandler_.queryClusters(queryParams); } } customElements.define(HistoryClustersElement.is, HistoryClustersElement);
the_stack
import {describe, beforeEach, it} from 'mocha'; // eslint-disable-next-line node/no-extraneous-import import {Octokit} from '@octokit/rest'; import assert from 'assert'; // eslint-disable-next-line @typescript-eslint/no-var-requires const LoggingOctokitPlugin = require('../src/logging/logging-octokit-plugin.js'); interface LogStatement { [key: string]: string | number | LogStatement; } class MockLogger { lastLogData: LogStatement | undefined; metric(json: LogStatement) { this.lastLogData = json; } } describe('Logging-Octokit-Plugin', () => { let loggingOctokit: Octokit; let logger: MockLogger; beforeEach(() => { const LoggingOctokit = Octokit.plugin(LoggingOctokitPlugin); logger = new MockLogger(); loggingOctokit = new LoggingOctokit({customLogger: logger}); }); it('logs information for issues.addLabels', () => { loggingOctokit.issues .addLabels({ owner: 'fooOwner', issue_number: 2, repo: 'barRepo', labels: ['a', 'b'], }) .catch((e: Error) => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_ADD_LABELS', value: 'a,b', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'ISSUE', object_id: 2, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.createComment', () => { loggingOctokit.issues .createComment({ owner: 'fooOwner', issue_number: 2, repo: 'barRepo', body: 'comment body', }) .catch((e: Error) => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_CREATE_COMMENT', value: 'comment body', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'ISSUE', object_id: 2, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.createLabel', () => { loggingOctokit.issues .createLabel({ owner: 'fooOwner', repo: 'barRepo', name: 'labelName', color: 'blue', }) .catch((e: Error) => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_CREATE_LABEL', value: 'labelName', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.removeLabel', () => { loggingOctokit.issues .removeLabel({ owner: 'fooOwner', repo: 'barRepo', issue_number: 3, name: 'labelName', }) .catch((e: Error) => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_REMOVE_LABEL', value: 'labelName', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'ISSUE', object_id: 3, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.deleteLabel', () => { loggingOctokit.issues .deleteLabel({owner: 'fooOwner', repo: 'barRepo', name: 'labelName'}) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_DELETE_LABEL', value: 'labelName', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.updateLabel', () => { loggingOctokit.issues .updateLabel({ owner: 'fooOwner', repo: 'barRepo', current_name: 'currName', name: 'labelName', }) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_UPDATE_LABEL', value: 'currName to labelName', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.update', () => { loggingOctokit.issues .update({ owner: 'fooOwner', repo: 'barRepo', issue_number: 3, body: 'issue body', state: 'open', }) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_UPDATE', value: 'updated: body,state', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'ISSUE', object_id: 3, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for issues.create', () => { loggingOctokit.issues .create({owner: 'fooOwner', repo: 'barRepo', title: 'new issue'}) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'ISSUE_CREATE', value: 'new issue', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for pulls.dismissReview', () => { loggingOctokit.pulls .dismissReview({ owner: 'fooOwner', repo: 'barRepo', message: 'bazMessage', pull_number: 3, review_id: 34, }) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'PULL_REQUEST_DISMISS_REVIEW', value: 'dismiss 34: bazMessage', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'PULL_REQUEST', object_id: 3, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for pulls.merge', () => { loggingOctokit.pulls .merge({owner: 'fooOwner', repo: 'barRepo', pull_number: 3}) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'PULL_REQUEST_MERGE', value: 'NONE', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'PULL_REQUEST', object_id: 3, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('logs information for pulls.updateBranch', () => { loggingOctokit.pulls .updateBranch({owner: 'fooOwner', repo: 'barRepo', pull_number: 3}) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = { action: { type: 'PULL_REQUEST_UPDATE_BRANCH', value: 'NONE', destination_repo: { repo_name: 'barRepo', owner: 'fooOwner', }, destination_object: { object_type: 'PULL_REQUEST', object_id: 3, }, }, }; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); it('does not log information for unknown actions', () => { loggingOctokit.issues .removeAssignees({ issue_number: 99, owner: 'fooOwner', repo: 'barRepo', assignee: 'bar', }) .catch(e => { // ignore HTTP Errors since Octokit is unauthenticated if (e.name !== 'HttpError') throw e; }) .finally(() => { const expected = undefined; const actual = logger.lastLogData; assert.deepEqual(actual, expected); }); }); });
the_stack
import {OnDestroy, OnInit} from "@angular/core"; import {StateService} from "@uirouter/angular"; import * as angular from "angular"; import {empty} from "rxjs/observable/empty"; import {of} from "rxjs/observable/of"; import {timer} from "rxjs/observable/timer"; import {catchError} from "rxjs/operators/catchError"; import {concatMap} from "rxjs/operators/concatMap"; import {expand} from "rxjs/operators/expand"; import {Subscription} from "rxjs/Subscription"; import * as _ from "underscore"; import {ImportComponentOption, ImportComponentType, ImportService, ImportTemplateResult, InputPortListItem, RemoteProcessInputPort} from '../../services/ImportComponentOptionTypes'; import {RegisterTemplateServiceFactory} from "../../services/RegisterTemplateServiceFactory"; import {moduleName} from "../module-name"; import Map = Common.Map; import {Common} from '../../../../lib/common/CommonTypes'; export class ImportTemplateController implements angular.IController, OnDestroy, OnInit { /** * the angular ng-form for validity checks * @type {{}} */ importTemplateForm = {}; /** * The file to upload * @type {null} */ templateFile: any = null; /** * the name of the file to upload * @type {null} */ fileName: string = null; /** * The type of upload (either 'zip', or 'xml') * @type {null} */ uploadType: string = null; /** * flag if uploading * @type {boolean} */ uploadInProgress: boolean = false; /** * Flag to indicate the upload produced validation errors * @type {boolean} */ validationErrors: boolean = false; /** * unique key to track upload status * @type {null} */ uploadKey: string = null; /** * Status of the current upload * @type {Array} */ uploadStatusMessages: any = []; /** * handle on the $interval object to cancel later * @type {null} */ uploadStatusCheck: Subscription; /** * Percent upload complete * @type {number} */ uploadProgress: number = 0; /** * Flag to indicate additional properties exist and a header show be shown for template options */ additionalInputNeeded: boolean = false; /** * All the importOptions that will be uploaded * @type {{}} */ importComponentOptions: Map<ImportComponentOption> = {}; /** * Registered Template import options */ templateDataImportOption: ImportComponentOption; /** * NiFi template options */ nifiTemplateImportOption: ImportComponentOption; /** * Reusable template options */ reusableTemplateImportOption: ImportComponentOption; /** * Connection information options to connect out ports to other input ports */ templateConnectionInfoImportOption: ImportComponentOption; /** * Option to indicate what ports should be pushed up and created as root level input ports for remote process groups */ remoteProcessGroupImportOption: ImportComponentOption; /** * Flag to indicate the user needs to provide ports before uploading * @type {boolean} */ remoteProcessGroupInputPortsNeeded: boolean = false /** * Array of the Remote Input Port options * @type {RemoteProcessInputPort[]} */ remoteProcessGroupInputPortNames: RemoteProcessInputPort[] = []; /** * Flag to indicate we need to ask the user to wire and connect the reusable flow out ports to other input ports * @type {boolean} */ reusableTemplateInputPortsNeeded: boolean = false; /** * Flag to indicate a connection is needed, but unable to find any * @type {boolean} */ noReusableConnectionsFound: boolean = false; /** * A map of the port names to the port Object * used for the connections from the outputs to input ports * @type {{}} */ connectionMap: Map<any> = {} /** * The available options in the list of possible inputPorts to connect to * @type {Array} of {label: port.name, value: port.name} */ inputPortList: InputPortListItem[] = []; /** * The Resulting object regurend after a user uploads * @type {null} */ importResult: ImportTemplateResult = null; /** * The resulting succsss/failure icon * @type {string} */ importResultIcon: string = "check_circle"; /** * The reuslting color of the icon * @type {string} */ importResultIconColor: string = "#009933"; /** * A mayp of any additional errors that should be displayed * @type {null} */ errorMap: any = null; /** * The count of errors after an upload * @type {number} */ errorCount: number = 0; /** * Flag to indicate if the Reorder list should be shown * @type {boolean} */ showReorderList: boolean = false; /** * Is this an XML file upload * @type {boolean} */ xmlType: boolean = false; /** * General message to be displayed after upload */ message: string; /** * Flag to see if we should check and use remote input ports. * This will be disabled until all of the Remte Input port and Remote Process Groups have been completed. */ remoteProcessGroupAware: boolean = false; templateParam: any; /** * When the controller is ready, initialize */ $onInit() { this.ngOnInit(); } /** * Initialize the controller and properties */ ngOnInit() { this.indexImportOptions(); this.setDefaultImportOptions(); this.checkRemoteProcessGroupAware(); } $onDestroy(): void { this.ngOnDestroy(); } ngOnDestroy(): void { this.stopUploadStatus(); } static $inject = ["$scope", "$http", "$timeout", "$mdDialog", "FileUpload", "RestUrlService", "ImportService", "RegisterTemplateService", "$state"]; constructor(private $scope: angular.IScope, private $http: angular.IHttpService, private $timeout: angular.ITimeoutService, private $mdDialog: angular.material.IDialogService, private FileUpload: any, private RestUrlService: any, private ImportService: ImportService, private registerTemplateService: RegisterTemplateServiceFactory, private $state: StateService) { /** * Watch when the file changes */ this.$scope.$watch(() => { return this.templateFile; }, (newVal: any, oldValue: any) => { if (newVal != null) this.checkFileName(newVal.name); //reset them if changed if (newVal != oldValue) { this.resetImportOptions(); } }); if (this.$state.params.template) { this.templateParam = this.$state.params.template; this.checkFileName(this.templateParam.fileName); } this.templateDataImportOption = this.ImportService.newTemplateDataImportOption(); this.nifiTemplateImportOption = this.ImportService.newNiFiTemplateImportOption(); this.reusableTemplateImportOption = this.ImportService.newReusableTemplateImportOption(); this.templateConnectionInfoImportOption = this.ImportService.newTemplateConnectionInfoImportOption(); this.remoteProcessGroupImportOption = this.ImportService.newRemoteProcessGroupImportOption(); } private checkFileName(newFileName: string) { if (newFileName != null) { this.fileName = newFileName; if (this.fileName.toLowerCase().endsWith(".xml")) { this.uploadType = 'xml'; } else { this.uploadType = 'zip' } } else { this.fileName = null; this.uploadType = null; } } /** * Called when a user changes a import option for overwriting */ onOverwriteSelectOptionChanged = this.ImportService.onOverwriteSelectOptionChanged; /** * Called when a user uploads a template */ importTemplate() { //reset some flags this.showReorderList = false; this.uploadInProgress = true; this.importResult = null; let file = this.templateFile; let uploadUrl = this.RestUrlService.ADMIN_IMPORT_TEMPLATE_URL; let successFn = (response: angular.IHttpResponse<ImportTemplateResult>) => { var responseData = response.data; this.xmlType = !responseData.zipFile; var processGroupName = (responseData.templateResults != undefined && responseData.templateResults.processGroupEntity != undefined) ? responseData.templateResults.processGroupEntity.name : '' /** * Count or errors after this upload * @type {number} */ let count = 0; /** * Map of errors by type after this upload * @type {{FATAL: any[]; WARN: any[]}} */ let errorMap: any = { "FATAL": [], "WARN": [] }; //reassign the options back from the response data let importComponentOptions = responseData.importOptions.importComponentOptions; //map the options back to the object map this.updateImportOptions(importComponentOptions); this.importResult = responseData; if (!responseData.valid || !responseData.success) { //Validation Error. Additional Input is needed by the end user this.additionalInputNeeded = true; this.importResultIcon = "error"; this.importResultIconColor = "#FF0000"; this.message = "Unable to import the template"; if (responseData.reusableFlowOutputPortConnectionsNeeded) { this.importResultIcon = "warning"; this.importResultIconColor = "#FF9901"; this.noReusableConnectionsFound = false; this.reusableTemplateInputPortsNeeded = true; this.message = "Additional connection information needed"; //show the user the list and allow them to configure and save it. //add button that will make these connections this.registerTemplateService.fetchRegisteredReusableFeedInputPorts().then((inputPortsResponse: any) => { //Update connectionMap and inputPortList this.inputPortList = []; if (inputPortsResponse.data) { angular.forEach(inputPortsResponse.data, (port, i) => { var disabled = angular.isUndefined(port.destinationProcessGroupName) || (angular.isDefined(port.destinationProcessGroupName) && port.destinationProcessGroupName != '' && port.destinationProcessGroupName == processGroupName); this.inputPortList.push({ label: port.name, value: port.name, description: port.destinationProcessGroupName, disabled: disabled }); this.connectionMap[port.name] = port; }); } if (this.inputPortList.length == 0) { this.noReusableConnectionsFound = true; } }); } if (responseData.remoteProcessGroupInputPortsNeeded) { this.importResultIcon = "warning"; this.importResultIconColor = "#FF9901"; this.message = "Remote input port assignments needed"; this.remoteProcessGroupInputPortsNeeded = true; //reset the value on the importResult that will be uploaded again this.remoteProcessGroupInputPortNames = responseData.remoteProcessGroupInputPortNames; var selected = _.filter(this.remoteProcessGroupInputPortNames, (inputPort: RemoteProcessInputPort) => { return inputPort.selected; }) this.importResult.remoteProcessGroupInputPortNames = selected; } } if (responseData.templateResults.errors) { angular.forEach(responseData.templateResults.errors, (processor) => { if (processor.validationErrors) { angular.forEach(processor.validationErrors, (error: any) => { var copy: any = {}; angular.extend(copy, error); angular.extend(copy, processor); copy.validationErrors = null; errorMap[error.severity].push(copy); count++; }); } }); this.errorMap = errorMap; this.errorCount = count; } if (!this.additionalInputNeeded) { if (count == 0) { this.showReorderList = responseData.zipFile; this.importResultIcon = "check_circle"; this.importResultIconColor = "#009933"; if (responseData.zipFile == true) { this.message = "Successfully imported and registered the template " + responseData.templateName; } else { this.message = "Successfully imported the template " + responseData.templateName + " into Nifi" } this.resetImportOptions(); } else { if (responseData.success) { this.resetImportOptions(); this.showReorderList = responseData.zipFile; this.message = "Successfully imported " + (responseData.zipFile == true ? "and registered " : "") + " the template " + responseData.templateName + " but some errors were found. Please review these errors"; this.importResultIcon = "warning"; this.importResultIconColor = "#FF9901"; } else { this.importResultIcon = "error"; this.importResultIconColor = "#FF0000"; this.message = "Unable to import " + (responseData.zipFile == true ? "and register " : "") + " the template " + responseData.templateName + ". Errors were found. You may need to fix the template or go to Nifi to fix the Controller Services and then try to import again."; } } } this.uploadInProgress = false; this.stopUploadStatus(1000); }; let errorFn = (response: angular.IHttpResponse<any>) => { this.importResult = response.data || {}; this.uploadInProgress = false; this.importResultIcon = "error"; this.importResultIconColor = "#FF0000"; this.message = (response.data && response.data.message) ? response.data.message : "Unable to import the template."; this.stopUploadStatus(1000); }; //build up the options from the Map and into the array for uploading var importComponentOptions = this.ImportService.getImportOptionsForUpload(this.importComponentOptions); //generate a new upload key for status tracking this.uploadKey = this.ImportService.newUploadKey(); var params = { uploadKey: this.uploadKey, importComponents: angular.toJson(importComponentOptions) }; this.additionalInputNeeded = false; this.startUploadStatus(); if (this.templateParam) { params['fileName'] = this.templateParam.fileName; params['repositoryName'] = this.templateParam.repository.name; params['repositoryType'] = this.templateParam.repository.type; this.importTemplateFromRepository(params, successFn, errorFn); } else this.FileUpload.uploadFileToUrl(file, uploadUrl, successFn, errorFn, params); } importTemplateFromRepository(params: any, successFn: any, errorFn: any) { this.$http.post("/proxy/v1/repository/templates/import", params, { headers: {'Content-Type': 'application/json'} }) .then(function (data) { if (successFn) { successFn(data) } }, function (err) { if (errorFn) { errorFn(err) } }); } /** * Stop the upload and stop the progress indicator * @param {number} delay wait this amount of millis before stopping */ stopUploadStatus(delay?: number) { const trigger = delay ? timer(delay) : empty(); trigger.subscribe(null, null, () => { this.uploadProgress = 0; if (this.uploadStatusCheck) { this.uploadStatusCheck.unsubscribe(); } }); } /** * Start the upload */ startUploadStatus() { this.stopUploadStatus(null); this.uploadStatusMessages = []; this.uploadStatusCheck = of(null).pipe( expand(() => { return timer(500).pipe( concatMap(() => this.$http.get(this.RestUrlService.ADMIN_UPLOAD_STATUS_CHECK(this.uploadKey))), catchError(err => { console.log("Failed to get upload status", err); return of(null); }) ); }), ).subscribe( (response: angular.IHttpResponse<any>) => { if (response && response.data && response.data != null) { this.uploadStatusMessages = response.data.messages; this.uploadProgress = response.data.percentComplete; } }, err => { console.log("Error in upload status loop", err); }); } /** * * @param importOptionsArr array of importOptions */ updateImportOptions(importOptionsArr: ImportComponentOption[]): void { var map = _.indexBy(importOptionsArr, 'importComponent'); _.each(importOptionsArr, (option: any) => { if (option.userAcknowledged) { option.overwriteSelectValue = "" + option.overwrite; } if (option.importComponent == ImportComponentType.TEMPLATE_DATA) { this.templateDataImportOption = option; } else if (option.importComponent == ImportComponentType.REUSABLE_TEMPLATE) { this.reusableTemplateImportOption = option; } else if (option.importComponent == ImportComponentType.NIFI_TEMPLATE) { this.nifiTemplateImportOption = option; } else if (option.importComponent == ImportComponentType.REMOTE_INPUT_PORT) { this.remoteProcessGroupImportOption = option; } else if (option.importComponent == ImportComponentType.TEMPLATE_CONNECTION_INFORMATION) { this.templateConnectionInfoImportOption = option; } this.importComponentOptions[option.importComponent] = option; }); } /** * Called when the user changes the output port connections * @param connection */ onReusableTemplateConnectionChange(connection: any) { var port = this.connectionMap[connection.inputPortDisplayName]; connection.reusableTemplateInputPortName = port.name; this.importTemplateForm["port-" + connection.feedOutputPortName].$setValidity("invalidConnection", true); }; /** * If a user adds connection information connecting templates together this will get called from the UI and will them import the template with the connection information */ setReusableConnections() { //TEMPLATE_CONNECTION_INFORMATION //submit form again for upload let option = ImportComponentType.TEMPLATE_CONNECTION_INFORMATION this.importComponentOptions[ImportComponentType[option]].connectionInfo = this.importResult.reusableTemplateConnections; this.importTemplate(); } /** * Called from the UI after a user has assigned some input ports to be 'remote aware input ports' */ setRemoteProcessInputPorts(): void { let option = ImportComponentType.REMOTE_INPUT_PORT this.importComponentOptions[ImportComponentType[option]].remoteProcessGroupInputPorts = this.importResult.remoteProcessGroupInputPortNames; var inputPortMap = {}; _.each(this.remoteProcessGroupInputPortNames, (port) => { port.selected = false; inputPortMap[port.inputPortName] = port; }); _.each(this.importResult.remoteProcessGroupInputPortNames, (inputPort) => { inputPort.selected = true; //find the matching in the complete set and mark it as selected var matchingPort = inputPortMap[inputPort.inputPortName]; if (angular.isDefined(matchingPort)) { matchingPort.selected = true; } }); //warn if existing ports are not selected let portsToRemove: RemoteProcessInputPort[] = []; _.each(this.remoteProcessGroupInputPortNames, (port) => { if (port.existing && !port.selected) { portsToRemove.push(port); } }); if (portsToRemove.length > 0) { //Warn and confirm before importing var names = _.map(portsToRemove, (port) => { return port.inputPortName }).join(","); var confirm = this.$mdDialog.confirm() .title('Warning You are about to delete template items.') .htmlContent('The following \'remote input ports\' exist, but are not selected to be imported:<br/><br/> <b>' + names + '</b>. <br/><br/>Continuing will result in these remote input ports being \ndeleted from the parent NiFi canvas. <br/><br/>Are you sure you want to continue?<br/>') .ariaLabel('Removal of Input Ports detected') .ok('Please do it!') .cancel('Cancel and Review'); this.$mdDialog.show(confirm).then(() => { let option = ImportComponentType.REMOTE_INPUT_PORT this.importComponentOptions[ImportComponentType[option]].userAcknowledged = true; this.importTemplate(); }, () => { //do nothing }); } else { if (this.importResult.remoteProcessGroupInputPortNames.length == 0) { var confirm = this.$mdDialog.confirm() .title('No remote input ports selected') .htmlContent('You have not selected any input ports to be exposed as \'remote input ports\'.<br/> Are you sure you want to continue?<br/>') .ariaLabel('No Remote Input Ports Selected') .ok('Please do it!') .cancel('Cancel and Review'); this.$mdDialog.show(confirm).then(() => { let option = ImportComponentType.REMOTE_INPUT_PORT this.importComponentOptions[ImportComponentType[option]].userAcknowledged = true; this.importTemplate(); }, () => { //do nothing }); } else { let option = ImportComponentType.REMOTE_INPUT_PORT this.importComponentOptions[ImportComponentType[option]].userAcknowledged = true; this.importTemplate(); } } } cancelImport() { //reset and reneable import button this.resetImportOptions(); this.uploadStatusMessages = []; this.importResult = null; } /** * Set the default values for the import options */ setDefaultImportOptions() { if (this.uploadType == 'zip') { //only if it is a zip do we continue with the niFi template this.templateDataImportOption.continueIfExists = false; this.reusableTemplateImportOption.shouldImport = true; this.reusableTemplateImportOption.userAcknowledged = true; //remote process group option this.remoteProcessGroupImportOption.shouldImport = true; this.remoteProcessGroupImportOption.userAcknowledged = true; } else { this.nifiTemplateImportOption.continueIfExists = false; this.reusableTemplateImportOption.shouldImport = false; this.reusableTemplateImportOption.userAcknowledged = true; this.remoteProcessGroupImportOption.shouldImport = false; this.remoteProcessGroupImportOption.userAcknowledged = false; } } /** * Determine if we are clustered and if so set the flag to show the 'remote input port' options */ private checkRemoteProcessGroupAware(): void { this.$http.get(this.RestUrlService.REMOTE_PROCESS_GROUP_AWARE).then((response: angular.IHttpResponse<any>) => { this.remoteProcessGroupAware = response.data.remoteProcessGroupAware; }); } /** * Index the import options in a map by their type */ indexImportOptions() { var arr = [this.templateDataImportOption, this.nifiTemplateImportOption, this.reusableTemplateImportOption, this.templateConnectionInfoImportOption, this.remoteProcessGroupImportOption]; this.importComponentOptions = _.indexBy(arr, 'importComponent'); } /** * Reset the options back to their orig. state */ resetImportOptions() { this.importComponentOptions = {}; this.templateDataImportOption = this.ImportService.newTemplateDataImportOption(); this.nifiTemplateImportOption = this.ImportService.newNiFiTemplateImportOption(); this.reusableTemplateImportOption = this.ImportService.newReusableTemplateImportOption(); this.templateConnectionInfoImportOption = this.ImportService.newTemplateConnectionInfoImportOption(); this.remoteProcessGroupImportOption = this.ImportService.newRemoteProcessGroupImportOption(); this.indexImportOptions(); this.setDefaultImportOptions(); this.additionalInputNeeded = false; this.reusableTemplateInputPortsNeeded = false; this.remoteProcessGroupInputPortsNeeded = false; this.inputPortList = []; this.connectionMap = {}; } } const module = angular.module(moduleName) .component('importTemplateController', { templateUrl: './import-template.html', controller: ImportTemplateController, controllerAs: 'vm' }) .component('importTemplateControllerEmbedded', { //Redefined the component with different name to be used in Angular //This component uses embedded template instead of templateUrl, else Angular complains template: "<import-template-controller></import-template-controller>", controller: ImportTemplateController, controllerAs: 'vm' }); export default module;
the_stack
import { html, render } from 'lit-html'; import ifNonNull from '../../src/globals/directives/if-non-null'; import '../../src/components/file-uploader/file-uploader'; import '../../src/components/file-uploader/drop-container'; import { FILE_UPLOADER_ITEM_STATE } from '../../src/components/file-uploader/file-uploader-item'; import EventManager from '../utils/event-manager'; const fileUploaderShellTemplate = (props?) => { const { helperText, labelText } = props ?? {}; return html` <bx-file-uploader helper-text="${ifNonNull(helperText)}" label-text="${ifNonNull(labelText)}"></bx-file-uploader> `; }; const dropContainerTemplate = (props?) => { const { accept, disabled, multiple } = props ?? {}; return html` <bx-file-drop-container accept="${ifNonNull(accept)}" ?disabled="${disabled}" ?multiple="${multiple}"> </bx-file-drop-container> `; }; const fileUploderItemTemplate = (props?) => { const { deleteAssistiveText, invalid, state, uploadingAssistiveText, uploadedAssistiveText, validityMessage } = props ?? {}; return html` <bx-file-uploader-item delete-assistive-text="${ifNonNull(deleteAssistiveText)}" ?invalid="${invalid}" state="${ifNonNull(state)}" uploading-assistive-text="${ifNonNull(uploadingAssistiveText)}" uploaded-assistive-text="${ifNonNull(uploadedAssistiveText)}" validity-message="${ifNonNull(validityMessage)}" > </bx-file-uploader-item> `; }; describe('file-uploader', function() { const events = new EventManager(); describe('bx-file-uploader', function() { describe('Misc attributes', function() { it('should render with minimum attributes', async function() { render(fileUploaderShellTemplate(), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render with various attributes', async function() { render( fileUploaderShellTemplate({ helperText: 'helper-text-foo', labelText: 'label-text-foo', }), document.body ); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader')).toMatchSnapshot({ mode: 'shadow' }); }); }); }); describe('bx-file-drop-container', function() { describe('Misc attributes', function() { it('should render with minimum attributes', async function() { render(dropContainerTemplate(), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-file-drop-container')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render with various attributes', async function() { render( dropContainerTemplate({ accept: 'image/png', disabled: true, multiple: true, }), document.body ); await Promise.resolve(); expect(document.body.querySelector('bx-file-drop-container')).toMatchSnapshot({ mode: 'shadow' }); }); }); describe('Handling events', function() { let elem; const pngFile = new File([new ArrayBuffer(0)], 'foo.png', { type: 'image/png' }); const jpegFile = new File([new ArrayBuffer(0)], 'foo.jpg', { type: 'image/jpeg' }); beforeEach(async function() { render(dropContainerTemplate({ accept: 'image/png' }), document.body); await Promise.resolve(); elem = document.querySelector('bx-file-drop-container'); }); it('Should handle drag-over', async function() { const dataTransfer: { dropEffect?: string } = {}; const event = Object.assign(new CustomEvent('dragover', { bubbles: true, composed: true }), { dataTransfer }); elem!.dispatchEvent(event); await Promise.resolve(); expect(elem).toMatchSnapshot({ mode: 'shadow' }); expect(dataTransfer.dropEffect).toBe('copy'); }); it('Should handle drag-leave', async function() { const dataTransfer: { dropEffect?: string } = {}; const event = Object.assign(new CustomEvent('dragleave', { bubbles: true, composed: true }), { dataTransfer }); elem!.dispatchEvent(event); expect(dataTransfer.dropEffect).toBe('move'); }); it('Should handle drop', async function() { const spyChange = jasmine.createSpy('after changed'); events.on(elem!, 'bx-file-drop-container-changed', spyChange); const dataTransfer = { files: [pngFile, jpegFile] }; const event = Object.assign(new CustomEvent('drop', { bubbles: true, composed: true }), { dataTransfer }); elem!.dispatchEvent(event); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles.length).toBe(1); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles[0]).toBe(pngFile); }); it('Should handle file upload link', async function() { const origGetFiles = (elem as any)._getFiles; // Workaround for `HTMLInputElement.files` that only accepts `FileList` while there is no `FileList` constructor spyOn(elem, '_getFiles').and.callFake(function(event) { // TODO: See if we can get around TS2683 // @ts-ignore return origGetFiles.call(this, { type: event.type, target: { files: [pngFile, jpegFile], }, }); }); const spyChange = jasmine.createSpy('after changed'); events.on(elem!, 'bx-file-drop-container-changed', spyChange); const input = elem!.shadowRoot!.querySelector('input'); const event = new CustomEvent('change', { bubbles: true, composed: true }); input!.dispatchEvent(event); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles.length).toBe(1); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles[0]).toBe(pngFile); }); it('Should handle filtering by file extension', async function() { render(dropContainerTemplate({ accept: '.png' }), document.body); await Promise.resolve(); elem = document.querySelector('bx-file-drop-container'); const pngFileWithoutMIMEType = new File([new ArrayBuffer(0)], 'foo.png'); const spyChange = jasmine.createSpy('after changed'); events.on(elem!, 'bx-file-drop-container-changed', spyChange); const dataTransfer = { files: [pngFileWithoutMIMEType, jpegFile] }; const event = Object.assign(new CustomEvent('drop', { bubbles: true, composed: true }), { dataTransfer }); elem!.dispatchEvent(event); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles.length).toBe(1); expect(spyChange.calls.argsFor(0)[0].detail.addedFiles[0]).toBe(pngFileWithoutMIMEType); }); }); }); describe('bx-file-uploader-item', function() { describe('Misc attributes', function() { it('should render with minimum attributes', async function() { render(fileUploderItemTemplate(), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader-item')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render with various attributes', async function() { render( fileUploderItemTemplate({ invalid: true, uploadingAssistiveText: 'uploading-assistive-text-foo', validityMessage: 'validity-message-foo', }), document.body ); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader-item')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render uploaded state', async function() { render(fileUploderItemTemplate({ state: FILE_UPLOADER_ITEM_STATE.UPLOADED }), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader-item')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render uploaded state with various attributes', async function() { render( fileUploderItemTemplate({ invalid: true, state: FILE_UPLOADER_ITEM_STATE.UPLOADED, uploadedAssistiveText: 'uploaded-assistive-text-foo', validityMessage: 'validity-message-foo', }), document.body ); await Promise.resolve(); expect( document.body .querySelector('bx-file-uploader-item')! .shadowRoot!.querySelector('svg')! .getAttribute('aria-label') ).toBe('uploaded-assistive-text-foo'); }); it('should render editing state', async function() { render(fileUploderItemTemplate({ state: FILE_UPLOADER_ITEM_STATE.EDITING }), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader-item')).toMatchSnapshot({ mode: 'shadow' }); }); it('should render editing state with various attributes', async function() { render( fileUploderItemTemplate({ deleteAssistiveText: 'delete-assistive-text-foo', invalid: true, state: FILE_UPLOADER_ITEM_STATE.EDITING, validityMessage: 'validity-message-foo', }), document.body ); await Promise.resolve(); expect(document.body.querySelector('bx-file-uploader-item')).toMatchSnapshot({ mode: 'shadow' }); }); }); describe('Handling delete button', function() { it('Should fire bx-file-uploader-item-beingdeleted/bx-file-uploader-item-deleted events upon hiding', async function() { render(fileUploderItemTemplate({ state: FILE_UPLOADER_ITEM_STATE.EDITING }), document.body); await Promise.resolve(); const elem = document.querySelector('bx-file-uploader-item'); const spyBeforeDelete = jasmine.createSpy('before deleted'); const spyDelete = jasmine.createSpy('after deleted'); events.on(elem!, 'bx-file-uploader-item-beingdeleted', spyBeforeDelete); events.on(elem!, 'bx-file-uploader-item-deleted', spyDelete); (elem!.shadowRoot!.querySelector('button') as HTMLElement).click(); await Promise.resolve(); expect(spyBeforeDelete).toHaveBeenCalled(); expect(spyDelete).toHaveBeenCalled(); }); it('Should support preventing modal from being deleted upon user gesture', async function() { render(fileUploderItemTemplate({ state: FILE_UPLOADER_ITEM_STATE.EDITING }), document.body); await Promise.resolve(); const elem = document.querySelector('bx-file-uploader-item'); const spyDelete = jasmine.createSpy('after deleted'); events.on(elem!, 'bx-file-uploader-item-beingdeleted', event => { event.preventDefault(); }); events.on(elem!, 'bx-file-uploader-item-deleted', spyDelete); (elem!.shadowRoot!.querySelector('button') as HTMLElement).click(); await Promise.resolve(); expect(spyDelete).not.toHaveBeenCalled(); }); }); }); afterEach(function() { render(undefined!, document.body); events.reset(); }); });
the_stack
import http from './http'; import req from './request'; import { TASK_TYPE_ENUM } from '@/constant'; export default { // 获取类型数据源 getTypeOriginData(params: any) { return http.post(req.GET_TYPE_ORIGIN_DATA, params); }, listTablesBySchema(params: any) { return http.post(req.LIST_TABLE_BY_SCHEMA, params); }, // 获取kafka topic预览数据 getDataPreview(params: any) { return http.post(req.GET_DATA_PREVIEW, params); }, pollPreview(params: any) { return http.post(req.POLL_PREVIEW, params); }, // 添加或更新任务 saveTask(params: any) { return http.post(req.SAVE_TASK, params); }, // 获取Topic getTopicType(params: any) { return http.post(req.GET_TOPIC_TYPE, params); }, getStreamTableColumn(params: { schema: string; sourceId: number; tableName: string; flinkVersion: string; }) { return http.post(req.GET_STREAM_TABLECOLUMN, params); }, // 获取源表中的时区列表 getTimeZoneList(params?: any) { return http.post(req.GET_TIMEZONE_LIST, params); }, // 转换向导到脚本模式 convertToScriptMode(params: any) { return http.post(req.CONVERT_TO_SCRIPT_MODE, params); }, checkSyntax(params: any) { return http.post(req.GRAMMAR_CHECK, params); }, sqlFormat(params: any) { return http.post(req.SQL_FORMAT, params); }, getTaskList(params: any) { return http.post(req.GET_TASK_LIST, params); }, getStatusCount(params: any) { return http.post(req.GET_STATUS_COUNT, params); }, startTask(params: any) { return http.post(req.START_TASK, params); }, startCollectionTask(params: any) { return http.post(req.START_COLLECTION_TASK, params); }, getTaskManagerLog(params: any) { return http.post(req.GET_TASK_MANAGER_LOG, params); }, getJobManagerLog(params: any) { return http.post(req.GET_JOB_MANAGER_LOG, params); }, listTaskManager(params: any) { return http.post(req.LIST_TASK_MANAGER, params); }, getTaskLogs(params: any) { return http.post(req.GET_TASK_LOGS, params); }, // failover 日志 getFailoverLogsByTaskId(params: any) { return http.post(req.GET_TASK_FAILOVER_LOG, params); }, getHistoryLog(params: any) { return http.post(req.GET_HISTORY_LOG, params); }, isOpenCdb(params: { dataInfoId: number }) { return http.post(req.IS_OPEN_CDB, params); }, getPDBList(params: { dataInfoId: number; searchKey?: string }) { return http.post(req.GET_PDB_LIST, params); }, // 数据开发 - 获取启停策略列表 getAllStrategy() { return http.post(req.GET_ALL_STRATEGY); }, getTopicPartitionNum(params: any) { return http.post(req.GET_TOPIC_PARTITION_NUM, params); }, getSchemaTableColumn(params: any) { return http.post(req.GET_SCHEMA_TABLE_COLUMN, params); }, getSlotList(params: any) { return http.post(req.GET_SLOT_LIST, params); }, getBinlogListBySource(params: any) { return http.post(req.GET_BINLOG_LIST_BY_SOURCE, params); }, // 获取指标 getTaskMetrics(params: { taskId: number; timespan: string; end: number; chartNames: string[]; }) { return http.post(req.GET_TASK_METRICS, params); }, getMetricValues(params: { taskId: number }) { // 获取所有指标 return http.get(req.GET_METRIC_VALUES, params); }, checkSourceStatus(params: { taskId: number }) { // 获取任务的异常数据源 return http.post(req.CHECK_SOURCE_STATUS, params); }, queryTaskMetrics(params: { taskId: number; chartName: string; timespan: string; end: number }) { // 查询指标数据 return http.post(req.QUERY_TASK_METRICES, params); }, getListHistory(params: any) { return http.post(req.GET_LIST_HISTORY, params); }, listCheckPoint(params: any) { return http.post(req.LIST_CHECK_POINT, params); }, stopTask(params: any) { return http.post(req.STOP_TASK, params); }, getTaskJson(params: any) { return http.post(req.GET_TASK_JSON, params); }, getTaskSqlText(params: any) { return http.post(req.GET_TASK_SQL_TEXT, params); }, addTenant(params: any) { return http.post(req.ADD_TENANT, params); }, switchTenant(params: { tenantId: number }) { return http.post(req.SWITCH_TENANT, params); }, login(params: { username: string; password: string }) { return http.postAsFormData(req.LOGIN, params); }, addCluster(params: { clusterName: string }) { return http.post(req.ADD_CLUSTER, params); // 新增集群 }, getClusterInfo(params: { clusterId: number }) { return http.get(req.GET_CLUSTER_INFO, params); }, uploadResource(params: { fileName: any; componentType: number }) { return http.postAsFormData(req.UPLOAD_RESOURCE, params); }, deleteComponent(params: { componentId: number }) { return http.post(req.DELETE_COMPONENT, params); // 删除组件 }, deleteCluster(params: { clusterId: number }) { return http.post(req.DELETE_CLUSTER, params); }, testConnect(params: { clusterName: string; componentType: number; versionName: string; deployType: number | string; }) { return http.post(req.TEST_CONNECT, params); }, testConnects(params: { clusterName: string }) { return http.post(req.TEST_CONNECTS, params); }, closeKerberos(params: { componentId: number }) { return http.post(req.CLOSE_KERBEROS, params); }, getVersionData(params?: any) { return http.get(req.GET_VERSION, params); }, saveComponent(params: any) { return http.postAsFormData(req.SAVE_COMPONENT, params); }, parseKerberos(params: any) { return http.postAsFormData(req.PARSE_KERBEROS, params); }, getClusterList(params: { currentPage: number; pageSize: number }) { return http.post(req.GET_CLUSTER_LIST, params); }, getTenantList(params?: any) { return http.get(req.GET_TENANT_LIST, params); }, getMetaComponent(params?: any) { return http.get(req.GET_META_COMPONENT, params); }, // 获取存储组件列表 getComponentStore(params: any) { return http.post(req.GET_COMPONENTSTORE, params); }, // 上传kerberos文件 uploadKerberos(params: { kerberosFile: any; clusterId: string; componentCode: number }) { return http.postAsFormData(req.UPLOAD_KERBEROS, params); }, // 更新krb5.conf文件 updateKrb5Conf(params: { krb5Content: string }) { return http.post(req.UPDATE_KRB5CONF, params); }, // 概览-获取集群 getClusterDetail(params: any) { return http.post(req.GET_CLUSTER_DETAIL, params); }, // 明细-杀死选中或者杀死全部任务 killTasks(params: { jobResource: string; nodeAddress: string; stage: number; jobIdList?: any[]; }) { return http.post(req.KILL_TASKS, params); }, killAllTask(params: { jobResource: string; nodeAddress: string }) { return http.post(req.KILL_ALL_TASK, params); }, stickJob(params: { jobId: string; jobResource: string }) { return http.post(req.JOB_STICK, params); }, // 查看明细 和搜索条件 getViewDetail(params: { stage: number; jobResource: string; nodeAddress?: string; currentPage: number; pageSize: number; }) { return http.post(req.GET_VIEW_DETAIL, params); }, getClusterResources(params: any) { return http.post(req.GET_CLUSTER_RESOURCES, params); }, getLoadTemplate(params: any) { return http.post(req.GET_LOADTEMPLATE, params); }, getAllCluster(params?: any) { return http.get(req.GET_ALL_CLUSTER, params); }, getEnginesByCluster(params?: any) { return http.get(req.GET_ENGINES_BY_CLUSTER, params); }, searchTenant(params: any) { return http.post(req.SEARCH_TENANT, params); }, bindTenant(params: any) { return http.post(req.BIND_TENANT, params); }, switchQueue(params: any) { return http.post(req.SWITCH_QUEUE, params); }, refreshQueue(params: { clusterName: string }) { return http.post(req.REFRESH_QUEUE, params); }, getRetainDBList(params?: any) { return http.post(req.GET_RETAINDB_LIST, params); }, convertToHiveColumns(params: any) { return http.post(req.CONVERT_TO_HIVE_COLUMNS, params); }, convertDataSyncToScriptMode(params: any) { return http.post(req.CONVERT_SYNC_T0_SCRIPT_MODE, params); }, getOfflineTaskByID(params: any) { return http.post(req.GET_TASK, params); }, getCustomParams(params?: any) { return http.post(req.GET_CUSTOM_TASK_PARAMS, params); }, getSyncTemplate(params: any) { return http.post(req.GET_SYNC_SCRIPT_TEMPLATE, params); }, publishOfflineTask(params: any) { return http.post(req.PUBLISH_TASK, params); }, getTaskTypes(params?: any) { return http.post(req.GET_TASK_TYPES, params); }, getTableInfoByDataSource(params: any) { return http.post(req.GET_TABLE_INFO_BY_DATASOURCE, params); }, execSQLImmediately<T>(params: any) { // 立即执行SQL return http.post<T>(req.EXEC_SQL_IMMEDIATELY, params); }, stopSQLImmediately(params: any) { // 停止执行数据同步 return http.post(req.STOP_SQL_IMMEDIATELY, params); }, execDataSyncImmediately<T>(params: any) { // 立即执行数据同步 return http.post<T>(req.EXEC_DATA_SYNC_IMMEDIATELY, params); }, stopDataSyncImmediately(params: any) { // 停止执行SQL return http.post(req.STOP_DATA_SYNC_IMMEDIATELY, params); }, getIncrementColumns(params: any) { // 获取增量字段 return http.post(req.GET_INCREMENT_COLUMNS, params); }, checkSyncMode(params: any) { // 检测是否满足增量数据同步 return http.post(req.CHECK_SYNC_MODE, params); }, getHivePartitions(params: any) { // 获取Hive分区 return http.post(req.CHECK_HIVE_PARTITIONS, params); }, /** * - 查询数据同步任务,SQL 执行结果 * - 需要补充增量同步 * @param {Object} params 请求参数 * @param {Number} taskType 任务类型 */ selectExecResultData(params: any, taskType: any) { // const url = taskType && taskType === TASK_TYPE_ENUM.SYNC ? req.SELECT_DATA_SYNC_RESULT : req.SELECT_SQL_RESULT_DATA; return http.post(url, params); }, forzenTask(params: any) { return http.post(req.FROZEN_TASK, params); }, getOfflineCatalogue(params: any) { return http.post(req.GET_OFFLINE_CATALOGUE, params); }, addOfflineCatalogue(params: any) { return http.post(req.ADD_OFFLINE_CATALOGUE, params); }, editOfflineCatalogue(params: any) { return http.post(req.EDIT_OFFLINE_CATALOGUE, params); }, addOfflineResource(params: any) { return http.postAsFormData(req.ADD_OFFLINE_RESOURCE, params); }, replaceOfflineResource(params: any) { return http.postAsFormData(req.REPLACE_OFFLINE_RESOURCE, params); }, addOfflineTask(params: any) { return http.post(req.ADD_OFFLINE_TASK, params); }, saveOfflineJobData(params: any) { return http.post(req.SAVE_OFFLINE_JOBDATA, params); }, addOfflineFunction(params: any) { return http.post(req.ADD_OFFLINE_FUNCTION, params); }, delOfflineTask(params: any) { return http.post(req.DEL_OFFLINE_TASK, params); }, delOfflineFolder(params: any) { return http.post(req.DEL_OFFLINE_FOLDER, params); }, delOfflineRes(params: any) { return http.post(req.DEL_OFFLINE_RES, params); }, delOfflineFn(params: any) { return http.post(req.DEL_OFFLINE_FN, params); }, getOfflineFn(params: any) { return http.post(req.GET_FN_DETAIL, params); }, getOfflineRes(params: any) { return http.post(req.GET_RES_DETAIL, params); }, getHBaseColumnFamily(params: any) { return http.post(req.GET_HBASE_COLUMN_FAMILY, params); }, queryOfflineTasks(params: any) { return http.post(req.QUERY_TASKS, params); }, getOfflineTaskLog(params: any) { // 获取离线任务日志 return http.post(req.GET_TASK_LOG, params); }, getOfflineTaskPeriods(params: any) { // 转到前后周期 return http.post(req.GET_TASK_PERIODS, params); }, queryJobs(params: any) { return http.post(req.QUERY_JOBS, params); }, patchTaskData(params: any) { // 补数据 return http.post(req.PATCH_TASK_DATA, params); }, getTaskChildren(params: any) { // 获取任务子节点 return http.post(req.GET_TASK_CHILDREN, params); }, getFillData(params: any) { // 补数据搜索 return http.post(req.GET_FILL_DATA, params); }, getFillDataDetail(params: any) { // 补数据详情 return http.post(req.GET_FILL_DATA_DETAIL, params); }, batchStopJob(params: any) { // 批量停止任务 return http.post(req.BATCH_STOP_JOBS, params); }, batchRestartAndResume(params: any) { // 重启并恢复任务 return http.post(req.BATCH_RESTART_AND_RESUME_JOB, params); }, getJobChildren(params: any) { // 获取任务子Job return http.post(req.GET_JOB_CHILDREN, params); }, queryJobStatics(params: any) { return http.post(req.QUERY_JOB_STATISTICS, params); }, stopFillDataJobs(params: any) { return http.post(req.STOP_FILL_DATA_JOBS, params); }, getPersonInCharge() { return http.post(req.USER_QUERYUSER); }, /** * 获取工作流任务节点实例的子节点 */ getTaskJobWorkflowNodes(params: any) { return http.post(req.GET_TASK_JOB_WORKFLOW_NODES, params); }, getOfflineTableList(params: any) { return http.post(req.TABLE_LIST, params); }, getOfflineTableColumn(params: any) { return http.post(req.GET_TABLE_COLUMN, params); }, getOfflineColumnForSyncopate(params: any) { return http.post(req.GET_COLUMN_FOR_SYNCOPATE, params); }, getHivePartitionsForDataSource(params: any) { return http.post(req.GET_HIVE_PARTITIONS, params); }, getDataSourcePreview(params: any) { return http.post(req.GET_DATA_SOURCE_PREVIEW, params); }, getAllSchemas(params: any) { return http.post(req.GET_ALL_SCHEMAS, params); }, queryByTenantId(params: any) { return http.get(req.QUREY_BY_TENANT_ID, params); }, dataSourcepage(params: any) { return http.post(req.GET_DATA_SOURCE_PAGE, params); }, typeList(params: any) { return http.post(req.GET_TYPE_LIST, params); }, dataSourceDelete(params: any) { return http.post(req.DELETE_SOURCE, params); }, queryDsClassifyList(params: any) { return http.post(req.QUERY_DATA_SOURCE_CLASSIFY_LIST, params); }, queryDsTypeByClassify(params: any) { return http.post(req.QUERY_LIST_BY_CLASSIFY, params); }, queryDsVersionByType(params: any) { return http.post(req.QUERY_VERSION_BY_CLASSIFY, params); }, findTemplateByTypeVersion(params: any) { return http.post(req.QUERY_TEMPLATE_BY_VERSION, params); }, addDatasource(params: any) { return http.post(req.ADD_DATA_SOURCE, params); }, addOrUpdateSourceWithKerberos(params: any) { return http.postForm(req.UPLOAD_DATA_SOURCE_WITH_KERBEROS, params); }, testCon(params: any) { return http.post(req.TEST_CONNECT_IN_DATA_SOURCE, params); }, testConWithKerberos(params: any) { return http.postForm(req.TEST_KERBEROS_IN_DATA_SOURCE, params); }, detail(params: any) { return http.post(req.GET_DATA_SOURCE_DETAIL, params); }, uploadCode(params: any) { return http.postForm(req.UPLOAD_CODE, params); }, getCreateTargetTable(params: any) { return http.post(req.GET_CREATE_TARGET_TABLE, params); }, createDdlTable(params: any) { return http.post(req.CREATE_DDL_TABLE, params); }, batchStopJobByDate(params: any) { // 按业务日期批量杀任务 return http.post(req.BATCH_STOP_JOBS_BY_DATE, params); }, allProductGlobalSearch(params: any) { return http.post(req.ALL_PRODUCT_GLOBAL_SEARCH, params); }, };
the_stack
import * as bitcoinjs from 'bitcoinjs-lib' import * as crypto from 'crypto' import { decodeToken, TokenSigner, TokenVerifier } from 'jsontokens' import { ecPairToHexString, ecPairToAddress } from 'blockstack' import { ValidationError, AuthTokenTimestampValidationError } from './errors' import { logger } from './utils' const DEFAULT_STORAGE_URL = 'storage.blockstack.org' export const LATEST_AUTH_VERSION = 'v1' function pubkeyHexToECPair (pubkeyHex: string) { const pkBuff = Buffer.from(pubkeyHex, 'hex') return bitcoinjs.ECPair.fromPublicKey(pkBuff) } export interface AuthScopeEntry { scope: string domain: string } export interface TokenPayloadType { gaiaChallenge: string iss: string exp: number iat?: number salt: string hubUrl?: string associationToken?: string scopes?: AuthScopeEntry[] childToAssociate?: string } export class AuthScopeValues { writePrefixes: string[] = [] writePaths: string[] = [] deletePrefixes: string[] = [] deletePaths: string[] = [] writeArchivalPrefixes: string[] = [] writeArchivalPaths: string[] = [] static parseEntries(scopes: AuthScopeEntry[]) { const scopeTypes = new AuthScopeValues() scopes.forEach(entry => { switch (entry.scope) { case AuthScopesTypes.putFilePrefix: return scopeTypes.writePrefixes.push(entry.domain) case AuthScopesTypes.putFile: return scopeTypes.writePaths.push(entry.domain) case AuthScopesTypes.putFileArchival: return scopeTypes.writeArchivalPaths.push(entry.domain) case AuthScopesTypes.putFileArchivalPrefix: return scopeTypes.writeArchivalPrefixes.push(entry.domain) case AuthScopesTypes.deleteFilePrefix: return scopeTypes.deletePrefixes.push(entry.domain) case AuthScopesTypes.deleteFile: return scopeTypes.deletePaths.push(entry.domain) } }) return scopeTypes } } export class AuthScopesTypes { static readonly putFile = 'putFile' static readonly putFilePrefix = 'putFilePrefix' static readonly deleteFile = 'deleteFile' static readonly deleteFilePrefix = 'deleteFilePrefix' static readonly putFileArchival = 'putFileArchival' static readonly putFileArchivalPrefix = 'putFileArchivalPrefix' } export const AuthScopeTypeArray: string[] = Object.values(AuthScopesTypes).filter(val => typeof val === 'string') export function getTokenPayload(token: import('jsontokens/lib/decode').TokenInterface) { if (typeof token.payload === 'string') { throw new Error('Unexpected token payload type of string') } return token.payload } export function decodeTokenForPayload(opts: { encodedToken: string; validationErrorMsg: string; }) { try { return getTokenPayload(decodeToken(opts.encodedToken)) } catch (e) { logger.error(`${opts.validationErrorMsg}, ${e}`) logger.error(opts.encodedToken) throw new ValidationError(opts.validationErrorMsg) } } export interface AuthenticationInterface { checkAssociationToken(token: string, bearerAddress: string): void getAuthenticationScopes(): AuthScopeEntry[] isAuthenticationValid( address: string, challengeTexts: string[], options?: { requireCorrectHubUrl?: boolean, validHubUrls?: string[], oldestValidTokenTimestamp?: number } ): string parseAuthScopes(): AuthScopeValues } export class V1Authentication implements AuthenticationInterface { token: string constructor(token: string) { this.token = token } static fromAuthPart(authPart: string) { if (!authPart.startsWith('v1:')) { throw new ValidationError('Authorization header should start with v1:') } const token = authPart.slice('v1:'.length) const payload = decodeTokenForPayload({ encodedToken: token, validationErrorMsg: 'fromAuthPart: Failed to decode authentication JWT' }) const publicKey = payload.iss if (!publicKey) { throw new ValidationError('Auth token should be a JWT with at least an `iss` claim') } const scopes = payload.scopes if (scopes) { validateScopes(scopes) } return new V1Authentication(token) } static makeAuthPart(secretKey: bitcoinjs.ECPairInterface, challengeText: string, associationToken?: string, hubUrl?: string, scopes?: AuthScopeEntry[], issuedAtDate?: number) { const FOUR_MONTH_SECONDS = 60 * 60 * 24 * 31 * 4 const publicKeyHex = secretKey.publicKey.toString('hex') const salt = crypto.randomBytes(16).toString('hex') if (scopes) { validateScopes(scopes) } const payloadIssuedAtDate = issuedAtDate || (Date.now()/1000|0) const payload: TokenPayloadType = { gaiaChallenge: challengeText, iss: publicKeyHex, exp: FOUR_MONTH_SECONDS + (Date.now() / 1000), iat: payloadIssuedAtDate, associationToken, hubUrl, salt, scopes } const signerKeyHex = ecPairToHexString(secretKey).slice(0, 64) const token = new TokenSigner('ES256K', signerKeyHex).sign(payload) return `v1:${token}` } static makeAssociationToken(secretKey: bitcoinjs.ECPairInterface, childPublicKey: string) { const FOUR_MONTH_SECONDS = 60 * 60 * 24 * 31 * 4 const publicKeyHex = secretKey.publicKey.toString('hex') const salt = crypto.randomBytes(16).toString('hex') const payload: TokenPayloadType = { childToAssociate: childPublicKey, iss: publicKeyHex, exp: FOUR_MONTH_SECONDS + (Date.now() / 1000), iat: (Date.now() / 1000 | 0), gaiaChallenge: String(undefined), salt } const signerKeyHex = ecPairToHexString(secretKey).slice(0, 64) const token = new TokenSigner('ES256K', signerKeyHex).sign(payload) return token } checkAssociationToken(token: string, bearerAddress: string) { // a JWT can have an `associationToken` that was signed by one of the // whitelisted addresses on this server. This method checks a given // associationToken and verifies that it authorizes the "outer" // JWT's address (`bearerAddress`) const payload = decodeTokenForPayload({ encodedToken: token, validationErrorMsg: 'checkAssociationToken: Failed to decode association token in JWT' }) // publicKey (the issuer of the association token) // will be the whitelisted address (i.e. the identity address) const publicKey = payload.iss const childPublicKey = payload.childToAssociate const expiresAt = payload.exp if (! publicKey) { throw new ValidationError('Must provide `iss` claim in association JWT.') } if (! childPublicKey) { throw new ValidationError('Must provide `childToAssociate` claim in association JWT.') } if (! expiresAt) { throw new ValidationError('Must provide `exp` claim in association JWT.') } const verified = new TokenVerifier('ES256K', publicKey).verify(token) if (!verified) { throw new ValidationError('Failed to verify association JWT: invalid issuer') } if (expiresAt < (Date.now()/1000)) { throw new ValidationError( `Expired association token: expire time of ${expiresAt} (secs since epoch)`) } // the bearer of the association token must have authorized the bearer const childAddress = ecPairToAddress(pubkeyHexToECPair(childPublicKey)) if (childAddress !== bearerAddress) { throw new ValidationError( `Association token child key ${childPublicKey} does not match ${bearerAddress}`) } const signerAddress = ecPairToAddress(pubkeyHexToECPair(publicKey)) return signerAddress } parseAuthScopes() { const scopes = this.getAuthenticationScopes() return AuthScopeValues.parseEntries(scopes) } /* * Get the authentication token's association token's scopes. * Does not validate the authentication token or the association token * (do that with isAuthenticationValid first). * * Returns the scopes, if there are any given. * Returns [] if there is no association token, or if the association token has no scopes */ getAuthenticationScopes() { const payload = decodeTokenForPayload({ encodedToken: this.token, validationErrorMsg: 'getAuthenticationScopes: Failed to decode authentication JWT' }) if (!payload['scopes']) { // not given return [] } // unambiguously convert to AuthScope const scopes: AuthScopeEntry[] = payload.scopes.map((s: any) => { const r = { scope: String(s.scope), domain: String(s.domain) } return r }) return scopes } /* * Determine if the authentication token is valid: * * must have signed the given `challengeText` * * must not be expired * * if it contains an associationToken, then the associationToken must * authorize the given address. * * Returns the address that signed off on this token, which will be * checked against the server's whitelist. * * If this token has an associationToken, then the signing address * is the address that signed the associationToken. * * Otherwise, the signing address is the given address. * * this throws a ValidationError if the authentication is invalid */ isAuthenticationValid(address: string, challengeTexts: Array<string>, options?: { requireCorrectHubUrl?: boolean, validHubUrls?: Array<string>, oldestValidTokenTimestamp?: number }): string { const payload = decodeTokenForPayload({ encodedToken: this.token, validationErrorMsg: 'isAuthenticationValid: Failed to decode authentication JWT' }) const publicKey = payload.iss const gaiaChallenge = payload.gaiaChallenge const scopes = payload.scopes if (!publicKey) { throw new ValidationError('Must provide `iss` claim in JWT.') } // check for revocations if (options && options.oldestValidTokenTimestamp && options.oldestValidTokenTimestamp > 0) { const tokenIssuedAtDate = payload.iat const oldestValidTokenTimestamp: number = options.oldestValidTokenTimestamp if (!tokenIssuedAtDate) { const message = `Gaia bucket requires auth token issued after ${oldestValidTokenTimestamp}` + ' but this token has no creation timestamp. This token may have been revoked by the user.' throw new AuthTokenTimestampValidationError(message, oldestValidTokenTimestamp) } if (tokenIssuedAtDate < options.oldestValidTokenTimestamp) { const message = `Gaia bucket requires auth token issued after ${oldestValidTokenTimestamp}` + ` but this token was issued ${tokenIssuedAtDate}.` + ' This token may have been revoked by the user.' throw new AuthTokenTimestampValidationError(message, oldestValidTokenTimestamp) } } const issuerAddress = ecPairToAddress(pubkeyHexToECPair(publicKey)) if (issuerAddress !== address) { throw new ValidationError('Address not allowed to write on this path') } if (options && options.requireCorrectHubUrl) { let claimedHub = payload.hubUrl if (!claimedHub) { throw new ValidationError( 'Authentication must provide a claimed hub. You may need to update blockstack.js.') } if (claimedHub.endsWith('/')) { claimedHub = claimedHub.slice(0, -1) } const validHubUrls = options.validHubUrls if (!validHubUrls) { throw new ValidationError( 'Configuration error on the gaia hub. validHubUrls must be supplied.') } if (!validHubUrls.includes(claimedHub)) { throw new ValidationError( `Auth token's claimed hub url '${claimedHub}' not found` + ` in this hubs set: ${JSON.stringify(validHubUrls)}`) } } if (scopes) { validateScopes(scopes) } let verified try { verified = new TokenVerifier('ES256K', publicKey).verify(this.token) } catch (err) { throw new ValidationError('Failed to verify supplied authentication JWT') } if (!verified) { throw new ValidationError('Failed to verify supplied authentication JWT') } if (!challengeTexts.includes(gaiaChallenge)) { throw new ValidationError(`Invalid gaiaChallenge text in supplied JWT: "${gaiaChallenge}"` + ` not found in ${JSON.stringify(challengeTexts)}`) } const expiresAt = payload.exp if (expiresAt && expiresAt < (Date.now()/1000)) { throw new ValidationError( `Expired authentication token: expire time of ${expiresAt} (secs since epoch)`) } if ('associationToken' in payload && payload.associationToken) { return this.checkAssociationToken( payload.associationToken, address) } else { return address } } } export class LegacyAuthentication implements AuthenticationInterface { checkAssociationToken(_token: string, _bearerAddress: string): void { throw new Error('Method not implemented.') } parseAuthScopes(): AuthScopeValues { return new AuthScopeValues() } publickey: bitcoinjs.ECPairInterface signature: string constructor(publickey: bitcoinjs.ECPairInterface, signature: string) { this.publickey = publickey this.signature = signature } static fromAuthPart(authPart: string) { const decoded = JSON.parse(Buffer.from(authPart, 'base64').toString()) const publickey = pubkeyHexToECPair(decoded.publickey) const hashType = Buffer.from([bitcoinjs.Transaction.SIGHASH_NONE]) const signatureBuffer = Buffer.concat([Buffer.from(decoded.signature, 'hex'), hashType]) const signature = bitcoinjs.script.signature.decode(signatureBuffer).signature.toString('hex') return new LegacyAuthentication(publickey, signature) } static makeAuthPart(secretKey: bitcoinjs.ECPairInterface, challengeText: string) { const publickey = secretKey.publicKey.toString('hex') const digest = bitcoinjs.crypto.sha256(Buffer.from(challengeText)) const signatureBuffer = secretKey.sign(digest) const signatureWithHash = bitcoinjs.script.signature.encode(signatureBuffer, bitcoinjs.Transaction.SIGHASH_NONE) // We only want the DER encoding so remove the sighash version byte at the end. // See: https://github.com/bitcoinjs/bitcoinjs-lib/issues/1241#issuecomment-428062912 const signature = signatureWithHash.toString('hex').slice(0, -2) const authObj = { publickey, signature } return Buffer.from(JSON.stringify(authObj)).toString('base64') } getAuthenticationScopes(): AuthScopeEntry[] { // no scopes supported in this version return [] } isAuthenticationValid(address: string, challengeTexts: Array<string>, options? : {}) { // eslint-disable-line @typescript-eslint/no-unused-vars if (ecPairToAddress(this.publickey) !== address) { throw new ValidationError('Address not allowed to write on this path') } for (const challengeText of challengeTexts) { const digest = bitcoinjs.crypto.sha256(Buffer.from(challengeText)) const valid = (this.publickey.verify(digest, Buffer.from(this.signature, 'hex')) === true) if (valid) { return address } } logger.debug(`Failed to validate with challenge text: ${JSON.stringify(challengeTexts)}`) throw new ValidationError('Invalid signature or expired authentication token.') } } export function getChallengeText(myURL: string = DEFAULT_STORAGE_URL) { const header = 'gaiahub' const allowedSpan = '0' const myChallenge = 'blockstack_storage_please_sign' return JSON.stringify( [header, allowedSpan, myURL, myChallenge] ) } export function getLegacyChallengeTexts(myURL: string = DEFAULT_STORAGE_URL): Array<string> { // make legacy challenge texts const header = 'gaiahub' const myChallenge = 'blockstack_storage_please_sign' const legacyYears = ['2018', '2019'] return legacyYears.map(year => JSON.stringify( [header, year, myURL, myChallenge])) } export function parseAuthHeader(authHeader: string): AuthenticationInterface { if (!authHeader || !authHeader.toLowerCase().startsWith('bearer')) { throw new ValidationError('Failed to parse authentication header.') } const authPart = authHeader.slice('bearer '.length) const versionIndex = authPart.indexOf(':') if (versionIndex < 0) { // default to legacy authorization header return LegacyAuthentication.fromAuthPart(authPart) } else { const version = authPart.slice(0, versionIndex) if (version === 'v1') { return V1Authentication.fromAuthPart(authPart) } else { throw new ValidationError('Unknown authentication header version: ${version}') } } } export function validateAuthorizationHeader(authHeader: string, serverName: string, address: string, requireCorrectHubUrl: boolean = false, validHubUrls: Array<string> = null, oldestValidTokenTimestamp?: number): string { const serverNameHubUrl = `https://${serverName}` if (!validHubUrls) { validHubUrls = [ serverNameHubUrl ] } else if (!validHubUrls.includes(serverNameHubUrl)) { validHubUrls.push(serverNameHubUrl) } let authObject = null try { authObject = parseAuthHeader(authHeader) } catch (err) { logger.error(err) } if (!authObject) { throw new ValidationError('Failed to parse authentication header.') } const challengeTexts = [] challengeTexts.push(getChallengeText(serverName)) getLegacyChallengeTexts(serverName).forEach(challengeText => challengeTexts.push(challengeText)) return authObject.isAuthenticationValid(address, challengeTexts, { validHubUrls, requireCorrectHubUrl, oldestValidTokenTimestamp }) } /* * Get the authentication scopes from the authorization header. * Does not check the authorization header or its association token * (do that with validateAuthorizationHeader first). * * Returns the scopes on success * Throws on malformed auth header */ export function getAuthenticationScopes(authHeader: string) { const authObject = parseAuthHeader(authHeader) return authObject.parseAuthScopes() } /* * Validate authentication scopes. They must be well-formed, * and there can't be too many of them. * Return true if valid. * Throw ValidationError on error */ function validateScopes(scopes: AuthScopeEntry[]) { if (scopes.length > 8) { throw new ValidationError('Too many authentication scopes') } for (let i = 0; i < scopes.length; i++) { const scope = scopes[i] // valid scope? const found = AuthScopeTypeArray.find((s) => (s === scope.scope)) if (!found) { throw new ValidationError(`Unrecognized scope ${scope.scope}`) } } return true }
the_stack
import { DirectiveHook, App, DirectiveBinding, ObjectDirective } from 'vue'; export interface ScrollBarElement extends HTMLElement { $scroll?: CustomScrollBar onmousewheel?: EventListener, mouseenterEvent?: EventListener, mouseleaveEvent?: EventListener } export interface ScrollBarOptions { direction: 'x' | 'y' | 'all', scrollBarWidth: number, scrollBarOffsetX: number, scrollBarOffsetY: number, scrollBarThumbColor: string, scrollBarThumbBorderRadius: boolean | number, scrollBarTrackColor: string, enableTrackClickScroll: boolean, scrollSpeed: number, dragScroll: boolean, thumbShow: 'always' | 'hover', scrollBarThumbHoverColor?: string } export type Direction = 'x' | 'y' class CustomScrollBar { private el: ScrollBarElement private options: ScrollBarOptions private directionArr: Direction[] private timer: number | null | NodeJS.Timeout private scrollWrapper?: HTMLElement | null constructor({ el, options }: { el: string | HTMLElement, options?: ScrollBarOptions }) { if (el instanceof HTMLElement) { this.el = el; } else { this.el = document.querySelector(el) as HTMLElement; } this.options = { direction: 'y', scrollBarWidth: 6, scrollBarOffsetX: 0, scrollBarOffsetY: 0, scrollBarThumbColor: '#aab', scrollBarThumbBorderRadius: true, scrollBarTrackColor: 'transparent', enableTrackClickScroll: true, scrollSpeed: 20, dragScroll: false, thumbShow: 'always', ...options }; this.directionArr = this.options.direction === 'all' ? ['x', 'y'] : ['x', 'y'].includes(this.options.direction) ? [this.options.direction] : ['y']; this.timer = null; this.el.$scroll = this; } init (defaultX = 0, defaultY = 0) { this.scrollWrapper = document.createElement('div') as HTMLElement; this.scrollWrapper.style.cssText = `position: absolute;top:0;left:0;bottom:0;right:0;transform:translate(${defaultX}px,${defaultY}px)`; this.scrollWrapper.setAttribute('class', 'scroll__wrapper'); this.el.appendChild(this.scrollWrapper); this.el.style.position = 'relative'; this.el.style.overflow = 'hidden'; this.directionArr.map(item => { this.createScrollBarTrack(item); }); if (this.options.dragScroll) { this.setDragScroll(this.el, this.directionArr); } if (this.options.thumbShow === 'hover') { this.setDisplayForHover(this.el); } } private createScrollBarTrack (direction: Direction) { const isY = direction === 'y'; let { scrollBarWidth, scrollBarOffsetX, scrollBarOffsetY, scrollBarThumbColor, scrollBarThumbHoverColor, scrollBarThumbBorderRadius, scrollBarTrackColor, enableTrackClickScroll, scrollSpeed } = this.options; const scrollBarThumbColorIsGradient = scrollBarThumbColor.includes('gradient'); scrollBarThumbBorderRadius = scrollBarThumbBorderRadius ? scrollBarWidth / 2 : 0; const track = document.createElement('div'); track.setAttribute('direction', direction); const trackCssText = isY ? `position: absolute;right: 0;top: 0;height: 100%; width: ${scrollBarWidth + scrollBarOffsetX * 2}px;background: ${scrollBarTrackColor};` : `position: absolute;left: 0;bottom: 0;width: 100%; height: ${scrollBarWidth + scrollBarOffsetX * 2}px;background: ${scrollBarTrackColor};`; track.style.cssText = trackCssText; track.setAttribute('class', `scroll__track_${direction}`); if (this.scrollWrapper) { this.scrollWrapper.appendChild(track); } const thumb = document.createElement('div'); let thumbCssText = isY ? `position: relative;top: 0;right: 0;width: ${scrollBarWidth + scrollBarOffsetX * 2}px;padding: ${scrollBarOffsetY}px ${scrollBarOffsetX}px;box-sizing:border-box;cursor: pointer;` : `position: relative;bottom: 0;left: 0;height: ${scrollBarWidth + scrollBarOffsetX * 2}px;padding: ${scrollBarOffsetX}px ${scrollBarOffsetY}px;box-sizing:border-box;cursor: pointer;`; const thumbInner = document.createElement('div'); let thumbInnerCssText = `width: 100%;height:100%;border-radius: ${scrollBarThumbBorderRadius}px;`; if (scrollBarThumbColorIsGradient) { thumbInnerCssText += `background-image: ${scrollBarThumbColor};`; } else { thumbInnerCssText += `background: ${scrollBarThumbColor};`; } const { offsetHeight, scrollHeight, offsetWidth, scrollWidth, scrollTop, scrollLeft } = this.el; const offsetSize = isY ? offsetHeight : offsetWidth; const scrollSize = isY ? scrollHeight : scrollWidth; if (scrollSize <= offsetSize) { // Don't need show overflow scroll return; } const thumbSize = offsetSize / scrollSize * offsetSize; thumbCssText += isY ? `height: ${thumbSize}px;` : `width: ${thumbSize}px`; thumb.style.cssText = thumbCssText; thumb.setAttribute('class', 'scroll__thumb'); thumbInner.style.cssText = thumbInnerCssText; thumbInner.setAttribute('class', 'scroll__thumb_inner'); thumb.appendChild(thumbInner); track.appendChild(thumb); let elScrollTop = isY ? scrollTop : scrollLeft; const thumbScrollTop = elScrollTop / scrollSize * offsetSize; thumb.style.transform = isY ? `translateY(${thumbScrollTop}px)` : `translateX(${thumbScrollTop}px)`; let isInThumbMouseMove = false; const elScrollTopMax = scrollSize - offsetSize; const thumbScrollTopMax = offsetSize - thumbSize; if (isY) { this.el.onmousewheel = function (wheel: any) { const deltaY = -wheel.wheelDelta || wheel.deltaY; if (!isInThumbMouseMove) { elScrollTop = deltaY < 0 ? elScrollTop < -deltaY ? 0 : elScrollTop + deltaY : elScrollTop >= elScrollTopMax - deltaY ? elScrollTopMax : elScrollTop + deltaY; __scroll__(track, elScrollTop / scrollSize * offsetSize); } return false; }; } if (scrollBarThumbHoverColor) { thumb.onmouseenter = function () { if (scrollBarThumbHoverColor) { thumbInner.style.background = scrollBarThumbHoverColor; } }; thumb.onmouseleave = function () { thumbInner.style.background = scrollBarThumbColor; }; } thumb.onmousedown = function (downEvent) { downEvent.stopPropagation(); const thumbEl = (<HTMLElement>downEvent.target).parentNode as HTMLElement; const beforeClientY = isY ? downEvent.clientY : downEvent.clientX; const [thumbBeforeOffset] = thumbEl.style.transform.match(/\d+(\.\d+)?/) || [0]; const _thumbBeforeOffset = ~~thumbBeforeOffset; isInThumbMouseMove = true; document.onmousemove = function (moveEvent) { document.body.style.userSelect = 'none'; const { clientY, clientX } = moveEvent; let thumbMoveOffset = (isY ? clientY : clientX) - beforeClientY + _thumbBeforeOffset; elScrollTop = thumbMoveOffset / offsetSize * scrollSize; if (elScrollTop < 0) { thumbMoveOffset = 0; elScrollTop = 0; } else if (elScrollTop > elScrollTopMax) { thumbMoveOffset = thumbScrollTopMax; elScrollTop = elScrollTopMax; } __scroll__(track, thumbMoveOffset); }; document.onmouseup = function () { isInThumbMouseMove = false; document.body.style.userSelect = 'auto'; document.onmousemove = null; document.onmouseup = null; }; }; // 允许点击轨道进行滚动 if (enableTrackClickScroll) { track.onmousedown = function (e) { const trackEl = e.target as HTMLElement; if (trackEl) { const clickPosition = isY ? (e.clientY - trackEl.getBoundingClientRect().top) : (e.clientX - trackEl.getBoundingClientRect().left); let thumbMoveOffset = clickPosition - thumbSize / 2; if (thumbMoveOffset < 0) { thumbMoveOffset = 0; } else if (thumbMoveOffset > thumbScrollTopMax) { thumbMoveOffset = thumbScrollTopMax; } __scroll__(trackEl, thumbMoveOffset); } }; } // 滚动函数,使用requestAnimationFrame实现滚动动画 let animateScroll: FrameRequestCallback; let rAF: number; const __scroll__ = (trackEl: HTMLElement, thumbMoveOffset: number) => { if (rAF) { window.cancelAnimationFrame(rAF); } animateScroll = () => { let thumbScrollTop, breakAnimation; let [thumbBeforeOffset] = (trackEl.childNodes[0] as HTMLElement).style.transform.match(/\d+(\.\d+)?/) || [0]; thumbBeforeOffset = ~~thumbBeforeOffset; if (thumbMoveOffset > thumbBeforeOffset) { thumbBeforeOffset += scrollSpeed; if (thumbBeforeOffset < thumbMoveOffset) { elScrollTop = thumbBeforeOffset / offsetSize * scrollSize; thumbScrollTop = thumbBeforeOffset; breakAnimation = false; } else { elScrollTop = thumbBeforeOffset > thumbScrollTopMax ? elScrollTopMax : (thumbMoveOffset / offsetSize * scrollSize); thumbScrollTop = thumbBeforeOffset > thumbScrollTopMax ? thumbScrollTopMax : thumbMoveOffset; breakAnimation = true; } } else { thumbBeforeOffset -= scrollSpeed; if (thumbBeforeOffset > thumbMoveOffset) { elScrollTop = thumbBeforeOffset / offsetSize * scrollSize; thumbScrollTop = thumbBeforeOffset; breakAnimation = false; } else { elScrollTop = thumbBeforeOffset < 0 ? 0 : thumbMoveOffset / offsetSize * scrollSize; thumbScrollTop = thumbBeforeOffset < 0 ? 0 : thumbMoveOffset; breakAnimation = true; } } this.setTranslate(direction, elScrollTop); thumb.style.transform = isY ? `translateY(${thumbScrollTop}px)` : `translateX(${thumbScrollTop}px)`; if (isY) { this.el.scrollTop = elScrollTop; } else { this.el.scrollLeft = elScrollTop; } if (breakAnimation) { window.cancelAnimationFrame(rAF); } else { rAF = window.requestAnimationFrame(animateScroll); } }; rAF = window.requestAnimationFrame(animateScroll); }; } update (wait = 200) { if (this.timer !== null) { clearTimeout(this.timer as number); } this.timer = setTimeout(() => { if (this.scrollWrapper) { const { transform } = window.getComputedStyle(this.scrollWrapper); const [, , , , x, y] = transform.match(/-?\d+\.?\d{0,}/g) as RegExpMatchArray; const _x = ~~x; const _y = ~~y; this.destroy(); this.init(_x, _y); } }, wait); } destroy () { if (this.scrollWrapper) { this.scrollWrapper.parentNode?.removeChild(this.scrollWrapper); this.scrollWrapper = null; } if (this.el.mouseenterEvent) { this.el.addEventListener('mouseenter', this.el.mouseenterEvent); } if (this.el.mouseleaveEvent) { this.el.addEventListener('mouseleave', this.el.mouseleaveEvent); } } private setTranslate (direction: Direction, value: number) { if (this.scrollWrapper) { const { transform } = window.getComputedStyle(this.scrollWrapper); const [a, b, c, d, x, y] = transform.match(/-?\d+\.?\d{0,}/g) as RegExpMatchArray; if (direction === 'x') { this.scrollWrapper.style.transform = `matrix(${a},${b},${c},${d},${value},${y})`; } else if (direction === 'y') { this.scrollWrapper.style.transform = `matrix(${a},${b},${c},${d},${x},${value})`; } } } private setDisplayForHover (el: ScrollBarElement) { const thumbAppendCss = 'opacity: 0;transition: opacity .4s ease-in-out'; const scrollThumb = Array.from(el.querySelectorAll('.scroll__thumb')) as HTMLElement[]; scrollThumb.map(item => { item.style.cssText = item.style.cssText + thumbAppendCss; }); el.mouseenterEvent = function () { scrollThumb.map(item => { item.style.opacity = '1'; }); }; el.mouseleaveEvent = function () { scrollThumb.map(item => { item.style.opacity = '0'; }); }; el.addEventListener('mouseenter', el.mouseenterEvent); el.addEventListener('mouseleave', el.mouseleaveEvent); } private setDragScroll (el: HTMLElement, directionArr: Direction[]) { el.onmousedown = function (e) { // const { top: elClientRectTop, left: elClientRectLeft } = el.getBoundingClientRect() const { scrollTop, scrollLeft, scrollHeight, offsetHeight, scrollWidth, offsetWidth } = el; const { clientX: beforeClientX, clientY: beforeClientY } = e; const [elScrollLeftMax, elScrollTopMax] = [scrollWidth - offsetWidth, scrollHeight - offsetHeight]; const [thumbScrollLeftMax, thumbScrollTopMax] = [offsetWidth - (offsetWidth / scrollWidth * offsetWidth), offsetHeight - (offsetHeight / scrollHeight * offsetHeight)]; document.body.style.userSelect = 'none'; document.body.style.cursor = 'pointer'; document.onmousemove = function (moveEvent) { const { clientX, clientY } = moveEvent; let [elScrollLeft, elScrollTop] = [beforeClientX - clientX + scrollLeft, beforeClientY - clientY + scrollTop]; let [thumbMoveOffsetX, thumbMoveOffsetY] = [elScrollLeft / scrollWidth * offsetWidth, elScrollTop / scrollHeight * offsetHeight]; if (elScrollLeft < 0) { thumbMoveOffsetX = 0; elScrollLeft = 0; } else if (elScrollLeft > elScrollLeftMax) { thumbMoveOffsetX = thumbScrollLeftMax; elScrollLeft = elScrollLeftMax; } if (elScrollTop < 0) { thumbMoveOffsetY = 0; elScrollTop = 0; } else if (elScrollTop > elScrollTopMax) { thumbMoveOffsetY = thumbScrollTopMax; elScrollTop = elScrollTopMax; } (el.querySelector('.scroll__wrapper') as HTMLElement).style.transform = `translate(${elScrollLeft}px, ${elScrollTop}px)`; if (directionArr.includes('x')) { (el.querySelector('.scroll__track_x .scroll__thumb') as HTMLElement).style.transform = `translateX(${thumbMoveOffsetX}px)`; } if (directionArr.includes('y')) { (el.querySelector('.scroll__track_y .scroll__thumb') as HTMLElement).style.transform = `translateY(${thumbMoveOffsetY}px)`; } el.scrollTop = elScrollTop; el.scrollLeft = elScrollLeft; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; document.body.style.userSelect = 'default'; document.body.style.cursor = 'default'; }; }; } } const mounted = (el: HTMLElement, binding: DirectiveBinding, userOptions?: ScrollBarOptions):void => { const { arg, value } = binding; const isMobile = /(Android|iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); const customGlobalOptions = userOptions || {}; if (!isMobile) { const options = { ...customGlobalOptions, ...value, direction: arg }; const scroll = new CustomScrollBar({ el, options }); scroll.init(); } }; const unmounted: DirectiveHook = (el: ScrollBarElement) => { el.$scroll && el.$scroll.destroy(); }; export const ScrollDirective: ObjectDirective = { mounted: (el: HTMLElement, binding: DirectiveBinding) => mounted(el, binding), unmounted, // @ts-ignore inserted: (el, binding) => mounted(el, binding), unbind: unmounted, install: (Vue: App, userOptions: ScrollBarOptions):void => { Vue.directive('scroll', { mounted: ((el, binding) => mounted(el, binding, userOptions)), unmounted, // @ts-ignore inserted: ((el, binding) => mounted(el, binding, userOptions)), unbind: unmounted }); } }; export default CustomScrollBar;
the_stack
export const replayScenarios = [ { incomingActivities: [ { // type: 'conversationUpdate', id: '1', }, { id: 'bot2a', replyToId: 'act-2', }, { id: 'bot2b', replyToId: 'act-2', }, { id: 'act-2', }, { id: 'bot3a', replyToId: 'act-3', }, { id: 'bot3b', replyToId: 'act-3', }, { id: 'act-3', }, ], postActivitiesSlots: [1, 4], activitiesToBePosted: [ { id: 'act-2', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-3', from: { role: 'user' }, channelData: { test: true } }, ], botResponsesForActivity: [ { // type: 'conversationUpdate', id: '1', }, { id: 'act-bot2a', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2b', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { matchIndexes: [1, 2] } }, ], }, { activitiesToBePosted: [ { id: 'act-2', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-3', from: { role: 'user' }, channelData: { test: true } }, ], incomingActivities: [ { // type: 'conversationUpdate', id: 'conv-1', }, { // type: 'conversationUpdate', id: 'conv-2', }, { id: 'bot2a', replyToId: 'act-2', }, { id: 'bot2b', replyToId: 'act-2', }, { id: 'conv-3', }, { // type: 'conversationUpdate', id: 'act-2', }, { id: 'bot3a', replyToId: 'act-3', }, { id: 'bot3b', replyToId: 'act-3', }, { id: 'act-3', }, ], postActivitiesSlots: [2, 6], botResponsesForActivity: [ { // type: 'conversationUpdate', id: 'dummy-conv-update-1', }, { // type: 'conversationUpdate', id: 'dummy-conv-update-2', }, { id: 'act-bot2a', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2b', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { test: true }, }, { // type: 'conversationUpdate', id: 'dummy-conv-update-3', }, { id: 'bdc9da50-30d0-4611-967e-182db8882533', from: { role: 'bot' }, channelData: { matchIndexes: [2, 3] } }, { id: 'act-bot3a', replyToId: 'bdc9da50-30d0-4611-967e-182db8882534', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3b', replyToId: 'bdc9da50-30d0-4611-967e-182db8882534', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db8882534', from: { role: 'bot' }, channelData: { matchIndexes: [2, 3] } }, ], }, { incomingActivities: [ { // type: 'conversationUpdate', id: '1', }, { id: 'bot2a', replyToId: 'act-2', }, { id: 'bot3a', replyToId: 'act-3', }, { id: 'bot3b', replyToId: 'act-3', }, { id: 'bot2b', replyToId: 'act-2', }, { id: 'bot3c', replyToId: 'act-3', }, { id: 'act-3', }, { id: 'bot2c', replyToId: 'act-2', }, { id: 'bot2d', replyToId: 'act-2', }, { id: 'act-2', }, { id: 'bot4a', replyToId: 'act-4', }, { id: 'bot4b', replyToId: 'act-4', }, { id: 'bot4c', replyToId: 'act-4', }, { id: 'act-4', }, ], postActivitiesSlots: [1, 2, 10], activitiesToBePosted: [ { id: 'act-2', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-3', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-4', from: { role: 'user' }, channelData: { test: true } }, ], botResponsesForActivity: [ { // type: 'conversationUpdate', id: '1', }, { id: 'act-bot2a', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3a', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3b', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2b', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3c', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { matchIndexes: [2, 3, 5] }, }, { id: 'act-bot2c', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2d', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { matchIndexes: [1, 4, 7, 8] }, }, { id: 'act-bot4a', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act4', from: { role: 'bot' }, channelData: { test: true }, }, ], }, { incomingActivities: [ { // type: 'conversationUpdate', id: '1', }, { id: 'bot2a', replyToId: 'act-2', }, { id: 'bot3a', replyToId: 'act-3', }, { id: 'bot3b', replyToId: 'act-3', }, { id: 'bot2b', replyToId: 'act-2', }, { id: 'bot3c', replyToId: 'act-3', }, { id: 'act-3', }, { id: 'bot2c', replyToId: 'act-2', }, { id: 'bot2d', replyToId: 'act-2', }, { id: 'act-2', }, { id: 'bot4a', replyToId: 'act-4', }, { id: 'bot4b', replyToId: 'act-4', }, { id: 'bot4c', replyToId: 'act-4', }, { id: 'bot2ProgressiveA', replyToId: 'act-2', }, { id: 'bot2ProgressiveB', replyToId: 'act-2', }, { id: 'act-4', }, { id: 'bot5A', replyToId: 'act-5', }, { id: 'act-5', }, ], postActivitiesSlots: [1, 2, 10, 16], activitiesToBePosted: [ { id: 'act-2', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-3', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-4', from: { role: 'user' }, channelData: { test: true } }, { id: 'act-5', from: { role: 'user' }, channelData: { test: true } }, ], botResponsesForActivity: [ { // type: 'conversationUpdate', id: '1', }, { id: 'act-bot2a', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3a', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3b', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2b', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot3c', replyToId: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db8882533Act3', from: { role: 'bot' }, channelData: { matchIndexes: [2, 3, 5] }, }, { id: 'act-bot2c', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2d', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { matchIndexes: [1, 4, 7, 8, 13, 14] }, }, { id: 'act-bot4a', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act4', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot4B', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act4', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot4C', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act4', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'act-bot2PRE', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: 'ProgressiveResponse' }, }, { id: 'act-bot2PRF', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act2', from: { role: 'bot' }, channelData: { test: 'ProgressiveResponse' }, }, { id: 'act-bot5a', replyToId: 'bdc9da50-30d0-4611-967e-182db888253Act5', from: { role: 'bot' }, channelData: { test: true }, }, { id: 'bdc9da50-30d0-4611-967e-182db888253Act5', from: { role: 'bot' }, channelData: { matchIndexes: [15] }, }, ], }, ];
the_stack
import * as React from "react"; import { Tabs, Tab, InputGroup, Classes, TabId } from "@blueprintjs/core"; import { Nullable, Undefinable, IStringDictionary } from "../../../shared/types"; import { Editor } from "../editor"; import { AbstractAssets, IAbstractAssets, IAssetComponentItem } from "../assets/abstract-assets"; import { Alert } from "../gui/alert"; import { Tools } from "../tools/tools"; import { IFile } from "../project/files"; import { Confirm } from "../gui/confirm"; export interface IAssetComponent { /** * The title of the assets component. */ title: string; /** * Defines the identifier of the component. */ identifier: string; /** * Constructor reference of the component. */ ctor: (new (props: IAssetsProps) => AbstractAssets); /** * @hidden */ _id?: string; /** * @hidden */ _ref?: AbstractAssets; } export interface IAssetsProps { /** * The editor reference to be used in the assets component. */ editor: Editor; } export interface IAssetsState { /** * Defines the Id of the active tab. */ activeTabId?: TabId; } export class Assets extends React.Component<IAssetsProps, IAssetsState> { private static _assetComponents: IAssetComponent[] = []; private _isRefreshing: boolean = false; private _needsRefresh: boolean = false; private _parentDiv: Nullable<HTMLDivElement> = null; private _tabs: Nullable<Tabs> = null; private _refHandler = { getParentDiv: (ref: HTMLDivElement) => this._parentDiv = ref, getTabs: (ref: Tabs) => this._tabs = ref, getAssetComponent: (ref: AbstractAssets) => ref && (Assets._assetComponents.find((a) => a._id === ref.props.id)!._ref = ref), }; /** * Adds the given component to the assets stack. * @param component the component to add in the assets stack. */ public static addAssetComponent(component: IAssetComponent): void { component._id = Tools.RandomId(); this._assetComponents.push(component); } /** * Returns all cached data of the asset components. */ public static GetCachedData(): IStringDictionary<IAssetComponentItem[]> { const result = { }; this._assetComponents.forEach((ac) => result[ac.title] = ac._ref?.items.map((i) => ({ id: i.id, key: i.key, base64: i.base64, style: i.style, }))); return result; } /** * Sets the cached data of asset components. Typically used when loading a project. * @param data the previously saved cached data. */ public static SetCachedData(data: IStringDictionary<IAssetComponentItem[]>) { for (const a in data) { const ac = this._assetComponents.find((ac) => ac.title === a); if (!ac || !ac._ref) { continue; } ac._ref.items = data[a]; } } /** * Cleans the assets. Typically removes the unused files. */ public static async Clean(): Promise<void> { for (const a of this._assetComponents) { await a._ref?.clean(); } } private _editor: Editor; /** * Constructor. * @param props the component's props. */ public constructor(props: IAssetsProps) { super(props); this._editor = props.editor; this._editor.assets = this; } /** * Renders the component. */ public render(): React.ReactNode { const tabs = Assets._assetComponents.map((ac) => { const component = <ac.ctor editor={this._editor} id={ac._id!} ref={this._refHandler.getAssetComponent} />; return <Tab id={ac._id} title={ac.title} key={ac._id} panel={component} />; }); tabs.push(<Tabs.Expander />); return ( <div style={{ width: "100%", height: "100%", overflow: "hidden" }}> <InputGroup className={Classes.FILL} leftIcon={"search"} type="search" placeholder="Search..." onChange={(e) => this._handleSearchChanged(e)} /> <div id="EDITOR-ASSETS" ref={this._refHandler.getParentDiv} style={{ width: "100%", height: "100%", overflow: "hidden" }}> <Tabs ref={this._refHandler.getTabs} animate={true} id="assets" key="assets" renderActiveTabPanelOnly={false} vertical={true} large={false} children={tabs} ></Tabs> </div> </div> ); } /** * Selects (activates) the tab of the given assets component. * @param component defines the component to show. */ public selectTab(component?: (new (props: IAssetsProps) => AbstractAssets)): void { const id = Assets._assetComponents.find((ac) => ac.ctor === component)?._id ?? null; if (id !== null && this._tabs && this._tabs.state.selectedTabId !== id) { this._tabs.setState({ selectedTabId: id }); } } /** * Refreshes all the assets. * @param component defines the component to refresh. * @param object defines the object to refresh. */ public refresh<T>(component?: (new (props: IAssetsProps) => AbstractAssets), object?: Undefinable<T>): Promise<void> { return this._refreshAllAssets(component, object); } /** * Forces refreshing all assets. * @param component the component to force refresh. */ public forceRefresh(component?: (new (props: IAssetsProps) => AbstractAssets)): Promise<void> { return this._refreshAllAssets(component, undefined, true); } /** * Clears all the unused assets by removing their files. */ public async clearUnusedAssets(): Promise<void> { if (!await Confirm.Show("Are You Sure?", "This operation will remove all files that are not used (meshes, textures, sounds, etc.). This operation is irreversible until you manually re-add the files yourself. Continue?", "warning-sign")) { return; } const components = Assets._assetComponents.filter((ac) => ac._ref?.clean); let currentStep = 0; const task = this._editor.addTaskFeedback(0, "Cleaning Assets..."); const step = 100 / components.length; for (const ac of components) { try { this._editor.updateTaskFeedback(task, currentStep, `Cleaning Assets "${ac.title}"`); await ac._ref!.clean(); this._editor.updateTaskFeedback(task, currentStep += step); } catch (e) { //Catch siently. } } this._editor.closeTaskFeedback(task, 500); } /** * Resizes the assets components. */ public resize(): void { Assets._assetComponents.forEach((ac) => ac._ref?.resize()); } /** * Called on the user drops files in the assets panel. * @param e the drop event reference. * @param files the dropped files list. */ public async addDroppedFiles(e: DragEvent, files: IFile[]): Promise<void> { if (!this._parentDiv) { return; } if (!Tools.IsElementChildOf(e.target as HTMLElement, this._parentDiv)) { return; } await this.addFilesToAssets(files); } /** * Returns all the assets of the given assets component. * @param componentCtor the component to get its assets already computed. */ public getAssetsOf(componentCtor: (new (props: IAssetsProps) => AbstractAssets)): Undefinable<IAssetComponentItem[]> { const assetComponent = Assets._assetComponents.find((a) => a.ctor === componentCtor); if (assetComponent) { return assetComponent._ref?.items; } return undefined; } /** * Returns all the assets of the component identified by the given Id. * @param id defines the id of the assets component to get its assets. */ public getAssetsOfComponentId(id: string): IAssetComponentItem[] { const component = Assets._assetComponents.find((a) => a.identifier === id); if (!component) { return []; } return this.getAssetsOf(component.ctor)!.map((c) => ({ id: c.id, base64: c.base64, key: c.key })); } /** * Returns the reference of the given assets component. * @param componentCtor the component to get its reference. */ public getComponent<T extends AbstractAssets>(componentCtor: (new (props: IAssetsProps) => T)): Nullable<T> { const assetComponent = Assets._assetComponents.find((a) => a.ctor === componentCtor); return assetComponent?._ref as T ?? null; } /** * Returns the list of all assets components. */ public getAssetsComponents(): IAssetComponent[] { return Assets._assetComponents; } /** * Adds the given files to the assets component. * @param files the files to add in the assets. */ public async addFilesToAssets(files: IFile[]): Promise<void> { if (this._isRefreshing) { return Alert.Show("Please wait.", "Assets are being refreshed. Please wait until the process is done before adding new files."); } const taskFeedBack = this._editor.addTaskFeedback(0, "Loading Files..."); const components = Assets._assetComponents.filter((ac) => ac._ref).map((ac) => ac._ref); const length = components.length; for (let i = 0; i < length; i++) { const component = components[i]; const iRef = component as IAbstractAssets; if (iRef.onDropFiles) { await iRef.onDropFiles(files); } this._editor.updateTaskFeedback(taskFeedBack, length / i * 100); }; this._editor.closeTaskFeedback(taskFeedBack); await this._refreshAllAssets(); this._editor.inspector.refresh(); } /** * Refreshes all assets components. */ private async _refreshAllAssets<T>(componentCtor?: (new (props: IAssetsProps) => AbstractAssets), object?: Undefinable<T>, force?: Undefinable<boolean>): Promise<void> { if (this._isRefreshing) { this._needsRefresh = true; return; } const task = !object ? this._editor.addTaskFeedback(0, "Updating assets", 0) : null; this._isRefreshing = true; const step = 100 / Assets._assetComponents.length; let progress = 0; for (const component of Assets._assetComponents) { if (componentCtor && componentCtor !== component.ctor) { continue; } if (!component._ref) { continue; } const assetStep = step / component._ref.items.length; if (force) { component._ref.items = []; } const observer = component._ref.updateAssetObservable.add(() => { if (!object && assetStep !== Infinity) { this._editor.updateTaskFeedback(task!, progress += assetStep, `Updating assets "${component.title}"`); } }); await (component._ref as IAbstractAssets).refresh(object); component._ref.updateAssetObservable.remove(observer); if (!object && assetStep === Infinity) { this._editor.updateTaskFeedback(task!, progress += step); } } if (!object) { this._editor.closeTaskFeedback(task!, 0); } this._isRefreshing = false; if (this._needsRefresh) { this._needsRefresh = false; return this._refreshAllAssets(); } } /** * Called on the user filters the assets. */ private _handleSearchChanged(e: React.SyntheticEvent): void { const target = e.target as HTMLInputElement; Assets._assetComponents.forEach((ac) => ac._ref?.setFilter(target.value)); } }
the_stack
import { EyeeyeCatcherCardComponent } from './components/eyeeye-catcher-card/eyeeye-catcher-card.component'; import { LoggerInstance } from './../chat21-core/providers/logger/loggerInstance'; import { TiledeskAuthService } from './../chat21-core/providers/tiledesk/tiledesk-auth.service'; import { AppStorageService } from '../chat21-core/providers/abstract/app-storage.service'; import { StarRatingWidgetService } from './components/star-rating-widget/star-rating-widget.service'; import { StarRatingWidgetComponent } from './components/star-rating-widget/star-rating-widget.component'; import { UserModel } from '../../src/chat21-core/models/user'; import { ElementRef, Component, OnInit, OnDestroy, AfterViewInit, NgZone, ViewEncapsulation, HostListener, ViewChild } from '@angular/core'; // import * as moment from 'moment'; import * as moment from 'moment/moment'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; // https://www.davebennett.tech/subscribe-to-variable-change-in-angular-4-service/ import 'rxjs/add/operator/takeWhile'; import { Subscription } from 'rxjs/Subscription'; // services import { Globals } from './utils/globals'; import { MessagingService } from './providers/messaging.service'; import { ContactService } from './providers/contact.service'; import { StorageService } from './providers/storage.service'; import { TranslatorService } from './providers/translator.service'; //import { ConversationsService } from './providers/conversations.service'; import { ChatPresenceHandlerService } from './providers/chat-presence-handler.service'; import { AgentAvailabilityService } from './providers/agent-availability.service'; // firebase import * as firebase from 'firebase/app'; import 'firebase/app'; import { environment } from '../environments/environment'; // utils // setLanguage, // getImageUrlThumb, import { strip_tags, isPopupUrl, popupUrl, detectIfIsMobile, supports_html5_storage, getImageUrlThumb, isJustRecived } from './utils/utils'; import { ConversationModel } from '../chat21-core/models/conversation'; import { AppConfigService } from './providers/app-config.service'; import { GlobalSettingsService } from './providers/global-settings.service'; import { SettingsSaverService } from './providers/settings-saver.service'; import { User } from '../models/User'; import { CustomTranslateService } from '../chat21-core/providers/custom-translate.service'; import { ConversationsHandlerService } from '../chat21-core/providers/abstract/conversations-handler.service'; import { ChatManager } from '../chat21-core/providers/chat-manager'; import { TypingService } from '../chat21-core/providers/abstract/typing.service'; import { MessagingAuthService } from '../chat21-core/providers/abstract/messagingAuth.service'; import { v4 as uuidv4 } from 'uuid'; import { FIREBASESTORAGE_BASE_URL_IMAGE, STORAGE_PREFIX, UID_SUPPORT_GROUP_MESSAGES } from './utils/constants'; import { ConversationHandlerBuilderService } from '../chat21-core/providers/abstract/conversation-handler-builder.service'; import { ConversationHandlerService } from '../chat21-core/providers/abstract/conversation-handler.service'; import { Triggerhandler } from '../chat21-core/utils/triggerHandler'; import { PresenceService } from '../chat21-core/providers/abstract/presence.service'; import { ArchivedConversationsHandlerService } from '../chat21-core/providers/abstract/archivedconversations-handler.service'; import { AUTH_STATE_OFFLINE, AUTH_STATE_ONLINE, TYPE_MSG_FILE, TYPE_MSG_IMAGE, URL_SOUND_LIST_CONVERSATION } from '../chat21-core/utils/constants'; import { ImageRepoService } from '../chat21-core/providers/abstract/image-repo.service'; import { UploadService } from '../chat21-core/providers/abstract/upload.service'; import { LoggerService } from '../chat21-core/providers/abstract/logger.service'; import { isInfo } from '../chat21-core/utils/utils-message'; @Component({ selector: 'chat-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], encapsulation: ViewEncapsulation.None /* it allows to customize 'Powered By' */ // providers: [AgentAvailabilityService, TranslatorService] }) export class AppComponent implements OnInit, AfterViewInit, OnDestroy { obsEndRenderMessage: any; stateLoggedUser; // ========= begin:: parametri di stato widget ======= // isInitialized = false; /** if true show button */ isOpenHome = true; /** check open/close component home ( sempre visibile xchè il primo dello stack ) */ isOpenConversation = false; /** check open/close component conversation if is true */ isOpenAllConversation = false; isOpenSelectionDepartment = false; /** check open/close modal select department */ // isOpenPrechatForm = false; /** check open/close modal prechatform if g.preChatForm is true */ isOpenStartRating = false; /** check open/close modal start rating chat if g.isStartRating is true */ // isWidgetActive: boolean; /** var bindata sullo stato conv aperta/chiusa !!!! da rivedere*/ // isModalLeaveChatActive = false; /** ???? */ isConversationArchived: boolean = false; departments = []; marginBottom: number; conversationSelected: ConversationModel; lastConversation: ConversationModel; // isBeingAuthenticated = false; /** authentication is started */ // ========= end:: parametri di stato widget ======= // // ========= begin:: dichiarazione funzioni ======= // detectIfIsMobile = detectIfIsMobile; /** utils: controllo se mi trovo su mobile */ isPopupUrl = isPopupUrl; popupUrl = popupUrl; strip_tags = strip_tags; // ========= end:: dichiarazione funzioni ======= // // ========= begin:: sottoscrizioni ======= // subscriptions: Subscription[] = []; /** */ // ========= end:: sottoscrizioni ======= // // ========= begin:: variabili del componente ======= // listConversations: Array<ConversationModel>; archivedConversations: Array<ConversationModel>; private audio: any; private setTimeoutSound: any; private setIntervalTime: any; private isTabVisible: boolean = true; private tabTitle: string; // ========= end:: variabili del componente ======== // // ========= begin:: DA SPOSTARE ======= // IMG_PROFILE_SUPPORT = 'https://user-images.githubusercontent.com/32448495/39111365-214552a0-46d5-11e8-9878-e5c804adfe6a.png'; // private aliveSubLoggedUser = true; /** ????? */ // THERE ARE TWO 'CARD CLOSE BUTTONS' THAT ARE DISPLAYED ON THE BASIS OF PLATFORM // isMobile: boolean; // ========= end:: DA SPOSTARE ========= // styleMapConversation: Map<string, string> = new Map(); @ViewChild(EyeeyeCatcherCardComponent) eyeeyeCatcherCardComponent: EyeeyeCatcherCardComponent private logger: LoggerService = LoggerInstance.getInstance(); constructor( private el: ElementRef, private ngZone: NgZone, public g: Globals, public triggerHandler: Triggerhandler, public translatorService: TranslatorService, private translateService: CustomTranslateService, public messagingAuthService: MessagingAuthService, public tiledeskAuthService: TiledeskAuthService, //public messagingService: MessagingService, public contactService: ContactService, //public chatPresenceHandlerService: ChatPresenceHandlerService, public presenceService: PresenceService, private agentAvailabilityService: AgentAvailabilityService, // private storageService: StorageService, private appStorageService: AppStorageService, public appConfigService: AppConfigService, public globalSettingsService: GlobalSettingsService, public settingsSaverService: SettingsSaverService, //public conversationsService: ConversationsService, public conversationsHandlerService: ConversationsHandlerService, public archivedConversationsService: ArchivedConversationsHandlerService, public conversationHandlerBuilderService: ConversationHandlerBuilderService, public chatManager: ChatManager, public typingService: TypingService, public imageRepoService: ImageRepoService, public uploadService: UploadService ) { // if (!appConfigService.getConfig().firebaseConfig || appConfigService.getConfig().firebaseConfig.apiKey === 'CHANGEIT') { // throw new Error('firebase config is not defined. Please create your widget-config.json. See the Chat21-Web_widget Installation Page'); // } // firebase.initializeApp(appConfigService.getConfig().firebaseConfig); // here shows the error this.obsEndRenderMessage = new BehaviorSubject(null); } /** */ ngOnInit() { this.logger.info('[APP-CONF]---------------- ngOnInit: APP.COMPONENT ---------------- ') this.initWidgetParamiters(); } @HostListener('document:visibilitychange') visibilitychange() { // this.logger.printDebug("document TITLE", this.g.windowContext.window.document.title); if (document.hidden) { this.isTabVisible = false // this.g.windowContext.window.document.title = this.tabTitle } else { // TAB IS ACTIVE --> restore title and DO NOT SOUND clearInterval(this.setIntervalTime) this.setIntervalTime = null; this.isTabVisible = true; this.g.windowContext.window.document.title = this.tabTitle; // this.g.windowContext.parent.title = "SHOWING" // this.g.windowContext.title = "SHOWING2" } } private manageTabNotification() { if (!this.isTabVisible) { // TAB IS HIDDEN --> manage title and SOUND // this.g.windowContext.parent.title = "HIDDEN" // this.g.windowContext.title = "HIDDEN2" let badgeNewConverstionNumber = this.conversationsHandlerService.countIsNew() this.logger.debug('[APP-COMP] badgeNewConverstionNumber::', badgeNewConverstionNumber) badgeNewConverstionNumber > 0 ? badgeNewConverstionNumber : badgeNewConverstionNumber= 1 this.g.windowContext.window.document.title = "(" + badgeNewConverstionNumber + ") " + this.tabTitle clearInterval(this.setIntervalTime) const that = this this.setIntervalTime = window.setInterval(function () { if (that.g.windowContext.window.document.title.charAt(0) === '(') { that.g.windowContext.window.document.title = that.tabTitle } else { that.g.windowContext.window.document.title = "(" + badgeNewConverstionNumber + ") " + that.tabTitle; } }, 1000); this.soundMessage() } } /** */ ngAfterViewInit() { // this.triggerOnViewInit(); this.ngZone.run(() => { const that = this; const subChangedConversation = this.conversationsHandlerService.conversationChanged.subscribe((conversation) => { // that.ngZone.run(() => { if (conversation) { this.onImageLoaded(conversation) this.onConversationLoaded(conversation) if(conversation.sender !== this.g.senderId && !isInfo(conversation)){ that.manageTabNotification(); } that.triggerOnConversationUpdated(conversation); } else { this.logger.debug('[APP-COMP] oBSconversationChanged null: errorrr') return; } if (that.g.isOpen === true) { that.g.setParameter('displayEyeCatcherCard', 'none'); this.logger.debug('[APP-COMP] obsChangeConversation ::: ', conversation); if (conversation.attributes && conversation.attributes['subtype'] === 'info') { return; } if (conversation.is_new && !this.isOpenConversation) { // this.soundMessage(); } } else { // if(conversation.is_new && isJustRecived(this.g.startedAt.getTime(), conversation.timestamp)){ //widget closed that.lastConversation = conversation; that.g.isOpenNewMessage = true; that.logger.debug('[APP-COMP] lastconversationnn', that.lastConversation) let badgeNewConverstionNumber = that.conversationsHandlerService.countIsNew() that.g.setParameter('conversationsBadge', badgeNewConverstionNumber); // } } // }); }); this.subscriptions.push(subChangedConversation); const subAddedConversation = this.conversationsHandlerService.conversationAdded.subscribe((conversation) => { // that.ngZone.run(() => { if (that.g.isOpen === true && conversation) { that.g.setParameter('displayEyeCatcherCard', 'none'); that.triggerOnConversationUpdated(conversation); that.logger.debug('[APP-COMP] obsAddedConversation ::: ', conversation); if (conversation && conversation.attributes && conversation.attributes['subtype'] === 'info') { return; } if (conversation.is_new) { that.manageTabNotification() // this.soundMessage(); } if(this.g.isOpen === false){ that.lastConversation = conversation; that.g.isOpenNewMessage = true; } } else { //widget closed let badgeNewConverstionNumber = that.conversationsHandlerService.countIsNew() that.g.setParameter('conversationsBadge', badgeNewConverstionNumber); } // that.manageTabNotification() // }); if(conversation){ this.onImageLoaded(conversation) this.onConversationLoaded(conversation) } }); this.subscriptions.push(subAddedConversation); const subArchivedConversations = this.archivedConversationsService.archivedConversationAdded.subscribe((conversation) => { // that.ngZone.run(() => { if (conversation) { that.triggerOnConversationUpdated(conversation); this.onImageLoaded(conversation) this.onConversationLoaded(conversation) } // }); }); this.subscriptions.push(subArchivedConversations); }); // this.authService.initialize() this.appStorageService.initialize(environment.storage_prefix, this.g.persistence, this.g.projectid) this.tiledeskAuthService.initialize(this.appConfigService.getConfig().apiUrl) this.messagingAuthService.initialize(); this.chatManager.initialize(); this.uploadService.initialize(); } // setStoragePrefix(): string{ // let prefix = STORAGE_PREFIX; // try { // prefix = environment.storage_prefix + '_'; // } catch (e) { // this.g.wdLog(['> Error :' + e]); // } // return prefix + this.g.projectid + '_'; // } // ========= begin:: SUBSCRIPTIONS ============// /** login subscription * GET CURRENT USER * recupero il current user se esiste * https://forum.ionicframework.com/t/firebase-auth-currentuser-shows-me-null-but-it-logged-in/68411/4 */ setAuthSubscription() { this.logger.debug('[APP-COMP] setLoginSubscription : '); const that = this; /** * SUBSCRIBE TO ASYNC LOGIN FUNCTION * RESP * -2: ho fatto il reinit * -1: ho fatto il logout * 0: non sono loggato * 200: sono loggato * 400: errore nel login * 410: errore login (firebase) */ // const obsLoggedUser = this.authService.obsLoggedUser.subscribe((resp) => { // this.g.wdLog(['obsLoggedUser ------------> ', resp]); // // if autostart == false don't autenticate! // // after called signInWithCustomToken need set autostart == true // // this.ngZone.run(() => { // // const tiledeskTokenTEMP = that.appStorageService.getItemWithoutProjectId('tiledeskToken'); // const tiledeskTokenTEMP = that.appStorageService.getItem('tiledeskToken'); // if (tiledeskTokenTEMP && tiledeskTokenTEMP !== undefined) { // that.g.tiledeskToken = tiledeskTokenTEMP; // } // const firebaseTokenTEMP = that.appStorageService.getItemWithoutProjectId('firebaseToken'); // if (firebaseTokenTEMP && firebaseTokenTEMP !== undefined) { // that.g.firebaseToken = firebaseTokenTEMP; // } // const autoStart = this.g.autoStart; // that.g.wdLog(['tiledeskToken ------------> ', that.g.tiledeskToken]); // if (resp === -2) { // that.stateLoggedUser = resp; // /** ho fatto un reinit */ // that.g.wdLog(['sono nel caso reinit -2']); // that.g.setParameter('isLogged', false); // that.hideAllWidget(); // // that.g.setParameter('isShown', false, true); // that.appStorageService.removeItem('tiledeskToken'); // that.g.isLogout = true; // // that.triggerOnAuthStateChanged(resp); // if (autoStart !== false) { // that.setAuthentication(); // that.initAll(); // } // } else if (resp === -1) { // that.stateLoggedUser = resp; // /** ho effettuato il logout: nascondo il widget */ // that.g.wdLog(['sono nel caso logout -1']); // // that.g.wdLog(['obsLoggedUser', obsLoggedUser); // // that.g.wdLog(['this.subscriptions', that.subscriptions); // that.g.setParameter('isLogged', false); // that.hideAllWidget(); // // that.g.setParameter('isShown', false, true); // that.appStorageService.removeItem('tiledeskToken'); // that.g.isLogout = true; // that.triggerOnAuthStateChanged(that.stateLoggedUser); // } else if (resp === 0) { // that.stateLoggedUser = resp; // /** non sono loggato */ // that.g.wdLog(['sono nel caso in cui non sono loggato 0']); // that.g.wdLog(['NO CURRENT USER AUTENTICATE: ']); // that.g.setParameter('isLogged', false); // that.hideAllWidget(); // // that.g.setParameter('isShown', false, true); // that.triggerOnAuthStateChanged(that.stateLoggedUser); // if (autoStart !== false) { // that.setAuthentication(); // } // } else if (resp === 200) { // if (that.stateLoggedUser === 0) { // that.stateLoggedUser = 201; // } else { // that.stateLoggedUser = resp; // } // /** sono loggato */ // const user = that.authService.getCurrentUser(); // that.g.wdLog(['sono nel caso in cui sono loggato']); // that.g.wdLog([' anonymousAuthenticationInNewProject']); // // that.authService.resigninAnonymousAuthentication(); // // confronto id utente tiledesk con id utente di firebase // // senderid deve essere == id di firebase // that.g.setParameter('senderId', user.uid); // that.g.setParameter('isLogged', true); // that.g.setParameter('attributes', that.setAttributesFromStorageService()); // /* faccio scattare il trigger del login solo una volta */ // // if (that.isBeingAuthenticated) { // // that.triggerOnLoggedIn(); // // that.isBeingAuthenticated = false; // // } // that.triggerOnAuthStateChanged(that.stateLoggedUser); // that.startUI(); // that.g.wdLog([' 1 - IMPOSTO STATO CONNESSO UTENTE ', autoStart]); // that.presenceService.setPresence(user.uid); // if (autoStart !== false) { // that.showAllWidget(); // // that.g.setParameter('isShown', true, true); // } // } else if (resp >= 400) { // that.g.wdLog([' ERRORE LOGIN ']); // // that.appStorageService.removeItem('tiledeskToken'); // return; // } else { // that.g.wdLog([' INIT obsLoggedUser']); // return; // } // // that.triggerOnAuthStateChanged(); // // }); // this.initConversationsHandler(environment.tenant, that.g.senderId) // }); // // that.g.wdLog(['onAuthStateChanged ------------> ']); // this.subscriptions.push(obsLoggedUser); // // this.authService.onAuthStateChanged(); const subAuthStateChanged = this.messagingAuthService.BSAuthStateChanged.subscribe(state => { //const tiledeskTokenTEMP = that.appStorageService.getItem('tiledeskToken'); const tiledeskTokenTEMP = this.appStorageService.getItem('tiledeskToken') //const tiledeskTokenTEMP = this.authService2.getTiledeskToken(); if (tiledeskTokenTEMP && tiledeskTokenTEMP !== undefined) { that.g.tiledeskToken = tiledeskTokenTEMP; } const firebaseTokenTEMP = this.messagingAuthService.getToken(); if (firebaseTokenTEMP && firebaseTokenTEMP !== undefined) { that.g.firebaseToken = firebaseTokenTEMP; } const autoStart = this.g.autoStart; that.stateLoggedUser = state; if (state && state === AUTH_STATE_ONLINE) { /** sono loggato */ const user = that.tiledeskAuthService.getCurrentUser() that.logger.info('[APP-COMP] ONLINE - LOGGED SUCCESSFULLY', user); // that.g.wdLog([' anonymousAuthenticationInNewProject']); // that.authService.resigninAnonymousAuthentication(); // confronto id utente tiledesk con id utente di firebase // senderid deve essere == id di firebase // const fullName = user.firstname + ' ' + user.lastname; that.g.setParameter('senderId', user.uid); // this.g.setParameter('userFullname', fullName); // this.g.setAttributeParameter('userFullname', fullName); // this.g.setParameter('userEmail', user.email); // this.g.setAttributeParameter('userEmail', user.email); that.g.setParameter('isLogged', true); that.g.setParameter('attributes', that.setAttributesFromStorageService()); that.startUI(); that.triggerOnAuthStateChanged(that.stateLoggedUser); that.logger.debug('[APP-COMP] 1 - IMPOSTO STATO CONNESSO UTENTE ', autoStart); that.typingService.initialize(this.g.tenant); that.presenceService.initialize(this.g.tenant); that.presenceService.setPresence(user.uid); this.initConversationsHandler(this.g.tenant, that.g.senderId); if (autoStart) { that.showWidget(); } } else if (state && state === AUTH_STATE_OFFLINE) { /** non sono loggato */ that.logger.info('[APP-COMP] OFFLINE - NO CURRENT USER AUTENTICATE: '); that.g.setParameter('isLogged', false); that.hideWidget(); // that.g.setParameter('isShown', false, true); that.triggerOnAuthStateChanged(that.stateLoggedUser); if (autoStart) { that.authenticate(); } } }); this.subscriptions.push(subAuthStateChanged); const subUserLogOut = this.messagingAuthService.BSSignOut.subscribe((state) => { // that.ngZone.run(() => { if (state === true) { //state = true -> user has logged out /** ho effettuato il logout: nascondo il widget */ that.logger.debug('[APP-COMP] sono nel caso logout -1'); // that.g.wdLog(['obsLoggedUser', obsLoggedUser); // that.g.wdLog(['this.subscriptions', that.subscriptions); that.g.tiledeskToken = null; //reset token to restart widget with different tildeskToken that.g.setParameter('isLogged', false); that.g.setParameter('isOpenPrechatForm', false); that.g.setParameter('userFullname', null); //clar parameter to enable preChatForm on logout with other token that.g.setParameter('userEmail', null);//clar parameter to enable preChatForm on logout with other token that.g.setAttributeParameter('userFullname', null);//clar parameter to enable preChatForm on logout with other token that.g.setAttributeParameter('userEmail', null);//clar parameter to enable preChatForm on logout with other token this.g.setAttributeParameter('preChatForm', null) this.g.setParameter('conversationsBadge', 0); this.g.setParameter('recipientId', null, false) that.hideWidget(); // that.g.setParameter('isShown', false, true); that.g.isLogout = true; that.triggerOnAuthStateChanged('offline'); // that.triggerOnLoggedOut() } // }); }); this.subscriptions.push(subUserLogOut); } // ========= end:: SUBSCRIPTIONS ============// private initWidgetParamiters() { // that.g.wdLog(['---------------- initWidgetParamiters ---------------- '); const that = this; // ------------------------------- // /** * SET WIDGET PARAMETERS * when globals is setting (loaded paramiters from server): * 1 - init widget * 2 - setLoginSubscription */ const obsSettingsService = this.globalSettingsService.obsSettingsService.subscribe((resp) => { this.ngZone.run(() => { if (resp) { // /** INIT */ // that.initAll(); this.logger.setLoggerConfig(this.g.isLogEnabled, this.g.logLevel) // (this.g.logLevel === 0 || this.g.logLevel !== 0) && this.g.logLevel !== undefined? this.logger.setLoggerConfig(this.g.isLogEnabled, this.g.logLevel) : this.logger.setLoggerConfig(this.g.isLogEnabled, this.appConfigService.getConfig().logLevel) this.tabTitle = this.g.windowContext.window.document.title this.appStorageService.initialize(environment.storage_prefix, this.g.persistence, this.g.projectid) this.logger.debug('[APP-COMP] controllo se è stato passato un token: ', this.g.jwt); if (this.g.jwt) { // mi loggo con custom token passato nell'url //aggiungo nel local storage e mi autentico this.logger.debug('[APP-COMP] token passato da url. isShown:', this.g.isShown, 'autostart:', this.g.autoStart) this.logger.debug('[APP-COMP] ---------------- mi loggo con custom token passato nell url ---------------- '); // this.g.autoStart = false; this.appStorageService.setItem('tiledeskToken', this.g.jwt) this.g.tiledeskToken = this.g.jwt; // this.signInWithCustomToken(this.g.jwt) // moved to authenticate() in else(tiledeskToken) } this.translatorService.initI18n().then((result) => { this.logger.debug('[APP-COMP] »»»» APP-COMPONENT.TS initI18n result', result); const browserLang = this.translatorService.getLanguage(); moment.locale(browserLang) this.translatorService.translate(this.g); }).then(() => { /** INIT */ that.initAll(); /** AUTH */ that.setAuthSubscription(); }) // /** AUTH */ // that.setLoginSubscription(); } }); }); this.subscriptions.push(obsSettingsService); this.globalSettingsService.initWidgetParamiters(this.g, this.el); // SET AUDIO this.audio = new Audio(); this.audio.src = this.g.baseLocation + URL_SOUND_LIST_CONVERSATION; this.audio.load(); // ------------------------------- // } /** * INITIALIZE: * 1 - set traslations * 2 - set attributes * 4 - triggerLoadParamsEvent * 4 - subscription to runtime changes in globals * add Component to Window * 4 - trigget Load Params Event * 5 - set Is Widget Open Or Active * 6 - get MongDb Departments * 7 - set isInitialized and enable principal button */ private initAll() { // that.g.wdLog(['---------------- initAll ---------------- '); this.addComponentToWindow(this.ngZone); //INIT TRIGGER-HANDLER this.triggerHandler.setElement(this.el) this.triggerHandler.setWindowContext(this.g.windowContext) // /** TRANSLATION LOADER: */ // // this.translatorService.translate(this.g); // this.translatorService.initI18n().then((result) => { // this.g.wdLog(['»»»» APP-COMPONENT.TS initI18n result', result]); // this.translatorService.translate(this.g); // }); /** SET ATTRIBUTES */ const attributes = this.setAttributesFromStorageService(); if (attributes) { this.g.attributes = attributes; } this.setStyleMap() /** * SUBSCRIPTION : * Subscription to runtime changes in globals * and save changes in localstorage */ this.settingsSaverService.initialize(); // ------------------------------- // // ------------------------------- // /** * INIZIALIZE GLOBALS : * create settings object used in trigger * set isMobile * set attributes */ this.g.initialize(); // ------------------------------- // this.removeFirebasewebsocketFromLocalStorage(); // this.triggerLoadParamsEvent(); // this.addComponentToWindow(this.ngZone); // forse dovrebbe stare prima di tutti i triggers this.initLauncherButton(); this.triggerLoadParamsEvent(); // first trigger //this.setAvailableAgentsStatus(); } /** initLauncherButton * posiziono e visualizzo il launcher button */ initLauncherButton() { this.isInitialized = true; this.marginBottom = +this.g.marginY + 70; } initConversationsHandler(tenant: string, senderId: string) { this.logger.debug('[APP-COMP] initialize: ListConversationsComponent'); const keys = ['YOU']; const translationMap = this.translateService.translateLanguage(keys); this.listConversations = []; this.archivedConversations = []; //this.availableAgents = this.g.availableAgents.slice(0, 5); this.logger.debug('[APP-COMP] senderId: ', senderId); this.logger.debug('[APP-COMP] tenant: ', tenant); // 1 - init chatConversationsHandler and archviedConversationsHandler this.conversationsHandlerService.initialize(tenant, senderId, translationMap) this.archivedConversationsService.initialize(tenant, senderId, translationMap) // 2 - get conversations from storage // this.chatConversationsHandler.getConversationsFromStorage(); // 5 - connect conversationHandler and archviedConversationsHandler to firebase event (add, change, remove) this.conversationsHandlerService.subscribeToConversations(() => { }) this.archivedConversationsService.subscribeToConversations(() => { }) this.listConversations = this.conversationsHandlerService.conversations; this.archivedConversations = this.archivedConversationsService.archivedConversations; // 6 - save conversationHandler in chatManager this.chatManager.setConversationsHandler(this.conversationsHandlerService); this.chatManager.setArchivedConversationsHandler(this.archivedConversationsService); this.logger.debug('[APP-COMP] this.listConversations.length', this.listConversations.length); this.logger.debug('[APP-COMP] this.listConversations appcomponent', this.listConversations, this.archivedConversations); } /** initChatSupportMode * se è una chat supportMode: * carico i dipartimenti * carico gli agenti disponibili */ // initChatSupportMode() { // this.g.wdLog([' ---------------- B1: supportMode ---------------- ', this.g.supportMode]); // if (this.g.supportMode) { // // this.getMongDbDepartments(); // // this.setAvailableAgentsStatus(); // } // } /** * */ removeFirebasewebsocketFromLocalStorage() { this.logger.debug('[APP-COMP] ---------------- A1 ---------------- '); // Related to https://github.com/firebase/angularfire/issues/970 if (supports_html5_storage()) { this.appStorageService.removeItem('firebase:previous_websocket_failure'); } } /** setAttributesFromStorageService * */ private setAttributesFromStorageService(): any { let attributes: any = {}; try { attributes = JSON.parse(this.appStorageService.getItem('attributes')); if (attributes.preChatForm) { const preChatForm = attributes.preChatForm; if(preChatForm.userEmail) this.g.userEmail = preChatForm.userEmail; if(preChatForm.userFullname) this.g.userFullname = preChatForm.userFullname } // this.g.wdLog(['> attributes: ', attributes]); } catch (error) { this.logger.debug('[APP-COMP] > Error :' + error); } const CLIENT_BROWSER = navigator.userAgent; const projectid = this.g.projectid; const userEmail = this.g.userEmail; const userFullname = this.g.userFullname; const senderId = this.g.senderId; const widgetVersion = this.g.BUILD_VERSION if (!attributes && attributes === null) { if (this.g.attributes) { attributes = this.g.attributes; } else { attributes = {}; } } // this.g.wdLog(['attributes: ', attributes, this.g.attributes]); // that.g.wdLog(['CLIENT_BROWSER: ', CLIENT_BROWSER); if (CLIENT_BROWSER) { attributes['client'] = CLIENT_BROWSER; } if (location.href) { attributes['sourcePage'] = location.href; } if (projectid) { attributes['projectId'] = projectid; } if (userEmail) { attributes['userEmail'] = userEmail; } if (userFullname) { attributes['userFullname'] = userFullname; } if (senderId) { attributes['requester_id'] = senderId; } if (widgetVersion) { attributes['widgetVer'] = widgetVersion; } try { // attributes['payload'] = this.g.customAttributes.payload; attributes['payload'] = [] if (this.g.customAttributes) { attributes['payload'] = this.g.customAttributes; } } catch (error) { this.logger.debug('[APP-COMP] > Error is handled payload: ', error); } this.appStorageService.setItem('attributes', JSON.stringify(attributes)); return attributes; } /** setAvailableAgentsStatus * mi sottoscrivo al nodo /projects/' + projectId + '/users/availables * per verificare se c'è un agent disponibile */ // private setAvailableAgentsStatus() { // const that = this; // const projectid = this.g.projectid; // this.g.wdLog(['projectId->', projectid]); // this.agentAvailabilityService.getAvailableAgents(projectid).subscribe( (availableAgents) => { // that.g.wdLog(['availableAgents->', availableAgents]); // if (availableAgents.length <= 0) { // that.g.setParameter('areAgentsAvailable', false); // that.g.setParameter('areAgentsAvailableText', that.g.AGENT_NOT_AVAILABLE); // that.g.setParameter('availableAgents', null); // that.appStorageService.removeItem('availableAgents'); // } else { // that.g.setParameter('areAgentsAvailable', true); // that.g.setParameter('areAgentsAvailableText', that.g.AGENT_AVAILABLE); // that.g.setParameter('availableAgents', availableAgents); // availableAgents.forEach(element => { // element.imageurl = getImageUrlThumb(element.id); // }); // // that.addFirstMessage(that.g.LABEL_FIRST_MSG); // } // that.g.setParameter('availableAgentsStatus', true); // }, (error) => { // console.error('setOnlineStatus::setAvailableAgentsStatus', error); // }, () => { // }); // } // ========= begin:: DEPARTEMENTS ============// /** GET DEPARTEMENTS * recupero elenco dipartimenti * - mi sottoscrivo al servizio * - se c'è un solo dipartimento la setto di default * - altrimenti visualizzo la schermata di selezione del dipartimento */ // getMongDbDepartments() { // const that = this; // const projectid = this.g.projectid; // this.g.wdLog(['getMongDbDepartments ::::', projectid]); // this.messagingService.getMongDbDepartments(projectid) // .subscribe(response => { // that.g.wdLog(['response DEP ::::', response]); // that.g.setParameter('departments', response); // that.initDepartments(); // }, // errMsg => { // this.g.wdLog(['http ERROR MESSAGE', errMsg]); // }, // () => { // this.g.wdLog(['API ERROR NESSUNO']); // }); // } /** * INIT DEPARTMENT: * get departments list * set department default * CALL AUTHENTICATION */ // initDepartments() { // const departments = this.g.departments; // this.g.setParameter('departmentSelected', null); // this.g.setParameter('departmentDefault', null); // this.g.wdLog(['SET DEPARTMENT DEFAULT ::::', departments[0]]); // this.setDepartment(departments[0]); // let i = 0; // departments.forEach(department => { // if (department['default'] === true) { // this.g.setParameter('departmentDefault', department); // departments.splice(i, 1); // return; // } // i++; // }); // if (departments.length === 1) { // // UN SOLO DEPARTMENT // this.g.wdLog(['DEPARTMENT FIRST ::::', departments[0]]); // this.setDepartment(departments[0]); // // return false; // } else if (departments.length > 1) { // // CI SONO + DI 2 DIPARTIMENTI // this.g.wdLog(['CI SONO + DI 2 DIPARTIMENTI ::::', departments[0]]); // } else { // // DEPARTMENT DEFAULT NON RESTITUISCE RISULTATI !!!! // this.g.wdLog(['DEPARTMENT DEFAULT NON RESTITUISCE RISULTATI ::::', departments[0]]); // } // } /** * SET DEPARTMENT: * set department selected * save department selected in attributes * save attributes in this.appStorageService */ // setDepartment(department) { // this.g.setParameter('departmentSelected', department); // const attributes = this.g.attributes; // if (department && attributes) { // attributes.departmentId = department._id; // attributes.departmentName = department.name; // this.g.setParameter('attributes', attributes); // this.g.setParameter('departmentSelected', department); // this.g.wdLog(['setAttributes setDepartment: ', JSON.stringify(attributes)]); // this.appStorageService.setItem('attributes', JSON.stringify(attributes)); // } // } // ========= end:: GET DEPARTEMENTS ============// // ========= begin:: AUTHENTICATION ============// /** * SET AUTHENTICATION: * authenticate in chat */ private authenticate() { // that.g.wdLog(['---------------- setAuthentication ----------------'); // this.g.wdLog([' ---------------- setAuthentication ---------------- ']); /** * 0 - controllo se è stato passato email e psw -> UNUSED * SI - mi autentico con email e psw * 1 - controllo se è stato passato userId -> UNUSED * SI - vado avanti senza autenticazione * 2 - controllo se esiste un token -> UNUSED * SI - sono già autenticato * 3 - controllo se esiste currentUser * SI - sono già autenticato * NO - mi autentico * 4 - controllo se esiste currentUser */ const tiledeskToken = this.g.tiledeskToken; const user = this.appStorageService.getItem('currentUser') this.logger.debug('[APP-COMP] tiledesktokennn', tiledeskToken, user) if (tiledeskToken) { // // SONO GIA' AUTENTICATO this.logger.debug('[APP-COMP] ---------------- 13 ---------------- '); this.logger.debug('[APP-COMP] ----------- sono già loggato ------- '); this.signInWithCustomToken(tiledeskToken) // this.tiledeskAuthService.signInWithCustomToken(tiledeskToken).then(user => { // this.messagingAuthService.createCustomToken(tiledeskToken) // }).catch(error => { console.error('SIGNINWITHCUSTOMTOKEN error::' + error) }) // const currentUser = this.authService2.getCurrentUser(); // this.g.senderId = currentUser.uid; // this.g.setParameter('senderId', currentUser.uid); // const fullName = currentUser.firstname + ' ' + currentUser.lastname; // this.g.setParameter('userFullname', fullName); // this.g.setAttributeParameter('userFullname', fullName); // this.g.setParameter('userEmail', currentUser.email); // this.g.setAttributeParameter('userEmail', currentUser.email); // // if(currentUser.firstname || currentUser.lastname){ // // this.g.wdLog([' ---------------- 13 fullname ---------------- ']); // // const fullName = currentUser.firstname + ' ' + currentUser.lastname; // // this.g.setParameter('userFullname', fullName); // // this.g.setAttributeParameter('userFullname', fullName); // // } // // if(currentUser.email){ // // this.g.wdLog([' ---------------- 13 email ---------------- ']); // // this.g.setParameter('userEmail', currentUser.email); // // this.g.setAttributeParameter('userEmail', currentUser.email); // // } // // this.g.setParameter('isLogged', true); // // this.g.setParameter('attributes', this.setAttributesFromStorageService()); // // this.startNwConversation(); // //this.startUI(); // // this.g.wdLog([' 13 - IMPOSTO STATO CONNESSO UTENTE ']); // // this.presenceService.setPresence(currentUser.uid); // } else { // AUTENTICAZIONE ANONIMA this.logger.debug('[APP-COMP] ---------------- 14 ---------------- '); this.logger.debug('[APP-COMP] authenticateFirebaseAnonymously'); this.tiledeskAuthService.signInAnonymously(this.g.projectid).then(tiledeskToken => { this.messagingAuthService.createCustomToken(tiledeskToken) const user = this.tiledeskAuthService.getCurrentUser(); //check if tiledesk_userFullname exist (passed from URL or tiledeskSettings) before update userFullname parameter //if tiledesk_userFullname not exist--> update parameter with tiledesk user returned from auth if ((user.firstname || user.lastname) && !this.g.userFullname) { const fullName = user.firstname + ' ' + user.lastname; this.g.setParameter('userFullname', fullName); this.g.setAttributeParameter('userFullname', fullName); } //check if tiledesk_userEmail exist (passed from URL or tiledeskSettings) before update userEmail parameter //if tiledesk_userEmail not exist--> update parameter with tiledesk user returned from auth if (user.email && !this.g.userEmail) { this.g.setParameter('userEmail', user.email); this.g.setAttributeParameter('userEmail', user.email); } }); // this.authService.anonymousAuthentication(); // this.g.wdLog([' authenticateFirebaseAnonymously']); // this.authService.authenticateFirebaseAnonymously(); } } // ========= end:: AUTHENTICATION ============// // ========= begin:: START UI ============// /** * set opening priority widget */ private startUI() { this.logger.debug('[APP-COMP] ============ startUI ==============='); const departments = this.g.departments; const attributes = this.g.attributes; const preChatForm = this.g.preChatForm; this.isOpenHome = true; this.isOpenConversation = false; this.g.setParameter('isOpenPrechatForm', false); this.isOpenSelectionDepartment = false; this.isOpenAllConversation = false; // const conversationActive: ConversationModel = JSON.parse(this.appStorageService.getItem('activeConversation')); const recipientId : string = this.appStorageService.getItem('recipientId') this.logger.debug('[APP-COMP] ============ idConversation ===============', recipientId, this.g.recipientId); // this.g.recipientId = null; if(this.g.recipientId){ this.logger.debug('[APP-COMP] conv da urll', this.g.recipientId) if (this.g.isOpen) { this.isOpenConversation = true; } this.g.setParameter('recipientId', this.g.recipientId); this.appStorageService.setItem('recipientId', this.g.recipientId) }else if(recipientId){ this.logger.debug('[APP-COMP] conv da storagee', recipientId) if (this.g.isOpen) { this.isOpenConversation = true; } this.g.recipientId = recipientId; this.g.setParameter('recipientId', recipientId); // this.returnSelectedConversation(conversationActive); } else if (this.g.startFromHome) { // this.logger.debug('[APP-COMP] 66666'); this.isOpenConversation = false; this.g.setParameter('isOpenPrechatForm', false); this.isOpenSelectionDepartment = false; } else if (preChatForm && (!attributes || !attributes.userFullname || !attributes.userEmail)) { // this.logger.debug('[APP-COMP] 55555'); this.g.setParameter('isOpenPrechatForm', true); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; if (departments.length > 1 && this.g.departmentID == null) { // this.logger.debug('[APP-COMP] 44444'); this.isOpenSelectionDepartment = true; } } else { // this.logger.debug('[APP-COMP] 33333'); this.g.setParameter('isOpenPrechatForm', false); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; if (departments.length > 1 && !this.g.departmentID == null) { // this.logger.debug('[APP-COMP] 22222'); this.isOpenSelectionDepartment = true; } else { // this.logger.debug('[APP-COMP] 11111', this.g.isOpen, this.g.recipientId); this.isOpenConversation = false; if (!this.g.recipientId && this.g.isOpen) { // this.startNwConversation(); this.openNewConversation(); } } } // visualizzo l'iframe!!! this.triggerOnViewInit(); // this.triggerOnAuthStateChanged(true) // mostro il widget // setTimeout(() => { // const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container'); // if (divWidgetContainer) { // divWidgetContainer.style.display = 'block'; // } // }, 500); } // ========= end:: START UI ============// private openNewConversation() { this.logger.debug('[APP-COMP] openNewConversation in APP COMPONENT'); this.g.newConversationStart = true; // controllo i dipartimenti se sono 1 o 2 seleziono dipartimento e nascondo modale dipartimento // altrimenti mostro modale dipartimenti const preChatForm = this.g.preChatForm; const attributes = this.g.attributes; const departments = this.g.departments; // that.g.wdLog(['departments: ', departments, departments.length); if (preChatForm && (!attributes || !attributes.userFullname || !attributes.userEmail)) { // if (preChatForm && (!attributes.userFullname || !attributes.userEmail)) { this.isOpenConversation = false; this.g.setParameter('isOpenPrechatForm', true); // this.settingsSaverService.setVariable('isOpenPrechatForm', true); this.isOpenSelectionDepartment = false; if (departments && departments.length > 1 && this.g.departmentID == null) { this.isOpenSelectionDepartment = true; } } else { // this.g.isOpenPrechatForm = false; this.g.setParameter('isOpenPrechatForm', false); // this.settingsSaverService.setVariable('isOpenPrechatForm', false); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; if (departments && departments.length > 1 && this.g.departmentID == null) { this.isOpenSelectionDepartment = true; } else { this.isOpenConversation = true; } } this.logger.debug('[APP-COMP] isOpenPrechatForm', this.g.isOpenPrechatForm, ' isOpenSelectionDepartment:', this.isOpenSelectionDepartment); if (this.g.isOpenPrechatForm === false && this.isOpenSelectionDepartment === false) { this.startNewConversation(); } } // ========= begin:: COMPONENT TO WINDOW ============// /** * http://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/ */ private addComponentToWindow(ngZone) { const that = this; const windowContext = this.g.windowContext; if (windowContext && windowContext['tiledesk']) { windowContext['tiledesk']['angularcomponent'] = { component: this, ngZone: ngZone }; /** loggin with token */ windowContext['tiledesk'].signInWithCustomToken = function (response):Promise<UserModel> { return ngZone.run(() => { return windowContext['tiledesk']['angularcomponent'].component.signInWithCustomToken(response); }); }; /** loggin anonymous */ windowContext['tiledesk'].signInAnonymous = function ():Promise<UserModel> { return ngZone.run(() => { return windowContext['tiledesk']['angularcomponent'].component.signInAnonymous(); }); }; // window['tiledesk'].on = function (event_name, handler) { // this.g.wdLog(["addEventListener for "+ event_name); // this.el.nativeElement.addEventListener(event_name, e => handler()); // }; /** show all widget */ windowContext['tiledesk'].show = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.showWidget(); }); }; /** hidden all widget */ windowContext['tiledesk'].hide = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.hideWidget(); }); }; /** close window chat */ windowContext['tiledesk'].close = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.f21_close(); }); }; /** open window chat */ windowContext['tiledesk'].open = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.f21_open(); }); }; /** set state PreChatForm close/open */ windowContext['tiledesk'].setPreChatForm = function (state) { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.setPreChatForm(state); }); }; windowContext['tiledesk'].setPrivacyPolicy = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.setPrivacyPolicy(); }); }; /** send first message */ windowContext['tiledesk'].sendMessage = function ( tenant, senderId, senderFullname, message, type, metadata, recipientId, recipientFullname, additional_attributes, projectid, channel_type ) { const _globals = windowContext['tiledesk'].angularcomponent.component.g; if (!tenant) { tenant = _globals.tenant; } if (!senderId) { senderId = _globals.senderId; } if (!senderFullname) { senderFullname = _globals.senderFullname; } if (!message) { message = 'hello'; } if (!type) { type = 'text'; } if (!metadata) { metadata = ''; } if (!recipientId) { recipientId = _globals.recipientId; } if (!recipientFullname) { recipientFullname = _globals.recipientFullname; } if (!projectid) { projectid = _globals.projectId; } if (!channel_type || channel_type === undefined) { channel_type = 'group'; } // set default attributes const g_attributes = _globals.attributes; const attributes = <any>{}; if (g_attributes) { for (const [key, value] of Object.entries(g_attributes)) { attributes[key] = value; } } if (additional_attributes) { for (const [key, value] of Object.entries(additional_attributes)) { attributes[key] = value; } } ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component .sendMessage( tenant, senderId, senderFullname, message, type, metadata, recipientId, recipientFullname, attributes, projectid, channel_type ); }); }; /** send custom message from html page */ windowContext['tiledesk'].sendSupportMessage = function ( message, recipientId, recipientFullname, type, metadata, additional_attributes ) { const _globals = windowContext['tiledesk'].angularcomponent.component.g; if (!message) { message = 'hello'; } if (!recipientId) { recipientId = _globals.recipientId; } if (!type) { type = 'text'; } if (!metadata) { metadata = {}; } const g_attributes = _globals.attributes; const attributes = <any>{}; if (g_attributes) { for (const [key, value] of Object.entries(g_attributes)) { attributes[key] = value; } } if (additional_attributes) { for (const [key, value] of Object.entries(additional_attributes)) { attributes[key] = value; } } ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component .sendMessage( _globals.tenant, _globals.senderId, _globals.userFullname, message, type, metadata, recipientId, recipientFullname, attributes, _globals.projectid, _globals.channelType ); }); }; /** set state PreChatForm close/open */ // windowContext['tiledesk'].endMessageRender = function () { // ngZone.run(() => { // windowContext['tiledesk']['angularcomponent'].component.endMessageRender(); // }); // }; /** set state reinit */ windowContext['tiledesk'].reInit = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.reInit(); }); }; /** set state reStart */ windowContext['tiledesk'].restart = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.restart(); }); }; /** set logout */ windowContext['tiledesk'].logout = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.logout(); }); }; /** show callout */ windowContext['tiledesk'].showCallout = function () { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.showCallout(); }); }; /** setPrechatForm */ windowContext['tiledesk'].setPreChatFormJson = function (form: Array<any>) { ngZone.run(() => { windowContext['tiledesk']['angularcomponent'].component.setPreChatFormJson(form); }); }; /** getPreChatForm */ windowContext['tiledesk'].getPreChatFormJson = function () { let preChatForm = {} ngZone.run(() => { preChatForm = windowContext['tiledesk']['angularcomponent'].component.getPreChatFormJson(); }); return preChatForm }; } } initConversationHandler(conversationWith: string): ConversationHandlerService { const tenant = this.g.tenant; const keys = [ // 'LABEL_AVAILABLE', // 'LABEL_NOT_AVAILABLE', // 'LABEL_TODAY', // 'LABEL_TOMORROW', // 'LABEL_TO', // 'LABEL_LAST_ACCESS', // 'ARRAY_DAYS', // 'LABEL_ACTIVE_NOW', // 'LABEL_WRITING', 'INFO_SUPPORT_USER_ADDED_SUBJECT', 'INFO_SUPPORT_USER_ADDED_YOU_VERB', 'INFO_SUPPORT_USER_ADDED_COMPLEMENT', 'INFO_SUPPORT_USER_ADDED_VERB', 'INFO_SUPPORT_CHAT_REOPENED', 'INFO_SUPPORT_CHAT_CLOSED', 'LABEL_TODAY', 'LABEL_TOMORROW', 'LABEL_TO', 'ARRAY_DAYS', ]; const translationMap = this.translateService.translateLanguage(keys); //TODO-GAB: da sistemare loggedUser in firebase-conversation-handler.service const loggedUser = { uid: this.g.senderId } const conversationWithFullname = this.g.recipientFullname; let handler: ConversationHandlerService = this.chatManager.getConversationHandlerByConversationId(conversationWith); this.logger.debug('[APP-COMP] DETTAGLIO CONV - handler **************', handler, conversationWith); if (!handler) { const conversationHandlerService = this.conversationHandlerBuilderService.build(); conversationHandlerService.initialize( conversationWith, conversationWithFullname, loggedUser, tenant, translationMap ); this.logger.debug('[APP-COMP] DETTAGLIO CONV - NEW handler **************', conversationHandlerService); this.chatManager.addConversationHandler(conversationHandlerService); handler = conversationHandlerService } return handler } /** */ // private endMessageRender() { // this.obsEndRenderMessage.next(); // } /** */ private sendMessage( tenant, senderId, senderFullname, msg, type, metadata, conversationWith, recipientFullname, attributes, projectid, channel_type) { this.logger.debug('[APP-COMP] sendMessage from window.tiledesk *********** ',tenant,senderId,senderFullname, msg,type,metadata,conversationWith,recipientFullname, attributes,projectid,channel_type); const messageSent = this.initConversationHandler(conversationWith).sendMessage( msg, type, metadata, conversationWith, recipientFullname, senderId, senderFullname, channel_type, attributes) // const messageSent = this.messagingService // .sendMessageFull( // tenant, // senderId, // senderFullname, // msg, // type, // metadata, // conversationWith, // recipientFullname, // attributes, // projectid, // channel_type); // sendMessage(senderFullname, msg, type, metadata, conversationWith, recipientFullname, attributes, projectid, channel_type) } /** * Custom Auth called from the test-custom-auth.html * note: https://tiledesk.atlassian.net/browse/TD-42?atlOrigin=eyJpIjoiMGMyZmVmNDgzNTFjNGZkZjhiMmM2Y2U1MmYyNzkwODMiLCJwIjoiaiJ9 */ private signInWithCustomToken(token: string):Promise<UserModel> { const that = this; return this.tiledeskAuthService.signInWithCustomToken(token).then((user: UserModel) => { this.messagingAuthService.createCustomToken(token) this.logger.debug('[APP-COMP] signInWithCustomToken user::', user) //check if tiledesk_userFullname exist (passed from URL or tiledeskSettings) before update userFullname parameter //if tiledesk_userFullname not exist--> update parameter with tiledesk user returned from auth if ((user.firstname || user.lastname) && !this.g.userFullname) { const fullName = user.firstname + ' ' + user.lastname; this.g.setParameter('userFullname', fullName); this.g.setAttributeParameter('userFullname', fullName); } //check if tiledesk_userEmail exist (passed from URL or tiledeskSettings) before update userEmail parameter //if tiledesk_userEmail not exist--> update parameter with tiledesk user returned from auth if (user.email && !this.g.userEmail) { this.g.setParameter('userEmail', user.email); this.g.setAttributeParameter('userEmail', user.email); } return Promise.resolve(user) // this.showWidget() }).catch(error => { this.logger.debug('[APP-COMP] signInWithCustomToken ERR ',error); that.signOut(); return Promise.reject(error) }); } // UNUSED // private signInWithCustomTokenUniLe(token) { // this.g.wdLog(['signInWithCustomToken token ', token]); // const that = this; // const projectid = this.g.projectid; // this.authService.createFirebaseToken(token, projectid).subscribe(response => { // that.authService.decode(token, projectid).subscribe(resDec => { // const attributes = that.g.attributes; // const firebaseToken = response; // this.g.wdLog(['firebaseToken', firebaseToken]); // this.g.wdLog(['resDec', resDec.decoded]); // that.g.setParameter('signInWithCustomToken', true); // that.g.setParameter('userEmail', resDec.decoded.email); // that.g.setParameter('userFullname', resDec.decoded.name); // that.g.setParameter('userToken', firebaseToken); // that.g.setParameter('signInWithCustomToken', true); // that.g.setParameter('signInWithCustomToken', true); // that.g.setParameter('signInWithCustomToken', true); // that.authService.authenticateFirebaseCustomToken(firebaseToken); // that.g.setAttributeParameter('userEmail', resDec.decoded.email); // that.g.setAttributeParameter('userFullname', resDec.decoded.name); // // attributes.userEmail = resDec.decoded.email; // // attributes.userFullname = resDec.decoded.name; // // that.g.setParameter('attributes', attributes); // // attributes = that.setAttributesFromStorageService(); ?????????????+ // // ???????????????????? // }, error => { // console.error('Error decoding token: ', error); // // that.g.wdLog(['call signout'); // that.signOut(); // }); // // , () => { // // that.g.wdLog(['!!! NEW REQUESTS HISTORY - DOWNLOAD REQUESTS AS CSV * COMPLETE *'); // // }); // }, error => { // console.error('Error creating firebase token: ', error); // // that.g.wdLog(['call signout'); // that.signOut(); // }); // // , () => { // // that.g.wdLog(['!!! NEW REQUESTS HISTORY - DOWNLOAD REQUESTS AS CSV * COMPLETE *'); // // }); // } /** */ private signInAnonymous(): Promise<UserModel> { this.logger.debug('[APP-COMP] signInAnonymous'); return this.tiledeskAuthService.signInAnonymously(this.g.projectid).then((tiledeskToken) => { this.messagingAuthService.createCustomToken(tiledeskToken) const user = this.tiledeskAuthService.getCurrentUser(); if (user.firstname || user.lastname) { const fullName = user.firstname + ' ' + user.lastname; this.g.setParameter('userFullname', fullName); this.g.setAttributeParameter('userFullname', fullName); } if (user.email) { this.g.setParameter('userEmail', user.email); this.g.setAttributeParameter('userEmail', user.email); } return Promise.resolve(user) }).catch((error)=> { this.logger.error('[APP-COMP] signInAnonymous ERR', error); return Promise.reject(error); }); // this.authService.anonymousAuthentication(); // this.authService.authenticateFirebaseAnonymously(); } /** */ private setPreChatForm(state: boolean) { if (state != null) { this.g.setParameter('preChatForm', state); if (state === true) { this.appStorageService.setItem('preChatForm', state); } else { this.appStorageService.removeItem('preChatForm'); } } } private setPreChatFormJson(form: Array<any>) { if(form){ this.g.setParameter('preChatFormJson', form); } this.logger.debug('[APP-COMP] setPreChatFormJson from external', form) } private getPreChatFormJson() { let preChatForm = {} if(this.g.preChatFormJson){ preChatForm = this.g.preChatFormJson } this.logger.debug('[APP-COMP] getPreChatFormJson from external', preChatForm) return preChatForm } private setPrivacyPolicy() { this.g.privacyApproved = true; this.g.setAttributeParameter('privacyApproved', this.g.privacyApproved); this.appStorageService.setItem('attributes', JSON.stringify(this.g.attributes)); this.g.setParameter('preChatForm', false); this.appStorageService.removeItem('preChatForm'); } /** show widget */ private showWidget() { this.logger.debug('[APP-COMP] show widget--> autoStart:', this.g.autoStart, 'startHidden', this.g.startHidden, 'isShown', this.g.isShown) const startHidden = this.g.startHidden; const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container'); if (divWidgetContainer && startHidden === false) { divWidgetContainer.style.display = 'block'; this.g.setParameter('isShown', true, true); } else { this.g.startHidden = false; this.g.setParameter('isShown', false, true); } } /** hide widget */ private hideWidget() { const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container'); if (divWidgetContainer) { divWidgetContainer.style.display = 'none'; } this.g.setParameter('isShown', false, true); } /** open popup conversation */ private f21_open() { const senderId = this.g.senderId; this.logger.debug('[APP-COMP] f21_open senderId: ', senderId); if (senderId) { // chiudo callout this.g.setParameter('displayEyeCatcherCard', 'none'); // this.g.isOpen = true; // !this.isOpen; this.g.setIsOpen(true); this.isInitialized = true; this.appStorageService.setItem('isOpen', 'true'); // this.g.displayEyeCatcherCard = 'none'; this.triggerOnOpenEvent(); // https://stackoverflow.com/questions/35232731/angular2-scroll-to-bottom-chat-style } } /** close popup conversation */ private f21_close() { this.g.setIsOpen(false); this.g.isOpenNewMessage = false; this.appStorageService.setItem('isOpen', 'false'); this.triggerOnCloseEvent(); } /**open widget in conversation when is closed */ private _f21_open() { // const senderId = this.g.senderId; // this.logger.debug('[APP-COMP] f21_open senderId' , senderId) // this.logger.printDebug() // this.g.wdLog(['f21_open senderId: ', senderId]); // if (senderId) { // chiudo callout this.g.setParameter('displayEyeCatcherCard', 'none'); // this.g.isOpen = true; // !this.isOpen; this.g.setIsOpen(true); // this.isInitialized = true; this.appStorageService.setItem('isOpen', 'true'); // this.g.displayEyeCatcherCard = 'none'; this.triggerOnOpenEvent(); // https://stackoverflow.com/questions/35232731/angular2-scroll-to-bottom-chat-style // } } /** * 1 - cleare local storage * 2 - remove div iframe widget * 3 - reinit widget */ private reInit() { // if (!firebase.auth().currentUser) { if (!this.tiledeskAuthService.getCurrentUser()) { this.logger.debug('[APP-COMP] reInit ma NON SONO LOGGATO!'); } else { this.tiledeskAuthService.logOut(); this.messagingAuthService.logout(); // this.authService.signOut(-2); /** ho fatto un reinit */ this.logger.debug('[APP-COMP] sono nel caso reinit -2'); this.g.setParameter('isLogged', false); this.hideWidget(); // that.g.setParameter('isShown', false, true); this.appStorageService.removeItem('tiledeskToken'); this.g.isLogout = true; if (this.g.autoStart !== false) { this.authenticate(); this.initAll(); } this.appStorageService.clear(); } const divWidgetRoot = this.g.windowContext.document.getElementsByTagName('chat-root')[0]; const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container'); divWidgetContainer.remove(); divWidgetRoot.remove(); this.g.windowContext.initWidget(); } /** * 1 - cleare local storage * 2 - remove div iframe widget * 3 - reinit widget */ private restart() { // if (!firebase.auth().currentUser) { this.hideWidget(); // that.triggerOnAuthStateChanged(resp); if (this.g.autoStart !== false) { this.authenticate(); this.initAll(); } const divWidgetRoot = this.g.windowContext.document.getElementsByTagName('chat-root')[0]; const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container'); divWidgetContainer.remove(); divWidgetRoot.remove(); this.g.windowContext.initWidget(); } // private reInit_old() { // // this.isOpenHome = false; // this.appStorageService.clear(); // let currentUser = this.authService.getCurrentUser(); // this.authService.reloadCurrentUser().then(() => { // // location.reload(); // currentUser = this.authService.getCurrentUser(); // // alert(currentUser.uid); // this.initAll(); // /** sono loggato */ // this.g.wdLog(['reInit_old USER AUTENTICATE: ', currentUser.uid]); // this.g.setParameter('senderId', currentUser.uid); // this.g.setParameter('isLogged', true); // this.g.setParameter('attributes', this.setAttributesFromStorageService()); // this.g.wdLog([' this.g.senderId', currentUser.uid]); // // this.startNwConversation(); // this.startUI(); // this.g.wdLog([' 1 - IMPOSTO STATO CONNESSO UTENTE ']); // this.presenceService.setPresence(currentUser.uid); // }); // } private logout() { this.signOut(); } /** show callout */ private showCallout() { if (this.g.isOpen === false) { // this.g.setParameter('calloutTimer', 1) this.eyeeyeCatcherCardComponent.openEyeCatcher(); this.g.setParameter('displayEyeCatcherCard', 'block'); this.triggerOnOpenEyeCatcherEvent(); } } // ========= end:: COMPONENT TO WINDOW ============// // ========= begin:: DESTROY ALL SUBSCRIPTIONS ============// /** elimino tutte le sottoscrizioni */ ngOnDestroy() { this.logger.debug('[APP-COMP] this.subscriptions', this.subscriptions); const windowContext = this.g.windowContext; if (windowContext && windowContext['tiledesk']) { windowContext['tiledesk']['angularcomponent'] = null; // this.g.setParameter('windowContext', windowContext); this.g.windowContext = windowContext; } this.unsubscribe(); } /** */ unsubscribe() { this.subscriptions.forEach(function (subscription) { subscription.unsubscribe(); }); this.subscriptions = []; this.logger.debug('[APP-COMP] this.subscriptions', this.subscriptions); } // ========= end:: DESTROY ALL SUBSCRIPTIONS ============// // ========= begin:: FUNCTIONS ============// /** * 1 - clear local storage * 2 - remove user in firebase */ signOut() { this.logger.debug('[APP-COMP] SIGNOUT'); if (this.g.isLogged === true) { this.g.wdLog(['prima ero loggato allora mi sloggo!']); this.g.setIsOpen(false); // this.g.setAttributeParameter('userFullname', null); // this.g.setAttributeParameter('userEmail', null); // this.g.setParameter('userFullname', null); // this.g.setParameter('userEmail', null); this.appStorageService.clear(); this.presenceService.removePresence(); this.tiledeskAuthService.logOut(); this.messagingAuthService.logout(); // this.authService.signOut(-2); } } /** * get status window chat from this.appStorageService * set status window chat open/close */ // SET IN LOCAL SETTINGS setVariableFromStorage IMPOSTA IL VALORE DI TUTTE LE VARIABILI // setIsWidgetOpenOrActive() { // if (this.appStorageService.getItem('isOpen') === 'true') { // // this.g.isOpen = true; // this.g.setIsOpen(true); // } else if (this.appStorageService.getItem('isOpen') === 'false') { // // this.g.isOpen = false; // this.g.setIsOpen(false); // } // // this.isWidgetActive = (this.appStorageService.getItem('isWidgetActive')) ? true : false; // } /** * attivo sound se è un msg nuovo */ private soundMessage() { this.logger.debug('[APP-COMP] ****** soundMessage *****', this.audio); const that = this; const soundEnabled = this.g.soundEnabled; if (soundEnabled) { this.audio.pause(); this.audio.currentTime = 0; clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(() => { that.audio.play().then(() => { this.logger.debug('[APP-COMP] ****** soundMessage played *****'); }).catch((error: any) => { this.logger.debug('[APP-COMP] ***soundMessage error*', error); }); }, 1000); } } // soundMessage() { // const soundEnabled = this.g.soundEnabled; // const baseLocation = this.g.baseLocation; // if (soundEnabled) { // const that = this; // this.audio = new Audio(); // this.audio.src = baseLocation + '/assets/sounds/justsaying.mp3'; // this.audio.load(); // // this.logger.debug('[APP-COMP] conversation play'); // clearTimeout(this.setTimeoutSound); // this.setTimeoutSound = setTimeout(function () { // that.audio.play(); // that.g.wdLog(['****** soundMessage 1 *****', that.audio.src]); // }, 1000); // } // } /** * genero un nuovo conversationWith * al login o all'apertura di una nuova conversazione */ generateNewUidConversation() { this.logger.debug('[APP-COMP] generateUidConversation **************: senderId= ', this.g.senderId); return UID_SUPPORT_GROUP_MESSAGES + this.g.projectid + '-' + uuidv4().replace(/-/g, ''); // return UID_SUPPORT_GROUP_MESSAGES + uuidv4(); >>>>>OLD } /** * premendo sul pulsante 'APRI UNA NW CONVERSAZIONE' * attivo una nuova conversazione */ startNewConversation() { this.logger.debug('[APP-COMP] AppComponent::startNewConversation'); const newConvId = this.generateNewUidConversation(); this.g.setParameter('recipientId', newConvId); this.appStorageService.setItem('recipientId', newConvId) this.logger.debug('[APP-COMP] recipientId: ', this.g.recipientId); this.isConversationArchived = false; this.triggerNewConversationEvent(newConvId); } // ========= end:: FUNCTIONS ============// // ========= begin:: CALLBACK FUNCTIONS ============// /** * MOBILE VERSION: * onClick button close widget */ onCloseWidget() { this.isOpenConversation = false; let badgeNewConverstionNumber = this.conversationsHandlerService.countIsNew() this.g.setParameter('conversationsBadge', badgeNewConverstionNumber); this.logger.debug('[APP-COMP] widgetclosed:::', this.g.conversationsBadge, this.conversationsHandlerService.countIsNew()) // this.g.isOpen = false; // this.g.setIsOpen(false); this.f21_close(); } onSoundChange(soundEnabled) { this.g.setParameter('soundEnabled', soundEnabled); } /** * LAUNCHER BUTTON: * onClick button open/close widget */ onOpenCloseWidget($event) { this.g.setParameter('displayEyeCatcherCard', 'none'); // const conversationActive: ConversationModel = JSON.parse(this.appStorageService.getItem('activeConversation')); const recipientId : string = this.appStorageService.getItem('recipientId') this.logger.debug('[APP-COMP] openCloseWidget', recipientId, this.g.isOpen, this.g.startFromHome); if (this.g.isOpen === true) { if (!recipientId) { if (this.g.startFromHome) { this.isOpenHome = true; this.isOpenConversation = false; } else { this.isOpenHome = false; this.isOpenConversation = true; this.onNewConversation() // this.startNwConversation(); } } else { //conversation is present in localstorage this.isOpenHome = false; this.isOpenConversation = true; } // if (!conversationActive && !this.g.startFromHome) { // this.isOpenHome = false; // this.isOpenConversation = true; // this.startNwConversation(); // } else if (conversationActive) { // this.isOpenHome = false; // this.isOpenConversation = true; // } // this.g.startFromHome = true; this.triggerOnOpenEvent(); } else { this.triggerOnCloseEvent(); } } /** * MODAL SELECTION DEPARTMENT: * selected department */ onDepartmentSelected($event) { if ($event) { this.logger.debug('[APP-COMP] onSelectDepartment: ', $event); this.g.setParameter('departmentSelected', $event); // this.settingsSaverService.setVariable('departmentSelected', $event); // this.isOpenHome = true; // this.isOpenSelectionDepartment = false; // if (this.g.isOpenPrechatForm === false && this.isOpenSelectionDepartment === false) { // this.isOpenConversation = true; // this.startNewConversation(); // } if (this.g.isOpenPrechatForm === false) { this.isOpenConversation = true; this.isOpenHome = false this.isOpenSelectionDepartment = false; this.startNewConversation(); } } } /** * MODAL SELECTION DEPARTMENT: * close modal */ onCloseModalDepartment() { this.logger.debug('[APP-COMP] returnCloseModalDepartment'); this.isOpenHome = true; this.isOpenSelectionDepartment = false; this.isOpenConversation = false; } /** * MODAL PRECHATFORM: * completed prechatform */ onPrechatFormComplete() { this.logger.debug('[APP-COMP] onPrechatFormComplete'); this.isOpenHome = true; this.g.setParameter('isOpenPrechatForm', false); if (this.g.isOpenPrechatForm === false && this.isOpenSelectionDepartment === false) { this.isOpenConversation = true; this.startNewConversation(); } // this.settingsSaverService.setVariable('isOpenPrechatForm', false); } /** * MODAL PRECHATFORM: * close modal */ onCloseModalPrechatForm() { this.logger.debug('[APP-COMP] onCloseModalPrechatForm'); this.isOpenHome = true; this.isOpenSelectionDepartment = false; this.isOpenConversation = false; this.g.setParameter('isOpenPrechatForm', false); this.g.newConversationStart = false; // this.settingsSaverService.setVariable('isOpenPrechatForm', false); } /** * MODAL HOME: * @param $event * return conversation selected from chat-last-message output event */ public onSelectedConversation($event: ConversationModel) { if ($event) { if (this.g.isOpen === false) { //this.f21_open(); this._f21_open() } // this.conversationSelected = $event; this.g.setParameter('recipientId', $event.recipient); this.appStorageService.setItem('recipientId', $event.recipient) this.isOpenConversation = true; $event.archived? this.isConversationArchived = $event.archived : this.isConversationArchived = false; this.logger.debug('[APP-COMP] onSelectConversation in APP COMPONENT: ', $event); // this.messagingService.initialize(this.senderId, this.tenant, this.channelType); // this.messages = this.messagingService.messages; } } /** * MODAL HOME: * controllo se prechat form è attivo e lo carico - stack 3 * controllo se departments è attivo e lo carico - stack 2 * carico conversazione - stack 1 * home - stack 0 */ onNewConversation() { this.logger.debug('[APP-COMP] returnNewConversation in APP COMPONENT'); this.g.newConversationStart = true; // controllo i dipartimenti se sono 1 o 2 seleziono dipartimento e nascondo modale dipartimento // altrimenti mostro modale dipartimenti const preChatForm = this.g.preChatForm; const attributes = this.g.attributes; const departments = this.g.departments; // that.g.wdLog(['departments: ', departments, departments.length); this.logger.debug('[APP-COMP] attributesssss', this.g.attributes, this.g.preChatForm) if (preChatForm && (!attributes || !attributes.userFullname || !attributes.userEmail)) { // if (preChatForm && (!attributes.userFullname || !attributes.userEmail)) { this.isOpenConversation = false; this.g.setParameter('isOpenPrechatForm', true); // this.settingsSaverService.setVariable('isOpenPrechatForm', true); this.isOpenSelectionDepartment = false; if (departments && departments.length > 1 && this.g.departmentID == null) { this.isOpenSelectionDepartment = true; } } else { // this.g.isOpenPrechatForm = false; this.g.setParameter('isOpenPrechatForm', false); // this.settingsSaverService.setVariable('isOpenPrechatForm', false); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; if (departments && departments.length > 1 && this.g.departmentID == null) { this.isOpenSelectionDepartment = true; } else { this.isOpenConversation = true; } } this.logger.debug('[APP-COMP] isOpenPrechatForm', this.g.isOpenPrechatForm, ' isOpenSelectionDepartment:', this.isOpenSelectionDepartment); if (this.g.isOpenPrechatForm === false && this.isOpenSelectionDepartment === false) { this.startNewConversation(); } } /** * MODAL HOME: * open all-conversation */ onOpenAllConversation() { this.isOpenHome = true; this.isOpenConversation = false; this.isOpenAllConversation = true; } /** * MODAL EYE CATCHER CARD: * open chat */ onOpenChatEyeEyeCatcherCard() { this.f21_open(); } /** * MODAL EYE CATCHER CARD: * close button */ onCloseEyeCatcherCard($e) { if ($e === true) { this.triggerOnOpenEyeCatcherEvent(); } else { this.triggerOnClosedEyeCatcherEvent(); } } /** * MODAL CONVERSATION: * close conversation */ onBackConversation() { this.logger.debug('[APP-COMP] onCloseConversation') this.appStorageService.removeItem('recipientId'); this.g.setParameter('recipientId', null, false) // this.g.setParameter('activeConversation', null, false); this.isOpenHome = true; this.isOpenAllConversation = false; this.isOpenConversation = false; setTimeout(() => { // this.isOpenAllConversation = isOpenAllConversationTEMP; // this.isOpenHome = isOpenHomeTEMP; // this.isOpenConversation = false; }, 200); // this.startNwConversation(); } /** * MODAL CONVERSATION: * conversation archived * @param conversationId * @description - if singleConversation is TRUE show new conv/load last active conversatio * - if singleConversation is FALSE -> back to Home component */ onConversationClosed(conversationId: string){ if(this.g.singleConversation){ //manage single conversation }else{ this.onBackConversation } } /** * CONVERSATION DETAIL FOOTER: * floating button -> start new Conversation(); */ onNewConversationButtonClicked(){ this.logger.debug('[APP-COMP] onNewConversationButtonClicked'); this.isOpenConversation = false; this.g.singleConversation? this.isOpenHome = false: null; const departments = this.g.departments; if (departments && departments.length > 1 && this.g.departmentID == null) { this.isOpenSelectionDepartment = true; } else { this.isOpenConversation = true; } this.logger.debug('[APP-COMP] isOpenPrechatForm', this.g.isOpenPrechatForm, ' isOpenSelectionDepartment:', this.isOpenSelectionDepartment); if (this.g.isOpenPrechatForm === false && this.isOpenSelectionDepartment === false) { this.startNewConversation(); } // setTimeout(() => { // this.onNewConversation(); // }, 0); } /** * MODAL ALL CONVERSATION: * close all-conversation */ onCloseAllConversation() { this.logger.debug('[APP-COMP] Close all conversation'); const isOpenHomeTEMP = this.isOpenHome; const isOpenConversationTEMP = this.isOpenConversation; this.isOpenHome = false; this.isOpenConversation = false; setTimeout(() => { this.isOpenHome = isOpenHomeTEMP; this.isOpenConversation = isOpenConversationTEMP; this.isOpenAllConversation = false; }, 200); } onImageLoaded(conversation: ConversationModel) { this.logger.debug('[APP-COMP] onLoadImage convvvv:::', conversation) conversation.image = this.imageRepoService.getImagePhotoUrl(conversation.sender) } onConversationLoaded(conversation: ConversationModel) { this.logger.debug('[APP-COMP] onConversationLoaded convvvv:::', conversation) const keys = ['YOU', 'SENT_AN_IMAGE', 'SENT_AN_ATTACHMENT']; const translationMap = this.translateService.translateLanguage(keys); if(conversation.sender === this.g.senderId){ if (conversation.type === TYPE_MSG_IMAGE) { this.logger.log('[CONVS-LIST-PAGE] HAS SENT AN IMAGE'); const SENT_AN_IMAGE = conversation['last_message_text'] = translationMap.get('SENT_AN_IMAGE') conversation.last_message_text = SENT_AN_IMAGE; // } else if (conversation.type !== "image" && conversation.type !== "text") { } else if (conversation.type === TYPE_MSG_FILE) { this.logger.log('[CONVS-LIST-PAGE] HAS SENT FILE') const SENT_AN_ATTACHMENT = conversation['last_message_text'] = translationMap.get('SENT_AN_ATTACHMENT') conversation.last_message_text = SENT_AN_ATTACHMENT; } } else { if (conversation.type === TYPE_MSG_IMAGE) { this.logger.log('[CONVS-LIST-PAGE] HAS SENT AN IMAGE'); const SENT_AN_IMAGE = conversation['last_message_text'] = translationMap.get('SENT_AN_IMAGE') conversation.last_message_text = SENT_AN_IMAGE; // } else if (conversation.type !== "image" && conversation.type !== "text") { } else if (conversation.type === TYPE_MSG_FILE) { this.logger.log('[CONVS-LIST-PAGE] HAS SENT FILE') const SENT_AN_ATTACHMENT = conversation['last_message_text'] = translationMap.get('SENT_AN_ATTACHMENT') conversation.last_message_text = SENT_AN_ATTACHMENT; } } } /** * MODAL MENU SETTINGS: * logout */ onSignOut() { this.signOut(); } /** * MODAL RATING WIDGET: * close modal page */ onCloseModalRateChat() { this.isOpenHome = true; this.g.setParameter('isOpenPrechatForm', false); // this.settingsSaverService.setVariable('isOpenPrechatForm', false); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; this.g.setParameter('isOpenStartRating', false); // this.settingsSaverService.setVariable('isOpenStartRating', false); // this.startNwConversation(); this.onBackConversation(); } /** * MODAL RATING WIDGET: * complete rate chat */ onRateChatComplete() { this.isOpenHome = true; this.g.setParameter('isOpenPrechatForm', false); // this.settingsSaverService.setVariable('isOpenPrechatForm', false); this.isOpenConversation = false; this.isOpenSelectionDepartment = false; this.g.setParameter('isOpenStartRating', false); // this.settingsSaverService.setVariable('isOpenStartRating', false); // this.startNwConversation(); this.onBackConversation(); } // ========= end:: CALLBACK FUNCTIONS ============// // ========= START:: TRIGGER FUNCTIONS ============// private triggerOnViewInit() { const detailOBJ = { global: this.g, default_settings: this.g.default_settings, appConfigs: this.appConfigService.getConfig() } this.triggerHandler.triggerOnViewInit(detailOBJ) } private triggerOnOpenEvent() { const detailOBJ = { default_settings: this.g.default_settings } this.triggerHandler.triggerOnOpenEvent(detailOBJ) } private triggerOnCloseEvent() { const detailOBJ = { default_settings: this.g.default_settings } this.triggerHandler.triggerOnCloseEvent(detailOBJ) } private triggerOnOpenEyeCatcherEvent() { const detailOBJ = { default_settings: this.g.default_settings } this.triggerHandler.triggerOnOpenEyeCatcherEvent(detailOBJ) } private triggerOnClosedEyeCatcherEvent() { this.triggerHandler.triggerOnClosedEyeCatcherEvent() } /** */ // private triggerOnLoggedIn() { // const detailOBJ = { user_id: this.g.senderId, global: this.g, default_settings: this.g.default_settings, appConfigs: this.appConfigService.getConfig() } // this.triggerHandler.triggerOnOpenEvent(detailOBJ) // } /** */ // private triggerOnLoggedOut() { // const detailOBJ = { isLogged: this.g.isLogged, global: this.g, default_settings: this.g.default_settings, appConfigs: this.appConfigService.getConfig() } // this.triggerHandler.triggerOnLoggedOut(detailOBJ) // } /** */ private triggerOnAuthStateChanged(event) { const detailOBJ = { event: event, isLogged: this.g.isLogged, user_id: this.g.senderId, global: this.g, default_settings: this.g.default_settings, appConfigs: this.appConfigService.getConfig() } this.triggerHandler.triggerOnAuthStateChanged(detailOBJ) } private triggerNewConversationEvent(newConvId) { const detailOBJ = { global: this.g, default_settings: this.g.default_settings, newConvId: newConvId, appConfigs: this.appConfigService.getConfig() } this.triggerHandler.triggerNewConversationEvent(detailOBJ) } /** */ private triggerLoadParamsEvent() { const detailOBJ = { default_settings: this.g.default_settings } this.triggerHandler.triggerLoadParamsEvent(detailOBJ) } /** */ private triggerOnConversationUpdated(conversation: ConversationModel) { this.triggerHandler.triggerOnConversationUpdated(conversation) } /** */ private triggerOnCloseMessagePreview() { this.triggerHandler.triggerOnCloseMessagePreview(); } // ========= END:: TRIGGER FUNCTIONS ============// // setSound() { // if (this.appStorageService.getItem('soundEnabled')) { // this.g.setParameter('soundEnabled', this.appStorageService.getItem('soundEnabled')); // // this.settingsSaverService.setVariable('soundEnabled', this.appStorageService.getItem('soundEnabled')); // } // } // /** // * carico url immagine profilo passando id utente // */ // setProfileImage(contact) { // const that = this; // // that.g.wdLog([' ********* displayImage::: '); // this.contactService.profileImage(contact.id, 'thumb') // .then((url) => { // contact.imageurl = url; // }) // .catch((error) => { // // that.g.wdLog(["displayImage error::: ",error); // }); // } private setStyleMap() { this.styleMapConversation.set('backgroundColor', this.g.colorBck) this.styleMapConversation.set('foregroundColor', this.g.themeForegroundColor) this.styleMapConversation.set('themeColor', this.g.themeColor) this.styleMapConversation.set('colorGradient', this.g.colorGradient180) this.styleMapConversation.set('bubbleSentBackground', this.g.bubbleSentBackground) this.styleMapConversation.set('bubbleSentTextColor', this.g.bubbleSentTextColor) this.styleMapConversation.set('bubbleReceivedBackground', this.g.bubbleReceivedBackground) this.styleMapConversation.set('bubbleReceivedTextColor', this.g.bubbleReceivedTextColor) this.styleMapConversation.set('fontSize', this.g.fontSize) this.styleMapConversation.set('fontFamily', this.g.fontFamily) this.styleMapConversation.set('buttonFontSize', this.g.buttonFontSize) this.styleMapConversation.set('buttonBackgroundColor', this.g.buttonBackgroundColor) this.styleMapConversation.set('buttonTextColor', this.g.buttonTextColor) this.styleMapConversation.set('buttonHoverBackgroundColor',this.g.buttonHoverBackgroundColor) this.styleMapConversation.set('buttonHoverTextColor', this.g.buttonHoverTextColor) this.el.nativeElement.style.setProperty('--button-in-msg-background-color', this.g.bubbleSentBackground) this.el.nativeElement.style.setProperty('--button-in-msg-font-size', this.g.buttonFontSize) } }
the_stack
'use strict'; import * as angular from 'angular'; import { ChoicefieldType } from './choicefieldTypeEnum'; describe('choicefieldDirective <uif-choicefield />', () => { beforeEach(() => { angular.mock.module('officeuifabric.components.choicefield'); }); it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue">' + '<uif-choicefield-group-title><label class="ms-Label is-required">Pick a value</label></uif-choicefield-group-title>' + '<uif-choicefield-option uif-type="radio" value="value1">Text 1</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value2">Text 2</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value3">Text 3</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value4">Text 4</uif-choicefield-option>' + '</uif-choicefield>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); let container: JQuery = choicefield.find('div.ms-ChoiceFieldGroup'); expect(container.length).toBe(1, 'Container should be present'); let items: JQuery = choicefield.find('input'); expect(items.length).toBe(4, 'There should be 4 inputs'); let titleLabel: JQuery = choicefield.find('.ms-ChoiceFieldGroup-title label.ms-Label'); expect(titleLabel.html()).toBe('Pick a value'); let input1: JQuery = jQuery(items[0]); expect(input1.attr('type')).toBe('radio', 'Type should be radio'); let span1: JQuery = container.find('label[for="' + input1.attr('id') + '"] span'); expect(span1.html()).toBe('Text 1', 'Label should be Text 1'); })); it('should be able to set options', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.selectedValue = 'value2'; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue">' + '<uif-choicefield-option uif-type="radio" value="value1">Text 1</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value2">Text 2</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value3">Text 3</uif-choicefield-option>' + '<uif-choicefield-option uif-type="radio" value="value4">Text 4</uif-choicefield-option>' + '</uif-choicefield-group>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); let input2: JQuery = choicefield.find('div.ms-ChoiceFieldGroup div.ms-ChoiceField:nth-child(2) input'); input2 = jQuery(choicefield.find('input')[1]); expect(input2.prop('checked')).toBe(true, 'Input 2 (value2) should be checked'); let input3: JQuery = jQuery(choicefield.find('input')[2]); expect(input3.attr('checked')).not.toBe('checked', 'Other inputs should not be checked.'); })); it('should be able to select an option in a group', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option1'; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue">' + '<uif-choicefield-option uif-type="radio" ng-repeat="option in options" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); let option1: JQuery = jQuery(choicefield.find('input')[0]); let option3: JQuery = jQuery(choicefield.find('input')[2]); expect(option1.prop('checked')).toBe(true, 'Option 1 - Checked should be true before click'); option3.click(); expect(option3.prop('checked')).toBe(true, 'Option 3 - Checked should be true after click'); expect(option3.prop('checked')).toBe(true, 'Option 1 - Checked should be false after click'); expect($scope.selectedValue).toBe('Option3', 'Scope value should be option3 now as it is a radio button group'); })); it('should be able to use ng-change', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option1'; $scope.ngChange = () => { $scope.ngChangeCalled = true; }; $scope.ngChangeCalled = false; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue" ng-change="ngChange()">' + '<uif-choicefield-option uif-type="radio" ng-repeat="option in options" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); expect($scope.ngChangeCalled).toBe(false, 'ngChangeCalled should be false initially'); let option3: JQuery = jQuery(choicefield.find('input')[2]); option3.click(); expect($scope.ngChangeCalled).toBe(true, 'ngChangeCalled should be true after option click'); })); it('should be able to select a single option', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.selectedValue = ''; let choicefield: JQuery = $compile('<uif-choicefield-option uif-type="checkbox" value="Option1"' + 'ng-model="selectedValue" ng-true-value="\'TRUEVALUE\'" ng-false-value="\'FALSEVALUE\'">Option 1</uif-choicefield>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); let input: JQuery = choicefield.find('input'); input.click(); expect(input.prop('checked')).toBe(true, 'Input should be checked after click'); expect($scope.selectedValue).toBe('TRUEVALUE', 'ng model should be "TRUEVALUE"'); })); it('should be validating attributes', inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => { let $scope: any = $rootScope.$new(); $scope.selectedValue = 'Option1'; expect($log.error.logs.length).toBe(0); $compile('<uif-choicefield-option uif-type="invalid" value="Option1"' + 'ng-model="selectedValue">Option 1</uif-choicefield>')($scope); $scope.$digest(); expect($log.error.logs[0]).toContain('Error [ngOfficeUiFabric] officeuifabric.components.choicefield - ' + '"invalid" is not a valid value for uifType. ' + 'Supported options are listed here: ' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/choicefield/choicefieldTypeEnum.ts'); })); it('should be able to disable an select', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option1'; $scope.disabled = true; $scope.disabledChild = false; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue" ng-disabled="disabled" uif-type="radio">' + '<uif-choicefield-option ng-repeat="option in options" ng-disabled="disabledChild" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); $scope.$digest(); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); let option1: JQuery = jQuery(choicefield.find('input')[0]); let option3: JQuery = jQuery(choicefield.find('input')[2]); option3.click(); expect(option3.prop('checked')).toBe(false, 'Option 3 - Checked should be false after click as parent element is disabled'); expect(option1.prop('checked')).toBe(true, 'Option 1 - Checked should still be true after click as parent element is disabled'); $scope.disabled = false; $scope.disabledChild = true; $scope.$digest(); option3.click(); expect(option3.prop('checked')).toBe(false, 'Option 3 - Checked should be false after click as child element is disabled'); expect(option1.prop('checked')).toBe(true, 'Option 1 - Checked should still be true after click as child element is disabled'); $scope.disabled = false; $scope.disabledChild = false; $scope.$digest(); option3.click(); expect(option3.prop('checked')).toBe(true, 'Option 3 - Checked should be true after click as element is not disabled'); expect(option1.prop('checked')).toBe(false, 'Option 1 - Checked should be false after click as element is not disabled'); })); it( 'should set $dirty & $touched on ng-model when value changed', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option1'; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue" ng-disabled="disabled" uif-type="radio">' + '<uif-choicefield-option ng-repeat="option in options" ng-disabled="disabledChild" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); $scope.$digest(); let option3: JQuery = jQuery(choicefield.find('input')[2]); option3.click(); let ngModel: angular.INgModelController = angular.element(choicefield).controller('ngModel'); expect($scope.selectedValue).toBe('Option3'); expect(ngModel.$dirty).toBeTruthy(); expect(ngModel.$touched).toBeTruthy(); })); it( 'should set $touched when value not changed & option clicked', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option3'; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue" ng-disabled="disabled" uif-type="radio">' + '<uif-choicefield-option ng-repeat="option in options" ng-disabled="disabledChild" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); $scope.$digest(); let option3: JQuery = jQuery(choicefield.find('input')[2]); option3.click(); let ngModel: angular.INgModelController = angular.element(choicefield).controller('ngModel'); expect($scope.selectedValue).toBe('Option3'); expect(ngModel.$dirty).toBeFalsy(); expect(ngModel.$touched).toBeTruthy(); })); it( 'should be validating presence of ng-model when value is changed', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; let choicefield: JQuery = $compile('<uif-choicefield-group ng-disabled="disabled" uif-type="radio">' + '<uif-choicefield-option ng-repeat="option in options" ng-disabled="disabledChild" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); $scope.$digest(); let option3: JQuery = jQuery(choicefield.find('input')[2]); option3.click(); let ngModel: angular.INgModelController = angular.element(choicefield).controller('ngModel'); expect(ngModel).toBeUndefined(); })); it('should not set $dirty & $touched on ng-model intially', inject(($compile: Function, $rootScope: angular.IRootScopeService) => { let $scope: any = $rootScope.$new(); $scope.options = [ { text: 'Option 1', value: 'Option1' }, { text: 'Option 2', value: 'Option2' }, { text: 'Option 3', value: 'Option3' }, { text: 'Option 4', value: 'Option4' } ]; $scope.selectedValue = 'Option1'; let choicefield: JQuery = $compile('<uif-choicefield-group ng-model="selectedValue" ng-disabled="disabled" uif-type="radio">' + '<uif-choicefield-option ng-repeat="option in options" ng-disabled="disabledChild" ' + 'value="{{option.value}}">{{option.text}}</uif-choicefield-option></uif-choicefield-group>')($scope); choicefield = jQuery(choicefield[0]); choicefield.appendTo(document.body); $scope.$digest(); let ngModel: angular.INgModelController = angular.element(choicefield).controller('ngModel'); expect(ngModel.$dirty).toBeFalsy(); expect(ngModel.$touched).toBeFalsy(); })); /** * Verify the field responds to changes in the uif-type attribute. */ it( 'should allow to interpolate uif-type value', inject(( $compile: angular.ICompileService, $rootScope: angular.IRootScopeService) => { let inputElement: JQuery = null; let scope: any = $rootScope.$new(); let html: string = `<uif-choicefield-group> <uif-choicefield-option uif-type="{{type}}" value="value1">value1</uif-choicefield-option> </uif-choicefield-group>`; let element: JQuery = angular.element(html); let choiceType: string = ''; $compile(element)(scope); // >>> test 1 // set to one icon in scope choiceType = ChoicefieldType[ChoicefieldType.radio]; scope.type = choiceType; // run digest cycle scope.$digest(); element = jQuery(element[0]); // test correct icon is used inputElement = element.find('input'); expect(inputElement.attr('type')).toBe(choiceType); // >>> test 2 // change icon type in scope choiceType = ChoicefieldType[ChoicefieldType.checkbox]; scope.type = choiceType; // run digest cycle scope.$digest(); element = jQuery(element[0]); // test that new type is there inputElement = element.find('input'); expect(inputElement.attr('type')).toBe(choiceType); }) ); });
the_stack
import { conststring, constsymbol, numstr } from "@esfx/type-model"; import * as structType from "./structType"; import * as primitives from "./primitives"; /** * Represents a primitive struct type. */ export interface StructPrimitiveType<K extends string = string, T extends number | bigint = number | bigint> { /** * Coerce the provided value into a value of this type. */ (value: number | bigint): T; /** * The name of the primitive type. */ readonly name: K; /** * The size, in bytes, of the primitive type. */ readonly SIZE: number; } /** * A primitive type representing a 1-byte signed integer. * * Aliases: `i8`, `sbyte` */ export const int8 = primitives.int8; /** * A primitive type representing a 2-byte signed integer. * * Aliases: `i16`, `short` */ export const int16 = primitives.int16; /** * A primitive type representing a 4-byte signed integer. * * Aliases: `i32`, `int` */ export const int32 = primitives.int32; /** * A primitive type representing a 1-byte unsigned integer. * * Aliases: `u8`, `byte` */ export const uint8 = primitives.uint8; /** * A primitive type representing a 2-byte unsigned integer. * * Aliases: `u16`, `ushort` */ export const uint16 = primitives.uint16; /** * A primitive type representing a 4-byte unsigned integer. * * Aliases: `u32`, `uint` */ export const uint32 = primitives.uint32; /** * A primitive type representing an 8-byte signed integer. * * Aliases: `i64`, `long` */ export const bigint64 = primitives.bigint64; /** * A primitive type representing an 8-byte unsigned integer. * * Aliases: `u64`, `ulong` */ export const biguint64 = primitives.biguint64; /** * A primitive type representing a 4-byte floating point number. * * Aliases: `f32`, `float` */ export const float32 = primitives.float32; /** * A primitive type representing an 8-byte floating point number. * * Aliases: `f64`, `double` */ export const float64 = primitives.float64; // wasm type names export { int8 as i8, int16 as i16, int32 as i32, uint8 as u8, uint16 as u16, uint32 as u32, bigint64 as i64, biguint64 as u64, float32 as f32, float64 as f64, }; // other type aliases export { int8 as sbyte, int16 as short, int32 as int, uint8 as byte, uint16 as ushort, uint32 as uint, bigint64 as long, biguint64 as ulong, float32 as float, float64 as double, }; export type StructFieldType = | typeof int8 | typeof int16 | typeof int32 | typeof uint8 | typeof uint16 | typeof uint32 | typeof bigint64 | typeof biguint64 | typeof float32 | typeof float64 | StructType; export interface StructFieldDefinition { readonly name: conststring | constsymbol; readonly type: StructFieldType; } type __Concat<L extends readonly any[], R extends readonly any[]> = L extends readonly [] ? R : L extends readonly [any] ? ((l0: L[0], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any] ? ((l0: L[0], l1: L[1], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], l5: L[5], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], l5: L[5], l6: L[6], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], l5: L[5], l6: L[6], l7: L[7], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], l5: L[5], l6: L[6], l7: L[7], l8: L[8], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : L extends readonly [any, any, any, any, any, any, any, any, any, any] ? ((l0: L[0], l1: L[1], l2: L[2], l3: L[3], l4: L[4], l5: L[5], l6: L[6], l7: L[7], l8: L[8], l9: L[9], ...r: R) => void) extends ((...c: infer C) => void) ? Readonly<C> : never : readonly never[]; /** * Gets the runtime type from a `StructFieldType`. */ export type StructFieldRuntimeType<TField extends StructFieldDefinition> = TField["type"] extends StructPrimitiveType ? ReturnType<TField["type"]> : TField["type"] extends StructType ? InstanceType<TField["type"]> : never; /** * Represents an instance of a struct type. */ export type Struct<TDef extends readonly StructFieldDefinition[] = any> = { /** * Gets the underlying `ArrayBuffer` or `SharedArrayBuffer` of a struct. */ readonly buffer: ArrayBufferLike; /** * Gets the byte offset into this struct's `buffer` at which the struct starts. */ readonly byteOffset: number; /** * Gets the size of this struct in bytes. */ readonly byteLength: number; /** * Gets the value of a named field of this struct. */ get<K extends TDef[number]["name"]>(key: K): StructFieldRuntimeType<Extract<TDef[number], { readonly name: K }>>; /** * Sets the value of a named field of this struct. */ set<K extends TDef[number]["name"]>(key: K, value: StructFieldRuntimeType<Extract<TDef[number], { readonly name: K }>>): void; /** * Gets the value of an ordinal field of this struct. */ getIndex<I extends keyof TDef & numstr<keyof TDef>>(index: I): StructFieldRuntimeType<Extract<TDef[I], StructFieldDefinition>>; /** * Sets the value of an ordinal field of this struct. */ setIndex<I extends keyof TDef & numstr<keyof TDef>>(index: I, value: StructFieldRuntimeType<Extract<TDef[I], StructFieldDefinition>>): boolean; /** * Writes the value of this struct to an array buffer. */ writeTo(buffer: ArrayBufferLike, byteOffset?: number): void; } & { /** * Gets or sets a named field of the struct. */ [K in TDef[number]["name"]]: StructFieldRuntimeType<Extract<TDef[number], { readonly name: K }>>; } & { /** * Gets or sets an ordinal field of the struct. */ [I in keyof TDef & numstr<keyof TDef> & number]: StructFieldRuntimeType<Extract<TDef[I], StructFieldDefinition>>; }; /** * Describes a type that can be used to initialize a property or element of a struct. */ export type StructInitFieldType<TField extends StructFieldDefinition> = TField["type"] extends StructPrimitiveType ? ReturnType<TField["type"]> : TField["type"] extends StructType<infer TDef> ? InstanceType<TField["type"]> | StructInitProperties<TDef> | StructInitElements<TDef> : never; /** * Describes the properties that can be used to initialize a struct. */ export type StructInitProperties<TDef extends readonly StructFieldDefinition[]> = { [P in TDef[number]["name"]]: StructInitFieldType<Extract<TDef[number], { readonly name: P }>>; }; /** * Describes the ordered elements that can be used to initialize a struct. */ export type StructInitElements<TDef extends readonly StructFieldDefinition[]> = { [I in keyof TDef]: StructInitFieldType<Extract<TDef[I], StructFieldDefinition>>; }; // declare const kFields: unique symbol; /** * Represents the constructor for a struct. */ export interface StructType<TDef extends readonly StructFieldDefinition[] = any> { new (): Struct<TDef>; new (shared: boolean): Struct<TDef>; new (buffer: ArrayBufferLike, byteOffset?: number): Struct<TDef>; new (object: Partial<StructInitProperties<TDef>>, shared?: boolean): Struct<TDef>; new (elements: Partial<StructInitElements<TDef>>, shared?: boolean): Struct<TDef>; readonly SIZE: number; // readonly [kFields]: TDef; } /** * Represents the constructor for a struct type. */ export interface StructTypeConstructor { /** * Creates a new Struct type from the provided field definition. * @param fields An array of `StructFieldDefinition` entries describing the ordered fields in the struct. * @param name A name for the struct. */ <TDef extends readonly StructFieldDefinition[]>(fields: TDef | [], name?: string): StructType<TDef>; /** * Creates a new Struct type from the provided field definition. * @param baseType A base struct from which this struct is derived. Fields in this struct will come after fields in the base struct. * @param fields An array of `StructFieldDefinition` entries describing the ordered fields in the struct. * @param name A name for the struct. */ <TDef extends readonly StructFieldDefinition[], TBaseDef extends readonly StructFieldDefinition[]>(baseType: StructType<TBaseDef>, fields: TDef | [], name?: string): StructType<__Concat<TBaseDef, TDef>>; /** * Creates a new Struct type from the provided field definition. * @param fields An array of `StructFieldDefinition` entries describing the ordered fields in the struct. * @param name A name for the struct. */ new <TDef extends readonly StructFieldDefinition[]>(fields: TDef | [], name?: string): StructType<TDef>; /** * Creates a new Struct type from the provided field definition. * @param baseType A base struct from which this struct is derived. Fields in this struct will come after fields in the base struct. * @param fields An array of `StructFieldDefinition` entries describing the ordered fields in the struct. * @param name A name for the struct. */ new <TDef extends readonly StructFieldDefinition[], TBaseDef extends readonly StructFieldDefinition[]>(baseType: StructType<TBaseDef>, fields: TDef | [], name?: string): StructType<__Concat<TBaseDef, TDef>>; prototype: StructType<[]>; } /** * Creates a new `Struct` type from a provided field definition. */ export const StructType = structType.StructType as StructTypeConstructor;
the_stack
import { clearSelection } from 'mobiledoc-kit/utils/selection-utils' import { forEach, contains } from 'mobiledoc-kit/utils/array-utils' import KEY_CODES from 'mobiledoc-kit/utils/keycodes' import { DIRECTION, MODIFIERS } from 'mobiledoc-kit/utils/key' import { isTextNode } from 'mobiledoc-kit/utils/dom-utils' import { merge } from 'mobiledoc-kit/utils/merge' import { Editor } from 'mobiledoc-kit' import { MIME_TEXT_PLAIN, MIME_TEXT_HTML } from 'mobiledoc-kit/utils/parse-utils' import { dasherize } from 'mobiledoc-kit/utils/string-utils' import { DOMEvent, DOMEventType } from 'mobiledoc-kit/editor/event-manager' import { Dict } from 'mobiledoc-kit/utils/types' function assertEditor(editor: any): asserts editor is Editor { if (!(editor instanceof Editor)) { throw new Error('Must pass editor as first argument') } } // walks DOWN the dom from node to childNodes, returning the element // for which `conditionFn(element)` is true function walkDOMUntil(topNode: Node, conditionFn: (node: Node) => boolean = () => false) { if (!topNode) { throw new Error('Cannot call walkDOMUntil without a node') } let stack = [topNode] let currentElement: Node while (stack.length) { currentElement = stack.pop()! if (conditionFn(currentElement)) { return currentElement } forEach(currentElement.childNodes, el => stack.push(el)) } } function findTextNode(parentElement: Node, text: string) { return walkDOMUntil(parentElement, node => { return isTextNode(node) && node.textContent!.indexOf(text) !== -1 }) } function selectRange(startNode: Node, startOffset: number, endNode: Node, endOffset: number) { clearSelection() const range = document.createRange() range.setStart(startNode, startOffset) range.setEnd(endNode, endOffset) const selection = window.getSelection()! selection.addRange(range) } function selectText( editor: Editor, startText: string, startContainingElement = editor.element, endText = startText, endContainingElement = startContainingElement ) { assertEditor(editor) let startTextNode = findTextNode(startContainingElement, startText) let endTextNode = findTextNode(endContainingElement, endText) if (!startTextNode) { throw new Error(`Could not find a starting textNode containing "${startText}"`) } if (!endTextNode) { throw new Error(`Could not find an ending textNode containing "${endText}"`) } const startOffset = startTextNode.textContent!.indexOf(startText), endOffset = endTextNode.textContent!.indexOf(endText) + endText.length selectRange(startTextNode, startOffset, endTextNode, endOffset) editor._readRangeFromDOM() } function moveCursorWithoutNotifyingEditorTo( _editor: Editor, node: Node, offset = 0, endNode = node, endOffset = offset ) { selectRange(node, offset, endNode, endOffset) } function moveCursorTo(editor: Editor, node: Node, offset = 0, endNode = node, endOffset = offset) { assertEditor(editor) if (!node) { throw new Error('Cannot moveCursorTo node without node') } moveCursorWithoutNotifyingEditorTo(editor, node, offset, endNode, endOffset) editor._readRangeFromDOM() } function triggerEvent(node: Node, eventType: string) { if (!node) { throw new Error(`Attempted to trigger event "${eventType}" on undefined node`) } let clickEvent = document.createEvent('MouseEvents') clickEvent.initEvent(eventType, true, true) return node.dispatchEvent(clickEvent) } function _triggerEditorEvent(editor: Editor, event: DOMEvent) { editor.triggerEvent(editor.element, event.type as DOMEventType, event) } function _buildDOM(tagName: string, attributes: Dict<string> = {}, children = []) { const el = document.createElement(tagName) Object.keys(attributes).forEach(k => el.setAttribute(k, attributes[k])) children.forEach(child => el.appendChild(child)) return el } _buildDOM.text = (string: string) => { return document.createTextNode(string) } /** * Usage: * build(t => * t('div', attributes={}, children=[ * t('b', {}, [ * t.text('I am a bold text node') * ]) * ]) * ); */ function build(tree: (t: typeof _buildDOM) => HTMLElement) { return tree(_buildDOM) } function getSelectedText() { const selection = window.getSelection()! if (selection.rangeCount === 0) { return null } else if (selection.rangeCount > 1) { // FIXME? throw new Error('Unable to get selected text for multiple ranges') } else { return selection.toString() } } // returns the node and the offset that the cursor is on function getCursorPosition() { const selection = window.getSelection()! return { node: selection.anchorNode, offset: selection.anchorOffset, } } function createMockEvent(eventName: string, element: HTMLElement, options = {}) { let event = { type: eventName, preventDefault() {}, target: element, } merge(event, options) return (event as unknown) as DOMEvent } // options is merged into the mocked `KeyboardEvent` data. // Useful for simulating modifier keys, eg: // triggerDelete(editor, DIRECTION.BACKWARD, {altKey: true}) function triggerDelete(editor: Editor, direction = DIRECTION.BACKWARD, options = {}) { assertEditor(editor) const keyCode = direction === DIRECTION.BACKWARD ? KEY_CODES.BACKSPACE : KEY_CODES.DELETE let eventOptions = merge({ keyCode }, options) let event = createMockEvent('keydown', editor.element, eventOptions) _triggerEditorEvent(editor, event) } function triggerForwardDelete(editor: Editor, options: Dict<unknown>) { return triggerDelete(editor, DIRECTION.FORWARD, options) } function triggerEnter(editor: Editor) { assertEditor(editor) let event = createMockEvent('keydown', editor.element, { keyCode: KEY_CODES.ENTER }) _triggerEditorEvent(editor, event) } // keyCodes and charCodes are similar but not the same. function keyCodeForChar(letter: string) { let keyCode switch (letter) { case '.': keyCode = KEY_CODES['.'] break case '\n': keyCode = KEY_CODES.ENTER break default: keyCode = letter.charCodeAt(0) } return keyCode } function insertText(editor: Editor, string: string) { if (!string && editor) { throw new Error('Must pass `editor` to `insertText`') } string.split('').forEach(letter => { let stop = false let keyCode = keyCodeForChar(letter) let charCode = letter.charCodeAt(0) let preventDefault = () => (stop = true) let keydown = createMockEvent('keydown', editor.element, { keyCode, charCode, preventDefault, }) let keypress = createMockEvent('keypress', editor.element, { keyCode, charCode, }) let keyup = createMockEvent('keyup', editor.element, { keyCode, charCode, preventDefault, }) _triggerEditorEvent(editor, keydown) if (stop) { return } _triggerEditorEvent(editor, keypress) if (stop) { return } _triggerEditorEvent(editor, keyup) }) } function triggerKeyEvent(editor: Editor, type: string, options: Dict<unknown>) { let event = createMockEvent(type, editor.element, options) _triggerEditorEvent(editor, event) } // triggers a key sequence like cmd-B on the editor, to test out // registered keyCommands function triggerKeyCommand(editor: Editor, string: keyof typeof KEY_CODES, modifiers: number | number[] = []) { if (typeof modifiers === 'number') { modifiers = [modifiers] // convert singular to array } let charCode = KEY_CODES[string] || string.toUpperCase().charCodeAt(0) let keyCode = charCode let keyEvent = createMockEvent('keydown', editor.element, { charCode, keyCode, shiftKey: contains(modifiers, MODIFIERS.SHIFT), metaKey: contains(modifiers, MODIFIERS.META), ctrlKey: contains(modifiers, MODIFIERS.CTRL), }) _triggerEditorEvent(editor, keyEvent) } function triggerRightArrowKey(editor: Editor, modifier?: number) { if (!(editor instanceof Editor)) { throw new Error('Must pass editor to triggerRightArrowKey') } let keydown = createMockEvent('keydown', editor.element, { keyCode: KEY_CODES.RIGHT, shiftKey: modifier === MODIFIERS.SHIFT, }) let keyup = createMockEvent('keyup', editor.element, { keyCode: KEY_CODES.RIGHT, shiftKey: modifier === MODIFIERS.SHIFT, }) _triggerEditorEvent(editor, keydown) _triggerEditorEvent(editor, keyup) } function triggerLeftArrowKey(editor: Editor, modifier?: number) { assertEditor(editor) let keydown = createMockEvent('keydown', editor.element, { keyCode: KEY_CODES.LEFT, shiftKey: modifier === MODIFIERS.SHIFT, }) let keyup = createMockEvent('keyup', editor.element, { keyCode: KEY_CODES.LEFT, shiftKey: modifier === MODIFIERS.SHIFT, }) _triggerEditorEvent(editor, keydown) _triggerEditorEvent(editor, keyup) } // Allows our fake copy and paste events to communicate with each other. const lastCopyData: Dict<unknown> = {} function triggerCopyEvent(editor: Editor) { let eventData = { clipboardData: { setData(type: string, value: unknown) { lastCopyData[type] = value }, }, } let event = createMockEvent('copy', editor.element, eventData) _triggerEditorEvent(editor, event) } function triggerCutEvent(editor: Editor) { let event = createMockEvent('cut', editor.element, { clipboardData: { setData(type: string, value: unknown) { lastCopyData[type] = value }, }, }) _triggerEditorEvent(editor, event) } function triggerPasteEvent(editor: Editor) { let eventData = { clipboardData: { getData(type: string) { return lastCopyData[type] }, }, } let event = createMockEvent('paste', editor.element, eventData) _triggerEditorEvent(editor, event) } function triggerDropEvent( editor: Editor, { html, text, clientX, clientY }: { html: string; text: string; clientX: number; clientY: number } ) { if (!clientX || !clientY) { throw new Error('Must pass clientX, clientY') } let event = createMockEvent('drop', editor.element, { clientX, clientY, dataTransfer: { getData(mimeType: string) { switch (mimeType) { case MIME_TEXT_HTML: return html case MIME_TEXT_PLAIN: return text default: throw new Error('invalid mime type ' + mimeType) } }, }, }) _triggerEditorEvent(editor, event) } function getCopyData(type: string) { return lastCopyData[type] } function setCopyData(type: string, value: unknown) { lastCopyData[type] = value } function clearCopyData() { Object.keys(lastCopyData).forEach(key => { delete lastCopyData[key] }) } function fromHTML(html: string) { html = $.trim(html) let div = document.createElement('div') div.innerHTML = html return div } /** * Tests fail in IE when using `element.blur`, so remove focus by refocusing * on another item instead of blurring the editor element */ function blur() { let input = $('<input>') input.appendTo('#qunit-fixture') input.focus() } function getData(element: HTMLElement, name: string) { if (element.dataset) { return element.dataset[name] } else { return element.getAttribute(dasherize(name)) } } const DOMHelper = { moveCursorTo, moveCursorWithoutNotifyingEditorTo, selectRange, selectText, clearSelection, triggerEvent, build, fromHTML, KEY_CODES, getCursorPosition, getSelectedText, triggerDelete, triggerForwardDelete, triggerEnter, insertText, triggerKeyEvent, triggerKeyCommand, triggerRightArrowKey, triggerLeftArrowKey, triggerCopyEvent, triggerCutEvent, triggerPasteEvent, triggerDropEvent, getCopyData, setCopyData, clearCopyData, createMockEvent, findTextNode, blur, getData, } export { triggerEvent } export default DOMHelper
the_stack
import { IonicNativePlugin } from '@ionic-native/core'; /** * @name HMSNearby * @description * The Cordova Nearby Plugin enables communication between Huawei Nearby Kit SDK and Cordova platform. This plugin exposes all functionality provided by Huawei Nearby Kit SDK. * * @usage * ```typescript * import { HMSNearby } from '@hmscore/ionic-native-hms-nearby'; * * * constructor(private hmsNearby: HMSNearby) { } * * ... * * * this.hmsNearby.functionName('Hello', 123) * .then((res: any) => console.log(res)) * .catch((error: any) => console.error(error)); * * ``` */ export declare class HMSNearbyOriginal extends IonicNativePlugin { /** * Enables HMSLogger capability which is used for sending usage analytics of Nearby SDK's methods. * @returns Promise<void> */ enableLogger(): Promise<void>; /** * Disables HMSLogger capability which is used for sending usage analytics of Nearby SDK's methods. * @returns Promise<void> */ disableLogger(): Promise<void>; /** * Checks whether permission is granted to use the services. * @param {HMSPermission} permission Permission. * @returns Promise<boolean> */ hasPermission(permission: HMSPermission): Promise<boolean>; /** * Obtains the necessary permissions to use the services. * @param {HMSPermission} permission Permission. * @returns Promise<void> */ requestPermission(permission: HMSPermission): Promise<void>; /** * Obtains the necessary permissions to use the services. * @param {HMSPermission[]} permissions Permissions List. * @returns Promise<void> */ requestPermissions(permissions: HMSPermission[]): Promise<void>; /** * Subscribes to Nearby events. Pass a callback to run codes when the event triggered. * @param {HMSNearbyEvent} event Event name. * @param {(res: any) => void} callback Callback to be called when the event triggered. */ on(event: HMSNearbyEvent, callback: (res: any) => void): void; /** * Starts broadcasting. * @param {string} name Local endpoint name. * @param {string} serviceId Service ID. The app package name is recommended. * @param {Policy} policy Object of the Policy type. * @returns Promise<void> */ startBroadcasting(name: string, serviceId: string, policy: Policy): Promise<void>; /** * Stops broadcasting. * @returns Promise<void> */ stopBroadcasting(): Promise<void>; /** * Starts to scan for remote endpoints with the specified service ID. * @param {string} serviceId Service ID. The app package name is recommended. * @param {Policy} policy Object of the Policy type. * @returns Promise<void> */ startScan(serviceId: string, policy: Policy): Promise<void>; /** * Stops discovering devices. * @returns Promise<void> */ stopScan(): Promise<void>; /** * Sends a request to connect to a remote endpoint. * @param {string} name Local endpoint name. * @param {string} endpointId ID of the remote endpoint. * @returns Promise<void> */ requestConnect(name: string, endpointId: string): Promise<void>; /** * Sends a request to connect to a remote endpoint. * @param {string} name Local endpoint name. * @param {string} endpointId ID of the remote endpoint. * @param {ChannelPolicy} channelPolicy Channel policy, which is used to select the channel for establishing a connection. * @returns Promise<void> */ requestConnectEx(name: string, endpointId: string, channelPolicy: ChannelPolicy): Promise<void>; /** * Accepts a connection. This API must be called before data transmission. If the connection request is not accepted within 8 seconds, the connection fails and needs to be re-initiated. * @param {string} endpointId ID of the remote endpoint. * @returns Promise<void> */ acceptConnect(endpointId: string): Promise<void>; /** * Rejects a connection request from a remote endpoint. * @param {string} endpointId ID of the remote endpoint. * @returns Promise<void> */ rejectConnect(endpointId: string): Promise<void>; /** * Disconnects from a remote endpoint. Then communication with the remote endpoint is no longer available. * @param {string} endpointId ID of the remote endpoint. * @returns Promise<void> */ disconnect(endpointId: string): Promise<void>; /** * Disconnects all connections. * @returns Promise<void> */ disconnectAll(): Promise<void>; /** * Transfers given bytes to given endpoint ids. * @param {number[]} bytes number array that contains your data. * @param {string[]} endpointIds string array of remote endpoint IDs. * @returns Promise<void> */ sendBytes(bytes: number[], endpointIds: string[]): Promise<void>; /** * Transfers file from given URI to given endpoint ids. Transferred file is saved in subscriber's device under Downloads/Nearby/ directory with name data id. * @param {string} fileUri File URI. * @param {string[]} endpointIds string array of remote endpoint IDs. * @returns Promise<void> */ sendFile(fileUri: string, endpointIds: string[]): Promise<void>; /** * Transfers stream from given URL to given endpoint ids. * @param {string} streamUrl Stream URL. * @param {string[]} endpointIds string array of remote endpoint IDs. * @returns Promise<void> */ sendStream(streamUrl: string, endpointIds: string[]): Promise<void>; /** * Cancels data transmission when sending or receiving data. * @param {string} dataId ID of the data whose transmission is to be canceled. * @returns Promise<void> */ cancelDataTransfer(dataId: string): Promise<void>; /** * Obtains the current API credential. * @returns Promise<string> Promise result of an execution that returns the current API credential. */ getApiKey(): Promise<string>; /** * Sets the API credential for your app. * @param {string} apiKey API credential. * @returns Promise<void> */ setApiKey(apiKey: string): Promise<void>; /** * Publishes a message and broadcasts a token for nearby devices to scan. * @param {Message} message Published message. * @returns Promise<void> */ put(message: Message): Promise<void>; /** * Publishes a message and broadcasts a token for nearby devices to scan. This message is published only to apps that use the same project ID and have registered the message type with the cloud for subscription. * @param {Message} message Published message. * @param {PutOption} putOption PutOption parameters. * @returns Promise<void> */ put(message: Message, putOption: PutOption): Promise<void>; /** * Obtains messages from the cloud using the default option (DEFAULT). * @returns Promise<void> */ get(): Promise<void>; /** * Registers the messages to be obtained with the cloud. Only messages with the same project ID can be obtained. * @param {GetOption} getOption * @returns Promise<void> */ get(getOption: GetOption): Promise<void>; /** * Identifies only BLE beacon messages. It subscribes to messages published by nearby devices in a persistent and low-power manner and uses the default configuration (DEFAULT). Scanning is going on no matter whether your app runs in the background or foreground. The scanning stops when the app process is killed. * @returns Promise<void> */ getInBackground(): Promise<void>; /** * Identifies only BLE beacon messages. Scanning is going on no matter whether your app runs in the background or foreground. The scanning stops when the app process is killed. * @param {GetOption} getOption * @returns Promise<void> */ getInBackground(getOption: GetOption): Promise<void>; /** * Cancels message publishing. * @param {Message} message Published message. * @returns Promise<void> */ unput(message: Message): Promise<void>; /** * Cancels a message subscription. * @returns Promise<void> */ unget(): Promise<void>; /** * Cancels the current message subscription. * @returns Promise<void> */ ungetInBackground(): Promise<void>; /** * Enable the Wi-Fi sharing function. Set WifiSharePolicy based on function requirements. * @param {WifiSharePolicy} wifiSharePolicy Wi-Fi sharing policy. Enable the Wi-Fi sharing mode or configuration mode as required. * @returns Promise<void> */ startWifiShare(wifiSharePolicy: WifiSharePolicy): Promise<void>; /** * Disables the Wi-Fi sharing function. * @returns Promise<void> */ stopWifiShare(): Promise<void>; /** * Shares Wi-Fi with a remote device. * @param {string} endpointId ID of the remote endpoint. * @returns Promise<void> */ shareWifiConfig(endpointId: string): Promise<void>; /** * Obtains the Nearby Service SDK version number. * @returns Promise<string> Version number of the Nearby Service SDK. */ getVersion(): Promise<string>; } export declare enum HMSNearbyEvent { EVENT_CONNECTION_ON_ESTABLISH = "eventConnectionOnEstablish", EVENT_CONNECTION_ON_RESULT = "eventConnectionOnResult", EVENT_CONNECTION_ON_DISCONNECT = "eventConnectionOnDisconnect", EVENT_SCAN_ON_FOUND = "eventScanOnFound", EVENT_SCAN_ON_LOST = "eventScanOnLost", EVENT_DATA_ON_RECEIVED = "eventDataOnReceived", EVENT_DATA_ON_TRANSFER_UPDATE = "eventDataOnTransferUpdate", EVENT_MESSAGE_ON_BLE_SIGNAL_CHANGED = "eventMessageOnBleSignalChanged", EVENT_MESSAGE_ON_DISTANCE_CHANGED = "eventMessageOnDistanceChanged", EVENT_MESSAGE_ON_FOUND = "eventMessageOnFound", EVENT_MESSAGE_ON_LOST = "eventMessageOnLost", EVENT_PUT_ON_TIMEOUT = "eventPutOnTimeout", EVENT_GET_ON_TIMEOUT = "eventGetOnTimeout", EVENT_STATUS_ON_PERMISSION_CHANGED = "eventStatusOnPermissionChanged", EVENT_WIFI_ON_FOUND = "eventWifiOnFound", EVENT_WIFI_ON_LOST = "eventWifiOnLost", EVENT_WIFI_ON_FETCH_AUTH_CODE = "eventWifiOnFetchAuthCode", EVENT_WIFI_ON_SHARE_RESULT = "eventWifiOnShareResult" } export declare enum HMSPermission { PERMISSION_BLUETOOTH = "android.permission.BLUETOOTH", PERMISSION_BLUETOOTH_ADMIN = "android.permission.BLUETOOTH_ADMIN", PERMISSION_ACCESS_WIFI_STATE = "android.permission.ACCESS_WIFI_STATE", PERMISSION_CHANGE_WIFI_STATE = "android.permission.CHANGE_WIFI_STATE", PERMISSION_ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION", PERMISSION_ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION", PERMISSION_READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE", PERMISSION_WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE" } export declare enum Policy { POLICY_MESH = 1, POLICY_P2P = 2, POLICY_STAR = 3 } export declare enum DataType { DATA_FILE = 1, DATA_BYTES = 2, DATA_STREAM = 3 } export declare enum TransferState { TRANSFER_STATE_SUCCESS = 1, TRANSFER_STATE_FAILURE = 2, TRANSFER_STATE_IN_PROGRESS = 3, TRANSFER_STATE_CANCELED = 4 } export declare enum MessagePolicyDistanceType { POLICY_DISTANCE_TYPE_DEFAULT = 0, POLICY_DISTANCE_TYPE_EARSHOT = 1 } export declare enum MessagePolicyFindingMode { POLICY_FINDING_MODE_DEFAULT = 0, POLICY_FINDING_MODE_BROADCAST = 1, POLICY_FINDING_MODE_SCAN = 2 } export declare enum MessagePolicyTtlSeconds { POLICY_TTL_SECONDS_DEFAULT = 240, POLICY_TTL_SECONDS_MAX = 86400, POLICY_TTL_SECONDS_INFINITE = 2147483647 } export declare enum WifiSharePolicy { POLICY_SHARE = 1, POLICY_SET = 2 } export declare enum ChannelPolicy { CHANNEL_AUTO = 1, CHANNEL_HIGH_THROUGHPUT = 2, CHANNEL_INSTANCE = 3 } export declare enum StatusCode { STATUS_SUCCESS = 0, STATUS_FAILURE = -1, STATUS_API_DISORDER = 8001, STATUS_NO_NETWORK = 8002, STATUS_NOT_CONNECTED = 8003, STATUS_TRANSFER_IO_ERROR = 8004, STATUS_ALREADY_BROADCASTING = 8005, STATUS_ALREADY_CONNECTED = 8006, STATUS_ALREADY_SCANNING = 8007, STATUS_POLICY_CONFLICT = 8008, STATUS_BLUETOOTH_OPERATION_FAILED = 8009, STATUS_CONNECT_REJECTED = 8010, STATUS_CONNECT_IO_ERROR = 8011, STATUS_ENDPOINT_UNKNOWN = 8012, STATUS_API_OCCUPIED = 8013, STATUS_MISSING_PERMISSION_ACCESS_COARSE_LOCATION = 8014, STATUS_MISSING_PERMISSION_ACCESS_WIFI_STATE = 8015, STATUS_MISSING_PERMISSION_BLUETOOTH = 8016, STATUS_MISSING_PERMISSION_BLUETOOTH_ADMIN = 8017, STATUS_MISSING_PERMISSION_CHANGE_WIFI_STATE = 8018, STATUS_MISSING_PERMISSION_RECORD_AUDIO = 8019, STATUS_MISSING_SETTING_LOCATION_ON = 8020, STATUS_AIRPLANE_MODE_MUST_BE_OFF = 8021, STATUS_MESSAGE_APP_UNREGISTERED = 8050, STATUS_MESSAGE_APP_QUOTA_LIMITED = 8051, STATUS_MESSAGE_BLE_BROADCASTING_UNSUPPORTED = 8052, STATUS_MESSAGE_BLE_SCANNING_UNSUPPORTED = 8053, STATUS_MESSAGE_BLUETOOTH_OFF = 8054, STATUS_MESSAGE_WRONG_CONTEXT = 8055, STATUS_MESSAGE_NOT_ALLOW = 8056, STATUS_MESSAGE_MISSING_PERMISSIONS = 8057, STATUS_MESSAGE_AUTH_FAILED = 8058, STATUS_MESSAGE_PENDING_INTENTS_LIMITED = 8059, STATUS_INTERNAL_ERROR = 8060, STATUS_FINDING_MODE_ERROR = 8061, STATUS_MESSAGE_TASK_ALREADY_IN_PROCESSING = 8062, STATUS_MISSING_PERMISSION_FILE_READ_WRITE = 8063, STATUS_MISSING_PERMISSION_INTERNET = 8064, STATUS_WIFI_SHARE_USER_AUTH_FAIL = 8065, STATUS_WIFI_SHARE_WIFI_CLOSED = 8066, STATUS_WIFI_CONNECT_FAIL = 8067 } export interface Message { content: number[]; namespace?: string; type?: string; } export interface EddystoneUid { hexNamespace: string; hexInstance: string; } export interface IBeaconId { iBeaconUuid: string; major: number; minor: number; } export interface NamespaceType { namespace: string; type: string; } export interface MessagePicker { includeAllTypes?: boolean; eddystoneUids?: EddystoneUid[]; iBeaconIds?: IBeaconId[]; namespaceTypes?: NamespaceType[]; } export interface MessagePolicy { distanceType?: MessagePolicyDistanceType; findingMode?: MessagePolicyFindingMode; ttlSeconds?: MessagePolicyTtlSeconds; } export interface PutOption { policy?: MessagePolicy; } export interface GetOption { picker?: MessagePicker; policy?: MessagePolicy; } export interface BleSignal { rssi: number; txPower: number; } export interface Distance { precision: number; meters: number; } export declare const BLE_UNKNOWN_TX_POWER: number; export declare const PRECISION_LOW: number; export declare const MAX_SIZE_DATA: number; export declare const MAX_CONTENT_SIZE: number; export declare const MAX_TYPE_LENGTH: number; export declare const MESSAGE_NAMESPACE_RESERVED: string; export declare const MESSAGE_TYPE_EDDYSTONE_UID: string; export declare const MESSAGE_TYPE_I_BEACON_ID: string; export declare const DISTANCE_UNKNOWN: Distance; export declare const MESSAGE_PICKER_INCLUDE_ALL_TYPES: MessagePicker; export declare const MESSAGE_POLICY_DEFAULT: MessagePolicy; export declare const MESSAGE_POLICY_BLE_ONLY: MessagePolicy; export declare const GET_OPTION_DEFAULT: GetOption; export declare const PUT_OPTION_DEFAULT: PutOption; export interface EndpointId { endpointId: string; } export interface ConnectInfo { endpointId: string; endpointName: string; authCode: string; isRemoteConnect: boolean; } export interface ConnectResult { endpointId: string; statusCode: StatusCode; statusMessage: string; channelPolicy: ChannelPolicy; } export interface ScanEndpointInfo { endpointId: string; serviceId: string; name: string; } export interface Data { endpointId: string; dataType: DataType; dataId: string; size?: number; data?: number[]; fileUri?: string; } export interface TransferStateUpdate { endpointId: string; dataId: string; status: TransferState; transferredBytes: number; totalBytes: number; } export interface BleSignalUpdate { message: Message; bleSignal: BleSignal; } export interface DistanceUpdate { message: Message; distance: Distance; } export interface MessageTimeout { message: Message; status: string; } export interface PermissionUpdate { grantPermission: boolean; } export interface AuthCodeUpdate { endpointId: string; authCode: string; } export interface WifiShareResult { endpointId: string; statusCode: StatusCode; } export declare const HMSNearby: HMSNearbyOriginal;
the_stack
export enum TYPES { "BYTE" = "BYTE", "UNSIGNED_BYTE" = "UNSIGNED_BYTE", "SHORT" = "SHORT", "UNSIGNED_SHORT" = "UNSIGNED_SHORT", "FLOAT" = "FLOAT", } export interface AttributeInfo { attribute: Attribute; size: Attribute["size"]; type: Attribute["type"]; normalized: Attribute["normalized"]; offset: number; stride: number; } /** * An exception for when two or more of the same attributes are found in the * same layout. * @private */ export class DuplicateAttributeException extends Error { /** * Create a DuplicateAttributeException * @param {Attribute} attribute - The attribute that was found more than * once in the {@link Layout} */ constructor(attribute: Attribute) { super(`found duplicate attribute: ${attribute.key}`); } } /** * Represents how a vertex attribute should be packed into an buffer. * @private */ export class Attribute { public sizeOfType: number; public sizeInBytes: number; /** * Create an attribute. Do not call this directly, use the predefined * constants. * @param {string} key - The name of this attribute as if it were a key in * an Object. Use the camel case version of the upper snake case * const name. * @param {number} size - The number of components per vertex attribute. * Must be 1, 2, 3, or 4. * @param {string} type - The data type of each component for this * attribute. Possible values:<br/> * "BYTE": signed 8-bit integer, with values in [-128, 127]<br/> * "SHORT": signed 16-bit integer, with values in * [-32768, 32767]<br/> * "UNSIGNED_BYTE": unsigned 8-bit integer, with values in * [0, 255]<br/> * "UNSIGNED_SHORT": unsigned 16-bit integer, with values in * [0, 65535]<br/> * "FLOAT": 32-bit floating point number * @param {boolean} normalized - Whether integer data values should be * normalized when being casted to a float.<br/> * If true, signed integers are normalized to [-1, 1].<br/> * If true, unsigned integers are normalized to [0, 1].<br/> * For type "FLOAT", this parameter has no effect. */ constructor(public key: string, public size: number, public type: TYPES, public normalized: boolean = false) { switch (type) { case "BYTE": case "UNSIGNED_BYTE": this.sizeOfType = 1; break; case "SHORT": case "UNSIGNED_SHORT": this.sizeOfType = 2; break; case "FLOAT": this.sizeOfType = 4; break; default: throw new Error(`Unknown gl type: ${type}`); } this.sizeInBytes = this.sizeOfType * size; } } /** * A class to represent the memory layout for a vertex attribute array. Used by * {@link Mesh}'s TBD(...) method to generate a packed array from mesh data. * <p> * Layout can sort of be thought of as a C-style struct declaration. * {@link Mesh}'s TBD(...) method will use the {@link Layout} instance to * pack an array in the given attribute order. * <p> * Layout also is very helpful when calling a WebGL context's * <code>vertexAttribPointer</code> method. If you've created a buffer using * a Layout instance, then the same Layout instance can be used to determine * the size, type, normalized, stride, and offset parameters for * <code>vertexAttribPointer</code>. * <p> * For example: * <pre><code> * * const index = glctx.getAttribLocation(shaderProgram, "pos"); * glctx.vertexAttribPointer( * layout.position.size, * glctx[layout.position.type], * layout.position.normalized, * layout.position.stride, * layout.position.offset); * </code></pre> * @see {@link Mesh} */ export class Layout { // Geometry attributes /** * Attribute layout to pack a vertex's x, y, & z as floats * * @see {@link Layout} */ static POSITION = new Attribute("position", 3, TYPES.FLOAT); /** * Attribute layout to pack a vertex's normal's x, y, & z as floats * * @see {@link Layout} */ static NORMAL = new Attribute("normal", 3, TYPES.FLOAT); /** * Attribute layout to pack a vertex's normal's x, y, & z as floats. * <p> * This value will be computed on-the-fly based on the texture coordinates. * If no texture coordinates are available, the generated value will default to * 0, 0, 0. * * @see {@link Layout} */ static TANGENT = new Attribute("tangent", 3, TYPES.FLOAT); /** * Attribute layout to pack a vertex's normal's bitangent x, y, & z as floats. * <p> * This value will be computed on-the-fly based on the texture coordinates. * If no texture coordinates are available, the generated value will default to * 0, 0, 0. * @see {@link Layout} */ static BITANGENT = new Attribute("bitangent", 3, TYPES.FLOAT); /** * Attribute layout to pack a vertex's texture coordinates' u & v as floats * * @see {@link Layout} */ static UV = new Attribute("uv", 2, TYPES.FLOAT); // Material attributes /** * Attribute layout to pack an unsigned short to be interpreted as a the index * into a {@link Mesh}'s materials list. * <p> * The intention of this value is to send all of the {@link Mesh}'s materials * into multiple shader uniforms and then reference the current one by this * vertex attribute. * <p> * example glsl code: * * <pre><code> * // this is bound using MATERIAL_INDEX * attribute int materialIndex; * * struct Material { * vec3 diffuse; * vec3 specular; * vec3 specularExponent; * }; * * uniform Material materials[MAX_MATERIALS]; * * // ... * * vec3 diffuse = materials[materialIndex]; * * </code></pre> * TODO: More description & test to make sure subscripting by attributes even * works for webgl * * @see {@link Layout} */ static MATERIAL_INDEX = new Attribute("materialIndex", 1, TYPES.SHORT); static MATERIAL_ENABLED = new Attribute("materialEnabled", 1, TYPES.UNSIGNED_SHORT); static AMBIENT = new Attribute("ambient", 3, TYPES.FLOAT); static DIFFUSE = new Attribute("diffuse", 3, TYPES.FLOAT); static SPECULAR = new Attribute("specular", 3, TYPES.FLOAT); static SPECULAR_EXPONENT = new Attribute("specularExponent", 3, TYPES.FLOAT); static EMISSIVE = new Attribute("emissive", 3, TYPES.FLOAT); static TRANSMISSION_FILTER = new Attribute("transmissionFilter", 3, TYPES.FLOAT); static DISSOLVE = new Attribute("dissolve", 1, TYPES.FLOAT); static ILLUMINATION = new Attribute("illumination", 1, TYPES.UNSIGNED_SHORT); static REFRACTION_INDEX = new Attribute("refractionIndex", 1, TYPES.FLOAT); static SHARPNESS = new Attribute("sharpness", 1, TYPES.FLOAT); static MAP_DIFFUSE = new Attribute("mapDiffuse", 1, TYPES.SHORT); static MAP_AMBIENT = new Attribute("mapAmbient", 1, TYPES.SHORT); static MAP_SPECULAR = new Attribute("mapSpecular", 1, TYPES.SHORT); static MAP_SPECULAR_EXPONENT = new Attribute("mapSpecularExponent", 1, TYPES.SHORT); static MAP_DISSOLVE = new Attribute("mapDissolve", 1, TYPES.SHORT); static ANTI_ALIASING = new Attribute("antiAliasing", 1, TYPES.UNSIGNED_SHORT); static MAP_BUMP = new Attribute("mapBump", 1, TYPES.SHORT); static MAP_DISPLACEMENT = new Attribute("mapDisplacement", 1, TYPES.SHORT); static MAP_DECAL = new Attribute("mapDecal", 1, TYPES.SHORT); static MAP_EMISSIVE = new Attribute("mapEmissive", 1, TYPES.SHORT); public stride: number; public attributes: Attribute[]; public attributeMap: { [idx: string]: AttributeInfo }; /** * Create a Layout object. This constructor will throw if any duplicate * attributes are given. * @param {Array} ...attributes - An ordered list of attributes that * describe the desired memory layout for each vertex attribute. * <p> * * @see {@link Mesh} */ constructor(...attributes: Attribute[]) { this.attributes = attributes; this.attributeMap = {}; let offset = 0; let maxStrideMultiple = 0; for (const attribute of attributes) { if (this.attributeMap[attribute.key]) { throw new DuplicateAttributeException(attribute); } // Add padding to satisfy WebGL's requirement that all // vertexAttribPointer calls have an offset that is a multiple of // the type size. if (offset % attribute.sizeOfType !== 0) { offset += attribute.sizeOfType - (offset % attribute.sizeOfType); console.warn("Layout requires padding before " + attribute.key + " attribute"); } this.attributeMap[attribute.key] = { attribute: attribute, size: attribute.size, type: attribute.type, normalized: attribute.normalized, offset: offset, } as AttributeInfo; offset += attribute.sizeInBytes; maxStrideMultiple = Math.max(maxStrideMultiple, attribute.sizeOfType); } // Add padding to the end to satisfy WebGL's requirement that all // vertexAttribPointer calls have a stride that is a multiple of the // type size. Because we're putting differently sized attributes into // the same buffer, it must be padded to a multiple of the largest // type size. if (offset % maxStrideMultiple !== 0) { offset += maxStrideMultiple - (offset % maxStrideMultiple); console.warn("Layout requires padding at the back"); } this.stride = offset; for (const attribute of attributes) { this.attributeMap[attribute.key].stride = this.stride; } } }
the_stack
import path = require('path'); import fs = require('graceful-fs'); import mkdirp = require('mkdirp'); import lockfile = require('proper-lockfile'); import { JspmError, JspmUserError, bold } from '../utils/common'; export type OrderingValue = string | [string, OrderingArray]; export interface OrderingArray extends Array<OrderingValue> {} export interface ConfigValue { value: any[] | number | boolean | string } export interface ObjectProperty { key: string, value: ConfigObject | ConfigValue } export type ConfigObject = ObjectProperty[]; export type ValueType = 'array' | 'number' | 'boolean' | 'string'; interface sourceStyle { trailingNewline: boolean, newline: string, quote: string, tab: string } /* * Configuration base class * For creating and managing configurations which sync to files */ export default class ConfigFile { fileName: string; _original: object; private ordering: OrderingArray; private style: sourceStyle = null; protected timestamp: number = null; /* * Properties are stored as an ordered array of { key, value } paris * Nested object are in turn array values * Value properties are { value } objects */ private properties: ConfigObject = []; protected changeEvents: ((configMember: string[]) => void | boolean)[] = []; // we only write when the file has actually changed protected changed: boolean = false; // keep track of originalName when renaming private originalName: string = undefined; private _unlock: () => void; protected locked = false; constructor (fileName: string, ordering: OrderingArray) { this.fileName = path.resolve(fileName); this.ordering = ordering; } rename (newName: string) { newName = path.resolve(newName); if (this.fileName === newName) return; this.originalName = this.originalName || this.timestamp !== -1 && this.fileName; this.fileName = newName; try { this.timestamp = fs.statSync(this.fileName).mtime.getTime(); } catch (e) { if (e.code !== 'ENOENT') throw e; this.timestamp = -1; } this.changed = true; } // only applies to values // Returns undefined for no value // throws if an object, with a fileName reference // member lookups not in objects throw // type is optional, and can be 'array', 'number', 'boolean', 'string' to add simple type checking protected getValue (memberArray: string[], type?: ValueType) { var parentProps = this.getProperties(memberArray.slice(0, memberArray.length - 1)); if (!parentProps) return; var prop = getProperty(parentProps, memberArray[memberArray.length - 1]).property; if (prop === undefined) return; if (Array.isArray(prop.value)) configError.call(this, memberArray, 'must be a value'); var value = prop.value.value; if (type === 'array' && !Array.isArray(value) || (type && type !== 'array' && typeof value !== type)) configError.call(this, memberArray, 'must be a' + (type === 'array' ? 'n ' : ' ') + type + ' value'); return value; } // returns properties array // If not a properties array, returns undefined // If any member is a value instead of an object, returns undefined // When createIfUndefined is set, object is created with the correct ordering // setting changed: true in the process if necessary // If any member is a value with createIfUndefined, throws an error protected getProperties (memberArray: string[], createIfUndefined = false) { var properties = this.properties; var ordering = this.ordering; var self = this; memberArray.some((member, index) => { var prop = getProperty(properties, member).property; if (prop) { properties = prop.value; if (!Array.isArray(properties)) { if (createIfUndefined) { configError.call(self, memberArray.slice(0, index + 1), 'should be an object'); } else { properties = undefined; return true; } } } else { if (createIfUndefined) { setProperty(properties, member, properties = [], ordering); self.onChange(memberArray); } else { properties = undefined; return true; } } ordering = getOrdering([member], ordering); }); return properties; } // returns properties array as a readable JS object of values. // Nested objects throw nice error unless nested is set to true // if the object does not exist, returns undefined // if the property corresponds to a value, throws protected getObject (memberArray = [], nested = true, createIfUndefined = false) { var properties = this.getProperties(memberArray, createIfUndefined); if (!properties) return; var obj = propertiesToObject(properties); var self = this; if (!nested) Object.keys(obj).forEach(key => { if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) configError.call(self, memberArray, 'should not contain a nested object at %' + key + '%'); }); return obj; } protected has (memberArray: string[]) { var parentProps = this.getProperties(memberArray.slice(0, memberArray.length - 1)); if (!parentProps) return false; return getProperty(parentProps, memberArray[memberArray.length - 1]).property !== undefined; } // removes the given property member name if it exists protected remove (memberArray: string[], clearParentsIfMadeEmpty = false) { var parentProps = this.getProperties(memberArray.slice(0, memberArray.length - 1)); if (!parentProps) return false; var self = this; var removed = parentProps.some((prop, index) => { if (prop.key === memberArray[memberArray.length - 1]) { parentProps.splice(index, 1); self.onChange(memberArray.slice(0, memberArray.length - 1)); return true; } }); if (clearParentsIfMadeEmpty && removed && parentProps.length === 0 && memberArray.length > 1) this.remove(memberArray.slice(0, memberArray.length - 1), true); return removed; } protected clearIfEmpty (memberArray: string[]) { var props = this.getProperties(memberArray); if (props && !props.length) this.remove(memberArray); } // sets this.changed if a change // retains property ordering // overwrites anything already existing // creates objects if not existing, at correct ordered location protected setValue (memberArray: string[], value, overwrite = true) { var properties = this.getProperties(memberArray.slice(0, memberArray.length - 1), true); var ordering = getOrdering(memberArray.slice(0, memberArray.length - 1), this.ordering); if (setProperty(properties, memberArray[memberArray.length - 1], { value: value }, ordering, overwrite)) this.onChange(memberArray); } // handles nested objects, memberArray can be 0 length for base-level population // where target object already exists, it overwrites retaining the same ordering // default behaviour is to not write empty objects, but to also not clear objects made empty // also avoids unnecessary changes protected setProperties (memberArray: string[], properties: ConfigObject, clearIfEmpty = false, keepOrder = false, extend = true, overwrite = false) { var targetProperties; if (!properties.length) { targetProperties = this.getProperties(memberArray); if (targetProperties && targetProperties.length) { if (clearIfEmpty) this.remove(memberArray); else targetProperties.splice(0, targetProperties.length); this.onChange(memberArray); } else if (!clearIfEmpty) this.getProperties(memberArray, true); return; } targetProperties = this.getProperties(memberArray, true); var ordering; if (!keepOrder) ordering = getOrdering(memberArray.slice(0, memberArray.length - 1), this.ordering); var self = this; var setKeys = []; properties.forEach(prop => { setKeys.push(prop.key); if (setProperty(targetProperties, prop.key, prop.value, ordering, overwrite)) self.onChange(memberArray); }); if (!extend) for (var i = 0; i < targetProperties.length; i++) { var prop = targetProperties[i]; if (setKeys.indexOf(prop.key) === -1) { targetProperties.splice(i--, 1); self.onChange(memberArray); } } } // ensures the given property is first in its containing object property // skips if the property does not exist protected orderFirst (memberArray: string[]) { var properties = this.getProperties(memberArray.slice(0, memberArray.length - 1)); if (!properties) return; var propIndex = getProperty(properties, memberArray[memberArray.length - 1]).index; if (propIndex !== -1 && propIndex !== 0) { properties.unshift(properties.splice(propIndex, 1)[0]); this.onChange(memberArray.slice(0, memberArray.length - 1)); } } // ensures the given property is last in its containing object property // skips if the property does not exist protected orderLast (memberArray: string[]) { var properties = this.getProperties(memberArray.slice(0, memberArray.length - 1)); if (!properties) return; var propIndex = getProperty(properties, memberArray[memberArray.length - 1]).index; if (propIndex !== -1 && propIndex !== properties.length - 1) { properties.push(properties.splice(propIndex, 1)[0]); this.onChange(memberArray.slice(0, memberArray.length - 1)); } } // only clears on empty if not already existing as empty // sets this.changed, retains ordering and overwrites as with setValue // keepOrder indicates if new properties should be added in current iteration order // instead of applying the ordering algorithm protected setObject (memberArray: string[] = [], obj, clearIfEmpty = false, keepOrder = false) { // convert object into a properties array return this.setProperties(memberArray, objectToProperties(obj), clearIfEmpty, keepOrder, false); } protected extendObject (memberArray: string[] | any, obj?, keepOrder = false) { if (!Array.isArray(memberArray)) { obj = memberArray; memberArray = []; } return this.setProperties(memberArray, objectToProperties(obj), false, keepOrder, true); } protected prependObject (memberArray: string[] | any, obj?, keepOrder = false) { if (!Array.isArray(memberArray)) { obj = memberArray; memberArray = []; } return this.setProperties(memberArray, objectToProperties(obj), false, keepOrder, true, false); } // default serialization is as a JSON file, but these can be overridden protected serialize (obj) { return serializeJson(obj, this.style); } protected deserialize (source: string) { return JSON.parse(source); } // note that the given proprety is changed // also triggers change events onChange (memberArray: string[]) { // run any attached change events if (!this.changeEvents.reduce((stopPropagation, evt) => stopPropagation || evt(memberArray), false)) this.changed = true; } protected lock (symlink = true) { try { this._unlock = lockfile.lockSync(this.fileName, symlink ? undefined : { realpath: false }); this.locked = true; } catch (e) { if (symlink && e.code === 'ENOENT') return this.lock(false); if (e.code === 'ELOCKED') throw new JspmUserError(`Configuration file ${bold(this.fileName)} is currently locked by another jspm process.`); throw e; } } protected unlock () { if (this._unlock) { this._unlock(); this._unlock = undefined; this.locked = false; } } exists (): boolean { if (this.timestamp === null) this.read(); return this.timestamp === -1 ? false : true; } // read and write are sync functions protected read () { var contents; try { this.timestamp = fs.statSync(this.fileName).mtime.getTime(); contents = fs.readFileSync(this.fileName).toString(); } catch (e) { if (e.code !== 'ENOENT') throw e; this.timestamp = -1; contents = ''; } this.style = detectStyle(contents); var deserializedObj; try { deserializedObj = this.deserialize(contents || '{}') || {}; } catch (e) { configError.call(this, e.toString()); } this.properties = []; this._original = deserializedObj; this.setObject([], deserializedObj, false, true); this.changed = false; } protected write () { var timestamp; try { timestamp = fs.statSync(this.fileName).mtime.getTime(); } catch (e) { if (e.code !== 'ENOENT') throw e; timestamp = -1; } if (timestamp !== this.timestamp) throw new JspmUserError('Configuration file ' + path.relative(process.cwd(), this.fileName) + ' has been modified by another process.'); if (this.changed || timestamp === -1) { // if the file doesn't exist make sure the folder exists mkdirp.sync(path.dirname(this.fileName)); var obj = this.getObject([], true); fs.writeFileSync(this.fileName, this.serialize(obj)); this.timestamp = fs.statSync(this.fileName).mtime.getTime(); this.changed = false; // if the file was renamed, remove the old file now after writing if (this.originalName) { fs.unlinkSync(this.originalName); this.originalName = null; } return true; } return false; } }; function configError (memberArray, msg) { if (arguments.length === 1) { msg = memberArray; memberArray = []; } throw new JspmUserError(`Error reading ${bold(path.relative(process.cwd(), this.fileName))}\n\t` + (memberArray.length ? bold(memberArray.join('.')) + ' ' : 'File ') + msg + '.'); } function propertyEquals (propA, propB) { if (Array.isArray(propA) || Array.isArray(propB)) { if (!(Array.isArray(propA) && Array.isArray(propB))) return false; if (propA.length !== propB.length) return false; return !propA.some((itemA, index) => { var itemB = propB[index]; return itemA.key !== itemB.key || !propertyEquals(itemA.value, itemB.value); }); } else { return propA.value === propB.value; } } // adds the new property to the given properties object // if the property exists, it is updated to the new value // if not the property is placed at the first appropriate position alphabetically // returns true when an actual change is made // ordering is an array representing the property order suggestion, to use to apply ordering algorithm function setProperty (properties: ConfigObject, key: string, value, ordering: OrderingArray, overwrite = true) { var changed = false; if (properties.some(prop => { if (prop.key === key) { if (!overwrite) return false; // determine equality if (!propertyEquals(prop.value, value)) changed = true; prop.value = value; return true; } })) return changed; if (!ordering || !ordering.length) { properties.push({ key: key, value: value }); return true; } // apply ordering algorithm var orderIndex = orderingIndex(ordering, key); // find the max and minimum index in this property list given the ordering spec var maxOrderIndex = properties.length, minOrderIndex = 0; if (orderIndex !== -1) properties.forEach((prop, index) => { // get the ordering index of the current property var propOrderIndex = orderingIndex(ordering, prop.key); if (propOrderIndex !== -1) { if (propOrderIndex < orderIndex && index + 1 > minOrderIndex && index < maxOrderIndex) minOrderIndex = index + 1; if (propOrderIndex > orderIndex && index < maxOrderIndex && index >= minOrderIndex) maxOrderIndex = index; } }); // within the ordering range, use alphabetical ordering orderIndex = -1; for (var i = minOrderIndex; i < maxOrderIndex; i++) if (properties[i].key > key) { orderIndex = i; break; } if (orderIndex === -1) orderIndex = maxOrderIndex; properties.splice(orderIndex, 0, { key: key, value: value }); return true; } // returns a property object for a given key from the property list // returns undefined if not found // properties is already assumed to be an array function getProperty (properties, key) { var propMatch = { index: -1, property: undefined }; properties.some((prop, index) => { if (prop.key === key) { propMatch = { property: prop, index: index }; return true; } }); return propMatch; } function orderingIndex (ordering: OrderingArray, key: string) { for (var i = 0; i < ordering.length; i++) if (ordering[i] === key || Array.isArray(ordering[i]) && ordering[i][0] === key) return i; return -1; } function getOrdering (memberArray: string[], ordering: OrderingArray): OrderingArray { memberArray.some(member => { let orderIndex = orderingIndex(ordering, member); let orderingValue; if (orderIndex !== -1) orderingValue = ordering[orderIndex]; if (Array.isArray(orderingValue)) { ordering = orderingValue[1]; } else { ordering = []; return true; } }); return ordering; } function propertiesToObject (properties: ConfigObject) { var obj = {}; properties.forEach(p => { var prop = p.key; var val = p.value; if (Array.isArray(val)) obj[prop] = propertiesToObject(val); else obj[prop] = val.value; }); return obj; } function objectToProperties (obj): ConfigObject { var properties = []; Object.keys(obj).forEach(key => { var value = obj[key]; if (typeof value === 'object' && !Array.isArray(value) && value !== null) value = objectToProperties(value); else value = { value: value }; properties.push({ key: key, value: value }); }); return properties; } export interface jsonStyle { tab: string, newline: string, trailingNewline: boolean, quote: string }; export async function readJSONStyled (filePath: string): Promise<{ json: any, style: jsonStyle }> { try { var source = await new Promise<string>((resolve, reject) => { fs.readFile(filePath, (err, source) => err ? reject(err) : resolve(source.toString())); }); } catch (e) { if (e.code === 'ENOENT') return { json, style }; throw e; } // remove any byte order mark if (source.startsWith('\uFEFF')) source = source.substr(1); var style = detectStyle(source); try { var json = JSON.parse(source); } catch (e) { throw new JspmError(`Error parsing JSON file ${filePath}.`); } return { json, style }; } export async function writeJSONStyled (filePath: string, json: any, style: jsonStyle) { await new Promise((resolve, reject) => fs.writeFile(filePath, serializeJson(json, style), err => err ? reject(err) : resolve())); } export const defaultStyle = { tab: ' ', newline: require('os').EOL, trailingNewline: true, quote: '"' }; export function detectStyle (string: string): jsonStyle { let style = Object.assign({}, defaultStyle); let newLineMatch = string.match( /\r?\n|\r(?!\n)/); if (newLineMatch) style.newline = newLineMatch[0]; // best-effort tab detection // yes this is overkill, but it avoids possibly annoying edge cases let tabSpaces = string.split(style.newline).map(line => line.match(/^[ \t]*/)[0]) || []; let tabDifferenceFreqs = {}; let lastLength = 0; tabSpaces.forEach(tabSpace => { let diff = Math.abs(tabSpace.length - lastLength); if (diff !== 0) tabDifferenceFreqs[diff] = (tabDifferenceFreqs[diff] || 0) + 1; lastLength = tabSpace.length; }); let bestTabLength; Object.keys(tabDifferenceFreqs).forEach(tabLength => { if (!bestTabLength || tabDifferenceFreqs[tabLength] >= tabDifferenceFreqs[bestTabLength]) bestTabLength = tabLength; }); // having determined the most common spacing difference length, // generate samples of this tab length from the end of each line space // the most common sample is then the tab string let tabSamples = {}; tabSpaces.forEach(tabSpace => { let sample = tabSpace.substr(tabSpace.length - bestTabLength); tabSamples[sample] = (tabSamples[sample] || 0) + 1; }); let bestTabSample; Object.keys(tabSamples).forEach(sample => { if (!bestTabSample || tabSamples[sample] > tabSamples[bestTabSample]) bestTabSample = sample; }); if (bestTabSample) style.tab = bestTabSample; let quoteMatch = string.match(/"|'/); if (quoteMatch) style.quote = quoteMatch[0]; if (string && !string.match(new RegExp(style.newline + '$'))) style.trailingNewline = false; return style; } export function serializeJson (json, style: jsonStyle) { let jsonString = JSON.stringify(json, null, style.tab); if (style.trailingNewline) jsonString += style.newline; return jsonString .replace(/([^\\])""/g, '$1' + style.quote + style.quote) // empty strings .replace(/([^\\])"/g, '$1' + style.quote) .replace(/\n/g, style.newline); }
the_stack
import React, { CSSProperties, useState } from 'react'; import JSONPretty from 'react-json-pretty'; import { Dropdown, getTheme, IColumn, Icon, IconButton, IDropdownOption, Pivot, PivotItem, ScrollablePane, ScrollbarVisibility, Stack, Text } from '@fluentui/react'; import { useQuery, useQueryClient } from 'react-query' import { CommandAuditEntity } from 'teamcloud'; import { api } from '../API'; import { ContentSearch, Lightbox } from './common'; import { useOrg, useAuditCommands } from '../hooks'; import { ContentList, ContentProgress } from '.'; import collaboration from '../img/MSC17_collaboration_010_noBG.png' export const AuditList: React.FC = () => { const theme = getTheme(); const timeRangeOptions: IDropdownOption[] = [ { key: '00:05:00', text: 'last 5 minutes', selected: true }, { key: '00:30:00', text: 'last 30 minutes' }, { key: '01:00:00', text: 'last hour' }, { key: '12:00:00', text: 'last 12 hours' }, { key: '1.00:00:00', text: 'last 24 hours' }, { key: '00:00:00', text: 'All time' }, ]; const [pivotKey, setPivotKey] = useState<string>('Details'); const [itemFilter, setItemFilter] = useState<string>(); const [selectedEntryId, setSelectedEntryId] = useState<string>(); const [selectedCommands, setSelectedCommands] = useState<string[]>([]); const [selectedTimeRange, setSelectedTimeRange] = useState<string>(timeRangeOptions.find(o => (o.selected ?? false))?.key as string); const queryClient = useQueryClient(); const { data: org } = useOrg(); const { data: auditCommands, isLoading: auditCommandsLoading } = useAuditCommands(); const { data: auditEntries, isLoading: auditEntriesLoading } = useQuery(['org', org?.id, 'audit', 'entries', selectedTimeRange, ...selectedCommands], async () => { const { data } = await api.getAuditEntries(org!.id, { timeRange: selectedTimeRange, commands: selectedCommands, onResponse: (raw, flat) => { if (raw.status >= 400) throw new Error(raw.parsedBody || raw.bodyAsText || `Error: ${raw.status}`) } }); return data; }, { enabled: !!org?.id, cacheTime: 1000 * 30 // cache for 30 secs (opposed to default 5 mins) }); const { data: auditEntry, isLoading: auditEntryLoading } = useQuery(['org', org?.id, 'audit', 'entries', selectedEntryId], async () => { const { data } = await api.getAuditEntry(selectedEntryId!, org!.id, { expand: true, onResponse: (raw, flat) => { if (raw.status >= 400) throw new Error(raw.parsedBody || raw.bodyAsText || `Error: ${raw.status}`) } }); return data; }, { enabled: !!org?.id && !!selectedEntryId }); const iconContainerStyle: CSSProperties = { display: 'flex', flexDirection: 'column', justifyContent: 'center', flexShrink: 0, fontSize: '16px', width: '32px', textAlign: 'center', color: 'rgb(161, 159, 157)', cursor: 'text', transition: 'width 0.167s ease 0s' }; const _applyFilter = (audit: CommandAuditEntity, filter: string): boolean => { if (!filter) return true; return JSON.stringify(audit).toUpperCase().includes(filter.toUpperCase()) } const onRenderDate = (date?: Date | null) => <Text>{date?.toDateTimeDisplayString(false)}</Text>; const onRenderParentId = (parentId: string | undefined) => parentId && parentId !== '00000000-0000-0000-0000-000000000000' ? <Text>{parentId}</Text> : <></>; const columns: IColumn[] = [ { key: 'commandId', name: 'Command ID', minWidth: 300, maxWidth: 300, fieldName: 'commandId' }, { key: 'parentId', name: 'Parent ID', minWidth: 300, maxWidth: 300, onRender: (a: CommandAuditEntity) => onRenderParentId(a?.parentId) }, { key: 'command', name: 'Command', minWidth: 300, maxWidth: 10000, fieldName: 'command' }, { key: 'runtimeStatus', name: 'Runtime Status', minWidth: 100, maxWidth: 100, fieldName: 'runtimeStatus' }, { key: 'customStatus', name: 'Custom Status', minWidth: 100, maxWidth: 100, fieldName: 'customStatus' }, { key: 'created', name: 'Created', minWidth: 200, onRender: (a: CommandAuditEntity) => onRenderDate(a?.created) }, { key: 'updated', name: 'Updated', minWidth: 200, onRender: (a: CommandAuditEntity) => onRenderDate(a?.updated) }, ]; return ( <> <ContentProgress progressHidden={!auditEntriesLoading && !auditCommandsLoading && !auditEntryLoading} /> <Stack tokens={{ childrenGap: '20px' }}> <ContentSearch placeholder='Filter audit records' onChange={(_ev, val) => setItemFilter(val)}> <Stack horizontal tokens={{ childrenGap: '20px' }} style={{ marginLeft: '10px' }}> <Stack horizontal tokens={{ childrenGap: '10px' }}> <Stack className='ms-SearchBox-iconContainer' theme={theme} style={iconContainerStyle}> <Icon theme={theme} iconName='Calendar' className='ms-SearchBox-icon' /> </Stack> <Dropdown theme={theme} title="Time range" options={timeRangeOptions} onChange={(e, o) => setSelectedTimeRange(o?.key as string)} styles={{ dropdown: { minWidth: 250 } }} /> </Stack> <Stack horizontal tokens={{ childrenGap: '10px' }} > <Stack className='ms-SearchBox-iconContainer' theme={theme} style={iconContainerStyle}> <Icon theme={theme} iconName='ReturnKey' className='ms-SearchBox-icon' /> </Stack> <Dropdown theme={theme} title="Command" options={auditCommands?.map(ac => ({ key: ac, text: ac } as IDropdownOption)) ?? []} multiSelect onChange={(e, o) => setSelectedCommands((o?.selected ?? false) ? [...selectedCommands, (o?.key ?? o?.text) as string] : selectedCommands.filter(c => c !== ((o?.key ?? o?.text) as string)))} styles={{ dropdown: { minWidth: 250 } }} /> </Stack> <IconButton theme={theme} iconProps={{ iconName: 'Refresh' }} onClick={() => queryClient.invalidateQueries(['org', org?.id, 'audit'])} /> </Stack> </ContentSearch> <ContentList noCheck noSearch columns={columns} items={auditEntries ? itemFilter ? auditEntries.filter(i => _applyFilter(i, itemFilter)) : auditEntries : undefined} onItemInvoked={(entry) => setSelectedEntryId(entry.commandId)} filterPlaceholder='Filter audit records' noDataTitle='Not audit records match your query' noDataDescription='Try changing your query parameters' noDataImage={collaboration} /> </Stack> <Lightbox title={`Command: ${auditEntry?.command} (${auditEntry?.commandId})`} titleSize='xxLargePlus' isOpen={(!!selectedEntryId && !!auditEntry)} onDismiss={() => setSelectedEntryId(undefined)}> <Pivot selectedKey={pivotKey} onLinkClick={(i, e) => setPivotKey(i?.props.itemKey ?? 'Details')} styles={{ root: { height: '100%', marginBottom: '12px' } }}> <PivotItem headerText='Details' itemKey='Details'> <div style={{ height: 'calc(100vh - 320px)', position: 'relative', maxHeight: 'inherit' }}> <ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto}> <JSONPretty data={auditEntry ? JSON.stringify(auditEntry) : {}} /> </ScrollablePane> </div> </PivotItem> <PivotItem headerText='Command' itemKey='Command'> <div style={{ height: 'calc(100vh - 320px)', position: 'relative', maxHeight: 'inherit' }}> <ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto}> <JSONPretty data={auditEntry?.commandJson} /> </ScrollablePane> </div> </PivotItem> <PivotItem headerText='Result' itemKey='Result'> <div style={{ height: 'calc(100vh - 320px)', position: 'relative', maxHeight: 'inherit' }}> <ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto}> <JSONPretty data={auditEntry?.resultJson} /> </ScrollablePane> </div> </PivotItem> </Pivot> </Lightbox> </> ); }
the_stack
import * as vscode from 'vscode'; import { PXML, PXMLMember, notifications, getFileListFromPXML, zipFiles, getVSCodeSetting, getFilteredFileList, dxService, } from '../services'; import * as path from 'path'; import klaw = require('klaw'); import { getAuraNameFromFileName, outputToString, getAnyTTMetadataFromPath } from '../parsers'; import * as xml2js from 'xml2js'; import * as fs from 'fs-extra'; import { isEmptyUndOrNull, toArray } from '../util'; import { DeployResult } from 'jsforce'; import { FCCancellationToken, ForcecodeCommand } from '.'; import { IMetadataObject } from '../forceCode'; import { getSrcDir, VSCODE_SETTINGS } from '../services/configuration'; export class DeployPackage extends ForcecodeCommand { constructor() { super(); this.commandName = 'ForceCode.deployPackage'; this.cancelable = true; this.name = 'Deploying package'; this.hidden = false; this.description = 'Deploy your package.'; this.detail = 'Deploy from a package.xml file or choose files to deploy'; this.icon = 'package'; this.label = 'Deploy Package'; } public command() { return deploy(this.cancellationToken); } } let deployOptions: any = { checkOnly: true, ignoreWarnings: false, rollbackOnError: true, singlePackage: true, allowMissingFiles: true, }; function deploy(cancellationToken: FCCancellationToken) { let options: vscode.QuickPickItem[] = [ { label: 'Deploy from package.xml', detail: 'If you have a package.xml file you can deploy based off of the contents of this file', }, { label: 'Choose files', detail: 'WARNING: This will overwrite your package.xml file and deploy any destructiveChanges.xml files!!!', }, ]; let config: {} = { matchOnDescription: true, matchOnDetail: true, placeHolder: 'Choose files to deploy', }; return vscode.window.showQuickPick(options, config).then((choice) => { if (!choice) { return Promise.resolve(); } if (choice.label === 'Choose files') { return getFileList() .then(showFileList) .then(createPackageXML) .then(getFileListFromPXML) .then((files) => { return deployFiles(files, cancellationToken); }); } else { return getFileListFromPXML().then((files) => { return deployFiles(files, cancellationToken); }); } }); function getFileList(): Promise<string[]> { return new Promise((resolve) => { let fileList: string[] = []; klaw(getSrcDir()) .on('data', (file) => { if ( file.stats.isFile() && !file.path.match(/resource\-bundles.*\.resource.*$/) && !( vscode.window.forceCode.config.spaDist !== '' && file.path.indexOf(vscode.window.forceCode.config.spaDist) !== -1 ) && !file.path.endsWith('-meta.xml') && path.dirname(file.path) !== getSrcDir() ) { if (file.path.indexOf(path.join(getSrcDir(), 'aura')) !== -1) { const auraName = getAuraNameFromFileName(file.path, 'aura'); if (auraName) { const auraPath: string = path.join(getSrcDir(), 'aura', auraName); if (fileList.indexOf(auraPath) === -1) { fileList.push(auraPath); } } // this check will exclude files like package.xml } else if (file.path.indexOf(path.join(getSrcDir(), 'lwc')) !== -1) { const lwcName = getAuraNameFromFileName(file.path, 'lwc'); if (lwcName) { const lwcPath: string = path.join(getSrcDir(), 'lwc', lwcName); if (fileList.indexOf(lwcPath) === -1) { fileList.push(lwcPath); } } // this check will exclude files like package.xml } else if (file.path.split(getSrcDir()).length > 1) { fileList.push(file.path); } } }) .on('end', () => { resolve(getFilteredFileList(fileList.sort())); }) .on('error', (err: Error, item: klaw.Item) => { notifications.writeLog(`ForceCode: Error reading ${item.path}. Message: ${err.message}`); }); }); } function showFileList(files: string[]): Promise<string[]> { return new Promise((resolve, reject) => { let options: vscode.QuickPickItem[] = files .map((file) => { const fname = file.split(path.sep).pop(); return { label: fname || '', detail: file, }; }) .filter((file) => file.label !== ''); let config: {} = { matchOnDescription: true, matchOnDetail: true, placeHolder: files.length === 0 ? 'No files in the current project' : 'Choose files to deploy', canPickMany: true, }; vscode.window.showQuickPick(options, config).then((files) => { if (isEmptyUndOrNull(files)) { reject(cancellationToken.cancel()); } let theFiles: string[] = []; toArray(files).forEach((file) => { if (file) { theFiles.push(file.detail); } }); resolve(theFiles); }); }); } } export function createPackageXML(files: string[], lwcPackageXML?: string): Promise<any> { return new Promise((resolve, reject) => { let types: PXMLMember[] = []; files.forEach((file) => { let fileTT: IMetadataObject | undefined = getAnyTTMetadataFromPath(file); if (!fileTT) { reject(); return; } let member: string | undefined; if (fileTT.xmlName === 'AuraDefinitionBundle') { member = getAuraNameFromFileName(file, 'aura'); } else if (fileTT.xmlName === 'LightningComponentBundle') { member = getAuraNameFromFileName(file, 'lwc'); } else if (fileTT.inFolder) { const file2 = file.split(getSrcDir() + path.sep).pop(); member = file2?.substring(file2.indexOf(path.sep) + 1); } else { member = file.split(path.sep).pop(); } const lIndexOfP = member?.lastIndexOf('.') || 0; member = lIndexOfP > 0 ? member?.substring(0, lIndexOfP) : member; if (member) { member = member.replace('\\', '/'); const index: number = findMDTIndex(types, fileTT.xmlName); const folderMeta = member.split('/')[0]; const memberIndex: number = index !== -1 ? findMemberIndex(types, index, folderMeta) : -1; if (index !== -1) { types[index].members.push(member); if (fileTT.inFolder && memberIndex === -1) { types[index].members.push(folderMeta); } } else { let newMem: PXMLMember = { members: [member], name: fileTT.xmlName, }; if (fileTT.inFolder) { newMem.members.push(folderMeta); } types.push(newMem); } } }); resolve(buildPackageXMLFile(types, lwcPackageXML)); }); function findMDTIndex(types: PXMLMember[], type: string) { return types.findIndex((curType) => { return curType.name === type; }); } function findMemberIndex(types: PXMLMember[], index: number, member: string) { return types[index].members.findIndex((curType) => { return curType === member; }); } } export function buildPackageXMLFile(types: PXMLMember[], lwcPackageXML?: string) { let packObj: PXML = { Package: { types: types, version: vscode.window.forceCode.config.apiVersion || getVSCodeSetting(VSCODE_SETTINGS.defaultApiVersion), }, }; const builder = new xml2js.Builder(); let xml: string = builder .buildObject(packObj) .replace('<Package>', '<Package xmlns="http://soap.sforce.com/2006/04/metadata">') .replace(' standalone="yes"', ''); fs.outputFileSync(path.join(lwcPackageXML || getSrcDir(), 'package.xml'), xml); } export function deployFiles( files: string[], cancellationToken: FCCancellationToken, lwcPackageXML?: string ): Promise<any> { const deployPath: string = getSrcDir(); if (isEmptyUndOrNull(files)) { return Promise.resolve(); } if (vscode.window.forceCode.config.useSourceFormat) { return dxService .deploySourceFormat( path.join(vscode.window.forceCode.storageRoot, 'package.xml'), cancellationToken, true ) .then(finished) .catch(finished); } let zip = zipFiles(files, deployPath, lwcPackageXML); Object.assign(deployOptions, vscode.window.forceCode.config.deployOptions); if (deployOptions.testLevel === 'Default') { delete deployOptions.testLevel; } notifications.showLog(); return new Promise((resolve, reject) => { return checkDeployStatus( vscode.window.forceCode.conn.metadata.deploy(zip, deployOptions), resolve, reject ); }) .then(finished) .catch(finished); // ======================================================================================================================================= function checkDeployStatus( deployResult: DeployResult, resolveFunction: any, rejectFunction: any ) { if (cancellationToken.isCanceled()) { // TODO: Find a way to cancel the deployment here. Currently, the deployment still occurs in the background return rejectFunction(); } else { return deployResult.check(function (err, res) { if (err) { return rejectFunction(err); } if (res.done) { return deployResult.complete(function (err, res) { if (err) { return rejectFunction(err); } else { return resolveFunction(res); } }); } else { setTimeout(() => { checkDeployStatus(deployResult, resolveFunction, rejectFunction); }, 2000); } }); } } function finished(res: any) /*Promise<any>*/ { if (cancellationToken.isCanceled()) { return Promise.reject(); } if (res.status && res.status !== 'Failed') { notifications.showStatus('ForceCode: Deployed $(thumbsup)'); } else if (!res.status) { let depId: string; const message: string = res.message || res; if (res.id) { depId = res.id; } else { depId = (res.message || res).split(' = ').pop(); } res = { status: 'Failed', message: message }; if (!message.startsWith('Polling time out')) { return res; // we don't know what happened so just throw it } notifications .showError('ForceCode: Deployment timed out. View details status in the org?', 'Yes', 'No') .then((choice) => { if (choice === 'Yes') { vscode.commands.executeCommand( 'ForceCode.openFileInOrg', `lightning/setup/DeployStatus/page?address=%2Fchangemgmt%2FmonitorDeploymentsDetails.apexp%3FasyncId%3D${depId}%26retURL%3D%252Fchangemgmt%252FmonitorDeployment.apexp` ); } }); } notifications.writeLog(outputToString(res).replace(/{/g, '').replace(/}/g, '')); return res; } }
the_stack
import * as React from 'react'; import styles from '../../webparts/siteDesigns/components/SiteDesigns.module.scss'; import { IAddSiteScriptToSiteDesignProps } from './IAddSiteScriptToSiteDesignProps'; import { escape } from '@microsoft/sp-lodash-subset'; import spservice from '../../services/spservices'; import { panelMode } from '../../webparts/siteDesigns/components/IEnumPanel'; import * as strings from 'SiteDesignsWebPartStrings'; import { IAddSiteScriptToSiteDesignState } from './IAddSiteScriptToSiteDesignState'; import { SiteScriptInfo, SiteScriptUpdateInfo, SiteDesignCreationInfo, SiteDesignUpdateInfo } from '@pnp/sp'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { Toggle } from 'office-ui-fabric-react/lib/Toggle'; import { IImageProps, Image, ImageFit } from 'office-ui-fabric-react/lib/Image'; import { ISiteScript } from '../../types/ISiteScript'; import { Dropdown, IDropdown, DropdownMenuItemType, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { ActionButton } from 'office-ui-fabric-react/lib/Button'; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar'; import { getGUID } from '@pnp/common'; import { FieldTextRenderer } from "@pnp/spfx-controls-react/lib/FieldTextRenderer"; export default class AddSiteScriptToSiteDesign extends React.Component<IAddSiteScriptToSiteDesignProps, IAddSiteScriptToSiteDesignState> { private spService: spservice; private siteScripts: SiteScriptInfo[]; private currentSiteScriptsIds: string[] = []; private AddScriptDialog = React.lazy(() => import('../AddSiteScript/AddSiteScript' /* webpackChunkName: "addscriptdialog" */)); public constructor(props) { super(props); // Initialize state this.state = ({ isLoading: false, readOnly: true, showPanel: false, panelMode: panelMode.New, showError: false, errorMessage: '', disableSaveButton: true, siteScriptsList: [], selectedItems: [], showPanelAddScript: false, saving: false, }); this.currentSiteScriptsIds = this.props.siteDesignInfo.SiteScriptIds.split(','); // Init class services this.spService = new spservice(this.props.context); // Register event handlers this.onCancel = this.onCancel.bind(this); this.onChangeMultiSelect = this.onChangeMultiSelect.bind(this); this.onAddScript = this.onAddScript.bind(this); this.onDismissAddScriptPanel = this.onDismissAddScriptPanel.bind(this); this.onSave = this.onSave.bind(this); } /** * * @private * @param {React.MouseEvent<HTMLButtonElement>} ev * @memberof AddSiteDesign */ private onCancel(ev: React.MouseEvent<HTMLButtonElement>) { ev.preventDefault(); this.props.onDismiss(); } /** * Save SiteDesign Event * * @private * @param {React.MouseEvent<HTMLButtonElement>} ev * @memberof AddSiteDesign */ private async onSave(ev: React.MouseEvent<HTMLButtonElement>) { ev.preventDefault(); try { for (const item of this.state.selectedItems) { this.currentSiteScriptsIds.push(item); } const siteDesignUpdateInfo: SiteDesignUpdateInfo = { Id: this.props.siteDesignInfo.Id, SiteScriptIds: this.currentSiteScriptsIds }; this.setState({ saving: true, disableSaveButton: true }); const result = await this.spService.updateSiteDesign(siteDesignUpdateInfo); this.props.onDismiss(true); } catch (error) { console.log(error.message); this.setState({ saving: false, disableSaveButton: true, showError: true, errorMessage: error.message }); } } /** * Add SiteScrit Event * * @private * @param {React.MouseEvent<HTMLButtonElement>} ev * @memberof AddSiteDesign */ private onAddScript(ev: React.MouseEvent<HTMLButtonElement>) { ev.preventDefault(); this.setState({ showPanelAddScript: true }); } private onDismissAddScriptPanel(refresh: boolean) { this.setState({ showPanelAddScript: false }); if (refresh) { this.loadSiteScripts(); } } /** * Check if SiteScript already exists in Site Design * * @private * @param {string} siteScriptId * @returns * @memberof AddSiteScriptToSiteDesign */ private async checkSiteScriptExists(siteScriptId: string) { let found: boolean = false; for (const currentSitescriptId of this.currentSiteScriptsIds) { if (currentSitescriptId === siteScriptId) { found = true; break; } } return found; } /** * Load SiteScript * @private * @memberof AddSiteDesign */ private async loadSiteScripts() { this.siteScripts = await this.spService.getSiteScripts(); let siteScriptsList: IDropdownOption[] = []; if (this.siteScripts) { for (const siteScript of this.siteScripts) { const exists = await this.checkSiteScriptExists(siteScript.Id); if (!exists) { siteScriptsList.push({ key: siteScript.Id, text: siteScript.Title }); } } this.setState({ siteScriptsList: siteScriptsList.sort() }); } } // Component Did Mount /** * * @memberof AddSiteDesign */ public async componentDidMount() { // LoadTenantProperties await this.loadSiteScripts(); } /** * * * @memberof AddSiteDesign */ public async onChangeMultiSelect(event: React.FormEvent<HTMLDivElement>, item: IDropdownOption) { const updatedSelectedItem = this.state.selectedItems ? this.copyArray(this.state.selectedItems) : []; if (item.selected) { // add the option if it's checked updatedSelectedItem.push(item.key); this.setState({ errorMessage: '', selectedItems: updatedSelectedItem, disableSaveButton: false }); } else { // remove the option if it's unchecked const currIndex = updatedSelectedItem.indexOf(item.key); if (currIndex > -1) { updatedSelectedItem.splice(currIndex, 1); } this.setState({ errorMessage: '', selectedItems: updatedSelectedItem, disableSaveButton: updatedSelectedItem.length > 0 ? false : true }); } } /** * * @memberof AddSiteDesign */ public copyArray(array: any[]): any[] { const newArray: any[] = []; for (let i = 0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * On Render * * @returns {React.ReactElement<IAddSiteDesignProps>} * @memberof AddSiteDesign */ public render(): React.ReactElement<IAddSiteScriptToSiteDesignProps> { return ( <div className={styles.siteDesigns}> <Panel isOpen={this.props.showPanel} onDismiss={this.onCancel} type={PanelType.medium} headerText={strings.AddSiteScriptToSiteDesignPanelTitle}> <TextField label={strings.AddSiteDesignTitleLabel} readOnly={this.state.readOnly} value={this.props.siteDesignInfo.Title} style={{backgroundColor: "#f8f8f8"}} /> <TextField label={"WebTemplate"} readOnly={this.state.readOnly} value={this.props.siteDesignInfo.WebTemplate} style={{backgroundColor: "#f8f8f8"}} /> <TextField label={strings.AddSiteDesignDescriptionLabel} readOnly={this.state.readOnly} value={this.props.siteDesignInfo.Description} style={{backgroundColor: "#f8f8f8"}} /> <br /> { this.props.siteDesignInfo.PreviewImageUrl && <Image src={this.props.siteDesignInfo ? this.props.siteDesignInfo.PreviewImageUrl : ''} imageFit={ImageFit.cover} width={200} height={200} /> } <Toggle defaultChecked={this.props.siteDesignInfo.IsDefault} label={strings.AddSiteDesignIsDefaultLabel} onText="On" offText="Off" disabled /> <div style={{ paddingTop: '10px', textAlign: 'right' }}> <ActionButton data-automation-id="test" iconProps={{ iconName: 'Add' }} allowDisabledFocus={true} title={strings.actionButtonTitle} onClick={this.onAddScript} > Add SiteScript </ActionButton> </div> <div> <Dropdown placeholder={strings.DropDownSelectSiteScriptPlaceHolder} label={strings.DropDownSelectSiteScriptLabel} selectedKeys={this.state.selectedItems} onChange={this.onChangeMultiSelect} multiSelect options={this.state.siteScriptsList} /> </div> <React.Suspense fallback={<div>Loading...</div>}> <this.AddScriptDialog hideDialog={!this.state.showPanelAddScript} onDismiss={this.onDismissAddScriptPanel} context={this.props.context} /> </React.Suspense> <br /> <DialogFooter> { this.state.saving && <div style={{ display: "inline-block", marginRight: '10px', verticalAlign: 'middle' }}> <Spinner size={SpinnerSize.small} ariaLive="assertive" /> </div> } <PrimaryButton onClick={this.onSave} text={strings.AddSiteScriptToSiteDesignPanelButtonSaveText} disabled={this.state.disableSaveButton} /> <DefaultButton onClick={this.onCancel} text={strings.AddSiteScriptToSiteDesignPanelButtonCancelText} /> </DialogFooter> { this.state.showError && <div style={{ marginTop: '15px' }}> <MessageBar messageBarType={MessageBarType.error} > <span>{this.state.errorMessage}</span> </MessageBar> </div> } </Panel> </div> ); } }
the_stack
import * as assert from "power-assert"; import fs = require("fs"); import path = require("path"); import childProcess = require("child_process"); import stream = require("stream"); import mkdirp = require("mkdirp"); import lib = require("../lib/"); function collectFileName(dirName: string): string[] { let fileName: string[] = []; fs .readdirSync(dirName) .forEach((name: string) => { let newName = dirName + "/" + name; let stats = fs.statSync(newName); if (stats.isDirectory()) { fileName = fileName.concat(collectFileName(newName)); } else if (stats.isFile()) { fileName.push(newName); } }); return fileName; } interface ExecResult { status: number; stdout: string; stderr: string; } function exec(cmd: string, args: string[], options: childProcess.SpawnOptions): Promise<ExecResult> { let process = childProcess.spawn(cmd, args, options); let stdout = ""; let stderr = ""; process.stdout.on("data", (data: Buffer) => stdout += data.toString()); process.stderr.on("data", (data: Buffer) => stderr += data.toString()); return new Promise((resolve, _reject) => { process.on("exit", (status: number) => { resolve({ status: status, stdout: stdout, stderr: stderr, }); }); }); } function checkByTslint(configFileName: string, tsfileName: string, errorExpected: boolean): Promise<boolean> { let process = childProcess.spawn("./node_modules/.bin/tslint", ["-c", configFileName, tsfileName]); let stdout = ""; process.stdout.on("data", (data: any) => { stdout += data.toString(); }); // @ts-ignore let stderr = ""; process.stderr.on("data", (data: any) => { stderr += data.toString(); }); return new Promise((resolve, reject) => { process.on("exit", (code: number) => { let success = !code; // 0 - exit with success if (!errorExpected) { // expected error if (success) { resolve(true); } else { reject(tsfileName + " must be a good code.\n" + stdout); } } else { // expected success if (success) { reject(tsfileName + " must be a bad code."); } else { resolve(true); } } }); }); } describe("tsfmt test", () => { let fixtureDir = "./test/fixture"; let expectedDir = "./test/expected"; describe("processFiles function", () => { let fileNames = collectFileName(fixtureDir); fileNames .filter(fileName => /\.tsx?$/.test(fileName)) .forEach(fileName => { let ignoreList: string[] = [ ]; if (ignoreList.indexOf(fileName) !== -1) { it.skip(fileName, () => { false; }); return; } if (fileName.indexOf("./test/fixture/specified-config/") === 0) { // uses later. return; } it(fileName, () => { return lib .processFiles([fileName], { dryRun: true, replace: false, verify: false, tsconfig: true, tsconfigFile: null, tslint: true, tslintFile: null, editorconfig: true, vscode: true, vscodeFile: null, tsfmt: true, tsfmtFile: null, }) .then(resultMap => { let result = resultMap[fileName]; assert(result !== null); assert(result.error === false); let expectedTsFileName = fileName.replace(fixtureDir, expectedDir); // console.log(fileName, expectedFileName); if (!fs.existsSync(expectedTsFileName)) { mkdirp.sync(path.dirname(expectedTsFileName)); fs.writeFileSync(expectedTsFileName, result.dest); } let expected = fs.readFileSync(expectedTsFileName, "utf-8"); assert(expected === result.dest); let expectedSettingsFileName = expectedTsFileName.replace(/\.tsx?$/, ".json"); if (!fs.existsSync(expectedSettingsFileName)) { fs.writeFileSync(expectedSettingsFileName, JSON.stringify(result.settings, null, 2)); } let expectedSettings = lib.parseJSON(fs.readFileSync(expectedSettingsFileName, "utf-8")); assert.deepEqual(expectedSettings, result.settings); let tslintConfigName = path.dirname(fileName) + "/tslint.json"; if (!fs.existsSync(tslintConfigName)) { return null; } if (fileName === "./test/fixture/tslint/indent/main.ts") { // NOTE indent enforces consistent indentation levels (currently disabled). return null; } return Promise.all([ checkByTslint(tslintConfigName, fileName, true), checkByTslint(tslintConfigName, expectedTsFileName, false), ]).then(() => null); }); }); }); it("verify unformatted file", () => { let fileName = "./test/fixture/tsfmt/a/main.ts"; return lib .processFiles([fileName], { dryRun: true, replace: false, verify: true, tsconfig: true, tsconfigFile: null, tslint: true, tslintFile: null, editorconfig: true, vscode: true, vscodeFile: null, tsfmt: true, tsfmtFile: null, }) .then(resultMap => { assert(resultMap[fileName].error); assert(resultMap[fileName].message === "./test/fixture/tsfmt/a/main.ts is not formatted\n"); }); }); }); describe("processStream function", () => { let fileName = "test/fixture/default/main.ts"; it(fileName, () => { let input = new stream.Readable(); input.push(`class Sample{getString():string{return "hi!";}}`); input.push(null); return lib .processStream(fileName, input, { dryRun: true, replace: false, verify: false, tsconfig: true, tsconfigFile: null, tslint: true, tslintFile: null, editorconfig: true, vscode: true, vscodeFile: null, tsfmt: true, tsfmtFile: null, }) .then(result => { assert(result !== null); assert(result.error === false); assert(result.dest === "class Sample { getString(): string { return \"hi!\"; } }"); }); }); }); describe("use specified config", () => { interface Matrix { name: string; settings: Partial<lib.Options>; targetFile: string; } const list: Matrix[] = [ { name: "tsconfig.json", settings: { tsconfigFile: "alt-tsconfig.json", }, targetFile: "./test/fixture/specified-config/tsconfig/main.ts", }, { name: "tslint.json", settings: { tslintFile: "alt-tslint.json", }, targetFile: "./test/fixture/specified-config/tslint/main.ts", }, { name: "tsfmt.json", settings: { tsfmtFile: "alt-tsfmt.json", }, targetFile: "./test/fixture/specified-config/tsfmt/main.ts", }, { name: "vscode settings.json", settings: { vscodeFile: "alt-vscode-settings.json", }, targetFile: "./test/fixture/specified-config/vscode/main.ts", }, ]; list.forEach(matrix => { it(`uses specified ${matrix.name} file`, () => { return lib .processFiles([matrix.targetFile], Object.assign({}, { dryRun: true, replace: false, verify: false, tsconfig: true, tsconfigFile: null, tslint: true, tslintFile: null, editorconfig: true, vscode: true, vscodeFile: null, tsfmt: true, tsfmtFile: null, }, matrix.settings)) .then(resultMap => { let result = resultMap[matrix.targetFile]; assert(result !== null); assert(result.error === false); let expectedTsFileName = matrix.targetFile.replace(fixtureDir, expectedDir); if (!fs.existsSync(expectedTsFileName)) { mkdirp.sync(path.dirname(expectedTsFileName)); fs.writeFileSync(expectedTsFileName, result.dest); } let expected = fs.readFileSync(expectedTsFileName, "utf-8"); assert(expected === result.dest); let expectedSettingsFileName = expectedTsFileName.replace(/\.ts$/, ".json"); if (!fs.existsSync(expectedSettingsFileName)) { fs.writeFileSync(expectedSettingsFileName, JSON.stringify(result.settings, null, 2)); } let expectedSettings = lib.parseJSON(fs.readFileSync(expectedSettingsFileName, "utf-8")); assert.deepEqual(expectedSettings, result.settings); }); }); }); }); describe("CLI test", () => { it("should reformat files specified at files in tsconfig.json", () => { return exec(path.resolve("./bin/tsfmt"), [], { cwd: path.resolve("./test/cli/files") }).then(result => { assert.equal(result.status, 0); assert.equal(result.stdout.trim(), ` class TestCLI { method() { } } `.trim().replace(/\n/g, "\r\n")); }); }); it("should reformat files specified at include, exclude in tsconfig.json", () => { return exec(path.resolve("./bin/tsfmt"), [], { cwd: path.resolve("./test/cli/includeExclude") }).then(result => { assert.equal(result.status, 0); assert.equal(result.stdout.trim(), ` export class TestCLI { method() { } } `.trim().replace(/\n/g, "\r\n")); }); }); it("should pickup files from --useTsconfig specified tsconfig.json", () => { return exec(path.resolve("./bin/tsfmt"), ["--verify", "--useTsconfig", "./tsconfig.main.json"], { cwd: path.resolve("./test/cli/useTsconfig") }).then(result => { assert.equal(result.status, 1); assert.equal(result.stdout.trim(), ""); assert.equal(result.stderr.replace(process.cwd(), "**").trim(), ` **/test/cli/useTsconfig/include.ts is not formatted `.trim().replace(/\n/g, "\r\n")); }); }); }); });
the_stack
import {Group, Intersection, Material as ThreeMaterial, Mesh, MeshStandardMaterial, Object3D, Raycaster} from 'three'; import {CorrelatedSceneGraph, GLTFElementToThreeObjectMap, ThreeObjectSet} from '../../three-components/gltf-instance/correlated-scene-graph.js'; import {GLTF, GLTFElement, Material as GLTFMaterial} from '../../three-components/gltf-instance/gltf-2.0.js'; import {Model as ModelInterface} from './api.js'; import {$setActive, $variantSet, Material} from './material.js'; import {$children, Node, PrimitiveNode} from './nodes/primitive-node.js'; import {$correlatedObjects, $sourceObject} from './three-dom-element.js'; export const $materials = Symbol('materials'); const $hierarchy = Symbol('hierarchy'); const $roots = Symbol('roots'); export const $primitivesList = Symbol('primitives'); export const $loadVariant = Symbol('loadVariant'); export const $correlatedSceneGraph = Symbol('correlatedSceneGraph'); export const $prepareVariantsForExport = Symbol('prepareVariantsForExport'); export const $switchVariant = Symbol('switchVariant'); export const $threeScene = Symbol('threeScene'); export const $materialsFromPoint = Symbol('materialsFromPoint'); export const $materialFromPoint = Symbol('materialFromPoint'); export const $variantData = Symbol('variantData'); export const $availableVariants = Symbol('availableVariants'); const $modelOnUpdate = Symbol('modelOnUpdate'); const $cloneMaterial = Symbol('cloneMaterial'); // Holds onto temporary scene context information needed to perform lazy loading // of a resource. export class LazyLoader { gltf: GLTF; gltfElementMap: GLTFElementToThreeObjectMap; mapKey: GLTFElement; doLazyLoad: () => Promise<{set: ThreeObjectSet, material: ThreeMaterial}>; constructor( gltf: GLTF, gltfElementMap: GLTFElementToThreeObjectMap, mapKey: GLTFElement, doLazyLoad: () => Promise<{set: ThreeObjectSet, material: ThreeMaterial}>) { this.gltf = gltf; this.gltfElementMap = gltfElementMap; this.mapKey = mapKey; this.doLazyLoad = doLazyLoad; } } /** * Facades variant mapping data. */ export interface VariantData { name: string; index: number; } /** * A Model facades the top-level GLTF object returned by Three.js' GLTFLoader. * Currently, the model only bothers itself with the materials in the Three.js * scene graph. */ export class Model implements ModelInterface { private[$materials] = new Array<Material>(); private[$hierarchy] = new Array<Node>(); private[$roots] = new Array<Node>(); private[$primitivesList] = new Array<PrimitiveNode>(); private[$threeScene]: Object3D|Group; private[$modelOnUpdate]: () => void = () => {}; private[$correlatedSceneGraph]: CorrelatedSceneGraph; private[$variantData] = new Map<string, VariantData>(); constructor( correlatedSceneGraph: CorrelatedSceneGraph, onUpdate: () => void = () => {}) { this[$modelOnUpdate] = onUpdate; this[$correlatedSceneGraph] = correlatedSceneGraph; const {gltf, threeGLTF, gltfElementMap} = correlatedSceneGraph; this[$threeScene] = threeGLTF.scene; for (const [i, material] of gltf.materials!.entries()) { const correlatedMaterial = gltfElementMap.get(material) as Set<MeshStandardMaterial>; if (correlatedMaterial != null) { this[$materials].push(new Material( onUpdate, gltf, material, i, true, this[$variantData], correlatedMaterial)); } else { const elementArray = gltf['materials'] || []; const gltfMaterialDef = elementArray[i]; // Loads the three.js material. const capturedMatIndex = i; const materialLoadCallback = async () => { const threeMaterial = await threeGLTF.parser.getDependency( 'material', capturedMatIndex) as MeshStandardMaterial; // Adds correlation, maps the variant gltf-def to the // three material set containing the variant material. const threeMaterialSet = new Set<MeshStandardMaterial>(); gltfElementMap.set(gltfMaterialDef, threeMaterialSet); threeMaterialSet.add(threeMaterial); return {set: threeMaterialSet, material: threeMaterial}; }; // Configures the material for lazy loading. this[$materials].push(new Material( onUpdate, gltf, gltfMaterialDef, i, false, this[$variantData], correlatedMaterial, new LazyLoader( gltf, gltfElementMap, gltfMaterialDef, materialLoadCallback))); } } // Creates a hierarchy of Nodes. Allows not just for switching which // material is applied to a mesh but also exposes a way to provide API // for switching materials and general assignment/modification. // Prepares for scene iteration. const parentMap = new Map<object, Node>(); const nodeStack = new Array<Object3D>(); for (const object of threeGLTF.scene.children) { nodeStack.push(object); } // Walks the hierarchy and creates a node tree. while (nodeStack.length > 0) { const object = nodeStack.pop()!; let node: Node|null = null; if (object instanceof Mesh) { node = new PrimitiveNode( object as Mesh, this.materials, this[$variantData], correlatedSceneGraph); this[$primitivesList].push(node as PrimitiveNode); } else { node = new Node(object.name); } const parent: Node|undefined = parentMap.get(object); if (parent != null) { parent[$children].push(node); } else { this[$roots].push(node); } this[$hierarchy].push(node); for (const child of object.children) { nodeStack.push(child); parentMap.set(object, node); } } } /** * Materials are listed in the order of the GLTF materials array, plus a * default material at the end if one is used. * * TODO(#1003): How do we handle non-active scenes? */ get materials(): Material[] { return this[$materials]; } [$availableVariants]() { const variants = Array.from(this[$variantData].values()); variants.sort((a, b) => { return a.index - b.index; }); return variants.map((data) => { return data.name; }); } getMaterialByName(name: string): Material|null { const matches = this[$materials].filter(material => { return material.name === name; }); if (matches.length > 0) { return matches[0]; } return null; } /** * Intersects a ray with the Model and returns a list of materials whose * objects were intersected. */ [$materialsFromPoint](raycaster: Raycaster): Material[] { const hits = raycaster.intersectObject(this[$threeScene], true); // Map the object hits to primitives and then to the active material of // the primitive. return hits.map((hit: Intersection<Object3D>) => { const found = this[$hierarchy].find((node: Node) => { if (node instanceof PrimitiveNode) { const primitive = node as PrimitiveNode; if (primitive.mesh === hit.object) { return true; } } return false; }) as PrimitiveNode; if (found != null) { return found.getActiveMaterial(); } return null; }) as Material[]; } /** * Intersects a ray with the Model and returns the first material whose * object was intersected. */ [$materialFromPoint](raycaster: Raycaster): Material|null { const materials = this[$materialsFromPoint](raycaster); if (materials.length > 0) { return materials[0]; } return null; } /** * Switches model variant to the variant name provided, or switches to * default/initial materials if 'null' is provided. */ async[$switchVariant](variantName: string|null) { for (const primitive of this[$primitivesList]) { await primitive.enableVariant(variantName); } for (const material of this.materials) { material[$setActive](false); } // Marks the materials that are now in use after the variant switch. for (const primitive of this[$primitivesList]) { this.materials[primitive.getActiveMaterial().index][$setActive](true); } } async[$prepareVariantsForExport]() { const promises = new Array<Promise<void>>(); for (const primitive of this[$primitivesList]) { promises.push(primitive.instantiateVariants()); } await Promise.all(promises); } [$cloneMaterial](index: number, newMaterialName: string): Material { const material = this.materials[index]; if (!material.isLoaded) { console.error(`Cloning an unloaded material, call 'material.ensureLoaded() before cloning the material.`); } const threeMaterialSet = material[$correlatedObjects] as Set<MeshStandardMaterial>; // clones the gltf material data and updates the material name. const gltfSourceMaterial = JSON.parse(JSON.stringify(material[$sourceObject])) as GLTFMaterial; gltfSourceMaterial.name = newMaterialName; // Adds the source material clone to the gltf def. const gltf = this[$correlatedSceneGraph].gltf; gltf.materials!.push(gltfSourceMaterial); const clonedSet = new Set<MeshStandardMaterial>(); for (const [i, threeMaterial] of threeMaterialSet.entries()) { const clone = threeMaterial.clone() as MeshStandardMaterial; clone.name = newMaterialName + (threeMaterialSet.size > 1 ? '_inst' + i : ''); clonedSet.add(clone); } const clonedMaterial = new Material( this[$modelOnUpdate], this[$correlatedSceneGraph].gltf, gltfSourceMaterial, this[$materials].length, false, // Cloned as inactive. this[$variantData], clonedSet); this[$materials].push(clonedMaterial); return clonedMaterial; } createMaterialInstanceForVariant( originalMaterialIndex: number, newMaterialName: string, variantName: string, activateVariant: boolean = true): Material|null { let variantMaterialInstance: Material|null = null; for (const primitive of this[$primitivesList]) { const variantData = this[$variantData].get(variantName); // Skips the primitive if the variant already exists. if (variantData != null && primitive.variantInfo.has(variantData.index)) { continue; } // Skips the primitive if the source/original material does not exist. if (primitive.getMaterial(originalMaterialIndex) == null) { continue; } if (!this.hasVariant(variantName)) { this.createVariant(variantName); } if (variantMaterialInstance == null) { variantMaterialInstance = this[$cloneMaterial](originalMaterialIndex, newMaterialName); } primitive.addVariant(variantMaterialInstance, variantName) } if (activateVariant && variantMaterialInstance != null) { (variantMaterialInstance as Material)[$setActive](true); this.materials[originalMaterialIndex][$setActive](false); for (const primitive of this[$primitivesList]) { primitive.enableVariant(variantName); } } return variantMaterialInstance; } createVariant(variantName: string) { if (!this[$variantData].has(variantName)) { // Adds the name if it's not already in the list. this[$variantData].set( variantName, {name: variantName, index: this[$variantData].size} as VariantData); } else { console.warn(`Variant '${variantName}'' already exists`); } } hasVariant(variantName: string) { return this[$variantData].has(variantName); } setMaterialToVariant(materialIndex: number, targetVariantName: string) { if (this[$availableVariants]().find(name => name === targetVariantName) == null) { console.warn(`Can't add material to '${ targetVariantName}', the variant does not exist.'`); return; } if (materialIndex < 0 || materialIndex >= this.materials.length) { console.error(`setMaterialToVariant(): materialIndex is out of bounds.`); return; } for (const primitive of this[$primitivesList]) { const material = primitive.getMaterial(materialIndex); // Ensures the material exists on the primitive before setting it to a // variant. if (material != null) { primitive.addVariant(material, targetVariantName); } } } updateVariantName(currentName: string, newName: string) { const variantData = this[$variantData].get(currentName); if (variantData == null) { return; } variantData.name = newName; this[$variantData].set(newName, variantData!); this[$variantData].delete(currentName); } deleteVariant(variantName: string) { const variant = this[$variantData].get(variantName); if (variant == null) { return; } for (const material of this.materials) { if (material.hasVariant(variantName)) { material[$variantSet].delete(variant.index); } } for (const primitive of this[$primitivesList]) { primitive.deleteVariant(variant.index); } this[$variantData].delete(variantName); } }
the_stack
import { BigNumber } from "bignumber.js"; import memoize from "lodash/memoize"; import last from "lodash/last"; import find from "lodash/find"; import type { AccountLikeArray, AccountLike, Account, BalanceHistory, AccountPortfolio, CurrencyPortfolio, PortfolioRange, BalanceHistoryWithCountervalue, Portfolio, AssetsDistribution, TokenCurrency, CryptoCurrency, } from "../types"; import { getOperationAmountNumberWithInternals } from "../operation"; import { flattenAccounts, getAccountCurrency } from "../account/helpers"; import { getEnv } from "../env"; import { getPortfolioRangeConfig, getDates } from "./range"; export * from "./range"; type GetBalanceHistory = ( account: AccountLike, r: PortfolioRange ) => BalanceHistory; /** * generate an array of {daysCount} datapoints, one per day, * for the balance history of an account. * The last item of the array is the balance available right now. * @memberof account */ const getBalanceHistoryImpl: GetBalanceHistory = (account, r) => { const conf = getPortfolioRangeConfig(r); const history: Array<{ date: Date; value: BigNumber }> = []; let { balance } = account; const operationsLength = account.operations.length; let i = 0; // index of operation let t = new Date(); history.unshift({ date: t, value: balance, }); t = new Date((conf.startOf(t) as any) - 1); // end of yesterday for (let d = conf.count - 1; d > 0; d--) { // accumulate operations after time t while (i < operationsLength && account.operations[i].date > t) { balance = balance.minus( getOperationAmountNumberWithInternals(account.operations[i]) ); i++; } if (i === operationsLength) { // When there is no more operation, we consider we reached ZERO to avoid invalid assumption that balance was already available. balance = new BigNumber(0); } history.unshift({ date: t, value: BigNumber.max(balance, 0), }); t = new Date((t as any) - conf.increment); } return history; }; const accountRateHash = (account, r) => `${r}_${account.id}_${account.balance.toString()}_${ account.operations[0] ? account.operations[0].id : "" }`; export const getBalanceHistoryJS: GetBalanceHistory = memoize( getBalanceHistoryImpl, accountRateHash ); export const getBalanceHistory: GetBalanceHistory = (account, r) => { // try to find it in the account object const balanceHistory = account.balanceHistory; if ( balanceHistory && balanceHistory[r] && (<BalanceHistory>balanceHistory[r]).length > 1 ) { return <BalanceHistory>balanceHistory[r]; } // fallback on JS implementation return getBalanceHistoryJS(account, r); }; type GetBalanceHistoryWithCountervalue = ( account: AccountLike, r: PortfolioRange, calculateAccountCounterValue: ( arg0: TokenCurrency | CryptoCurrency, arg1: BigNumber, arg2: Date ) => BigNumber | null | undefined, useEffectiveFrom?: boolean ) => AccountPortfolio; // hash the "stable" part of the histo // only the latest datapoint is "unstable" meaning it always changes because it's the current date. const accountRateHashCVStable = (account, r, cvRef, useEffectiveFrom) => `${accountRateHash(account, r)}_${cvRef ? cvRef.toString() : "none"}_${ useEffectiveFrom ? "withEffectiveFrom" : "" }`; const accountCVstableCache = {}; const ZERO = new BigNumber(0); const percentageHighThreshold = 100000; const meaningfulPercentage = ( deltaChange: BigNumber | null | undefined, balanceDivider: BigNumber | null | undefined ): BigNumber | null | undefined => { if (deltaChange && balanceDivider && !balanceDivider.isZero()) { const percent = deltaChange.div(balanceDivider); if (percent.lt(percentageHighThreshold)) { return percent; } } }; export const getBalanceHistoryWithCountervalue: GetBalanceHistoryWithCountervalue = (account, r, calc, useEffectiveFrom = true) => { const history = getBalanceHistory(account, r); const cur = getAccountCurrency(account); // a high enough value so we can compare if something changes const cacheReferenceValue = new BigNumber("10").pow( 3 + cur.units[0].magnitude ); // pick a stable countervalue point in time to hash for the cache const cvRef = calc(cur, cacheReferenceValue, history[0].date); const mapFn = (p) => ({ ...p, countervalue: (cvRef && calc(cur, p.value, p.date)) || ZERO, }); const stableHash = accountRateHashCVStable( account, r, cvRef, useEffectiveFrom ); let stable = accountCVstableCache[stableHash]; const lastPoint = mapFn(history[history.length - 1]); const calcChanges = (h: BalanceHistoryWithCountervalue) => { // previous existing implementation here const from = h[0]; const to = h[h.length - 1]; const fromEffective = useEffectiveFrom ? find(h, (record) => record.value.isGreaterThan(0)) || from : from; return { countervalueReceiveSum: new BigNumber(0), // not available here countervalueSendSum: new BigNumber(0), cryptoChange: { value: to.value.minus(fromEffective.value), percentage: null, }, countervalueChange: { value: (to.countervalue || ZERO).minus( fromEffective.countervalue || ZERO ), percentage: meaningfulPercentage( (to.countervalue || ZERO).minus(fromEffective.countervalue || ZERO), fromEffective.countervalue ), }, }; }; if (!stable) { const h = history.map(mapFn); stable = { history: h, countervalueAvailable: !!cvRef, ...calcChanges(h), }; accountCVstableCache[stableHash] = stable; return stable; } const lastStable: any = last(stable.history); if (lastPoint.countervalue.eq(lastStable.countervalue)) { return stable; } const h = stable.history.slice(0, -1).concat(lastPoint); const copy = { ...stable, history: h, ...calcChanges(h) }; accountCVstableCache[stableHash] = copy; return copy; }; /** * calculate the total balance history for all accounts in a reference fiat unit * and using a CalculateCounterValue function (see countervalue helper) * NB the last item of the array is actually the current total balance. * @memberof account */ export function getPortfolio( topAccounts: Account[], range: PortfolioRange, calc: ( arg0: TokenCurrency | CryptoCurrency, arg1: BigNumber, arg2: Date ) => BigNumber | null | undefined ): Portfolio { const accounts: AccountLike[] = flattenAccounts(topAccounts); const availableAccounts: AccountLike[] = []; const unavailableAccounts: AccountLike[] = []; const histories: BalanceHistoryWithCountervalue[] = []; const changes: BigNumber[] = []; const countervalueReceiveSums: BigNumber[] = []; const countervalueSendSums: BigNumber[] = []; for (let i = 0; i < accounts.length; i++) { const account = accounts[i]; const r = getBalanceHistoryWithCountervalue(account, range, calc, false); if (r.countervalueAvailable) { availableAccounts.push(account); histories.push(r.history); changes.push(r.countervalueChange.value); countervalueReceiveSums.push(r.countervalueReceiveSum); countervalueSendSums.push(r.countervalueSendSum); } else { unavailableAccounts.push(account); } } const unavailableCurrencies: any[] = [ ...new Set(unavailableAccounts.map(getAccountCurrency)), ]; const balanceAvailable = accounts.length === 0 || availableAccounts.length > 0; const balanceHistory = getDates(range).map((date) => ({ date, value: ZERO, })); for (let i = 0; i < histories.length; i++) { const history = histories[i]; for (let j = 0; j < history.length; j++) { const res = balanceHistory[j]; if (res) { res.value = res.value.plus(history[j].countervalue); } } } const countervalueChangeValue: BigNumber = changes.reduce( (sum, v) => sum.plus(v), new BigNumber(0) ); const countervalueReceiveSum: BigNumber = countervalueReceiveSums.reduce( (sum, v) => sum.plus(v), new BigNumber(0) ); const countervalueSendSum: BigNumber = countervalueSendSums.reduce( (sum, v) => sum.plus(v), new BigNumber(0) ); // in case there were no receive, we just track the market change // weighted by the current balances let countervalueChangePercentage; if (getEnv("EXPERIMENTAL_ROI_CALCULATION")) { if (countervalueReceiveSum.isZero()) { countervalueChangePercentage = meaningfulPercentage( countervalueChangeValue, balanceHistory[0].value.plus(countervalueSendSum) ); } else { countervalueChangePercentage = meaningfulPercentage( countervalueChangeValue, countervalueReceiveSum ); } } else { countervalueChangePercentage = meaningfulPercentage( countervalueChangeValue, // in non experimental mode, we were dividing by first point balanceHistory[0].value ); } const ret = { balanceHistory, balanceAvailable, availableAccounts, unavailableCurrencies, accounts, range, histories, countervalueReceiveSum, countervalueSendSum, countervalueChange: { percentage: countervalueChangePercentage, value: countervalueChangeValue, }, }; return ret; } /** * calculate the total balance history for all accounts in a reference fiat unit * and using a CalculateCounterValue function (see countervalue helper) * NB the last item of the array is actually the current total balance. * @memberof account */ export function getCurrencyPortfolio( accounts: AccountLikeArray, range: PortfolioRange, calc: ( arg0: TokenCurrency | CryptoCurrency, arg1: BigNumber, arg2: Date ) => BigNumber | null | undefined ): CurrencyPortfolio { const histories: BalanceHistoryWithCountervalue[] = []; let countervalueAvailable = false; for (let i = 0; i < accounts.length; i++) { const account = accounts[i]; const r = getBalanceHistoryWithCountervalue(account, range, calc); histories.push(r.history); countervalueAvailable = r.countervalueAvailable; } const history = getDates(range).map((date) => ({ date, value: ZERO, countervalue: ZERO, })); for (let i = 0; i < histories.length; i++) { const h = histories[i]; for (let j = 0; j < h.length; j++) { const res = history[j]; res.value = res.value.plus(h[j].value); res.countervalue = res.countervalue.plus(h[j].countervalue); } } // previous existing implementation here const from = history[0]; const to = history[history.length - 1]; const fromEffective = (find(history, (record) => record.value.isGreaterThan(0)) as { date: Date; value: any; countervalue: any; }) || from; const cryptoChange = { value: to.value.minus(from.value), percentage: null, }; const countervalueChange = { value: (to.countervalue || ZERO).minus(fromEffective.countervalue || ZERO), percentage: meaningfulPercentage( (to.countervalue || ZERO).minus(fromEffective.countervalue || ZERO), fromEffective.countervalue ), }; const ret = { history, countervalueAvailable, accounts, range, histories, cryptoChange, countervalueChange, }; return ret; } export const defaultAssetsDistribution = { minShowFirst: 1, maxShowFirst: 6, showFirstThreshold: 0.95, }; export type AssetsDistributionOpts = typeof defaultAssetsDistribution; const assetsDistributionNotAvailable: AssetsDistribution = { isAvailable: false, list: [], showFirst: 0, sum: new BigNumber(0), }; const previousDistributionCache = { hash: "", data: assetsDistributionNotAvailable, }; export function getAssetsDistribution( topAccounts: Account[], calculateCountervalue: ( currency: TokenCurrency | CryptoCurrency, value: BigNumber ) => BigNumber | null | undefined, opts?: AssetsDistributionOpts ): AssetsDistribution { const { minShowFirst, maxShowFirst, showFirstThreshold } = { ...defaultAssetsDistribution, ...opts, }; let sum = new BigNumber(0); const idBalances = {}; const idCurrencies = {}; const accounts = flattenAccounts(topAccounts); for (let i = 0; i < accounts.length; i++) { const account = accounts[i]; const cur = getAccountCurrency(account); const id = cur.id; if (account.balance.isGreaterThan(0)) { idCurrencies[id] = cur; idBalances[id] = (idBalances[id] || new BigNumber(0)).plus( account.balance ); } } const idCountervalues = {}; for (const id in idBalances) { const countervalue = calculateCountervalue( idCurrencies[id], idBalances[id] ); if (countervalue) { idCountervalues[id] = countervalue; sum = sum.plus(countervalue); } } const idCurrenciesKeys = Object.keys(idCurrencies); if (idCurrenciesKeys.length === 0) { return assetsDistributionNotAvailable; } const isAvailable = !sum.isZero(); const hash = `${idCurrenciesKeys.length}_${sum.toString()}`; if (hash === previousDistributionCache.hash) { return previousDistributionCache.data; } const list = idCurrenciesKeys .map((id) => { const currency = idCurrencies[id]; const amount = idBalances[id]; const countervalue = idCountervalues[id] || new BigNumber(0); return { currency, countervalue, amount, distribution: isAvailable ? countervalue.div(sum).toNumber() : 0, }; }) .sort((a, b) => { const diff = b.countervalue.minus(a.countervalue).toNumber(); if (diff === 0) return a.currency.name.localeCompare(b.currency.name); return diff; }); let i; let acc = 0; for (i = 0; i < maxShowFirst && i < list.length; i++) { if (acc > showFirstThreshold) { break; } acc += list[i].distribution; } const showFirst = Math.max(minShowFirst, i); const data = { isAvailable, list, showFirst, sum, }; previousDistributionCache.hash = hash; previousDistributionCache.data = data; return data; }
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import '../settings_shared_css.js'; import '../settings_vars_css.js'; import '../controls/settings_textarea.js'; import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {assertNotReached} from 'chrome://resources/js/assert.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {flush, html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from '../i18n_setup.js'; export interface SettingsAddressEditDialogElement { $: { dialog: CrDialogElement, emailInput: CrInputElement, phoneInput: CrInputElement, saveButton: CrButtonElement, cancelButton: CrButtonElement, }; } const SettingsAddressEditDialogElementBase = I18nMixin(PolymerElement); export class SettingsAddressEditDialogElement extends SettingsAddressEditDialogElementBase { static get is() { return 'settings-address-edit-dialog'; } static get template() { return html`{__html_template__}`; } static get properties() { return { address: Object, title_: String, countries_: Array, /** * Updates the address wrapper. */ countryCode_: { type: String, observer: 'onUpdateCountryCode_', }, addressWrapper_: Object, phoneNumber_: String, email_: String, canSave_: Boolean, /** * True if honorifics are enabled. */ showHonorific_: { type: Boolean, value() { return loadTimeData.getBoolean('showHonorific'); } } }; } address: chrome.autofillPrivate.AddressEntry; private title_: string; private countries_: Array<chrome.autofillPrivate.CountryEntry>; private countryCode_: string|undefined; private addressWrapper_: Array<Array<AddressComponentUI>>; private phoneNumber_: string; private email_: string; private canSave_: boolean; private showHonorific_: boolean; private countryInfo_: CountryDetailManager = CountryDetailManagerImpl.getInstance(); connectedCallback() { super.connectedCallback(); this.countryInfo_.getCountryList().then(countryList => { this.countries_ = countryList; this.title_ = this.i18n(this.address.guid ? 'editAddressTitle' : 'addAddressTitle'); // |phoneNumbers| and |emailAddresses| are a single item array. // See crbug.com/497934 for details. this.phoneNumber_ = this.address.phoneNumbers ? this.address.phoneNumbers[0] : ''; this.email_ = this.address.emailAddresses ? this.address.emailAddresses[0] : ''; microTask.run(() => { if (Object.keys(this.address).length === 0 && countryList.length > 0) { // If the address is completely empty, the dialog is creating a new // address. The first address in the country list is what we suspect // the user's country is. this.address.countryCode = countryList[0].countryCode; } if (this.countryCode_ === this.address.countryCode) { this.updateAddressWrapper_(); } else { this.countryCode_ = this.address.countryCode; } }); }); // Open is called on the dialog after the address wrapper has been // updated. } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } /** * @return A CSS class to denote how long this entry is. */ private long_(setting: AddressComponentUI): string { return setting.component.isLongField ? 'long' : ''; } /** * Updates the wrapper that represents this address in the country's format. */ private updateAddressWrapper_() { // Default to the last country used if no country code is provided. const countryCode = this.countryCode_ || this.countries_[0].countryCode; this.countryInfo_.getAddressFormat(countryCode as string).then(format => { this.addressWrapper_ = format.components.flatMap(component => { // If this is the name field, add a honorific title row before the // name. const addHonorific = component.row[0].field === chrome.autofillPrivate.AddressField.FULL_NAME && this.showHonorific_; const row = component.row.map( component => new AddressComponentUI(this.address, component)); return addHonorific ? [[this.createHonorificAddressComponentUI(this.address)], row] : [row]; }); // Flush dom before resize and savability updates. flush(); this.updateCanSave_(); this.fire_('on-update-address-wrapper'); // For easier testing. if (!this.$.dialog.open) { this.$.dialog.showModal(); } }); } private updateCanSave_() { const inputs = this.$.dialog.querySelectorAll('.address-column, select') as NodeListOf<HTMLSelectElement|CrInputElement>; for (let i = 0; i < inputs.length; ++i) { if (inputs[i].value) { this.canSave_ = true; this.fire_('on-update-can-save'); // For easier testing. return; } } this.canSave_ = false; this.fire_('on-update-can-save'); // For easier testing. } private getCode_(country: chrome.autofillPrivate.CountryEntry): string { return country.countryCode || 'SPACER'; } private getName_(country: chrome.autofillPrivate.CountryEntry): string { return country.name || '------'; } private isDivision_(country: chrome.autofillPrivate.CountryEntry): boolean { return !country.countryCode; } private onCancelTap_() { this.$.dialog.cancel(); } /** * Handler for tapping the save button. */ private onSaveButtonTap_() { // The Enter key can call this function even if the button is disabled. if (!this.canSave_) { return; } // Set a default country if none is set. if (!this.address.countryCode) { this.address.countryCode = this.countries_[0].countryCode; } this.address.phoneNumbers = this.phoneNumber_ ? [this.phoneNumber_] : []; this.address.emailAddresses = this.email_ ? [this.email_] : []; this.fire_('save-address', this.address); this.$.dialog.close(); } /** * Syncs the country code back to the address and rebuilds the address * wrapper for the new location. */ private onUpdateCountryCode_(countryCode: string|undefined) { this.address.countryCode = countryCode; this.updateAddressWrapper_(); } private onCountryChange_() { const countrySelect = this.shadowRoot!.querySelector('select'); this.countryCode_ = countrySelect!.value; } /** * Propagates focus to the <select> when country row is focused * (e.g. using tab navigation). */ private onCountryRowFocus_() { this.shadowRoot!.querySelector('select')!.focus(); } /** * Prevents clicking random spaces within country row but outside of <select> * from triggering focus. */ private onCountryRowPointerDown_(e: Event) { if ((e.composedPath()[0] as HTMLElement).tagName !== 'SELECT') { e.preventDefault(); } } createHonorificAddressComponentUI( address: chrome.autofillPrivate.AddressEntry): AddressComponentUI { return new AddressComponentUI(address, { field: chrome.autofillPrivate.AddressField.HONORIFIC, fieldName: this.i18n('honorificLabel'), isLongField: true, placeholder: undefined, }); } } declare global { interface HTMLElementTagNameMap { 'settings-address-edit-dialog': SettingsAddressEditDialogElement; } } customElements.define( SettingsAddressEditDialogElement.is, SettingsAddressEditDialogElement); /** * Creates a wrapper against a single data member for an address. */ class AddressComponentUI { private address_: chrome.autofillPrivate.AddressEntry; component: chrome.autofillPrivate.AddressComponent; isTextArea: boolean; constructor( address: chrome.autofillPrivate.AddressEntry, component: chrome.autofillPrivate.AddressComponent) { Object.defineProperty(this, 'value', { get() { return this.getValue_(); }, set(newValue) { this.setValue_(newValue); }, }); this.address_ = address; this.component = component; this.isTextArea = component.field === chrome.autofillPrivate.AddressField.ADDRESS_LINES; } /** * Gets the value from the address that's associated with this component. */ private getValue_(): string|undefined { const address = this.address_; switch (this.component.field) { case chrome.autofillPrivate.AddressField.HONORIFIC: return address.honorific; case chrome.autofillPrivate.AddressField.FULL_NAME: // |fullNames| is a single item array. See crbug.com/497934 for // details. return address.fullNames ? address.fullNames[0] : undefined; case chrome.autofillPrivate.AddressField.COMPANY_NAME: return address.companyName; case chrome.autofillPrivate.AddressField.ADDRESS_LINES: return address.addressLines; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_1: return address.addressLevel1; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_2: return address.addressLevel2; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_3: return address.addressLevel3; case chrome.autofillPrivate.AddressField.POSTAL_CODE: return address.postalCode; case chrome.autofillPrivate.AddressField.SORTING_CODE: return address.sortingCode; case chrome.autofillPrivate.AddressField.COUNTRY_CODE: return address.countryCode; default: assertNotReached(); return ''; } } /** * Sets the value in the address that's associated with this component. */ private setValue_(value: string) { const address = this.address_; switch (this.component.field) { case chrome.autofillPrivate.AddressField.HONORIFIC: address.honorific = value; break; case chrome.autofillPrivate.AddressField.FULL_NAME: address.fullNames = [value]; break; case chrome.autofillPrivate.AddressField.COMPANY_NAME: address.companyName = value; break; case chrome.autofillPrivate.AddressField.ADDRESS_LINES: address.addressLines = value; break; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_1: address.addressLevel1 = value; break; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_2: address.addressLevel2 = value; break; case chrome.autofillPrivate.AddressField.ADDRESS_LEVEL_3: address.addressLevel3 = value; break; case chrome.autofillPrivate.AddressField.POSTAL_CODE: address.postalCode = value; break; case chrome.autofillPrivate.AddressField.SORTING_CODE: address.sortingCode = value; break; case chrome.autofillPrivate.AddressField.COUNTRY_CODE: address.countryCode = value; break; default: assertNotReached(); } } } export interface CountryDetailManager { /** * Gets the list of available countries. * The default country will be first, followed by a separator, followed by * an alphabetized list of countries available. */ getCountryList(): Promise<Array<chrome.autofillPrivate.CountryEntry>>; /** * Gets the address format for a given country code. */ getAddressFormat(countryCode: string): Promise<chrome.autofillPrivate.AddressComponents>; } /** * Default implementation. Override for testing. */ export class CountryDetailManagerImpl implements CountryDetailManager { getCountryList() { return new Promise<Array<chrome.autofillPrivate.CountryEntry>>(function( callback) { chrome.autofillPrivate.getCountryList(callback); }); } getAddressFormat(countryCode: string) { return new Promise<chrome.autofillPrivate.AddressComponents>(function( callback) { chrome.autofillPrivate.getAddressComponents(countryCode, callback); }); } static getInstance(): CountryDetailManager { return instance || (instance = new CountryDetailManagerImpl()); } static setInstance(obj: CountryDetailManager) { instance = obj; } } let instance: CountryDetailManager|null = null;
the_stack
import * as dbcontributions from '../../db/contributions'; import * as dbgroups from '../../db/groups'; import * as dbprojects from '../../db/projects'; import * as dbusers from '../../db/users'; export async function listGroups(req) { const groupList = await dbgroups.listGroups(); for (const group of groupList) { const users = ( await dbusers.getUsernamesByGroup([group.group_id.toString()]) ).names; const contribWeek = await dbcontributions.getLastWeekCount( group.projects, users ); const contribMTD = await dbcontributions.getMTDCount(group.projects, users); const contribMonth = await dbcontributions.getLastMonthCount( group.projects, users ); const contribYear = await dbcontributions.getYTDCount( group.projects, users ); group.numUsers = users ? users.length : 0; group.numProjects = group.projects.length; group.contribWeek = parseInt(contribWeek.numcontribs, 10); group.contribMTD = parseInt(contribMTD.numcontribs, 10); group.contribMonth = parseInt(contribMonth.numcontribs, 10); group.contribYear = parseInt(contribYear.numcontribs, 10); } return { groupList }; } export async function listStrategicProjects(req) { const projectList = await dbprojects.getAllStrategicProjects(); for (const project of projectList) { const groups = ( await dbgroups.searchGroupIdsByProjectId(project.project_id) ).groups; const users = (await dbusers.getUsernamesByGroup(groups)).names; const contribWeek = await dbcontributions.getLastWeekCount( [project.project_id], users ); const contribMTD = await dbcontributions.getMTDCount( [project.project_id], users ); const contribMonth = await dbcontributions.getLastMonthCount( [project.project_id], users ); const contribYear = await dbcontributions.getYTDCount( [project.project_id], users ); project.numGroups = groups.length; project.numUsers = users ? users.length : 0; project.contribWeek = parseInt(contribWeek.numcontribs, 10); project.contribMTD = parseInt(contribMTD.numcontribs, 10); project.contribMonth = parseInt(contribMonth.numcontribs, 10); project.contribYear = parseInt(contribYear.numcontribs, 10); } return { projectList }; } export async function getGroupDetails(req, id) { const group = await dbgroups.getGroupById(id); return { group }; } export async function getGroup(req, id) { const group = await dbgroups.getGroupById(id); const projects = await dbprojects.getProjectsByGroup(id); const users = await dbusers.getUsersByGroup(id.toString()); const usernames = (await dbusers.getUsernamesByGroup([id.toString()])).names; for (const project of projects) { const projId = [project.project_id]; const contribWeek = await dbcontributions.getLastWeekCount( projId, usernames ); const contribMTD = await dbcontributions.getMTDCount(projId, usernames); const contribMonth = await dbcontributions.getLastMonthCount( projId, usernames ); const contribYear = await dbcontributions.getYTDCount(projId, usernames); project.contribWeek = parseInt(contribWeek.numcontribs, 10); project.contribMTD = parseInt(contribMTD.numcontribs, 10); project.contribMonth = parseInt(contribMonth.numcontribs, 10); project.contribYear = parseInt(contribYear.numcontribs, 10); } for (const user of users) { const username = [user.company_alias]; const pList = group.projects; const contribWeek = await dbcontributions.getLastWeekCount(pList, username); const contribMTD = await dbcontributions.getMTDCount(pList, username); const contribMonth = await dbcontributions.getLastMonthCount( pList, username ); const contribYear = await dbcontributions.getYTDCount(pList, username); user.contribWeek = parseInt(contribWeek.numcontribs, 10); user.contribMTD = parseInt(contribMTD.numcontribs, 10); user.contribMonth = parseInt(contribMonth.numcontribs, 10); user.contribYear = parseInt(contribYear.numcontribs, 10); } return { group, projects, users }; } export async function getStrategicProject(req, id) { const project = await dbprojects.getUniqueProjectById(id); const groups = await dbgroups.getGroupsByProjectId([id]); const groupIds = (await dbgroups.searchGroupIdsByProjectId(id)).groups; const users = (await dbusers.getUsernamesByGroup(groupIds)).names; const projId = [project.project_id]; const userList = []; for (const group of groups) { const usernames = ( await dbusers.getUsernamesByGroup([group.group_id.toString()]) ).names; const contribWeek = await dbcontributions.getLastWeekCount( projId, usernames ); const contribMTD = await dbcontributions.getMTDCount(projId, usernames); const contribMonth = await dbcontributions.getLastMonthCount( projId, usernames ); const contribYear = await dbcontributions.getYTDCount(projId, usernames); group.contribWeek = parseInt(contribWeek.numcontribs, 10); group.contribMTD = parseInt(contribMTD.numcontribs, 10); group.contribMonth = parseInt(contribMonth.numcontribs, 10); group.contribYear = parseInt(contribYear.numcontribs, 10); } for (const user of users) { const github_alias = (await dbusers.getGitHubAliasByUsername(user)) .github_alias; const contribWeek = await dbcontributions.getLastWeekCount(projId, [user]); const contribMTD = await dbcontributions.getMTDCount(projId, [user]); const contribMonth = await dbcontributions.getLastMonthCount(projId, [ user, ]); const contribYear = await dbcontributions.getYTDCount(projId, [user]); const data = { company_alias: user, contribWeek: parseInt(contribWeek.numcontribs, 10), contribMTD: parseInt(contribMTD.numcontribs, 10), contribMonth: parseInt(contribMonth.numcontribs, 10), contribYear: parseInt(contribYear.numcontribs, 10), github_alias, }; userList.push(data); } return { project, groups, users: userList }; } export async function getUser(req, id) { return { user: await dbusers.searchUserByCompanyAlias(id) }; } export async function listProjects(req) { return { projectList: await dbprojects.getProjectsByGroup(req.body.id) }; } export async function updateProject(req, body) { const { project_id, project_name, project_url, project_license, project_groups, project_is_org, } = body; // update project await dbprojects.updateProject( project_id, project_name, project_url, project_license, project_is_org ); // update groups const groupList = project_groups.split(',').map(groupID => { return parseInt(groupID, 10); }); const projectGroups = await dbgroups.getGroupsByProjectId([project_id]); for (const group of projectGroups) { // clean up existing groups from project if (!groupList.includes(group.group_id)) { // group not in list and should be group.projects.splice(group.projects.indexOf(project_id), 1); await dbgroups.updateGroup( group.group_id, group.group_name, group.sponsor, group.goal, group.projects ); } else if (groupList.indexOf(group.group_id) !== -1) { // group groupList.splice(groupList.indexOf(group.group_id), 1); } } // add project to new groups for (const id of groupList) { const groupInfo = await dbgroups.getGroupById(id); groupInfo.projects.push(project_id); await dbgroups.updateGroup( groupInfo.group_id, groupInfo.group_name, groupInfo.sponsor, groupInfo.goal, groupInfo.projects ); } return { success: true }; } export async function listUsers(req) { return { users: await dbusers.listAllUsers() }; } export async function listGroupUsers(req) { return { users: await dbusers.listAllUsersInGroups() }; } export async function addNewGroup(req, body) { const groupId = await dbgroups.addNewGroup( body.groupName, body.sponsorName, body.goals, body.projects ); for (const user of body.users) { const id = groupId.group_id; const date = new Date().toISOString().substring(0, 10); const group = {}; group[id] = date; await dbusers.addGroupsToUser(user, group); } return { groupId }; } export async function addNewUser(req, body) { const groups = {}; if (body.groups.length) { const date = body.date || new Date().toISOString().substring(0, 10); for (const group of body.groups) { groups[group] = date; } } return { result: await dbusers.addNewUser( body.company_alias, body.github_alias, groups ), }; } export async function updateGroup(req, body) { const { groupId, groupName, sponsorName, goals, projects, users } = body; const oldUsers = (await dbusers.getUsernamesByGroup([groupId.toString()])) .names; const updatedGroup = await dbgroups.updateGroup( groupId, groupName, sponsorName, goals, projects ); const updatedUsers = []; for (const user of users) { updatedUsers.push(user); if (!oldUsers || !oldUsers.includes(user)) { const id = groupId; const date = new Date().toISOString().substring(0, 10); const group = {}; group[id] = date; await dbusers.addGroupsToUser(user, group); } } const deletedUsers = oldUsers ? oldUsers.filter(user => updatedUsers.indexOf(user) < 0) : []; for (const user of deletedUsers) { await dbusers.removeGroupFromUser(user, groupId); } return { updatedGroup }; } export async function deleteGroup(req, body) { const users = (await dbusers.getUsernamesByGroup([body.id.toString()])).names; if (users) { for (const user of users) { await dbusers.removeGroupFromUser(user, body.id); } } return { group: await dbgroups.deleteGroup(body.id) }; } export async function updateUser(req, id, body) { return { user: await dbusers.updateUser(id, body.github_alias, body.groups) }; } export async function getReport(req, id, date) { const group = await dbgroups.getGroupById(id); const projects = await dbprojects.getProjectsByGroup(id); const users = await dbusers.getUsersByGroup(id); const usernames = (await dbusers.getUsernamesByGroup([id])).names; group.total = 0; group.strategic = 0; for (const project of projects) { const projId = project.project_id; project.contributions = await dbcontributions.monthlyStrategicContributionsByProject( projId, usernames, date ); project.total = parseInt( (await dbcontributions.monthlyTotalByProject(projId, date)).total, 10 ); project.strategic = project.contributions.length; group.total += project.total; group.strategic += project.strategic; } for (const user of users) { user.total = parseInt( ( await dbcontributions.monthlyTotalByUser( group.projects, user.company_alias, date ) ).total, 10 ); } return { group, projects, users }; }
the_stack
"use strict"; // uuid: ff759cf5-29fb-4cb9-a460-8b70e6bec95a // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ /** @module developer | This module won't be part of release version */ import { assert } from "chai"; import * as sysFs from "fs"; import * as sysPath from "path"; import * as sysProcess from "process"; import { Consts } from "../shared/lib/consts.js"; import { RelConsts } from "../shared/rel-consts.js"; import { DevConsts } from "../shared/lib/dev-consts.js"; import { fsix } from "../shared/vendor/fsix.js"; import { DevCfg } from "../shared/dev-config.js"; /** * ## Description * * **Exact** is a test framework created to test ABeamer functionality. * It makes a copy of the template, modifying its data. * It executes abeamer under headless browser and captures its output. * */ export namespace Exact { // @TODO: Implement Image compare // const mic = require('mocha-image-compare')({ // report: './report', // threshold: 0.002, // highlight: 'yellow', // }); // ------------------------------------------------------------------------ // Consts // ------------------------------------------------------------------------ const TEMPLATE_PATH = 'template'; const RUN_PATH = 'tests.run'; const ASSETS_PATH = 'assets'; const DEFAULT_TEST_WIDTH = 640; const DEFAULT_TEST_HEIGHT = 480; const _DEFAULT_TIMEOUT = 20 * 1000; const DEFAULT_TEST_GEN_FRAMES_WIDTH = 100; const DEFAULT_TEST_GEN_FRAMES_HEIGHT = 100; const _DEFAULT_EXPECTED_PATH = './expected/frames'; export let _TEST_DIGIT_LIMIT: int = 1000; // same as interpolator.js // ------------------------------------------------------------------------ // Types & Interfaces // ------------------------------------------------------------------------ type StringOrCommand = string | '@@no-wrap-add-animation' // sets the scene number. @default 1 | '@@scene'; export type AnimeArrayType = (object | string | [StringOrCommand, string | object])[]; export type AnimesType = string | AnimeArrayType; export type TestFunc = (rd: ExactResult, done, index?: int) => void; export interface Tests { [name: string]: TestFunc; } interface ExactInMacros { width?: int; height?: int; fps?: int; css?: string; js?: string; /** To run animations in parallel enclose on brackets and set parallelAnimes. */ animes?: AnimesType; html?: string; } interface ExactParams { jsMacros?: [string, string][]; plugins?: string[]; // render params exitRenderOnFinished?: boolean; renderFrameOptions?: ABeamer.RenderFrameOptions; extraRenderCalls?: ABeamer.RenderFrameOptions[]; /** Name of the headless server. * @default DEFAULT_SERVER */ server?: string; /** * Sets the log level * @default LL_VERBOSE */ logLevel?: uint; /** * Set the timeout per test case. * @default DEFAULT_TIMEOUT */ timeout?: uint; /** If true, it creates the story-frames files */ toGenFrames?: boolean; // @TODO: Implement expectedFolder /** * If toGenFrames is true, it uses this folder to compare with actual images * and report with the expected images */ expectedFolder?: string; /** If true, runs the test against the release version instead of the * development version */ toUseReleaseVersion?: boolean; /** If it's true, after receiving the execution results, it doesn't sets the ResData.actions */ toNotParseActions?: boolean; /** * Deletes previous created frames. * @default True */ toDelPreviousFrames?: boolean; /** Sends to console stdout */ toLogStdOut?: boolean; /** * Sends to console stderr. * @default true */ toNotLogStdErr?: boolean; /** Sends to console the list of actions */ toLogActions?: boolean; /** Boolean list of animations indexes that run in parallel. */ parallelAnimes?: boolean[]; /** * Sends to console the execution time. * @default True */ toNotTimeExecution?: boolean; /** Set to true, if an exception in a test case should stop all test cases */ casesAreDependent?: boolean; /** Allows to modify the command line */ onCmdLine?: (cmdLine: string) => string; /** Allows to process each line of the resulting output */ onParseOutputLine?: (line: string) => void; /** Lists of errors that are expected to occur */ expectedErrors?: string[]; tests?: Tests; } export interface ExactResult { suiteName: string; params: ExactParams; inMacros: ExactInMacros; fps: int; startTime?: Date; executionTime?: number; root?: string; inFolder?: string; runPath?: string; outFolder?: string; cmdLine?: string; error?: any; out?: string; err?: string; hasError?: boolean; hasCriticalError?: boolean; outLines?: string[]; errLines?: string[]; filteredErrLines?: string[]; actions?: Actions; exceptions: { [id: number]: string }; } // ------------------------------------------------------------------------ // Test Builder // ------------------------------------------------------------------------ export interface TestParams { preLabel?: string; postLabel?: string; duration?: string | int; /** * This is the test duration or element duration * Used to calculate the frame count */ realDuration?: string | int; frameCount?: int; easingFunc?: (t) => number; easingName?: string; min?: int; max?: int; elDuration?: string | int; elIndex?: int; elName?: string; prop?: string; sceneIndex?: int; builder?: TestBuilder; isPosAbsolute?: boolean; } export class TestBuilder { // default input params elDuration: string | int = '1s'; elIndex: int; prop = 'left'; fps = 4; min = 20; max = 40; cssClassesForHtml: HtmlOptions; isPosAbsolute: boolean = true; // generated properties tests?: TestParams[]; runTestParams: Tests = {}; testCountForHtml?: int; testFunc?: TestFunc = defaultTestFunc; getTestLabel(test: TestParams) { return `${test.preLabel || ''}${test.elName} ` + `${test.prop} goes from ${test.min} to ${test.max}${test.postLabel || ''}`; } getTestAnime(test: TestParams): ABeamer.Animation { return { selector: `#${test.elName}`, duration: test.elDuration, props: [{ duration: test.duration, easing: test.easingName, prop: test.prop, value: test.max, }], }; } buildRunTest(test: TestParams) { this.runTestParams[this.getTestLabel(test)] = defaultTestFunc; } runTest(rd: Exact.ExactResult, test: TestParams) { rd.actions.isIdPropActions(test.elName, test.prop, Exact.simulatePixelAction( Exact.interpolateMinMax(test.min, test.max, test.frameCount, test.easingFunc))); } addTests(tests: TestParams[]) { builder = this; this.tests = tests; this.testCountForHtml = tests.length; tests.forEach((test, index) => { test.builder = this; test.elIndex = test.elIndex || this.elIndex; if (test.elIndex === undefined) { test.elIndex = index; } if (test.isPosAbsolute === undefined) { test.isPosAbsolute = this.isPosAbsolute; } test.elName = `t${test.elIndex}`; test.min = test.min || this.min; test.max = test.max || this.max; test.prop = test.prop || this.prop; test.elDuration = test.elDuration || this.elDuration; test.realDuration = test.duration || test.elDuration; if (test.frameCount === undefined) { test.frameCount = calcFrameCount(test.realDuration, this.fps); } this.buildRunTest(test); }); } getInMacros() { return { fps: this.fps, css: this.tests.map((test) => `#${test.elName} {${test.isPosAbsolute ? 'position: absolute; ' : ''}` + `${test.prop}: ${test.min}px}`).join('\n'), animes: this.tests.map((test) => { return this.getTestAnime(test); }), html: Exact.genTestHtml(this.testCountForHtml, this.cssClassesForHtml), }; } } export let builder: TestBuilder; export function defaultTestFunc(rd: Exact.ExactResult, done, index): void { builder.runTest(rd, builder.tests[index]); done(); } // ------------------------------------------------------------------------ // Tools // ------------------------------------------------------------------------ export const obj2String = (obj: any) => JSON.stringify(obj, undefined, 2); export function hexToRgb(hex: string): string { const _hh2Int = (delta) => parseInt(hex.substr(delta, 2), 16); return `rgb(${_hh2Int(1)}, ${_hh2Int(3)}, ${_hh2Int(5)})`; } export const roundTestDigit = (v: number) => Math.round(v * _TEST_DIGIT_LIMIT) / _TEST_DIGIT_LIMIT; export function calcFrameCount(duration: string | int, fps: int, defaultDuration?: int): int { if (!duration) { return Math.round(defaultDuration * fps - 0.0001); } if (typeof duration === 'number') { return duration as int; } const [all, sValue, unit] = duration.match(/^([\d\.]+)(s|ms|f|%)$/) || ['', '', '']; if (!all) { throw `Unknown duration ${duration}`; } let value = parseFloat(sValue); switch (unit) { case '%': value = (value / 100) * fps * defaultDuration; break; case 's': value = value * fps; break; case 'ms': value = (value / 1000) * fps; break; } return Math.round(value - 0.0001); } // ------------------------------------------------------------------------ // Generators // ------------------------------------------------------------------------ export interface HtmlOptions { cssClass?: string; htmlTag?: string; idPrefix?: string; textPrefix?: string; sceneMarkers?: int[]; } export function genTestHtml(count: int, opts?: HtmlOptions): string { const res = []; opts = opts || {}; opts.cssClass = opts.cssClass === undefined ? 'abslf' : opts.cssClass; opts.htmlTag = opts.htmlTag || 'div'; opts.idPrefix = opts.idPrefix || 't'; opts.textPrefix = opts.textPrefix || 't'; let sceneIndex = 0; for (let i = 0; i < count; i++) { if (opts.sceneMarkers && opts.sceneMarkers.length > sceneIndex && opts.sceneMarkers[sceneIndex] === i) { sceneIndex++; res.push(' </div>'); res.push(` <div class="abeamer-scene" id=scene${sceneIndex + 1}>`); } res.push(` <${opts.htmlTag} class='${opts.cssClass}' ` + `id='${opts.idPrefix}${i}'>${opts.textPrefix}${i}</${opts.htmlTag}>`); } return getTestSquare + res.join('\n'); } /** * Returns the Html for Test Square * A Test square is a red square at the left top designed * to be easier for a human to visualize a frame.png file in a image viewer * */ export const getTestSquare = '<div id="test-square"></div>\n'; // ------------------------------------------------------------------------ // Simulators // ------------------------------------------------------------------------ export function interpolateMinMax(min, max: int, frameCount: number, interpolator?: (t) => number) { // @TIP: JS doesn't differentiate between int and float but this code // for a future differentiation const framesInt = Math.round(frameCount); const res: number[] = []; const delta = (max - min); for (let i = 0; i < framesInt; i++) { const t = framesInt > 1 ? i / (framesInt - 1) : 1; const v = interpolator ? interpolator(t) : t; res.push(v * delta + min); } return res; } export function interpolateList(list: any[], cycle: number[]): any[] { const res = []; const listLen = list.length; // tslint:disable-next-line:prefer-for-of for (let i = 0; i < cycle.length; i++) { const listIndex = Math.floor(listLen * Math.min(Math.max(0, cycle[i]), 0.999)); res.push(list[listIndex]); } return res; } export function roundToTestDigits(values: number[]): void { values.forEach((v, i) => { values[i] = Math.round(v * _TEST_DIGIT_LIMIT) / _TEST_DIGIT_LIMIT; }); } export let simulatePixelAction = (values: number[]): string[] => values.map(value => Math.round(value) + 'px'); export let simulateNumAction = (values: number[]): string[] => values.map(value => value.toString()); export function simulateAction(values: any[], propType: uint): string[] { switch (propType) { case DevConsts.PT_PIXEL: return Exact.simulatePixelAction(values); case DevConsts.PT_NUMBER: return Exact.simulateNumAction(values); } } // ------------------------------------------------------------------------ // Assertion // ------------------------------------------------------------------------ export function AssertHasLine(rd: ExactResult, line: string, isError: boolean = false) { assert.isTrue((!isError ? rd.out : rd.errLines).indexOf(line) !== -1, `missing: [${line}]`); } // ------------------------------------------------------------------------ // Actions // ------------------------------------------------------------------------ export class Actions { constructor(public actions: [string, string, string][], public ranges: [string, string, int, int][]) { } // ------------------------------------------------------------------------ // Filter // ------------------------------------------------------------------------ filterByElement = (elementId: string) => this.actions.filter(action => action[0] === elementId). map(action => [action[1], action[2]]) filterByElementProp = (elementId: string, propName: string) => this.actions.filter(action => action[0] === elementId && action[1] === propName). map(action => action[2]) filterRangeByElementProp = (elementId: string, propName: string) => this.ranges.filter(range => range[0] === elementId && range[1] === propName). map(range => [range[2], range[3]] as [int, int]) // ------------------------------------------------------------------------ // Log // ------------------------------------------------------------------------ log(): void { console.log(this.actions); } logByElement(elementId: string): void { console.log(this.filterByElement(elementId)); } logByElementProp(elementId: string, propName: string): void { console.log(this.filterByElementProp(elementId, propName)); } // ------------------------------------------------------------------------ // Assertion // ------------------------------------------------------------------------ isIdPropActions( elementId: string, propName: string, expected: string[], toAssert: boolean = true, toLogIfFails: boolean = true, actualStartIndex: int = 0, actualLength?: int) { function failTestAndLog(): void { if (toLogIfFails) { console.log('Actual:'); console.log(actual); console.log('Expected:'); console.log(expected); } } let actual = this.filterByElementProp(elementId, propName); actual = actual.slice(actualStartIndex, actualLength === undefined ? actual.length : actualStartIndex + actualLength); if (expected.length !== actual.length) { if (toAssert) { failTestAndLog(); throw `id: ${elementId} prop: ${propName} actions ` + `expected ${expected.length} length, but actual is ${actual.length}`; } return -2; } return actual.findIndex((value, index) => { if (value !== expected[index]) { failTestAndLog(); if (toAssert) { throw `id: ${elementId} prop: ${propName} index: ${index} ` + `expected ${value} length, but actual is ${expected[index]}`; } return true; } else { return false; } }); } isActions( _expected: [string, string, string][], toAssert: boolean = true, _toLogIfFails: boolean = true) { return this.actions.findIndex((action, index) => { const expectedIt = action[index]; const res = action[0] === expectedIt[0] && (action[1] === expectedIt[1]) && (action[2] === expectedIt[2]); if (!res && toAssert) { } return !res; }); } isIdPropRanges( elementId: string, propName: string, expected: [int, int][], toAssert: boolean = true, toLogIfFails: boolean = true, actualStartIndex: int = 0, actualLength?: int): number { function failTestAndLog(): void { if (toLogIfFails) { console.log('Actual:'); console.log(actual); console.log('Expected:'); console.log(expected); } } let actual = this.filterRangeByElementProp(elementId, propName); actual = actual.slice(actualStartIndex, actualLength === undefined ? actual.length : actualStartIndex + actualLength); if (expected.length !== actual.length) { if (toAssert) { failTestAndLog(); throw `id: ${elementId} prop: ${propName} actions ` + `expected ${expected.length} length, but actual is ${actual.length}`; } return -2; } return actual.findIndex((value, index) => { if (value[0] !== expected[index][0] || value[1] !== expected[index][1]) { failTestAndLog(); if (toAssert) { throw `id: ${elementId} prop: ${propName} index: ${index} ` + `expected ${value} length, but actual is ${expected[index]}`; } return true; } else { return false; } }); } } // ------------------------------------------------------------------------ // Assertion Manager // ------------------------------------------------------------------------ interface ResultHolder { rd?: Exact.ExactResult; } function assertionManager(suiteName: string, params: ExactParams, holder: ResultHolder, callback: (resolve) => void): void { before(() => { return new Promise((resolve) => { callback(resolve); }); }); const tests = params.tests || {}; const testNames = Object.keys(tests); // tslint:disable-next-line:only-arrow-functions space-before-function-paren describe(suiteName, function (): void { testNames.forEach((name, index) => { const func = tests[name]; // tslint:disable-next-line:only-arrow-functions space-before-function-paren it(name, function (done): void { this.timeout(/* holder.rd.params.timeout || DEFAULT_TIMEOUT */0); if (!holder.rd.hasCriticalError) { func(holder.rd, done, index); } else { done('Critical Error, Test Aborted'); } }); }); }); } // ------------------------------------------------------------------------ // Runs Test Suite // ------------------------------------------------------------------------ /** * Creates the folder tests.run/<name>, copies and transforms the test template * Executes the test under server * * @param suiteName Test Suite name or filename containing the Test Suite */ export function runTestSuite(suiteName: string, inMacros: ExactInMacros, params: ExactParams, callback?: (rd: ExactResult) => void): void { // converts __filename to the suiteName suiteName = fsix.toPosixSlash(suiteName).replace(/^.*\/([^\/]+)\.js$/, '$1'); params.toNotTimeExecution = params.toNotTimeExecution !== false ? true : false; const rd: ExactResult = { suiteName, params, inMacros, fps: inMacros.fps, exceptions: {}, }; rd.root = fsix.toPosixSlash(__dirname); rd.inFolder = rd.root + '/' + TEMPLATE_PATH; rd.runPath = rd.root + '/' + RUN_PATH; rd.outFolder = rd.runPath + '/' + suiteName; fsix.mkdirpSync(rd.runPath); fsix.mkdirpSync(rd.outFolder); initInMacros(inMacros, params); const macros = initReplaceMacros(inMacros, params); const files = sysFs.readdirSync(rd.inFolder); files.forEach((fileName) => { let text = fsix.readUtf8Sync(sysPath.join(rd.inFolder, fileName)); macros.forEach(item => { text = text.replace(item[0], item[1]); }); sysFs.writeFileSync(sysPath.join(rd.outFolder, fileName), text); }); buildCmdLine(rd); createShellFile(rd); const holder: ResultHolder = {}; assertionManager(suiteName, params, holder, (resolve) => { if (params.toNotTimeExecution) { console.log(`${suiteName} started`); rd.startTime = new Date(); } runExternal(rd, callback, holder, resolve); }); } // ------------------------------------------------------------------------ // parseAnimes // ------------------------------------------------------------------------ function parseAnimes(jsAnimes: AnimesType, parallelAnimes: boolean[]): string { const PRE_ADD_TRY_CATCH = `try {`; const POST_ADD_TRY_CATCH = ` } catch (error) { story.logFrmt('EXCEPTION', [['index', __INDEX__], ['error', error]]); if (!independentCases) story.exit(); } `; jsAnimes = (typeof jsAnimes === 'object') ? jsAnimes : [jsAnimes]; const addedScenes = ['1']; return (jsAnimes as AnimeArrayType).map((jsAnime, animeIndex) => { let toWrapAddAnimations = true; let sceneNr = '1'; let preAdd = ''; if (typeof jsAnime === 'object' && (jsAnime as object[]).length === 2 && typeof (jsAnime[0]) === 'string' && jsAnime[0][0] === '@') { const [command, value] = jsAnime[0].split(':'); jsAnime = jsAnime[1]; switch (command) { case '@@scene': sceneNr = value; if (addedScenes.indexOf(sceneNr) === -1) { preAdd += `var scene${sceneNr} = ` + `story.scenes[${parseInt(sceneNr) - 1}];\n`; } break; case '@@no-wrap-add-animation': toWrapAddAnimations = false; break; } } if (typeof jsAnime === 'object') { jsAnime = Array.isArray(jsAnime) && parallelAnimes && parallelAnimes[animeIndex] ? obj2String(jsAnime) : '[' + obj2String(jsAnime) + ']'; } if (toWrapAddAnimations) { jsAnime = `\nscene${sceneNr}.addAnimations(` + jsAnime + `);\n`; } return preAdd + PRE_ADD_TRY_CATCH + jsAnime + POST_ADD_TRY_CATCH.replace(/__INDEX__/, animeIndex.toString()); }).join(''); } // ------------------------------------------------------------------------ // initInMacros // ------------------------------------------------------------------------ function initInMacros(inMacros: ExactInMacros, params: ExactParams): void { if (inMacros.animes) { inMacros.js = parseAnimes(inMacros.animes, params.parallelAnimes); inMacros.animes = undefined; } if (params.jsMacros) { params.jsMacros.forEach(macro => { inMacros.js = inMacros.js.replace(macro[0], macro[1]); }); } inMacros.width = inMacros.width || (!params.toGenFrames ? DEFAULT_TEST_WIDTH : DEFAULT_TEST_GEN_FRAMES_WIDTH); inMacros.height = inMacros.height || (!params.toGenFrames ? DEFAULT_TEST_HEIGHT : DEFAULT_TEST_GEN_FRAMES_HEIGHT); } /** * Initializes the `Macros`. * Usage: replace text on `.js/.html/.css` files. */ function initReplaceMacros(inMacros: ExactInMacros, params: ExactParams): [RegExp, string][] { const cfg = DevCfg.getConfig(sysPath.dirname(__dirname)); const macros = Object.keys(inMacros).map(key => [new RegExp(`__${key.toUpperCase()}__`, 'g'), inMacros[key] || ''] as [RegExp, string]); macros.push([/__LIB_FILES__/, (fsix.loadJsonSync(cfg.paths.MODULES_LIST_FILE) as Shared.ModulesList) .libModules.map(file => ` <script src="../../../client/lib/js/${file}.js"></script>\n`, ).join('')], ); macros.push([/__PLUGINS__/, params.plugins ? params.plugins.map(plugin => ` <script src="../../../client/lib/plugins/${plugin}/${plugin}.js"></script>\n`, ).join('') : ''], ); macros.push([/__ASSETS_PATH__/g, `../../${ASSETS_PATH}`]); macros.push([/__IND_CASES__/, params.casesAreDependent !== true ? 'true' : 'false']); macros.push([/__EXIT_RENDER_ON_FINISHED__/, params.exitRenderOnFinished !== false ? 'true' : 'false']); macros.push([/__RENDER_FRAME_OPTIONS__/, params.renderFrameOptions ? JSON.stringify(params.renderFrameOptions, undefined, 2) : 'undefined']); macros.push([/__EXTRA_RENDER_CALLS__/, params.extraRenderCalls && params.extraRenderCalls.length ? params.extraRenderCalls.map(frameOptions => ` story.render(story.bestPlaySpeed(),` + JSON.stringify(frameOptions, undefined, 2) + ');\n', ).join('\n') : '']); return macros; } // ------------------------------------------------------------------------ // createShellFile // ------------------------------------------------------------------------ /** * Creates a shell file. * Usage: manually execute a test. */ function createShellFile(rd: ExactResult): void { const isWin = sysProcess.platform === 'win32'; const scriptName = rd.outFolder + '/run' + (isWin ? '.bat' : '.sh'); const shell = '#/usr/bin/env sh\n'; sysFs.writeFileSync(scriptName, (isWin ? '' : shell) + rd.cmdLine + '\n'); if (!isWin) { sysFs.chmodSync(scriptName, '0775'); } } // ------------------------------------------------------------------------ // buildCmdLine // ------------------------------------------------------------------------ /** * Creates the command line. * Usage: execute the render server agent. */ function buildCmdLine(rd: ExactResult): void { const params = rd.params; const serverName = (params.server || RelConsts.DEFAULT_SERVER); let cmdLine = (RelConsts.NODE_SERVERS.indexOf(serverName) !== -1 ? 'node' : serverName) // use double quotes for files to support space files and windows + ` "${rd.root}/../cli/../server/server-agent-${serverName}.js"` + ` --ll ${params.logLevel !== undefined ? params.logLevel : Consts.LL_VERBOSE}` + (params.toDelPreviousFrames !== false ? ' --dp' : '') + (params.toGenFrames ? '' : ' --noframes') + ` --config "${rd.outFolder}/abeamer.ini"`; if (params.onCmdLine) { cmdLine = params.onCmdLine(cmdLine); } rd.cmdLine = cmdLine; } // ------------------------------------------------------------------------ // runExternal // ------------------------------------------------------------------------ function runExternal( rd: ExactResult, callback: (rd: ExactResult) => void, holder: ResultHolder, resolve): void { fsix.runExternal(rd.cmdLine, (error, stdout, stderr) => { if (rd.params.toNotTimeExecution) { rd.executionTime = new Date() as any - (rd.startTime as any); console.log(`${rd.suiteName} finished ${rd.executionTime} (ms)\n`); } rd.error = error; rd.out = (stdout || '').trim(); rd.err = (stderr || '').trim(); rd.outLines = rd.out.split('\n'); rd.errLines = rd.err.split('\n'); // browser can send error but the server doesn't log as an error rd.outLines.forEach(line => { if (line.search(/\[(CRITICAL|ERROR|EXCEPTION)\]/) !== -1) { rd.errLines.push(line); } }); rd.hasError = error || rd.err.length > 0; if (rd.hasError) { if (rd.errLines && rd.params.expectedErrors) { rd.filteredErrLines = rd.errLines .filter(item => rd.params.expectedErrors.indexOf(item) === -1); rd.hasError = rd.filteredErrLines.length > 0; } else { rd.filteredErrLines = rd.errLines; } if (rd.hasError) { console.log(`rd.hasError: ${rd.hasError}`); } if (rd.hasError && rd.params.toNotLogStdErr !== false) { console.error('Error:', rd.error); console.log('StdErr:[', rd.filteredErrLines); } rd.hasCriticalError = rd.hasError; } if (!rd.params.toNotParseActions) { parseActions(rd); } if (callback) { callback(rd); } holder.rd = rd; resolve(); }); } // ------------------------------------------------------------------------ // parseActions // ------------------------------------------------------------------------ export function getResTagParams(line: string, tag: string, callback?: (res: string[]) => void): string[] | undefined { if (line.substr(0, tag.length + 1) === tag + ':') { const res = []; line.replace(/_\[([^\]]*)\]_/g, (match, p) => { res.push(p); return match; }); if (callback) { callback(res); } return res; } return undefined; } function parseActions(rd: ExactResult): void { const actions: [string, string, string][] = []; const ranges: [string, string, int, int][] = []; if (rd.params.toLogStdOut) { rd.outLines.forEach((line, index) => { console.log(`${index}:[${line}]`); }); } rd.outLines.forEach(line => { getResTagParams(line, 'action', (action) => { actions.push(action as any); }); getResTagParams(line, 'action-range', (range) => { ranges.push([range[0], range[1], parseInt(range[2]), parseInt(range[3])]); }); Exact.getResTagParams(line, 'EXCEPTION', (exprData) => { rd.exceptions[parseInt(exprData[0])] = exprData[1]; }); if (rd.params.onParseOutputLine) { rd.params.onParseOutputLine(line); } }); rd.actions = new Actions(actions, ranges); if (rd.params.toLogActions) { console.log(rd.actions); } } }
the_stack
import { Map as ImmutableMap } from 'immutable'; import { Selector } from 'reselect'; import { useEffect, useCallback, useMemo, useRef } from 'react'; import { useDispatch, useMappedState } from 'redux-react-hook'; import { Action } from '~redux/index'; import { DataObject, KeyedDataObject, RemoveFirstFromTuple, } from '~types/index'; import { ActionTransformFnType } from '~utils/actions'; import { FetchableDataRecord } from '~immutable/index'; import promiseListener, { AsyncFunction } from '~redux/createPromiseListener'; import { isFetchingData, shouldFetchData } from '~immutable/utils'; import { getMainClasses } from '~utils/css'; import { RootStateRecord } from '../../modules/state'; interface DataFetcher<S> { select: S; fetch: (...fetchArgs: any[]) => Action<any>; ttl?: number; } interface DataSubscriber<S> { select: S; start: (...subArgs: any[]) => Action<any>; stop: (...subArgs: any[]) => Action<any>; } type DataMapFetcher<T> = { select: (( rootState: RootStateRecord, ) => ImmutableMap<string, FetchableDataRecord<T>>) & { filter?: (data: any, ...args: any[]) => any; }; fetch: (key: any) => Action<any>; ttl?: number; }; type DataTupleFetcher<T> = { select: ( rootState: RootStateRecord, args: [any, any][], ) => ImmutableMap<string, FetchableDataRecord<T>>; fetch: (arg0: [any, any]) => Action<any>; ttl?: number; }; type DataTupleSubscriber<T> = { select: ( rootState: RootStateRecord, keys: [any, any][], ) => ImmutableMap<string, FetchableDataRecord<T>>; start: (...subArgs: any[]) => Action<any>; stop: (...subArgs: any[]) => Action<any>; }; type DependantSelector = ( selector: Selector<RootStateRecord, any>, reduxState: RootStateRecord, extraArgs?: any[], ) => boolean; export type Given = ( potentialSelector: Selector<RootStateRecord, any>, dependantSelector?: DependantSelector, ) => any | boolean; type DataFetcherOptions = { ttl?: number; }; // This conditional type allows data to be undefined/null, but uses // further conditional types in order to get the possibly-toJS'ed type // of the record property. type MaybeFetchedData<T extends undefined | null | { record: any }> = T extends | undefined | null ? T : T extends { record: any } ? T extends { record: { toJS: Function } } ? ReturnType<T['record']['toJS']> : T['record'] : T; export { default as useNaiveBranchingDialogWizard, WizardDialogType, } from './naiveBranchingDialogWizardHook'; /* Used in cases where we need to memoize the transformed output of any data. * Transform function has to be pure, obviously */ export const useTransformer = < T extends (...args: any[]) => any, A extends Parameters<T> >( transform: T, args: A = ([] as unknown) as A, ): ReturnType<T> => // eslint-disable-next-line react-hooks/exhaustive-deps useMemo<ReturnType<T>>(() => transform(...args), [ transform, // eslint-disable-next-line react-hooks/exhaustive-deps ...args, ]); export const usePrevious = <T extends any>(value: T): T | void => { const ref = useRef<T>(); useEffect(() => { ref.current = value; }); return ref.current; }; const transformSelectedData = (data?: any) => { if (!data) return undefined; const record = typeof data.get === 'function' ? data.get('record') : data.record; return record && typeof record.toJS === 'function' ? record.toJS() : record; }; // @TODO-redux (remove this) const defaultTransform = <T extends { toJS(): any }>( obj: T, // The return type of this could be improved if there was a way // to map from immutable to non-immutable types // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars ...args: any[] ) => (obj && typeof obj.toJS === 'function' ? obj.toJS() : obj); /* * Given a redux selector and optional selector arguments, get the * (immutable) redux state and return a mutable version of it. */ export const useSelector = < S extends ( ...args: any[] ) => any & { transform?: <T>(obj: T, ...args: any[]) => any }, A extends RemoveFirstFromTuple<Parameters<S>> // Omit the first arg (state) >( select: S, args: A = [] as A, ) => { // eslint-disable-next-line react-hooks/exhaustive-deps const mapState = useCallback((state) => select(state, ...args), [ // eslint-disable-next-line react-hooks/exhaustive-deps ...args, select, ]); const data: ReturnType<typeof select> = useMappedState(mapState); const transformFn = (select as { transform?: <T>(obj: T, ...args: A) => any }).transform || defaultTransform; return useMemo<ReturnType<typeof transformFn>>( () => transformFn(data, ...args), [args, data, transformFn], ); }; /* * Esteemed React developer! * * Are *you* tired of giving `useMemo` some dependencies, only to find * recomputations with the same data (e.g. arrays)? * * Better make a memo to self: simply use `createCustomMemo`™! * * It's only the memoization function designed *by* a developer, *for* that * very same developer. Upgrade today! */ export const createCustomMemo = ( comparator: (...compArgs: any[]) => boolean, ) => (fn: Function, deps: any[]) => { const lastDeps = useRef(deps); const lastResult = useRef(fn()); if (comparator(lastDeps.current, deps)) { return lastResult.current; } lastResult.current = fn(); lastDeps.current = deps; return lastResult.current; }; const areFlatArraysEqual = (arr1: any[], arr2: any[]) => { if (arr1.length !== arr2.length) { return false; } for (let i = arr1.length - 1; i >= 0; i -= 1) { if (arr1[i] !== arr2[i]) { return false; } } return true; }; // Only supporting a 2-length tuple for now const areTupleArraysEqual = (arr1: [any, any][], arr2: [any, any][]) => { if (arr1.length !== arr2.length) { return false; } for (let i = arr1.length - 1; i >= 0; i -= 1) { if (arr1[i][0] !== arr2[i][0] || arr1[i][1] !== arr2[i][1]) { return false; } } return true; }; export const useMemoWithFlatArray = createCustomMemo(areFlatArraysEqual); export const useMemoWithTupleArray = createCustomMemo(areTupleArraysEqual); // @TODO-redux (remove) export const useDataFetcher = < S extends (...args: any[]) => any, A extends RemoveFirstFromTuple<Parameters<S>> >( { fetch, select, ttl = 0 }: DataFetcher<S>, selectArgs: A, fetchArgs: any[], { ttl: ttlOverride }: DataFetcherOptions = {}, ) => { const dispatch = useDispatch(); const mapState = useCallback((state) => select(state, ...selectArgs), [ select, selectArgs, ]); const data: ReturnType<typeof select> = useMappedState(mapState); const isFirstMount = useRef(true); /* * @todo Fetches are not guarded properly for the same item when called together */ const shouldFetch = shouldFetchData( data, // I don't know whether there's a nicer way to do this and make flow happy at the same time ttlOverride === 0 ? 0 : ttlOverride || ttl, isFirstMount.current, fetchArgs, ); useEffect(() => { isFirstMount.current = false; if (shouldFetch) { dispatch(fetch(...fetchArgs)); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [dispatch, fetch, shouldFetch, ...fetchArgs]); return { data: transformSelectedData(data) as MaybeFetchedData<typeof data>, isFetching: !!(shouldFetch && isFetchingData(data)), error: data && data.error ? data.error : undefined, }; }; /* * Given a `DataMapFetcher` object and an array of keys (the items * to fetch data for), select the data and fetch the parts that need * to be (re-)fetched. */ export const useDataMapFetcher = <T>( { fetch, select, ttl: ttlDefault = 0 }: DataMapFetcher<T>, keys: string[], { ttl: ttlOverride }: DataFetcherOptions = {}, ) => { const dispatch = useDispatch(); const mapState = useCallback((state) => select(state), [select]); const rawData: ImmutableMap<string, FetchableDataRecord<T>> = useMappedState( mapState, ); let allData; if (typeof select.filter == 'function') { allData = select.filter(rawData, keys); } else { allData = rawData; } const isFirstMount = useRef(true); const ttl = ttlOverride || ttlDefault; /* * Use with the array of keys we want data for, get the data from `allData` * and use `shouldFetchData` to obtain an array of keys we should * dispatch fetch actions for. */ const keysToFetchFor = useMemo( () => keys.filter((key) => shouldFetchData(rawData.get(key), ttl, isFirstMount.current, [key]), ), [rawData, keys, ttl], ); /* * Set the `isFirstMount` ref and dispatch any needed fetch actions. */ useEffect(() => { isFirstMount.current = false; keysToFetchFor.map((key) => dispatch(fetch(key))); }, [keysToFetchFor, dispatch, fetch]); /* * Return an array of data objects with keys by mapping over the keys * and getting the data from `allData`. */ return useMemo< KeyedDataObject<MaybeFetchedData<ReturnType<typeof allData['get']>>>[] >( () => keys.map((key) => { const data = allData.get(key); return { key, data: transformSelectedData(data), isFetching: !!(keysToFetchFor.includes(key) && isFetchingData(data)), error: data && data.error ? data.error : null, }; }), [keys, allData, keysToFetchFor], ); }; /* * T: JS type of the fetched and transformed data, e.g. ColonyType */ export const useDataSubscriber = < S extends (...args: any[]) => any, A extends RemoveFirstFromTuple<Parameters<S>> >( { start, stop, select }: DataSubscriber<S>, selectArgs: A, subArgs: any[], ) => { const dispatch = useDispatch(); const mapState = useCallback((state) => select(state, ...selectArgs), [ select, selectArgs, ]); const data: ReturnType<typeof select> = useMappedState(mapState); const isFirstMount = useRef(true); const shouldSubscribe = shouldFetchData( data, Infinity, isFirstMount.current, subArgs, true, ); useEffect(() => { if (shouldSubscribe) { dispatch(start(...subArgs)); } isFirstMount.current = false; // eslint-disable-next-line react-hooks/exhaustive-deps }, [dispatch, shouldSubscribe, start, stop, ...subArgs]); useEffect( () => () => { dispatch(stop(...subArgs)); }, // eslint-disable-next-line react-hooks/exhaustive-deps [dispatch, stop, ...subArgs], ); return { data: transformSelectedData(data) as MaybeFetchedData<typeof data>, isFetching: !!(shouldSubscribe && isFetchingData(data)), error: data && data.error ? data.error : undefined, }; }; /* * Given a `DataTupleSubscriber` object and a tuple with the items * to fetch data for, select the data and subscribe to any future data. */ export const useDataTupleSubscriber = <T>( { start, stop, select }: DataTupleSubscriber<T>, keys: any[], ): DataObject<T>[] => { const memoizedKeys = useMemoWithTupleArray(() => keys, keys); const dispatch = useDispatch(); const allData: ImmutableMap< string, FetchableDataRecord<any> > = useMappedState( useCallback((state) => select(state, memoizedKeys), [select, memoizedKeys]), ); const isFirstMount = useRef(true); const keysToFetchFor = useMemo( () => memoizedKeys.filter((entry) => shouldFetchData( allData.get(entry[1]), Infinity, isFirstMount.current, [entry], true, ), ), [allData, memoizedKeys], ); useEffect(() => { isFirstMount.current = false; keysToFetchFor.map((key) => dispatch(start(...key))); }, [keysToFetchFor, dispatch, memoizedKeys, start]); useEffect( () => () => { keysToFetchFor.map((key) => dispatch(stop(...key))); }, [dispatch, keysToFetchFor, stop], ); return useMemo( () => memoizedKeys.map((entry) => { const data = allData.get(entry[1]); return { key: entry[1], entry, data: transformSelectedData(data) as MaybeFetchedData<typeof data>, isFetching: keysToFetchFor.includes(entry[1]) && isFetchingData(data), error: data ? data.error : null, }; }), [allData, memoizedKeys, keysToFetchFor], ); }; /* * Given a `DataTupleFetcher` object and a tuple with the items * to fetch data for, select the data and fetch the parts that need * to be (re-)fetched. */ export const useDataTupleFetcher = <T>( { fetch, select, ttl: ttlDefault = 0 }: DataTupleFetcher<T>, keys: any[], { ttl: ttlOverride }: DataFetcherOptions = {}, ): KeyedDataObject<T>[] => { /* * Created memoized keys to guard the rest of the function against * unnecessary updates. */ const memoizedKeys = useMemoWithTupleArray(() => keys, keys); const dispatch = useDispatch(); const allData: ImmutableMap< string, FetchableDataRecord<any> > = useMappedState( useCallback((state) => select(state, memoizedKeys), [select, memoizedKeys]), ); const isFirstMount = useRef(true); const ttl = ttlOverride || ttlDefault; /* * Use with the array of keys we want data for, get the data from `allData` * and use `shouldFetchData` to obtain an array of keys we should * dispatch fetch actions for. */ const keysToFetchFor = useMemo( () => memoizedKeys.filter((entry) => shouldFetchData(allData.get(entry[1]), ttl, isFirstMount.current, [ entry, ]), ), [allData, memoizedKeys, ttl], ); /* * Set the `isFirstMount` ref and dispatch any needed fetch actions. */ useEffect(() => { isFirstMount.current = false; keysToFetchFor.map((key) => dispatch(fetch(key))); }, [keysToFetchFor, dispatch, fetch, memoizedKeys]); /* * Return an array of data objects with keys by mapping over the keys * and getting the data from `allData`. */ return useMemo( () => memoizedKeys.map((entry) => { const data = allData.get(entry[1]); return { key: entry[1], entry, data: transformSelectedData(data) as MaybeFetchedData<typeof data>, isFetching: keysToFetchFor.includes(entry[1]) && isFetchingData(data), error: data ? data.error : null, }; }), [memoizedKeys, allData, keysToFetchFor], ); }; export const useAsyncFunction = <P, R>({ submit, success, error, transform, }: { submit: string; success: string; error: string; transform?: ActionTransformFnType; }): AsyncFunction<P, R>['asyncFunction'] => { const asyncFunc = useMemo(() => { let setPayload; if (transform) { setPayload = (action, payload) => { const newAction = transform({ ...action, payload }); return { ...newAction, meta: { ...action.meta, ...newAction.meta } }; }; } return promiseListener.createAsyncFunction<P, R>({ start: submit, resolve: success, reject: error, setPayload, }); }, [submit, success, error, transform]); // Unsubscribe from the previous async function when it changes const prevAsyncFunc = usePrevious(asyncFunc); if (prevAsyncFunc && prevAsyncFunc !== asyncFunc) { prevAsyncFunc.unsubscribe(); } // Automatically unsubscribe on unmount useEffect(() => () => asyncFunc.unsubscribe(), [asyncFunc]); return asyncFunc.asyncFunction as any; }; /* * To avoid state updates when this component is unmounted, use a ref * that is set to false when cleaning up. */ export const useMounted = () => { const ref = useRef(true); useEffect( () => () => { ref.current = false; }, [], ); return ref; }; export const useMainClasses = ( appearance: any, styles: any, className?: string, ) => useMemo(() => className || getMainClasses(appearance, styles), [ appearance, className, styles, ]);
the_stack
export namespace iTunes { // 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. */ /** * an AirPlay device */ export interface AirPlayDevice { /** * is the device currently being played to? */ active(): boolean; /** * is the device currently available? */ available(): boolean; /** * the kind of the device */ kind(): any; /** * the network (MAC) address of the device */ networkAddress(): string; /** * is the device password- or passcode-protected? */ protected(): boolean; /** * is the device currently selected? */ selected(): boolean; /** * does the device support audio playback? */ supportsAudio(): boolean; /** * does the device support video playback? */ supportsVideo(): boolean; /** * the output volume for the device (0 = minimum, 100 = maximum) */ soundVolume(): 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. */ /** * The application program */ export interface Application { /** * is AirPlay currently enabled? */ airPlayEnabled(): boolean; /** * is a track currently being converted? */ converting(): boolean; /** * the currently selected AirPlay device(s) */ currentAirPlayDevices(): any; /** * the currently selected encoder (MP3, AIFF, WAV, etc.) */ currentEncoder(): any; /** * the currently selected equalizer preset */ currentEQPreset(): any; /** * the playlist containing the currently targeted track */ currentPlaylist(): any; /** * the name of the current song in the playing stream (provided by streaming server) */ currentStreamTitle(): string; /** * the URL of the playing stream or streaming web site (provided by streaming server) */ currentStreamURL(): string; /** * the current targeted track */ currentTrack(): any; /** * the currently selected visual plug-in */ currentVisual(): any; /** * is the equalizer enabled? */ EQEnabled(): boolean; /** * true if all AppleScript track indices should be independent of the play order of the owning playlist. */ fixedIndexing(): boolean; /** * is iTunes the frontmost application? */ frontmost(): boolean; /** * are visuals displayed using the entire screen? */ fullScreen(): boolean; /** * the name of the application */ name(): string; /** * has the sound output been muted? */ mute(): boolean; /** * the player’s position within the currently playing track in seconds. */ playerPosition(): any; /** * is iTunes stopped, paused, or playing? */ playerState(): any; /** * the selection visible to the user */ selection(): any; /** * are songs played in random order? */ shuffleEnabled(): boolean; /** * the playback shuffle mode */ shuffleMode(): any; /** * the playback repeat mode */ songRepeat(): any; /** * the sound output volume (0 = minimum, 100 = maximum) */ soundVolume(): number; /** * the version of iTunes */ version(): string; /** * are visuals currently being displayed? */ visualsEnabled(): boolean; /** * the size of the displayed visual */ visualSize(): 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 piece of art within a track or playlist */ export interface Artwork { /** * data for this artwork, in the form of a picture */ data(): any; /** * description of artwork as a string */ description(): string; /** * was this artwork downloaded by iTunes? */ downloaded(): boolean; /** * the data format for this piece of artwork */ format(): any; /** * kind or purpose of this piece of artwork */ kind(): number; /** * data for this artwork, in original format */ rawData(): 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 playlist representing an audio CD */ export interface AudioCDPlaylist { /** * the artist of the CD */ artist(): string; /** * is this CD a compilation album? */ compilation(): boolean; /** * the composer of the CD */ composer(): string; /** * the total number of discs in this CD’s album */ discCount(): number; /** * the index of this CD disc in the source album */ discNumber(): number; /** * the genre of the CD */ genre(): string; /** * the year the album was recorded/released */ year(): 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 track on an audio CD */ export interface AudioCDTrack { /** * the location of the file represented by this track */ location(): 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. */ /** * the main iTunes window */ export interface BrowserWindow { /** * the selected songs */ selection(): any; /** * the playlist currently displayed in the window */ view(): 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. */ /** * converts a track to a specific file format */ export interface Encoder { /** * the data format created by the encoder */ format(): 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. */ /** * equalizer preset configuration */ export interface EQPreset { /** * the equalizer 32 Hz band level (-12.0 dB to +12.0 dB) */ band1(): any; /** * the equalizer 64 Hz band level (-12.0 dB to +12.0 dB) */ band2(): any; /** * the equalizer 125 Hz band level (-12.0 dB to +12.0 dB) */ band3(): any; /** * the equalizer 250 Hz band level (-12.0 dB to +12.0 dB) */ band4(): any; /** * the equalizer 500 Hz band level (-12.0 dB to +12.0 dB) */ band5(): any; /** * the equalizer 1 kHz band level (-12.0 dB to +12.0 dB) */ band6(): any; /** * the equalizer 2 kHz band level (-12.0 dB to +12.0 dB) */ band7(): any; /** * the equalizer 4 kHz band level (-12.0 dB to +12.0 dB) */ band8(): any; /** * the equalizer 8 kHz band level (-12.0 dB to +12.0 dB) */ band9(): any; /** * the equalizer 16 kHz band level (-12.0 dB to +12.0 dB) */ band10(): any; /** * can this preset be modified? */ modifiable(): boolean; /** * the equalizer preamp level (-12.0 dB to +12.0 dB) */ preamp(): any; /** * should tracks which refer to this preset be updated when the preset is renamed or deleted? */ updateTracks(): 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. */ /** * the iTunes equalizer window */ export interface EQWindow {} /** * 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 track representing an audio file (MP3, AIFF, etc.) */ export interface FileTrack { /** * the location of the file represented by this track */ location(): 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 folder that contains other playlists */ export interface FolderPlaylist {} /** * 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 */ export interface Item { /** * the class of the item */ class(): any; /** * the container of the item */ container(): any; /** * the id of the item */ id(): number; /** * The index of the item in internal application order. */ index(): number; /** * the name of the item */ name(): string; /** * the id of the item as a hexadecimal string. This id does not change over time. */ persistentID(): string; /** * every property of the item */ properties(): 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. */ /** * the master music library playlist */ export interface LibraryPlaylist {} /** * 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 miniplayer window */ export interface MiniplayerWindow {} /** * 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 list of songs/streams */ export interface Playlist { /** * the description of the playlist */ description(): string; /** * is this playlist disliked? */ disliked(): boolean; /** * the total length of all songs (in seconds) */ duration(): number; /** * the name of the playlist */ name(): string; /** * is this playlist loved? */ loved(): boolean; /** * folder which contains this playlist (if any) */ parent(): any; /** * play the songs in this playlist in random order? (obsolete; always false) */ shuffle(): boolean; /** * the total size of all songs (in bytes) */ size(): number; /** * playback repeat mode (obsolete; always off) */ songRepeat(): any; /** * special playlist kind */ specialKind(): any; /** * the length of all songs in MM:SS format */ time(): string; /** * is this playlist visible in the Source list? */ visible(): 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. */ /** * a sub-window showing a single playlist */ export interface PlaylistWindow { /** * the selected songs */ selection(): any; /** * the playlist displayed in the window */ view(): 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. */ /** * the radio tuner playlist */ export interface RadioTunerPlaylist {} /** * 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 track residing in a shared library */ export interface SharedTrack {} /** * 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 music source (music library, CD, device, etc.) */ export interface Source { /** * the total size of the source if it has a fixed size */ capacity(): any; /** * the free space on the source if it has a fixed size */ freeSpace(): any; kind(): 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 subscription playlist from Apple Music */ export interface SubscriptionPlaylist {} /** * 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. */ /** * playable audio source */ export interface Track { /** * the album name of the track */ album(): string; /** * the album artist of the track */ albumArtist(): string; /** * is the album for this track disliked? */ albumDisliked(): boolean; /** * is the album for this track loved? */ albumLoved(): boolean; /** * the rating of the album for this track (0 to 100) */ albumRating(): number; /** * the rating kind of the album rating for this track */ albumRatingKind(): any; /** * the artist/source of the track */ artist(): string; /** * the bit rate of the track (in kbps) */ bitRate(): number; /** * the bookmark time of the track in seconds */ bookmark(): any; /** * is the playback position for this track remembered? */ bookmarkable(): boolean; /** * the tempo of this track in beats per minute */ bpm(): number; /** * the category of the track */ category(): string; /** * the iCloud status of the track */ cloudStatus(): any; /** * freeform notes about the track */ comment(): string; /** * is this track from a compilation album? */ compilation(): boolean; /** * the composer of the track */ composer(): string; /** * the common, unique ID for this track. If two tracks in different playlists have the same database ID, they are sharing the same data. */ databaseID(): number; /** * the date the track was added to the playlist */ dateAdded(): any; /** * the description of the track */ description(): string; /** * the total number of discs in the source album */ discCount(): number; /** * the index of the disc containing this track on the source album */ discNumber(): number; /** * is this track disliked? */ disliked(): boolean; /** * the Apple ID of the person who downloaded this track */ downloaderAppleID(): string; /** * the name of the person who downloaded this track */ downloaderName(): string; /** * the length of the track in seconds */ duration(): any; /** * is this track checked for playback? */ enabled(): boolean; /** * the episode ID of the track */ episodeID(): string; /** * the episode number of the track */ episodeNumber(): number; /** * the name of the EQ preset of the track */ EQ(): string; /** * the stop time of the track in seconds */ finish(): any; /** * is this track from a gapless album? */ gapless(): boolean; /** * the music/audio genre (category) of the track */ genre(): string; /** * the grouping (piece) of the track. Generally used to denote movements within a classical work. */ grouping(): string; /** * a text description of the track */ kind(): string; longDescription(): string; /** * is this track loved? */ loved(): boolean; /** * the lyrics of the track */ lyrics(): string; /** * the media kind of the track */ mediaKind(): any; /** * the modification date of the content of this track */ modificationDate(): any; /** * the movement name of the track */ movement(): string; /** * the total number of movements in the work */ movementCount(): number; /** * the index of the movement in the work */ movementNumber(): number; /** * number of times this track has been played */ playedCount(): number; /** * the date and time this track was last played */ playedDate(): any; /** * the Apple ID of the person who purchased this track */ purchaserAppleID(): string; /** * the name of the person who purchased this track */ purchaserName(): string; /** * the rating of this track (0 to 100) */ rating(): number; /** * the rating kind of this track */ ratingKind(): any; /** * the release date of this track */ releaseDate(): any; /** * the sample rate of the track (in Hz) */ sampleRate(): number; /** * the season number of the track */ seasonNumber(): number; /** * is this track included when shuffling? */ shufflable(): boolean; /** * number of times this track has been skipped */ skippedCount(): number; /** * the date and time this track was last skipped */ skippedDate(): any; /** * the show name of the track */ show(): string; /** * override string to use for the track when sorting by album */ sortAlbum(): string; /** * override string to use for the track when sorting by artist */ sortArtist(): string; /** * override string to use for the track when sorting by album artist */ sortAlbumArtist(): string; /** * override string to use for the track when sorting by name */ sortName(): string; /** * override string to use for the track when sorting by composer */ sortComposer(): string; /** * override string to use for the track when sorting by show name */ sortShow(): string; /** * the size of the track (in bytes) */ size(): any; /** * the start time of the track in seconds */ start(): any; /** * the length of the track in MM:SS format */ time(): string; /** * the total number of tracks on the source album */ trackCount(): number; /** * the index of the track on the source album */ trackNumber(): number; /** * is this track unplayed? */ unplayed(): boolean; /** * kind of video track */ videoKind(): any; /** * relative volume adjustment of the track (-100% to 100%) */ volumeAdjustment(): number; /** * the work name of the track */ work(): string; /** * the year the track was recorded/released */ year(): 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 track representing a network stream */ export interface URLTrack { /** * the URL for this track */ address(): 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. */ /** * custom playlists created by the user */ export interface UserPlaylist { /** * is this playlist shared? */ shared(): boolean; /** * is this a Smart Playlist? */ smart(): boolean; /** * is this a Genius Playlist? */ genius(): 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. */ /** * the video window */ export interface VideoWindow {} /** * 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 visual plug-in */ export interface Visual {} /** * 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. */ /** * any window */ export interface Window { /** * the boundary rectangle for the window */ bounds(): any; /** * does the window have a close button? */ closeable(): boolean; /** * does the window have a collapse button? */ collapseable(): boolean; /** * is the window collapsed? */ collapsed(): boolean; /** * is the window full screen? */ fullScreen(): boolean; /** * the upper left position of the window */ position(): any; /** * is the window resizable? */ resizable(): boolean; /** * is the window visible? */ visible(): boolean; /** * is the window zoomable? */ zoomable(): boolean; /** * is the window zoomed? */ zoomed(): boolean; } // CLass Extension // 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 PrintSettings { /** * the number of copies of a document to be printed */ copies(): number; /** * Should printed copies be collated? */ collating(): boolean; /** * the first page of the document to be printed */ startingPage(): number; /** * the last page of the document to be printed */ endingPage(): number; /** * number of logical pages laid across a physical page */ pagesAcross(): number; /** * number of logical pages laid out down a physical page */ pagesDown(): number; /** * how errors are handled */ errorHandling(): any; /** * the time at which the desktop printer should print the document */ requestedPrintTime(): any; /** * printer specific options */ printerFeatures(): any; /** * for fax number */ faxNumber(): string; /** * for target printer */ targetPrinter(): string; } // 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 PrintOptionalParameter { /** * Should the application show the print dialog */ printDialog?: boolean; /** * the print settings */ withProperties?: any; /** * the kind of printout desired */ kind?: any; /** * name of theme to use for formatting the printout */ theme?: 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. */ export interface CountOptionalParameter { /** * the class of the elements to be counted. Keyword 'each' is optional in AppleScript */ each: 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 new location for the object(s) */ 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 element. Keyword 'new' is optional in AppleScript */ new: any; /** * the location at which to insert the element */ at?: any; /** * the initial values for the properties of the element */ 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 MoveOptionalParameter { /** * the new location for the playlist(s) */ 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 AddOptionalParameter { /** * the location of the added file(s) */ 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 PlayOptionalParameter { /** * If true, play this track once and then stop. */ once?: 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 SearchOptionalParameter { /** * the search text */ for: string; /** * area to search (default is all) */ only?: any; } } export interface iTunes extends iTunes.Application { // Functions /** * Print the specified object(s) * @param directParameter list of objects to print * @param option * */ print(directParameter?: any, option?: iTunes.PrintOptionalParameter): void; /** * Close an object * @param directParameter the object to close * */ close(directParameter: any, ): void; /** * Return the number of elements of a particular class within an object * @param directParameter the object whose elements are to be counted * @param option * @return the number of elements */ count(directParameter: any, option?: iTunes.CountOptionalParameter): number; /** * Delete an element from an object * @param directParameter the element to delete * */ delete(directParameter: any, ): void; /** * Duplicate one or more object(s) * @param directParameter the object(s) to duplicate * @param option * @return to the duplicated object(s) */ duplicate(directParameter: any, option?: iTunes.DuplicateOptionalParameter): any; /** * Verify if an object exists * @param directParameter the object in question * @return true if it exists, false if not */ exists(directParameter: any, ): boolean; /** * Make a new element * @param option * @return to the new object(s) */ make(option?: iTunes.MakeOptionalParameter): any; /** * Move playlist(s) to a new location * @param directParameter the playlist(s) to move * @param option * */ move(directParameter: iTunes.Playlist, option?: iTunes.MoveOptionalParameter): void; /** * Open the specified object(s) * @param directParameter list of objects to open * */ open(directParameter: any, ): void; /** * Run iTunes * */ run(): void; /** * Quit iTunes * */ quit(): void; /** * Save the specified object(s) * @param directParameter the object(s) to save * */ save(directParameter: any, ): void; /** * add one or more files to a playlist * @param directParameter the file(s) to add * @param option * @return reference to added track(s) */ add(directParameter: {}, option?: iTunes.AddOptionalParameter): iTunes.Track; /** * reposition to beginning of current track or go to previous track if already at start of current track * */ backTrack(): void; /** * convert one or more files or tracks * @param directParameter the file(s)/tracks(s) to convert * @return reference to converted track(s) */ convert(directParameter: {}, ): iTunes.Track; /** * download a cloud track or playlist, or a podcast episode * @param directParameter the shared track, URL track or playlist to download * */ download(directParameter: iTunes.Item, ): void; /** * eject the specified iPod * @param directParameter the iPod to eject * */ eject(directParameter?: iTunes.Source, ): void; /** * skip forward in a playing track * */ fastForward(): void; /** * advance to the next track in the current playlist * */ nextTrack(): void; /** * pause playback * */ pause(): void; /** * play the current track or the specified track or file. * @param directParameter item to play * @param option * */ play(directParameter?: any, option?: iTunes.PlayOptionalParameter): void; /** * toggle the playing/paused state of the current track * */ playpause(): void; /** * return to the previous track in the current playlist * */ previousTrack(): void; /** * update file track information from the current information in the track’s file * @param directParameter the file track to update * */ refresh(directParameter: iTunes.FileTrack, ): void; /** * disable fast forward/rewind and resume playback, if playing. * */ resume(): void; /** * reveal and select a track or playlist * @param directParameter the item to reveal * */ reveal(directParameter: iTunes.Item, ): void; /** * skip backwards in a playing track * */ rewind(): void; /** * search a playlist for tracks matching the search string. Identical to entering search text in the Search field in iTunes. * @param directParameter the playlist to search * @param option * @return reference to found track(s) */ search(directParameter: iTunes.Playlist, option?: iTunes.SearchOptionalParameter): iTunes.Track; /** * select the specified object(s) * @param directParameter the object(s) to select * */ select(directParameter: any, ): void; /** * stop playback * */ stop(): void; /** * subscribe to a podcast feed * @param directParameter the URL of the feed to subscribe to * */ subscribe(directParameter: string, ): void; /** * update the specified iPod * @param directParameter the iPod to update * */ update(directParameter?: iTunes.Source, ): void; /** * update all subscribed podcast feeds * */ updateAllPodcasts(): void; /** * update podcast feed * */ updatePodcast(): void; /** * Opens a Music Store or audio stream URL * @param directParameter the URL to open * */ openLocation(directParameter?: string, ): void; }
the_stack
import * as angular from 'angular'; import {moduleName} from "./module-name"; import PivotTableUtil from "./PivotTableUtil"; import * as _ from "underscore"; import * as moment from "moment"; import './module-require'; import 'pivottable-c3-renderers'; import '../../../bower_components/c3/c3.css'; import OpsManagerRestUrlService from '../services/OpsManagerRestUrlService'; export class controller implements ng.IComponentController{ selectedFeedNames: any; startDate: any; endDate: any; limitRows: any; limitOptions: any; message: any; isWarning: any; filtered: any; loading: any; pivotConfig: any; responseData: any; currentRequest: any; feedNames: any; constructor(private $scope: any, private $element: any, private $http: any, private HttpService: any, private OpsManagerJobService: any, private OpsManagerRestUrlService: any){ this.selectedFeedNames = ['All']; this.startDate = null; this.endDate = null; this.limitRows = 500; this.limitOptions=[200,500,1000,5000,10000]; this.message = ''; this.isWarning = false; this.filtered = false; this.loading = false; this.pivotConfig = {//rendererName:"Job Details", aggregatorName: "Average", vals: ["Duration (min)"], rendererName: "Stacked Bar Chart", cols: ["Start Date"], rows: ["Feed Name"], unusedAttrsVertical: false}; this.refreshPivotTable(); this.onWindowResize(); this.getFeedNames(); $scope.$on("$destroy",()=>{ $(window).off("resize.doResize"); //remove the handler added earlier }); }// end of Constructor removeAllFromArray = (arr: any)=>{ if(arr != null && arr.length >0 && _.indexOf(arr,'All') >=0){ return _.without(arr,'All'); } else { return arr; } } refreshPivotTable = ()=> { var successFn = (response: any)=> { this.responseData = response.data; var data = response.data; if(this.responseData .length >= this.limitRows && this.filtered == true){ this.message = "Warning. Only returned the first "+this.limitRows+" records. Either increase the limit or modify the filter." this.isWarning = true; } else { this.message = 'Showing '+data.length+' jobs'; } this.loading = false; this.renderPivotTable(data); }; var errorFn = (err: any)=> { console.log('error', err) } var finallyFn = ()=> { } var addToFilter = (filterStr: any, addStr: any)=> { if (filterStr != null && filterStr != "") { filterStr += ","; } filterStr += addStr; return filterStr; } var formParams = {}; var startDateSet = false; var endDateSet = false; this.filtered = false; formParams['limit'] = this.limitRows; formParams['sort'] = '-executionid'; var filter = ""; if(!_.contains(this.selectedFeedNames,'All') && this.selectedFeedNames.length >0){ filter = addToFilter(filter, "feedName==\"" + this.selectedFeedNames.join(',') + "\""); this.filtered = true; } if(this.startDate != null && this.startDate !== '') { var m = moment(this.startDate); var filterStr = 'startTimeMillis>' + m.toDate().getTime(); filter = addToFilter(filter, filterStr) this.filtered = true; startDateSet = true; } if(this.endDate != null && this.endDate !== '') { var m = moment(this.endDate); var filterStr = 'startTimeMillis<' + m.toDate().getTime(); filter = addToFilter(filter, filterStr) this.filtered = true; endDateSet = true; } if(startDateSet && !endDateSet || startDateSet && endDateSet){ formParams['sort'] = 'executionid'; } formParams['filter'] = filter; $("#charts_tab_pivot_chart").html('<div class="bg-info">Rendering Pivot Table...</div>') var rqst = this.HttpService.newRequestBuilder(this.OpsManagerJobService.JOBS_CHARTS_QUERY_URL).params(formParams).success(successFn).error(errorFn).finally(finallyFn).build(); this.currentRequest = rqst; this.loading = true; } getFeedNames=()=>{ var successFn = (response: any)=> { if (response.data) { this.feedNames = _.unique(response.data); this.feedNames.unshift('All'); } } var errorFn = (err: any)=> { } var finallyFn = ()=> { } this.$http.get(this.OpsManagerRestUrlService.FEED_NAMES_URL).then( successFn, errorFn); } renderPivotTable = (tableData: any)=> { var hideColumns = ["exceptions", "executionContext", "jobParameters", "lastUpdated", "executedSteps", "jobConfigurationName","executionId","instanceId","jobId","latest","exitStatus"]; var pivotNameMap = { "startTime": { name: "Start Time", fn: (val: any)=> { return new Date(val); } }, "endTime": { name: "End Time", fn: (val: any)=> { return new Date(val); } }, "runTime": { name: "Duration (min)", fn: (val: any)=> { return val / 1000 / 60; } } }; var pivotData = PivotTableUtil.transformToPivotTable(tableData, hideColumns, pivotNameMap); var renderers = $.extend(($ as any).pivotUtilities.renderers, ($ as any).pivotUtilities.c3_renderers); var derivers = ($ as any).pivotUtilities.derivers; var width = this.getWidth(); var height = this.getHeight(); ($("#charts_tab_pivot_chart") as any).pivotUI(pivotData, { onRefresh:(config: any)=>{ var config_copy = JSON.parse(JSON.stringify(config)); //delete some values which are functions delete config_copy["aggregators"]; delete config_copy["renderers"]; delete config_copy["derivedAttributes"]; //delete some bulky default values delete config_copy["rendererOptions"]; delete config_copy["localeStrings"]; this.pivotConfig = config_copy; this.assignLabels(); }, renderers: renderers, rendererOptions:{c3:{size:{width:width,height:height}}}, derivedAttributes: { "Start Date": ($ as any).pivotUtilities.derivers.dateFormat("Start Time", "%y-%m-%d"), "End Date": ($ as any).pivotUtilities.derivers.dateFormat("End Time", "%y-%m-%d"), "Duration (sec)": (mp: any)=>{ return mp["Duration (min)"] * 60;} }, rendererName: this.pivotConfig.rendererName, aggregatorName: this.pivotConfig.aggregatorName, vals: this.pivotConfig.vals, // rendererName: this.pivotConfig.rendererName, cols: this.pivotConfig.cols, rows: this.pivotConfig.rows, unusedAttrsVertical: this.pivotConfig.unusedAttrsVertical },true); this.$scope.lastRefreshed = new Date(); } getWidth=()=> { var sideNav = $('md-sidenav').width(); if($('.toggle-side-nav').is(':visible')){ sideNav = 0; } var rightCard = $('.filter-chart').width(); return $(window).innerWidth() -(sideNav + 400) - rightCard; } getHeight=()=> { var header = $('page-header').height(); var height = $(window).innerHeight() - (header + 450); if(height <400 ) { height = 400; } return height; } onWindowResize=()=> { $(window).on("resize.doResize", _.debounce( ()=>{ this.$scope.$apply(()=>{ if(this.$scope.lastRefreshed) { $("#charts_tab_pivot_chart").html('Rendering Chart ...'); this.renderPivotTable(this.responseData); } }); },100)); } assignLabels=()=> { if($('.pivot-label').length == 0) { $('.pvtUi').find('tbody:first').prepend('<tr><td><div class="pivot-label accent-color-3">Chart Type</div></td><td><div class="pivot-label accent-color-3">Attributes (drag and drop to customize the chart)</div></td></tr>'); $('.pvtAggregator').parents('tr:first').before('<tr><td style="font-size:3px;">&nbsp;</td><td style="font-size:3px;">&nbsp;<td></tr>') $('.pvtAggregator').parents('td:first').css('padding-bottom','10px') $('.pvtAggregator').before('<div class="pivot-label accent-color-3" style="padding-bottom:8px;">Aggregrator</div>'); $('.pvtRenderer').parent().css('vertical-align', 'top') $('.pvtRenderer').parent().css('vertical-align', 'top'); var selectWidth = $('.pvtAggregator').width(); $('#charts_tab_pivot_chart').find('select').css('width',selectWidth); $('.pvtCols').css('vertical-align','top'); } } } const module = angular.module(moduleName) .controller('ChartsController', ["$scope","$element","$http","HttpService","OpsManagerJobService","OpsManagerRestUrlService",controller]); export default module;
the_stack
import angular from 'angular' import moment from 'moment' export default function ($scope, $timeout, $log, ganttUtils, GanttObjectModel, DemoService, ganttMouseOffset, ganttDebounce) { 'ngInject' let objectModel let dataToRemove // Event handler let logScrollEvent = function (left, date, direction) { if (date !== undefined) { $log.info('[Event] api.on.scroll: ' + left + ', ' + (date === undefined ? 'undefined' : date.format()) + ', ' + direction) } } // Event handler let logDataEvent = function (eventName) { $log.info('[Event] ' + eventName) } // Event handler let logTaskEvent = function (eventName, task) { $log.info('[Event] ' + eventName + ': ' + task.model.name) } // Event handler let logRowEvent = function (eventName, row) { $log.info('[Event] ' + eventName + ': ' + row.model.name) } // Event handler let logTimespanEvent = function (eventName, timespan) { $log.info('[Event] ' + eventName + ': ' + timespan.model.name) } // Event handler let logLabelsEvent = function (eventName, width) { $log.info('[Event] ' + eventName + ': ' + width) } // Event handler let logColumnsGenerateEvent = function (columns, headers) { $log.info('[Event] ' + 'columns.on.generate' + ': ' + columns.length + ' column(s), ' + headers.length + ' header(s)') } // Event handler let logRowsFilterEvent = function (rows, filteredRows) { $log.info('[Event] rows.on.filter: ' + filteredRows.length + '/' + rows.length + ' rows displayed.') } // Event handler let logTasksFilterEvent = function (tasks, filteredTasks) { $log.info('[Event] tasks.on.filter: ' + filteredTasks.length + '/' + tasks.length + ' tasks displayed.') } // Event handler let logReadyEvent = function () { $log.info('[Event] core.on.ready') } // Event utility function let addEventName = function (eventName, func) { return function (data) { return func(eventName, data) } } // angular-gantt options $scope.options = { mode: 'custom', scale: 'day', sortMode: undefined, sideMode: 'TreeTable', daily: false, maxHeight: false, width: false, zoom: 1, columns: ['model.name', 'from', 'to'], treeTableColumns: ['from', 'to'], columnsHeaders: {'model.name': 'Name', 'from': 'From', 'to': 'To'}, columnsClasses: {'model.name': 'gantt-column-name', 'from': 'gantt-column-from', 'to': 'gantt-column-to'}, columnsFormatters: { 'from': function (from) { return from !== undefined ? from.format('lll') : undefined }, 'to': function (to) { return to !== undefined ? to.format('lll') : undefined } }, treeHeaderContent: '<i class="fa fa-align-justify"></i> {{getHeader()}}', columnsHeaderContents: { 'model.name': '<i class="fa fa-align-justify"></i> {{getHeader()}}', 'from': '<i class="fa fa-calendar"></i> {{getHeader()}}', 'to': '<i class="fa fa-calendar"></i> {{getHeader()}}' }, autoExpand: 'none', taskOutOfRange: 'truncate', fromDate: moment(null), toDate: undefined, rowContent: '<i class="fa fa-align-justify"></i> {{row.model.name}}', taskContent: '<i class="fa fa-tasks"></i> {{task.model.name}}', allowSideResizing: true, labelsEnabled: true, currentDate: 'line', currentDateValue: new Date(2013, 9, 23, 11, 20, 0), draw: false, readOnly: false, groupDisplayMode: 'group', filterTask: '', filterRow: '', timeFrames: { 'day': { start: moment('8:00', 'HH:mm'), end: moment('20:00', 'HH:mm'), color: '#ACFFA3', working: true, default: true }, 'noon': { start: moment('12:00', 'HH:mm'), end: moment('13:30', 'HH:mm'), working: false, default: true }, 'closed': { working: false, default: true }, 'weekend': { working: false }, 'holiday': { working: false, color: 'red', classes: ['gantt-timeframe-holiday'] } }, dateFrames: { 'weekend': { evaluator: function (date) { return date.isoWeekday() === 6 || date.isoWeekday() === 7 }, targets: ['weekend'] }, '11-november': { evaluator: function (date) { return date.month() === 10 && date.date() === 11 }, targets: ['holiday'] } }, timeFramesWorkingMode: 'hidden', timeFramesNonWorkingMode: 'visible', columnMagnet: '15 minutes', timeFramesMagnet: true, dependencies: { enabled: true, conflictChecker: true }, movable: { allowRowSwitching: function (task, targetRow) { return task.row.model.name !== 'Milestones' && targetRow.model.name !== 'Milestones' } }, corner: { headersLabels: function (key) { return key.charAt(0).toUpperCase() + key.slice(1) }, headersLabelsTemplates: '{{getLabel(header)}} <i class="fa fa-calendar"></i>' }, targetDataAddRowIndex: undefined, canDraw: function (event) { let isLeftMouseButton = event.button === 0 || event.button === 1 return $scope.options.draw && !$scope.options.readOnly && isLeftMouseButton }, drawTaskFactory: function () { return { id: ganttUtils.randomUuid(), // Unique id of the task. name: 'Drawn task', // Name shown on top of each task. color: '#AA8833' // Color of the task in HEX format (Optional). } }, api: function (api) { // API Object is used to control methods and events from angular-gantt. $scope.api = api api.core.on.ready($scope, function () { // Log various events to console api.scroll.on.scroll($scope, logScrollEvent) api.core.on.ready($scope, logReadyEvent) api.data.on.remove($scope, addEventName('data.on.remove', logDataEvent)) api.data.on.load($scope, addEventName('data.on.load', logDataEvent)) api.data.on.clear($scope, addEventName('data.on.clear', logDataEvent)) api.data.on.change($scope, addEventName('data.on.change', logDataEvent)) api.tasks.on.add($scope, addEventName('tasks.on.add', logTaskEvent)) api.tasks.on.change($scope, addEventName('tasks.on.change', logTaskEvent)) api.tasks.on.rowChange($scope, addEventName('tasks.on.rowChange', logTaskEvent)) api.tasks.on.remove($scope, addEventName('tasks.on.remove', logTaskEvent)) if (api.tasks.on.moveBegin) { api.tasks.on.moveBegin($scope, addEventName('tasks.on.moveBegin', logTaskEvent)) // api.tasks.on.move($scope, addEventName('tasks.on.move', logTaskEvent)); api.tasks.on.moveEnd($scope, addEventName('tasks.on.moveEnd', logTaskEvent)) api.tasks.on.resizeBegin($scope, addEventName('tasks.on.resizeBegin', logTaskEvent)) // api.tasks.on.resize($scope, addEventName('tasks.on.resize', logTaskEvent)); api.tasks.on.resizeEnd($scope, addEventName('tasks.on.resizeEnd', logTaskEvent)) } if (api.tasks.on.drawBegin) { api.tasks.on.drawBegin($scope, addEventName('tasks.on.drawBegin', logTaskEvent)) // api.tasks.on.draw($scope, addEventName('tasks.on.draw', logTaskEvent)); api.tasks.on.drawEnd($scope, addEventName('tasks.on.drawEnd', logTaskEvent)) } api.rows.on.add($scope, addEventName('rows.on.add', logRowEvent)) api.rows.on.change($scope, addEventName('rows.on.change', logRowEvent)) api.rows.on.move($scope, addEventName('rows.on.move', logRowEvent)) api.rows.on.remove($scope, addEventName('rows.on.remove', logRowEvent)) api.side.on.resizeBegin($scope, addEventName('labels.on.resizeBegin', logLabelsEvent)) // api.side.on.resize($scope, addEventName('labels.on.resize', logLabelsEvent)); api.side.on.resizeEnd($scope, addEventName('labels.on.resizeEnd', logLabelsEvent)) api.timespans.on.add($scope, addEventName('timespans.on.add', logTimespanEvent)) api.columns.on.generate($scope, logColumnsGenerateEvent) api.rows.on.filter($scope, logRowsFilterEvent) api.tasks.on.filter($scope, logTasksFilterEvent) api.data.on.change($scope, function (newData) { if (dataToRemove === undefined) { dataToRemove = [ {'id': newData[2].id}, // Remove Kickoff row { 'id': newData[0].id, 'tasks': [ {'id': newData[0].tasks[0].id}, {'id': newData[0].tasks[3].id} ] }, // Remove some Milestones { 'id': newData[7].id, 'tasks': [ {'id': newData[7].tasks[0].id} ] } // Remove order basket from Sprint 2 ] } }) // When gantt is ready, load data. // `data` attribute could have been used too. $scope.load() // Add some DOM events api.directives.on.new($scope, function (directiveName, directiveScope, element) { if (directiveName === 'ganttTask') { element.bind('click', function (event) { event.stopPropagation() logTaskEvent('task-click', directiveScope.task) }) element.bind('mousedown touchstart', function (event) { event.stopPropagation() $scope.live.row = directiveScope.task.row.model if (directiveScope.task.originalModel !== undefined) { $scope.live.task = directiveScope.task.originalModel } else { $scope.live.task = directiveScope.task.model } $scope.$digest() }) } else if (directiveName === 'ganttRow') { element.bind('click', function (event) { event.stopPropagation() logRowEvent('row-click', directiveScope.row) }) element.bind('mousedown touchstart', function (event) { event.stopPropagation() $scope.live.row = directiveScope.row.model $scope.$digest() }) } else if (directiveName === 'ganttRowLabel') { element.bind('click', function () { logRowEvent('row-label-click', directiveScope.row) }) element.bind('mousedown touchstart', function () { $scope.live.row = directiveScope.row.model $scope.$digest() }) } }) api.tasks.on.rowChange($scope, function (task) { $scope.live.row = task.row.model }) objectModel = new GanttObjectModel(api) }) } } $scope.handleTaskIconClick = function (taskModel) { alert('Icon from ' + taskModel.name + ' task has been clicked.') } $scope.handleRowIconClick = function (rowModel) { alert('Icon from ' + rowModel.name + ' row has been clicked.') } $scope.expandAll = function () { $scope.api.tree.expandAll() } $scope.collapseAll = function () { $scope.api.tree.collapseAll() } $scope.$watch('options.sideMode', function (newValue, oldValue) { if (newValue !== oldValue) { $scope.api.side.setWidth(undefined) $timeout(function () { $scope.api.columns.refresh() }) } }) $scope.canAutoWidth = function (scale) { if (scale.match(/.*?hour.*?/) || scale.match(/.*?minute.*?/)) { return false } return true } $scope.getColumnWidth = function (widthEnabled, scale, zoom) { if (!widthEnabled && $scope.canAutoWidth(scale)) { return undefined } if (scale.match(/.*?week.*?/)) { return 150 * zoom } if (scale.match(/.*?month.*?/)) { return 300 * zoom } if (scale.match(/.*?quarter.*?/)) { return 500 * zoom } if (scale.match(/.*?year.*?/)) { return 800 * zoom } return 40 * zoom } // Reload data action $scope.load = function () { $scope.data = DemoService.getSampleData() dataToRemove = undefined $scope.timespans = DemoService.getSampleTimespans() } $scope.reload = function () { $scope.load() } // Remove data action $scope.remove = function () { $scope.api.data.remove(dataToRemove) $scope.api.dependencies.refresh() } // Clear data action $scope.clear = function () { $scope.data = [] } // Add data to target row index $scope.addOverlapTaskToTargetRowIndex = function () { let targetDataAddRowIndex = parseInt($scope.options.targetDataAddRowIndex, 10) if (targetDataAddRowIndex) { let targetRow = $scope.data[$scope.options.targetDataAddRowIndex] if (targetRow && targetRow.tasks && targetRow.tasks.length > 0) { let firstTaskInRow = targetRow.tasks[0] let copiedColor = firstTaskInRow.color let firstTaskEndDate = firstTaskInRow.to.toDate() let overlappingFromDate = new Date(firstTaskEndDate) overlappingFromDate.setDate(overlappingFromDate.getDate() - 1) let overlappingToDate = new Date(overlappingFromDate) overlappingToDate.setDate(overlappingToDate.getDate() + 7) targetRow.tasks.push({ 'name': 'Overlapping', 'from': overlappingFromDate, 'to': overlappingToDate, 'color': copiedColor }) } } } // Visual two way binding. $scope.live = {} let debounceValue = 1000 let listenTaskJson = ganttDebounce(function (taskJson) { if (taskJson !== undefined) { let task = angular.fromJson(taskJson) objectModel.cleanTask(task) let model = $scope.live.task angular.merge(model, task) } }, debounceValue) $scope.$watch('live.taskJson', listenTaskJson) let listenRowJson = ganttDebounce(function (rowJson) { if (rowJson !== undefined) { let row = angular.fromJson(rowJson) objectModel.cleanRow(row) let tasks = row.tasks delete row.tasks delete row.drawTask let rowModel = $scope.live.row angular.merge(rowModel, row) let newTasks = {} let i let l if (tasks !== undefined) { for (i = 0, l = tasks.length; i < l; i++) { objectModel.cleanTask(tasks[i]) } for (i = 0, l = tasks.length; i < l; i++) { newTasks[tasks[i].id] = tasks[i] } if (rowModel.tasks === undefined) { rowModel.tasks = [] } for (i = rowModel.tasks.length - 1; i >= 0; i--) { let existingTask = rowModel.tasks[i] let newTask = newTasks[existingTask.id] if (newTask === undefined) { rowModel.tasks.splice(i, 1) } else { objectModel.cleanTask(newTask) angular.merge(existingTask, newTask) delete newTasks[existingTask.id] } } } else { delete rowModel.tasks } angular.forEach(newTasks, function (newTask) { rowModel.tasks.push(newTask) }) } }, debounceValue) $scope.$watch('live.rowJson', listenRowJson) $scope.$watchCollection('live.task', function (task) { $timeout(function () { $scope.live.taskJson = angular.toJson(task, true) $scope.live.rowJson = angular.toJson($scope.live.row, true) }) }) $scope.$watchCollection('live.row', function (row) { $timeout(function () { $scope.live.rowJson = angular.toJson(row, true) if (row !== undefined && row.tasks !== undefined && row.tasks.indexOf($scope.live.task) < 0) { $scope.live.task = row.tasks[0] } }) }) $scope.$watchCollection('live.row.tasks', function () { $timeout(function () { $scope.live.rowJson = angular.toJson($scope.live.row, true) }) }) }
the_stack
import { Component, ContentChild, EventEmitter, forwardRef, Injector, Input, OnDestroy, OnInit, Output, Renderer2, TemplateRef, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subscription, Observable, of } from 'rxjs'; import { catchError, debounceTime, switchMap } from 'rxjs/operators'; import { get } from '../../../utility/services/object-utility.class'; import { DropdownTranslations } from '../../models/dropdown-translations.model'; import { DropdownOption } from '../../models/dropdown-option.model'; import { DropdownOptionGroup } from '../../models/dropdown-option-group.model'; import { DropdownRequestParams } from '../../models/dropdown-request-params.model'; import { DropdownDataBindCallback } from '../../models/dropdown-data-bind-callback.model'; import { DropdownQueryResult } from '../../models/dropdown-query-result.model'; import { DropdownSelectMode } from '../../models/dropdown-select-mode.model'; import { DropdownViewComponent } from '../dropdown-view/dropdown-view.component'; import { PopoverComponentLoaderFactoryService } from '../../../utility/utility.module'; import { DropdownConfigService } from '../../services/dropdown-config.service'; import { DropdownDataStateService } from '../../services/dropdown-data-state.service'; import { DropdownEventStateService } from '../../services/dropdown-event-state.service'; import { DropdownResourceService } from '../../services/dropdown-resource.service'; import { ViewPosition } from '../../../utility/models/view-position.model'; import { ValidatorService } from '../../../utility/services/validator.service'; /** * Dropdown main component. */ @Component({ selector: 'ng-dropdown', templateUrl: './dropdown.component.html', providers: [ DropdownConfigService, DropdownDataStateService, DropdownEventStateService, DropdownResourceService, { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropdownComponent), multi: true } ] }) export class DropdownComponent implements OnInit, OnDestroy, ControlValueAccessor { private onSelectChangeSubscription: Subscription; @ContentChild('ngDropdownLoadingSpinner', { static: true }) public loadingSpinnerTemplate: TemplateRef<any>; @ContentChild('ngDropdownOption', { static: true }) public set optionTemplate(value: TemplateRef<any>) { this.dataStateService.dropdownOptionTemplate = value; } @ContentChild('ngDropdownOptionGroupHeader', { static: true }) public set optionGroupHeaderTemplate(value: TemplateRef<any>) { this.dataStateService.dropdownOptionGroupHeaderTemplate = value; } // Outputs : Event Handlers /** * Dropdown initialize event handler */ @Output() public init: EventEmitter<DropdownComponent>; /** * Dropdown option select change event handler */ @Output() public selectChange: EventEmitter<any[] | any>; /** * Dropdown data bind event handler */ @Output() public dataBound: EventEmitter<void>; // Input - Event handlers /** * Set data bind callback. This handler is fired on each data fetch request. */ @Input() public set onDataBind(value: DropdownDataBindCallback<any>) { this.dataStateService.onDataBind = value; } // Inputs /** * Set dropdown loading spinner template reference object. Used by data table component to explicitly pass the template reference. */ @Input() public set loadingSpinnerTemplateRef(value: TemplateRef<any>) { this.loadingSpinnerTemplate = value; } /** * Set dropdown option template reference. Used by data table component to explicitly pass the template reference. */ @Input() public set optionTemplateRef(value: TemplateRef<any>) { this.optionTemplate = value; } /** * Set dropdown options group header template reference. Used by data table component to explicitly pass the template reference. */ @Input() public set optionGroupHeaderTemplateRef(value: TemplateRef<any>) { this.optionGroupHeaderTemplate = value; } /** * Set static dropdown options collection. No need to set data source when static options collection is provided. */ @Input() public set options(value: any[]) { if (!value) { return; } this.eventStateService.staticDataSourceStream.next(value); } /** * Set data source observable. This observable is used to retrieve dropdown options for data binding. */ @Input() public set dataSource(source: Observable<any[]>) { this.initDataSource(source); } /** * Set dropdown unique identifier. */ @Input() public set id(value: string) { if (!ValidatorService.idPatternValidatorExpression.test(value)) { throw Error('Invalid [id] input value. Unique identifier parameter only accept string begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_").'); } this.dataStateService.id = value; } /** * Set translation data object. Used to localize table static label text. */ @Input() public set translations(value: DropdownTranslations) { this.config.translations = value; } /** * Set select option track by field path which is used to uniquely identify options for selection tracking. * This field support object paths expressions 'root[0].nest'. */ @Input() public set selectTrackBy(value: string) { this.config.selectTrackBy = value; } /** * Set display value track by field path which is used to extract dropdown option display value. * This field support object paths expressions 'root[0].nest'. */ @Input() public set displayTrackBy(value: string) { this.config.displayTrackBy = value; } /** * Set options group field path which is used to group the dropdown options. * This field support object paths expressions 'root[0].nest'. */ @Input() public set groupByField(value: string) { this.config.groupByField = value; } /** * Set dropdown option disable state field path which is used to disabled state dropdown options. * This field support object paths expressions 'root[0].nest'. */ @Input() public set disabledTrackBy(value: string) { this.config.disabledTrackBy = value; } /** * Set selected options collection. These options will be set selected by default on initial load. * Applicable only when multi select mode is enabled. */ @Input() public set selectedOptions(value: any[]) { this.dataStateService.selectedOptions = value || []; } /** * Set selected option. This option is selected by default on initial load. * Applicable only when single select mode is enabled. */ @Input() public set selectedOption(value: any) { this.dataStateService.selectedOption = value; } /** * Set number of options to fetch on scroll to bottom action when load on scroll mode is enabled. */ @Input() public set limit(value: number) { this.config.limit = value; } /** * Set wrap selected options in dropdown view and show the number of options selected instead when * limit is met or exceeded. Applicable only when multi select mode is enabled. */ @Input() public set wrapDisplaySelectLimit(value: number) { this.config.wrapDisplaySelectLimit = value; } /** * Set infinite scrollable state to load data on demand with scroll motion. Dropdown data fetch call is * initiated with limit and offset when user scroll to bottom hence loading the full data set on init. */ @Input() public set loadOnScroll(value: boolean) { this.config.loadOnScroll = value; } /** * Set view height ratio to trigger data fetch with infinite scrollable mode. * Higher ratio will will increase the scroll sensitivity. */ @Input() public set loadViewDistanceRatio(value: number) { this.config.loadViewDistanceRatio = value; } /** * Set option select mode. * - 'multi' : Support selecting multiple options. * - 'single' : Support selecting a single option from options collection. * - 'single-toggle' : Support selecting a single option from options collection. Selection can not be removed but * only toggled by tapping on another option. */ @Input() public set selectMode(value: DropdownSelectMode) { this.config.selectMode = value; } /** * Show dropdown option search filter text-box if true. */ @Input() public set filterable(value: boolean) { this.config.filterable = value; } /** * Set default filter value to be applied on initial load. All options are displayed when filter text value is * empty string. Applicable only when dropdown is filterable. */ @Input() public set filterText(value: string) { this.dataStateService.filterText = value; } /** * Set time based filter debounce to optimize performance and avoid request flooding by reducing the filter * request frequency if true. Applicable only when dropdown filterable state is enabled. */ @Input() public set filterDebounce(value: boolean) { this.config.filterDebounce = value; } /** * Set filter debounce time in milliseconds. Applicable only when searchDebounce is true. */ @Input() public set filterDebounceTime(value: number) { this.config.filterDebounceTime = value; } /** * Set load data on component initialize if true. */ @Input() public set loadDataOnInit(value: boolean) { this.config.loadDataOnInit = value; } /** * Show selected option remove button if true. * Applicable only when multi select mode ios enabled. */ @Input() public set showSelectedOptionRemoveButton(value: boolean) { this.config.showSelectedOptionRemoveButton = value; } /** * Set show all select options clear button if true. * Applicable only when multi select mode ios enabled. */ @Input() public set showClearSelectionButton(value: boolean) { this.config.showClearSelectionButton = value; } /** * Set options menu width in pixels. */ @Input() public set menuWidth(value: number) { this.config.menuWidth = value; } /** * Set options menu height in pixels. */ @Input() public set menuHeight(value: number) { this.config.menuHeight = value; } /** * Set popup options menu display position relative to dropdown component. * Support 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' values. */ @Input() public set menuPosition(value: ViewPosition) { this.config.menuPosition = value; } /** * Set dropdown view disabled state. */ @Input() public set disabled(value: boolean) { this.dataStateService.disabled = value; } /** * Set Close dropdown menu on option select if true. */ @Input() public set closeMenuOnSelect(value: boolean) { this.config.closeMenuOnSelect = value; } /** * Set show dropdown option select checkbox if true. */ @Input() public set showOptionSelectCheckbox(value: boolean) { this.config.showOptionSelectCheckbox = value; } /** * Set show dropdown option index checkbox if true. */ @Input() public set showOptionIndex(value: boolean) { this.config.showOptionIndex = value; } /** * Set show dropdown option TrackBy id checkbox if true. */ @Input() public set showOptionTrackBy(value: boolean) { this.config.showOptionTrackBy = value; } /** * Multi select option selected item maximum width. Apply ellipsis when selected option display text * exceed the max width. */ @Input() public set multiSelectOptionMaxWidth(value: number) { this.config.multiSelectOptionMaxWidth = value; } /** * Set first dropdown option selected on data fetch if true. */ @Input() public set setFirstOptionSelected(value: boolean) { this.config.setFirstOptionSelected = value; } /** * Trigger select change event on init if true. * Can be used to enable selectedOptions or selectedOption associated change trigger. */ @Input() public set triggerSelectChangeOnInit(value: boolean) { this.config.triggerSelectChangeOnInit = value; } /** * Set trigger select change on explicit model update if true. * Applicable only when form binding is used. */ @Input() public set triggerSelectChangeOnModelUpdate(value: boolean) { this.config.triggerSelectChangeOnModelUpdate = value; } /** * Set trigger select change on first option select change if true. * Applicable only when setFirstOptionSelected is true. */ @Input() public set triggerSelectChangeOnFirstOptionSelect(value: boolean) { this.config.triggerSelectChangeOnFirstOptionSelect = value; } /** * Set dynamically calculate dropdown view dimensions relative to dropdown button width. * MenuWith and menuHeight values are ignored when true. */ @Input() public set dynamicDimensionCalculation(value: boolean) { this.config.dynamicDimensionCalculation = value; } /** * Set dynamic dropdown options view dimensions calculation width ratio relative to dropdown selector. */ @Input() public set dynamicWidthRatio(value: number) { this.config.dynamicWidthRatio = value; } /** * Set dynamic dropdown options view dimensions calculation height ratio relative to dropdown selector. */ @Input() public set dynamicHeightRatio(value: number) { this.config.dynamicHeightRatio = value; } /** * Set relative parent element to render dropdown view container. */ @Input() public set relativeParentElement(value: HTMLElement) { this.config.relativeParentElement = value; } constructor( private componentLoaderFactory: PopoverComponentLoaderFactoryService, private injector: Injector, private eventStateService: DropdownEventStateService, private dropdownResourceService: DropdownResourceService<any>, private renderer: Renderer2, public dataStateService: DropdownDataStateService, public config: DropdownConfigService ) { this.dataStateService.componentLoaderRef = this.componentLoaderFactory.createLoader(this.renderer); this.dataBound = this.eventStateService.dataBoundStream; this.selectChange = this.eventStateService.selectChangeStream; this.init = this.eventStateService.initStream; } /** * Initialize data source. * @param source Data source stream. */ private initDataSource(source: Observable<any>): void { this.dropdownResourceService.setDataSource(source); this.dataStateService.onDataBind = (params: DropdownRequestParams): Observable<DropdownQueryResult<any>> => { if (params.hardReload) { this.dropdownResourceService.setDataSource(source); } return this.dropdownResourceService.query(params); }; } /** * Performs dropdown toggle event. * @param event Mouse click event args. * @param element Dropdown button element. */ public toggleDropdown(event: MouseEvent, element: HTMLElement): void { const target = event.target as HTMLElement; if (target && target.classList && target.classList.contains('ng-ignore-propagation')) { return; } this.dataStateService.componentLoaderRef.toggle(DropdownViewComponent, element, this.injector, { relativeParentElement: this.config.relativeParentElement, position: this.config.menuPosition }); if (this.config.dynamicDimensionCalculation) { this.config.menuWidth = element.offsetWidth * this.config.dynamicWidthRatio; this.config.menuHeight = element.offsetWidth * this.config.dynamicHeightRatio; } } /** * Get options wrapped state. */ public get wrapSelectedOptions(): boolean { if (this.config.wrapDisplaySelectLimit !== undefined) { return this.dataStateService.selectedOptions.length > this.config.wrapDisplaySelectLimit; } return false; } /** * Get wrapped option display text. */ public get wrappedOptionDisplayText(): string { return `(${this.dataStateService.selectedOptions.length}) ${this.config.translations.selectedOptionWrapPlaceholder}`; } /** * Lifecycle hook that is called when component is destroyed. */ public ngOnDestroy(): void { if (this.onSelectChangeSubscription) { this.onSelectChangeSubscription.unsubscribe(); } this.dataStateService.componentLoaderRef.dispose(); } /** * Get selected options availability state. */ public get hasSelectedOptions(): boolean { if (this.config.selectMode === 'multi') { return !!this.dataStateService.selectedOptions.length; } return !!this.dataStateService.selectedOption; } /** * Trigger select change. */ public triggerSelectChange(): void { if (this.config.selectMode === 'multi') { this.eventStateService.selectChangeStream.emit(this.dataStateService.selectedOptions); } else { this.eventStateService.selectChangeStream.emit(this.dataStateService.selectedOption); } } /** * Clear selected options. */ public clearSelectedOptions(): void { if (this.config.selectMode === 'multi') { this.dataStateService.selectedOptions = []; this.eventStateService.selectChangeStream.emit(this.dataStateService.selectedOptions); } else { this.dataStateService.selectedOption = undefined; this.eventStateService.selectChangeStream.emit(this.dataStateService.selectedOption); } } /** * Set disabled state. * ControlValueAccessor implementation. * @param isDisabled True if disabled. */ public setDisabledState?(isDisabled: boolean): void { this.dataStateService.disabled = isDisabled; } /** * Called when value selected value gets updated. * ControlValueAccessor implementation. * @param value Selected value. */ public writeValue(value: any): void { if (this.config.selectMode === 'multi') { this.dataStateService.selectedOptions = value || []; } else { this.dataStateService.selectedOption = value; } if (this.config.triggerSelectChangeOnModelUpdate) { this.triggerSelectChange(); } } /** * Register on change event. * ControlValueAccessor implementation. * @param onSelectChange On select change callback function. */ public registerOnChange(onSelectChange: (value: any[] | any) => void): void { this.onSelectChangeSubscription = this.selectChange.subscribe(value => { onSelectChange(value); }); } /** * Register on touched event. * ControlValueAccessor implementation. * @param fn Function reference. */ public registerOnTouched(fn: any): void { // TODO: Implement touch event handler } /** * Lifecycle hook that is called when component is initialized. */ public ngOnInit(): void { if (!this.dataStateService.id) { throw Error('Missing required parameter value for [id] input.'); } if (!this.dataStateService.onDataBind) { this.dataSource = this.eventStateService.staticDataSourceStream; } this.initDataFetchEvent(); if (this.config.loadDataOnInit) { this.eventStateService.dataFetchStream.emit(false); } if (this.config.triggerSelectChangeOnInit) { this.triggerSelectChange(); } this.eventStateService.initStream.emit(this); } /** * Map source data object to dropdown option model. * @param option Source dropdown option. * @param index Current index. */ private mapDropdownOption(option: any, index: number): DropdownOption { const id = get(option, this.config.selectTrackBy); return { disabled: get(option, this.config.disabledTrackBy), id, index: index + this.dataStateService.offset + 1, option, text: get(option, this.config.displayTrackBy) }; } /** * * Set dropdown options data. * @param queryResult Query result object reference. */ private setDropdownOptions(queryResult: DropdownQueryResult<any>) { if (this.config.groupByField) { this.dataStateService.dropdownOptionGroups = queryResult.options.reduce( (accumulator: DropdownOptionGroup[], option: any, index: number) => { const groupFieldValue = get(option, this.config.groupByField); const currentGroup = accumulator.find((group: DropdownOptionGroup) => group.groupName === groupFieldValue); if (currentGroup) { currentGroup.options.push(this.mapDropdownOption(option, index)); } else { accumulator.push({ groupName: groupFieldValue, options: [this.mapDropdownOption(option, index)] }); } return accumulator; }, this.config.loadOnScroll && this.dataStateService.offset > 0 ? this.dataStateService.dropdownOptionGroups : [] ); } else { this.dataStateService.dropdownOptions = queryResult.options.reduce( (accumulator: DropdownOption[], option: any, index: number) => { accumulator.push(this.mapDropdownOption(option, index)); return accumulator; }, this.config.loadOnScroll && this.dataStateService.offset > 0 ? this.dataStateService.dropdownOptions : [] ); } if (this.config.setFirstOptionSelected && queryResult.options.length) { if (this.config.selectMode === 'multi') { this.dataStateService.selectedOptions = [queryResult.options[0]]; } else { this.dataStateService.selectedOption = queryResult.options[0]; } if (this.config.triggerSelectChangeOnFirstOptionSelect) { this.triggerSelectChange(); } } this.dataStateService.totalOptionCount = queryResult.count; this.dataStateService.currentOptionCount += queryResult.options.length; } /** * On after data bind event handler. * @param queryResult Query result object reference. */ private onAfterDataBind(queryResult: DropdownQueryResult<any>): void { this.setDropdownOptions(queryResult); this.dataStateService.dataLoading = false; this.eventStateService.dataBoundStream.emit(); } /** * Fetch query results. * @param hardReload Hard reload state. */ private fetchQueryResults(hardReload: boolean): Observable<DropdownQueryResult<any>> { this.dataStateService.dataLoading = true; if (hardReload) { this.dataStateService.offset = 0; this.dataStateService.filterText = ''; } const requestParams: DropdownRequestParams = { hardReload }; if (this.config.loadOnScroll) { requestParams.limit = this.config.limit; requestParams.offset = this.dataStateService.offset; } if (this.config.filterable) { requestParams.filter = { key: this.config.displayTrackBy, value: this.dataStateService.filterText }; } return this.dataStateService.onDataBind(requestParams); } /** * Initialize data fetch event. */ private initDataFetchEvent(): void { const noop = { options: [], count: 0 }; this.eventStateService.dataFetchStream .pipe( debounceTime(20), switchMap((hardReload: boolean) => this.fetchQueryResults(hardReload)), catchError(() => { return of(noop); }) ) .subscribe( (queryResult: DropdownQueryResult<any>) => { this.onAfterDataBind(queryResult); }, () => { this.onAfterDataBind(noop); } ); } /** * Trigger explicit data fetch. * @param hardReload Hard reload state. */ public fetchData(hardReload: boolean = false): void { this.eventStateService.dataFetchStream.emit(hardReload); } /** * On select option remove event handler. * @param index Selected option index. */ public onSelectOptionRemove(index: number): void { this.dataStateService.selectedOptions.splice(index, 1); this.eventStateService.selectChangeStream.emit(this.dataStateService.selectedOptions); } /** * Close dropdown options menu. */ public close(): void { this.dataStateService.componentLoaderRef.hide(); } }
the_stack
import { fabric } from "fabric"; import { Button, Tooltip, Modal, InputNumber, Upload, Input } from 'antd'; import { nanoid } from 'nanoid'; import { history } from 'umi'; import { ArrowLeftOutlined, FontSizeOutlined, PictureOutlined, LineOutlined, BorderOutlined, ArrowUpOutlined } from '@ant-design/icons'; import { useEffect, useState, useRef, ChangeEventHandler } from 'react'; import { drawArrow, download } from '@/utils/tool'; import msk from '@/assets/msk.png'; import logo from '@/assets/logo.png'; import styles from './index.less'; type ElementType = 'IText' | 'Triangle' | 'Circle' | 'Rect' | 'Line' | 'Image' | 'Arrow' | 'Mask' const baseShapeConfig = { IText: { text: 'H5-Dooring', width : 60, height : 60, fill : '#06c' }, Triangle: { width: 100, height: 100, fill: '#06c' }, Circle: { radius: 50, fill: '#06c' }, Rect: { width : 60, height : 60, fill : '#06c' }, Line: { width: 100, height: 1, fill: '#06c' }, Arrow: {}, Image: {}, Mask: {} } export default function IndexPage() { const [imgUrl, setImgUrl] = useState(''); const [size, setSize] = useState([600, 400]); const [isShow, setIsShow] = useState(false); const [tpls, setTpls] = useState<any>(() => { const tpls = JSON.parse(localStorage.getItem('tpls') || "{}") return Object.keys(tpls).map(item => ({t: tpls[item].t, id: item})) }); const [isTplShow, setIsTplShow] = useState(false); const [attrs, setAttrs] = useState({ fill: '#0066cc', stroke: '', strokeWidth: 0, }) const canvasRef = useRef<any>(null); const tplNameRef = useRef<any>(null); // 插入元素 const insertElement = (type:ElementType, url?:string) => { let shape = null; if(type === 'IText') { shape = new fabric[type](nanoid(8), { ...baseShapeConfig[type], left: size[0] / 3, top: size[1] / 3 }) } else if(type === 'Line') { shape = new fabric.Path('M 0 0 L 100 0', { stroke: '#ccc', strokeWidth: 2, objectCaching: false, left: size[0] / 3, top: size[1] / 3 }) } else if(type === 'Arrow') { shape = new fabric.Path(drawArrow(0, 0, 100, 100, 30, 30), { stroke: '#ccc', fill: 'rgba(255,255,255,0)', strokeWidth: 2, angle: -90, objectCaching: false, left: size[0] / 3, top: size[1] / 3 }) } else if(type === 'Image'){ fabric.Image.fromURL(url || logo, function(oImg:any) { oImg.scale(0.5);//图片缩小10倍 canvasRef.current.add(oImg); }); return } else if(type === 'Mask') { fabric.Image.fromURL(msk, function(oImg:any) { oImg.scale(0.5);//图片缩小10倍 canvasRef.current.add(oImg); }, {crossOrigin: 'anonymous'}); return } else { shape = new fabric[type]({ ...baseShapeConfig[type], left: size[0] / 3, top: size[1] / 3 }) } canvasRef.current.add(shape); } // 预览 const handlePreview = () => { canvasRef.current.discardActiveObject() canvasRef.current.renderAll(); setImgUrl(getImgUrl) setIsShow(true) } // 清空画布 const clear = () => { canvasRef.current.clear(); canvasRef.current.backgroundColor = 'rgba(255,255,255,1)'; } // 关闭预览 const closeModal = () => { setIsShow(false) } // 更新画布 const updateSize = (type: 0 | 1, v:number) => { if(type) { }else { canvasRef.current.setWidth(v) setSize([v, size[1]]) } } const goBack = () => { history.goBack(); } const handleJumpH5 = () => { window.open('http://h5.dooring.cn/h5_plus'); } const getImgUrl = () => { const img = document.getElementById("canvas"); const src = (img as HTMLCanvasElement).toDataURL("image/png"); return src } const saveImg = () => { canvasRef.current.discardActiveObject() canvasRef.current.renderAll(); download(getImgUrl(), nanoid(8) + '.png') } const props = { action: '', beforeUpload(file:File) { return new Promise(resolve => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { insertElement('Image', reader.result || logo) }; }); }, }; const updateAttr = (type: 'fill' | 'stroke' | 'strokeWidth' | 'imgUrl', val:string | number) => { setAttrs({...attrs, [type]: val}) const obj = canvasRef.current.getActiveObject() obj.set({...attrs}) canvasRef.current.renderAll(); } const closeTplModal = () => { setIsTplShow(false); } const handleSaveTpl = () => { const val = tplNameRef.current.state.value const json = canvasRef.current.toDatalessJSON() const id = nanoid(8) // 存json const tpls = JSON.parse(localStorage.getItem('tpls') || "{}") tpls[id] = {json, t: val}; localStorage.setItem('tpls', JSON.stringify(tpls)) // 存图片 canvasRef.current.discardActiveObject() canvasRef.current.renderAll() const imgUrl = getImgUrl() const tplImgs = JSON.parse(localStorage.getItem('tplImgs') || "{}") tplImgs[id] = imgUrl localStorage.setItem('tplImgs', JSON.stringify(tplImgs)) setTpls((prev:any) => [...prev, {id, t: val}]) setIsTplShow(false) } const renderJson = (id:string) => { const tpls = JSON.parse(localStorage.getItem('tpls') || "{}") canvasRef.current.clear(); canvasRef.current.backgroundColor = 'rgba(255,255,255,1)'; canvasRef.current.loadFromJSON(tpls[id].json, canvasRef.current.renderAll.bind(canvasRef.current)) } const showTplModal = () => { setIsTplShow(true); } useEffect(() => { canvasRef.current = new fabric.Canvas('canvas'); // 自定义删除按钮 const deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E"; const img = document.createElement('img'); img.src = deleteIcon; fabric.Object.prototype.controls.deleteControl = new fabric.Control({ x: 0.5, y: -0.5, offsetY: -32, cursorStyle: 'pointer', mouseUpHandler: deleteObject, render: renderIcon, cornerSize: 24 }); const shape = new fabric.IText(nanoid(8), { text: 'H5-Dooring', width : 60, height : 60, fill : '#06c', left: 30, top: 30 }) canvasRef.current.add(shape); canvasRef.current.backgroundColor = 'rgba(255,255,255,1)'; canvasRef.current.on("mouse:down", function (options:any) { console.log(options, options.e.offsetX, options.e.offsetY) if(options.target) { const { fill = '#0066cc', stroke, strokeWidth = 0 } = options.target setAttrs({ fill, stroke: stroke || '', strokeWidth: strokeWidth }) canvasRef.current.renderAll(); } }); canvasRef.current.on("mouse:up", function (options:any) { }); canvasRef.current.on("mouse:move", function (options:any) { }); function deleteObject(eventData:any, transform:any) { const target = transform.target; const canvas = target.canvas; canvas.remove(target); canvas.requestRenderAll(); } function renderIcon(ctx:any, left:number, top:number, styleOverride:any, fabricObject:any) { const size = this.cornerSize; ctx.save(); ctx.translate(left, top); ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); ctx.drawImage(img, -size/2, -size/2, size, size); ctx.restore(); } }, []) return ( <div className={styles.wrap}> <header className={styles.header}> <div className={styles.goBack} onClick={goBack}><ArrowLeftOutlined /> 返回H5编辑器</div> <div className={styles.logo}>Dooring | 图片编辑器</div> <div className={styles.rightArea}><Button type="primary" onClick={handleJumpH5}>制作H5</Button></div> </header> <main className={styles.contentWrap}> <section className={styles.tplWrap}> <div className={styles.simpleTit}>模版素材</div> <div className={styles.tpls}> { tpls.map((item:{id:string,t:string},i:number) => { return <div key={i} className={styles.tplItem} onClick={() => renderJson(item.id)}> <img src={JSON.parse(localStorage.getItem('tplImgs') || "{}")[item.id]} alt="" /> <div>{ item.t }</div> </div> }) } </div> </section> <section className={styles.canvasWrap}> <div className={styles.controlWrap}> <div className={styles.leftArea}> {/* <Button className={styles.btn} size="small">撤销</Button> <Button className={styles.btn} size="small">重做</Button> */} <div> <span style={{marginRight: '10px'}}>画布大小: </span> <InputNumber size="small" min={1} defaultValue={size[0]} onChange={(v) => updateSize(0, v)} style={{width: 60, marginRight: 10}} /> <InputNumber size="small" min={1} defaultValue={size[1]} disabled style={{width: 60}} /> </div> </div> <div className={styles.rightArea}> <Button className={styles.btn} size="small">背景</Button> <Button className={styles.btn} size="small" onClick={clear}>清空</Button> <Button className={styles.btn} size="small" onClick={handlePreview}>预览</Button> </div> </div> <canvas id="canvas" width={600} height={size[1]}></canvas> </section> <section className={styles.panelWrap}> <div className={styles.simpleTit}>属性编辑</div> <div className={styles.attrPanel}> <span className={styles.label}>填充: </span> <input type="color" style={{width: 60}} value={attrs.fill} onChange={(e:ChangeEventHandler<HTMLInputElement>) => updateAttr('fill', e.target.value)} /> <span className={styles.label}>描边: </span><input type="color" value={attrs.stroke} style={{width: 60}} onChange={(e:ChangeEventHandler<HTMLInputElement>) => updateAttr('stroke', e.target.value)} /> <span className={styles.label}>描边宽度: </span> <InputNumber size="small" min={0} value={attrs.strokeWidth} style={{width: 60}} onChange={(v) => updateAttr('strokeWidth', v)} /> </div> <div className={styles.simpleTit}>插入元素</div> <div className={styles.shapeWrap}> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.text} onClick={() => insertElement('IText')}><FontSizeOutlined /></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <Upload {...props}> <div className={styles.img}><PictureOutlined /></div> </Upload> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.line} onClick={() => insertElement('Line')}><LineOutlined /></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.rect} onClick={() => insertElement('Rect')}><BorderOutlined /></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.circle} onClick={() => insertElement('Circle')}></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.tringle} onClick={() => insertElement('Triangle')}></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.arrow} onClick={() => insertElement('Arrow')}><ArrowUpOutlined /></div> </Tooltip> </div> <div className={styles.shape}> <Tooltip placement="bottom" title="点击使用"> <div className={styles.mask} onClick={() => insertElement('Mask')}><img src={msk} alt="" /></div> </Tooltip> </div> </div> <div className={styles.simpleTit}>保存</div> <div className={styles.operationArea}> <Button type="primary" block className={styles.control} onClick={saveImg}>保存图片</Button> <Button block className={styles.control} onClick={showTplModal}>保存为模版</Button> </div> </section> </main> <footer>点赞支持<a href="http://cdn.dooring.cn/dr/WechatIMG2.jpeg" target="_blank"></a></footer> <Modal title="预览图片" visible={isShow} footer={null} onCancel={closeModal} width={size[0]}> <img src={imgUrl} alt="" style={{width: '100%'}} /> </Modal> <Modal title="保存模版" visible={isTplShow} onCancel={closeTplModal} onOk={handleSaveTpl} width={500} okText="确定" cancelText="取消" > <div> <label htmlFor="">模版名称: </label> <Input placeholder="请输入模版名称" ref={tplNameRef} /> </div> </Modal> </div> ); }
the_stack
import { VNode } from 'vue'; import * as Vue from 'vue-tsx-support'; import Component from 'vue-class-component'; import { Prop, Provide, Watch } from 'vue-property-decorator'; import classNames from 'classnames'; import _Hls from 'hls.js'; import Audio, { ReadyState, events } from '@moefe/vue-audio'; import Store from '@moefe/vue-store'; import Mixin from 'utils/mixin'; import Player, { Notice } from './Player'; import PlayList from './PlayList'; import Lyric from './Lyric'; import { shuffle, HttpRequest } from '../utils'; import '../assets/style/aplayer.scss'; declare global { const Hls: typeof _Hls; } const instances: APlayer[] = []; const store = new Store(); let channel: BroadcastChannel | null = null; if (typeof BroadcastChannel !== 'undefined') { channel = new BroadcastChannel('aplayer'); } @Component({ mixins: [Mixin] }) export default class APlayer extends Vue.Component< APlayer.Options, APlayer.Events > { public static readonly version: string = APLAYER_VERSION; public readonly $refs!: { container: HTMLDivElement; }; // #region [只读] 播放器选项 @Prop({ type: Boolean, required: false, default: false }) private readonly fixed!: boolean; @Prop({ type: Boolean, required: false, default: null }) private readonly mini!: boolean; @Prop({ type: Boolean, required: false, default: false }) private readonly autoplay!: boolean; @Prop({ type: String, required: false, default: '#b7daff' }) private readonly theme!: string; @Prop({ type: String, required: false, default: 'all' }) private readonly loop!: APlayer.LoopMode; @Prop({ type: String, required: false, default: 'list' }) private readonly order!: APlayer.OrderMode; @Prop({ type: String, required: false, default: 'auto' }) private readonly preload!: APlayer.Preload; @Prop({ type: Number, required: false, default: 0.7 }) private readonly volume!: number; @Prop({ type: [Object, Array], required: true }) private readonly audio!: APlayer.Audio | Array<APlayer.Audio>; @Prop({ type: Object, required: false }) private readonly customAudioType?: any; @Prop({ type: Boolean, required: false, default: true }) private readonly mutex!: boolean; @Prop({ type: Number, required: false, default: 0 }) private readonly lrcType!: APlayer.LrcType; @Prop({ type: Boolean, required: false, default: false }) private readonly listFolded!: boolean; @Prop({ type: Number, required: false, default: 250 }) private readonly listMaxHeight!: number; @Prop({ type: String, required: false, default: 'aplayer-setting' }) private readonly storageName!: string; // #endregion // 提供当前实例的引用,让子组件获取该实例的可响应数据 @Provide() private get aplayer() { return this; } private get settings(): APlayer.Settings[] { return this.store.store; } public get currentSettings(): APlayer.Settings { return this.settings[instances.indexOf(this)]; } // 当前播放模式对应的播放列表 private get currentList() { return this.currentOrder === 'list' ? this.orderList : this.randomList; } // 数据源,自动生成 ID 作为播放列表项的 key private get dataSource(): APlayer.Audio[] { return (Array.isArray(this.audio) ? this.audio : [this.audio]) .filter(x => x) .map((item, index) => ({ id: index + 1, ...item, })); } // 根据数据源生成顺序播放列表(处理 VNode) private get orderList(): APlayer.Audio[] { const text = (vnode: string | VNode, key: string) => typeof vnode === 'string' ? vnode : vnode.data && vnode.data.attrs && vnode.data.attrs[`data-${key}`]; return this.dataSource.map(({ name, artist, ...item }) => ({ ...item, name: text(name, 'name'), artist: text(artist, 'artist'), })); } // 根据顺序播放列表生成随机播放列表 private get randomList(): APlayer.Audio[] { return shuffle([...this.orderList]); } // 是否正在缓冲 private get isLoading(): boolean { const { preload, currentPlayed, currentLoaded } = this; const { src, paused, duration } = this.media; const loading = !!src && (currentPlayed > currentLoaded || !duration); return preload === 'none' ? !paused && loading : loading; } private readonly options!: APlayer.InstallOptions; private readonly isMobile!: boolean; // 是否正在拖动进度条(防止抖动) private isDraggingProgressBar = false; // 是否正在等待进度条更新(防止抖动) private isAwaitChangeProgressBar = false; // 是否是迷你模式 private isMini = this.mini !== null ? this.mini : this.fixed; // 是否是 arrow 模式 private isArrow = false; // 当 currentMusic 改变时是否允许播放 private canPlay = !this.isMobile && this.autoplay; // 播放列表是否可见 private listVisible = !this.listFolded; private get listScrollTop(): number { return this.currentOrderIndex * 33; } // 控制迷你模式下的歌词是否可见 private lyricVisible = true; // 封面图片对象 private img = new Image(); // 封面下载对象 private xhr = new HttpRequest(); // 响应式媒体对象 private media = new Audio(); // 核心音频对象 private player = this.media.audio; // 播放器设置存储对象 private store = store; // 当前播放的音乐 private currentMusic: APlayer.Audio = { id: NaN, name: '未加载音频', artist: '(ಗ ‸ ಗ )', url: '', }; // 当前播放的音乐索引 public get currentIndex(): number { return this.currentOrder === 'list' ? this.currentOrderIndex : this.currentRandomIndex; } private get currentOrderIndex(): number { const { id, url } = this.currentMusic; return this.orderList.findIndex( item => item.id === id || item.url === url, ); } private get currentRandomIndex() { const { id, url } = this.currentMusic; return this.randomList.findIndex( item => item.id === id || item.url === url, ); } // 当前已缓冲比例 private get currentLoaded(): number { if (this.media.readyState < ReadyState.HAVE_FUTURE_DATA) return 0; const { length } = this.media.buffered; return length > 0 ? this.media.buffered.end(length - 1) / this.media.duration : 1; } // 当前已播放比例 private currentPlayed = 0; // 当前音量 private currentVolume = this.volume; // 当前循环模式 private currentLoop = this.loop; // 当前顺序模式 private currentOrder = this.order; // 当前主题,通过封面自适应主题 > 当前播放的音乐指定的主题 > 主题选项 private currentTheme = this.currentMusic.theme || this.theme; // 通知对象 private notice: Notice = { text: '', time: 2000, opacity: 0 }; // #region 监听属性 @Watch('orderList', { immediate: true, deep: true }) private async handleChangePlayList( newList: APlayer.Audio[], oldList?: APlayer.Audio[], ) { if (oldList) { const newLength = newList.length; const oldLength = oldList.length; if (newLength !== oldLength) { if (newLength <= 0) this.$emit('listClear'); else if (newLength > oldLength) this.$emit('listAdd'); else { if (this.currentOrderIndex < 0) { const { id, url } = this.currentMusic; const oldIndex = oldList.findIndex( item => item.id === id || item.url === url, ); Object.assign(this.currentMusic, oldList[oldIndex - 1]); } this.canPlay = !this.player.paused; this.$emit('listRemove'); } } } // 播放列表初始化 if (this.orderList.length > 0) { if (!this.currentMusic.id) { [this.currentMusic] = this.currentList; } else { this.canPlay = !this.player.paused; const music = this.orderList[this.currentOrderIndex] || this.orderList[0]; // eslint-disable-line max-len Object.assign(this.currentMusic, music); } await this.$nextTick(); this.canPlay = true; } } @Watch('currentMusic', { immediate: true, deep: true }) private async handleChangeCurrentMusic( newMusic: APlayer.Audio, oldMusic?: APlayer.Audio, ) { if (newMusic.theme) { this.currentTheme = newMusic.theme; } else { const cover = newMusic.cover || this.options.defaultCover; if (cover) { setTimeout(async () => { try { this.currentTheme = await this.getThemeColorFromCover(cover); } catch (e) { this.currentTheme = newMusic.theme || this.theme; } }); } } if (newMusic.url) { if ( (oldMusic !== undefined && oldMusic.url) !== newMusic.url || this.player.src !== newMusic.url ) { this.currentPlayed = 0; if (oldMusic && oldMusic.id) { // 首次初始化时不要触发事件 this.handleChangeSettings(); this.$emit('listSwitch', newMusic); } const src = await this.getAudioUrl(newMusic); if (src) this.player.src = src; this.player.playbackRate = newMusic.speed || 1; this.player.preload = this.preload; this.player.volume = this.currentVolume; this.player.currentTime = 0; this.player.onerror = (e: Event | string) => { this.showNotice(e.toString()); }; } // **请勿移动此行**,否则当歌曲结束播放时如果歌单中只有一首歌曲将无法重复播放 if (this.canPlay) this.play(); } } @Watch('volume') private handleChangeVolume(volume: number) { this.currentVolume = volume; } @Watch('currentVolume') private handleChangeCurrentVolume() { this.player.volume = this.currentVolume; this.$emit('update:volume', this.currentVolume); } @Watch('media.currentTime') private handleChangeCurrentTime() { if (!this.isDraggingProgressBar && !this.isAwaitChangeProgressBar) { this.currentPlayed = this.media.currentTime / this.media.duration || 0; } } @Watch('media.$data', { deep: true }) private handleChangeSettings() { const settings: APlayer.Settings = { currentTime: this.media.currentTime, duration: this.media.duration, paused: this.media.paused, mini: this.isMini, lrc: this.lyricVisible, list: this.listVisible, volume: this.currentVolume, loop: this.currentLoop, order: this.currentOrder, music: this.currentMusic, }; if (settings.volume <= 0) { settings.volume = this.currentSettings.volume; } this.saveSettings(settings); } @Watch('media.ended') private handleChangeEnded() { if (!this.media.ended) return; this.currentPlayed = 0; switch (this.currentLoop) { default: case 'all': this.handleSkipForward(); break; case 'one': this.play(); break; case 'none': if (this.currentIndex === this.currentList.length - 1) { [this.currentMusic] = this.currentList; this.pause(); this.canPlay = false; } else this.handleSkipForward(); break; } } @Watch('mini') private handleChangeMini() { this.isMini = this.mini; } @Watch('isMini', { immediate: true }) private async handleChangeCurrentMini(newVal: boolean, oldVal?: boolean) { await this.$nextTick(); const { container } = this.$refs; this.isArrow = container && container.offsetWidth <= 300; if (oldVal !== undefined) { this.$emit('update:mini', this.isMini); this.handleChangeSettings(); } } @Watch('loop') private handleChangeLoop() { this.currentLoop = this.loop; } @Watch('currentLoop') private handleChangeCurrentLoop() { this.$emit('update:loop', this.currentLoop); this.handleChangeSettings(); } @Watch('order') private handleChangeOrder() { this.currentOrder = this.order; } @Watch('currentOrder') private handleChangeCurrentOrder() { this.$emit('update:order', this.currentOrder); this.handleChangeSettings(); } @Watch('listVisible') private handleChangeListVisible() { this.$emit(this.listVisible ? 'listShow' : 'listHide'); this.$emit('update:listFolded', this.listVisible); this.handleChangeSettings(); } @Watch('lyricVisible') private handleChangeLyricVisible() { this.$emit(this.lyricVisible ? 'lrcShow' : 'lrcHide'); this.handleChangeSettings(); } // #endregion // #region 公开 API public async play() { try { if (this.mutex) this.pauseOtherInstances(); await this.player.play(); } catch (e) { this.showNotice(e.message); this.player.pause(); } } public pause() { this.player.pause(); } public toggle() { if (this.media.paused) this.play(); else this.pause(); } private async seeking(percent: number, paused: boolean = true) { try { this.isAwaitChangeProgressBar = true; if (this.preload === 'none') { if (!this.player.src) await this.media.srcLoaded(); const oldPaused = this.player.paused; await this.play(); // preload 为 none 的情况下必须先 play if (paused && oldPaused) this.pause(); } if (paused) this.pause(); await this.media.loaded(); this.player.currentTime = percent * this.media.duration; if (!paused) { this.play(); if (channel && this.mutex) { channel.postMessage('mutex'); } } } catch (e) { this.showNotice(e.message); } finally { this.isAwaitChangeProgressBar = false; } } public seek(time: number) { this.seeking(time / this.media.duration, this.media.paused); } public switch(audio: number | string) { switch (typeof audio) { case 'number': this.currentMusic = this.orderList[ Math.min(Math.max(0, audio), this.orderList.length - 1) ]; break; // eslint-disable-next-line no-case-declarations default: const music = this.orderList.find( item => typeof item.name === 'string' && item.name.includes(audio), ); if (music) this.currentMusic = music; break; } } public skipBack() { const playIndex = this.getPlayIndexByMode('skipBack'); this.currentMusic = { ...this.currentList[playIndex] }; } public skipForward() { const playIndex = this.getPlayIndexByMode('skipForward'); this.currentMusic = { ...this.currentList[playIndex] }; } public showLrc() { this.lyricVisible = true; } public hideLrc() { this.lyricVisible = false; } public toggleLrc() { this.lyricVisible = !this.lyricVisible; } public showList() { this.listVisible = true; } public hideList() { this.listVisible = false; } public toggleList() { this.listVisible = !this.listVisible; } public showNotice( text: string, time: number = 2000, opacity: number = 0.8, ): Promise<void> { return new Promise((resolve) => { if (this.isMini) { // eslint-disable-next-line no-console console.warn('aplayer notice:', text); resolve(); } else { this.notice = { text, time, opacity }; this.$emit('noticeShow'); if (time > 0) { setTimeout(() => { this.notice.opacity = 0; this.$emit('noticeHide'); resolve(); }, time); } } }); } // #endregion // #region 私有 API // 从封面中获取主题颜色 private getThemeColorFromCover(url: string): Promise<string> { return new Promise<string>(async (resolve, reject) => { try { if (typeof ColorThief !== 'undefined') { const image = await this.xhr.download<Blob>(url, 'blob'); const reader = new FileReader(); reader.onload = () => { this.img.src = reader.result as string; this.img.onload = () => { const [r, g, b] = new ColorThief().getColor(this.img); const theme = `rgb(${r}, ${g}, ${b})`; resolve(theme || this.currentMusic.theme || this.theme); }; this.img.onabort = reject; this.img.onerror = reject; }; reader.onabort = reject; reader.onerror = reject; reader.readAsDataURL(image); } else resolve(this.currentMusic.theme || this.theme); } catch (e) { resolve(this.currentMusic.theme || this.theme); } }); } private getAudioUrl(music: APlayer.Audio): Promise<string> { return new Promise<string>((resolve, reject) => { let { type } = music; if (type && this.customAudioType && this.customAudioType[type]) { if (typeof this.customAudioType[type] === 'function') { this.customAudioType[type](this.player, music, this); } else { // eslint-disable-next-line no-console console.error(`Illegal customType: ${type}`); } resolve(); } else { if (!type || type === 'auto') { type = /m3u8(#|\?|$)/i.test(music.url) ? 'hls' : 'normal'; } if (type === 'hls') { try { if (Hls.isSupported()) { const hls: Hls = new Hls(); hls.loadSource(music.url); hls.attachMedia(this.player as HTMLVideoElement); resolve(); } else if ( this.player.canPlayType('application/x-mpegURL') || this.player.canPlayType('application/vnd.apple.mpegURL') ) { resolve(music.url); } else { reject(new Error('HLS is not supported.')); } } catch (e) { reject(new Error('HLS is not supported.')); } } else { resolve(music.url); } } }); } private getPlayIndexByMode(type: 'skipBack' | 'skipForward'): number { const { length } = this.currentList; const index = this.currentIndex; return (type === 'skipBack' ? length + (index - 1) : index + 1) % length; } private pauseOtherInstances() { instances.filter(inst => inst !== this).forEach(inst => inst.pause()); } private saveSettings(settings: APlayer.Settings | null) { const instanceIndex = instances.indexOf(this); if (settings === null) delete instances[instanceIndex]; this.store.set( this.settings[instanceIndex] !== undefined ? this.settings.map((item, index) => index === instanceIndex ? settings : item, ) : [...this.settings, settings], ); } // #endregion // #region 事件处理 // 切换上一曲 private handleSkipBack() { this.skipBack(); } // 切换下一曲 private handleSkipForward() { this.skipForward(); } // 切换播放 private handleTogglePlay() { this.toggle(); } // 处理切换顺序模式 private handleToggleOrderMode() { this.currentOrder = this.currentOrder === 'list' ? 'random' : 'list'; } // 处理切换循环模式 private handleToggleLoopMode() { this.currentLoop = this.currentLoop === 'all' ? 'one' : this.currentLoop === 'one' ? 'none' : 'all'; } // 处理切换播放/暂停事件 private handleTogglePlaylist() { this.toggleList(); } // 处理切换歌词显隐事件 private handleToggleLyric() { this.toggleLrc(); } // 处理进度条改变事件 private handleChangeProgress(e: MouseEvent | TouchEvent, percent: number) { this.currentPlayed = percent; this.isDraggingProgressBar = e.type.includes('move'); if (['touchend', 'mouseup'].includes(e.type)) { this.seeking(percent, this.media.paused); // preload 为 none 的情况下无法获取到 duration } } // 处理切换迷你模式事件 private handleMiniSwitcher() { this.isMini = !this.isMini; } // 处理播放曲目改变事件 private handleChangePlaylist(music: APlayer.Audio, index: number) { if (music.id === this.currentMusic.id) this.handleTogglePlay(); else this.currentMusic = this.orderList[index]; } // #endregion beforeMount() { this.store.key = this.storageName; const emptyIndex = instances.findIndex(x => !x); if (emptyIndex > -1) instances[emptyIndex] = this; else instances.push(this); if (this.currentSettings) { const { mini, lrc, list, volume, loop, order, music, currentTime, duration, paused, } = this.currentSettings; this.isMini = mini; this.lyricVisible = lrc; this.listVisible = list; this.currentVolume = volume; this.currentLoop = loop; this.currentOrder = order; if (music) { this.currentMusic = music; if (!this.isMobile && duration) { this.seeking(currentTime / duration, paused); } } } // 处理多页面互斥 if (channel) { if (this.mutex) { channel.addEventListener('message', ({ data }) => { if (data === 'mutex') this.pause(); }); } } else { // 不支持 BroadcastChannel,暂不处理 } events.forEach((event) => { this.player.addEventListener(event, e => this.$emit(event, e)); }); } beforeDestroy() { this.pause(); this.saveSettings(null); this.$emit('destroy'); this.$el.remove(); } render() { const { dataSource, fixed, lrcType, isMini, isMobile, isArrow, isLoading, notice, listVisible, listScrollTop, currentMusic, lyricVisible, } = this; return ( <div ref="container" class={classNames({ aplayer: true, 'aplayer-withlist': dataSource.length > 1, 'aplayer-withlrc': !fixed && (lrcType !== 0 && lyricVisible), 'aplayer-narrow': isMini, 'aplayer-fixed': fixed, 'aplayer-mobile': isMobile, 'aplayer-arrow': isArrow, 'aplayer-loading': isLoading, })} > <Player notice={notice} onSkipBack={this.handleSkipBack} onSkipForward={this.handleSkipForward} onTogglePlay={this.handleTogglePlay} onToggleOrderMode={this.handleToggleOrderMode} onToggleLoopMode={this.handleToggleLoopMode} onTogglePlaylist={this.handleTogglePlaylist} onToggleLyric={this.handleToggleLyric} onChangeVolume={this.handleChangeVolume} onChangeProgress={this.handleChangeProgress} onMiniSwitcher={this.handleMiniSwitcher} /> <PlayList visible={listVisible} scrollTop={listScrollTop} currentMusic={currentMusic} dataSource={dataSource} onChange={this.handleChangePlaylist} /> {fixed && lrcType !== 0 ? <Lyric visible={lyricVisible} /> : null} </div> ); } }
the_stack
import Adapt, { FinalDomElement, handle, PrimitiveComponent, Sequence, useMethod } from "@adpt/core"; import { mochaTmpdir, writePackage } from "@adpt/testutils"; import execa from "execa"; import fs from "fs-extra"; import { uniq } from "lodash"; import path from "path"; import should from "should"; import { createActionPlugin } from "../../src/action/action_plugin"; import { deleteAllImages, deployIDFilter } from "../docker/common"; import { MockDeploy } from "../testlib"; import { DockerImageInstance } from "../../src/docker"; import { hasId } from "../../src/docker/image-ref"; import { LocalNodeImage, NodeImageBuildOptions, } from "../../src/nodejs"; async function checkDockerRun(image: string, ...args: string[]) { const { stdout } = await execa("docker", ["run", "--rm", image, ...args]); return stdout; } interface FinalProps { id: string; tag?: string; } class Final extends PrimitiveComponent<FinalProps> { static noPlugin = true; } describe("LocalNodeImage tests", function () { let imageIds: string[]; let mockDeploy: MockDeploy; let pluginDir: string; const deployIDs: string[] = []; this.timeout(60 * 1000); this.slow(2 * 1000); mochaTmpdir.all(`adapt-cloud-dockerbuild`); before(async function () { this.timeout(2 * 60 * 1000); await createProject(); await createWorkspaceProject(); pluginDir = path.join(process.cwd(), "plugins"); }); after(async function () { this.timeout(20 * 1000); for (const id of deployIDs) { await deleteAllImages(deployIDFilter(id)); } }); beforeEach(async () => { imageIds = []; await fs.remove(pluginDir); mockDeploy = new MockDeploy({ pluginCreates: [createActionPlugin], tmpDir: pluginDir, uniqueDeployID: true, }); await mockDeploy.init(); deployIDs.push(mockDeploy.deployID); }); interface TypescriptBuildProps { srcDir: string; options?: NodeImageBuildOptions; } function TypescriptProject(props: TypescriptBuildProps) { const img = handle<DockerImageInstance>(); const image = useMethod(img, "image"); if (image && !hasId(image)) throw new Error(`Image has no ID`); if (image) imageIds.push(image.id); return ( <Sequence> <LocalNodeImage handle={img} srcDir={props.srcDir} options={{ imageName: "tsservice", runNpmScripts: "build", ...props.options }} /> {image ? <Final id={image.id} tag={image.nameTag} /> : null} </Sequence> ); } const pkgJson = { name: "testproject", version: "0.0.1", main: "dist/index.js", scripts: { "build": "tsc && npm run build-test-var", "build-test-var": `printf '#!/usr/bin/env bash'"\\necho \${TEST_VAR}\\n" > /test-var.sh && chmod 755 /test-var.sh`, "prepublish": "if [ -r index.ts ]; then touch prepared; fi", }, devDependencies: { typescript: "3.2.x" } }; const tsConfig = JSON.stringify({ compilerOptions: { outDir: "./dist/", }, include: [ "." ] }, null, 2); const indexTs = ` function main(): void { console.log("SUCCESS"); } main(); `; const numWorkspaces = 5; // Must be at least 1 and less than 10 const pkgJsonWorkspaces = { name: "testprojectworkspaces", private: true, version: "0.0.1", scripts: { build: "yarn workspaces run build", prepare: "if [ -r workspace1/index.ts ]; then touch prepared; fi", }, workspaces: [ "workspace1", "workspace2", "**/workspace[3-9]" ], }; async function createProject() { await writePackage("./testProj", { pkgJson, files: { "index.ts": indexTs, "tsconfig.json": tsConfig, } }); } async function createWorkspaceProject() { await writePackage("./testProjWorkspaces", { pkgJson: pkgJsonWorkspaces, files: { ".dockerignore": "workspace5" } }); for (let i = 1; i <= numWorkspaces; i++) { const ws = `workspace${i}`; const name = `testproject-${ws}`; const dependencies = (i === 3) ? { "is-regexp": "^2.1.0" } : undefined; const indexContents = (() => { switch (i) { case 1: return indexTs; case 3: return `import isRegexp = require("is-regexp");\nconsole.log(isRegexp(/foo/))`; default: return indexTs.replace("SUCCESS", `SUCCESS${i}`); } })(); await writePackage(`./testProjWorkspaces/${ws}`, { pkgJson: { ...pkgJson, name, dependencies, }, files: { "index.ts": indexContents, "tsconfig.json": tsConfig, } }); } } const imgName = (options?: NodeImageBuildOptions | undefined) => ` '${(options && options.imageName) || "tsservice"}'`; async function basicTest(optionsIn?: NodeImageBuildOptions & { project?: "testProj" | "testProjWorkspaces", outputCheck?: boolean }) { const { outputCheck = true, project = "testProj", ...options } = optionsIn || {}; const orig = <TypescriptProject srcDir={`./${project}`} options={options} />; const { dom } = await mockDeploy.deploy(orig); if (dom == null) throw should(dom).not.be.Null(); const img = imgName(options); const { stdout } = mockDeploy.logger; should(stdout).equal(`INFO: Doing Building Docker image${img}\n`); should(dom.props.children).be.an.Array().with.length(2); const final: FinalDomElement = dom.props.children[1]; should(final.componentName).equal("Final"); const { id, tag } = final.props; if (id === undefined) throw should(id).not.be.Undefined(); if (tag === undefined) throw should(tag).not.be.Undefined(); should(id).match(/^sha256:[a-f0-9]{64}$/); let output = await checkDockerRun(id); if (outputCheck) should(output).equal("SUCCESS"); output = await checkDockerRun(tag); if (outputCheck) should(output).equal("SUCCESS"); const npmVersion = await checkDockerRun(id, "npm", "--version"); if (options.packageManager === "yarn" || npmVersion.startsWith("7.")) { await checkDockerRun(id, "test", "-r", "prepared"); } return { id, tag }; } it("Should build and run docker image", async () => { const { id, tag } = await basicTest(); should(tag).match(/^tsservice:[a-z]{8}$/); should(uniq(imageIds)).eql([id]); const output = await checkDockerRun(id, "node", "--version"); should(output).startWith("v14"); }); it("Should build and run docker image with different node version", async () => { const { id } = await basicTest({ nodeVersion: 12 }); const output = await checkDockerRun(id, "node", "--version"); should(output).startWith("v12"); }); it("Should build and run docker image with different base image", async () => { const { id } = await basicTest({ baseImage: "node:15-buster-slim" }); const output = await checkDockerRun(id, "node", "--version"); should(output).startWith("v15"); }); it("Should use custom name and base tag", async () => { const options = { imageName: "myimage", imageTag: "foo", }; const { id, tag } = await basicTest(options); should(tag).match(/^myimage:foo-[a-z]{8}$/); should(uniq(imageIds)).eql([id]); }); it("Should use custom name and non-random tag", async () => { const options = { imageName: "myimage", imageTag: "bar", uniqueTag: false, }; const { id, tag } = await basicTest(options); should(tag).equal("myimage:bar"); should(uniq(imageIds)).eql([id]); }); it("Should expose buildArgs during build", async () => { const testVarValue = "This is a test"; const { id } = await basicTest({ buildArgs: { TEST_VAR: testVarValue } }); const output = await checkDockerRun(id, "/test-var.sh"); should(output).equal(testVarValue); }); it("Should allow a custom command string", async () => { const testVarValue = "This is a test"; const { id } = await basicTest({ cmd: "node --version", buildArgs: { TEST_VAR: testVarValue }, outputCheck: false, }); const output = await checkDockerRun(id); should(output).startWith("v14"); }); it("Should allow a custom command array", async () => { const testVarValue = "This is a test"; const { id } = await basicTest({ cmd: ["node", "--version"], buildArgs: { TEST_VAR: testVarValue }, outputCheck: false, }); const output = await checkDockerRun(id); should(output).startWith("v14"); }); it("Should use yarn as package manager", async () => { const { id } = await basicTest({ packageManager: "yarn" }); const output = await checkDockerRun(id, "node", "--version"); should(output).startWith("v14"); }); it("Should do optimized image build", async () => { const { id } = await basicTest({ packageManager: "yarn", optimizedImage: true }); const output = await checkDockerRun(id, "node", "--version"); should(output).startWith("v14"); }); it("Should allow yarn workspaces", async () => { const { id } = await basicTest({ cmd: ["node", "/app/workspace1/dist/index.js"], packageManager: "yarn", project: "testProjWorkspaces", }); for (let i = 2; i <= numWorkspaces; i++) { switch (i) { case 3: const reVal = await checkDockerRun(id, "node", `/app/workspace${i}/dist/index.js`); should(reVal).equal(`true`); break; case 5: continue; //This is in .dockerignore, so skip it default: const output = await checkDockerRun(id, "node", `/app/workspace${i}/dist/index.js`); should(output).equal(`SUCCESS${i}`); break; } } }); it("Should do optimized workspace build", async () => { const { id } = await basicTest({ cmd: ["node", "/app/workspace1/dist/index.js"], optimizedImage: true, packageManager: "yarn", project: "testProjWorkspaces", }); for (let i = 2; i <= numWorkspaces; i++) { switch (i) { case 3: const reVal = await checkDockerRun(id, "node", `/app/workspace${i}/dist/index.js`); should(reVal).equal(`true`); break; case 5: continue; //This is in .dockerignore, so skip it default: const output = await checkDockerRun(id, "node", `/app/workspace${i}/dist/index.js`); should(output).equal(`SUCCESS${i}`); break; } } }); });
the_stack
import * as dom5 from 'dom5'; import * as fuzzaldrin from 'fuzzaldrin'; import {Document, Element, isPositionInsideRange, ParsedHtmlDocument, SourcePosition} from 'polymer-analyzer'; import {CssCustomPropertyAssignment, CssCustomPropertyUse} from 'polymer-analyzer/lib/css/css-custom-property-scanner'; import {ClientCapabilities, CompletionItem, CompletionItemKind, CompletionList, IConnection, InsertTextFormat} from 'vscode-languageserver'; import {TextDocumentPositionParams} from 'vscode-languageserver-protocol'; import {AttributesSection, AttributeValue, TagName, TextNode} from '../ast-from-source-position'; import {standardJavaScriptSnippets} from '../standard-snippets'; import {LsAnalyzer} from './analyzer-synchronizer'; import AnalyzerLSPConverter from './converter'; import FeatureFinder, {DatabindingFeature} from './feature-finder'; import {Handler} from './util'; /** * Handles as-you-type autocompletion. * * It registers on construction so that the client knows it can be called to * give suggested completions at a given position. */ export default class AutoCompleter extends Handler { private readonly clientCannotFilter: boolean; private readonly clientSupportsSnippets: boolean; private readonly preferredDocumentationFormat: 'plaintext'|'markdown'; constructor( protected connection: IConnection, private converter: AnalyzerLSPConverter, private featureFinder: FeatureFinder, private analyzer: LsAnalyzer, private capabilities: ClientCapabilities) { super(); const completionCapabilities = (this.capabilities.textDocument && this.capabilities.textDocument.completion) || {}; const completionItemCapabilities = completionCapabilities.completionItem || {}; this.clientSupportsSnippets = !!completionItemCapabilities.snippetSupport; this.preferredDocumentationFormat = 'plaintext'; const preferredFormats = completionItemCapabilities.documentationFormat || ['plaintext']; for (const preferredFormat of preferredFormats) { if (preferredFormat === 'plaintext' || preferredFormat === 'markdown') { this.preferredDocumentationFormat = preferredFormat; break; } } // Work around https://github.com/atom/atom-languageclient/issues/150 const ourExperimentalCapabilities = this.capabilities.experimental && this.capabilities.experimental['polymer-ide']; this.clientCannotFilter = ourExperimentalCapabilities ? !!ourExperimentalCapabilities.doesNotFilterCompletions : false; this.connection.onCompletion(async (request) => { const result = await this.handleErrors( this.autoComplete(request), {isIncomplete: true, items: []}); return result; }); } private async autoComplete(textPosition: TextDocumentPositionParams): Promise<CompletionList> { const url = textPosition.textDocument.uri; const result = (await this.analyzer.analyze([url], { reason: 'autocomplete' })).getDocument(url); if (!result.successful) { return {isIncomplete: true, items: []}; } const document = result.value; const position = this.converter.convertPosition(textPosition.position); const completions = await this.getTypeaheadCompletionsAtPosition(document, position); if (!completions) { return {isIncomplete: true, items: []}; } if (this.clientCannotFilter) { return this.filterCompletions(completions, position, document); } return completions; } private async getTypeaheadCompletionsAtPosition( document: Document, position: SourcePosition): Promise<CompletionList|undefined> { const locResult = await this.featureFinder.getAstAtPosition(document, position); if (!locResult) { return; } const result = await this.featureFinder.getFeatureForAstLocation(locResult, position); if (result && (result.feature instanceof DatabindingFeature)) { return this.getDatabindingCompletions(result.feature); } if (result && (result.feature instanceof CssCustomPropertyAssignment)) { return this.getCustomPropertyAssignmentCompletions( document, result.feature); } if (result && (result.feature instanceof CssCustomPropertyUse)) { return this.getCustomPropertyUseCompletions(document); } if (locResult.language === 'html') { const location = locResult.node; if (location.kind === 'tagName' || location.kind === 'text') { return this.getElementTagCompletions(document, location); } if (location.kind === 'attributeValue') { return this.getAttributeValueCompletions(document, location); } if (location.kind === 'attribute') { return this.getAttributeCompletions(document, location); } // TODO(timvdlippe): Also return these snippets if the user is in a // javascript file (locResult.language === 'js') if (location.kind === 'scriptTagContents') { return this.getStandardJavaScriptSnippetCompletions(); } } } private getCustomPropertyAssignmentCompletions( document: Document, assignment: CssCustomPropertyAssignment) { const propertyAssignments = document.getFeatures({ kind: 'css-custom-property-assignment', imported: true, externalPackages: true }); const propertyUses = document.getFeatures({ kind: 'css-custom-property-use', imported: true, externalPackages: true }); const names = new Set<string>(); for (const assignment of propertyAssignments) { names.add(assignment.name); } for (const use of propertyUses) { names.add(use.name); } names.delete(assignment.name); const items = [...names].sort().map((name): CompletionItem => { return {label: name, kind: CompletionItemKind.Variable}; }); return {isIncomplete: false, items}; } private getCustomPropertyUseCompletions(document: Document) { const propertyAssignments = document.getFeatures({ kind: 'css-custom-property-assignment', imported: true, externalPackages: true }); const names = new Set<string>([...propertyAssignments].map((a) => a.name)); const items = [...names].sort().map((name): CompletionItem => { return {label: name, kind: CompletionItemKind.Variable}; }); return {isIncomplete: false, items}; } private getDatabindingCompletions(feature: DatabindingFeature) { const element = feature.element; return { isIncomplete: false, items: [...element.properties.values(), ...element.methods.values()] .map((p) => { const sortPrefix = p.inheritedFrom ? 'ddd-' : 'aaa-'; return { label: p.name, documentation: p.description || '', type: p.type, sortText: sortPrefix + p.name, inheritedFrom: p.inheritedFrom }; }) .sort(compareAttributeResults) .map((c) => this.attributeCompletionToCompletionItem(c)) }; } private getElementTagCompletions( document: Document, location: TagName|TextNode) { const elements = [ ...document.getFeatures( {kind: 'element', externalPackages: true, imported: true}) ].filter((e) => e.tagName); const prefix = location.kind === 'tagName' ? '' : '<'; const items = elements.map((e) => { const tagName = e.tagName!; const item: CompletionItem = { label: `<${tagName}>`, documentation: this.documentationFromMarkdown(e.description), filterText: tagName.replace(/-/g, ''), kind: CompletionItemKind.Class, insertText: `${prefix}${e.tagName}></${e.tagName}>` }; if (this.clientSupportsSnippets) { item.insertText = `${prefix}${this.generateAutoCompletionForElement(e)}`; item.insertTextFormat = InsertTextFormat.Snippet; } return item; }); return {isIncomplete: false, items}; } private generateAutoCompletionForElement(e: Element): string { let autocompletion = `${e.tagName}`; let tabindex = 1; if (e.attributes.size > 0) { autocompletion += ` $${tabindex++}`; } autocompletion += `>`; if (e.slots.length === 1 && !e.slots[0]!.name) { autocompletion += `$${tabindex++}`; } else { for (const slot of e.slots) { const tagTabIndex = tabindex++; const slotAttribute = slot.name ? ` slot="${slot.name}"` : ''; autocompletion += '\n\t<${' + tagTabIndex + ':div}' + slotAttribute + '>$' + tabindex++ + '</${' + tagTabIndex + ':div}>'; } if (e.slots.length) { autocompletion += '\n'; } } return autocompletion + `</${e.tagName}>$0`; } private getAttributeValueCompletions( document: Document, location: AttributeValue): CompletionList|undefined { if (location.attribute === 'slot') { return this.getSlotNameCompletions(document, location); } const domModule = this.getAncestorDomModuleForElement(document, location.element); if (!domModule || !domModule.id) { return; } const [outerElement] = document.getFeatures({ kind: 'element', id: domModule.id, imported: true, externalPackages: true }); if (!outerElement) { return; } const sortPrefixes = this.createSortPrefixes(outerElement); const [innerElement] = document.getFeatures({ kind: 'element', id: location.element.nodeName, imported: true, externalPackages: true }); if (!innerElement) { return; } const innerAttribute = innerElement.attributes.get(location.attribute); if (!innerAttribute) { return; } const attributeValue = dom5.getAttribute(location.element, innerAttribute.name)!; const hasDelimeters = /^\s*(\{\{|\[\[)/.test(attributeValue); const attributes = [...outerElement.properties.values()].map((p) => { const sortText = (sortPrefixes.get(p.inheritedFrom) || `ddd-`) + p.name; let autocompletion; const autocompletionSnippet = undefined; if (attributeValue && hasDelimeters) { autocompletion = p.name; } else { if (innerAttribute.changeEvent) { autocompletion = `{{${p.name}}}`; } else { autocompletion = `[[${p.name}]]`; } } return { label: p.name, documentation: p.description || '', type: p.type, inheritedFrom: p.inheritedFrom, sortText, autocompletion, autocompletionSnippet, }; }); return { isIncomplete: false, items: attributes.sort(compareAttributeResults) .map((c) => this.attributeCompletionToCompletionItem(c)) }; } private getSlotNameCompletions(document: Document, location: AttributeValue) { const parent = location.element.parentNode; if (!parent || !parent.tagName) { return {isIncomplete: false, items: []}; } const parentDefinitions = document.getFeatures({ kind: 'element', id: parent.tagName, imported: true, externalPackages: true }); const slotNames = new Set(); for (const parentDefn of parentDefinitions) { for (const slot of parentDefn.slots) { if (slot.name) { slotNames.add(slot.name); } } } const items = [...slotNames].map((name): CompletionItem => { return { label: name, kind: CompletionItemKind.Variable, }; }); return {isIncomplete: false, items}; } private getAncestorDomModuleForElement( document: Document, element: dom5.Node) { const parsedDocument = document.parsedDocument; if (!(parsedDocument instanceof ParsedHtmlDocument)) { return; } const elementSourcePosition = parsedDocument.sourceRangeForNode(element)!.start; const domModules = document.getFeatures({kind: 'dom-module', imported: false}); for (const domModule of domModules) { if (isPositionInsideRange( elementSourcePosition, parsedDocument.sourceRangeForNode(domModule.node))) { return domModule; } } } private getAttributeCompletions( document: Document, location: AttributesSection) { const [element] = document.getFeatures({ kind: 'element', id: location.element.nodeName, externalPackages: true, imported: true }); const attributes: AttributeCompletion[] = []; if (element) { const sortPrefixes = this.createSortPrefixes(element); attributes.push(...[...element.attributes.values()].map((p) => { const sortText = (sortPrefixes.get(p.inheritedFrom) || `ddd-`) + p.name; return { label: p.name, documentation: p.description || '', type: p.type, inheritedFrom: p.inheritedFrom, sortText }; })); attributes.push(...[...element.events.values()].map((e) => { const postfix = sortPrefixes.get(e.inheritedFrom) || 'ddd-'; const sortText = `eee-${postfix}on-${e.name}`; return { label: `on-${e.name}`, documentation: e.description || '', type: e.type || 'CustomEvent', inheritedFrom: e.inheritedFrom, sortText }; })); } return { isIncomplete: false, items: attributes.sort(compareAttributeResults) .map((c) => this.attributeCompletionToCompletionItem(c)), }; } private getStandardJavaScriptSnippetCompletions(): CompletionList { return {isIncomplete: false, items: standardJavaScriptSnippets}; } private createSortPrefixes(element: Element): Map<string|undefined, string> { // A map from the inheritedFrom to a sort prefix. Note that // `undefined` is a legal value for inheritedFrom. const sortPrefixes = new Map<string|undefined, string>(); // Not inherited, that means local! Sort it early. sortPrefixes.set(undefined, 'aaa-'); if (element.superClass) { sortPrefixes.set(element.superClass.identifier, 'bbb-'); } if (element.extends) { sortPrefixes.set(element.extends, 'ccc-'); } return sortPrefixes; } private attributeCompletionToCompletionItem(attrCompletion: AttributeCompletion) { const item: CompletionItem = { label: attrCompletion.label, kind: CompletionItemKind.Field, documentation: this.documentationFromMarkdown(attrCompletion.documentation), sortText: attrCompletion.sortText }; if (attrCompletion.type) { item.detail = `{${attrCompletion.type}}`; } if (attrCompletion.inheritedFrom) { if (item.detail) { item.detail = `${item.detail} ⊃ ${attrCompletion.inheritedFrom}`; } else { item.detail = `⊃ ${attrCompletion.inheritedFrom}`; } } if (this.clientSupportsSnippets && attrCompletion.autocompletionSnippet) { item.insertText = attrCompletion.autocompletionSnippet; item.insertTextFormat = InsertTextFormat.Snippet; } else if (attrCompletion.autocompletion) { item.insertText = attrCompletion.autocompletion; } return item; } private filterCompletions( completions: CompletionList, position: SourcePosition, document: Document): CompletionList { const leadingText = this.getLeadingIdentifier(position, document); const filterableCompletions = completions.items.map((completion) => { return { filterText: completion.filterText || completion.label, completion }; }); const items = fuzzaldrin .filter(filterableCompletions, leadingText, {key: 'filterText'}) .map((i) => i.completion); return {isIncomplete: true, items}; } /** * If the client supports markdown for completion items, send our markdown as * markdown. * * Otherwise send it as plain text. */ documentationFromMarkdown(markdown: string) { if (this.preferredDocumentationFormat === 'markdown') { return {kind: 'markdown' as 'markdown', value: markdown}; } return markdown; } /** * Gets the identifier that comes right before the given source position. * * So e.g. calling it at the end of "hello world" should return "world", but * calling it with the line 0, character 4 should return "hell". */ private getLeadingIdentifier(position: SourcePosition, document: Document): string { const contents = document.parsedDocument.contents; const endOfSpan = document.parsedDocument.sourcePositionToOffset(position); let startOfSpan = endOfSpan; while (true) { const candidateChar = contents[startOfSpan - 1]; if (candidateChar === undefined || !candidateChar.match(/[a-zA-Z\-]/)) { break; } startOfSpan--; } return contents.slice(startOfSpan, endOfSpan); } } /** * Compare the two attributes, for sorting. * * These comparisons need to fit two constraints: * - more useful attributes at the top * - ordering is consistent, so that results don't jump around. * * Returns a comparison number for `Array#sort`. * -1 means < 0 means == 1 means > */ function compareAttributeResults< A extends {sortText: string, label: string, inheritedFrom?: string}>( a1: A, a2: A): number { let comparison = a1.sortText.localeCompare(a2.sortText); if (comparison !== 0) { return comparison; } comparison = (a1.inheritedFrom || '').localeCompare(a2.inheritedFrom || ''); if (comparison !== 0) { return comparison; } return a1.label.localeCompare(a2.label); } /** * Describes an attribute. */ interface AttributeCompletion { label: string; documentation: string; type: string|undefined; sortText: string; inheritedFrom?: string; autocompletion?: string; autocompletionSnippet?: string; }
the_stack
import { Stack } from "@aws-cdk/core"; import { IotToSqs, IotToSqsProps } from "../lib"; import '@aws-cdk/assert/jest'; import * as sqs from '@aws-cdk/aws-sqs'; import * as kms from '@aws-cdk/aws-kms'; // -------------------------------------------------------------- // Pattern deployment with default props // -------------------------------------------------------------- test('Pattern deployment with default props', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a default sqs queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: { "Fn::GetAtt": [ "testiotsqsEncryptionKey64EE64B1", "Arn" ] } }); // Creates a dead letter queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); // Creates an IoT Topic Rule expect(stack).toHaveResource("AWS::IoT::TopicRule", { TopicRulePayload: { Actions: [ { Sqs: { QueueUrl: { Ref: "testiotsqsqueue630B4C1F" }, RoleArn: { "Fn::GetAtt": [ "testiotsqsiotactionsrole93B1D327", "Arn" ] } } } ], Description: "Processing messages from IoT devices or factory machines", RuleDisabled: false, Sql: "SELECT * FROM 'test/topic/#'" } }); // Creates an encryption key expect(stack).toHaveResource("AWS::KMS::Key", { EnableKeyRotation: true }); }); // -------------------------------------------------------------- // Testing with existing SQS Queue // -------------------------------------------------------------- test('Pattern deployment with existing queue', () => { // Initial Setup const stack = new Stack(); const queue = new sqs.Queue(stack, 'existing-queue-obj', { queueName: 'existing-queue-obj' }); const props: IotToSqsProps = { existingQueueObj: queue, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a default sqs queue expect(stack).toHaveResource("AWS::SQS::Queue", { QueueName: "existing-queue-obj" }); }); // -------------------------------------------------------------- // Testing with passing queue and dead letter queue props // -------------------------------------------------------------- test('Pattern deployment with queue and dead letter queue props', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { deadLetterQueueProps: { queueName: 'dlq-name' }, queueProps: { queueName: 'queue-name' }, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a queue using the provided props expect(stack).toHaveResource("AWS::SQS::Queue", { QueueName: "queue-name", RedrivePolicy: { deadLetterTargetArn: { "Fn::GetAtt": [ "testiotsqsdeadLetterQueue66A04E81", "Arn", ], }, maxReceiveCount: 15 } }); // Creates a dead letter queue using the provided props expect(stack).toHaveResource("AWS::SQS::Queue", { QueueName: "dlq-name" }); }); // -------------------------------------------------------------- // Testing with dead letter queue turned off // -------------------------------------------------------------- test('Pattern deployment with dead letter queue turned off', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { deployDeadLetterQueue: false, queueProps: { queueName: 'queue-name' }, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a queue using the provided props expect(stack).toHaveResource("AWS::SQS::Queue", { QueueName: "queue-name" }); // Does not create the default dead letter queue expect(stack).not.toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); }); // -------------------------------------------------------------- // Testing with custom maxReceiveCount // -------------------------------------------------------------- test('Pattern deployment with custom maxReceiveCount', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { deadLetterQueueProps: { queueName: 'dlq-name' }, deployDeadLetterQueue: true, maxReceiveCount: 1, queueProps: { queueName: 'queue-name' }, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a queue using the provided props expect(stack).toHaveResource("AWS::SQS::Queue", { QueueName: "queue-name", RedrivePolicy: { deadLetterTargetArn: { "Fn::GetAtt": [ "testiotsqsdeadLetterQueue66A04E81", "Arn", ], }, maxReceiveCount: 1 }, }); }); // -------------------------------------------------------------- // Testing without creating a KMS key // -------------------------------------------------------------- test('Pattern deployment without creating a KMS key', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { enableEncryptionWithCustomerManagedKey: false, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a default sqs queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); // Creates a dead letter queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); // Creates an IoT Topic Rule expect(stack).toHaveResource("AWS::IoT::TopicRule", { TopicRulePayload: { Actions: [ { Sqs: { QueueUrl: { Ref: "testiotsqsqueue630B4C1F" }, RoleArn: { "Fn::GetAtt": [ "testiotsqsiotactionsrole93B1D327", "Arn" ] } } } ], Description: "Processing messages from IoT devices or factory machines", RuleDisabled: false, Sql: "SELECT * FROM 'test/topic/#'" } }); // Does not create an encryption key expect(stack).not.toHaveResource("AWS::KMS::Key"); }); // -------------------------------------------------------------- // Testing with existing KMS key // -------------------------------------------------------------- test('Pattern deployment with existing KMS key', () => { // Initial Setup const stack = new Stack(); const kmsKey = new kms.Key(stack, 'existing-key', { enableKeyRotation: false, alias: 'existing-key-alias' }); const props: IotToSqsProps = { encryptionKey: kmsKey, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a default sqs queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: { "Fn::GetAtt": [ "existingkey205DFC01", "Arn" ] } }); // Creates a dead letter queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); // Creates an IoT Topic Rule expect(stack).toHaveResource("AWS::IoT::TopicRule", { TopicRulePayload: { Actions: [ { Sqs: { QueueUrl: { Ref: "testiotsqsqueue630B4C1F" }, RoleArn: { "Fn::GetAtt": [ "testiotsqsiotactionsrole93B1D327", "Arn" ] } } } ], Description: "Processing messages from IoT devices or factory machines", RuleDisabled: false, Sql: "SELECT * FROM 'test/topic/#'" } }); // Uses the provided key expect(stack).toHaveResource("AWS::KMS::Key", { EnableKeyRotation: false }); }); // -------------------------------------------------------------- // Testing with passing KMS key props // -------------------------------------------------------------- test('Pattern deployment passing KMS key props', () => { // Initial Setup const stack = new Stack(); const props: IotToSqsProps = { encryptionKeyProps: { enableKeyRotation: false, alias: 'new-key-alias-from-props' }, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; new IotToSqs(stack, 'test-iot-sqs', props); // Creates a default sqs queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: { "Fn::GetAtt": [ "testiotsqsEncryptionKey64EE64B1", "Arn" ] } }); // Creates a dead letter queue expect(stack).toHaveResource("AWS::SQS::Queue", { KmsMasterKeyId: "alias/aws/sqs" }); // Creates an IoT Topic Rule expect(stack).toHaveResource("AWS::IoT::TopicRule", { TopicRulePayload: { Actions: [ { Sqs: { QueueUrl: { Ref: "testiotsqsqueue630B4C1F" }, RoleArn: { "Fn::GetAtt": [ "testiotsqsiotactionsrole93B1D327", "Arn" ] } } } ], Description: "Processing messages from IoT devices or factory machines", RuleDisabled: false, Sql: "SELECT * FROM 'test/topic/#'" } }); // Uses the props to create the key expect(stack).toHaveResource("AWS::KMS::Key", { EnableKeyRotation: false }); expect(stack).toHaveResource("AWS::KMS::Alias", { AliasName: "alias/new-key-alias-from-props", TargetKeyId: { "Fn::GetAtt": [ "testiotsqsEncryptionKey64EE64B1", "Arn", ] } }); }); // -------------------------------------------------------------- // Testing with passing a FIFO queue (not supported by IoT) // -------------------------------------------------------------- test('Pattern deployment with passing a FIFO queue (not supported by IoT)', () => { // Initial Setup const stack = new Stack(); const queue = new sqs.Queue(stack, 'existing-fifo-queue-obj', { queueName: 'existing-queue.fifo', fifo: true }); const props: IotToSqsProps = { existingQueueObj: queue, iotTopicRuleProps: { topicRulePayload: { ruleDisabled: false, description: "Processing messages from IoT devices or factory machines", sql: "SELECT * FROM 'test/topic/#'", actions: [] } } }; expect.assertions(1); try { new IotToSqs(stack, 'test-iot-sqs', props); } catch (err) { expect(err.message).toBe('The IoT SQS action doesn\'t support Amazon SQS FIFO (First-In-First-Out) queues'); } });
the_stack
import ClusterSchema, { IColumnDef } from '@/models/cassandra/ClusterSchema'; import QueryTokenizer from './CassQueryTokenizer'; const uppercaseRegex = new RegExp(/[A-Z]+/); const quotedRegex = new RegExp(/^"(.*)"$/); interface ISuggestion { name: string; value: string; score: number; meta: any; icon: string; className: string; } export default class QueryCompleter { private schema: ClusterSchema | undefined; constructor( readonly queryTokenizer: QueryTokenizer, clusterSchema: ClusterSchema | undefined, ) { this.schema = clusterSchema; } public updateSchema(schema: ClusterSchema | undefined): void { this.schema = schema; } public getCompleter(): { getCompletions(editor, _session, pos, _prefix, callback): void; } { /* eslint-disable @typescript-eslint/no-this-alias */ const self = this; const queryTokenizer = this.queryTokenizer; return { getCompletions(editor, _session, pos, _prefix, callback) { const { row, column } = pos; const allPriorTokens = queryTokenizer.getTokensUpToRow(row); const keyspaceName = queryTokenizer.getKeyspace(); const tableName = queryTokenizer.getTable(); let currentToken = editor.session.getTokenAt(row, column); if ( currentToken && (currentToken.type === 'text' || currentToken.type === 'empty') ) { currentToken = self.queryTokenizer.getPreviousNonTextToken( allPriorTokens, currentToken, ); } let suggestions = new Array<ISuggestion>(); if (currentToken) { switch (currentToken.type) { case 'statement.terminator': suggestions = []; break; case 'paren.lparen': { const previousToken = self.queryTokenizer.getPreviousNonTextToken( allPriorTokens, currentToken, ); if ( previousToken && previousToken.value.toLowerCase() === 'values' ) { suggestions = []; // user is expected to enter freeform values } else { suggestions = self.getColumnSuggestions( keyspaceName, tableName, ); } break; } case 'punctuation.comma': case 'punctuation.separator': suggestions = self.getColumnSuggestions(keyspaceName, tableName); break; case 'identifier': { const previousToken = self.queryTokenizer.getPreviousNonTextToken( allPriorTokens, currentToken, ); if ( previousToken && previousToken.type === 'keyword' && keyspaceName && tableName ) { suggestions = self.getSuggestionsForKeyword( keyspaceName, tableName, allPriorTokens, previousToken, ); } else { suggestions = self.getKeyspaceSuggestions(); } break; } case 'entity.name.table': { if ( keyspaceName && tableName && self.schema && self.schema.hasTable(keyspaceName, tableName) ) { // show the next suggestions based on the current action suggestions = self.getCurrentActionOptionSuggestions(); } else { // otherwise it's a partial match, in which case, get the list of tables for the // keyspace and use the default filtering provided by the autocomplete. suggestions = self.getTableSuggestions(keyspaceName); } break; } case 'entity.name.keyspace': suggestions = self.getKeyspaceSuggestions(); break; case 'statement.operator.equals': // no-op break; case 'punctuation.operator': // '.' character case 'where.statement.column_name': case 'select.statement.column': suggestions = self.getTableSuggestions(keyspaceName); break; case 'where.statement.column_value': suggestions = self.getCurrentActionOptionSuggestions(); break; case 'keyword': suggestions = self.getSuggestionsForKeyword( keyspaceName, tableName, allPriorTokens, currentToken, ); break; default: } } else { const containsActionToken = self.queryTokenizer.containsActionToken(); // if there's no action token (e.g. SELECT), but there is a keyspace, the user might be changing keywords, so give them the list if (!containsActionToken && keyspaceName) { suggestions = self.getActionSuggestions([ 'SELECT', 'INSERT', 'UPDATE', ]); } } callback(null, suggestions); }, }; } /** * Helper that returns a quoted representation of an entity name if necessary. * Keyspace, table, and column names are all case sensitive. If they contain mixed case, * C* requires that they be wrapped in double-quotes. * @param name The name of the entity. * @returns Returns the name wrapped in double-quotes if necessary. * @private */ private quoteName(name: string): string { if (quotedRegex.test(name)) { return name; } if (uppercaseRegex.test(name)) { return `"${name}"`; } return name; } private getKeyspaceSuggestions() { if (!this.schema) { return []; } const keyspaceNames = this.schema.getKeyspaceNames().map(this.quoteName); return this.getSuggestions(keyspaceNames, 'keyspace'); } private getColumnSuggestions(keyspaceName, tableName): ISuggestion[] { if (!this.schema) { return []; } const columns = this.schema.getColumns(keyspaceName, tableName); const columnMap = columns.reduce( (prev, curr) => prev.set(this.quoteName(curr.name), curr), new Map<string, IColumnDef>(), ); const columnNames = Array.from(columnMap.keys()); return this.getSuggestions(columnNames, (columnName) => { const column = columnMap.get(columnName) as any; if (column.isPartitionKey) { return 'partition key'; } else if (column.isClusteringColumn) { return 'clustering column'; } return 'column'; }); } private getTableSuggestions(keyspaceName) { if (!this.schema) { return []; } const tableNames = this.schema .getTableNames(keyspaceName) .map(this.quoteName); return this.getSuggestions(tableNames, 'table'); } private getActionSuggestions(actions) { return this.getSuggestions(actions, 'action'); } /** * Attempts to get the list of suggested options for the current action (e.g. SELECT/INSERT). * @returns {Array.<Object>} Returns the suggestion objects. */ private getCurrentActionOptionSuggestions() { const actionToken = this.queryTokenizer.getActionToken(); if (!actionToken) { return []; } const actionOptions = this.queryTokenizer.getOptionsForKeyword( actionToken.value, ); return this.getSuggestions(actionOptions, 'option'); } /** * Helper method for building a list of suggestions to be displayed by the completer. * @param items The items to display to the user. * @param {String|Function} meta The meta tag for each item. If the meta tag is dynamic, * a function can be passed which will be passed a single parameter `name`. * @param [options] Map of additional options. */ private getSuggestions( items: string[], meta: string | ((name: string) => string), options = {} as any, ): ISuggestion[] { return items.map((item, index) => { const metaValue = typeof meta === 'string' ? meta : meta(item); const className = `${metaValue.replace(/\s+/, '_')}Icon`; return { name: `${item}`, value: `${item}`, score: options.score || items.length - index, meta: metaValue, icon: 'property', className, }; // docText: 'some wicked doc text', }); } private getSuggestionsForKeyword( keyspaceName: string | null, tableName: string | null, previousTokens, token, ): ISuggestion[] { if (!token) { return []; } let suggestions = new Array<ISuggestion>(); switch (token.value.toLowerCase()) { case 'update': case 'from': case 'into': suggestions = this.getKeyspaceSuggestions(); break; case 'set': case 'where': case 'and': suggestions = this.getColumnSuggestions(keyspaceName, tableName); break; case 'select': { // create suggestions for the columns and an additional wildcard option suggestions = new Array<ISuggestion>().concat( this.getColumnSuggestions(keyspaceName, tableName), this.getSuggestions(['*'], 'column'), ); // fix up the score order suggestions.forEach( (item: any, index) => (item.score = suggestions.length - index), ); break; } default: { // if we have an unknown keyword, try a previous keyword const previousToken = this.queryTokenizer.getPreviousToken( previousTokens, token, ); if (previousToken && previousToken.type === 'keyword') { suggestions = this.getSuggestionsForKeyword( keyspaceName, tableName, previousTokens, previousToken, ); } break; } } return suggestions; } }
the_stack
import { ifElse } from "../App/Utilities/ifElse" import { pipe } from "../App/Utilities/pipe" import { ident } from "./Function" import { fmap, fmapF } from "./Functor" import { Internals } from "./Internals" import { cons, consF, List } from "./List" import { fromJust, isJust, Just, Maybe, Nothing } from "./Maybe" import { Pair, Tuple } from "./Tuple" export import Left = Internals.Left export import Right = Internals.Right export import isLeft = Internals.isLeft export import isRight = Internals.isRight export type Either<A, B> = Left<A> | Right<B> /** * @module Data.Either.Extra * * This module extends `Data.Either` with extra operations, particularly to * quickly extract from inside an `Either`. Some of these operations are * partial, and should be used with care in production-quality code. * * @author Lukas Obermann * @see Data.Either */ /** * `fromLeft :: a -> Either a b -> a` * * Return the contents of a `Left`-value or a default value otherwise. * * `fromLeft 1 (Left 3) == 3` * `fromLeft 1 (Right "foo") == 1` */ export const fromLeft = <A> (def: A) => (x: Either<A, any>): A => isLeft (x) ? x .value : def /** * `fromRight :: b -> Either a b -> b` * * * Return the contents of a `Right`-value or a default value otherwise. * * `fromRight 1 (Right 3) == 3` * `fromRight 1 (Left "foo") == 1` */ export const fromRight = <B> (def: B) => (x: Either<any, B>): B => isRight (x) ? x .value : def /** * `fromEither :: Either a a -> a` * * Pull the value out of an `Either` where both alternatives have the same type. * * `\x -> fromEither (Left x ) == x` * `\x -> fromEither (Right x) == x` */ export const fromEither = <A> (x: Either<A, A>): A => isRight (x) ? x .value : x .value /** * `fromLeft' :: Either l r -> l` * * The `fromLeft'` function extracts the element out of a `Left` and throws an * error if its argument is `Right`. Much like `fromJust`, using this function * in polished code is usually a bad idea. * * `\x -> fromLeft' (Left x) == x` * `\x -> fromLeft' (Right x) == undefined` * * @throws TypeError */ export const fromLeft_ = <L> (x: Left<L>): L => { if (isLeft (x)) { return x .value } throw new TypeError (`Cannot extract a Left value out of ${x}.`) } /** * `fromRight' :: Either l r -> r` * * The `fromRight'` function extracts the element out of a `Right` and throws an * error if its argument is `Left`. Much like `fromJust`, using this function * in polished code is usually a bad idea. * * `\x -> fromRight' (Right x) == x` * `\x -> fromRight' (Left x) == undefined` * * @throws TypeError */ export const fromRight_ = <R> (x: Right<R>): R => { if (isRight (x)) { return x .value } throw new TypeError (`Cannot extract a Right value out of ${x}.`) } /** * `eitherToMaybe :: Either a b -> Maybe b` * * Given an `Either`, convert it to a `Maybe`, where `Left` becomes `Nothing`. * * `\x -> eitherToMaybe (Left x) == Nothing` * `\x -> eitherToMaybe (Right x) == Just x` */ export const eitherToMaybe = <B> (x: Either<any, B>): Maybe<B> => isRight (x) ? Just (x .value) : Nothing /** * `maybeToEither :: a -> Maybe b -> Either a b` * * Given a `Maybe`, convert it to an `Either`, providing a suitable value for * the `Left` should the value be `Nothing`. * * `\a b -> maybeToEither a (Just b) == Right b` * `\a -> maybeToEither a Nothing == Left a` */ export const maybeToEither = <A> (left: A) => <B> (x: Maybe<B>): Either<A, B> => isJust (x) ? Right (fromJust (x)) : Left (left) /** * `maybeToEither' :: (() -> a) -> Maybe b -> Either a b` * * Given a `Maybe`, convert it to an `Either`, providing a suitable value for * the `Left` should the value be `Nothing`. * * `\a b -> maybeToEither a (Just b) == Right b` * `\a -> maybeToEither a Nothing == Left a` * * Lazy version of `maybeToEither`. */ export const maybeToEither_ = <A> (left: () => A) => <B> (x: Maybe<B>): Either<A, B> => isJust (x) ? Right (fromJust (x)) : Left (left ()) // BIFUNCTOR /** * `bimap :: (a -> b) -> (c -> d) -> Either a c -> Either b d` */ export const bimap = <A, B> (fLeft: (l: A) => B) => <C, D> (fRight: (r: C) => D) => (x: Either<A, C>): Either<B, D> => isRight (x) ? Right (fRight (x .value)) : Left (fLeft (x .value)) /** * `first :: (a -> b) -> Either a c -> Either b c` */ export const first = <A, B> (f: (l: A) => B) => <C> (x: Either<A, C>): Either<B, C> => isLeft (x) ? Left (f (x .value)) : x /** * `second :: (b -> c) -> Either a b -> Either a c` */ export const second = <B, C> (f: (r: B) => C) => <A> (x: Either<A, B>): Either<A, C> => isRight (x) ? Right (f (x .value)) : x // APPLICATIVE /** * `pure :: a -> Either e a` * * Lift a value. */ export const pure = Right /** * `(<*>) :: Either e (a -> b) -> Either e a -> Either e b` * * Sequential application. */ export const ap = <E, A, B> (f: Either<E, (x: A) => B>) => (x: Either<E, A>): Either<E, B> => isRight (f) ? fmap (f .value) (x) : f // MONAD /** * `(>>=) :: Either e a -> (a -> Either e b) -> Either e b` */ export const bind = <E, A> (x: Either<E, A>) => <B> (f: (x: A) => Either<E, B>): Either<E, B> => isRight (x) ? f (x .value) : x /** * `(=<<) :: (a -> Either e b) -> Either e a -> Either e b` */ export const bindF = <E, A, B> (f: (x: A) => Either<E, B>) => (x: Either<E, A>): Either<E, B> => bind (x) (f) /** * `(>>) :: Either e a -> Either e b -> Either e b` * * Sequentially compose two actions, discarding any value produced by the * first, like sequencing operators (such as the semicolon) in imperative * languages. * * ```a >> b = a >>= \ _ -> b``` */ export const then = <E, B> (x: Either<E, any>) => (y: Either<E, B>): Either<E, B> => bind (x) (_ => y) /** * `(>=>) :: (a -> Either e b) -> (b -> Either e c) -> a -> Either e c` * * Left-to-right Kleisli composition of monads. */ export const kleisli = <E, A, B, C> (f: (x: A) => Either<E, B>) => (g: (x: B) => Either<E, C>) => pipe (f, bindF (g)) /** * `join :: Either e (Either e a) -> Either e a` * * The `join` function is the conventional monad join operator. It is used to * remove one level of monadic structure, projecting its bound argument into the * outer level. */ export const join = <E, A> (x: Either<E, Either<E, A>>): Either<E, A> => bind (x) (ident) /** * `mapM :: (a -> Either e b) -> [a] -> Either e [b]` * * `mapM f xs` takes a function and a list and maps the function over every * element in the list. If the function returns a `Left`, it is immediately * returned by the function. If `f` did not return any `Left`, the list of * unwrapped return values is returned as a `Right`. If `xs` is empty, * `Right []` is returned. */ export const mapM = <E, A, B> (f: (x: A) => Either<E, B>) => (xs: List<A>): Either<E, List<B>> => List.fnull (xs) ? Right (List.empty) : ifElse<Either<E, B>, Left<E>> (isLeft) <Either<E, List<B>>> (ident) (y => second (consF (fromRight_ (y))) (mapM (f) (xs .xs))) (f (xs .x)) /** * `liftM2 :: (a1 -> a2 -> r) -> Either e a1 -> Either e a2 -> Either e r` * * Promote a function to a monad, scanning the monadic arguments from left to * right. */ export const liftM2 = <A1, A2, B> (f: (a1: A1) => (a2: A2) => B) => <E> (x1: Either<E, A1>) => (x2: Either<E, A2>): Either<E, B> => bind (x1) (pipe (f, fmapF (x2))) /** * `liftM2F :: Either e a1 -> Either e a2 -> (a1 -> a2 -> r) -> Either e r` * * Promote a function to a monad, scanning the monadic arguments from left to * right. * * Flipped version of `liftM2`. */ export const liftM2F = <E, A1> (x1: Either<E, A1>) => <A2> (x2: Either<E, A2>) => <B> (f: (a1: A1) => (a2: A2) => B): Either<E, B> => bind (x1) (pipe (f, fmapF (x2))) // FOLDABLE /** * `foldr :: (a0 -> b -> b) -> b -> Either a a0 -> b` * * Right-associative fold of a structure. */ export const foldr = <A0, B> (f: (x: A0) => (acc: B) => B) => (initial: B) => (x: Either<any, A0>): B => isRight (x) ? f (x .value) (initial) : initial /** * `foldl :: (b -> a0 -> b) -> b -> Either a a0 -> b` * * Left-associative fold of a structure. */ export const foldl = <A0, B> (f: (acc: B) => (x: A0) => B) => (initial: B) => (x: Either<any, A0>): B => isRight (x) ? f (initial) (x .value) : initial /** * `toList :: Either a a0 -> [a0]` * * List of elements of a structure, from left to right. */ export const toList = <A0> (x: Either<any, A0>): List<A0> => isRight (x) ? List (x .value) : List.empty /** * `null :: Either a a0 -> Bool` * * Test whether the structure is empty. The default implementation is optimized * for structures that are similar to cons-lists, because there is no general * way to do better. */ export const fnull = isLeft /** * `length :: Either a a0 -> Int` * * Returns the size/length of a finite structure as an `Int`. The default * implementation is optimized for structures that are similar to cons-lists, * because there is no general way to do better. */ export const flength = (x: Either<any, any>): number => isRight (x) ? 1 : 0 /** * `elem :: Eq a0 => a0 -> Either a a0 -> Bool` * * Does the element occur in the structure? * * Always returns `False` if the provided `Either` is a `Left`. */ export const elem = <A0> (x: A0) => (y: Either<any, A0>): boolean => isRight (y) && x === y .value /** * `elemF :: Eq a0 => Either a a0 -> a0 -> Bool` * * Does the element occur in the structure? * * Always returns `False` if the provided `Either` is a `Left`. * * Flipped version of `elem`. */ export const elemF = <A> (y: Either<A, A>) => (x: A): boolean => elem (x) (y) /** * `sum :: Num a => Either a a0 -> a` * * The `sum` function computes the sum of the numbers of a structure. */ export const sum = fromRight (0) /** * `product :: Num a => Either a a0 -> a` * * The `product` function computes the product of the numbers of a structure. */ export const product = fromRight (1) // Specialized folds /** * `concat :: Either a [a0] -> [a0]` * * The concatenation of all the elements of a container of lists. */ export const concat = <A0>(x: Either<any, List<A0>>): List<A0> => fromRight<List<A0>> (List.empty) (x) /** * `concatMap :: (a0 -> [b]) -> Either a a0 -> [b]` * * Map a function over all the elements of a container and concatenate the * resulting lists. */ export const concatMap = <A0, B> (f: (x: A0) => List<B>) => (x: Either<any, A0>): List<B> => fromRight<List<B>> (List.empty) (fmap (f) (x)) /** * `and :: Either a Bool -> Bool` * * `and` returns the conjunction of a container of Bools. For the result to be * `True`, the container must be finite `False`, however, results from a * `False` value finitely far from the left end. */ export const and = fromRight (true) /** * `or :: Either a Bool -> Bool` * * `or` returns the disjunction of a container of Bools. For the result to be * `False`, the container must be finite `True`, however, results from a * `True` value finitely far from the left end. */ export const or = fromRight (false) interface Any { /** * `any :: (a0 -> Bool) -> Either a a0 -> Bool` * * Determines whether any element of the structure satisfies the predicate. */ <A, A1 extends A> (f: (x: A) => x is A1): (x: Either<any, A>) => x is Right<A1> /** * `any :: (a0 -> Bool) -> Either a a0 -> Bool` * * Determines whether any element of the structure satisfies the predicate. */ <A> (f: (x: A) => boolean): (x: Either<any, A>) => x is Right<A> } /** * `any :: (a0 -> Bool) -> Either a a0 -> Bool` * * Determines whether any element of the structure satisfies the predicate. */ export const any: Any = <A0>(f: (x: A0) => boolean) => (x: Either<any, A0>): x is Right<A0> => fromRight (false) (fmap (f) (x)) /** * `all :: (a0 -> Bool) -> Either a a0 -> Bool` * * Determines whether all elements of the structure satisfy the predicate. */ export const all = <A0>(f: (x: A0) => boolean) => (x: Either<any, A0>): boolean => fromRight (true) (fmap (f) (x)) // Searches /** * `notElem :: Eq a0 => a0 -> Either a a0 -> Bool` * * `notElem` is the negation of `elem`. */ export const notElem = <A0> (x: A0) => (y: Either<any, A0>): boolean => !elem (x) (y) interface Find { /** * `find :: (a0 -> Bool) -> Either a a0 -> Maybe a0` * * The `find` function takes a predicate and a structure and returns the * leftmost element of the structure matching the predicate, or `Nothing` if * there is no such element. */ <A, A1 extends A> (pred: (x: A) => x is A1): (x: Either<any, A>) => Maybe<A1> /** * `find :: (a0 -> Bool) -> Either a a0 -> Maybe a0` * * The `find` function takes a predicate and a structure and returns the * leftmost element of the structure matching the predicate, or `Nothing` if * there is no such element. */ <A> (pred: (x: A) => boolean): (x: Either<any, A>) => Maybe<A> } /** * `find :: (a0 -> Bool) -> Either a a0 -> Maybe a0` * * The `find` function takes a predicate and a structure and returns the * leftmost element of the structure matching the predicate, or `Nothing` if * there is no such element. */ export const find: Find = <A> (pred: (x: A) => boolean) => (x: Either<any, A>): Maybe<A> => isRight (x) && pred (x .value) ? Just (x .value) : Nothing // ORD /** * `(>) :: Either a b -> Either a b -> Bool` * * Returns if the *second* value is greater than the first value. * * If the second value is a `Right` and the first is a `Left`, `(>)` always * returns `True`. * * If the second value is a `Left` and the first is a `Right`, `(>)` always * returns `False`. */ export const gt = <A extends number | string, B extends number | string> (m1: Either<A, B>) => (m2: Either<A, B>): boolean => (isRight (m2) && isLeft (m1)) || (isRight (m1) && isRight (m2) && m2 .value > m1 .value) || (isLeft (m1) && isLeft (m2) && m2 .value > m1 .value) /** * `(<) :: Either a b -> Either a b -> Bool` * * Returns if the *second* value is lower than the first value. * * If the second value is a `Left` and the first is a `Right`, `(<)` always * returns `True`. * * If the second value is a `Right` and the first is a `Left`, `(<)` always * returns `False`. */ export const lt = <A extends number | string, B extends number | string> (m1: Either<A, B>) => (m2: Either<A, B>): boolean => (isLeft (m2) && isRight (m1)) || (isRight (m1) && isRight (m2) && m2 .value < m1 .value) || (isLeft (m1) && isLeft (m2) && m2 .value < m1 .value) /** * `(>=) :: Either a b -> Either a b -> Bool` * * Returns if the *second* value is greater than or equals the first * value. * * If the second value is a `Right` and the first is a `Left`, `(>=)` always * returns `True`. * * If the second value is a `Left` and the first is a `Right`, `(>=)` always * returns `False`. */ export const gte = <A extends number | string, B extends number | string> (m1: Either<A, B>) => (m2: Either<A, B>): boolean => (isRight (m2) && isLeft (m1)) || (isRight (m1) && isRight (m2) && m2 .value >= m1 .value) || (isLeft (m1) && isLeft (m2) && m2 .value >= m1 .value) /** * `(<=) :: Either a b -> Either a b -> Bool` * * Returns if the *second* value is lower than or equals the second * value. * * If the second value is a `Left` and the first is a `Right`, `(<=)` always * returns `True`. * * If the second value is a `Right` and the first is a `Left`, `(<=)` always * returns `False`. */ export const lte = <A extends number | string, B extends number | string> (m1: Either<A, B>) => (m2: Either<A, B>): boolean => (isLeft (m2) && isRight (m1)) || (isRight (m1) && isRight (m2) && m2 .value <= m1 .value) || (isLeft (m1) && isLeft (m2) && m2 .value <= m1 .value) // EITHER FUNCTIONS (PART 2) /** * `either :: (a -> c) -> (b -> c) -> Either a b -> c` * * Case analysis for the `Either` type. If the value is `Left a`, apply the * first function to `a` if it is `Right b`, apply the second function to `b`. */ export const either = <A, C> (fLeft: (l: A) => C) => <B> (fRight: (r: B) => C) => (x: Either<A, B>): C => isRight (x) ? fRight (x .value) : fLeft (x .value) /** * `lefts :: [Either a b] -> [a]` * * Extracts from a list of `Either` all the `Left` elements. All the `Left` * elements are extracted in order. */ export const lefts = <A, B> (xs: List<Either<A, B>>): List<A> => List.foldr<Either<A, B>, List<A>> (x => acc => isLeft (x) ? cons (acc) (x .value) : acc) (List.empty) (xs) /** * `rights :: [Either a b] -> [b]` * * Extracts from a list of `Either` all the `Right` elements. All the `Right` * elements are extracted in order. */ export const rights = <A, B> (xs: List<Either<A, B>>): List<B> => List.foldr<Either<A, B>, List<B>> (x => acc => isRight (x) ? cons (acc) (x .value) : acc) (List.empty) (xs) /** * `partitionEithers :: [Either a b] -> ([a], [b])` * * Partitions a list of `Either` into two lists. All the `Left` elements are * extracted, in order, to the first component of the output. Similarly the * `Right` elements are extracted to the second component of the output. */ export const partitionEithers = <A, B> (xs: List<Either<A, B>>): Pair<List<A>, List<B>> => List.foldr<Either<A, B>, Pair<List<A>, List<B>>> (x => isRight (x) ? Tuple.second (consF (x .value)) : Tuple.first (consF (x .value))) (Pair<List<A>, List<B>> (List.empty, List.empty)) (xs) // CUSTOM FUNCTIONS export import isEither = Internals.isEither const imapMIndex = (i: number) => <E, A, B> (f: (i: number) => (x: A) => Either<E, B>) => (xs: List<A>): Either<E, List<B>> => List.fnull (xs) ? Right (List.empty) : ifElse<Either<E, B>, Left<E>> (isLeft) <Either<E, List<B>>> (ident) (y => second (consF (fromRight_ (y))) (imapMIndex (i + 1) (f) (xs .xs))) (f (i) (xs .x)) /** * `imapM :: (Int -> a -> Either e b) -> [a] -> Either e [b]` * * `imapM f xs` takes a function and a list and maps the function over every * element in the list. If the function returns a `Left`, it is immediately * returned by the function. If `f` did not return any `Left`, the list of * unwrapped return values is returned as a `Right`. If `xs` is empty, * `Right []` is returned. */ export const imapM = <E, A, B> (f: (index: number) => (x: A) => Either<E, B>) => (xs: List<A>): Either<E, List<B>> => imapMIndex (0) (f) (xs) /** * `invertEither :: Either l r -> Either r l` * * Converts a `Left` into a `Right` and a `Right` into a `Left`. */ export const invertEither = <L, R> (x: Either<L, R>): Either<R, L> => isLeft (x) ? Right (x .value) : Left (x .value) // TYPE HELPERS export type LeftI<A> = A extends Left<infer I> ? I : never export type RightI<A> = A extends Right<infer I> ? I : never // NAMESPACED FUNCTIONS // eslint-disable-next-line @typescript-eslint/no-redeclare export const Either = { Left, Right, fromLeft, fromRight, fromEither, fromLeft_, fromRight_, eitherToMaybe, maybeToEither, maybeToEither_, bimap, first, second, pure, ap, bind, bindF, then, kleisli, join, mapM, liftM2, foldr, foldl, toList, fnull, flength, elem, elemF, sum, product, concat, concatMap, and, or, any, all, notElem, find, gt, lt, gte, lte, isLeft, isRight, either, lefts, rights, partitionEithers, isEither, imapM, invertEither, }
the_stack
import type { OffsetRange, Token, VDocumentFragment, VElement, VExpressionContainer, VStyleElement, VText, } from "../ast" import { ParseError } from "../ast" import { getLang, getOwnerDocument } from "../common/ast-utils" import { debug } from "../common/debug" import { insertError } from "../common/error-utils" import type { LocationCalculatorForHtml } from "../common/location-calculator" import type { ParserOptions } from "../common/parser-options" import { createSimpleToken, insertComments, replaceAndSplitTokens, } from "../common/token-utils" import { parseExpression } from "../script" import { DEFAULT_ECMA_VERSION } from "../script-setup/parser-options" import { resolveReferences } from "../template" type CSSParseOption = { inlineComment?: boolean } /** * Parse the source code of the given `<style>` elements. * @param elements The `<style>` elements to parse. * @param globalLocationCalculator The location calculator for fixLocations. * @param parserOptions The parser options. * @returns The result of parsing. */ export function parseStyleElements( elements: VElement[], globalLocationCalculator: LocationCalculatorForHtml, originalParserOptions: ParserOptions, ): void { const parserOptions: ParserOptions = { ...originalParserOptions, ecmaVersion: originalParserOptions.ecmaVersion || DEFAULT_ECMA_VERSION, } for (const style of elements) { ;(style as VStyleElement).style = true parseStyleElement( style as VStyleElement, globalLocationCalculator, parserOptions, { inlineComment: (getLang(style) || "css") !== "css", }, ) } } function parseStyleElement( style: VStyleElement, globalLocationCalculator: LocationCalculatorForHtml, parserOptions: ParserOptions, cssOptions: CSSParseOption, ) { if (style.children.length !== 1) { return } const textNode = style.children[0] if (textNode.type !== "VText") { return } const code = textNode.value // short circuit if (!/v-bind(?:\(|\/)/u.test(code)) { return } const locationCalculator = globalLocationCalculator.getSubCalculatorAfter( textNode.range[0], ) const document = getOwnerDocument(style) parseStyle( document, style, code, locationCalculator, parserOptions, cssOptions, ) } function parseStyle( document: VDocumentFragment | null, style: VStyleElement, code: string, locationCalculator: LocationCalculatorForHtml, parserOptions: ParserOptions, cssOptions: CSSParseOption, ) { let textStart = 0 for (const { range, expr, exprOffset, quote, openingParenOffset, comments, } of iterateVBind(code, cssOptions)) { insertComments( document, comments.map((c) => createSimpleToken( c.type, locationCalculator.getOffsetWithGap(c.range[0]), locationCalculator.getOffsetWithGap(c.range[1]), c.value, locationCalculator, ), ), ) const container: VExpressionContainer = { type: "VExpressionContainer", range: [ locationCalculator.getOffsetWithGap(range[0]), locationCalculator.getOffsetWithGap(range[1]), ], loc: { start: locationCalculator.getLocation(range[0]), end: locationCalculator.getLocation(range[1]), }, parent: style, expression: null, references: [], } const openingParenStart = locationCalculator.getOffsetWithGap(openingParenOffset) const beforeTokens: Token[] = [ createSimpleToken( "HTMLRawText", container.range[0], container.range[0] + 6 /* v-bind */, "v-bind", locationCalculator, ), createSimpleToken( "Punctuator", openingParenStart, openingParenStart + 1, "(", locationCalculator, ), ] const afterTokens: Token[] = [ createSimpleToken( "Punctuator", container.range[1] - 1, container.range[1], ")", locationCalculator, ), ] if (quote) { const openStart = locationCalculator.getOffsetWithGap( exprOffset - 1, ) beforeTokens.push( createSimpleToken( "Punctuator", openStart, openStart + 1, quote, locationCalculator, ), ) const closeStart = locationCalculator.getOffsetWithGap( exprOffset + expr.length, ) afterTokens.unshift( createSimpleToken( "Punctuator", closeStart, closeStart + 1, quote, locationCalculator, ), ) } const beforeLast = beforeTokens[beforeTokens.length - 1] replaceAndSplitTokens( document, { range: [container.range[0], beforeLast.range[1]], loc: { start: container.loc.start, end: beforeLast.loc.end }, }, beforeTokens, ) const afterFirst = afterTokens[0] replaceAndSplitTokens( document, { range: [afterFirst.range[0], container.range[1]], loc: { start: afterFirst.loc.start, end: container.loc.end }, }, afterTokens, ) const lastChild = style.children[style.children.length - 1] style.children.push(container) if (lastChild.type === "VText") { const newTextNode: VText = { type: "VText", range: [container.range[1], lastChild.range[1]], loc: { start: { ...container.loc.end }, end: { ...lastChild.loc.end }, }, parent: style, value: code.slice(range[1]), } style.children.push(newTextNode) lastChild.range[1] = container.range[0] lastChild.loc.end = { ...container.loc.start } lastChild.value = code.slice(textStart, range[0]) textStart = range[1] } try { const ret = parseExpression( expr, locationCalculator.getSubCalculatorShift(exprOffset), parserOptions, { allowEmpty: false, allowFilters: false }, ) if (ret.expression) { ret.expression.parent = container container.expression = ret.expression container.references = ret.references } replaceAndSplitTokens( document, { range: [beforeLast.range[1], afterFirst.range[0]], loc: { start: beforeLast.loc.end, end: afterFirst.loc.start, }, }, ret.tokens, ) insertComments(document, ret.comments) for (const variable of ret.variables) { style.variables.push(variable) } resolveReferences(container) } catch (err) { debug("[style] Parse error: %s", err) if (ParseError.isParseError(err)) { insertError(document, err) } else { throw err } } } } function isQuote(c: string): c is '"' | "'" { return c === '"' || c === "'" } function isCommentStart(c: string): c is "/*" | "//" { return c === "/*" || c === "//" } const COMMENT = { "/*": { type: "Block" as const, closing: "*/" as const, }, "//": { type: "Line" as const, closing: "\n" as const, }, } type VBindLocations = { range: OffsetRange expr: string exprOffset: number quote: '"' | "'" | null openingParenOffset: number comments: { type: string range: OffsetRange value: string }[] } /** * Iterate the `v-bind()` information. */ function* iterateVBind( code: string, cssOptions: CSSParseOption, ): IterableIterator<VBindLocations> { const re = cssOptions.inlineComment ? /"|'|\/[*/]|\bv-bind/gu : /"|'|\/\*|\bv-bind/gu let match while ((match = re.exec(code))) { const startToken = match[0] if (isQuote(startToken)) { // skip string re.lastIndex = skipString(code, startToken, re.lastIndex) } else if (isCommentStart(startToken)) { // skip comment re.lastIndex = skipComment( code, COMMENT[startToken].closing, re.lastIndex, ) } else { // v-bind const openingParen = findVBindOpeningParen( code, re.lastIndex, cssOptions, ) if (!openingParen) { continue } const start = match.index const arg = parseVBindArg( code, openingParen.openingParenOffset + 1, cssOptions, ) if (!arg) { continue } yield { range: [start, arg.end], expr: arg.expr, exprOffset: arg.exprOffset, quote: arg.quote, openingParenOffset: openingParen.openingParenOffset, comments: [...openingParen.comments, ...arg.comments], } re.lastIndex = arg.end } } } function findVBindOpeningParen( code: string, nextIndex: number, cssOptions: CSSParseOption, ): { openingParenOffset: number comments: { type: string range: OffsetRange value: string }[] } | null { const re = cssOptions.inlineComment ? /\/[*/]|[\s\S]/gu : /\/\*|[\s\S]/gu re.lastIndex = nextIndex let match const comments: { type: string range: OffsetRange value: string }[] = [] while ((match = re.exec(code))) { const token = match[0] if (token === "(") { return { openingParenOffset: match.index, comments, } } else if (isCommentStart(token)) { // Comment between `v-bind` and opening paren. const comment = COMMENT[token] const start = match.index const end = (re.lastIndex = skipComment( code, comment.closing, re.lastIndex, )) comments.push({ type: comment.type, range: [start, end], value: code.slice( start + token.length, end - comment.closing.length, ), }) continue } // There were no opening parens. return null } return null } function parseVBindArg( code: string, nextIndex: number, cssOptions: CSSParseOption, ): { expr: string exprOffset: number quote: '"' | "'" | null end: number comments: { type: string range: OffsetRange value: string }[] } | null { const re = cssOptions.inlineComment ? /"|'|\/[*/]|\)/gu : /"|'|\/\*|\)/gu const startTokenIndex = (re.lastIndex = skipSpaces(code, nextIndex)) let match const stringRanges: OffsetRange[] = [] const comments: { type: string range: OffsetRange value: string }[] = [] while ((match = re.exec(code))) { const token = match[0] if (isQuote(token)) { const start = match.index const end = (re.lastIndex = skipString(code, token, re.lastIndex)) stringRanges.push([start, end]) } else if (isCommentStart(token)) { const comment = COMMENT[token] const start = match.index const end = (re.lastIndex = skipComment( code, comment.closing, re.lastIndex, )) comments.push({ type: comment.type, range: [start, end], value: code.slice( start + token.length, end - comment.closing.length, ), }) } else { // closing paren if (stringRanges.length === 1) { // for v-bind( 'expr' ), and v-bind( /**/ 'expr' /**/ ) const range = stringRanges[0] const exprRange: OffsetRange = [range[0] + 1, range[1] - 1] return { expr: code.slice(...exprRange), exprOffset: exprRange[0], quote: code[range[0]] as '"' | "'", end: re.lastIndex, comments, } } return { expr: code.slice(startTokenIndex, match.index).trim(), exprOffset: startTokenIndex, quote: null, end: re.lastIndex, comments: [], } } } return null } function skipString(code: string, quote: '"' | "'", nextIndex: number): number { for (let index = nextIndex; index < code.length; index++) { const c = code[index] if (c === "\\") { index++ // escaping continue } if (c === quote) { return index + 1 } } return code.length } function skipComment( code: string, closing: "*/" | "\n", nextIndex: number, ): number { const index = code.indexOf(closing, nextIndex) if (index >= nextIndex) { return index + closing.length } return code.length } function skipSpaces(code: string, nextIndex: number): number { for (let index = nextIndex; index < code.length; index++) { const c = code[index] if (c.trim()) { return index } } return code.length }
the_stack
import React, { useCallback, useState } from "react"; import { Icon } from "@webiny/ui/Icon"; import { cloneDeep } from "lodash"; import { Center, Vertical, Horizontal } from "../../DropZone"; import Draggable from "../../Draggable"; import EditFieldDialog from "./EditFieldDialog"; import Field from "./Field"; import { ReactComponent as HandleIcon } from "../../../../icons/round-drag_indicator-24px.svg"; import { rowHandle, EditContainer, fieldHandle, fieldContainer, Row, RowContainer } from "./Styled"; import { FormEditorFieldError, useFormEditor } from "../../Context"; import { FbFormModelField, FieldLayoutPositionType } from "~/types"; import { i18n } from "@webiny/app/i18n"; import { Alert } from "@webiny/ui/Alert"; import styled from "@emotion/styled"; const t = i18n.namespace("FormsApp.Editor.EditTab"); const Block = styled("span")({ display: "block" }); const keyNames: Record<string, string> = { label: "Label", fieldId: "Field ID", helpText: "Help Text", placeholderText: "Placeholder Text", ["settings.defaultValue"]: "Default value" }; interface FieldErrorsProps { errors: FormEditorFieldError[] | null; } interface FieldErrorProps { error: FormEditorFieldError; } const FieldError: React.FC<FieldErrorProps> = ({ error }) => { return ( <> <Block> <strong>{error.label}</strong> </Block> {Object.keys(error.errors).map(key => { return ( <Block key={key}> {keyNames[key] || "unknown"}: {error.errors[key]} </Block> ); })} </> ); }; const FieldErrors: React.FC<FieldErrorsProps> = ({ errors }) => { if (!errors) { return null; } return ( <Alert title={"Error while saving form!"} type="warning"> {errors.map(error => { return <FieldError error={error} key={`${error.fieldId}`} />; })} </Alert> ); }; export const EditTab: React.FC = () => { const { getLayoutFields, insertField, updateField, deleteField, data, errors, moveField, moveRow, getFieldPlugin } = useFormEditor(); const [editingField, setEditingField] = useState<FbFormModelField | null>(null); const [dropTarget, setDropTarget] = useState<FieldLayoutPositionType | null>(null); const editField = useCallback((field: FbFormModelField | null) => { if (!field) { setEditingField(null); return; } setEditingField(cloneDeep(field)); }, []); // TODO @ts-refactor figure out source type const handleDropField = useCallback( (source: any, position: FieldLayoutPositionType): void => { const { pos, name, ui } = source; if (name === "custom") { /** * We can cast because field is empty in the start */ editField({} as FbFormModelField); setDropTarget(position); return; } if (ui === "row") { // Reorder rows. // Reorder logic is different depending on the source and target position. moveRow(pos.row, position.row); return; } // If source pos is set, we are moving an existing field. if (pos) { if (pos.index === null) { console.log("Tried to move Form Field but its position index is null."); console.log(source); return; } const fieldId = data.layout[pos.row][pos.index]; moveField({ field: fieldId, position }); return; } // Find field plugin which handles the dropped field type "name". const plugin = getFieldPlugin({ name }); if (!plugin) { return; } insertField(plugin.field.createField(), position); }, [data] ); const fields = getLayoutFields(); return ( <EditContainer> <FieldErrors errors={errors} /> {fields.length === 0 && ( <Center onDrop={item => { handleDropField(item, { row: 0, index: 0 }); return undefined; }} > {t`Drop your first field here`} </Center> )} {fields.map((row, index) => ( <Draggable beginDrag={{ ui: "row", pos: { row: index } }} key={`row-${index}`}> {( { drag, isDragging } /* RowContainer start - includes drag handle, drop zones and the Row itself. */ ) => ( <RowContainer style={{ opacity: isDragging ? 0.3 : 1 }}> <div className={rowHandle} ref={drag}> <Icon icon={<HandleIcon />} /> </div> <Horizontal onDrop={item => { handleDropField(item, { row: index, index: null }); return undefined; }} /> {/* Row start - includes field drop zones and fields */} <Row> {row.map((field, fieldIndex) => ( <Draggable key={`field-${fieldIndex}`} beginDrag={{ ui: "field", name: field.name, pos: { row: index, index: fieldIndex } }} > {({ drag }) => ( <div className={fieldContainer} ref={drag}> <Vertical onDrop={item => { handleDropField(item, { row: index, index: fieldIndex }); return undefined; }} isVisible={item => item.ui === "field" && (row.length < 4 || item?.pos?.row === index) } /> <div className={fieldHandle}> <Field field={field} onEdit={editField} onDelete={deleteField} /> </div> {/* Field end */} {fieldIndex === row.length - 1 && ( <Vertical last isVisible={item => item.ui === "field" && (row.length < 4 || item?.pos?.row === index) } onDrop={item => { handleDropField(item, { row: index, index: fieldIndex + 1 }); return undefined; }} /> )} </div> )} </Draggable> ))} </Row> {/* Row end */} {index === fields.length - 1 && ( <Horizontal last onDrop={item => { handleDropField(item, { row: index + 1, index: null }); return undefined; }} /> )} </RowContainer> )} </Draggable> ))} <EditFieldDialog field={editingField} onClose={() => { editField(null); }} onSubmit={initialData => { const data = initialData as unknown as FbFormModelField; if (data._id) { updateField(data); } else if (!dropTarget) { console.log("Missing drop target on EditFieldDialog submit."); } else { insertField(data, dropTarget); } editField(null); }} /> </EditContainer> ); };
the_stack
import Taro, { Component, Config } from "@tarojs/taro"; import { View, Image, Text, ScrollView, Button, Picker } from "@tarojs/components"; import "./index.less"; import { AtTabs, AtTabsPane, AtIcon } from 'taro-ui' import { connect } from '@tarojs/redux'; import { createOrders, userInfo, addressToLngAndLat, distanceCalculation, freightPrice, free, couponsList, createBalanceOrder } from "./service"; interface IState { current: number; number: number; modal: string; couponId: number; storeId: number; couponPrice: number; require: number; activiId: number; myCheck: boolean; query: { data?: any; }; StoreName: { data: any; }; storeAddress: { data: any; }; couponsQuery: { data?: any; }; lngAndLat: { data?: any; }; calculation: { data?: any; }; freightQuery: { data?: any; }; freeQuery: { data?: any; }; myShoppingCart?: any; } @connect(({ common }) => ({ common })) export default class itemDetails extends Component<any, IState> { config: Config = { navigationBarTitleText: "确认订单" }; state = { couponPrice: 0, require: 0, activiId: 0, current: 0, discount: 0, number: 0, couponId: 0, storeId: 0, modal: "none", query: { loading: true, data: null }, StoreName: { data: null, loading: true, }, storeAddress: { data: null, loading: true, }, couponsQuery: { data: { coupons: { list: [], } } }, lngAndLat: { data: null }, calculation: { data: null }, selector: [ '09:00-18:00', ], choose: [ '09:00-18:00', ], selectorChecked: '', timeSeltimeSel: '', freightQuery: { data: { config: { value: 1, } } }, freeQuery: { data: { config: { value: 1, } } }, myShoppingCart: [], myCheck: true, }; onChange = e => { this.setState({ selectorChecked: this.state.selector[e.detail.value] }) } onTimeChange = e => { this.setState({ timeSeltimeSel: this.state.choose[e.detail.value] }) } couponsChoose(id, require, amount) { const { myShoppingCart } = this.state; const totalPrice = myShoppingCart.reduce((total, currentValue) => { if (currentValue.checked) { return total + (currentValue.price * currentValue.number); } return total; }, 0) if (totalPrice >= require) { this.setState({ activiId: id, couponPrice: amount, require }); } else { Taro.showToast({ title: "商品总价不足", icon: "none" }); } } handleSpecifications() { this.setState({ modal: "block" }); } handleClose() { this.setState({ modal: "none" }); } // 支付 async buyNow(itemTotalPrice) { console.log('立即支付itemTotalPrice', itemTotalPrice) const { receiverInfo, distance } = this.props.common; const { myShoppingCart, activiId, myCheck, query } = this.state; const userBalance = query.data.userInfo.balance; console.log('activiId', activiId); const { timeSeltimeSel, selectorChecked, current } = this.state; const myDate = new Date();//获取系统当前时间 myDate.setTime(myDate.getTime() + 24 * 60 * 60 * 1000); const pickupTime = myDate.getFullYear() + "年" + (myDate.getMonth() + 1) + "月" + myDate.getDate() + "日"; const time = timeSeltimeSel || selectorChecked const storeId = Taro.getStorageSync("storeId"); const itemIds: any = []; myShoppingCart.forEach(element => { itemIds.push({ itemId: element.itemId, number: element.number }); }) const cancel = "requestPayment:fail cancel"; if (this.state.current === 2 && !receiverInfo) { Taro.showToast({ title: "请添加收货地址", icon: "none" }); } else { if (current === 2 && distance > 500) { Taro.showToast({ title: "暂只支持500M内的订单配送!", icon: "none" }); } else { if (current === 2 && !time || current === 1 && !time) { Taro.showToast({ title: "请添加时间", icon: "none" }); } else { console.log('执行了调用接口吗'); try { let result: any = {}; let resultBalance: any = {}; switch (current) { case 0: if (myCheck) { result = await createOrders( itemIds, storeId, activiId === 0 ? null : activiId, null, null, 'storeBuy', 'wechatPay', false ); console.log('case0 mycheck result', result); } else { if (userBalance > itemTotalPrice) { resultBalance = await createBalanceOrder( itemIds, storeId, activiId === 0 ? null : activiId, null, null, 'storeBuy', 'balance', false ); } else { Taro.showToast({ title: "余额不足,请充值!", icon: "none", duration: 1000 }); } } break; case 1: const tomorrow = pickupTime; const pickUpTheGoods = `${tomorrow}&${time}`; console.log('pickUpTheGoods', pickUpTheGoods); if (myCheck) { result = await createOrders( itemIds, storeId, activiId === 0 ? null : activiId, pickUpTheGoods, null, 'unmanned', 'wechatPay', false ); } else { if (userBalance > itemTotalPrice) { resultBalance = await createBalanceOrder( itemIds, storeId, activiId === 0 ? null : activiId, pickUpTheGoods, null, 'unmanned', 'balance', false ); } else { Taro.showToast({ title: "余额不足,请充值!", icon: "none", duration: 1000 }); } } break; case 2: console.log('case 2 配送上门'); if (myCheck) { result = await createOrders( itemIds, storeId, activiId === 0 ? null : activiId, time, receiverInfo, 'distribution', 'wechatPay', false ); } else { if (userBalance > itemTotalPrice) { resultBalance = await createBalanceOrder( itemIds, storeId, activiId === 0 ? null : activiId, time, receiverInfo, 'distribution', 'balance', false ); } else { Taro.showToast({ title: "余额不足,请充值!", icon: "none", duration: 1000 }); } } break; default: break; } const { cartItems } = this.props.common; Taro.setTabBarBadge({ index: 2, text: cartItems.length, }) const response1 = result.data; const { dispatch } = this.props; const responseBalance1 = resultBalance.data; if (responseBalance1) { const responseBalance = responseBalance1.createBalanceOrder; if (responseBalance) { dispatch({ type: 'common/delete', payload: myShoppingCart }) Taro.navigateTo({ url: "../results/index" }); } } if (response1) { const response = response1.createOrder; const { nonceStr, paySign, signType, timeStamp } = response; const packageer = response.package; console.log('response',response); await wx.showModal({ title: '是否授权订阅消息', success(){ wx.requestSubscribeMessage({ tmplIds: ['8_r9fJI0Qwz326pRDZHgVPci3nn93sZBGCoaWNhaoLE'], success(res) { console.log('requestSubscribeMessage success', res); Taro.requestPayment({ nonceStr: nonceStr, package: packageer, signType: signType, paySign: paySign, timeStamp, success(res) { dispatch({ type: 'common/delete', payload: myShoppingCart }) console.log('success res', res); Taro.navigateTo({ url: "../results/index" }); } }); }, fail(error) { console.log('requestSubscribeMessage error', error); } }) }, fail(){ Taro.requestPayment({ nonceStr: nonceStr, package: packageer, signType: signType, paySign: paySign, timeStamp, success(res) { dispatch({ type: 'common/delete', payload: myShoppingCart }) console.log('success res', res); Taro.navigateTo({ url: "../results/index" }); } }); } }) } } catch (e) { if (e.errMsg === cancel) { Taro.showToast({ title: "用户取消了支付", icon: "none", duration: 1000 }); } else { Taro.showToast({ title: "支付失败", icon: "none", duration: 1000, mask: true }); } } } } } } // 选择地址 async handleAddAddress() { const { dispatch } = this.props; Taro.chooseAddress({ async success(e) { const receiverAddress = e.provinceName + e.cityName + e.countyName + e.detailInfo; const { data } = await addressToLngAndLat(receiverAddress); const { lng, lat } = data.addressToLngAndLat; const from: any = {}; const to: any = {}; const { longitude, latitude } = Taro.getStorageSync("storeLngAndLat"); from.lng = longitude; from.lat = latitude; to.lng = lng; to.lat = lat; const { data: result } = await distanceCalculation(from, to); const { distance } = result.distanceCalculation; dispatch({ type: 'common/preAddress', payload: { distance: distance, receiverInfo: { receiverName: e.userName, receiverPhone: e.telNumber, receiverAddress: receiverAddress, } } }); } }); } handleClick(value) { this.setState({ current: value }) } // 页面加载前 async componentWillMount() { const userResult = await userInfo(); const couponsResult = await couponsList("useable", 1); const freightResult = await freightPrice(); const freeResult = await free(); const nearbyStoreName = Taro.getStorageSync("nearbyStoreName"); const storeAddress = Taro.getStorageSync("storeAddress"); const { cartItems } = this.props.common; const { myShoppingCart } = this.state; if (cartItems) { if (userResult.data.userInfo.role==='member') { for (const iterator of cartItems) { if (iterator.checked) { if (iterator.memberPrice !==0) { iterator.price = iterator.memberPrice; myShoppingCart.push(iterator); }else{ myShoppingCart.push(iterator); } } } }else{ for (const iterator of cartItems) { if (iterator.checked) { myShoppingCart.push(iterator); } } } } this.setState({ query: userResult, couponsQuery: couponsResult, freightQuery: freightResult, freeQuery: freeResult, StoreName: nearbyStoreName, storeAddress: storeAddress.slice(), myShoppingCart, }); } changeCheck(value) { this.setState({ myCheck: value }) } componentDidMount() { } render() { const { cartItems, receiverInfo, distance } = this.props.common; const totalPrice = cartItems.reduce((total, currentValue) => { if (currentValue.checked) { return total + (currentValue.price * currentValue.number); } return total; }, 0) const { activiId, StoreName, couponsQuery, couponPrice, storeAddress, freightQuery, freeQuery, current, require, myShoppingCart, myCheck, } = this.state; const couponsLists = couponsQuery.data.coupons.list; const total = (totalPrice ? totalPrice : 0) / 100 - (this.state.discount); // 定义运费 let freight; console.log('freightQuery,freightQuery,freightQuery', freightQuery); // 若订单总金额大于应配送的金额 if (total >= freeQuery.data.config.value / 100) { freight = 0; } else { freight = freightQuery.data.config.value / 100; } console.log('couponPrice / 100', typeof (couponPrice / 100)); console.log('total', typeof (total)); let itemTotalPrice; const thisTotalPrice = total - couponPrice / 100; if (current === 2) { itemTotalPrice = thisTotalPrice + freight; } else { itemTotalPrice = thisTotalPrice; } const myDate = new Date();//获取系统当前时间 myDate.setTime(myDate.getTime() + 24 * 60 * 60 * 1000); const pickupTime = myDate.getFullYear() + "年" + (myDate.getMonth() + 1) + "月" + myDate.getDate() + "日"; return ( <ScrollView className="index"> {/* 分割线 */} <View className="topLine" /> <AtTabs animated={false} current={this.state.current} tabList={[ { title: '门店现购' }, { title: '门店自提' }, { title: '配送上门' }, ]} onClick={this.handleClick.bind(this)} className='attab' > {/* 门店现购 */} <AtTabsPane current={this.state.current} index={0} > <View className="lainx"> <Text className='textTitle'>门店信息</Text> <View className="dizhi"> <View className="index1"> <Text className="zit">{StoreName}</Text> <Text className="zit">{storeAddress}</Text> </View> <AtIcon value='check-circle' size='30' color='#006D75'></AtIcon> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 配送 */} <View className="yuy"> <View className="yhui" style='margin-left:5px'> <Text className="zit3">商品清单</Text> </View> {myShoppingCart.map(item => ( <View key={item.id} className="goodBox"> <Image src={item.imageUrl} className="img" /> <View > <View> <Text className='goodName'>{item.name}</Text> </View> <Text className='goodName1'> ¥{(item.price * item.number / 100)}/元 </Text> </View> <Text className='shuliang'>数量:{item.number}</Text> </View> ))} </View> {/* 分割线 */} <View className="coarseLine" /> {/* 优惠劵 */} <View className="yuy" onClick={this.handleSpecifications}> <View className="yhui"> <Text className="coupons_text">优惠券选择</Text> <View className="choose_coupons"> { require ? (<Text className="coupons">满{require / 100}减{couponPrice / 100}</Text>) : (<AtIcon value='chevron-right'></AtIcon>) } </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 商品金额 */} <View className="yuy"> <View className="yhui"> <Text className="coupons_text">商品总额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {total}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">优惠金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {couponPrice ? couponPrice / 100 : '0'}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">支付金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {itemTotalPrice.toFixed(2)}/元 </Text> </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> <View className="lainx"> <Text className='textTitle'>支付方式</Text> <View className="myPay"> <View className="Payment" onClick={this.changeCheck.bind(this, true)}> <Text className="zit">微信支付</Text> { myCheck ? (<AtIcon value='check-circle' className='checked'></AtIcon>) : (<AtIcon value='check-circle' className='unChecked'></AtIcon>) } </View> <View className="Payment" onClick={this.changeCheck.bind(this, false)}> <Text className="zit">余额支付</Text> { myCheck ? (<AtIcon value='check-circle' className='unChecked'></AtIcon>) : (<AtIcon value='check-circle' className='checked'></AtIcon>) } </View> </View> </View> </AtTabsPane> {/* 门店自提 */} <AtTabsPane current={this.state.current} index={1} > <View className="lainx"> <Text className='textTitle'>门店信息</Text> <View className="dizhi"> <View className="index1"> <Text className="zit">{StoreName}</Text> <Text className="zit">{storeAddress}</Text> </View> <AtIcon value='check-circle' size='30' color='#006D75'></AtIcon> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 自提 */} <View className="yuy"> <View className="yhui"> <Text className="zit3">商品清单</Text> </View> {myShoppingCart.map(item => ( <View key={item.id} className="goodBox"> <Image src={item.imageUrl} className="img" /> <View > <View> <Text className='goodName'>{item.name}</Text> </View> <Text className='goodName1'> ¥{(item.price * item.number / 100)}/元 </Text> </View> <Text className='shuliang'>数量:{item.number}</Text> </View> ))} </View> {/* 分割线 */} <View className="coarseLine" /> {/* 优惠劵 */} <View className="yuy" onClick={this.handleSpecifications}> <View className="yhui"> <Text className="coupons_text">优惠券选择</Text> <View className="choose_coupons"> { require ? (<Text className="coupons">满{require / 100}减{couponPrice / 100}</Text>) : (<AtIcon value='chevron-right' className='rightIcon'></AtIcon>) } </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 优惠劵 */} <View className="yuy"> <View className="yhui"> <Text className="coupons_text">取货日期:</Text> <View className="choose_coupons"> <Text className='coupons_text1'> {pickupTime} </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">取货时间:</Text> <View className="yhui1"> <View className='page-section'> <Picker mode='selector' range={this.state.choose} onChange={this.onTimeChange}> <View className='picker'> {this.state.timeSeltimeSel ? this.state.timeSeltimeSel : '请选择取货时间!'} </View> </Picker> </View> </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 商品金额 */} <View className="yuy"> <View className="yhui"> <Text className="coupons_text">商品总额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {total}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">优惠金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {couponPrice ? couponPrice / 100 : '0'}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">支付金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {itemTotalPrice}/元 </Text> </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> <View className="lainx"> <Text className='textTitle'>支付方式</Text> <View className="myPay"> <View className="Payment" onClick={this.changeCheck.bind(this, true)}> <Text className="zit">微信支付</Text> { myCheck ? (<AtIcon value='check-circle' className='checked'></AtIcon>) : (<AtIcon value='check-circle' className='unChecked'></AtIcon>) } </View> <View className="Payment" onClick={this.changeCheck.bind(this, false)}> <Text className="zit">余额支付</Text> { myCheck ? (<AtIcon value='check-circle' className='unChecked'></AtIcon>) : (<AtIcon value='check-circle' className='checked'></AtIcon>) } </View> </View> </View> </AtTabsPane> {/* 预约配送 */} <AtTabsPane current={this.state.current} index={2} > <View className="lainx"> <Text className='textTitle'>门店信息</Text> <View className="dizhi"> <View className="index1"> <Text className="zit">{StoreName}</Text> <Text className="zit">{storeAddress}</Text> </View> <AtIcon value='check-circle' size='30' color='#006D75'></AtIcon> </View> </View> {/* 分割线 */} <View className="coarseLine" /> <View className="lainx"> <Text className='textTitle'>配送地址</Text> <View className="dizhi" onClick={this.handleAddAddress}> <View className="index1"> <Text className="zit"> {receiverInfo ? `${receiverInfo.receiverAddress}` : '添加收货地址!'} </Text> </View> <AtIcon value='chevron-right' className='rightIcon'></AtIcon> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 配送 */} <View className="yuy"> <View className="yhui"> <Text className="zit3">商品清单</Text> </View> {myShoppingCart.map(item => ( <View key={item.id} className="goodBox"> <Image src={item.imageUrl} className="img" /> <View > <View> <Text className='goodName'>{item.name}</Text> </View> <Text className='goodName1'> ¥{(item.price * item.number / 100)}/元 </Text> </View> <Text className='shuliang'>数量:{item.number}</Text> </View> ))} </View> {/* 分割线 */} <View className="coarseLine" /> {/* 优惠劵 */} <View className="yuy" onClick={this.handleSpecifications}> <View className="yhui"> <Text className="coupons_text">优惠券选择</Text> <View className="choose_coupons"> { require ? (<Text className="coupons">满{require / 100}减{couponPrice / 100}</Text>) : (<AtIcon value='chevron-right' className='rightIcon'></AtIcon>) } </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> <View className="yuy"> <View className="yhui"> <Text className="zit3">配送时间:</Text> <View className="yhui1"> <View className='page-section'> <Picker mode='selector' range={this.state.selector} onChange={this.onChange}> <View className='picker'> {this.state.selectorChecked ? this.state.selectorChecked : '请选择配送时间!'} </View> </Picker> </View> <AtIcon value='chevron-right' className='rightIcon'></AtIcon> </View> </View> {/* 分割线 */} <View className="coarseLine" /> {/* 商品金额 */} <View className="yuy"> <View className="yhui"> <Text className="coupons_text">商品总额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {total}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">优惠金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {couponPrice ? couponPrice / 100 : '0'}/元 </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">配送费:</Text> <View className="choose_coupons"> <Text className='goodName1'> {freight > 0 ? `¥${freight}` : "免配送费"} </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">距离:</Text> <View className="choose_coupons"> <Text className='coupons_text'> {distance / 1000} KM </Text> </View> </View> <View className="yhui"> <Text className="coupons_text">支付金额:</Text> <View className="choose_coupons"> <Text className='goodName1'> {itemTotalPrice}/元 </Text> </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> <View className="lainx"> <Text className='textTitle'>支付方式</Text> <View className="myPay"> <View className="Payment" onClick={this.changeCheck.bind(this, true)}> <Text className="zit">微信支付</Text> { myCheck ? (<AtIcon value='check-circle' className='checked'></AtIcon>) : (<AtIcon value='check-circle' className='unChecked'></AtIcon>) } </View> <View className="Payment" onClick={this.changeCheck.bind(this, false)}> <Text className="zit">余额支付</Text> { myCheck ? (<AtIcon value='check-circle' className='unChecked'></AtIcon>) : (<AtIcon value='check-circle' className='checked'></AtIcon>) } </View> </View> </View> </View> {/* 分割线 */} <View className="coarseLine" /> </AtTabsPane> </AtTabs> <View className="settlem"> 合计总额: <View className="settlement1"> ¥{itemTotalPrice.toFixed(2)}/元 </View> <Button size='mini' className="settlement2" onClick={this.buyNow.bind(this, itemTotalPrice)} > 立即支付 </Button> </View> {/**-------优惠券选择*/} <View style={{ display: this.state.modal }}> {/*-------底部透明背景------*/} <View className="transparent"> {/*--------弹窗主体框-------*/} <View className="bodyBox"> {/*----------第一行优惠券以及关闭按钮------*/} <View className="topFirstLine"> <Text>优惠券</Text> <View onClick={this.handleClose}> <AtIcon value='close' size='20'></AtIcon> </View> </View> {/*--------第二行选择优惠券---------*/} <View className="secondLine"> <Text className="secondText">请选择优惠券</Text> </View> <ScrollView className="grayBack" scrollY> {couponsLists.map(item => ( <View className="box" key={item.id}> <View className="bottomBox" onClick={this.couponsChoose.bind( this, item.id, item.require, item.amount, )} > <View className="Left"> <View className="leftView"> <Text className="symbol">¥</Text> <Text className="amount">{item.amount / 100}</Text> </View> <View className="centerView"> <View className="viewBox"> <Image src='https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/background.png' className="background" /> <Text className="fullAmount"> 满{item.require / 100}元可用 </Text> </View> <Text className="timeData">待使用</Text> </View> </View> <View className="rightView"> {activiId === item.id ? ( <Image src="https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/choose.png" className="radio" /> ) : null} </View> </View> </View> ))} </ScrollView> <View className="determineBox" onClick={this.handleClose}> <Text className="determine">确定</Text> </View> </View> </View> </View> </ScrollView> ); } }
the_stack
import { tsst, the } from 'tsst-tycho'; import { Obj, List } from '../src/util'; import { KeyedSafe, Keyed, ObjectHasKey, HasKey, ObjectHasKeySafe, ObjectProp, Omit, Overwrite, IntersectValueOf, IntersectionObjectKeys, IntersectionObjects, ObjectValsToUnion, ObjectHasStringIndex, Simplify, Swap, Jsonified, DeepPartial, DeepReadonly, FunctionPropNames, FunctionProps, NonFunctionPropNames, NonFunctionProps, MatchingPropNames, MatchingProps, NonMatchingPropNames, NonMatchingProps, StripIndex, OptionalPropNames, OptionalProps, RequiredPropNames, RequiredProps, Spread, DeepWiden, DeepAssert, ObjectHasNumberIndex, ObjectHasElem, ObjectNumberKeys, LiteralPropNames, LiteralProps, DeepRequired, Mutable, DeepMutable } from '../src/object'; import { NumArr, Part } from './fixtures'; type Item1 = { a: string, b: number, c: boolean }; type Item2 = { a: number }; type ItemA = { a: string, b: number, c: boolean, toString(): string }; type Obj1 = { a: 1, b: 2 }; type Obj2 = { b: 'X', c: 'Z' }; type abc = { a: 1, b: 2, foo: () => string, toString: () => string }; // , toLocaleString: () => string // https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458 // type sfsd = { [P in PrototypeMethods]: P; [k: string]: never; }; // type sdkjdsl = { toString: "toString"; [P in keyof "a"]: never }; // type sdkjds2l = { [P in keyof U]: never; [K in keyof PrototypeMethods]: K; }; describe(`object`, () => { describe(`Keyed`, () => { it(`the<{a:'a',b:'b'}, Keyed<{a:1,b:2}>>`, () => { tsst(() => { the<{a:'a',b:'b'}, Keyed<{a:1,b:2}>>(); }).expectToCompile(); }); }); describe(`KeyedSafe`, () => { it(`the<{a:'a',b:'b'} & Obj<never>, KeyedSafe<{a:1} & {b:2}>>`, () => { tsst(() => { the<{a:'a',b:'b'} & Obj<never>, KeyedSafe<{a:1} & {b:2}>>(); }).expectToCompile(); }); }); describe(`ObjectHasKey`, () => { it(`the<'1', ObjectHasKey<{a:1}, 'a'>>`, () => { tsst(() => { the<'1', ObjectHasKey<{a:1}, 'a'>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasKey<{a:1}, 'b'>>`, () => { tsst(() => { the<'0', ObjectHasKey<{a:1}, 'b'>>(); }).expectToCompile(); }); it(`the<'0'|'1', ObjectHasKey<{a?:1}, 'a'>>`, () => { tsst(() => { the<'0'|'1', ObjectHasKey<{a?:1}, 'a'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKey<NumArr, 1>>`, () => { tsst(() => { the<'1', ObjectHasKey<NumArr, 1>>(); }).expectToFail(); }); it(`the<'0', ObjectHasKey<NumArr, -1>>`, () => { tsst(() => { the<'0', ObjectHasKey<NumArr, -1>>(); }).expectToFail(); }); it(`the<'0', ObjectHasKey<{ a: 1 }, "toString">>`, () => { tsst(() => { the<'0', ObjectHasKey<{ a: 1 }, "toString">>(); }).expectToCompile(); }); // ^ error: () => string }); describe(`HasKey`, () => { it(`the<'0', HasKey<any[], 2>>`, () => { tsst(() => { the<'0', HasKey<any[], 2>>(); }).expectToCompile(); }); it(`the<'1', HasKey<NumArr, 2>>`, () => { tsst(() => { the<'1', HasKey<NumArr, 2>>(); }).expectToCompile(); }); // ^ error: 0 it(`the<'0', HasKey<NumArr, 5>>`, () => { tsst(() => { the<'0', HasKey<NumArr, 5>>(); }).expectToCompile(); }); it(`the<'1', HasKey<{ a: 1 }, 'a'>>`, () => { tsst(() => { the<'1', HasKey<{ a: 1 }, 'a'>>(); }).expectToCompile(); }); // ^ error: 0 it(`the<'0', HasKey<{ a: 1 }, 'b'>>`, () => { tsst(() => { the<'0', HasKey<{ a: 1 }, 'b'>>(); }).expectToCompile(); }); }); describe(`ObjectHasKeySafe`, () => { it(`the<'1', ObjectHasKeySafe<{ a: 1 }, 'a'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1 }, 'a'>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasKeySafe<{ a: 1 }, 'b'>>`, () => { tsst(() => { the<'0', ObjectHasKeySafe<{ a: 1 }, 'b'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1 }, 'a' | 'b'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1 }, 'a' | 'b'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'a'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'a'>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasKeySafe<{ a: 1, toString(): string }, 'b'>>`, () => { tsst(() => { the<'0', ObjectHasKeySafe<{ a: 1, toString(): string }, 'b'>>(); }).expectToCompile(); }); // error: 1 :( it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'a' | 'b'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'a' | 'b'>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasKeySafe<{ a: 1 }, 'toString'>>`, () => { tsst(() => { the<'0', ObjectHasKeySafe<{ a: 1 }, 'toString'>>(); // what do I want? }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'a'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'a'>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'b'>>`, () => { tsst(() => { the<'0', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'b'>>(); // what do I want? }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'a' | 'b'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1 }, 'toString' | 'a' | 'b'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'a'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'a'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'b'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'b'>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'a' | 'b'>>`, () => { tsst(() => { the<'1', ObjectHasKeySafe<{ a: 1, toString(): string }, 'toString' | 'a' | 'b'>>(); }).expectToCompile(); }); }); // if this works, I may need to replace string member access with this in other places... describe(`ObjectProp`, () => { it(`the<1, ObjectProp<{ a: 1 }, 'a'>>`, () => { tsst(() => { the<1, ObjectProp<{ a: 1 }, 'a'>>(); }).expectToCompile(); }); it(`the<never, ObjectProp<{ a: 1 }, 'b'>>`, () => { tsst(() => { the<never, ObjectProp<{ a: 1 }, 'b'>>(); }).expectToCompile(); }); it(`the<never, ObjectProp<{ a: 1 }, 'toString'>>`, () => { tsst(() => { the<never, ObjectProp<{ a: 1 }, 'toString'>>(); }).expectToCompile(); }); it(`the<1, ObjectProp<{ a: 1, toString(): string }, 'a'>>`, () => { tsst(() => { the<1, ObjectProp<{ a: 1, toString(): string }, 'a'>>(); }).expectToCompile(); }); it(`the<never, ObjectProp<{ a: 1, toString(): string }, 'b'>>`, () => { tsst(() => { the<never, ObjectProp<{ a: 1, toString(): string }, 'b'>>(); }).expectToCompile(); }); // error: any :( it(`the<() => string, ObjectProp<{ a: 1, toString(): string }, 'toString'>>`, () => { tsst(() => { the<() => string, ObjectProp<{ a: 1, toString(): string }, 'toString'>>(); }).expectToCompile(); }); }); describe(`Omit`, () => { it(`the<{ b: number, c: boolean }, Omit<Item1, "a">>`, () => { tsst(() => { the<{ b: number, c: boolean }, Omit<Item1, "a">>(); }).expectToCompile(); }); it(`the<'b'|'c'|'toString', Exclude<keyof ItemA, "a">>`, () => { tsst(() => { type KeyedItem1 = keyof ItemA the<'b'|'c'|'toString', Exclude<keyof ItemA, "a">>(); }).expectToCompile(); }); it(`the<{ b: number, c: boolean, toString(): string }, Omit<ItemA, "a">>`, () => { tsst(() => { the<{ b: number, c: boolean, toString(): string }, Omit<ItemA, "a">>(); }).expectToCompile(); }); }); describe(`Overwrite`, () => { it(`the<{ a: number, b: number, c: boolean }, Overwrite<Item1, Item2>>`, () => { tsst(() => { the<{ a: number, b: number, c: boolean }, Overwrite<Item1, Item2>>(); }).expectToCompile(); }); // keys optional in 2nd arg: works without `strictNullChecks` }); describe(`IntersectionObjectKeys`, () => { it(`the<'b', IntersectionObjectKeys<Obj1, Obj2>>`, () => { tsst(() => { the<'b', IntersectionObjectKeys<Obj1, Obj2>>(); }).expectToCompile(); }); }); describe(`IntersectionObjects`, () => { it(`the<{ b: 2 }, IntersectionObjects<Obj1, Obj2>>`, () => { tsst(() => { the<{ b: 2 }, IntersectionObjects<Obj1, Obj2>>(); }).expectToCompile(); }); it(`the<{ b: 'X' }, IntersectionObjects<Obj2, Obj1>>`, () => { tsst(() => { the<{ b: 'X' }, IntersectionObjects<Obj2, Obj1>>(); }).expectToCompile(); }); }); describe(`ObjectValsToUnion`, () => { it(`the<1|2, ObjectValsToUnion<Obj1>>`, () => { tsst(() => { the<1|2, ObjectValsToUnion<Obj1>>(); }).expectToCompile(); }); }); describe(`Simplify`, () => { it(`the<{ a: 1, b: 2}, Simplify<{ a: 1 } & { b: 2}>>`, () => { tsst(() => { the<{ a: 1, b: 2}, Simplify<{ a: 1 } & { b: 2}>>(); }).expectToCompile(); }); }); describe(`Swap`, () => { it(`the<{ b: 'a', d: 'c' }, Swap<{ a: 'b', c: 'd' }>>`, () => { tsst(() => { the<{ b: 'a', d: 'c' }, Swap<{ a: 'b', c: 'd' }>>(); }).expectToCompile(); }); }); describe(`toString experimenting`, () => { it(`the<{ a: 1, foo: () => string, toString: () => string }, Omit<abc, "b">>`, () => { tsst(() => { the<{ a: 1, foo: () => string, toString: () => string }, Omit<abc, "b">>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: () => string }, Omit<abc, "toString">>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: () => string }, Omit<abc, "toString">>(); }).expectToCompile(); }); it(`the<abc, Simplify<abc & { "b": never }>>`, () => { tsst(() => { the<abc, Simplify<abc & { "b": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: any, foo: () => string, toString: () => string }, Simplify<abc & { "b": any }>>`, () => { tsst(() => { the<{ a: 1, b: any, foo: () => string, toString: () => string }, Simplify<abc & { "b": any }>>(); }).expectToCompile(); }); it(`the<abc, Simplify<abc & { "toString": never }>>`, () => { tsst(() => { the<abc, Simplify<abc & { "toString": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: () => string, toString: any }, Simplify<abc & { "toString": any }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: () => string, toString: any }, Simplify<abc & { "toString": any }>>(); }).expectToCompile(); }); it(`the<abc, Simplify<abc & { "foo": never }>>`, () => { tsst(() => { the<abc, Simplify<abc & { "foo": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: any, toString: () => string }, Simplify<abc & { "foo": any }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: any, toString: () => string }, Simplify<abc & { "foo": any }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: never, foo: () => string, toString: () => string }, Overwrite<abc, { "b": never }>>`, () => { tsst(() => { the<{ a: 1, b: never, foo: () => string, toString: () => string }, Overwrite<abc, { "b": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: any, foo: () => string, toString: () => string }, Overwrite<abc, { "b": any }>>`, () => { tsst(() => { the<{ a: 1, b: any, foo: () => string, toString: () => string }, Overwrite<abc, { "b": any }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: () => string }, Overwrite<abc, { "toString": never }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: () => string }, Overwrite<abc, { "toString": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: () => string, toString: any }, Overwrite<abc, { "toString": any }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: () => string, toString: any }, Overwrite<abc, { "toString": any }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: never, toString: () => string }, Overwrite<abc, { "foo": never }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: never, toString: () => string }, Overwrite<abc, { "foo": never }>>(); }).expectToCompile(); }); it(`the<{ a: 1, b: 2, foo: any, toString: () => string }, Overwrite<abc, { "foo": any }>>`, () => { tsst(() => { the<{ a: 1, b: 2, foo: any, toString: () => string }, Overwrite<abc, { "foo": any }>>(); }).expectToCompile(); }); it(`the<abc, Simplify<abc & { "toString": never }>>`, () => { tsst(() => { the<abc, Simplify<abc & { "toString": never }>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasStringIndex<{ [k: string]: 123 }>>`, () => { tsst(() => { the<'1', ObjectHasStringIndex<{ [k: string]: 123 }>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasStringIndex<{ a: 123 }>>`, () => { tsst(() => { the<'0', ObjectHasStringIndex<{ a: 123 }>>(); }).expectToCompile(); }); }); describe(`StripIndex`, () => { it(`the<StripIndex<{ a: 1, [k: string]: number }>, { a: 1 }>`, () => { tsst(() => { the<StripIndex<{ a: 1, [k: string]: number }>, { a: 1 }>(); }).expectToCompile(); }); }); describe(`Jsonified`, () => { it(`the<{ b: 'a' }, Jsonified<{ b: 'a', d: undefined, f: () => void }>>`, () => { tsst(() => { the<{ b: 'a' }, Jsonified<{ b: 'a', d: undefined, f: () => void }>>(); }).expectToCompile(); }); }); describe(`IntersectValueOf`, () => { it(`IntersectValueOf`, () => { tsst(() => { type Thing = { foo: {a: string}, bar: {b: number}, baz: {c: boolean} } type Everything = IntersectValueOf<Thing>; the<string, Everything['a']>(); the<string, Everything['b']>(); the<string, Everything['c']>(); }).expectToCompile(); }); }); describe(`DeepWiden`, () => { it(`the<{ a: number }, DeepWiden<{ a: 1 }>>`, () => { tsst(() => { the<{ a: number }, DeepWiden<{ a: 1 }>>(); }).expectToCompile(); }); }); describe(`DeepPartial`, () => { it(`the<{ a?: { b?: 1 } }, DeepPartial<{ a: { b: 1 } }>>`, () => { tsst(() => { the<{ a?: { b?: 1 } }, DeepPartial<{ a: { b: 1 } }>>(); }).expectToCompile(); }); it(`the<1, DeepPartial<{ a: [{ b: 1 }] }>['a'][0]['b']>`, () => { tsst(() => { let o: DeepPartial<{ a: [{ b: 1 }] }> = null! as DeepPartial<{ a: [{ b: 1 }] }>; if (typeof o.a === 'undefined') {} else { let b = o.a[0].b; if (typeof b === 'number') { let c: 1 = b; } else { let c: undefined = b; } } }).expectToCompile(); }); }); describe(`DeepRequired`, () => { it(`the<{ a: { b: 1 } }, DeepRequired<{ a?: { b?: 1 } }>>`, () => { tsst(() => { the<{ a: { b: 1 } }, DeepRequired<{ a?: { b?: 1 } }>>(); }).expectToCompile(); }); }); describe(`Mutable`, () => { it(`the<{ a: 1 }, Mutable<{ readonly a: 1 }>>`, () => { tsst(() => { the<{ a: 1 }, Mutable<{ readonly a: 1 }>>(); }).expectToCompile(); }); }); describe(`DeepMutable`, () => { it(`the<{ a: { b: 1 } }, DeepMutable<{ readonly a: { readonly b: 1 } }>>`, () => { tsst(() => { the<{ a: { b: 1 } }, DeepMutable<{ readonly a: { readonly b: 1 } }>>(); }).expectToCompile(); }); }); describe(`DeepAssert`, () => { it(`the<{ a: 1 }, DeepAssert<{ a: 1|null }>>`, () => { tsst(() => { the<{ a: 1 }, DeepAssert<{ a: 1|null }>>(); }).expectToCompile(); }); }); describe(`DeepReadonly`, () => { it(`still allows reading`, () => { tsst(() => { function f10(part: DeepReadonly<Part>) { let name: string = part.name; let id: number = part.subparts[0].id; } }).expectToCompile(); }); it(`disallows writing - layer 0`, () => { tsst(() => { function f10(part: DeepReadonly<Part>) { part.id = part.id; } }).expectToFailWith('read-only'); }); it(`disallows writing - layer 1`, () => { tsst(() => { function f10(part: DeepReadonly<Part>) { part.subparts[0] = part.subparts[0]; } }).expectToFailWith('only permits reading'); }); it(`disallows writing - layer 2`, () => { tsst(() => { function f10(part: DeepReadonly<Part>) { part.subparts[0].id = part.subparts[0].id; } }).expectToFailWith('read-only'); }); it(`strips out methods`, () => { tsst(() => { function f10(part: DeepReadonly<Part>) { part.updatePart("hello"); } }).expectToFailWith('does not exist'); }); }); describe(`LiteralPropNames`, () => { it(`the<'a', LiteralPropNames<{ a: 1, [k: string]: number }>>`, () => { tsst(() => { the<'a', LiteralPropNames<{ a: 1, [k: string]: number }>>(); }).expectToCompile(); }); }); describe(`LiteralProps`, () => { it(`the<{ a: 1 }, LiteralProps<{ a: 1, [k: string]: number }>>`, () => { tsst(() => { the<{ a: 1 }, LiteralProps<{ a: 1, [k: string]: number }>>(); }).expectToCompile(); }); }); describe(`FunctionPropNames`, () => { it(`the<'f', FunctionPropNames<{ a: 1, f: () => void }>>`, () => { tsst(() => { the<'f', FunctionPropNames<{ a: 1, f: () => void }>>(); }).expectToCompile(); }); }); describe(`FunctionProps`, () => { it(`the<{ f: () => void }, FunctionProps<{ a: 1, f: () => void }>>`, () => { tsst(() => { the<{ f: () => void }, FunctionProps<{ a: 1, f: () => void }>>(); }).expectToCompile(); }); }); describe(`NonFunctionPropNames`, () => { it(`the<'a', NonFunctionPropNames<{ a: 1, f: () => void }>>`, () => { tsst(() => { the<'a', NonFunctionPropNames<{ a: 1, f: () => void }>>(); }).expectToCompile(); }); }); describe(`NonFunctionProps`, () => { it(`the<{ a: 1 }, NonFunctionProps<{ a: 1, f: () => void }>>`, () => { tsst(() => { the<{ a: 1 }, NonFunctionProps<{ a: 1, f: () => void }>>(); }).expectToCompile(); }); }); describe(`MatchingPropNames`, () => { it(`the<'f', MatchingPropNames<{ a: 1, f: true }, boolean>>`, () => { tsst(() => { the<'f', MatchingPropNames<{ a: 1, f: true }, boolean>>(); }).expectToCompile(); }); }); describe(`MatchingProps`, () => { it(`the<{ f: true }, MatchingProps<{ a: 1, f: true }, boolean>>`, () => { tsst(() => { the<{ f: true }, MatchingProps<{ a: 1, f: true }, boolean>>(); }).expectToCompile(); }); }); describe(`NonMatchingPropNames`, () => { it(`the<'a', NonMatchingPropNames<{ a: 1, f: true }, boolean>>`, () => { tsst(() => { the<'a', NonMatchingPropNames<{ a: 1, f: true }, boolean>>(); }).expectToCompile(); }); }); describe(`NonMatchingProps`, () => { it(`the<{ a: 1 }, NonMatchingProps<{ a: 1, f: true }, boolean>>`, () => { tsst(() => { the<{ a: 1 }, NonMatchingProps<{ a: 1, f: true }, boolean>>(); }).expectToCompile(); }); }); describe(`OptionalPropNames`, () => { it(`the<'a', OptionalPropNames<{ a?: 1, b: 2 }>>`, () => { tsst(() => { the<'a', OptionalPropNames<{ a?: 1, b: 2 }>>(); }).expectToCompile(); }); }); describe(`OptionalProps`, () => { it(`the<{ a?: 1 }, OptionalProps<{ a?: 1, b: 2 }>>`, () => { tsst(() => { the<{ a?: 1 }, OptionalProps<{ a?: 1, b: 2 }>>(); }).expectToCompile(); }); }); describe(`RequiredPropNames`, () => { it(`the<'b', RequiredPropNames<{ a?: 1, b: 2 }>>`, () => { tsst(() => { the<'b', RequiredPropNames<{ a?: 1, b: 2 }>>(); }).expectToCompile(); }); }); describe(`RequiredProps`, () => { it(`the<{ b: 2 }, RequiredProps<{ a?: 1, b: 2 }>>`, () => { tsst(() => { the<{ b: 2 }, RequiredProps<{ a?: 1, b: 2 }>>(); }).expectToCompile(); }); }); describe(`Spread`, () => { it(`the<{ a: number, b: number, c: boolean }, Spread<Item1, Item2>>`, () => { tsst(() => { the<{ a: number, b: number, c: boolean }, Spread<Item1, Item2>>(); }).expectToCompile(); }); // keys optional in 2nd arg: works without `strictNullChecks` it(`the<AB, Spread<A, B>>`, () => { tsst(() => { type A = { a: boolean; b: number; c: string; }; type B = { b: number[]; c: string[] | undefined; d: string; e: number | undefined; }; type AB = { a: boolean; b: number[]; c: string | string[]; d: string; e: number | undefined; }; the<AB, Spread<A, B>>(); }).expectToCompile(); }); }); describe(`ObjectHasNumberIndex`, () => { it(`the<'0', ObjectHasNumberIndex<{ 0: 'a' }>>`, () => { tsst(() => { the<'0', ObjectHasNumberIndex<{ 0: 'a' }>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasNumberIndex<['a']>>`, () => { tsst(() => { the<'0', ObjectHasNumberIndex<['a']>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasNumberIndex<{ [i: number]: 'a' }>>`, () => { tsst(() => { the<'1', ObjectHasNumberIndex<{ [i: number]: 'a' }>>(); }).expectToCompile(); }); it(`the<'1', ObjectHasNumberIndex<'a'[]>>`, () => { tsst(() => { the<'1', ObjectHasNumberIndex<'a'[]>>(); }).expectToCompile(); }); }); describe(`ObjectHasElem`, () => { it(`the<'1', ObjectHasElem<{ a: 1 }, 1>>`, () => { tsst(() => { the<'1', ObjectHasElem<{ a: 1 }, 1>>(); }).expectToCompile(); }); it(`the<'0', ObjectHasElem<{ a: 1 }, 0>>`, () => { tsst(() => { the<'0', ObjectHasElem<{ a: 1 }, 0>>(); }).expectToCompile(); }); }); describe(`ObjectNumberKeys`, () => { it(`the<'0'|'1', ObjectNumberKeys<['a','b']>>`, () => { tsst(() => { the<'0'|'1', ObjectNumberKeys<['a','b']>>(); }).expectToCompile(); }); it(`the<'0'|'1', ObjectNumberKeys<{0:'a',1:'b',length:2}>>`, () => { tsst(() => { the<'0'|'1', ObjectNumberKeys<{0:'a',1:'b',length:2}>>(); }).expectToCompile(); }); }); // describe(``, () => { // it(``, () => { // tsst(() => { // the<>(); // }).expectToCompile(); // }); // }); });
the_stack
import 'react-toastify/dist/ReactToastify.css' import { CardContent } from '@material-ui/core' import { Map } from 'immutable' import { ToastContainer, toast } from 'react-toastify' import { connect } from 'react-redux' import { css } from 'glamor' import { fade } from '@material-ui/core/styles/colorManipulator' import { localize } from 'react-localize-redux' import { withRouter } from 'react-router-dom' import { withStyles } from '@material-ui/core/styles' import Button from '@material-ui/core/Button' import Card from '@material-ui/core/Card' import Checkbox from '@material-ui/core/Checkbox' import Divider from '@material-ui/core/Divider' import FormControl from '@material-ui/core/FormControl' import FormControlLabel from '@material-ui/core/FormControlLabel' import FormGroup from '@material-ui/core/FormGroup' import Grid from '@material-ui/core/Grid/Grid' import InputLabel from '@material-ui/core/InputLabel' import OutlinedInput from '@material-ui/core/OutlinedInput' import Paper from '@material-ui/core/Paper' import React, { Component } from 'react' import ReactPaginate from 'react-paginate' import Select from '@material-ui/core/Select' import Slider from '@material-ui/lab/Slider' import TextField from '@material-ui/core/TextField' import Typography from '@material-ui/core/Typography' import { productActions } from 'src/store/actions' import CommonAPI from 'api/CommonAPI' import FormButton from 'src/components/formButton' import ProductComponent from 'src/components/product' import * as userActions from 'store/actions/userActions' import { IProductsComponentProps } from './IProductsComponentProps' import { IProductsComponentState} from './IProductsComponentState' const styles = (theme: any) => ({ root: { display: 'flex' }, demo: { height: 240 }, paper: { padding: theme.spacing(2), height: '100%', color: theme.palette.text.secondary, }, control: { padding: theme.spacing(2) }, formControl: { margin: theme.spacing.unit, minWidth: 120 }, button: { margin: 5, borderRadius: 30, padding: 15, display: 'inline-block', }, slider: { padding: '22px 0px' }, search: { position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: fade(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: fade(theme.palette.common.white, 0.25), }, marginLeft: 0, width: '100%', [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(1), width: 'auto', }, }, searchIcon: { width: theme.spacing(7), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', }, inputRoot: { color: 'inherit', }, filterlabel: { '&$cssFocused $notchedOutline:': { position: 'absolute', top: 0, textAlign: 'left', }, }, inputInput: { padding: theme.spacing(1, 1, 1, 7), transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('sm')]: { width: 120, '&:focus': { width: 200, }, }, }, }) class ProductsComponent extends Component< IProductsComponentProps, IProductsComponentState > { styles = { singinOptions: { paddingBottom: 10, justifyContent: 'space-around', display: 'flex' }, divider: { marginBottom: 10, marginTop: 15 } } /** * Component constructor * @param {object} props is an object properties of component */ constructor(props: IProductsComponentProps) { super(props) const availablePaging = [ 'Cheap Monday', 'ASOS', 'Adidas Original', 'Abercrombie & Fitch', 'ASOS', 'Cheap Monday', 'ASOS', 'Adidas Original', 'Abercrombie & Fitch', 'ASOS', 'Cheap Monday', 'ASOS', 'Adidas Original', 'Abercrombie & Fitch', 'ASOS', 'Cheap Monday', 'ASOS', 'Adidas Original', 'Abercrombie & Fitch', 'ASOS' ] // an example array of items to be paged var exampleItems = availablePaging.map(i => ({ id: i + 1, name: 'Item ' + (i + 1) })) this.state = { emailInput: '', emailInputError: '', passwordInput: '', passwordInputError: '', confirmInputError: '', value: 3, exampleItems: exampleItems, pageOfItems: [], data: [], offset: 0, searchText: '' } // Binding function to `this` this.handleForm = this.handleForm.bind(this) this.productLoad = this.productLoad.bind(this) this.onChangePage = this.onChangePage.bind(this) this.notify = this.notify.bind(this) } onChangePage(pageOfItems: any) { // update state with new page of items this.setState({ pageOfItems: pageOfItems }) } /** * Create a list of posts * @return {DOM} posts */ productLoad = () => { const { mergedProducts } = this.props let productList: any = [] mergedProducts.map((product, index) => { let newProduct: any = ( <ProductComponent key={product.get('productId')} product={product! as any} /> ) productList.push(newProduct as never) }) return productList } /** * Handle register form */ handleForm = () => { const { translate } = this.props let error = false if (this.state.emailInput === '') { this.setState({ emailInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.passwordInput === '') { this.setState({ passwordInputError: translate!('login.passwordRequiredError') }) error = true } // if (!error) { // this.props.login!(this.state.emailInput, this.state.passwordInput) // } } componentWillMount() { const { loadData } = this.props loadData!() } handleChangeGender = (name: any) => (event: any) => { this.setState({ [name]: event.target.value }) } handleChangeCasual = (name: any) => (event: any) => { this.setState({ [name]: event.target.value }) } handleChangeColor = (name: any) => (event: any) => { this.setState({ [name]: event.target.value }) } handleChange = (event: any, value: any) => { this.setState({ value }) } handleChangeCheckedBrand = (name: any) => (event: any) => { this.setState({ [name]: event.target.checked }) } handlePageClick = (data: any) => { let selected = data.selected let offset = Math.ceil(selected + 1) this.setState({ offset: offset }, () => { this.props.loadProductsStream!(this.state.offset, 10) }) } handleInputChange = (event: any) => { const target = event.target const value = target.value if ( value === '') { this.props.clearSearchList!() this.props.loadProductsStream!(this.state.offset, 10) } else { this.setState( { searchText: value}, () => { this.props.loadProductsSearch!(0, 20, this.state.searchText) }) } } notify = () => { toast.success(this.props.translate!('common.featureImplementLater'), { position: toast.POSITION.TOP_CENTER, className: css({ background: '#ff3366' }), }) } /** * Reneder component DOM * @return {react element} return the DOM which rendered by component */ render() { const { classes } = this.props const { value } = this.state const availableSizes = ['All', 'XL', 'L', 'M', 'S', 'XS'] const availableBrands = [ 'Cheap Monday', 'ASOS', 'Adidas Original', 'Abercrombie & Fitch', 'ASOS' ] const availableColors = [ '#000000', '#ffffff', '#e2e2e2', '#ff3366', '#228B22', '#2E8B57' ] const styles = (x: any, selectedColor: any) => ({ backgroundColor: x, margin: '3px', width: '30px', height: '30px', display: 'inline-block', cursor: 'pointer', borderRadius: '50%', boxShadow: x === selectedColor ? '0px 0px 6px 1px rgba(0,0,0,1)' : '0px 0px 2px 1px rgba(0,0,0,1)' }) const productList = this.productLoad() return ( <React.Fragment> <Card style={{ margin: 10 }}> <CardContent className={classes.root}> <Typography variant='subtitle1' style={{ padding: 10, alignSelf: 'center' }} > Filter </Typography> <FormControl variant='outlined' className={classes.formControl}> <InputLabel className={classes.filterlabel} ref={ref => { // this.InputLabelRef = ref }} htmlFor='outlined-age-native-simple' > Gender </InputLabel> <Select native value={this.state.gender} onChange={this.handleChangeGender('age')} input={ <OutlinedInput name='age' labelWidth={this.state.labelWidth} id='outlined-age-native-simple' /> } > <option value='' /> <option value={1}>Male</option> <option value={2}>Female</option> </Select> </FormControl> <FormControl variant='outlined' className={classes.formControl}> <InputLabel ref={ref => { // this.InputLabelRef = ref }} htmlFor='outlined-age-native-simple' > Casual </InputLabel> <Select native value={this.state.casual} onChange={this.handleChangeCasual('age')} input={ <OutlinedInput name='age' labelWidth={this.state.labelWidth} id='outlined-age-native-simple' /> } > <option value='' /> <option value={10}>Ten</option> <option value={20}>Twenty</option> <option value={30}>Thirty</option> </Select> </FormControl> <FormControl variant='outlined' className={classes.formControl}> <InputLabel ref={ref => { // this.InputLabelRef = ref }} htmlFor='outlined-age-native-simple' > Color </InputLabel> <Select native value={this.state.color} onChange={this.handleChangeColor('age')} input={ <OutlinedInput name='age' labelWidth={this.state.labelWidth} id='outlined-age-native-simple' /> } > <option value='' /> <option value={1}>Red</option> <option value={2}>Green</option> <option value={3}>Yellow</option> <option value={4}>Black</option> <option value={5}>Gray</option> <option value={6}>Blue</option> </Select> </FormControl> <Typography variant='subtitle1' style={{ padding: 10, alignSelf: 'center' }} > Sort </Typography> <FormControl variant='outlined' className={classes.formControl}> <InputLabel ref={ref => { // this.InputLabelRef = ref }} htmlFor='outlined-age-native-simple' > Sort by </InputLabel> <Select native value={this.state.sort} onChange={this.handleChangeColor('age')} input={ <OutlinedInput name='age' labelWidth={this.state.labelWidth} id='outlined-age-native-simple' /> } > <option value='' /> <option value={1}>Most Relevant</option> <option value={2}>Less Relevant</option> <option value={3}>From High to Low</option> <option value={4}>From Low to high</option> </Select> </FormControl> <FormControl variant='outlined' className={classes.formControl}> <TextField variant='outlined' id='email-input' onChange={this.handleInputChange} name='emailInput' label={'Search...'} /> </FormControl> </CardContent> </Card> <Paper elevation={1} style={{ textAlign: 'center', boxShadow: '0px 0px 0px 0px'}}> <ReactPaginate previousLabel={'previous'} nextLabel={'next'} breakLabel={'...'} breakClassName={'break-me'} pageCount={this.props.productsPageCount} marginPagesDisplayed={2} pageRangeDisplayed={5} onPageChange={this.handlePageClick} containerClassName={'pagination'} subContainerClassName={'pages pagination'} activeClassName={'active'} /> </Paper> <div className={classes.root} style={{ margin: 10 }}> <Grid xs={6} container spacing={5} direction='column' justify='flex-start' alignItems='center' > <Grid item> <Paper className={classes.paper}> <Typography variant='subtitle1' color='textSecondary'> Color </Typography> {availableColors.map(x => ( <div key={x} style={styles(x, '')} /> ))} <Typography variant='subtitle1' color='textSecondary'> Size </Typography> {availableSizes.map(x => ( <Button color='secondary' key={x}> {x} </Button> ))} <Typography variant='subtitle1' color='textSecondary'> Price Range </Typography> <Slider classes={{ container: classes.slider }} value={value} min={0} max={6} step={1} onChange={this.handleChange} /> <Typography variant='subtitle1' color='textSecondary'> Brand </Typography> {availableBrands.map(x => ( <FormGroup key={x} row> <FormControlLabel control={ <Checkbox checked={this.state.checkedA} onChange={this.handleChangeCheckedBrand('checkedA')} value='checkedA' key={x} /> } label={x} /> </FormGroup> ))} <Divider /> <Grid container> <Grid item container xs={12} sm={6} direction='row' justify='center' alignItems='center' > <FormButton className={classes.button} align='center' color='secondary' onClick={this.notify} > {'Apply'} </FormButton> </Grid> <ToastContainer autoClose={2000}/> <Grid item xs={12} sm={6} container direction='row' justify='center' alignItems='center' > <Typography variant='subtitle1' color='error' align='right'> Clear All </Typography> </Grid> </Grid> </Paper> </Grid> </Grid> <Grid container spacing={1} direction='row' justify='flex-start' alignItems='flex-start' > {productList} </Grid> </div> </React.Fragment> ) } } /** * Map dispatch to props * @param {func} dispatch is the function to dispatch action to reducers * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapDispatchToProps = (dispatch: any, ownProps: IProductsComponentProps) => { const { productsCategoryId } = ownProps.match.params return { loadProductsStream: (page: number, limit: number) => { if (productsCategoryId) { dispatch(productActions.dbGetProductsByCategory(page, limit, productsCategoryId)) } else { dispatch(productActions.dbClearAllCategoryProductList()) dispatch(productActions.dbGetProducts(page, limit)) } }, loadProductsSearch: (page: number, limit: number, searchText: string) => { dispatch(productActions.dbGetProductsBySearchText(page, limit, searchText)) }, loadData: () => { if (productsCategoryId) { dispatch(productActions.dbGetProductsByCategory(1, 10, productsCategoryId)) } else { dispatch(productActions.dbClearAllCategoryProductList()) dispatch(productActions.dbGetProducts()) } }, clearSearchList: () => (dispatch(productActions.dbClearAllSearchList())), openEditor: () => dispatch(userActions.openEditProfile()) } } /** * Map state to props */ const mapStateToProps = ( state: Map<string, any>, ownProps: IProductsComponentProps ) => { let mergedProducts = Map({}) const products = state.getIn(['products', 'userProducts']) mergedProducts = mergedProducts.merge(products) let mergedProductsBySearchText = Map({}) const productsBySearchText = state.getIn([ 'products', 'userProductsBySearchText' ]) mergedProductsBySearchText = mergedProductsBySearchText.merge( productsBySearchText ) if ( mergedProductsBySearchText.keySeq().count() > 0 ) { mergedProducts = mergedProductsBySearchText } let mergedProductsByCategory = Map({}) const productsByCategory = state.getIn(['products', 'userProductsByCategory']) mergedProductsByCategory = mergedProductsByCategory.merge(productsByCategory) if ( mergedProductsByCategory.keySeq().count() > 0 ) { mergedProducts = mergedProductsByCategory } const productsPageCount = state.getIn(['products', 'productsPageCount']) const editProfileOpen = state.getIn(['user', 'openEditProfile']) return { mergedProducts, mergedProductsBySearchText, mergedProductsByCategory, productsPageCount, editProfileOpen } } // - Connect component to redux store export default withRouter<any>( connect( mapStateToProps, mapDispatchToProps )(withStyles(styles as any)(localize( ProductsComponent as any, 'locale', CommonAPI.getStateSlice ) as any) as any) ) as typeof ProductsComponent
the_stack
import * as chai from 'chai' import * as chaiAsPromised from 'chai-as-promised' import 'mocha' import { SerializerV3 as Serializer } from '../../src' import { InvalidHexString, InvalidSchemaType, InvalidString } from '../../src/errors' import { IACMessageDefinitionObjectV3 as IACMessageDefinitionObject } from '../../src/serializer-v3/message' import { SchemaRoot } from '../../src/serializer-v3/schemas/schema' import { AnyMessage } from './schemas/definitions/AnyMessage' import { ArrayMessage } from './schemas/definitions/ArrayMessage' import { BooleanMessage } from './schemas/definitions/BooleanMessage' import { ComplexMessage } from './schemas/definitions/ComplexMessage' import { HexMessage } from './schemas/definitions/HexMessage' import { NumberMessage } from './schemas/definitions/NumberMessage' import { ObjectMessage } from './schemas/definitions/ObjectMessage' import { SimpleMessage } from './schemas/definitions/SimpleMessage' import { StringMessage } from './schemas/definitions/StringMessage' import { TupleMessage } from './schemas/definitions/TupleMessage' const anyMessage: SchemaRoot = require('./schemas/generated/any-message.json') const arrayMessage: SchemaRoot = require('./schemas/generated/array-message.json') const booleanMessage: SchemaRoot = require('./schemas/generated/boolean-message.json') const complexMessage: SchemaRoot = require('./schemas/generated/complex-message.json') const hexMessage: SchemaRoot = require('./schemas/generated/hex-message.json') const numberMessage: SchemaRoot = require('./schemas/generated/number-message.json') const objectMessage: SchemaRoot = require('./schemas/generated/object-message.json') const simpleMessage: SchemaRoot = require('./schemas/generated/simple-message.json') const stringMessage: SchemaRoot = require('./schemas/generated/string-message.json') const tupleMessage: SchemaRoot = require('./schemas/generated/tuple-message.json') // use chai-as-promised plugin chai.use(chaiAsPromised) const expect: Chai.ExpectStatic = chai.expect Serializer.addSchema(1000, { schema: anyMessage }) Serializer.addSchema(1001, { schema: arrayMessage }) Serializer.addSchema(1002, { schema: booleanMessage }) Serializer.addSchema(1003, { schema: complexMessage }) Serializer.addSchema(1004, { schema: hexMessage }) Serializer.addSchema(1005, { schema: numberMessage }) Serializer.addSchema(1006, { schema: objectMessage }) Serializer.addSchema(1007, { schema: simpleMessage }) Serializer.addSchema(1008, { schema: stringMessage }) Serializer.addSchema(1009, { schema: tupleMessage }) const serializer: Serializer = new Serializer() const test = async <T>(type: number, payload: T, expectedError?: string): Promise<void> => { const message: IACMessageDefinitionObject = { id: 12345678, type, protocol: '' as any, payload: payload as any } try { const serialized1: string = await serializer.serialize([message]) const deserialized1 = await serializer.deserialize(serialized1) expect(deserialized1, 'full payload').to.deep.eq([message]) } catch (error) { if (!expectedError) { throw new Error(`Unexpected error with ${JSON.stringify(payload)}: ${error.toString()}`) } expect(error.toString()).to.equal(expectedError) } } describe(`Serializer`, async () => { // TODO: create an issue it('should correctly serialize and deserialize a string message', async () => { await test<StringMessage>(1008, { x: 'str1' }) await test<StringMessage>(1008, { x: '' }) await test<StringMessage>( 1008, { x: '0x1234' }, `${new InvalidString( 'string "0x1234" starts with "0x". This causes problems with RLP. Please use the "HexString" type instead of "string"' )}` ) await test<StringMessage>( 1008, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<StringMessage>( 1008, { x: true as any }, `${new InvalidSchemaType('x: expected type "string", but got "boolean", value: true')}` ) await test<StringMessage>( 1008, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "string", but got "undefined", value: undefined')}` ) await test<StringMessage>( 1008, { x: [] as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: []')}` ) await test<StringMessage>( 1008, { x: {} as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: {}')}` ) }) it('should correctly serialize and deserialize a number message', async () => { await test<NumberMessage>(1005, { x: 1 }) await test<NumberMessage>(1005, { x: 0 }) await test<NumberMessage>(1005, { x: -1 }) await test<NumberMessage>( 1005, { x: 'str1' as any }, `${new InvalidSchemaType('x: expected type "number", but got "string", value: str1')}` ) await test<NumberMessage>( 1005, { x: '' as any }, `${new InvalidSchemaType('x: expected type "number", but got "string", value: ')}` ) await test<NumberMessage>( 1005, { x: true as any }, `${new InvalidSchemaType('x: expected type "number", but got "boolean", value: true')}` ) await test<NumberMessage>( 1005, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "number", but got "undefined", value: undefined')}` ) await test<NumberMessage>( 1005, { x: [] as any }, `${new InvalidSchemaType('x: expected type "number", but got "object", value: []')}` ) await test<NumberMessage>( 1005, { x: {} as any }, `${new InvalidSchemaType('x: expected type "number", but got "object", value: {}')}` ) }) it('should correctly serialize and deserialize a boolean message', async () => { await test<BooleanMessage>(1002, { x: true as any }) await test<BooleanMessage>(1002, { x: false as any }) await test<BooleanMessage>( 1002, { x: 'str1' as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "string", value: str1')}` ) await test<BooleanMessage>( 1002, { x: '' as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "string", value: ')}` ) await test<BooleanMessage>( 1002, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "number", value: 1')}` ) await test<BooleanMessage>( 1002, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "undefined", value: undefined')}` ) await test<BooleanMessage>( 1002, { x: [] as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "object", value: []')}` ) await test<BooleanMessage>( 1002, { x: {} as any }, `${new InvalidSchemaType('x: expected type "boolean", but got "object", value: {}')}` ) }) it('should correctly serialize and deserialize an array message', async () => { await test<ArrayMessage>(1001, { x: [] }) await test<ArrayMessage>(1001, { x: ['str1', 'str2', 'str3'] }) await test<ArrayMessage>( 1001, { x: ['str1', 1] as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<ArrayMessage>( 1001, { x: [undefined, undefined] as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: null')}` ) await test<ArrayMessage>( 1001, { x: [1, 2, 3] as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<ArrayMessage>( 1001, { x: 'str1' as any }, `${new InvalidSchemaType('x: expected type "array", but got "string", value: str1')}` ) await test<ArrayMessage>( 1001, { x: '' as any }, `${new InvalidSchemaType('x: expected type "array", but got "string", value: ')}` ) await test<ArrayMessage>( 1001, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "array", but got "number", value: 1')}` ) await test<ArrayMessage>( 1001, { x: true as any }, `${new InvalidSchemaType('x: expected type "array", but got "boolean", value: true')}` ) await test<ArrayMessage>( 1001, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "array", but got "undefined", value: undefined')}` ) await test<ArrayMessage>( 1001, { x: {} as any }, `${new InvalidSchemaType('x: expected type "array", but got "object", value: {}')}` ) }) it('should correctly serialize and deserialize an object message', async () => { await test<ObjectMessage>(1006, { x: { name: 'str1' } as any }) await test<ObjectMessage>( 1006, { x: { x: 1 } as any }, `${new InvalidSchemaType('name: expected type "string", but got "undefined", value: undefined')}` ) await test<ObjectMessage>( 1006, { x: {} as any }, `${new InvalidSchemaType('name: expected type "string", but got "undefined", value: undefined')}` ) await test<ObjectMessage>( 1006, { x: 'str1' as any }, `${new InvalidSchemaType('x: expected type "object", but got "string", value: str1')}` ) await test<ObjectMessage>( 1006, { x: '' as any }, `${new InvalidSchemaType('x: expected type "object", but got "string", value: ')}` ) await test<ObjectMessage>( 1006, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "object", but got "number", value: 1')}` ) await test<ObjectMessage>( 1006, { x: true as any }, `${new InvalidSchemaType('x: expected type "object", but got "boolean", value: true')}` ) await test<ObjectMessage>( 1006, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "object", but got "undefined", value: undefined')}` ) await test<ObjectMessage>( 1006, { x: [] as any }, `${new InvalidSchemaType('x: expected type "object", but got "object", value: []')}` ) }) it('should throw correct errors when serializing and deserializing invalid hex message', async () => { await test<HexMessage>( 1004, { x: '' as any }, `${new InvalidHexString('"" does not start with "0x"')}` ) await test<HexMessage>( 1004, { x: 'str1' }, `${new InvalidHexString('"str1" does not start with "0x"')}` ) await test<HexMessage>( 1004, { x: { x: 1 } as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: {"x":1}')}` ) await test<HexMessage>( 1004, { x: {} as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: {}')}` ) await test<HexMessage>( 1004, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<HexMessage>( 1004, { x: true as any }, `${new InvalidSchemaType('x: expected type "string", but got "boolean", value: true')}` ) await test<HexMessage>( 1004, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "string", but got "undefined", value: undefined')}` ) await test<HexMessage>( 1004, { x: [] as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: []')}` ) }) it('should correctly serialize and deserialize HEX messages', async () => { await test<HexMessage>(1004, { x: '0xzzzz' // STRING_WITH_HEX_PREFIX_EVEN }) await test<HexMessage>(1004, { x: '0xffff' // HEX_WITH_PREFIX_EVEN }) await test<HexMessage>(1004, { x: 'ffffff' // HEX_WITHOUT_PREFIX_EVEN }) await test<HexMessage>(1004, { x: '0xzzz' // STRING_WITH_HEX_PREFIX_ODD }) await test<HexMessage>(1004, { x: '0xfff' // HEX_WITH_PREFIX_ODD }) await test<HexMessage>(1004, { x: 'fffff' // HEX_WITHOUT_PREFIX_ODD }) }) it('should correctly serialize and deserialize an any message', async () => { await test<AnyMessage>(1000, { x: 'str1' }) await test<AnyMessage>(1000, { x: '' }) await test<AnyMessage>( 1000, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<AnyMessage>( 1000, { x: true as any }, `${new InvalidSchemaType('x: expected type "string", but got "boolean", value: true')}` ) await test<AnyMessage>( 1000, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "string", but got "undefined", value: undefined')}` ) await test<AnyMessage>( 1000, { x: [] as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: []')}` ) await test<AnyMessage>( 1000, { x: {} as any }, `${new InvalidSchemaType('x: expected type "string", but got "object", value: {}')}` ) }) it('should correctly serialize and deserialize a tuple message', async () => { await test<TupleMessage>(1009, { x: ['str', 1, true, { name: 'str' }, ['str']] }) await test<TupleMessage>( 1009, { x: 'str1' as any }, `${new InvalidSchemaType('x: expected type "array", but got "string", value: str1')}` ) await test<TupleMessage>( 1009, { x: 1 as any }, `${new InvalidSchemaType('x: expected type "array", but got "number", value: 1')}` ) await test<TupleMessage>( 1009, { x: true as any }, `${new InvalidSchemaType('x: expected type "array", but got "boolean", value: true')}` ) await test<TupleMessage>( 1009, { x: undefined as any }, `${new InvalidSchemaType('x: expected type "array", but got "undefined", value: undefined')}` ) await test<TupleMessage>( 1009, { x: [] as any }, `${new InvalidSchemaType('x: expected type "string", but got "undefined", value: ')}` ) await test<TupleMessage>( 1009, { x: {} as any }, `${new InvalidSchemaType('x: expected type "array", but got "object", value: {}')}` ) await test<TupleMessage>( 1009, { x: ['str', 1, true, { name: 1 } as any, []] }, `${new InvalidSchemaType('name: expected type "string", but got "number", value: 1')}` ) await test<TupleMessage>( 1009, { x: [1, 'str', true, { name: 'str' }, []] as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) await test<TupleMessage>( 1009, { x: ['str', 1, true, { name: 'str' }, [1]] as any }, `${new InvalidSchemaType('x: expected type "string", but got "number", value: 1')}` ) }) it('should correctly serialize and deserialize a simple message', async () => { const payload: SimpleMessage = { name: '', test: 0, bool: false, obj: { name: '', test: 0, bool: false }, arr1: ['str1', ''], arr2: [1, 0, 9999999999], arr3: [true, false] } await test(1007, payload) }) it('should give an error if not all parameters are provided', async () => { try { const message: IACMessageDefinitionObject = { id: 12345678, type: 1003, protocol: '' as any, payload: ({ name: 'test' } as ComplexMessage) as any } await serializer.serialize([message]) } catch (error) { expect(error.toString()).to.equal(`${new InvalidSchemaType('arr1: expected type "array", but got "undefined", value: undefined')}`) } }) it('should give an error if not all parameters are provided', async () => { try { const message: IACMessageDefinitionObject = { id: 12345678, type: 1003, protocol: '' as any, payload: ({ name: 'test' } as ComplexMessage) as any } await serializer.serialize([message]) } catch (error) { expect(error.toString()).to.equal(`${new InvalidSchemaType('arr1: expected type "array", but got "undefined", value: undefined')}`) } }) // it('should give an error if not all parameters are provided', async () => { // const message: IACMessageDefinitionObjectV3 = { // id: 12345678, // type: 1003, // protocol: '' as any, // payload: { // publicKey: '02179ec62cac6a75e3e177bef2f92499ebf14a4b7cfdb7f6c5410288b5273acf3f', // transaction: { // nonce: '0x2c', // gasPrice: '0x21e66fb00', // gasLimit: '0x493e0', // to: '0xd709a66264b4055EC23E2Af8B13D06a6375Bb24c', // value: '0x0', // chainId: 1, // data: '0x' // }, // callbackURL: 'airgap-wallet://?d=' // } // } // const serialized1: string = await serializer.serialize([message]) // expect(await serializer.deserialize(serialized1), 'full chunk').to.deep.eq([message]) // }) it('should serialize a complex, nested object', async () => { const payload: ComplexMessage = { name: 'str', test: 1, bool: true, obj1: { name: 'str', test: 1, bool: true }, arr1: ['str1', 'str2'], arr2: [1, 2, 3, 4], arr3: [true, false, true], arr4: [ { name: 'str', test: 1, bool: true } ], arr5: ['str1', 'str2', 'str3', 1, true, { name: 'str', test: 1, bool: true }], obj2: { name: 'str', test: 1, bool: true, obj1: { name: 'str', test: 1, bool: true }, arr1: ['str1', 'str2'], arr2: [1, 2, 3, 4], arr3: [true, false, true], arr4: [{ name: 'str', test: 1, bool: true }], arr5: ['str1', 'str2', 'str3', 1, true, { name: 'str', test: 1, bool: true }] }, obj3: { arr1: [[['str1']], [['str2'], ['str3', 'str4']]] }, obj4: { arr1: [{ arr1: [{ name: 'str1' }] }, { arr1: [{ name: 'str1' }, { name: 'str2' }] }] } } const message: IACMessageDefinitionObject = { id: 12345678, type: 1003, protocol: '' as any, payload: payload as any } const serialized1: string = await serializer.serialize([message]) expect(await serializer.deserialize(serialized1), 'full chunk').to.deep.eq([message]) }) })
the_stack
import { CSSObject, UseThemeFunction } from '@theme-ui/css' import { Platform } from 'react-native' import { defaultBreakpoints } from './breakpoints' import { SUPPORT_FRESNEL_SSR } from '../utils/deprecated-ssr' import { DripsyFinalTheme } from '../declarations' import type { SxProp } from './types' import { get } from './get' import { Aliases, aliases, scales, Scales } from './scales' type SxProps = SxProp type Theme = DripsyFinalTheme type CssPropsArgument = ({ theme?: Theme } | Theme) & { /** * We use this for a custom font family. */ fontFamily?: string themeKey?: keyof DripsyFinalTheme } const defaultTheme = { space: [0, 4, 8, 16, 32, 64, 128, 256, 512], fontSizes: [12, 14, 16, 20, 24, 32, 48, 64, 72], } export type ResponsiveSSRStyles = Exclude< NonNullable<SxProps>, UseThemeFunction >[] const responsive = ( styles: Exclude<SxProps, UseThemeFunction>, { breakpoint }: { breakpoint?: number } = {} ) => (theme?: Theme) => { const next: Exclude<SxProps, UseThemeFunction> & { responsiveSSRStyles?: ResponsiveSSRStyles } = {} for (const key in styles) { const value = typeof styles[key] === 'function' ? styles[key](theme) : styles[key] if (value == null) continue if (!Array.isArray(value)) { // @ts-ignore next[key] = value continue } if (key === 'transform') { // @ts-ignore next[key] = value continue } if (Platform.OS === 'web' && SUPPORT_FRESNEL_SSR) { next.responsiveSSRStyles = next.responsiveSSRStyles || [] const mediaQueries = [0, ...defaultBreakpoints] for (let i = 0; i < mediaQueries.length; i++) { next.responsiveSSRStyles[i] = next.responsiveSSRStyles[i] || {} let styleAtThisMediaQuery = value[i] // say we have value value = ['blue', null, 'green'] // then styleAtThisMediaQuery[1] = null // we want it to be blue, since it's mobile-first if (styleAtThisMediaQuery == null) { if (i === 0) { // if we're at the first breakpoint, and it's null, just do nothing // for later values, we'll extract this value from the previous value continue } // if we're after the first breakpoint, let's extract this style value from a previous breakpoint const nearestBreakpoint = (breakpointIndex: number): number => { // mobile-first breakpoints if (breakpointIndex <= 0 || typeof breakpointIndex !== 'number') return 0 if (value[breakpointIndex] == null) { // if this value doesn't have a breakpoint, find the previous, recursively return nearestBreakpoint(breakpointIndex - 1) } return breakpointIndex } const previousBreakpoint = nearestBreakpoint(i) const styleAtPreviousMediaQuery = value[previousBreakpoint] if (styleAtPreviousMediaQuery) { styleAtThisMediaQuery = styleAtPreviousMediaQuery } } next.responsiveSSRStyles[i][key] = styleAtThisMediaQuery } } else { // since we aren't on web, we let RN handle the breakpoints with JS const nearestBreakpoint = (breakpointIndex: number): number => { // mobile-first breakpoints if (breakpointIndex <= 0 || typeof breakpointIndex !== 'number') return 0 if (value[breakpointIndex] == null) { // if this value doesn't have a breakpoint, find the previous, recursively return nearestBreakpoint(breakpointIndex - 1) } return breakpointIndex } // if we're on mobile, we do have a breakpoint // so we can override TS here w/ `as number` const breakpointIndex = nearestBreakpoint(breakpoint as number) next[key] = value[breakpointIndex] } } return next } const positiveOrNegative = (scale: object, value: string | number) => { if (typeof value !== 'number' || value >= 0) { if (typeof value === 'string' && value.startsWith('-')) { const valueWithoutMinus = value.substring(1) const n = get(scale, valueWithoutMinus, valueWithoutMinus) return `-${n}` } return get(scale, value, value) } const absolute = Math.abs(value) const n = get(scale, absolute, absolute) if (typeof n === 'string') return '-' + n return Number(n) * -1 } const transforms = [ 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'marginBlock', 'marginBlockEnd', 'marginBlockStart', 'marginInline', 'marginInlineEnd', 'marginInlineStart', 'top', 'bottom', 'left', 'right', ].reduce( (acc, curr) => ({ ...acc, [curr]: positiveOrNegative, }), {} ) /** * Here we remove web style keys from components to prevent annoying errors on native */ const filterWebStyleKeys = ( styleProp: Exclude<SxProps, UseThemeFunction> = {} ): Exclude<SxProps, UseThemeFunction> => { if (Platform.OS == 'web') { return styleProp } // avoid prop mutations const finalStyles = { ...styleProp } const webOnlyKeys = [ // from https://necolas.github.io/react-native-web/docs/styling/#non-standard-properties 'animationKeyframes', 'animationFillMode', 'transitionProperty', 'whiteSpace', 'userSelect', 'transitionDuration', 'transitionTimingFunction', 'cursor', 'animationDuration', 'animationDelay', 'transitionDelay', 'animationDirection', 'animationIterationCount', 'outlineColor', ] webOnlyKeys.forEach((key) => { if (finalStyles?.[key as keyof typeof styleProp]) { delete finalStyles?.[key as keyof typeof styleProp] } }) return finalStyles } export const css = ( args: SxProps = {}, breakpoint?: number // { ssr }: { ssr?: boolean } = {} ) => ({ themeKey, fontFamily: fontFamilyFromProps, ...props }: CssPropsArgument = {}): CSSObject => { const theme: DripsyFinalTheme = { ...defaultTheme, ...('theme' in props ? props.theme : props), } as DripsyFinalTheme let result: CSSObject = {} const obj = typeof args === 'function' ? args(theme) : args const filteredOutWebKeys = filterWebStyleKeys(obj) const styles = responsive(filteredOutWebKeys, { breakpoint })(theme) for (const key in styles) { const x = styles[key] const val = typeof x == 'function' ? x(theme) : x if (key == 'variant') { // const variant = css(get(theme, val))(theme) const variant = css( get(theme, themeKey + '.' + val, get(theme, val)), breakpoint )({ theme }) result = { ...result, ...variant } continue } if (key == 'transform') { result[key] = val continue } if (key == 'textShadow' && val && theme.textShadows?.[val]) { // we want to change textShadowColor to theme keys via css function // @ts-expect-error theme UI doesn't have RN textShadow*, need to add this later const styledTextShadow = css(theme.textShadows[val], breakpoint)(theme) result = { ...result, ...styledTextShadow } continue } if (key == 'boxShadow' && val && theme.shadows?.[val]) { // @ts-expect-error theme UI doesn't have RN shadow*, need to add this later const styledBoxShadow = css(theme.shadows[val], breakpoint)(theme) result = { ...result, ...styledBoxShadow } continue } if (val === '') { console.error( `[dripsy] Invalid style. You passed an empty string ('') for ${key}. Please fix this.` ) continue } if (val && typeof val == 'object') { // @ts-ignore result[key] = css(val, breakpoint)(theme) continue } if (typeof val == 'boolean') { // StyleSheet doesn't allow booleans continue } const prop = key in aliases ? aliases[key as keyof Aliases] : key const scaleName = prop in scales ? scales[prop as keyof Scales] : undefined // @ts-expect-error const scale = get(theme, scaleName, get(theme, prop, {})) const transform = get(transforms, prop, get) const value = transform(scale, val, val) if (key === 'fontFamily') { // ok, building off of fontWeight prior // we just need to check if we've already set the fontFamily based on the weight // if we have, continue. Otherwise, set it if (result?.fontFamily) { continue } if (value === 'root') { // if we're setting this font to the `root` font, // make sure it actually exists // why? because by default, our text sets the `root` style // however, this only applies if you have a custom font // if you don't have a custom font named root, we shold ignore the fontFamily: 'root' definition if (!theme?.fonts?.root) { // techincally speaking, if value === 'root', this means that we already know there's no custom root font // why? bc value extracts the theme values. Since `root` is a reserved word in dripsy, we know this wouldn't work. // however, we still check to make sure. It's also easier to understand if I forget later, // ...or if someone accidentally names a font `root` even though the docs say not to continue } } // ok, no font-family set yet, so let's continue. } if (key == 'fontWeight' && styles?.fontWeight) { // let's check if we have a custom font that corresponds to this font weight // we have a custom font for this family in our theme // example: if we pass fontWeight: 'bold', and fontFamily: 'arial', this will be true for themes that have // customFonts: {arial: {bold: 'arialBold'}} // we also pass the font-family from other CSS props here at the top of the function, so fall back to that if it exists const fontFamilyKeyFromStyles = (styles?.fontFamily as string) ?? fontFamilyFromProps // default font for all text styles const rootFontFamilyFromTheme = theme?.fonts?.root // either the raw value, or one from our theme if (fontFamilyKeyFromStyles || rootFontFamilyFromTheme) { const fontWeight = value let fontFamily if (fontFamilyKeyFromStyles) { // first, check if our theme has a font with this name. If not, just use the normal name. // for instance, if we pass fontFamily: 'body', and our theme has: // { fonts: {body: 'arial'}} (<- in this case, if fontFamilyKey = 'body', we get 'arial' back) // then we'd want to get fonts.body = 'arial' // however, if we're just writing fontFamily: 'arial' instead of 'body', we need no alias fontFamily = theme?.fonts?.[fontFamilyKeyFromStyles] ?? fontFamilyKeyFromStyles } else if (rootFontFamilyFromTheme) { fontFamily = rootFontFamilyFromTheme } // const fontFamily = // (theme?.fonts as any)?.[fontFamilyKey] ?? fontFamilyKey if (fontFamily) { if (typeof fontFamily != 'string') { console.error( `[dripsy] error. Passed font family name that was not a string. This value should either be a string which corresponds to a key of your theme.fonts, or, it should be a string that corresponds to a raw font name. Your font will not be applied, please resolve this.` ) continue } const customFontFamilyForWeight = theme?.customFonts?.[fontFamily]?.[fontWeight] if (customFontFamilyForWeight) { // ok, now we just need to set the fontFamily to this value. oof // following the comment above, in this case, we set fontFamily: `arialBold` result.fontFamily = customFontFamilyForWeight continue } } } } if (key == 'size') { result.width = value result.height = value } else { result[prop] = value } } return result } export class Styles { static create<T extends { [key: string]: NonNullable<SxProps> }>( styles: T ): T { return styles } }
the_stack
import { AssetConfigurationMap } from "@akashic/game-configuration"; import { AssetManager, AssetManagerLoadHandler, AudioAssetConfigurationBase, GameConfiguration, Asset, ScriptAsset, AudioAsset, ImageAsset, ImageAssetConfigurationBase } from ".."; import { customMatchers, Game, Surface } from "./helpers"; expect.extend(customMatchers); describe("test AssetManager", () => { const gameConfiguration: GameConfiguration = { width: 320, height: 320, fps: 30, main: "mainScene", audio: { user2: { loop: true, hint: { streaming: true } } }, assets: { foo: { type: "image", path: "/path1.png", virtualPath: "path1.png", width: 1, height: 1 }, bar: { type: "image", path: "/path2.png", virtualPath: "path2.png", width: 1, height: 1, hint: { untainted: true } }, zoo: { type: "audio", path: "/path/to/a/file", virtualPath: "path/to/a/file", systemId: "music", duration: 1984 }, baz: { type: "audio", path: "/path/to/a/file", virtualPath: "path/to/a/file", systemId: "music", duration: 42, loop: false, hint: { streaming: false } }, qux: { type: "audio", path: "/path/to/a/file", virtualPath: "path/to/a/file", systemId: "sound", duration: 667408 }, quux: { type: "audio", path: "/path/to/a/file", virtualPath: "path/to/a/file", systemId: "sound", duration: 5972, loop: true, hint: { streaming: true } } } }; it("初期化", () => { const game = new Game(gameConfiguration, "/"); const manager = game._assetManager; const assets = gameConfiguration.assets as AssetConfigurationMap; expect(manager.configuration.foo.path).toBe(assets.foo.path); expect(manager.configuration.bar.path).toBe(assets.bar.path); expect(manager.configuration.zoo.path).toBe(assets.zoo.path); expect(manager.configuration.baz.path).toBe(assets.baz.path); expect(manager.configuration.qux.path).toBe(assets.qux.path); expect(manager.configuration.quux.path).toBe(assets.quux.path); expect(Object.keys(manager._assets).length).toEqual(0); expect(Object.keys(manager._liveAssetVirtualPathTable).length).toEqual(0); expect(Object.keys(manager._liveAssetPathTable).length).toEqual(0); expect(Object.keys(manager._refCounts).length).toEqual(0); expect(Object.keys((manager as any)._loadings).length).toEqual(0); expect(manager.configuration.zoo.systemId).toEqual("music"); expect(manager.configuration.zoo.duration).toEqual((assets.zoo as AudioAssetConfigurationBase).duration); expect(manager.configuration.zoo.loop).toEqual(true); expect(manager.configuration.zoo.hint).toEqual({ streaming: true }); expect(manager.configuration.baz.systemId).toEqual("music"); expect(manager.configuration.baz.duration).toEqual((assets.baz as AudioAssetConfigurationBase).duration); expect(manager.configuration.baz.loop).toEqual(false); expect(manager.configuration.baz.hint).toEqual({ streaming: false }); expect(manager.configuration.qux.systemId).toEqual("sound"); expect(manager.configuration.qux.duration).toEqual((assets.qux as AudioAssetConfigurationBase).duration); expect(manager.configuration.qux.loop).toEqual(false); expect(manager.configuration.qux.hint).toEqual({ streaming: false }); expect(manager.configuration.quux.systemId).toEqual("sound"); expect(manager.configuration.quux.duration).toEqual((assets.quux as AudioAssetConfigurationBase).duration); expect(manager.configuration.quux.loop).toEqual(true); expect(manager.configuration.quux.hint).toEqual({ streaming: true }); }); it("rejects illegal configuration", () => { const illegalConf = { foo: { type: "image", virtualPath: "foo.png" // no path given } } as any; expect(() => new Game({ width: 320, height: 320, assets: illegalConf, main: "mainScene" })).toThrowError("AssertionError"); const illegalConf2 = { foo: { type: "image", path: "/foo.png", width: 1 // no virtualPath given } } as any; expect(() => new Game({ width: 320, height: 320, assets: illegalConf2, main: "mainScene" })).toThrowError("AssertionError"); const illegalConf3 = { foo: { type: "image", path: "/foo.png", virtualPath: "foo.png", width: 1 // no height given } } as any; expect(() => new Game({ width: 320, height: 320, assets: illegalConf3, main: "mainScene" })).toThrowError("AssertionError"); const legalConf: { [id: string]: ImageAssetConfigurationBase } = { foo: { type: "image", path: "/foo.png", virtualPath: "foo.png", width: 1, height: 1 } }; expect(() => { return new Game( { width: "320" as any /* not a number */, height: 320, assets: legalConf, main: "mainScene" }, "/foo/bar/" ); }).toThrowError("AssertionError"); expect(() => { return new Game( { width: 320, height: "320" as any /* not a number */, assets: legalConf, main: "mainScene" }, "/foo/bar/" ); }).toThrowError("AssertionError"); expect(() => { return new Game( { width: 320, height: 320, fps: "60" as any /* not a number */, assets: legalConf, main: "mainScene" }, "/foo/bar/" ); }).toThrowError("AssertionError"); expect(() => { return new Game( { width: 320, height: 320, fps: 120 /* out of (0-60] */, assets: legalConf, main: "mainScene" }, "/foo/bar/" ); }).toThrowError("AssertionError"); const audioIllegalConf: { [id: string]: AudioAssetConfigurationBase } = { corge: { type: "audio", path: "/path/to/a/file", virtualPath: "path/to/a/file", systemId: "user" as any, // `music` と `sound` 以外のsystemIdはエラーとなる duration: 91 } }; expect(() => new Game({ width: 320, height: 320, assets: audioIllegalConf, main: "mainScene" })).toThrowError("AssertionError"); }); it("loads/unloads an asset", done => { const game = new Game(gameConfiguration); const manager = game._assetManager; const handler: AssetManagerLoadHandler = { _onAssetLoad: (a: ImageAsset) => { expect(a.id).toBe("foo"); expect(a.hint).toBeUndefined(); expect(a.destroyed()).toBe(false); manager.unrefAsset("foo"); expect(a.destroyed()).toBe(true); done(); }, _onAssetError: () => { fail("asset load error: should not fail"); done(); } }; expect(manager.requestAsset("foo", handler)).toBe(true); }); it("loads assets", done => { const game = new Game(gameConfiguration); const manager = game._assetManager; const handler: AssetManagerLoadHandler = { _onAssetLoad: (a: ImageAsset) => { expect(a.id).toBe("bar"); expect(a.hint).toEqual({ untainted: true }); done(); }, _onAssetError: () => { fail("asset load error: should not fail"); done(); } }; manager.requestAssets(["bar"], handler); }); it("loads assets multiple times", done => { const game = new Game(gameConfiguration, "/"); const manager = game._assetManager; const innerAssets = ["foo", "bar"]; const outerAssets = ["foo"]; const loadedNames: string[] = []; const handlerInner: AssetManagerLoadHandler = { _onAssetLoad: a => { loadedNames.push(a.id); if (loadedNames.length === 2) { expect(loadedNames.indexOf("foo")).not.toBe(-1); expect(loadedNames.indexOf("bar")).not.toBe(-1); expect(manager._refCounts.foo).toBe(2); expect(manager._refCounts.bar).toBe(1); expect(manager._assets).toHaveProperty("foo"); expect(manager._assets).toHaveProperty("bar"); expect(manager._liveAssetVirtualPathTable["path1.png"].id).toBe("foo"); expect(manager._liveAssetVirtualPathTable["path2.png"].id).toBe("bar"); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("/path/to/a/file"); expect(manager._liveAssetPathTable["/path1.png"]).toBe("path1.png"); expect(manager._liveAssetPathTable["/path2.png"]).toBe("path2.png"); expect(manager._liveAssetPathTable).not.toHaveProperty("path/to/a/file"); manager.unrefAssets(innerAssets); expect(manager._refCounts.foo).toBe(1); expect(manager._refCounts).not.toHaveProperty("bar"); expect(manager._assets.foo).not.toBe(undefined); expect(manager._assets.bar).toBe(undefined); expect(manager._liveAssetVirtualPathTable["path1.png"].id).toBe("foo"); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("path2.png"); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("path/to/a/file"); expect(manager._liveAssetPathTable["/path1.png"]).toBe("path1.png"); expect(manager._liveAssetPathTable).not.toHaveProperty("/path2.png"); expect(manager._liveAssetPathTable).not.toHaveProperty("/path/to/a/file"); manager.unrefAssets(outerAssets); expect(manager._refCounts).not.toHaveProperty("foo"); expect(manager._refCounts).not.toHaveProperty("bar"); expect(manager._assets.foo).toBe(undefined); expect(manager._assets.bar).toBe(undefined); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("path1.png"); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("path2.png"); expect(manager._liveAssetVirtualPathTable).not.toHaveProperty("path/to/a/file"); expect(manager._liveAssetPathTable).not.toHaveProperty("/path1.png"); expect(manager._liveAssetPathTable).not.toHaveProperty("/path2.png"); expect(manager._liveAssetPathTable).not.toHaveProperty("/path/to/a/file"); expect(a.destroyed()).toBe(true); done(); } }, _onAssetError: () => { fail("asset load error: should not fail"); done(); } }; const handlerOuter: AssetManagerLoadHandler = { _onAssetLoad: () => { manager.requestAssets(innerAssets, handlerInner); }, _onAssetError: () => { fail("asset load error: should not fail"); done(); } }; manager.requestAssets(outerAssets, handlerOuter); }); it("handles loading failure", done => { const game = new Game(gameConfiguration); const manager = game._assetManager; const assetIds = ["foo", "zoo"]; const failureCounts: { [id: string]: number } = {}; let loadCount = 0; const handler: AssetManagerLoadHandler = { _onAssetLoad: a => { expect(failureCounts[a.id]).toBe(2); ++loadCount; if (loadCount === assetIds.length) { expect(manager._countLoadingAsset()).toBe(0); done(); } }, _onAssetError: (a, _err, callback) => { if (!failureCounts.hasOwnProperty(a.id)) failureCounts[a.id] = 0; ++failureCounts[a.id]; callback(a); } }; game.resourceFactory.withNecessaryRetryCount(2, () => { manager.requestAssets(assetIds, handler); }); }); it("handles loading failure - never success", done => { const game = new Game(gameConfiguration); const manager = game._assetManager; const assetIds = ["foo", "zoo"]; const failureCounts: { [id: string]: number } = {}; let gaveUpCount = 0; const handler: AssetManagerLoadHandler = { _onAssetLoad: () => { fail("should not succeed to load"); done(); }, _onAssetError: (a, err, callback) => { if (!failureCounts.hasOwnProperty(a.id)) failureCounts[a.id] = 0; ++failureCounts[a.id]; if (!err.retriable) { expect(failureCounts[a.id]).toBe(AssetManager.MAX_ERROR_COUNT + 1); expect(() => { callback(a); }).toThrowError("AssertionError"); ++gaveUpCount; } else { callback(a); } if (gaveUpCount === 2) { setTimeout(() => { expect(manager._countLoadingAsset()).toBe(0); done(); }, 0); } } }; game.resourceFactory.withNecessaryRetryCount(AssetManager.MAX_ERROR_COUNT + 1, () => { manager.requestAssets(assetIds, handler); }); }); it("handles loading failure - non-retriable", done => { const game = new Game(gameConfiguration); const manager = game._assetManager; const assetIds = ["foo", "zoo"]; const failureCounts: { [id: string]: number } = {}; let gaveUpCount = 0; const handler: AssetManagerLoadHandler = { _onAssetLoad: () => { fail("should not succeed to load"); done(); }, _onAssetError: (a, err, callback) => { if (!failureCounts.hasOwnProperty(a.id)) failureCounts[a.id] = 0; ++failureCounts[a.id]; if (!err.retriable) { expect(failureCounts[a.id]).toBe(1); expect(() => { callback(a); }).toThrowError("AssertionError"); ++gaveUpCount; } else { callback(a); } if (gaveUpCount === 2) { setTimeout(() => { expect(manager._countLoadingAsset()).toBe(0); done(); }, 0); } } }; game.resourceFactory.withNecessaryRetryCount(-1, () => { manager.requestAssets(assetIds, handler); }); }); it("can be instanciated without configuration", () => { const game = new Game(gameConfiguration); const manager = new AssetManager(game); expect(manager.configuration).toEqual({}); expect(manager.destroyed()).toBe(false); manager.destroy(); expect(manager.destroyed()).toBe(true); }); it("loads dynamically defined assets", done => { const game = new Game(gameConfiguration); const manager = new AssetManager(game); manager.requestAsset( { id: "testDynamicAsset", type: "image", width: 10, height: 24, uri: "http://dummy.example/unused-name.png" }, { _onAssetError: () => { done.fail(); }, _onAssetLoad: (asset: ImageAsset) => { expect(asset.id).toBe("testDynamicAsset"); expect(asset.width).toBe(10); expect(asset.height).toBe(24); expect(asset.asSurface() instanceof Surface).toBe(true); expect(manager._assets.testDynamicAsset).toBe(asset); expect(manager._refCounts.testDynamicAsset).toBe(1); manager.requestAssets(["testDynamicAsset"], { _onAssetError: () => { done.fail(); }, _onAssetLoad: asset2 => { expect(asset2).toBe(asset); expect(manager._refCounts.testDynamicAsset).toBe(2); manager.unrefAsset(asset2); expect(manager._refCounts.testDynamicAsset).toBe(1); manager.unrefAssets(["testDynamicAsset"]); expect(manager._refCounts.testDynamicAsset).toBe(undefined); // 0 のエントリは削除される expect(asset2.destroyed()).toBe(true); done(); } }); } } ); }); it("releases assets when destroyed", done => { const game = new Game(gameConfiguration); const manager = new AssetManager(game); manager.requestAsset( { id: "testDynamicAsset", type: "image", width: 10, height: 24, uri: "http://dummy.example/unused-name.png" }, { _onAssetError: () => { done.fail(); }, _onAssetLoad: asset => { expect(asset.destroyed()).toBe(false); manager.destroy(); expect(manager.destroyed()).toBe(true); expect(asset.destroyed()).toBe(true); done(); } } ); }); describe("accessorPath", () => { // AssetManager のメソッドは配列の順序は保証しないので、このテストは全体的に実装依存になっていることに注意。 const gameConfiguration: GameConfiguration = { width: 320, height: 240, fps: 30, main: "./script/main.js", assets: { "id-script/main.js": { type: "script", path: "script/main.js", virtualPath: "script/main.js", global: true }, "id-assets/stage01/bgm01": { type: "audio", path: "assets/stage01/bgm01", virtualPath: "assets/stage01/bgm01", systemId: "music", duration: 10000 }, "id-assets/stage01/se01": { type: "audio", path: "assets/stage01/se01", virtualPath: "assets/stage01/se01", systemId: "sound", duration: 10000 }, "id-assets/stage01/boss.png": { type: "image", path: "assets/stage01/boss.png", virtualPath: "assets/stage01/boss.png", width: 64, height: 64 }, "id-assets/stage01/map.json": { type: "text", path: "assets/stage01/map.json", virtualPath: "assets/stage01/map.json" }, "id-assets/chara01/image.png": { type: "image", path: "assets/chara01/image.png", virtualPath: "assets/chara01/image.png", width: 32, height: 32 }, "node_modules/@akashic-extension/some-library/lib/index.js": { type: "script", path: "node_modules/@akashic-extension/some-library/lib/index.js", virtualPath: "node_modules/@akashic-extension/some-library/lib/index.js", global: true }, "node_modules/@akashic-extension/some-library/assets/image.png": { type: "image", path: "node_modules/@akashic-extension/some-library/assets/image.png", virtualPath: "node_modules/@akashic-extension/some-library/assets/image.png", width: 2048, height: 1024 }, "node_modules/@akashic-extension/some-library/assets/boss.png": { type: "image", path: "node_modules/@akashic-extension/some-library/assets/boss.png", virtualPath: "node_modules/@akashic-extension/some-library/assets/boss.png", width: 324, height: 196 } }, moduleMainScripts: { "@akashic-extension/some-library": "node_modules/@akashic-extension/some-library/lib/index.js" } }; it("can resolve patterns to asset IDs", () => { const game = new Game(gameConfiguration); const manager = game._assetManager; expect(manager.resolvePatternsToAssetIds(["/assets/**/*"])).toEqual([ "id-assets/stage01/bgm01", "id-assets/stage01/se01", "id-assets/stage01/boss.png", "id-assets/stage01/map.json", "id-assets/chara01/image.png" ]); expect(manager.resolvePatternsToAssetIds(["@akashic-extension/some-library/**/*"])).toEqual([ "node_modules/@akashic-extension/some-library/lib/index.js", "node_modules/@akashic-extension/some-library/assets/image.png", "node_modules/@akashic-extension/some-library/assets/boss.png" ]); }); it("can resolve a filter to asset IDs", () => { const game = new Game(gameConfiguration); const manager = game._assetManager; expect(manager.resolvePatternsToAssetIds([s => /\/stage\d+\//.test(s)])).toEqual([ "id-assets/stage01/bgm01", "id-assets/stage01/se01", "id-assets/stage01/boss.png", "id-assets/stage01/map.json" ]); }); it("can resolve patterns to asset IDs", () => { const game = new Game(gameConfiguration); const manager = game._assetManager; expect(manager.resolvePatternsToAssetIds(["/assets/**/*"])).toEqual([ "id-assets/stage01/bgm01", "id-assets/stage01/se01", "id-assets/stage01/boss.png", "id-assets/stage01/map.json", "id-assets/chara01/image.png" ]); }); it("can resolve multiple patterns/filters to asset IDs", () => { const game = new Game(gameConfiguration); const manager = game._assetManager; expect(manager.resolvePatternsToAssetIds(["**/*.js", s => /\/bgm\d+$/.test(s)])).toEqual([ "id-script/main.js", "node_modules/@akashic-extension/some-library/lib/index.js", "id-assets/stage01/bgm01" ]); }); function setupAssetLoadedGame( assetIds: string[], fail: (arg: any) => void, callback: (arg: { manager: AssetManager; game: Game }) => void ): void { const game = new Game(gameConfiguration); const manager = game._assetManager; let count = 0; manager.requestAssets(assetIds, { _onAssetLoad: () => { if (++count < assetIds.length) return; callback({ game, manager }); }, _onAssetError: () => { fail("asset load error: should not fail"); } }); } it("can peek live assets by IDs", done => { const assetIds = ["id-script/main.js", "id-assets/stage01/se01", "id-assets/chara01/image.png"]; setupAssetLoadedGame( assetIds, s => done.fail(s), ({ manager }) => { // live でも type が合わなければエラー expect(() => manager.peekLiveAssetById("id-script/main.js", "image")).toThrowError("AssertionError"); const mainjs = manager.peekLiveAssetById("id-script/main.js", "script") as ScriptAsset; expect(mainjs.type).toBe("script"); expect(mainjs.path).toBe("script/main.js"); expect(typeof mainjs.execute).toBe("function"); // 読んでない (live でない) アセットはエラー expect(() => manager.peekLiveAssetById("id-assets/stage01/bgm01", "text")).toThrowError("AssertionError"); expect(() => manager.peekLiveAssetById("id-assets/stage01/bgm01", "audio")).toThrowError("AssertionError"); expect(() => manager.peekLiveAssetById("id-assets/stage01/se01", "text")).toThrowError("AssertionError"); const se01 = manager.peekLiveAssetById("id-assets/stage01/se01", "audio") as AudioAsset; expect(se01.type).toBe("audio"); expect(se01.path).toBe("assets/stage01/se01"); expect(se01.duration).toBe(10000); done(); } ); }); it("can peek live assets by accessorPath", done => { const assetIds = [ "id-script/main.js", "id-assets/stage01/se01", "id-assets/chara01/image.png", "node_modules/@akashic-extension/some-library/assets/boss.png" ]; setupAssetLoadedGame( assetIds, s => done.fail(s), ({ manager }) => { // live でも type が合わなければエラー expect(() => manager.peekLiveAssetByAccessorPath("/script/main.js", "image")).toThrowError("AssertionError"); const mainjs = manager.peekLiveAssetByAccessorPath("/script/main.js", "script") as ScriptAsset; expect(mainjs.type).toBe("script"); expect(mainjs.path).toBe("script/main.js"); expect(typeof mainjs.execute).toBe("function"); // 読んでない (live でない) アセットはエラー expect(() => manager.peekLiveAssetByAccessorPath("/assets/stage01/bgm01", "text")).toThrowError("AssertionError"); expect(() => manager.peekLiveAssetByAccessorPath("/assets/stage01/bgm01", "audio")).toThrowError("AssertionError"); expect(() => manager.peekLiveAssetByAccessorPath("/assets/stage01/se01", "text")).toThrowError("AssertionError"); const se01 = manager.peekLiveAssetByAccessorPath("/assets/stage01/se01", "audio") as AudioAsset; expect(se01.type).toBe("audio"); expect(se01.path).toBe("assets/stage01/se01"); expect(se01.duration).toBe(10000); const boss = manager.peekLiveAssetByAccessorPath( "@akashic-extension/some-library/assets/boss.png", "image" ) as ImageAsset; expect(boss.type).toBe("image"); expect(boss.path).toBe("node_modules/@akashic-extension/some-library/assets/boss.png"); expect(boss.width).toBe(324); expect(boss.height).toBe(196); // "/" 始まりでないのはエラー expect(() => manager.peekLiveAssetByAccessorPath("assets/stage01/se01", "audio")).toThrowError("AssertionError"); done(); } ); }); function extractAssetProps(asset: Asset): { id: string; type: string; path: string } { return { id: asset.id, type: asset.type, path: asset.path }; } it("can peek live assets by a pattern", done => { const assetIds = [ "id-script/main.js", "id-assets/stage01/bgm01", "id-assets/stage01/se01", "id-assets/stage01/boss.png", "id-assets/stage01/map.json", "id-assets/chara01/image.png", "node_modules/@akashic-extension/some-library/assets/image.png", "node_modules/@akashic-extension/some-library/assets/boss.png" ]; setupAssetLoadedGame( assetIds, s => done.fail(s), ({ manager }) => { expect(manager.peekAllLiveAssetsByPattern("/script/main.js", "image")).toEqual([]); const result0 = manager.peekAllLiveAssetsByPattern("/script/main.js", "script"); expect(result0.length).toBe(1); expect(extractAssetProps(result0[0])).toEqual({ id: "id-script/main.js", type: "script", path: "script/main.js" }); const result1 = manager.peekAllLiveAssetsByPattern("/assets/stage01/*", null).map(extractAssetProps); expect(result1.length).toEqual(4); expect(result1[0]).toEqual({ id: "id-assets/stage01/bgm01", type: "audio", path: "assets/stage01/bgm01" }); expect(result1[1]).toEqual({ id: "id-assets/stage01/se01", type: "audio", path: "assets/stage01/se01" }); expect(result1[2]).toEqual({ id: "id-assets/stage01/boss.png", type: "image", path: "assets/stage01/boss.png" }); expect(result1[3]).toEqual({ id: "id-assets/stage01/map.json", type: "text", path: "assets/stage01/map.json" }); const result2 = manager.peekAllLiveAssetsByPattern("**/*", "audio").map(extractAssetProps); expect(result2.length).toEqual(2); expect(result2[0]).toEqual({ id: "id-assets/stage01/bgm01", type: "audio", path: "assets/stage01/bgm01" }); expect(result2[1]).toEqual({ id: "id-assets/stage01/se01", type: "audio", path: "assets/stage01/se01" }); const result3 = manager.peekAllLiveAssetsByPattern("/*/*/*.png", "image").map(extractAssetProps); expect(result3.length).toEqual(2); expect(result3[0]).toEqual({ id: "id-assets/stage01/boss.png", type: "image", path: "assets/stage01/boss.png" }); expect(result3[1]).toEqual({ id: "id-assets/chara01/image.png", type: "image", path: "assets/chara01/image.png" }); const result4 = manager .peekAllLiveAssetsByPattern("@akashic-extension/some-library/*/*.png", "image") .map(extractAssetProps); expect(result4).toEqual([ { id: "node_modules/@akashic-extension/some-library/assets/image.png", type: "image", path: "node_modules/@akashic-extension/some-library/assets/image.png" }, { id: "node_modules/@akashic-extension/some-library/assets/boss.png", type: "image", path: "node_modules/@akashic-extension/some-library/assets/boss.png" } ]); done(); } ); }); it("can peek live assets by a filter", done => { const assetIds = [ "id-script/main.js", "id-assets/stage01/bgm01", "id-assets/stage01/se01", "id-assets/stage01/boss.png", "id-assets/stage01/map.json", "id-assets/chara01/image.png", "node_modules/@akashic-extension/some-library/assets/image.png", "node_modules/@akashic-extension/some-library/assets/boss.png" ]; setupAssetLoadedGame( assetIds, s => done.fail(s), ({ manager }) => { expect(manager.peekAllLiveAssetsByPattern("/script/main.js", "image")).toEqual([]); const result0 = manager.peekAllLiveAssetsByPattern(s => s === "/script/main.js", "script"); expect(result0.length).toBe(1); expect(extractAssetProps(result0[0])).toEqual({ id: "id-script/main.js", type: "script", path: "script/main.js" }); const result1 = manager.peekAllLiveAssetsByPattern(s => /^\/assets\/stage01\/.*$/.test(s), null).map(extractAssetProps); expect(result1.length).toEqual(4); expect(result1[0]).toEqual({ id: "id-assets/stage01/bgm01", type: "audio", path: "assets/stage01/bgm01" }); expect(result1[1]).toEqual({ id: "id-assets/stage01/se01", type: "audio", path: "assets/stage01/se01" }); expect(result1[2]).toEqual({ id: "id-assets/stage01/boss.png", type: "image", path: "assets/stage01/boss.png" }); expect(result1[3]).toEqual({ id: "id-assets/stage01/map.json", type: "text", path: "assets/stage01/map.json" }); const result2 = manager.peekAllLiveAssetsByPattern(() => true, "audio").map(extractAssetProps); expect(result2.length).toEqual(2); expect(result2[0]).toEqual({ id: "id-assets/stage01/bgm01", type: "audio", path: "assets/stage01/bgm01" }); expect(result2[1]).toEqual({ id: "id-assets/stage01/se01", type: "audio", path: "assets/stage01/se01" }); const result3 = manager.peekAllLiveAssetsByPattern(s => /\.png$/.test(s), "image").map(extractAssetProps); expect(result3).toEqual([ { id: "id-assets/stage01/boss.png", type: "image", path: "assets/stage01/boss.png" }, { id: "id-assets/chara01/image.png", type: "image", path: "assets/chara01/image.png" }, { id: "node_modules/@akashic-extension/some-library/assets/image.png", type: "image", path: "node_modules/@akashic-extension/some-library/assets/image.png" }, { id: "node_modules/@akashic-extension/some-library/assets/boss.png", type: "image", path: "node_modules/@akashic-extension/some-library/assets/boss.png" } ]); done(); } ); }); }); });
the_stack
import * as React from "react" import { connect, ConnectedProps } from "react-redux" import { get } from "lodash" import { Link, RouteComponentProps } from "react-router-dom" import { Card, Spinner, Classes, Button, Icon, Tabs, Tab, Tooltip, Callout, Intent, } from "@blueprintjs/core" import Request, { ChildProps as RequestChildProps, RequestStatus, } from "./Request" import api from "../api" import { Run as RunShape, RunStatus, ExecutionEngine, RunTabId, ExecutableType, EnhancedRunStatusEmojiMap, EnhancedRunStatus, } from "../types" import ViewHeader from "./ViewHeader" import StopRunButton from "./StopRunButton" import { RUN_FETCH_INTERVAL_MS } from "../constants" import Toggler from "./Toggler" import LogRequesterCloudWatchLogs from "./LogRequesterCloudWatchLogs" import LogRequesterS3 from "./LogRequesterS3" import RunEvents from "./RunEvents" import QueryParams, { ChildProps as QPChildProps } from "./QueryParams" import { RUN_TAB_ID_QUERY_KEY } from "../constants" import Attribute from "./Attribute" import RunTag from "./RunTag" import Duration from "./Duration" import ErrorCallout from "./ErrorCallout" import RunSidebar from "./RunSidebar" import Helmet from "react-helmet" import AutoscrollSwitch from "./AutoscrollSwitch" import { RootState } from "../state/store" import CloudtrailRecords from "./CloudtrailRecords" import getEnhancedRunStatus from "../helpers/getEnhancedRunStatus" const connected = connect((state: RootState) => state.runView) export type Props = QPChildProps & RequestChildProps<RunShape, { runID: string }> & { runID: string } & ConnectedProps<typeof connected> export class Run extends React.Component<Props> { requestIntervalID: number | undefined constructor(props: Props) { super(props) this.request = this.request.bind(this) } componentDidMount() { const { data } = this.props // If data has been fetched and the run hasn't stopped, start polling. if (data && data.status !== RunStatus.STOPPED) this.setRequestInterval() } componentDidUpdate(prevProps: Props) { if ( prevProps.requestStatus === RequestStatus.NOT_READY && this.props.requestStatus === RequestStatus.READY && this.props.data && this.props.data.status !== RunStatus.STOPPED ) { // If the RequestStatus transitions from NOT_READY to READY and the run // isn't stopped, start polling. this.setRequestInterval() } if (this.props.data && this.props.data.status === RunStatus.STOPPED) { // If the Run transitions to a STOPPED state, stop polling. this.clearRequestInterval() } } componentWillUnmount() { window.clearInterval(this.requestIntervalID) } request() { const { isLoading, error, request, runID } = this.props if (isLoading === true || error !== null) return request({ runID }) } setRequestInterval() { this.requestIntervalID = window.setInterval( this.request, RUN_FETCH_INTERVAL_MS ) } clearRequestInterval() { window.clearInterval(this.requestIntervalID) } getActiveTabId(): RunTabId { const { data, query, hasLogs } = this.props const queryTabId: RunTabId | null = get(query, RUN_TAB_ID_QUERY_KEY, null) if (queryTabId === null) { if (hasLogs === true) { return RunTabId.LOGS } if ( data && data.engine === ExecutionEngine.EKS && data.status !== RunStatus.STOPPED ) { return RunTabId.EVENTS } return RunTabId.LOGS } return queryTabId } setActiveTabId(id: RunTabId): void { this.props.setQuery({ [RUN_TAB_ID_QUERY_KEY]: id }) } getExecutableLinkName(): string { const { data } = this.props if (data) { switch (data.executable_type) { case ExecutableType.ExecutableTypeDefinition: return data.alias case ExecutableType.ExecutableTypeTemplate: return data.executable_id } } return "" } getExecutableLinkURL(): string { const { data } = this.props if (data) { switch (data.executable_type) { case ExecutableType.ExecutableTypeDefinition: return `/tasks/${data.definition_id}` case ExecutableType.ExecutableTypeTemplate: return `/templates/${data.executable_id}` } } return "" } render() { const { data, requestStatus, runID, error } = this.props switch (requestStatus) { case RequestStatus.ERROR: return <ErrorCallout error={error} /> case RequestStatus.READY: if (data) { const cloudtrailRecords = get( data, ["cloudtrail_notifications", "Records"], null ) const hasCloudtrailRecords = cloudtrailRecords !== null let btn: React.ReactNode = null if (data.status === RunStatus.STOPPED) { btn = ( <Link className={Classes.BUTTON} to={{ pathname: `${this.getExecutableLinkURL()}/execute`, state: data, }} > <div className="bp3-button-text">Retry</div> <Icon icon="repeat" /> </Link> ) } else { btn = ( <StopRunButton runID={runID} definitionID={data.definition_id} /> ) } return ( <Toggler> {metadataVisibility => ( <> <ViewHeader leftButton={ <Button onClick={metadataVisibility.toggleVisibility} icon={ metadataVisibility.isVisible ? "menu-closed" : "menu-open" } style={{ marginRight: 12 }} > {metadataVisibility.isVisible ? "Hide" : "Show"} </Button> } breadcrumbs={[ { text: this.getExecutableLinkName(), href: this.getExecutableLinkURL(), }, { text: data.run_id, href: `/runs/${data.run_id}`, }, ]} buttons={btn} /> <div className="flotilla-sidebar-view-container"> {metadataVisibility.isVisible && <RunSidebar data={data} />} <div className="flotilla-sidebar-view-content"> <Card style={{ marginBottom: 12 }}> <div className="flotilla-attributes-container flotilla-attributes-container-horizontal"> <Attribute name="Status" value={<RunTag {...data} />} /> <Attribute name="Duration" value={ data.started_at && ( <Duration start={data.started_at} end={data.finished_at} isActive={data.status !== RunStatus.STOPPED} /> ) } /> <Attribute name="Exit Code" value={data.exit_code} /> <Attribute name="Exit Reason" value={data.exit_reason || "-"} /> <Attribute name="Autoscroll" value={<AutoscrollSwitch />} /> </div> </Card> <Tabs selectedTabId={this.getActiveTabId()} onChange={id => { this.setActiveTabId(id as RunTabId) }} > <Tab id={RunTabId.LOGS} title="Container Logs" panel={ data.engine === ExecutionEngine.EKS ? ( <LogRequesterS3 runID={data.run_id} status={data.status} /> ) : ( <LogRequesterCloudWatchLogs runID={data.run_id} status={data.status} /> ) } /> <Tab id={RunTabId.EVENTS} title={ data.engine !== ExecutionEngine.EKS ? ( <Tooltip content="Run events are only available for tasks run on EKS."> EKS Pod Events </Tooltip> ) : ( "EKS Pod Events" ) } panel={ <RunEvents runID={data.run_id} status={data.status} hasLogs={this.props.hasLogs} /> } disabled={data.engine !== ExecutionEngine.EKS} /> <Tab id={RunTabId.CLOUDTRAIL} title={ data.engine !== ExecutionEngine.EKS ? ( <Tooltip content="Cloudtrail records are only available for tasks run on EKS."> Cloudtrail Records </Tooltip> ) : ( `EKS Cloudtrail Records (${ hasCloudtrailRecords ? get( data, ["cloudtrail_notifications", "Records"], [] ).length : 0 })` ) } panel={ <CloudtrailRecords data={cloudtrailRecords || []} /> } disabled={ data.engine !== ExecutionEngine.EKS || hasCloudtrailRecords === false } /> </Tabs> </div> </div> </> )} </Toggler> ) } return <Callout title="Run not found" intent={Intent.WARNING} /> case RequestStatus.NOT_READY: default: return <Spinner /> } } } const ReduxConnectedRun = connected(Run) const Connected: React.FunctionComponent<RouteComponentProps<{ runID: string }>> = ({ match }) => ( <QueryParams> {({ query, setQuery }) => ( <Request<RunShape, { runID: string }> requestFn={api.getRun} initialRequestArgs={{ runID: match.params.runID }} > {props => ( <> <Helmet> <title> {`${ props.data ? EnhancedRunStatusEmojiMap.get( getEnhancedRunStatus(props.data) as EnhancedRunStatus ) : "" } ${match.params.runID}`} </title> </Helmet> <ReduxConnectedRun {...props} runID={match.params.runID} query={query} setQuery={setQuery} /> </> )} </Request> )} </QueryParams> ) export default Connected
the_stack
import * as querystring from 'querystring'; import * as assert from 'assert'; import * as path from 'path'; import { BrowserWindow, dialog, nativeImage, app, net } from 'electron'; import type { Menu } from 'electron'; import windowState = require('electron-window-state'); import { TweetAutoLinkBreaker, UNLINK_ALL_CONFIG } from 'break-tweet-autolink'; import log from './log'; import { ON_DARWIN, IS_DEBUG, PRELOAD_JS, ICON_PATH } from './constants'; import type Ipc from './ipc'; import { touchBar } from './menu'; import { openConfig } from './config'; // XXX: TENTATIVE: detect back button by aria label const INJECTED_CSS = 'a[href="/"] { display: none !important; }\n' + 'a[href="/home"] { display: none !important; }\n' + 'header[role="banner"] { display: none !important; }\n' + ['Back', '戻る'].map(aria => `[aria-label="${aria}"] { display: none !important; }`).join('\n'); export default class TweetWindow { public readonly screenName: string | undefined; public readonly wantToQuit: Promise<void>; public didClose: Promise<void>; public prevTweetId: string | null; private readonly partition: string | undefined; private win: BrowserWindow | null; private hashtags: string; private resolveWantToQuit: () => void; private actionAfterTweet: ConfigAfterTweet | undefined; private onlineStatus: OnlineStatus; public constructor( screenName: string | undefined, private readonly config: Config, private readonly ipc: Ipc, opts: CommandLineOptions, private readonly menu: Menu, ) { // Note: This is necessary for enabling strictPropertyInitialization this.hashtags = ''; this.updateOptions(opts); if (screenName !== undefined && screenName !== '') { this.screenName = screenName; if (this.screenName.startsWith('@')) { this.screenName = this.screenName.slice(1); } this.partition = `persist:tweet:${this.screenName}`; } this.win = null; this.prevTweetId = null; this.onPrevTweetIdReceived = this.onPrevTweetIdReceived.bind(this); this.onOnlineStatusChange = this.onOnlineStatusChange.bind(this); this.onResetWindow = this.onResetWindow.bind(this); this.resolveWantToQuit = (): void => {}; this.wantToQuit = new Promise<void>(resolve => { this.resolveWantToQuit = resolve; }); this.didClose = Promise.resolve(); this.onlineStatus = net.online ? 'online' : 'offline'; } public updateOptions(opts: CommandLineOptions): void { this.hashtags = (opts.hashtags ?? []).join(','); this.actionAfterTweet = opts.afterTweet ?? this.config.after_tweet; if (this.actionAfterTweet !== undefined) { this.actionAfterTweet = this.actionAfterTweet.toLowerCase() as ConfigAfterTweet; } } public openNewTweet(text?: string): Promise<void> { return this.open(false, text); } public openReply(text?: string): Promise<void> { return this.open(true, text); } public close(): Promise<void> { if (this.win !== null) { log.debug('Will close window'); this.win.close(); } else { log.debug('Window was already closed'); } return this.didClose; } public isOpen(): boolean { return this.win !== null; } public async openPreviousTweet(): Promise<void> { log.info('Open previous tweet', this.screenName, this.prevTweetId); if (this.screenName === undefined) { await this.requireConfigWithDialog('open previous tweet page'); return; } else if (this.prevTweetId === null) { await this.notifyReplyUnavailableUntilTweet('open previous tweet page'); return; } if (this.win === null) { await this.openNewTweet(); } else if (this.win.isMinimized()) { this.win.restore(); } assert.ok(this.win !== null); const url = `https://mobile.twitter.com/${this.screenName}/status/${this.prevTweetId}`; return new Promise<void>(resolve => { this.ipc.send('tweetapp:open', url); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.win!.webContents.once('dom-ready', () => { log.debug('Opened previous tweet:', url); resolve(); }); }); } public unlinkSelection(text: string): void { if (this.win === null) { log.debug('Window is not open. Cannot unlink selection'); return; } const breaker = new TweetAutoLinkBreaker(UNLINK_ALL_CONFIG); const unlinked = breaker.breakAutoLinks(text); log.debug('Text was unlinked:', text, '->', unlinked); if (text === unlinked) { log.debug('Nothing was unlinked. Skip replacing text'); return; } // This removes selected text and put the unlinked text instead this.win.webContents.insertText(unlinked); } public cancelTweet(): void { console.debug('Try to cancel tweet'); this.ipc.send('tweetapp:cancel-tweet'); } private notifyReplyUnavailableUntilTweet(doSomething: string): Promise<unknown> { return dialog.showMessageBox({ type: 'info', title: `Cannot ${doSomething}`, message: `To ${doSomething}, at least one tweet must be posted before`, detail: `Please choose "New Tweet" from menu and post a new tweet at first`, icon: nativeImage.createFromPath(ICON_PATH), buttons: ['OK'], }); } private async requireConfigWithDialog(doSomething: string): Promise<unknown> { const buttons = ['Edit Config', 'OK']; const result = await dialog.showMessageBox({ type: 'info', title: 'Config is required', message: `Configuration is required to ${doSomething}`, detail: "Please click 'Edit Config', enter your @screen_name at 'default_account' field, restart app", icon: nativeImage.createFromPath(ICON_PATH), buttons, }); const idx = result.response; const label = buttons[idx]; if (label === 'Edit Config') { await openConfig(); } return; } private composeNewTweetUrl(text?: string): string { const queries = []; if (text !== undefined && text !== '') { queries.push('text=' + querystring.escape(text)); } if (this.hashtags.length > 0) { queries.push('hashtags=' + querystring.escape(this.hashtags)); } let url = 'https://mobile.twitter.com/compose/tweet'; if (queries.length > 0) { url += '?' + queries.join('&'); } return url; } private composeReplyUrl(text?: string): string { let url = this.composeNewTweetUrl(text); if (this.prevTweetId === null) { log.warn( 'Fall back to new tweet form since previous tweet is not found. You need to tweet at least once before this item', ); return url; } if (url.includes('?')) { url += '&in_reply_to=' + this.prevTweetId; } else { url += '?in_reply_to=' + this.prevTweetId; } return url; } private composeTweetUrl(reply: boolean, text?: string): string { if (reply) { return this.composeReplyUrl(text); } else { return this.composeNewTweetUrl(text); } } private windowConfig<T extends number | boolean>(name: keyof WindowConfig, defaultVal: T): T { if (this.config.window === undefined) { return defaultVal; } if (this.config.window[name] === undefined) { return defaultVal; } return this.config.window[name] as T; } private async open(reply: boolean, text?: string, force?: boolean): Promise<void> { const forceReopen = force ?? false; if (reply) { if (this.screenName === undefined) { await this.requireConfigWithDialog('reply to previous tweet'); } else if (this.prevTweetId === null) { await this.notifyReplyUnavailableUntilTweet('reply to previous tweet'); } } if (this.win !== null) { if (this.win.isMinimized()) { this.win.restore(); } this.win.focus(); const url = this.composeTweetUrl(reply, text); if (!forceReopen && this.win.webContents.getURL() === url) { log.info('Skip reopening content since URL is the same:', url); return Promise.resolve(); } log.info('Window is already open. Will reopen content:', url); return new Promise<void>(resolve => { this.ipc.send('tweetapp:open', url); assert.ok(this.win); this.win.webContents.once('dom-ready', () => { log.debug('Reopened content:', url); resolve(); }); }); } return new Promise<void>(resolve => { log.debug('Start application'); const width = this.windowConfig('width', 600); const height = this.windowConfig('height', 600); const zoomFactor = this.windowConfig('zoom', 1.0); const autoHideMenuBar = this.windowConfig('auto_hide_menu_bar', true); const state = windowState({}); const winOpts: Electron.BrowserWindowConstructorOptions = { width, height, resizable: false, x: state.x, y: state.y, icon: ICON_PATH, show: false, title: 'Tweet', titleBarStyle: 'hiddenInset' as const, frame: !ON_DARWIN, fullscreenable: false, useContentSize: true, autoHideMenuBar, webPreferences: { allowRunningInsecureContent: false, experimentalFeatures: false, contextIsolation: true, nodeIntegration: false, nodeIntegrationInWorker: false, partition: this.partition, preload: PRELOAD_JS, sandbox: true, webSecurity: true, webviewTag: false, zoomFactor, spellcheck: true, }, }; log.debug('Create BrowserWindow with options:', winOpts); const win = new BrowserWindow(winOpts); state.manage(win); if (!ON_DARWIN) { win.setMenu(this.menu); } this.ipc.attach(win.webContents); win.once('ready-to-show', () => { log.debug('Event: ready-to-show'); win.show(); }); win.once('close', _ => { log.debug('Event: close'); assert.ok(this.win !== null); /* eslint-disable @typescript-eslint/no-non-null-assertion */ this.ipc.detach(this.win!.webContents); this.ipc.forget('tweetapp:prev-tweet-id', this.onPrevTweetIdReceived); this.ipc.forget('tweetapp:online-status', this.onOnlineStatusChange); this.ipc.forget('tweetapp:reset-window', this.onResetWindow); this.win!.webContents.removeAllListeners(); this.win!.webContents.session.setPermissionRequestHandler(null); this.win!.webContents.session.webRequest.onBeforeRequest(null); this.win!.webContents.session.webRequest.onCompleted(null); /* eslint-enable @typescript-eslint/no-non-null-assertion */ }); win.on('page-title-updated', e => { e.preventDefault(); }); this.didClose = new Promise<void>(resolve => { win.once('closed', (_: Event) => { log.debug('Event: closed'); assert.ok(this.win !== null); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.win!.removeAllListeners(); this.win = null; if (ON_DARWIN) { app.hide(); } resolve(); }); }); win.webContents.on('will-navigate', (e, url) => { log.info('Event: will-navigate:', url); // Do not allow to go outside Twitter site if (url.startsWith('https://mobile.twitter.com/')) { return; } e.preventDefault(); log.warn('Blocked navigation:', url); }); // Note: This event was deprecated in favor of `contents.setWindowOpenHandler()` win.webContents.on('new-window', (e, url) => { log.info('Event: new-window:', url); e.preventDefault(); log.warn('Blocked gew window creation:', url); }); win.webContents.setWindowOpenHandler(details => { log.warn('Blocked new window creation:', details.url, ', opener:', details.frameName); return { action: 'deny' }; }); win.webContents.on('did-finish-load', () => { log.debug('Event: did-finish-load'); let css = INJECTED_CSS; if (ON_DARWIN) { // Allow to move window by dragging any part of the window. Exception is a tweet // form since it prevents text selection css += '\nbody {-webkit-app-region: drag;}\n.DraftEditor-root {-webkit-app-region: no-drag;}'; } if (this.screenName !== undefined) { css += `\na[href="/${this.screenName}"] { display: none !important; }`; } win.webContents.insertCSS(css); }); win.webContents.on('dom-ready', () => { log.debug('Event: dom-ready'); if (this.screenName !== undefined) { this.ipc.send('tweetapp:screen-name', this.screenName); } this.ipc.send('tweetapp:action-after-tweet', this.actionAfterTweet); }); win.webContents.once('dom-ready', () => { if (IS_DEBUG) { win.webContents.openDevTools({ mode: 'detach' }); } resolve(); }); win.webContents.session.webRequest.onCompleted( { urls: [ 'https://mobile.twitter.com/i/api/graphql/*/CreateTweet', 'https://mobile.twitter.com/i/api/1.1/statuses/destroy.json', ], }, details => { if (details.statusCode !== 200 || details.fromCache) { return; } if (details.url.endsWith('/destroy.json')) { const url = this.composeTweetUrl(false); log.info('Destroyed tweet:', details.url, 'Next URL:', url); this.prevTweetId = null; // Clear previous tweet ID since it would no longer exist this.ipc.send('tweetapp:open', url); return; } switch (this.actionAfterTweet) { case 'close': log.info("Will close window since action after tweet is 'close'"); this.close(); break; case 'quit': log.info("Will quit since action after tweet is 'quit'"); this.resolveWantToQuit(); break; default: { const url = this.composeTweetUrl(false); log.info('Posted tweet:', details.url, 'Next URL:', url); this.ipc.send('tweetapp:sent-tweet', url); break; } } }, ); // TODO?: May be blocked for better performance? // - 'https://api.twitter.com/2/notifications/all.json?*', // - 'https://api.twitter.com/2/timeline/home.json?*', // - 'https://api.twitter.com/1.1/client_event.json', win.webContents.session.webRequest.onBeforeRequest( { urls: [ 'https://www.google-analytics.com/r/*', 'https://mobile.twitter.com/i/api/graphql/*/CreateTweet', ], }, (details: any, callback) => { if (details.url.endsWith('/CreateTweet')) { log.debug('/i/api/graphql/*/CreateTweet', details.uploadData?.[0]?.bytes?.toString()); // Tweet was posted. It means that user has already logged in. win.webContents.session.webRequest.onBeforeRequest(null); // Unsubscribe this hook } else if (details.referrer === 'https://mobile.twitter.com/login') { // XXX: TENTATIVE: detect login from google-analitics requests log.debug('Login detected from URL', details.url); this.ipc.send('tweetapp:login'); // Remove listener anymore win.webContents.session.webRequest.onBeforeRequest(null); // Unsubscribe this hook } callback({}); }, ); // NOTE: Uncomment this block when analyzing issues about hooking web requests. Be careful that previous // hooks will be removed when below hooks are set. // // win.webContents.session.webRequest.onCompleted({ urls: ['*://*/*'] }, details => { // console.log('WEBREQUEST.ON_COMPLETED:', details); // }); // win.webContents.session.webRequest.onBeforeRequest({ urls: ['*://*/*'] }, (details, callback) => { // console.log('WEBREQUEST.ON_BEFORE_REQUEST:', details); // callback({}); // }); win.webContents.session.setPermissionRequestHandler((webContents, perm, callback, details) => { const url = webContents.getURL(); if (!url.startsWith('https://mobile.twitter.com/')) { log.info('Blocked permission request', perm, 'from', url, 'Details:', details); callback(false); return; } const allowed = ['media', 'geolocation']; if (!allowed.includes(perm)) { log.info( 'Blocked not allowed permission', perm, 'from url', url, 'Allowed permissions are:', allowed, 'Details:', details, ); callback(false); return; } dialog .showMessageBox({ type: 'info', title: 'Permission was requested', message: `Permission '${perm}' was requested from ${url}`, detail: "Please click 'Accept' to allow the request or 'Reject' to reject it", icon: nativeImage.createFromPath(ICON_PATH), buttons: ['Accept', 'Reject'], }) .then(result => { const idx = result.response; callback(idx === 0); }); }); this.ipc.on('tweetapp:prev-tweet-id', this.onPrevTweetIdReceived); this.ipc.on('tweetapp:online-status', this.onOnlineStatusChange); this.ipc.on('tweetapp:reset-window', this.onResetWindow); if (this.onlineStatus === 'online') { const url = this.composeTweetUrl(reply, text); log.info('Opening', url); win.loadURL(url); } else { const url = `file://${path.join(__dirname, 'offline.html')}`; win.loadURL(url); log.debug('Opening offline page:', url); } if (ON_DARWIN) { win.setTouchBar( touchBar(this.screenName, { tweet: this.open.bind(this, false), reply: this.open.bind(this, true), openPrevTweet: this.openPreviousTweet.bind(this), cancelTweet: this.cancelTweet.bind(this), }), ); log.debug('Touch bar was set'); } if (this.windowConfig('visible_on_all_workspaces', false)) { win.setVisibleOnAllWorkspaces(true); } log.info('Created window for', this.screenName); this.win = win; }); } private onPrevTweetIdReceived(_: Event, id: string): void { log.info('Previous tweet:', id); this.prevTweetId = id; } private onOnlineStatusChange(_: Event, status: OnlineStatus): void { log.info('Online status changed:', status, 'Previous status:', this.onlineStatus); if (this.onlineStatus === status) { log.debug('Do nothing for online status change'); return; } this.onlineStatus = status; if (this.win === null) { log.info('Do nothing on online status change since no window is shown'); return; } if (status === 'online') { const url = this.composeTweetUrl(false); log.info('Reopen window since network is now online:', url); this.win.loadURL(url); return; } // When offline const html = `file://${path.join(__dirname, 'offline.html')}`; this.win.loadURL(html); log.debug('Open offline page:', html); } private async onResetWindow(_: Event): Promise<void> { log.info('Reopen tweet window to reset'); try { await this.open(false, undefined, true); } catch (err) { // XXX: This error is handled internally and a user of this class cannot handle it log.error('Could not open tweet window due to error:', err); } } }
the_stack
const { ccclass, property } = cc._decorator; import { CacheArray, Resetable } from "./CacheArray"; import { CatmullRomSpline, Knot, Marker, SplineParameterization } from "./CatmullRomSpline" import { SplineTrailRendererAssembler } from "./SplineTrailAssembler"; export class ResetableVec2 extends cc.Vec2 implements Resetable { public Reset() { this.x = this.y = 0; } } export enum CornerType { // Mesh在拐角处连续 / 断开。目前只有原点效果是用后者,原点效果用连续的话,原点会被拉伸 Continuous = 0, Fragmented = 1, } export enum FadeType { None = 0, // 不渐变 MeshShrinking, // 尾巴变细 Alpha, // 尾巴变透明 Both, // 变细+变透明 } export enum PositionType { World = 0, // 使用世界坐标 Local = 1, // 使用本地坐标,跟随cc.Node移动 } @ccclass export class SplineTrailRenderer extends cc.RenderComponent { @property({ type: cc.Enum(PositionType) }) _positionType: PositionType = PositionType.World; @property({ type: cc.Enum(PositionType), displayName: '坐标类型', tooltip: 'World: 世界坐标,如果需要整体移动轨迹则需要移动摄像机; Local: 本地坐标,轨迹整体跟随节点移动' }) set positionType(value: PositionType) { this._positionType = value; this.FlushMatProperties(); } get positionType(): PositionType { return this._positionType; } @property({ type: cc.Enum(CornerType), displayName: '折角类型', tooltip: '连续模式下更平滑但是局部可能出现形变; 分段模式下各分段独立绘制,适用于非连续特效' }) cornerType: CornerType = CornerType.Continuous; @property({ type: cc.Enum(SplineParameterization) }) _splineParam: SplineParameterization = SplineParameterization.Centripetal; @property({ type: cc.Enum(SplineParameterization), displayName: '参数化方式', tooltip: '主要区别是曲线折角处理,Centripetal相对来说更加自然,计算量大一点' }) set splineParam(value: SplineParameterization) { this._splineParam = value; if (!CC_EDITOR) { this.spline.splineParam = value; } } get splineParam(): SplineParameterization { return this._splineParam; } @property({ type: cc.Float, displayName: '最大长度(px)', tooltip: '超出该长度后尾部会被自动裁剪' }) maxLength: number = 500; @property({ type: cc.Float, displayName: '精度(px)', tooltip: '每个Quad表示的线段长度,值越小曲线越平滑' }) segmentLength = 30; @property({ type: cc.Float, displayName: '曲线宽度(px)', tooltip: '折角处的宽度会略窄,夹角越小宽度越窄' }) segmentWidth = 40; // 非常关键的属性,决定了头部的平滑程度 // 取值越高头部越平滑,但是越有可能出现偏移(重算Mesh导致) @property({ type: cc.Float, displayName: '头部平滑距离(px)', tooltip: '取值越高头部越平滑,但是头部可能出现位移。默认取值: 精度*2' }) smoothDistance = 60; @property({ displayName: '自动生成轨迹', tooltip: '物体移动时自动调用AddPoint()生成轨迹' }) selfEmit = false; @property({ type: cc.Float, displayName: '显示时间(s)', tooltip: '展示X秒后自动消失。<=0表示不消失' }) showDuration: number = -1; // 每次重绘的头部线段数。 // 如果重绘距离越长,头部越平滑,但是会看到明显的Mesh侧移 // 如果重绘距离很短,折角会比较明显,同时跨Mesh的效果会出现拉伸(uv不平均) // 目测取值=3的情况下,折角Mesh效果较好,头部侧移可以通过宽度渐变来掩盖 public nbSegmentToParametrize = 3; //0 means all segments public fadeType: FadeType = FadeType.None; public fadeLengthBegin: number = 5; public fadeLengthEnd = 5; // public debugDrawSpline = false; public spline: CatmullRomSpline; // Mesh数据,CC里需要设置进MeshData _vertices = new CacheArray<ResetableVec2>(); _sideDist: number[] = []; // a_width attribute _dist: number[] = []; // a_dist attribute // uv: cc.Vec2[] = []; // _colors: cc.Color[] = []; protected _lastStartingQuad: number; // 小于这个值的Quad不计算Mesh,配合maxLength使用 protected _quadOffset: number; // _quadOffset只在重分配buff的时候有用 onLoad() { this.spline = new CatmullRomSpline; //@ts-ignore let gfx = cc.gfx; let vfmtSplineTrail = new gfx.VertexFormat([ { name: 'a_position', type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: 'a_width', type: gfx.ATTR_TYPE_FLOAT32, num: 1 }, // 旁侧相对于中心线的距离,范围(0, segmentWidth) { name: 'a_dist', type: gfx.ATTR_TYPE_FLOAT32, num: 1 }, // 距离线段起始点的距离(累积线段长度) { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, // 4个uint8 ]); vfmtSplineTrail.name = 'vfmtSplineTrail'; this.FlushMatProperties(); // update spline properties this.spline.splineParam = this._splineParam; } start() { if (this.selfEmit) this.StartPath(this.FromLocalPos(cc.Vec2.ZERO)); } update() { if (this.selfEmit && !CC_EDITOR) { let pos = this.FromLocalPos(cc.Vec2.ZERO); this.AddPoint(pos); } } public FromWorldPos(worldPos: cc.Vec2): cc.Vec2 { if (this._positionType === PositionType.World) { return worldPos; } return this.node.convertToNodeSpaceAR(worldPos); } public FromLocalPos(localPos: cc.Vec2): cc.Vec2 { if (this._positionType === PositionType.World) { return this.node.convertToWorldSpaceAR(localPos); } return localPos; } protected FlushMatProperties(): void { let renderer = this; let ass = renderer._assembler as SplineTrailRendererAssembler; let useWolrdPos: boolean = (this._positionType === PositionType.World); ass.useWorldPos = useWolrdPos; let mat = renderer.getMaterial(0); if (mat.getDefine("USE_WORLD_POS") !== undefined) { mat.define("USE_WORLD_POS", useWolrdPos); } } public StartPath(point: cc.Vec2): void { this._lastStartingQuad = 0; this._quadOffset = 0; this._vertices.Reset(); // this.uv.length = 0; // this._colors.length = 0; this.spline.Clear(); let emitTime = cc.director.getTotalTime(); this._fixedPointIndex = 0; let knots = this.spline.knots; knots.push(new Knot(point, emitTime)); } public Clear(): void { this.StartPath(this.node.convertToWorldSpaceAR(cc.Vec2.ZERO)); } // 更换材质和属性 public ImitateTrail(trail: SplineTrailRenderer) { // this.emit = trail.emit; this.smoothDistance = trail.smoothDistance; this.segmentWidth = trail.segmentWidth; this.segmentLength = trail.segmentLength; // this.vertexColor = trail.vertexColor; // this.normal = trail.normal; this.cornerType = trail.cornerType; this.fadeType = trail.fadeType; this.fadeLengthBegin = trail.fadeLengthBegin; this.fadeLengthEnd = trail.fadeLengthEnd; this.maxLength = trail.maxLength; this.splineParam = trail.splineParam; // this.debugDrawSpline = trail.debugDrawSpline; // this.GetComponent<Renderer>().material = trail.GetComponent<Renderer>().material; } // 最后一个定点的下标。新的点需要和该定点做距离比较来判断是否变为新的定点 protected _fixedPointIndex: number = 0; protected _distTolerance: number = 4; public AddPoint(point: cc.Vec2) { // console.warn(`x: ${point.x}, y: ${point.y}`); let knots = this.spline.knots; if (knots.length === 0) { knots.push(new Knot(point)); this._fixedPointIndex = 0; return; } else if (knots.length === 1) { // check distance to 1st point let dist = cc.Vec2.distance(knots[0].position, point); if (dist <= this._distTolerance) { // 前几个点可以密一点,不要求和smoothDistance比较 return; } // 反向计算P0,向后计算P3 let P0 = knots[0].position.mul(2).sub(point); let P3 = point.mul(2).sub(knots[0].position); knots.splice(0, 0, new Knot(P0)); knots.push(new Knot(point)); knots.push(new Knot(P3)); if (dist > this.smoothDistance) { this._fixedPointIndex = 2; } else { this._fixedPointIndex = 1; } // should now render } else { // let point = this.node.position; // 初始5个点,最后2个点总是变化,但是有可能点又被抛弃? // 如果最后2个点参与渲染,那么头部就会发生偏移 // 尝试替换P2 // 如果和P1距离太近则直接抛弃 let fixedPointIndex = this._fixedPointIndex; let P0 = knots[fixedPointIndex-1].position; let P1 = knots[fixedPointIndex].position; let dist = cc.Vec2.distance(P1, point); if (dist <= this._distTolerance) { return; } // 替换P2 let P2 = knots[fixedPointIndex+1].position; P2.set(point); // P1->P2延伸重算P3 if (knots.length <= fixedPointIndex+2) knots.push(new Knot(cc.v2(0, 0))); let P3 = knots[fixedPointIndex+2].position; P3.set(P2.mul(2).sub(P1)); if (cc.Vec2.distance(P1, P2) > this.smoothDistance && cc.Vec2.distance(P0, P2) > this.smoothDistance) { // 新的P2足够远,固化P2 ++ this._fixedPointIndex; } } // todo: 如果没有新增节点,考虑不要进行重算。时间相关的消失通过shader控制 // 4个控制点,最后一个点是占位用的,和P3相等 this.RenderMesh(); } protected _tmpVec2 = new cc.Vec2; protected _halfWidthVec2 = new cc.Vec2; protected _prePosition = new cc.Vec2; protected _preTangent = new cc.Vec2; protected _preBinormal = new cc.Vec2; protected _curPosition = new cc.Vec2; protected _curTangent = new cc.Vec2; protected _curBinormal = new cc.Vec2; public RenderMesh() { let spline = this.spline; if (spline.knots.length < 4) return; let segmentLength = this.segmentLength; let segmentWidth = this.segmentWidth; if (this.nbSegmentToParametrize === 0) { spline.Parametrize(0, spline.NbSegments-1); } else { // 倒数第3个线段开始重新计算,主要内容是细分线段(subsegment),计算每个细分线段的距离 spline.Parametrize(spline.NbSegments-this.nbSegmentToParametrize, spline.NbSegments); } let length = Math.max(spline.Length() - 0.1, 0); // TODO: 此处0.1是干嘛的?0.1刚好是Epsilon // _quadOffset只在重分配buff的时候有用 // nbQuad表示渲染当前长度的线段需要的总quad数(包含已过期的quad) let nbQuad = Math.floor(1./segmentLength * length) + 1 - this._quadOffset; let startingQuad = this._lastStartingQuad; let lastDistance = startingQuad * segmentLength + this._quadOffset * segmentLength; // 不需要绘制的线段已经经过的距离。每个quad表示的距离大小固定,都是segmentLength=0.2 let marker: Marker = new Marker; // marker是一个游标,从需要计算的quad + subsegment开始往后移动 spline.PlaceMarker(marker, lastDistance); let prePosition = spline.GetPosition(marker, this._prePosition); let preTangent = spline.GetTangent(marker, this._preTangent); let preBinormal = CatmullRomSpline.ComputeBinormal(preTangent, null/*dummy*/, this._preBinormal); // Vector3 lastPosition = spline.GetPosition(marker); // Vector3 lastTangent = spline.GetTangent(marker); // Vector3 lastBinormal = CatmullRomSpline.ComputeBinormal(lastTangent, normal); // let drawingEnd = (this.meshDisposition === MeshDisposition.Fragmented) ? nbQuad-1 : nbQuad-1; let drawingEnd = nbQuad-1; // int drawingEnd = meshDisposition == MeshDisposition.Fragmented ? nbQuad-1 : nbQuad-1; let vertexPerQuad = 4; this._vertices.Resize((drawingEnd - startingQuad) * vertexPerQuad, ResetableVec2); this._sideDist.length = this._vertices.length; this._dist.length = this._vertices.length; // this._colors.length = this._vertices.length; for (let i=startingQuad; i<drawingEnd; i++) { let distance = lastDistance + segmentLength; let firstVertexIndex = (i-startingQuad) * vertexPerQuad; spline.MoveMarker(marker, distance); let position = spline.GetPosition(marker, this._curPosition); let tangent = spline.GetTangent(marker, this._curTangent); // Mesh在xz平面,此时normal = (0, -1, 0) // 此时binormal在xz平面上,往Quad的侧面走 let binormal = CatmullRomSpline.ComputeBinormal(tangent, null/*dummy*/, this._curBinormal); // Vector3 binormal = CatmullRomSpline.ComputeBinormal(tangent, normal); let h = this.FadeMultiplier(lastDistance, length); // be 1.0 for simple let h2 = this.FadeMultiplier(distance, length); // be 1.0 for simple let rh = h * segmentWidth, rh2 = h2 * segmentWidth; // be segmentWidth for simple // float h = FadeMultiplier(lastDistance, length); // be 1.0 for simple // float h2 = FadeMultiplier(distance, length); // be 1.0 for simple // float rh = h * segmentWidth, rh2 = h2 * segmentWidth; // be segmentWidth for simple if (this.fadeType === FadeType.Alpha || this.fadeType === FadeType.None) { rh = h > 0 ? segmentWidth : 0; rh2 = h2 > 0 ? segmentWidth : 0; } // if(fadeType == FadeType.Alpha || fadeType == FadeType.None) // { // rh = h > 0 ? segmentWidth : 0; // rh2 = h2 > 0 ? segmentWidth : 0; // } // 核心代码!!! if (this.cornerType == CornerType.Continuous) { let tmpVec2 = this._tmpVec2; // quad是一个四边形,每个途经点沿自己的两侧延伸 let halfWidth = preBinormal.mul(rh * 0.5, this._halfWidthVec2); this._vertices.Get(firstVertexIndex).set(prePosition.add(halfWidth, tmpVec2)); this._vertices.Get(firstVertexIndex + 1).set(prePosition.add(halfWidth.neg(tmpVec2), tmpVec2)); halfWidth = binormal.mul(rh2 * 0.5, halfWidth); this._vertices.Get(firstVertexIndex + 2).set(position.add(halfWidth, tmpVec2)); this._vertices.Get(firstVertexIndex + 3).set(position.add(halfWidth.neg(tmpVec2), tmpVec2)); // 注释部分是以上代码的易读版本 // this._vertices[firstVertexIndex] = lastPosition.add(lastBinormal.mul(rh * 0.5)); // this._vertices[firstVertexIndex + 1] = lastPosition.add(lastBinormal.mul(-rh * 0.5)); // this._vertices[firstVertexIndex + 2] = position.add(binormal.mul(rh2 * 0.5)); // this._vertices[firstVertexIndex + 3] = position.add(binormal.mul(-rh2 * 0.5)); this._sideDist[firstVertexIndex] = 0; this._sideDist[firstVertexIndex + 1] = segmentWidth; this._sideDist[firstVertexIndex + 2] = 0; this._sideDist[firstVertexIndex + 3] = segmentWidth; this._dist[firstVertexIndex] = lastDistance; this._dist[firstVertexIndex + 1] = lastDistance; this._dist[firstVertexIndex + 2] = distance; this._dist[firstVertexIndex + 3] = distance; // this.uv[firstVertexIndex] = new Vector2(lastDistance/segmentWidth, 1); // this.uv[firstVertexIndex + 1] = new Vector2(lastDistance/segmentWidth, 0); // this.uv[firstVertexIndex + 2] = new Vector2(distance/segmentWidth, 1); // this.uv[firstVertexIndex + 3] = new Vector2(distance/segmentWidth, 0); } else { // quad是一个长方形,保持上一个点的切向伸展 // 以起点为中心两头延伸,这样segment衔接的时候更加自然 // todo: use preposition instead let tmpVec2 = this._tmpVec2; prePosition.addSelf(preTangent.mul(segmentLength * -0.5, tmpVec2)); // 注意此处值已经覆盖,后面不要用 let halfWidth = preBinormal.mul(rh * 0.5, this._halfWidthVec2); this._vertices.Get(firstVertexIndex).set(prePosition.add(halfWidth, tmpVec2)); this._vertices.Get(firstVertexIndex + 1).set(prePosition.add(halfWidth.neg(tmpVec2), tmpVec2)); // prePosition向后移动一个segment prePosition.addSelf(preTangent.mul(segmentLength, tmpVec2)); this._vertices.Get(firstVertexIndex + 2).set(prePosition.add(halfWidth, tmpVec2)); this._vertices.Get(firstVertexIndex + 3).set(prePosition.add(halfWidth.neg(tmpVec2), tmpVec2)); // 注释部分是以上代码的易读版本 // this._vertices[firstVertexIndex] = pos.add(lastBinormal.mul(rh * 0.5)); // this._vertices[firstVertexIndex + 1] = pos.add(lastBinormal.mul(-rh * 0.5)); // this._vertices[firstVertexIndex + 2] = pos.add(preTangent.mul(segmentLength)).add(lastBinormal.mul(rh * 0.5)); // this._vertices[firstVertexIndex + 3] = pos.add(preTangent.mul(segmentLength)).add(lastBinormal.mul(-rh * 0.5)); this._sideDist[firstVertexIndex] = 0; this._sideDist[firstVertexIndex + 1] = segmentWidth; this._sideDist[firstVertexIndex + 2] = 0; this._sideDist[firstVertexIndex + 3] = segmentWidth; this._dist[firstVertexIndex] = lastDistance; this._dist[firstVertexIndex + 1] = lastDistance; this._dist[firstVertexIndex + 2] = distance; this._dist[firstVertexIndex + 3] = distance; // this.uv[firstVertexIndex] = cc.v2(0, 1); // this.uv[firstVertexIndex + 1] = cc.v2(0, 0); // this.uv[firstVertexIndex + 2] = cc.v2(1, 1); // this.uv[firstVertexIndex + 3] = cc.v2(1, 0); } // let color = this.node.color; // this._colors[firstVertexIndex] = color; // this._colors[firstVertexIndex + 1] = color; // this._colors[firstVertexIndex + 2] = color; // this._colors[firstVertexIndex + 3] = color; // if (this.fadeType == FadeType.Alpha || this.fadeType == FadeType.Both) { // this._colors[firstVertexIndex].a *= h; // this._colors[firstVertexIndex + 1].a *= h; // this._colors[firstVertexIndex + 2].a *= h2; // this._colors[firstVertexIndex + 3].a *= h2; // } prePosition.set(position); preTangent.set(tangent); preBinormal.set(binormal); lastDistance = distance; } // 根据maxLength计算下次刷新计算的第一个quad,如果总长度很长了,下次计算会出现一些截断 this._lastStartingQuad = Math.max(0, nbQuad - (Math.floor(this.maxLength / segmentLength) + 5)); // update mesh parameter let renderer = this; let mat = renderer.getMaterial(0); if (mat.getProperty("size", 0) !== undefined) { mat.setProperty("size", [segmentLength, segmentWidth, 1/segmentLength, 1/segmentWidth]); } // mark for dirty // force assembler to refresh this.setVertsDirty(); } protected FadeMultiplier(distance: number, length: number): number { // todo: use multiplier in shader return 1.0; // float ha = Mathf.Clamp01((distance - Mathf.Max(length-maxLength, 0)) / fadeLengthBegin); // float hb = Mathf.Clamp01((length-distance) / fadeLengthEnd); // return Mathf.Min(ha, hb); } }
the_stack
import * as React from 'react' import { useDispatch } from 'react-redux' import cx from 'classnames' import { Icon, InputField, OutlineButton, Tooltip, useConditionalConfirm, useHoverTooltip, TOOLTIP_TOP, TOOLTIP_TOP_END, } from '@opentrons/components' import { i18n } from '../../../localization' import * as steplistActions from '../../../steplist/actions' import { PROFILE_CYCLE, ProfileStepItem, ProfileItem, ProfileCycleItem, } from '../../../form-types' import { getProfileFieldErrors, maskProfileField, } from '../../../steplist/fieldLevel' import { ConfirmDeleteModal, DELETE_PROFILE_CYCLE, } from '../../modals/ConfirmDeleteModal' import { getDynamicFieldFocusHandlerId } from '../utils' import styles from '../StepEditForm.css' import { FocusHandlers } from '../types' export const showProfileFieldErrors = ({ fieldId, focusedField, dirtyFields, }: { fieldId: string focusedField?: string | null dirtyFields: string[] }): boolean => !(fieldId === focusedField) && dirtyFields && dirtyFields.includes(fieldId) interface ProfileCycleRowProps { cycleItem: ProfileCycleItem focusHandlers: FocusHandlers stepOffset: number } export const ProfileCycleRow = (props: ProfileCycleRowProps): JSX.Element => { const { cycleItem, focusHandlers, stepOffset } = props const dispatch = useDispatch() const addStepToCycle = (): void => { dispatch(steplistActions.addProfileStep({ cycleId: cycleItem.id })) } // TODO IMMEDIATELY make conditional const deleteProfileCycle = (): steplistActions.DeleteProfileCycleAction => dispatch(steplistActions.deleteProfileCycle({ id: cycleItem.id })) const [ addStepToCycleTargetProps, addStepToCycleTooltipProps, ] = useHoverTooltip({ placement: TOOLTIP_TOP_END, }) const { confirm: confirmDeleteCycle, showConfirmation: showConfirmDeleteCycle, cancel: cancelConfirmDeleteCycle, } = useConditionalConfirm(deleteProfileCycle, true) const [deleteCycleTargetProps, deleteCycleTooltipProps] = useHoverTooltip({ placement: TOOLTIP_TOP, }) return ( <> {showConfirmDeleteCycle && ( <ConfirmDeleteModal modalType={DELETE_PROFILE_CYCLE} onContinueClick={confirmDeleteCycle} onCancelClick={cancelConfirmDeleteCycle} /> )} <div className={styles.profile_cycle_wrapper}> <div className={styles.profile_cycle_group}> {cycleItem.steps.length > 0 && ( <div className={styles.cycle_steps}> <div className={styles.cycle_row}> {cycleItem.steps.map((stepItem, index) => { return ( <ProfileStepRow profileStepItem={stepItem} focusHandlers={focusHandlers} key={stepItem.id} stepNumber={stepOffset + index} isCycle /> ) })} </div> <ProfileField name="repetitions" focusHandlers={focusHandlers} profileItem={cycleItem} units={i18n.t('application.units.cycles')} className={cx(styles.small_field, styles.cycles_field)} updateValue={(name, value) => dispatch( steplistActions.editProfileCycle({ id: cycleItem.id, fields: { [name]: value }, }) ) } /> </div> )} <Tooltip {...addStepToCycleTooltipProps}> {i18n.t('tooltip.profile.add_step_to_cycle')} </Tooltip> <div className={styles.add_cycle_step} {...addStepToCycleTargetProps}> <OutlineButton onClick={addStepToCycle}>+ Step</OutlineButton> </div> </div> <div onClick={confirmDeleteCycle} {...deleteCycleTargetProps}> <Tooltip {...deleteCycleTooltipProps}> {i18n.t('tooltip.profile.delete_cycle')} </Tooltip> <Icon name="close" className={styles.delete_step_icon} /> </div> </div> </> ) } export interface ProfileItemRowsProps { focusHandlers: FocusHandlers orderedProfileItems: string[] profileItemsById: { [key: string]: ProfileItem } } export const ProfileItemRows = (props: ProfileItemRowsProps): JSX.Element => { const { orderedProfileItems, profileItemsById } = props const dispatch = useDispatch() const addProfileCycle = (): void => { dispatch(steplistActions.addProfileCycle(null)) } const addProfileStep = (): void => { dispatch(steplistActions.addProfileStep(null)) } const [addCycleTargetProps, addCycleTooltipProps] = useHoverTooltip({ placement: TOOLTIP_TOP, }) const [addStepTargetProps, addStepTooltipProps] = useHoverTooltip({ placement: TOOLTIP_TOP, }) let counter = 0 const rows = orderedProfileItems.map((itemId, index) => { const itemFields: ProfileItem = profileItemsById[itemId] if (itemFields.type === PROFILE_CYCLE) { const cycleRow = ( <ProfileCycleRow cycleItem={itemFields} focusHandlers={props.focusHandlers} key={itemId} stepOffset={counter + 1} /> ) counter += itemFields.steps.length return cycleRow } counter++ return ( <ProfileStepRow profileStepItem={itemFields} focusHandlers={props.focusHandlers} key={itemId} stepNumber={counter} /> ) }) return ( <> {rows.length > 0 && ( <div className={styles.profile_step_labels}> <div>Name:</div> <div>Temperature:</div> <div>Time:</div> </div> )} {rows} <Tooltip {...addStepTooltipProps}> {i18n.t('tooltip.profile.add_step')} </Tooltip> <Tooltip {...addCycleTooltipProps}> {i18n.t('tooltip.profile.add_cycle')} </Tooltip> <div className={styles.profile_button_group}> <OutlineButton hoverTooltipHandlers={addStepTargetProps} onClick={addProfileStep} > {i18n.t( 'form.step_edit_form.field.thermocyclerProfile.add_step_button' )} </OutlineButton> <OutlineButton hoverTooltipHandlers={addCycleTargetProps} onClick={addProfileCycle} > {i18n.t( 'form.step_edit_form.field.thermocyclerProfile.add_cycle_button' )} </OutlineButton> </div> </> ) } interface ProfileFieldProps { name: string focusHandlers: FocusHandlers profileItem: ProfileItem units?: React.ReactNode className?: string updateValue: (name: string, value: unknown) => unknown } const ProfileField = (props: ProfileFieldProps): JSX.Element => { const { focusHandlers, name, profileItem, units, className, updateValue, } = props const value = profileItem[name as keyof ProfileItem] // this is not very safe but I don't know how else to tell TS that name should be keyof ProfileItem without being a discriminated union const fieldId = getDynamicFieldFocusHandlerId({ id: profileItem.id, name, }) const onChange = (e: React.ChangeEvent<HTMLInputElement>): void => { const value = e.currentTarget.value const maskedValue = maskProfileField(name, value) updateValue(name, maskedValue) } const showErrors = showProfileFieldErrors({ fieldId, focusedField: focusHandlers.focusedField, dirtyFields: focusHandlers.dirtyFields, }) const errors = getProfileFieldErrors(name, value) const errorToShow = showErrors && errors.length > 0 ? errors.join(', ') : null const onBlur = (): void => { focusHandlers.blur(fieldId) } const onFocus = (): void => { focusHandlers.focus(fieldId) } return ( <div className={styles.step_input_wrapper}> <InputField className={cx(styles.step_input, className)} error={errorToShow} units={units} {...{ name, onChange, onBlur, onFocus, value }} /> </div> ) } interface ProfileStepRowProps { focusHandlers: FocusHandlers profileStepItem: ProfileStepItem stepNumber: number isCycle?: boolean | null } const ProfileStepRow = (props: ProfileStepRowProps): JSX.Element => { const { focusHandlers, profileStepItem, isCycle } = props const dispatch = useDispatch() const updateStepFieldValue = (name: string, value: unknown): void => { dispatch( steplistActions.editProfileStep({ id: profileStepItem.id, fields: { [name]: value }, }) ) } const deleteProfileStep = (): void => { dispatch(steplistActions.deleteProfileStep({ id: profileStepItem.id })) } const names = [ 'title', 'temperature', 'durationMinutes', 'durationSeconds', ] as const const units: Record<typeof names[number], string | null> = { title: null, temperature: i18n.t('application.units.degrees'), durationMinutes: i18n.t('application.units.minutes'), durationSeconds: i18n.t('application.units.seconds'), } const [targetProps, tooltipProps] = useHoverTooltip({ placement: TOOLTIP_TOP, }) const fields = names.map(name => { const className = name === 'title' ? styles.title : styles.profile_field return ( <ProfileField key={name} units={units[name]} className={className} {...{ name, focusHandlers, profileItem: profileStepItem, updateValue: updateStepFieldValue, }} /> ) }) return ( <div className={cx(styles.profile_step_row, { [styles.cycle]: isCycle })}> <div className={cx(styles.profile_step_fields, { [styles.profile_cycle_fields]: isCycle, })} > <span className={styles.profile_step_number}>{props.stepNumber}. </span> {fields} </div> <div onClick={deleteProfileStep} className={cx({ [styles.cycle_step_delete]: isCycle })} {...targetProps} > <Tooltip {...tooltipProps}> {i18n.t('tooltip.profile.delete_step')} </Tooltip> <Icon name="close" className={styles.delete_step_icon} /> </div> </div> ) }
the_stack
import { appendStmt, ArgExpr, removeStmt, replaceStmt, stmtExists, } from "analysis/SubstanceAnalysis"; import { prettyStmt, prettySubNode } from "compiler/Substance"; import { dummyIdentifier } from "engine/EngineUtils"; import { ApplyPredicate, Bind, SubExpr, SubProg, SubStmt, } from "types/substance"; import { addID, removeID, SynthesisContext, WithContext } from "./Synthesizer"; //#region Mutation types export type MutationGroup = Mutation[]; export type Mutation = Add | Delete | Update; export type MutationType = Mutation["tag"]; export interface IMutation { tag: MutationType; additionalMutations?: Mutation[]; mutate: ( op: this, prog: SubProg, ctx: SynthesisContext ) => WithContext<SubProg>; } export type Update = | SwapExprArgs | SwapStmtArgs | ReplaceStmtName | ReplaceExprName | ChangeStmtType | ChangeExprType; export interface Add extends IMutation { tag: "Add"; stmt: SubStmt; } export interface Delete extends IMutation { tag: "Delete"; stmt: SubStmt; } export interface SwapStmtArgs extends IMutation { tag: "SwapStmtArgs"; stmt: ApplyPredicate; elem1: number; elem2: number; } export interface SwapExprArgs extends IMutation { tag: "SwapExprArgs"; stmt: Bind; expr: ArgExpr; elem1: number; elem2: number; } export interface ReplaceStmtName extends IMutation { tag: "ReplaceStmtName"; stmt: ApplyPredicate; newName: string; } export interface ReplaceExprName extends IMutation { tag: "ReplaceExprName"; stmt: Bind; expr: ArgExpr; newName: string; } export interface ChangeStmtType extends IMutation { tag: "ChangeStmtType"; stmt: ApplyPredicate; newStmt: SubStmt; additionalMutations: Mutation[]; } export interface ChangeExprType extends IMutation { tag: "ChangeExprType"; stmt: Bind; expr: ArgExpr; newStmt: SubStmt; additionalMutations: Mutation[]; } export const showMutations = (ops: Mutation[]): string => { return ops.map((op) => showMutation(op)).join("\n"); }; export const showMutation = (op: Mutation): string => { switch (op.tag) { case "SwapStmtArgs": return `Swap arguments of ${prettyStmt(op.stmt)}`; case "SwapExprArgs": return `Swap arguments of ${prettySubNode(op.expr)} in ${prettyStmt( op.stmt )}`; case "ChangeStmtType": case "ChangeExprType": return `Change ${prettyStmt(op.stmt)} to ${prettyStmt(op.newStmt)}`; case "ReplaceExprName": case "ReplaceStmtName": return `Replace the name of ${prettyStmt(op.stmt)} with ${op.newName}`; case "Add": case "Delete": return `${op.tag} ${prettySubNode(op.stmt)}`; } }; //#endregion //#region Mutation execution export const executeMutation = ( mutation: Mutation, prog: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => mutation.mutate(mutation as any, prog, ctx); // TODO: typecheck this? export const executeMutations = ( mutations: Mutation[], prog: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => mutations.reduce( ({ res, ctx }: WithContext<SubProg>, m: Mutation) => m.mutate(m as any, res, ctx), { res: prog, ctx } ); const swap = (arr: any[], a: number, b: number) => arr.map((current, idx) => { if (idx === a) return arr[b]; if (idx === b) return arr[a]; return current; }); //#endregion //#region Mutation constructors export const deleteMutation = (stmt: SubStmt): Delete => ({ tag: "Delete", stmt, mutate: removeStmtCtx, }); export const addMutation = (stmt: SubStmt): Add => ({ tag: "Add", stmt, mutate: appendStmtCtx, }); //#endregion //#region Context-sensitive AST operations const withCtx = <T>(res: T, ctx: SynthesisContext): WithContext<T> => ({ res, ctx, }); export const appendStmtCtx = ( { stmt }: Add, p: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => { if (stmt.tag === "Decl") { const newCtx = addID(ctx, stmt.type.name.value, stmt.name); return withCtx(appendStmt(p, stmt), newCtx); } else { return withCtx(appendStmt(p, stmt), ctx); } }; export const removeStmtCtx = ( { stmt }: Delete, prog: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => { if (stmt.tag === "Decl") { const newCtx = removeID(ctx, stmt.type.name.value, stmt.name); return withCtx(removeStmt(prog, stmt), newCtx); } else { return withCtx(removeStmt(prog, stmt), ctx); } }; //#endregion //#region Mutation guard functions export const checkAddStmts = ( prog: SubProg, cxt: SynthesisContext, newStmts: (cxt: SynthesisContext) => SubStmt[] ): Add[] | undefined => { const stmts: SubStmt[] = newStmts(cxt); return stmts.map((stmt: SubStmt) => addMutation(stmt)); }; export const checkAddStmt = ( prog: SubProg, cxt: SynthesisContext, newStmt: (cxt: SynthesisContext) => SubStmt ): Add | undefined => { const stmt: SubStmt = newStmt(cxt); return addMutation(stmt); }; export const checkSwapStmtArgs = ( stmt: SubStmt, elems: (p: ApplyPredicate) => [number, number] ): SwapStmtArgs | undefined => { if (stmt.tag === "ApplyPredicate") { if (stmt.args.length < 2) return undefined; const [elem1, elem2] = elems(stmt); return { tag: "SwapStmtArgs", stmt, elem1, elem2, mutate: ( { stmt, elem1, elem2 }: SwapStmtArgs, prog: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => { const newStmt: SubStmt = { ...stmt, args: swap(stmt.args, elem1, elem2), }; return withCtx(replaceStmt(prog, stmt, newStmt), ctx); }, }; } else return undefined; }; export const checkSwapExprArgs = ( stmt: SubStmt, elems: (p: ArgExpr) => [number, number] ): SwapExprArgs | undefined => { if (stmt.tag === "Bind") { const { expr } = stmt; if ( expr.tag === "ApplyConstructor" || expr.tag === "ApplyFunction" || expr.tag === "Func" ) { if (expr.args.length < 2) return undefined; const [elem1, elem2] = elems(expr); return { tag: "SwapExprArgs", stmt, expr, elem1, elem2, mutate: ( { stmt, expr, elem1, elem2 }: SwapExprArgs, prog: SubProg, ctx: SynthesisContext ): WithContext<SubProg> => { const newStmt: SubStmt = { ...stmt, expr: { ...expr, args: swap(expr.args, elem1, elem2), } as SubExpr, // TODO: fix types to avoid casting }; return withCtx(replaceStmt(prog, stmt, newStmt), ctx); }, }; } else return undefined; } else return undefined; }; export const checkReplaceStmtName = ( stmt: SubStmt, newName: (p: ApplyPredicate) => string | undefined ): ReplaceStmtName | undefined => { if (stmt.tag === "ApplyPredicate") { const name = newName(stmt); if (name) { return { tag: "ReplaceStmtName", stmt, newName: name, mutate: ({ stmt, newName }: ReplaceStmtName, prog, ctx) => { return withCtx( replaceStmt(prog, stmt, { ...stmt, name: dummyIdentifier(newName, "SyntheticSubstance"), }), ctx ); }, }; } else return undefined; } else return undefined; }; export const checkReplaceExprName = ( stmt: SubStmt, newName: (p: ArgExpr) => string | undefined ): ReplaceExprName | undefined => { if (stmt.tag === "Bind") { const { expr } = stmt; if ( expr.tag === "ApplyConstructor" || expr.tag === "ApplyFunction" || expr.tag === "Func" ) { const name = newName(expr); if (name) { return { tag: "ReplaceExprName", stmt, expr, newName: name, mutate: ({ stmt, expr, newName }: ReplaceExprName, prog, ctx) => { return withCtx( replaceStmt(prog, stmt, { ...stmt, expr: { ...expr, name: dummyIdentifier(newName, "SyntheticSubstance"), }, }), ctx ); }, }; } else return undefined; } else return undefined; } else return undefined; }; export const checkDeleteStmt = ( prog: SubProg, stmt: SubStmt ): Delete | undefined => { const s = stmt; if (stmtExists(s, prog)) { return deleteMutation(s); } else return undefined; }; const changeType = ( { stmt, newStmt, additionalMutations }: ChangeStmtType | ChangeExprType, prog: SubProg, ctx: SynthesisContext ) => { const { res: newProg, ctx: newCtx } = executeMutations( additionalMutations, prog, ctx ); return withCtx(appendStmt(newProg, newStmt), newCtx); }; export const checkChangeStmtType = ( stmt: SubStmt, cxt: SynthesisContext, getMutations: ( s: ApplyPredicate, cxt: SynthesisContext ) => { newStmt: SubStmt; additionalMutations: Mutation[] } | undefined ): ChangeStmtType | undefined => { if (stmt.tag === "ApplyPredicate") { const res = getMutations(stmt, cxt); if (res) { const { newStmt, additionalMutations } = res; return { tag: "ChangeStmtType", stmt, newStmt, additionalMutations, mutate: changeType, }; } else return undefined; } else undefined; }; export const checkChangeExprType = ( stmt: SubStmt, cxt: SynthesisContext, getMutations: ( oldStmt: Bind, oldExpr: ArgExpr, cxt: SynthesisContext ) => { newStmt: SubStmt; additionalMutations: Mutation[] } | undefined ): ChangeExprType | undefined => { if (stmt.tag === "Bind") { const { expr } = stmt; if ( expr.tag === "ApplyConstructor" || expr.tag === "ApplyFunction" || expr.tag === "Func" ) { const res = getMutations(stmt, expr, cxt); if (res) { const { newStmt, additionalMutations } = res; return { tag: "ChangeExprType", stmt, expr, newStmt, additionalMutations, mutate: changeType, }; } else return undefined; } else return undefined; } else return undefined; }; //#endregion
the_stack
import { MonitoringDB } from "@src/constants"; import { Dashboard, UnitEnum } from "@src/models"; export const RemoteReplicationDashboard: Dashboard = { rows: [ { panels: [ { chart: { title: "Replica Lag", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'replica_lag' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 24, }, ], }, { panels: [ { chart: { title: "Number Of Replica", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'replicas' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Replica Traffic", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'replica_bytes' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Bytes, }, span: 12, }, ], }, { panels: [ { chart: { title: "Active Replicators", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'active_replicators' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Consumer Message", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'consume_msg' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Consumer Message Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'consume_msg_failures' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Replica Painc", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'replica_panics' from 'lindb.storage.replicator.runner' where type='remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Send Message", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'send_msg' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Send Message Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'send_msg_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Receive Message", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'receive_msg' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Receive Message Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'receive_msg_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Ack Replica Sequence", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'ack_sequence' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Invalid Ack Sequence", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'invalid_ack_sequence' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Not Ready", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'not_ready' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Remote Follower Offline", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'follower_offline' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Need Close Last Replica Stream", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'need_close_last_stream' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Close Last Stream Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'close_last_stream_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Create Replica Client", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'create_replica_cli' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Create Reaplica Client Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'create_replica_cli_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Create Replica Stream", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'create_replica_stream' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Create Replica Stream Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'create_replica_stream_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Get Last Ack Sequence Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'get_last_ack_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Reset Remote Follower Append Index", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'reset_follower_append_idx' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Reset Remote Follower Append Index Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'reset_follower_append_idx_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Reset Append Index", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'reset_append_idx' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, { panels: [ { chart: { title: "Reset Replica Index", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'reset_replica_idx' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, { chart: { title: "Reset Replica Index Failure", config: { type: "line" }, targets: [ { db: MonitoringDB, sql: "select 'reset_replica_failures' from 'lindb.storage.replica.remote' group by db,node", watch: ["node", "db"], }, ], unit: UnitEnum.Short, }, span: 12, }, ], }, ], };
the_stack
import { BaseTableProps, collectNodes, features, isLeafNode, makeRecursiveMapper, TablePipeline, } from 'ali-react-table'; import cx from 'classnames'; import React from 'react'; import styled from 'styled-components'; import { omit } from '../../utils'; import { Pagination, PaginationProps } from '../pagination'; import { Toolbar, ToolbarProps } from '../toolbar'; import { BaseTable, Column, REX_TABLE_PIPELINE_CTX } from './base-table'; import { ColumnFilterDrawer } from './column-filter-drawer'; import { columnCollapse, ColumnCollapseFeatureOptions } from './feature-columnCollapse'; import { parseColumns } from './parseColumns'; import * as tableUtils from './table-utils'; const ProTableWrapperDiv = styled.div` > .rex-toolbar { margin-bottom: 8px; } > .rex-table-footer { margin-top: 8px; } `; const featDict = { sort: tableUtils.sortCompatibleWithDataIndex, singleSelect: features.singleSelect, multiSelect: features.multiSelect, treeMode: features.treeMode, treeSelect: features.treeSelect, rowGrouping: features.rowGrouping, columnRangeHover: features.columnRangeHover, columnHover: features.columnHover, rowDetail: features.rowDetail, tips: features.tips, columnResize: features.columnResize, autoRowSpan: features.autoRowSpan, columnCollapse: columnCollapse, }; const featureNames = Object.keys(featDict) as (keyof typeof featDict)[]; export interface ProTableFeatureProps { sort?: boolean | tableUtils.SortCompatibleWithDataIndexFeatureOptions; singleSelect?: boolean | features.SingleSelectFeatureOptions; multiSelect?: boolean | features.MultiSelectFeatureOptions; treeMode?: boolean | features.TreeModeFeatureOptions; treeSelect?: boolean | features.TreeSelectFeatureOptions; rowGrouping?: boolean | features.RowGroupingFeatureOptions; columnRangeHover?: boolean; columnHover?: boolean; rowDetail?: boolean | features.RowDetailFeatureOptions; tips?: boolean; columnResize?: boolean | features.ColumnResizeFeatureOptions; autoRowSpan?: boolean; columnCollapse?: boolean | ColumnCollapseFeatureOptions; columnFilter?: ColumnFilterOptions; } const BEFORE_COLUMN_FILTER = 'BEFORE_COLUMN_FILTER'; /** * 获取 pipeline 实例上的 cache,用于缓存一些中间计算结果 * pro table 会使用 cache 来存放 visibleCodes 的计算结果 */ function getPipelineCache(_pipeline: TablePipeline) { const pipeline: any = _pipeline; if (pipeline._cache == null) { pipeline._cache = {}; } return pipeline._cache; } // columnFilter 包含额外的 UI,且实现过程中涉及大量内部渲染逻辑,所以我们在这里单独定义 ColumnFilterOptions interface ColumnFilterOptions { /** * 受控用法,当前可见的列; * 设置 column.features.enforceVisible=true 时,对应的列总是可见; * 不设置 visibleCodes 时为非受控用法,所有列均默认可见,可以通过 column.features.defaultVisible=false 配置默认不可见 * */ visibleCodes?: string[]; /** 受控用法,visibleCodes 发生变化的回调 */ onChange?(nextVisibleCodes: string[]): void; /** 为 columnFilter 提供自定义的列配置 */ columns?: Column[]; /** 设置自定义列抽屉标题 */ drawerTitle?: React.ReactNode; /** 设置自定义列抽屉宽度,默认 500px */ drawerWidth?: number; /** 是否显示「全选」按钮 */ showCheckAll?: boolean; /** 是否显示「清空」按钮 */ showUncheckAll?: boolean; /** 设置为 true 后,columnFilter 将不对表格产生影响(表格会根据 props.columns 来决定渲染哪些列) */ keepTableColumns?: boolean; // 自定义列 drawer 是否打开目前只支持非受控用法,后续有需求再进行拓展 } export interface ProTableProps extends BaseTableProps, ProTableFeatureProps { pagination?: PaginationProps & { keepDataSource?: boolean }; toolbar?: ToolbarProps & { totalCount?: number | 'auto' | '-' }; footer?: ToolbarProps; // 表格外层 div wrapperProps?: React.HTMLAttributes<HTMLDivElement>; wrapperStyle?: React.CSSProperties; wrapperClassName?: string; } interface ProTableState { columnFilterState: { drawerVisible: boolean; visibleCodes: null | string[]; }; pipelineState: object; pagination: { pageSize: number; current: number; }; } /** 开箱即用的 ReX Design 表格组件 */ export class ProTable extends React.Component<ProTableProps, ProTableState> { static Column = (props: Omit<Column, 'children'>) => { /** <ProTable.Column /> */ return null as React.ReactElement; }; static ColumnGroup = (props: Omit<Column, 'children'> & { children?: React.ReactNode }) => { /** <ProTable.ColumnGroup /> */ return null as React.ReactElement; }; static parseColumns = parseColumns; static features = { ...features, ...featDict, }; constructor(props: ProTableProps) { super(props); this.state = { columnFilterState: { drawerVisible: false, // 这里 visibleCodes 是特意设置为 null 的 // 在渲染时,若 columnFilterState.visibleCodes 为 null,则所有列均默认可见 visibleCodes: null, }, pipelineState: {}, pagination: { current: props.pagination?.defaultCurrent ?? 1, pageSize: props.pagination?.pageSize ?? 10, }, }; } _setPipelineState = (updater: React.ReducerWithoutAction<object>) => { this.setState((prev) => ({ pipelineState: updater(prev.pipelineState), })); }; _setupFeatures(pipeline: TablePipeline) { const props = this.props; // 多个表格拓展的应用顺序是固定的 for (const featName of featureNames) { let opts: any = props[featName]; if (opts == null || opts === false) { continue; } if (opts === true) { opts = {}; } const feature = featDict[featName]; pipeline.use(feature(opts)); } } _onPaginationChange = (current: number) => { this.props.pagination.onChange?.(current); this.setState((prev) => ({ pagination: { ...prev.pagination, current }, })); }; _onPaginationPageSizeChange = (pageSize: number) => { this.props.pagination.onPageSizeChange?.(pageSize); this.setState((prev) => ({ pagination: { ...prev.pagination, pageSize }, })); }; _setColumnFilterDrawerVisibility = (visible: boolean) => { this.setState((prev) => ({ columnFilterState: { ...prev.columnFilterState, drawerVisible: visible, }, })); }; _setColumnFilterVisibleCodes = (nextVisibleCodes: string[]) => { this.setState((prev) => ({ columnFilterState: { ...prev.columnFilterState, visibleCodes: nextVisibleCodes, }, })); }; _renderToolbar(pipeline: TablePipeline) { const { toolbar, columnFilter } = this.props; if (toolbar == null && columnFilter == null) { return null; } let renderedColumnFilter = null; const { columnFilterState } = this.state; // eslint-disable-next-line prefer-const let { tipNode, totalCount, rightActions = [], ...others } = toolbar ?? {}; if (tipNode == null) { if (typeof totalCount === 'string' || typeof totalCount === 'number') { tipNode = `共 ${totalCount} 条数据`; } } if (columnFilter != null) { rightActions.push({ key: 'columnFilter', label: '自定义列', icon: 'setting', onSelect: () => this._setColumnFilterDrawerVisibility(true), }); const columnsBeforeFilter = pipeline.getColumns(BEFORE_COLUMN_FILTER); const leafColumnsBeforeFilter = collectNodes(columnsBeforeFilter, 'leaf-only'); const enforceVisibleCodes = leafColumnsBeforeFilter .filter((col) => col.features?.enforceVisible) .map((col) => col.code); const { visibleCodes } = getPipelineCache(pipeline); renderedColumnFilter = ( <ColumnFilterDrawer // drawer 配置 title={columnFilter.drawerTitle} width={columnFilter.drawerWidth} visible={columnFilterState.drawerVisible} onRequestClose={() => this._setColumnFilterDrawerVisibility(false)} // 其他配置 columns={columnFilter.columns ?? columnsBeforeFilter} showCheckAll={columnFilter.showCheckAll} showUncheckAll={columnFilter.showUncheckAll} enforceCheckedCodes={enforceVisibleCodes} checkedCodes={visibleCodes} onChange={(nextVisibleCodes) => { columnFilter.onChange?.(nextVisibleCodes); this._setColumnFilterVisibleCodes(nextVisibleCodes); }} /> ); } return ( <> <Toolbar tipNode={tipNode} rightActions={rightActions} {...others} /> {renderedColumnFilter} </> ); } _renderFooter() { const { dataSource, pagination, footer } = this.props; if (footer || pagination) { return ( <Toolbar {...footer} className={cx('rex-table-footer', footer?.className)} rightNode={ footer?.rightNode ?? (pagination ? ( <Pagination total={dataSource.length} {...omit(pagination, ['keepDataSource'])} onChange={this._onPaginationChange} onPageSizeChange={this._onPaginationPageSizeChange} /> ) : null) } /> ); } return null; } render() { const { // 基本 props style, className, primaryKey, dataSource, columns, getRowProps, // UI 拓展(表格工具栏 & 翻页器) wrapperProps, wrapperClassName, wrapperStyle, toolbar, pagination, columnFilter, ...others } = this.props; const { columnFilterState } = this.state; const pipeline = new TablePipeline({ state: this.state.pipelineState, setState: this._setPipelineState, ctx: REX_TABLE_PIPELINE_CTX, }); pipeline.input({ dataSource, columns }); if (primaryKey != null) { pipeline.primaryKey(primaryKey); } // 兼容 dataIndex pipeline.mapColumns(tableUtils.compatWithDataIndex); pipeline.mapColumns(tableUtils.compatWithColumnCell); if (columnFilter != null) { pipeline.snapshot(BEFORE_COLUMN_FILTER); const columnsBeforeFilter = pipeline.getColumns(BEFORE_COLUMN_FILTER); const leafColumnsBeforeFilter = collectNodes(columnsBeforeFilter, 'leaf-only'); const visibleCodes = columnFilter.visibleCodes ?? columnFilterState.visibleCodes ?? leafColumnsBeforeFilter.filter((col) => col.features?.defaultVisible !== false).map((col) => col.code); getPipelineCache(pipeline).visibleCodes = visibleCodes; if (!columnFilter.keepTableColumns) { const visibleCodeSet = new Set(visibleCodes); pipeline.mapColumns( makeRecursiveMapper((col) => { if (!isLeafNode(col)) { return col; } const enforceChecked = col.features?.enforceVisible; const checked = visibleCodeSet.has(col.code); return checked || enforceChecked ? col : []; }), ); } } if (pagination && !pagination.keepDataSource) { const pageSize = pagination.pageSize ?? this.state.pagination.pageSize; const current = pagination.current ?? this.state.pagination.current; pipeline.mapDataSource((rows) => rows.slice((current - 1) * pageSize, current * pageSize)); } this._setupFeatures(pipeline); if (getRowProps) { pipeline.appendRowPropsGetter(getRowProps); } return ( <ProTableWrapperDiv {...wrapperProps} className={cx('rex-table-wrapper', wrapperClassName)} style={wrapperStyle}> {this._renderToolbar(pipeline)} <BaseTable {...omit(others, featureNames)} style={style} className={cx(className, 'rex-table')} {...pipeline.getProps()} /> {this._renderFooter()} </ProTableWrapperDiv> ); } }
the_stack
import { java } from 'j4ts/j4ts'; import { Token } from './Token'; import { SimpleCharStream } from './SimpleCharStream'; import { SyntaxCheckerTokenManager } from './SyntaxCheckerTokenManager'; import { ParseException } from './ParseException'; import { SyntaxCheckerConstants } from './SyntaxCheckerConstants'; /** * Constructor with InputStream and supplied encoding * @param {InputStream} stream * @param {string} encoding * @class */ export class SyntaxChecker implements SyntaxCheckerConstants { static __static_initialized: boolean = false; static __static_initialize() { if (!SyntaxChecker.__static_initialized) { SyntaxChecker.__static_initialized = true; SyntaxChecker.__static_initializer_0(); } } public checkSyntax() { this.start(); } public start() { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 46 /* LEFT_PAR */: case 48 /* PLUS */: case 49 /* MINUS */: case 60 /* UNIT */: case 68 /* NOT */: case 69 /* BITNOT */: case 82 /* DECIMAL */: case 83 /* BASE1 */: case 84 /* BASE2 */: case 85 /* BASE3 */: case 86 /* BASE4 */: case 87 /* BASE5 */: case 88 /* BASE6 */: case 89 /* BASE7 */: case 90 /* BASE8 */: case 91 /* BASE9 */: case 92 /* BASE10 */: case 93 /* BASE11 */: case 94 /* BASE12 */: case 95 /* BASE13 */: case 96 /* BASE14 */: case 97 /* BASE15 */: case 98 /* BASE16 */: case 99 /* BASE17 */: case 100 /* BASE18 */: case 101 /* BASE19 */: case 102 /* BASE20 */: case 103 /* BASE21 */: case 104 /* BASE22 */: case 105 /* BASE23 */: case 106 /* BASE24 */: case 107 /* BASE25 */: case 108 /* BASE26 */: case 109 /* BASE27 */: case 110 /* BASE28 */: case 111 /* BASE29 */: case 112 /* BASE30 */: case 113 /* BASE31 */: case 114 /* BASE32 */: case 115 /* BASE33 */: case 116 /* BASE34 */: case 117 /* BASE35 */: case 118 /* BASE36 */: case 119 /* BINARY */: case 120 /* OCTAL */: case 121 /* HEXADECIMAL */: case 122 /* FRACTION */: case 123 /* IDENTIFIER */: case 124 /* FUNCTION */: case 125: { this.expression(); this.jj_consume_token(0); break; }; case 0: { this.jj_consume_token(0); break; }; default: this.jj_la1[0] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } } public expression() { this.binaryExpression(); } public binaryExpression() { this.unaryRigthExpression(); label_1: while((true)) {{ switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 48 /* PLUS */: case 49 /* MINUS */: case 50 /* MULTIPLY */: case 51 /* DIV */: case 52 /* POWER */: case 53 /* TETRATION */: case 54 /* MODULO */: case 59 /* EQ */: case 61 /* NEQ */: case 62 /* LT */: case 63 /* LEQ */: case 64 /* GT */: case 65 /* GEQ */: case 66 /* OR */: case 67 /* AND */: case 70 /* IMP */: case 71 /* CIMP */: case 72 /* NIMP */: case 73 /* CNIMP */: case 74 /* NAND */: case 75 /* EQV */: case 76 /* NOR */: case 77 /* BITWISE */: case 78 /* XOR */: { break; }; default: this.jj_la1[1] = this.jj_gen; break label_1; } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 48 /* PLUS */: { this.jj_consume_token(SyntaxCheckerConstants.PLUS); this.unaryRigthExpression(); break; }; case 49 /* MINUS */: { this.jj_consume_token(SyntaxCheckerConstants.MINUS); this.unaryRigthExpression(); break; }; case 50 /* MULTIPLY */: { this.jj_consume_token(SyntaxCheckerConstants.MULTIPLY); this.unaryRigthExpression(); break; }; case 51 /* DIV */: { this.jj_consume_token(SyntaxCheckerConstants.DIV); this.unaryRigthExpression(); break; }; case 54 /* MODULO */: { this.jj_consume_token(SyntaxCheckerConstants.MODULO); this.unaryRigthExpression(); break; }; case 52 /* POWER */: { this.jj_consume_token(SyntaxCheckerConstants.POWER); this.unaryRigthExpression(); break; }; case 53 /* TETRATION */: { this.jj_consume_token(SyntaxCheckerConstants.TETRATION); this.unaryRigthExpression(); break; }; case 59 /* EQ */: { this.jj_consume_token(SyntaxCheckerConstants.EQ); this.unaryRigthExpression(); break; }; case 61 /* NEQ */: { this.jj_consume_token(SyntaxCheckerConstants.NEQ); this.unaryRigthExpression(); break; }; case 64 /* GT */: { this.jj_consume_token(SyntaxCheckerConstants.GT); this.unaryRigthExpression(); break; }; case 65 /* GEQ */: { this.jj_consume_token(SyntaxCheckerConstants.GEQ); this.unaryRigthExpression(); break; }; case 62 /* LT */: { this.jj_consume_token(SyntaxCheckerConstants.LT); this.unaryRigthExpression(); break; }; case 63 /* LEQ */: { this.jj_consume_token(SyntaxCheckerConstants.LEQ); this.unaryRigthExpression(); break; }; case 66 /* OR */: { this.jj_consume_token(SyntaxCheckerConstants.OR); this.unaryRigthExpression(); break; }; case 67 /* AND */: { this.jj_consume_token(SyntaxCheckerConstants.AND); this.unaryRigthExpression(); break; }; case 76 /* NOR */: { this.jj_consume_token(SyntaxCheckerConstants.NOR); this.unaryRigthExpression(); break; }; case 74 /* NAND */: { this.jj_consume_token(SyntaxCheckerConstants.NAND); this.unaryRigthExpression(); break; }; case 78 /* XOR */: { this.jj_consume_token(SyntaxCheckerConstants.XOR); this.unaryRigthExpression(); break; }; case 70 /* IMP */: { this.jj_consume_token(SyntaxCheckerConstants.IMP); this.unaryRigthExpression(); break; }; case 71 /* CIMP */: { this.jj_consume_token(SyntaxCheckerConstants.CIMP); this.unaryRigthExpression(); break; }; case 72 /* NIMP */: { this.jj_consume_token(SyntaxCheckerConstants.NIMP); this.unaryRigthExpression(); break; }; case 73 /* CNIMP */: { this.jj_consume_token(SyntaxCheckerConstants.CNIMP); this.unaryRigthExpression(); break; }; case 75 /* EQV */: { this.jj_consume_token(SyntaxCheckerConstants.EQV); this.unaryRigthExpression(); break; }; case 77 /* BITWISE */: { this.jj_consume_token(SyntaxCheckerConstants.BITWISE); this.unaryRigthExpression(); break; }; default: this.jj_la1[2] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } }}; } public unaryRigthExpression() { this.unaryLeftExpression(); switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 55 /* FACTORIAL */: case 56 /* PERCENTAGE */: { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 55 /* FACTORIAL */: { this.jj_consume_token(SyntaxCheckerConstants.FACTORIAL); break; }; case 56 /* PERCENTAGE */: { this.jj_consume_token(SyntaxCheckerConstants.PERCENTAGE); break; }; default: this.jj_la1[3] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } break; }; default: this.jj_la1[4] = this.jj_gen; ; } } public unaryLeftExpression() { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 68 /* NOT */: case 69 /* BITNOT */: { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 68 /* NOT */: { this.jj_consume_token(SyntaxCheckerConstants.NOT); break; }; case 69 /* BITNOT */: { this.jj_consume_token(SyntaxCheckerConstants.BITNOT); break; }; default: this.jj_la1[5] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } break; }; default: this.jj_la1[6] = this.jj_gen; ; } this.itemExpression(); } public itemExpression() { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 48 /* PLUS */: case 49 /* MINUS */: { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 48 /* PLUS */: { this.jj_consume_token(SyntaxCheckerConstants.PLUS); break; }; case 49 /* MINUS */: { this.jj_consume_token(SyntaxCheckerConstants.MINUS); break; }; default: this.jj_la1[7] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } break; }; default: this.jj_la1[8] = this.jj_gen; ; } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 82 /* DECIMAL */: case 83 /* BASE1 */: case 84 /* BASE2 */: case 85 /* BASE3 */: case 86 /* BASE4 */: case 87 /* BASE5 */: case 88 /* BASE6 */: case 89 /* BASE7 */: case 90 /* BASE8 */: case 91 /* BASE9 */: case 92 /* BASE10 */: case 93 /* BASE11 */: case 94 /* BASE12 */: case 95 /* BASE13 */: case 96 /* BASE14 */: case 97 /* BASE15 */: case 98 /* BASE16 */: case 99 /* BASE17 */: case 100 /* BASE18 */: case 101 /* BASE19 */: case 102 /* BASE20 */: case 103 /* BASE21 */: case 104 /* BASE22 */: case 105 /* BASE23 */: case 106 /* BASE24 */: case 107 /* BASE25 */: case 108 /* BASE26 */: case 109 /* BASE27 */: case 110 /* BASE28 */: case 111 /* BASE29 */: case 112 /* BASE30 */: case 113 /* BASE31 */: case 114 /* BASE32 */: case 115 /* BASE33 */: case 116 /* BASE34 */: case 117 /* BASE35 */: case 118 /* BASE36 */: case 119 /* BINARY */: case 120 /* OCTAL */: case 121 /* HEXADECIMAL */: case 122 /* FRACTION */: { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 82 /* DECIMAL */: { this.jj_consume_token(SyntaxCheckerConstants.DECIMAL); break; }; case 121 /* HEXADECIMAL */: { this.jj_consume_token(SyntaxCheckerConstants.HEXADECIMAL); break; }; case 120 /* OCTAL */: { this.jj_consume_token(SyntaxCheckerConstants.OCTAL); break; }; case 119 /* BINARY */: { this.jj_consume_token(SyntaxCheckerConstants.BINARY); break; }; case 83 /* BASE1 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE1); break; }; case 84 /* BASE2 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE2); break; }; case 85 /* BASE3 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE3); break; }; case 86 /* BASE4 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE4); break; }; case 87 /* BASE5 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE5); break; }; case 88 /* BASE6 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE6); break; }; case 89 /* BASE7 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE7); break; }; case 90 /* BASE8 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE8); break; }; case 91 /* BASE9 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE9); break; }; case 92 /* BASE10 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE10); break; }; case 93 /* BASE11 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE11); break; }; case 94 /* BASE12 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE12); break; }; case 95 /* BASE13 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE13); break; }; case 96 /* BASE14 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE14); break; }; case 97 /* BASE15 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE15); break; }; case 98 /* BASE16 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE16); break; }; case 99 /* BASE17 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE17); break; }; case 100 /* BASE18 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE18); break; }; case 101 /* BASE19 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE19); break; }; case 102 /* BASE20 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE20); break; }; case 103 /* BASE21 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE21); break; }; case 104 /* BASE22 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE22); break; }; case 105 /* BASE23 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE23); break; }; case 106 /* BASE24 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE24); break; }; case 107 /* BASE25 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE25); break; }; case 108 /* BASE26 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE26); break; }; case 109 /* BASE27 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE27); break; }; case 110 /* BASE28 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE28); break; }; case 111 /* BASE29 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE29); break; }; case 112 /* BASE30 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE30); break; }; case 113 /* BASE31 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE31); break; }; case 114 /* BASE32 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE32); break; }; case 115 /* BASE33 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE33); break; }; case 116 /* BASE34 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE34); break; }; case 117 /* BASE35 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE35); break; }; case 118 /* BASE36 */: { this.jj_consume_token(SyntaxCheckerConstants.BASE36); break; }; case 122 /* FRACTION */: { this.jj_consume_token(SyntaxCheckerConstants.FRACTION); break; }; default: this.jj_la1[9] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } break; }; case 60 /* UNIT */: case 123 /* IDENTIFIER */: case 124 /* FUNCTION */: case 125: { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 60 /* UNIT */: case 123 /* IDENTIFIER */: case 125: { this.identifier(); break; }; case 124 /* FUNCTION */: { this.jj_consume_token(SyntaxCheckerConstants.FUNCTION); break; }; default: this.jj_la1[10] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 46 /* LEFT_PAR */: { this.jj_consume_token(SyntaxCheckerConstants.LEFT_PAR); this.argumentList(); this.jj_consume_token(SyntaxCheckerConstants.RIGHT_PAR); break; }; default: this.jj_la1[11] = this.jj_gen; ; } break; }; case 46 /* LEFT_PAR */: { this.jj_consume_token(SyntaxCheckerConstants.LEFT_PAR); this.expression(); this.jj_consume_token(SyntaxCheckerConstants.RIGHT_PAR); break; }; default: this.jj_la1[12] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } } public argumentList() { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 46 /* LEFT_PAR */: case 48 /* PLUS */: case 49 /* MINUS */: case 60 /* UNIT */: case 68 /* NOT */: case 69 /* BITNOT */: case 82 /* DECIMAL */: case 83 /* BASE1 */: case 84 /* BASE2 */: case 85 /* BASE3 */: case 86 /* BASE4 */: case 87 /* BASE5 */: case 88 /* BASE6 */: case 89 /* BASE7 */: case 90 /* BASE8 */: case 91 /* BASE9 */: case 92 /* BASE10 */: case 93 /* BASE11 */: case 94 /* BASE12 */: case 95 /* BASE13 */: case 96 /* BASE14 */: case 97 /* BASE15 */: case 98 /* BASE16 */: case 99 /* BASE17 */: case 100 /* BASE18 */: case 101 /* BASE19 */: case 102 /* BASE20 */: case 103 /* BASE21 */: case 104 /* BASE22 */: case 105 /* BASE23 */: case 106 /* BASE24 */: case 107 /* BASE25 */: case 108 /* BASE26 */: case 109 /* BASE27 */: case 110 /* BASE28 */: case 111 /* BASE29 */: case 112 /* BASE30 */: case 113 /* BASE31 */: case 114 /* BASE32 */: case 115 /* BASE33 */: case 116 /* BASE34 */: case 117 /* BASE35 */: case 118 /* BASE36 */: case 119 /* BINARY */: case 120 /* OCTAL */: case 121 /* HEXADECIMAL */: case 122 /* FRACTION */: case 123 /* IDENTIFIER */: case 124 /* FUNCTION */: case 125: { this.expression(); label_2: while((true)) {{ switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 57 /* COMMA */: case 58 /* SEMICOLON */: { break; }; default: this.jj_la1[13] = this.jj_gen; break label_2; } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 57 /* COMMA */: { this.jj_consume_token(SyntaxCheckerConstants.COMMA); break; }; case 58 /* SEMICOLON */: { this.jj_consume_token(SyntaxCheckerConstants.SEMICOLON); break; }; default: this.jj_la1[14] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } this.expression(); }}; break; }; default: this.jj_la1[15] = this.jj_gen; ; } } public identifier() { switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 123 /* IDENTIFIER */: { this.jj_consume_token(SyntaxCheckerConstants.IDENTIFIER); break; }; case 60 /* UNIT */: { this.jj_consume_token(SyntaxCheckerConstants.UNIT); break; }; case 125: { this.jj_consume_token(125); label_3: while((true)) {{ switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 79 /* CHAR */: { this.jj_consume_token(SyntaxCheckerConstants.CHAR); break; }; case 123 /* IDENTIFIER */: { this.jj_consume_token(SyntaxCheckerConstants.IDENTIFIER); label_4: while((true)) {{ switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 46 /* LEFT_PAR */: case 47 /* RIGHT_PAR */: case 48 /* PLUS */: case 49 /* MINUS */: case 50 /* MULTIPLY */: case 51 /* DIV */: case 52 /* POWER */: case 54 /* MODULO */: case 57 /* COMMA */: case 62 /* LT */: case 64 /* GT */: case 66 /* OR */: case 67 /* AND */: case 68 /* NOT */: case 82 /* DECIMAL */: { break; }; default: this.jj_la1[16] = this.jj_gen; break label_4; } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 68 /* NOT */: { this.jj_consume_token(SyntaxCheckerConstants.NOT); break; }; case 54 /* MODULO */: { this.jj_consume_token(SyntaxCheckerConstants.MODULO); break; }; case 52 /* POWER */: { this.jj_consume_token(SyntaxCheckerConstants.POWER); break; }; case 67 /* AND */: { this.jj_consume_token(SyntaxCheckerConstants.AND); break; }; case 50 /* MULTIPLY */: { this.jj_consume_token(SyntaxCheckerConstants.MULTIPLY); break; }; case 51 /* DIV */: { this.jj_consume_token(SyntaxCheckerConstants.DIV); break; }; case 46 /* LEFT_PAR */: { this.jj_consume_token(SyntaxCheckerConstants.LEFT_PAR); break; }; case 47 /* RIGHT_PAR */: { this.jj_consume_token(SyntaxCheckerConstants.RIGHT_PAR); break; }; case 49 /* MINUS */: { this.jj_consume_token(SyntaxCheckerConstants.MINUS); break; }; case 48 /* PLUS */: { this.jj_consume_token(SyntaxCheckerConstants.PLUS); break; }; case 57 /* COMMA */: { this.jj_consume_token(SyntaxCheckerConstants.COMMA); break; }; case 66 /* OR */: { this.jj_consume_token(SyntaxCheckerConstants.OR); break; }; case 64 /* GT */: { this.jj_consume_token(SyntaxCheckerConstants.GT); break; }; case 62 /* LT */: { this.jj_consume_token(SyntaxCheckerConstants.LT); break; }; case 82 /* DECIMAL */: { this.jj_consume_token(SyntaxCheckerConstants.DECIMAL); break; }; default: this.jj_la1[17] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } }}; break; }; default: this.jj_la1[18] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } switch(((this.jj_ntk === -1) ? this.jj_ntk_f() : this.jj_ntk)) { case 79 /* CHAR */: case 123 /* IDENTIFIER */: { break; }; default: this.jj_la1[19] = this.jj_gen; break label_3; } }}; this.jj_consume_token(126); break; }; default: this.jj_la1[20] = this.jj_gen; this.jj_consume_token(-1); throw new ParseException(); } } /** * Generated Token Manager. */ public token_source: SyntaxCheckerTokenManager; jj_input_stream: SimpleCharStream; /** * Current token. */ public token: Token; /** * Next token. */ public jj_nt: Token; /*private*/ jj_ntk: number; /*private*/ jj_gen: number; /*private*/ jj_la1: number[]; static jj_la1_0: number[]; public static jj_la1_0_$LI$(): number[] { SyntaxChecker.__static_initialize(); return SyntaxChecker.jj_la1_0; } static jj_la1_1: number[]; public static jj_la1_1_$LI$(): number[] { SyntaxChecker.__static_initialize(); return SyntaxChecker.jj_la1_1; } static jj_la1_2: number[]; public static jj_la1_2_$LI$(): number[] { SyntaxChecker.__static_initialize(); return SyntaxChecker.jj_la1_2; } static jj_la1_3: number[]; public static jj_la1_3_$LI$(): number[] { SyntaxChecker.__static_initialize(); return SyntaxChecker.jj_la1_3; } static jj_la1_4: number[]; public static jj_la1_4_$LI$(): number[] { SyntaxChecker.__static_initialize(); return SyntaxChecker.jj_la1_4; } static __static_initializer_0() { SyntaxChecker.jj_la1_init_0(); SyntaxChecker.jj_la1_init_1(); SyntaxChecker.jj_la1_init_2(); SyntaxChecker.jj_la1_init_3(); SyntaxChecker.jj_la1_init_4(); } /*private*/ static jj_la1_init_0() { SyntaxChecker.jj_la1_0 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } /*private*/ static jj_la1_init_1() { SyntaxChecker.jj_la1_1 = [268648448, -394330112, -394330112, 25165824, 25165824, 0, 0, 196608, 196608, 0, 268435456, 16384, 268451840, 100663296, 100663296, 268648448, 1113571328, 1113571328, 0, 0, 268435456]; } /*private*/ static jj_la1_init_2() { SyntaxChecker.jj_la1_2 = [-262096, 32719, 32719, 0, 0, 48, 48, 0, 0, -262144, 0, 0, -262144, 0, 0, -262096, 262173, 262173, 32768, 32768, 0]; } /*private*/ static jj_la1_init_3() { SyntaxChecker.jj_la1_3 = [1073741823, 0, 0, 0, 0, 0, 0, 0, 0, 134217727, 939524096, 0, 1073741823, 0, 0, 1073741823, 0, 0, 134217728, 134217728, 671088640]; } /*private*/ static jj_la1_init_4() { SyntaxChecker.jj_la1_4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } public constructor(stream?: any, encoding?: any) { if (((stream != null && stream instanceof <any>java.io.InputStream) || stream === null) && ((typeof encoding === 'string') || encoding === null)) { let __args = arguments; if (this.token_source === undefined) { this.token_source = null; } if (this.jj_input_stream === undefined) { this.jj_input_stream = null; } if (this.token === undefined) { this.token = null; } if (this.jj_nt === undefined) { this.jj_nt = null; } if (this.jj_ntk === undefined) { this.jj_ntk = 0; } if (this.jj_gen === undefined) { this.jj_gen = 0; } if (this.jj_expentry === undefined) { this.jj_expentry = null; } this.jj_la1 = (s => { let a=[]; while(s-->0) a.push(0); return a; })(21); this.jj_expentries = <any>(new java.util.ArrayList<number[]>()); this.jj_kind = -1; try { this.jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(e) { throw new java.lang.RuntimeException(e); } this.token_source = new SyntaxCheckerTokenManager(this.jj_input_stream); this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } else if (((stream != null && stream instanceof <any>java.io.InputStream) || stream === null) && encoding === undefined) { let __args = arguments; { let __args = arguments; let encoding: any = null; if (this.token_source === undefined) { this.token_source = null; } if (this.jj_input_stream === undefined) { this.jj_input_stream = null; } if (this.token === undefined) { this.token = null; } if (this.jj_nt === undefined) { this.jj_nt = null; } if (this.jj_ntk === undefined) { this.jj_ntk = 0; } if (this.jj_gen === undefined) { this.jj_gen = 0; } if (this.jj_expentry === undefined) { this.jj_expentry = null; } this.jj_la1 = (s => { let a=[]; while(s-->0) a.push(0); return a; })(21); this.jj_expentries = <any>(new java.util.ArrayList<number[]>()); this.jj_kind = -1; try { this.jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(e) { throw new java.lang.RuntimeException(e); } this.token_source = new SyntaxCheckerTokenManager(this.jj_input_stream); this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } if (this.token_source === undefined) { this.token_source = null; } if (this.jj_input_stream === undefined) { this.jj_input_stream = null; } if (this.token === undefined) { this.token = null; } if (this.jj_nt === undefined) { this.jj_nt = null; } if (this.jj_ntk === undefined) { this.jj_ntk = 0; } if (this.jj_gen === undefined) { this.jj_gen = 0; } if (this.jj_expentry === undefined) { this.jj_expentry = null; } this.jj_la1 = (s => { let a=[]; while(s-->0) a.push(0); return a; })(21); this.jj_expentries = <any>(new java.util.ArrayList<number[]>()); this.jj_kind = -1; } else if (((stream != null && stream instanceof <any>java.io.Reader) || stream === null) && encoding === undefined) { let __args = arguments; if (this.token_source === undefined) { this.token_source = null; } if (this.jj_input_stream === undefined) { this.jj_input_stream = null; } if (this.token === undefined) { this.token = null; } if (this.jj_nt === undefined) { this.jj_nt = null; } if (this.jj_ntk === undefined) { this.jj_ntk = 0; } if (this.jj_gen === undefined) { this.jj_gen = 0; } if (this.jj_expentry === undefined) { this.jj_expentry = null; } this.jj_la1 = (s => { let a=[]; while(s-->0) a.push(0); return a; })(21); this.jj_expentries = <any>(new java.util.ArrayList<number[]>()); this.jj_kind = -1; this.jj_input_stream = new SimpleCharStream(stream, 1, 1); this.token_source = new SyntaxCheckerTokenManager(this.jj_input_stream); this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } else if (((stream != null && stream instanceof <any>SyntaxCheckerTokenManager) || stream === null) && encoding === undefined) { let __args = arguments; let tm: any = __args[0]; if (this.token_source === undefined) { this.token_source = null; } if (this.jj_input_stream === undefined) { this.jj_input_stream = null; } if (this.token === undefined) { this.token = null; } if (this.jj_nt === undefined) { this.jj_nt = null; } if (this.jj_ntk === undefined) { this.jj_ntk = 0; } if (this.jj_gen === undefined) { this.jj_gen = 0; } if (this.jj_expentry === undefined) { this.jj_expentry = null; } this.jj_la1 = (s => { let a=[]; while(s-->0) a.push(0); return a; })(21); this.jj_expentries = <any>(new java.util.ArrayList<number[]>()); this.jj_kind = -1; this.token_source = tm; this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } else throw new Error('invalid overload'); } public ReInit$java_io_InputStream(stream: java.io.InputStream) { this.ReInit$java_io_InputStream$java_lang_String(stream, null); } public ReInit$java_io_InputStream$java_lang_String(stream: java.io.InputStream, encoding: string) { try { this.jj_input_stream.ReInit$java_io_InputStream$java_lang_String$int$int(stream, encoding, 1, 1); } catch(e) { throw new java.lang.RuntimeException(e); } this.token_source.ReInit$org_mariuszgromada_math_mxparser_syntaxchecker_SimpleCharStream(this.jj_input_stream); this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } /** * Reinitialise. * @param {InputStream} stream * @param {string} encoding */ public ReInit(stream?: any, encoding?: any) { if (((stream != null && stream instanceof <any>java.io.InputStream) || stream === null) && ((typeof encoding === 'string') || encoding === null)) { return <any>this.ReInit$java_io_InputStream$java_lang_String(stream, encoding); } else if (((stream != null && stream instanceof <any>java.io.InputStream) || stream === null) && encoding === undefined) { return <any>this.ReInit$java_io_InputStream(stream); } else if (((stream != null && stream instanceof <any>java.io.Reader) || stream === null) && encoding === undefined) { return <any>this.ReInit$java_io_Reader(stream); } else if (((stream != null && stream instanceof <any>SyntaxCheckerTokenManager) || stream === null) && encoding === undefined) { return <any>this.ReInit$org_mariuszgromada_math_mxparser_syntaxchecker_SyntaxCheckerTokenManager(stream); } else throw new Error('invalid overload'); } public ReInit$java_io_Reader(stream: java.io.Reader) { this.jj_input_stream.ReInit$java_io_Reader$int$int(stream, 1, 1); this.token_source.ReInit$org_mariuszgromada_math_mxparser_syntaxchecker_SimpleCharStream(this.jj_input_stream); this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } public ReInit$org_mariuszgromada_math_mxparser_syntaxchecker_SyntaxCheckerTokenManager(tm: SyntaxCheckerTokenManager) { this.token_source = tm; this.token = new Token(); this.jj_ntk = -1; this.jj_gen = 0; for(let i: number = 0; i < 21; i++) {this.jj_la1[i] = -1;} } /*private*/ jj_consume_token(kind: number): Token { let oldToken: Token; if ((oldToken = this.token).next != null)this.token = this.token.next; else this.token = this.token.next = this.token_source.getNextToken(); this.jj_ntk = -1; if (this.token.kind === kind){ this.jj_gen++; return this.token; } this.token = oldToken; this.jj_kind = kind; throw this.generateParseException(); } /** * Get the next Token. * @return {Token} */ public getNextToken(): Token { if (this.token.next != null)this.token = this.token.next; else this.token = this.token.next = this.token_source.getNextToken(); this.jj_ntk = -1; this.jj_gen++; return this.token; } /** * Get the specific Token. * @param {number} index * @return {Token} */ public getToken(index: number): Token { let t: Token = this.token; for(let i: number = 0; i < index; i++) {{ if (t.next != null)t = t.next; else t = t.next = this.token_source.getNextToken(); };} return t; } /*private*/ jj_ntk_f(): number { if ((this.jj_nt = this.token.next) == null)return (this.jj_ntk = (this.token.next = this.token_source.getNextToken()).kind); else return (this.jj_ntk = this.jj_nt.kind); } /*private*/ jj_expentries: java.util.List<number[]>; /*private*/ jj_expentry: number[]; /*private*/ jj_kind: number; /** * Generate ParseException. * @return {ParseException} */ public generateParseException(): ParseException { this.jj_expentries.clear(); const la1tokens: boolean[] = (s => { let a=[]; while(s-->0) a.push(false); return a; })(129); if (this.jj_kind >= 0){ la1tokens[this.jj_kind] = true; this.jj_kind = -1; } for(let i: number = 0; i < 21; i++) {{ if (this.jj_la1[i] === this.jj_gen){ for(let j: number = 0; j < 32; j++) {{ if ((SyntaxChecker.jj_la1_0_$LI$()[i] & (1 << j)) !== 0){ la1tokens[j] = true; } if ((SyntaxChecker.jj_la1_1_$LI$()[i] & (1 << j)) !== 0){ la1tokens[32 + j] = true; } if ((SyntaxChecker.jj_la1_2_$LI$()[i] & (1 << j)) !== 0){ la1tokens[64 + j] = true; } if ((SyntaxChecker.jj_la1_3_$LI$()[i] & (1 << j)) !== 0){ la1tokens[96 + j] = true; } if ((SyntaxChecker.jj_la1_4_$LI$()[i] & (1 << j)) !== 0){ la1tokens[128 + j] = true; } };} } };} for(let i: number = 0; i < 129; i++) {{ if (la1tokens[i]){ this.jj_expentry = [0]; this.jj_expentry[0] = i; this.jj_expentries.add(this.jj_expentry); } };} const exptokseq: number[][] = (s => { let a=[]; while(s-->0) a.push(null); return a; })(this.jj_expentries.size()); for(let i: number = 0; i < this.jj_expentries.size(); i++) {{ exptokseq[i] = this.jj_expentries.get(i); };} return new ParseException(this.token, exptokseq, SyntaxCheckerConstants.tokenImage); } /** * Enable tracing. */ public enable_tracing() { } /** * Disable tracing. */ public disable_tracing() { } } SyntaxChecker["__class"] = "org.mariuszgromada.math.mxparser.syntaxchecker.SyntaxChecker"; SyntaxChecker["__interfaces"] = ["org.mariuszgromada.math.mxparser.syntaxchecker.SyntaxCheckerConstants"]; SyntaxChecker.__static_initialize();
the_stack
import * as triplesec from 'triplesec'; import * as elliptic from 'elliptic'; import * as webCryptoPolyfill from '@peculiar/webcrypto'; import { encryptECIES, decryptECIES, getHexFromBN, signECDSA, verifyECDSA, encryptMnemonic, decryptMnemonic, } from '../src'; import { bytesToHex, ERROR_CODES, getGlobalScope, utf8ToBytes } from '@stacks/common'; import * as pbkdf2 from '../src/pbkdf2'; import * as aesCipher from '../src/aesCipher'; import * as sha2Hash from '../src/sha2Hash'; import * as hmacSha256 from '../src/hmacSha256'; import * as ripemd160 from '../src/hashRipemd160'; // https://github.com/paulmillr/scure-bip39 // Secure, audited & minimal implementation of BIP39 mnemonic phrases. import { validateMnemonic, mnemonicToEntropy, entropyToMnemonic } from '@scure/bip39'; // Word lists not imported by default as that would increase bundle sizes too much as in case of bitcoinjs/bip39 // Use default english world list similiar to bitcoinjs/bip39 // Backward compatible with bitcoinjs/bip39 dependency // Very small in size as compared to bitcoinjs/bip39 wordlist // Reference: https://github.com/paulmillr/scure-bip39 import { wordlist } from '@scure/bip39/wordlists/english'; import { getBufferFromBN } from '../src/ec'; import { getPublicKey as nobleGetPublicKey, getSharedSecret, signSync as nobleSecp256k1Sign, utils, verify as nobleSecp256k1Verify, } from '@noble/secp256k1'; import { Buffer } from '@stacks/common'; const privateKey = 'a5c61c6ca7b3e7e55edee68566aeab22e4da26baa285c7bd10e8d2218aa3b229'; const publicKey = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'; test('ripemd160 digest tests', async () => { const vectors = [ ['The quick brown fox jumps over the lazy dog', '37f332f68db77bd9d7edd4969571ad671cf9dd3b'], ['The quick brown fox jumps over the lazy cog', '132072df690933835eb8b6ad0b77e7b6f14acad7'], ['a', '0bdc9d2d256b3ee9daae347be6f4dc835a467ffe'], ['abc', '8eb208f7e05d987a9b044a8e98c6b087f15a0bfc'], ['message digest', '5d0689ef49d2fae572b881b123a85ffa21595f36'], ['', '9c1185a5c5e9fc54612808977ee8f548b2258d31'], ]; const nodeCryptoHasher = await ripemd160.createHashRipemd160(); expect(nodeCryptoHasher instanceof ripemd160.NodeCryptoRipemd160Digest).toEqual(true); for (const [input, expected] of vectors) { const result = await nodeCryptoHasher.digest(Buffer.from(input)); const resultHex = result.toString('hex'); expect(resultHex).toEqual(expected); } const polyfillHasher = new ripemd160.Ripemd160PolyfillDigest(); for (const [input, expected] of vectors) { const result = await polyfillHasher.digest(Buffer.from(input)); const resultHex = result.toString('hex'); expect(resultHex).toEqual(expected); } const nodeCrypto = require('crypto'); const createHashOrig = nodeCrypto.createHash; nodeCrypto.createHash = () => { throw new Error('Artificial broken hash'); }; try { await ripemd160.hashRipemd160(Buffer.from('acb')); } finally { nodeCrypto.createHash = createHashOrig; } }); test('sha2 digest tests', async () => { const globalScope = getGlobalScope() as any; // Remove any existing global `crypto` variable for testing const globalCryptoOrig = { defined: 'crypto' in globalScope, value: globalScope.crypto }; // Set global web `crypto` polyfill for testing const webCrypto = new webCryptoPolyfill.Crypto(); globalScope.crypto = webCrypto; const vectors = [ [ 'abc', 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f', ], [ '', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e', ], [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1', '204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445', ], ]; try { const webCryptoHasher = await sha2Hash.createSha2Hash(); expect(webCryptoHasher instanceof sha2Hash.WebCryptoSha2Hash).toBe(true); for (const [input, expected256, expected512] of vectors) { const result256 = await webCryptoHasher.digest(Buffer.from(input), 'sha256'); expect(result256.toString('hex')).toEqual(expected256); const result512 = await webCryptoHasher.digest(Buffer.from(input), 'sha512'); expect(result512.toString('hex')).toEqual(expected512); } const nodeCryptoHasher = new sha2Hash.NodeCryptoSha2Hash(require('crypto').createHash); for (const [input, expected256, expected512] of vectors) { const result256 = await nodeCryptoHasher.digest(Buffer.from(input), 'sha256'); expect(result256.toString('hex')).toEqual(expected256); const result512 = await nodeCryptoHasher.digest(Buffer.from(input), 'sha512'); expect(result512.toString('hex')).toEqual(expected512); } } finally { // Restore previous `crypto` global var if (globalCryptoOrig.defined) { globalScope.crypto = globalCryptoOrig.value; } else { delete globalScope.crypto; } } }); test('sha2 native digest fallback tests', async () => { const input = Buffer.from('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'); const expectedOutput256 = '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'; const expectedOutput512 = '204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445'; // Test WebCrypto fallback const webCryptoSubtle = new webCryptoPolyfill.Crypto().subtle; webCryptoSubtle.digest = () => { throw new Error('Artificial broken hash'); }; const nodeCryptoHasher = new sha2Hash.WebCryptoSha2Hash(webCryptoSubtle); const result256 = await nodeCryptoHasher.digest(input, 'sha256'); expect(result256.toString('hex')).toEqual(expectedOutput256); const result512 = await nodeCryptoHasher.digest(input, 'sha512'); expect(result512.toString('hex')).toEqual(expectedOutput512); // Test Node.js `crypto.createHash` fallback const nodeCrypto = require('crypto'); const createHashOrig = nodeCrypto.createHash; nodeCrypto.createHash = () => { throw new Error('Artificial broken hash'); }; try { const nodeCryptoHasher = new sha2Hash.NodeCryptoSha2Hash(require('crypto').createHash); const result256 = await nodeCryptoHasher.digest(input, 'sha256'); expect(result256.toString('hex')).toEqual(expectedOutput256); const result512 = await nodeCryptoHasher.digest(input, 'sha512'); expect(result512.toString('hex')).toEqual(expectedOutput512); } finally { nodeCrypto.createHash = createHashOrig; } }); test('hmac-sha256 tests', async () => { const key = Buffer.alloc(32, 0xf5); const data = Buffer.alloc(100, 0x44); const expected = 'fe44c2197eb8a5678daba87ff2aba891d8b12224d8219acd4cfa5cee4f9acc77'; const globalScope = getGlobalScope() as any; // Remove any existing global `crypto` variable for testing const globalCryptoOrig = { defined: 'crypto' in globalScope, value: globalScope.crypto }; delete globalScope.crypto; try { const nodeCryptoHmac = await hmacSha256.createHmacSha256(); expect(nodeCryptoHmac instanceof hmacSha256.NodeCryptoHmacSha256).toEqual(true); // Set global web `crypto` polyfill for testing const webCrypto = new webCryptoPolyfill.Crypto(); globalScope.crypto = webCrypto; const webCryptoHmac = await hmacSha256.createHmacSha256(); expect(webCryptoHmac instanceof hmacSha256.WebCryptoHmacSha256).toEqual(true); const derivedNodeCrypto = (await nodeCryptoHmac.digest(key, data)).toString('hex'); const derivedWebCrypto = (await webCryptoHmac.digest(key, data)).toString('hex'); expect(expected).toEqual(derivedNodeCrypto); expect(expected).toEqual(derivedWebCrypto); } finally { // Restore previous `crypto` global var if (globalCryptoOrig.defined) { globalScope.crypto = globalCryptoOrig.value; } else { delete globalScope.crypto; } } }); test('pbkdf2 digest tests', async () => { const salt = Buffer.alloc(16, 0xf0); const password = 'password123456'; const digestAlgo = 'sha512'; const iterations = 100000; const keyLength = 48; const globalScope = getGlobalScope() as any; // Remove any existing global `crypto` variable for testing const globalCryptoOrig = { defined: 'crypto' in globalScope, value: globalScope.crypto }; delete globalScope.crypto; try { const nodeCryptoPbkdf2 = await pbkdf2.createPbkdf2(); expect(nodeCryptoPbkdf2 instanceof pbkdf2.NodeCryptoPbkdf2).toEqual(true); // Set global web `crypto` polyfill for testing const webCrypto = new webCryptoPolyfill.Crypto(); globalScope.crypto = webCrypto; const webCryptoPbkdf2 = await pbkdf2.createPbkdf2(); expect(webCryptoPbkdf2 instanceof pbkdf2.WebCryptoPbkdf2).toEqual(true); const polyFillPbkdf2 = new pbkdf2.WebCryptoPartialPbkdf2(webCrypto.subtle); const derivedNodeCrypto = ( await nodeCryptoPbkdf2.derive(password, salt, iterations, keyLength, digestAlgo) ).toString('hex'); const derivedWebCrypto = ( await webCryptoPbkdf2.derive(password, salt, iterations, keyLength, digestAlgo) ).toString('hex'); const derivedPolyFill = ( await polyFillPbkdf2.derive(password, salt, iterations, keyLength, digestAlgo) ).toString('hex'); const expected = '92f603459cc45a33eeb6ee06bb75d12bb8e61d9f679668392362bb104eab6d95027398e02f500c849a3dd1ccd63fb310'; expect(expected).toEqual(derivedNodeCrypto); expect(expected).toEqual(derivedWebCrypto); expect(expected).toEqual(derivedPolyFill); } finally { // Restore previous `crypto` global var if (globalCryptoOrig.defined) { globalScope.crypto = globalCryptoOrig.value; } else { delete globalScope.crypto; } } }); test('aes-cbc tests', async () => { const globalScope = getGlobalScope() as any; // Remove any existing global `crypto` variable for testing const globalCryptoOrig = { defined: 'crypto' in globalScope, value: globalScope.crypto }; delete globalScope.crypto; try { const nodeCryptoAesCipher = await aesCipher.createCipher(); expect(nodeCryptoAesCipher instanceof aesCipher.NodeCryptoAesCipher).toEqual(true); // Set global web `crypto` polyfill for testing const webCrypto = new webCryptoPolyfill.Crypto(); globalScope.crypto = webCrypto; const webCryptoAesCipher = await aesCipher.createCipher(); expect(webCryptoAesCipher instanceof aesCipher.WebCryptoAesCipher).toEqual(true); const key128 = Buffer.from('0f'.repeat(16), 'hex'); const key256 = Buffer.from('0f'.repeat(32), 'hex'); const iv = Buffer.from('f7'.repeat(16), 'hex'); const inputData = Buffer.from('TestData'.repeat(20)); const inputDataHex = inputData.toString('hex'); const expected128Cbc = '5aa1100a0a3133c9184dc661bc95c675a0fe5f02a67880f50702f8c88e7a445248d6dedfca80e72d00c3d277ea025eebde5940265fa00c1bfe80aebf3968b6eaf0564eda6ddd9e97548be1fa6d487e71353b11136193782d76d3b8d1895047e08a121c1706c083ceefdb9605a75a2310cccee1b0aaca632230f45f1172001cad96ae6d15db38ab9eed27b27b6f80353a5f30e3532a526a834a0f8273ffb2e9caaa92843b40c893e298f3b472fb26b11f'; const expected128CbcBuffer = Buffer.from(expected128Cbc, 'hex'); const expected256Cbc = '66a21fa53680d8182a79c1b90cdc38d398fe34d85c7ca5d45b8381fea4a84536e38514b3bcdba06655314607534be7ea370952ed6f334af709efc6504e600ce0b7c20fe3b469c29b63a391983b74aa12f1d859b477092c61e7814bd6c8d143ec21d34f79468c74c97ae9763ec11695e1e9a3a3b33f12561ecef9fbae79ddf7f2701c97ba1531801862662a9ce87a880934318a9e46a3941367fa68da3340f83941211aba7ec741826ff35d4f880243db'; const expected256CbcBuffer = Buffer.from(expected256Cbc, 'hex'); // Test aes-256-cbc encrypt const encrypted256NodeCrypto = ( await nodeCryptoAesCipher.encrypt('aes-256-cbc', key256, iv, inputData) ).toString('hex'); const encrypted256WebCrypto = ( await webCryptoAesCipher.encrypt('aes-256-cbc', key256, iv, inputData) ).toString('hex'); expect(expected256Cbc).toEqual(encrypted256NodeCrypto); expect(expected256Cbc).toEqual(encrypted256WebCrypto); // Test aes-256-cbc decrypt const decrypted256NodeCrypto = ( await nodeCryptoAesCipher.decrypt('aes-256-cbc', key256, iv, expected256CbcBuffer) ).toString('hex'); const decrypted256WebCrypto = ( await webCryptoAesCipher.decrypt('aes-256-cbc', key256, iv, expected256CbcBuffer) ).toString('hex'); expect(inputDataHex).toEqual(decrypted256NodeCrypto); expect(inputDataHex).toEqual(decrypted256WebCrypto); // Test aes-128-cbc encrypt const encrypted128NodeCrypto = ( await nodeCryptoAesCipher.encrypt('aes-128-cbc', key128, iv, inputData) ).toString('hex'); const encrypted128WebCrypto = ( await webCryptoAesCipher.encrypt('aes-128-cbc', key128, iv, inputData) ).toString('hex'); expect(expected128Cbc).toEqual(encrypted128NodeCrypto); expect(expected128Cbc).toEqual(encrypted128WebCrypto); // Test aes-128-cbc decrypt const decrypted128NodeCrypto = ( await nodeCryptoAesCipher.decrypt('aes-128-cbc', key128, iv, expected128CbcBuffer) ).toString('hex'); const decrypted128WebCrypto = ( await webCryptoAesCipher.decrypt('aes-128-cbc', key128, iv, expected128CbcBuffer) ).toString('hex'); expect(inputDataHex).toEqual(decrypted128NodeCrypto); expect(inputDataHex).toEqual(decrypted128WebCrypto); } finally { // Restore previous `crypto` global var if (globalCryptoOrig.defined) { globalScope.crypto = globalCryptoOrig.value; } else { delete globalScope.crypto; } } }); test('encrypt-to-decrypt works', async () => { const testString = 'all work and no play makes jack a dull boy'; let cipherObj = await encryptECIES(publicKey, Buffer.from(testString), true); let deciphered = await decryptECIES(privateKey, cipherObj); expect(deciphered).toEqual(testString); const testBuffer = Buffer.from(testString); cipherObj = await encryptECIES(publicKey, testBuffer, false); deciphered = await decryptECIES(privateKey, cipherObj); expect(deciphered.toString('hex')).toEqual(testBuffer.toString('hex')); }); test('encrypt-to-decrypt fails on bad mac', async () => { const testString = 'all work and no play makes jack a dull boy'; const cipherObj = await encryptECIES(publicKey, Buffer.from(testString), true); const evilString = 'some work and some play makes jack a dull boy'; const evilObj = await encryptECIES(publicKey, Buffer.from(evilString), true); cipherObj.cipherText = evilObj.cipherText; try { await decryptECIES(privateKey, cipherObj); expect(false).toEqual(true); } catch (e: any) { expect(e.code).toEqual(ERROR_CODES.FAILED_DECRYPTION_ERROR); expect(e.message.indexOf('failure in MAC check')).not.toEqual(-1); } }); test('Should be able to prevent a public key twist attack for secp256k1', async () => { const curve = new elliptic.ec('secp256k1'); // Pick a bad point to generate a public key. // If a bad point can be passed it's possible to perform a twist attack. const point = curve.keyFromPublic({ x: '14', y: '16', }); const badPublicKey = point.getPublic('hex'); try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(badPublicKey, Buffer.from(testString), true); expect(false).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('IsNotPoint'); } }); test('Should be able to accept public key with valid point on secp256k', async () => { const curve = new elliptic.ec('secp256k1'); // Pick a valid point on secp256k to generate a public key. const point = curve.keyFromPublic({ x: '0C6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5', y: '1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A', }); const goodPublicKey = point.getPublic('hex'); try { const testString = 'all work and no play makes jack a dull boy'; // encryptECIES should not throw invalid point exception await encryptECIES(goodPublicKey, Buffer.from(testString), true); expect(true).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('IsNotPoint'); } }); test('Should reject public key having invalid length', async () => { const invalidPublicKey = '0273d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(invalidPublicKey, Buffer.from(testString), true); //Should throw invalid format exception expect(false).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('Should accept public key having valid length', async () => { const publicKey = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(publicKey, Buffer.from(testString), true); // Should not throw invalid format exception expect(true).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('Should reject invalid uncompressed public key', async () => { const invalidPublicKey = '02ad90e5b6bc86b3ec7fac2c5fbda7423fc8ef0d58df594c773fa05e2c281b2bfe877677c668bd13603944e34f4818ee03cadd81a88542b8b4d5431264180e2c28'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(invalidPublicKey, Buffer.from(testString), true); // Should throw invalid format exception expect(false).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('Should accept valid uncompressed public key', async () => { const publicKey = '04ad90e5b6bc86b3ec7fac2c5fbda7423fc8ef0d58df594c773fa05e2c281b2bfe877677c668bd13603944e34f4818ee03cadd81a88542b8b4d5431264180e2c28'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(publicKey, Buffer.from(testString), true); // Should not throw invalid format exception expect(true).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('Should reject invalid compressed public key', async () => { const invalidPublicKey = '017d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(invalidPublicKey, Buffer.from(testString), true); // Should throw invalid format exception expect(false).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('Should accept valid compressed public key', async () => { const publicKey = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'; try { const testString = 'all work and no play makes jack a dull boy'; await encryptECIES(publicKey, Buffer.from(testString), true); // Should not throw invalid format exception expect(true).toEqual(true); } catch (error: any) { expect(error.reason).toEqual('InvalidFormat'); } }); test('sign-to-verify-works', async () => { const testString = 'all work and no play makes jack a dull boy'; let sigObj = await signECDSA(privateKey, testString); expect(await verifyECDSA(testString, sigObj.publicKey, sigObj.signature)).toEqual(true); const testBuffer = Buffer.from(testString); sigObj = await signECDSA(privateKey, testBuffer); expect(await verifyECDSA(testBuffer, sigObj.publicKey, sigObj.signature)).toEqual(true); }); test('sign-to-verify-fails', async () => { const testString = 'all work and no play makes jack a dull boy'; const failString = 'I should fail'; let sigObj = await signECDSA(privateKey, testString); expect(await verifyECDSA(failString, sigObj.publicKey, sigObj.signature)).toEqual(false); const testBuffer = Buffer.from(testString); sigObj = await signECDSA(privateKey, testBuffer); expect(await verifyECDSA(Buffer.from(failString), sigObj.publicKey, sigObj.signature)).toEqual( false ); const badPK = '0288580b020800f421d746f738b221d384f098e911b81939d8c94df89e74cba776'; sigObj = await signECDSA(privateKey, testBuffer); expect(await verifyECDSA(Buffer.from(failString), badPK, sigObj.signature)).toEqual(false); }); test('bn-padded-to-64-bytes', () => { const ecurve = new elliptic.ec('secp256k1'); const evilHexes = [ 'ba40f85b152bea8c3812da187bcfcfb0dc6e15f9e27cb073633b1c787b19472f', 'e346010f923f768138152d0bad063999ff1da5361a81e6e6f9106241692a0076', ]; const results = evilHexes.map(hex => { const ephemeralSK = ecurve.keyFromPrivate(hex); const ephemeralPK = ephemeralSK.getPublic(); const sharedSecret = ephemeralSK.derive(ephemeralPK); return getHexFromBN(BigInt(sharedSecret.toString())).length === 64; }); expect(results.every(x => x)).toEqual(true); const bnBuffer = getBufferFromBN(BigInt(123)); expect(bnBuffer.byteLength).toEqual(32); expect(bnBuffer.toString('hex')).toEqual(getHexFromBN(BigInt(123))); }); test('encryptMnemonic & decryptMnemonic', async () => { const rawPhrase = 'march eager husband pilot waste rely exclude taste ' + 'twist donkey actress scene'; const rawPassword = 'testtest'; const encryptedPhrase = 'ffffffffffffffffffffffffffffffffca638cc39fc270e8be5c' + 'bf98347e42a52ee955e287ab589c571af5f7c80269295b0039e32ae13adf11bc6506f5ec' + '32dda2f79df4c44276359c6bac178ae393de'; const preEncryptedPhrase = '7573f4f51089ba7ce2b95542552b7504de7305398637733' + '0579649dfbc9e664073ba614fac180d3dc237b21eba57f9aee5702ba819fe17a0752c4dc7' + '94884c9e75eb60da875f778bbc1aaca1bd373ea3'; const legacyPhrase = 'vivid oxygen neutral wheat find thumb cigar wheel ' + 'board kiwi portion business'; const legacyPassword = 'supersecret'; const legacyEncrypted = '1c94d7de0000000304d583f007c71e6e5fef354c046e8c64b1' + 'adebd6904dcb007a1222f07313643873455ab2a3ab3819e99d518cc7d33c18bde02494aa' + '74efc35a8970b2007b2fc715f6067cee27f5c92d020b1806b0444994aab80050a6732131' + 'd2947a51bacb3952fb9286124b3c2b3196ff7edce66dee0dbd9eb59558e0044bddb3a78f' + '48a66cf8d78bb46bb472bd2d5ec420c831fc384293252459524ee2d668869f33c586a944' + '67d0ce8671260f4cc2e87140c873b6ca79fb86c6d77d134d7beb2018845a9e71e6c7ecde' + 'dacd8a676f1f873c5f9c708cc6070642d44d2505aa9cdba26c50ad6f8d3e547fb0cba710' + 'a7f7be54ff7ea7e98a809ddee5ef85f6f259b3a17a8d8dbaac618b80fe266a1e63ec19e4' + '76bee9177b51894ee'; // Test encryption -> decryption. Can't be done with hard-coded values // due to random salt. await encryptMnemonic(rawPhrase, rawPassword) .then( encoded => decryptMnemonic(encoded.toString('hex'), rawPassword, triplesec.decrypt), err => { fail(`Should encrypt mnemonic phrase, instead errored: ${err}`); } ) .then( (decoded: string) => { expect(decoded.toString() === rawPhrase).toEqual(true); }, err => { fail(`Should decrypt encrypted phrase, instead errored: ${err}`); } ); // // Test encryption with mocked randomBytes generator to use same salt try { const mockSalt = Buffer.from('ff'.repeat(16), 'hex'); const encoded = await encryptMnemonic(rawPhrase, rawPassword, { getRandomBytes: () => mockSalt, }); expect(encoded.toString('hex') === encryptedPhrase).toEqual(true); } catch (err) { fail(`Should have encrypted phrase with deterministic salt, instead errored: ${err}`); } // // Test decryption with mocked randomBytes generator to use same salt try { const decoded = await decryptMnemonic( Buffer.from(encryptedPhrase, 'hex'), rawPassword, triplesec.decrypt ); expect(decoded === rawPhrase).toEqual(true); } catch (err) { fail(`Should have decrypted phrase with deterministic salt, instead errored: ${err}`); } // // Test valid input (No salt, so it's the same every time) await decryptMnemonic(legacyEncrypted, legacyPassword, triplesec.decrypt).then( decoded => { expect(decoded === legacyPhrase).toEqual(true); }, err => { fail(`Should decrypt legacy encrypted phrase, instead errored: ${err}`); } ); const errorCallback = jest.fn(); // // Invalid inputs await encryptMnemonic('not a mnemonic phrase', 'password').then(() => { fail('Should have thrown on invalid mnemonic input'); }, errorCallback); expect(errorCallback).toHaveBeenCalledTimes(1); await decryptMnemonic(preEncryptedPhrase, 'incorrect password', triplesec.decrypt).then(() => { fail('Should have thrown on incorrect password for decryption'); }, errorCallback); expect(errorCallback).toHaveBeenCalledTimes(2); }); test('Shared secret from a keypair should be same using elliptic or noble', () => { // Consider a privateKey, publicKey pair and get shared secret using noble and then elliptic // Both secret's should match noble <=> elliptic //Step 1: Get shared secret using noble secp256k1 library const sharedSecretNoble = getSharedSecret(privateKey, publicKey, true); // Trim the compressed mode prefix byte const sharedSecretNobleBuffer = Buffer.from(sharedSecretNoble).slice(1); //Step 2: Get shared secret using elliptic library const ecurve = new elliptic.ec('secp256k1'); const ecPK = ecurve.keyFromPublic(publicKey, 'hex').getPublic(); const keyPair = ecurve.keyFromPrivate(privateKey); // Get shared secret using elliptic library const sharedSecretEC = keyPair.derive(ecPK).toBuffer(); // Both shared secret should match to verify the compatibility expect(sharedSecretNobleBuffer).toEqual(sharedSecretEC); }); test('Sign msg using elliptic/secp256k1 and verify signature using @noble/secp256k1', () => { // Maximum keypairs to try if a keypairs is not accepted by @noble/secp256k1 const keyPairAttempts = 8; // Normally a keypairs is accepted in first or second attempt let nobleVerifyResult = false; const ec = new elliptic.ec('secp256k1'); for (let i = 0; i < keyPairAttempts && !nobleVerifyResult; i++) { // Generate keys const options = { entropy: utils.randomBytes(32) }; const keyPair = ec.genKeyPair(options); const msg = 'hello world'; const msgHex = bytesToHex(utf8ToBytes(msg)); // Sign msg using elliptic/secp256k1 // input must be an array, or a hex-string const signature = keyPair.sign(msgHex); // Export DER encoded signature in hex format const signatureHex = signature.toDER('hex'); // Verify signature using elliptic/secp256k1 const ellipticVerifyResult = keyPair.verify(msgHex, signatureHex); expect(ellipticVerifyResult).toBeTruthy(); // Get public key from key-pair const publicKey = keyPair.getPublic().encodeCompressed('hex'); // Verify same signature using @noble/secp256k1 nobleVerifyResult = nobleSecp256k1Verify(signatureHex, msgHex, publicKey); } // Verification result by @noble/secp256k1 should be true expect(nobleVerifyResult).toBeTruthy(); }); test('Sign msg using @noble/secp256k1 and verify signature using elliptic/secp256k1', () => { // Generate private key const privateKey = utils.randomPrivateKey(); const msg = 'hello world'; const msgHex = bytesToHex(utf8ToBytes(msg)); // Sign msg using @noble/secp256k1 // input must be a hex-string const signature = nobleSecp256k1Sign(msgHex, privateKey); const publicKey = nobleGetPublicKey(privateKey); // Verify signature using @noble/secp256k1 const nobleVerifyResult = nobleSecp256k1Verify(signature, msgHex, publicKey); // Verification result by @noble/secp256k1 expect(nobleVerifyResult).toBeTruthy(); // Generate keypair using private key const ec = new elliptic.ec('secp256k1'); const keyPair = ec.keyFromPrivate(privateKey); // Verify signature using elliptic/secp256k1 const ellipticVerifyResult = keyPair.verify(msgHex, signature); // Verification result by elliptic/secp256k1 should be true expect(ellipticVerifyResult).toBeTruthy(); }); test('Verify compatibility @scure/bip39 <=> bitcoinjs/bip39', () => { // Consider an entropy const entropy = '00000000000000000000000000000000'; // Consider same entropy in array format const entropyUint8Array = new Uint8Array(entropy.split('').map(Number)); // Based on Aaron comment do not import bitcoinjs/bip39 for these tests const bitcoinjsBip39 = { // Consider it equivalent to bitcoinjs/bip39 (offloaded now) // Using this map of required functions from bitcoinjs/bip39 and mocking the output for considered entropy entropyToMnemonicBip39: (_: string) => 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', validateMnemonicBip39: (_: string) => true, mnemonicToEntropyBip39: (_: string) => '00000000000000000000000000000000', }; // entropyToMnemonicBip39 imported from bitcoinjs/bip39 const bip39Mnemonic = bitcoinjsBip39.entropyToMnemonicBip39(entropy); // entropyToMnemonic imported from @scure/bip39 const mnemonic = entropyToMnemonic(entropyUint8Array, wordlist); //Phase 1: Cross verify mnemonic validity: @scure/bip39 <=> bitcoinjs/bip39 // validateMnemonic imported from @scure/bip39 expect(validateMnemonic(bip39Mnemonic, wordlist)).toEqual(true); // validateMnemonicBip39 imported from bitcoinjs/bip39 expect(bitcoinjsBip39.validateMnemonicBip39(mnemonic)).toEqual(true); // validateMnemonic imported from @scure/bip39 expect(validateMnemonic(mnemonic, wordlist)).toEqual(true); // validateMnemonicBip39 imported from bitcoinjs/bip39 expect(bitcoinjsBip39.validateMnemonicBip39(bip39Mnemonic)).toEqual(true); //Phase 2: Get back entropy from mnemonic and verify @scure/bip39 <=> bitcoinjs/bip39 // mnemonicToEntropy imported from @scure/bip39 expect(mnemonicToEntropy(mnemonic, wordlist)).toEqual(entropyUint8Array); // mnemonicToEntropyBip39 imported from bitcoinjs/bip39 expect(bitcoinjsBip39.mnemonicToEntropyBip39(bip39Mnemonic)).toEqual(entropy); // mnemonicToEntropy imported from @scure/bip39 expect(Buffer.from(mnemonicToEntropy(bip39Mnemonic, wordlist)).toString('hex')).toEqual(entropy); // mnemonicToEntropyBip39 imported from bitcoinjs/bip39 const entropyString = bitcoinjsBip39.mnemonicToEntropyBip39(mnemonic); // Convert entropy to bytes const entropyInBytes = new Uint8Array(entropyString.split('').map(Number)); // entropy should match with entropyUint8Array expect(entropyInBytes).toEqual(entropyUint8Array); });
the_stack
import * as lcs from "./lcs"; import type { Delta } from "./types"; type Input = unknown; export type ObjectHashFunction = (object: object, index?: number) => string; type Context = { left: Input; leftType?: string; leftIsArray?: boolean; right: Input; rightType?: string; rightIsArray?: boolean; result: unknown; children?: Array<Context>; name?: string | number; includePreviousValue: boolean; objectHash?: ObjectHashFunction; matchByPosition?: boolean; stopped: boolean; }; export type DiffOptions = { /** * A function for generating a identifier from an object in order to produce more performant list update patches. */ objectHash?: ObjectHashFunction; /** Whether you wanna force matching by array position. (Note: You do not wanna do this. Please specify a objectHash function :). */ matchByPosition?: boolean; /** * Whether the previous value should be included in the diff. * This can drastically increase the patch size and should only be used for debugging * or cases where you need to perform more advanced consistency checks. * * Default: `false` * */ includePreviousValue?: boolean; }; export function diff( input: { left: Input; right: Input }, options?: DiffOptions ): Delta { const includePreviousValue = options?.includePreviousValue ?? false; const objectHash = options?.objectHash; const matchByPosition = options?.matchByPosition; const context: Context = { result: undefined, left: input.left, right: input.right, includePreviousValue, objectHash, matchByPosition, stopped: false, }; function process(context: Context) { const steps = [ nested_collectChildrenDiffFilter, trivialDiffFilter, nested_objectsDiffFilter, array_diffFilter, ]; for (const step of steps) { step(context); if (context.stopped) { context.stopped = false; break; } } if (context.children?.length) { for (const childrenContext of context.children) { process(childrenContext); if (childrenContext.result !== undefined) { context.result = context.result ?? {}; (context.result as object)[childrenContext.name!] = childrenContext.result; } } if (context.result && context.leftIsArray) { (context.result as any)._t = "a"; } } } process(context); return context.result as Delta; } // diff primitive values and non arrays function trivialDiffFilter(context: Context) { if (context.left === context.right) { context.result = undefined; context.stopped = true; return; } // Item was added if (typeof context.left === "undefined") { context.result = [context.right]; context.stopped = true; return; } // Item was removed if (typeof context.right === "undefined") { const previousValue = context.includePreviousValue ? context.left : null; context.result = [previousValue, 0, 0]; context.stopped = true; return; } context.leftType = context.left === null ? "null" : typeof context.left; context.rightType = context.right === null ? "null" : typeof context.right; if (context.leftType !== context.rightType) { const previousValue = context.includePreviousValue ? context.left : null; context.result = [previousValue, context.right]; context.stopped = true; return; } if ( context.leftType === "boolean" || context.leftType === "number" || context.leftType === "string" ) { const previousValue = context.includePreviousValue ? context.left : null; context.result = [previousValue, context.right]; context.stopped = true; return; } if (context.leftType === "object") { context.leftIsArray = Array.isArray(context.left); } if (context.rightType === "object") { context.rightIsArray = Array.isArray(context.right); } if (context.leftIsArray !== context.rightIsArray) { const previousValue = context.includePreviousValue ? context.left : null; context.result = [previousValue, context.right]; context.stopped = true; return; } } function nested_collectChildrenDiffFilter(context: Context) { if (!context || !context.children) { return; } const length = context.children.length; let child; let result = context.result as object; for (let index = 0; index < length; index++) { child = context.children[index]; if (typeof child.result === "undefined") { continue; } result = result ?? {}; result[child.name!] = child.result; } if (result && context.leftIsArray) { result["_t"] = "a"; } context.result = result; context.stopped = true; } function nested_objectsDiffFilter(context: Context) { if (context.leftIsArray || context.leftType !== "object") { return; } const left = context.left as Record<string | number | symbol, unknown>; const right = context.right as Record<string | number | symbol, unknown>; for (const name in left) { if (!Object.prototype.hasOwnProperty.call(left, name)) { continue; } if (context.children === undefined) { context.children = []; } context.children.push({ left: left[name], right: right[name], result: undefined, name, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); } for (const name in right) { if (!Object.prototype.hasOwnProperty.call(right, name)) { continue; } if (typeof left[name] === "undefined") { if (context.children === undefined) { context.children = []; } context.children.push({ left: undefined, right: right[name], result: undefined, name, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); } } if (!context.children || context.children.length === 0) { context.result = undefined; context.stopped = true; return; } context.stopped = true; } type MatchContext = { objectHash?: ObjectHashFunction; matchByPosition: boolean | undefined; hashCache1?: Array<unknown>; hashCache2?: Array<unknown>; }; const ARRAY_MOVE = 3; function array_diffFilter(context: Context) { if (!context.leftIsArray) { return; } let matchContext: MatchContext = { objectHash: context.objectHash, matchByPosition: context.matchByPosition, }; let commonHead = 0; let commonTail = 0; let index; let index1; let index2; const array1 = context.left as Array<unknown>; const array2 = context.right as Array<unknown>; const len1 = array1.length; const len2 = array2.length; if ( len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== "boolean" ) { matchContext.matchByPosition = !arraysHaveMatchByRef( array1, array2, len1, len2 ); } // separate common head while ( commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext) ) { index = commonHead; const left = context.left as Array<unknown>; const right = context.right as Array<unknown>; if (context.children === undefined) { context.children = []; } context.children.push({ left: left[index], right: right[index], result: undefined, name: index, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); commonHead++; } // separate common tail while ( commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems( array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext ) ) { index1 = len1 - 1 - commonTail; index2 = len2 - 1 - commonTail; const left = context.left as Array<unknown>; const right = context.right as Array<unknown>; if (context.children === undefined) { context.children = []; } context.children.push({ left: left[index1], right: right[index2], result: undefined, name: index2, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); commonTail++; } if (commonHead + commonTail === len1) { if (len1 === len2) { // arrays are identical context.result = undefined; context.stopped = true; return; } // trivial case, a block (1 or more consecutive items) was added const result = { _t: "a", }; for (index = commonHead; index < len2 - commonTail; index++) { result[index] = [array2[index]]; } context.result = result; context.stopped = true; return; } if (commonHead + commonTail === len2) { // trivial case, a block (1 or more consecutive items) was removed const result = { _t: "a", }; for (index = commonHead; index < len1 - commonTail; index++) { result[`_${index}`] = [ context.includePreviousValue ? array1[index] : null, 0, 0, ]; } context.result = result; context.stopped = true; return; } // reset hash cache delete matchContext.hashCache1; delete matchContext.hashCache2; // diff is not trivial, find the LCS (Longest Common Subsequence) let trimmed1 = array1.slice(commonHead, len1 - commonTail); let trimmed2 = array2.slice(commonHead, len2 - commonTail); let seq = lcs.get(trimmed1, trimmed2, matchItems as any, matchContext); let removedItems = []; const result = { _t: "a", }; for (index = commonHead; index < len1 - commonTail; index++) { if (seq.indices1.indexOf(index - commonHead) < 0) { // removed result[`_${index}`] = [ context.includePreviousValue ? array1[index] : null, 0, 0, ]; removedItems.push(index); } } const detectMove = true; let includeValueOnMove = true; let removedItemsLength = removedItems.length; for (index = commonHead; index < len2 - commonTail; index++) { let indexOnArray2 = seq.indices2.indexOf(index - commonHead); if (indexOnArray2 < 0) { // added, try to match with a removed item and register as position move let isMove = false; if (detectMove && removedItemsLength > 0) { for ( let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++ ) { index1 = removedItems[removeItemIndex1]; if ( matchItems( trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext ) ) { // store position move as: [originalValue, newPosition, ARRAY_MOVE] result[`_${index1}`].splice(1, 2, index, ARRAY_MOVE); if (!includeValueOnMove) { // don't include moved value on diff, to save bytes result[`_${index1}`][0] = ""; } index2 = index; if (context.children === undefined) { context.children = []; } const left = context.left as Array<unknown>; const right = context.right as Array<unknown>; context.children.push({ left: left[index1], right: right[index2], result: undefined, name: index2, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); removedItems.splice(removeItemIndex1, 1); isMove = true; break; } } } if (!isMove) { // added result[index] = [array2[index]]; } } else { // match, do inner diff index1 = seq.indices1[indexOnArray2] + commonHead; index2 = seq.indices2[indexOnArray2] + commonHead; if (context.children === undefined) { context.children = []; } const left = context.left as Array<unknown>; const right = context.right as Array<unknown>; context.children.push({ left: left[index1], right: right[index2], result: undefined, name: index2, includePreviousValue: context.includePreviousValue, objectHash: context.objectHash, matchByPosition: context.matchByPosition, stopped: false, }); } } context.result = result; context.stopped = true; } function arraysHaveMatchByRef( array1: Array<unknown>, array2: Array<unknown>, len1: number, len2: number ): boolean { for (let index1 = 0; index1 < len1; index1++) { let val1 = array1[index1]; for (let index2 = 0; index2 < len2; index2++) { let val2 = array2[index2]; if (index1 !== index2 && val1 === val2) { return true; } } } return false; } function matchItems( array1: Array<unknown>, array2: Array<unknown>, index1: number, index2: number, context: MatchContext ) { let value1 = array1[index1]; let value2 = array2[index2]; if (value1 === value2) { return true; } if (typeof value1 !== "object" || typeof value2 !== "object") { return false; } let objectHash = context.objectHash; if (!objectHash) { // no way to match objects was provided, try match by position return context.matchByPosition && index1 === index2; } let hash1; let hash2; if (typeof index1 === "number") { context.hashCache1 = context.hashCache1 || []; hash1 = context.hashCache1[index1]; if (typeof hash1 === "undefined") { context.hashCache1[index1] = hash1 = objectHash(value1 as object, index1); } } else { hash1 = objectHash(value1 as object); } if (typeof hash1 === "undefined") { return false; } if (typeof index2 === "number") { context.hashCache2 = context.hashCache2 || []; hash2 = context.hashCache2[index2]; if (typeof hash2 === "undefined") { context.hashCache2[index2] = hash2 = objectHash(value2 as object, index2); } } else { hash2 = objectHash(value2 as object); } if (typeof hash2 === "undefined") { return false; } return hash1 === hash2; }
the_stack
import { readFixtureJSON } from './helpers' import { DEVICE_MODELS, StreamDeck } from '../' import { DeviceModelId, OpenStreamDeckOptions } from '../models' import { DummyHID } from './hid' import { EncodeJPEGHelper } from '../models/base' function openStreamDeck(path: string, deviceModel: DeviceModelId, userOptions?: OpenStreamDeckOptions): StreamDeck { const encodeJpegMock: jest.MockedFunction<EncodeJPEGHelper> = jest.fn((_b: Buffer, _w: number, _h: number) => { throw new Error('Not implemented') }) const options: Required<OpenStreamDeckOptions> = { useOriginalKeyOrder: false, encodeJPEG: encodeJpegMock, ...userOptions, } const model = DEVICE_MODELS.find((m) => m.id === deviceModel) if (!model) { throw new Error('Stream Deck is of unexpected type.') } const device = new DummyHID(path, encodeJpegMock) return new model.class(device, options || {}) } function runForDevice(path: string, model: DeviceModelId): void { let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(path, model, { useOriginalKeyOrder: true }) }) test('checkValidKeyIndex', async () => { await expect(() => streamDeck.clearKey(-1)).rejects.toThrow() await expect(() => streamDeck.clearKey(15)).rejects.toThrow() }) test('clearKey', async () => { const mockedFn = ((streamDeck as any).fillImageRange = jest.fn(() => Promise.resolve())) await streamDeck.clearKey(2) expect(mockedFn).toHaveBeenCalledTimes(1) expect(mockedFn).toHaveBeenNthCalledWith(1, 2, expect.anything(), expect.anything()) }) test('clearPanel', async () => { const mockedFn = ((streamDeck as any).fillImageRange = jest.fn(() => Promise.resolve())) await streamDeck.clearPanel() const keyCount = streamDeck.NUM_KEYS expect(mockedFn).toHaveBeenCalledTimes(keyCount) for (let i = 0; i < keyCount; i++) { expect(mockedFn).toHaveBeenNthCalledWith(i + 1, i, expect.anything(), expect.anything()) } }) test('fillKeyBuffer throws on undersized buffers', async () => { const smallBuffer = Buffer.alloc(1) await expect(() => streamDeck.fillKeyBuffer(0, smallBuffer)).rejects.toThrow('Expected image buffer') }) test('forwards error events from the device', () => { const errorSpy = jest.fn() streamDeck.on('error', errorSpy) const device = getDevice() device.emit('error', new Error('Test')) expect(errorSpy).toHaveBeenCalledTimes(1) expect(errorSpy).toHaveBeenNthCalledWith(1, new Error('Test')) }) if (model !== DeviceModelId.XL && model !== DeviceModelId.ORIGINALV2 && model !== DeviceModelId.ORIGINALMK2) { test('setBrightness', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.setBrightness(100) await streamDeck.setBrightness(0) expect(device.sendFeatureReport).toHaveBeenCalledTimes(2) // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, Buffer.from([0x05, 0x55, 0xaa, 0xd1, 0x01, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(2, Buffer.from([0x05, 0x55, 0xaa, 0xd1, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) await expect(() => streamDeck.setBrightness(101)).rejects.toThrow() await expect(() => streamDeck.setBrightness(-1)).rejects.toThrow() }) test('resetToLogo', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.resetToLogo() expect(device.sendFeatureReport).toHaveBeenCalledTimes(1) // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, Buffer.from([0x0B, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) }) test('firmwareVersion', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { return Buffer.from([4, 85, 170, 212, 4, 49, 46, 48, 46, 49, 55, 48, 49, 51, 51, 0, 0]) } const firmware = await streamDeck.getFirmwareVersion() expect(firmware).toEqual('1.0.170133') }) test('serialNumber', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { return Buffer.from([3, 85, 170, 211, 3, 65, 76, 51, 55, 71, 49, 65, 48, 50, 56, 52, 48]) } const firmware = await streamDeck.getSerialNumber() expect(firmware).toEqual('AL37G1A02840') }) } else { test('setBrightness-jpeg', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.setBrightness(100) await streamDeck.setBrightness(0) expect(device.sendFeatureReport).toHaveBeenCalledTimes(2) const expected = Buffer.alloc(32, 0) expected[0] = 0x03 expected[1] = 0x08 expected[2] = 0x64 // 100% // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, expected) expected[2] = 0x00 // 100% expect(device.sendFeatureReport).toHaveBeenNthCalledWith(2, expected) await expect(() => streamDeck.setBrightness(101)).rejects.toThrow() await expect(() => streamDeck.setBrightness(-1)).rejects.toThrow() }) test('resetToLogo-jpeg', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.resetToLogo() expect(device.sendFeatureReport).toHaveBeenCalledTimes(1) // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, Buffer.from([0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) }) test('firmwareVersion-jpeg', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { // prettier-ignore return Buffer.from([ 5, 12, 254, 90, 239, 250, 49, 46, 48, 48, 46, 48, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) } const firmware = await streamDeck.getFirmwareVersion() expect(firmware).toEqual('1.00.004') }) test('serialNumber-jpeg', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { // prettier-ignore return Buffer.from([ 6, 12, 67, 76, 49, 56, 73, 49, 65, 48, 48, 57, 49, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) } const firmware = await streamDeck.getSerialNumber() expect(firmware).toEqual('CL18I1A00913') }) } test('close', async () => { const device = getDevice() device.close = jest.fn() await streamDeck.close() expect(device.close).toHaveBeenCalledTimes(1) }) test('fillPanelBuffer', async () => { const buffer = Buffer.alloc(streamDeck.NUM_KEYS * streamDeck.ICON_BYTES) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillPanelBuffer(buffer) expect(fillKeyBufferMock).toHaveBeenCalledTimes(streamDeck.NUM_KEYS) const stride = streamDeck.KEY_COLUMNS * streamDeck.ICON_SIZE * 3 for (let i = 0; i < streamDeck.NUM_KEYS; i++) { expect(fillKeyBufferMock).toHaveBeenCalledWith(i, expect.any(Buffer), { format: 'rgb', offset: expect.any(Number), stride, }) // Buffer has to be seperately as a deep equality check is really slow expect(fillKeyBufferMock.mock.calls[i][1]).toBe(buffer) } }) test('fillPanelBuffer with format', async () => { const buffer = Buffer.alloc(streamDeck.NUM_KEYS * streamDeck.ICON_PIXELS * 4) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillPanelBuffer(buffer, { format: 'bgra' }) expect(fillKeyBufferMock).toHaveBeenCalledTimes(streamDeck.NUM_KEYS) const stride = streamDeck.KEY_COLUMNS * streamDeck.ICON_SIZE * 4 for (let i = 0; i < streamDeck.NUM_KEYS; i++) { expect(fillKeyBufferMock).toHaveBeenCalledWith(i, expect.any(Buffer), { format: 'bgra', offset: expect.any(Number), stride, }) // Buffer has to be seperately as a deep equality check is really slow expect(fillKeyBufferMock.mock.calls[i][1]).toBe(buffer) } }) test('fillPanelBuffer bad format', async () => { const buffer = Buffer.alloc(streamDeck.NUM_KEYS * streamDeck.ICON_BYTES) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await expect(() => streamDeck.fillPanelBuffer(buffer, { format: 'abc' as any })).rejects.toThrow() expect(fillKeyBufferMock).toHaveBeenCalledTimes(0) }) test('fillPanelBuffer bad buffer', async () => { const buffer = Buffer.alloc(100) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await expect(() => streamDeck.fillPanelBuffer(buffer)).rejects.toThrow() expect(fillKeyBufferMock).toHaveBeenCalledTimes(0) }) test('fillKeyBuffer', async () => { const buffer = Buffer.alloc(streamDeck.ICON_BYTES) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillKeyBuffer(2, buffer) expect(fillKeyBufferMock).toHaveBeenCalledTimes(1) expect(fillKeyBufferMock).toHaveBeenCalledWith(2, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) // Buffer has to be seperately as a deep equality check is really slow expect(fillKeyBufferMock.mock.calls[0][1]).toBe(buffer) }) test('fillKeyBuffer with format', async () => { const buffer = Buffer.alloc(streamDeck.ICON_PIXELS * 4) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillKeyBuffer(2, buffer, { format: 'rgba' }) expect(fillKeyBufferMock).toHaveBeenCalledTimes(1) expect(fillKeyBufferMock).toHaveBeenCalledWith(2, expect.any(Buffer), { format: 'rgba', offset: 0, stride: streamDeck.ICON_SIZE * 4, }) // Buffer has to be seperately as a deep equality check is really slow expect(fillKeyBufferMock.mock.calls[0][1]).toBe(buffer) }) test('fillKeyBuffer bad key', async () => { const buffer = Buffer.alloc(streamDeck.ICON_BYTES) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await expect(() => streamDeck.fillKeyBuffer(-1, buffer)).rejects.toThrow() await expect(() => streamDeck.fillKeyBuffer(streamDeck.NUM_KEYS + 1, buffer)).rejects.toThrow() expect(fillKeyBufferMock).toHaveBeenCalledTimes(0) }) test('fillKeyBuffer bad format', async () => { const buffer = Buffer.alloc(streamDeck.ICON_BYTES) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await expect(() => streamDeck.fillKeyBuffer(1, buffer, { format: 'abc' as any })).rejects.toThrow() expect(fillKeyBufferMock).toHaveBeenCalledTimes(0) }) test('fillKeyBuffer bad buffer', async () => { const buffer = Buffer.alloc(100) const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await expect(() => streamDeck.fillKeyBuffer(2, buffer)).rejects.toThrow() expect(fillKeyBufferMock).toHaveBeenCalledTimes(0) }) test('fillKeyColor', async () => { const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillKeyColor(4, 123, 255, 86) expect(fillKeyBufferMock).toHaveBeenCalledTimes(1) expect(fillKeyBufferMock).toHaveBeenCalledWith(4, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) // console.log(JSON.stringify(bufferToIntArray(fillKeyBufferMock.mock.calls[0][1]))) expect(fillKeyBufferMock.mock.calls[0][1]).toEqual( readFixtureJSON(`fillColor-buffer-${streamDeck.ICON_SIZE}.json`) ) }) test('fillKeyColor bad rgb', async () => { await expect(() => streamDeck.fillKeyColor(0, 256, 0, 0)).rejects.toThrow() await expect(() => streamDeck.fillKeyColor(0, 0, 256, 0)).rejects.toThrow() await expect(() => streamDeck.fillKeyColor(0, 0, 0, 256)).rejects.toThrow() await expect(() => streamDeck.fillKeyColor(0, -1, 0, 0)).rejects.toThrow() }) test('fillKeyColor bad key', async () => { await expect(() => streamDeck.fillKeyColor(-1, 0, 0, 0)).rejects.toThrow() await expect(() => streamDeck.fillKeyColor(streamDeck.NUM_KEYS + 1, 0, 256, 0)).rejects.toThrow() }) } describe('StreamDeck', () => { const devicePath = 'some_random_path_here' let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(devicePath, DeviceModelId.ORIGINAL, { useOriginalKeyOrder: true }) }) test('constructor uses the provided devicePath', () => { const streamDeck2 = openStreamDeck(devicePath, DeviceModelId.ORIGINAL) const device = getDevice(streamDeck2) expect(device.path).toEqual(devicePath) expect(streamDeck2.MODEL).toEqual(DeviceModelId.ORIGINAL) }) runForDevice(devicePath, DeviceModelId.ORIGINAL) test('fillImage', async () => { const device = getDevice() const writeFn: jest.Mock<Promise<void>, [Buffer[]]> = (device.sendReports = jest.fn()) expect(writeFn).toHaveBeenCalledTimes(0) await streamDeck.fillKeyBuffer(0, readFixtureJSON('fillImage-sample-icon-72.json')) expect(writeFn.mock.calls).toMatchSnapshot() }) test('down and up events', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('up', upSpy) streamDeck.on('down', downSpy) const device = getDevice() // prettier-ignore device.emit('input', Buffer.from([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(1) expect(upSpy).toHaveBeenCalledTimes(1) expect(downSpy).toHaveBeenNthCalledWith(1, 0) expect(upSpy).toHaveBeenNthCalledWith(1, 0) }) test('down and up events: combined presses', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('down', downSpy) streamDeck.on('up', upSpy) const device = getDevice() // Press 1 // prettier-ignore device.emit('input', Buffer.from([0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // Press 8 // prettier-ignore device.emit('input', Buffer.from([0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(2) expect(upSpy).toHaveBeenCalledTimes(0) // Release both // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(2) expect(upSpy).toHaveBeenCalledTimes(2) expect(downSpy).toHaveBeenNthCalledWith(1, 1) expect(upSpy).toHaveBeenNthCalledWith(1, 1) expect(downSpy).toHaveBeenNthCalledWith(2, 8) expect(upSpy).toHaveBeenNthCalledWith(2, 8) }) }) describe('StreamDeck (Flipped keymap)', () => { const devicePath = 'some_random_path_here' let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(devicePath, DeviceModelId.ORIGINAL, { useOriginalKeyOrder: false }) }) test('fillKeyColor', async () => { const fillKeyBufferMock = ((streamDeck as any).fillImageRange = jest.fn()) await streamDeck.fillKeyColor(0, 1, 2, 3) await streamDeck.fillKeyColor(4, 1, 2, 3) await streamDeck.fillKeyColor(7, 1, 2, 3) await streamDeck.fillKeyColor(14, 1, 2, 3) expect(fillKeyBufferMock).toHaveBeenCalledTimes(4) expect(fillKeyBufferMock).toHaveBeenNthCalledWith(1, 4, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) expect(fillKeyBufferMock).toHaveBeenNthCalledWith(2, 0, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) expect(fillKeyBufferMock).toHaveBeenNthCalledWith(3, 7, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) expect(fillKeyBufferMock).toHaveBeenNthCalledWith(4, 10, expect.any(Buffer), { format: 'rgb', offset: 0, stride: streamDeck.ICON_SIZE * 3, }) }) test('down and up events', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('down', downSpy) streamDeck.on('up', upSpy) const device = getDevice() // prettier-ignore device.emit('input', Buffer.from([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(2) expect(upSpy).toHaveBeenCalledTimes(2) expect(downSpy).toHaveBeenNthCalledWith(1, 4) expect(upSpy).toHaveBeenNthCalledWith(1, 4) expect(downSpy).toHaveBeenNthCalledWith(2, 8) expect(upSpy).toHaveBeenNthCalledWith(2, 8) }) }) describe('StreamDeck Mini', () => { const devicePath = 'some_path_for_mini' let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(devicePath, DeviceModelId.MINI) }) test('constructor uses the provided devicePath', () => { const streamDeck2 = openStreamDeck(devicePath, DeviceModelId.MINI) const device = getDevice(streamDeck2) expect(device.path).toEqual(devicePath) expect(streamDeck2.MODEL).toEqual(DeviceModelId.MINI) }) runForDevice(devicePath, DeviceModelId.MINI) test('fillImage', async () => { const device = getDevice() const writeFn: jest.Mock<Promise<void>, [Buffer[]]> = (device.sendReports = jest.fn()) expect(writeFn).toHaveBeenCalledTimes(0) await streamDeck.fillKeyBuffer(0, readFixtureJSON('fillImage-sample-icon-80.json')) expect(writeFn.mock.calls).toMatchSnapshot() }) test('down and up events', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('down', downSpy) streamDeck.on('up', upSpy) const device = getDevice() // prettier-ignore device.emit('input', Buffer.from([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(1) expect(upSpy).toHaveBeenCalledTimes(1) expect(downSpy).toHaveBeenNthCalledWith(1, 0) expect(upSpy).toHaveBeenNthCalledWith(1, 0) }) }) describe('StreamDeck XL', () => { const devicePath = 'some_path_for_xl' let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(devicePath, DeviceModelId.XL) }) test('constructor uses the provided devicePath', () => { const streamDeck2 = openStreamDeck(devicePath, DeviceModelId.XL) const device = getDevice(streamDeck2) expect(device.path).toEqual(devicePath) expect(streamDeck2.MODEL).toEqual(DeviceModelId.XL) }) runForDevice(devicePath, DeviceModelId.XL) test('setBrightness', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.setBrightness(100) await streamDeck.setBrightness(0) expect(device.sendFeatureReport).toHaveBeenCalledTimes(2) const expected = Buffer.alloc(32, 0) expected[0] = 0x03 expected[1] = 0x08 expected[2] = 0x64 // 100% // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, expected) expected[2] = 0x00 // 100% expect(device.sendFeatureReport).toHaveBeenNthCalledWith(2, expected) await expect(() => streamDeck.setBrightness(101)).rejects.toThrow() await expect(() => streamDeck.setBrightness(-1)).rejects.toThrow() }) test('resetToLogo', async () => { const device = getDevice() device.sendFeatureReport = jest.fn() await streamDeck.resetToLogo() expect(device.sendFeatureReport).toHaveBeenCalledTimes(1) // prettier-ignore expect(device.sendFeatureReport).toHaveBeenNthCalledWith(1, Buffer.from([0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) }) test('firmwareVersion', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { // prettier-ignore return Buffer.from([ 5, 12, 254, 90, 239, 250, 49, 46, 48, 48, 46, 48, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) } const firmware = await streamDeck.getFirmwareVersion() expect(firmware).toEqual('1.00.004') }) test('serialNumber', async () => { const device = getDevice() device.getFeatureReport = async (): Promise<Buffer> => { // prettier-ignore return Buffer.from([ 6, 12, 67, 76, 49, 56, 73, 49, 65, 48, 48, 57, 49, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) } const firmware = await streamDeck.getSerialNumber() expect(firmware).toEqual('CL18I1A00913') }) test('fillImage', async () => { const device = getDevice() device.encodeJPEG.mockImplementationOnce(async (buffer: Buffer) => { const start = buffer.length / 8 return buffer.slice(start, start * 2) }) const writeFn: jest.Mock<Promise<void>, [Buffer[]]> = (device.sendReports = jest.fn()) expect(writeFn).toHaveBeenCalledTimes(0) await streamDeck.fillKeyBuffer(0, readFixtureJSON('fillImage-sample-icon-96.json')) expect(writeFn.mock.calls).toMatchSnapshot() }) test('down and up events', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('down', downSpy) streamDeck.on('up', upSpy) const device = getDevice() // prettier-ignore device.emit('input', Buffer.from([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(1) expect(upSpy).toHaveBeenCalledTimes(1) expect(downSpy).toHaveBeenNthCalledWith(1, 0) expect(upSpy).toHaveBeenNthCalledWith(1, 0) }) }) describe('StreamDeck Original V2', () => { const devicePath = 'some_path_for_v2' let streamDeck: StreamDeck function getDevice(sd?: StreamDeck): DummyHID { return (sd || (streamDeck as any)).device } beforeEach(() => { streamDeck = openStreamDeck(devicePath, DeviceModelId.ORIGINALV2) }) test('constructor uses the provided devicePath', () => { const streamDeck2 = openStreamDeck(devicePath, DeviceModelId.ORIGINALV2) const device = getDevice(streamDeck2) expect(device.path).toEqual(devicePath) expect(streamDeck2.MODEL).toEqual(DeviceModelId.ORIGINALV2) }) runForDevice(devicePath, DeviceModelId.ORIGINALV2) test('fillImage', async () => { const device = getDevice() device.encodeJPEG.mockImplementationOnce(async (buffer: Buffer) => { const start = buffer.length / 8 return buffer.slice(start, start * 2) }) const writeFn: jest.Mock<Promise<void>, [Buffer[]]> = (device.sendReports = jest.fn()) expect(writeFn).toHaveBeenCalledTimes(0) await streamDeck.fillKeyBuffer(0, readFixtureJSON('fillImage-sample-icon-72.json')) expect(writeFn.mock.calls).toMatchSnapshot() }) test('down and up events', () => { const downSpy = jest.fn() const upSpy = jest.fn() streamDeck.on('down', downSpy) streamDeck.on('up', upSpy) const device = getDevice() // prettier-ignore device.emit('input', Buffer.from([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) // prettier-ignore device.emit('input', Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) expect(downSpy).toHaveBeenCalledTimes(1) expect(upSpy).toHaveBeenCalledTimes(1) expect(downSpy).toHaveBeenNthCalledWith(1, 0) expect(upSpy).toHaveBeenNthCalledWith(1, 0) }) })
the_stack
import { AddItemsEventData, AddItemsResultSummary, UserStorage, ShareKeyType, Notification, NotificationType, NotificationSubscribeEventData, InvitationStatus, SpaceUser } from '@spacehq/sdk'; import { tryParsePublicKey } from '@spacehq/utils'; import { expect, use } from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as chaiSubset from 'chai-subset'; import { TestsDefaultTimeout, TestStorageConfig } from './fixtures/configs'; import { authenticateAnonymousUser } from './helpers/userHelper'; use(chaiAsPromised.default); use(chaiSubset.default); async function acceptNotification(inviteeStorage: UserStorage, notification: Notification, inviter: SpaceUser) { // accept the notification await inviteeStorage.handleFileInvitation(notification.id, true); // verify notification status is now accepted const updatedNotification = await inviteeStorage.getNotifications(); expect(updatedNotification.notifications, 'updatedNotification').to.containSubset([{ id: notification.id, relatedObject: { status: InvitationStatus.ACCEPTED, }, }]); // verify get recently shared contains accepted file const recentlyAccepted = await inviteeStorage.getFilesSharedWithMe(); expect(recentlyAccepted.files).not.to.be.empty; expect(recentlyAccepted.files[0], 'recentlyAcceptedFiles[0]').to.containSubset({ sharedBy: Buffer.from(inviter.identity.public.pubKey).toString('hex'), entry: { name: 'top.txt', path: '/top.txt', }, }); } const uploadTxtContent = async ( storage: UserStorage, txtContent = 'Some manual text should be in the file', fileName = 'top.txt'): Promise<{ txtContent: string; response: AddItemsEventData; }> => { const uploadResponse = await storage.addItems({ bucket: 'personal', files: [ { path: fileName, data: txtContent, mimeType: 'plain/text', }, ], }); const response = await new Promise<AddItemsEventData>((resolve) => { uploadResponse.once('done', resolve); }); return { txtContent, response, }; }; describe('Users sharing data', () => { it('users can share, accept and view shared files', async () => { const { user: user1 } = await authenticateAnonymousUser(); const { user: user2 } = await authenticateAnonymousUser(); const { user: user3 } = await authenticateAnonymousUser(); const user1Pk = Buffer.from(user1.identity.public.pubKey).toString('hex'); const user2Pk = Buffer.from(user2.identity.public.pubKey).toString('hex'); const user3Pk = Buffer.from(user3.identity.public.pubKey).toString('hex'); const storage1 = new UserStorage(user1, TestStorageConfig); await storage1.initMailbox(); await uploadTxtContent(storage1); const storage2 = new UserStorage(user2, TestStorageConfig); await storage2.initMailbox(); // share with new user const shareResult = await storage1.shareViaPublicKey({ publicKeys: [{ id: 'new-space-user@fleek.co', pk: user2Pk, }], paths: [{ bucket: 'personal', path: '/top.txt', }], }); const ld = await storage1.listDirectory({ bucket: 'personal', path: '' }); expect(ld.items[0].members[0].publicKey).to.equal(user2Pk); expect(shareResult.publicKeys).not.to.be.empty; expect(shareResult.publicKeys[0].type).to.equal(ShareKeyType.Existing); expect(shareResult.publicKeys[0].pk).not.to.be.empty; // verify user1's recently shared with is updated const recentlySharedWith = await storage1.getRecentlySharedWith(); expect(recentlySharedWith.members, 'recentlySharedwith.members').to.containSubset([{ publicKey: user2.identity.public.toString(), // ... // verify address and role too }]); const ts = Date.now(); await storage2.setNotificationsLastSeenAt(ts); // verify user2 get notification const received = await storage2.getNotifications(); expect(received.notifications[0]).not.to.be.null; expect(received.notifications[0].from).to.equal(tryParsePublicKey(user1Pk).toString()); expect(received.notifications[0].to).to.equal(tryParsePublicKey(user2Pk).toString()); expect(received.notifications[0].id).not.to.be.null; expect(received.notifications[0].createdAt).not.to.be.null; expect(received.notifications[0].type).to.equal(NotificationType.INVITATION); expect(received.notifications[0].relatedObject).not.to.be.null; expect(received.notifications[0].relatedObject?.inviteePublicKey).to.equal(user2.identity.public.toString()); expect(received.notifications[0].relatedObject?.inviterPublicKey).to.equal(user1Pk); expect(received.notifications[0].relatedObject?.itemPaths[0].bucket).to.equal('personal'); expect(received.notifications[0].relatedObject?.itemPaths[0].path).to.equal('/top.txt'); // console.log('dbid: ', received.notifications[0].relatedObject?.itemPaths[0].dbId); expect(received.notifications[0].relatedObject?.itemPaths[0].dbId).not.to.be.null; expect(received.notifications[0].relatedObject?.itemPaths[0].uuid).to.equal(ld.items[0].uuid); expect(received.notifications[0].relatedObject?.itemPaths[0].bucketKey).not.to.be.null; expect(received.notifications[0].relatedObject?.keys[0]).not.to.be.null; expect(received.lastSeenAt).to.equal(ts); // accept the notification await acceptNotification(storage2, received.notifications[0], user1); // reshare file const storage3 = new UserStorage(user3, TestStorageConfig); await storage3.initMailbox(); const share2Result = await storage2.shareViaPublicKey({ publicKeys: [{ id: 'new-space-user-2@fleek.co', pk: user3Pk, }], paths: [{ bucket: 'personal', path: '/top.txt', dbId: received.notifications[0].relatedObject?.itemPaths[0].dbId, }], }); const secondReceivedNotifs = await storage3.getNotifications(); // accept the notification await acceptNotification(storage3, secondReceivedNotifs.notifications[0], user2); }).timeout(TestsDefaultTimeout); it('should allow invited users to make file publicly accessible', async () => { const { user: user1 } = await authenticateAnonymousUser(); const { user: user2 } = await authenticateAnonymousUser(); const user2Pk = Buffer.from(user2.identity.public.pubKey).toString('hex'); const storage1 = new UserStorage(user1, TestStorageConfig); await storage1.initMailbox(); const storage2 = new UserStorage(user2, TestStorageConfig); await storage2.initMailbox(); const { txtContent } = await uploadTxtContent(storage1); await storage1.shareViaPublicKey({ publicKeys: [{ id: 'new-space-user@fleek.co', pk: user2Pk, }], paths: [{ bucket: 'personal', path: '/top.txt', }], }); const received = await storage2.getNotifications(); await acceptNotification(storage2, received.notifications[0], user1); // console.log('Accepted notification', { notif: received.notifications[0] }); // make shared file public await storage2.setFilePublicAccess({ bucket: 'personal', path: '/top.txt', dbId: received.notifications[0].relatedObject?.itemPaths[0].dbId, allowAccess: true, }); // console.log('Made file publicly accessible'); // verify anonymous user can access file const { user: anonymousUser } = await authenticateAnonymousUser(); const anonymousStorage = new UserStorage(anonymousUser, TestStorageConfig); // console.log('Opening public file by uuid'); const fileResponse = await anonymousStorage.openFileByUuid({ uuid: received.notifications[0].relatedObject?.itemPaths[0].uuid || '', }); const actualTxtContent = await fileResponse.consumeStream(); expect(new TextDecoder('utf8').decode(actualTxtContent)).to.equal(txtContent); }).timeout(TestsDefaultTimeout); it('users can receive sharing notifications subscription events', async () => { const { user: user1 } = await authenticateAnonymousUser(); const { user: user2 } = await authenticateAnonymousUser(); const user1Pk = Buffer.from(user1.identity.public.pubKey).toString('hex'); const user2Pk = Buffer.from(user2.identity.public.pubKey).toString('hex'); const txtContent = 'Some manual text should be in the file'; const storage1 = new UserStorage(user1, TestStorageConfig); const uploadResponse = await storage1.addItems({ bucket: 'personal', files: [ { path: 'top.txt', data: txtContent, mimeType: 'plain/text', }, ], }); await new Promise<AddItemsEventData>((resolve) => { uploadResponse.once('done', resolve); }); await storage1.initMailbox(); const storage2 = new UserStorage(user2, TestStorageConfig); await storage2.initMailbox(); const ee = await storage2.notificationSubscribe(); const eventData = new Promise<NotificationSubscribeEventData>((resolve) => { ee.once('data', (d:NotificationSubscribeEventData) => resolve(d)); }); // share with new user const shareResult = await storage1.shareViaPublicKey({ publicKeys: [{ id: 'new-space-user@fleek.co', pk: user2Pk, }], paths: [{ bucket: 'personal', path: '/top.txt', }], }); const data = await eventData; expect(shareResult.publicKeys).not.to.be.empty; expect(shareResult.publicKeys[0].type).to.equal(ShareKeyType.Existing); expect(shareResult.publicKeys[0].pk).not.to.be.empty; expect(data.notification).not.to.be.null; expect(data.notification.from).to.equal(tryParsePublicKey(user1Pk).toString()); expect(data.notification.to).to.equal(tryParsePublicKey(user2Pk).toString()); expect(data.notification.id).not.to.be.null; expect(data.notification.createdAt).not.to.be.null; expect(data.notification.type).to.equal(NotificationType.INVITATION); expect(data.notification.relatedObject).not.to.be.null; expect(data.notification.relatedObject?.inviteePublicKey).to.equal(user2.identity.public.toString()); expect(data.notification.relatedObject?.inviterPublicKey).to.equal(user1Pk); expect(data.notification.relatedObject?.itemPaths[0].bucket).to.equal('personal'); expect(data.notification.relatedObject?.itemPaths[0].path).to.equal('/top.txt'); expect(data.notification.relatedObject?.itemPaths[0].dbId).not.to.be.null; expect(data.notification.relatedObject?.itemPaths[0].bucketKey).not.to.be.null; expect(data.notification.relatedObject?.keys[0]).not.to.be.null; }).timeout(TestsDefaultTimeout); it('sharing empty pk (temp key) should work', async () => { const { user: user1 } = await authenticateAnonymousUser(); const user1Pk = Buffer.from(user1.identity.public.pubKey).toString('hex'); const txtContent = 'Some manual text should be in the file'; const storage1 = new UserStorage(user1, TestStorageConfig); await storage1.addItems({ bucket: 'personal', files: [ { path: 'top.txt', data: txtContent, mimeType: 'plain/text', }, ], }); await storage1.initMailbox(); // share with new user const shareResult = await storage1.shareViaPublicKey({ publicKeys: [{ id: 'new-space-user@fleek.co', pk: '', }], paths: [{ bucket: 'personal', path: '/top.txt', }], }); expect(shareResult.publicKeys).not.to.be.empty; expect(shareResult.publicKeys[0].type).to.equal(ShareKeyType.Temp); expect(shareResult.publicKeys[0].pk).not.to.be.empty; // authenticate new user to sync notifications const { user: user2 } = await authenticateAnonymousUser(); const storage2 = new UserStorage(user2, TestStorageConfig); await storage2.syncFromTempKey(shareResult.publicKeys[0].tempKey || ''); await new Promise((resolve) => setTimeout(resolve, 1000)); // verify notification now contains invite to `top.txt` const received = await storage2.getNotifications(); expect(received.notifications).to.containSubset([{ relatedObject: { inviterPublicKey: Buffer.from(user1.identity.public.pubKey).toString('hex'), inviteePublicKey: user2.identity.public.toString(), }, type: NotificationType.INVITATION, }]); await acceptNotification(storage2, received.notifications[0], user1); }).timeout(TestsDefaultTimeout); });
the_stack
/// <reference path="../bws/packer/API.ts" /> /** * <p> A set of programs that calculate the best fit for boxes on a pallet migrated from language C. </p> * * <ul> * <li> Original Boxologic: https://github.com/exad/boxologic </li> * </ul> * * @author Bill Knechtel, <br> * Migrated and Refactored by Jeongho Nam <http://samchon.org> */ namespace boxologic { /** * <p> A facade class of boxologic. </p> * * <p> The Boxologic class dudcts the best solution of packing boxes to a pallet. </p> * * <ul> * <li> Reference: https://github.com/exad/boxologic </li> * </ul> * * @author Bill Knechtel, <br> * Migrated and Refactored by Jeongho Nam <http://samchon.org> */ export class Boxologic { /* =========================================================== PARAMETRIC DATA =========================================================== */ /** * A Wrapper to pack instances. */ private wrapper: bws.packer.Wrapper; /** * Instances trying to put into the wrapper. */ private instanceArray: bws.packer.InstanceArray; /** * Instances failed to pack by overloading. */ private leftInstances: bws.packer.InstanceArray; /* =========================================================== BACKGROUND DATA - STRUCTURES - VARIABLES FOR ITERATION - FLAGS FOR TERMINATING ITERATION - THE BEST ============================================================== STRUCTURES ----------------------------------------------------------- */ /** * A pallet containing {@link Box boxes}. * * @see Wrapper */ private pallet: Pallet; /** * Boxes, trying to pack into the {@link pallet}. */ private box_array: std.Vector<Box>; /** * Sum of all boxes' volume. */ private total_box_volume: number; /** * <p> All different lengths of {@link box_array all box} dimensions along with evaluation values. </p> * * <p> In other word, the <i>layer_map</i> stores those entries; each {@link Boxbox}'s length on each * axis as a <i>key</i> (width, height or length) and evaluation value as a <i>value</i>. The evaluation * value means sum of minimum gaps between the key and other {@link Box boxes}' width, height and length * </p> * * <code> FOR i := 0 to box_array.size() WHILE key IN width, length and height in box_array[i] BEGIN value := 0 FOR j to box_array.size() value += min ( abs(key - box_array[j].width), abs(key - box_array[j].height), abs(key - box_array[j].length) ) layer_map.insert({key, value}); END * </code> * * <ul> * <li> key: A dimension value </li> * <li> value: Evaluation weight value for the corresponding key. </li> * </ul> */ private layer_map: std.HashMap<number, number>; /** * {@link List} of {@link Scrapped} instances, edges of layers under construction. * * @see Scrapped * @see scrap_min_z */ private scrap_list: std.List<Scrap>; /** * The topology {@link Scrapped}, the edge of the current layer under construction. * * @see Scrapped * @see scrap_list */ private scrap_min_z: std.ListIterator<Scrap>; /* ----------------------------------------------------------- VARIABLES FOR ITERATIONS - BOX - LAYER - REMAINS & PACKED - FINDER & ANALYZER -------------------------------------------------------------- // BOX /////////////////////////////////////////////////////////// */ /** * Index of the current {@link box}. */ private cboxi: number; /** * Candidate {@link Box.layout_width layout_width} of the {@link cboxi current box}. */ private cbox_layout_width: number; /** * Candidate {@link Box.layout_height layout_height} of the {@link cboxi current box}. */ private cbox_layout_height: number; /** * Candidate {@link Box.layout_length layout_length} of the {@link cboxi current box}. */ private cbox_layout_length: number; ////////////////////////////////////////////////////////////// // LAYER ////////////////////////////////////////////////////////////// /** * Current layer's key on iteration. */ private layer_thickness: number; /** * Previous layer's key had iterated. */ private pre_layer: number; /** * Key of the unevened layer in the current packing layer. */ private layer_in_layer: number; /** * Little Z, gotten from {@link Scrapped.cumz cumz} in {@link min_scrap_z} */ private lilz: number; ////////////////////////////////////////////////////////////// // REMAINS & PACKED ////////////////////////////////////////////////////////////// /** * Remained (unfilled) {@link Pallet.layout_height layout_height} of the {@link pallet}. */ private remain_layout_height: number; /** * Remained (unfilled) {@link Pallet.layout_length layout_length} of the {@link pallet}. */ private remain_layout_length: number; /** * Packed (filled) {@link Pallet.layout_height layout_height} of the {@link pallet}. */ private packed_layout_height: number; /** * Packed {@link Pallet.vo1lume volume} of the {@lnk pallet}. */ private packed_volume: number; ////////////////////////////////////////////////////////////// // FINDER & ANALYZER ////////////////////////////////////////////////////////////// private boxi: number; private bboxi: number; private boxx: number; private boxy: number; private boxz: number; private bboxx: number; private bboxy: number; private bboxz: number; private bfx: number; private bfy: number; private bfz: number; private bbfx: number; private bbfy: number; private bbfz: number; /* ----------------------------------------------------------- FLAGS FOR TERMINATING ITERATION ----------------------------------------------------------- */ /** * <p> Whether the packing is on progress. </p> * * <p> The {@link packing} is a flag variable for terminating iterations in * {@link iterate_orientations iterate_orientations()}, who deducts the best packing solution. </p> */ private packing: boolean; /** * Whether packing a layer is done. */ private layer_done: boolean; /** * Whether the current packing layer is evened. */ private evened: boolean; /** * Whether the best solution is deducted. */ private packing_best: boolean; /** * Whether the utilization degree of pallet space is 100%. */ private hundred_percent: boolean; /** * The best orientation of the pallet, which can deduct the {@link best_solution_volume}. */ private best_orientation: number; /** * The best layer, which can deduct the {@link best_solution_volume}. */ private best_layer: number; /** * The best volume, fit the best utilization degree of the pallet space. */ private best_solution_volume: number; /* =========================================================== CONSTRUCTORS - CONSTRUCTOR - ENCODER & DECODER ============================================================== CONSTRUCTOR ----------------------------------------------------------- */ /** * Construct from a wrapper and instances. * * @param wrapper A Wrapper to pack instances. * @param instanceArray Instances trying to put into the wrapper. */ public constructor(wrapper: bws.packer.Wrapper, instanceArray: bws.packer.InstanceArray) { this.wrapper = wrapper; this.instanceArray = instanceArray; this.leftInstances = new bws.packer.InstanceArray(); } /* ----------------------------------------------------------- ENCODER & DECODER ----------------------------------------------------------- */ /** * <p> Encode data </p> * * <p> Encodes {@link bws.packer Packer}'s data to be suitable for the * {@link boxologic Boxologic}'s parametric data. </p> */ private encode(): void { ///////////////////////////////////// // STRUCTURES ///////////////////////////////////// this.pallet = new Pallet(this.wrapper); this.box_array = new std.Vector<Box>(); this.total_box_volume = 0.0; this.layer_map = new std.HashMap<number, number>(); this.scrap_list = new std.List<Scrap>(); // CHILDREN ELEMENTS - BOX this.box_array.assign(this.instanceArray.size(), null); for (let i: number = 0; i < this.instanceArray.size(); i++) { let box: Box = new Box(this.instanceArray.at(i)); this.total_box_volume += box.volume; this.box_array.set(i, box); } // SCRAP_LIST this.scrap_list.push_back(new Scrap()); ///////////////////////////////////// // BEST VARIABLES ///////////////////////////////////// this.best_solution_volume = 0.0; this.packing_best = false; this.hundred_percent = false; } /** * <p> Decode data </p> * * <p> Decodes the Boxologic's optimization result data to be suitable for the Packer's own. </p> */ private decode(): void { this.wrapper.clear(); this.leftInstances.clear(); this.inspect_validity(); for (let i: number = 0; i < this.box_array.size(); i++) { let instance: bws.packer.Instance = this.instanceArray.at(i); let box: Box = this.box_array.at(i); if (box.is_packed == true) { let wrap: bws.packer.Wrap = new bws.packer.Wrap ( this.wrapper, instance, box.cox, box.coy, box.coz ); wrap.estimateOrientation(box.layout_width, box.layout_height, box.layout_length); if (this.wrapper.getThickness() != 0) wrap.setPosition ( wrap.getX() + this.wrapper.getThickness(), wrap.getY() + this.wrapper.getThickness(), wrap.getZ() + this.wrapper.getThickness() ); this.wrapper.push_back(wrap); } else { // NOT WRAPED INSTANCES BY LACK OF VOLUME this.leftInstances.push_back(instance); } } } private inspect_validity(): void { //let boxes: std.Vector<Box> = new std.Vector<Box>(); // CANDIDATES TO BE PACKED //for (let i: number = 0; i < this.box_array.size(); i++) //{ // let box: Box = this.box_array.at(i); // if (box.is_packed == false) // continue; // if (box.cox < 0 || box.cox + box.layout_width > this.pallet.layout_width || // box.coy < 0 || box.coy + box.layout_height > this.pallet.layout_height || // box.coz < 0 || box.coz + box.layout_length > this.pallet.layout_length) // { // // NOT PAKCED OR BE PLACED OUT OF THE PALLET // box.is_packed = false; // continue; // } // boxes.push(box); //} //// FIND OVERLAPS //let is_overlapped: boolean = false; //for (let i: number = 0; i < boxes.size(); i++) // for (let j: number = 0; j < boxes.size(); j++) // if (i == j) // continue; // else if (boxes[i].hit_test(boxes[j])) // { // is_overlapped = true; // boxes[i].overlapped_boxes.insert(boxes[j]); // boxes[j].overlapped_boxes.insert(boxes[i]); // } //if (is_overlapped == false) // return; //// SORT OVERLAPS //for (let i: number = 0; i < 2; i++) // std.sort(boxes.begin(), boxes.end(), // function (x: Box, y: Box): boolean // { // if (x.overlapped_boxes.size() == y.overlapped_boxes.size()) // return x.volume > y.volume; // else // return x.overlapped_boxes.size() > y.overlapped_boxes.size(); // } // ); //for (let i: number = 0; i < boxes.size(); i++) // if (boxes[i].overlapped_boxes.empty() == true) // continue; // else // { // // ERASE FROM NEIGHBORS // let overlapped_boxes = boxes[i].overlapped_boxes; // for (let it = overlapped_boxes.begin(); !it.equals(overlapped_boxes.end()); it = it.next()) // boxes[i].overlapped_boxes.erase(boxes[i]); // // ERASE FROM PALLET // boxes[i].is_packed = false; // } } /* =========================================================== MAIN PROCEDURES - OPERATORS - CHECKERS - GETTERS - REPORTERS ============================================================== OPERATORS ------------------------------------------------------------ */ /** * <p> Pack instances to the {@link wrapper}. </p> * * <p> The {@link Boxologic.pack} is an adaptor method between {@link bws.packer Packer} and * {@link boxologic}. It encodes data from {@link bws.packer Packer}, deducts the best packing * solution decodes the optimization result and returns it. </p> * * <p> The optimization result is returned as a {@link Pair} like below: </p> * <ul> * <li> first: The {@link wrapper} with packed instances. </li> * <li> second: {@link leftInstances Left instances failed to pack} by overloading. </li> * </ul> * * @return A pair of {@link wrapper} with packed instances and * {@link leftInstances instances failed to pack} by overloading. */ public pack(): std.Pair<bws.packer.Wrapper, bws.packer.InstanceArray> { this.encode(); this.iterate_orientations(); this.report_results(); this.decode(); return new std.Pair<bws.packer.Wrapper, bws.packer.InstanceArray>(this.wrapper, this.leftInstances); } /** * <p> Execute iterations by calling proper functions. </p> * * <p> Iterations are done and parameters of the best solution are found. </p> */ private iterate_orientations(): void { for (let orientation: number = 1; orientation <= 6; orientation++) { this.pallet.set_orientation(orientation); // CONSTRUCT LAYERS this.construct_layers(); // ITERATION IN LAYERS for (let it = this.layer_map.begin(); !it.equals(this.layer_map.end()); it = it.next()) { // BEGINS PACKING this.iterate_layer(it.first); if (this.packed_volume > this.best_solution_volume) { // NEW VOLUME IS THE BEST this.best_solution_volume = this.packed_volume; this.best_orientation = orientation; this.best_layer = it.first; } if (this.hundred_percent) break; // SUCCESS TO UTILIZE ALL } if (this.hundred_percent) break; // SUCCESS TO UTILIZE ALL // IF THE PALLET IS REGULAR CUBE, if (this.pallet.width == this.pallet.height && this.pallet.height == this.pallet.length) orientation = 6; // DON'T ITERATE ALL ORIENTATIONS } } /** * Iterate a layer. * * @param thickness Thickness of the iterating layer. */ private iterate_layer(thickness: number): void { // INIT PACKED this.packing = true; this.packed_volume = 0.0; this.packed_layout_height = 0; this.layer_thickness = thickness; // SET REMAINS FROM PALLET'S DIMENSIONS this.remain_layout_height = this.pallet.layout_height; this.remain_layout_length = this.pallet.layout_length; // UNPACK ALL BOXES for (let i: number = 0; i < this.box_array.size(); i++) this.box_array.at(i).is_packed = false; do { // INIT VARS OF LAYER ITERATION this.layer_in_layer = 0; this.layer_done = false; // PACK_LAYER AND POST-PROCESS this.pack_layer(); this.packed_layout_height += this.layer_thickness; this.remain_layout_height = this.pallet.layout_height - this.packed_layout_height; if (this.layer_in_layer != 0) { // STORE ORDINARY PACKING VARS let pre_packed_y: number = this.packed_layout_height; let pre_remain_py: number = this.remain_layout_height; // STORE CAUCLATED RESULTS this.remain_layout_height = this.layer_thickness - this.pre_layer; this.packed_layout_height -= this.layer_thickness + this.pre_layer; this.remain_layout_length = this.lilz; this.layer_thickness = this.layer_in_layer; // ITERATION IS NOT FINISHED YET this.layer_done = false; // RE-CALL PACK_LAYER this.pack_layer(); // REVERT TO THE STORED ORDINARIES this.packed_layout_height = pre_packed_y; this.remain_layout_height = pre_remain_py; this.remain_layout_length = this.pallet.layout_length; } // CALL FIND_LAYER this.find_layer(this.remain_layout_height); } while (this.packing); } /** * <p> Construct layers. </p> * * <p> Creates all possible layer heights by giving a weight value to each of them. </p> */ private construct_layers(): void { this.layer_map.clear(); for (let i: number = 0; i < this.box_array.size(); i++) { let box: Box = this.box_array.at(i); for (let j: number = 1; j <= 3; j++) { let ex_dim: number; // STANDARD LENGTH ON THE DIMENSION let dimen2: number; // THE SECOND, LENGTH ON A RESIDUAL DIMENSION let dimen3: number; // THE THIRD, LENGTH ON A RESIDUAL DIMENSION let layer_eval: number = 0; // SUM OF LAYERS (height) // FETCH STANDARD DIMENSIONS FROM EACH AXIS switch (j) { case 1: ex_dim = box.width; dimen2 = box.height; dimen3 = box.length; break; case 2: ex_dim = box.height; dimen2 = box.width; dimen3 = box.length; break; case 3: ex_dim = box.length; dimen2 = box.width; dimen3 = box.height; break; } // A DIMENSIONAL LENGTH IS GREATER THAN THE PALLET ? if (ex_dim > this.pallet.layout_height || ( (dimen2 > this.pallet.layout_width || dimen3 > this.pallet.layout_length) && (dimen3 > this.pallet.layout_width || dimen2 > this.pallet.layout_length) )) { // A DIMENSIONAL LENGTH IS GREATER THAN THE PALLET continue; } // WHEN A DUPLICATED LAYER EXISTS, SKIPS if (this.layer_map.has(ex_dim) == true) continue; // ABOUT ALL BOXES, FIND THE MINIMUM LENGTH OF GAP ~, // STACK ON THE CURRENT LAYER (ADD ON TO THE LAYER_EVAL) for (let k: number = 0; k < this.box_array.size(); k++) { // SAME INSTANCE WITH THE SAME INDEX if (i == k) continue; let my_box: Box = this.box_array.at(k); let dim_diff: number = Math.min ( Math.abs(ex_dim - my_box.width), Math.abs(ex_dim - my_box.height), Math.abs(ex_dim - my_box.length) ); layer_eval += dim_diff; } // RECORD THE SUM this.layer_map.set(ex_dim, layer_eval); } } } /** * <p> Packs the boxes found and arranges all variables and records properly. </p> * * <p> Update the linked list and the Boxlist[] array as a box is packed. </p> */ private pack_layer(): void { if (this.layer_thickness == 0) { this.packing = false; return; } else if (this.scrap_list.empty() == true) return; let lenx: number; let lenz: number; let lpz: number; this.scrap_list.begin().value.cumx = this.pallet.layout_width; this.scrap_list.begin().value.cumz = 0; while (true) { // INIT SCRAP_MIN_Z this.find_smallest_z(); // FETCH LEFT AND RIGHT OF SCRAP_MIN_Z let prev = this.scrap_min_z.prev(); let next = this.scrap_min_z.next(); if (this.scrap_min_z.equals(this.scrap_list.end())) { break; } if (prev.equals(this.scrap_list.end()) && next.equals(this.scrap_list.end())) { ///////////////////////////////////////////////////////// // NO LEFT AND RIGHT ///////////////////////////////////////////////////////// //*** SITUATION-1: NO BOXES ON THE RIGHT AND LEFT SIDES *** lenx = this.scrap_min_z.value.cumx; lpz = this.remain_layout_length - this.scrap_min_z.value.cumz; // CALL FIND_BOX AND CHECK_FOUND this.find_box(lenx, this.layer_thickness, this.remain_layout_height, lpz, lpz); this.check_found(); // BREAK ? if (this.layer_done) break; if (this.evened) continue; // UPDATE CURRENT BOX let box: Box = this.box_array.at(this.cboxi); box.cox = 0; box.coy = this.packed_layout_height; box.coz = this.scrap_min_z.value.cumz; if (this.cbox_layout_width == this.scrap_min_z.value.cumx) { // CUMULATE this.scrap_min_z.value.cumz += this.cbox_layout_length; } else { // CREATE A NEW NODE AND IT'S THE NEW MIN_Z // ORDINARY MIN_Z WILL BE SHIFTED TO THE RIGHT let scrap: Scrap = new Scrap ( this.cbox_layout_width, this.scrap_min_z.value.cumz + this.cbox_layout_length ); // SHIFTS ORDINARY MIN_Z TO RIGHT // AND THE NEW NODE'S ITERATOR IS THE NEW MIN_Z FROM NOW ON this.scrap_min_z = this.scrap_list.insert(this.scrap_min_z, scrap); } } else if (prev.equals(this.scrap_list.end())) { ///////////////////////////////////////////////////////// // NO LEFT, BUT RIGHT ///////////////////////////////////////////////////////// //*** SITUATION-2: NO BOXES ON THE LEFT SIDE *** lenx = this.scrap_min_z.value.cumx; lenz = next.value.cumz - this.scrap_min_z.value.cumz; lpz = this.remain_layout_length - this.scrap_min_z.value.cumz; // CALL FIND_BOX AND CHECK_FOUND this.find_box(lenx, this.layer_thickness, this.remain_layout_height, lenz, lpz); this.check_found(); // BREAK ? if (this.layer_done) break; if (this.evened) continue; // RE-FETCH LEFT AND RIGHT next = this.scrap_min_z.next(); // UPDATE CURRENT BOX let box: Box = this.box_array.at(this.cboxi); box.coy = this.packed_layout_height; box.coz = this.scrap_min_z.value.cumz; if (this.cbox_layout_width == this.scrap_min_z.value.cumx) { box.cox = 0; if (this.scrap_min_z.value.cumz + this.cbox_layout_length == next.value.cumz) { // RIGHT IS THE NEW MIN_Z // ORDINARY MIN_Z WILL BE ERASED this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z); } else { // CUMULATE this.scrap_min_z.value.cumz += this.cbox_layout_length; } } else { box.cox = this.scrap_min_z.value.cumx - this.cbox_layout_width; if (this.scrap_min_z.value.cumz + this.cbox_layout_length == next.value.cumz) { // DE-CUMULATE this.scrap_min_z.value.cumx -= this.cbox_layout_width; } else { // UPDATE MIN_Z this.scrap_min_z.value.cumx -= this.cbox_layout_width; // CREATE A NEW NODE BETWEEN MIN_Z AND RIGHT let scrap: Scrap = new Scrap ( this.scrap_min_z.value.cumx, this.scrap_min_z.value.cumz + this.cbox_layout_length ); this.scrap_list.insert(next, scrap); } } } else if (next.equals(this.scrap_list.end())) { //////////////////////////////////////////////////////// // NO RIGHT BUT LEFT ///////////////////////////////////////////////////////// //*** SITUATION-3: NO BOXES ON THE RIGHT SIDE *** lenx = this.scrap_min_z.value.cumx - prev.value.cumx; lenz = prev.value.cumz - this.scrap_min_z.value.cumz; lpz = this.remain_layout_length - this.scrap_min_z.value.cumz; // CALL FIND_BOX AND CHECK_FOUND this.find_box(lenx, this.layer_thickness, this.remain_layout_height, lenz, lpz); this.check_found(); // BREAK ? if (this.layer_done) break; if (this.evened) continue; // RE-FETCH LEFT AND RIGHT prev = this.scrap_min_z.prev(); // UPDATE CURRENT BOX let box: Box = this.box_array.at(this.cboxi); box.coy = this.packed_layout_height; box.coz = this.scrap_min_z.value.cumz; box.cox = prev.value.cumx; if (this.cbox_layout_width == this.scrap_min_z.value.cumx - prev.value.cumx) { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // LEFT FETCHES MIN_Z'S CUM_X prev.value.cumx = this.scrap_min_z.value.cumx; // ERASE FROM MIN_Z TO END this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z, this.scrap_list.end()); } else { // CUMULATE this.scrap_min_z.value.cumz += this.cbox_layout_length; } } else { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // CUMULATE prev.value.cumx += this.cbox_layout_width; } else { // CREATE A NEW NODE BETWEEN LEFT AND MIN_Z let scrap: Scrap = new Scrap ( prev.value.cumx + this.cbox_layout_width, this.scrap_min_z.value.cumz + this.cbox_layout_length ); this.scrap_list.insert(this.scrap_min_z, scrap); } } } else if (prev.value.cumz == next.value.cumz) { //////////////////////////////////////////////////////// // LEFT AND RIGHT ARE ALL EXIST .value. SAME CUMZ ///////////////////////////////////////////////////////// //*** SITUATION-4: THERE ARE BOXES ON BOTH OF THE SIDES *** //*** SUBSITUATION-4A: SIDES ARE EQUAL TO EACH OTHER *** lenx = this.scrap_min_z.value.cumx - prev.value.cumx; lenz = prev.value.cumz - this.scrap_min_z.value.cumz; lpz = this.remain_layout_length - this.scrap_min_z.value.cumz; // CALL FIND_BOX AND CHECK_FOUND this.find_box(lenx, this.layer_thickness, this.remain_layout_height, lenz, lpz); this.check_found(); // BREAK ? if (this.layer_done) break; if (this.evened) continue; // RE-FETCH LEFT AND RIGHT prev = this.scrap_min_z.prev(); next = this.scrap_min_z.next(); // UPDATE CURRENT BOX let box: Box = this.box_array.at(this.cboxi); box.coy = this.packed_layout_height; box.coz = this.scrap_min_z.value.cumz; if (this.cbox_layout_width == this.scrap_min_z.value.cumx - prev.value.cumx) { box.cox = prev.value.cumx; if (this.scrap_min_z.value.cumz + this.cbox_layout_length == next.value.cumz) { // LEFT FETCHES RIGHT'S CUM_X prev.value.cumx = next.value.cumx; // ERASE MIN_Z AND RIGHT this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z, next.next()); } else { // CUMULATE this.scrap_min_z.value.cumz += this.cbox_layout_length; } } else if (prev.value.cumx < this.pallet.layout_width - this.scrap_min_z.value.cumx) { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // DE-CUMULATE this.scrap_min_z.value.cumx -= this.cbox_layout_width; box.cox = this.scrap_min_z.value.cumx; } else { box.cox = prev.value.cumx; // CREATE A NODE BETWEEN LEFT AND MIN_Z let scrap: Scrap = new Scrap ( prev.value.cumx + this.cbox_layout_width, this.scrap_min_z.value.cumz + this.cbox_layout_length ); this.scrap_list.insert(this.scrap_min_z, scrap); } } else { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // CUMULATE prev.value.cumx += this.cbox_layout_width; box.cox = prev.value.cumx; } else { box.cox = this.scrap_min_z.value.cumx - this.cbox_layout_width; // CREATE A NODE BETWEEN MIN_Z AND RIGHT let scrap: Scrap = new Scrap ( this.scrap_min_z.value.cumx, this.scrap_min_z.value.cumz + this.cbox_layout_length ); this.scrap_list.insert(next, scrap); // UPDATE MIN_Z this.scrap_min_z.value.cumx -= this.cbox_layout_width; } } } else { //////////////////////////////////////////////////////// // LEFT AND RIGHT ARE ALL EXIST //////////////////////////////////////////////////////// //*** SUBSITUATION-4B: SIDES ARE NOT EQUAL TO EACH OTHER *** lenx = this.scrap_min_z.value.cumx - prev.value.cumx; lenz = prev.value.cumz - this.scrap_min_z.value.cumz; lpz = this.remain_layout_length - this.scrap_min_z.value.cumz; // CALL FIND_BOX AND CHECK_FOUND this.find_box(lenx, this.layer_thickness, this.remain_layout_height, lenz, lpz); this.check_found(); // BREAK ? if (this.layer_done) break; if (this.evened) continue; // RE-FETCH LEFT AND RIGHT prev = this.scrap_min_z.prev(); next = this.scrap_min_z.next(); // UPDATE CURRENT BOX let box: Box = this.box_array.at(this.cboxi); box.coy = this.packed_layout_height; box.coz = this.scrap_min_z.value.cumz; box.cox = prev.value.cumx; if (this.cbox_layout_width == this.scrap_min_z.value.cumx - prev.value.cumx) { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // LEFT FETCHES MIN_Z'S prev.value.cumx = this.scrap_min_z.value.cumx; // ERASE MIN_Z this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z); } else { // CUMULATE this.scrap_min_z.value.cumz += this.cbox_layout_length; } } else { if (this.scrap_min_z.value.cumz + this.cbox_layout_length == prev.value.cumz) { // CUMULATE prev.value.cumx += this.cbox_layout_width; } else if (this.scrap_min_z.value.cumz + this.cbox_layout_length == next.value.cumz) { // DE-CUMULATE this.scrap_min_z.value.cumx -= this.cbox_layout_width; box.cox = this.scrap_min_z.value.cumx; } else { // CREATE NODE BETWEEN LEFT AND MIN_Z let scrap: Scrap = new Scrap ( prev.value.cumx + this.cbox_layout_width, this.scrap_min_z.value.cumz + this.cbox_layout_length ); this.scrap_list.insert(this.scrap_min_z, scrap); } } } this.volume_check(); } } /** * Find the most proper layer height by looking at the unpacked boxes and * the remaining empty space available. */ private find_layer(thickness: number): void { // MINIMUM SUM OF LAYERS (height) let min_eval: number = Number.MAX_VALUE; this.layer_thickness = 0; for (let i: number = 0; i < this.box_array.size(); i++) { let box: Box = this.box_array.at(i); if (box.is_packed) continue; for (let j: number = 1; j <= 3; j++) { let ex_dim: number; // STANDARD LENGTH ON THE DIMENSION let dim2: number; // THE SECOND, LENGTH ON A RESIDUAL DIMENSION let dim3: number; // THE THIRD, LENGTH ON A RESIDUAL DIMENSION let my_eval: number = 0; // FETCH STANDARD DIMENSIONS FROM EACH AXIS switch (j) { case 1: ex_dim = box.width; dim2 = box.height; dim3 = box.length; break; case 2: ex_dim = box.height; dim2 = box.width; dim3 = box.length; break; case 3: ex_dim = box.length; dim2 = box.width; dim3 = box.height; break; } // ABOUT ALL BOXES, FIND THE MINIMUM LENGTH OF GAP ~, // STACK ON THE CURRENT LAYER (ADD ON TO THE LAYER_EVAL) if ( ex_dim <= thickness && ( (dim2 <= this.pallet.layout_width && dim3 <= this.pallet.layout_length) || (dim3 <= this.pallet.layout_width && dim2 <= this.pallet.layout_length) ) ) { for (let k: number = 0; k < this.box_array.size(); k++) { let my_box: Box = this.box_array.at(k); // SAME INSTANCE WITH THE SAME INDEX OR ALREADY PACKED if (i == k || my_box.is_packed == true) continue; let dim_diff: number = Math.min ( Math.abs(ex_dim - my_box.width), Math.abs(ex_dim - my_box.height), Math.abs(ex_dim - my_box.length) ); my_eval += dim_diff; } if (my_eval < min_eval) { min_eval = my_eval; this.layer_thickness = ex_dim; } } } } if (this.layer_thickness == 0 || this.layer_thickness > this.remain_layout_height) this.packing = false; } /** * <p> Determine the gap with the samllest z value in the current layer. </p> * * <p> Find the most proper boxes by looking at all six possible orientations, * empty space given, adjacent boxes, and pallet limits. </p> * * @param hmx Maximum available x-dimension of the current gap to be filled. * @param hy Current layer thickness value. * @param hmy Current layer thickness value. * @param hz Z-dimension of the current gap to be filled. * @param hmz Maximum available z-dimension to the current gap to be filled. */ private find_box(hmx: number, hy: number, hmy: number, hz: number, hmz: number): void { this.boxi = -1; this.bboxi = -1; this.bfx = Number.MAX_VALUE; this.bfy = Number.MAX_VALUE; this.bfz = Number.MAX_VALUE; this.bbfx = Number.MAX_VALUE; this.bbfy = Number.MAX_VALUE; this.bbfz = Number.MAX_VALUE; for (let i: number = 0; i < this.box_array.size(); i++) { let box: Box = this.box_array.at(i); if (box.is_packed) continue; this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.width, box.height, box.length); // WHEN REGULAR CUBE if (box.width == box.length && box.length == box.height) continue; this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.width, box.length, box.height); this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.height, box.width, box.length); this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.height, box.length, box.width); this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.length, box.width, box.height); this.analyze_box(i, hmx, hy, hmy, hz, hmz, box.length, box.height, box.width); } } /** * <p> Analyzes each unpacked {@link Box box} to find the best fitting one to the empty space. </p> * * <p> Used by {@link find_box find_box()} to analyze box dimensions. </p> * * @param x index of a {@link Box box} in the {@link box_array}. * * @param hmx Maximum available x-dimension of the current gap to be filled. * @param hy Current layer thickness value. * @param hmy Current layer thickness value. * @param hz Z-dimension of the current gap to be filled. * @param hmz Maximum available z-dimension to the current gap to be filled. * * @param dim1 X-dimension of the orientation of the box being examined. * @param dim2 Y-dimension of the orientation of the box being examined. * @param dim3 Z-dimension of the orientation of the box being examined. */ private analyze_box(index: number, hmx: number, hy: number, hmy: number, hz: number, hmz: number, dim1: number, dim2: number, dim3: number): void { // OUT OF BOUNDARY RANGE if (dim1 > hmx || dim2 > hmy || dim3 > hmz) return; if (dim2 <= hy && ( hy - dim2 < this.bfy || (hy - dim2 == this.bfy && hmx - dim1 < this.bfx) || (hy - dim2 == this.bfy && hmx - dim1 == this.bfx && Math.abs(hz - dim3) < this.bfz) ) ) { this.boxx = dim1; this.boxy = dim2; this.boxz = dim3; this.bfx = hmx - dim1; this.bfy = hy - dim2; this.bfz = Math.abs(hz - dim3); this.boxi = index; } else if (dim2 > hy && ( dim2 - hy < this.bbfy || (dim2 - hy == this.bbfy && hmx - dim1 < this.bbfx) || (dim2 - hy == this.bbfy && hmx - dim1 == this.bbfx && Math.abs(hz - dim3) < this.bbfz) ) ) { this.bboxx = dim1; this.bboxy = dim2; this.bboxz = dim3; this.bbfx = hmx - dim1; this.bbfy = dim2 - hy; this.bbfz = Math.abs(hz - dim3); this.bboxi = index; } } /** * After finding each box, the candidate boxes and the condition of the layer are examined. */ private check_found(): void { this.evened = false; if (this.boxi != -1) { this.cboxi = this.boxi; this.cbox_layout_width = this.boxx; this.cbox_layout_height = this.boxy; this.cbox_layout_length = this.boxz; } else { let prev = this.scrap_min_z.prev(); let next = this.scrap_min_z.next(); if (this.bboxi != -1 && // IN RANGE ( this.layer_in_layer != 0 || ( // NO LEFT AND RIGHT EXISTS prev.equals(this.scrap_list.end()) && next.equals(this.scrap_list.end()) ) )) { //////////////////////////////////////////// // ~ OR SCRAP_MIN_Z HAS NO NEIGHBOR //////////////////////////////////////////// if (this.layer_in_layer == 0) { this.pre_layer = this.layer_thickness; this.lilz = this.scrap_min_z.value.cumz; } this.cboxi = this.bboxi; this.cbox_layout_width = this.bboxx; this.cbox_layout_height = this.bboxy; this.cbox_layout_length = this.bboxz; this.layer_in_layer += this.bboxy - this.layer_thickness; this.layer_thickness = this.bboxy; } else { if (prev.equals(this.scrap_list.end()) && next.equals(this.scrap_list.end())) { /////////////////////////////////////////// // SCRAP_MIN_Z HAS NO NEIGHBOR /////////////////////////////////////////// // IN RANGE & NO NEIGHBOR // LAYER HAS DONE. this.layer_done = true; } else { this.evened = true; if (prev.equals(this.scrap_list.end())) { /////////////////////////////////////////// // NO LEFT, BUT RIGHT /////////////////////////////////////////// // ERASE SCRAP_MIN_Z // RIGHT IS THE NEW SCRAP_MIN_Z this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z); } else if (next.equals(this.scrap_list.end())) { /////////////////////////////////////////// // NO RIGHT, BUT LEFT /////////////////////////////////////////// // ERASE CURRENT SCRAP_MIN_Z // THE LEFT ITEM FETCHES MIN'S CUM_X prev.value.cumx = this.scrap_min_z.value.cumx; // ERASE FROM MIN_Z TO END this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z, this.scrap_list.end()); } else { /////////////////////////////////////////// // LEFT & RIGHT ARE ALL EXIST /////////////////////////////////////////// if (prev.value.cumz == next.value.cumz) { // ---------------------------------------- // LEFT AND RIGHT'S CUM_Z ARE EQUAL // ---------------------------------------- // LEFT FETCHES THE RIGHT'S CUM_X prev.value.cumx = next.value.cumx; // ERASE MIN AND ITS RIGHT this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z, next.next()); } else { // ---------------------------------------- // LEFT AND RIGHT'S CUM_Z ARE NOT EQUAL // ---------------------------------------- if (prev.value.cumz == next.value.cumz) prev.value.cumx = this.scrap_min_z.value.cumx; // ERASE SCRAP_MIN_Z this.scrap_min_z = this.scrap_list.erase(this.scrap_min_z); } } } } } } /** * After packing of each box, 100% packing condition is checked. */ private volume_check(): void { let box: Box = this.box_array.at(this.cboxi); box.is_packed = true; box.layout_width = this.cbox_layout_width; box.layout_height = this.cbox_layout_height; box.layout_length = this.cbox_layout_length; this.packed_volume += box.volume; if (this.packing_best) { // BOXOLOGIC DOESN'T MEMORIZE OPTIMIZED ORIENTATION // THUS IT NEEDS ADDITIONAL PROCEDURES FOR EXPORTING this.write_box_file(); } else if (this.packed_volume == this.pallet.volume || this.packed_volume == this.total_box_volume) { this.packing = false; this.hundred_percent = true; } } /* ----------------------------------------------------------- GETTERS ----------------------------------------------------------- */ /** * <p> Find the first to be packed gap in the layer edge. </p> * * <p> Determine the gap with the {@link scrap_min_z smallest z} value in the current layer. </p> */ private find_smallest_z(): void { this.scrap_min_z = this.scrap_list.begin(); for (let it = this.scrap_min_z; !it.equals(this.scrap_list.end()); it = it.next()) if (it.value.cumz < this.scrap_min_z.value.cumz) this.scrap_min_z = it; } /* ----------------------------------------------------------- REPORTERS ----------------------------------------------------------- */ /** * <p> Determine {@link box_arrray boxes}. </p> * * <p> Using the parameters found, packs the best solution found and reports. </p> */ private report_results(): void { //////////////////////////////////////////////////// // BEGINS RE-PACKING FOLLOWING THE BEST VARS //////////////////////////////////////////////////// this.packing_best = true; this.pallet.set_orientation(this.best_orientation); this.construct_layers(); this.iterate_layer(this.best_layer); } /** * <p> Determine a {@link Box}. </p> * * <p> Transforms the found co-ordinate system to the one entered by the user and write them to the * report. </p> */ private write_box_file(): void { let box: Box = this.box_array.at(this.cboxi); let cox: number; let coy: number; let coz: number; let layout_width: number; let layout_height: number; let layout_length: number; switch (this.best_orientation) { case 1: cox = box.cox; coy = box.coy; coz = box.coz; layout_width = box.layout_width; layout_height = box.layout_height; layout_length = box.layout_length; break; case 2: cox = box.coz; coy = box.coy; coz = box.cox; layout_width = box.layout_length; layout_height = box.layout_height; layout_length = box.layout_width; break; case 3: cox = box.coy; coy = box.coz; coz = box.cox; layout_width = box.layout_height; layout_height = box.layout_length; layout_length = box.layout_width; break; case 4: cox = box.coy; coy = box.cox; coz = box.coz; layout_width = box.layout_height; layout_height = box.layout_width; layout_length = box.layout_length; break; case 5: cox = box.cox; coy = box.coz; coz = box.coy; layout_width = box.layout_width; layout_height = box.layout_length; layout_length = box.layout_height; break; case 6: cox = box.coz; coy = box.cox; coz = box.coy; layout_width = box.layout_length; layout_height = box.layout_width; layout_length = box.layout_height; break; } box.cox = cox; box.coy = coy; box.coz = coz; box.layout_width = layout_width; box.layout_height = layout_height; box.layout_length = layout_length; } } }
the_stack
export default { // 菜单 'Home': '主页', 'Nodes': '节点', 'Node Detail': '节点详情', 'Spiders': '爬虫', 'Spider Detail': '爬虫详情', 'Task': '任务', 'Tasks': '任务', 'Task Detail': '任务详情', 'Schedules': '定时任务', 'Deploys': '部署', 'Sites': '网站', 'Setting': '设置', 'Project': '项目', 'Spider Market': '爬虫市场', // 标签 'Overview': '概览', 'Files': '文件', 'Deployed Spiders': '已部署爬虫', 'Log': '日志', 'Results': '结果', 'Environment': '环境', 'Analytics': '分析', 'Rules': '规则', 'Config': '配置', // 选择 'Spider': '爬虫', // 块标题 'Latest Tasks': '最近任务', 'Latest Deploys': '最近部署', // 任务状态 Pending: '待定', Running: '进行中', Finished: '已完成', Error: '错误', Errors: '错误', NA: '未知', Cancelled: '已取消', Abnormal: '异常', // 操作 Add: '添加', Create: '创建', Run: '运行', Deploy: '部署', Save: '保存', Cancel: '取消', Import: '导入', Submit: '提交', 'Import Spiders': '导入爬虫', 'Deploy All': '部署所有爬虫', 'Refresh': '刷新', 'View': '查看', 'Edit': '编辑', 'Remove': '删除', 'Confirm': '确认', 'Stop': '停止', 'Preview': '预览', 'Extract Fields': '提取字段', 'Download': '下载', 'Download CSV': '下载CSV', 'Upload Zip File': '上传Zip文件', 'Upload': '上传', 'Item Threshold': '子项阈值', 'Back': '返回', 'New File': '新建文件', 'Rename': '重命名', 'Install': '安装', 'Uninstall': '卸载', 'Create Directory': '新建目录', 'Create File': '新建文件', 'Add Node': '添加节点', 'Add Project': '添加项目', 'Sync': '同步', 'Auto Sync': '自动同步', 'Sync Frequency': '同步频率', 'Reset': '重置', 'Copy': '复制', 'Upgrade': '版本升级', 'Ok': '确定', // 主页 'Total Tasks': '总任务数', 'Active Nodes': '在线节点', 'Total Deploys': '总部署数', 'Daily New Tasks': '每日新增任务数', // 节点 'Node Info': '节点信息', 'Node Name': '节点名称', 'Node IP': '节点IP', 'Node MAC': '节点MAC', 'Node Port': '节点端口', 'Description': '描述', 'All Nodes': '所有节点', 'Node List': '节点列表', 'Network': '拓扑图', 'Node Network': '节点拓扑图', 'Master': '主节点', 'Worker': '工作节点', 'Installation': '安装', 'Search Dependencies': '搜索依赖', 'Monitor': '监控', 'Time Range': '时间区间', 'Started to install': '开始安装', // 节点列表 'IP': 'IP地址', 'Port': '端口', // 节点状态 Online: '在线', Offline: '离线', Unavailable: '未知', // 监控指标 'node_stats_cpu_usage_percent': '节点 CPU 使用百分比', 'node_stats_disk_total': '节点总磁盘大小', 'node_stats_disk_usage': '节点磁盘使用量', 'node_stats_disk_usage_percent': '节点磁盘使用百分比', 'node_stats_mem_total': '节点总内存大小', 'node_stats_mem_usage': '节点内存使用量', 'node_stats_mem_usage_percent': '节点内存使用百分比', 'node_stats_network_bytes_recv': '节点网络接收字节数', 'node_stats_network_bytes_sent': '节点网络发送字节数', 'node_stats_network_packets_recv': '节点网络接收包数', 'node_stats_network_packets_sent': '节点网络发送包数', 'mongo_stats_mem_resident': 'MongoDB 内存使用量', 'mongo_stats_mem_virtual': 'MongoDB 虚拟内存大小', 'mongo_stats_mem_usage_percent': 'MongoDB 内存使用百分比', 'mongo_stats_fs_total': 'MongoDB 总文件系统大小', 'mongo_stats_fs_used': 'MongoDB 文件系统使用量', 'mongo_stats_fs_usage_percent': 'MongoDB 文件系统使用百分比', 'mongo_stats_storage_size': 'MongoDB 储存大小', 'mongo_stats_data_size': 'MongoDB 数据大小', 'mongo_stats_index_size': 'MongoDB 索引大小', 'mongo_stats_objects': 'MongoDB Object 数量', 'mongo_stats_collections': 'MongoDB Collection 数量', 'mongo_stats_indexes': 'MongoDB 索引数量', 'mongo_stats_avg_obj_size': 'MongoDB 平均 Object 大小', 'redis_stats_dataset_bytes': 'Redis 数据字节数', 'redis_stats_keys_count': 'Redis Key 数量', 'redis_stats_overhead_total': 'Redis Overhead 总大小', 'redis_stats_peak_allocated': 'Redis 峰值分配大小', 'redis_stats_startup_allocated': 'Redis 启动分配大小', 'redis_stats_total_allocated': 'Redis 总分配大小', // 爬虫 'Spider Info': '爬虫信息', 'Spider ID': '爬虫ID', 'Spider Name': '爬虫名称', 'Source Folder': '代码目录', 'Execute Command': '执行命令', 'Results Collection': '结果集', 'Results Table': '结果表', 'Default': '默认', 'Spider Type': '爬虫类型', 'Language': '语言', 'Schedule Enabled': '是否开启定时任务', 'Schedule Cron': '定时任务', 'Variable': '变量', 'Value': '值', 'Add Environment Variables': '添加环境变量', 'Add Spider': '添加爬虫', 'Add Configurable Spider': '添加可配置爬虫', 'Add Customized Spider': '添加自定义爬虫', 'Add Field': '添加字段', 'Last 7-Day Tasks': '最近7天任务数', 'Last 5-Run Errors': '最近5次运行错误数', '30-Day Tasks': '最近30天任务数', '30-Day Results': '最近30天结果数', 'Success Rate': '运行成功率', 'Avg Duration (sec)': '平均运行时长(秒)', 'Tasks by Status': '分状态任务数', 'Tasks by Node': '分节点任务数', 'Daily Tasks': '每日任务数', 'Daily Avg Duration (sec)': '每日平均运行时长(秒)', 'Configurable Spider': '可配置爬虫', 'Customized Spider': '自定义爬虫', 'Configurable': '可配置', 'Customized': '自定义', 'configurable': '可配置', 'customized': '自定义', 'Text': '文本', 'Attribute': '属性', 'Field Name': '字段名称', 'Query Type': '查询类别', 'Query': '查询', 'Extract Type': '提取类别', 'CSS Selector': 'CSS选择器', 'CSS': 'CSS', 'XPath': 'Xpath', 'Crawl Type': '抓取类别', 'List Only': '仅列表', 'Detail Only': '仅详情页', 'List + Detail': '列表+详情页', 'Start URL': '开始URL', 'Item Selector': '列表项选择器', 'Item Selector Type': '列表项选择器类别', 'Pagination Selector': '分页选择器', 'Pagination Selector Type': '分页项选择器类别', 'Preview Results': '预览结果', 'Obey robots.txt': '遵守Robots协议', 'List Page Fields': '列表页字段', 'Detail Page Fields': '详情页字段', 'Detail Page URL': '详情页URL', 'All': '全部', 'Stages': '阶段', 'Process': '流程', 'Stage Process': '流程图', 'Stage Name': '阶段名称', 'Start Stage': '开始阶段', 'Engine': '引擎', 'Selector Type': '选择器类别', 'Selector': '选择器', 'Is Attribute': '是否为属性', 'Next Stage': '下一阶段', 'No Next Stage': '没有下一阶段', 'Fields': '字段', 'Stage': '阶段', 'Is List': '是否为列表', 'List': '列表', 'Pagination': '分页', 'Settings': '设置', 'Display Name': '显示名称', 'Template': '模版', 'Is Scrapy': '是否为 Scrapy', 'Scrapy Spider': 'Scrapy 爬虫', 'Scrapy Spiders': 'Scrapy 爬虫', 'Scrapy Log Level': 'Scrapy 日志等级', 'Parameter Name': '参数名', 'Parameter Value': '参数值', 'Parameter Type': '参数类别', 'Other': '其他', 'Scrapy Config': 'Scrapy 配置', 'Scrapy Settings': 'Scrapy 设置', 'Variable Name': '变量名', 'Variable Type': '变量类型', 'Variable Value': '变量值', 'Parameter Edit': '参数编辑', 'Add Scrapy Spider': '添加 Scrapy 爬虫', 'Is Git': '是否为 Git', 'Git Settings': 'Git 设置', 'Git URL': 'Git URL', 'Git Branch': 'Git 分支', 'Git Username': 'Git 用户名', 'Git Password': 'Git 密码', 'Has Credential': '需要验证', 'SSH Public Key': 'SSH 公钥', 'Is Long Task': '是否为长任务', 'Long Task': '长任务', 'Running Task Count': '运行中的任务数', 'Running Tasks': '运行中的任务', 'Item Name': 'Item 名称', 'Add Item': '添加 Item', 'Add Variable': '添加变量', 'Copy Spider': '复制爬虫', 'New Spider Name': '新爬虫名称', 'All Spiders': '所有爬虫', 'My Spiders': '我的爬虫', 'Public Spiders': '公共爬虫', 'Is Public': '是否公共', 'Owner': '所有者', 'Convert to Customized': '转化为自定义', 'Is De-Duplicated': '是否去重', 'Please enter de-duplicated field': '请输入去重字段', 'Overwrite': '覆盖', 'Ignore': '忽略', 'De-Duplication': '去重', 'Same Above': '同上', 'Batch Run': '批量运行', 'Set Projects': '设置项目', // 爬虫列表 'Name': '名称', 'Last Run': '上次运行', 'Action': '操作', 'No command line': '没有执行命令', 'Last Status': '上次运行状态', 'Remark': '备注', // 任务 'Task Info': '任务信息', 'Task ID': '任务ID', 'Status': '状态', 'Log File Path': '日志文件路径', 'Create Timestamp': '创建时间', 'Finish Timestamp': '完成时间', 'Duration (sec)': '用时(秒)', 'Error Message': '错误信息', 'Results Count': '结果数', 'Average Results Count per Second': '抓取速度(个/秒)', 'Wait Duration (sec)': '等待时长(秒)', 'Runtime Duration (sec)': '运行时长(秒)', 'Total Duration (sec)': '总时长(秒)', 'Run Type': '运行类型', 'Random': '随机', 'Selected Nodes': '指定节点', 'Search Log': '搜索日志', 'Auto-Scroll': '自动滚动', 'Auto-Refresh': '自动刷新', 'Updating log...': '正在更新日志...', 'Error Count': '错误数', 'Log with errors': '日志错误', 'Empty results': '空结果', 'Navigate to Spider': '导航到爬虫', 'Navigate to Node': '导航到节点', 'Restart': '重新运行', 'Redirect to task detail': '跳转到任务详情页', 'Retry (Maximum 5 Times)': '是否重试(最多 5 次)', 'Delete Tasks': '删除任务', 'Stop Tasks': '停止任务', // 任务列表 'Node': '节点', 'Create Time': '创建时间', 'Start Time': '开始时间', 'Finish Time': '结束时间', 'Update Time': '更新时间', 'Type': '类别', 'Spider Tasks': '爬虫任务', 'System Tasks': '系统任务', // 部署 'Time': '时间', // 项目 'All Tags': '全部标签', 'Projects': '项目', 'Project Name': '项目名称', 'Project Description': '项目描述', 'Tags': '标签', 'Enter Tags': '输入标签', 'No Project': '无项目', 'All Projects': '所有项目', // 定时任务 'Schedule Name': '定时任务名称', 'Schedule Description': '定时任务描述', 'Parameters': '参数', 'Add Schedule': '添加定时任务', 'stop': '暂停', 'running': '运行', 'error': '错误', 'Not Found Node': '节点配置错误', 'Not Found Spider': '爬虫配置错误', '[minute] [hour] [day] [month] [day of week]': '[分] [时] [天] [月] [星期几]', 'Enable/Disable': '启用/禁用', 'Cron': 'Cron', 'Cron Expression': 'Cron 表达式', 'Cron expression is invalid': 'Cron 表达式不正确', 'View Tasks': '查看任务', 'Batch Add': '批量添加', 'Enable': '启用', 'Disable': '禁用', // 网站 'Site': '网站', 'Rank': '排名', 'Domain': '域名', 'Main Category': '主类别', 'Category': '类别', 'Select': '请选择', 'Select Main Category': '请选择主类别', 'Select Category': '请选择类别', 'Spider Count': '爬虫数', 'Robots Protocol': 'Robots 协议', 'Home Page Response Time (sec)': '首页响应时间(秒)', 'Home Page Response Status Code': '首页响应状态码', // 反馈 'Feedback': '反馈', 'Feedbacks': '反馈', 'Wechat': '微信', 'Content': '内容', 'Rating': '评分', // 用户 'Super Admin': '超级管理员', // 文件 'Choose Folder': '选择文件', 'File': '文件', 'Folder': '文件夹', 'Directory': '目录', // 导入 'Import Spider': '导入爬虫', 'Source URL': '来源URL', 'Source Type': '来源类别', // 搜索 Search: '搜索', // 下拉框 User: '用户', Logout: '退出登录', Documentation: '文档', // 变量类型 'String': '字符串', 'Number': '数字', 'Boolean': '布尔值', 'Array/List': '数组/列表', 'Object/Dict': '对象/字典', // 选择 'Yes': '是', 'No': '否', // 系统 'OS': '操作系统', 'ARCH': '操作架构', 'Number of CPU': 'CPU数', 'Executables': '执行文件', 'Latest Version': '最新版本', 'Version': '版本', 'Installed': '已安装', 'Not Installed': '未安装', 'Installing': '正在安装', 'Install All': '安装全部', 'Other language installing': '其他语言正在安装', 'This language is not installed yet.': '语言还未安装', 'Languages': '语言', 'Dependencies': '依赖', 'Install on All Nodes': '安装在所有节点', // 弹出框 'Notification': '提示', 'Are you sure to delete this node?': '你确定要删除该节点?', 'Are you sure to run this spider?': '你确定要运行该爬虫?', 'Are you sure to delete this file/directory?': '你确定要删除该文件/文件夹?', 'Are you sure to convert this spider to customized spider?': '你确定要转化该爬虫为自定义爬虫?', 'Are you sure to delete this task?': '您确定要删除该任务?', 'Added spider successfully': '成功添加爬虫', 'Converted successfully': '成功转化', 'Converted unsuccessfully': '未成功转化', 'Uploaded spider files successfully': '成功上传爬虫文件', 'Node info has been saved successfully': '节点信息已成功保存', 'A task has been scheduled successfully': '已经成功派发一个任务', 'Are you sure to delete this spider?': '你确定要删除该爬虫?', 'Are you sure to delete this user?': '你确定要删除该用户?', 'Spider info has been saved successfully': '爬虫信息已成功保存', 'Do you allow us to collect some statistics to improve Crawlab?': '您允许我们收集统计数据以更好地优化Crawlab?', 'Saved file successfully': '成功保存文件', 'An error happened when fetching the data': '请求数据时出错', 'Error when logging in (Please read documentation Q&A)': '登录时出错(请查看文档 Q&A)', 'Please enter the correct username': '请输入正确用户名', 'Password length should be no shorter than 5': '密码长度不能小于5', 'Two passwords must be the same': '两个密码必须要一致', 'username already exists': '用户名已存在', 'Deleted successfully': '成功删除', 'Saved successfully': '成功保存', 'Renamed successfully': '重命名保存', 'You can click "Add" to create an empty spider and upload files later.': '您可以点击"添加"按钮创建空的爬虫,之后再上传文件。', 'OR, you can also click "Upload" and upload a zip file containing your spider project.': '或者,您也可以点击"上传"按钮并上传一个包含爬虫项目的 zip 文件。', 'NOTE: When uploading a zip file, please zip your spider files from the ROOT DIRECTORY.': '注意: 上传 zip 文件时,请从 根目录 下开始压缩爬虫文件。', 'English': 'English', 'Are you sure to delete the schedule task?': '确定删除定时任务?', ' is not installed, do you want to install it?': ' 还没有安装,您是否打算安装它?', 'Disclaimer': '免责声明', 'Please search dependencies': '请搜索依赖', 'No Data': '暂无数据', 'No data available': '暂无数据', 'No data available. Please check whether your spiders are missing dependencies or no spiders created.': '暂无数据。请检查您的爬虫是否缺少依赖,或者没有创建爬虫。', 'Show installed': '查看已安装', 'Installing dependency successful': '安装依赖成功', 'Installing dependency failed': '安装依赖失败', 'You have successfully installed a dependency: ': '您已成功安装依赖: ', 'The dependency installation is unsuccessful: ': '安装依赖失败: ', 'Uninstalling dependency successful': '卸载依赖成功', 'Uninstalling dependency failed': '卸载依赖失败', 'You have successfully uninstalled a dependency: ': '您已成功卸载依赖: ', 'The dependency uninstallation is unsuccessful: ': '卸载依赖失败: ', 'Installing language successful': '安装语言成功', 'Installing language failed': '安装语言失败', 'You have successfully installed a language: ': '您已成功安装语言: ', 'The language installation is unsuccessful: ': '安装语言失败: ', 'Enabling the schedule successful': '启用定时任务成功', 'Disabling the schedule successful': '禁用定时任务成功', 'Enabling the schedule unsuccessful': '启用定时任务失败', 'Disabling the schedule unsuccessful': '禁用定时任务失败', 'The schedule has been removed': '已删除定时任务', 'The schedule has been added': '已添加定时任务', 'The schedule has been saved': '已保存定时任务', 'Email format invalid': '邮箱地址格式不正确', 'Please select a file or click the add button on the left.': '请在左侧选择一个文件或点击添加按钮.', 'New Directory': '新建目录', 'Enter new directory name': '输入新目录名称', 'New directory name': '新目录名称', 'Enter new file name': '输入新文件名称', 'New file name': '新文件名称', 'Release Note': '发布记录', 'How to Upgrade': '升级方式', 'Release': '发布', 'Add Wechat to join discussion group': '添加微信 tikazyq1 加入交流群', 'Submitted successfully': '提交成功', // 登录 'Sign in': '登录', 'Sign-in': '登录', 'Sign out': '退出登录', 'Sign-out': '退出登录', 'Sign up': '注册', 'Sign-up': '注册', 'Forgot Password': '忘记密码', 'Has Account': '已有账号', 'New to Crawlab': 'Crawlab新用户', 'Initial Username/Password': '初始用户名/密码', 'Username': '用户名', 'Password': '密码', 'Confirm Password': '确认密码', 'normal': '普通用户', 'admin': '管理用户', 'Role': '角色', 'Edit User': '更改用户', 'Users': '用户', 'Email': '邮箱', 'Optional': '可选', // 设置 'Notification Trigger Timing': '消息通知触发时机', 'On Task End': '当任务结束', 'On Task Error': '当任务发生错误', 'Never': '从不', 'DingTalk Robot Webhook': '钉钉机器人 Webhook', 'Wechat Robot Webhook': '微信机器人 Webhook', 'Password Settings': '密码设置', 'Notifications': '消息通知', 'Global Variable': '全局变量', 'Add Global Variable': '新增全局变量', 'Are you sure to delete this global variable': '确定删除该全局变量?', 'Key': '设置', 'Allow Sending Statistics': '允许发送统计信息', 'General': '通用', 'Enable Tutorial': '启用教程', 'Error Regex Pattern': '异常正则表达式', 'By default: ': '默认: ', 'Max Error Logs Display': '最大异常日志展示', 'Log Errors': '日志错误', 'No Expire': '不过期', 'Log Expire Duration': '日志过期时间', 'Database': '数据库', 'Data Source': '数据源', 'Data Source Type': '数据源类别', 'Host': '主机', 'Host address, e.g. 192.168.0.1': '主机地址,例如 192.168.0.1', 'Port, e.g. 27017': '端口,例如 27017', 'Auth Source (Default: admin)': 'Auth Source (默认: admin)', 'Change Password': '更改密码', // 挑战 'Challenge': '挑战', 'Challenges': '挑战', 'Difficulty': '难度', 'Achieved': '已达成', 'Not Achieved': '未达成', 'Start Challenge': '开始挑战', // 时间 'Second': '秒', 'Seconds': '秒', 'Minute': '分', 'Minutes': '分', 'Hour': '小时', 'Hours': '小时', 'Day': '天', 'Days': '天', 'Week': '周', 'Weeks': '周', 'Month': '月', 'Months': '月', 'Year': '年', 'Years': '年', // 爬虫市场 'Search Keyword': '搜索关键词', 'Sort': '排序', 'Default Sort': '默认排序', 'Most Stars': '最多 Stars', 'Most Forks': '最多 Forks', 'Latest Pushed': '最近提交', 'Pushed At': '提交时间', // 全局 'Related Documentation': '相关文档', 'Click to view related Documentation': '点击查看相关文档', // 其他 tagsView: { closeOthers: '关闭其他', close: '关闭', refresh: '刷新', closeAll: '关闭所有' }, nodeList: { type: '节点类型' }, schedules: { cron: 'Cron', addCron: '生成Cron', // Cron Format: [second] [minute] [hour] [day of month] [month] [day of week] cronFormat: 'Cron 格式: [秒] [分] [小时] [日] [月] [周]' }, // 监控 'Disk': '磁盘', 'Data Size': '数据大小', 'Storage Size': '储存大小', 'Memory': '内存', 'CPU': 'CPU', 'Index Size': '索引大小', 'Total Allocated': '总分配内存', 'Peak Allocated': '峰值内存', 'Dataset Size': '数据大小', 'Overhead Size': '额外开销', 'Disk Usage': '磁盘使用量', 'Memory Usage': '内存使用量', // 内容 addNodeInstruction: ` 您不能在 Crawlab 的 Web 界面直接添加节点。 添加节点的方式非常简单,您只需要在目标机器上运行一个 Crawlab 服务就可以了。 具体操作,请参照 [多节点部署文档](https://docs.crawlab.cn/Installation/MultiNode.html)。 `, // 教程 'Skip': '跳过', 'Previous': '上一步', 'Next': '下一步', 'Finish': '结束', 'Click to add a new spider.<br><br>You can also add a <strong>Customized Spider</strong> through <a href="https://docs.crawlab.cn/Usage/SDK/CLI.html" target="_blank" style="color: #409EFF">CLI Tool</a>.': '点击并添加爬虫<br><br>您也可以通过 <a href="https://docs.crawlab.cn/Usage/SDK/CLI.html" target="_blank" style="color: #409EFF">CLI 工具</a> 添加<strong>自定义爬虫</strong>', 'You can view your created spiders here.<br>Click a table row to view <strong>spider details</strong>.': '您可以查看创建的爬虫<br>点击行来查看<strong>爬虫详情</strong>', 'View a list of <strong>Configurable Spiders</strong>': '查看<strong>可配置爬虫</strong>列表', 'View a list of <strong>Customized Spiders</strong>': '查看<strong>自定义爬虫</strong>列表', '<strong>Customized Spider</strong> is a highly customized spider, which is able to run on any programming language and any web crawler framework.': '<strong>自定义爬虫</strong>是高度自定义化的爬虫,能够运行任何编程语言和爬虫框架', '<strong>Configurable Spider</strong> is a spider defined by config data, aimed at streamlining spider development and improving dev efficiency.': '<strong>可配置爬虫</strong>被配置数据所定义,旨在将爬虫开发流程化以及提高爬虫开发效率', 'Unique identifier for the spider': '爬虫的唯一识别符', 'How the spider is displayed on Crawlab': '爬虫在 Crawlab 上的展示名称', 'A shell command to be executed when the spider is triggered to run (only available for <strong>Customized Spider</strong>': '当爬虫被触发时执行的一行 Shell 命令(仅<strong>自定义爬虫</strong>有效)', 'Where the results are stored in the database': '抓取结果在数据库中储存的位置', 'Upload a zip file containing all spider files to create the spider (only available for <strong>Customized Spider</strong>)': '上传一个包含所有爬虫文件的 zip 文件,然后创建爬虫(仅<strong>自定义爬虫</strong>有效)', 'The spider template to create from (only available for <strong>Configurable Spider</strong>)': '创建爬虫时引用的模版(仅<strong>可配置爬虫</strong>有效)', 'Click to confirm to add the spider': '点击并确认添加爬虫', 'You can switch to each section of the spider detail.': '您可以切换到爬虫详情的每一个部分', 'You can switch to different spider using this selector.': '您可以通过这个选择器切换不同的爬虫', 'You can view latest tasks for this spider and click each row to view task detail.': '您可以查看最近的爬虫任务以及点击行来查看任务详情', 'You can edit the detail info for this spider.': '您可以编辑爬虫详情信息', 'Here you can action on the spider, including running a task, uploading a zip file and save the spider info.': '这里您可以对爬虫进行操作,包括运行爬虫任务、上传 zip 文件以及保存爬虫信息', 'File navigation panel.<br><br>You can right click on <br>each item to create or delete<br> a file/directory.': '文件导航栏<br><br>您可以右键点击一个元素<br>来添加或删除文件/文件夹', 'Click to add a file or directory<br> on the root directory.': '点击并添加一个文件<br>或文件夹', 'You can edit, save, rename<br> and delete the selected file <br>in this box.': '在这个栏位中,您可以<br>编辑、保存、重命名、<br>删除所选择的文件', 'Here you can add environment variables that will be passed to the spider program when running a task.': '这里您可以添加环境变量,这些环境变量会被传入运行的爬虫程序中', 'You can add, edit and delete schedules (cron jobs) for the spider.': '您可以添加、修改、删除爬虫的定时任务', 'You can switch to each section of configurable spider.': '您可以切换到可配置爬虫的每一个部分', 'Here is the starting URL of the spider.': '这里是爬虫的起始URL', 'Here is the starting stage of the spider.<br><br>A <strong>Stage</strong> is basically a callback in the Scrapy spider.': '这里是爬虫的起始阶段<br><br><strong>阶段</strong>就是 Scrapy 爬虫中的回调函数', 'You can run a spider task.<br><br>Spider will be automatically saved when clicking on this button.': '您可以运行爬虫任务<br><br>点击该按钮会自动保存爬虫', 'Add/duplicate/delete a stage.': '添加/复制/删除阶段', 'Add/duplicate/delete an extract field in the stage.': '添加/复制/删除该阶段下的抓取字段', 'You can decide whether this is a list page.<br><br>Click on the CSS/XPath tag to enter the selector expression for list items.<br>For example, "<code>ul > li</code>"': '您可以决定这是否为一个列表页<br><br>点击 CSS/XPath 标签来输入列表元素的选择器表达式<br>例如 "<code>ul > li</code>"', 'You can decide whether this is a list page with pagination.<br><br>Click on the CSS/XPath tag to enter the selector expression for the pagination.<br>For example, "<code>a.next</code>"': '您可以决定这是否为一个含分页的列表页<br><br>点击 CSS/XPath 标签来输入分页的选择器表达式<br>例如 "<code>a.next</code>"', 'You should enter necessary information for all fields in the stage.': '您应该输入该阶段下所有字段的信息', 'If you have multiple stages, e.g. list page + detail page, you should select the next stage in the detail link\'s field.': '如果您有多个阶段,例如列表页+详情页,您应该在详情页链接字段中选择下一个阶段', 'You can view the<br> visualization of the stage<br> workflow.': '您可以查看阶段工作流的<br>可视化界面', 'You can add the settings here, which will be loaded in the Scrapy\'s <code>settings.py</code> file.<br><br>JSON and Array data are supported.': '您可以在这里添加设置,它们会在 Scrapy 中的 <code>settings.py</code> 中被加载<br><br>JSON 和数组都支持', 'You can edit the <code>Spiderfile</code> here.<br><br>For more information, please refer to the <a href="https://docs.crawlab.cn/Usage/Spider/ConfigurableSpider.html" target="_blank" style="color: #409EFF">Documentation (Chinese)</a>.': '您可以在这里编辑 <code>Spiderfile</code><br><br>更多信息, 请参考 <a href="https://docs.crawlab.cn/Usage/Spider/ConfigurableSpider.html" target="_blank" style="color: #409EFF">文档</a>.', 'You can filter tasks from this area.': '您可以在这个区域筛选任务', 'This is a list of spider tasks executed sorted in a time descending order.': '这是执行过的爬虫任务的列表,按时间降序排列', 'Click the row to or the view button to view the task detail.': '点击行或查看按钮来查看任务详情', 'Tick and select the tasks you would like to delete in batches.': '勾选您想批量删除的任务', 'Click this button to delete selected tasks.': '点击并删除勾选的任务', 'This is the info of the task detail.': '这是任务详情信息', 'This is the spider info of the task.': '这是任务的爬虫信息', 'You can click to view the spider detail for the task.': '您可以点击查看该任务的爬虫详情', 'This is the node info of the task.': '这是任务的节点信息', 'You can click to view the node detail for the task.': '您可以点击查看该任务的节点详情', 'Here you can view the log<br> details for the task. The<br> log is automatically updated.': '这里您可以查看该任务<br>的日志详情,日志是<br>自动更新的', 'Here you can view the results scraped by the spider.<br><br><strong>Note:</strong> If you find your results here are empty, please refer to the <a href="https://docs.crawlab.cn/Integration/" target="_blank" style="color: #409EFF">Documentation (Chinese)</a> about how to integrate your spider into Crawlab.': '这里您可以查看爬虫抓取下来的结果<br><br><strong>注意:</strong> 如果这里结果是空的,请参考 <a href="https://docs.crawlab.cn/Integration/" target="_blank" style="color: #409EFF">相关文档</a> 来集成您的爬虫到 Crawlab', 'You can download your results as a CSV file by clicking this button.': '您可以点击下载结果为 CSV 文件', 'Switch between different nodes.': '在节点间切换', 'You can view the latest executed spider tasks.': '您可以查看最近执行过的爬虫任务', 'This is the detailed node info.': '这是节点详情', 'Here you can install<br> dependencies and modules<br> that are required<br> in your spiders.': '这里您可以安装您爬虫中<br>需要的依赖或模块', 'You can search dependencies in the search box and install them by clicking the "Install" button below.': '您可以在搜索框中搜索依赖并点击下面的"安装"按钮来进行安装', 'You should fill the form before adding the new schedule.': '在添加新定时任务前,您需要填写这个表单', 'The name of the schedule': '定时任务名称', 'The type of how to run the task.<br><br>Please refer to the <a href="https://docs.crawlab.cn/Usage/Spider/Run.html" target="_blank" style="color: #409EFF">Documentation (Chinese)</a> for detailed explanation for the options.<br><br>Let\'s select <strong>Selected Nodes</strong> for example.': '表示以哪种方式运行任务,<br><br>请参考 <a href="https://docs.crawlab.cn/Usage/Spider/Run.html" target="_blank" style="color: #409EFF">文档</a> 参考选项解释<br><br>让我们选择 <strong>指定节点</strong> 这个选项', 'The spider to run': '运行的爬虫', '<strong>Cron</strong> expression for the schedule.<br><br>If you are not sure what a cron expression is, please refer to this <a href="https://baike.baidu.com/item/crontab/8819388" target="_blank" style="color: #409EFF">Article</a>.': '定时任务的 <strong>Cron</strong> 表达式<br><br>如果您不清楚什么是 Cron 表达式,请参考这篇 <a href="https://baike.baidu.com/item/crontab/8819388" target="_blank" style="color: #409EFF">文章(英文)</a>.', 'You can select the correct options in the cron config box to configure the cron expression.': '您可以在 Cron 配置栏里选择正确的选项来配置 Cron 表达式', 'The parameters which will be passed into the spider program.': '将被传入爬虫程序里的参数', 'The description for the schedule': '定时任务的描述', 'Once you have filled all fields, click this button to submit.': '当您填完所有字段,请点击这个按钮来提交定时任务', 'Here you can set your general settings.': '这里您可以设置您的通用设置', 'In this tab you can configure your notification settings.': '在这个标签中,您可以<br>配置您的消息通知配置', 'Here you can add/edit/delete global environment variables which will be passed into your spider programs.': '这里您可以添加/修改/删除全局环境变量,它们会被传入爬虫程序中', 'You are running on a mobile device, which is not optimized yet. Please try with a laptop or desktop.': '您正在没有优化过的移动端上浏览,我们建议您用电脑来访问', 'Git has been synchronized successfully': 'Git 已经成功同步', 'Git has been reset successfully': 'Git 已经成功重置', 'This would delete all files of the spider. Are you sure to continue?': '重置将删除该爬虫所有文件,您希望继续吗?', 'SSH Public Key is copied to the clipboard': 'SSH 公钥已粘贴到剪切板', 'Removed successfully': '已成功删除', 'Are you sure to delete selected items?': '您是否确认删除所选项?', 'Are you sure to stop selected items?': '您是否确认停止所选项?', 'Sent signals to cancel selected tasks': '已经向所选任务发送取消任务信号', 'Copied successfully': '已成功复制', 'You have started the challenge.': '您已开始挑战', 'Please enter your email': '请输入您的邮箱', 'Please enter your Wechat account': '请输入您的微信账号', 'Please enter your feedback content': '请输入您的反馈内容', 'No response from the server. Please make sure your server is running correctly. You can also refer to the documentation to solve this issue.': '服务器无响应,请保证您的服务器正常运行。您也可以参考文档来解决这个问题(文档链接在下方)', 'Are you sure to restart this task?': '确认重新运行该任务?', 'Are you sure to delete the project?': '确认删除该项目?', 'You have no projects created. You can create a project by clicking the "Add" button.': '您没有创建项目,请点击 "添加项目" 按钮来创建一个新项目', 'Added API token successfully': '成功添加 API Token', 'Deleted API token successfully': '成功删除 API Token', 'Are you sure to add an API token?': '确认创建 API Token?', 'Are you sure to delete this API token?': '确认删除该 API Token?', 'Please enter Web Hook URL': '请输入 Web Hook URL', 'Change data source failed': '更改数据源失败', 'Changed data source successfully': '更改数据源成功', 'Are you sure to delete this data source?': '您确定删除该数据源?', 'Are you sure to download this spider?': '您确定要下载该爬虫?', 'Downloaded successfully': '下载成功', 'Unable to submit because of some errors': '有错误,无法提交', 'Are you sure to stop these tasks': '确认停止这些任务?', 'Are you sure to delete these tasks': '确认删除这些任务?', 'Stopped successfully': '成功停止', 'Are you sure to restart these tasks': '确认重新运行这些任务?', 'Restarted successfully': '成功重新运行', 'Are you sure to stop this task?': '确认停止这个任务?', 'Enabled successfully': '成功启用', 'Disabled successfully': '成功禁用', 'Request Error': '请求错误', 'Changed password successfully': '成功修改密码', 'Two passwords do not match': '两次密码不匹配', // 其他 'Star crawlab-team/crawlab on GitHub': '在 GitHub 上为 Crawlab 加星吧', 'How to buy': '如何购买' };
the_stack
import * as d3 from "d3"; import { assert } from "chai"; import * as Plottable from "../../src"; import * as TestMethods from "../testMethods"; describe("Interactions", () => { describe("Click Interaction", () => { const DIV_WIDTH = 400; const DIV_HEIGHT = 400; let clickedPoint: Plottable.Point; let div: d3.Selection<HTMLDivElement, any, any, any>; let component: Plottable.Component; let clickInteraction: Plottable.Interactions.Click; beforeEach(() => { div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT); component = new Plottable.Component(); component.renderTo(div); clickInteraction = new Plottable.Interactions.Click(); clickInteraction.attachTo(component); clickedPoint = {x: DIV_WIDTH / 2, y: DIV_HEIGHT / 2}; }); afterEach(function() { if (this.currentTest.state === "passed") { div.remove(); } }); type ClickTestCallback = { lastPoint: Plottable.Point; called: boolean; calledCount: number; reset: () => void; (p: Plottable.Point): void; }; function makeClickCallback() { const callback = <ClickTestCallback> function(p?: Plottable.Point) { callback.lastPoint = p; callback.called = true; callback.calledCount += 1; }; callback.called = false; callback.calledCount = 0; callback.reset = () => { callback.lastPoint = undefined; callback.called = false; }; return callback; } function clickPoint(point: Plottable.Point, mode: TestMethods.InteractionMode = TestMethods.InteractionMode.Mouse) { clickPointWithMove(point, point, mode); } function clickPointWithMove(clickStartPoint: Plottable.Point, clickEndPoint: Plottable.Point, mode: TestMethods.InteractionMode) { TestMethods.triggerFakeInteractionEvent(mode, TestMethods.InteractionType.Start, component.content(), clickStartPoint.x, clickStartPoint.y); TestMethods.triggerFakeInteractionEvent(mode, TestMethods.InteractionType.End, component.content(), clickEndPoint.x, clickEndPoint.y); } function doubleClickPoint(point: Plottable.Point, mode: TestMethods.InteractionMode = TestMethods.InteractionMode.Mouse) { doubleClickPointWithMove(point, point, mode); } function doubleClickPointWithMove(firstClickPoint: Plottable.Point, secondClickPoint: Plottable.Point, mode: TestMethods.InteractionMode) { clickPoint(firstClickPoint, mode); clickPoint(secondClickPoint, mode); TestMethods.triggerFakeMouseEvent("dblclick", component.content(), secondClickPoint.x, secondClickPoint.y); } // All the tests require setTimouts becuase of the internal logic in click interactions function runAsserts(callback: () => void, done: () => void) { setTimeout(() => { callback(); done(); }, 0); } describe("registering click callbacks", () => { it("registers callback using onClick", (done) => { const callback = makeClickCallback(); assert.strictEqual( clickInteraction.onClick(callback), clickInteraction, "registration returns the calling Interaction", ); clickPoint(clickedPoint); runAsserts(() => { assert.isTrue(callback.called, "Interaction should trigger the callback"); }, done); }); it("deregisters callback using offClick", (done) => { const callback = makeClickCallback(); clickInteraction.onClick(callback); assert.strictEqual( clickInteraction.offClick(callback), clickInteraction, "deregistration returns the calling Interaction", ); clickPoint(clickedPoint); runAsserts(() => { assert.isFalse(callback.called, "Callback should be disconnected from the Interaction"); }, done); }); it("can register multiple onClick callbacks", (done) => { const callback1 = makeClickCallback(); const callback2 = makeClickCallback(); clickInteraction.onClick(callback1); clickInteraction.onClick(callback2); clickPoint(clickedPoint); runAsserts(() => { assert.isTrue(callback1.called, "Interaction should trigger the first callback"); assert.isTrue(callback2.called, "Interaction should trigger the second callback"); }, done); }); it("can deregister a callback without affecting the other ones", (done) => { const callback1 = makeClickCallback(); const callback2 = makeClickCallback(); clickInteraction.onClick(callback1); clickInteraction.onClick(callback2); clickInteraction.offClick(callback1); clickPoint(clickedPoint); runAsserts(() => { assert.isFalse(callback1.called, "Callback1 should be disconnected from the click interaction"); assert.isTrue(callback2.called, "Callback2 should still exist on the click interaction"); }, done); }); }); describe("registering double click callbacks", () => { it("registers callback using onDoubleClick", (done) => { const callback = makeClickCallback(); assert.strictEqual( clickInteraction.onDoubleClick(callback), clickInteraction, "registration returns the calling Interaction", ); doubleClickPoint(clickedPoint); runAsserts(() => { assert.isTrue(callback.called, "Interaction should trigger the callback"); }, done); }); it("deregisters callback using offDoubleClick", (done) => { const callback = makeClickCallback(); clickInteraction.onDoubleClick(callback); assert.strictEqual( clickInteraction.offDoubleClick(callback), clickInteraction, "deregistration returns the calling Interaction", ); doubleClickPoint(clickedPoint); runAsserts(() => { assert.isFalse(callback.called, "Callback should be disconnected from the Interaction"); }, done); }); it("can register multiple onDoubleClick callbacks", (done) => { const callback1 = makeClickCallback(); const callback2 = makeClickCallback(); clickInteraction.onDoubleClick(callback1); clickInteraction.onDoubleClick(callback2); doubleClickPoint(clickedPoint); runAsserts(() => { assert.isTrue(callback1.called, "Interaction should trigger the first callback"); assert.isTrue(callback2.called, "Interaction should trigger the second callback"); }, done); }); it("can deregister a callback without affecting the other ones", (done) => { const callback1 = makeClickCallback(); const callback2 = makeClickCallback(); clickInteraction.onDoubleClick(callback1); clickInteraction.onDoubleClick(callback2); clickInteraction.offDoubleClick(callback1); doubleClickPoint(clickedPoint); runAsserts(() => { assert.isFalse(callback1.called, "Callback1 should be disconnected from the click interaction"); assert.isTrue(callback2.called, "Callback2 should still exist on the click interaction"); }, done); }); }); [TestMethods.InteractionMode.Mouse, TestMethods.InteractionMode.Touch].forEach((mode) => { describe(`invoking click callbacks with ${TestMethods.InteractionMode[mode]} events`, () => { let callback: ClickTestCallback; const quarterPoint = {x: DIV_WIDTH / 4, y: DIV_HEIGHT / 4}; const halfPoint = {x: DIV_WIDTH / 2, y: DIV_HEIGHT / 2}; const outsidePoint = {x: DIV_WIDTH * 2, y: DIV_HEIGHT * 2}; beforeEach(() => { callback = makeClickCallback(); clickInteraction.onClick(callback); }); it("invokes onClick callback on single location click", (done) => { clickPoint(halfPoint, mode); runAsserts(() => { assert.isTrue(callback.called, "callback called on clicking Component without moving pointer"); assert.deepEqual(callback.lastPoint, halfPoint, "was passed correct point"); }, done); }); it("provides correct release point to onClick callback on click", (done) => { clickPointWithMove(halfPoint, halfPoint, mode); runAsserts(() => { assert.isTrue(callback.called, "callback called on clicking and releasing inside the Component"); assert.deepEqual(callback.lastPoint, halfPoint, "was passed mouseup point"); }, done); }); it("does not invoke callback if interaction start and end in different locations", (done) => { clickPointWithMove(halfPoint, quarterPoint, mode); runAsserts(() => { assert.isFalse(callback.called, "callback not called if click is released at a different location"); }, done); }); it("does not invoke callback if click is released outside Component", (done) => { clickPointWithMove(halfPoint, outsidePoint, mode); runAsserts(() => { assert.isFalse(callback.called, "callback not called if click is released outside Component"); }, done); }); it("does not invoke callback if click is started outside Component", (done) => { clickPointWithMove(outsidePoint, halfPoint, mode); runAsserts(() => { assert.isFalse(callback.called, "callback not called if click was started outside Component"); }, done); }); it("invokes callback if the pointer is moved out then back inside the Component before releasing", (done) => { TestMethods.triggerFakeInteractionEvent(mode, TestMethods.InteractionType.Start, component.content(), DIV_WIDTH / 2, DIV_HEIGHT / 2); TestMethods.triggerFakeInteractionEvent(mode, TestMethods.InteractionType.Move, component.content(), DIV_WIDTH * 2, DIV_HEIGHT * 2); TestMethods.triggerFakeInteractionEvent(mode, TestMethods.InteractionType.End, component.content(), DIV_WIDTH / 2, DIV_HEIGHT / 2); runAsserts(() => { assert.isTrue( callback.called, "callback still called if the pointer is moved out then back inside the Component before releasing", ); }, done); }); if (mode === TestMethods.InteractionMode.Touch) { it("does not trigger callback if touch event is cancelled", (done) => { TestMethods.triggerFakeTouchEvent("touchstart", component.content(), [halfPoint]); TestMethods.triggerFakeTouchEvent("touchcancel", component.content(), [halfPoint]); TestMethods.triggerFakeTouchEvent("touchend", component.content(), [halfPoint]); runAsserts(() => { assert.isFalse(callback.called, "callback not called if touch was cancelled"); }, done); }); } }); }); describe(`invoking double click callbacks with mouse events`, () => { // The current implementation assumes there will be at least some delay between clicks it("silences click event associated with a double click event", (done) => { const singleClickCallback: ClickTestCallback = makeClickCallback(); const doubleClickCallback: ClickTestCallback = makeClickCallback(); clickInteraction.onClick(singleClickCallback); clickInteraction.onDoubleClick(doubleClickCallback); clickPoint(clickedPoint); setTimeout(() => { clickPoint(clickedPoint); TestMethods.triggerFakeMouseEvent("dblclick", component.content(), clickedPoint.x, clickedPoint.y); runAsserts(() => { assert.equal(singleClickCallback.calledCount, 1, "single click callback only called once on doubleclick"); assert.isTrue(doubleClickCallback.called, "double click callback called on doubleclick"); }, done); }, 0); }); it("does not invoke callback if clicking in the same place without doubleclick event", (done) => { const callback: ClickTestCallback = makeClickCallback(); clickInteraction.onDoubleClick(callback); clickPoint(clickedPoint); clickPoint(clickedPoint); runAsserts(() => { assert.isFalse(callback.called, "double click callback not called without double click event"); }, done); }); }); }); });
the_stack
import * as coreClient from "@azure/core-client"; /** Represents the SKU name and Azure pricing tier for Analysis Services resource. */ export interface ResourceSku { /** Name of the SKU level. */ name: string; /** The name of the Azure pricing tier to which the SKU applies. */ tier?: SkuTier; /** The number of instances in the read only query pool. */ capacity?: number; } /** An object that represents a set of mutable Analysis Services resource properties. */ export interface AnalysisServicesServerMutableProperties { /** A collection of AS server administrators */ asAdministrators?: ServerAdministrators; /** The SAS container URI to the backup container. */ backupBlobContainerUri?: string; /** The gateway details configured for the AS server. */ gatewayDetails?: GatewayDetails; /** The firewall settings for the AS server. */ ipV4FirewallSettings?: IPv4FirewallSettings; /** How the read-write server's participation in the query pool is controlled.<br/>It can have the following values: <ul><li>readOnly - indicates that the read-write server is intended not to participate in query operations</li><li>all - indicates that the read-write server can participate in query operations</li></ul>Specifying readOnly when capacity is 1 results in error. */ querypoolConnectionMode?: ConnectionMode; /** The managed mode of the server (0 = not managed, 1 = managed). */ managedMode?: ManagedMode; /** The server monitor mode for AS server */ serverMonitorMode?: ServerMonitorMode; } /** An array of administrator user identities. */ export interface ServerAdministrators { /** An array of administrator user identities. */ members?: string[]; } /** The gateway details. */ export interface GatewayDetails { /** Gateway resource to be associated with the server. */ gatewayResourceId?: string; /** * Gateway object id from in the DMTS cluster for the gateway resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly gatewayObjectId?: string; /** * Uri of the DMTS cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dmtsClusterUri?: string; } /** An array of firewall rules. */ export interface IPv4FirewallSettings { /** An array of firewall rules. */ firewallRules?: IPv4FirewallRule[]; /** The indicator of enabling PBI service. */ enablePowerBIService?: boolean; } /** The detail of firewall rule. */ export interface IPv4FirewallRule { /** The rule name. */ firewallRuleName?: string; /** The start range of IPv4. */ rangeStart?: string; /** The end range of IPv4. */ rangeEnd?: string; } /** Represents an instance of an Analysis Services resource. */ export interface Resource { /** * An identifier that represents the Analysis Services resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the Analysis Services resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the Analysis Services resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Location of the Analysis Services resource. */ location: string; /** The SKU of the Analysis Services resource. */ sku: ResourceSku; /** Key-value pairs of additional resource provisioning properties. */ tags?: { [propertyName: string]: string }; } /** Describes the format of Error response. */ export interface ErrorResponse { /** The error object */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error sub code * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly subCode?: number; /** * The http status code * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly httpStatusCode?: number; /** * the timestamp for the error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly timeStamp?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** Provision request specification */ export interface AnalysisServicesServerUpdateParameters { /** The SKU of the Analysis Services resource. */ sku?: ResourceSku; /** Key-value pairs of additional provisioning properties. */ tags?: { [propertyName: string]: string }; /** A collection of AS server administrators */ asAdministrators?: ServerAdministrators; /** The SAS container URI to the backup container. */ backupBlobContainerUri?: string; /** The gateway details configured for the AS server. */ gatewayDetails?: GatewayDetails; /** The firewall settings for the AS server. */ ipV4FirewallSettings?: IPv4FirewallSettings; /** How the read-write server's participation in the query pool is controlled.<br/>It can have the following values: <ul><li>readOnly - indicates that the read-write server is intended not to participate in query operations</li><li>all - indicates that the read-write server can participate in query operations</li></ul>Specifying readOnly when capacity is 1 results in error. */ querypoolConnectionMode?: ConnectionMode; /** The managed mode of the server (0 = not managed, 1 = managed). */ managedMode?: ManagedMode; /** The server monitor mode for AS server */ serverMonitorMode?: ServerMonitorMode; } /** An array of Analysis Services resources. */ export interface AnalysisServicesServers { /** An array of Analysis Services resources. */ value: AnalysisServicesServer[]; } /** An object that represents enumerating SKUs for new resources. */ export interface SkuEnumerationForNewResourceResult { /** The collection of available SKUs for new resources. */ value?: ResourceSku[]; } /** An object that represents enumerating SKUs for existing resources. */ export interface SkuEnumerationForExistingResourceResult { /** The collection of available SKUs for existing resources. */ value?: SkuDetailsForExistingResource[]; } /** An object that represents SKU details for existing resources. */ export interface SkuDetailsForExistingResource { /** The SKU in SKU details for existing resources. */ sku?: ResourceSku; /** The resource type. */ resourceType?: string; } /** Status of gateway is live. */ export interface GatewayListStatusLive { /** Live message of list gateway. Status: 0 - Live */ status?: "undefined"; } /** Status of gateway is error. */ export interface GatewayListStatusError { /** Error of the list gateway status. */ error?: ErrorDetail; } /** Details of server name request body. */ export interface CheckServerNameAvailabilityParameters { /** Name for checking availability. */ name?: string; /** The resource type of azure analysis services. */ type?: string; } /** The checking result of server name availability. */ export interface CheckServerNameAvailabilityResult { /** Indicator of available of the server name. */ nameAvailable?: boolean; /** The reason of unavailability. */ reason?: string; /** The detailed message of the request unavailability. */ message?: string; } /** The status of operation. */ export interface OperationStatus { /** The operation Id. */ id?: string; /** The operation name. */ name?: string; /** The start time of the operation. */ startTime?: string; /** The end time of the operation. */ endTime?: string; /** The status of the operation. */ status?: string; /** The error detail of the operation if any. */ error?: ErrorDetail; } /** Result of listing consumption operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationListResult { /** * List of analysis services operations supported by the Microsoft.AnalysisServices resource provider. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: 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; } /** A Consumption 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 origin * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly origin?: string; /** Additional properties to expose performance metrics to shoebox. */ properties?: OperationProperties; } /** The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.Consumption. * 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: UsageDetail, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * Operation type: Read, write, delete, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; /** * Description of the operation object. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; } /** Additional properties to expose performance metrics to shoebox. */ export interface OperationProperties { /** Performance metrics to shoebox. */ serviceSpecification?: OperationPropertiesServiceSpecification; } /** Performance metrics to shoebox. */ export interface OperationPropertiesServiceSpecification { /** * The metric specifications. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricSpecifications?: MetricSpecifications[]; /** * The log specifications. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly logSpecifications?: LogSpecifications[]; } /** Available operation metric specification for exposing performance metrics to shoebox. */ export interface MetricSpecifications { /** * The name of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The displayed name of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly displayName?: string; /** * The displayed description of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly displayDescription?: string; /** * The unit of the metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly unit?: string; /** * The aggregation type of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly aggregationType?: string; /** * The dimensions of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dimensions?: MetricDimensions[]; } /** Metric dimension. */ export interface MetricDimensions { /** * Dimension name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Dimension display name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly displayName?: string; } /** The log metric specification for exposing performance metrics to shoebox. */ export interface LogSpecifications { /** * The name of metric. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The displayed name of log. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly displayName?: string; /** * The blob duration for the log. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly blobDuration?: string; } /** Properties of Analysis Services resource. */ export type AnalysisServicesServerProperties = AnalysisServicesServerMutableProperties & { /** * The current state of Analysis Services resource. The state is to indicate more states outside of resource provisioning. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: State; /** * The current deployment state of Analysis Services resource. The provisioningState is to indicate states for resource provisioning. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningState; /** * The full name of the Analysis Services resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serverFullName?: string; /** The SKU of the Analysis Services resource. */ sku?: ResourceSku; }; /** Represents an instance of an Analysis Services resource. */ export type AnalysisServicesServer = Resource & { /** A collection of AS server administrators */ asAdministrators?: ServerAdministrators; /** The SAS container URI to the backup container. */ backupBlobContainerUri?: string; /** The gateway details configured for the AS server. */ gatewayDetails?: GatewayDetails; /** The firewall settings for the AS server. */ ipV4FirewallSettings?: IPv4FirewallSettings; /** How the read-write server's participation in the query pool is controlled.<br/>It can have the following values: <ul><li>readOnly - indicates that the read-write server is intended not to participate in query operations</li><li>all - indicates that the read-write server can participate in query operations</li></ul>Specifying readOnly when capacity is 1 results in error. */ querypoolConnectionMode?: ConnectionMode; /** The managed mode of the server (0 = not managed, 1 = managed). */ managedMode?: ManagedMode; /** The server monitor mode for AS server */ serverMonitorMode?: ServerMonitorMode; /** * The current state of Analysis Services resource. The state is to indicate more states outside of resource provisioning. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: State; /** * The current deployment state of Analysis Services resource. The provisioningState is to indicate states for resource provisioning. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningState; /** * The full name of the Analysis Services resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serverFullName?: string; /** The SKU of the Analysis Services resource. */ skuPropertiesSku?: ResourceSku; }; /** Known values of {@link State} that the service accepts. */ export enum KnownState { Deleting = "Deleting", Succeeded = "Succeeded", Failed = "Failed", Paused = "Paused", Suspended = "Suspended", Provisioning = "Provisioning", Updating = "Updating", Suspending = "Suspending", Pausing = "Pausing", Resuming = "Resuming", Preparing = "Preparing", Scaling = "Scaling" } /** * Defines values for State. \ * {@link KnownState} can be used interchangeably with State, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Deleting** \ * **Succeeded** \ * **Failed** \ * **Paused** \ * **Suspended** \ * **Provisioning** \ * **Updating** \ * **Suspending** \ * **Pausing** \ * **Resuming** \ * **Preparing** \ * **Scaling** */ export type State = string; /** Known values of {@link ProvisioningState} that the service accepts. */ export enum KnownProvisioningState { Deleting = "Deleting", Succeeded = "Succeeded", Failed = "Failed", Paused = "Paused", Suspended = "Suspended", Provisioning = "Provisioning", Updating = "Updating", Suspending = "Suspending", Pausing = "Pausing", Resuming = "Resuming", Preparing = "Preparing", Scaling = "Scaling" } /** * Defines values for ProvisioningState. \ * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Deleting** \ * **Succeeded** \ * **Failed** \ * **Paused** \ * **Suspended** \ * **Provisioning** \ * **Updating** \ * **Suspending** \ * **Pausing** \ * **Resuming** \ * **Preparing** \ * **Scaling** */ export type ProvisioningState = string; /** Known values of {@link SkuTier} that the service accepts. */ export enum KnownSkuTier { Development = "Development", Basic = "Basic", Standard = "Standard" } /** * Defines values for SkuTier. \ * {@link KnownSkuTier} can be used interchangeably with SkuTier, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Development** \ * **Basic** \ * **Standard** */ export type SkuTier = string; /** Defines values for ConnectionMode. */ export type ConnectionMode = "All" | "ReadOnly"; /** Defines values for ManagedMode. */ export type ManagedMode = 0 | 1; /** Defines values for ServerMonitorMode. */ export type ServerMonitorMode = 0 | 1; /** Optional parameters. */ export interface ServersGetDetailsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDetails operation. */ export type ServersGetDetailsResponse = AnalysisServicesServer; /** Optional parameters. */ export interface ServersCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type ServersCreateResponse = AnalysisServicesServer; /** Optional parameters. */ export interface ServersDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ServersUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type ServersUpdateResponse = AnalysisServicesServer; /** Optional parameters. */ export interface ServersSuspendOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ServersResumeOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ServersListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ServersListByResourceGroupResponse = AnalysisServicesServers; /** Optional parameters. */ export interface ServersListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ServersListResponse = AnalysisServicesServers; /** Optional parameters. */ export interface ServersListSkusForNewOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSkusForNew operation. */ export type ServersListSkusForNewResponse = SkuEnumerationForNewResourceResult; /** Optional parameters. */ export interface ServersListSkusForExistingOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSkusForExisting operation. */ export type ServersListSkusForExistingResponse = SkuEnumerationForExistingResourceResult; /** Optional parameters. */ export interface ServersListGatewayStatusOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listGatewayStatus operation. */ export type ServersListGatewayStatusResponse = GatewayListStatusLive; /** Optional parameters. */ export interface ServersDissociateGatewayOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ServersCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type ServersCheckNameAvailabilityResponse = CheckServerNameAvailabilityResult; /** Optional parameters. */ export interface ServersListOperationResultsOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ServersListOperationStatusesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listOperationStatuses operation. */ export type ServersListOperationStatusesResponse = OperationStatus; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface AzureAnalysisServicesOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { match, not, Pattern, select, when, __ } from '../src'; import { Equal, Expect } from '../src/types/helpers'; import { Option, some, none, BigUnion, State, Event } from './utils'; describe('large exhaustive', () => { // prettier-ignore type LargeObject = { a1: number; b1: number; c1: number; d1: number; e1: number; f1: number; g1: number; h1: number; i1: number; j1: number; k1: number; l1: number; m1: number; n1: number; o1: number; p1: number; q1: number; r1: number; s1: number; t1: number; u1: number; v1: number; w1: number; x1: number; y1: number; z1: number; a2: number; b2: number; c2: number; d2: number; e2: number; f2: number; g2: number; h2: number; i2: number; j2: number; k2: number; l2: number; m2: number; n2: number; o2: number; p2: number; q2: number; r2: number; s2: number; t2: number; u2: number; v2: number; w2: number; x2: number; y2: number; z2: number; a3: number; b3: number; c3: number; d3: number; e3: number; f3: number; g3: number; h3: number; i3: number; j3: number; k3: number; l3: number; m3: number; n3: number; o3: number; p3: number; q3: number; r3: number; s3: number; t3: number; u3: number; v3: number; w3: number; x3: number; y3: number; z3: number; }; it('large objects', () => { expect( match<LargeObject | null>(null) .with( // prettier-ignore { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, }, (x) => 'match' ) .with(null, () => 'Null') .with( // prettier-ignore { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, }, () => 'nope' ) .exhaustive() ).toBe('Null'); }); it('large tuple', () => { expect( match< [LargeObject, LargeObject, LargeObject, LargeObject, LargeObject] | null >(null) .with( // prettier-ignore [ { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, }, { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, }, { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, }, { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, }, { a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0, g1: 0, h1: 0, i1: 0, j1: 0, k1: 0, l1: 0, m1: 0, n1: 0, o1: 0, p1: 0, q1: 0, r1: 0, s1: 0, t1: 0, u1: 0, v1: 0, w1: 0, x1: 0, y1: 0, z1: 0, a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0, g2: 0, h2: 0, i2: 0, j2: 0, k2: 0, l2: 0, m2: 0, n2: 0, o2: 0, p2: 0, q2: 0, r2: 0, s2: 0, t2: 0, u2: 0, v2: 0, w2: 0, x2: 0, y2: 0, z2: 0, a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0, g3: 0, h3: 0, i3: 0, j3: 0, k3: 0, l3: 0, m3: 0, n3: 0, o3: 0, p3: 0, q3: 0, r3: 0, s3: 0, t3: 0, u3: 0, v3: 0, w3: 0, x3: 0, y3: 0, z3: 0, } ], (x) => { type t = Expect< Equal< typeof x, [ LargeObject, LargeObject, LargeObject, LargeObject, LargeObject ] > >; return 'match'; } ) .with(null, () => 'Null') .with( // prettier-ignore [ { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, }, { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, }, { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, }, { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, }, { a1: __.number, b1: __.number, c1: __.number, d1: __.number, e1: __.number, f1: __.number, g1: __.number, h1: __.number, i1: __.number, j1: __.number, k1: __.number, l1: __.number, m1: __.number, n1: __.number, o1: __.number, p1: __.number, q1: __.number, r1: __.number, s1: __.number, t1: __.number, u1: __.number, v1: __.number, w1: __.number, x1: __.number, y1: __.number, z1: __.number, a2: __.number, b2: __.number, c2: __.number, d2: __.number, e2: __.number, f2: __.number, g2: __.number, h2: __.number, i2: __.number, j2: __.number, k2: __.number, l2: __.number, m2: __.number, n2: __.number, o2: __.number, p2: __.number, q2: __.number, r2: __.number, s2: __.number, t2: __.number, u2: __.number, v2: __.number, w2: __.number, x2: __.number, y2: __.number, z2: __.number, a3: __.number, b3: __.number, c3: __.number, d3: __.number, e3: __.number, f3: __.number, g3: __.number, h3: __.number, i3: __.number, j3: __.number, k3: __.number, l3: __.number, m3: __.number, n3: __.number, o3: __.number, p3: __.number, q3: __.number, r3: __.number, s3: __.number, t3: __.number, u3: __.number, v3: __.number, w3: __.number, x3: __.number, y3: __.number, z3: __.number, } ], () => 'nope' ) .exhaustive() ).toBe('Null'); }); // prettier-ignore type DeepObject = { 1: { 2: { 3: { 4: { a: number; b: number; c: number; d: number; e: number; f: number; g: number; h: number; i: number; j: number; k: number; l: number; m: number; n: number; o: number; p: number; q: number; r: number; s: number; t: number; u: number; v: number; w: number; x: number; y: number; z: number; } } } } }; it('deep objects', () => { expect( match<DeepObject | null>(null) .with( // prettier-ignore { 1: { 2: { 3: { 4: { a: 0, b: 0, c: 0, d: 0, e: 0, f: 0, g: 0, h: 0, i: 0, j: 0, k: 0, l: 0, m: 0, n: 0, o: 0, p: 0, q: 0, r: 0, s: 0, t: 0, u: 0, v: 0, w: 0, x: 0, y: 0, z: 0, } } } } }, (x) => 'match' ) .with(null, () => 'Null') .with( // prettier-ignore { 1: { 2: { 3: { 4: { a: __.number, b: __.number, c: __.number, d: __.number, e: __.number, f: __.number, g: __.number, h: __.number, i: __.number, j: __.number, k: __.number, l: __.number, m: __.number, n: __.number, o: __.number, p: __.number, q: __.number, r: __.number, s: __.number, t: __.number, u: __.number, v: __.number, w: __.number, x: __.number, y: __.number, z: __.number, } } } } }, () => 'nope' ) .exhaustive() ).toBe('Null'); }); });
the_stack
import Base from '~/src/command/base' import MBlog from '~/src/model/mblog' import MblogUser from '~/src/model/mblog_user' import fs from 'fs' import path from 'path' // import path from 'path' // import jsPDF from '~/src/library/pdf/jspdf.node.js' // import { BrowserWindow } from 'electron' // import CommonUtil from '~/src/library/util/common' // import { TypeTransConfigPackageList } from './generate/trans_config' import imageSize from 'image-size' import * as mozjpeg from "mozjpeg-js" import sharp from "sharp" // const outputUri = path.resolve('F:/www/share/github/stablog/缓存文件/pdf_debug_1.pdf') // /** // * 单张页面渲染时间不能超过20秒 // */ // const Const_Render_Html_Timeout_Second = 20 // /** // * 渲染webview最大高度(经实验, 当Electron窗口高度超过16380时, 会直接黑屏卡死, 所以需要专门限制下) // */ // const Const_Max_Webview_Render_Height_Px = 5000 // // 硬编码传入 // // let globalSubWindow: InstanceType<typeof BrowserWindow> = null // const Const_Default_Webview_Width = 760; // const Const_Default_Webview_Height = 10; class CommandDebug extends Base { static get signature() { return ` debug ` } static get description() { return '专业Debug' } async execute() { const Const_Max_Webview_Render_Height_Px = 5000 const Const_Default_Webview_Width = 760; let inputList: any[] = [] let totalImgCount = 16; let baseUri = path.resolve("F:/www/share/github/win_stablog/缓存文件/test_img/测试图片_2018-08-04 07:46:07_4269199607885116_") for (let imgIndex = 0; imgIndex < totalImgCount; imgIndex++) { let filename = `${baseUri}${imgIndex}.jpg` let content = fs.readFileSync(filename) inputList.push({ input: content, top: Const_Max_Webview_Render_Height_Px * imgIndex, left: 0, }) } let mergeImg = sharp({ create: { width: Const_Default_Webview_Width, height: Const_Max_Webview_Render_Height_Px * totalImgCount, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1, }, } }).png({ // "force": false, }) mergeImg.composite( inputList ) let pngContent = await mergeImg.toBuffer().catch(e => { this.log("mergeImg error => ", e) return new Buffer("") }) let outputPngImage = baseUri + 'output_all_png.png' fs.writeFileSync(outputPngImage, pngContent) // let outputImage_v2 = baseUri + 'output_all_jpg.jpg' // let a = await Jimp.read(pngContent) // let raw_jpgContent = await a.writeAsync(outputImage_v2) // fs.writeFileSync(outputImage_v2, raw_jpgContent) // let outputImage_v3 = baseUri + 'output_all_tiny_jpg.jpg' // let out = mozjpeg.encode(raw_jpgContent, { // //处理质量 百分比 // quality: 80 // }); // let d = out.data // fs.writeFileSync(outputImage_v3, d) // await images(jpgContent).save(outputImage, "jpeg") // let imgSize = imageSize.imageSize(jpgContent) // console.log({ // width: imgSize.width as number, // height: imgSize.height as number, // }) // let result = await sharp({ // create: { // width: 760, // height: 60000, // channels: 4, // background: { // r: 255, g: 255, b: 255, alpha: 1, // }, // } // }) // .png({ // "colors": // "compressionLevel": 9, // }) // .toBuffer() // .catch(e => { // console.log(e) // }) fs.writeFileSync(`${baseUri}final.jpg`, pngContent) // await MblogUser.asyncGetUserList() // let configUri = path.resolve("F:/www/share/github/stablog/缓存文件/pdf_html_config.json") // let content = fs.readFileSync(configUri).toString() // let weiboDayConfigList = JSON.parse(content) // this.generatePdf([ // ...weiboDayConfigList, // ...weiboDayConfigList, // ...weiboDayConfigList, // ...weiboDayConfigList, // ...weiboDayConfigList, // ...weiboDayConfigList, // ]) // let result = await MBlog.autoUpdate() // this.log(`debug it`) // console.log(result) } // async generatePdf(weiboDayList: TypeTransConfigPackageList) { // let doc = new jsPDF({ // unit: 'px', // format: [Const_Default_Webview_Width, 500], // orientation: "landscape" // }) // // let fontUri = path.resolve(__dirname, '../../public/font/alibaba_PuHuiTi_Regular.ttf') // // let fontContent = fs.readFileSync(fontUri) // // let fontName = "alibaba_PuHuiTi_Regular" // // doc.addFileToVFS(`${fontName}.ttf`, fontContent.toString("base64")) // // doc.addFont(`${fontName}.ttf`, fontName, "normal") // // doc.setFont(fontName, "normal"); // // doc.setFontSize(32) // // demo => yaozeyuan93-微博整理-第1/2卷-(2011-07-07~2012-01-25) // let rawBooktitle = 'yaozeyuan93-微博整理-第1/2卷-(2011-07-07~2012-01-25)'//this.bookname // let contentList = rawBooktitle.split(`-微博整理-`) // let accountName = contentList[0] // let timeRangeStartAt = contentList[1].indexOf('(') // let timeRangeEndAt = contentList[1].indexOf(')') // let timeRangeStr = contentList[1].slice(timeRangeStartAt + '('.length, timeRangeEndAt) // let columnStartAt = contentList[1].indexOf('第') // let columnEndAt = contentList[1].indexOf('卷') // let columnStr = '' // if (columnStartAt >= 0) { // // 先把关键语句提取出来, 后续根据需要再处理 // columnStr = contentList[1].slice(columnStartAt + '第'.length, columnEndAt) // columnStr = `-第${columnStr}卷` // } // let lineAt = 0 // let lineHeight = 40 // let paddingLeft = Const_Default_Webview_Width / 2 // function addLine(content: string) { // lineAt = lineAt + 1 // doc.text(content, paddingLeft, lineHeight * lineAt, { // align: 'center', // }) // } // function addLink(content: string) { // lineAt = lineAt + 1 // doc.setTextColor("blue") // doc.textWithLink(content, paddingLeft, lineHeight * lineAt, { // align: 'center', // url: content // }) // } // addLine("") // addLine(accountName) // addLine(`微博整理${columnStr}`) // addLine(timeRangeStr) // addLine("") // addLine("该文件由稳部落自动生成") // addLine("") // addLine("项目主页") // addLink("https://www.yaozeyuan.online/stablog") // let currentPageNo = 2 // let outlineConfigList: { // title: string, // pageNo: number, // }[] = [] // let debugCounter = 0 // // 先加一页, 避免出现空白页 // let dayIndex = 0 // for (let weiboDayRecord of weiboDayList) { // dayIndex++ // this.log(`将页面${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)添加到pdf文件中`) // let weiboIndex = 0 // outlineConfigList.push({ // title: weiboDayRecord.title, // pageNo: currentPageNo, // }) // for (let weiboRecord of weiboDayRecord.configList) { // debugCounter++ // weiboIndex++ // this.log( // `[${debugCounter}]正在添加页面${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)下,第${weiboIndex}/${weiboDayRecord.configList.length}条微博`, // ) // let imgUri = weiboRecord.imageUri // if (fs.existsSync(imgUri) === false) { // // 图片渲染失败 // this.log(`第${weiboIndex}/${weiboDayRecord.configList.length}条微博渲染失败, 自动跳过`) // continue // } else { // let imageBuffer = fs.readFileSync(imgUri) // let size = await imageSize.imageSize(imageBuffer) // let { width, height } = size // if (!width || width <= 0 || !height || height <= 0) { // this.log(`第${weiboIndex}/${weiboDayRecord.configList.length}条微博截图捕获失败, 自动跳过`) // continue // } // doc.addPage([width, height], width > height ? "landscape" : "portrait") // doc.addImage( // { // imageData: imageBuffer, // x: 0, // y: 0, // width: width, // height: height // }) // doc.setFontSize(0.001) // doc.text(weiboRecord.htmlContent, 0, 0, { // // align: 'center', // }) // currentPageNo = currentPageNo + 1 // } // } // } // this.log("开始创建导航栏") // // 开始补充导航栏 // var node = doc.outline.add(null, '首页', { pageNumber: 1 }); // // 通过hack的方式, 生成年月日三级目录 // type Type_Node = { // node: any, // pageNo: number, // children: { // [key: string]: Type_Node // } // } // let node_map: { // [year: string]: Type_Node // } = {} // for (let outlineConfig of outlineConfigList) { // let [year, month, day] = outlineConfig.title.split('-'); // if (node_map[year] === undefined) { // // 初始化年份 // let yearNode = doc.outline.add(node, year, { pageNumber: outlineConfig.pageNo }); // node_map[year] = { // node: yearNode, // pageNo: outlineConfig.pageNo, // children: {} // } // let monthNode = doc.outline.add(yearNode, `${year}-${month}`, { pageNumber: outlineConfig.pageNo }); // node_map[year] = { // node: yearNode, // pageNo: outlineConfig.pageNo, // children: { // [month]: { // node: monthNode, // pageNo: outlineConfig.pageNo, // children: {} // } // } // } // let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); // node_map[year] = { // node: yearNode, // pageNo: outlineConfig.pageNo, // children: { // [month]: { // node: monthNode, // pageNo: outlineConfig.pageNo, // children: { // [day]: { // node: dayNode, // pageNo: outlineConfig.pageNo, // children: {} // } // } // } // } // } // continue; // } // if (node_map[year]['children'][month] === undefined) { // // 初始化月份 // let yearNode = node_map[year]['node'] // let monthNode = doc.outline.add(yearNode, `${year}-${month}`, { pageNumber: outlineConfig.pageNo }); // node_map[year]['children'][month] = { // node: monthNode, // pageNo: outlineConfig.pageNo, // children: {} // } // let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); // node_map[year]['children'][month]['children'][day] = { // node: dayNode, // pageNo: outlineConfig.pageNo, // children: {} // } // continue; // } // // 否则, 添加日期节点 // let yearNode = node_map[year]['node'] // let monthNode = node_map[year]['children'][month]['node'] // let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); // node_map[year]['children'][month]['children'][day] = { // node: dayNode, // pageNo: outlineConfig.pageNo, // children: {} // } // } // this.log("开始输出文件") // await doc.save(outputUri, { returnPromise: true }) // this.log(`pdf输出完毕`) // } } export default CommandDebug
the_stack
import { observable } from 'mobx' import { observer } from 'mobx-react' import * as React from 'react' import * as ReactDOM from 'react-dom' import * as xmldom from 'xmldom' import * as xpath from 'xpath' import { Paper } from '../api/document' import '../App.css' import { pageElementModal } from '../arxiv_page' import { API_ARXIV_METADATA, API_CROSSREF_CITE } from '../bib_config' import { normalize_whitespace, random_id } from '../bib_lib' // FIXME -- add https://crosscite.org/ const provider_desc = { arxiv: 'arXiv API', doi: 'Crossref Citation Format' } const provider_url = { arxiv: 'https://arxiv.org/help/api/index', doi: 'https://www.crossref.org/labs/citation-formatting-service/' } const STOPWORDS = new Set(['a', 'about', 'above', 'above', 'across', 'after', 'afterwards', 'again', 'against', 'all', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always', 'am', 'among', 'amongst', 'amoungst', 'amount', 'an', 'and', 'another', 'any', 'anyhow', 'anyone', 'anything', 'anyway', 'anywhere', 'are', 'around', 'as', 'at', 'back', 'be', 'became', 'because', 'become', 'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below', 'beside', 'besides', 'between', 'beyond', 'bill', 'both', 'bottom', 'but', 'by', 'call', 'can', 'cannot', 'cant', 'co', 'con', 'could', 'couldnt', 'cry', 'de', 'describe', 'detail', 'do', 'done', 'down', 'due', 'during', 'each', 'eg', 'eight', 'either', 'eleven', 'else', 'elsewhere', 'empty', 'enough', 'etc', 'even', 'ever', 'every', 'everyone', 'everything', 'everywhere', 'except', 'few', 'fifteen', 'fify', 'fill', 'find', 'fire', 'first', 'five', 'for', 'former', 'formerly', 'forty', 'found', 'four', 'from', 'front', 'full', 'further', 'get', 'give', 'go', 'had', 'has', 'hasnt', 'have', 'he', 'hence', 'her', 'here', 'hereafter', 'hereby', 'herein', 'hereupon', 'hers', 'herself', 'him', 'himself', 'his', 'how', 'however', 'hundred', 'ie', 'if', 'in', 'inc', 'indeed', 'interest', 'into', 'is', 'it', 'its', 'itself', 'keep', 'last', 'latter', 'latterly', 'least', 'less', 'ltd', 'made', 'many', 'may', 'me', 'meanwhile', 'might', 'mill', 'mine', 'more', 'moreover', 'most', 'mostly', 'move', 'much', 'must', 'my', 'myself', 'name', 'namely', 'neither', 'never', 'nevertheless', 'next', 'nine', 'no', 'nobody', 'none', 'noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of', 'off', 'often', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'part', 'per', 'perhaps', 'please', 'put', 'rather', 're', 'same', 'see', 'seem', 'seemed', 'seeming', 'seems', 'serious', 'several', 'she', 'should', 'show', 'side', 'since', 'sincere', 'six', 'sixty', 'so', 'some', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhere', 'still', 'such', 'system', 'take', 'ten', 'than', 'that', 'the', 'their', 'them', 'themselves', 'then', 'thence', 'there', 'thereafter', 'thereby', 'therefore', 'therein', 'thereupon', 'these', 'they', 'thickv', 'thin', 'third', 'this', 'those', 'though', 'three', 'through', 'throughout', 'thru', 'thus', 'to', 'together', 'too', 'top', 'toward', 'towards', 'twelve', 'twenty', 'two', 'un', 'under', 'until', 'up', 'upon', 'us', 'very', 'via', 'was', 'we', 'well', 'were', 'what', 'whatever', 'when', 'whence', 'whenever', 'where', 'whereafter', 'whereas', 'whereby', 'wherein', 'whereupon', 'wherever', 'whether', 'which', 'while', 'whither', 'who', 'whoever', 'whole', 'whom', 'whose', 'why', 'will', 'with', 'within', 'without', 'would', 'yet', 'you', 'your', 'yours', 'yourself', 'yourselves', 'the']) @observer export class CiteModal extends React.Component<{ paper: Paper }, {}> { cache = {} @observable active: boolean = true @observable source: 'arxiv' | 'doi' = 'doi' @observable format: 'bibtex' | 'mla' = 'bibtex' @observable content: string = '' constructor(props: any) { super(props) if (!this.props.paper.doi) { this.source = 'arxiv' } this.active = true this.query() } key(): string { return `${this.source}_${this.format}` } get cached_value(): string { return this.cache[this.key()] } set cached_value(val: string) { this.cache[this.key()] = val } chars_only(data: string): string { return data.replace(/[^a-z0-9 ]/gmi, '') } fmt_first_last_name(data: string) { const name = this.chars_only(data).split('and') if (name.length <= 0) { return 'unknown' } const parts = name[0].trim().split(' ') if (parts.length <= 0) { return 'unknown' } return parts[parts.length - 1] } fmt_first_nonstop(data: string) { const words = this.chars_only(data).split(' ') if (words.length <= 0) { return 'unknown' } for (const word of words) { if (!STOPWORDS.has(word.toLocaleLowerCase())) { return word } } return 'unknown' } fmt_author_list(authors: any[]): string { /*if (authors.length >= 10) { authors = authors.slice(0, 10) authors.push('others') }*/ return authors.map((i) => i.toString().trim()).join(' and ') } format_bibtex_arxiv(data: string) { const parser = new xmldom.DOMParser() const xml = parser.parseFromString(data, 'text/xml') const select = xpath.useNamespaces({ atom: 'http://www.w3.org/2005/Atom', arxiv: 'http://arxiv.org/schemas/atom' }) const title = select('string(//atom:entry/atom:title/text())', xml) const auths = select('//atom:entry/atom:author/atom:name/text()', xml) const year = select('//atom:entry/atom:published/text()', xml) const primary = select('string(//atom:entry/arxiv:primary_category/@term)', xml) const txt_title = normalize_whitespace(title.toString()) const txt_auths = this.fmt_author_list(auths) const txt_year = year.toString().split('-')[0] const id_auths = this.fmt_first_last_name(txt_auths).toLocaleLowerCase() const id_title = this.fmt_first_nonstop(txt_title).toLocaleLowerCase() const txt_id = this.chars_only(`${id_auths}${txt_year}${id_title}`) const output = `@misc{${txt_id}, title={${txt_title}}, author={${txt_auths}}, year={${txt_year}}, eprint={${this.props.paper.arxivId}}, archivePrefix={arXiv}, primaryClass={${primary}} }` return output } format_mla_doi(data: string) { data = data.replace('Crossref. Web.', '') return data } format_bibtex_doi(data: string) { data = data.replace(/^\s+/, '') data = data.replace(/},/g, '},\n ') data = data.replace(', title=', ',\n title=') data = data.replace('}}', '}\n}') return data } query_arxiv() { this.content = '' if (this.cached_value) { this.content = this.cached_value return } const url: string = API_ARXIV_METADATA + this.props.paper.arxivId fetch(url) .then(resp => error_check(resp)) .then(resp => resp.text()) .then(txt => { this.content = this.format_bibtex_arxiv(txt) this.cached_value = this.content }) .catch((e) => this.content = e.message) } query_doi() { this.content = '' if (this.cached_value) { this.content = this.cached_value return } const url: string = API_CROSSREF_CITE + this.props.paper.doi const headers = {headers: {Accept: `text/bibliography; style=${this.format}`}} fetch(url, headers) .then(resp => error_check(resp)) .then(resp => resp.text()) .then(txt => { this.content = this.format_bibtex_doi(txt) this.cached_value = this.content }) .catch((e) => this.content = e.message) } query() { if (this.source === 'arxiv') { this.query_arxiv() } else { this.query_doi() } } change_source(event: any) { this.source = event.target.value if (this.source === 'arxiv') { this.format = 'bibtex' } this.query() } change_format(event: any) { this.format = event.target.value this.query() } public render() { const paper = this.props.paper if (!this.active || (!paper.doi && !paper.arxivId)) { return null } const hasarxiv = !(paper.arxivId == null) const hasdoi = !(paper.doi == null || paper.doi === '') const hasmla = !(this.source === 'arxiv') return ( <div className='modal'> <div className='modal-content'> <div className='modal-title'> <h2>Export formatted citation</h2> <span className='modal-close' onClick={() => {this.active = false}}>&times;</span> </div> <div className='modal-buttons'> <div className='modal-button-group'> <h4>Article to reference:</h4> <input id='doi' type='radio' name='article' value='doi' checked={this.source === 'doi'} onChange={this.change_source.bind(this)} disabled={!hasdoi} /> <label htmlFor='doi' className={hasdoi ? '' : 'disabled'}>Journal article</label> <br/> <input id='arxiv' type='radio' name='article' value='arxiv' checked={this.source === 'arxiv'} onChange={this.change_source.bind(this)} disabled={!hasarxiv} /> <label htmlFor='arxiv' className={hasarxiv ? '' : 'disabled'}>arXiv e-print</label> <br/> </div> <div className='modal-button-group'> <h4>Reference format:</h4> <input id='bibtex' type='radio' name='format' value='bibtex' checked={this.format === 'bibtex'} onChange={this.change_format.bind(this)} /> <label htmlFor='bibtex'>BibTeX</label> <br/> <input id='mla' type='radio' name='format' value='mla' checked={this.format === 'mla'} onChange={this.change_format.bind(this)} disabled={!hasmla} /> <label htmlFor='mla' className={hasmla ? '' : 'disabled'}>MLA</label> <br/> </div> </div> <div> <h4>Formatted citation:</h4> <textarea rows={15} cols={75} value={this.content || 'loading...'}></textarea> </div> <div> <span>Data provided by: </span> <a href={provider_url[this.source]}>{provider_desc[this.source]}</a> </div> </div> </div> ) } } export function cite_modal(paper: Paper) { ReactDOM.render( <CiteModal paper={paper} key={random_id()} />, pageElementModal() ) } function error_check(response: Response) { if (response.status === 200) { return response } switch (response.status) { case 0: throw new Error('Query prevented by browser -- CORS, firewall, or unknown error') case 404: throw new Error('Citation entry not found.') case 500: throw new Error('Citation entry returned 500: internal server error') default: throw new Error('Citation error ' + response.status) } }
the_stack
import { HttpResponse, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs';import { HttpOptions } from '../../types'; import * as models from '../../models'; export interface ReposAPIClientInterface { /** * Arguments object for method `deleteReposOwnerRepo`. */ deleteReposOwnerRepoParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a Repository. * Deleting a repository requires admin access. If OAuth is used, the delete_repo * scope is required. * * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepo( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepo( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepo( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepo`. */ getReposOwnerRepoParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepo( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repo>; getReposOwnerRepo( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repo>>; getReposOwnerRepo( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repo>>; /** * Arguments object for method `patchReposOwnerRepo`. */ patchReposOwnerRepoParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.RepoEdit, }; /** * Edit repository. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepo( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repo>; patchReposOwnerRepo( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repo>>; patchReposOwnerRepo( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repo>>; /** * Arguments object for method `getReposOwnerRepoAssignees`. */ getReposOwnerRepoAssigneesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List assignees. * This call lists all the available assignees (owner + collaborators) to which * issues may be assigned. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoAssignees( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Assignees>; getReposOwnerRepoAssignees( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Assignees>>; getReposOwnerRepoAssignees( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Assignees>>; /** * Arguments object for method `getReposOwnerRepoAssigneesAssignee`. */ getReposOwnerRepoAssigneesAssigneeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Login of the assignee. */ assignee: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Check assignee. * You may also check to see if a particular user is an assignee for a repository. * * Response generated for [ 204 ] HTTP response code. */ getReposOwnerRepoAssigneesAssignee( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getReposOwnerRepoAssigneesAssignee( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getReposOwnerRepoAssigneesAssignee( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoAssigneesAssigneeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoBranches`. */ getReposOwnerRepoBranchesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of branches * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoBranches( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Branches>; getReposOwnerRepoBranches( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Branches>>; getReposOwnerRepoBranches( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Branches>>; /** * Arguments object for method `getReposOwnerRepoBranchesBranch`. */ getReposOwnerRepoBranchesBranchParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Name of the branch. */ branch: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get Branch * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoBranchesBranch( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Branch>; getReposOwnerRepoBranchesBranch( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Branch>>; getReposOwnerRepoBranchesBranch( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoBranchesBranchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Branch>>; /** * Arguments object for method `getReposOwnerRepoCollaborators`. */ getReposOwnerRepoCollaboratorsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List. * When authenticating as an organization owner of an organization-owned * repository, all organization owners are included in the list of * collaborators. Otherwise, only users with access to the repository are * returned in the collaborators list. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCollaborators( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getReposOwnerRepoCollaborators( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getReposOwnerRepoCollaborators( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `deleteReposOwnerRepoCollaboratorsUser`. */ deleteReposOwnerRepoCollaboratorsUserParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Login of the user. */ user: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Remove collaborator. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoCollaboratorsUser`. */ getReposOwnerRepoCollaboratorsUserParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Login of the user. */ user: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Check if user is a collaborator * Response generated for [ 204 ] HTTP response code. */ getReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `putReposOwnerRepoCollaboratorsUser`. */ putReposOwnerRepoCollaboratorsUserParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Login of the user. */ user: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Add collaborator. * Response generated for [ 204 ] HTTP response code. */ putReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putReposOwnerRepoCollaboratorsUser( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoCollaboratorsUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoComments`. */ getReposOwnerRepoCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List commit comments for a repository. * Comments are ordered by ascending ID. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RepoComments>; getReposOwnerRepoComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RepoComments>>; getReposOwnerRepoComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RepoComments>>; /** * Arguments object for method `deleteReposOwnerRepoCommentsCommentId`. */ deleteReposOwnerRepoCommentsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a commit comment * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoCommentsCommentId`. */ getReposOwnerRepoCommentsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single commit comment. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitComments>; getReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitComments>>; getReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitComments>>; /** * Arguments object for method `patchReposOwnerRepoCommentsCommentId`. */ patchReposOwnerRepoCommentsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommentBody, }; /** * Update a commit comment. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitComments>; patchReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitComments>>; patchReposOwnerRepoCommentsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoCommentsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitComments>>; /** * Arguments object for method `getReposOwnerRepoCommits`. */ getReposOwnerRepoCommitsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * The time should be passed in as UTC in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Example: "2012-10-09T23:39:01Z". * */ since?: string, /** Sha or branch to start listing commits from. */ sha?: string, /** Only commits containing this file path will be returned. */ path?: string, /** GitHub login, name, or email by which to filter by commit author. */ author?: string, /** ISO 8601 Date - Only commits before this date will be returned. */ until?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List commits on a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Commits>; getReposOwnerRepoCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Commits>>; getReposOwnerRepoCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Commits>>; /** * Arguments object for method `getReposOwnerRepoCommitsRefStatus`. */ getReposOwnerRepoCommitsRefStatusParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the combined Status for a specific Ref * The Combined status endpoint is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the blog post for full details. * To access this endpoint during the preview period, you must provide a custom media type in the Accept header: * application/vnd.github.she-hulk-preview+json * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCommitsRefStatus( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RefStatus>; getReposOwnerRepoCommitsRefStatus( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RefStatus>>; getReposOwnerRepoCommitsRefStatus( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsRefStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RefStatus>>; /** * Arguments object for method `getReposOwnerRepoCommitsShaCode`. */ getReposOwnerRepoCommitsShaCodeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** SHA-1 code of the commit. */ shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single commit. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Commit>; getReposOwnerRepoCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Commit>>; getReposOwnerRepoCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Commit>>; /** * Arguments object for method `getReposOwnerRepoCommitsShaCodeComments`. */ getReposOwnerRepoCommitsShaCodeCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** SHA-1 code of the commit. */ shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments for a single commitList comments for a single commit. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RepoComments>; getReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RepoComments>>; getReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RepoComments>>; /** * Arguments object for method `postReposOwnerRepoCommitsShaCodeComments`. */ postReposOwnerRepoCommitsShaCodeCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** SHA-1 code of the commit. */ shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommitBody, }; /** * Create a commit comment. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitComments>; postReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitComments>>; postReposOwnerRepoCommitsShaCodeComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoCommitsShaCodeCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitComments>>; /** * Arguments object for method `getReposOwnerRepoCompareBaseIdHeadId`. */ getReposOwnerRepoCompareBaseIdHeadIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, baseId: string, headId: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Compare two commits * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoCompareBaseIdHeadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CompareCommits>; getReposOwnerRepoCompareBaseIdHeadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CompareCommits>>; getReposOwnerRepoCompareBaseIdHeadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoCompareBaseIdHeadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CompareCommits>>; /** * Arguments object for method `deleteReposOwnerRepoContentsPath`. */ deleteReposOwnerRepoContentsPathParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, path: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.DeleteFileBody, }; /** * Delete a file. * This method deletes a file in a repository. * * Response generated for [ 200 ] HTTP response code. */ deleteReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.DeleteFile>; deleteReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.DeleteFile>>; deleteReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.DeleteFile>>; /** * Arguments object for method `getReposOwnerRepoContentsPath`. */ getReposOwnerRepoContentsPathParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, path: string, /** The content path. */ queryPath?: string, /** The String name of the Commit/Branch/Tag. Defaults to 'master'. */ ref?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get contents. * This method returns the contents of a file or directory in a repository. * Files and symlinks support a custom media type for getting the raw content. * Directories and submodules do not support custom media types. * Note: This API supports files up to 1 megabyte in size. * Here can be many outcomes. For details see "http://developer.github.com/v3/repos/contents/" * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ContentsPath>; getReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ContentsPath>>; getReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ContentsPath>>; /** * Arguments object for method `putReposOwnerRepoContentsPath`. */ putReposOwnerRepoContentsPathParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, path: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CreateFileBody, }; /** * Create a file. * Response generated for [ 200 ] HTTP response code. */ putReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CreateFile>; putReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CreateFile>>; putReposOwnerRepoContentsPath( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoContentsPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CreateFile>>; /** * Arguments object for method `getReposOwnerRepoContributors`. */ getReposOwnerRepoContributorsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Set to 1 or true to include anonymous contributors in results. */ anon: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of contributors. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Contributors>; getReposOwnerRepoContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Contributors>>; getReposOwnerRepoContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Contributors>>; /** * Arguments object for method `getReposOwnerRepoDeployments`. */ getReposOwnerRepoDeploymentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Users with pull access can view deployments for a repository * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RepoDeployments>; getReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RepoDeployments>>; getReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RepoDeployments>>; /** * Arguments object for method `postReposOwnerRepoDeployments`. */ postReposOwnerRepoDeploymentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Deployment, }; /** * Users with push access can create a deployment for a given ref * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.DeploymentResp>; postReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.DeploymentResp>>; postReposOwnerRepoDeployments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.DeploymentResp>>; /** * Arguments object for method `getReposOwnerRepoDeploymentsIdStatuses`. */ getReposOwnerRepoDeploymentsIdStatusesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** The Deployment ID to list the statuses from. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Users with pull access can view deployment statuses for a deployment * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.DeploymentStatuses>; getReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.DeploymentStatuses>>; getReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.DeploymentStatuses>>; /** * Arguments object for method `postReposOwnerRepoDeploymentsIdStatuses`. */ postReposOwnerRepoDeploymentsIdStatusesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** The Deployment ID to list the statuses from. */ id: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.DeploymentStatusesCreate, }; /** * Create a Deployment Status * Users with push access can create deployment statuses for a given deployment: * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; postReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; postReposOwnerRepoDeploymentsIdStatuses( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoDeploymentsIdStatusesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoDownloads`. */ getReposOwnerRepoDownloadsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Deprecated. List downloads for a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoDownloads( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Downloads>; getReposOwnerRepoDownloads( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Downloads>>; getReposOwnerRepoDownloads( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Downloads>>; /** * Arguments object for method `deleteReposOwnerRepoDownloadsDownloadId`. */ deleteReposOwnerRepoDownloadsDownloadIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of download. */ downloadId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Deprecated. Delete a download. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoDownloadsDownloadId`. */ getReposOwnerRepoDownloadsDownloadIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of download. */ downloadId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Deprecated. Get a single download. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Downloads>; getReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Downloads>>; getReposOwnerRepoDownloadsDownloadId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoDownloadsDownloadIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Downloads>>; /** * Arguments object for method `getReposOwnerRepoEvents`. */ getReposOwnerRepoEventsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of repository events. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Events>; getReposOwnerRepoEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Events>>; getReposOwnerRepoEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Events>>; /** * Arguments object for method `getReposOwnerRepoForks`. */ getReposOwnerRepoForksParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** If not set, server will use the default value: newes */ sort?: ('newes' | 'oldes' | 'watchers'), /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List forks. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Forks>; getReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Forks>>; getReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Forks>>; /** * Arguments object for method `postReposOwnerRepoForks`. */ postReposOwnerRepoForksParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.ForkBody, }; /** * Create a fork. * Forking a Repository happens asynchronously. Therefore, you may have to wai * a short period before accessing the git objects. If this takes longer than 5 * minutes, be sure to contact Support. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Fork>; postReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Fork>>; postReposOwnerRepoForks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoForksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Fork>>; /** * Arguments object for method `postReposOwnerRepoGitBlobs`. */ postReposOwnerRepoGitBlobsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Blob, }; /** * Create a Blob. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoGitBlobs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Blobs>; postReposOwnerRepoGitBlobs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Blobs>>; postReposOwnerRepoGitBlobs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Blobs>>; /** * Arguments object for method `getReposOwnerRepoGitBlobsShaCode`. */ getReposOwnerRepoGitBlobsShaCodeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** SHA-1 code. */ shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Blob. * Since blobs can be any arbitrary binary data, the input and responses for * the blob API takes an encoding parameter that can be either utf-8 or * base64. If your data cannot be losslessly sent as a UTF-8 string, you can * base64 encode it. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitBlobsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Blob>; getReposOwnerRepoGitBlobsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Blob>>; getReposOwnerRepoGitBlobsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Blob>>; /** * Arguments object for method `postReposOwnerRepoGitCommits`. */ postReposOwnerRepoGitCommitsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.RepoCommitBody, }; /** * Create a Commit. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoGitCommits( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.GitCommit>; postReposOwnerRepoGitCommits( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.GitCommit>>; postReposOwnerRepoGitCommits( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.GitCommit>>; /** * Arguments object for method `getReposOwnerRepoGitCommitsShaCode`. */ getReposOwnerRepoGitCommitsShaCodeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** SHA-1 code. */ shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Commit. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RepoCommit>; getReposOwnerRepoGitCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RepoCommit>>; getReposOwnerRepoGitCommitsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitCommitsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RepoCommit>>; /** * Arguments object for method `getReposOwnerRepoGitRefs`. */ getReposOwnerRepoGitRefsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get all References * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Refs>; getReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Refs>>; getReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Refs>>; /** * Arguments object for method `postReposOwnerRepoGitRefs`. */ postReposOwnerRepoGitRefsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.RefsBody, }; /** * Create a Reference * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.HeadBranch>; postReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.HeadBranch>>; postReposOwnerRepoGitRefs( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitRefsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.HeadBranch>>; /** * Arguments object for method `deleteReposOwnerRepoGitRefsRef`. */ deleteReposOwnerRepoGitRefsRefParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a Reference * Example: Deleting a branch: DELETE /repos/octocat/Hello-World/git/refs/heads/feature-a * Example: Deleting a tag: DELETE /repos/octocat/Hello-World/git/refs/tags/v1.0 * * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoGitRefsRef`. */ getReposOwnerRepoGitRefsRefParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Reference * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.HeadBranch>; getReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.HeadBranch>>; getReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.HeadBranch>>; /** * Arguments object for method `patchReposOwnerRepoGitRefsRef`. */ patchReposOwnerRepoGitRefsRefParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.GitRefPatch, }; /** * Update a Reference * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.HeadBranch>; patchReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.HeadBranch>>; patchReposOwnerRepoGitRefsRef( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoGitRefsRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.HeadBranch>>; /** * Arguments object for method `postReposOwnerRepoGitTags`. */ postReposOwnerRepoGitTagsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Tag, }; /** * Create a Tag Object. * Note that creating a tag object does not create the reference that makes a * tag in Git. If you want to create an annotated tag in Git, you have to do * this call to create the tag object, and then create the refs/tags/[tag] * reference. If you want to create a lightweight tag, you only have to create * the tag reference - this call would be unnecessary. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoGitTags( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Tags>; postReposOwnerRepoGitTags( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Tags>>; postReposOwnerRepoGitTags( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Tags>>; /** * Arguments object for method `getReposOwnerRepoGitTagsShaCode`. */ getReposOwnerRepoGitTagsShaCodeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, shaCode: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Tag. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitTagsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Tag>; getReposOwnerRepoGitTagsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Tag>>; getReposOwnerRepoGitTagsShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTagsShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Tag>>; /** * Arguments object for method `postReposOwnerRepoGitTrees`. */ postReposOwnerRepoGitTreesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Tree, }; /** * Create a Tree. * The tree creation API will take nested entries as well. If both a tree and * a nested path modifying that tree are specified, it will overwrite the * contents of that tree with the new path contents and write a new tree out. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoGitTrees( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Trees>; postReposOwnerRepoGitTrees( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Trees>>; postReposOwnerRepoGitTrees( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoGitTreesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Trees>>; /** * Arguments object for method `getReposOwnerRepoGitTreesShaCode`. */ getReposOwnerRepoGitTreesShaCodeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Tree SHA. */ shaCode: string, /** Get a Tree Recursively. (0 or 1) */ recursive?: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Tree. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoGitTreesShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Tree>; getReposOwnerRepoGitTreesShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Tree>>; getReposOwnerRepoGitTreesShaCode( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoGitTreesShaCodeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Tree>>; /** * Arguments object for method `getReposOwnerRepoHooks`. */ getReposOwnerRepoHooksParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of hooks. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Hook>; getReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Hook>>; getReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Hook>>; /** * Arguments object for method `postReposOwnerRepoHooks`. */ postReposOwnerRepoHooksParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.HookBody, }; /** * Create a hook. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Hook>; postReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Hook>>; postReposOwnerRepoHooks( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Hook>>; /** * Arguments object for method `deleteReposOwnerRepoHooksHookId`. */ deleteReposOwnerRepoHooksHookIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of hook. */ hookId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a hook. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoHooksHookId`. */ getReposOwnerRepoHooksHookIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of hook. */ hookId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get single hook. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Hook>; getReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Hook>>; getReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Hook>>; /** * Arguments object for method `patchReposOwnerRepoHooksHookId`. */ patchReposOwnerRepoHooksHookIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of hook. */ hookId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.HookBody, }; /** * Edit a hook. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Hook>; patchReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Hook>>; patchReposOwnerRepoHooksHookId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoHooksHookIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Hook>>; /** * Arguments object for method `postReposOwnerRepoHooksHookIdTests`. */ postReposOwnerRepoHooksHookIdTestsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of hook. */ hookId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Test a push hook. * This will trigger the hook with the latest push to the current repository * if the hook is subscribed to push events. If the hook is not subscribed * to push events, the server will respond with 204 but no test POST will * be generated. * Note: Previously /repos/:owner/:repo/hooks/:id/tes * * Response generated for [ 204 ] HTTP response code. */ postReposOwnerRepoHooksHookIdTests( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; postReposOwnerRepoHooksHookIdTests( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; postReposOwnerRepoHooksHookIdTests( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoHooksHookIdTestsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoIssues`. */ getReposOwnerRepoIssuesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * Issues assigned to you / created by you / mentioning you / you're * subscribed to updates for / All issues the authenticated user can see * * If not set, server will use the default value: all */ filter: ('assigned' | 'created' | 'mentioned' | 'subscribed' | 'all'), /** If not set, server will use the default value: open */ state: ('open' | 'closed'), /** String list of comma separated Label names. Example - bug,ui,@high. */ labels: string, /** If not set, server will use the default value: created */ sort: ('created' | 'updated' | 'comments'), /** If not set, server will use the default value: desc */ direction: ('asc' | 'desc'), /** * Optional string of a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Only issues updated at or after this time are returned. * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List issues for a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issues>; getReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issues>>; getReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issues>>; /** * Arguments object for method `postReposOwnerRepoIssues`. */ postReposOwnerRepoIssuesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Issue, }; /** * Create an issue. * Any user with pull access to a repository can create an issue. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issue>; postReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issue>>; postReposOwnerRepoIssues( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issue>>; /** * Arguments object for method `getReposOwnerRepoIssuesComments`. */ getReposOwnerRepoIssuesCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Ignored without 'sort' parameter. */ direction?: string, sort?: ('created' | 'updated'), /** * The time should be passed in as UTC in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Example: "2012-10-09T23:39:01Z". * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments in a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComments>; getReposOwnerRepoIssuesComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComments>>; getReposOwnerRepoIssuesComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComments>>; /** * Arguments object for method `deleteReposOwnerRepoIssuesCommentId`. */ deleteReposOwnerRepoIssuesCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** ID of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a comment. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoIssuesCommentId`. */ getReposOwnerRepoIssuesCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** ID of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single comment. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComment>; getReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComment>>; getReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComment>>; /** * Arguments object for method `patchReposOwnerRepoIssuesCommentId`. */ patchReposOwnerRepoIssuesCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** ID of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommentBody, }; /** * Edit a comment. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComment>; patchReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComment>>; patchReposOwnerRepoIssuesCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComment>>; /** * Arguments object for method `getReposOwnerRepoIssuesEvents`. */ getReposOwnerRepoIssuesEventsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List issue events for a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Events>; getReposOwnerRepoIssuesEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Events>>; getReposOwnerRepoIssuesEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Events>>; /** * Arguments object for method `getReposOwnerRepoIssuesEventId`. */ getReposOwnerRepoIssuesEventIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of the event. */ eventId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single event. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesEventId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Event>; getReposOwnerRepoIssuesEventId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Event>>; getReposOwnerRepoIssuesEventId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesEventIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Event>>; /** * Arguments object for method `getReposOwnerRepoIssuesNumber`. */ getReposOwnerRepoIssuesNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single issue * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issue>; getReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issue>>; getReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issue>>; /** * Arguments object for method `patchReposOwnerRepoIssuesNumber`. */ patchReposOwnerRepoIssuesNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.Issue, }; /** * Edit an issue. * Issue owners and users with push access can edit an issue. * * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issue>; patchReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issue>>; patchReposOwnerRepoIssuesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoIssuesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issue>>; /** * Arguments object for method `getReposOwnerRepoIssuesNumberComments`. */ getReposOwnerRepoIssuesNumberCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments on an issue. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComments>; getReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComments>>; getReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComments>>; /** * Arguments object for method `postReposOwnerRepoIssuesNumberComments`. */ postReposOwnerRepoIssuesNumberCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommentBody, }; /** * Create a comment. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComment>; postReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComment>>; postReposOwnerRepoIssuesNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComment>>; /** * Arguments object for method `getReposOwnerRepoIssuesNumberEvents`. */ getReposOwnerRepoIssuesNumberEventsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List events for an issue. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesNumberEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Events>; getReposOwnerRepoIssuesNumberEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Events>>; getReposOwnerRepoIssuesNumberEvents( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Events>>; /** * Arguments object for method `deleteReposOwnerRepoIssuesNumberLabels`. */ deleteReposOwnerRepoIssuesNumberLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Remove all labels from an issue. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoIssuesNumberLabels`. */ getReposOwnerRepoIssuesNumberLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List labels on an issue. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Labels>; getReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Labels>>; getReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Labels>>; /** * Arguments object for method `postReposOwnerRepoIssuesNumberLabels`. */ postReposOwnerRepoIssuesNumberLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.EmailsPost, }; /** * Add labels to an issue. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Label>; postReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Label>>; postReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Label>>; /** * Arguments object for method `putReposOwnerRepoIssuesNumberLabels`. */ putReposOwnerRepoIssuesNumberLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.EmailsPost, }; /** * Replace all labels for an issue. * Sending an empty array ([]) will remove all Labels from the Issue. * * Response generated for [ 201 ] HTTP response code. */ putReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Label>; putReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Label>>; putReposOwnerRepoIssuesNumberLabels( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoIssuesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Label>>; /** * Arguments object for method `deleteReposOwnerRepoIssuesNumberLabelsName`. */ deleteReposOwnerRepoIssuesNumberLabelsNameParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of issue. */ number: number, /** Name of the label. */ name: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Remove a label from an issue. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoIssuesNumberLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoIssuesNumberLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoIssuesNumberLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoIssuesNumberLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoKeys`. */ getReposOwnerRepoKeysParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of keys. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Keys>; getReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Keys>>; getReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Keys>>; /** * Arguments object for method `postReposOwnerRepoKeys`. */ postReposOwnerRepoKeysParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.UserKeysPost, }; /** * Create a key. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserKeysKeyId>; postReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserKeysKeyId>>; postReposOwnerRepoKeys( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserKeysKeyId>>; /** * Arguments object for method `deleteReposOwnerRepoKeysKeyId`. */ deleteReposOwnerRepoKeysKeyIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of key. */ keyId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a key. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoKeysKeyId`. */ getReposOwnerRepoKeysKeyIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of key. */ keyId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a key * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserKeysKeyId>; getReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserKeysKeyId>>; getReposOwnerRepoKeysKeyId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserKeysKeyId>>; /** * Arguments object for method `getReposOwnerRepoLabels`. */ getReposOwnerRepoLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List all labels for this repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Labels>; getReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Labels>>; getReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Labels>>; /** * Arguments object for method `postReposOwnerRepoLabels`. */ postReposOwnerRepoLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.EmailsPost, }; /** * Create a label. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Label>; postReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Label>>; postReposOwnerRepoLabels( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Label>>; /** * Arguments object for method `deleteReposOwnerRepoLabelsName`. */ deleteReposOwnerRepoLabelsNameParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Name of the label. */ name: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a label. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoLabelsName`. */ getReposOwnerRepoLabelsNameParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Name of the label. */ name: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single label. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Label>; getReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Label>>; getReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Label>>; /** * Arguments object for method `patchReposOwnerRepoLabelsName`. */ patchReposOwnerRepoLabelsNameParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Name of the label. */ name: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.EmailsPost, }; /** * Update a label. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Label>; patchReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Label>>; patchReposOwnerRepoLabelsName( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoLabelsNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Label>>; /** * Arguments object for method `getReposOwnerRepoLanguages`. */ getReposOwnerRepoLanguagesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List languages. * List languages for the specified repository. The value on the right of a * language is the number of bytes of code written in that language. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoLanguages( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Languages>; getReposOwnerRepoLanguages( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Languages>>; getReposOwnerRepoLanguages( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoLanguagesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Languages>>; /** * Arguments object for method `postReposOwnerRepoMerges`. */ postReposOwnerRepoMergesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.MergesBody, }; /** * Perform a merge. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoMerges( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.MergesSuccessful>; postReposOwnerRepoMerges( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.MergesSuccessful>>; postReposOwnerRepoMerges( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMergesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.MergesSuccessful>>; /** * Arguments object for method `getReposOwnerRepoMilestones`. */ getReposOwnerRepoMilestonesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * String to filter by state. * If not set, server will use the default value: open */ state?: ('open' | 'closed'), /** Ignored without 'sort' parameter. */ direction?: string, /** If not set, server will use the default value: due_date */ sort?: ('due_date' | 'completeness'), /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List milestones for a repository. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Milestone>; getReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Milestone>>; getReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Milestone>>; /** * Arguments object for method `postReposOwnerRepoMilestones`. */ postReposOwnerRepoMilestonesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.MilestoneUpdate, }; /** * Create a milestone. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Milestone>; postReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Milestone>>; postReposOwnerRepoMilestones( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoMilestonesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Milestone>>; /** * Arguments object for method `deleteReposOwnerRepoMilestonesNumber`. */ deleteReposOwnerRepoMilestonesNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of milestone. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a milestone. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoMilestonesNumber`. */ getReposOwnerRepoMilestonesNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of milestone. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single milestone. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Milestone>; getReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Milestone>>; getReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Milestone>>; /** * Arguments object for method `patchReposOwnerRepoMilestonesNumber`. */ patchReposOwnerRepoMilestonesNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of milestone. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.MilestoneUpdate, }; /** * Update a milestone. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Milestone>; patchReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Milestone>>; patchReposOwnerRepoMilestonesNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoMilestonesNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Milestone>>; /** * Arguments object for method `getReposOwnerRepoMilestonesNumberLabels`. */ getReposOwnerRepoMilestonesNumberLabelsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Number of milestone. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get labels for every issue in a milestone. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoMilestonesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Labels>; getReposOwnerRepoMilestonesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Labels>>; getReposOwnerRepoMilestonesNumberLabels( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoMilestonesNumberLabelsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Labels>>; /** * Arguments object for method `getReposOwnerRepoNotifications`. */ getReposOwnerRepoNotificationsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** True to show notifications marked as read. */ all?: boolean, /** * True to show only notifications in which the user is directly participating * or mentioned. * */ participating?: boolean, /** * The time should be passed in as UTC in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Example: "2012-10-09T23:39:01Z". * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List your notifications in a repository * List all notifications for the current user. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Notifications>; getReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Notifications>>; getReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Notifications>>; /** * Arguments object for method `putReposOwnerRepoNotifications`. */ putReposOwnerRepoNotificationsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.NotificationMarkRead, }; /** * Mark notifications as read in a repository. * Marking all notifications in a repository as "read" removes them from the * default view on GitHub.com. * * Response generated for [ 205 ] HTTP response code. */ putReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putReposOwnerRepoNotifications( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoNotificationsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoPulls`. */ getReposOwnerRepoPullsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * String to filter by state. * If not set, server will use the default value: open */ state?: ('open' | 'closed'), /** * Filter pulls by head user and branch name in the format of 'user:ref-name'. * Example: github:new-script-format. * */ head?: string, /** Filter pulls by base branch name. Example - gh-pages. */ base?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List pull requests. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pulls>; getReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pulls>>; getReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pulls>>; /** * Arguments object for method `postReposOwnerRepoPulls`. */ postReposOwnerRepoPullsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.PullsPost, }; /** * Create a pull request. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pulls>; postReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pulls>>; postReposOwnerRepoPulls( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pulls>>; /** * Arguments object for method `getReposOwnerRepoPullsComments`. */ getReposOwnerRepoPullsCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Ignored without 'sort' parameter. */ direction?: string, sort?: ('created' | 'updated'), /** * The time should be passed in as UTC in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Example: "2012-10-09T23:39:01Z". * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments in a repository. * By default, Review Comments are ordered by ascending ID. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.IssuesComments>; getReposOwnerRepoPullsComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.IssuesComments>>; getReposOwnerRepoPullsComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.IssuesComments>>; /** * Arguments object for method `deleteReposOwnerRepoPullsCommentId`. */ deleteReposOwnerRepoPullsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a comment. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoPullsCommentId`. */ getReposOwnerRepoPullsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single comment. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PullsComment>; getReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PullsComment>>; getReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PullsComment>>; /** * Arguments object for method `patchReposOwnerRepoPullsCommentId`. */ patchReposOwnerRepoPullsCommentIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of comment. */ commentId: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.CommentBody, }; /** * Edit a comment. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PullsComment>; patchReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PullsComment>>; patchReposOwnerRepoPullsCommentId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsCommentIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PullsComment>>; /** * Arguments object for method `getReposOwnerRepoPullsNumber`. */ getReposOwnerRepoPullsNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single pull request. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PullRequest>; getReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PullRequest>>; getReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PullRequest>>; /** * Arguments object for method `patchReposOwnerRepoPullsNumber`. */ patchReposOwnerRepoPullsNumberParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.PullUpdate, }; /** * Update a pull request. * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repo>; patchReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repo>>; patchReposOwnerRepoPullsNumber( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoPullsNumberParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repo>>; /** * Arguments object for method `getReposOwnerRepoPullsNumberComments`. */ getReposOwnerRepoPullsNumberCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List comments on a pull request. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PullsComment>; getReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PullsComment>>; getReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PullsComment>>; /** * Arguments object for method `postReposOwnerRepoPullsNumberComments`. */ postReposOwnerRepoPullsNumberCommentsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.PullsCommentPost, }; /** * Create a comment. * * #TODO Alternative input * ( http://developer.github.com/v3/pulls/comments/ ) * * description: | * * Alternative Input. * * Instead of passing commit_id, path, and position you can reply to an * * existing Pull Request Comment like this: * * * * body * * Required string * * in_reply_to * * Required number - Comment id to reply to. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.PullsComment>; postReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.PullsComment>>; postReposOwnerRepoPullsNumberComments( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoPullsNumberCommentsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.PullsComment>>; /** * Arguments object for method `getReposOwnerRepoPullsNumberCommits`. */ getReposOwnerRepoPullsNumberCommitsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List commits on a pull request. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsNumberCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Commits>; getReposOwnerRepoPullsNumberCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Commits>>; getReposOwnerRepoPullsNumberCommits( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberCommitsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Commits>>; /** * Arguments object for method `getReposOwnerRepoPullsNumberFiles`. */ getReposOwnerRepoPullsNumberFilesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List pull requests files. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoPullsNumberFiles( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pulls>; getReposOwnerRepoPullsNumberFiles( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pulls>>; getReposOwnerRepoPullsNumberFiles( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberFilesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pulls>>; /** * Arguments object for method `getReposOwnerRepoPullsNumberMerge`. */ getReposOwnerRepoPullsNumberMergeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get if a pull request has been merged. * Response generated for [ 204 ] HTTP response code. */ getReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `putReposOwnerRepoPullsNumberMerge`. */ putReposOwnerRepoPullsNumberMergeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** Id of pull. */ number: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.MergePullBody, }; /** * Merge a pull request (Merge Button's) * Response generated for [ 200 ] HTTP response code. */ putReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Merge>; putReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Merge>>; putReposOwnerRepoPullsNumberMerge( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoPullsNumberMergeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Merge>>; /** * Arguments object for method `getReposOwnerRepoReadme`. */ getReposOwnerRepoReadmeParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** The String name of the Commit/Branch/Tag. Defaults to master. */ ref?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the README. * This method returns the preferred README for a repository. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoReadme( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ContentsPath>; getReposOwnerRepoReadme( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ContentsPath>>; getReposOwnerRepoReadme( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReadmeParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ContentsPath>>; /** * Arguments object for method `getReposOwnerRepoReleases`. */ getReposOwnerRepoReleasesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Users with push access to the repository will receive all releases (i.e., published releases and draft releases). Users with pull access will receive published releases only * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Releases>; getReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Releases>>; getReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Releases>>; /** * Arguments object for method `postReposOwnerRepoReleases`. */ postReposOwnerRepoReleasesParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.ReleaseCreate, }; /** * Create a release * Users with push access to the repository can create a release. * * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Release>; postReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Release>>; postReposOwnerRepoReleases( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoReleasesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Release>>; /** * Arguments object for method `deleteReposOwnerRepoReleasesAssetsId`. */ deleteReposOwnerRepoReleasesAssetsIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a release asset * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoReleasesAssetsId`. */ getReposOwnerRepoReleasesAssetsIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single release asset * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Asset>; getReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Asset>>; getReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Asset>>; /** * Arguments object for method `patchReposOwnerRepoReleasesAssetsId`. */ patchReposOwnerRepoReleasesAssetsIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.AssetPatch, }; /** * Edit a release asset * Users with push access to the repository can edit a release asset. * * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Asset>; patchReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Asset>>; patchReposOwnerRepoReleasesAssetsId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesAssetsIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Asset>>; /** * Arguments object for method `deleteReposOwnerRepoReleasesId`. */ deleteReposOwnerRepoReleasesIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Users with push access to the repository can delete a release. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoReleasesId`. */ getReposOwnerRepoReleasesIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single release * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Release>; getReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Release>>; getReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Release>>; /** * Arguments object for method `patchReposOwnerRepoReleasesId`. */ patchReposOwnerRepoReleasesIdParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.ReleaseCreate, }; /** * Users with push access to the repository can edit a release * Response generated for [ 200 ] HTTP response code. */ patchReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Release>; patchReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Release>>; patchReposOwnerRepoReleasesId( args: Exclude<ReposAPIClientInterface['patchReposOwnerRepoReleasesIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Release>>; /** * Arguments object for method `getReposOwnerRepoReleasesIdAssets`. */ getReposOwnerRepoReleasesIdAssetsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, id: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List assets for a release * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoReleasesIdAssets( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Assets>; getReposOwnerRepoReleasesIdAssets( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Assets>>; getReposOwnerRepoReleasesIdAssets( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoReleasesIdAssetsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Assets>>; /** * Arguments object for method `getReposOwnerRepoStargazers`. */ getReposOwnerRepoStargazersParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List Stargazers. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStargazers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getReposOwnerRepoStargazers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getReposOwnerRepoStargazers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStargazersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `getReposOwnerRepoStatsCodeFrequency`. */ getReposOwnerRepoStatsCodeFrequencyParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the number of additions and deletions per week. * Returns a weekly aggregate of the number of additions and deletions pushed * to a repository. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatsCodeFrequency( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CodeFrequencyStats>; getReposOwnerRepoStatsCodeFrequency( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CodeFrequencyStats>>; getReposOwnerRepoStatsCodeFrequency( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCodeFrequencyParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CodeFrequencyStats>>; /** * Arguments object for method `getReposOwnerRepoStatsCommitActivity`. */ getReposOwnerRepoStatsCommitActivityParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the last year of commit activity data. * Returns the last year of commit activity grouped by week. The days array * is a group of commits per day, starting on Sunday. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatsCommitActivity( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitActivityStats>; getReposOwnerRepoStatsCommitActivity( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitActivityStats>>; getReposOwnerRepoStatsCommitActivity( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsCommitActivityParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitActivityStats>>; /** * Arguments object for method `getReposOwnerRepoStatsContributors`. */ getReposOwnerRepoStatsContributorsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get contributors list with additions, deletions, and commit counts. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatsContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ContributorsStats>; getReposOwnerRepoStatsContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ContributorsStats>>; getReposOwnerRepoStatsContributors( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsContributorsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ContributorsStats>>; /** * Arguments object for method `getReposOwnerRepoStatsParticipation`. */ getReposOwnerRepoStatsParticipationParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the weekly commit count for the repo owner and everyone else. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatsParticipation( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ParticipationStats>; getReposOwnerRepoStatsParticipation( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ParticipationStats>>; getReposOwnerRepoStatsParticipation( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsParticipationParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ParticipationStats>>; /** * Arguments object for method `getReposOwnerRepoStatsPunchCard`. */ getReposOwnerRepoStatsPunchCardParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get the number of commits per hour in each day. * Each array contains the day number, hour number, and number of commits * 0-6 Sunday - Saturday * 0-23 Hour of day * Number of commits * * * For example, [2, 14, 25] indicates that there were 25 total commits, during * the 2.00pm hour on Tuesdays. All times are based on the time zone of * individual commits. * * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatsPunchCard( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CodeFrequencyStats>; getReposOwnerRepoStatsPunchCard( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CodeFrequencyStats>>; getReposOwnerRepoStatsPunchCard( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatsPunchCardParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CodeFrequencyStats>>; /** * Arguments object for method `getReposOwnerRepoStatusesRef`. */ getReposOwnerRepoStatusesRefParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * Ref to list the statuses from. It can be a SHA, a branch name, or a tag name. * */ ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List Statuses for a specific Ref. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Ref>; getReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Ref>>; getReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Ref>>; /** * Arguments object for method `postReposOwnerRepoStatusesRef`. */ postReposOwnerRepoStatusesRefParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * Ref to list the statuses from. It can be a SHA, a branch name, or a tag name. * */ ref: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.HeadBranch, }; /** * Create a Status. * Response generated for [ 201 ] HTTP response code. */ postReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Ref>; postReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Ref>>; postReposOwnerRepoStatusesRef( args: Exclude<ReposAPIClientInterface['postReposOwnerRepoStatusesRefParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Ref>>; /** * Arguments object for method `getReposOwnerRepoSubscribers`. */ getReposOwnerRepoSubscribersParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List watchers. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoSubscribers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getReposOwnerRepoSubscribers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getReposOwnerRepoSubscribers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscribersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `deleteReposOwnerRepoSubscription`. */ deleteReposOwnerRepoSubscriptionParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Delete a Repository Subscription. * Response generated for [ 204 ] HTTP response code. */ deleteReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['deleteReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getReposOwnerRepoSubscription`. */ getReposOwnerRepoSubscriptionParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a Repository Subscription. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Subscribition>; getReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Subscribition>>; getReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Subscribition>>; /** * Arguments object for method `putReposOwnerRepoSubscription`. */ putReposOwnerRepoSubscriptionParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, body: models.SubscribitionBody, }; /** * Set a Repository Subscription * Response generated for [ 200 ] HTTP response code. */ putReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Subscribition>; putReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Subscribition>>; putReposOwnerRepoSubscription( args: Exclude<ReposAPIClientInterface['putReposOwnerRepoSubscriptionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Subscribition>>; /** * Arguments object for method `getReposOwnerRepoTags`. */ getReposOwnerRepoTagsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of tags. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoTags( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Tags>; getReposOwnerRepoTags( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Tags>>; getReposOwnerRepoTags( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Tags>>; /** * Arguments object for method `getReposOwnerRepoTeams`. */ getReposOwnerRepoTeamsParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get list of teams * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoTeams( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Teams>; getReposOwnerRepoTeams( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Teams>>; getReposOwnerRepoTeams( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Teams>>; /** * Arguments object for method `getReposOwnerRepoWatchers`. */ getReposOwnerRepoWatchersParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List Stargazers. New implementation. * Response generated for [ 200 ] HTTP response code. */ getReposOwnerRepoWatchers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getReposOwnerRepoWatchers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getReposOwnerRepoWatchers( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoWatchersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `getReposOwnerRepoArchiveFormatPath`. */ getReposOwnerRepoArchiveFormatPathParams?: { /** Name of repository owner. */ owner: string, /** Name of repository. */ repo: string, archiveFormat: ('tarball' | 'zipball'), /** Valid Git reference, defaults to 'master'. */ path: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get archive link. * This method will return a 302 to a URL to download a tarball or zipball * archive for a repository. Please make sure your HTTP framework is * configured to follow redirects or you will need to use the Location header * to make a second GET request. * Note: For private repositories, these links are temporary and expire quickly. * * Response generated for [ default ] HTTP response code. */ getReposOwnerRepoArchiveFormatPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getReposOwnerRepoArchiveFormatPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getReposOwnerRepoArchiveFormatPath( args: Exclude<ReposAPIClientInterface['getReposOwnerRepoArchiveFormatPathParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; }
the_stack
* @typedef PinataMetadataFilter * @property {string} [name] * @property {Record<string, {value: string, op: string}>} keyvalues */ /** * @typedef {{id: string, desiredReplicationCount: number}} PinataPinPolicyItem */ /** * @typedef PinataPinByHashOptions * @property {string[]} [hostNodes] * @property {{regions: PinataPinPolicyItem[]}} [customPinPolicy] */ /** * @typedef PinataPinByHashPinOptions * @property {PinataMetadata} [pinataMetadata] * @property {PinataPinByHashOptions} [pinataOptions] */ /** * @typedef PinataOptions * @property {0 | 1} [cidVersion] * @property {boolean} [wrapWithDirectory] * @property {{regions: PinataPinPolicyItem[]}} [customPinPolicy] */ /** * @typedef PinataPinOptions * @property {PinataMetadata} [pinataMetadata] * @property {PinataOptions} [pinataOptions] */ /** * @typedef PinataPinJobsFilterOptions * @property {'ASC' | 'DESC'} sort * @property {string} [status] * @property {string} [ipfs_pin_hash] * @property {number} [limit] * @property {number} [offset] */ /** * @typedef PinataPinListFilterOptions * @property {string} [hashContains] * @property {string} [pinStart] * @property {string} [pinEnd] * @property {string} [unpinStart] * @property {string} [unpinEnd] * @property {number} [pinSizeMin] * @property {number} [pinSizeMax] * @property {string} [status] * @property {number} [pageLimit] * @property {number} [pageOffset] * @property {PinataMetadataFilter} [metadata] */ /** * @typedef PinataPinByHashResponse * @property {number | string} id * @property {string} ipfsHash * @property {string} status * @property {string} name */ /** * @typedef PinataPinResponse * @property {string} IpfsHash * @property {number} PinSize * @property {string} Timestamp */ /** * @typedef PinataPinJobsResponseRow * @property {number | string} id * @property {string} ipfs_pin_hash * @property {string} date_queued * @property {string | undefined | null} name * @property {string} status */ /** * @typedef PinataPinJobsResponse * @property {number} count * @property {PinataPinJobsResponseRow[]} rows */ /** * @typedef PinataPinListResponseRow * @property {number | string} id * @property {string} ipfs_pin_hash * @property {number} size * @property {string | number} user_id * @property {string} date_pinned * @property {string} date_unpinned * @property {PinataMetadata} metadata */ /** * @typedef PinataPinListResponse * @property {number} count * @property {PinataPinListResponseRow[]} rows */ /** * Hash meta data * @callback hashMetadata * @param {string} ipfsPinHash * @param {PinataMetadata} metadata * @returns {Promise<any>} */ /** * Hash pin policy * @callback hashPinPolicy * @param {string} ipfsPinHash * @param {{regions: PinataPinPolicyItem[]}} newPinPolicy * @returns {Promise<any>} */ /** * Pin by hash * @callback pinByHash * @param {string} hashToPin * @param {PinataPinByHashPinOptions} [options] * @returns {Promise<PinataPinByHashResponse>} */ /** * Pin file to IPFS * @callback pinFileToIPFS * @param {ReadStream} readableStream * @param {PinataPinOptions} [options] * @returns {Promise<PinataPinResponse>} */ /** * Pin from FS * @callback pinFromFS * @param {string} sourcePath * @param {PinataPinOptions} [options] * @returns {Promise<PinataPinResponse>} */ /** * Pin Jobs * @callback pinJobs * @param {PinataPinJobsFilterOptions} [filters] * @returns {Promise<PinataPinJobsResponse>} */ /** * Pin JSON to IPFS * @callback pinJSONToIPFS * @param {Object} body * @param {PinataPinOptions} [options] * @returns {Promise<PinataPinResponse>} */ /** * Unpin * @callback unpin * @param {string} hashToUnpin * @returns {Promise<any>} */ /** * User Pin Policy * @callback userPinPolicy * @param {{regions: PinataPinPolicyItem[]}} newPinPolicy * @returns {Promise<any>} */ /** * Test Authentication * @callback testAuthentication * @returns {Promise<{authenticated: boolean}>} */ /** * Pin List * @callback pinList * @param {PinataPinListFilterOptions} [filters] * @returns {Promise<PinataPinListResponse>} */ /** * User Pinned Data Total * @callback userPinnedDataTotal * @returns {Promise<number>} */ /** * @typedef PinataClient * @property {pinByHash} pinByHash * @property {hashMetadata} hashMetadata * @property {hashPinPolicy} hashPinPolicy * @property {pinFileToIPFS} pinFileToIPFS * @property {pinFromFS} pinFromFS * @property {pinJSONToIPFS} pinJSONToIPFS * @property {pinJobs} pinJobs * @property {unpin} unpin * @property {userPinPolicy} userPinPolicy * @property {testAuthentication} testAuthentication * @property {pinList} pinList * @property {userPinnedDataTotal} userPinnedDataTotal */ /** * Pinata Client * * @param {string} pinataApiKey * @param {string} pinataSecretApiKey * @returns {PinataClient} */ export default function pinataClient(pinataApiKey: string, pinataSecretApiKey: string): PinataClient; export type PinataMetadata = Record<string, string | number | null>; export type PinataMetadataFilter = { name?: string | undefined; keyvalues: Record<string, { value: string; op: string; }>; }; export type PinataPinPolicyItem = { id: string; desiredReplicationCount: number; }; export type PinataPinByHashOptions = { hostNodes?: string[] | undefined; customPinPolicy?: { regions: PinataPinPolicyItem[]; } | undefined; }; export type PinataPinByHashPinOptions = { pinataMetadata?: Record<string, string | number | null> | undefined; pinataOptions?: PinataPinByHashOptions | undefined; }; export type PinataOptions = { cidVersion?: 0 | 1 | undefined; wrapWithDirectory?: boolean | undefined; customPinPolicy?: { regions: PinataPinPolicyItem[]; } | undefined; }; export type PinataPinOptions = { pinataMetadata?: Record<string, string | number | null> | undefined; pinataOptions?: PinataOptions | undefined; }; export type PinataPinJobsFilterOptions = { sort: 'ASC' | 'DESC'; status?: string | undefined; ipfs_pin_hash?: string | undefined; limit?: number | undefined; offset?: number | undefined; }; export type PinataPinListFilterOptions = { hashContains?: string | undefined; pinStart?: string | undefined; pinEnd?: string | undefined; unpinStart?: string | undefined; unpinEnd?: string | undefined; pinSizeMin?: number | undefined; pinSizeMax?: number | undefined; status?: string | undefined; pageLimit?: number | undefined; pageOffset?: number | undefined; metadata?: PinataMetadataFilter | undefined; }; export type PinataPinByHashResponse = { id: number | string; ipfsHash: string; status: string; name: string; }; export type PinataPinResponse = { IpfsHash: string; PinSize: number; Timestamp: string; }; export type PinataPinJobsResponseRow = { id: number | string; ipfs_pin_hash: string; date_queued: string; name: string | undefined | null; status: string; }; export type PinataPinJobsResponse = { count: number; rows: PinataPinJobsResponseRow[]; }; export type PinataPinListResponseRow = { id: number | string; ipfs_pin_hash: string; size: number; user_id: string | number; date_pinned: string; date_unpinned: string; metadata: PinataMetadata; }; export type PinataPinListResponse = { count: number; rows: PinataPinListResponseRow[]; }; /** * Hash meta data */ export type hashMetadata = (ipfsPinHash: string, metadata: PinataMetadata) => Promise<any>; /** * Hash pin policy */ export type hashPinPolicy = (ipfsPinHash: string, newPinPolicy: { regions: PinataPinPolicyItem[]; }) => Promise<any>; /** * Pin by hash */ export type pinByHash = (hashToPin: string, options?: PinataPinByHashPinOptions | undefined) => Promise<PinataPinByHashResponse>; /** * Pin file to IPFS */ export type pinFileToIPFS = (readableStream: any, options?: PinataPinOptions | undefined) => Promise<PinataPinResponse>; /** * Pin from FS */ export type pinFromFS = (sourcePath: string, options?: PinataPinOptions | undefined) => Promise<PinataPinResponse>; /** * Pin Jobs */ export type pinJobs = (filters?: PinataPinJobsFilterOptions | undefined) => Promise<PinataPinJobsResponse>; /** * Pin JSON to IPFS */ export type pinJSONToIPFS = (body: Object, options?: PinataPinOptions | undefined) => Promise<PinataPinResponse>; /** * Unpin */ export type unpin = (hashToUnpin: string) => Promise<any>; /** * User Pin Policy */ export type userPinPolicy = (newPinPolicy: { regions: PinataPinPolicyItem[]; }) => Promise<any>; /** * Test Authentication */ export type testAuthentication = () => Promise<{ authenticated: boolean; }>; /** * Pin List */ export type pinList = (filters?: PinataPinListFilterOptions | undefined) => Promise<PinataPinListResponse>; /** * User Pinned Data Total */ export type userPinnedDataTotal = () => Promise<number>; export type PinataClient = { pinByHash: pinByHash; hashMetadata: hashMetadata; hashPinPolicy: hashPinPolicy; pinFileToIPFS: pinFileToIPFS; pinFromFS: pinFromFS; pinJSONToIPFS: pinJSONToIPFS; pinJobs: pinJobs; unpin: unpin; userPinPolicy: userPinPolicy; testAuthentication: testAuthentication; pinList: pinList; userPinnedDataTotal: userPinnedDataTotal; }; import pinByHash from "./commands/pinning/pinByHash"; import hashMetadata from "./commands/pinning/hashMetadata"; import hashPinPolicy from "./commands/pinning/hashPinPolicy"; import pinFileToIPFS from "./commands/pinning/pinFileToIPFS"; import pinFromFS from "./commands/pinning/pinFromFS"; import pinJSONToIPFS from "./commands/pinning/pinJSONToIPFS"; import pinJobs from "./commands/pinning/pinJobs/pinJobs"; import unpin from "./commands/pinning/unpin"; import userPinPolicy from "./commands/pinning/userPinPolicy"; import testAuthentication from "./commands/data/testAuthentication"; import pinList from "./commands/data/pinList/pinList"; import userPinnedDataTotal from "./commands/data/userPinnedDataTotal";
the_stack
export namespace GamelistDB { interface GameEntryRomName { u06: string; } interface GameEntryMemoryPositions { /** * example: { dataStartOffset: 0x1C61, dataEndOffset: 0x1C80, checksumOffset: 0x1C81, checksum: '16bit', name: 'HI_SCORE' }, */ checksum: object[]; /** * example: { offset: 0x86, name: 'GAME_RUNNING', description: '0: not running, 1: running', type: 'uint8' }, */ knownValues: object[]; } interface IdNameMap { id: number; name: string; } interface AudioData { url: string; sample: object; sprite: object; } interface GameEntryPinmame { /** * known game rom names */ knownNames: string[]; /** * game name defined by pinmame */ gameName: string; /** * pinmame game id */ id: string; /** * if VPDB.io id differs from pinmame id, its defined here */ vpdbId?: string; } interface ClientGameEntry { /** * name if this WPC game */ name: string; /** * Game version (Like L-8) */ version: string; /** * data from pinmame */ pinmame: GameEntryPinmame; /** * rom file names, currently only u06 - the main ROM is included */ rom: GameEntryRomName; /** * number to name mapping of the switches */ switchMapping: IdNameMap[]; /** * optional fliptronics number to name mapping */ fliptronicsMapping?: IdNameMap[]; /** * Should the Williams ROM boot time be increased, skip ROM check? */ skipWpcRomCheck?: boolean; /** * features of this pinball machine: 'securityPic', 'wpc95', 'wpcAlphanumeric', 'wpcDmd', 'wpcFliptronics', 'wpcSecure', 'wpcDcs' */ features?: string[]; /** * array of cabinet colors, excluding black and white colors */ cabinetColors?: string[]; /** * defines memory positions of this game to evaluate game state (like current ball, current player etc) */ memoryPosition?: GameEntryMemoryPositions; /** * audio definition for this game */ audio?: AudioData; /** * playfield information, mainly used for playfield.dev */ playfield?: any; /** * actions that should be done when starting, like close cabinet input, mainly used for playfield.dev */ initialise?: any; } interface RomData { u06: Uint8Array; } interface GameEntry { name: string; rom: GameEntryRomName; /** * ROM filename */ fileName?: string; skipWpcRomCheck?: boolean; /** * features of this pinball machine: 'securityPic', 'wpc95', 'wpcAlphanumeric', 'wpcDmd', 'wpcFliptronics', 'wpcSecure', 'wpcDcs' */ features?: string[]; memoryPosition?: GameEntryMemoryPositions; } /** * get all supported game names */ function getAllNames(): string[]; /** * load metadata for a specific game name like "WPC-Fliptronics: Fish Tales" * @param name case sensitive game name */ function getByName(name: string): ClientGameEntry; /** * load metadata for a specific game by its pinmame name, like "tz_94h" * @param filename case insensitive filename */ function getByPinmameName(filename: string): ClientGameEntry | undefined; } export namespace WpcEmuApi { interface AudioMessage { command: string; id?: number; channel?: number; value?: number; } class Emulator { /** * Start the Emulator - reset the CPU */ start(): void; /** * Returns the current ui state of the emu used to render EMU State. * NOTE: compared to the getState function call, getUiState delivers only an element if the content changed. * @param includeExpensiveData if set to false, expensive/large state objects (RAM, VideoRAM) are excluded, default is to include this kind of data */ getUiState(includeExpensiveData?: boolean): WpcEmuWebWorkerApi.EmuState; /** * Get (raw) state of the EMU - main use case is to restore this state at a later time */ getState(): WpcEmuWebWorkerApi.EmuState; /** * Restore a saved state */ setState(stateObject: WpcEmuWebWorkerApi.EmuState): void; /** * Callback to playback audio samples */ registerAudioConsumer(callbackFunction: (audioJSON: AudioMessage) => void): void; /** * Run the system for a particular amount of ticks * @param ticksToRun how many ticks should the CPU run, 2'000'000 ticks means one seconds * @param tickSteps how many cycles the cpu should run before other systems should be updated? see BENCHMARK.md for more details * @returns executed ticks */ executeCycle(ticksToRun: number, tickSteps: number): number; /** * Run the system for a particular amount of time * @param advanceByMs how many ms should the CPU run, 1000 ticks means one seconds * @param tickSteps how many cycles the cpu should run before other systems should be updated? see BENCHMARK.md for more details * @returns executed ticks */ executeCycleForTime(advanceByMs: number, tickSteps: number): number; /** * Cabinet key emulation (Coins, ESC, +, -, ENTER) * @param value number between 1 and 8 */ setCabinetInput(value: number): void; /** * Set or toggle a switch * @param switchNr number between 11 and 99 * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setSwitchInput(switchNr: number, optionalValue?: boolean): void; /** * Fliptronic flipper move (depends on the machine if this is supported) * @param value the switch name, like 'F1', 'F2' .. 'F8' * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setFliptronicsInput(value: string, optionalValue?: boolean): void; /** * Set the internal time some seconds before midnight madness time (toggles) */ toggleMidnightMadnessMode(): void; /** * update the dipswitch setting (country setting) * Known settings: FRENCH = 48, GERMAN = 112, EUROPE = 208, USA = 0, USA2 = 240 */ setDipSwitchByte(dipSwitch: number): void; /** * get the current dip switch setting */ getDipSwitchByte(): number; /** * Reset the emulator */ reset(): void; /** * Returns current WPC-Emu version */ version(): string; } /** * initialize emulator * @param romData the game rom as { u06: UInt8Array } * @param gameEntry game metadata from the internal database */ function initVMwithRom(romData: GamelistDB.RomData, gameEntry: GamelistDB.GameEntry): Promise<Emulator>; function getVersion(): string; } export namespace WpcEmuWebWorkerApi { /** * create new webworker API interface * @param optionalWebWorkerInstance Optional worker instance, useful if you use https://github.com/webpack-contrib/worker-loader * @returns new WebWorkerApi instance */ function initializeWebworkerAPI(optionalWebWorkerInstance?: any): WebWorkerApi; interface WorkerStatistic { averageRTTms: number; sentMessages: number; failedMessages: number; } interface WorkerMessage { requestId: number; message: string; parameter?: string; } interface EmuStateWpc { diagnosticLed: number; /** * the output lamp state */ lampState?: Uint8Array; solenoidState?: Uint8Array; /** * Contains 8 bytes of the GI lamps */ generalIlluminationState: Uint8Array; /** * the switch state */ inputState?: Uint8Array; diagnosticLedToggleCount: number; midnightModeEnabled: boolean; irqEnabled: boolean; activeRomBank: number; time: string; blankSignalHigh: boolean; watchdogExpiredCounter: number; watchdogTicks: number; zeroCrossFlag: number; inputSwitchMatrixActiveColumn: Uint8Array; lampRow: number; lampColumn: number; wpcSecureScrambler: number; } interface EmuStateSound { volume: number; readDataBytes: number; writeDataBytes: number; readControlBytes: number; writeControlBytes: number; } interface EmuStateDMD { scanline: number; dmdPageMapping: number[]; activepage?: number; /** * the raw and unblended video RAM */ videoRam?: Uint8Array; /** * shaded DMD video output, one pixel uses 1 byte (0=off, 1=33%, 2=66%, 3=100%) */ dmdShadedBuffer?: Uint8Array; videoOutputBuffer?: Uint8Array; nextActivePage?: number; requestFIRQ?: boolean; ticksUpdateDmd?: number; } interface EmuStateAsic { ram?: Uint8Array; memoryPosition?: object[]; sound: EmuStateSound; wpc: EmuStateWpc; dmd: EmuStateDMD; } interface EmuStateCpu { /** * Current PC register state */ regPC: number; regS: number; regU: number; regA: number; regB: number; /** * how many FIRQ calls were executed */ firqCount: number; /** * how many IRQ calls were executed */ irqCount: number; /** * how man FIRQ calls were missed (due flag state?) */ missedFIRQ: number; /** * how man IRQ calls were missed (due flag state?) */ missedIRQ: number; /** * how many NMI calls were made * NOTE: should be 0 as NMI functions are not implemented! */ nmiCount: number; regCC: number; regDP: number; regX: number; regY: number; /** * how many ticks were processed */ tickCount: number; } interface EmuState { asic: EmuStateAsic; cpuState: EmuStateCpu; /** * Average ops per ms * TODO should be renamed to averageTickerPerMs */ opsMs: number; /** * how many times a RAM write was refused because it was protected */ protectedMemoryWriteAttempts: number; /** * Absolute emulator runtime in ms */ runtime: number; /** * how many ticks are left until the next IRQ will be executed */ ticksIrq: number; /** * internal version number of the data */ version: number; } class WebWorkerApi { /** * initialize emulator * @param romData the game rom as { u06: UInt8Array } * @param gameEntry game metadata from the internal database */ initializeEmulator(romData: GamelistDB.RomData, gameEntry: GamelistDB.GameEntry): Promise<WorkerMessage>; /** * reset the RPC proxy to its initial state. used when a new game is loaded. */ reset(): void; /** * returns meta data about the connection with the webworker process */ getStatistics(): WorkerStatistic; /** * reboots the emulator */ resetEmulator(): Promise<WorkerMessage>; /** * Cabinet key emulation (Coins, ESC, +, -, ENTER) * @param value number between 1 and 8 */ setCabinetInput(value: number): Promise<WorkerMessage>; /** * Set or toggle a switch * @param switchNr number between 11 and 99 * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setSwitchInput(switchNr: number, optionalValue?: boolean): Promise<WorkerMessage>; /** * fliptronic flipper move (depends on the machine if this is supported) * @param value the switch name, like 'F1', 'F2' .. 'F8' * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setFliptronicsInput(value: string, optionalValue?: boolean): Promise<WorkerMessage>; /** * set target framerate of the client * @param framerate the new framerate of the emulator */ adjustFramerate(framerate: number): Promise<WorkerMessage>; /** * set the internal time some seconds before midnight madness time (toggles) */ toggleMidnightMadnessMode(): Promise<WorkerMessage>; /** * update the dipswitch setting (country setting) * Known settings: FRENCH = 48, GERMAN = 112, EUROPE = 208, USA = 0, USA2 = 240 */ setDipSwitchByte(dipSwitch: number): void; /** * get the current dip switch setting */ getDipSwitchByte(): number; /** * Debugging tool, write to emu ram * @param offset of memory, must be between 0..0x3FFF * @param value to write to the memory location (uint8) */ writeMemory(offset: number, value: number): Promise<WorkerMessage>; /** * stop setInterval loop in web worker */ pauseEmulator(): Promise<WorkerMessage>; /** * resume setInterval loop in web worker */ resumeEmulator(): Promise<WorkerMessage>; /** * callback to playback audio samples * @param callbackFunction function will be called when a sampleId should be played */ registerAudioConsumer(callbackFunction: (audioJSON: WpcEmuApi.AudioMessage) => void): Promise<WorkerMessage>; /** * register ui callback function * @param callbackFunction function will be called when new ui state is available */ registerUiUpdateConsumer(callbackFunction: (uiState: EmuState) => void): Promise<void>; /** * get the internal state of the emulator, used to save current emulator state */ getEmulatorState(): Promise<EmuState>; /** * Run the system for a particular amount of time * @param advanceByMs how many ms should the CPU run, 1000 ticks means one seconds * @param tickSteps how many cycles the cpu should run before other systems should be updated? see BENCHMARK.md for more details * @returns executed ticks */ emuStepByTime(advanceByMs: number, ticksStep: number): number; /** * restore a previously saved emulator state * @param emuState the new state */ setEmulatorState(emuState: EmuState): Promise<WorkerMessage>; /** * returns current WPC-Emu version */ getVersion(): Promise<string>; /** * returns current rom name */ getEmulatorRomName(): Promise<string>; } namespace WebWorker { class WpcEmu { /** * configure new framerate for the setInterval calls */ configureFramerate(frameRate: number): void; /** * returns the current ui state of the emu. * NOTE: compared to the getEmulatorState function call, getUiState delivers only an element if the content changed. */ getUiState(): EmuState; /** * callback to playback audio samples * @param callbackFunction function will be called when a sampleId should be played */ registerAudioConsumer(callbackFunction: (audioJSON: WpcEmuApi.AudioMessage) => void): void; /** * reset the emulator */ reset(): void; /** * Cabinet key emulation (Coins, ESC, +, -, ENTER) * @param value number between 1 and 8 */ setCabinetInput(value: number): void; /** * Toggle or set a switch * @param switchNr number between 11 and 99 * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setSwitchInput(switchNr: number, optionalValue?: boolean): void; /** * fliptronic flipper move (depends on the machine if this is supported) * @param value the switch name, like 'F1', 'F2' .. 'F8' * @param optionalValue if undefined, switch will toggle, else set to the defined state */ setFliptronicsInput(value: string, optionalValue?: boolean): void; /** * set the internal time some seconds before midnight madness time (toggles) */ toggleMidnightMadnessMode(): void; /** * returns current WPC-Emu version */ getVersion(): string; /** * returns current rom name */ getEmulatorRomName(): string; /** * get the internal state of the emulator, used to save current emulator state */ getEmulatorState(): EmuState; /** * restore a previously saved emulator state * @param emuState the new state */ setEmulatorState(emuState: EmuState): void; /** * start the emulator (Reset CPU Board, TODO should go awa) */ start(): void; /** * clear setInterval loop in web worker */ stop(): void; /** * stop setInterval loop in web worker, if emulator is already paused, next step will be executed */ pause(): void; /** * resume setInterval loop in web worker */ resume(): void; /** * Debugging tool, write to emu ram * @param offset of memory, must be between 0..0x3FFF * @param value to write to the memory location (uint8) */ writeMemory(offset: number, value: number): void; /** * if you don't want to use the setInterval function (pause/resume) because there is already * a loop running, use this function to run the emulator for N ms. */ emuStepByTime(advanceByMs: number): void; } /** * pass RPC messages from WpcEmuWebWorkerApi to the real implementaion * @param event message revieved from the WpcEmuWebWorkerApi * @param postMessage webworked postMessage function */ function handleMessage(event: any, postMessage: any): void; /** * returns the current emu instance, so the emu can be used within a worker thread. * Note: the emu might not be initialized yet - so consumer must make sure emu is defined */ function getEmu(): WpcEmu; /** * clears the state of webworker */ function clearState(): void; } }
the_stack
import { artifacts } from "@connext/contracts"; import { Address, AssetId, ContractAddresses, HexString, ILoggerService, IStoreService, multiAssetMultiPartyCoinTransferEncoding, MultiAssetMultiPartyCoinTransferInterpreterParams, NetworkContext, OutcomeType, PureActionApps, SingleAssetTwoPartyCoinTransferInterpreterParams, TwoPartyFixedOutcome, TwoPartyFixedOutcomeInterpreterParams, ProtocolMessageData, ProtocolName, PublicIdentifier, CHANNEL_PROTOCOL_VERSION, ProtocolParam, ProtocolMessage, } from "@connext/types"; import { logTime, recoverAddressFromChannelMessage, getAddressFromAssetId, stringify, } from "@connext/utils"; import { BigNumber, utils, constants } from "ethers"; import { AppInstance, CoinTransfer, convertCoinTransfersToCoinTransfersMap, TokenIndexedCoinTransferMap, StateChannel, } from "../models"; import { NO_STATE_CHANNEL_FOR_MULTISIG_ADDR, TWO_PARTY_OUTCOME_DIFFERENT_ASSETS } from "../errors"; const { MaxUint256 } = constants; const { defaultAbiCoder, getAddress } = utils; export const parseProtocolMessage = (message?: ProtocolMessage): ProtocolMessage => { const { data, type, from } = message || {}; const { to, protocol, processID, seq, params, error, prevMessageReceived, customData, protocolVersion, } = data || {}; // verify the correct protocol version // FIXME: remove when types package is published const toCompare = CHANNEL_PROTOCOL_VERSION || "1.0.0"; if (!protocolVersion || protocolVersion !== toCompare) { throw new Error( `Incorrect protocol version number detected. Got ${protocolVersion}, expected: ${toCompare}. Please update packages. Message payload: ${stringify( data, )}`, ); } // check that all mandatory fields are properly defined const exists = (x: any) => x !== undefined && x !== null; if (!exists(data) || !exists(type) || !exists(from)) { throw new Error( `Malformed message, missing one of the following fields: data, from, type. Message: ${stringify( message, false, 1, )}`, ); } if ( !exists(to) || !exists(protocol) || !exists(processID) || !exists(seq) || !exists(params) || !exists(customData) ) { throw new Error( `Malformed protocol message data, missing one of the following fields within the data object: to, protocol, processID, seq, params, customData. Message: ${stringify( message?.data, false, 1, )}`, ); } return { type: type!, from: from!, data: { processID: processID!, // uuid protocol: protocol!, protocolVersion, params: params!, to: to!, error, seq: seq!, // protocol responders should not send messages + error if the protocol // timeout has elapsed during their execution. this edgecase // is handled within the IO_SEND opcode for the final protocol message, // and by default when using IO_SEND_AND_WAIT prevMessageReceived, // customData: Additional data which depends on the protocol (or even the specific message // number in a protocol) lives here. Includes signatures customData: customData!, }, }; }; export const generateProtocolMessageData = ( to: PublicIdentifier, protocol: ProtocolName, processID: string, seq: number, params: ProtocolParam, messageData: Partial<{ error: string; prevMessageReceived: number; customData: { [key: string]: any }; }> = {}, ): ProtocolMessageData => { const { error, prevMessageReceived, customData } = messageData; return { processID, // uuid protocol, // FIXME: remove optional default after publishing protocolVersion: CHANNEL_PROTOCOL_VERSION || "1.0.0", params, to, error, seq, // protocol responders should not send messages + error if the protocol // timeout has elapsed during their execution. this edgecase // is handled within the IO_SEND opcode for the final protocol message, // and by default when using IO_SEND_AND_WAIT prevMessageReceived, // customData: Additional data which depends on the protocol (or even the specific message // number in a protocol) lives here. Includes signatures customData: customData || {}, }; }; export const getPureBytecode = ( appDefinition: Address, contractAddresses: ContractAddresses, ): HexString | undefined => { // If this app's action is pure, provide bytecode to use for faster in-memory evm calls const appEntry = Object.entries(contractAddresses).find((entry) => entry[1] === appDefinition); const bytecode = appEntry && appEntry[0] && PureActionApps && PureActionApps.includes(appEntry[0]) ? artifacts[appEntry[0]].deployedBytecode : undefined; return bytecode; }; export async function assertIsValidSignature( expectedSigner: string, commitmentHash?: string, signature?: string, loggingContext?: string, ): Promise<void> { if (typeof commitmentHash === "undefined") { throw new Error( `assertIsValidSignature received an undefined commitment. ${ loggingContext ? `${loggingContext}` : "" }`, ); } if (typeof signature === "undefined") { throw new Error( `assertIsValidSignature received an undefined signature. ${ loggingContext ? `${loggingContext}` : "" }`, ); } // recoverAddressFromChannelMessage: 83 ms, hashToSign: 7 ms const signer = await recoverAddressFromChannelMessage(commitmentHash, signature); if (getAddress(expectedSigner).toLowerCase() !== signer.toLowerCase()) { throw new Error( `Validating a signature with expected signer ${expectedSigner} but recovered ${signer} for commitment hash ${commitmentHash}. ${ loggingContext ? `${loggingContext}` : "" }`, ); } } export async function stateChannelClassFromStoreByMultisig( multisigAddress: string, store: IStoreService, ) { const json = await store.getStateChannel(multisigAddress); if (!json) { throw new Error(NO_STATE_CHANNEL_FOR_MULTISIG_ADDR(multisigAddress)); } return StateChannel.fromJson(json); } /** * Get the outcome of the app instance given, decode it according * to the outcome type stored in the app instance model, and return * a value uniformly across outcome type and whether the app is virtual * or direct. This return value must not contain the intermediary. */ export async function computeTokenIndexedFreeBalanceIncrements( appInstance: AppInstance, network: NetworkContext, encodedOutcomeOverride: string = "", log?: ILoggerService, ): Promise<TokenIndexedCoinTransferMap> { const { outcomeType } = appInstance; const checkpoint = Date.now(); if (!encodedOutcomeOverride || encodedOutcomeOverride === "") { try { encodedOutcomeOverride = await appInstance.computeOutcomeWithCurrentState( network.provider, getPureBytecode(appInstance.appDefinition, network.contractAddresses), ); } catch (e) { throw new Error(`Unable to compute outcome: ${e.stack || e.message}`); } } const encodedOutcome = encodedOutcomeOverride; if (log) logTime(log, checkpoint, `Computed outcome with current state`); switch (outcomeType) { case OutcomeType.TWO_PARTY_FIXED_OUTCOME: { return handleTwoPartyFixedOutcome( encodedOutcome, appInstance.outcomeInterpreterParameters as TwoPartyFixedOutcomeInterpreterParams, ); } case OutcomeType.SINGLE_ASSET_TWO_PARTY_COIN_TRANSFER: { return handleSingleAssetTwoPartyCoinTransfer( encodedOutcome, appInstance.outcomeInterpreterParameters as SingleAssetTwoPartyCoinTransferInterpreterParams, ); } case OutcomeType.MULTI_ASSET_MULTI_PARTY_COIN_TRANSFER: { return handleMultiAssetMultiPartyCoinTransfer( encodedOutcome, appInstance.outcomeInterpreterParameters as MultiAssetMultiPartyCoinTransferInterpreterParams, ); } default: { throw new Error( `computeTokenIndexedFreeBalanceIncrements received an AppInstance with unknown OutcomeType: ${outcomeType}`, ); } } } function handleTwoPartyFixedOutcome( encodedOutcome: string, interpreterParams: TwoPartyFixedOutcomeInterpreterParams, ): TokenIndexedCoinTransferMap { const { amount, playerAddrs, tokenAddress } = interpreterParams; switch (decodeTwoPartyFixedOutcome(encodedOutcome)) { case TwoPartyFixedOutcome.SEND_TO_ADDR_ONE: return { [tokenAddress]: { [playerAddrs[0]]: amount, }, }; case TwoPartyFixedOutcome.SEND_TO_ADDR_TWO: return { [tokenAddress]: { [playerAddrs[1]]: amount, }, }; case TwoPartyFixedOutcome.SPLIT_AND_SEND_TO_BOTH_ADDRS: default: return { [tokenAddress]: { [playerAddrs[0]]: amount.div(2), [playerAddrs[1]]: amount.sub(amount.div(2)), }, }; } } function handleMultiAssetMultiPartyCoinTransfer( encodedOutcome: string, interpreterParams: MultiAssetMultiPartyCoinTransferInterpreterParams, ): TokenIndexedCoinTransferMap { const decodedTransfers = decodeMultiAssetMultiPartyCoinTransfer(encodedOutcome); return interpreterParams.tokenAddresses.reduce( (acc, tokenAddress, index) => ({ ...acc, [tokenAddress]: convertCoinTransfersToCoinTransfersMap(decodedTransfers[index]), }), {}, ); } function handleSingleAssetTwoPartyCoinTransfer( encodedOutcome: string, interpreterParams: SingleAssetTwoPartyCoinTransferInterpreterParams, ): TokenIndexedCoinTransferMap { const { tokenAddress } = interpreterParams; // 0ms const [ { to: to1, amount: amount1 }, { to: to2, amount: amount2 }, ] = decodeSingleAssetTwoPartyCoinTransfer(encodedOutcome); return { [tokenAddress]: { [to1 as string]: amount1 as BigNumber, [to2 as string]: amount2 as BigNumber, }, }; } function decodeTwoPartyFixedOutcome(encodedOutcome: string): TwoPartyFixedOutcome { const [twoPartyFixedOutcome] = defaultAbiCoder.decode(["uint256"], encodedOutcome) as [BigNumber]; return twoPartyFixedOutcome.toNumber(); } function decodeSingleAssetTwoPartyCoinTransfer( encodedOutcome: string, ): [CoinTransfer, CoinTransfer] { const [[[to1, amount1], [to2, amount2]]] = defaultAbiCoder.decode( ["tuple(address to, uint256 amount)[2]"], encodedOutcome, ); return [ { to: to1, amount: amount1 }, { to: to2, amount: amount2 }, ]; } function decodeMultiAssetMultiPartyCoinTransfer(encodedOutcome: string): CoinTransfer[][] { const [coinTransferListOfLists] = defaultAbiCoder.decode( [multiAssetMultiPartyCoinTransferEncoding], encodedOutcome, ); return coinTransferListOfLists.map((coinTransferList) => coinTransferList.map(({ to, amount }) => ({ to, amount })), ); } /** * Returns the parameters for two hard-coded possible interpreter types. * * Note that this is _not_ a built-in part of the protocol. Here we are _restricting_ * all newly installed AppInstances to be either of type COIN_TRANSFER or * TWO_PARTY_FIXED_OUTCOME. In the future, we will be extending the ProtocolParams.Install * to indidicate the interpreterAddress and interpreterParams so the developers * installing apps have more control, however for now we are putting this logic * inside of the client (the Node) by adding an "outcomeType" variable which * is a simplification of the actual decision a developer has to make with their app. * * TODO: update doc on how MultiAssetMultiPartyCoinTransferInterpreterParams work * * @param {OutcomeType} outcomeType - either COIN_TRANSFER or TWO_PARTY_FIXED_OUTCOME * @param {utils.BigNumber} initiatorBalanceDecrement - amount Wei initiator deposits * @param {utils.BigNumber} responderBalanceDecrement - amount Wei responder deposits * @param {string} initiatorFbAddress - the address of the recipient of initiator * @param {string} responderFbAddress - the address of the recipient of responder * * @returns An object with the required parameters for both interpreter types, one * will be undefined and the other will be a correctly structured POJO. The AppInstance * object currently accepts both in its constructor and internally manages them. */ export function computeInterpreterParameters( multisigOwners: string[], outcomeType: OutcomeType, initiatorAssetId: AssetId, responderAssetId: AssetId, initiatorBalanceDecrement: BigNumber, responderBalanceDecrement: BigNumber, initiatorFbAddress: string, responderFbAddress: string, disableLimit: boolean, ): | TwoPartyFixedOutcomeInterpreterParams | MultiAssetMultiPartyCoinTransferInterpreterParams | SingleAssetTwoPartyCoinTransferInterpreterParams { const initiatorDepositAssetId = getAddressFromAssetId(initiatorAssetId); const responderDepositAssetId = getAddressFromAssetId(responderAssetId); // make sure the interpreter params ordering corr. with the fb const sameOrder = initiatorFbAddress === multisigOwners[0]; switch (outcomeType) { case OutcomeType.TWO_PARTY_FIXED_OUTCOME: { if (initiatorDepositAssetId !== responderDepositAssetId) { throw new Error( TWO_PARTY_OUTCOME_DIFFERENT_ASSETS(initiatorDepositAssetId, responderDepositAssetId), ); } return { tokenAddress: initiatorDepositAssetId, playerAddrs: sameOrder ? [initiatorFbAddress, responderFbAddress] : [responderFbAddress, initiatorFbAddress], amount: initiatorBalanceDecrement.add(responderBalanceDecrement), }; } case OutcomeType.MULTI_ASSET_MULTI_PARTY_COIN_TRANSFER: { if (initiatorDepositAssetId === responderDepositAssetId) { return { limit: [initiatorBalanceDecrement.add(responderBalanceDecrement)], tokenAddresses: [initiatorDepositAssetId], }; } const limit = sameOrder ? [initiatorBalanceDecrement, responderBalanceDecrement] : [responderBalanceDecrement, initiatorBalanceDecrement]; const tokenAddresses = sameOrder ? [initiatorDepositAssetId, responderDepositAssetId] : [responderDepositAssetId, initiatorDepositAssetId]; return { limit, tokenAddresses, }; } case OutcomeType.SINGLE_ASSET_TWO_PARTY_COIN_TRANSFER: { if (initiatorDepositAssetId !== responderDepositAssetId) { throw new Error( TWO_PARTY_OUTCOME_DIFFERENT_ASSETS(initiatorDepositAssetId, responderDepositAssetId), ); } return { limit: disableLimit ? MaxUint256 : initiatorBalanceDecrement.add(responderBalanceDecrement), tokenAddress: initiatorDepositAssetId, }; } default: { throw new Error("The outcome type in this application logic contract is not supported yet."); } } }
the_stack
import React, { ForwardRefRenderFunction, useEffect, useRef, useState } from 'react' import clsx from 'clsx' import { capitalizeFirstLetter, humanFriendlyDuration, pluralize } from 'lib/utils' import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo' import { Button, ButtonProps, Popover } from 'antd' import { ArrowRightOutlined, InfoCircleOutlined } from '@ant-design/icons' import { SeriesGlyph } from 'lib/components/SeriesGlyph' import { ArrowBottomRightOutlined, IconInfinity } from 'lib/components/icons' import { funnelLogic } from './funnelLogic' import { useThrottledCallback } from 'use-debounce' import './FunnelBarGraph.scss' import { useActions, useValues } from 'kea' import { LEGACY_InsightTooltip } from 'scenes/insights/InsightTooltip/LEGACY_InsightTooltip' import { FunnelLayout } from 'lib/constants' import { formatDisplayPercentage, getBreakdownMaxIndex, getReferenceStep, getSeriesColor, getSeriesPositionName, humanizeOrder, humanizeStepCount, } from './funnelUtils' import { FunnelStepReference, StepOrderValue } from '~/types' import { Tooltip } from 'lib/components/Tooltip' import { FunnelStepTable } from 'scenes/insights/InsightTabs/FunnelTab/FunnelStepTable' import { EntityFilterInfo } from 'lib/components/EntityFilterInfo' import { getActionFilterFromFunnelStep } from 'scenes/insights/InsightTabs/FunnelTab/funnelStepTableUtils' import { FunnelStepDropdown } from './FunnelStepDropdown' import { insightLogic } from 'scenes/insights/insightLogic' import { useResizeObserver } from '../../lib/hooks/useResizeObserver' interface BarProps { percentage: number name?: string onBarClick?: () => void disabled?: boolean isBreakdown?: boolean breakdownIndex?: number breakdownMaxIndex?: number breakdownSumPercentage?: number popoverTitle?: string | JSX.Element | null popoverMetrics?: { title: string; value: number | string; visible?: boolean }[] aggregationTargetLabel: { singular: string; plural: string } } type LabelPosition = 'inside' | 'outside' function DuplicateStepIndicator(): JSX.Element { return ( <span style={{ marginLeft: 4 }}> <Tooltip title={ <> <b>Sequential &amp; Repeated Events</b> <p> When an event is repeated across funnel steps, it is interpreted as a sequence. For example, a three-step funnel consisting of pageview events is interpretted as first pageview, followed by second pageview, followed by a third pageview. </p> </> } > <InfoCircleOutlined className="info-indicator" /> </Tooltip> </span> ) } function Bar({ percentage, name, onBarClick, disabled, isBreakdown = false, breakdownIndex, breakdownMaxIndex, breakdownSumPercentage, popoverTitle = null, popoverMetrics = [], aggregationTargetLabel, }: BarProps): JSX.Element { const barRef = useRef<HTMLDivElement | null>(null) const labelRef = useRef<HTMLDivElement | null>(null) const [labelPosition, setLabelPosition] = useState<LabelPosition>('inside') const [labelVisible, setLabelVisible] = useState(true) const LABEL_POSITION_OFFSET = 8 // Defined here and in SCSS const { insightProps } = useValues(insightLogic) const { clickhouseFeaturesEnabled } = useValues(funnelLogic(insightProps)) const cursorType = clickhouseFeaturesEnabled && !disabled ? 'pointer' : '' const hasBreakdownSum = isBreakdown && typeof breakdownSumPercentage === 'number' const shouldShowLabel = !isBreakdown || (hasBreakdownSum && labelVisible) function decideLabelPosition(): void { if (hasBreakdownSum) { // Label is always outside for breakdowns, but don't show if it doesn't fit in the wrapper setLabelPosition('outside') const barWidth = barRef.current?.clientWidth ?? null const barOffset = barRef.current?.offsetLeft ?? null const wrapperWidth = barRef.current?.parentElement?.clientWidth ?? null const labelWidth = labelRef.current?.clientWidth ?? null if (barWidth !== null && barOffset !== null && wrapperWidth !== null && labelWidth !== null) { if (wrapperWidth - (barWidth + barOffset) < labelWidth + LABEL_POSITION_OFFSET * 2) { setLabelVisible(false) } else { setLabelVisible(true) } } return } // Place label inside or outside bar, based on whether it fits const barWidth = barRef.current?.clientWidth ?? null const labelWidth = labelRef.current?.clientWidth ?? null if (barWidth !== null && labelWidth !== null) { if (labelWidth + LABEL_POSITION_OFFSET * 2 > barWidth) { setLabelPosition('outside') return } } setLabelPosition('inside') } useResizeObserver({ onResize: useThrottledCallback(decideLabelPosition, 200), ref: barRef, }) return ( <Popover trigger="hover" placement="right" content={ <LEGACY_InsightTooltip altTitle={popoverTitle}> {popoverMetrics.map(({ title, value, visible }, index) => visible !== false ? <MetricRow key={index} title={title} value={value} /> : null )} </LEGACY_InsightTooltip> } > <div ref={barRef} className={`funnel-bar ${getSeriesPositionName(breakdownIndex, breakdownMaxIndex)}`} style={{ flex: `${percentage} 1 0`, cursor: cursorType, backgroundColor: getSeriesColor(breakdownIndex), }} onClick={() => { if (clickhouseFeaturesEnabled && !disabled && onBarClick) { onBarClick() } }} > {shouldShowLabel && ( <div ref={labelRef} className={`funnel-bar-percentage ${labelPosition}`} title={ name ? `${capitalizeFirstLetter(aggregationTargetLabel.plural)} who did ${name}` : undefined } role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={(breakdownSumPercentage ?? percentage) * 100} > {formatDisplayPercentage(breakdownSumPercentage ?? percentage)}% </div> )} </div> </Popover> ) } interface ValueInspectorButtonProps { icon?: JSX.Element onClick: (e?: React.MouseEvent) => void children: React.ReactNode disabled?: boolean style?: React.CSSProperties title?: string | undefined innerRef?: React.MutableRefObject<HTMLElement | null> } export function ValueInspectorButton({ icon, onClick, children, disabled = false, style, title, innerRef: refProp, }: ValueInspectorButtonProps): JSX.Element { const props = { type: 'link' as const, icon, onClick, className: 'funnel-inspect-button', disabled, style, title, children: <span className="funnel-inspect-label">{children}</span>, } if (refProp) { const InnerComponent: ForwardRefRenderFunction<HTMLElement | null, ButtonProps> = (_, ref) => ( <Button ref={ref} {...props} /> ) const RefComponent = React.forwardRef(InnerComponent) return <RefComponent ref={refProp} /> } else { return <Button {...props} /> } } interface AverageTimeInspectorProps { onClick: (e?: React.MouseEvent) => void disabled?: boolean averageTime: number aggregationTargetLabel: { singular: string; plural: string } } function AverageTimeInspector({ onClick, disabled, averageTime, aggregationTargetLabel, }: AverageTimeInspectorProps): JSX.Element { // Inspector button which automatically shows/hides the info text. const wrapperRef = useRef<HTMLDivElement | null>(null) const infoTextRef = useRef<HTMLDivElement | null>(null) const buttonRef = useRef<HTMLDivElement | null>(null) const [infoTextVisible, setInfoTextVisible] = useState(true) function decideTextVisible(): void { // Show/hide label position based on whether both items fit horizontally const wrapperWidth = wrapperRef.current?.clientWidth ?? null const infoTextWidth = infoTextRef.current?.offsetWidth ?? null const buttonWidth = buttonRef.current?.offsetWidth ?? null if (wrapperWidth !== null && infoTextWidth !== null && buttonWidth !== null) { if (infoTextWidth + buttonWidth <= wrapperWidth) { setInfoTextVisible(true) return } } setInfoTextVisible(false) } useEffect(() => { decideTextVisible() }, []) useResizeObserver({ onResize: useThrottledCallback(decideTextVisible, 200), ref: wrapperRef, }) return ( <div ref={wrapperRef}> <span ref={infoTextRef} className="text-muted-alt" style={{ paddingRight: 4, display: 'inline-block', visibility: infoTextVisible ? undefined : 'hidden' }} > Average time: </span> <ValueInspectorButton innerRef={buttonRef} style={{ paddingLeft: 0, paddingRight: 0 }} onClick={onClick} disabled={disabled} title={`Average of time elapsed for each ${aggregationTargetLabel.singular} between completing this step and starting the next one.`} > {humanFriendlyDuration(averageTime, 2)} </ValueInspectorButton> </div> ) } export function MetricRow({ title, value }: { title: string; value: string | number }): JSX.Element { return ( <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between' }}> <div>{title}</div> <div> <strong style={{ paddingLeft: 6 }}>{value}</strong> </div> </div> ) } export function FunnelBarGraph({ color = 'white' }: { color?: string }): JSX.Element { const { insightProps } = useValues(insightLogic) const { dashboardItemId } = insightProps const logic = funnelLogic(insightProps) const { filters, visibleStepsWithConversionMetrics: steps, stepReference, barGraphLayout: layout, clickhouseFeaturesEnabled, aggregationTargetLabel, isModalActive, } = useValues(logic) const { openPersonsModalForStep } = useActions(logic) // If the layout is vertical, we render bars using the table as a legend. See FunnelStepTable if (layout === FunnelLayout.vertical) { return <FunnelStepTable /> } // Everything rendered after is a funnel in top-to-bottom mode. return ( <div data-attr="funnel-bar-graph" className={clsx( 'funnel-bar-graph', FunnelLayout.horizontal, color && color !== 'white' && 'colored', color )} style={insightProps.syncWithUrl ? { minHeight: 450 } : {}} > {steps.map((step, stepIndex) => { const basisStep = getReferenceStep(steps, stepReference, stepIndex) const previousStep = getReferenceStep(steps, FunnelStepReference.previous, stepIndex) const showLineBefore = stepIndex > 0 const showLineAfter = stepIndex < steps.length - 1 const breakdownMaxIndex = getBreakdownMaxIndex( Array.isArray(step.nested_breakdown) ? step.nested_breakdown : undefined ) const breakdownSum = (Array.isArray(step.nested_breakdown) && step.nested_breakdown?.reduce((sum, item) => sum + item.count, 0)) || 0 const isBreakdown = Array.isArray(step.nested_breakdown) && step.nested_breakdown?.length !== undefined && !(step.nested_breakdown.length === 1 && step.nested_breakdown[0].breakdown_value === 'Baseline') const dropOffCount = step.order > 0 ? steps[stepIndex - 1].count - step.count : 0 return ( <section key={step.order} className="funnel-step"> <div className="funnel-series-container"> <div className={`funnel-series-linebox ${showLineBefore ? 'before' : ''}`} /> {filters.funnel_order_type === StepOrderValue.UNORDERED ? ( <SeriesGlyph variant="funnel-step-glyph"> <IconInfinity style={{ fill: 'var(--primary_alt)', width: 14 }} /> </SeriesGlyph> ) : ( <SeriesGlyph variant="funnel-step-glyph">{humanizeOrder(step.order)}</SeriesGlyph> )} <div className={`funnel-series-linebox ${showLineAfter ? 'after' : ''}`} /> </div> <header> <div style={{ display: 'flex', maxWidth: '100%', flexGrow: 1 }}> <div className="funnel-step-title"> {filters.funnel_order_type === StepOrderValue.UNORDERED ? ( <span>Completed {humanizeOrder(step.order)} steps</span> ) : ( <EntityFilterInfo filter={getActionFilterFromFunnelStep(step)} /> )} </div> {clickhouseFeaturesEnabled && filters.funnel_order_type !== StepOrderValue.UNORDERED && stepIndex > 0 && step.action_id === steps[stepIndex - 1].action_id && <DuplicateStepIndicator />} <FunnelStepDropdown index={stepIndex} /> </div> <div className={`funnel-step-metadata funnel-time-metadata ${FunnelLayout.horizontal}`}> {step.average_conversion_time && step.average_conversion_time >= 0 + Number.EPSILON ? ( <AverageTimeInspector onClick={() => {}} averageTime={step.average_conversion_time} aggregationTargetLabel={aggregationTargetLabel} disabled /> ) : null} </div> </header> <div className="funnel-inner-viz"> <div className={clsx('funnel-bar-wrapper', { breakdown: isBreakdown })}> {isBreakdown ? ( <> {step?.nested_breakdown?.map((breakdown, index) => { const barSizePercentage = breakdown.count / basisStep.count return ( <Bar key={`${breakdown.action_id}-${step.breakdown_value}-${index}`} isBreakdown={true} breakdownIndex={index} breakdownMaxIndex={breakdownMaxIndex} breakdownSumPercentage={ index === breakdownMaxIndex && breakdownSum ? breakdownSum / basisStep.count : undefined } percentage={barSizePercentage} name={breakdown.name} onBarClick={() => openPersonsModalForStep({ step, converted: true, }) } disabled={!isModalActive} popoverTitle={ <div style={{ wordWrap: 'break-word' }}> <PropertyKeyInfo value={step.name} /> {' • '} {(Array.isArray(breakdown.breakdown) ? breakdown.breakdown.join(', ') : breakdown.breakdown) || 'Other'} </div> } popoverMetrics={[ { title: 'Completed step', value: pluralize( breakdown.count, aggregationTargetLabel.singular, aggregationTargetLabel.plural ), }, { title: 'Conversion rate (total)', value: formatDisplayPercentage( breakdown.conversionRates.total ) + '%', }, { title: `Conversion rate (from step ${humanizeOrder( previousStep.order )})`, value: formatDisplayPercentage( breakdown.conversionRates.fromPrevious ) + '%', visible: step.order !== 0, }, { title: 'Dropped off', value: pluralize( breakdown.droppedOffFromPrevious, aggregationTargetLabel.singular, aggregationTargetLabel.plural ), visible: step.order !== 0 && breakdown.droppedOffFromPrevious > 0, }, { title: `Dropoff rate (from step ${humanizeOrder( previousStep.order )})`, value: formatDisplayPercentage( 1 - breakdown.conversionRates.fromPrevious ) + '%', visible: step.order !== 0 && breakdown.droppedOffFromPrevious > 0, }, { title: 'Average time on step', value: humanFriendlyDuration( breakdown.average_conversion_time ), visible: !!breakdown.average_conversion_time, }, ]} aggregationTargetLabel={aggregationTargetLabel} /> ) })} <div className="funnel-bar-empty-space" onClick={() => openPersonsModalForStep({ step, converted: false })} // dropoff value for steps is negative style={{ flex: `${1 - breakdownSum / basisStep.count} 1 0`, cursor: `${ clickhouseFeaturesEnabled && !dashboardItemId ? 'pointer' : '' }`, }} /> </> ) : ( <> <Bar percentage={step.conversionRates.fromBasisStep} name={step.name} onBarClick={() => openPersonsModalForStep({ step, converted: true })} disabled={!isModalActive} popoverTitle={<PropertyKeyInfo value={step.name} />} popoverMetrics={[ { title: 'Completed step', value: pluralize( step.count, aggregationTargetLabel.singular, aggregationTargetLabel.plural ), }, { title: 'Conversion rate (total)', value: formatDisplayPercentage(step.conversionRates.total) + '%', }, { title: `Conversion rate (from step ${humanizeOrder( previousStep.order )})`, value: formatDisplayPercentage(step.conversionRates.fromPrevious) + '%', visible: step.order !== 0, }, { title: 'Dropped off', value: pluralize( step.droppedOffFromPrevious, aggregationTargetLabel.singular, aggregationTargetLabel.plural ), visible: step.order !== 0 && step.droppedOffFromPrevious > 0, }, { title: `Dropoff rate (from step ${humanizeOrder( previousStep.order )})`, value: formatDisplayPercentage(1 - step.conversionRates.fromPrevious) + '%', visible: step.order !== 0 && step.droppedOffFromPrevious > 0, }, { title: 'Average time on step', value: humanFriendlyDuration(step.average_conversion_time), visible: !!step.average_conversion_time, }, ]} aggregationTargetLabel={aggregationTargetLabel} /> <div className="funnel-bar-empty-space" onClick={() => openPersonsModalForStep({ step, converted: false })} // dropoff value for steps is negative style={{ flex: `${1 - step.conversionRates.fromBasisStep} 1 0`, cursor: `${ clickhouseFeaturesEnabled && !dashboardItemId ? 'pointer' : '' }`, }} /> </> )} </div> <div className="funnel-conversion-metadata funnel-step-metadata"> <div className="step-stat"> <div className="center-flex"> <ValueInspectorButton onClick={() => openPersonsModalForStep({ step, converted: true })} disabled={!isModalActive} > <span className="value-inspector-button-icon"> <ArrowRightOutlined style={{ color: 'var(--success)' }} /> </span> <b> {humanizeStepCount(step.count)}{' '} {pluralize( step.count, aggregationTargetLabel.singular, aggregationTargetLabel.plural, false )} </b> </ValueInspectorButton> <span className="text-muted-alt"> ( {formatDisplayPercentage( step.order > 0 ? step.count / steps[stepIndex - 1].count : 1 )} %) </span> </div> <div className="text-muted-alt conversion-metadata-caption" style={{ flexGrow: 1 }}> completed step </div> </div> <div className="step-stat" style={stepIndex === 0 ? { visibility: 'hidden' } : undefined} > <div className="center-flex"> <ValueInspectorButton onClick={() => openPersonsModalForStep({ step, converted: false })} disabled={!isModalActive} > <span className="value-inspector-button-icon"> <ArrowBottomRightOutlined style={{ color: 'var(--danger)' }} /> </span> <b> {humanizeStepCount(dropOffCount)}{' '} {pluralize( dropOffCount, aggregationTargetLabel.singular, aggregationTargetLabel.plural, false )} </b> </ValueInspectorButton> <span className="text-muted-alt"> ( {formatDisplayPercentage( step.order > 0 ? 1 - step.count / steps[stepIndex - 1].count : 0 )} %) </span> </div> <div className="text-muted-alt conversion-metadata-caption">dropped off</div> </div> </div> </div> </section> ) })} </div> ) }
the_stack
import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; export type Maybe<T> = T | null; export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string, String: string, Boolean: boolean, Int: number, Float: number, DateTime: any, }; export type AddAnswerInput = { text: Scalars['String'], inAnswerTo: QuestionRef, }; export type AddAuthorInput = { username: Scalars['String'], password: Scalars['String'], email: Scalars['String'], dob?: Maybe<Scalars['DateTime']>, }; export type AddCommentInput = { text: Scalars['String'], commentsOn: PostRef, }; export type AddQuestionInput = { text: Scalars['String'], title: Scalars['String'], tags?: Maybe<Array<Maybe<Scalars['String']>>>, }; export type Answer = Post & { __typename?: 'Answer', id: Scalars['ID'], text?: Maybe<Scalars['String']>, datePublished?: Maybe<Scalars['DateTime']>, likes?: Maybe<Scalars['Int']>, author: Author, inAnswerTo: Question, comments?: Maybe<Array<Maybe<Comment>>>, }; export type Author = { __typename?: 'Author', username: Scalars['String'], email: Scalars['String'], dob?: Maybe<Scalars['DateTime']>, questions?: Maybe<Array<Maybe<Question>>>, answers?: Maybe<Array<Maybe<Answer>>>, }; export type Comment = Post & { __typename?: 'Comment', id: Scalars['ID'], text?: Maybe<Scalars['String']>, datePublished?: Maybe<Scalars['DateTime']>, likes?: Maybe<Scalars['Int']>, author: Author, commentsOn: Post, comments?: Maybe<Array<Maybe<Comment>>>, }; export type DateTimeFilter = { eq?: Maybe<Scalars['DateTime']>, le?: Maybe<Scalars['DateTime']>, lt?: Maybe<Scalars['DateTime']>, ge?: Maybe<Scalars['DateTime']>, gt?: Maybe<Scalars['DateTime']>, }; export type Mutation = { __typename?: 'Mutation', /** # Keep some of the mutations from the backend */ addQuestion?: Maybe<Question>, addAnswer?: Maybe<Answer>, addComment?: Maybe<Comment>, /** # Change the updatePost mutation to some more intentional operations */ editPostText?: Maybe<Post>, likePost?: Maybe<Post>, }; export type MutationAddQuestionArgs = { input: AddQuestionInput }; export type MutationAddAnswerArgs = { input: AddAnswerInput }; export type MutationAddCommentArgs = { input: AddCommentInput }; export type MutationEditPostTextArgs = { id: Scalars['ID'], newText: Scalars['String'] }; export type MutationLikePostArgs = { id: Scalars['ID'], likes: Scalars['Int'] }; export type Post = { id: Scalars['ID'], text?: Maybe<Scalars['String']>, datePublished?: Maybe<Scalars['DateTime']>, likes?: Maybe<Scalars['Int']>, author: Author, }; export type PostRef = { id: Scalars['ID'], }; export type Query = { __typename?: 'Query', /** # Expose only some of the queries from the Dgraph backend */ getQuestion?: Maybe<Question>, getAnswer?: Maybe<Answer>, getComment?: Maybe<Comment>, queryQuestion?: Maybe<Array<Maybe<Question>>>, /** # And add some extra queries */ myTopQuestions?: Maybe<Array<Maybe<Question>>>, }; export type QueryGetQuestionArgs = { id: Scalars['ID'] }; export type QueryGetAnswerArgs = { id: Scalars['ID'] }; export type QueryGetCommentArgs = { id: Scalars['ID'] }; export type QueryQueryQuestionArgs = { filter?: Maybe<QuestionFilter>, order?: Maybe<QuestionOrder>, first?: Maybe<Scalars['Int']>, offset?: Maybe<Scalars['Int']> }; export type Question = Post & { __typename?: 'Question', id: Scalars['ID'], text?: Maybe<Scalars['String']>, datePublished?: Maybe<Scalars['DateTime']>, likes?: Maybe<Scalars['Int']>, author: Author, title: Scalars['String'], tags?: Maybe<Array<Maybe<Scalars['String']>>>, answers?: Maybe<Array<Maybe<Answer>>>, comments?: Maybe<Array<Maybe<Comment>>>, }; export type QuestionFilter = { title?: Maybe<StringTermFilter>, tags?: Maybe<StringExactFilter>, text?: Maybe<StringFullTextFilter>, datePublished?: Maybe<DateTimeFilter>, or?: Maybe<QuestionFilter>, }; export type QuestionOrder = { asc?: Maybe<QuestionOrderable>, desc?: Maybe<QuestionOrderable>, then?: Maybe<QuestionOrder>, }; export enum QuestionOrderable { Likes = 'likes', DatePublished = 'datePublished' } export type QuestionRef = { id: Scalars['ID'], }; export type StringExactFilter = { eq?: Maybe<Scalars['String']>, }; export type StringFullTextFilter = { alloftext?: Maybe<Scalars['String']>, anyoftext?: Maybe<Scalars['String']>, }; export type StringHashFilter = { eq?: Maybe<Scalars['String']>, }; export type StringTermFilter = { allofterms?: Maybe<Scalars['String']>, anyofterms?: Maybe<Scalars['String']>, }; export type WithIndex<TObject> = TObject & Record<string, any>; export type ResolversObject<TObject> = WithIndex<TObject>; export type ResolverTypeWrapper<T> = Promise<T> | T; export type ResolverFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => Promise<TResult> | TResult; export type StitchingResolver<TResult, TParent, TContext, TArgs> = { fragment: string; resolve: ResolverFn<TResult, TParent, TContext, TArgs>; }; export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = | ResolverFn<TResult, TParent, TContext, TArgs> | StitchingResolver<TResult, TParent, TContext, TArgs>; export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>; export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>; } export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>; resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>; } export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> = | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs> | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>; export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>) | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>; export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = ( parent: TParent, context: TContext, info: GraphQLResolveInfo ) => Maybe<TTypes>; export type isTypeOfResolverFn = (obj: any, info: GraphQLResolveInfo) => boolean; export type NextResolverFn<T> = () => Promise<T>; export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = ( next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = ResolversObject<{ Query: ResolverTypeWrapper<{}>, ID: ResolverTypeWrapper<Scalars['ID']>, Question: ResolverTypeWrapper<Question>, Post: ResolverTypeWrapper<Post>, String: ResolverTypeWrapper<Scalars['String']>, DateTime: ResolverTypeWrapper<Scalars['DateTime']>, Int: ResolverTypeWrapper<Scalars['Int']>, Author: ResolverTypeWrapper<Author>, Answer: ResolverTypeWrapper<Answer>, Comment: ResolverTypeWrapper<Comment>, QuestionFilter: QuestionFilter, StringTermFilter: StringTermFilter, StringExactFilter: StringExactFilter, StringFullTextFilter: StringFullTextFilter, DateTimeFilter: DateTimeFilter, QuestionOrder: QuestionOrder, QuestionOrderable: QuestionOrderable, Mutation: ResolverTypeWrapper<{}>, AddQuestionInput: AddQuestionInput, AddAnswerInput: AddAnswerInput, QuestionRef: QuestionRef, AddCommentInput: AddCommentInput, PostRef: PostRef, Boolean: ResolverTypeWrapper<Scalars['Boolean']>, AddAuthorInput: AddAuthorInput, StringHashFilter: StringHashFilter, }>; /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = ResolversObject<{ Query: {}, ID: Scalars['ID'], Question: Question, Post: Post, String: Scalars['String'], DateTime: Scalars['DateTime'], Int: Scalars['Int'], Author: Author, Answer: Answer, Comment: Comment, QuestionFilter: QuestionFilter, StringTermFilter: StringTermFilter, StringExactFilter: StringExactFilter, StringFullTextFilter: StringFullTextFilter, DateTimeFilter: DateTimeFilter, QuestionOrder: QuestionOrder, QuestionOrderable: QuestionOrderable, Mutation: {}, AddQuestionInput: AddQuestionInput, AddAnswerInput: AddAnswerInput, QuestionRef: QuestionRef, AddCommentInput: AddCommentInput, PostRef: PostRef, Boolean: Scalars['Boolean'], AddAuthorInput: AddAuthorInput, StringHashFilter: StringHashFilter, }>; export type AnswerResolvers<ContextType = any, ParentType extends ResolversParentTypes['Answer'] = ResolversParentTypes['Answer']> = ResolversObject<{ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, datePublished?: Resolver<Maybe<ResolversTypes['DateTime']>, ParentType, ContextType>, likes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, author?: Resolver<ResolversTypes['Author'], ParentType, ContextType>, inAnswerTo?: Resolver<ResolversTypes['Question'], ParentType, ContextType>, comments?: Resolver<Maybe<Array<Maybe<ResolversTypes['Comment']>>>, ParentType, ContextType>, __isTypeOf?: isTypeOfResolverFn, }>; export type AuthorResolvers<ContextType = any, ParentType extends ResolversParentTypes['Author'] = ResolversParentTypes['Author']> = ResolversObject<{ username?: Resolver<ResolversTypes['String'], ParentType, ContextType>, email?: Resolver<ResolversTypes['String'], ParentType, ContextType>, dob?: Resolver<Maybe<ResolversTypes['DateTime']>, ParentType, ContextType>, questions?: Resolver<Maybe<Array<Maybe<ResolversTypes['Question']>>>, ParentType, ContextType>, answers?: Resolver<Maybe<Array<Maybe<ResolversTypes['Answer']>>>, ParentType, ContextType>, __isTypeOf?: isTypeOfResolverFn, }>; export type CommentResolvers<ContextType = any, ParentType extends ResolversParentTypes['Comment'] = ResolversParentTypes['Comment']> = ResolversObject<{ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, datePublished?: Resolver<Maybe<ResolversTypes['DateTime']>, ParentType, ContextType>, likes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, author?: Resolver<ResolversTypes['Author'], ParentType, ContextType>, commentsOn?: Resolver<ResolversTypes['Post'], ParentType, ContextType>, comments?: Resolver<Maybe<Array<Maybe<ResolversTypes['Comment']>>>, ParentType, ContextType>, __isTypeOf?: isTypeOfResolverFn, }>; export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['DateTime'], any> { name: 'DateTime' } export type MutationResolvers<ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = ResolversObject<{ addQuestion?: Resolver<Maybe<ResolversTypes['Question']>, ParentType, ContextType, RequireFields<MutationAddQuestionArgs, 'input'>>, addAnswer?: Resolver<Maybe<ResolversTypes['Answer']>, ParentType, ContextType, RequireFields<MutationAddAnswerArgs, 'input'>>, addComment?: Resolver<Maybe<ResolversTypes['Comment']>, ParentType, ContextType, RequireFields<MutationAddCommentArgs, 'input'>>, editPostText?: Resolver<Maybe<ResolversTypes['Post']>, ParentType, ContextType, RequireFields<MutationEditPostTextArgs, 'id' | 'newText'>>, likePost?: Resolver<Maybe<ResolversTypes['Post']>, ParentType, ContextType, RequireFields<MutationLikePostArgs, 'id' | 'likes'>>, }>; export type PostResolvers<ContextType = any, ParentType extends ResolversParentTypes['Post'] = ResolversParentTypes['Post']> = ResolversObject<{ __resolveType: TypeResolveFn<'Question' | 'Answer' | 'Comment', ParentType, ContextType>, id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, datePublished?: Resolver<Maybe<ResolversTypes['DateTime']>, ParentType, ContextType>, likes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, author?: Resolver<ResolversTypes['Author'], ParentType, ContextType>, }>; export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = ResolversObject<{ getQuestion?: Resolver<Maybe<ResolversTypes['Question']>, ParentType, ContextType, RequireFields<QueryGetQuestionArgs, 'id'>>, getAnswer?: Resolver<Maybe<ResolversTypes['Answer']>, ParentType, ContextType, RequireFields<QueryGetAnswerArgs, 'id'>>, getComment?: Resolver<Maybe<ResolversTypes['Comment']>, ParentType, ContextType, RequireFields<QueryGetCommentArgs, 'id'>>, queryQuestion?: Resolver<Maybe<Array<Maybe<ResolversTypes['Question']>>>, ParentType, ContextType, QueryQueryQuestionArgs>, myTopQuestions?: Resolver<Maybe<Array<Maybe<ResolversTypes['Question']>>>, ParentType, ContextType>, }>; export type QuestionResolvers<ContextType = any, ParentType extends ResolversParentTypes['Question'] = ResolversParentTypes['Question']> = ResolversObject<{ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, datePublished?: Resolver<Maybe<ResolversTypes['DateTime']>, ParentType, ContextType>, likes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, author?: Resolver<ResolversTypes['Author'], ParentType, ContextType>, title?: Resolver<ResolversTypes['String'], ParentType, ContextType>, tags?: Resolver<Maybe<Array<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>, answers?: Resolver<Maybe<Array<Maybe<ResolversTypes['Answer']>>>, ParentType, ContextType>, comments?: Resolver<Maybe<Array<Maybe<ResolversTypes['Comment']>>>, ParentType, ContextType>, __isTypeOf?: isTypeOfResolverFn, }>; export type Resolvers<ContextType = any> = ResolversObject<{ Answer?: AnswerResolvers<ContextType>, Author?: AuthorResolvers<ContextType>, Comment?: CommentResolvers<ContextType>, DateTime?: GraphQLScalarType, Mutation?: MutationResolvers<ContextType>, Post?: PostResolvers, Query?: QueryResolvers<ContextType>, Question?: QuestionResolvers<ContextType>, }>; /** * @deprecated * Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config. */ export type IResolvers<ContextType = any> = Resolvers<ContextType>;
the_stack
import { createElement } from "@syncfusion/ej2-base"; import { ProgressButton } from "../src/progress-button/progress-button"; import { profile , inMB, getMemoryProfile } from './common.spec'; describe('Progress Button', () => { beforeAll(() => { const isDef: any = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log('Unsupported environment, window.performance.memory is unavailable'); this.skip(); // skips test (in Chai) return; } }); beforeEach(() => { jasmine.clock().install(); }); afterEach(() => { jasmine.clock().uninstall(); }); it('Progress and Spinner', () => { const ele: any = createElement('button', { id: 'progressbtn1' }); document.body.appendChild(ele); new ProgressButton({ content: 'Progress', iconCss: 'e-icons e-add-icon', enableProgress: true }, '#progressbtn1'); expect(ele.childNodes[1].classList).toContain('e-btn-content'); expect(ele.childNodes[0].classList).toContain('e-spinner'); expect(ele.childNodes[2].classList).toContain('e-progress'); expect(ele.childNodes[1].textContent).toEqual('Progress'); expect(ele.getElementsByClassName('e-btn-content')[0].childNodes[0].classList).toContain('e-btn-icon'); }); it('Hide Progress', () => { const ele: any = createElement('button', { id: 'progressbtn2' }); document.body.appendChild(ele); new ProgressButton({ content: 'Progress' }, '#progressbtn2'); expect(ele.getElementsByClassName('e-progress').length).toBe(0); }); it('Hide Spinner', () => { const ele: any = createElement('button', { id: 'progressbtn3' }); document.body.appendChild(ele); new ProgressButton({ content: 'Progress', cssClass: 'e-hide-spinner' }, '#progressbtn3'); expect(ele.classList).toContain('e-hide-spinner'); }); it('Spinner Only', () => { const ele: any = createElement('button', { id: 'progressbtn4' }); document.body.appendChild(ele); new ProgressButton({ content: 'Spinner', duration: 1000 }, '#progressbtn4'); ele.click(); expect(ele.classList).toContain('e-progress-active'); jasmine.clock().tick(50000); setTimeout(() => { expect(ele.getElementsByClassName('e-spinner-pane')[0].classList).toContain('e-spin-hide'); expect(ele.classList).not.toContain('e-progress-active'); }, 20000); jasmine.clock().tick(20000); }); it('Progress Only', () => { const ele: any = createElement('button', { id: 'progressbtn5' }); document.body.appendChild(ele); new ProgressButton({ content: 'Progress', duration: 1000, enableProgress: true, cssClass: 'e-hide-spinner', begin: begin, progress: progress, end: end }, '#progressbtn5'); ele.click(); expect(ele.classList).toContain('e-progress-active'); jasmine.clock().tick(20000); function begin(args: any) { expect(args.percent).toBe(0); expect(args.currentDuration).toBe(0); } function progress(args: any) { expect(args.percent).toBeGreaterThan(0); expect(args.currentDuration).toBeGreaterThan(0); expect(args.percent).toBeLessThan(100); expect(args.currentDuration).toBeLessThan(1000); } function end(args: any) { expect(args.percent).toBe(100); expect(args.currentDuration).toBe(1000); } }); it('Progress methods', () => { const ele: any = createElement('button', { id: 'progressbtn6' }); document.body.appendChild(ele); const button: ProgressButton = new ProgressButton({ content: 'Progress', enableProgress: true, duration: 1000, cssClass: 'e-hide-spinner', progress: progress, end: end }, '#progressbtn6'); ele.click(); jasmine.clock().tick(20000); button.start(); function progress(args: any) { if (args.percent === 50) { this.stop(); } } function end(args: any) { expect(args.percent).toBe(100); } }); it('Progress Step', () => { const ele: any = createElement('button', { id: 'progressbtn7' }); document.body.appendChild(ele); new ProgressButton({ content: 'Progress', duration: 1000, enableProgress: true, cssClass: 'e-hide-spinner', begin: begin, progress: progress, end: end }, '#progressbtn7'); ele.click(); jasmine.clock().tick(10000); function begin(args: any) { args.step = 25; } function progress(args: any) { if (args.currentDuration >= 250 && args.currentDuration < 500) { expect(args.percent).toBe(25); } else if (args.currentDuration > 500 && args.currentDuration < 750) { expect(args.percent).toBe(50); } else if (args.currentDuration > 750 && args.currentDuration < 1000) { expect(args.percent).toBe(75); } } function end(args: any) { expect(args.percent).toBe(100); expect(args.currentDuration).toBe(1000); } }); it('Progress percent', () => { const ele: any = createElement('button', { id: 'progressbtn8' }); document.body.appendChild(ele); ele.textContent = 'Progress'; new ProgressButton({ duration: 1000, enableProgress: true, begin: begin, end: end }, '#progressbtn8'); ele.click(); jasmine.clock().tick(10000); function begin(args: any) { args.percent = 98; } function end(args: any) { expect(args.percent).toBe(100); expect(args.currentDuration).toBeLessThan(1000); } }); it('Progress stop', () => { const ele: any = createElement('button', { id: 'progressbtn9' }); document.body.appendChild(ele); const button: any = new ProgressButton({ content: 'Progress', enableProgress: true, duration: 1000 }, '#progressbtn9'); button.start(10); jasmine.clock().tick(2000); button.stop(); expect(button.percent).toBeGreaterThan(0); expect(button.progressTime).toBeGreaterThan(0); button.start(30); jasmine.clock().tick(2000); expect(button.percent).toBeGreaterThanOrEqual(30); expect(button.progressTime).toBeGreaterThan(0); }); it('content property change', () => { const ele: any = createElement('button', { id: 'progressbtn10' }); document.body.appendChild(ele); const button: ProgressButton = new ProgressButton({ content: 'Progress', enableProgress: true }, '#progressbtn10'); button.content = 'Progress2'; button.iconCss = 'e-icons e-add-icon'; button.dataBind(); expect(button.content).toBe('Progress2'); expect(ele.getElementsByClassName('e-btn-content')[0].textContent).toBe('Progress2'); expect(ele.getElementsByClassName('e-btn-content')[0].childNodes[0].classList).toContain('e-btn-icon'); button.iconPosition = 'Right'; button.dataBind(); expect(ele.getElementsByClassName('e-btn-content')[0].childNodes[1].classList).toContain('e-btn-icon'); button.iconPosition = 'Left'; button.dataBind(); expect(ele.getElementsByClassName('e-btn-content')[0].childNodes[0].classList).toContain('e-btn-icon'); button.enableProgress = false; button.dataBind(); expect(ele.getElementsByClassName('e-progress')[0]).toBe(undefined); button.content = 'Progress3'; button.dataBind(); expect(ele.getElementsByClassName('e-btn-content')[0].textContent).toBe('Progress3'); button.iconCss = 'e-icons e-add-icon1'; button.dataBind(); expect(ele.getElementsByClassName('e-btn-content')[0].childNodes[0].classList).toContain('e-add-icon1'); button.enableProgress = true; button.dataBind(); expect(ele.childNodes[2].classList).toContain('e-progress'); }); it('destroy method', () => { const ele: any = createElement('button', { id: 'progressbtn11' }); document.body.appendChild(ele); let button: any = new ProgressButton({ content: 'Progress', enableProgress: true }, '#progressbtn11'); button.destroy(); expect(ele.innerHTML).toBe(''); button = new ProgressButton({ enableProgress: true }, '#progressbtn11'); button.destroy(); expect(ele.innerHTML).toBe(''); button = new ProgressButton({ cssClass: 'e-hide-spinner', enableProgress: true }, '#progressbtn11'); button.destroy(); expect(ele.innerHTML).toBe(''); }); it('Spin Position', () => { const ele: any = createElement('button', { id: 'progressbtn13' }); document.body.appendChild(ele); let button: any = new ProgressButton({ content: 'Spin Right', spinSettings: { position: 'Right' } }, '#progressbtn13'); expect(ele.childNodes[1].classList).toContain('e-spinner'); button.destroy(); button = new ProgressButton({ content: 'Spin Top', spinSettings: { position: 'Top' } }, '#progressbtn13'); expect(ele.childNodes[0].classList).toContain('e-spinner'); button.destroy(); button = new ProgressButton({ content: 'Spin bottom', spinSettings: { position: 'Bottom' } }, '#progressbtn13'); expect(ele.childNodes[1].classList).toContain('e-spinner'); }); it('Animation settings - SlideLeft', () => { const ele: any = createElement('button', { id: 'progressbtn14' }); document.body.appendChild(ele); new ProgressButton({ content: 'Slide Left', duration: 1000, spinSettings: { position: 'Center' }, animationSettings: { effect: 'SlideLeft', duration: 400 } }, '#progressbtn14'); ele.click(); setTimeout(() => { expect(ele.getElementsByClassName('e-btn-content')[0].classList).not.toContain('e-cont-animate'); }, 2000); jasmine.clock().tick(20000); }); it('Animation settings - Center', () => { const ele: any = createElement('button', { id: 'progressbtn15' }); document.body.appendChild(ele); new ProgressButton({ content: 'Spin Center', duration: 1000, spinSettings: { position: 'Center' } }, '#progressbtn15'); ele.click(); expect(ele.getElementsByClassName('e-btn-content')[0].classList).toContain('e-cont-animate'); jasmine.clock().tick(50000); setTimeout(() => { expect(ele.getElementsByClassName('e-btn-content')[0].classList).not.toContain('e-cont-animate'); }, 20000); jasmine.clock().tick(20000); }); it('Spin Settings property change', () => { const ele: any = createElement('button', { id: 'progressbtn12' }); document.body.appendChild(ele); const button: ProgressButton = new ProgressButton({ content: 'Spin Left' }, '#progressbtn12'); button.spinSettings.position = 'Right'; button.dataBind(); expect(ele.childNodes[1].classList).toContain('e-spinner'); expect(ele.classList).toContain('e-spin-right'); expect(ele.classList).not.toContain('e-spin-left'); button.spinSettings.width = 30; button.dataBind(); // expect(ele.getElementsByClassName('e-spin-material')[0].style.width).toBe('30px'); }); it('Spinner Events', () => { const ele: any = createElement('button', { id: 'progressbtn16' }); document.body.appendChild(ele); new ProgressButton({ content: 'Spinner', duration: 1000, begin: begin, progress: progress, end: end }, '#progressbtn16'); ele.click(); function begin(args: any) { expect(args.percent).toBe(0); expect(args.currentDuration).toBe(0); } function progress(args: any) { expect(args.percent).toBeGreaterThan(0); expect(args.currentDuration).toBeGreaterThan(0); expect(args.percent).toBeLessThan(100); expect(args.currentDuration).toBeLessThan(1000); } function end(args: any) { expect(args.percent).toBe(100); expect(args.currentDuration).toBe(1000); } }); it('Enable Html Sanitizer', () => { new ProgressButton({ content: 'Progress<style>body{background:rgb(0, 0, 255)}</style>', enableHtmlSanitizer: true }, '#progressbtn17'); const htmlele: Element = document.body; expect(window.getComputedStyle(htmlele).backgroundColor).not.toBe('rgb(0, 0, 255)'); }); it('Enable Html Sanitizer disabled', () => { const ele: any = createElement('button', { id: 'progressbtn17' }); document.body.appendChild(ele); const button: ProgressButton = new ProgressButton({ content: 'Progress<style>body{background:rgb(0, 0, 255)}</style>' }, '#progressbtn17'); const htmlele: Element = document.body; expect(window.getComputedStyle(htmlele).backgroundColor).toBe('rgb(0, 0, 255)'); button.destroy(); }); it('Progress Complete', () => { const ele: any = createElement('button', { id: 'progressbtn18' }); document.body.appendChild(ele); const button: any = new ProgressButton({ content: 'ProgressComplete', enableProgress: true, duration: 1000 }, '#progressbtn9'); button.start(50); button.stop(); expect(button.percent).toBeGreaterThan(40); button.progressComplete(); expect(button.percent).toEqual(0); }); it('memory leak', () => { profile.sample(); const average: any = inMB(profile.averageChange); // check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); const memory: any = inMB(getMemoryProfile()); // check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { Signer } from "@ethersproject/abstract-signer"; import { ContractTransaction, ContractFactory, Overrides } from "@ethersproject/contracts"; import { Wallet } from "@ethersproject/wallet"; import { Decimal } from "@liquity/lib-base"; import { _LiquityContractAddresses, _LiquityContracts, _LiquityDeploymentJSON, _connectToContracts } from "../src/contracts"; import { createUniswapV2Pair } from "./UniswapV2Factory"; let silent = true; export const log = (...args: unknown[]): void => { if (!silent) { console.log(...args); } }; export const setSilent = (s: boolean): void => { silent = s; }; const deployContractAndGetBlockNumber = async ( deployer: Signer, getContractFactory: (name: string, signer: Signer) => Promise<ContractFactory>, contractName: string, ...args: unknown[] ): Promise<[address: string, blockNumber: number]> => { log(`Deploying ${contractName} ...`); const contract = await (await getContractFactory(contractName, deployer)).deploy(...args); log(`Waiting for transaction ${contract.deployTransaction.hash} ...`); const receipt = await contract.deployTransaction.wait(); log({ contractAddress: contract.address, blockNumber: receipt.blockNumber, gasUsed: receipt.gasUsed.toNumber() }); log(); return [contract.address, receipt.blockNumber]; }; const deployContract: ( ...p: Parameters<typeof deployContractAndGetBlockNumber> ) => Promise<string> = (...p) => deployContractAndGetBlockNumber(...p).then(([a]) => a); const deployContracts = async ( deployer: Signer, getContractFactory: (name: string, signer: Signer) => Promise<ContractFactory>, priceFeedIsTestnet = true, overrides?: Overrides ): Promise<[addresses: Omit<_LiquityContractAddresses, "uniToken">, startBlock: number]> => { const [activePoolAddress, startBlock] = await deployContractAndGetBlockNumber( deployer, getContractFactory, "ActivePool", { ...overrides } ); const addresses = { activePool: activePoolAddress, borrowerOperations: await deployContract(deployer, getContractFactory, "BorrowerOperations", { ...overrides }), troveManager: await deployContract(deployer, getContractFactory, "TroveManager", { ...overrides }), collSurplusPool: await deployContract(deployer, getContractFactory, "CollSurplusPool", { ...overrides }), communityIssuance: await deployContract(deployer, getContractFactory, "CommunityIssuance", { ...overrides }), defaultPool: await deployContract(deployer, getContractFactory, "DefaultPool", { ...overrides }), hintHelpers: await deployContract(deployer, getContractFactory, "HintHelpers", { ...overrides }), lockupContractFactory: await deployContract( deployer, getContractFactory, "LockupContractFactory", { ...overrides } ), lqtyStaking: await deployContract(deployer, getContractFactory, "LQTYStaking", { ...overrides }), priceFeed: await deployContract( deployer, getContractFactory, priceFeedIsTestnet ? "PriceFeedTestnet" : "PriceFeed", { ...overrides } ), sortedTroves: await deployContract(deployer, getContractFactory, "SortedTroves", { ...overrides }), stabilityPool: await deployContract(deployer, getContractFactory, "StabilityPool", { ...overrides }), gasPool: await deployContract(deployer, getContractFactory, "GasPool", { ...overrides }), unipool: await deployContract(deployer, getContractFactory, "Unipool", { ...overrides }) }; return [ { ...addresses, lusdToken: await deployContract( deployer, getContractFactory, "LUSDToken", addresses.troveManager, addresses.stabilityPool, addresses.borrowerOperations, { ...overrides } ), lqtyToken: await deployContract( deployer, getContractFactory, "LQTYToken", addresses.communityIssuance, addresses.lqtyStaking, addresses.lockupContractFactory, Wallet.createRandom().address, // _bountyAddress (TODO: parameterize this) addresses.unipool, // _lpRewardsAddress Wallet.createRandom().address, // _multisigAddress (TODO: parameterize this) { ...overrides } ), multiTroveGetter: await deployContract( deployer, getContractFactory, "MultiTroveGetter", addresses.troveManager, addresses.sortedTroves, { ...overrides } ) }, startBlock ]; }; export const deployTellorCaller = ( deployer: Signer, getContractFactory: (name: string, signer: Signer) => Promise<ContractFactory>, tellorAddress: string, overrides?: Overrides ): Promise<string> => deployContract(deployer, getContractFactory, "TellorCaller", tellorAddress, { ...overrides }); const connectContracts = async ( { activePool, borrowerOperations, troveManager, lusdToken, collSurplusPool, communityIssuance, defaultPool, lqtyToken, hintHelpers, lockupContractFactory, lqtyStaking, priceFeed, sortedTroves, stabilityPool, gasPool, unipool, uniToken }: _LiquityContracts, deployer: Signer, overrides?: Overrides ) => { if (!deployer.provider) { throw new Error("Signer must have a provider."); } const txCount = await deployer.provider.getTransactionCount(deployer.getAddress()); const connections: ((nonce: number) => Promise<ContractTransaction>)[] = [ nonce => sortedTroves.setParams(1e6, troveManager.address, borrowerOperations.address, { ...overrides, nonce }), nonce => troveManager.setAddresses( borrowerOperations.address, activePool.address, defaultPool.address, stabilityPool.address, gasPool.address, collSurplusPool.address, priceFeed.address, lusdToken.address, sortedTroves.address, lqtyToken.address, lqtyStaking.address, { ...overrides, nonce } ), nonce => borrowerOperations.setAddresses( troveManager.address, activePool.address, defaultPool.address, stabilityPool.address, gasPool.address, collSurplusPool.address, priceFeed.address, sortedTroves.address, lusdToken.address, lqtyStaking.address, { ...overrides, nonce } ), nonce => stabilityPool.setAddresses( borrowerOperations.address, troveManager.address, activePool.address, lusdToken.address, sortedTroves.address, priceFeed.address, communityIssuance.address, { ...overrides, nonce } ), nonce => activePool.setAddresses( borrowerOperations.address, troveManager.address, stabilityPool.address, defaultPool.address, { ...overrides, nonce } ), nonce => defaultPool.setAddresses(troveManager.address, activePool.address, { ...overrides, nonce }), nonce => collSurplusPool.setAddresses( borrowerOperations.address, troveManager.address, activePool.address, { ...overrides, nonce } ), nonce => hintHelpers.setAddresses(sortedTroves.address, troveManager.address, { ...overrides, nonce }), nonce => lqtyStaking.setAddresses( lqtyToken.address, lusdToken.address, troveManager.address, borrowerOperations.address, activePool.address, { ...overrides, nonce } ), nonce => lockupContractFactory.setLQTYTokenAddress(lqtyToken.address, { ...overrides, nonce }), nonce => communityIssuance.setAddresses(lqtyToken.address, stabilityPool.address, { ...overrides, nonce }), nonce => unipool.setParams(lqtyToken.address, uniToken.address, 2 * 30 * 24 * 60 * 60, { ...overrides, nonce }) ]; const txs = await Promise.all(connections.map((connect, i) => connect(txCount + i))); let i = 0; await Promise.all(txs.map(tx => tx.wait().then(() => log(`Connected ${++i}`)))); }; const deployMockUniToken = ( deployer: Signer, getContractFactory: (name: string, signer: Signer) => Promise<ContractFactory>, overrides?: Overrides ) => deployContract( deployer, getContractFactory, "ERC20Mock", "Mock Uniswap V2", "UNI-V2", Wallet.createRandom().address, // initialAccount 0, // initialBalance { ...overrides } ); export const deployAndSetupContracts = async ( deployer: Signer, getContractFactory: (name: string, signer: Signer) => Promise<ContractFactory>, _priceFeedIsTestnet = true, _isDev = true, wethAddress?: string, overrides?: Overrides ): Promise<_LiquityDeploymentJSON> => { if (!deployer.provider) { throw new Error("Signer must have a provider."); } log("Deploying contracts..."); log(); const deployment: _LiquityDeploymentJSON = { chainId: await deployer.getChainId(), version: "unknown", deploymentDate: new Date().getTime(), bootstrapPeriod: 0, totalStabilityPoolLQTYReward: "0", liquidityMiningLQTYRewardRate: "0", _priceFeedIsTestnet, _uniTokenIsMock: !wethAddress, _isDev, ...(await deployContracts(deployer, getContractFactory, _priceFeedIsTestnet, overrides).then( async ([addresses, startBlock]) => ({ startBlock, addresses: { ...addresses, uniToken: await (wethAddress ? createUniswapV2Pair(deployer, wethAddress, addresses.lusdToken, overrides) : deployMockUniToken(deployer, getContractFactory, overrides)) } }) )) }; const contracts = _connectToContracts(deployer, deployment); log("Connecting contracts..."); await connectContracts(contracts, deployer, overrides); const lqtyTokenDeploymentTime = await contracts.lqtyToken.getDeploymentStartTime(); const bootstrapPeriod = await contracts.troveManager.BOOTSTRAP_PERIOD(); const totalStabilityPoolLQTYReward = await contracts.communityIssuance.LQTYSupplyCap(); const liquidityMiningLQTYRewardRate = await contracts.unipool.rewardRate(); return { ...deployment, deploymentDate: lqtyTokenDeploymentTime.toNumber() * 1000, bootstrapPeriod: bootstrapPeriod.toNumber(), totalStabilityPoolLQTYReward: `${Decimal.fromBigNumberString( totalStabilityPoolLQTYReward.toHexString() )}`, liquidityMiningLQTYRewardRate: `${Decimal.fromBigNumberString( liquidityMiningLQTYRewardRate.toHexString() )}` }; };
the_stack
import { extractPartitionKey, PartitionKeyDefinition } from "@azure/cosmos"; import * as ko from "knockout"; import Q from "q"; import * as Constants from "../../Common/Constants"; import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils"; import * as Logger from "../../Common/Logger"; import { createDocument, deleteDocument, queryDocuments, readDocument, updateDocument, } from "../../Common/MongoProxyClient"; import MongoUtility from "../../Common/MongoUtility"; import * as DataModels from "../../Contracts/DataModels"; import * as ViewModels from "../../Contracts/ViewModels"; import { Action } from "../../Shared/Telemetry/TelemetryConstants"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import { useDialog } from "../Controls/Dialog"; import DocumentId from "../Tree/DocumentId"; import ObjectId from "../Tree/ObjectId"; import DocumentsTab from "./DocumentsTab"; export default class MongoDocumentsTab extends DocumentsTab { public collection: ViewModels.Collection; private continuationToken: string; constructor(options: ViewModels.DocumentsTabOptions) { super(options); this.lastFilterContents = ko.observableArray<string>(['{"id":"foo"}', "{ qty: { $gte: 20 } }"]); if (this.partitionKeyProperty && ~this.partitionKeyProperty.indexOf(`"`)) { this.partitionKeyProperty = this.partitionKeyProperty.replace(/["]+/g, ""); } if (this.partitionKeyProperty && this.partitionKeyProperty.indexOf("$v") > -1) { // From $v.shard.$v.key.$v > shard.key this.partitionKeyProperty = this.partitionKeyProperty.replace(/.\$v/g, "").replace(/\$v./g, ""); this.partitionKeyPropertyHeader = "/" + this.partitionKeyProperty; } this.isFilterExpanded = ko.observable<boolean>(true); super.buildCommandBarOptions.bind(this); super.buildCommandBarOptions(); } public onSaveNewDocumentClick = (): Promise<any> => { const documentContent = JSON.parse(this.selectedDocumentContent()); this.displayedError(""); const startKey: number = TelemetryProcessor.traceStart(Action.CreateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), }); if ( this.partitionKeyProperty && this.partitionKeyProperty !== "_id" && !this._hasShardKeySpecified(documentContent) ) { const message = `The document is lacking the shard property: ${this.partitionKeyProperty}`; this.displayedError(message); let that = this; setTimeout(() => { that.displayedError(""); }, Constants.ClientDefaults.errorNotificationTimeoutMs); this.isExecutionError(true); TelemetryProcessor.traceFailure( Action.CreateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), error: message, }, startKey ); Logger.logError("Failed to save new document: Document shard key not defined", "MongoDocumentsTab"); throw new Error("Document without shard key"); } this.isExecutionError(false); this.isExecuting(true); return createDocument(this.collection.databaseId, this.collection, this.partitionKeyProperty, documentContent) .then( (savedDocument: any) => { let partitionKeyArray = extractPartitionKey( savedDocument, this._getPartitionKeyDefinition() as PartitionKeyDefinition ); let partitionKeyValue = partitionKeyArray && partitionKeyArray[0]; let id = new ObjectId(this, savedDocument, partitionKeyValue); let ids = this.documentIds(); ids.push(id); delete savedDocument._self; let value: string = this.renderObjectForEditor(savedDocument || {}, null, 4); this.selectedDocumentContent.setBaseline(value); this.selectedDocumentId(id); this.documentIds(ids); this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits); TelemetryProcessor.traceSuccess( Action.CreateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), }, startKey ); }, (error) => { this.isExecutionError(true); const errorMessage = getErrorMessage(error); useDialog.getState().showOkModalDialog("Create document failed", errorMessage); TelemetryProcessor.traceFailure( Action.CreateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), error: errorMessage, errorStack: getErrorStack(error), }, startKey ); } ) .finally(() => this.isExecuting(false)); }; public onSaveExisitingDocumentClick = (): Promise<any> => { const selectedDocumentId = this.selectedDocumentId(); const documentContent = this.selectedDocumentContent(); this.isExecutionError(false); this.isExecuting(true); const startKey: number = TelemetryProcessor.traceStart(Action.UpdateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), }); return updateDocument(this.collection.databaseId, this.collection, selectedDocumentId, documentContent) .then( (updatedDocument: any) => { let value: string = this.renderObjectForEditor(updatedDocument || {}, null, 4); this.selectedDocumentContent.setBaseline(value); this.documentIds().forEach((documentId: DocumentId) => { if (documentId.rid === updatedDocument._rid) { const partitionKeyArray = extractPartitionKey( updatedDocument, this._getPartitionKeyDefinition() as PartitionKeyDefinition ); let partitionKeyValue = partitionKeyArray && partitionKeyArray[0]; const id = new ObjectId(this, updatedDocument, partitionKeyValue); documentId.id(id.id()); } }); this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits); TelemetryProcessor.traceSuccess( Action.UpdateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), }, startKey ); }, (error) => { this.isExecutionError(true); const errorMessage = getErrorMessage(error); useDialog.getState().showOkModalDialog("Update document failed", errorMessage); TelemetryProcessor.traceFailure( Action.UpdateDocument, { dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), error: errorMessage, errorStack: getErrorStack(error), }, startKey ); } ) .finally(() => this.isExecuting(false)); }; public buildQuery(filter: string): string { return filter || "{}"; } public async selectDocument(documentId: DocumentId): Promise<void> { this.selectedDocumentId(documentId); const content = await readDocument(this.collection.databaseId, this.collection, documentId); this.initDocumentEditor(documentId, content); } public loadNextPage(): Q.Promise<any> { this.isExecuting(true); this.isExecutionError(false); const filter: string = this.filterContent().trim(); const query: string = this.buildQuery(filter); return Q(queryDocuments(this.collection.databaseId, this.collection, true, query, this.continuationToken)) .then( ({ continuationToken, documents }) => { this.continuationToken = continuationToken; let currentDocuments = this.documentIds(); const currentDocumentsRids = currentDocuments.map((currentDocument) => currentDocument.rid); const nextDocumentIds = documents .filter((d: any) => { return currentDocumentsRids.indexOf(d._rid) < 0; }) .map((rawDocument: any) => { const partitionKeyValue = rawDocument._partitionKeyValue; return new DocumentId(this, rawDocument, partitionKeyValue); }); const merged = currentDocuments.concat(nextDocumentIds); this.documentIds(merged); currentDocuments = this.documentIds(); if (this.filterContent().length > 0 && currentDocuments.length > 0) { currentDocuments[0].click(); } else { this.selectedDocumentContent(""); this.selectedDocumentId(null); this.editorState(ViewModels.DocumentExplorerState.noDocumentSelected); } if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) { TelemetryProcessor.traceSuccess( Action.Tab, { databaseName: this.collection.databaseId, collectionName: this.collection.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), }, this.onLoadStartKey ); this.onLoadStartKey = null; } }, (error: any) => { if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) { TelemetryProcessor.traceFailure( Action.Tab, { databaseName: this.collection.databaseId, collectionName: this.collection.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: this.tabTitle(), error: getErrorMessage(error), errorStack: getErrorStack(error), }, this.onLoadStartKey ); this.onLoadStartKey = null; } } ) .finally(() => this.isExecuting(false)); } protected _onEditorContentChange(newContent: string) { try { if ( this.editorState() === ViewModels.DocumentExplorerState.newDocumentValid || this.editorState() === ViewModels.DocumentExplorerState.newDocumentInvalid ) { let parsed: any = JSON.parse(newContent); } // Mongo uses BSON format for _id, trying to parse it as JSON blocks normal flow in an edit this.onValidDocumentEdit(); } catch (e) { this.onInvalidDocumentEdit(); } } /** Renders a Javascript object to be displayed inside Monaco Editor */ public renderObjectForEditor(value: any, replacer: any, space: string | number): string { return MongoUtility.tojson(value, null, false); } private _hasShardKeySpecified(document: any): boolean { return Boolean(extractPartitionKey(document, this._getPartitionKeyDefinition() as PartitionKeyDefinition)); } private _getPartitionKeyDefinition(): DataModels.PartitionKey { let partitionKey: DataModels.PartitionKey = this.partitionKey; if ( this.partitionKey && this.partitionKey.paths && this.partitionKey.paths.length && this.partitionKey.paths.length > 0 && this.partitionKey.paths[0].indexOf("$v") > -1 ) { // Convert BsonSchema2 to /path format partitionKey = { kind: partitionKey.kind, paths: ["/" + this.partitionKeyProperty.replace(/\./g, "/")], version: partitionKey.version, }; } return partitionKey; } protected __deleteDocument(documentId: DocumentId): Promise<void> { return deleteDocument(this.collection.databaseId, this.collection, documentId); } }
the_stack
import { testTokenization } from '../test/testRunner'; testTokenization('css', [ // Skip whitespace [ { line: ' body', tokens: [ { startIndex: 0, type: '' }, { startIndex: 6, type: 'tag.css' } ] } ], // CSS rule // body { // margin: 0; // padding: 3em 6em; // font-family: tahoma, arial, sans-serif; // text-decoration: none !important; // color: #000 // } [ { line: 'body {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 4, type: '' }, { startIndex: 5, type: 'delimiter.bracket.css' } ] }, { line: ' margin: 0;', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 9, type: '' }, { startIndex: 10, type: 'attribute.value.number.css' }, { startIndex: 11, type: 'delimiter.css' } ] }, { line: ' padding: 3em 6em;', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'attribute.value.number.css' }, { startIndex: 12, type: 'attribute.value.unit.css' }, { startIndex: 14, type: '' }, { startIndex: 15, type: 'attribute.value.number.css' }, { startIndex: 16, type: 'attribute.value.unit.css' }, { startIndex: 18, type: 'delimiter.css' } ] }, { line: ' font-family: tahoma, arial, sans-serif;', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 14, type: '' }, { startIndex: 15, type: 'attribute.value.css' }, { startIndex: 21, type: 'delimiter.css' }, { startIndex: 22, type: '' }, { startIndex: 23, type: 'attribute.value.css' }, { startIndex: 28, type: 'delimiter.css' }, { startIndex: 29, type: '' }, { startIndex: 30, type: 'attribute.value.css' }, { startIndex: 40, type: 'delimiter.css' } ] }, { line: ' text-decoration: none !important;', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 18, type: '' }, { startIndex: 19, type: 'attribute.value.css' }, { startIndex: 23, type: '' }, { startIndex: 24, type: 'keyword.css' }, { startIndex: 34, type: 'delimiter.css' } ] }, { line: ' color: #000', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'attribute.value.hex.css' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'delimiter.bracket.css' } ] } ], // CSS units and numbers [ { line: '* { padding: 3em -9pt -0.5px; }', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'delimiter.bracket.css' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'attribute.name.css' }, { startIndex: 12, type: '' }, { startIndex: 13, type: 'attribute.value.number.css' }, { startIndex: 14, type: 'attribute.value.unit.css' }, { startIndex: 16, type: '' }, { startIndex: 17, type: 'attribute.value.number.css' }, { startIndex: 19, type: 'attribute.value.unit.css' }, { startIndex: 21, type: '' }, { startIndex: 22, type: 'attribute.value.number.css' }, { startIndex: 26, type: 'attribute.value.unit.css' }, { startIndex: 28, type: 'delimiter.css' }, { startIndex: 29, type: '' }, { startIndex: 30, type: 'delimiter.bracket.css' } ] } ], // CSS unfinished unit and numbers [ { line: '* { padding: -', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'delimiter.bracket.css' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'attribute.name.css' }, { startIndex: 12, type: '' }, { startIndex: 13, type: 'delimiter.css' } ] } ], // CSS single line comment // h1 /*comment*/ p { [ { line: 'h1 /*comment*/ p {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 2, type: '' }, { startIndex: 3, type: 'comment.css' }, { startIndex: 14, type: '' }, { startIndex: 15, type: 'tag.css' }, { startIndex: 16, type: '' }, { startIndex: 17, type: 'delimiter.bracket.css' } ] } ], // CSS multi line comment // h1 /*com // ment*/ p { [ { line: 'h1 /*com', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 2, type: '' }, { startIndex: 3, type: 'comment.css' } ] }, { line: 'ment*/ p', tokens: [ { startIndex: 0, type: 'comment.css' }, { startIndex: 6, type: '' }, { startIndex: 7, type: 'tag.css' } ] } ], // CSS ID rule [ { line: '#myID {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.bracket.css' } ] } ], // CSS Class rules [ { line: '.myID {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.bracket.css' } ] } ], // CSS @import etc [ { line: '@import url("something.css");', tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'attribute.value.css' }, { startIndex: 11, type: 'delimiter.parenthesis.css' }, { startIndex: 12, type: 'string.css' }, { startIndex: 27, type: 'delimiter.parenthesis.css' }, { startIndex: 28, type: 'delimiter.css' } ] } ], // CSS multi-line string with an escaped newline // body { // content: 'con\ // tent'; [ { line: 'body {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 4, type: '' }, { startIndex: 5, type: 'delimiter.bracket.css' } ] }, { line: ' content: "con\\', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'string.css' } ] }, { line: 'tent";', tokens: [ { startIndex: 0, type: 'string.css' }, { startIndex: 5, type: 'delimiter.css' } ] } ], // CSS empty string value // body { // content: ''; [ { line: 'body {', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 4, type: '' }, { startIndex: 5, type: 'delimiter.bracket.css' } ] }, { line: ' content: "";', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'string.css' }, { startIndex: 13, type: 'delimiter.css' } ] } ], // CSS font face // @font-face { // font-family: 'Opificio'; // } [ { line: '@font-face {', tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'delimiter.bracket.css' } ] }, { line: ' font-family: "Opificio";', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 14, type: '' }, { startIndex: 15, type: 'string.css' }, { startIndex: 25, type: 'delimiter.css' } ] } ], // CSS string with escaped quotes // 's\"tr' [ { line: '"s\\"tr" ', tokens: [ { startIndex: 0, type: 'string.css' }, { startIndex: 7, type: '' } ] } ], // CSS key frame animation syntax //@-webkit-keyframes infinite-spinning { // from { // -webkit-transform: rotate(0deg); // } // to { // -webkit-transform: rotate(360deg); // } //} [ { line: '@-webkit-keyframes infinite-spinning {', tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 18, type: '' }, { startIndex: 19, type: 'attribute.value.css' }, { startIndex: 36, type: '' }, { startIndex: 37, type: 'delimiter.bracket.css' } ] }, { line: ' from {', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.value.css' }, { startIndex: 6, type: '' }, { startIndex: 7, type: 'delimiter.bracket.css' } ] }, { line: ' -webkit-transform: rotate(0deg);', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 20, type: '' }, { startIndex: 21, type: 'attribute.value.css' }, { startIndex: 28, type: 'attribute.value.number.css' }, { startIndex: 29, type: 'attribute.value.unit.css' }, { startIndex: 32, type: 'attribute.value.css' }, { startIndex: 33, type: 'delimiter.css' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'delimiter.bracket.css' } ] }, { line: ' to {', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.value.css' }, { startIndex: 4, type: '' }, { startIndex: 5, type: 'delimiter.bracket.css' } ] }, { line: ' -webkit-transform: rotate(360deg);', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'attribute.name.css' }, { startIndex: 20, type: '' }, { startIndex: 21, type: 'attribute.value.css' }, { startIndex: 28, type: 'attribute.value.number.css' }, { startIndex: 31, type: 'attribute.value.unit.css' }, { startIndex: 34, type: 'attribute.value.css' }, { startIndex: 35, type: 'delimiter.css' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: '' }, { startIndex: 2, type: 'delimiter.bracket.css' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.bracket.css' }] } ], // CSS @import related coloring bug 9553 // @import url('something.css'); // .rule1{} // .rule2{} [ { line: '@import url("something.css");', tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'attribute.value.css' }, { startIndex: 11, type: 'delimiter.parenthesis.css' }, { startIndex: 12, type: 'string.css' }, { startIndex: 27, type: 'delimiter.parenthesis.css' }, { startIndex: 28, type: 'delimiter.css' } ] }, { line: '.rule1{}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 6, type: 'delimiter.bracket.css' } ] }, { line: '.rule2{}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 6, type: 'delimiter.bracket.css' } ] } ], // Triple quotes - bug #9870 [ { line: '"""', tokens: [{ startIndex: 0, type: 'string.css' }] } ], [ { line: '""""', tokens: [{ startIndex: 0, type: 'string.css' }] } ], [ { line: '"""""', tokens: [{ startIndex: 0, type: 'string.css' }] } ], // import statement - bug #10308 // @import url('something.css');@import url('something.css'); [ { line: '@import url("something.css");@import url("something.css");', tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'attribute.value.css' }, { startIndex: 11, type: 'delimiter.parenthesis.css' }, { startIndex: 12, type: 'string.css' }, { startIndex: 27, type: 'delimiter.parenthesis.css' }, { startIndex: 28, type: 'delimiter.css' }, { startIndex: 29, type: 'keyword.css' }, { startIndex: 36, type: '' }, { startIndex: 37, type: 'attribute.value.css' }, { startIndex: 40, type: 'delimiter.parenthesis.css' }, { startIndex: 41, type: 'string.css' }, { startIndex: 56, type: 'delimiter.parenthesis.css' }, { startIndex: 57, type: 'delimiter.css' } ] } ], // !important - bug #9578 // .a{background:#f5f9fc !important}.b{font-family:"Helvetica Neue", Helvetica;height:31px;} [ { line: '.a{background:#f5f9fc !important}.b{font-family:"Helvetica Neue", Helvetica;height:31px;}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 2, type: 'delimiter.bracket.css' }, { startIndex: 3, type: 'attribute.name.css' }, { startIndex: 14, type: 'attribute.value.hex.css' }, { startIndex: 21, type: '' }, { startIndex: 22, type: 'keyword.css' }, { startIndex: 32, type: 'delimiter.bracket.css' }, { startIndex: 33, type: 'tag.css' }, { startIndex: 35, type: 'delimiter.bracket.css' }, { startIndex: 36, type: 'attribute.name.css' }, { startIndex: 48, type: 'string.css' }, { startIndex: 64, type: 'delimiter.css' }, { startIndex: 65, type: '' }, { startIndex: 66, type: 'attribute.value.css' }, { startIndex: 75, type: 'delimiter.css' }, { startIndex: 76, type: 'attribute.name.css' }, { startIndex: 83, type: 'attribute.value.number.css' }, { startIndex: 85, type: 'attribute.value.unit.css' }, { startIndex: 87, type: 'delimiter.css' }, { startIndex: 88, type: 'delimiter.bracket.css' } ] } ], // base64-encoded data uris - bug #9580 //.even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7) repeat-x bottom} [ { line: '.even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7) repeat-x bottom}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.bracket.css' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'attribute.name.css' }, { startIndex: 19, type: '' }, { startIndex: 20, type: 'attribute.value.hex.css' }, { startIndex: 24, type: '' }, { startIndex: 25, type: 'attribute.value.css' }, { startIndex: 28, type: 'delimiter.parenthesis.css' }, { startIndex: 29, type: 'string.css' }, { startIndex: 215, type: 'delimiter.parenthesis.css' }, { startIndex: 216, type: '' }, { startIndex: 217, type: 'attribute.value.css' }, { startIndex: 225, type: '' }, { startIndex: 226, type: 'attribute.value.css' }, { startIndex: 232, type: 'delimiter.bracket.css' } ] } ], // /a colorization is incorrect in url - bug #9581 //.a{background:url(/a.jpg)} [ { line: '.a{background:url(/a.jpg)}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 2, type: 'delimiter.bracket.css' }, { startIndex: 3, type: 'attribute.name.css' }, { startIndex: 14, type: 'attribute.value.css' }, { startIndex: 17, type: 'delimiter.parenthesis.css' }, { startIndex: 18, type: 'string.css' }, { startIndex: 24, type: 'delimiter.parenthesis.css' }, { startIndex: 25, type: 'delimiter.bracket.css' } ] } ], // Bracket Matching [ { line: 'p{}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 1, type: 'delimiter.bracket.css' } ] } ], [ { line: 'p:nth() {}', tokens: [ { startIndex: 0, type: 'tag.css' }, { startIndex: 5, type: '' }, { startIndex: 8, type: 'delimiter.bracket.css' } ] } ], [ { line: "@import 'https://example.com/test.css';", tokens: [ { startIndex: 0, type: 'keyword.css' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'string.css' }, { startIndex: 38, type: 'delimiter.css' } ] } ] ]);
the_stack
namespace ts { function editFlat(position: number, deletedLength: number, newText: string, source: string) { return source.substring(0, position) + newText + source.substring(position + deletedLength, source.length); } function lineColToPosition(lineIndex: server.LineIndex, line: number, col: number) { const lineInfo = lineIndex.lineNumberToInfo(line); return (lineInfo.offset + col - 1); } function validateEdit(lineIndex: server.LineIndex, sourceText: string, position: number, deleteLength: number, insertString: string): void { const checkText = editFlat(position, deleteLength, insertString, sourceText); const snapshot = lineIndex.edit(position, deleteLength, insertString); const editedText = snapshot.getText(0, snapshot.getLength()); assert.equal(editedText, checkText); } describe(`VersionCache TS code`, () => { let validateEditAtLineCharIndex: (line: number, char: number, deleteLength: number, insertString: string) => void; before(() => { const testContent = `/// <reference path="z.ts" /> var x = 10; var y = { zebra: 12, giraffe: "ell" }; z.a; class Point { x: number; } k=y; var p:Point=new Point(); var q:Point=<Point>p;`; const { lines } = server.LineIndex.linesFromText(testContent); assert.isTrue(lines.length > 0, "Failed to initialize test text. Expected text to have at least one line"); const lineIndex = new server.LineIndex(); lineIndex.load(lines); validateEditAtLineCharIndex = (line: number, char: number, deleteLength: number, insertString: string) => { const position = lineColToPosition(lineIndex, line, char); validateEdit(lineIndex, testContent, position, deleteLength, insertString); }; }); after(() => { validateEditAtLineCharIndex = undefined; }); it(`change 9 1 0 1 {"y"}`, () => { validateEditAtLineCharIndex(9, 1, 0, "y"); }); it(`change 9 2 0 1 {"."}`, () => { validateEditAtLineCharIndex(9, 2, 0, "."); }); it(`change 9 3 0 1 {"\\n"}`, () => { validateEditAtLineCharIndex(9, 3, 0, "\n"); }); it(`change 10 1 0 10 {"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n"}`, () => { validateEditAtLineCharIndex(10, 1, 0, "\n\n\n\n\n\n\n\n\n\n"); }); it(`change 19 1 1 0`, () => { validateEditAtLineCharIndex(19, 1, 1, ""); }); it(`change 18 1 1 0`, () => { validateEditAtLineCharIndex(18, 1, 1, ""); }); }); describe(`VersionCache simple text`, () => { let validateEditAtPosition: (position: number, deleteLength: number, insertString: string) => void; let testContent: string; let lines: string[]; let lineMap: number[]; before(() => { testContent = `in this story: the lazy brown fox jumped over the cow that ate the grass that was purple at the tips and grew 1cm per day`; ({ lines, lineMap } = server.LineIndex.linesFromText(testContent)); assert.isTrue(lines.length > 0, "Failed to initialize test text. Expected text to have at least one line"); const lineIndex = new server.LineIndex(); lineIndex.load(lines); validateEditAtPosition = (position: number, deleteLength: number, insertString: string) => { validateEdit(lineIndex, testContent, position, deleteLength, insertString); }; }); after(() => { validateEditAtPosition = undefined; testContent = undefined; lines = undefined; lineMap = undefined; }); it(`Insert at end of file`, () => { validateEditAtPosition(testContent.length, 0, "hmmmm...\r\n"); }); it(`Unusual line endings merge`, () => { validateEditAtPosition(lines[0].length - 1, lines[1].length, ""); }); it(`Delete whole line and nothing but line (last line)`, () => { validateEditAtPosition(lineMap[lineMap.length - 2], lines[lines.length - 1].length, ""); }); it(`Delete whole line and nothing but line (first line)`, () => { validateEditAtPosition(0, lines[0].length, ""); }); it(`Delete whole line (first line) and insert with no line breaks`, () => { validateEditAtPosition(0, lines[0].length, "moo, moo, moo! "); }); it(`Delete whole line (first line) and insert with multiple line breaks`, () => { validateEditAtPosition(0, lines[0].length, "moo, \r\nmoo, \r\nmoo! "); }); it(`Delete multiple lines and nothing but lines (first and second lines)`, () => { validateEditAtPosition(0, lines[0].length + lines[1].length, ""); }); it(`Delete multiple lines and nothing but lines (second and third lines)`, () => { validateEditAtPosition(lines[0].length, lines[1].length + lines[2].length, ""); }); it(`Insert multiple line breaks`, () => { validateEditAtPosition(21, 1, "cr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr...\r\ncr"); }); it(`Insert multiple line breaks`, () => { validateEditAtPosition(21, 1, "cr...\r\ncr...\r\ncr"); }); it(`Insert multiple line breaks with leading \\n`, () => { validateEditAtPosition(21, 1, "\ncr...\r\ncr...\r\ncr"); }); it(`Single line no line breaks deleted or inserted, delete 1 char`, () => { validateEditAtPosition(21, 1, ""); }); it(`Single line no line breaks deleted or inserted, insert 1 char`, () => { validateEditAtPosition(21, 0, "b"); }); it(`Single line no line breaks deleted or inserted, delete 1, insert 2 chars`, () => { validateEditAtPosition(21, 1, "cr"); }); it(`Delete across line break (just the line break)`, () => { validateEditAtPosition(21, 22, ""); }); it(`Delete across line break`, () => { validateEditAtPosition(21, 32, ""); }); it(`Delete across multiple line breaks and insert no line breaks`, () => { validateEditAtPosition(21, 42, ""); }); it(`Delete across multiple line breaks and insert text`, () => { validateEditAtPosition(21, 42, "slithery "); }); }); describe(`VersionCache stress test`, () => { let rsa: number[] = []; let la: number[] = []; let las: number[] = []; let elas: number[] = []; let ersa: number[] = []; let ela: number[] = []; const iterationCount = 20; // const iterationCount = 20000; // uncomment for testing let lines: string[]; let lineMap: number[]; let lineIndex: server.LineIndex; let testContent: string; before(() => { // Use scanner.ts, decent size, does not change frequently const testFileName = "src/compiler/scanner.ts"; testContent = Harness.IO.readFile(testFileName); const totalChars = testContent.length; assert.isTrue(totalChars > 0, "Failed to read test file."); ({ lines, lineMap } = server.LineIndex.linesFromText(testContent)); assert.isTrue(lines.length > 0, "Failed to initialize test text. Expected text to have at least one line"); lineIndex = new server.LineIndex(); lineIndex.load(lines); let etotalChars = totalChars; for (let j = 0; j < 100000; j++) { rsa[j] = Math.floor(Math.random() * totalChars); la[j] = Math.floor(Math.random() * (totalChars - rsa[j])); if (la[j] > 4) { las[j] = 4; } else { las[j] = la[j]; } if (j < 4000) { ersa[j] = Math.floor(Math.random() * etotalChars); ela[j] = Math.floor(Math.random() * (etotalChars - ersa[j])); if (ela[j] > 4) { elas[j] = 4; } else { elas[j] = ela[j]; } etotalChars += (las[j] - elas[j]); } } }); after(() => { rsa = undefined; la = undefined; las = undefined; elas = undefined; ersa = undefined; ela = undefined; lines = undefined; lineMap = undefined; lineIndex = undefined; testContent = undefined; }); it("Range (average length 1/4 file size)", () => { for (let i = 0; i < iterationCount; i++) { const s2 = lineIndex.getText(rsa[i], la[i]); const s1 = testContent.substring(rsa[i], rsa[i] + la[i]); assert.equal(s1, s2); } }); it("Range (average length 4 chars)", () => { for (let j = 0; j < iterationCount; j++) { const s2 = lineIndex.getText(rsa[j], las[j]); const s1 = testContent.substring(rsa[j], rsa[j] + las[j]); assert.equal(s1, s2); } }); it("Edit (average length 4)", () => { for (let i = 0; i < iterationCount; i++) { const insertString = testContent.substring(rsa[100000 - i], rsa[100000 - i] + las[100000 - i]); const snapshot = lineIndex.edit(rsa[i], las[i], insertString); const checkText = editFlat(rsa[i], las[i], insertString, testContent); const snapText = snapshot.getText(0, checkText.length); assert.equal(checkText, snapText); } }); it("Edit ScriptVersionCache ", () => { const svc = server.ScriptVersionCache.fromString(<server.ServerHost>ts.sys, testContent); let checkText = testContent; for (let i = 0; i < iterationCount; i++) { const insertString = testContent.substring(rsa[i], rsa[i] + las[i]); svc.edit(ersa[i], elas[i], insertString); checkText = editFlat(ersa[i], elas[i], insertString, checkText); if (0 == (i % 4)) { const snap = svc.getSnapshot(); const snapText = snap.getText(0, checkText.length); assert.equal(checkText, snapText); } } }); it("Edit (average length 1/4th file size)", () => { for (let i = 0; i < iterationCount; i++) { const insertString = testContent.substring(rsa[100000 - i], rsa[100000 - i] + la[100000 - i]); const snapshot = lineIndex.edit(rsa[i], la[i], insertString); const checkText = editFlat(rsa[i], la[i], insertString, testContent); const snapText = snapshot.getText(0, checkText.length); assert.equal(checkText, snapText); } }); it("Line/offset from pos", () => { for (let i = 0; i < iterationCount; i++) { const lp = lineIndex.charOffsetToLineNumberAndPos(rsa[i]); const lac = ts.computeLineAndCharacterOfPosition(lineMap, rsa[i]); assert.equal(lac.line + 1, lp.line, "Line number mismatch " + (lac.line + 1) + " " + lp.line + " " + i); assert.equal(lac.character, (lp.offset), "Charachter offset mismatch " + lac.character + " " + lp.offset + " " + i); } }); it("Start pos from line", () => { for (let i = 0; i < iterationCount; i++) { for (let j = 0; j < lines.length; j++) { const lineInfo = lineIndex.lineNumberToInfo(j + 1); const lineIndexOffset = lineInfo.offset; const lineMapOffset = lineMap[j]; assert.equal(lineIndexOffset, lineMapOffset); } } }); }); }
the_stack
const AGENT_LIST = [ { // empty agent "name": "empty agent", "ua": "", "os": { "name": "unknown", "version": "-1", }, "browser": { "name": "unknown", "version": "-1", }, "isMobile": false, }, { // Unknown agent "name": "unknown agent", "ua": "Mozilla/5.0 (PLAYSTATION 3; 1.00)", "os": { "name": "unknown", "version": "-1", }, "browser": { "name": "unknown", "version": "-1", }, "isMobile": false, }, { // iPhone 3.0 "name": "iPhone 3.0", "ua": "Mozilla/5.0 (iPod; U; CPU iPhone OS 3_0 like Mac OS X;ko-kr)AppleWebKit/528.18(KHTML, like Gecko)Version/4.0 Mobile/7A341 Safari/528.16", "os": { "name": "ios", "version": "3.0", }, "browser": { "name": "safari", "version": "4.0", "webkit": true, "webkitVersion": "528.18", }, "isMobile": true, }, { // iPhone 4.3.3 "name": "iPhone 4.3.3", "ua": "Mozilla/5.0 (iPhone;U;CPU iPhone OS 4_3_3 like Max OS X;ko-kr) AppleWebKit/533.17.9(KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", "os": { "name": "ios", "version": "4.3.3", }, "browser": { "name": "safari", "version": "5.0.2", "webkit": true, "webkitVersion": "533.17.9", }, "isMobile": true, }, { // iPad 4.2.1 "name": "ipad 4.2.1", "ua": "Mozilla/5.0 (iPad;U;CPU OS 4_2_1 like Mac OS X;ko-kr) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5", "os": { "name": "ios", "version": "4.2.1", }, "browser": { "name": "safari", "version": "5.0.2", "webkit": true, "webkitVersion": "533.17.9", }, "isMobile": true, }, { // iPad 4.3.3 "name": "ipad 4.3.3", "ua": "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X;ko-kr)AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", "os": { "name": "ios", "version": "4.3.3", }, "browser": { "name": "safari", "version": "5.0.2", "webkit": true, "webkitVersion": "533.17.9", }, "isMobile": true, }, { // iPad 14.0 "name": "iPad 14.0 (Mobile, Firefox)", "ua": "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/28.0 Mobile/15E148 Safari/605.1.15", "os": { "name": "ios", "version": "14.0", }, "browser": { "name": "firefox", "version": "28.0", "webkit": true, "webkitVersion": "605.1.15", }, "isMobile": true, }, { // iPad 14.0 "name": "iPad 14.0 (Mobile, Edge)", "ua": "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 EdgiOS/45.7.3 Mobile/15E148 Safari/605.1.15", "os": { "name": "ios", "version": "14.0", }, "browser": { "name": "edge", "version": "45.7.3", "webkit": true, "webkitVersion": "605.1.15", }, "isMobile": true, }, { // iPad 14.0 "name": "iPad 14.0 (PC, Edge)", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/10.1 Safari/602.1 EdgiOS/45.7.3", "os": { "name": "mac", "version": "10.12.4", }, "browser": { "name": "edge", "version": "45.7.3", "webkit": true, "webkitVersion": "604.3.5", }, "isMobile": false, }, { // iPad 14.0 "name": "iPad 14.0 (Mobile, Whale)", "ua": "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Whale/1.7.0.2222 Mobile/15E148 Safari/605.1.15", "os": { "name": "ios", "version": "14.0", }, "browser": { "name": "whale", "version": "1.7.0.2222", "webkit": true, "webkitVersion": "605.1.15", }, "isMobile": true, }, { "name": "iPad 14.0 (Mobile, Whale bug)", "ua": "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Whale/1.7.0.2222 Mobile/15E148 Safari/605.1.15 NAVER(inapp; whale; 134; 5.8.0)", "os": { "name": "ios", "version": "14.0", }, "browser": { "name": "whale", "version": "1.7.0.2222", "webkit": true, "webview": false, "webkitVersion": "605.1.15", }, "isMobile": true, }, { // iPad 14.0 "name": "iPad 14.0 (PC, Whale)", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Whale/1.7.0.2222 Safari/600.7.12", "os": { "name": "mac", "version": "10.10.4", }, "browser": { "name": "whale", "version": "1.7.0.2222", "webkit": true, "webkitVersion": "600.7.12", }, "isMobile": false, }, { // iPhone 5.0.1 "name": "iPhone 5.0.1", "ua": "Mozilla/5.0 (iPhone;CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3", "os": { "name": "ios", "version": "5.0.1", }, "browser": { "name": "safari", "version": "5.1", "webkit": true, "webkitVersion": "534.46", }, "isMobile": true, }, { // iPhone 6.0 "name": "iPhone 6.0", "ua": "Mozilla/5.0 (iPhone;CPU iPhone OS 6_0_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A551 Safari/8536.25", "os": { "name": "ios", "version": "6.0.2", }, "browser": { "name": "safari", "version": "6.0", "webkit": true, "webkitVersion": "536.26", }, "isMobile": true, }, { // iPhone 6.1.2 "name": "iPhone 6.1.2", "ua": "Mozilla/5.0 (iPhone;CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25", "os": { "name": "ios", "version": "6.1.2", }, "browser": { "name": "safari", "version": "6.0", "webkit": true, "webkitVersion": "536.26", }, "isMobile": true, }, { // iPhone 7.0 "name": "iPhone 7.0", "ua": "Mozilla/5.0 (iPhone;CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25", "os": { "name": "ios", "version": "7.0", }, "browser": { "name": "safari", "version": "6.0", "webkit": true, "webkitVersion": "536.26", }, "isMobile": true, }, { // iPhone 8.0 "name": "iPhone 8.0", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4", "os": { "name": "ios", "version": "8.0", }, "browser": { "name": "safari", "version": "8.0", "webkit": true, "webkitVersion": "600.1.4", }, "isMobile": true, }, { // iPhone 8.0 - webview (Naver) "name": "iPhone 8.0 - webview (Naver)", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B440 NAVER(inapp; search; 390; 6.0.2)", "os": { "name": "ios", "version": "8.0", }, "browser": { "name": "safari", "version": "-1", "webview": true, "webkit": true, "webkitVersion": "600.1.4", }, "isMobile": true, }, { // iPhone 8.0 - webview "name": "iPhone 8.0 - webview", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B440", "os": { "name": "ios", "version": "8.0", }, "browser": { "name": "safari", "version": "-1", "webview": true, "webkit": true, "webkitVersion": "600.1.4", }, "isMobile": true, }, { // iPhone 9.0 "name": "iPhone 9.0", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A452 Safari/601.1", "os": { "name": "ios", "version": "9.0", }, "browser": { "name": "safari", "version": "9.0", "webkit": true, "webkitVersion": "601.1.46", }, "isMobile": true, }, { // iPhone 9.0 - webview (Naver) on iPhone 4S "name": "iPhone 9.0 - webview (Naver app)", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13A452 NAVER(inapp; search; 450; 6.4.5; 4S)", "os": { "name": "ios", "version": "9.0", }, "browser": { "name": "safari", "version": "-1", "webview": true, "webkit": true, "webkitVersion": "601.1.46", }, "isMobile": true, }, { // iPhone 9.0 - webview (LINE app) "name": "iPhone 9.0 - webview (LINE app)", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13A452 Safari Line/5.4.0", "os": { "name": "ios", "version": "9.0", }, "browser": { "name": "safari", "version": "-1", "webview": true, "webkit": true, "webkitVersion": "601.1.46", }, "isMobile": true, }, { // iPhone 10.0 - WKWebView "name": "iPhone 10.0 - WKWebView", "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A456 NAVER(inapp; search; 560; 7.7.0; 7)", "os": { "name": "ios", "version": "10.0.2", }, "browser": { "name": "safari", "version": "-1", "webview": true, "webkit": true, "webkitVersion": "602.1.50", }, "isMobile": true, }, { // iPad 10.0 - WKWebView "name": "iPad 10.0 - WKWebView", "ua": "Mozilla/5.0 (iPad; CPU OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A456 Version/5.1 Safari/7534.48.3 NAVER(inapp; search; 134; 7.7.0)", "os": { "name": "ios", "version": "10.0.2", }, "browser": { "name": "safari", "version": "5.1", "webview": true, "webkit": true, "webkitVersion": "602.1.50", }, "isMobile": true, }, { // GalaxyS:2.1 "name": "GalaxyS:2.1", "ua": "Mozilla/5.0 (Linux;U;Android 2.1;ko-kr;SHW-M110S Build/ÉCLAIR) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17", "os": { "name": "android", "version": "2.1", "webkit": true, "webkitVersion": "530.17", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "530.17", }, "isMobile": true, }, { // GalaxyS:2.2 "name": "GalaxyS:2.2", "ua": "Mozilla/5.0 (Linux;U;Android 2.2;ko-kr;SHW-M110S Build/FROYO) AppleWebKit/533.1(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "os": { "name": "android", "version": "2.2", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "533.1", }, "isMobile": true, }, { // GalaxyS:2.3.4 "name": "GalaxyS:2.3.4", "ua": "Mozilla/5.0 (Linux;U;Android 2.3.4;ko-kr;SHW-M110S Build/GINGERBREAD)AppleWebKit/533.1(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "os": { "name": "android", "version": "2.3.4", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "533.1", }, "isMobile": true, }, { // GalaxyS2:2.3.3 "name": "GalaxyS2:2.3.3", "ua": "Mozilla/5.0 (Linux;U;Android 2.3.3;ko-kr;SHW-M250S Build/GINGERBREAD) AppleWebKit/533.1(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "os": { "name": "android", "version": "2.3.3", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "533.1", }, "isMobile": true, }, { // GalaxyNote:2.3.6 "name": "GalaxyNote:2.3.6", "ua": "Mozilla/5.0 (Linux;U;Android 2.3.6;ko-kr;SHV-E160S Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "os": { "name": "android", "version": "2.3.6", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "533.1", }, "isMobile": true, }, { // GalaxyTab2:3.1 "name": "GalaxyTab2:3.1", "ua": "Mozilla/5.0 (Linux;U; Android 3.1;ko-kr;SHW-M380S Build/HMJ37) AppleWebkit/534.13(KHTML, like Gecko) Version/4.0 Safari/534.13", "os": { "name": "android", "version": "3.1", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "534.13", }, "isMobile": false, }, { // GalaxyNexus:4.0.1 "name": "GalaxyNexus:4.0.1", "ua": "Mozilla/5.0 (Linux;U;Android 4.0.1;ko-kr;Galaxy Nexus Build/ITL41F)AppleWebKit/534.30 (KHTML, like Gecko)Version/4.0 Mobile Safari/534.30", "os": { "name": "android", "version": "4.0.1", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "534.30", }, "isMobile": true, }, { // GalaxyS3:4.0.4 "name": "GalaxyS3:4.0.4", "ua": "Mozilla/5.0 (Linux; U; Android 4.0.4; ko-kr; SHV-E210S Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", "os": { "name": "android", "version": "4.0.4", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "534.30", }, "isMobile": true, }, { // GalaxyS2:chrome "name": "GalaxyS2:chrome", "ua": "Mozilla/5.0 (Linux; U;Android 4.0.3;ko-kr; SHW-M250S Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Mobile Safari/535.7", "os": { "name": "android", "version": "4.0.3", }, "browser": { "name": "chrome", "version": "16.0.912.77", "chromium": true, "chromiumVersion": "16.0.912.77", }, "isMobile": true, }, { // GalaxyS4:4.2.2 "name": "GalaxyS4:4.2.2", "ua": "Mozilla/5.0 (Linux; Android 4.2.2; ko-kr; SAMSUNG SHV-E300S Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Version/1.0 Chrome/18.0.1025.308 Mobile Safari/535.19", "os": { "name": "android", "version": "4.2.2", }, "browser": { "name": "samsung internet", "version": "1.0", "chromium": true, "chromiumVersion": "18.0.1025.308", }, "isMobile": true, }, { // GalaxyS4:chrome "name": "GalaxyS4:chrome", "ua": "Mozilla/5.0 (Linux; Android 4.2.2; SHV-E300S Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19", "os": { "name": "android", "version": "4.2.2", }, "browser": { "name": "chrome", "version": "18.0.1025.166", "chromium": true, "chromiumVersion": "18.0.1025.166", }, "isMobile": true, }, { // GalaxyS5:chrome "name": "GalaxyS5:chrome", "ua": "Mozilla/5.0 (Linux; Android 4.4.2; SM-G900S Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.108 Mobile Safari/537.36", "os": { "name": "android", "version": "4.4.2", }, "browser": { "name": "chrome", "version": "42.0.2311.108", "chromium": true, "chromiumVersion": "42.0.2311.108", }, "isMobile": true, }, { // GalaxyS5 4.4.2 - webview (NAVER app) "name": "GalaxyS5 - webview", "ua": "Mozilla/5.0 (Linux; Android 4.4.2; SM-G900S Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/28.0.1500.94 Mobile Safari/537.36 NAVER(inapp; search; 340; 6.0.5)", "os": { "name": "android", "version": "4.4.2", }, "browser": { "name": "chrome", "version": "28.0.1500.94", "webview": true, "chromium": true, "chromiumVersion": "28.0.1500.94", }, "isMobile": true, }, { // GalaxyS5 5.0 - webview "name": "GalaxyS5 5.0 - webview", "ua": "Mozilla/5.0 (Linux; Android 5.0; SM-G900S Build/LRX21T; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/42.0.2311.138 Mobile Safari/537.36", "os": { "name": "android", "version": "5.0", }, "browser": { "name": "chrome", "version": "42.0.2311.138", "webview": true, "chromium": true, "chromiumVersion": "42.0.2311.138", }, "isMobile": true, }, { // GalaxyS5 - higgs "name": "GalaxyS5 - higgs", "ua": "Mozilla/5.0 (Linux; Android 4.4.2; SM-G900S Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.61 Mobile Safari/537.36 NAVER(higgs; search; 340; 6.0.5; 1.0.6.2)", "os": { "name": "android", "version": "4.4.2", }, "browser": { "name": "chrome", "version": "33.0.1750.61", "webview": true, "chromium": true, "chromiumVersion": "33.0.1750.61", }, "isMobile": true, }, { // GalaxyS6 5.1.1 "name": "GalaxyS6:5.1.1", "ua": "Mozilla/5.0 (Linux; Android 5.1.1; SAMSUNG SM-G925S Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/3.2 Chrome/38.0.2125.102 Mobile Safari/537.36", "os": { "name": "android", "version": "5.1.1", }, "browser": { "name": "samsung internet", "version": "3.2", "chromium": true, "chromiumVersion": "38.0.2125.102", }, "isMobile": true, }, { // GalaxyS6:chrome "name": "GalaxyS6:chrome", "ua": "Mozilla/5.0 (Linux; Android 5.1.1; SM-G925S Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.84 Mobile Safari/537.36", "os": { "name": "android", "version": "5.1.1", }, "browser": { "name": "chrome", "version": "45.0.2454.84", "chromium": true, "chromiumVersion": "45.0.2454.84", }, "isMobile": true, }, { // GalaxyS6 5.1.1 - webview (Naver app) "name": "GalaxyS6 - webview (Naver app)", "ua": "Mozilla/5.0 (Linux; Android 5.1.1; SM-G925S Build/LMY47X; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.95 Mobile Safari/537.36 NAVER(inapp; search; 390; 6.4.5)", "os": { "name": "android", "version": "5.1.1", }, "browser": { "name": "chrome", "version": "45.0.2454.95", "webview": true, "chromium": true, "chromiumVersion": "45.0.2454.95", }, "isMobile": true, }, { // GalaxyS6 5.1.1 - webview (KAKAOTALK app) "name": "GalaxyS6 - webview (KAKAOTALK app)", "ua": "Mozilla/5.0 (Linux; Android 5.1.1; SM-G925S Build/LMY47X; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/45.0.2454.95 Mobile Safari/537.36;KAKAOTALK", "os": { "name": "android", "version": "5.1.1", }, "browser": { "name": "chrome", "version": "45.0.2454.95", "webview": true, "chromium": true, "chromiumVersion": "45.0.2454.95", }, "isMobile": true, }, { // GalaxyS6 5.1.1 - webview (Facebook app) "name": "GalaxyS6 - webview (Facebook app)", "ua": "Mozilla/5.0 (Linux; Android 5.1.1; SM-G925S Build/LMY47X; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/45.0.2454.95 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/50.0.0.10.54;]", "os": { "name": "android", "version": "5.1.1", }, "browser": { "name": "chrome", "version": "45.0.2454.95", "webview": true, "chromium": true, "chromiumVersion": "45.0.2454.95", }, "isMobile": true, }, { // GalaxyS7 Edge 6.0.1 "name": "GalaxyS7Edge:6.0.1", "ua": "Mozilla/5.0 (Linux; Android 6.0.1; SAMSUNG SM-G935L Build/MMB29K) AppleWebkit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/44.0.2403.133 Mobile Safari/537.36", "os": { "name": "android", "version": "6.0.1", }, "browser": { "name": "samsung internet", "version": "4.0", "chromium": true, "chromiumVersion": "44.0.2403.133", }, "isMobile": true, }, { // GalaxyS7 Edge 6.0.1:chrome "name": "GalaxyS7Edge:chrome", "ua": "Mozilla/5.0 (Linux; Android 6.0.1; SM-G935L Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.91 Mobile Safari/537.36", "os": { "name": "android", "version": "6.0.1", }, "browser": { "name": "chrome", "version": "49.0.2623.91", "chromium": true, "chromiumVersion": "49.0.2623.91", }, "isMobile": true, }, { // GalaxyS7 Edge 6.0.1 - webview (Naver app) "name": "GalaxyS7Edge - webview (Naver app)", "ua": "Mozilla/5.0 (Linux; Android 6.0.1; SM-G935L Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/48.0.2564.10 Mobile Safari/537.36 NAVER(inapp; search; 430; 6.9.1)", "os": { "name": "android", "version": "6.0.1", }, "browser": { "name": "chrome", "version": "48.0.2564.10", "webview": true, "chromium": true, "chromiumVersion": "48.0.2564.10", }, "isMobile": true, }, { // GalaxyNexus:4.2.2 "name": "GalaxyNexus:4.2.2", "ua": "Mozilla/5.0 (Linux; Android 4.2.2;ko-kr; Galaxy Nexus Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", "os": { "name": "android", "version": "4.2.2", }, "browser": { "name": "android browser", "version": "4.0", "webkit": true, "webkitVersion": "534.30", }, "isMobile": true, }, { // GalaxyNexus:chrome "name": "GalaxyNexus:chrome", "ua": "Mozilla/5.0 (Linux; Android 4.2.2; Galaxy Nexus Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/18.0.1364.169 Mobile Safari/537.22", "os": { "name": "android", "version": "4.2.2", }, "browser": { "name": "chrome", "version": "18.0.1364.169", "chromium": true, "chromiumVersion": "18.0.1364.169", }, "isMobile": true, }, { // GalaxyNexus:chrome "name": "GalaxyNexus:chrome", "ua": "Mozilla/5.0 (Linux; Android 4.2.2; Galaxy Nexus Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.169 Mobile Safari/537.22", "os": { "name": "android", "version": "4.2.2", }, "browser": { "name": "chrome", "version": "25.0.1364.169", "chromium": true, "chromiumVersion": "25.0.1364.169", }, "isMobile": true, }, { // GalaxyNote2:chrome "name": "GalaxyNote2:chrome", "ua": "Mozilla/5.0 (Linux; Android 4.3; SHV-E250S Build/JSS15J) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36", "os": { "name": "android", "version": "4.3", }, "browser": { "name": "chrome", "version": "31.0.1650.59", "chromium": true, "chromiumVersion": "31.0.1650.59", }, "isMobile": true, }, { // Xiaomi_2013061_TD:browser "name": "Xiaomi_2013061_TD:browser", "ua": "Xiaomi_2013061_TD/V1 Linux/3.4.5 Android/4.2.1 Release/09.18.2013 Browser/AppleWebKit534.30 Mobile Safari/534.30 MBBMS/2.2 System/Android 4.2.1 XiaoMi/MiuiBrowser/1.0", "os": { "name": "android", "version": "4.2.1", }, "browser": { "name": "miui browser", "version": "1.0", "webkit": true, "webkitVersion": "534.30", }, "isMobile": true, }, { // window && IE "name": "window && IE", "ua": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; IPMS/930D0D0A-04A359770A0; TCO_20090615095913; InfoPath.2; .NET CLR 2.0.50727)", "os": { "name": "window", "version": "5.1", }, "browser": { "name": "ie", "version": "7.0", }, "isMobile": false, }, { // Windows 7 && IE "name": "Windows 7 && IE", "ua": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)", "os": { "name": "window", "version": "6.1", }, "browser": { "name": "ie", "version": "8.0", }, "isMobile": false, }, { // Windows 7 && IE "name": "Windows 7 && IE", "ua": "Mozilla/5.0 (Windows NT 6.1;; APCPMS=^N20120502090046254556C65BBCE3E22DEE3F_24184^; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; TCO_20150325103347; rv:11.0) like Gecko", "os": { "name": "window", "version": "6.1", }, "browser": { "name": "ie", "version": "11.0", }, "isMobile": false, }, { // Windows 7 && Chrome "name": "Windows 7 && Chrome", "ua": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36", "os": { "name": "window", "version": "6.1", }, "browser": { "name": "chrome", "version": "41.0.2272.101", "chromium": true, "chromiumVersion": "41.0.2272.101", }, "isMobile": false, }, { // Windows 7 && Firefox "name": "Windows 7 && Firefox", "ua": "Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0", "os": { "name": "window", "version": "6.1", }, "browser": { "name": "firefox", "version": "36.0", }, "isMobile": false, }, { // IE11 on Windows 10 "name": "Windows 10 Update && IE11", "ua": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko", "os": { "name": "window", "version": "10.0", }, "browser": { "name": "ie", "version": "11.0", }, "isMobile": false, }, { // 64-bit Windows 8.1 Update && IE11 "name": "64-bit Windows 8.1 Update && IE11", "ua": "Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; Touch; rv:11.0) like Gecko", "os": { "name": "window", "version": "6.3", }, "browser": { "name": "ie", "version": "11.0", }, "isMobile": false, }, { // 64-bit Windows 8.1 Update && IE11 for the desktop "name": "64-bit Windows 8.1 Update && IE11 for the desktop", "ua": "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko", "os": { "name": "window", "version": "6.3", }, "browser": { "name": "ie", "version": "11.0", }, "isMobile": false, }, { // Windows 10 && Microsoft Edge for desktop "name": "Windows 10 && Microsoft Edge for desktop", "ua": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240", "os": { "name": "window", "version": "10.0", }, "browser": { "name": "edge", "version": "12.10240", "chromium": true, "chromiumVersion": "42.0.2311.135", }, "isMobile": false, }, { // Mac && Chrome "name": "Mac && Chrome", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36", "os": { "name": "mac", "version": "10.10.2", }, "browser": { "name": "chrome", "version": "41.0.2272.101", "chromium": true, "chromiumVersion": "41.0.2272.101", }, "isMobile": false, }, { "name": "Mac && Chrome2", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36", "os": { "name": "mac", "version": "10.15.4", }, "browser": { "name": "chrome", "version": "84.0.4147.135", "webkit": false, "chromium": true, "chromiumVersion": "84.0.4147.135", }, "isMobile": false, }, { "name": "Mac && Firefox", "ua": " Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:79.0) Gecko/20100101 Firefox/79.0", "os": { "name": "mac", "version": "10.15", }, "browser": { "name": "firefox", "version": "79.0", }, "isMobile": false, }, { // Mac && Safari "name": "Mac && Safari", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18", "os": { "name": "mac", "version": "10.10.2", }, "browser": { "name": "safari", "version": "8.0.3", "webkit": true, "webkitVersion": "600.3.18", }, "isMobile": false, }, { // Phantomjs (default value) "name": "Phantomjs (default value)", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34", "os": { "name": "mac", "version": "-1", }, "browser": { "name": "phantomjs", "version": "1.9.8", "webkit": true, "webkitVersion": "534.34", }, "isMobile": false, }, { // Window XP && ie6 "name": "Window XP && ie6", "ua": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.37052000; Media Center PC 3.1)", "os": { "name": "window", "version": "5.1", }, "browser": { "name": "ie", "version": "6.0", }, "isMobile": false, }, { // Window 2000 && ie7 "name": "Window 2000 && ie7", "ua": "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.0; Trident/4.0; FBSMTWB; .NET CLR 2.0.34861; .NET CLR 3.0.3746.3218; .NET CLR 3.5.33652; msn OptimizedIE8;ENUS)", "os": { "name": "window", "version": "5.0", }, "browser": { "name": "ie", "version": "7.0", }, "isMobile": false, }, { // Window Vista && ie6.2 "name": "Window Vista && ie6.2", "ua": "Mozilla/5.3 (compatible; MSIE 6.2; Windows NT 6.0)", "os": { "name": "window", "version": "6.0", }, "browser": { "name": "ie", "version": "6.2", }, "isMobile": false, }, { // Window 2000 && ie6 "name": "Window 2000 && ie6", "ua": "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)", "os": { "name": "window", "version": "5.0", }, "browser": { "name": "ie", "version": "6.0", }, "isMobile": false, }, { // Phantomjs Window 7 (default value) "name": "Phantomjs Window (default value)", "ua": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34", "os": { "name": "window", "version": "6.1", }, "browser": { "name": "phantomjs", "version": "1.9.8", "webkit": true, "webkitVersion": "534.34", }, "isMobile": false, }, { "name": "Phantomjs (default value)", "ua": "Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34", "browser": { "name": "phantomjs", "version": "1.9.8", "webkit": true, "webkitVersion": "534.34", }, "os": { "name": "unknown", "version": "-1", }, "isMobile": false, }, { "name": "Windows 10 & Whale", "ua": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Whale/0.7.31.4 Safari/537.36", "os": { "name": "window", "version": "10.0", }, "browser": { "name": "whale", "version": "0.7.31.4", "chromium": true, "chromiumVersion": "52.0.2743.116", }, "isMobile": false, }, { "name": "Tizen 2.3 & FamilyHub", "ua": "Mozilla/5.0 (Linux; Tizen 2.3; FamilyHub) AppleWebKit/537.3 (KHTML, like Gecko) Version/2.3 Mobile Safari/537.3", "os": { "name": "tizen", "version": "2.3", }, "browser": { "name": "safari", "version": "2.3", "webkit": true, "webkitVersion": "537.3", }, "isMobile": true, }, { "name": "Tizen 3.0 & FamilyHub", "ua": "Mozilla/5.0 (Linux; Tizen 3.0; FamilyHub) AppleWebKit/537.3 (KHTML, like Gecko) Version/2.3 Mobile Safari/537.3", "os": { "name": "tizen", "version": "3.0", }, "browser": { "name": "safari", "version": "2.3", "webkit": true, "webkitVersion": "537.3", }, "isMobile": true, }, { "name": "Tizen 2.4.0 & Z3 & samsung internet", "ua": "Mozilla/5.0 (Linux; Tizen 2.4.0; TIZEN SM-Z300H) AppleWebKit/537.3 (KHTML, like Gecko)SamsungBrowser/1.1 Mobile Safari/537.3", "os": { "name": "tizen", "version": "2.4.0", "webkit": true, "webkitVersion": "537.3", }, "browser": { "name": "samsung internet", "version": "1.1", "webkit": true, "webkitVersion": "537.3", }, "isMobile": true, }, { "name": "Tizen 2.3 & SMART-TV & samsung internet", "ua": "Mozilla/5.0 (SMART-TV; Linux; Tizen 2.3) AppleWebkit/538.1 (KHTML, like Gecko) SamsungBrowser/1.0 TV Safari/538.1", "browser": { "name": "samsung internet", "version": "1.0", "webkit": true, "webkitVersion": "538.1", }, "os": { "name": "tizen", "version": "2.3", }, "isMobile": false, }, { "name": "Android 5.x & Gear VR & samsung internet", "ua": "Mozilla/5.0 (Linux; Android 5.0.2; SAMSUNG SM-G925K Build/LRX22G) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/44.0.2403.133 Mobile VR Safari/537.36", "browser": { "name": "samsung internet", "version": "4.0", "chromium": true, "chromiumVersion": "44.0.2403.133", }, "os": { "name": "android", "version": "5.0.2", }, "isMobile": true, }, { "name": "WebOS & TV & app", "ua": "Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.2.1 Chrome/38.0.2125.122 Safari/537.36 WebAppManager", "browser": { "name": "chrome", "version": "38.0.2125.122", "chromium": true, "chromiumVersion": "38.0.2125.122", }, "os": { "name": "webos", "version": "-1", }, "isMobile": false, }, ]; // complement AGENT_LIST.forEach(agent => { if (!agent.browser.webview) { agent.browser.webview = false; } if (!agent.browser.webkit) { agent.browser.webkit = false; agent.browser.webkitVersion = "-1"; } if (!agent.browser.chromium) { agent.browser.chromium = false; agent.browser.chromiumVersion = "-1"; } }); export default AGENT_LIST;
the_stack
import { strict as assert } from "assert"; import * as path from "path"; import * as vs from "vscode"; import { DebuggerType, VmService } from "../../../shared/enums"; import { fsPath } from "../../../shared/utils/fs"; import { DartDebugClient } from "../../dart_debug_client"; import { createDebugClient, ensureVariable, waitAllThrowIfTerminates } from "../../debug_helpers"; import { activate, closeAllOpenFiles, defer, delay, extApi, getLaunchConfiguration, getPackages, logger, openFile, positionOf, sb, setConfigForTest, waitForResult, watchPromise, webBrokenIndexFile, webBrokenMainFile, webHelloWorldExampleSubFolder, webHelloWorldExampleSubFolderIndexFile, webHelloWorldIndexFile, webHelloWorldMainFile, webProjectContainerFolder } from "../../helpers"; describe.skip("web debugger", () => { before("get packages (0)", () => getPackages(webHelloWorldIndexFile)); before("get packages (1)", () => getPackages(webBrokenIndexFile)); beforeEach("activate webHelloWorldIndexFile", () => activate(webHelloWorldIndexFile)); let dc: DartDebugClient; beforeEach("create debug client", () => { dc = createDebugClient(DebuggerType.Web); }); async function startDebugger(script?: vs.Uri | string, cwd?: string): Promise<vs.DebugConfiguration> { const config = await getLaunchConfiguration(script, { cwd, }); if (!config) throw new Error(`Could not get launch configuration (got ${config})`); await watchPromise("startDebugger->start", dc.start()); return config; } it("runs a web application and remains active until told to quit", async () => { const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, watchPromise("assertOutputContains(serving web on)", dc.assertOutputContains("stdout", "Serving `web` on http://127.0.0.1:")), watchPromise("configurationSequence", dc.configurationSequence()), watchPromise("launch", dc.launch(config)), ); // Ensure we're still responsive after 3 seconds. await delay(3000); await watchPromise("threadsRequest", dc.threadsRequest()); await waitAllThrowIfTerminates(dc, watchPromise("waitForEvent(terminated)", dc.waitForEvent("terminated")), watchPromise("terminateRequest", dc.terminateRequest()), ); }); it("expected debugger services are available in debug mode", async () => { const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.configurationSequence(), dc.launch(config), ); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotReload) === false); // TODO: Make true when supported! await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotRestart) === true); await waitAllThrowIfTerminates(dc, dc.waitForEvent("terminated"), dc.terminateRequest(), ); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotReload) === false); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotRestart) === false); }); it("expected debugger services are available in noDebug mode", async () => { const config = await startDebugger(webHelloWorldIndexFile); config.noDebug = true; await waitAllThrowIfTerminates(dc, dc.configurationSequence(), dc.launch(config), ); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotReload) === false); // TODO: Make true when supported! await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotRestart) === true); await waitAllThrowIfTerminates(dc, dc.waitForEvent("terminated"), dc.terminateRequest(), ); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotReload) === false); await waitForResult(() => extApi.debugCommands.vmServices.serviceIsRegistered(VmService.HotRestart) === false); }); // Skipped because this is super-flaky. If we quit to early, the processes are not // cleaned up properly. This should be fixed when we move to the un-forked version. it.skip("can quit during a build", async () => { const config = await startDebugger(webHelloWorldIndexFile); // Kick off a build, but do not await it... // eslint-disable-next-line @typescript-eslint/no-floating-promises Promise.all([ dc.configurationSequence(), dc.launch(config), ]); // Wait 5 seconds to ensure the build is in progress... await delay(5000); // Send a disconnect request and ensure it happens within 5 seconds. await Promise.race([ Promise.all([ dc.waitForEvent("terminated"), dc.terminateRequest(), ]), new Promise((resolve, reject) => setTimeout(() => reject(new Error("Did not complete terminateRequest within 5s")), 5000)), ]); }); it("resolves relative paths", async () => { const config = await getLaunchConfiguration( path.relative(fsPath(webProjectContainerFolder), fsPath(webHelloWorldMainFile)), ); assert.equal(config!.program, fsPath(webHelloWorldMainFile)); }); it("hot reloads successfully", async function () { if (!extApi.dartCapabilities.webSupportsHotReload) { this.skip(); return; } const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, watchPromise("hot_reloads_successfully->configurationSequence", dc.configurationSequence()), watchPromise("hot_reloads_successfully->launch", dc.launch(config)), ); await watchPromise("hot_reloads_successfully->hotReload", dc.hotReload()); await waitAllThrowIfTerminates(dc, watchPromise("hot_reloads_successfully->waitForEvent:terminated", dc.waitForEvent("terminated")), watchPromise("hot_reloads_successfully->terminateRequest", dc.terminateRequest()), ); }); it("hot restarts successfully", async () => { const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.configurationSequence(), dc.launch(config), ); // If we restart too fast, things fail :-/ await delay(1000); await waitAllThrowIfTerminates(dc, dc.assertOutputContains("stdout", "Restarted app"), dc.customRequest("hotRestart"), ); await waitAllThrowIfTerminates(dc, dc.waitForEvent("terminated"), dc.terminateRequest(), ); }); it.skip("resolves project program/cwds in sub-folders when the open file is in a project sub-folder", async () => { await openFile(webHelloWorldExampleSubFolderIndexFile); const config = await getLaunchConfiguration(); assert.equal(config!.program, fsPath(webHelloWorldExampleSubFolderIndexFile)); assert.equal(config!.cwd, fsPath(webHelloWorldExampleSubFolder)); }); it.skip("can run projects in sub-folders when cwd is set to a project sub-folder", async () => { await closeAllOpenFiles(); const config = await getLaunchConfiguration(undefined, { cwd: "example" }); assert.equal(config!.program, fsPath(webHelloWorldExampleSubFolderIndexFile)); assert.equal(config!.cwd, fsPath(webHelloWorldExampleSubFolder)); }); it("can launch DevTools externally", async () => { await setConfigForTest("dart", "embedDevTools", false); const openBrowserCommand = sb.stub(extApi.envUtils, "openInBrowser").resolves(); const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, watchPromise("launchDevTools->start->configurationSequence", dc.configurationSequence()), watchPromise("launchDevTools->start->launch", dc.launch(config)), ); logger.info("Executing dart.openDevTools"); const devTools = await vs.commands.executeCommand("dart.openDevTools") as { url: string, dispose: () => void }; assert.ok(openBrowserCommand.calledOnce); assert.ok(devTools); assert.ok(devTools.url); defer(devTools.dispose); const serverResponse = await extApi.webClient.fetch(devTools.url); assert.notEqual(serverResponse.indexOf("Dart DevTools"), -1); await waitAllThrowIfTerminates(dc, dc.waitForEvent("terminated"), dc.terminateRequest(), ); }); const numReloads = 1; it(`stops at a breakpoint after each reload (${numReloads})`, async function () { if (!extApi.dartCapabilities.webSupportsDebugging || !extApi.dartCapabilities.webSupportsHotReload) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await startDebugger(webHelloWorldIndexFile); const expectedLocation = { line: positionOf("^// BREAKPOINT1").line, path: fsPath(webHelloWorldMainFile), }; // TODO: Remove the last parameter here (and the other things below) when we are mapping breakpoints in org-dartland-app // URIs back to the correct file system paths. await watchPromise("stops_at_a_breakpoint->hitBreakpoint", dc.hitBreakpoint(config, expectedLocation, {})); // TODO: Put these back (and the ones below) when the above is fixed. // const stack = await dc.getStack(); // const frames = stack.body.stackFrames; // assert.equal(frames[0].name, "main"); // assert.equal(frames[0].source!.path, expectedLocation.path); // assert.equal(frames[0].source!.name, "package:hello_world/main.dart"); await watchPromise("stops_at_a_breakpoint->resume", dc.resume()); // Add some invalid breakpoints because in the past they've caused us issues // https://github.com/Dart-Code/Dart-Code/issues/1437. // We need to also include expectedLocation since this overwrites all BPs. await dc.setBreakpointsRequest({ breakpoints: [{ line: 0 }, expectedLocation], source: { path: fsPath(webHelloWorldMainFile) }, }); // Reload and ensure we hit the breakpoint on each one. for (let i = 0; i < numReloads; i++) { await delay(2000); // TODO: Remove this attempt to see if reloading too fast is causing our flakes... await waitAllThrowIfTerminates(dc, // TODO: Remove the last parameter here (and the other things above and below) when we are mapping breakpoints in org-dartland-app // URIs back to the correct file system paths. watchPromise(`stops_at_a_breakpoint->reload:${i}->assertStoppedLocation:breakpoint`, dc.assertStoppedLocation("breakpoint", /* expectedLocation,*/ {})) .then(async () => { // TODO: Put these back (and the ones below) when the above is fixed. // const stack = await watchPromise(`stops_at_a_breakpoint->reload:${i}->getStack`, dc.getStack()); // const frames = stack.body.stackFrames; // assert.equal(frames[0].name, "MyHomePage.build"); // assert.equal(frames[0].source!.path, expectedLocation.path); // assert.equal(frames[0].source!.name, "package:hello_world/main.dart"); }) .then(() => watchPromise(`stops_at_a_breakpoint->reload:${i}->resume`, dc.resume())), watchPromise(`stops_at_a_breakpoint->reload:${i}->hotReload:breakpoint`, dc.hotReload()), ); } }); describe("can evaluate at breakpoint", () => { it("simple expressions", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.hitBreakpoint(config, { line: positionOf("^// BREAKPOINT1").line, // positionOf is 0-based, and seems to want 1-based, BUT comment is on next line! path: fsPath(webHelloWorldMainFile), }, {}), ); const evaluateResult = await dc.evaluateForFrame(`"test"`); assert.ok(evaluateResult); assert.equal(evaluateResult.result, `"test"`); assert.equal(evaluateResult.variablesReference, 0); }); it("complex expression expressions", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.hitBreakpoint(config, { line: positionOf("^// BREAKPOINT1").line, // positionOf is 0-based, and seems to want 1-based, BUT comment is on next line! path: fsPath(webHelloWorldMainFile), }), ); const evaluateResult = await dc.evaluateForFrame(`(new DateTime.now()).year`); assert.ok(evaluateResult); assert.equal(evaluateResult.result, (new Date()).getFullYear().toString()); assert.equal(evaluateResult.variablesReference, 0); }); it("an expression that returns a variable", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.hitBreakpoint(config, { line: positionOf("^// BREAKPOINT1").line, // positionOf is 0-based, and seems to want 1-based, BUT comment is on next line! path: fsPath(webHelloWorldMainFile), }), ); const evaluateResult = await dc.evaluateForFrame(`new DateTime.now()`); const thisYear = new Date().getFullYear().toString(); assert.ok(evaluateResult); assert.ok(evaluateResult.result.startsWith("DateTime (" + thisYear), `Result '${evaluateResult.result}' did not start with ${thisYear}`); assert.ok(evaluateResult.variablesReference); }); it("complex expression expressions when in a top level function", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await startDebugger(webHelloWorldIndexFile); await waitAllThrowIfTerminates(dc, dc.hitBreakpoint(config, { line: positionOf("^// BREAKPOINT2").line, path: fsPath(webHelloWorldMainFile), }), ); const evaluateResult = await dc.evaluateForFrame(`(new DateTime.now()).year`); assert.ok(evaluateResult); assert.equal(evaluateResult.result, (new Date()).getFullYear().toString()); assert.equal(evaluateResult.variablesReference, 0); }); }); // Skipped due to https://github.com/flutter/flutter/issues/17007. it("stops on exception", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webBrokenIndexFile); const config = await startDebugger(webBrokenIndexFile); await waitAllThrowIfTerminates(dc, dc.configurationSequence(), dc.assertStoppedLocation("exception", { line: positionOf("^Oops").line + 1, // positionOf is 0-based, but seems to want 1-based path: fsPath(webBrokenIndexFile), }), dc.launch(config), ); }); // Skipped because unable to set break-on-exceptions without start-paused it.skip("provides exception details when stopped on exception", async () => { await openFile(webBrokenMainFile); const config = await startDebugger(webBrokenIndexFile); await waitAllThrowIfTerminates(dc, dc.configurationSequence(), dc.assertStoppedLocation("exception", { line: positionOf("^Oops").line + 1, // positionOf is 0-based, but seems to want 1-based path: fsPath(webBrokenIndexFile), }), dc.launch(config), ); const variables = await dc.getTopFrameVariables("Exceptions"); ensureVariable(variables, "$_threadException.message", "message", `"(TODO WHEN UNSKIPPING)"`); }); // Skipped because unable to set logpoints reliably without start-paused it.skip("logs expected text (and does not stop) at a logpoint", async function () { if (!extApi.dartCapabilities.webSupportsEvaluation) { this.skip(); return; } await openFile(webHelloWorldMainFile); const config = await watchPromise("logs_expected_text->startDebugger", startDebugger(webHelloWorldIndexFile)); await waitAllThrowIfTerminates(dc, watchPromise("logs_expected_text->waitForEvent:initialized", dc.waitForEvent("initialized")) .then(() => watchPromise("logs_expected_text->setBreakpointsRequest", dc.setBreakpointsRequest({ breakpoints: [{ line: positionOf("^// BREAKPOINT1").line, // VS Code says to use {} for expressions, but we want to support Dart's native too, so // we have examples of both (as well as "escaped" brackets). logMessage: "The \\{year} is {(new DateTime.now()).year}", }], source: { path: fsPath(webHelloWorldMainFile) }, }))).then(() => watchPromise("logs_expected_text->configurationDoneRequest", dc.configurationDoneRequest())), watchPromise("logs_expected_text->assertOutputContainsYear", dc.assertOutputContains("stdout", `The {year} is ${(new Date()).getFullYear()}\n`)), watchPromise("logs_expected_text->launch", dc.launch(config)), ); }); // Skipped due to https://github.com/dart-lang/webdev/issues/837. it.skip("writes failure output", async () => { // This test really wants to check stderr, but since the widgets library catches the exception is // just comes via stdout. await openFile(webBrokenIndexFile); const config = await startDebugger(webBrokenIndexFile); await waitAllThrowIfTerminates(dc, watchPromise("writes_failure_output->configurationSequence", dc.configurationSequence()), watchPromise("writes_failure_output->assertOutputContains", dc.assertOutputContains("stderr", "Exception: Oops\n")), watchPromise("writes_failure_output->launch", dc.launch(config)), ); }); // Skipped due to https://github.com/dart-lang/webdev/issues/379 it.skip("moves known files from call stacks to metadata", async () => { await openFile(webBrokenIndexFile); const config = await startDebugger(webBrokenIndexFile); await waitAllThrowIfTerminates(dc, watchPromise("writes_failure_output->configurationSequence", dc.configurationSequence()), watchPromise( "writes_failure_output->assertOutputContains", dc.assertOutputContains("stderr", "methodThatThrows") .then((event) => { assert.equal(event.body.output.indexOf("package:broken/main.dart"), -1); assert.equal(event.body.source!.name, "package:broken/main.dart"); assert.equal(event.body.source!.path, fsPath(webBrokenIndexFile)); assert.equal(event.body.line, positionOf("^Oops").line + 1); // positionOf is 0-based, but seems to want 1-based assert.equal(event.body.column, 5); }), ), watchPromise("writes_failure_output->launch", dc.launch(config)), ); }); });
the_stack
import { SpriteFrame } from "../../cocos/2d/assets/sprite-frame"; import { ImageAsset } from "../../cocos/core"; import { AssetManager, assetManager, loader, resources } from "../../cocos/core/asset-manager"; import { js } from "../../cocos/core/utils/js"; import { TestSprite } from "./common-class"; describe('asset-manager', function () { const assetDir = './tests/fixtures'; const libPath = assetDir + '/library'; //_resetGame(); assetManager.init({ importBase: libPath, nativeBase: libPath, }); resources.init({ name: AssetManager.BuiltinBundleName.RESOURCES, importBase: libPath, nativeBase: libPath, paths: { '0000001': ['grossini/grossini', js._getClassId(ImageAsset)], '123201': ['grossini/grossini', js._getClassId(TestSprite), 1], '0000000': ['grossini', js._getClassId(ImageAsset)], '1232218': ['grossini', js._getClassId(TestSprite), 1], // sprite in texture '123200': ['grossini', js._getClassId(TestSprite), 1], // sprite in plist }, uuids: [ '0000001', '123201', '0000000', '1232218', '123200' ], base: '', deps: [], scenes: {}, packs: {}, versions: { import: [], native: []}, redirect: [], debug: false, types: [], extensionMap: {}, }); const grossini_uuid = '748321'; const grossiniSprite_uuid = '1232218'; const selfReferenced_uuid = '123200'; const circleReferenced_uuid = '65535'; test('Load', function (done) { const image1 = assetDir + '/button.png'; const json1 = assetDir + '/library/12/123200.json'; const json2 = assetDir + '/library/deferred-loading/74/748321.json'; const resources = [ image1, json1, json2, ]; assetManager.loadAny(resources, { __requestType__: 'url'}, function (finish, total, item) { if (item.uuid === image1) { expect(item.content).toBeInstanceOf(Image); } else if (item.uuid === json1) { expect(item.content.width).toBe(89); } else if (item.uuid === json2) { expect(item.content._native).toBe('YouKnowEverything'); } else { fail('should not load an unknown url'); } }, function (err, assets) { expect(assets.length).toBe(3); expect(assets[0]).toBeInstanceOf(Image); expect(assets[1].width).toBe(89); expect(assets[2]._native).toBe('YouKnowEverything'); expect(assetManager.assets.has(image1)).toBeFalsy(); expect(assetManager.assets.has(json1)).toBeFalsy(); expect(assetManager.assets.has(json2)).toBeFalsy(); done(); }); }); test('Load single file', function (done) { const image1 = assetDir + '/button.png'; assetManager.loadAny({ url: image1 }, function (completedCount, totalCount, item) { if (item.uuid === image1) { expect(item.content).toBeInstanceOf(Image); } else { fail('should not load an unknown url'); } }, function (error, image) { expect(error).toBeFalsy(); expect(image).toBeInstanceOf(Image); expect(assetManager.assets.has(image1)).toBeFalsy(); done(); }); }); test('Loading font', function (done) { const image = assetDir + '/button.png'; const font = { url: assetDir + '/Thonburi.ttf', ext: '.ttf', }; const resources = [ image, font ]; const total = resources.length; const progressCallback = jest.fn(function (completedCount, totalCount, item) { if (item.uuid === image) { expect(item.content).toBeInstanceOf(Image); } else if (item.uuid === font.url) { expect(item.content).toBe('Thonburi_LABEL'); } else { fail('should not load an unknown url'); } }); assetManager.loadAny(resources, { __requestType__: 'url' }, progressCallback, function (error, assets) { expect(assets.length).toBe(2); expect(assets[0]).toBeInstanceOf(Image); expect(assets[1]).toBe('Thonburi_LABEL'); expect(progressCallback).toBeCalledTimes(total); done(); }); }); test('Loading texture with query', function (done) { const image1 = assetDir + '/button.png?url=http://.../1'; const image2 = assetDir + '/button.png?url=http://.../2'; assetManager.loadAny({url: image1, ext: '.png' }, function (error, image1) { assetManager.loadAny({url: image2, ext: '.png' }, function (error, image2) { expect(image1).toBeInstanceOf(Image);; expect(image2).toBeInstanceOf(Image);; expect(image1 !== image2).toBeTruthy(); done(); }); }); }); test('Loading remote image', function (done) { const image = assetDir + '/button.png'; assetManager.loadRemote(image, function (error, texture) { expect(texture).toBeInstanceOf(ImageAsset);; expect(texture._nativeAsset).toBeInstanceOf(Image);; expect(texture.refCount === 0).toBeTruthy(); done(); }); }); test('load asset with depends asset', function (done) { assetManager.loadAny(grossiniSprite_uuid, function (err, asset) { if (err) { fail(err.message); } expect((asset as SpriteFrame).texture).toBeTruthy(); expect((asset as SpriteFrame).texture.refCount).toBe(1); expect((asset as SpriteFrame).refCount).toBe(0); expect((asset as SpriteFrame).texture.height).toBe(123); done(); }); }, 2000); test('load asset with depends asset recursively if no cache', function (done) { assetManager.loadAny(selfReferenced_uuid, function (err, asset) { if (err) { fail(err.message); } expect((asset as SpriteFrame).texture).toBe(asset); expect((asset as SpriteFrame).refCount).toBe(1); done(); }); }, 200); test('load asset with circle referenced dependencies', function (done) { assetManager.loadAny(circleReferenced_uuid, function (err, asset) { if (err) { fail(err.message); } expect((asset as any).dependency).toBeTruthy(); expect((asset as any).dependency.refCount).toBe(1); expect(asset.refCount).toBe(1); expect((asset as any).dependency.dependency).toBe(asset); done(); }); }, 200); test('matching rules - 1', function (done) { resources.load('grossini', TestSprite, function (err, sprite) { expect(sprite._uuid === '1232218' || sprite._uuid === '123200').toBeTruthy(); if (sprite._uuid === '123200') { expect(sprite.refCount).toBe(1); expect((sprite as any).texture.refCount).toBe(1); } else { expect(sprite.refCount).toBe(0); expect((sprite as any).texture.refCount).toBe(1); } resources.loadDir('grossini', TestSprite, function (err, array) { expect(array.length).toBe(3); ['123200', '1232218', '123201'].forEach(function (uuid) { expect(array.some(function (item) { return item._uuid === uuid; })).toBeTruthy(); }); done() }); }); }); test('load single', function (done) { //loader.loadRes('grossini/grossini.png', function (err, texture) { // expect(!texture, 'could not load texture with file extname'); resources.load('grossini/grossini', function (err, imageAsset) { expect(imageAsset).toBeInstanceOf(ImageAsset); expect(imageAsset.refCount).toBe(0); done(); }); //}); }); test('load single by type', function (done) { resources.load('grossini', TestSprite, function (err, sprite) { expect(sprite).toBeInstanceOf(TestSprite); resources.load('grossini', ImageAsset, function (err, texture) { expect(texture).toBeInstanceOf(ImageAsset); done(); }); }); }); test('load main asset and sub asset by loadResDir', function (done) { resources.loadDir('grossini', function (err, results) { expect(Array.isArray(results)).toBeTruthy(); ['123200', '1232218', '123201', '0000000', '0000001'].forEach(function (uuid) { expect(results.some(function (item) { return item._uuid === uuid; })).toBeTruthy(); }); done(); }); }); test('loadResDir by type', function (done) { resources.loadDir('grossini', TestSprite, function (err, results) { expect(Array.isArray(results)).toBeTruthy(); const sprite = results[0]; expect(sprite instanceof TestSprite).toBeTruthy(); done(); }); }); test('load all resources by loadResDir', function (done) { resources.loadDir('', function (err, results) { expect(Array.isArray(results)).toBeTruthy(); expect(results.length).toBe(5); done(); }); }); test('url dict of loadResDir', function (done) { resources.loadDir('', ImageAsset, function (err, results) { expect(results.length).toBe(2); resources.load('grossini', ImageAsset, function (err, result) { expect(result).toBe(results[0]); done(); }); }); }); test('loadResArray', function (done) { const urls = [ 'grossini/grossini', 'grossini' ]; resources.load(urls, TestSprite, function (err, results) { expect(Array.isArray(results)).toBeTruthy(); const expectCount = urls.length; expect(results.length).toBe(expectCount); done(); }); }); test('loader.onProgress', function (done) { const onProgress = jest.fn(function (completedCount, totalCount, item) { }); loader.onProgress = onProgress; resources.loadDir('', ImageAsset, function (err, results) { expect(onProgress).toBeCalledTimes(2); loader.onProgress = null; done(); }); }); });
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Features * __NOTE__: An instance of this class is automatically created for an * instance of the FeatureClient. */ export interface Features { /** * Gets all the preview features that are available through AFEC for the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureOperationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAllWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureOperationsListResult>>; /** * Gets all the preview features that are available through AFEC for the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureOperationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureOperationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureOperationsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAll(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureOperationsListResult>; listAll(callback: ServiceCallback<models.FeatureOperationsListResult>): void; listAll(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureOperationsListResult>): void; /** * Gets all the preview features in a provider namespace that are available * through AFEC for the subscription. * * @param {string} resourceProviderNamespace The namespace of the resource * provider for getting features. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureOperationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceProviderNamespace: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureOperationsListResult>>; /** * Gets all the preview features in a provider namespace that are available * through AFEC for the subscription. * * @param {string} resourceProviderNamespace The namespace of the resource * provider for getting features. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureOperationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureOperationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureOperationsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceProviderNamespace: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureOperationsListResult>; list(resourceProviderNamespace: string, callback: ServiceCallback<models.FeatureOperationsListResult>): void; list(resourceProviderNamespace: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureOperationsListResult>): void; /** * Gets the preview feature with the specified name. * * @param {string} resourceProviderNamespace The resource provider namespace * for the feature. * * @param {string} featureName The name of the feature to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceProviderNamespace: string, featureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureResult>>; /** * Gets the preview feature with the specified name. * * @param {string} resourceProviderNamespace The resource provider namespace * for the feature. * * @param {string} featureName The name of the feature to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceProviderNamespace: string, featureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureResult>; get(resourceProviderNamespace: string, featureName: string, callback: ServiceCallback<models.FeatureResult>): void; get(resourceProviderNamespace: string, featureName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureResult>): void; /** * Registers the preview feature for the subscription. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} featureName The name of the feature to register. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ registerWithHttpOperationResponse(resourceProviderNamespace: string, featureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureResult>>; /** * Registers the preview feature for the subscription. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} featureName The name of the feature to register. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ register(resourceProviderNamespace: string, featureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureResult>; register(resourceProviderNamespace: string, featureName: string, callback: ServiceCallback<models.FeatureResult>): void; register(resourceProviderNamespace: string, featureName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureResult>): void; /** * Gets all the preview features that are available through AFEC for the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureOperationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAllNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureOperationsListResult>>; /** * Gets all the preview features that are available through AFEC for the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureOperationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureOperationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureOperationsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAllNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureOperationsListResult>; listAllNext(nextPageLink: string, callback: ServiceCallback<models.FeatureOperationsListResult>): void; listAllNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureOperationsListResult>): void; /** * Gets all the preview features in a provider namespace that are available * through AFEC for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureOperationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureOperationsListResult>>; /** * Gets all the preview features in a provider namespace that are available * through AFEC for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureOperationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureOperationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link FeatureOperationsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureOperationsListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.FeatureOperationsListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureOperationsListResult>): void; }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>The number of active statements exceeds the limit.</p> */ export interface ActiveStatementsExceededException extends __SmithyException, $MetadataBearer { name: "ActiveStatementsExceededException"; $fault: "client"; Message?: string; } export namespace ActiveStatementsExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ActiveStatementsExceededException): any => ({ ...obj, }); } /** * <p>An SQL statement encountered an environmental error while running.</p> */ export interface BatchExecuteStatementException extends __SmithyException, $MetadataBearer { name: "BatchExecuteStatementException"; $fault: "server"; Message: string | undefined; /** * <p>Statement identifier of the exception.</p> */ StatementId: string | undefined; } export namespace BatchExecuteStatementException { /** * @internal */ export const filterSensitiveLog = (obj: BatchExecuteStatementException): any => ({ ...obj, }); } export interface BatchExecuteStatementInput { /** * <p>One or more SQL statements to run. </p> */ Sqls: string[] | undefined; /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>The name of the database. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ Database: string | undefined; /** * <p>A value that indicates whether to send an event to the Amazon EventBridge event bus after the SQL statements run. </p> */ WithEvent?: boolean; /** * <p>The name of the SQL statements. You can name the SQL statements when you create them to identify the query. </p> */ StatementName?: string; } export namespace BatchExecuteStatementInput { /** * @internal */ export const filterSensitiveLog = (obj: BatchExecuteStatementInput): any => ({ ...obj, }); } export interface BatchExecuteStatementOutput { /** * <p>The identifier of the SQL statement whose results are to be fetched. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. * This identifier is returned by <code>BatchExecuteStatment</code>. </p> */ Id?: string; /** * <p>The date and time (UTC) the statement was created. </p> */ CreatedAt?: Date; /** * <p>The cluster identifier. </p> */ ClusterIdentifier?: string; /** * <p>The database user name.</p> */ DbUser?: string; /** * <p>The name of the database.</p> */ Database?: string; /** * <p>The name or ARN of the secret that enables access to the database. </p> */ SecretArn?: string; } export namespace BatchExecuteStatementOutput { /** * @internal */ export const filterSensitiveLog = (obj: BatchExecuteStatementOutput): any => ({ ...obj, }); } /** * <p>The Amazon Redshift Data API operation failed due to invalid input. </p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; /** * <p>The exception message.</p> */ Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } export interface CancelStatementRequest { /** * <p>The identifier of the SQL statement to cancel. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. * This identifier is returned by <code>BatchExecuteStatment</code>, <code>ExecuteStatment</code>, and <code>ListStatements</code>. </p> */ Id: string | undefined; } export namespace CancelStatementRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelStatementRequest): any => ({ ...obj, }); } export interface CancelStatementResponse { /** * <p>A value that indicates whether the cancel statement succeeded (true). </p> */ Status?: boolean; } export namespace CancelStatementResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelStatementResponse): any => ({ ...obj, }); } /** * <p>The Amazon Redshift Data API operation failed due to invalid input. </p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; /** * <p>The exception message.</p> */ Message: string | undefined; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>The Amazon Redshift Data API operation failed due to a missing resource. </p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The exception message.</p> */ Message: string | undefined; /** * <p>Resource identifier associated with the exception.</p> */ ResourceId: string | undefined; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>The properties (metadata) of a column. </p> */ export interface ColumnMetadata { /** * <p>A value that indicates whether the column is case-sensitive. </p> */ isCaseSensitive?: boolean; /** * <p>A value that indicates whether the column contains currency values.</p> */ isCurrency?: boolean; /** * <p>A value that indicates whether an integer column is signed.</p> */ isSigned?: boolean; /** * <p>The label for the column. </p> */ label?: string; /** * <p>The name of the column. </p> */ name?: string; /** * <p>A value that indicates whether the column is nullable. </p> */ nullable?: number; /** * <p>The precision value of a decimal number column. </p> */ precision?: number; /** * <p>The scale value of a decimal number column. </p> */ scale?: number; /** * <p>The name of the schema that contains the table that includes the column.</p> */ schemaName?: string; /** * <p>The name of the table that includes the column. </p> */ tableName?: string; /** * <p>The database-specific data type of the column. </p> */ typeName?: string; /** * <p>The length of the column.</p> */ length?: number; /** * <p>The default value of the column. </p> */ columnDefault?: string; } export namespace ColumnMetadata { /** * @internal */ export const filterSensitiveLog = (obj: ColumnMetadata): any => ({ ...obj, }); } export interface DescribeStatementRequest { /** * <p>The identifier of the SQL statement to describe. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. * A suffix indicates the number of the SQL statement. * For example, <code>d9b6c0c9-0747-4bf4-b142-e8883122f766:2</code> has a suffix of <code>:2</code> that indicates the second SQL statement of a batch query. * This identifier is returned by <code>BatchExecuteStatment</code>, <code>ExecuteStatement</code>, and <code>ListStatements</code>. </p> */ Id: string | undefined; } export namespace DescribeStatementRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStatementRequest): any => ({ ...obj, }); } /** * <p>A parameter used in a SQL statement.</p> */ export interface SqlParameter { /** * <p>The name of the parameter.</p> */ name: string | undefined; /** * <p>The value of the parameter. * Amazon Redshift implicitly converts to the proper data type. For more inforation, see * <a href="https://docs.aws.amazon.com/redshift/latest/dg/c_Supported_data_types.html">Data types</a> in the * <i>Amazon Redshift Database Developer Guide</i>. </p> */ value: string | undefined; } export namespace SqlParameter { /** * @internal */ export const filterSensitiveLog = (obj: SqlParameter): any => ({ ...obj, }); } export enum StatusString { ABORTED = "ABORTED", ALL = "ALL", FAILED = "FAILED", FINISHED = "FINISHED", PICKED = "PICKED", STARTED = "STARTED", SUBMITTED = "SUBMITTED", } export enum StatementStatusString { ABORTED = "ABORTED", FAILED = "FAILED", FINISHED = "FINISHED", PICKED = "PICKED", STARTED = "STARTED", SUBMITTED = "SUBMITTED", } /** * <p>Information about an SQL statement.</p> */ export interface SubStatementData { /** * <p>The identifier of the SQL statement. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. * A suffix indicates the number of the SQL statement. * For example, <code>d9b6c0c9-0747-4bf4-b142-e8883122f766:2</code> has a suffix of <code>:2</code> that indicates the second SQL statement of a batch query.</p> */ Id: string | undefined; /** * <p>The amount of time in nanoseconds that the statement ran.</p> */ Duration?: number; /** * <p>The error message from the cluster if the SQL statement encountered an error while running.</p> */ Error?: string; /** * <p>The status of the SQL statement. An * example is the that the SQL statement finished. * </p> */ Status?: StatementStatusString | string; /** * <p>The date and time (UTC) the statement was created. </p> */ CreatedAt?: Date; /** * <p>The date and time (UTC) that the statement metadata was last updated.</p> */ UpdatedAt?: Date; /** * <p>The SQL statement text.</p> */ QueryString?: string; /** * <p>Either the number of rows returned from the SQL statement or the number of rows affected. * If result size is greater than zero, the result rows can be the number of rows affected by SQL statements such as INSERT, UPDATE, DELETE, COPY, and others. * A <code>-1</code> indicates the value is null.</p> */ ResultRows?: number; /** * <p>The size in bytes of the returned results. A <code>-1</code> indicates the value is null.</p> */ ResultSize?: number; /** * <p>The SQL statement identifier. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. </p> */ RedshiftQueryId?: number; /** * <p>A value that indicates whether the statement has a result set. The result set can be empty.</p> */ HasResultSet?: boolean; } export namespace SubStatementData { /** * @internal */ export const filterSensitiveLog = (obj: SubStatementData): any => ({ ...obj, }); } export interface DescribeStatementResponse { /** * <p>The identifier of the SQL statement described. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. </p> */ Id: string | undefined; /** * <p>The name or Amazon Resource Name (ARN) of the secret that enables access to the database. </p> */ SecretArn?: string; /** * <p>The database user name. </p> */ DbUser?: string; /** * <p>The name of the database. </p> */ Database?: string; /** * <p>The cluster identifier. </p> */ ClusterIdentifier?: string; /** * <p>The amount of time in nanoseconds that the statement ran. </p> */ Duration?: number; /** * <p>The error message from the cluster if the SQL statement encountered an error while running. </p> */ Error?: string; /** * <p>The status of the SQL statement being described. Status values are defined as follows: </p> * <ul> * <li> * <p>ABORTED - The query run was stopped by the user. </p> * </li> * <li> * <p>ALL - A status value that includes all query statuses. This value can be used to filter results. </p> * </li> * <li> * <p>FAILED - The query run failed. </p> * </li> * <li> * <p>FINISHED - The query has finished running. </p> * </li> * <li> * <p>PICKED - The query has been chosen to be run. </p> * </li> * <li> * <p>STARTED - The query run has started. </p> * </li> * <li> * <p>SUBMITTED - The query was submitted, but not yet processed. </p> * </li> * </ul> */ Status?: StatusString | string; /** * <p>The date and time (UTC) when the SQL statement was submitted to run. </p> */ CreatedAt?: Date; /** * <p>The date and time (UTC) that the metadata for the SQL statement was last updated. An * example is the time the status last changed. </p> */ UpdatedAt?: Date; /** * <p>The process identifier from Amazon Redshift. </p> */ RedshiftPid?: number; /** * <p>A value that indicates whether the statement has a result set. The result set can be empty. </p> */ HasResultSet?: boolean; /** * <p>The SQL statement text. </p> */ QueryString?: string; /** * <p>Either the number of rows returned from the SQL statement or the number of rows affected. * If result size is greater than zero, the result rows can be the number of rows affected by SQL statements such as INSERT, UPDATE, DELETE, COPY, and others. * A <code>-1</code> indicates the value is null.</p> */ ResultRows?: number; /** * <p>The size in bytes of the returned results. A <code>-1</code> indicates the value is null.</p> */ ResultSize?: number; /** * <p>The identifier of the query generated by Amazon Redshift. * These identifiers are also available in the <code>query</code> column of the <code>STL_QUERY</code> system view. </p> */ RedshiftQueryId?: number; /** * <p>The parameters for the SQL statement.</p> */ QueryParameters?: SqlParameter[]; /** * <p>The SQL statements from a multiple statement run.</p> */ SubStatements?: SubStatementData[]; } export namespace DescribeStatementResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStatementResponse): any => ({ ...obj, }); } export interface DescribeTableRequest { /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>The name of the database that contains the tables to be described. * If <code>ConnectedDatabase</code> is not specified, this is also the database to connect to with your authentication credentials.</p> */ Database: string | undefined; /** * <p>A database name. The connected database is specified when you connect with your authentication credentials. </p> */ ConnectedDatabase?: string; /** * <p>The schema that contains the table. If no schema is specified, then matching tables for all schemas are returned. </p> */ Schema?: string; /** * <p>The table name. If no table is specified, then all tables for all matching schemas are returned. * If no table and no schema is specified, then all tables for all schemas in the database are returned</p> */ Table?: string; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; /** * <p>The maximum number of tables to return in the response. * If more tables exist than fit in one response, then <code>NextToken</code> is returned to page through the results. </p> */ MaxResults?: number; } export namespace DescribeTableRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTableRequest): any => ({ ...obj, }); } export interface DescribeTableResponse { /** * <p>The table name. </p> */ TableName?: string; /** * <p>A list of columns in the table. </p> */ ColumnList?: ColumnMetadata[]; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace DescribeTableResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTableResponse): any => ({ ...obj, }); } /** * <p>The SQL statement encountered an environmental error while running.</p> */ export interface ExecuteStatementException extends __SmithyException, $MetadataBearer { name: "ExecuteStatementException"; $fault: "server"; /** * <p>The exception message.</p> */ Message: string | undefined; /** * <p>Statement identifier of the exception.</p> */ StatementId: string | undefined; } export namespace ExecuteStatementException { /** * @internal */ export const filterSensitiveLog = (obj: ExecuteStatementException): any => ({ ...obj, }); } export interface ExecuteStatementInput { /** * <p>The SQL statement text to run. </p> */ Sql: string | undefined; /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>The name of the database. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ Database: string | undefined; /** * <p>A value that indicates whether to send an event to the Amazon EventBridge event bus after the SQL statement runs. </p> */ WithEvent?: boolean; /** * <p>The name of the SQL statement. You can name the SQL statement when you create it to identify the query. </p> */ StatementName?: string; /** * <p>The parameters for the SQL statement.</p> */ Parameters?: SqlParameter[]; } export namespace ExecuteStatementInput { /** * @internal */ export const filterSensitiveLog = (obj: ExecuteStatementInput): any => ({ ...obj, }); } export interface ExecuteStatementOutput { /** * <p>The identifier of the SQL statement whose results are to be fetched. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. </p> */ Id?: string; /** * <p>The date and time (UTC) the statement was created. </p> */ CreatedAt?: Date; /** * <p>The cluster identifier. </p> */ ClusterIdentifier?: string; /** * <p>The database user name.</p> */ DbUser?: string; /** * <p>The name of the database.</p> */ Database?: string; /** * <p>The name or ARN of the secret that enables access to the database. </p> */ SecretArn?: string; } export namespace ExecuteStatementOutput { /** * @internal */ export const filterSensitiveLog = (obj: ExecuteStatementOutput): any => ({ ...obj, }); } /** * <p>A data value in a column. </p> */ export type Field = | Field.BlobValueMember | Field.BooleanValueMember | Field.DoubleValueMember | Field.IsNullMember | Field.LongValueMember | Field.StringValueMember | Field.$UnknownMember; export namespace Field { /** * <p>A value that indicates whether the data is NULL. </p> */ export interface IsNullMember { isNull: boolean; booleanValue?: never; longValue?: never; doubleValue?: never; stringValue?: never; blobValue?: never; $unknown?: never; } /** * <p>A value of the Boolean data type. </p> */ export interface BooleanValueMember { isNull?: never; booleanValue: boolean; longValue?: never; doubleValue?: never; stringValue?: never; blobValue?: never; $unknown?: never; } /** * <p>A value of the long data type. </p> */ export interface LongValueMember { isNull?: never; booleanValue?: never; longValue: number; doubleValue?: never; stringValue?: never; blobValue?: never; $unknown?: never; } /** * <p>A value of the double data type. </p> */ export interface DoubleValueMember { isNull?: never; booleanValue?: never; longValue?: never; doubleValue: number; stringValue?: never; blobValue?: never; $unknown?: never; } /** * <p>A value of the string data type. </p> */ export interface StringValueMember { isNull?: never; booleanValue?: never; longValue?: never; doubleValue?: never; stringValue: string; blobValue?: never; $unknown?: never; } /** * <p>A value of the BLOB data type. </p> */ export interface BlobValueMember { isNull?: never; booleanValue?: never; longValue?: never; doubleValue?: never; stringValue?: never; blobValue: Uint8Array; $unknown?: never; } export interface $UnknownMember { isNull?: never; booleanValue?: never; longValue?: never; doubleValue?: never; stringValue?: never; blobValue?: never; $unknown: [string, any]; } export interface Visitor<T> { isNull: (value: boolean) => T; booleanValue: (value: boolean) => T; longValue: (value: number) => T; doubleValue: (value: number) => T; stringValue: (value: string) => T; blobValue: (value: Uint8Array) => T; _: (name: string, value: any) => T; } export const visit = <T>(value: Field, visitor: Visitor<T>): T => { if (value.isNull !== undefined) return visitor.isNull(value.isNull); if (value.booleanValue !== undefined) return visitor.booleanValue(value.booleanValue); if (value.longValue !== undefined) return visitor.longValue(value.longValue); if (value.doubleValue !== undefined) return visitor.doubleValue(value.doubleValue); if (value.stringValue !== undefined) return visitor.stringValue(value.stringValue); if (value.blobValue !== undefined) return visitor.blobValue(value.blobValue); return visitor._(value.$unknown[0], value.$unknown[1]); }; /** * @internal */ export const filterSensitiveLog = (obj: Field): any => { if (obj.isNull !== undefined) return { isNull: obj.isNull }; if (obj.booleanValue !== undefined) return { booleanValue: obj.booleanValue }; if (obj.longValue !== undefined) return { longValue: obj.longValue }; if (obj.doubleValue !== undefined) return { doubleValue: obj.doubleValue }; if (obj.stringValue !== undefined) return { stringValue: obj.stringValue }; if (obj.blobValue !== undefined) return { blobValue: obj.blobValue }; if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; }; } export interface GetStatementResultRequest { /** * <p>The identifier of the SQL statement whose results are to be fetched. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. * A suffix indicates then number of the SQL statement. * For example, <code>d9b6c0c9-0747-4bf4-b142-e8883122f766:2</code> has a suffix of <code>:2</code> that indicates the second SQL statement of a batch query. * This identifier is returned by <code>BatchExecuteStatment</code>, <code>ExecuteStatment</code>, and <code>ListStatements</code>. </p> */ Id: string | undefined; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace GetStatementResultRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetStatementResultRequest): any => ({ ...obj, }); } export interface GetStatementResultResponse { /** * <p>The results of the SQL statement.</p> */ Records: Field[][] | undefined; /** * <p>The properties (metadata) of a column. </p> */ ColumnMetadata?: ColumnMetadata[]; /** * <p>The total number of rows in the result set returned from a query. * You can use this number to estimate the number of calls to the <code>GetStatementResult</code> operation needed to page through the results. </p> */ TotalNumRows?: number; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace GetStatementResultResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetStatementResultResponse): any => ({ ...obj, ...(obj.Records && { Records: obj.Records.map((item) => item.map((item) => Field.filterSensitiveLog(item))) }), }); } export interface ListDatabasesRequest { /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name of the database. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ Database: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; /** * <p>The maximum number of databases to return in the response. * If more databases exist than fit in one response, then <code>NextToken</code> is returned to page through the results. </p> */ MaxResults?: number; } export namespace ListDatabasesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDatabasesRequest): any => ({ ...obj, }); } export interface ListDatabasesResponse { /** * <p>The names of databases. </p> */ Databases?: string[]; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace ListDatabasesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDatabasesResponse): any => ({ ...obj, }); } export interface ListSchemasRequest { /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>The name of the database that contains the schemas to list. * If <code>ConnectedDatabase</code> is not specified, this is also the database to connect to with your authentication credentials.</p> */ Database: string | undefined; /** * <p>A database name. The connected database is specified when you connect with your authentication credentials. </p> */ ConnectedDatabase?: string; /** * <p>A pattern to filter results by schema name. Within a schema pattern, "%" means match any * substring of 0 or more characters and "_" means match any one character. Only schema name * entries matching the search pattern are returned. </p> */ SchemaPattern?: string; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; /** * <p>The maximum number of schemas to return in the response. * If more schemas exist than fit in one response, then <code>NextToken</code> is returned to page through the results. </p> */ MaxResults?: number; } export namespace ListSchemasRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSchemasRequest): any => ({ ...obj, }); } export interface ListSchemasResponse { /** * <p>The schemas that match the request pattern. </p> */ Schemas?: string[]; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace ListSchemasResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSchemasResponse): any => ({ ...obj, }); } export interface ListStatementsRequest { /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; /** * <p>The maximum number of SQL statements to return in the response. * If more SQL statements exist than fit in one response, then <code>NextToken</code> is returned to page through the results. </p> */ MaxResults?: number; /** * <p>The name of the SQL statement specified as input to <code>BatchExecuteStatement</code> or <code>ExecuteStatement</code> to identify the query. * You can list multiple statements by providing a prefix that matches the beginning of the statement name. * For example, to list myStatement1, myStatement2, myStatement3, and so on, then provide the a value of <code>myStatement</code>. * Data API does a case-sensitive match of SQL statement names to the prefix value you provide. </p> */ StatementName?: string; /** * <p>The status of the SQL statement to list. Status values are defined as follows: </p> * <ul> * <li> * <p>ABORTED - The query run was stopped by the user. </p> * </li> * <li> * <p>ALL - A status value that includes all query statuses. This value can be used to filter results. </p> * </li> * <li> * <p>FAILED - The query run failed. </p> * </li> * <li> * <p>FINISHED - The query has finished running. </p> * </li> * <li> * <p>PICKED - The query has been chosen to be run. </p> * </li> * <li> * <p>STARTED - The query run has started. </p> * </li> * <li> * <p>SUBMITTED - The query was submitted, but not yet processed. </p> * </li> * </ul> */ Status?: StatusString | string; /** * <p>A value that filters which statements to return in the response. If true, all statements run by the caller's IAM role are returned. * If false, only statements run by the caller's IAM role in the current IAM session are returned. The default is true. </p> */ RoleLevel?: boolean; } export namespace ListStatementsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListStatementsRequest): any => ({ ...obj, }); } /** * <p>The SQL statement to run.</p> */ export interface StatementData { /** * <p>The SQL statement identifier. This value is a universally unique identifier (UUID) generated by Amazon Redshift Data API. </p> */ Id: string | undefined; /** * <p>The SQL statement.</p> */ QueryString?: string; /** * <p>One or more SQL statements. Each query string in the array corresponds to one of the queries in a batch query request.</p> */ QueryStrings?: string[]; /** * <p>The name or Amazon Resource Name (ARN) of the secret that enables access to the database. </p> */ SecretArn?: string; /** * <p>The status of the SQL statement. An * example is the that the SQL statement finished. * </p> */ Status?: StatusString | string; /** * <p>The name of the SQL statement. </p> */ StatementName?: string; /** * <p>The date and time (UTC) the statement was created. </p> */ CreatedAt?: Date; /** * <p>The date and time (UTC) that the statement metadata was last updated.</p> */ UpdatedAt?: Date; /** * <p>The parameters used in a SQL statement.</p> */ QueryParameters?: SqlParameter[]; /** * <p>A value that indicates whether the statement is a batch query request.</p> */ IsBatchStatement?: boolean; } export namespace StatementData { /** * @internal */ export const filterSensitiveLog = (obj: StatementData): any => ({ ...obj, }); } export interface ListStatementsResponse { /** * <p>The SQL statements. </p> */ Statements: StatementData[] | undefined; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace ListStatementsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListStatementsResponse): any => ({ ...obj, }); } export interface ListTablesRequest { /** * <p>The cluster identifier. This parameter is required when authenticating using either Secrets Manager or temporary credentials. </p> */ ClusterIdentifier: string | undefined; /** * <p>The name or ARN of the secret that enables access to the database. This parameter is required when authenticating using Secrets Manager. </p> */ SecretArn?: string; /** * <p>The database user name. This parameter is required when authenticating using temporary credentials. </p> */ DbUser?: string; /** * <p>The name of the database that contains the tables to list. * If <code>ConnectedDatabase</code> is not specified, this is also the database to connect to with your authentication credentials.</p> */ Database: string | undefined; /** * <p>A database name. The connected database is specified when you connect with your authentication credentials. </p> */ ConnectedDatabase?: string; /** * <p>A pattern to filter results by schema name. Within a schema pattern, "%" means match any * substring of 0 or more characters and "_" means match any one character. Only schema name * entries matching the search pattern are returned. If <code>SchemaPattern</code> is not specified, then all tables that match * <code>TablePattern</code> are returned. * If neither <code>SchemaPattern</code> or <code>TablePattern</code> are specified, then all tables are returned. </p> */ SchemaPattern?: string; /** * <p>A pattern to filter results by table name. Within a table pattern, "%" means match any * substring of 0 or more characters and "_" means match any one character. Only table name * entries matching the search pattern are returned. If <code>TablePattern</code> is not specified, then all tables that match * <code>SchemaPattern</code>are returned. * If neither <code>SchemaPattern</code> or <code>TablePattern</code> are specified, then all tables are returned. </p> */ TablePattern?: string; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; /** * <p>The maximum number of tables to return in the response. * If more tables exist than fit in one response, then <code>NextToken</code> is returned to page through the results. </p> */ MaxResults?: number; } export namespace ListTablesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTablesRequest): any => ({ ...obj, }); } /** * <p>The properties of a table. </p> */ export interface TableMember { /** * <p>The name of the table. </p> */ name?: string; /** * <p>The type of the table. Possible values include TABLE, VIEW, SYSTEM TABLE, GLOBAL * TEMPORARY, LOCAL TEMPORARY, ALIAS, and SYNONYM. </p> */ type?: string; /** * <p>The schema containing the table. </p> */ schema?: string; } export namespace TableMember { /** * @internal */ export const filterSensitiveLog = (obj: TableMember): any => ({ ...obj, }); } export interface ListTablesResponse { /** * <p>The tables that match the request pattern. </p> */ Tables?: TableMember[]; /** * <p>A value that indicates the starting point for the next set of response records in a subsequent request. If a value is returned in a response, you can retrieve the next set of records by providing this returned NextToken value in the next NextToken parameter and retrying the command. If the NextToken field is empty, all response records have been retrieved for the request. </p> */ NextToken?: string; } export namespace ListTablesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTablesResponse): any => ({ ...obj, }); }
the_stack
import { LayoutBase } from '../layout-base'; import { View, CSSType } from '../../core/view'; import { CssProperty, ShorthandProperty, makeParser, makeValidator, unsetValue } from '../../core/properties'; import { Style } from '../../styling/style'; export type Basis = 'auto' | number; export const ORDER_DEFAULT = 1; export const FLEX_GROW_DEFAULT = 0.0; export const FLEX_SHRINK_DEFAULT = 1.0; export type FlexDirection = 'row' | 'row-reverse' | 'column' | 'column-reverse'; export namespace FlexDirection { export const ROW = 'row'; export const ROW_REVERSE = 'row-reverse'; export const COLUMN = 'column'; export const COLUMN_REVERSE = 'column-reverse'; export const isValid = makeValidator<FlexDirection>(ROW, ROW_REVERSE, COLUMN, COLUMN_REVERSE); export const parse = makeParser<FlexDirection>(isValid); } export type FlexWrap = 'nowrap' | 'wrap' | 'wrap-reverse'; export namespace FlexWrap { export const NOWRAP = 'nowrap'; export const WRAP = 'wrap'; export const WRAP_REVERSE = 'wrap-reverse'; export const isValid = makeValidator<FlexWrap>(NOWRAP, WRAP, WRAP_REVERSE); export const parse = makeParser<FlexWrap>(isValid); } export type JustifyContent = 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around'; export namespace JustifyContent { export const FLEX_START = 'flex-start' as const; export const FLEX_END = 'flex-end' as const; export const CENTER = 'center' as const; export const SPACE_BETWEEN = 'space-between'; export const SPACE_AROUND = 'space-around'; export const isValid = makeValidator<JustifyContent>(FLEX_START, FLEX_END, CENTER, SPACE_BETWEEN, SPACE_AROUND); export const parse = makeParser<JustifyContent>(isValid); } export type FlexBasisPercent = number; export namespace FlexBasisPercent { export const DEFAULT = -1; } export type AlignItems = 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; export namespace AlignItems { export const FLEX_START = 'flex-start'; export const FLEX_END = 'flex-end'; export const CENTER = 'center'; export const BASELINE = 'baseline'; export const STRETCH = 'stretch'; export const isValid = makeValidator<AlignItems>(FLEX_START, FLEX_END, CENTER, BASELINE, STRETCH); export const parse = makeParser<AlignItems>(isValid); } export type AlignContent = 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'stretch'; export namespace AlignContent { export const FLEX_START = 'flex-start'; export const FLEX_END = 'flex-end'; export const CENTER = 'center'; export const SPACE_BETWEEN = 'space-between'; export const SPACE_AROUND = 'space-around'; export const STRETCH = 'stretch'; export const isValid = makeValidator<AlignContent>(FLEX_START, FLEX_END, CENTER, SPACE_BETWEEN, SPACE_AROUND, STRETCH); export const parse = makeParser<AlignContent>(isValid); } export type Order = number; export namespace Order { export function isValid(value): boolean { return isFinite(parseInt(value)); } export const parse = parseInt; } export type FlexGrow = number; export namespace FlexGrow { export function isValid(value: any): boolean { const parsed = parseInt(value); return isFinite(parsed) && value >= 0; } export const parse = parseFloat; } export type FlexShrink = number; export namespace FlexShrink { export function isValid(value: any): boolean { const parsed = parseInt(value); return isFinite(parsed) && value >= 0; } export const parse = parseFloat; } export type FlexWrapBefore = boolean; export namespace FlexWrapBefore { export function isValid(value) { if (typeof value === 'boolean') { return true; } if (typeof value === 'string') { const str = value.trim().toLowerCase(); return str === 'true' || str === 'false'; } return false; } export function parse(value: string): FlexWrapBefore { return value && value.toString().trim().toLowerCase() === 'true'; } } export type AlignSelf = 'auto' | AlignItems; export namespace AlignSelf { export const AUTO = 'auto'; export const FLEX_START = 'flex-start'; export const FLEX_END = 'flex-end'; export const CENTER = 'center'; export const BASELINE = 'baseline'; export const STRETCH = 'stretch'; export const isValid = makeValidator<AlignSelf>(AUTO, FLEX_START, FLEX_END, CENTER, BASELINE, STRETCH); export const parse = makeParser<AlignSelf>(isValid); } function validateArgs(element: View): View { if (!element) { throw new Error('element cannot be null or undefinied.'); } return element; } /** * A common base class for all cross platform flexbox layout implementations. */ @CSSType('FlexboxLayout') export abstract class FlexboxLayoutBase extends LayoutBase { get flexDirection(): FlexDirection { return this.style.flexDirection; } set flexDirection(value: FlexDirection) { this.style.flexDirection = value; } get flexWrap(): FlexWrap { return this.style.flexWrap; } set flexWrap(value: FlexWrap) { this.style.flexWrap = value; } get justifyContent(): JustifyContent { return this.style.justifyContent; } set justifyContent(value: JustifyContent) { this.style.justifyContent = value; } get alignItems(): AlignItems { return this.style.alignItems; } set alignItems(value: AlignItems) { this.style.alignItems = value; } get alignContent(): AlignContent { return this.style.alignContent; } set alignContent(value: AlignContent) { this.style.alignContent = value; } public static setOrder(view: View, order: number) { validateArgs(view).style.order = order; } public static getOrder(view: View): number { return validateArgs(view).style.order; } public static setFlexGrow(view: View, grow: number) { validateArgs(view).style.flexGrow = grow; } public static getFlexGrow(view: View) { return validateArgs(view).style.flexGrow; } public static setFlexShrink(view: View, shrink: number) { validateArgs(view).style.flexShrink = shrink; } public static getFlexShrink(view: View): number { return validateArgs(view).style.flexShrink; } public static setAlignSelf(view: View, align: AlignSelf) { validateArgs(view).style.alignSelf = align; } public static getAlignSelf(view: View): AlignSelf { return validateArgs(view).style.alignSelf; } public static setFlexWrapBefore(view: View, wrap: boolean) { validateArgs(view).style.flexWrapBefore = wrap; } public static getFlexWrapBefore(view: View): boolean { return validateArgs(view).style.flexWrapBefore; } } FlexboxLayoutBase.prototype.recycleNativeView = 'auto'; export const flexDirectionProperty = new CssProperty<Style, FlexDirection>({ name: 'flexDirection', cssName: 'flex-direction', defaultValue: FlexDirection.ROW, affectsLayout: global.isIOS, valueConverter: FlexDirection.parse, }); flexDirectionProperty.register(Style); export const flexWrapProperty = new CssProperty<Style, FlexWrap>({ name: 'flexWrap', cssName: 'flex-wrap', defaultValue: 'nowrap', affectsLayout: global.isIOS, valueConverter: FlexWrap.parse, }); flexWrapProperty.register(Style); export const justifyContentProperty = new CssProperty<Style, JustifyContent>({ name: 'justifyContent', cssName: 'justify-content', defaultValue: JustifyContent.FLEX_START, affectsLayout: global.isIOS, valueConverter: JustifyContent.parse, }); justifyContentProperty.register(Style); export const alignItemsProperty = new CssProperty<Style, AlignItems>({ name: 'alignItems', cssName: 'align-items', defaultValue: AlignItems.STRETCH, affectsLayout: global.isIOS, valueConverter: AlignItems.parse, }); alignItemsProperty.register(Style); export const alignContentProperty = new CssProperty<Style, AlignContent>({ name: 'alignContent', cssName: 'align-content', defaultValue: AlignContent.STRETCH, affectsLayout: global.isIOS, valueConverter: AlignContent.parse, }); alignContentProperty.register(Style); export const orderProperty = new CssProperty<Style, Order>({ name: 'order', cssName: 'order', defaultValue: ORDER_DEFAULT, valueConverter: Order.parse, }); orderProperty.register(Style); Object.defineProperty(View.prototype, 'order', { get(this: View): Order { return this.style.order; }, set(this: View, value: Order) { this.style.order = value; }, enumerable: true, configurable: true, }); export const flexGrowProperty = new CssProperty<Style, FlexGrow>({ name: 'flexGrow', cssName: 'flex-grow', defaultValue: FLEX_GROW_DEFAULT, valueConverter: FlexGrow.parse, }); flexGrowProperty.register(Style); Object.defineProperty(View.prototype, 'flexGrow', { get(this: View): FlexGrow { return this.style.flexGrow; }, set(this: View, value: FlexGrow) { this.style.flexGrow = value; }, enumerable: true, configurable: true, }); export const flexShrinkProperty = new CssProperty<Style, FlexShrink>({ name: 'flexShrink', cssName: 'flex-shrink', defaultValue: FLEX_SHRINK_DEFAULT, valueConverter: FlexShrink.parse, }); flexShrinkProperty.register(Style); Object.defineProperty(View.prototype, 'flexShrink', { get(this: View): FlexShrink { return this.style.flexShrink; }, set(this: View, value: FlexShrink) { this.style.flexShrink = value; }, enumerable: true, configurable: true, }); export const flexWrapBeforeProperty = new CssProperty<Style, FlexWrapBefore>({ name: 'flexWrapBefore', cssName: 'flex-wrap-before', defaultValue: false, valueConverter: FlexWrapBefore.parse, }); flexWrapBeforeProperty.register(Style); Object.defineProperty(View.prototype, 'flexWrapBefore', { get(this: View): FlexWrapBefore { return this.style.flexWrapBefore; }, set(this: View, value: FlexWrapBefore) { this.style.flexWrapBefore = value; }, enumerable: true, configurable: true, }); export const alignSelfProperty = new CssProperty<Style, AlignSelf>({ name: 'alignSelf', cssName: 'align-self', defaultValue: AlignSelf.AUTO, valueConverter: AlignSelf.parse, }); alignSelfProperty.register(Style); Object.defineProperty(View.prototype, 'alignSelf', { get(this: View): AlignSelf { return this.style.alignSelf; }, set(this: View, value: AlignSelf) { this.style.alignSelf = value; }, enumerable: true, configurable: true, }); // flex-flow: <flex-direction> || <flex-wrap> const flexFlowProperty = new ShorthandProperty<Style, string>({ name: 'flexFlow', cssName: 'flex-flow', getter: function (this: Style) { return `${this.flexDirection} ${this.flexWrap}`; }, converter: function (value: string) { const properties: [CssProperty<any, any>, any][] = []; if (value === unsetValue) { properties.push([flexDirectionProperty, value]); properties.push([flexWrapProperty, value]); } else { const trimmed = value && value.trim(); if (trimmed) { const values = trimmed.split(/\s+/); if (values.length >= 1 && FlexDirection.isValid(values[0])) { properties.push([flexDirectionProperty, FlexDirection.parse(values[0])]); } if (value.length >= 2 && FlexWrap.isValid(values[1])) { properties.push([flexWrapProperty, FlexWrap.parse(values[1])]); } } } return properties; }, }); flexFlowProperty.register(Style); // flex: inital | auto | none | <flex-grow> <flex-shrink> || <flex-basis> const flexProperty = new ShorthandProperty<Style, string>({ name: 'flex', cssName: 'flex', getter: function (this: Style) { return `${this.flexGrow} ${this.flexShrink}`; }, converter: function (value: string) { const properties: [CssProperty<any, any>, any][] = []; if (value === unsetValue) { properties.push([flexGrowProperty, value]); properties.push([flexShrinkProperty, value]); } else { const trimmed = value && value.trim(); if (trimmed) { const values = trimmed.split(/\s+/); if (values.length === 1) { switch (values[0]) { case 'inital': properties.push([flexGrowProperty, 0]); properties.push([flexShrinkProperty, 1]); // properties.push([flexBasisProperty, FlexBasis.AUTO]) break; case 'auto': properties.push([flexGrowProperty, 1]); properties.push([flexShrinkProperty, 1]); // properties.push([flexBasisProperty, FlexBasis.AUTO]) break; case 'none': properties.push([flexGrowProperty, 0]); properties.push([flexShrinkProperty, 0]); // properties.push([flexBasisProperty, FlexBasis.AUTO]) break; default: if (FlexGrow.isValid(values[0])) { properties.push([flexGrowProperty, FlexGrow.parse(values[0])]); properties.push([flexShrinkProperty, 1]); // properties.push([flexBasisProperty, 0]) } } } if (values.length >= 2) { if (FlexGrow.isValid(values[0]) && FlexShrink.isValid(values[1])) { properties.push([flexGrowProperty, FlexGrow.parse(values[0])]); properties.push([flexShrinkProperty, FlexShrink.parse(values[1])]); } } // if (value.length >= 3) { // properties.push({ property: flexBasisProperty, value: FlexBasis.parse(values[2])}) // } } } return properties; }, }); flexProperty.register(Style);
the_stack
import classnames from 'classnames' import React, { FormEventHandler, RefObject } from 'react' import { Button } from '@sourcegraph/wildcard' import { ErrorAlert } from '../../../../../../../../components/alerts' import { LoaderButton } from '../../../../../../../../components/LoaderButton' import { FormGroup } from '../../../../../../components/form/form-group/FormGroup' import { FormInput } from '../../../../../../components/form/form-input/FormInput' import { FormRadioInput } from '../../../../../../components/form/form-radio-input/FormRadioInput' import { useFieldAPI } from '../../../../../../components/form/hooks/useField' import { FORM_ERROR, SubmissionErrors } from '../../../../../../components/form/hooks/useForm' import { RepositoriesField } from '../../../../../../components/form/repositories-field/RepositoriesField' import { VisibilityPicker } from '../../../../../../components/visibility-picker/VisibilityPicker' import { SupportedInsightSubject } from '../../../../../../core/types/subjects' import { CreateInsightFormFields, EditableDataSeries } from '../../types' import { FormSeries } from '../form-series/FormSeries' import styles from './SearchInsightCreationForm.module.scss' interface CreationSearchInsightFormProps { /** This component might be used in edit or creation insight case. */ mode?: 'creation' | 'edit' innerRef: RefObject<any> handleSubmit: FormEventHandler submitErrors: SubmissionErrors submitting: boolean submitted: boolean className?: string isFormClearActive?: boolean title: useFieldAPI<CreateInsightFormFields['title']> repositories: useFieldAPI<CreateInsightFormFields['repositories']> allReposMode: useFieldAPI<CreateInsightFormFields['allRepos']> visibility: useFieldAPI<CreateInsightFormFields['visibility']> subjects: SupportedInsightSubject[] series: useFieldAPI<CreateInsightFormFields['series']> step: useFieldAPI<CreateInsightFormFields['step']> stepValue: useFieldAPI<CreateInsightFormFields['stepValue']> onCancel: () => void /** * Handler to listen latest value form particular series edit form * Used to get information for live preview chart. */ onSeriesLiveChange: (liveSeries: EditableDataSeries, isValid: boolean, index: number) => void /** * Handlers for CRUD operation over series. Add, delete, update and cancel * series edit form. */ onEditSeriesRequest: (openedCardIndex: number) => void onEditSeriesCommit: (seriesIndex: number, editedSeries: EditableDataSeries) => void onEditSeriesCancel: (closedCardIndex: number) => void onSeriesRemove: (removedSeriesIndex: number) => void onFormReset: () => void } /** * Displays creation code insight form (title, visibility, series, etc.) * UI layer only, all controlled data should be managed by consumer of this component. */ export const SearchInsightCreationForm: React.FunctionComponent<CreationSearchInsightFormProps> = props => { const { mode, innerRef, handleSubmit, submitErrors, submitting, submitted, title, repositories, allReposMode, visibility, subjects, series, stepValue, step, className, isFormClearActive, onCancel, onSeriesLiveChange, onEditSeriesRequest, onEditSeriesCommit, onEditSeriesCancel, onSeriesRemove, onFormReset, } = props const isEditMode = mode === 'edit' return ( // eslint-disable-next-line react/forbid-elements <form noValidate={true} ref={innerRef} onSubmit={handleSubmit} onReset={onFormReset} className={classnames(className, 'd-flex flex-column')} > <FormGroup name="insight repositories" title="Targeted repositories" subtitle="Create a list of repositories to run your search over" > <FormInput as={RepositoriesField} autoFocus={true} required={true} title="Repositories" description="Separate repositories with commas" placeholder={ allReposMode.input.value ? 'All repositories' : 'Example: github.com/sourcegraph/sourcegraph' } loading={repositories.meta.validState === 'CHECKING'} valid={repositories.meta.touched && repositories.meta.validState === 'VALID'} error={repositories.meta.touched && repositories.meta.error} {...repositories.input} className="mb-0 d-flex flex-column" /> <label className="d-flex flex-wrap align-items-center mb-2 mt-3 font-weight-normal"> <input type="checkbox" {...allReposMode.input} value="all-repos-mode" checked={allReposMode.input.value} /> <span className="pl-2">Run your insight over all your repositories</span> <small className="w-100 mt-2 text-muted"> This feature is actively in development. Read about the{' '} <a href="https://docs.sourcegraph.com/code_insights/explanations/current_limitations_of_code_insights" target="_blank" rel="noopener noreferrer" > beta limitations here. </a> </small> </label> <hr className={styles.creationInsightFormSeparator} /> </FormGroup> <FormGroup name="data series group" title="Data series" subtitle="Add any number of data series to your chart" error={series.meta.touched && series.meta.error} innerRef={series.input.ref} > <FormSeries series={series.input.value} isBackendInsightEdit={isEditMode && allReposMode.input.value} showValidationErrorsOnMount={submitted} onLiveChange={onSeriesLiveChange} onEditSeriesRequest={onEditSeriesRequest} onEditSeriesCommit={onEditSeriesCommit} onEditSeriesCancel={onEditSeriesCancel} onSeriesRemove={onSeriesRemove} /> </FormGroup> <hr className={styles.creationInsightFormSeparator} /> <FormGroup name="chart settings group" title="Chart settings"> <FormInput title="Title" required={true} description="Shown as the title for your insight" placeholder="Example: Migration to React function components" valid={title.meta.touched && title.meta.validState === 'VALID'} error={title.meta.touched && title.meta.error} {...title.input} className="d-flex flex-column" /> <VisibilityPicker subjects={subjects} value={visibility.input.value} labelClassName={styles.creationInsightFormGroupLabel} onChange={visibility.input.onChange} /> <FormGroup name="insight step group" title="Granularity: distance between data points" description="The prototype supports 7 datapoints, so your total x-axis timeframe is 6 times the distance between each point." error={stepValue.meta.touched && stepValue.meta.error} className="mt-4" labelClassName={styles.creationInsightFormGroupLabel} contentClassName="d-flex flex-wrap mb-n2" > <FormInput placeholder="ex. 2" required={true} type="number" min={1} {...stepValue.input} valid={stepValue.meta.touched && stepValue.meta.validState === 'VALID'} errorInputState={stepValue.meta.touched && stepValue.meta.validState === 'INVALID'} className={classnames(styles.creationInsightFormStepInput)} /> <FormRadioInput title="Hours" name="step" value="hours" checked={step.input.value === 'hours'} onChange={step.input.onChange} disabled={step.input.disabled} className="mr-3" /> <FormRadioInput title="Days" name="step" value="days" checked={step.input.value === 'days'} onChange={step.input.onChange} disabled={step.input.disabled} className="mr-3" /> <FormRadioInput title="Weeks" name="step" value="weeks" checked={step.input.value === 'weeks'} onChange={step.input.onChange} disabled={step.input.disabled} className="mr-3" /> <FormRadioInput title="Months" name="step" value="months" checked={step.input.value === 'months'} onChange={step.input.onChange} disabled={step.input.disabled} className="mr-3" /> <FormRadioInput title="Years" name="step" value="years" checked={step.input.value === 'years'} onChange={step.input.onChange} disabled={step.input.disabled} className="mr-3" /> </FormGroup> </FormGroup> <hr className={styles.creationInsightFormSeparator} /> <div className="d-flex flex-wrap align-items-center"> {submitErrors?.[FORM_ERROR] && <ErrorAlert className="w-100" error={submitErrors[FORM_ERROR]} />} <LoaderButton alwaysShowLabel={true} loading={submitting} label={submitting ? 'Submitting' : isEditMode ? 'Save insight' : 'Create code insight'} type="submit" disabled={submitting} data-testid="insight-save-button" className="btn btn-primary mr-2 mb-2" /> <Button type="button" variant="secondary" outline={true} className="mb-2 mr-auto" onClick={onCancel}> Cancel </Button> <Button type="reset" disabled={!isFormClearActive} variant="secondary" outline={true} className="border-0" > Clear all fields </Button> </div> </form> ) }
the_stack
import chalk from 'chalk'; import * as a from '../src/parser/ast'; import { tokenize } from '../src/lexer/'; import { parse } from '../src/parser/'; import { desugarBefore } from '../src/desugarer/'; import { Compose } from '../src/util'; import { checkExprType, checkBlockType, assertType, typeCheck, } from '../src/typechecker/'; import { TypeContext } from '../src/typechecker/context'; import { TypeError } from '../src/typechecker/error'; console.log(chalk.bold('Running typechecker tests...')); // complex type constructors const tupleType = (v: a.Tuple<a.Type<any>>) => new a.TupleType(v, -1, -1); const arrayType = (v: a.Type<any>) => new a.ArrayType(v, -1, -1); const funcType = (v: { param: a.Type<any>; return: a.Type<any> }) => new a.FuncType(v, -1, -1); const compileAST = Compose.then(tokenize) .then(parse) .then(desugarBefore).f; function exprTypeTest( exprStr: string, ctx: TypeContext, expectedType: a.Type<any>, shouldThrow?: string, ) { const moduleStr = `let x = ${exprStr}`; function failWith(errMsg: string) { console.error(chalk.blue.bold('Test:')); console.error(exprStr); console.error(); console.error(chalk.red.bold('Error:')); console.error(errMsg); process.exit(1); } try { const mod = compileAST(moduleStr); const actualType = checkExprType(mod.value.decls[0].value.expr, ctx); assertType(actualType, expectedType); } catch (err) { if ( shouldThrow && err instanceof TypeError && err.message.includes(shouldThrow) ) { return; } failWith(err); } if (shouldThrow) { failWith(`No error was thrown for '${shouldThrow}'`); } } function blockTypeTest( blockStr: string, ctx: TypeContext, expectedType: a.Type<any>, ) { const moduleStr = `let x = fn () ${expectedType.name} ${blockStr}`; try { const mod = compileAST(moduleStr); const fn = mod.value.decls[0].value.expr as a.FuncExpr; const actualType = checkBlockType(fn.value.body, ctx); assertType(actualType, expectedType); } catch (err) { console.error(chalk.blue.bold('Test:')); console.error(blockStr); console.error(); console.error(chalk.red.bold('Error:')); console.error(err); process.exit(1); } } function ctx(obj: Array<{ [name: string]: a.Type<any> }> = []): TypeContext { const ctx = new TypeContext(); for (const scopeObj of obj) { Object.keys(scopeObj).forEach(name => ctx.push({ ident: new a.Ident(name, -1, -1), type: scopeObj[name] }), ); } return ctx; } // literal exprTypeTest('123', ctx(), new a.IntType(0, 0)); exprTypeTest('.123', ctx(), new a.FloatType(0, 0)); exprTypeTest('"hello, world"', ctx(), new a.StrType(0, 0)); exprTypeTest('true', ctx(), new a.BoolType(0, 0)); exprTypeTest('false', ctx(), new a.BoolType(0, 0)); exprTypeTest("'\\n'", ctx(), new a.CharType(0, 0)); // ident exprTypeTest( 'some_ident', ctx([{ some_ident: a.IntType.instance }]), a.IntType.instance, ); exprTypeTest( 'some_ident', ctx([ {}, { other_ident: a.FloatType.instance }, { some_ident: a.IntType.instance }, {}, ]), a.IntType.instance, ); exprTypeTest( 'some_ident', ctx([ {}, { one_ident: a.IntType.instance }, { some_ident: a.StrType.instance }, {}, ]), a.StrType.instance, ); exprTypeTest( 'invalid_ident', ctx([ {}, { one_ident: a.IntType.instance }, { some_ident: a.StrType.instance }, {}, ]), a.StrType.instance, 'undefined identifier: found invalid_ident', ); // tuple exprTypeTest( '(123, hello, true)', ctx([{ hello: a.StrType.instance }]), tupleType({ size: 3, items: [a.IntType.instance, a.StrType.instance, a.BoolType.instance], }), ); exprTypeTest( '(123, hello, false)', ctx([{ hello: a.StrType.instance }]), tupleType({ size: 4, items: [ a.IntType.instance, a.StrType.instance, a.BoolType.instance, a.CharType.instance, ], }), 'Tuple length mismatch: expected (int, str, bool, char), found (int, str, bool)', ); exprTypeTest( '(1234, hello, true)', ctx([{ hello: a.StrType.instance }]), tupleType({ size: 3, items: [a.IntType.instance, a.CharType.instance, a.BoolType.instance], }), 'Type mismatch: expected (int, char, bool), found (int, str, bool)', ); // array exprTypeTest('[1, 2, 3, 4]', ctx(), arrayType(a.IntType.instance)); exprTypeTest('[]', ctx(), arrayType(a.IntType.instance)); exprTypeTest('[]', ctx(), arrayType(a.StrType.instance)); exprTypeTest( '[[1], [2, 3, 4], []]', ctx(), arrayType(arrayType(a.IntType.instance)), ); exprTypeTest( '[some_ident, 4]', ctx([{ some_ident: a.IntType.instance }]), arrayType(a.IntType.instance), ); exprTypeTest( '[some_ident, 4]', ctx([{ some_ident: a.IntType.instance }]), arrayType(a.StrType.instance), 'Type mismatch: expected [str], found [int]', ); exprTypeTest( '[some_ident, "str", 4]', ctx([{ some_ident: a.IntType.instance }]), arrayType(a.IntType.instance), 'Type mismatch: expected int, found str', ); // function exprTypeTest( 'fn (a int) bool { true }', ctx(), funcType({ param: a.IntType.instance, return: a.BoolType.instance, }), ); exprTypeTest( 'fn (a int, b str) bool { true }', ctx(), funcType({ param: tupleType({ size: 2, items: [a.IntType.instance, a.StrType.instance], }), return: a.BoolType.instance, }), ); exprTypeTest( "fn (a int, b str) bool -> char { fn (c bool) char { 'a' } }", ctx(), funcType({ param: tupleType({ size: 2, items: [a.IntType.instance, a.StrType.instance], }), return: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }), ); exprTypeTest( "fn (a str -> int) bool -> char { fn (c bool) char { 'a' } }", ctx(), funcType({ param: funcType({ param: a.StrType.instance, return: a.IntType.instance, }), return: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }), ); exprTypeTest( "fn (a float, b str -> int) bool -> char { fn (c bool) char { 'a' } }", ctx(), funcType({ param: tupleType({ size: 2, items: [ a.FloatType.instance, funcType({ param: a.StrType.instance, return: a.IntType.instance, }), ], }), return: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }), ); exprTypeTest( 'fn (a int, b str) bool { false }', ctx(), funcType({ param: tupleType({ size: 2, items: [a.CharType.instance, a.StrType.instance], }), return: a.BoolType.instance, }), 'Type mismatch: expected (char, str) -> bool, found (int, str) -> bool', ); exprTypeTest( "fn (a int, b str) bool -> char { fn (c bool) char { 'a' } }", ctx(), funcType({ param: tupleType({ size: 2, items: [a.IntType.instance, a.StrType.instance], }), return: funcType({ param: a.BoolType.instance, return: a.BoolType.instance, }), }), 'Type mismatch: expected (int, str) -> bool -> bool, found (int, str) -> bool -> char', ); exprTypeTest( "fn (a str -> int) bool -> char { fn (c bool) char { 'a' } }", ctx(), funcType({ param: funcType({ param: a.StrType.instance, return: a.BoolType.instance, }), return: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }), 'Type mismatch: expected (str -> bool) -> bool -> char, found (str -> int) -> bool -> char', ); exprTypeTest( 'fn (a int) bool {}', ctx(), funcType({ param: a.IntType.instance, return: a.BoolType.instance, }), 'Function return type mismatch: expected bool, found void', ); exprTypeTest( 'fn (a int) bool { a }', ctx(), funcType({ param: a.IntType.instance, return: a.BoolType.instance, }), 'Function return type mismatch: expected bool, found int', ); exprTypeTest( 'fn (a int) void { a }', ctx(), funcType({ param: a.IntType.instance, return: a.VoidType.instance, }), "Function return type mismatch, ';' may be missing: expected void, found int", ); exprTypeTest( 'fn (a int) void { a; }', ctx(), funcType({ param: a.IntType.instance, return: a.VoidType.instance, }), ); // call expr exprTypeTest('fn (a int, b int) int { a } (1, 2)', ctx(), a.IntType.instance); exprTypeTest('fn (a str) char { \'a\' } ("hello")', ctx(), a.CharType.instance); exprTypeTest( "fn (a str -> int) bool -> char { fn (c bool) char { 'a' } } (fn (a str) int { 1 })", ctx(), funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), ); exprTypeTest( 'f1(f2)', ctx([ { f1: funcType({ param: funcType({ param: a.StrType.instance, return: a.BoolType.instance, }), return: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }), f2: funcType({ param: a.StrType.instance, return: a.BoolType.instance, }), }, ]), funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), ); exprTypeTest( '"i am not callable"(1, \'c\')', ctx(), a.VoidType.instance, 'non-callable target: expected function, found str', ); exprTypeTest( "fn (a int, b int) int { a } (1, 'c')", ctx(), a.IntType.instance, 'Function parameter type mismatch: expected (int, int), found (int, char)', ); exprTypeTest( "fn (a str) char { 'a' } (.123)", ctx(), a.CharType.instance, 'Function parameter type mismatch: expected str, found float', ); // block blockTypeTest('{}', ctx(), a.VoidType.instance); blockTypeTest( ` { let x = fn () int { x() }; x() } `, ctx(), a.IntType.instance, ); blockTypeTest( ` { f(123); let y = f(g); h(y) } `, ctx([ { f: funcType({ param: a.IntType.instance, return: a.BoolType.instance, }), }, { g: a.IntType.instance }, { h: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }, ]), a.CharType.instance, ); blockTypeTest( ` { f(123); let y = f(g); h(y); } `, ctx([ { f: funcType({ param: a.IntType.instance, return: a.BoolType.instance, }), }, { g: a.IntType.instance }, { h: funcType({ param: a.BoolType.instance, return: a.CharType.instance, }), }, ]), a.VoidType.instance, ); // index expr exprTypeTest( 'arr[3]', ctx([{ arr: arrayType(a.IntType.instance) }]), a.IntType.instance, ); exprTypeTest('"hello"[3]', ctx(), a.CharType.instance); exprTypeTest('("hello", false, 123)[0]', ctx(), a.StrType.instance); exprTypeTest('("hello", false, 123)[1]', ctx(), a.BoolType.instance); exprTypeTest('("hello", false, 123)[2]', ctx(), a.IntType.instance); exprTypeTest( '("hello", false, 123)[3]', ctx(), a.VoidType.instance, 'Tuple index out of range: expected int < 3, found 3', ); exprTypeTest( 'arr[no_int]', ctx([ { arr: arrayType(a.IntType.instance), no_int: a.CharType.instance, }, ]), a.IntType.instance, 'Index type mismatch: expected int, found char', ); exprTypeTest( '"hello"[no_int]', ctx([{ no_int: a.CharType.instance }]), a.CharType.instance, 'Index type mismatch: expected int, found char', ); exprTypeTest( '("hello", false, 123)[i]', ctx([{ i: a.IntType.instance }]), a.VoidType.instance, 'Invalid tuple index: only int literal is allowed for tuple index: found expr', ); exprTypeTest( '("hello", false, 123)[no_int]', ctx([{ no_int: a.CharType.instance }]), a.VoidType.instance, 'Invalid tuple index: only int literal is allowed for tuple index: found expr', ); exprTypeTest( '3[0]', ctx(), a.VoidType.instance, 'Indexable type mismatch: expected array, str or tuple, found int', ); // cond expr exprTypeTest( 'if some_bool { 10 } else { 20 }', ctx([{ some_bool: a.BoolType.instance }]), a.IntType.instance, ); exprTypeTest( 'if f(123) { "hello" } else { "world" }', ctx([ { f: funcType({ param: a.IntType.instance, return: a.BoolType.instance }), }, ]), a.StrType.instance, ); exprTypeTest( 'if some_char { 10 } else { 20 }', ctx([{ some_char: a.CharType.instance }]), a.IntType.instance, 'Type mismatch: expected bool, found char', ); exprTypeTest( 'if some_bool { 10 } else { "hello" }', ctx([{ some_bool: a.BoolType.instance }]), a.IntType.instance, "'else' block should have the same type as 'if' block: expected int, found str", ); exprTypeTest( 'if some_bool { } else { "hello" }', ctx([{ some_bool: a.BoolType.instance }]), a.VoidType.instance, "'else' block should have the same type as 'if' block, ';' may be missing: expected void, found str", ); exprTypeTest( 'if some_bool { } else { "hello"; }', ctx([{ some_bool: a.BoolType.instance }]), a.VoidType.instance, ); // loop expr exprTypeTest( 'while true { f(123) }', ctx([ { f: funcType({ param: a.IntType.instance, return: a.BoolType.instance }), }, ]), a.VoidType.instance, ); exprTypeTest( 'while cond { f(123); }', ctx([ { cond: a.BoolType.instance, f: funcType({ param: a.IntType.instance, return: a.BoolType.instance }), }, ]), a.VoidType.instance, ); exprTypeTest( 'while true { if i > 10 { break } else { i = i + 1 } }', ctx([ { i: a.IntType.instance, }, ]), a.VoidType.instance, ); exprTypeTest( 'while i { if i > 10 { break } else { i = i + 1 } }', ctx([ { i: a.IntType.instance, }, ]), a.VoidType.instance, 'Loop condition should be a boolean: found int', ); exprTypeTest( 'if true { break } else { }', ctx([]), a.VoidType.instance, 'break can be only used in a loop: found unexpected break', ); // unary expr exprTypeTest( '+x', ctx([ { x: a.IntType.instance, }, ]), a.IntType.instance, ); exprTypeTest( '-x', ctx([ { x: a.IntType.instance, }, ]), a.IntType.instance, ); exprTypeTest( '+x', ctx([ { x: a.FloatType.instance, }, ]), a.FloatType.instance, ); exprTypeTest( '-x', ctx([ { x: a.FloatType.instance, }, ]), a.FloatType.instance, ); exprTypeTest( '!x', ctx([ { x: a.BoolType.instance, }, ]), a.BoolType.instance, ); exprTypeTest( '-x', ctx([ { x: a.BoolType.instance, }, ]), a.BoolType.instance, "Operand type mismatch for '-': expected int or float, found bool", ); exprTypeTest( '!x', ctx([ { x: a.IntType.instance, }, ]), a.IntType.instance, "Operand type mismatch for '!': expected bool, found int", ); // binary expr // eq op exprTypeTest('1 == 1', ctx(), a.BoolType.instance); exprTypeTest('"hello" != "hello"', ctx(), a.BoolType.instance); exprTypeTest( '"hello" == 3', ctx(), a.BoolType.instance, "Right-hand operand type mismatch for '==': expected str, found int", ); // comp op exprTypeTest('3.5 > .0', ctx(), a.BoolType.instance); exprTypeTest("'c' > 'a'", ctx(), a.BoolType.instance); exprTypeTest( "'c' < 3", ctx(), a.BoolType.instance, "Right-hand operand type mismatch for '<': expected char, found int", ); exprTypeTest( 'fn () void {} <= 3', ctx(), a.BoolType.instance, "Left-hand operand type mismatch for '<=': expected int, float, bool, char or str, found () -> void", ); // add & mul op exprTypeTest('3 + 0', ctx(), a.IntType.instance); exprTypeTest('3 * 123 / 13', ctx(), a.IntType.instance); exprTypeTest('3.5 + .0', ctx(), a.FloatType.instance); exprTypeTest('3.5 * .0 / 1.0', ctx(), a.FloatType.instance); exprTypeTest( '3.5 * 1 / 1.0', ctx(), a.FloatType.instance, "Right-hand operand type mismatch for '*': expected float, found int", ); exprTypeTest( '"4" | 1', ctx(), a.IntType.instance, "Left-hand operand type mismatch for '|': expected int, found str", ); // bool op exprTypeTest('true && false', ctx(), a.BoolType.instance); exprTypeTest('true || false', ctx(), a.BoolType.instance); exprTypeTest( '.1 || false', ctx(), a.BoolType.instance, "Left-hand operand type mismatch for '||': expected bool, found float", ); exprTypeTest( 'true && 1', ctx(), a.BoolType.instance, "Right-hand operand type mismatch for '&&': expected bool, found int", ); function typeCheckTest( program: string, context: TypeContext, shouldThrow?: string, ) { function failWith(errMsg: string) { console.error(chalk.blue.bold('Test:')); console.error(program); console.error(); console.error(chalk.red.bold('Error:')); console.error(errMsg); process.exit(1); } try { typeCheck(compileAST(program), context); } catch (err) { if ( shouldThrow && err instanceof TypeError && err.message.includes(shouldThrow) ) { return; } failWith(err); } if (shouldThrow) { failWith(`No error was thrown for '${shouldThrow}'`); } } typeCheckTest( ` let main = fn () void { print("hello, world!"); } `, ctx([ { print: funcType({ param: a.StrType.instance, return: a.VoidType.instance, }), }, ]), ); typeCheckTest( ` let fac = fn (n int) int { if (n == 1) { 1 } else { n * fac(n - 1) } } let main = fn () void { print(i2s(fac(10))); } `, ctx([ { print: funcType({ param: a.StrType.instance, return: a.VoidType.instance, }), i2s: funcType({ param: a.IntType.instance, return: a.StrType.instance }), }, ]), ); typeCheckTest( ` let fac = fn (n int) int { if (n == 1) { 1 } else { n * fac(n - 1) } } let print_int = fn (n int) void { print(i2s(n)) } let main = fn () void { print_int(fac(10)) } `, ctx([ { print: funcType({ param: a.StrType.instance, return: a.VoidType.instance, }), i2s: funcType({ param: a.IntType.instance, return: a.StrType.instance }), }, ]), ); typeCheckTest( ` let fac = fn (n int) int { if (n == 1) { 1 } else { n * fac(n - 1) } } let print_int = fn (n int, blah str) void { print(i2s(n)) } let main = fn () void { print_int(fac(10)) } `, ctx([ { print: funcType({ param: a.StrType.instance, return: a.VoidType.instance, }), i2s: funcType({ param: a.IntType.instance, return: a.StrType.instance }), }, ]), 'Function parameter type mismatch: expected (int, str), found int at 15:13', ); // no void decl tests typeCheckTest( ` let f = fn () void {} let x: void = f() `, ctx(), 'A decl type cannot contain void: found void at 3:1', ); typeCheckTest( ` let f = fn () void {} let x = f() `, ctx(), 'A decl type cannot contain void: found void at 3:1', ); typeCheckTest( ` let f = fn () void {} let x = (1, f()) `, ctx(), 'A decl type cannot contain void: found (int, void) at 3:1', ); typeCheckTest( ` let f = fn () void {} let x = (1, ("hello", f(), false)) `, ctx(), 'A decl type cannot contain void: found (int, (str, void, bool)) at 3:1', ); typeCheckTest( ` let f = fn () void {} let x = [f()] `, ctx(), 'A decl type cannot contain void: found [void] at 3:1', ); typeCheckTest( ` let f = fn () void { let x: void = f() } `, ctx(), 'A decl type cannot contain void: found void at 3:3', ); typeCheckTest( ` let f = fn () void { let x = f() } `, ctx(), 'A decl type cannot contain void: found void at 3:3', ); typeCheckTest( ` let f = fn () void { let x = (1, f()) } `, ctx(), 'A decl type cannot contain void: found (int, void) at 3:3', ); typeCheckTest( ` let f = fn () void { let x = (1, ("hello", f(), false)) } `, ctx(), 'A decl type cannot contain void: found (int, (str, void, bool)) at 3:3', ); typeCheckTest( ` let f = fn () void { let x = [f()] } `, ctx(), 'A decl type cannot contain void: found [void] at 3:3', ); // Assignments typeCheckTest( ` let f = fn () void { let x = 10; x = 2; } `, ctx(), ); typeCheckTest( ` let f = fn () void { let x = 10; x = 1.0; } `, ctx(), 'Type mismatch: expected int, found float', ); typeCheckTest( ` let f = fn () void { let x = (10, true); x[1] = false; } `, ctx(), ); typeCheckTest( ` let f = fn () void { let x = (10, true); x[1] = "hi"; } `, ctx(), 'Type mismatch: expected bool, found str', ); typeCheckTest( ` let f = fn () void { let x = (10, true); let y = 1; x[y] = "hi"; } `, ctx(), 'Invalid tuple index: only int literal is allowed for tuple index: found expr', ); typeCheckTest( ` let f = fn () void { let x = [1, 2, 3]; x[1] = 1234; } `, ctx(), ); typeCheckTest( ` let f = fn () void { let x = [1, 2, 3]; x[1] = true; } `, ctx(), 'Type mismatch: expected int, found bool', ); // new expr exprTypeTest('new int[10]', ctx(), arrayType(a.IntType.instance)); exprTypeTest( 'new int[l]', ctx([{ l: a.IntType.instance }]), arrayType(a.IntType.instance), ); exprTypeTest( 'new int[int(f)]', ctx([{ f: a.FloatType.instance }]), arrayType(a.IntType.instance), ); exprTypeTest( 'new int[c]', ctx([{ c: a.CharType.instance }]), arrayType(a.IntType.instance), 'Length type mismatch: expected int, found char', ); console.log(chalk.green.bold('Passed!'));
the_stack