text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as React from 'react'; import classNames from 'classnames'; import { connect, AppState, CodeSpace, RedrawMode, } from '../../appState'; import CodeSpaceStateViewer from '../CodeSpaceStateViewer'; import PathTrack from './PathTrack'; import { CellLine, Cursor } from '.'; import * as styles from './style.css'; import * as redrawModeStyle from './redraw-mode.css'; interface CodeSpaceProps { appState: AppState; redrawMode: RedrawMode; codeSpace: CodeSpace; onScroll: (scroll: { scrollTop: number, scrollLeft: number }) => void; initialScrollTop: number; initialScrollLeft: number; } interface CodeSpaceState { mouseOn: boolean; mouseDown: boolean; mouseX: number; mouseY: number; ghostCaretX: number; ghostCaretY: number; codeSpaceX: number; codeSpaceY: number; } export default connect<CodeSpaceProps, { appState: AppState, redrawMode: RedrawMode }>( appState => ({ appState, redrawMode: appState.specialMode as RedrawMode }), )(class RedrawModeCodeSpaceComponent extends React.Component<CodeSpaceProps, CodeSpaceState> { scrollElement: HTMLElement; codeSpaceElement: HTMLElement; mouseDragUpHandler: (e: MouseEvent) => void; mouseDragMoveHandler: (e: MouseEvent) => void; mouseDragShift: () => void; // mousemove ์ด๋ฒคํŠธ ์“ฐ๋กœํ‹€์„ ์œ„ํ•œ ์†์„ฑ raf: (() => void) | null; throttled: Map<(...args: any[]) => void, any[] | null>; constructor(props: CodeSpaceProps) { super(props); this.state = { mouseOn: false, mouseDown: false, mouseX: 0, mouseY: 0, ghostCaretX: 0, ghostCaretY: 0, codeSpaceX: 0, codeSpaceY: 0, }; } onMouseDragUp(_e: MouseEvent) { this.setState({ mouseDown: false }); this.removeMouseDragEventListeners(); } onMouseDragMove(e: MouseEvent) { const { appState, redrawMode, codeSpace, } = this.props; const [ mouseX, mouseY ] = [ e.clientX, e.clientY ]; const cellPos = this.getCellPosFromMousePos(mouseX, mouseY); switch (redrawMode.phase.type) { case 'select': selectPhaseLogic.move(cellPos, redrawMode, codeSpace, appState); break; case 'draw': drawPhaseLogic.move(cellPos, redrawMode, codeSpace, appState); break; } this.scrollToFocus(cellPos); } removeMouseDragEventListeners() { window.removeEventListener('mouseup', this.mouseDragUpHandler, true); window.removeEventListener('mousemove', this.mouseDragMoveHandler, true); } componentDidMount() { this.throttled = new Map(); this.raf = () => { try { for (let [handler, args] of this.throttled.entries()) { if (args) { handler.apply(this, args); // FIXME: delete ํ•ด์•ผํ•˜์ง€ ์•Š์œผ๋ ค๋‚˜ this.throttled.set(handler, null); } } } finally { this.raf && window.requestAnimationFrame(this.raf); } }; window.requestAnimationFrame(this.raf); this.mouseDragUpHandler = e => { this.onMouseDragUp(e); }; this.mouseDragMoveHandler = e => this.throttled.set(this.onMouseDragMove, [e]); this.mouseDragShift = () => this.props.appState.squareSelection(); this.scrollElement.scrollTo(this.props.initialScrollLeft, this.props.initialScrollTop); this.updateCodeSpacePosition(); } componentWillUnmount() { this.raf = null; this.removeMouseDragEventListeners(); } updateCodeSpacePosition() { const { left, top } = this.codeSpaceElement.getBoundingClientRect(); this.setState({ codeSpaceX: left, codeSpaceY: top, }); } getCellPosFromMousePos( mouseX: number, mouseY: number, codeSpaceX = this.state.codeSpaceX, codeSpaceY = this.state.codeSpaceY, ): CellPos { return { x: ((mouseX - codeSpaceX) / 30) | 0, y: ((mouseY - codeSpaceY) / 30) | 0, }; } updateGhostCaret(mouseX: number, mouseY: number, mouseOn: boolean) { this.setState(({ codeSpaceX, codeSpaceY }) => { const cellPos = this.getCellPosFromMousePos( mouseX, mouseY, codeSpaceX, codeSpaceY, ); return { mouseX, mouseY, mouseOn, ghostCaretX: cellPos.x, ghostCaretY: cellPos.y, }; }); } scrollToFocus(focus: CellPos) { let { scrollTop, scrollLeft, clientWidth, clientHeight } = this.scrollElement; const [ scrollBottom, scrollRight ] = [scrollTop + clientHeight, scrollLeft + clientWidth]; const [ focusTop, focusLeft ] = [ focus.y * 30, focus.x * 30 ]; const [ focusBottom, focusRight ] = [ focusTop + 30, focusLeft + 30 ]; if (scrollTop > focusTop) scrollTop = focusTop; if (scrollBottom < focusBottom) scrollTop = focusBottom - clientHeight; if (scrollLeft > focusLeft) scrollLeft = focusLeft; if (scrollRight < focusRight) scrollLeft = focusRight - clientWidth; Object.assign(this.scrollElement, { scrollTop, scrollLeft }); this.props.onScroll({ scrollTop, scrollLeft }); } renderSelectState(codeSpace: CodeSpace) { const { redrawMode } = this.props; const { phase } = redrawMode; const isSelectPhase = phase.type === 'select'; const { lastMoment } = phase.selectedPath; return <> { lastMoment && <Cursor x={lastMoment.p.x} y={lastMoment.p.y} className={classNames( redrawModeStyle.selectPhaseCursor, { [redrawModeStyle.fade]: !isSelectPhase }, )} /> } <PathTrack className={classNames( redrawModeStyle.selectPhasePathTrack, { [redrawModeStyle.fade]: !isSelectPhase }, )} path={phase.selectedPath} codeSpace={codeSpace} /> </>; } renderDrawState(codeSpace: CodeSpace) { const { redrawMode } = this.props; const { phase } = redrawMode; if (phase.type !== 'draw') return null; const { lastMoment } = phase.drawingPath; return <> { lastMoment && <Cursor x={lastMoment.p.x} y={lastMoment.p.y} className={redrawModeStyle.drawPhaseCursor} /> } <PathTrack className={redrawModeStyle.drawPhasePathTrack} path={phase.drawingPath} codeSpace={codeSpace} /> </>; } render() { const { appState, redrawMode, } = this.props; const { phase } = redrawMode; const codeSpace = phase.type === 'select' ? this.props.codeSpace : phase.drawingCodeSpace; const { mouseOn, mouseDown, ghostCaretX, ghostCaretY, } = this.state; return <div ref={scrollElement => this.scrollElement = scrollElement!} className={classNames(styles.codeSpaceScroll, { [styles.focus]: mouseDown, })} onScroll={() => { this.updateCodeSpacePosition(); this.updateGhostCaret( this.state.mouseX, this.state.mouseY, this.state.mouseOn, ); this.props.onScroll({ scrollTop: this.scrollElement.scrollTop, scrollLeft: this.scrollElement.scrollLeft, }); }} onMouseOverCapture={e => this.updateGhostCaret(e.clientX, e.clientY, true)} onMouseOutCapture={e => this.updateGhostCaret(e.clientX, e.clientY, false)} onMouseDownCapture={e => { const [ mouseX, mouseY ] = [ e.clientX, e.clientY ]; const { mouseDown } = this.state; const cellPos = this.getCellPosFromMousePos(mouseX, mouseY); switch (phase.type) { case 'select': selectPhaseLogic.down(cellPos, redrawMode, codeSpace, appState); break; case 'draw': drawPhaseLogic.down(cellPos, redrawMode, codeSpace, appState); break; } if (!mouseDown) { this.setState({ mouseDown: true }); window.addEventListener('mouseup', this.mouseDragUpHandler, true); window.addEventListener('mousemove', this.mouseDragMoveHandler, true); } }} onMouseMoveCapture={e => { const [ mouseX, mouseY ] = [ e.clientX, e.clientY ]; const { mouseOn } = this.state; this.throttled.set( this.updateGhostCaret, [mouseX, mouseY, mouseOn] ); }} > { this.renderSelectState(codeSpace) } { this.renderDrawState(codeSpace) } <CodeSpaceStateViewer codeSpace={codeSpace}> <div ref={codeSpaceElement => this.codeSpaceElement = codeSpaceElement!} className={styles.codeSpace} style={{ width: `calc(100% + ${ (codeSpace.width - 1) * 30 }px)`, height: `calc(100% + ${ (codeSpace.height - 1) * 30 }px)`, }} > { codeSpace.map( (codeLine, index) => <CellLine key={index} index={index} codeLine={codeLine}/> ) } </div> </CodeSpaceStateViewer> <div className={classNames(styles.ghostCaret, { [styles.on]: mouseOn && !mouseDown })} style={{ top: ghostCaretY * 30, left: ghostCaretX * 30, }} /> </div>; } }); interface CellPos { x: number; y: number; } interface PhaseLogic { down( cellPos: CellPos, redrawMode: RedrawMode, codeSpace: CodeSpace, appState: AppState, ): void; move( cellPos: CellPos, redrawMode: RedrawMode, codeSpace: CodeSpace, appState: AppState, ): void; } const selectPhaseLogic: PhaseLogic = { down(cellPos, redrawMode, codeSpace) { if (redrawMode.phase.type !== 'select') return; toggle: if (redrawMode.isSelected(cellPos)) { if (redrawMode.phase.selectedPath.moments.length !== 1) break toggle; const lastMoment = redrawMode.phase.selectedPath.lastMoment!; if (lastMoment.p.x !== cellPos.x) break toggle; if (lastMoment.p.y !== cellPos.y) break toggle; redrawMode.clearSelection(); } else { redrawMode.select(cellPos, codeSpace); } }, move(cellPos, redrawMode, codeSpace) { if (redrawMode.phase.type !== 'select') return; // TODO: ๋งˆ์šฐ์Šค๊ฐ€ ๋น ๋ฅด๊ฒŒ ๋“œ๋ž˜๊ทธ ๋˜์—ˆ์„ ๊ฒฝ์šฐ ์ค‘๊ฐ„ ์…€๋“ค๋„ ์ผ๊ด„ ์„ ํƒ๋˜๋„๋ก ์ฒ˜๋ฆฌ redrawMode.selectOrDeselect(cellPos, codeSpace); }, }; const drawPhaseLogic: PhaseLogic = { down(cellPos, redrawMode, _codeSpace, appState) { if (redrawMode.phase.type !== 'draw') return; toggle: if (redrawMode.phase.drawingPath.moments.length === 1) { const lastMoment = redrawMode.phase.selectedPath.lastMoment!; if (lastMoment.p.x !== cellPos.x) break toggle; if (lastMoment.p.y !== cellPos.y) break toggle; redrawMode.clearSelection(); return; } redrawMode.draw(cellPos, appState.spaceChars, appState.spaceFillChar); }, move(cellPos, redrawMode, _codeSpace, appState) { if (redrawMode.phase.type !== 'draw') return; // TODO: ๋งˆ์šฐ์Šค๊ฐ€ ๋น ๋ฅด๊ฒŒ ๋“œ๋ž˜๊ทธ ๋˜์—ˆ์„ ๊ฒฝ์šฐ ์ค‘๊ฐ„ ์…€๋“ค๋„ ์ผ๊ด„ ์„ ํƒ๋˜๋„๋ก ์ฒ˜๋ฆฌ // a star ์‚ฌ์šฉํ•  ๊ฒƒ redrawMode.drawOrErase(cellPos, appState.spaceChars, appState.spaceFillChar); }, };
the_stack
๏ปฟ//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormConversation_Form { interface tab_Details_Sections { Details: DevKit.Controls.Section; Details_section_4: DevKit.Controls.Section; Details_skills_5: DevKit.Controls.Section; tab_2_section_3: DevKit.Controls.Section; tab_2_section_4: DevKit.Controls.Section; } interface tab_Details extends DevKit.Controls.ITab { Section: tab_Details_Sections; } interface Tabs { Details: tab_Details; } interface Body { Tab: Tabs; /** Last agent assigned to the conversation */ msdyn_activeagentid: DevKit.Controls.Lookup; /** Unique identifier for Queue associated with Conversation. */ msdyn_cdsqueueid: DevKit.Controls.Lookup; /** Date and time when conversation was closed */ msdyn_closedon: DevKit.Controls.DateTime; /** Date and time when the activity was created. */ msdyn_createdon: DevKit.Controls.DateTime; /** Customer with which the activity is associated. */ msdyn_customer: DevKit.Controls.Lookup; /** Number of times conversation was escalated to Supervisor i.e. transferred to Supervisor */ msdyn_escalationcount: DevKit.Controls.Integer; /** Work stream associated to the conversation */ msdyn_liveworkstreamid: DevKit.Controls.Lookup; /** Date and time when conversation was last modified */ msdyn_modifiedon: DevKit.Controls.DateTime; /** Date and time when conversation status was last modified */ msdyn_statusupdatedon: DevKit.Controls.DateTime; /** Conversation Title */ msdyn_title: DevKit.Controls.String; /** Conversation Title */ msdyn_title_1: DevKit.Controls.String; /** Placeholder for Transcript Control */ msdyn_TranscriptControl: DevKit.Controls.String; /** Number of times the conversation was transferred */ msdyn_transfercount: DevKit.Controls.Integer; /** Unique identifier of the object with which the activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** State of the conversation record */ StateCode: DevKit.Controls.OptionSet; /** Reason for the status of the activity. */ StatusCode: DevKit.Controls.OptionSet; } interface Navigation { nav_msdyn_msdyn_ocliveworkitem_msdyn_cdsentityengagementctx_liveworkitemid: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_ocliveworkitem_msdyn_chatquestionnaireresponse: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_ocliveworkitem_msdyn_livechatengagementctx_liveworkitemid: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_ocliveworkitem_msdyn_ocliveworkitemcontextitem_ocliveworkitemid: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_ocliveworkitem_msdyn_ocsession_liveworkstreamid: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_ocliveworkitem_msdyn_transcript: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem } interface Grid { SessionDetails: DevKit.Controls.Grid; } } class FormConversation_Form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Conversation_Form * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Conversation_Form */ Body: DevKit.FormConversation_Form.Body; /** The Navigation of form Conversation_Form */ Navigation: DevKit.FormConversation_Form.Navigation; /** The Grid of form Conversation_Form */ Grid: DevKit.FormConversation_Form.Grid; } namespace FormCustomer_summary { interface tab_Details_Sections { Details_section_3: DevKit.Controls.Section; Details_section_4: DevKit.Controls.Section; tab_2_section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_KBSearch_Sections { tab_2_section_5: DevKit.Controls.Section; } interface tab_OCSearchRuntimeControl_Sections { tab_3_section_5: DevKit.Controls.Section; } interface tab_Details extends DevKit.Controls.ITab { Section: tab_Details_Sections; } interface tab_KBSearch extends DevKit.Controls.ITab { Section: tab_KBSearch_Sections; } interface tab_OCSearchRuntimeControl extends DevKit.Controls.ITab { Section: tab_OCSearchRuntimeControl_Sections; } interface Tabs { Details: tab_Details; KBSearch: tab_KBSearch; OCSearchRuntimeControl: tab_OCSearchRuntimeControl; } interface Body { Tab: Tabs; KBSearchcontrol: DevKit.Controls.WebResource; /** Field to bind conversation summary control */ msdyn_ConversationSummaryField: DevKit.Controls.String; /** Customer with which the activity is associated. */ msdyn_customer: DevKit.Controls.Lookup; /** Unique identifier for Case associated with Conversation. */ msdyn_IssueId: DevKit.Controls.Lookup; /** Field to bind Timelinewall control */ msdyn_TimelineControlField: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; OCSearchRuntimeControl: DevKit.Controls.IFrame; } interface quickForm_CustomerProfile_Body { Address1_City: DevKit.Controls.QuickView; PrimaryContactId: DevKit.Controls.QuickView; Telephone1: DevKit.Controls.QuickView; } interface quickForm_RecentCases_Body { } interface quickForm_IssueSnapshot_Body { PriorityCode: DevKit.Controls.QuickView; StateCode: DevKit.Controls.QuickView; SubjectId: DevKit.Controls.QuickView; } interface quickForm_CustomerProfile extends DevKit.Controls.IQuickView { Body: quickForm_CustomerProfile_Body; } interface quickForm_RecentCases extends DevKit.Controls.IQuickView { Body: quickForm_RecentCases_Body; } interface quickForm_IssueSnapshot extends DevKit.Controls.IQuickView { Body: quickForm_IssueSnapshot_Body; } interface QuickForm { CustomerProfile: quickForm_CustomerProfile; RecentCases: quickForm_RecentCases; IssueSnapshot: quickForm_IssueSnapshot; } } class FormCustomer_summary extends DevKit.IForm { /** * DynamicsCrm.DevKit form Customer_summary * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Customer_summary */ Body: DevKit.FormCustomer_summary.Body; /** The QuickForm of form Customer_summary */ QuickForm: DevKit.FormCustomer_summary.QuickForm; } class msdyn_ocliveworkitemApi { /** * DynamicsCrm.DevKit msdyn_ocliveworkitemApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Additional information provided by the external application as JSON. For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Actual duration of the activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Actual end time of the activity. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Actual start time of the activity. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Description of the activity. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Information regarding whether the activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information regarding whether the activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the activitypointer. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when last agent was assigned to the conversation */ msdyn_activeagentassignedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Last agent assigned to the conversation */ msdyn_activeagentid: DevKit.WebApi.LookupValue; /** Unique identifier for Queue associated with Conversation. */ msdyn_cdsqueueid: DevKit.WebApi.LookupValue; /** The channel(s) in the conversation. */ msdyn_channel: DevKit.WebApi.MultiOptionSetValue; /** Channel Provider Name. */ msdyn_channelproviderName: DevKit.WebApi.StringValue; /** Date and time when conversation was closed */ msdyn_closedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Field to bind conversation summary control */ msdyn_ConversationSummaryField: DevKit.WebApi.StringValue; /** Date and time when the activity was created. */ msdyn_createdon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_customer_msdyn_ocliveworkitem_account: DevKit.WebApi.LookupValue; msdyn_customer_msdyn_ocliveworkitem_contact: DevKit.WebApi.LookupValue; /** The language of the customer in this conversation. */ msdyn_customerlanguageid: DevKit.WebApi.LookupValue; /** The locale of the customer participated in this conversation. */ msdyn_customerlocale: DevKit.WebApi.StringValue; /** Customer Sentiment Label powered by Sentiment Service */ msdyn_customersentimentlabel: DevKit.WebApi.OptionSetValue; /** Look up to daily topic entity. */ msdyn_dailytopicid: DevKit.WebApi.LookupValue; /** Number of times conversation was escalated to Supervisor i.e. transferred to Supervisor */ msdyn_escalationcount: DevKit.WebApi.IntegerValue; /** Time when conversation was initiated */ msdyn_initiatedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Indicates if its an outbound Conversation */ msdyn_isoutbound: DevKit.WebApi.BooleanValue; /** Unique identifier for Case associated with Conversation. */ msdyn_IssueId: DevKit.WebApi.LookupValue; /** Last agent session */ msdyn_lastsessionid: DevKit.WebApi.LookupValue; /** Work stream associated to the conversation */ msdyn_liveworkstreamid: DevKit.WebApi.LookupValue; /** LiveWorkStream notification data provided as JSON. For internal use only. */ msdyn_liveworkstreamnotificationdata: DevKit.WebApi.StringValue; /** Date and time when conversation was last modified */ msdyn_modifiedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique Id of conversation */ msdyn_ocliveworkitemid: DevKit.WebApi.StringValue; /** Unique identifier for msdyn_omnichannelqueue associated with Conversation */ msdyn_queueid: DevKit.WebApi.LookupValue; /** Queue item associated with the conversation */ msdyn_queueitemid: DevKit.WebApi.LookupValue; /** Unique identifier of the routed record. */ msdyn_routableobjectid: DevKit.WebApi.LookupValue; /** Lookup for the Social Profile Entity Record. */ msdyn_socialprofileid: DevKit.WebApi.LookupValue; /** Date and time when conversation was started */ msdyn_startedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Date and time when conversation status was last modified */ msdyn_statusupdatedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Third Party Conversation */ msdyn_thirdpartyconversation: DevKit.WebApi.BooleanValue; /** Field to bind Timelinewall control */ msdyn_TimelineControlField: DevKit.WebApi.StringValue; /** Conversation Title */ msdyn_title: DevKit.WebApi.StringValue; /** Placeholder for Transcript Control */ msdyn_TranscriptControl: DevKit.WebApi.StringValue; /** Number of times the conversation was transferred */ msdyn_transfercount: DevKit.WebApi.IntegerValue; /** Work distribution mode of the associated work stream */ msdyn_workstreamworkdistributionmode: DevKit.WebApi.OptionSetValue; /** Date and time when conversation end */ msdyn_wrapupinitiatedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of the activity. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_account_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebooking_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebookingheader_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bulkoperation_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaign_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaignactivity_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contact_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contract_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlement_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlementtemplate_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_incident_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_new_interactionforemail_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_invoice_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgearticle_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgebaserecord_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_lead_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreement_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingrule_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_customerasset_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryjournal_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventorytransfer_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_payment_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentdetail_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentmethod_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentterm_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_playbookinstance_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalbum_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalcode_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_processnotes_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_productinventory_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_projectteam_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorder_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingincident_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservice_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_resourceterritory_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rma_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmaproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceipt_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmasubstatus_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtv_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_shipvia_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroup_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroupdetail_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timeoffrequest_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_warehouse_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorder_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderincident_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderproduct_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservice_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservicetask_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_opportunity_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_quote_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_salesorder_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_site_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_action_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_hostedapplication_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_nonhostedapplication_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_option_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_savedsession_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflowstep_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Scheduled duration of the activity, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Scheduled end time of the activity. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Scheduled start time of the activity. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of an associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** State of the conversation record */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the activity. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Subject associated with the activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the activitypointer. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace msdyn_ocliveworkitem { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum msdyn_channel { /** 192390000 */ Co_browse, /** 192350002 */ Custom, /** 192350000 */ Entity_Records, /** 192330000 */ Facebook, /** 192310000 */ LINE, /** 192360000 */ Live_chat, /** 19241000 */ Microsoft_Teams, /** 192400000 */ Screen_sharing, /** 192340000 */ SMS, /** 192350001 */ Twitter, /** 192380000 */ Video, /** 192370000 */ Voice, /** 192320000 */ WeChat, /** 192300000 */ WhatsApp } enum msdyn_customersentimentlabel { /** 0 */ NA, /** 8 */ Negative, /** 10 */ Neutral, /** 12 */ Positive, /** 9 */ Slightly_negative, /** 11 */ Slightly_positive, /** 7 */ Very_negative, /** 13 */ Very_positive } enum msdyn_workstreamworkdistributionmode { /** 192350001 */ Pick, /** 192350000 */ Push } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 1 */ Closed, /** 0 */ Open, /** 2 */ Resolved, /** 3 */ Scheduled, /** 4 */ Wrap_up_Deprecated } enum StatusCode { /** 2 */ Active, /** 4 */ Closed, /** 1 */ Open, /** 6 */ Resolved, /** 7 */ Scheduled, /** 3 */ Waiting, /** 5 */ Wrap_up } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Conversation Form','Customer summary'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Nullable } from "../../../shared/types"; import * as React from "react"; import { Classes, ButtonGroup, Button, NonIdealState, Tabs, TabId, Tab } from "@blueprintjs/core"; import GoldenLayout from "golden-layout"; import { Animation, IAnimatable, Node, Observer, Scene, SubMesh } from "babylonjs"; import { AbstractEditorPlugin, IEditorPluginProps } from "../../editor/tools/plugin"; import { Icon } from "../../editor/gui/icon"; import { Select } from "../../editor/gui/select"; import { Tools } from "../../editor/tools/tools"; import { ChartEditor, IChartEditorProps } from "./chart-editor"; import { TimelineEditor } from "./timeline/timeline"; import { AnimationsPanel } from "./animations-panel"; import { SelectedTab, SyncType } from "./tools/types"; import { AnimationObject } from "./tools/animation-object"; import { ISyncAnimatable, SyncTool } from "./tools/sync-tools"; import { AnimationTools } from "./tools/animation-to-dataset"; import "./inspectors/key-inspector"; import "./inspectors/animation-inspector"; export const title = "Animation Editor"; export interface IAnimationEditorPluginState { /** * Defines the reference to the selected animatable. */ selectedAnimatable: Nullable<IAnimatable & { name?: string; }>; /** * Defines the reference to the selected animation. */ selectedAnimation: Nullable<Animation>; /** * Defines the reference to the animatable. */ playingAnimatables: ISyncAnimatable[]; /** * Defines the synchronization type for animation when playing/moving time tracker. */ synchronizationType: SyncType; /** * Defines the Id of the selected tab. */ selectedTab: TabId; } export default class AnimationEditorPlugin extends AbstractEditorPlugin<IAnimationEditorPluginState> { private _timelineEditor: Nullable<TimelineEditor> = null; private _graphDiv: Nullable<HTMLDivElement> = null; private _graphAnimationsPanel: Nullable<AnimationsPanel> = null; private _chartEditor: Nullable<ChartEditor> = null; private _refHandler = { getTimelineEditor: (ref: TimelineEditor) => this._timelineEditor = ref, getGraphDiv: (ref: HTMLDivElement) => this._graphDiv = ref, getGraphAnimationsPanel: (ref: AnimationsPanel) => this._graphAnimationsPanel = ref, getChartEdior: (ref: ChartEditor) => this._chartEditor = ref, }; private _graphLayout: Nullable<GoldenLayout> = null; private _selectedNodeObserver: Nullable<Observer<Node>> = null; private _selectedSceneObserver: Nullable<Observer<Scene>> = null; private _selectedSubMeshObserver: Nullable<Observer<SubMesh>> = null; /** * Constructor. * @param props the component's props. */ public constructor(props: IEditorPluginProps) { super(props); this.state = { playingAnimatables: [], selectedAnimation: null, selectedAnimatable: null, selectedTab: SelectedTab.Graph, synchronizationType: SyncType.Scene, }; } /** * Renders the component. */ public render(): React.ReactNode { let noAnimatable: React.ReactNode; if (!this.state.selectedAnimatable) { noAnimatable = ( <NonIdealState icon="citation" title="No Animatable Selected." description={`Please first select a node in the scene to add/edit its animations.`} /> ); } return ( <div style={{ width: "100%", height: "100%", overflow: "hidden" }}> {noAnimatable} <div className={Classes.FILL} key="documentation-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px", visibility: (this.state.selectedAnimatable ? "visible" : "hidden") }}> <ButtonGroup className={Classes.DARK}> <Button small={true} disabled={this.state.selectedTab === SelectedTab.Timeline || this.state.selectedAnimation === null} text="Add Single Key" icon="key" onClick={() => this._handleAddKey(SyncType.Animation)} /> <Button small={true} disabled={this.state.selectedAnimation === null} text="Add Key" icon="key" onClick={() => this._handleAddKey()} /> </ButtonGroup> <ButtonGroup style={{ float: "right" }}> <Select items={[SyncType.Animation, SyncType.Object, SyncType.Scene]} text={`Sync type: ${this.state.synchronizationType}`} onChange={(v) => this._handleSyncTypeChanged(SyncType[v])} /> </ButtonGroup> </div> <div style={{ width: "100%", height: "calc(100% - 30px)", visibility: (this.state.selectedAnimatable ? "visible" : "hidden") }}> <div style={{ position: "relative", width: "100%", height: "100%" }}> <Tabs selectedTabId={this.state.selectedTab} renderActiveTabPanelOnly={false} onChange={(selectedTab) => this._handleTabChanged(selectedTab)} > <Tab id={SelectedTab.Timeline} title="Timeline (Beta)" panel={ <div style={{ position: "absolute", width: "100%", height: "100%" }}> <TimelineEditor ref={this._refHandler.getTimelineEditor} editor={this.editor} synchronizationType={this.state.synchronizationType} selectedAnimatable={this.state.selectedAnimatable} onUpdatedKey={() => this._chartEditor?.refresh()} onFrameChange={(v) => this._chartEditor?.setCurrentFrameValue(v)} /> </div> } /> <Tab id={SelectedTab.Graph} title="Graph" panel={ <div ref={this._refHandler.getGraphDiv} style={{ position: "absolute", width: "100%", height: "100%" }} ></div> } /> </Tabs> <ButtonGroup style={{ position: "relative", left: "50%", transform: "translate(-50%)", top: "-40px", marginTop: "-5px", padding: "5px", background: "#333333", borderRadius: "10px", borderWidth: "50px" }}> <Button disabled={!this.state.selectedAnimation || this.state.playingAnimatables.length > 0} icon={<Icon src="play.svg"/>} text="Play" onClick={() => this._handlePlayAnimation()} /> <Button disabled={this.state.playingAnimatables.length === 0} icon={<Icon src="square-full.svg" />} text="Stop" onClick={() => this._handleStopAnimation()} /> </ButtonGroup> </div> </div> </div> ); } /** * Called on the plugin is ready. */ public onReady(): void { // Build layout if (!this._graphDiv) { return; } this._graphLayout = new GoldenLayout({ settings: { showPopoutIcon: false, showCloseIcon: false, showMaximiseIcon: true, reorderEnabled: false, }, dimensions: { minItemWidth: 240, minItemHeight: 50 }, labels: { close: "Close", maximise: "Maximize", minimise: "Minimize" }, content: [ { type: "row", content: [ { type: "react-component", id: "animations-list", component: "animations-list", componentName: "Animations", title: "Animations", isClosable: false, width: 33, props: { ref: this._refHandler.getGraphAnimationsPanel, selectedAnimatable: this.state.selectedAnimatable, onSelectedAnimation: (a) => this._handleSelectedAnimation(a, true), } }, { type: "react-component", id: "graph", component: "graph", componentName: "Graph", title: "Graph", isClosable: false, props: { ref: this._refHandler.getChartEdior, editor: this.editor, synchronizationType: this.state.synchronizationType, onFrameChange: (v) => this._timelineEditor?.setCurrentFrameValue(v), } as IChartEditorProps }, ] }, ], }, jQuery(this._graphDiv)); this._graphLayout.registerComponent("animations-list", AnimationsPanel); this._graphLayout.registerComponent("graph", ChartEditor); this._graphLayout.init(); // Register events this._selectedNodeObserver = this.editor.selectedNodeObservable.add((n) => this._handleAnimatableSelected(n)); this._selectedSceneObserver = this.editor.selectedSceneObservable.add((s) => this._handleAnimatableSelected(s)); this._selectedSubMeshObserver = this.editor.selectedSubMeshObservable.add((sm) => this._handleAnimatableSelected(sm.getMesh())); } /** * Called on the plugin is closed. */ public onClose(): void { // Reset all this._chartEditor?.resetObjectToFirstFrame(); // Remove event listeners this.editor.selectedNodeObservable.remove(this._selectedNodeObserver); this.editor.selectedSceneObservable.remove(this._selectedSceneObserver); this.editor.selectedSubMeshObservable.remove(this._selectedSubMeshObserver); } /** * Called on the panel has been resized. * @param height the new height of the plugin's panel. */ public resize(width?: number, height?: number): void { setTimeout(() => { this._graphLayout?.updateSize(); if (width && height) { this._timelineEditor?.resize(height); } }, 0); } /** * Called on the user changed the current tab. */ private _handleTabChanged(selectedTab: TabId): void { this.setState({ selectedTab }); setTimeout(() => this.resize(), 0); this._timelineEditor?.chart?.update(0); this._chartEditor?.chart?.update(0); } /** * Called on the user changes the synchronzation type. */ private _handleSyncTypeChanged(synchronizationType: SyncType): void { this._chartEditor?.setSyncType(synchronizationType); this.setState({ synchronizationType }); } /** * Called on the user selected a node. */ private _handleAnimatableSelected(animatable: IAnimatable): void { if (this.state.selectedAnimatable === animatable || !animatable.animations) { return; } this.setState({ selectedAnimatable: animatable }); this._timelineEditor?.setAnimatable(animatable); this._graphAnimationsPanel?.setAnimatable(animatable); this._chartEditor?.setAnimatable(animatable); this._handleSelectedAnimation(animatable.animations[0] ?? null, false); } /** * Called on the user selects an animation. */ private _handleSelectedAnimation(animation: Nullable<Animation>, notifySelected: boolean): void { if (this.state.selectedAnimatable) { this._timelineEditor?.setAnimatable(this.state.selectedAnimatable); } this._chartEditor?.setAnimation(animation, true); this.setState({ selectedAnimation: animation }, () => { if (notifySelected) { this._handleEditAnimation(); } }); } /** * Called on the user wants to play the animation. */ private _handlePlayAnimation(): void { if (!this.state.selectedAnimatable || !this.state.selectedAnimation || !this._chartEditor?.timeTracker) { return; } const range = AnimationTools.GetFramesRange(this.state.selectedAnimation); let fromFrame = this._chartEditor.timeTracker.getValue(); if (fromFrame === range.max) { fromFrame = 0; } const animatables = SyncTool.PlayAnimation( fromFrame, this.state.synchronizationType, this.state.selectedAnimatable, this.state.selectedAnimation, this.editor.scene!, () => { this.setState({ playingAnimatables: [] }); }, ); this._chartEditor.playAnimation(fromFrame); this.setState({ playingAnimatables: animatables }); } /** * Called on the user wants to stop the animation. */ private _handleStopAnimation(): void { if (!this.state.playingAnimatables || !this.state.selectedAnimatable) { return; } this.state.playingAnimatables.forEach((a) => { a.animatable.stop(); this.editor.scene!.stopAnimation(a.object); }); if (this._chartEditor) { this._chartEditor.stopAnimation(); } this.setState({ playingAnimatables: [] }); } /** * Called on the user wants to edit the animation. */ private _handleEditAnimation(): void { if (!this.state.selectedAnimation) { return; } this.editor.inspector.setSelectedObject(new AnimationObject(this.state.selectedAnimation, () => { // Nothing to do at the moment })); } /** * Called on the user wants to add a new key. */ private _handleAddKey(syncType?: SyncType): void { if (!this._chartEditor?.timeTracker || !this.state.selectedAnimatable?.animations || !this.state.selectedAnimation) { return; } const frame = this._chartEditor.timeTracker.getValue(); let animations: Animation[] = []; switch (syncType ?? this.state.synchronizationType) { case SyncType.Animation: animations = [this.state.selectedAnimation]; break; case SyncType.Object: case SyncType.Scene: animations = this.state.selectedAnimatable.animations; break; } for (const animation of animations) { const property = Tools.GetProperty<any>(this.state.selectedAnimatable, animation.targetProperty); if (property === null) { return; } const keys = animation.getKeys(); const existingKey = keys.find((k) => k.frame === frame); let value: unknown = null; switch (animation.dataType) { case Animation.ANIMATIONTYPE_FLOAT: value = property; break; case Animation.ANIMATIONTYPE_VECTOR2: case Animation.ANIMATIONTYPE_VECTOR3: case Animation.ANIMATIONTYPE_COLOR3: case Animation.ANIMATIONTYPE_COLOR4: case Animation.ANIMATIONTYPE_QUATERNION: value = property.clone(); break; } if (value === null) { return; } if (existingKey) { existingKey.value = value; } else { keys.push({ frame, value }); keys.sort((a, b) => a.frame - b.frame); } } this._handleSelectedAnimation(this.state.selectedAnimation, false); } }
the_stack
import { HasProposedValue, ProposedOrPrevious, ProposedValueOf } from "../../src/chrono/Effect.js" import { ChronoGraph } from "../../src/chrono/Graph.js" import { CalculatedValueGen, CalculatedValueSync } from "../../src/chrono/Identifier.js" import { Revision } from "../../src/chrono/Revision.js" import { Transaction } from "../../src/chrono/Transaction.js" import { CalculationIterator } from "../../src/primitives/Calculation.js" declare const StartTest : any StartTest(t => { t.it('Lazy identifier, generators', async t => { const graph : ChronoGraph = ChronoGraph.new() const var1 = graph.variableNamed('var1', 0) const var2 = graph.variableNamed('var2', 1) const ident1 = graph.addIdentifier(CalculatedValueGen.new({ name : 'ident1', lazy : true, calculation : function * () { return (yield var1) + (yield var2) } })) const ident2 = graph.addIdentifier(CalculatedValueGen.new({ name : 'ident2', lazy : true, calculation : function * () { return (yield ident1) + 1 } })) const spy1 = t.spyOn(ident1, 'calculation') const spy2 = t.spyOn(ident2, 'calculation') graph.commit() t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) // ---------------- t.is(graph.read(ident1), 1, "Correct result calculated #1") t.expect(spy1).toHaveBeenCalled(1) t.expect(spy2).toHaveBeenCalled(0) // ---------------- spy1.reset() spy2.reset() t.is(graph.read(ident2), 2, "Correct result calculated #2") t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(1) // ---------------- spy1.reset() spy2.reset() t.is(graph.read(ident2), 2, "Correct result calculated #3") t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) // ---------------- spy1.reset() spy2.reset() graph.write(var1, 1) graph.commit() t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) t.is(graph.read(ident2), 3, "Correct result calculated #4") t.expect(spy1).toHaveBeenCalled(1) t.expect(spy2).toHaveBeenCalled(1) }) t.it('Lazy identifier, sync', async t => { const graph : ChronoGraph = ChronoGraph.new() const var1 = graph.variableNamed('var1', 0) const var2 = graph.variableNamed('var2', 1) const ident1 = graph.addIdentifier(CalculatedValueSync.new({ name : 'ident1', lazy : true, calculation : function (YIELD) { return YIELD(var1) + YIELD(var2) } })) const ident2 = graph.addIdentifier(CalculatedValueSync.new({ name : 'ident2', lazy : true, calculation : function (YIELD) { return YIELD(ident1) + 1 } })) const spy1 = t.spyOn(ident1, 'calculation') const spy2 = t.spyOn(ident2, 'calculation') graph.commit() t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) // ---------------- t.is(graph.read(ident1), 1, "Correct result calculated #1") t.expect(spy1).toHaveBeenCalled(1) t.expect(spy2).toHaveBeenCalled(0) // ---------------- spy1.reset() spy2.reset() t.is(graph.read(ident2), 2, "Correct result calculated #2") t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(1) // ---------------- spy1.reset() spy2.reset() t.is(graph.read(ident2), 2, "Correct result calculated #3") t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) // ---------------- spy1.reset() spy2.reset() graph.write(var1, 1) graph.commit() t.expect(spy1).toHaveBeenCalled(0) t.expect(spy2).toHaveBeenCalled(0) t.is(graph.read(ident2), 3, "Correct result calculated #4") t.expect(spy1).toHaveBeenCalled(1) t.expect(spy2).toHaveBeenCalled(1) }) t.it('Should not use stale deep history', async t => { const graph1 : ChronoGraph = ChronoGraph.new() const i1 = graph1.variableNamed('i1', 0) const i2 = graph1.variableNamed('i2', 1) const dispatcher = graph1.variableNamed('dispatcher', i1) const c1 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c1', lazy : true, calculation : function * () { return (yield (yield dispatcher)) + 1 } })) graph1.commit() t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, i1, 1 ], "Correct result calculated #1") // ---------------- const c1Spy = t.spyOn(c1, 'calculation') graph1.write(dispatcher, i2) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, i2, 2 ], "Correct result calculated #2") t.expect(c1Spy).toHaveBeenCalled(1) // ---------------- c1Spy.reset() graph1.write(i1, 10) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 10, 1, i2, 2 ], "Correct result calculated #3") t.expect(c1Spy).toHaveBeenCalled(0) }) t.it('Should be able to calculate lazy identifier that uses `ProposedOrPrevious`', async t => { const graph1 : ChronoGraph = ChronoGraph.new() const i1 = graph1.variableNamed('i1', 0) const i2 = graph1.variableNamed('i2', 1) const dispatcher = graph1.variableNamed('dispatcher', 'pure') const c1 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c1', lazy : true, calculation : function * () : CalculationIterator<number> { const dispatch : string = yield dispatcher if (dispatch === 'pure') { return (yield i1) + (yield i2) } else { return (yield ProposedOrPrevious) } } })) graph1.commit() t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, 'pure', 1 ], "Correct result calculated") // ---------------- const c1Spy = t.spyOn(c1, 'calculation') graph1.write(dispatcher, 'proposed') graph1.write(c1, 10) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, 'proposed', 10 ], "Correctly calculated lazy value") t.expect(c1Spy).toHaveBeenCalled(1) // ---------------- c1Spy.reset() graph1.write(i1, 10) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 10, 1, 'proposed', 10 ], "Correct result calculated") t.expect(c1Spy).toHaveBeenCalled(0) }) t.it('Should be able to calculate lazy identifier that uses `ProposedOrPrevious` - sync', async t => { const graph1 : ChronoGraph = ChronoGraph.new() const i1 = graph1.variableNamed('i1', 0) const i2 = graph1.variableNamed('i2', 1) const dispatcher = graph1.variableNamed('dispatcher', 'pure') const c1 = graph1.addIdentifier(CalculatedValueSync.new({ name : 'c1', lazy : true, calculation : function (YIELD) : number { const dispatch : string = YIELD(dispatcher) if (dispatch === 'pure') { return YIELD(i1) + YIELD(i2) } else { return YIELD(ProposedOrPrevious) } } })) graph1.commit() t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, 'pure', 1 ], "Correct result calculated") // ---------------- const c1Spy = t.spyOn(c1, 'calculation') graph1.write(dispatcher, 'proposed') graph1.write(c1, 10) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 0, 1, 'proposed', 10 ], "Correctly calculated lazy value") t.expect(c1Spy).toHaveBeenCalled(1) // ---------------- c1Spy.reset() graph1.write(i1, 10) graph1.commit() t.expect(c1Spy).toHaveBeenCalled(0) t.isDeeply([ i1, i2, dispatcher, c1 ].map(node => graph1.read(node)), [ 10, 1, 'proposed', 10 ], "Correct result calculated") t.expect(c1Spy).toHaveBeenCalled(0) }) t.it('Should calculate lazy identifiers in a batch', async t => { const graph1 : ChronoGraph = ChronoGraph.new() const i1 = graph1.variableNamed('i1', 0) const i2 = graph1.variableNamed('i2', 1) const c1 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c1', lazy : true, calculation : function * () : CalculationIterator<number> { return (yield i1) + (yield i2) } })) const c2 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c2', lazy : true, calculation : function * () : CalculationIterator<number> { return (yield c1) + 1 } })) const c3 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c3', lazy : true, calculation : function * () : CalculationIterator<number> { return (yield c2) + 1 } })) graph1.commit() t.isDeeply([ i1, i2, c1, c2, c3 ].map(node => graph1.read(node)), [ 0, 1, 1, 2, 3 ], "Correct result calculated") // ---------------- const c1Spy = t.spyOn(Transaction.prototype, 'calculateTransitionsStackSync') graph1.write(i1, 1) graph1.commit() // reading `c3` should calculate `c2` and `c1` inside the `calculateTransitionsStack` once, not as // separate calls for every lazy identifier t.isDeeply([ c3 ].map(node => graph1.read(node)), [ 4 ], "Correct result calculated") t.expect(c1Spy).toHaveBeenCalled(1) }) t.it('Should calculate lazy identifiers in the current transaction', async t => { const graph1 : ChronoGraph = ChronoGraph.new() const i1 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'i1', calculation : function * () : CalculationIterator<number> { return yield ProposedOrPrevious } })) const c1 = graph1.addIdentifier(CalculatedValueGen.new({ name : 'c1', lazy : true, calculation : function * () : CalculationIterator<number> { return (yield ProposedValueOf(i1)) != null ? 1 : 0 } })) graph1.commit() // ---------------- graph1.write(i1, 1) t.is(graph1.read(c1), 1) }) })
the_stack
import { call, fork, put, takeEvery } from 'redux-saga/effects'; import { ClientType } from '@colony/colony-js'; import { Action, ActionTypes } from '~redux/index'; import { putError, takeFrom, routeRedirect } from '~utils/saga/effects'; import { ProcessedColonyDocument, ProcessedColonyQuery, ProcessedColonyQueryVariables, RecoveryEventsForSessionQueryVariables, RecoveryEventsForSessionQuery, RecoveryEventsForSessionDocument, RecoveryRolesAndApprovalsForSessionQuery, RecoveryRolesAndApprovalsForSessionQueryVariables, RecoveryRolesAndApprovalsForSessionDocument, RecoverySystemMessagesForSessionQuery, RecoverySystemMessagesForSessionQueryVariables, RecoverySystemMessagesForSessionDocument, ActionsThatNeedAttentionQuery, ActionsThatNeedAttentionQueryVariables, ActionsThatNeedAttentionDocument, RecoveryRolesUsersQuery, RecoveryRolesUsersQueryVariables, RecoveryRolesUsersDocument, } from '~data/index'; import { ContextModule, TEMP_getContext } from '~context/index'; import { transactionReady, transactionPending, transactionAddParams, } from '../../../core/actionCreators'; import { createTransaction, getTxChannel, createTransactionChannels, } from '../../../core/sagas'; import { ipfsUpload } from '../../../core/sagas/ipfs'; function* enterRecoveryAction({ payload: { colonyAddress, walletAddress, colonyName, annotationMessage }, meta: { id: metaId, history }, meta, }: Action<ActionTypes.COLONY_ACTION_RECOVERY>) { let txChannel; try { const apolloClient = TEMP_getContext(ContextModule.ApolloClient); txChannel = yield call(getTxChannel, metaId); const batchKey = 'recoveryAction'; const { recoveryAction, annotateRecoveryAction, } = yield createTransactionChannels(metaId, [ 'recoveryAction', 'annotateRecoveryAction', ]); yield fork(createTransaction, recoveryAction.id, { context: ClientType.ColonyClient, methodName: 'enterRecoveryMode', identifier: colonyAddress, group: { key: batchKey, id: metaId, index: 0, }, ready: false, }); if (annotationMessage) { yield fork(createTransaction, annotateRecoveryAction.id, { context: ClientType.ColonyClient, methodName: 'annotateTransaction', identifier: colonyAddress, params: [], group: { key: batchKey, id: metaId, index: 1, }, ready: false, }); } yield takeFrom(recoveryAction.channel, ActionTypes.TRANSACTION_CREATED); if (annotationMessage) { yield takeFrom( annotateRecoveryAction.channel, ActionTypes.TRANSACTION_CREATED, ); } yield put(transactionReady(recoveryAction.id)); const { payload: { hash: txHash, blockNumber }, } = yield takeFrom( recoveryAction.channel, ActionTypes.TRANSACTION_HASH_RECEIVED, ); yield takeFrom(recoveryAction.channel, ActionTypes.TRANSACTION_SUCCEEDED); if (annotationMessage) { yield put(transactionPending(annotateRecoveryAction.id)); let ipfsHash = null; ipfsHash = yield call( ipfsUpload, JSON.stringify({ annotationMessage, }), ); yield put( transactionAddParams(annotateRecoveryAction.id, [txHash, ipfsHash]), ); yield put(transactionReady(annotateRecoveryAction.id)); yield takeFrom( annotateRecoveryAction.channel, ActionTypes.TRANSACTION_SUCCEEDED, ); } /* * Refesh the current colony data object */ yield apolloClient.query< ProcessedColonyQuery, ProcessedColonyQueryVariables >({ query: ProcessedColonyDocument, variables: { address: colonyAddress, }, fetchPolicy: 'network-only', }); /* * Refesh the current colony data object */ yield apolloClient.query< RecoveryRolesUsersQuery, RecoveryRolesUsersQueryVariables >({ query: RecoveryRolesUsersDocument, variables: { colonyAddress, endBlockNumber: blockNumber, }, }); /* * Refresh recovery events */ yield apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber, }, fetchPolicy: 'network-only', }); /* * Actions that need attention */ yield apolloClient.query< ActionsThatNeedAttentionQuery, ActionsThatNeedAttentionQueryVariables >({ query: ActionsThatNeedAttentionDocument, variables: { colonyAddress, walletAddress, }, fetchPolicy: 'network-only', }); yield put({ type: ActionTypes.COLONY_ACTION_RECOVERY_SUCCESS, meta, }); if (colonyName) { yield routeRedirect(`/colony/${colonyName}/tx/${txHash}`, history); } } catch (error) { return yield putError( ActionTypes.COLONY_ACTION_RECOVERY_ERROR, error, meta, ); } finally { txChannel.close(); } return null; } function* setStorageSlotValue({ payload: { colonyAddress, walletAddress, startBlock, storageSlotLocation, storageSlotValue, }, meta: { id: metaId }, meta, }: Action<ActionTypes.COLONY_ACTION_RECOVERY_SET_SLOT>) { let txChannel; try { if (!storageSlotLocation) { throw new Error( 'The storage slot location is required in order to update it', ); } if (!storageSlotValue) { throw new Error( 'The storage slot value is required in order to update it', ); } const apolloClient = TEMP_getContext(ContextModule.ApolloClient); txChannel = yield call(getTxChannel, metaId); const batchKey = 'setStorageSlot'; const { setStorageSlot } = yield createTransactionChannels(metaId, [ 'setStorageSlot', ]); yield fork(createTransaction, setStorageSlot.id, { context: ClientType.ColonyClient, methodName: 'setStorageSlotRecovery', identifier: colonyAddress, group: { key: batchKey, id: metaId, index: 0, }, params: [storageSlotLocation, storageSlotValue], ready: false, }); yield takeFrom(setStorageSlot.channel, ActionTypes.TRANSACTION_CREATED); yield put(transactionReady(setStorageSlot.id)); yield takeFrom(setStorageSlot.channel, ActionTypes.TRANSACTION_SUCCEEDED); /* * Refresh recovery events */ yield apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); /* * Refresh user approvals */ yield apolloClient.query< RecoveryRolesAndApprovalsForSessionQuery, RecoveryRolesAndApprovalsForSessionQueryVariables >({ query: RecoveryRolesAndApprovalsForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); /* * Refresh Actions that need attention */ yield apolloClient.query< ActionsThatNeedAttentionQuery, ActionsThatNeedAttentionQueryVariables >({ query: ActionsThatNeedAttentionDocument, variables: { colonyAddress, walletAddress, }, fetchPolicy: 'network-only', }); yield put({ type: ActionTypes.COLONY_ACTION_RECOVERY_SET_SLOT_SUCCESS, meta, }); } catch (error) { return yield putError( ActionTypes.COLONY_ACTION_RECOVERY_SET_SLOT_ERROR, error, meta, ); } finally { txChannel.close(); } return null; } function* approveExitRecovery({ payload: { colonyAddress, walletAddress, startBlock, scrollToRef }, meta: { id: metaId }, meta, }: Action<ActionTypes.COLONY_ACTION_RECOVERY_APPROVE>) { let txChannel; try { const apolloClient = TEMP_getContext(ContextModule.ApolloClient); txChannel = yield call(getTxChannel, metaId); const batchKey = 'approveExit'; const { approveExit } = yield createTransactionChannels(metaId, [ 'approveExit', ]); yield fork(createTransaction, approveExit.id, { context: ClientType.ColonyClient, methodName: 'approveExitRecovery', identifier: colonyAddress, group: { key: batchKey, id: metaId, index: 0, }, params: [], ready: false, }); yield takeFrom(approveExit.channel, ActionTypes.TRANSACTION_CREATED); yield put(transactionReady(approveExit.id)); yield takeFrom(approveExit.channel, ActionTypes.TRANSACTION_SUCCEEDED); /* * Refresh recovery events */ yield apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); /* * Refresh user approvals */ yield apolloClient.query< RecoveryRolesAndApprovalsForSessionQuery, RecoveryRolesAndApprovalsForSessionQueryVariables >({ query: RecoveryRolesAndApprovalsForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); /* * Refresh system messages */ yield apolloClient.query< RecoverySystemMessagesForSessionQuery, RecoverySystemMessagesForSessionQueryVariables >({ query: RecoverySystemMessagesForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); /* * Refresh Actions that need attention */ yield apolloClient.query< ActionsThatNeedAttentionQuery, ActionsThatNeedAttentionQueryVariables >({ query: ActionsThatNeedAttentionDocument, variables: { colonyAddress, walletAddress, }, fetchPolicy: 'network-only', }); yield put({ type: ActionTypes.COLONY_ACTION_RECOVERY_APPROVE_SUCCESS, meta, }); /* * This is such a HACKY WAY to do this... * * We're scrolling to the bottom of the page because the `ActionButton` * internal logic is broken, and doesn't trigger `onSuccess` after the * correct action has been dispatch * * Instead it triggers it randomly which breaks *something* in React internal's * rendering logic so that it won't find the element to scroll to anymore * * But this way suprisingly works, as it will fire it at the end of the saga * where everything else is cleaned up. * * As long as we're aware of it, it's not really such a big deal */ scrollToRef?.current?.scrollIntoView({ behavior: 'smooth' }); } catch (error) { return yield putError( ActionTypes.COLONY_ACTION_RECOVERY_APPROVE_ERROR, error, meta, ); } finally { txChannel.close(); } return null; } function* exitRecoveryMode({ payload: { colonyAddress, startBlock, scrollToRef }, meta: { id: metaId }, meta, }: Action<ActionTypes.COLONY_ACTION_RECOVERY_APPROVE>) { let txChannel; try { const apolloClient = TEMP_getContext(ContextModule.ApolloClient); txChannel = yield call(getTxChannel, metaId); const batchKey = 'exitRecovery'; const { exitRecovery } = yield createTransactionChannels(metaId, [ 'exitRecovery', ]); yield fork(createTransaction, exitRecovery.id, { context: ClientType.ColonyClient, methodName: 'exitRecoveryMode', identifier: colonyAddress, group: { key: batchKey, id: metaId, index: 0, }, params: [], ready: false, }); yield takeFrom(exitRecovery.channel, ActionTypes.TRANSACTION_CREATED); yield put(transactionReady(exitRecovery.id)); yield takeFrom(exitRecovery.channel, ActionTypes.TRANSACTION_SUCCEEDED); /* * Refresh recovery events */ yield apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber: startBlock, }, fetchPolicy: 'network-only', }); yield put({ type: ActionTypes.COLONY_ACTION_RECOVERY_APPROVE_SUCCESS, meta, }); /* * This is such a HACKY WAY to do this... * * We're scrolling to the bottom of the page because the `ActionButton` * internal logic is broken, and doesn't trigger `onSuccess` after the * correct action has been dispatch * * Instead it triggers it randomly which breaks *something* in React internal's * rendering logic so that it won't find the element to scroll to anymore * * But this way suprisingly works, as it will fire it at the end of the saga * where everything else is cleaned up. * * As long as we're aware of it, it's not really such a big deal */ scrollToRef?.current?.scrollIntoView({ behavior: 'smooth' }); } catch (error) { return yield putError( ActionTypes.COLONY_ACTION_RECOVERY_APPROVE_ERROR, error, meta, ); } finally { txChannel.close(); } return null; } export default function* enterRecoveryActionSaga() { yield takeEvery(ActionTypes.COLONY_ACTION_RECOVERY, enterRecoveryAction); yield takeEvery( ActionTypes.COLONY_ACTION_RECOVERY_SET_SLOT, setStorageSlotValue, ); yield takeEvery( ActionTypes.COLONY_ACTION_RECOVERY_APPROVE, approveExitRecovery, ); yield takeEvery(ActionTypes.COLONY_ACTION_RECOVERY_EXIT, exitRecoveryMode); }
the_stack
Copyright (C) 1992 Clarendon Hill Software. Permission is granted to any individual or institution to use, copy, or redistribute this software, provided this copyright notice is retained. This software is provided "as is" without any expressed or implied warranty. If this software brings on any sort of damage -- physical, monetary, emotional, or brain -- too bad. You've got no one to blame but yourself. The software may be modified for your own purposes, but modified versions must retain this notice. *** Copyright (c) 1996-2020, Timothy P. Mann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Original Model I character set. */ const GLYPH_CG1 = [ 0x00,0x1f,0x11,0x11,0x11,0x11,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x1f,0x00,0x00,0x00,0x00, 0x00,0x10,0x10,0x10,0x10,0x10,0x10,0x1f,0x00,0x00,0x00,0x00, 0x00,0x02,0x04,0x08,0x1e,0x04,0x08,0x10,0x00,0x00,0x00,0x00, 0x00,0x1f,0x11,0x1b,0x15,0x1b,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x08,0x05,0x03,0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x1f,0x0a,0x0a,0x1b,0x00,0x00,0x00,0x00, 0x00,0x04,0x02,0x0f,0x12,0x14,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x08,0x1f,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x1f,0x00,0x00,0x1f,0x00,0x00,0x1f,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x04,0x15,0x0e,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x15,0x0e,0x04,0x15,0x0e,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x02,0x1f,0x02,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x1b,0x15,0x1b,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x15,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x1f,0x11,0x11,0x1f,0x11,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x0e,0x15,0x15,0x1d,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x1d,0x15,0x15,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x17,0x15,0x15,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x15,0x15,0x17,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x14,0x08,0x15,0x03,0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x0e,0x0a,0x0a,0x0a,0x0a,0x0a,0x1b,0x00,0x00,0x00,0x00, 0x00,0x10,0x10,0x10,0x1f,0x10,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x1f,0x11,0x0a,0x04,0x0a,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x0e,0x0e,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x01,0x02,0x04,0x00,0x04,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x1f,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x1f,0x15,0x15,0x17,0x11,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x11,0x11,0x17,0x15,0x15,0x1f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x11,0x11,0x1d,0x15,0x15,0x1f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x15,0x15,0x1d,0x11,0x11,0x1f,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x04,0x04,0x04,0x00,0x04,0x00,0x00,0x00,0x00, 0x00,0x0a,0x0a,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x0a,0x0a,0x1f,0x0a,0x1f,0x0a,0x0a,0x00,0x00,0x00,0x00, 0x00,0x04,0x1e,0x05,0x0e,0x14,0x0f,0x04,0x00,0x00,0x00,0x00, 0x00,0x03,0x13,0x08,0x04,0x02,0x19,0x18,0x00,0x00,0x00,0x00, 0x00,0x02,0x05,0x05,0x02,0x15,0x09,0x16,0x00,0x00,0x00,0x00, 0x00,0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x08,0x04,0x02,0x02,0x02,0x04,0x08,0x00,0x00,0x00,0x00, 0x00,0x02,0x04,0x08,0x08,0x08,0x04,0x02,0x00,0x00,0x00,0x00, 0x00,0x04,0x15,0x0e,0x1f,0x0e,0x15,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x04,0x1f,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x08,0x04,0x02,0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x19,0x15,0x13,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x04,0x06,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x10,0x0e,0x01,0x01,0x1f,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x10,0x0c,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x08,0x0c,0x0a,0x09,0x1f,0x08,0x08,0x00,0x00,0x00,0x00, 0x00,0x1f,0x01,0x0f,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0c,0x02,0x01,0x0f,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x1f,0x10,0x08,0x04,0x02,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x1e,0x10,0x08,0x06,0x00,0x00,0x00,0x00, 0x00,0x00,0x06,0x06,0x00,0x06,0x06,0x00,0x00,0x00,0x00,0x00, 0x00,0x06,0x06,0x00,0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00, 0x00,0x08,0x04,0x02,0x01,0x02,0x04,0x08,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x1f,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x02,0x04,0x08,0x10,0x08,0x04,0x02,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x10,0x08,0x04,0x00,0x04,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x10,0x16,0x15,0x15,0x0e,0x00,0x00,0x00,0x00, 0x00,0x04,0x0a,0x11,0x11,0x1f,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x0f,0x12,0x12,0x0e,0x12,0x12,0x0f,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x01,0x01,0x01,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0f,0x12,0x12,0x12,0x12,0x12,0x0f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x01,0x01,0x07,0x01,0x01,0x1f,0x00,0x00,0x00,0x00, 0x00,0x1f,0x01,0x01,0x07,0x01,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x1e,0x01,0x01,0x19,0x11,0x11,0x1e,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00, 0x00,0x10,0x10,0x10,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x11,0x09,0x05,0x03,0x05,0x09,0x11,0x00,0x00,0x00,0x00, 0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x1f,0x00,0x00,0x00,0x00, 0x00,0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x11,0x13,0x15,0x19,0x11,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0f,0x11,0x11,0x0f,0x01,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x11,0x11,0x15,0x09,0x16,0x00,0x00,0x00,0x00, 0x00,0x0f,0x11,0x11,0x0f,0x05,0x09,0x11,0x00,0x00,0x00,0x00, 0x00,0x0e,0x11,0x01,0x0e,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x11,0x0a,0x0a,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x11,0x11,0x15,0x1b,0x11,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x1f,0x10,0x08,0x04,0x02,0x01,0x1f,0x00,0x00,0x00,0x00, 0x00,0x04,0x0e,0x15,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x04,0x04,0x15,0x0e,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x02,0x1f,0x02,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x08,0x1f,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00, 0x00,0x0c,0x0c,0x04,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x0e,0x10,0x1e,0x11,0x1e,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x01,0x01,0x0d,0x13,0x11,0x13,0x0d,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0e,0x11,0x01,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x10,0x10,0x16,0x19,0x11,0x19,0x16,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0e,0x11,0x1f,0x01,0x0e,0x00,0x00,0x00,0x00, 0x00,0x08,0x14,0x04,0x0e,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x16,0x19,0x19,0x16,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x01,0x01,0x0d,0x13,0x11,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x04,0x00,0x06,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00, 0x00,0x10,0x00,0x10,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x01,0x01,0x09,0x05,0x03,0x05,0x09,0x00,0x00,0x00,0x00, 0x00,0x06,0x04,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0b,0x15,0x15,0x15,0x15,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0d,0x13,0x11,0x11,0x11,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0e,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x0d,0x13,0x11,0x13,0x0d,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x16,0x19,0x11,0x19,0x16,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x0d,0x13,0x01,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x1e,0x01,0x0e,0x10,0x0f,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x1f,0x04,0x04,0x14,0x08,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x11,0x11,0x11,0x19,0x16,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x11,0x11,0x11,0x0a,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x11,0x11,0x15,0x15,0x0a,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x11,0x0a,0x04,0x0a,0x11,0x00,0x00,0x00,0x00, 0x00,0x11,0x11,0x11,0x1e,0x10,0x11,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x1f,0x08,0x04,0x02,0x1f,0x00,0x00,0x00,0x00, 0x00,0x08,0x04,0x04,0x02,0x04,0x04,0x08,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x04,0x00,0x04,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x02,0x04,0x04,0x08,0x04,0x04,0x02,0x00,0x00,0x00,0x00, 0x00,0x02,0x15,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x0a,0x15,0x0a,0x15,0x0a,0x15,0x0a,0x00,0x00,0x00,0x00, ]; /** * Model I character set with official Radio Shack upgrade. */ const GLYPH_CG2 = [ 0x0e,0x11,0x10,0x16,0x15,0x15,0x0e,0x00,0x00,0x00,0x00,0x00, 0x04,0x0a,0x11,0x11,0x1f,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0f,0x12,0x12,0x0e,0x12,0x12,0x0f,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x01,0x01,0x01,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0f,0x12,0x12,0x12,0x12,0x12,0x0f,0x00,0x00,0x00,0x00,0x00, 0x1f,0x01,0x01,0x07,0x01,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x1f,0x01,0x01,0x07,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x1e,0x01,0x01,0x19,0x11,0x11,0x1e,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x10,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x11,0x09,0x05,0x03,0x05,0x09,0x11,0x00,0x00,0x00,0x00,0x00, 0x01,0x01,0x01,0x01,0x01,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x13,0x15,0x19,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0f,0x11,0x11,0x0f,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x11,0x15,0x09,0x16,0x00,0x00,0x00,0x00,0x00, 0x0f,0x11,0x11,0x0f,0x05,0x09,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x01,0x0e,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x0a,0x0a,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x11,0x15,0x1b,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x1f,0x10,0x08,0x04,0x02,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x04,0x0e,0x15,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x04,0x04,0x15,0x0e,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x02,0x1f,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x08,0x1f,0x08,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x04,0x04,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x00, 0x0a,0x0a,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x0a,0x0a,0x1f,0x0a,0x1f,0x0a,0x0a,0x00,0x00,0x00,0x00,0x00, 0x04,0x1e,0x05,0x0e,0x14,0x0f,0x04,0x00,0x00,0x00,0x00,0x00, 0x03,0x13,0x08,0x04,0x02,0x19,0x18,0x00,0x00,0x00,0x00,0x00, 0x02,0x05,0x05,0x02,0x15,0x09,0x16,0x00,0x00,0x00,0x00,0x00, 0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x08,0x04,0x02,0x02,0x02,0x04,0x08,0x00,0x00,0x00,0x00,0x00, 0x02,0x04,0x08,0x08,0x08,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x04,0x15,0x0e,0x1f,0x0e,0x15,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x1f,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x00,0x00,0x00,0x00,0x00, 0x00,0x10,0x08,0x04,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x19,0x15,0x13,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x04,0x06,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x10,0x0e,0x01,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x10,0x0c,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x08,0x0c,0x0a,0x09,0x1f,0x08,0x08,0x00,0x00,0x00,0x00,0x00, 0x1f,0x01,0x0f,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0c,0x02,0x01,0x0f,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x1f,0x10,0x08,0x04,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x1e,0x10,0x08,0x06,0x00,0x00,0x00,0x00,0x00, 0x00,0x06,0x06,0x00,0x06,0x06,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x06,0x06,0x00,0x06,0x06,0x02,0x01,0x00,0x00,0x00,0x00, 0x08,0x04,0x02,0x01,0x02,0x04,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x1f,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x02,0x04,0x08,0x10,0x08,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x10,0x08,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x10,0x16,0x15,0x15,0x0e,0x00,0x00,0x00,0x00,0x00, 0x04,0x0a,0x11,0x11,0x1f,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0f,0x12,0x12,0x0e,0x12,0x12,0x0f,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x01,0x01,0x01,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0f,0x12,0x12,0x12,0x12,0x12,0x0f,0x00,0x00,0x00,0x00,0x00, 0x1f,0x01,0x01,0x07,0x01,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x1f,0x01,0x01,0x07,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x1e,0x01,0x01,0x19,0x11,0x11,0x1e,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x10,0x10,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x11,0x09,0x05,0x03,0x05,0x09,0x11,0x00,0x00,0x00,0x00,0x00, 0x01,0x01,0x01,0x01,0x01,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x13,0x15,0x19,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x0f,0x11,0x11,0x0f,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x11,0x11,0x15,0x09,0x16,0x00,0x00,0x00,0x00,0x00, 0x0f,0x11,0x11,0x0f,0x05,0x09,0x11,0x00,0x00,0x00,0x00,0x00, 0x0e,0x11,0x01,0x0e,0x10,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x0a,0x0a,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x11,0x11,0x15,0x1b,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x1f,0x10,0x08,0x04,0x02,0x01,0x1f,0x00,0x00,0x00,0x00,0x00, 0x04,0x0e,0x15,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x04,0x04,0x15,0x0e,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x02,0x1f,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x08,0x1f,0x08,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00, 0x04,0x0a,0x02,0x07,0x02,0x12,0x0f,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0e,0x10,0x1e,0x11,0x1e,0x00,0x00,0x00,0x00,0x00, 0x01,0x01,0x0d,0x13,0x11,0x13,0x0d,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0e,0x11,0x01,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x16,0x19,0x11,0x19,0x16,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0e,0x11,0x1f,0x01,0x0e,0x00,0x00,0x00,0x00,0x00, 0x08,0x14,0x04,0x0e,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0e,0x11,0x11,0x1e,0x10,0x0e,0x00,0x00,0x00,0x00, 0x01,0x01,0x0d,0x13,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x04,0x00,0x06,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00,0x00, 0x10,0x00,0x18,0x10,0x10,0x10,0x12,0x0c,0x00,0x00,0x00,0x00, 0x02,0x02,0x12,0x0a,0x06,0x0a,0x12,0x00,0x00,0x00,0x00,0x00, 0x06,0x04,0x04,0x04,0x04,0x04,0x0e,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0b,0x15,0x15,0x15,0x15,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0d,0x13,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0e,0x11,0x11,0x11,0x0e,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x0d,0x13,0x13,0x0d,0x01,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x16,0x19,0x19,0x16,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x00,0x0d,0x13,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x1e,0x01,0x0e,0x10,0x0f,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x0e,0x04,0x04,0x14,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x11,0x11,0x11,0x19,0x16,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x11,0x11,0x11,0x0a,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x11,0x11,0x15,0x15,0x0a,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x11,0x0a,0x04,0x0a,0x11,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x11,0x11,0x11,0x1e,0x10,0x0e,0x00,0x00,0x00,0x00, 0x00,0x00,0x1f,0x08,0x04,0x02,0x1f,0x00,0x00,0x00,0x00,0x00, 0x08,0x04,0x04,0x02,0x04,0x04,0x08,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x04,0x00,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x02,0x04,0x04,0x08,0x04,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x11,0x0a,0x04,0x1f,0x04,0x1f,0x04,0x00,0x00,0x00,0x00,0x00, 0x15,0x0a,0x15,0x0a,0x15,0x0a,0x15,0x0a,0x00,0x00,0x00,0x00, ]; /** * Original Model III character set. */ const GLYPH_CG4 = [ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x30,0x48,0x08,0x3e,0x08,0x48,0x3e,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x3c,0x42,0x7e,0x02,0x3c,0x00,0x00,0x00,0x00,0x00, 0x24,0x00,0x42,0x42,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x10,0x28,0x10,0x28,0x44,0x7c,0x44,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x7e,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00, 0x28,0x00,0x38,0x44,0x44,0x44,0x38,0x00,0x00,0x00,0x00,0x00, 0xb8,0x44,0x64,0x54,0x4c,0x44,0x3a,0x00,0x00,0x00,0x00,0x00, 0x08,0x10,0x42,0x42,0x42,0x62,0x5c,0x00,0x00,0x00,0x00,0x00, 0x4c,0x32,0x00,0x34,0x4c,0x44,0x44,0x00,0x00,0x00,0x00,0x00, 0x10,0x20,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x1c,0x00,0x1c,0x20,0x3c,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x7c,0x5e,0x22,0x22,0x1e,0x12,0x22,0x00,0x00,0x00,0x00,0x00, 0x28,0x00,0x10,0x28,0x44,0x7c,0x44,0x00,0x00,0x00,0x00,0x00, 0x4c,0x32,0x10,0x28,0x44,0x7c,0x44,0x00,0x00,0x00,0x00,0x00, 0x4c,0x32,0x44,0x4c,0x54,0x64,0x44,0x00,0x00,0x00,0x00,0x00, 0x00,0x28,0x38,0x44,0x44,0x44,0x38,0x00,0x00,0x00,0x00,0x00, 0x90,0x68,0x64,0x54,0x4c,0x2c,0x12,0x00,0x00,0x00,0x00,0x00, 0x4c,0x32,0x00,0x3c,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x3c,0x44,0x44,0x3c,0x44,0x44,0x3e,0x00,0x00,0x00,0x00,0x00, 0x24,0x00,0x42,0x42,0x42,0x62,0x5c,0x00,0x00,0x00,0x00,0x00, 0x4c,0x32,0x00,0x18,0x24,0x24,0x18,0x00,0x00,0x00,0x00,0x00, 0x38,0x54,0x50,0x38,0x14,0x54,0x38,0x00,0x00,0x00,0x00,0x00, 0x14,0x00,0x1c,0x20,0x3c,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x04,0x08,0x1c,0x20,0x3c,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x08,0x00,0x1c,0x20,0x3c,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x3c,0x02,0x3e,0x42,0x7c,0x40,0x3c,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x7c,0x04,0x7c,0x04,0x7c,0x00,0x00,0x00,0x00,0x00, 0x10,0x78,0x24,0x64,0x3c,0x24,0x64,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x04,0x04,0x44,0x38,0x10,0x08,0x00,0x00,0x00,0x00, 0x00,0x00,0x4c,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x10,0x10,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00, 0x24,0x24,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x24,0x24,0x7e,0x24,0x7e,0x24,0x24,0x00,0x00,0x00,0x00,0x00, 0x10,0x78,0x14,0x38,0x50,0x3c,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x46,0x26,0x10,0x08,0x64,0x62,0x00,0x00,0x00,0x00,0x00, 0x0c,0x12,0x12,0x0c,0x52,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x08,0x08,0x08,0x10,0x20,0x00,0x00,0x00,0x00,0x00, 0x04,0x08,0x10,0x10,0x10,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x10,0x54,0x38,0x7c,0x38,0x54,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x10,0x10,0x7c,0x10,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x10,0x10,0x08,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x40,0x20,0x10,0x08,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x62,0x5a,0x46,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x10,0x18,0x14,0x10,0x10,0x10,0x7c,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x40,0x30,0x0c,0x02,0x7e,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x40,0x38,0x40,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x20,0x30,0x28,0x24,0x7e,0x20,0x20,0x00,0x00,0x00,0x00,0x00, 0x7e,0x02,0x1e,0x20,0x40,0x22,0x1c,0x00,0x00,0x00,0x00,0x00, 0x38,0x04,0x02,0x3e,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x7e,0x42,0x20,0x10,0x08,0x08,0x08,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x42,0x3c,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x42,0x7c,0x40,0x20,0x1c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x00,0x00,0x10,0x10,0x08,0x00,0x00,0x00,0x00, 0x60,0x30,0x18,0x0c,0x18,0x30,0x60,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7e,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x06,0x0c,0x18,0x30,0x18,0x0c,0x06,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x40,0x30,0x08,0x00,0x08,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x52,0x6a,0x32,0x04,0x78,0x00,0x00,0x00,0x00,0x00, 0x18,0x24,0x42,0x7e,0x42,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x3e,0x44,0x44,0x3c,0x44,0x44,0x3e,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x02,0x02,0x02,0x44,0x38,0x00,0x00,0x00,0x00,0x00, 0x1e,0x24,0x44,0x44,0x44,0x24,0x1e,0x00,0x00,0x00,0x00,0x00, 0x7e,0x02,0x02,0x1e,0x02,0x02,0x7e,0x00,0x00,0x00,0x00,0x00, 0x7e,0x02,0x02,0x1e,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x02,0x72,0x42,0x44,0x38,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x42,0x7e,0x42,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x38,0x10,0x10,0x10,0x10,0x10,0x38,0x00,0x00,0x00,0x00,0x00, 0x70,0x20,0x20,0x20,0x20,0x22,0x1c,0x00,0x00,0x00,0x00,0x00, 0x42,0x22,0x12,0x0e,0x12,0x22,0x42,0x00,0x00,0x00,0x00,0x00, 0x02,0x02,0x02,0x02,0x02,0x02,0x7e,0x00,0x00,0x00,0x00,0x00, 0x42,0x66,0x5a,0x5a,0x42,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x42,0x46,0x4a,0x52,0x62,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x42,0x42,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x3e,0x42,0x42,0x3e,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x42,0x42,0x52,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x3e,0x42,0x42,0x3e,0x12,0x22,0x42,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0x02,0x3c,0x40,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x7c,0x10,0x10,0x10,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x42,0x42,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x42,0x24,0x24,0x18,0x18,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x42,0x5a,0x5a,0x66,0x42,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x24,0x18,0x24,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x44,0x44,0x44,0x38,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x20,0x18,0x04,0x02,0x7e,0x00,0x00,0x00,0x00,0x00, 0x3c,0x04,0x04,0x04,0x04,0x04,0x3c,0x00,0x00,0x00,0x00,0x00, 0x00,0x02,0x04,0x08,0x10,0x20,0x40,0x00,0x00,0x00,0x00,0x00, 0x3c,0x20,0x20,0x20,0x20,0x20,0x3c,0x00,0x00,0x00,0x00,0x00, 0x10,0x28,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x00,0x00,0x00,0x00, 0x08,0x10,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x1c,0x20,0x3c,0x22,0x5c,0x00,0x00,0x00,0x00,0x00, 0x02,0x02,0x3a,0x46,0x42,0x46,0x3a,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3c,0x42,0x02,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x40,0x40,0x5c,0x62,0x42,0x62,0x5c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3c,0x42,0x7e,0x02,0x3c,0x00,0x00,0x00,0x00,0x00, 0x30,0x48,0x08,0x3e,0x08,0x08,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x5c,0x62,0x62,0x5c,0x40,0x3c,0x00,0x00,0x00,0x00, 0x02,0x02,0x3a,0x46,0x42,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x10,0x00,0x18,0x10,0x10,0x10,0x38,0x00,0x00,0x00,0x00,0x00, 0x20,0x00,0x30,0x20,0x20,0x20,0x22,0x1c,0x00,0x00,0x00,0x00, 0x02,0x02,0x22,0x12,0x0a,0x16,0x22,0x00,0x00,0x00,0x00,0x00, 0x18,0x10,0x10,0x10,0x10,0x10,0x38,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x6e,0x92,0x92,0x92,0x92,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3a,0x46,0x42,0x42,0x42,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3c,0x42,0x42,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3a,0x46,0x46,0x3a,0x02,0x02,0x00,0x00,0x00,0x00, 0x00,0x00,0x5c,0x62,0x62,0x5c,0x40,0x40,0x00,0x00,0x00,0x00, 0x00,0x00,0x3a,0x46,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x02,0x3c,0x40,0x3e,0x00,0x00,0x00,0x00,0x00, 0x08,0x08,0x3e,0x08,0x08,0x48,0x30,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x42,0x42,0x42,0x62,0x5c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x42,0x42,0x42,0x24,0x18,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x82,0x92,0x92,0x92,0x6c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x42,0x24,0x18,0x24,0x42,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x42,0x42,0x62,0x5c,0x40,0x3c,0x00,0x00,0x00,0x00, 0x00,0x00,0x7e,0x20,0x18,0x04,0x7e,0x00,0x00,0x00,0x00,0x00, 0x30,0x08,0x08,0x04,0x08,0x08,0x30,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x10,0x00,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x0c,0x10,0x10,0x20,0x10,0x10,0x0c,0x00,0x00,0x00,0x00,0x00, 0x0c,0x92,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x10,0x10,0x7c,0x10,0x10,0x00,0x7c,0x00,0x00,0x00,0x00,0x00, 0x10,0x38,0x7c,0xfe,0xfe,0x7c,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x6c,0xfe,0xfe,0x7c,0x38,0x10,0x00,0x00,0x00,0x00,0x00, 0x10,0x38,0x7c,0xfe,0x7c,0x38,0x10,0x00,0x00,0x00,0x00,0x00, 0x38,0x38,0x10,0xd6,0xfe,0xd6,0x10,0x38,0x00,0x00,0x00,0x00, 0x3c,0x42,0xa5,0x81,0xa5,0x99,0x42,0x3c,0x00,0x00,0x00,0x00, 0x3c,0x42,0xa5,0x81,0x99,0xa5,0x42,0x3c,0x00,0x00,0x00,0x00, 0x20,0x10,0x08,0x04,0x08,0x10,0x20,0x3c,0x00,0x00,0x00,0x00, 0x04,0x08,0x10,0x20,0x10,0x08,0x04,0x3c,0x00,0x00,0x00,0x00, 0x00,0x00,0x9c,0x62,0x62,0x9c,0x00,0x00,0x00,0x00,0x00,0x00, 0x3c,0x44,0x3c,0x44,0x44,0x3c,0x04,0x02,0x00,0x00,0x00,0x00, 0x86,0x48,0x28,0x18,0x08,0x0c,0x0c,0x00,0x00,0x00,0x00,0x00, 0x30,0x48,0x08,0x30,0x50,0x48,0x30,0x00,0x00,0x00,0x00,0x00, 0x60,0x10,0x08,0x7c,0x08,0x10,0x60,0x00,0x00,0x00,0x00,0x00, 0x68,0x60,0x10,0x08,0x38,0x40,0x30,0x00,0x00,0x00,0x00,0x00, 0x34,0x4a,0x48,0x48,0x40,0x40,0x40,0x00,0x00,0x00,0x00,0x00, 0x10,0x28,0x44,0x7c,0x44,0x28,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x04,0x04,0x04,0x44,0x44,0x38,0x00,0x00,0x00,0x00,0x00, 0x02,0x12,0x0a,0x06,0x0a,0x52,0x22,0x00,0x00,0x00,0x00,0x00, 0x04,0x08,0x08,0x08,0x18,0x24,0x42,0x00,0x00,0x00,0x00,0x00, 0x24,0x24,0x24,0x24,0x5c,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x4c,0x48,0x28,0x18,0x08,0x00,0x00,0x00,0x00,0x00, 0x10,0x38,0x04,0x18,0x04,0x38,0x40,0x30,0x00,0x00,0x00,0x00, 0x00,0x18,0x24,0x42,0x42,0x24,0x18,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x2a,0x28,0x28,0x28,0x00,0x00,0x00,0x00,0x00, 0x00,0x18,0x24,0x24,0x1c,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x12,0x12,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x12,0x10,0x10,0x10,0x10,0x00,0x00,0x00,0x00, 0x00,0x40,0x26,0x24,0x24,0x24,0x18,0x00,0x00,0x00,0x00,0x00, 0x10,0x38,0x54,0x54,0x54,0x38,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x46,0x28,0x10,0x28,0xc4,0x00,0x00,0x00,0x00,0x00, 0x92,0x54,0x54,0x38,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x44,0x82,0x92,0x92,0x6c,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x82,0x82,0xc6,0x44,0xc6,0x00,0x00,0x00,0x00,0x00, 0x78,0x08,0x08,0x08,0x0a,0x0c,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x10,0x00,0x7c,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x7e,0x04,0x08,0x30,0x08,0x04,0x7e,0x00,0x00,0x00,0x00,0x00, 0x00,0x4c,0x32,0x00,0x4c,0x32,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x28,0x44,0xfe,0x00,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x08,0x08,0x10,0x10,0x08,0x04,0x00,0x00,0x00,0x00, 0x80,0x40,0xfe,0x10,0xfe,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x08,0x10,0x20,0x7c,0x08,0x10,0x20,0x00,0x00,0x00,0x00,0x00, 0xfc,0x4a,0x24,0x10,0x48,0xa4,0x42,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x82,0x82,0xfe,0x44,0x44,0xc6,0x00,0x00,0x00,0x00, 0x00,0x00,0x6c,0x92,0x92,0x6c,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x40,0x20,0x12,0x0a,0x06,0x02,0x00,0x00,0x00,0x00,0x00, 0x78,0x04,0x38,0x44,0x38,0x40,0x3c,0x00,0x00,0x00,0x00,0x00, 0x44,0xaa,0x54,0x28,0x54,0xaa,0x44,0x00,0x00,0x00,0x00,0x00, 0x3c,0x42,0xb9,0x85,0x85,0xb9,0x42,0x3c,0x00,0x00,0x00,0x00, 0x42,0x24,0x18,0x24,0x18,0x24,0x42,0x00,0x00,0x00,0x00,0x00, 0x7c,0x52,0x52,0x5c,0x50,0x50,0x50,0x50,0x00,0x00,0x00,0x00, 0x10,0x38,0x54,0x14,0x54,0x38,0x10,0x00,0x00,0x00,0x00,0x00, 0x3c,0x5e,0xa5,0xa5,0x9d,0x95,0x66,0x3c,0x00,0x00,0x00,0x00, 0xfa,0x06,0xc6,0x46,0x26,0xde,0x06,0xfa,0x00,0x00,0x00,0x00, 0xff,0x20,0xc0,0x3f,0x40,0x3f,0x20,0x1f,0x00,0x00,0x00,0x00, 0x3f,0x40,0x3f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x1e,0x22,0x22,0x1e,0x52,0x22,0xd2,0x00,0x00,0x00,0x00,0x00, 0x86,0x41,0x21,0x16,0x68,0x94,0x92,0x61,0x00,0x00,0x00,0x00, 0x70,0x60,0x50,0x0e,0x09,0x09,0x06,0x00,0x00,0x00,0x00,0x00, 0x38,0x44,0x44,0x44,0x38,0x10,0x38,0x10,0x00,0x00,0x00,0x00, 0x70,0x10,0x10,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0xff,0xc7,0xbb,0xcf,0xef,0xff,0xef,0xff,0x00,0x00,0x00,0x00, 0x10,0x28,0x10,0x38,0x54,0x10,0x28,0x44,0x00,0x00,0x00,0x00, 0x10,0x28,0x10,0x38,0x54,0x28,0x7c,0x28,0x00,0x00,0x00,0x00, 0x10,0x28,0x44,0x44,0x44,0x54,0x6c,0x44,0x00,0x00,0x00,0x00, 0x44,0x28,0x10,0x7c,0x10,0x7c,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x04,0x0a,0x04,0x00,0x00,0x00,0x00,0x00, 0x7c,0x04,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x20,0x20,0x20,0x20,0x3e,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x02,0x04,0x08,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x3c,0x20,0x3c,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x40,0x30,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x20,0x10,0x18,0x14,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x7c,0x44,0x40,0x20,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x38,0x10,0x10,0x7c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x10,0x3c,0x18,0x14,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x08,0x7c,0x48,0x08,0x08,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x38,0x20,0x20,0x7c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x7c,0x40,0x78,0x40,0x7c,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x54,0x54,0x44,0x20,0x10,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x28,0x18,0x08,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x40,0x20,0x10,0x18,0x14,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x10,0x7c,0x44,0x44,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x7c,0x10,0x10,0x10,0x10,0x10,0x7c,0x00,0x00,0x00,0x00,0x00, 0x10,0x7e,0x10,0x18,0x14,0x12,0x10,0x00,0x00,0x00,0x00,0x00, 0x08,0x7e,0x48,0x48,0x48,0x44,0x72,0x00,0x00,0x00,0x00,0x00, 0x10,0x38,0x10,0x7c,0x10,0x10,0x10,0x00,0x00,0x00,0x00,0x00, 0x7c,0x44,0x44,0x42,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x7c,0x14,0x12,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x40,0x40,0x40,0x40,0x7e,0x00,0x00,0x00,0x00,0x00, 0x24,0x7e,0x24,0x24,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x1c,0x40,0x4e,0x40,0x40,0x24,0x18,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x20,0x10,0x18,0x24,0x42,0x00,0x00,0x00,0x00,0x00, 0x08,0x7e,0x48,0x28,0x08,0x48,0x38,0x00,0x00,0x00,0x00,0x00, 0x42,0x44,0x48,0x20,0x10,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x7e,0x42,0x42,0x50,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x50,0x3e,0x10,0x7c,0x10,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x7e,0x00,0x7e,0x40,0x20,0x10,0x0c,0x00,0x00,0x00,0x00,0x00, 0x38,0x00,0x7c,0x10,0x10,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x1c,0x24,0x44,0x04,0x04,0x00,0x00,0x00,0x00,0x00, 0x10,0x7c,0x10,0x10,0x10,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x38,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x40,0x28,0x10,0x28,0x44,0x00,0x00,0x00,0x00,0x00, 0x10,0x7e,0x40,0x20,0x30,0x58,0x14,0x00,0x00,0x00,0x00,0x00, 0x60,0x40,0x20,0x10,0x08,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x10,0x20,0x50,0x50,0x50,0x48,0x44,0x00,0x00,0x00,0x00,0x00, 0x02,0x02,0x7e,0x02,0x02,0x42,0x3c,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x40,0x20,0x10,0x08,0x04,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x08,0x14,0x22,0x40,0x00,0x00,0x00,0x00,0x00,0x00, 0x10,0x7c,0x10,0x54,0x54,0x54,0x10,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x40,0x28,0x10,0x20,0x40,0x00,0x00,0x00,0x00,0x00, 0x02,0x3c,0x42,0x3c,0x42,0x3c,0x40,0x00,0x00,0x00,0x00,0x00, 0x20,0x10,0x08,0x04,0x12,0x22,0x5e,0x00,0x00,0x00,0x00,0x00, 0x40,0x44,0x28,0x10,0x28,0x04,0x02,0x00,0x00,0x00,0x00,0x00, 0x7e,0x08,0x3c,0x08,0x08,0x48,0x30,0x00,0x00,0x00,0x00,0x00, 0x08,0x7e,0x48,0x28,0x08,0x08,0x08,0x00,0x00,0x00,0x00,0x00, 0x3c,0x20,0x20,0x20,0x10,0x08,0x7e,0x00,0x00,0x00,0x00,0x00, 0x7e,0x40,0x40,0x7c,0x40,0x40,0x7e,0x00,0x00,0x00,0x00,0x00, 0x54,0x54,0x44,0x40,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x42,0x42,0x42,0x42,0x22,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x0a,0x0a,0x0a,0x4a,0x4a,0x2a,0x1a,0x00,0x00,0x00,0x00,0x00, 0x04,0x04,0x04,0x44,0x44,0x24,0x1c,0x00,0x00,0x00,0x00,0x00, 0x7e,0x42,0x42,0x42,0x42,0x42,0x7e,0x00,0x00,0x00,0x00,0x00, 0x7e,0x42,0x42,0x40,0x20,0x10,0x08,0x00,0x00,0x00,0x00,0x00, 0x4e,0x40,0x40,0x40,0x20,0x12,0x0e,0x00,0x00,0x00,0x00,0x00, 0x08,0x12,0x24,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x04,0x0a,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, ]; /** * Options when rasterizing each glyph. */ export interface GlyphOptions { /** * RGB (0-255) of "on" pixels. */ color: number[]; /** * Whether to draw fake scanlines. */ scanLines: boolean; } /** * Class representing a font and able to generate its glyphs. */ export class Font { // Bit array. Each character is 12 bytes, top to bottom. public readonly bits: number[]; // Number of horizontal pixels in each character, left-aligned in the bits. public readonly width: number; // Number of vertical pixels in each character, top-aligned in the bits. public readonly height: number; // Index of each 64-character bank, or -1 for graphics characters. private readonly banks: number[]; // Cache from glyph key (see makeImage()) to the canvas element for it. private readonly glyphCache = new Map<string,HTMLCanvasElement>(); constructor(bits: number[], width: number, height: number, banks: number[]) { this.bits = bits; this.width = width; this.height = height; this.banks = banks; } /** * Make a bitmap for the specified character (0-255). "on" pixels are the * specified color, "off" pixels are fully transparent. */ public makeImage(char: number, expanded: boolean, options: GlyphOptions): HTMLCanvasElement { const key = { char: char, expanded: expanded, options: options, }; const stringKey = JSON.stringify(key); // Cache the glyph since we create a set of these for each created canvas. let glyph = this.glyphCache.get(stringKey); if (glyph === undefined) { glyph = this.makeImageInternal(char, expanded, options); this.glyphCache.set(stringKey, glyph); } return glyph; } /** * Actually creates the glyph. */ private makeImageInternal(char: number, expanded: boolean, options: GlyphOptions): HTMLCanvasElement { const canvas = document.createElement("canvas"); let expandedMultiplier = expanded ? 2 : 1; canvas.width = this.width*expandedMultiplier; canvas.height = this.height*2; const ctx = canvas.getContext("2d"); if (ctx === null) { throw new Error("2d context not supported"); } const imageData = ctx.createImageData(canvas.width, canvas.height); // Light pixel at (x,y) in imageData if bit "bit" of "byte" is on. const lightPixel = (x: number, y: number, byte: number, bit: number): void => { const pixel = (byte & (1 << bit)) !== 0; if (pixel) { const pixelOffset = (y * canvas.width + x) * 4; const alpha = options.scanLines ? (y % 2 == 0 ? 0xFF : 0xAA) : 0xFF; imageData.data[pixelOffset + 0] = options.color[0]; imageData.data[pixelOffset + 1] = options.color[1]; imageData.data[pixelOffset + 2] = options.color[2]; imageData.data[pixelOffset + 3] = alpha; } }; const bankOffset = this.banks[Math.floor(char/64)]; if (bankOffset === -1) { // Graphical character. const byte = char%64; for (let y = 0; y < canvas.height; y++) { const py = Math.floor(y/(canvas.height/3)); for (let x = 0; x < canvas.width; x++) { const px = Math.floor(x/(canvas.width/2)); const bit = py*2 + px; lightPixel(x, y, byte, bit); } } } else { // Bitmap character. const charOffset = bankOffset + char % 64; const byteOffset = charOffset * 12; for (let y = 0; y < canvas.height; y++) { const byte = this.bits[byteOffset + Math.floor(y / 2)]; for (let x = 0; x < canvas.width; x++) { lightPixel(x, y, byte, Math.floor(x/expandedMultiplier)); } } } ctx.putImageData(imageData, 0, 0); return canvas; } } // Original Model I. export const MODEL1A_FONT = new Font(GLYPH_CG1, 6, 12, [0, 64, -1, -1]); // Model I with lower case mod. export const MODEL1B_FONT = new Font(GLYPH_CG2, 6, 12, [0, 64, -1, -1]); // Original Model III, with special symbols. export const MODEL3_FONT = new Font(GLYPH_CG4, 8, 12, [0, 64, -1, 128]); // Original Model III, with Katakana. export const MODEL3_ALT_FONT = new Font(GLYPH_CG4, 8, 12, [0, 64, -1, 192]);
the_stack
import { API, APIEvent, HAP, Logging, PlatformAccessory } from "homebridge"; import { PLATFORM_NAME, PLUGIN_NAME, PROTECT_NVR_UNIFIOS_REFRESH_INTERVAL } from "./settings"; import { ProtectApi, ProtectCameraConfig, ProtectLightConfig, ProtectSensorConfig, ProtectViewerConfig } from "unifi-protect"; import { ProtectCamera } from "./protect-camera"; import { ProtectDoorbell } from "./protect-doorbell"; import { ProtectLight } from "./protect-light"; import { ProtectLiveviews } from "./protect-liveviews"; import { ProtectMqtt } from "./protect-mqtt"; import { ProtectNvrEvents } from "./protect-nvr-events"; import { ProtectNvrOptions } from "./protect-options"; import { ProtectNvrSystemInfo } from "./protect-nvr-systeminfo"; import { ProtectPlatform } from "./protect-platform"; import { ProtectSensor } from "./protect-sensor"; import { ProtectViewer } from "./protect-viewer"; // Some type aliases to signify what we support. type ProtectDeviceConfigTypes = ProtectCameraConfig | ProtectLightConfig | ProtectSensorConfig | ProtectViewerConfig; type ProtectDevices = ProtectCamera | ProtectDoorbell | ProtectLight | ProtectSensor | ProtectViewer; export class ProtectNvr { private api: API; public config: ProtectNvrOptions; public readonly configuredDevices: { [index: string]: ProtectDevices }; private debug: (message: string, ...parameters: unknown[]) => void; public doorbellCount: number; public events!: ProtectNvrEvents; private isEnabled: boolean; private hap: HAP; private lastMotion: { [index: string]: number }; private lastRing: { [index: string]: number }; private liveviews: ProtectLiveviews | null; private log: Logging; public mqtt: ProtectMqtt | null; private readonly eventTimers: { [index: string]: NodeJS.Timeout }; private name: string; public nvrAddress: string; public nvrApi!: ProtectApi; public systemInfo!: ProtectNvrSystemInfo | null; public platform: ProtectPlatform; private pollingTimer!: NodeJS.Timeout; public refreshInterval: number; private unsupportedDevices: { [index: string]: boolean }; constructor(platform: ProtectPlatform, nvrOptions: ProtectNvrOptions) { this.api = platform.api; this.config = nvrOptions; this.configuredDevices = {}; this.debug = platform.debug.bind(platform); this.doorbellCount = 0; this.isEnabled = false; this.hap = this.api.hap; this.lastMotion = {}; this.lastRing = {}; this.liveviews = null; this.log = platform.log; this.mqtt = null; this.name = nvrOptions.name; this.eventTimers = {}; this.nvrAddress = nvrOptions.address; this.platform = platform; this.refreshInterval = nvrOptions.refreshInterval; this.systemInfo = null; this.unsupportedDevices = {}; // Assign a name, if we don't have one. if(!this.name) { this.name = this.nvrAddress; } // Validate our Protect address and login information. if(!nvrOptions.address || !nvrOptions.username || !nvrOptions.password) { return; } // Initialize our connection to the UniFi Protect API. this.nvrApi = new ProtectApi(nvrOptions.address, nvrOptions.username, nvrOptions.password, this.log); // Initialize our event handlers. this.events = new ProtectNvrEvents(this); // Initialize our liveviews. this.liveviews = new ProtectLiveviews(this); // Initialize our NVR system information. this.systemInfo = new ProtectNvrSystemInfo(this); // Cleanup any stray ffmpeg sessions on shutdown. this.api.on(APIEvent.SHUTDOWN, () => { for(const protectCamera of Object.values(this.configuredDevices)) { if(protectCamera instanceof ProtectCamera) { this.debug("%s: Shutting down all video stream processes.", protectCamera.name()); void protectCamera.stream?.shutdown(); } } }); } // Configure a UniFi Protect device in HomeKit. private configureDevice(accessory: PlatformAccessory, device: ProtectDeviceConfigTypes): boolean { if(!accessory || !device) { return false; } switch(device.modelKey) { case "camera": // We have a UniFi Protect camera or doorbell. if((device as ProtectCameraConfig).featureFlags.hasChime) { this.configuredDevices[accessory.UUID] = new ProtectDoorbell(this, accessory); } else { this.configuredDevices[accessory.UUID] = new ProtectCamera(this, accessory); } return true; break; case "light": // We have a UniFi Protect light. this.configuredDevices[accessory.UUID] = new ProtectLight(this, accessory); return true; break; case "sensor": // We have a UniFi Protect sensor. this.configuredDevices[accessory.UUID] = new ProtectSensor(this, accessory); return true; break; case "viewer": // We have a UniFi Protect viewer. this.configuredDevices[accessory.UUID] = new ProtectViewer(this, accessory); return true; break; default: this.log.error("%s: Unknown device class `%s` detected for ``%s``", this.nvrApi.getNvrName(), device.modelKey, device.name); return false; } } // Discover UniFi Protect devices that may have been added to the NVR since we last checked. private discoverDevices(devices: ProtectDeviceConfigTypes[]): boolean { // Iterate through the list of cameras that Protect has returned and sync them with what we show HomeKit. for(const device of devices ?? []) { // If we have no MAC address, name, or this camera isn't being managed by Protect, we skip. if(!device.mac || !device.name || device.isAdopting || !device.isAdopted) { continue; } // We only support certain devices. switch(device.modelKey) { case "camera": case "light": case "sensor": case "viewer": break; default: // If we've already informed the user about this one, we're done. if(this.unsupportedDevices[device.mac]) { continue; } // Notify the user we see this device, but we aren't adding it to HomeKit. this.unsupportedDevices[device.mac] = true; this.log.info("%s: UniFi Protect device type '%s' is not currently supported, ignoring: %s.", this.nvrApi.getNvrName(), device.modelKey, this.nvrApi.getDeviceName(device)); continue; } // Exclude or include certain devices based on configuration parameters. if(!this.optionEnabled(device)) { continue; } // Generate this device's unique identifier. const uuid = this.hap.uuid.generate(device.mac); let accessory: PlatformAccessory | undefined; // See if we already know about this accessory or if it's truly new. If it is new, add it to HomeKit. if((accessory = this.platform.accessories.find(x => x.UUID === uuid)) === undefined) { accessory = new this.api.platformAccessory(device.name, uuid); this.log.info("%s: Adding %s to HomeKit.", this.nvrApi.getFullName(device), device.modelKey); // Register this accessory with homebridge and add it to the accessory array so we can track it. this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]); this.platform.accessories.push(accessory); } // Link the accessory to it's device object and it's hosting NVR. accessory.context.device = device; accessory.context.nvr = this.nvrApi.bootstrap?.nvr.mac; // Setup the Protect device if it hasn't been configured yet. if(!this.configuredDevices[accessory.UUID]) { this.configureDevice(accessory, device); } else { // Device-specific periodic reconfiguration. We need to do this to reflect state changes in // the Protect NVR (e.g. device settings changes) that we want to catch. Many of the realtime // changes are sent through the realtime update API, but a few things aren't, so we deal with that // here. switch(device.modelKey) { case "camera": // Check if we have changes to the exposed RTSP streams on our cameras. void (this.configuredDevices[accessory.UUID] as ProtectCamera).configureVideoStream(); // Check for changes to the doorbell LCD as well. if((device as ProtectCameraConfig).featureFlags.hasLcdScreen) { void (this.configuredDevices[accessory.UUID] as ProtectDoorbell).configureDoorbellLcdSwitch(); } break; case "viewer": // Sync the viewer state with HomeKit. void (this.configuredDevices[accessory.UUID] as ProtectViewer).updateDevice(); break; default: break; } } } return true; } // Discover and sync UniFi Protect devices between HomeKit and the Protect NVR. private discoverAndSyncAccessories(): boolean { if(this.nvrApi.cameras && !this.discoverDevices(this.nvrApi.cameras)) { this.log.error("%s: Error discovering camera devices.", this.nvrApi.getNvrName()); } if(this.nvrApi.lights && !this.discoverDevices(this.nvrApi.lights)) { this.log.error("%s: Error discovering light devices.", this.nvrApi.getNvrName()); } if(this.nvrApi.sensors && !this.discoverDevices(this.nvrApi.sensors)) { this.log.error("%s: Error discovering sensor devices.", this.nvrApi.getNvrName()); } if(this.nvrApi.viewers && !this.discoverDevices(this.nvrApi.viewers)) { this.log.error("%s: Error discovering viewer devices.", this.nvrApi.getNvrName()); } // Remove Protect devices that are no longer found on this Protect NVR, but we still have in HomeKit. this.cleanupDevices(); // Configure our liveview-based accessories. this.liveviews?.configureLiveviews(); // Configure our NVR system information-related accessories. this.systemInfo?.configureAccessory(); return true; } // Update HomeKit with the latest status from Protect. private async updateAccessories(): Promise<boolean> { // Refresh the full device list from the Protect API. if(!(await this.nvrApi.refreshDevices())) { return false; } // This NVR has been disabled. Stop polling for updates and let the user know that we're done here. // Only run this check once, since we don't need to repeat it again. if(!this.isEnabled && !this.optionEnabled(null)) { this.log.info("%s: Disabling this Protect controller.", this.nvrApi.getNvrName()); this.nvrApi.clearLoginCredentials(); return true; } // Set a name for this NVR, if we haven't configured one for ourselves. if(!this.name && this.nvrApi.bootstrap?.nvr) { this.name = this.nvrApi.bootstrap.nvr.name; } // If not already configured by the user, set the refresh interval here depending on whether we // have UniFi OS devices or not, since non-UniFi OS devices don't have a realtime API. We also // check to see whether doorbell devices have been removed and restore the prior refresh interval, if needed. let refreshUpdated = false; if(!this.refreshInterval || (!this.doorbellCount && (this.refreshInterval !== this.config.refreshInterval))) { if(!this.refreshInterval) { this.refreshInterval = this.config.refreshInterval = PROTECT_NVR_UNIFIOS_REFRESH_INTERVAL; } else { this.refreshInterval = this.config.refreshInterval; } // In case someone puts in an overly aggressive default value. if(this.refreshInterval < 2) { this.refreshInterval = this.config.refreshInterval = 2; } refreshUpdated = true; } if(refreshUpdated || !this.isEnabled) { // On startup or refresh interval change, we want to notify the user. this.log.info("%s: Controller refresh interval set to %s seconds.", this.nvrApi.getNvrName(), this.refreshInterval); } this.isEnabled = true; // Create an MQTT connection, if needed. if(!this.mqtt && this.config.mqttUrl) { this.mqtt = new ProtectMqtt(this); } // Check for any updates to the events API connection. this.events.update(); // Sync status and check for any new or removed accessories. this.discoverAndSyncAccessories(); // Refresh the accessory cache. this.api.updatePlatformAccessories(this.platform.accessories); return true; } // Periodically poll the Protect API for status. public async poll(): Promise<void> { // Loop forever. for(;;) { // Sleep until our next update. // eslint-disable-next-line no-await-in-loop await this.sleep(this.refreshInterval * 1000); // Refresh our Protect device information and gracefully handle Protect errors. // eslint-disable-next-line no-await-in-loop if(await this.updateAccessories()) { // Our Protect NVR is disabled. We're done. if(!this.isEnabled) { return; } } } } // Cleanup removed Protect devices from HomeKit. private cleanupDevices(): void { const nvr = this.nvrApi.bootstrap?.nvr; // If we don't have a valid bootstrap configuration, we're done here. if(!nvr) { return; } for(const oldAccessory of this.platform.accessories) { const oldDevice = oldAccessory.context.device as ProtectCameraConfig; const oldNvr = oldAccessory.context.nvr as string; // Since we're accessing the shared accessories list for the entire platform, we need to ensure we // are only touching our cameras and not another NVR's. if(oldNvr !== nvr.mac) { continue; } // The NVR system information accessory is handled elsewhere. if(("systemInfo" in oldAccessory.context)) { continue; } // Liveview-centric accessories are handled elsewhere. if(("liveview" in oldAccessory.context) || oldAccessory.getService(this.hap.Service.SecuritySystem)) { continue; } // We found this accessory and it's for this NVR. Figure out if we really want to see it in HomeKit. if(oldDevice) { // Check to see if the device still exists on the NVR and the user has not chosen to hide it. switch(oldDevice.modelKey) { case "camera": if(this.nvrApi.cameras?.some((x: ProtectCameraConfig) => x.mac === oldDevice.mac) && this.optionEnabled(oldDevice)) { continue; } break; case "light": if(this.nvrApi.lights?.some((x: ProtectLightConfig) => x.mac === oldDevice.mac) && this.optionEnabled(oldDevice)) { continue; } break; case "sensor": if(this.nvrApi.sensors?.some((x: ProtectSensorConfig) => x.mac === oldDevice.mac) && this.optionEnabled(oldDevice)) { continue; } break; case "viewer": if(this.nvrApi.viewers?.some((x: ProtectViewerConfig) => x.mac === oldDevice.mac) && this.optionEnabled(oldDevice)) { continue; } break; default: break; } } // Decrement our doorbell count. if(oldAccessory.getService(this.hap.Service.Doorbell)) { this.doorbellCount--; } // Remove this device. this.log.info("%s %s: Removing %s from HomeKit.", this.nvrApi.getNvrName(), oldDevice ? this.nvrApi.getDeviceName(oldDevice) : oldAccessory.displayName, oldDevice ? oldDevice.modelKey : "device"); // Unregister the accessory and delete it's remnants from HomeKit and the plugin. this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [oldAccessory]); delete this.configuredDevices[oldAccessory.UUID]; this.platform.accessories.splice(this.platform.accessories.indexOf(oldAccessory), 1); } } // Lookup a device by it's identifier and return the associated accessory, if any. public accessoryLookup(deviceId: string | undefined | null): PlatformAccessory | undefined { if(!deviceId) { return undefined; } // Find the device in our list of accessories. const foundDevice = Object.keys(this.configuredDevices).find(x => (this.configuredDevices[x].accessory.context.device as ProtectCameraConfig).id === deviceId); return foundDevice ? this.configuredDevices[foundDevice].accessory : undefined; } // Utility function to let us know if a device or feature should be enabled or not. public optionEnabled(device: ProtectDeviceConfigTypes | null, option = "", defaultReturnValue = true, address = "", addressOnly = false): boolean { // There are a couple of ways to enable and disable options. The rules of the road are: // // 1. Explicitly disabling, or enabling an option on the NVR propogates to all the devices // that are managed by that NVR. Why might you want to do this? Because... // // 2. Explicitly disabling, or enabling an option on a device by its MAC address will always // override the above. This means that it's possible to disable an option for an NVR, // and all the cameras that are managed by it, and then override that behavior on a single // camera that it's managing. const configOptions = this.platform?.configOptions; // Nothing configured - we assume the default return value. if(!configOptions) { return defaultReturnValue; } // Upper case parameters for easier checks. option = option ? option.toUpperCase() : ""; address = address ? address.toUpperCase() : ""; const deviceMac = device?.mac ? device.mac.toUpperCase() : ""; let optionSetting; // If we've specified an address parameter - we check for device and address-specific options before // anything else. if(address && option) { // Test for device-specific and address-specific option settings, used together. if(deviceMac) { optionSetting = option + "." + deviceMac + "." + address; // We've explicitly enabled this option for this device and address combination. if(configOptions.indexOf("ENABLE." + optionSetting) !== -1) { return true; } // We've explicitly disabled this option for this device and address combination. if(configOptions.indexOf("DISABLE." + optionSetting) !== -1) { return false; } } // Test for address-specific option settings only. optionSetting = option + "." + address; // We've explicitly enabled this option for this address. if(configOptions.indexOf("ENABLE." + optionSetting) !== -1) { return true; } // We've explicitly disabled this option for this address. if(configOptions.indexOf("DISABLE." + optionSetting) !== -1) { return false; } // We're only interested in address-specific options. if(addressOnly) { return false; } } // If we've specified a device, check for device-specific options first. Otherwise, we're dealing // with an NVR-specific or global option. if(deviceMac) { // First we test for camera-level option settings. // No option specified means we're testing to see if this device should be shown in HomeKit. optionSetting = option ? option + "." + deviceMac : deviceMac; // We've explicitly enabled this option for this device. if(configOptions.indexOf("ENABLE." + optionSetting) !== -1) { return true; } // We've explicitly disabled this option for this device. if(configOptions.indexOf("DISABLE." + optionSetting) !== -1) { return false; } } // If we don't have a managing device attached, we're done here. if(!this.nvrApi.bootstrap?.nvr?.mac) { return defaultReturnValue; } // Now we test for NVR-level option settings. // No option specified means we're testing to see if this NVR (and it's attached devices) should be shown in HomeKit. const nvrMac = this.nvrApi.bootstrap.nvr.mac.toUpperCase(); optionSetting = option ? option + "." + nvrMac : nvrMac; // We've explicitly enabled this option for this NVR and all the devices attached to it. if(configOptions.indexOf("ENABLE." + optionSetting) !== -1) { return true; } // We've explicitly disabled this option for this NVR and all the devices attached to it. if(configOptions.indexOf("DISABLE." + optionSetting) !== -1) { return false; } // Finally, let's see if we have a global option here. // No option means we're done - it's a special case for testing if an NVR or camera should be hidden in HomeKit. if(!option) { return defaultReturnValue; } // We've explicitly enabled this globally for all devices. if(configOptions.indexOf("ENABLE." + option) !== -1) { return true; } // We've explicitly disabled this globally for all devices. if(configOptions.indexOf("DISABLE." + option) !== -1) { return false; } // Nothing special to do - assume the option is defaultReturnValue. return defaultReturnValue; } // Utility function to return a configuration parameter for a Protect device. public optionGet(device: ProtectDeviceConfigTypes | null, option: string, address = ""): string | undefined { // Using the same rules as we do to test for whether an option is enabled, retrieve options with parameters and // return them. If we don't find anything, we return undefined. const configOptions = this.platform?.configOptions; // Nothing configured - we assume there's nothing. if(!configOptions || !option) { return undefined; } // Upper case parameters for easier checks. address = address ? address.toUpperCase() : ""; option = option.toUpperCase(); const deviceMac = device?.mac.toUpperCase() ?? null; let foundOption; let optionSetting: string; // If we've specified an address parameter - we check for device and address-specific options before // anything else. if(address) { // Test for device-specific and address-specific option settings, used together. if(deviceMac) { // We've explicitly enabled this option for this device and address combination. optionSetting = "ENABLE." + option + "." + deviceMac + "." + address + "."; if((foundOption = configOptions.find(x => optionSetting === x.slice(0, optionSetting.length))) !== undefined) { return foundOption.slice(optionSetting.length); } // We've explicitly disabled this option for this device and address combination. optionSetting = "DISABLE." + option + "." + deviceMac + "." + address; if(configOptions.indexOf(optionSetting) !== -1) { return undefined; } } // We've explicitly enabled this option for this address. optionSetting = "ENABLE." + option + "." + address + "."; if((foundOption = configOptions.find(x => optionSetting === x.slice(0, optionSetting.length))) !== undefined) { return foundOption.slice(optionSetting.length); } // We've explicitly disabled this option for this address. optionSetting = "DISABLE." + option + "." + address; if(configOptions.indexOf(optionSetting) !== -1) { return undefined; } } // If we've specified a device, check for device-specific options first. Otherwise, we're dealing // with an NVR-specific or global option. if(deviceMac) { // First we test for camera-level option settings. // No option specified means we're testing to see if this device should be shown in HomeKit. optionSetting = "ENABLE." + option + "." + deviceMac + "."; // We've explicitly enabled this option for this device. if((foundOption = configOptions.find(x => optionSetting === x.slice(0, optionSetting.length))) !== undefined) { return foundOption.slice(optionSetting.length); } // We've explicitly disabled this option for this device. optionSetting = "DISABLE." + option + "." + deviceMac; if(configOptions.indexOf(optionSetting) !== -1) { return undefined; } } // If we don't have a managing device attached, we're done here. if(!this.nvrApi.bootstrap?.nvr?.mac) { return undefined; } // Now we test for NVR-level option settings. // No option specified means we're testing to see if this NVR (and it's attached devices) should be shown in HomeKit. const nvrMac = this.nvrApi.bootstrap.nvr.mac.toUpperCase(); optionSetting = "ENABLE." + option + "." + nvrMac + "."; // We've explicitly enabled this option for this NVR and all the devices attached to it. if((foundOption = configOptions.find(x => optionSetting === x.slice(0, optionSetting.length))) !== undefined) { return foundOption.slice(optionSetting.length); } // We've explicitly disabled this option for this NVR and all the devices attached to it. optionSetting = "DISABLE." + option + "." + nvrMac; if(configOptions.indexOf(optionSetting) !== -1) { return undefined; } // Finally, let's see if we have a global option here. optionSetting = "ENABLE." + option + "."; // We've explicitly enabled this globally for all devices. if((foundOption = configOptions.find(x => optionSetting === x.slice(0, optionSetting.length))) !== undefined) { return foundOption.slice(optionSetting.length); } // Nothing special to do - assume the option is defaultReturnValue. return undefined; } // Emulate a sleep function. public sleep(ms: number): Promise<NodeJS.Timeout> { return new Promise(resolve => setTimeout(resolve, ms)); } }
the_stack
import {Component, OnInit} from '@angular/core'; import {DashboardCard} from '../cards/dashboard-card'; import {Observable} from 'rxjs/Observable'; import {DashboardCardsService} from '../services/dashboard-cards/dashboard-cards.service'; import {ObservableMedia} from '@angular/flex-layout'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/startWith'; import {DashboardUsersComponent} from '../cards/dashboard-users/dashboard-users.component'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'], entryComponents: [DashboardUsersComponent] }) export class DashboardComponent implements OnInit { cards: DashboardCard[] = []; cols: Observable<number>; cols_big: Observable<number>; cols_sml: Observable<number>; constructor(private cardsService: DashboardCardsService, private observableMedia: ObservableMedia) { this.cardsService.cards.subscribe(cards => { this.cards = cards; }); } ngOnInit() { /* Grid column map */ const cols_map = new Map([ ['xs', 1], ['sm', 4], ['md', 8], ['lg', 10], ['xl', 18] ]); /* Big card column span map */ const cols_map_big = new Map([ ['xs', 1], ['sm', 4], ['md', 4], ['lg', 4], ['xl', 4] ]); /* Small card column span map */ const cols_map_sml = new Map([ ['xs', 1], ['sm', 2], ['md', 2], ['lg', 2], ['xl', 2] ]); let start_cols: number; let start_cols_big: number; let start_cols_sml: number; cols_map.forEach((cols, mqAlias) => { if (this.observableMedia.isActive(mqAlias)) { start_cols = cols; } }); cols_map_big.forEach((cols_big, mqAlias) => { if (this.observableMedia.isActive(mqAlias)) { start_cols_big = cols_big; } }); cols_map_sml.forEach((cols_sml, mqAliast) => { if (this.observableMedia.isActive(mqAliast)) { start_cols_sml = cols_sml; } }); this.cols = this.observableMedia.asObservable() .map(change => { return cols_map.get(change.mqAlias); }).startWith(start_cols); this.cols_big = this.observableMedia.asObservable() .map(change => { return cols_map_big.get(change.mqAlias); }).startWith(start_cols_big); this.cols_sml = this.observableMedia.asObservable() .map(change => { return cols_map_sml.get(change.mqAlias); }).startWith(start_cols_sml); this.createCards(); } createCards(): void { this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_big }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_big }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent /* Reference to the component we'd like to spawn */ ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_big }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_big }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_big }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_big }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); this.cardsService.addCard( new DashboardCard( { name: { key: DashboardCard.metadata.NAME, value: 'users' }, routerLink: { key: DashboardCard.metadata.ROUTERLINK, value: '/dashboard/users' }, iconClass: { key: DashboardCard.metadata.ICONCLASS, value: 'fa-users' }, cols: { key: DashboardCard.metadata.COLS, value: this.cols_sml }, rows: { key: DashboardCard.metadata.ROWS, value: this.cols_sml }, color: { key: DashboardCard.metadata.COLOR, value: 'blue' } }, DashboardUsersComponent ) ); } }
the_stack
import { FormArray as NativeFormArray } from '@angular/forms'; import { Observable } from 'rxjs'; import { ControlType, Status, ValidatorFn, AsyncValidatorFn, ValidatorsModel, ValidationErrors, AbstractControlOptions, StringKeys, ExtractModelValue, FormControlState, } from './types'; export class FormArray<Item = any, V extends object = ValidatorsModel> extends NativeFormArray { readonly value: ExtractModelValue<Item>[]; readonly valueChanges: Observable<ExtractModelValue<Item>[]>; readonly status: Status; readonly statusChanges: Observable<Status>; readonly errors: ValidationErrors<V> | null; /** * Creates a new `FormArray` instance. * * @param controls An array of child controls. Each child control is given an index * where it is registered. * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * @param asyncValidator A single async validator or array of async validator functions * */ constructor( public controls: ControlType<Item, V>[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null ) { super(controls, validatorOrOpts, asyncValidator); } /** * Get the Control at the given `index` in the array. * * @param index Index in the array to retrieve the control */ at(index: number) { return super.at(index) as ControlType<Item, V>; } /** * Insert a new Control at the end of the array. * * @param control Form control to be inserted */ push(control: ControlType<Item, V>) { return super.push(control); } /** * Insert a new Control at the given `index` in the array. * * @param index Index in the array to insert the control * @param control Form control to be inserted */ insert(index: number, control: ControlType<Item, V>) { return super.insert(index, control); } /** * Replace an existing control. * * @param index Index in the array to replace the control * @param control The Control control to replace the existing control */ setControl(index: number, control: ControlType<Item, V>) { return super.setControl(index, control); } /** * Sets the value of the `FormArray`. It accepts an array that matches * the structure of the control. * * This method performs strict checks, and throws an error if you try * to set the value of a control that doesn't exist or if you exclude the * value of a control. * * ### Set the values for the controls in the form array * ```ts const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.setValue(['Nancy', 'Drew']); console.log(arr.value); // ['Nancy', 'Drew'] ``` * * @param value Array of values for the controls * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * The configuration options are passed to the * [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method. */ setValue(value: ExtractModelValue<Item>[], options: { onlySelf?: boolean; emitEvent?: boolean } = {}) { return super.setValue(value, options); } /** * Patches the value of the `FormArray`. It accepts an array that matches the * structure of the control, and does its best to match the values to the correct * controls in the group. * * It accepts both super-sets and sub-sets of the array without throwing an error. * * ### Patch the values for controls in a form array * ```ts const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.patchValue(['Nancy']); console.log(arr.value); // ['Nancy', null] ``` * * @param value Array of latest values for the controls * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * The configuration options are passed to the * [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method. */ patchValue(value: ExtractModelValue<Item>[], options: { onlySelf?: boolean; emitEvent?: boolean } = {}) { return super.patchValue(value, options); } /** * Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the * value of all descendants to null or null maps. * * You reset to a specific form state by passing in an array of states * that matches the structure of the control. The state is a standalone value * or a form state object with both a value and a disabled status. * * ### Reset the values in a form array * ```ts const arr = new FormArray([ new FormControl(), new FormControl() ]); arr.reset(['name', 'last name']); console.log(this.arr.value); // ['name', 'last name'] ``` * * ### Reset the values in a form array and the disabled status for the first control * ``` this.arr.reset([ {value: 'name', disabled: true}, 'last' ]); console.log(this.arr.value); // ['name', 'last name'] console.log(this.arr.get(0).status); // 'DISABLED' ``` * * @param value Array of values for the controls * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is reset. * When false, no events are emitted. * The configuration options are passed to the * [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method. */ reset(value: FormControlState<Item>[] = [], options: { onlySelf?: boolean; emitEvent?: boolean } = {}) { return super.reset(value, options); } /** * The aggregate value of the array, including any disabled controls. * * Reports all values regardless of disabled status. * For enabled controls only, the `value` property is the best way to get the value of the array. */ getRawValue() { return super.getRawValue() as ExtractModelValue<Item>[]; } /** * Sets the synchronous validators that are active on this control. Calling * this overwrites any existing sync validators. */ setValidators(newValidator: ValidatorFn | ValidatorFn[] | null) { return super.setValidators(newValidator); } /** * Sets the async validators that are active on this control. Calling this * overwrites any existing async validators. */ setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null) { return super.setAsyncValidators(newValidator); } /** * Sets errors on a form control when running validations manually, rather than automatically. * * Calling `setErrors` also updates the validity of the parent control. * * ### Manually set the errors for a control * * ```ts * const login = new FormControl('someLogin'); * login.setErrors({ * notUnique: true * }); * * expect(login.valid).toEqual(false); * expect(login.errors).toEqual({ notUnique: true }); * * login.setValue('someOtherLogin'); * * expect(login.valid).toEqual(true); * ``` */ setErrors(errors: ValidationErrors | null, opts: { emitEvent?: boolean } = {}) { return super.setErrors(errors, opts); } /** * Reports error data for the control with the given controlName. * * @param errorCode The code of the error to check * @param controlName A control name that designates how to move from the current control * to the control that should be queried for errors. * * For example, for the following `FormGroup`: * ```ts form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` * * The controlName to the 'street' control from the root form would be 'address' -> 'street'. * * It can be provided to this method in combination with `get()` method: * ```ts form.get('address').getError('someErrorCode', 'street'); ``` * * @returns error data for that particular error. If the control or error is not present, * null is returned. */ getError<P extends StringKeys<V>, K extends StringKeys<Item>>(errorCode: P, controlName?: K) { return super.getError(errorCode, controlName) as V[P] | null; } /** * Reports whether the control with the given controlName has the error specified. * * @param errorCode The code of the error to check * @param controlName A control name that designates how to move from the current control * to the control that should be queried for errors. * * For example, for the following `FormGroup`: * ```ts form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` * * The controlName to the 'street' control from the root form would be 'address' -> 'street'. * * It can be provided to this method in combination with `get()` method: ```ts form.get('address').hasError('someErrorCode', 'street'); ``` * * If no controlName is given, this method checks for the error on the current control. * * @returns whether the given error is present in the control at the given controlName. * * If the control is not present, false is returned. */ hasError<P extends StringKeys<V>, K extends StringKeys<Item>>(errorCode: P, controlName?: K) { return super.hasError(errorCode, controlName); } }
the_stack
import { Component, Event, EventEmitter, Prop, State, Watch } from '@stencil/core'; import { Column } from './grid-helpers'; import { renderRow, RowOptions, RowSelectionPattern } from './row'; import { renderHeaderCell, Sort } from './header-cell'; @Component({ tag: 'sui-grid-new', styleUrl: './grid.css' }) export class SuiGridv2 { /** * Grid data */ @Prop() cells: string[][]; /** * Column definitions */ @Prop() columns: Column[]; /** * Caption/description for the grid */ @Prop() description: string; /** * Grid type: grids have controlled focus and fancy behavior, tables are simple static content */ @Prop() gridType: 'grid' | 'table'; /** * String ID of labelling element */ @Prop() labelledBy: string; /** * Number of rows in one "page": used to compute pageUp/pageDown key behavior, and when paging is used */ @Prop() pageLength = 30; /** * Custom function to control the render of cell content */ @Prop() renderCustomCell: (content: string, colIndex: number, rowIndex: number) => string | HTMLElement; /** * Index of the column that best labels a row */ @Prop() titleColumn = 0; /** Properties for Usability test case behaviors: **/ @Prop() editable: boolean = true; @Prop() headerActionsMenu: boolean; @Prop() rowSelection: RowSelectionPattern; @Prop() modalCell: boolean = false; /** * Emit a custom filter event */ @Event({ eventName: 'filter' }) filterEvent: EventEmitter; /** * Emit a custom row selection event */ @Event({ eventName: 'rowSelect' }) rowSelectionEvent: EventEmitter; /** * Emit a custom edit event when cell content change is submitted */ @Event({ eventName: 'editCell' }) editCellEvent: EventEmitter<{value: string; column: number; row: number;}>; /** * Emit a custom stepper value change event */ @Event({ eventName: 'stepperChange' }) stepperChangeEvent: EventEmitter<{row: number; value: number}>; /** * Save number of selected rows */ @State() selectedRowCount = 0; /** * Save column sort state */ @State() sortedColumn: number; @State() sortState: Sort; // save cell focus and edit states // active cell refers to the [column, row] indices of the cell @State() activeCell: [number, number] = [0, 0]; @State() isEditing = false; /** * Save current filter strings */ private filters: WeakMap<Column, string> = new WeakMap(); /** * Save selection state by row */ private selectedRows: WeakMap<string[], boolean> = new WeakMap(); /** * Save current sorted cell array * Will likely need to be moved out of component to allow on-demand and paged grids */ private sortedCells: string[][]; /* * DOM Refs: */ // Save a reference to whatever element should receive focus private focusRef: HTMLElement; // Save a reference to whatever the current cell is private activeCellRef: HTMLElement; /* * Private properties used to trigger DOM methods in the correct lifecycle callback */ private callFocus = false; private callInputSelection = false; private preventSave = false; // prevent saves on escape private mouseDown = false; // handle focus/click behavior @Watch('cells') watchOptions(newValue: string[][]) { this.sortedCells = this.getSortedCells(newValue); // reset selectedRowCount let selectedRowCount = 0; newValue.forEach((row: string[]) => { this.selectedRows.has(row) && selectedRowCount++; }); this.selectedRowCount = selectedRowCount; } componentWillLoad() { this.sortedCells = this.cells; } componentDidUpdate() { if (!this.focusRef) return; // handle focus this.callFocus && this.focusRef.focus(); this.callFocus = false; // handle input text selection this.callInputSelection && (this.focusRef as HTMLInputElement).select && (this.focusRef as HTMLInputElement).select(); this.callInputSelection = false; } render() { const { columns = [], description, editable, gridType = 'table', headerActionsMenu, rowSelection, selectedRows, sortedCells = [], sortedColumn, sortState } = this; const rowSelectionState = this.getSelectionState(); const activeCellId = this.activeCell.join('-'); const colOffset = rowSelection === RowSelectionPattern.Checkbox ? 1 : 0; return <table role={gridType} class="grid" aria-labelledby={this.labelledBy} aria-readonly={editable ? null : 'true'} onKeyDown={this.onCellKeydown.bind(this)}> {description ? <caption>{description}</caption> : null} <thead role="rowgroup" class="grid-header"> <tr role="row" class="row"> {rowSelection !== RowSelectionPattern.None ? <th role="columnheader" aria-labelledby="select-all-header" class={{'checkbox-cell': true, 'indeterminate': rowSelectionState === 'indeterminate'}} > <span class="visuallyHidden" id="select-all-header">select row</span> <input type="checkbox" aria-label="select all rows" checked={!!rowSelectionState} tabIndex={this.gridType === 'grid' ? activeCellId === '0-0' ? 0 : -1 : null} ref={(el) => { if (rowSelectionState === 'indeterminate') { el.indeterminate = true; } if (activeCellId === '0-0') { this.focusRef = el; } }} onChange={(event) => this.onSelectAll((event.target as HTMLInputElement).checked)} /> <span class="selection-indicator"></span> </th> : null} {columns.map((column, index) => { const headerIndex = index + colOffset; return renderHeaderCell({ column, colIndex: headerIndex, actionsMenu: headerActionsMenu, isActiveCell: activeCellId === `${headerIndex}-0`, isSortedColumn: sortedColumn === headerIndex, setFocusRef: (el) => this.focusRef = el, sortDirection: sortState, onSort: this.onSortColumn.bind(this), onFilter: this.onFilterInput.bind(this) }); })} </tr> </thead> <tbody role="rowgroup" class="grid-body"> {sortedCells.map((cells = [], index) => { const isSelected = !!selectedRows.get(cells); let rowOptions: RowOptions = { cells, index: index + 1, isSelected, selection: rowSelection, renderCell: this.renderCell.bind(this), renderCheckboxCell: this.renderCheckboxCell.bind(this), onSelectionChange: this.onRowSelect.bind(this) }; if (this.rowSelection === RowSelectionPattern.Aria) { const isActiveRow = this.activeCell[1] === index + 1; rowOptions = { ...rowOptions, isActiveRow, setFocusRef: (el) => this.focusRef = el, onRowKeyDown: this.onRowKeyDown.bind(this) } } return renderRow(rowOptions); })} </tbody> </table>; } // dedicated function, because internal index can be off by one depending on whether there's a checkbox column private getColumnData(colIndex) { const cellColumn = this.rowSelection === RowSelectionPattern.Checkbox ? colIndex - 1 : colIndex; return this.columns[cellColumn]; } private getSelectionState(): boolean | 'indeterminate' { return this.selectedRowCount === 0 ? false : this.selectedRowCount === this.cells.length ? true : 'indeterminate'; } private getSortedCells(cells: string[][]) { if (this.sortedColumn !== undefined && this.sortState !== Sort.None) { return [ ...cells ].sort(this.getSortFunction(this.sortedColumn, this.sortState)); } return cells; } private getSortFunction(columnIndex: number, order: Sort) { return function(row1, row2) { const a = row1[columnIndex].toLowerCase(); const b = row2[columnIndex].toLowerCase(); if (a < b) { return order === Sort.Ascending ? -1 : 1; } else if (a > b) { return order === Sort.Ascending ? 1 : -1; } else { return 0; } } } private onCellClick(row, column) { const previousCell = this.activeCell; this.activeCell = [column, row]; const isActiveCellClick = previousCell[0] === column && previousCell[1] === row; // exit editing if not clicking on active cell if (!isActiveCellClick && this.isEditing) { this.saveCell(previousCell[0], previousCell[1], (this.focusRef as HTMLInputElement).value); this.updateEditing(false, false); } } private onCellDoubleClick(column) { if (!this.getColumnData(column).actionsColumn) { console.log('double click, editing') this.updateEditing(true, true); } } private onCellFocus(row, column) { if (this.mouseDown) { this.mouseDown = false; return; } this.activeCell = [column, row]; } private onCellKeydown(event: KeyboardEvent) { const { isEditing, pageLength } = this; const maxCellIndex = this.rowSelection === RowSelectionPattern.Checkbox ? this.columns.length : this.columns.length - 1; let [colIndex, rowIndex] = this.activeCell; switch(event.key) { case 'ArrowUp': rowIndex = Math.max(0, rowIndex - 1); break; case 'ArrowDown': rowIndex = Math.min(this.cells.length - 1, rowIndex + 1); break; case 'ArrowLeft': colIndex = Math.max(0, colIndex - 1); break; case 'ArrowRight': colIndex = Math.min(maxCellIndex, colIndex + 1); break; case 'Home': colIndex = 0; break; case 'End': colIndex = maxCellIndex; break; case ' ': // space never enters into actions column if (this.getColumnData(colIndex).actionsColumn) return; case 'Enter': // enter also doesn't enter into actions column unless the keyboard modal variant is true if (this.getColumnData(colIndex).actionsColumn && !this.modalCell) return; console.log('go into editing mode', this.modalCell, 'is action col?', this.getColumnData(colIndex)); event.preventDefault(); this.updateEditing(true, true); break; case 'Escape': this.updateEditing(false, true); event.stopPropagation(); break; case 'PageUp': rowIndex = Math.max(0, rowIndex - pageLength); break; case 'PageDown': rowIndex = Math.min(this.cells.length - 1, rowIndex + pageLength); break; case 'Tab': // prevent tabbing outside cell if modal this.modalCell && this.isEditing && this.trapCellFocus(event); } if (!isEditing && this.updateActiveCell(colIndex, rowIndex)) { event.preventDefault(); } } private onEditButtonClick(event: MouseEvent, row: number, column: number, edit: boolean, save = false) { event.stopPropagation(); this.activeCell = [column, row]; this.updateEditing(edit, true); if (save) { this.saveCell(column, row, (this.focusRef as HTMLInputElement).value); } } private onFilterInput(value: string, column: Column) { this.filters.set(column, value); const filters = {}; this.columns.forEach((column, index) => { if (column.filterable && this.filters.has(column)) { const filterString = this.filters.get(column); if (filterString.trim() !== '') { filters[index] = filterString; } } }); this.filterEvent.emit(filters); } private onInputKeyDown(event: KeyboardEvent) { // allow input to handle its own keystrokes event.stopPropagation(); const { key } = event; if (key === 'Escape') { this.preventSave = true; } // switch out of edit mode on enter or escape if (key === 'Escape' || key === 'Enter') { this.updateEditing(false, true); } // save value on enter if (key === 'Enter') { const cellIndex = this.rowSelection === RowSelectionPattern.Checkbox ? this.activeCell[0] - 1 : this.activeCell[0]; this.saveCell(cellIndex, this.activeCell[1], (event.target as HTMLInputElement).value); } // trap focus on tab if (this.modalCell && key === 'Tab') { this.trapCellFocus(event); } } private onRowKeyDown(event: KeyboardEvent) { const { pageLength } = this; let [colIndex, rowIndex] = this.activeCell; switch(event.key) { case 'ArrowUp': rowIndex = Math.max(0, rowIndex - 1); break; case 'ArrowDown': rowIndex = Math.min(this.cells.length - 1, rowIndex + 1); break; case 'PageUp': rowIndex = Math.max(0, rowIndex - pageLength); break; case 'PageDown': rowIndex = Math.min(this.cells.length - 1, rowIndex + pageLength); break; } if (this.updateActiveCell(colIndex, rowIndex)) { event.preventDefault(); event.stopPropagation(); } } private onRowSelect(row: string[], selected: boolean) { this.selectedRows.set(row, selected); this.selectedRowCount = this.selectedRowCount + (selected ? 1 : -1); } private onSelectAll(selected: boolean) { this.cells.forEach((row) => { this.selectedRows.set(row, selected); }); this.selectedRowCount = selected ? this.cells.length : 0; } private onSortColumn(columnIndex: number) { if (columnIndex === this.sortedColumn) { this.sortState = this.sortState === Sort.Descending ? Sort.Ascending : Sort.Descending; } else { this.sortedColumn = columnIndex; this.sortState = Sort.Ascending; } this.sortedCells = this.getSortedCells(this.cells); } private renderCell(rowIndex: number, cellIndex: number, content: string) { const activeCellId = this.activeCell.join('-'); const currentCellKey = `${cellIndex}-${rowIndex}`; const isActiveCell = activeCellId === currentCellKey; const columnData = this.getColumnData(cellIndex); const isGrid = this.gridType === 'grid'; return <td role={isGrid ? 'gridcell' : 'cell'} id={`cell-${rowIndex}-${cellIndex}`} class={{'cell': true, 'editing': this.isEditing && isActiveCell, 'hover-icon': this.modalCell }} aria-readonly={!this.editable || columnData.actionsColumn ? 'true' : null} aria-labelledby={!this.isEditing ? `cell-${rowIndex}-${cellIndex}-content` : null} tabIndex={isGrid && this.rowSelection !== RowSelectionPattern.Aria ? isActiveCell && (!this.isEditing || !this.modalCell) ? 0 : -1 : null} ref={isActiveCell ? (el) => { this.activeCellRef = el; if (!this.isEditing && this.rowSelection !== RowSelectionPattern.Aria) this.focusRef = el; } : null} onFocus={() => { this.onCellFocus(rowIndex, cellIndex)}} onClick={this.editable ? () => { this.onCellClick(rowIndex, cellIndex); } : null} onDblClick={this.editable ? () => { this.onCellDoubleClick(cellIndex); } : null} onMouseDown={() => { this.mouseDown = true; }} > {this.isEditing && isActiveCell && !columnData.actionsColumn ? <input type="text" value={content} class="cell-edit" onKeyDown={this.onInputKeyDown.bind(this)} ref={(el) => this.focusRef = el} /> : <span class="cell-content" id={`cell-${rowIndex}-${cellIndex}-content`}>{this.renderCellContent(content, cellIndex, rowIndex)}</span> } {!columnData.actionsColumn ? this.isEditing && isActiveCell ? [ <button class="confirm-button" key={`${currentCellKey}-save`} type="button" onClick={(event) => { this.onEditButtonClick(event, rowIndex, cellIndex, false, true) }} onKeyDown={(event) => (event.key === 'Enter' || event.key === ' ') && event.stopPropagation()}> <svg role="img" aria-label="Save" width="32" height="32" viewBox="0 0 32 32" fill="currentColor"> <path d="M27 4l-15 15-7-7-5 5 12 12 20-20z"></path> </svg> </button>, <button class="confirm-button" key={`${currentCellKey}-cancel`} type="button" onClick={(event) => { this.onEditButtonClick(event, rowIndex, cellIndex, false) }} onKeyDown={(event) => (event.key === 'Enter' || event.key === ' ') && event.stopPropagation()}> <svg role="img" aria-label="Cancel" width="32" height="32" viewBox="0 0 32 32" fill="currentColor"> <path d="M31.708 25.708c-0-0-0-0-0-0l-9.708-9.708 9.708-9.708c0-0 0-0 0-0 0.105-0.105 0.18-0.227 0.229-0.357 0.133-0.356 0.057-0.771-0.229-1.057l-4.586-4.586c-0.286-0.286-0.702-0.361-1.057-0.229-0.13 0.048-0.252 0.124-0.357 0.228 0 0-0 0-0 0l-9.708 9.708-9.708-9.708c-0-0-0-0-0-0-0.105-0.104-0.227-0.18-0.357-0.228-0.356-0.133-0.771-0.057-1.057 0.229l-4.586 4.586c-0.286 0.286-0.361 0.702-0.229 1.057 0.049 0.13 0.124 0.252 0.229 0.357 0 0 0 0 0 0l9.708 9.708-9.708 9.708c-0 0-0 0-0 0-0.104 0.105-0.18 0.227-0.229 0.357-0.133 0.355-0.057 0.771 0.229 1.057l4.586 4.586c0.286 0.286 0.702 0.361 1.057 0.229 0.13-0.049 0.252-0.124 0.357-0.229 0-0 0-0 0-0l9.708-9.708 9.708 9.708c0 0 0 0 0 0 0.105 0.105 0.227 0.18 0.357 0.229 0.356 0.133 0.771 0.057 1.057-0.229l4.586-4.586c0.286-0.286 0.362-0.702 0.229-1.057-0.049-0.13-0.124-0.252-0.229-0.357z"></path> </svg> </button> ] : <button class="edit-button" key={`${currentCellKey}-edit`} type="button" tabIndex={isActiveCell && !this.modalCell ? null : -1} onFocus={() => { this.onCellFocus(rowIndex, cellIndex)}} onClick={(event) => { this.onEditButtonClick(event, rowIndex, cellIndex, true) }}> <svg role="img" aria-label="Edit" width="32" height="32" viewBox="0 0 32 32" fill="currentColor"> <path d="M27 0c2.761 0 5 2.239 5 5 0 1.126-0.372 2.164-1 3l-2 2-7-7 2-2c0.836-0.628 1.874-1 3-1zM2 23l-2 9 9-2 18.5-18.5-7-7-18.5 18.5zM22.362 11.362l-14 14-1.724-1.724 14-14 1.724 1.724z"></path> </svg> </button> : null } </td>; } private renderCellContent(content: string, colIndex: number, rowIndex: number) { const { renderCustomCell = (content) => content } = this; const columnData = this.getColumnData(colIndex); // spoofing different types of custom content for testing if (columnData && columnData.actionsColumn) { const actionsType = content.split(', ').shift(); switch(actionsType) { case 'button': return this.renderCellContentButtons(content, colIndex, rowIndex); case 'radio': return this.renderCellContentRadios(content, colIndex, rowIndex); case 'stepper': return this.renderCellContentStepper(content, colIndex, rowIndex); } } else { return renderCustomCell(content, colIndex, rowIndex); } } private renderCellContentButtons(content: string, colIndex: number, rowIndex: number) { const isActiveCell = this.activeCell.join('-') === `${colIndex}-${rowIndex}`; const buttons = content.split(', '); buttons.shift(); return buttons.map((button, i) => ( <button class="test-actions grid-button" id={`action-${rowIndex}-${colIndex}`} ref={isActiveCell && this.isEditing && i === 0 ? (el) => { this.focusRef = el; } : null} tabIndex={this.gridType === 'grid' ? isActiveCell && (this.isEditing || !this.modalCell) ? 0 : -1 : null} onClick={(() => alert(`This is just a test, you successfully activated the ${button} button`))} onKeyDown={(event) => (event.key === 'Enter' || event.key === ' ') && event.stopPropagation()} onFocus={() => { this.onCellFocus(rowIndex, colIndex)}} >{button}</button> )); } private renderCellContentStepper(content: string, colIndex: number, rowIndex: number) { const isActiveCell = this.activeCell.join('-') === `${colIndex}-${rowIndex}`; const data = content.split(', '); const label = data[1]; const value = Number(data[2]); const add = () => { this.stepperChangeEvent.emit({row: rowIndex - 1, value: value + 1}); }; const subtract = () => { this.stepperChangeEvent.emit({row: rowIndex - 1, value: value - 1}); }; return ([ <input type="tel" class="test-actions grid-stepper" aria-label={label} value={value || 0} ref={isActiveCell && this.isEditing ? (el) => { this.focusRef = el; } : null} tabIndex={isActiveCell && (this.isEditing || !this.modalCell) ? null : -1} onChange={(event) => this.stepperChangeEvent.emit({row: rowIndex-1, value: Number((event.target as HTMLInputElement).value) })} onFocus={() => { this.onCellFocus(rowIndex, colIndex)}} onKeyDown={this.onInputKeyDown.bind(this)} />, <button type="button" aria-label="add" class="test-actions grid-button" tabIndex={isActiveCell && (this.isEditing || !this.modalCell) ? null : -1} onClick={add} onKeyDown={(event) => (event.key === 'Enter' || event.key === ' ') && event.stopPropagation()}>+</button>, <button type="button" aria-label="subtract" class="test-actions grid-button" tabIndex={isActiveCell && (this.isEditing || !this.modalCell) ? null : -1} onClick={subtract} onKeyDown={(event) => (event.key === 'Enter' || event.key === ' ') && event.stopPropagation()}>-</button> ]) } private renderCellContentRadios(content: string, colIndex: number, rowIndex: number) { const isActiveCell = this.activeCell.join('-') === `${colIndex}-${rowIndex}`; const radios = content.split(', '); const name = `radio-${colIndex}-${rowIndex}`; radios.shift(); return radios.map((radio) => ( <label class="test-actions grid-radio" id={`action-${rowIndex}-${colIndex}`} > <input type="radio" name={name} ref={isActiveCell && this.isEditing ? (el) => { this.focusRef = el; } : null} tabIndex={this.gridType === 'grid' ? isActiveCell && (this.isEditing || !this.modalCell) ? 0 : -1 : null} onKeyDown={(event) => { (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'ArrowLeft' || event.key === 'ArrowRight') && event.stopPropagation(); }} onFocus={() => { this.onCellFocus(rowIndex, colIndex)}} /> {radio} </label> )); } private renderCheckboxCell(rowIndex: number, selected: boolean) { const activeCellId = this.activeCell.join('-'); return <td role="gridcell" class="checkbox-cell"> <input type="checkbox" checked={selected} aria-labelledby={`cell-${rowIndex}-${this.titleColumn + 1}`} tabIndex={activeCellId === `0-${rowIndex}` ? 0 : -1} ref={activeCellId === `0-${rowIndex}` ? (el) => { this.focusRef = el; } : null} onChange={(event) => this.onRowSelect(this.sortedCells[rowIndex - 1], (event.target as HTMLInputElement).checked)} onKeyDown={(event) => { (event.key === ' ' || event.key === 'Enter') && event.stopPropagation(); }} /> <span class="selection-indicator"></span> </td>; } private saveCell(column: number, row: number, value: string) { if (this.preventSave) { this.preventSave = false; return; } if (this.getColumnData(column).actionsColumn) { return; } this.editCellEvent.emit({ column, row: row - 1, value }); } private trapCellFocus(event: KeyboardEvent) { const cell = this.activeCellRef; const focusableSelector = 'button, [href], input, select, textarea, [tabindex]'; const focusables = cell.querySelectorAll(focusableSelector) as NodeListOf<HTMLElement>; if (!event.shiftKey && event.target === focusables[focusables.length - 1]) { event.preventDefault(); focusables[0].focus(); } else if (event.shiftKey && event.target === focusables[0]) { event.preventDefault(); focusables[focusables.length - 1].focus(); } } private updateActiveCell(colIndex, rowIndex): boolean { if (colIndex !== this.activeCell[0] || rowIndex !== this.activeCell[1]) { this.callFocus = true; this.activeCell = [colIndex, rowIndex]; return true; } return false; } private updateEditing(editing: boolean, callFocus: boolean) { if (!this.editable) { return }; this.isEditing = editing; this.callFocus = callFocus; this.callInputSelection = editing && callFocus; } }
the_stack
import { createMutator, runQuery, setOnGraphQLError } from '../server/vulcan-lib'; import Users from '../lib/collections/users/collection'; import { Posts } from '../lib/collections/posts' import { Comments } from '../lib/collections/comments' import Conversations from '../lib/collections/conversations/collection'; import Messages from '../lib/collections/messages/collection'; import {ContentState, convertToRaw} from 'draft-js'; import { randomId } from '../lib/random'; import type { PartialDeep } from 'type-fest' import { asyncForeachSequential } from '../lib/utils/asyncUtils'; import Localgroups from '../lib/collections/localgroups/collection'; // Hooks Vulcan's runGraphQL to handle errors differently. By default, Vulcan // would dump errors to stderr; instead, we want to (a) suppress that output, // (b) assert that particular errors are present in unit tests, and (c) if no // error was asserted to be present, assert that there were no errors. // // This should be called in unit tests from inside describe() but outside of // it(). For example: // // describe('Thing that uses GraphQL', () => { // let graphQLErrorCatcher = catchGraphQLErrors(); // // it('produces a permission-denied error', async () => { // // Do a thing that produces an error // // graphQLErrorCatcher.getErrors().should.equal(["app.mutation_not_allowed"]); // }) // // it('does not produce errors', async () => { // // Do a thing that should not produce errors // // Because this test does not interact with graphQLErrorCatcher, when // // it returns, it will implicitly assert that there were no errors. // }) // }); export const catchGraphQLErrors = function(before?: any, after?: any) { class ErrorCatcher { errors: Array<any> errorsRetrieved: boolean constructor() { this.errors = []; this.errorsRetrieved = false; } getErrors() { this.errorsRetrieved = true; return this.errors; } cleanup() { if (!this.errorsRetrieved && this.errors.length>0) { //eslint-disable-next-line no-console console.error("Unexpected GraphQL errors in test:"); //eslint-disable-next-line no-console console.error(this.errors); this.errors = []; this.errorsRetrieved = false; throw new Error(this.errors as any); } this.errors = []; this.errorsRetrieved = false; } addError(error: any) { if (Array.isArray(error)) { for (let i=0; i<error.length; i++) { this.errors.push(error); } } else { this.errors.push(error); } } } let errorCatcher = new ErrorCatcher(); (before ? before : beforeEach)(() => { setOnGraphQLError((errors: any) => { errorCatcher.addError(errors); }); }); (after ? after : afterEach)(() => { errorCatcher.cleanup(); setOnGraphQLError(null); }); return errorCatcher; }; // Given an error thrown from GraphQL, assert that it is permissions-flavored // (as opposed to a type error, syntax error, or random unrecognized thing). If // given an array of errors, asserts that all of them are permissions flavored. export const assertIsPermissionsFlavoredError = (error: any): void => { if (!isPermissionsFlavoredError(error)) { //eslint-disable-next-line no-console console.error(JSON.stringify(error)); throw new Error("Error is not permissions-flavored"); } } const isPermissionsFlavoredError = (error: any): boolean => { if (Array.isArray(error)) { if (error.length === 0) return false; for(let i=0; i<error.length; i++) { if (!isPermissionsFlavoredError(error[i])) return false; } return true; } if (!error) { return false; } if ("app.validation_error" in error) { return true; } if (!error.message) return false; if (isPermissionsFlavoredErrorString(error.message)) return true; let errorData: any = null; try { errorData = JSON.parse(error.message); } catch(e) { return false; } if (!errorData) return false; if (Array.isArray(errorData)) errorData = errorData[0]; if (isPermissionsFlavoredErrorString(errorData)) return true; if (errorData.id && isPermissionsFlavoredErrorString(errorData.id)) return true; return false; }; const isPermissionsFlavoredErrorString = (str: any): boolean => { switch (str) { case 'errors.disallowed_property_detected': case 'app.operation_not_allowed': case 'app.mutation_not_allowed': case 'app.user_cannot_moderate_post': return true; default: return false; } } export const createDefaultUser = async() => { // Creates defaultUser if they don't already exist const defaultUser = await Users.findOne({username:"defaultUser"}) if (!defaultUser) { return createDummyUser({username:"defaultUser"}) } else { return defaultUser } } // Posts can be created pretty flexibly type TestPost = Omit<PartialDeep<DbPost>, 'postedAt'> & {postedAt?: Date | number} export const createDummyPost = async (user?: AtLeast<DbUser, '_id'> | null, data?: TestPost) => { let user_ = user || await createDefaultUser() const defaultData = { userId: user_._id, title: randomId(), } const postData = {...defaultData, ...data}; const newPostResponse = await createMutator({ collection: Posts, // Not the best, createMutator should probably be more flexible about what // it accepts, as long as validate is false document: postData as DbPost, // As long as user has a _id it should be fine currentUser: user_ as DbUser, validate: false, }); return newPostResponse.data } export const createDummyUser = async (data?: any) => { const testUsername = randomId() const defaultData = { username: testUsername, email: testUsername + "@test.lesserwrong.com", reviewedByUserId: "fakeuserid", // TODO: make this user_id correspond to something real that would hold up if we had proper validation previousDisplayName: randomId() } const userData = {...defaultData, ...data}; const newUserResponse = await createMutator({ collection: Users, document: userData, validate: false, }) return newUserResponse.data; } export const createDummyComment = async (user: any, data?: any) => { const defaultUser = await createDefaultUser(); let defaultData: any = { userId: (user || defaultUser)._id, contents: { originalContents: { type: "markdown", data: "This is a test comment" } }, } if (!data.postId) { const randomPost = await Posts.findOne() if (!randomPost) throw Error("Can't find any post to generate random comment for") defaultData.postId = randomPost._id; // By default, just grab ID from a random post } const commentData = {...defaultData, ...data}; const newCommentResponse = await createMutator({ collection: Comments, document: commentData, currentUser: user || defaultUser, validate: false, }); return newCommentResponse.data } export const createDummyConversation = async (user: any, data?: any) => { let defaultData = { title: user.displayName, participantIds: [user._id], } const conversationData = {...defaultData, ...data}; const newConversationResponse = await createMutator({ collection: Conversations, document: conversationData, currentUser: user, validate: false, }); return newConversationResponse.data } export const createDummyMessage = async (user: any, data?: any) => { let defaultData = { contents: convertToRaw(ContentState.createFromText('Dummy Message Content')), userId: user._id, } const messageData = {...defaultData, ...data}; const newMessageResponse = await createMutator({ collection: Messages, document: messageData, currentUser: user, validate: false, }); return newMessageResponse.data } export const createDummyLocalgroup = async (data?: any) => { let defaultData = { name: randomId() } const groupData = {...defaultData, ...data}; const groupResponse = await createMutator({ collection: Localgroups, document: groupData, validate: false, }); return groupResponse.data } export const clearDatabase = async () => { await asyncForeachSequential(await Users.find().fetch(), async (i) => { await Users.rawRemove(i._id) }); await asyncForeachSequential(await Posts.find().fetch(), async (i) => { await Posts.rawRemove(i._id) }); await asyncForeachSequential(await Comments.find().fetch(), async (i) => { await Comments.rawRemove(i._id) }); } // Replacement for JSON.stringify, because that puts quotes around keys, and GraphQL does not // accept objects with quotes around the keys. // Copied from here: https://stackoverflow.com/a/11233515/8083739 // Jim's note: This will not work on objects that contain arrays that contain objects function stringifyObject(obj_from_json: any): string { if(typeof obj_from_json !== "object" || Array.isArray(obj_from_json) || obj_from_json instanceof Date){ // not an object or is a Date, stringify using native function return JSON.stringify(obj_from_json); } // Implements recursive object serialization according to JSON spec // but without quotes around the keys. let props = Object .keys(obj_from_json) .map((key: any) => `${key}:${stringifyObject(obj_from_json[key])}`) .join(","); return `{${props}}`; } export const userUpdateFieldFails = async ({user, document, fieldName, newValue, collectionType, fragment}: any) => { if (newValue === undefined) { newValue = randomId() } let newValueString = JSON.stringify(newValue) if (typeof newValue === "object") { newValueString = stringifyObject(newValue) } const query = ` mutation { update${collectionType}(selector: {_id:"${document._id}"},data:{${fieldName}:${newValueString}}) { data { ${fragment || fieldName} } } } `; const response = runQuery(query,{},{currentUser:user}) await (response as any).should.be.rejected; } export const userUpdateFieldSucceeds = async ({user, document, fieldName, collectionType, newValue, fragment}: any) => { let comparedValue = newValue if (newValue === undefined) { comparedValue = randomId() newValue = comparedValue; } let newValueString = JSON.stringify(newValue) if (typeof newValue === "object") { newValueString = stringifyObject(newValue) } const query = ` mutation { update${collectionType}(selector: {_id:"${document._id}"},data:{${fieldName}:${newValueString}}) { data { ${fragment || fieldName} } } } `; const response = runQuery(query,{},{currentUser:user}) const expectedOutput = { data: { [`update${collectionType}`]: { data: { [fieldName]: comparedValue} }}} return (response as any).should.eventually.deep.equal(expectedOutput); } export const stubbedTests = () => { describe("Stubbed unit test file", () => { it("Has a placeholder", () => { }); }); }
the_stack
import { formatQuery } from '..'; // If modulators have to be wrapped, they should be indented with two additional spaces, but consecutive steps should // not be indented with two additional spaces. Check that as-steps are indented as modulators. test('Wrapped modulators should be indented with two spaces', () => { // Test as()-modulator indentation expect( formatQuery( "g.V().has('name', within('marko', 'vadas', 'josh')).as('person').V().has('name', within('lop', 'ripple')).addE('uses').from('person')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V(). has('name', within('marko', 'vadas', 'josh')). as('person'). V(). has('name', within('lop', 'ripple')). addE('uses').from('person')`); // Test as_()-modulator indentation expect( formatQuery( "g.V().has('name', within('marko', 'vadas', 'josh')).as_('person').V().has('name', within('lop', 'ripple')).addE('uses').from('person')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V(). has('name', within('marko', 'vadas', 'josh')). as_('person'). V(). has('name', within('lop', 'ripple')). addE('uses').from('person')`); // Test by()-modulator indentation expect( formatQuery( "g.V().hasLabel('person').group().by(values('name', 'age').fold()).unfold().filter(select(values).count(local).is(gt(1)))", { indentation: 0, maxLineLength: 40, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V(). hasLabel('person'). group(). by(values('name', 'age').fold()). unfold(). filter( select(values). count(local). is(gt(1)))`); expect( formatQuery( "g.V().hasLabel('person').groupCount().by(values('age').choose(is(lt(28)),constant('young'),choose(is(lt(30)), constant('old'), constant('very old'))))", { indentation: 0, maxLineLength: 80, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V(). hasLabel('person'). groupCount(). by( values('age'). choose( is(lt(28)), constant('young'), choose(is(lt(30)), constant('old'), constant('very old'))))`); // Test emit()-modulator indentation expect( formatQuery("g.V(1).repeat(bothE('created').dedup().otherV()).emit().path()", { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(1). repeat(bothE('created').dedup().otherV()). emit(). path()`, ); expect( formatQuery('g.V().repeat(both()).times(1000000).emit().range(6,10)', { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). repeat(both()). times(1000000). emit(). range(6, 10)`, ); expect( formatQuery("g.V(1).repeat(out()).times(2).emit().path().by('name')", { indentation: 0, maxLineLength: 30, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(1). repeat(out()). times(2). emit(). path().by('name')`, ); expect( formatQuery("g.withSack(1).V(1).repeat(sack(sum).by(constant(1))).times(10).emit().sack().math('sin _')", { indentation: 0, maxLineLength: 40, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.withSack(1). V(1). repeat(sack(sum).by(constant(1))). times(10). emit(). sack(). math('sin _')`, ); // Test from()-modulator indentation expect( formatQuery( "g.V().has('person','name','vadas').as('e').in('knows').as('m').out('knows').where(neq('e')).path().from('m').by('name')", { indentation: 0, maxLineLength: 20, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has( 'person', 'name', 'vadas'). as('e'). in('knows'). as('m'). out('knows'). where(neq('e')). path(). from('m'). by('name')`, ); // Test from()-modulator indentation expect( formatQuery( "g.V().has('person','name','vadas').as_('e').in('knows').as_('m').out('knows').where(neq('e')).path().from_('m').by('name')", { indentation: 0, maxLineLength: 20, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has( 'person', 'name', 'vadas'). as_('e'). in('knows'). as_('m'). out('knows'). where(neq('e')). path(). from_('m'). by('name')`, ); // Test option()-modulator indentation expect( formatQuery( "g.V().hasLabel('person').choose(values('name')).option('marko', values('age')).option('josh', values('name')).option('vadas', elementMap()).option('peter', label())", { indentation: 0, maxLineLength: 80, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). choose(values('name')). option('marko', values('age')). option('josh', values('name')). option('vadas', elementMap()). option('peter', label())`, ); // Test read()-modulator indentation expect( formatQuery('g.io(someInputFile).read().iterate()', { indentation: 0, maxLineLength: 20, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someInputFile). read(). iterate()`, ); // Test times()-modulator indentation expect( formatQuery("g.V().repeat(both()).times(3).values('age').max()", { indentation: 0, maxLineLength: 20, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). repeat(both()). times(3). values('age'). max()`, ); // Test to()-modulator indentation expect( formatQuery("g.V(v1).addE('knows').to(v2).property('weight',0.75).iterate()", { indentation: 0, maxLineLength: 20, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(v1). addE('knows'). to(v2). property( 'weight', 0.75). iterate()`, ); // Test until()-modulator indentation expect( formatQuery( "g.V(6).repeat('a', both('created').simplePath()).emit(repeat('b', both('knows')).until(loops('b').as('b').where(loops('a').as('b'))).hasId(2)).dedup()", { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(6). repeat('a', both('created').simplePath()). emit( repeat('b', both('knows')). until( loops('b').as('b'). where(loops('a').as('b'))). hasId(2)). dedup()`, ); // Test with()-modulator indentation expect( formatQuery( "g.V().connectedComponent().with(ConnectedComponent.propertyName, 'component').project('name','component').by('name').by('component')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). project('name', 'component'). by('name'). by('component')`, ); expect( formatQuery( "g.V().hasLabel('person').connectedComponent().with(ConnectedComponent.propertyName, 'component').with(ConnectedComponent.edges, outE('knows')).project('name','component').by('name').by('component')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). with(ConnectedComponent.edges, outE('knows')). project('name', 'component'). by('name'). by('component')`, ); expect( formatQuery( "g.V().hasLabel('software').values('name').fold().order(Scope.local).index().with(WithOptions.indexer, WithOptions.list).unfold().order().by(__.tail(Scope.local, 1))", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('software'). values('name'). fold(). order(Scope.local). index(). with(WithOptions.indexer, WithOptions.list). unfold(). order().by(__.tail(Scope.local, 1))`, ); expect( formatQuery( "g.V().hasLabel('person').values('name').fold().order(Scope.local).index().with(WithOptions.indexer, WithOptions.map)", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). values('name'). fold(). order(Scope.local). index(). with(WithOptions.indexer, WithOptions.map)`, ); expect( formatQuery('g.io(someInputFile).with(IO.reader, IO.graphson).read().iterate()', { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someInputFile). with(IO.reader, IO.graphson). read(). iterate()`, ); expect( formatQuery('g.io(someOutputFile).with(IO.writer,IO.graphml).write().iterate()', { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someOutputFile). with(IO.writer, IO.graphml). write(). iterate()`, ); expect( formatQuery( "g.V().hasLabel('person').pageRank().with(PageRank.edges, __.outE('knows')).with(PageRank.propertyName, 'friendRank').order().by('friendRank',desc).elementMap('name','friendRank')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). pageRank(). with(PageRank.edges, __.outE('knows')). with(PageRank.propertyName, 'friendRank'). order().by('friendRank', desc). elementMap('name', 'friendRank')`, ); expect( formatQuery( "g.V().hasLabel('person').peerPressure().with(PeerPressure.propertyName, 'cluster').group().by('cluster').by('name')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). peerPressure(). with(PeerPressure.propertyName, 'cluster'). group().by('cluster').by('name')`, ); expect( formatQuery("g.V().shortestPath().with(ShortestPath.target, __.has('name','peter'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). shortestPath(). with(ShortestPath.target, __.has('name', 'peter'))`, ); expect( formatQuery( "g.V().shortestPath().with(ShortestPath.edges, Direction.IN).with(ShortestPath.target, __.has('name','josh'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). shortestPath(). with(ShortestPath.edges, Direction.IN). with(ShortestPath.target, __.has('name', 'josh'))`, ); expect( formatQuery("g.V().has('person','name','marko').shortestPath().with(ShortestPath.target,__.has('name','josh'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with(ShortestPath.target, __.has('name', 'josh'))`, ); expect( formatQuery( "g.V().has('person','name','marko').shortestPath().with(ShortestPath.target, __.has('name','josh')).with(ShortestPath.distance, 'weight')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with(ShortestPath.target, __.has('name', 'josh')). with(ShortestPath.distance, 'weight')`, ); expect( formatQuery( "g.V().has('person','name','marko').shortestPath().with(ShortestPath.target, __.has('name','josh')).with(ShortestPath.includeEdges, true)", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with(ShortestPath.target, __.has('name', 'josh')). with(ShortestPath.includeEdges, true)`, ); expect( formatQuery( "g.inject(g.withComputer().V().shortestPath().with(ShortestPath.distance, 'weight').with(ShortestPath.includeEdges, true).with(ShortestPath.maxDistance, 1).toList().toArray()).map(unfold().values('name','weight').fold())", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.inject( g.withComputer(). V(). shortestPath(). with(ShortestPath.distance, 'weight'). with(ShortestPath.includeEdges, true). with(ShortestPath.maxDistance, 1). toList(). toArray()). map(unfold().values('name', 'weight').fold())`, ); expect( formatQuery("g.V().hasLabel('person').valueMap().with(WithOptions.tokens)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). hasLabel('person'). valueMap(). with(WithOptions.tokens)`, ); expect( formatQuery("g.V().hasLabel('person').valueMap('name').with(WithOptions.tokens,WithOptions.labels)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). hasLabel('person'). valueMap('name'). with( WithOptions.tokens, WithOptions.labels)`, ); expect( formatQuery( "g.V().hasLabel('person').properties('location').valueMap().with(WithOptions.tokens, WithOptions.values)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). properties('location'). valueMap(). with( WithOptions.tokens, WithOptions.values)`, ); // Test with_()-modulator indentation expect( formatQuery( "g.V().connectedComponent().with_(ConnectedComponent.propertyName, 'component').project('name','component').by('name').by('component')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). connectedComponent(). with_(ConnectedComponent.propertyName, 'component'). project('name', 'component'). by('name'). by('component')`, ); expect( formatQuery( "g.V().hasLabel('person').connectedComponent().with_(ConnectedComponent.propertyName, 'component').with_(ConnectedComponent.edges, outE('knows')).project('name','component').by('name').by('component')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). connectedComponent(). with_(ConnectedComponent.propertyName, 'component'). with_(ConnectedComponent.edges, outE('knows')). project('name', 'component'). by('name'). by('component')`, ); expect( formatQuery( "g.V().hasLabel('software').values('name').fold().order(Scope.local).index().with_(WithOptions.indexer, WithOptions.list).unfold().order().by(__.tail(Scope.local, 1))", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('software'). values('name'). fold(). order(Scope.local). index(). with_(WithOptions.indexer, WithOptions.list). unfold(). order().by(__.tail(Scope.local, 1))`, ); expect( formatQuery( "g.V().hasLabel('person').values('name').fold().order(Scope.local).index().with_(WithOptions.indexer, WithOptions.map)", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). values('name'). fold(). order(Scope.local). index(). with_(WithOptions.indexer, WithOptions.map)`, ); expect( formatQuery('g.io(someInputFile).with_(IO.reader, IO.graphson).read().iterate()', { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someInputFile). with_(IO.reader, IO.graphson). read(). iterate()`, ); expect( formatQuery('g.io(someOutputFile).with_(IO.writer,IO.graphml).write().iterate()', { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someOutputFile). with_(IO.writer, IO.graphml). write(). iterate()`, ); expect( formatQuery( "g.V().hasLabel('person').pageRank().with_(PageRank.edges, __.outE('knows')).with_(PageRank.propertyName, 'friendRank').order().by('friendRank',desc).elementMap('name','friendRank')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). pageRank(). with_(PageRank.edges, __.outE('knows')). with_(PageRank.propertyName, 'friendRank'). order().by('friendRank', desc). elementMap('name', 'friendRank')`, ); expect( formatQuery( "g.V().hasLabel('person').peerPressure().with_(PeerPressure.propertyName, 'cluster').group().by('cluster').by('name')", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). peerPressure(). with_(PeerPressure.propertyName, 'cluster'). group().by('cluster').by('name')`, ); expect( formatQuery("g.V().shortestPath().with_(ShortestPath.target, __.has('name','peter'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). shortestPath(). with_(ShortestPath.target, __.has('name', 'peter'))`, ); expect( formatQuery( "g.V().shortestPath().with_(ShortestPath.edges, Direction.IN).with_(ShortestPath.target, __.has('name','josh'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). shortestPath(). with_(ShortestPath.edges, Direction.IN). with_(ShortestPath.target, __.has('name', 'josh'))`, ); expect( formatQuery("g.V().has('person','name','marko').shortestPath().with_(ShortestPath.target,__.has('name','josh'))", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with_(ShortestPath.target, __.has('name', 'josh'))`, ); expect( formatQuery( "g.V().has('person','name','marko').shortestPath().with_(ShortestPath.target, __.has('name','josh')).with_(ShortestPath.distance, 'weight')", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with_(ShortestPath.target, __.has('name', 'josh')). with_(ShortestPath.distance, 'weight')`, ); expect( formatQuery( "g.V().has('person','name','marko').shortestPath().with_(ShortestPath.target, __.has('name','josh')).with_(ShortestPath.includeEdges, true)", { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). has('person', 'name', 'marko'). shortestPath(). with_(ShortestPath.target, __.has('name', 'josh')). with_(ShortestPath.includeEdges, true)`, ); expect( formatQuery( "g.inject(g.withComputer().V().shortestPath().with_(ShortestPath.distance, 'weight').with_(ShortestPath.includeEdges, true).with_(ShortestPath.maxDistance, 1).toList().toArray()).map(unfold().values('name','weight').fold())", { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.inject( g.withComputer(). V(). shortestPath(). with_(ShortestPath.distance, 'weight'). with_(ShortestPath.includeEdges, true). with_(ShortestPath.maxDistance, 1). toList(). toArray()). map(unfold().values('name', 'weight').fold())`, ); expect( formatQuery("g.V().hasLabel('person').valueMap().with_(WithOptions.tokens)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). hasLabel('person'). valueMap(). with_(WithOptions.tokens)`, ); expect( formatQuery("g.V().hasLabel('person').valueMap('name').with_(WithOptions.tokens,WithOptions.labels)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.V(). hasLabel('person'). valueMap('name'). with_( WithOptions.tokens, WithOptions.labels)`, ); expect( formatQuery( "g.V().hasLabel('person').properties('location').valueMap().with_(WithOptions.tokens, WithOptions.values)", { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe( `g.V(). hasLabel('person'). properties('location'). valueMap(). with_( WithOptions.tokens, WithOptions.values)`, ); // Test write()-modulator indentation expect( formatQuery('g.io(someOutputFile).write().iterate()', { indentation: 0, maxLineLength: 25, shouldPlaceDotsAfterLineBreaks: false, }), ).toBe( `g.io(someOutputFile). write(). iterate()`, ); });
the_stack
import Table from '../classes/Table' import Entity, { EntityConstructor} from '../classes/Entity' import { DocumentClient } from './bootstrap-tests' describe('Entity creation', ()=> { it('creates basic entity w/ defaults', async () => { // Create entity const TestEntity = new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true } } }) expect(TestEntity.name).toBe('TestEntity') expect(TestEntity.schema.attributes.pk).toEqual({ partitionKey: true, type: 'string', coerce: true }) expect(TestEntity.schema.keys).toEqual({ partitionKey: 'pk' }) expect(TestEntity.schema.attributes.created).toHaveProperty('default') expect(TestEntity.schema.attributes.created.map).toBe('_ct') expect(TestEntity.schema.attributes.modified).toHaveProperty('default') expect(TestEntity.schema.attributes.modified.map).toBe('_md') expect(TestEntity.schema.attributes).toHaveProperty('_ct') expect(TestEntity.schema.attributes).toHaveProperty('_md') expect(TestEntity.defaults).toHaveProperty('_ct') expect(TestEntity.defaults).toHaveProperty('_md') expect(TestEntity._etAlias).toBe('entity') }) it('creates basic entity w/o timestamps', () => { let TestEntity = new Entity({ name: 'TestEntity', timestamps: false, attributes: { pk: { partitionKey: true } } }) expect(TestEntity.name).toBe('TestEntity') expect(TestEntity.schema.attributes.pk).toEqual({ partitionKey: true, type: 'string', coerce: true }) expect(TestEntity.schema.keys).toEqual({ partitionKey: 'pk' }) expect(TestEntity.schema.attributes).not.toHaveProperty('created') expect(TestEntity.schema.attributes).not.toHaveProperty('_ct') expect(TestEntity.schema.attributes).not.toHaveProperty('created') expect(TestEntity.schema.attributes).not.toHaveProperty('_md') expect(TestEntity.defaults).not.toHaveProperty('_ct') expect(TestEntity.defaults).not.toHaveProperty('_md') expect(TestEntity._etAlias).toBe('entity') }) it('creates entity that overrides timestamp names', () => { let TestEntity = new Entity({ name: 'TestEntity', created: 'createdAt', modified: 'modifiedAt', attributes: { pk: { partitionKey: true } } }) expect(TestEntity.schema.keys).toEqual({ partitionKey: 'pk' }) expect(TestEntity.schema.attributes.createdAt).toHaveProperty('default') expect(TestEntity.schema.attributes.modifiedAt).toHaveProperty('default') expect(TestEntity.defaults).toHaveProperty('createdAt') expect(TestEntity.defaults).toHaveProperty('modifiedAt') }) it('creates basic entity w/ required fields', () => { let TestEntity = new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: { type: 'string', required: true }, test2: { type: 'string', required: 'always' } } }) expect(TestEntity.required.test).toEqual(false) expect(TestEntity.required.test2).toEqual(true) }) it('creates entity w/ composite field type defaults and string assignment', () => { let TestEntity = new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: ['pk',0], test2: ['pk',1,'number'] } }) expect(TestEntity.schema.attributes.test.type).toBe('string') expect(TestEntity.schema.attributes.test2.type).toBe('number') expect(TestEntity.linked).toEqual({ pk: [ 'test', 'test2' ] }) }) it('creates entity w/ composite field alias', () => { let TestEntity = new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: ['pk',0, {alias: 'test2' }] } }) expect(TestEntity.schema.attributes.test2.map).toBe('test') }) it('fails when creating a entity without a partitionKey', () => { let result = () => new Entity({ name: 'TestEntity', attributes: {} }) expect(result).toThrow(`Entity requires a partitionKey attribute`) }) it('fails when creating a entity without a name', () => { // @ts-expect-error let result = () => new Entity({ attributes: { pk: { partitionKey: true } } }) expect(result).toThrow(`'name' must be defined`) }) it('fails when creating a entity with an invalid attributes object (array)', () => { let result = () => new Entity({ name: 'TestEntity', // @ts-expect-error attributes: [1,2,3] }) expect(result).toThrow(`Please provide a valid 'attributes' object`) }) it('fails when creating a entity with an invalid attributes object (string)', () => { let result = () => new Entity({ name: 'TestEntity', // @ts-expect-error attributes: 'test' }) expect(result).toThrow(`Please provide a valid 'attributes' object`) }) it('fails when attribute has an invalid type (string style)', () => { let result = () => new Entity({ name: 'TestEntity', attributes: { // @ts-expect-error pk: 'x' } }) expect(result).toThrow(`Invalid or missing type for 'pk'. Valid types are 'string', 'boolean', 'number', 'list', 'map', 'binary', and 'set'.`) }) it('fails when attribute has an invalid type (object style)', () => { let result = () => new Entity({ name: 'TestEntity', attributes: { // @ts-expect-error pk: { type: 'x' } } }) expect(result).toThrow(`Invalid or missing type for 'pk'. Valid types are 'string', 'boolean', 'number', 'list', 'map', 'binary', and 'set'.`) }) it(`fails when an attribute has invalid 'onUpdate' setting`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: { type: 'string', onUpdate: 'x' } } }) expect(result).toThrow(`'onUpdate' must be a boolean`) }) it(`fails when attribute alias duplicates existing property`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: { type: 'string', alias: 'pk' } } }) expect(result).toThrow(`'alias' must be a unique string`) }) it(`fails when an attribute uses 'setType' when not a 'set'`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: { type: 'string', setType: 'string' } } }) expect(result).toThrow(`'setType' is only valid for type 'set'`) }) it(`fails when attribute uses invalid 'setType'`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: { type: 'set', setType: 'test' } } }) expect(result).toThrow(`Invalid 'setType', must be 'string', 'number', or 'binary'`) }) it(`fails when setting an invalid attribute property type`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: { type: 'string', unknown: true } } }) expect(result).toThrow(`'unknown' is not a valid property type`) }) it(`fails when setting an invalid required property`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: { type: 'string', required: 'x' } } }) expect(result).toThrow(`'required' must be a boolean or set to 'always'`) }) it(`fails when composite references missing field`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: ['x',0] } }) expect(result).toThrow(`'test' must reference another field`) }) it(`fails when composite uses non-numeric index`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: ['pk','x'] } }) expect(result).toThrow(`'test' position value must be numeric`) }) it(`fails when composite uses invalid type`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, test: ['pk',1,'x'] } }) expect(result).toThrow(`'test' type must be 'string', 'number', 'boolean' or a configuration object`) }) it(`fails when composite array length is incorrect`, () => { let result = () => new Entity({ name: 'TestEntity', attributes: { pk: { partitionKey: true }, // @ts-expect-error test: ['pk'] } }) expect(result).toThrow(`Composite key configurations must have 2 or 3 items`) }) it(`fails when missing entity definition`, () => { // @ts-expect-error let result = () => new Entity() expect(result).toThrow(`Please provide a valid entity definition`) }) it(`fails when providing an invalid entity definition`, () => { // @ts-expect-error let result = () => new Entity('test') expect(result).toThrow(`Please provide a valid entity definition`) }) it(`fails when providing an array as the entity definition`, () => { // @ts-expect-error let result = () => new Entity([]) expect(result).toThrow(`Please provide a valid entity definition`) }) // it('creates entity w/ table', async () => { // // Create basic table // const TestTable = new Table({ // name: 'test-table', // partitionKey: 'pk' // }) // // Create basic entity // const TestEntity = new Entity({ // name: 'TestEnt', // attributes: { // pk: { partitionKey: true } // }, // table: TestTable // }) // expect(TestTable instanceof Table).toBe(true) // expect(TestTable.name).toBe('test-table') // expect(TestTable.Table.partitionKey).toBe('pk') // expect(TestTable.Table.sortKey).toBeNull() // expect(TestTable.Table.entityField).toBe('_et') // expect(TestTable.Table.indexes).toEqual({}) // expect(TestTable.Table.attributes).toEqual({ // _et: { type: 'string', mappings: {} }, // pk: { type: 'string', mappings: { TestEnt: { pk: 'string' } } }, // _ct: { mappings: { TestEnt: { created: 'string' } } }, // _md: { mappings: { TestEnt: { modified: 'string' } } } // }) // expect(TestTable.autoExecute).toBe(true) // expect(TestTable.autoParse).toBe(true) // expect(TestTable.entities).toEqual(['TestEnt']) // expect(TestEntity.schema.keys).toEqual({ partitionKey: 'pk' }) // expect(TestEntity.schema.attributes.created).toHaveProperty('default') // expect(TestEntity.schema.attributes.created.map).toBe('_ct') // expect(TestEntity.schema.attributes.modified).toHaveProperty('default') // expect(TestEntity.schema.attributes.modified.map).toBe('_md') // expect(TestEntity.schema.attributes).toHaveProperty('_ct') // expect(TestEntity.schema.attributes).toHaveProperty('_md') // expect(TestEntity.defaults).toHaveProperty('_ct') // expect(TestEntity.defaults).toHaveProperty('_md') // expect(TestEntity._etAlias).toBe('entity') // }) // creates entity w/ table // it('creates entity composite key delimiter, prefix and suffix', async () => { // // Create basic table // const TestTable = new Table({ // name: 'test-table', // partitionKey: 'pk', // DocumentClient // }) // // Create basic entity // const TestEntity = new Entity({ // name: 'TestEnt', // attributes: { // pk: { partitionKey: true }, // sk: { delimiter: '|', prefix: 'test---', suffix: '-end', map: 'skx' }, // test0: ['sk',0], // test1: ['sk',1], // test2: ['sk',2], // comp1: {}, // test0c: ['comp1',0, { save: false }], // test1c: ['comp1',1], // test2c: ['comp1',2] // }, // table: TestTable, // timestamps: false // }) // let result = TestEntity.putParams({ // pk: 'test', // test0: '0', // test1: '1', // test2: '2', // test0c: '0', // test1c: 1, // test2c: '2' // }) // expect(result).toEqual({ // TableName: 'test-table', // Item: { // skx: 'test---0|1|2-end', // comp1: '0#1#2', // _et: 'TestEnt', // pk: 'test', // test0: '0', // test1: '1', // test2: '2', // test1c: '1', // test2c: '2' // } // }) // expect(TestEntity.parse({ // skx: 'test---0|1|2-end', // comp1: '0#1#2', // _et: 'TestEnt', // pk: 'test', // test0: '0', // test1: '1', // test2: '2', // test1c: '1', // test2c: '2' // })).toEqual({ // sk: '0|1|2', // test0c: '0', // comp1: '0#1#2', // entity: 'TestEnt', // pk: 'test', // test0: '0', // test1: '1', // test2: '2', // test1c: '1', // test2c: '2' // }) // }) // it('creates an attribute with a prefix and suffix', async () => { // // Create basic table // const TestTable = new Table({ // name: 'test-table', // partitionKey: 'pk', // DocumentClient // }) // // Create basic entity // const TestEntity = new Entity({ // name: 'TestEnt', // attributes: { // pk: { partitionKey: true, prefix: '#user#' }, // test: { prefix: 'startX--', suffix: '--endX' }, // num: { type: 'number' } // }, // table: TestTable, // timestamps: false // }) // let result = TestEntity.putParams({ // pk: 'test', // test: 'testx', // num: 5 // }) // expect(result).toEqual({ // TableName: 'test-table', // Item: { // _et: 'TestEnt', // pk: '#user#test', // test: 'startX--testx--endX', // num: 5 // } // }) // expect(TestEntity.parse({ // _et: 'TestEnt', // pk: '#user#test', // test: 'startX--testx--endX', // num: 5 // })).toEqual({ // entity: 'TestEnt', pk: 'test', test: 'testx', num: 5 // }) // }) // creates attribute with prefix/suffix // it('creates an attribute a transformation function', async () => { // // Create basic table // const TestTable = new Table({ // name: 'test-table', // partitionKey: 'pk', // sortKey: 'sk', // DocumentClient // }) // // Create basic entity // const TestEntity = new Entity({ // name: 'TestEnt', // attributes: { // pk: { partitionKey: true, transform: (val) => val.toUpperCase(), default: 'pkDef' }, // test: { // transform: (val,data) => { // return val.toUpperCase() // }, // default: () => 'defaultVal', // prefix: 'pre-' // }, // sk: { type: 'string', prefix: 'testprev-', sortKey: true, delimiter: '|' }, // testx: ['sk',0], // testy: ['sk',1, { // default: () => 'testDefaultX', // transform: (val) => { return '__'+val.toUpperCase() } // }] // }, // table: TestTable, // timestamps: false // }) // let result = TestEntity.putParams({ // testx: 1 // }) // expect(result).toEqual({ // TableName: 'test-table', // Item: { // sk: 'testprev-1|__TESTDEFAULTX', // pk: 'PKDEF', // test: 'pre-DEFAULTVAL', // testy: '__TESTDEFAULTX', // _et: 'TestEnt', // testx: '1' // } // }) // let result2 = TestEntity.getParams({ // testx: 'test', // testy: 'testx' // }) // expect(result2).toEqual({ // TableName: 'test-table', // Key: { pk: 'PKDEF', sk: 'testprev-test|__TESTX' } // }) // let result3 = TestEntity.updateParams({ // testx: 'test', // testy: 'testx', // test: 'uppercase' // }) // expect(result3).toEqual({ // TableName: 'test-table', // Key: { pk: 'PKDEF', sk: 'testprev-test|__TESTX' }, // UpdateExpression: 'SET #test = :test, #testy = :testy, #_et = if_not_exists(#_et,:_et), #testx = :testx', // ExpressionAttributeNames: { // '#test': 'test', // '#testy': 'testy', // '#_et': '_et', // '#testx': 'testx' // }, // ExpressionAttributeValues: { // ':test': 'pre-UPPERCASE', // ':testy': '__TESTX', // ':_et': 'TestEnt', // ':testx': 'test' // } // }) // // console.log(result); // // console.log(result2); // // console.log(result3); // }) // creates attribute with transformations })
the_stack
import * as crypto from "crypto"; import * as fs from "fs-plus"; import * as getmac from "getmac"; import { Guid } from "guid-typescript"; import * as _ from "lodash"; import * as opn from "opn"; import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; import * as WinReg from "winreg"; import { BoardProvider } from "../boardProvider"; import { ArduinoCommands } from "../common/Commands"; import { TypeNotSupportedError } from "../common/Error/SystemErrors/TypeNotSupportedError"; import { ResourceNotFoundError } from "../common/Error/OperationFailedErrors/ResourceNotFoundError"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError"; import { FileNames, OSPlatform, ScaffoldType } from "../constants"; import { DialogResponses } from "../DialogResponses"; import { FileUtility } from "../FileUtility"; import { TelemetryContext } from "../telemetry"; import { delay, getEnumKeyByEnumValue, getRegistryValues } from "../utils"; import { Board } from "./Interfaces/Board"; import { reject } from "bluebird"; import { ArduinoDeviceBase } from "./ArduinoDeviceBase"; import { DeviceType } from "./Interfaces/Device"; import { DeviceConfig, TemplateFileInfo } from "./Interfaces/ProjectTemplate"; import { FileNotFoundError } from "../common/Error/OperationFailedErrors/FileNotFound"; import { DirectoryNotFoundError } from "../common/Error/OperationFailedErrors/DirectoryNotFoundError"; import { SystemResourceNotFoundError } from "../common/Error/SystemErrors/SystemResourceNotFoundError"; import { AzureConfigFileHandler } from "./AzureComponentConfig"; import { ComponentType } from "./Interfaces/Component"; const importLazy = require("import-lazy"); const forEach = importLazy(() => require("lodash.foreach"))() as typeof import("lodash.foreach"); const trimStart = importLazy(() => require("lodash.trimstart"))(); interface SerialPortInfo { path: string; manufacturer: string; vendorId: string; productId: string; } const constants = { outputPath: "./.build", platformLocalFileName: "platform.local.txt", cExtraFlag: 'compiler.c.extra_flags=-DCORRELATIONID="', cppExtraFlag: 'compiler.cpp.extra_flags=-DCORRELATIONID="', traceExtraFlag: " -DENABLETRACE=", informationPageUrl: "https://aka.ms/AA35xln" }; enum ConfigDeviceOptions { ConnectionString = "Config Device Connection String", UDS = "Config DPS Unique Device Secret (UDS)", DPS = "Config DPS credentials", CRC = "Generate CRC for OTA" } enum DeviceConnectionStringAcquisitionMethods { Input = "Input IoT Hub Device Connection String", Select = "Select IoT Hub Device Connection String" } export class AZ3166Device extends ArduinoDeviceBase { // eslint-disable-next-line @typescript-eslint/no-explicit-any static get serialport(): any { if (!AZ3166Device._serialport) { AZ3166Device._serialport = require("node-usb-native").SerialPort; } return AZ3166Device._serialport; } // eslint-disable-next-line @typescript-eslint/no-explicit-any private static _serialport: any; private componentId: string; get id(): string { return this.componentId; } private static _boardId = "devkit"; private azureConfigFileHandler: AzureConfigFileHandler; static get boardId(): string { return AZ3166Device._boardId; } constructor( context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext, devicePath: string, templateFiles?: TemplateFileInfo[] ) { super(context, devicePath, channel, telemetryContext, DeviceType.MXChipAZ3166); this.channel = channel; this.componentId = Guid.create().toString(); if (templateFiles) { this.templateFiles = templateFiles; } const projectFolder = devicePath + "/.."; this.azureConfigFileHandler = new AzureConfigFileHandler(projectFolder); } name = "AZ3166"; get board(): Board { const boardProvider = new BoardProvider(this.boardFolderPath); const az3166 = boardProvider.find({ id: AZ3166Device._boardId }); if (!az3166) { throw new SystemResourceNotFoundError("AZ3166 board", `board id ${AZ3166Device._boardId}`, "board list"); } return az3166; } get version(): string { const packageRootPath = this.getArduinoPackagePath(); let version = "0.0.1"; if (fs.existsSync(packageRootPath)) { const versions = fs.readdirSync(packageRootPath); if (versions[0]) { version = versions[0]; } } return version; } async create(): Promise<void> { this.createCore(); } async preCompileAction(): Promise<boolean> { await this.generatePlatformLocal(); return true; } async preUploadAction(): Promise<boolean> { const isStlinkInstalled = await this.stlinkDriverInstalled(); if (!isStlinkInstalled) { const message = "The ST-LINK driver for DevKit is not installed. Install now?"; const result: vscode.MessageItem | undefined = await vscode.window.showWarningMessage( message, DialogResponses.yes, DialogResponses.skipForNow, DialogResponses.cancel ); if (result === DialogResponses.yes) { // Open the download page const installUri = "http://www.st.com/en/development-tools/stsw-link009.html"; opn(installUri); return true; } else if (result !== DialogResponses.cancel) { return false; } } // Enable logging on IoT Devkit await this.generatePlatformLocal(); return true; } async configDeviceSettings(): Promise<void> { // Select device settings type const deviceSettingType = await this.selectDeviceSettingType(); let credentials = ""; switch (deviceSettingType) { case ConfigDeviceOptions.CRC: await this.generateCrc(this.channel); return; case ConfigDeviceOptions.ConnectionString: // Get device connection string credentials = await this.getDeviceConnectionString(); await this.logAndSetCredentials(credentials, ConfigDeviceOptions.ConnectionString); return; case ConfigDeviceOptions.DPS: // Get DPS Credential credentials = await this.getDPSCredentialsFromInput(); await this.logAndSetCredentials(credentials, ConfigDeviceOptions.DPS); return; case ConfigDeviceOptions.UDS: // Get UDS string credentials = await this.getUDSStringFromInput(); await this.logAndSetCredentials(credentials, ConfigDeviceOptions.UDS); return; default: throw new TypeNotSupportedError("device setting type", `${deviceSettingType}`); } } // Private functions for configure device settings /** * Print credentials in log. Set credentials to device. * Pop up information message suggesting configuration operation is * successful. * @param credentials device credentials * @param deviceSettingType device setting type * @param deviceSettingsType device settings type info to be print in warning * window */ private async logAndSetCredentials(credentials: string, deviceSettingType: ConfigDeviceOptions): Promise<void> { // Log Credentials console.log(credentials); // Set credentials const res = await this.setDeviceConfig(credentials, deviceSettingType); // TODO: Mind the return value. if (!res) { throw new OperationFailedError( "flush configuration to device", "", "Please check out error message in the output channel." ); } let deviceSettingTypeForLog; switch (deviceSettingType) { case ConfigDeviceOptions.ConnectionString: deviceSettingTypeForLog = "device connection string"; break; case ConfigDeviceOptions.DPS: deviceSettingTypeForLog = "DPS credentials"; break; case ConfigDeviceOptions.UDS: deviceSettingTypeForLog = "Unique Device String (UDS)"; break; default: throw new TypeNotSupportedError("device setting type", `${deviceSettingType}`); } vscode.window.showInformationMessage(`Successfully configure ${deviceSettingTypeForLog}.`); } /** * Select device setting type. */ private async selectDeviceSettingType(): Promise<ConfigDeviceOptions> { const configSelectionItems = await this.getConfigDeviceSettingTypeOptions(); const configSelection = await vscode.window.showQuickPick(configSelectionItems, { ignoreFocusOut: true, matchOnDescription: true, matchOnDetail: true, placeHolder: "Select an option" }); if (!configSelection) { throw new OperationCanceledError("Config device settings option selection cancelled."); } const deviceSettingsType: ConfigDeviceOptions = getEnumKeyByEnumValue(ConfigDeviceOptions, configSelection.label); return deviceSettingsType; } /** * Get config device setting type options. */ private async getConfigDeviceSettingTypeOptions(): Promise<vscode.QuickPickItem[]> { // Read options configuration JSON const devciceConfigFilePath: string = this.extensionContext.asAbsolutePath( path.join(FileNames.resourcesFolderName, FileNames.templatesFolderName, FileNames.configDeviceOptionsFileName) ); const configSelectionItemsFilePath = await FileUtility.readFile(ScaffoldType.Local, devciceConfigFilePath, "utf8"); const configSelectionItemsContent = JSON.parse(configSelectionItemsFilePath as string); const configSelectionItems: vscode.QuickPickItem[] = []; configSelectionItemsContent.configSelectionItems.forEach((element: DeviceConfig) => { configSelectionItems.push({ label: element.label, description: "", detail: element.detail }); }); return configSelectionItems; } /** * Get device connection string. * Either get from workspace config or input one. */ private async getDeviceConnectionString(): Promise<string> { // Get device connection string from workspace config let deviceConnectionStringFromConfig: string | undefined; const componentConfig = await this.azureConfigFileHandler.getComponentByType( ScaffoldType.Workspace, ComponentType.IoTHubDevice ); if (componentConfig) { deviceConnectionStringFromConfig = componentConfig.componentInfo?.values.iotHubDeviceConnectionString; } let deviceConnectionString: string; if (deviceConnectionStringFromConfig) { // Select method to acquire device connection string const deviceConnectionStringAcquisitionMethodSelection = await this.selectDeviceConnectionStringAcquisitionMethod( deviceConnectionStringFromConfig ); if (deviceConnectionStringAcquisitionMethodSelection.label === DeviceConnectionStringAcquisitionMethods.Select) { deviceConnectionString = deviceConnectionStringFromConfig; return deviceConnectionString; } } deviceConnectionString = await this.getInputDeviceConnectionString(); return deviceConnectionString; } /** * Select method to get device connection string: input a new one or get from * configuration. */ private async selectDeviceConnectionStringAcquisitionMethod( deviceConnectionString: string ): Promise<vscode.QuickPickItem> { const deviceConnectionStringAcquisitionOptions = this.getDeviceConnectionStringAcquisitionOptions( deviceConnectionString ); const deviceConnectionStringAcquisitionSelection = await vscode.window.showQuickPick( deviceConnectionStringAcquisitionOptions, { ignoreFocusOut: true, placeHolder: "Choose an option:" } ); if (!deviceConnectionStringAcquisitionSelection) { throw new OperationCanceledError("Device connection string acquisition method selection cancelled."); } return deviceConnectionStringAcquisitionSelection; } private getDeviceConnectionStringAcquisitionOptions(deviceConnectionString: string): vscode.QuickPickItem[] { let deviceConnectionStringAcquisitionOptions: vscode.QuickPickItem[] = []; const inputDeviceConnectionStringOption = { label: DeviceConnectionStringAcquisitionMethods.Input, description: "", detail: "" }; let hostName = ""; let deviceId = ""; const hostnameMatches = deviceConnectionString.match(/HostName=(.*?)(;|$)/); if (hostnameMatches) { hostName = hostnameMatches[0]; } const deviceIDMatches = deviceConnectionString.match(/DeviceId=(.*?)(;|$)/); if (deviceIDMatches) { deviceId = deviceIDMatches[0]; } if (deviceId && hostName) { deviceConnectionStringAcquisitionOptions = [ { label: DeviceConnectionStringAcquisitionMethods.Select, description: "", detail: `Device Information: ${hostName} ${deviceId}` }, inputDeviceConnectionStringOption ]; } else { deviceConnectionStringAcquisitionOptions = [inputDeviceConnectionStringOption]; } return deviceConnectionStringAcquisitionOptions; } private async getInputDeviceConnectionString(): Promise<string> { const option = this.getInputDeviceConnectionStringOptions(); const deviceConnectionString = await vscode.window.showInputBox(option); if (!deviceConnectionString) { const message = "Need more information on how to get device connection string?"; const result: vscode.MessageItem | undefined = await vscode.window.showWarningMessage( message, DialogResponses.yes, DialogResponses.no ); if (result === DialogResponses.yes) { opn(constants.informationPageUrl); } throw new OperationCanceledError("Fail to get input device connection string."); } return deviceConnectionString; } private getInputDeviceConnectionStringOptions(): vscode.InputBoxOptions { const option: vscode.InputBoxOptions = { value: "HostName=<Host Name>;DeviceId=<Device Name>;SharedAccessKey=<Device Key>", prompt: `Please input device connection string here.`, ignoreFocusOut: true, validateInput: (deviceConnectionString: string) => { if (!deviceConnectionString) { return "Please provide a valid device connection string."; } if ( deviceConnectionString.indexOf("HostName") === -1 || deviceConnectionString.indexOf("DeviceId") === -1 || deviceConnectionString.indexOf("SharedAccessKey") === -1 ) { return "The format of the IoT Hub Device connection string is invalid."; } return; } }; return option; } /** * Get DPS credentials from input box. */ private async getDPSCredentialsFromInput(): Promise<string> { const option = this.getDPSConnectionStringOptions(); const dpsCredential = await vscode.window.showInputBox(option); if (!dpsCredential) { throw new OperationCanceledError("DPS credentials input cancelled."); } return dpsCredential; } private getDPSConnectionStringOptions(): vscode.InputBoxOptions { const option: vscode.InputBoxOptions = { value: "DPSEndpoint=global.azure-devices-provisioning.net;IdScope=<Id Scope>;DeviceId=<Device Id>;SymmetricKey=<Symmetric Key>", prompt: `Please input DPS credentials here.`, ignoreFocusOut: true, validateInput: (deviceConnectionString: string) => { if (!deviceConnectionString) { return "Please provide a valid DPS credentials."; } if ( deviceConnectionString.indexOf("DPSEndpoint") === -1 || deviceConnectionString.indexOf("IdScope") === -1 || deviceConnectionString.indexOf("DeviceId") === -1 || deviceConnectionString.indexOf("SymmetricKey") === -1 ) { return "The format of the DPS credentials is invalid."; } return; } }; return option; } /** * Get UDS string from input box. */ private async getUDSStringFromInput(): Promise<string> { const option = this.getUDSStringOptions(); const UDS = await vscode.window.showInputBox(option); if (!UDS) { throw new OperationCanceledError("UDS string input cancelled."); } return UDS; } private getUDSStringOptions(): vscode.InputBoxOptions { function generateRandomHex(): string { const chars = "0123456789abcdef".split(""); let hexNum = ""; for (let i = 0; i < 64; i++) { hexNum += chars[Math.floor(Math.random() * 16)]; } return hexNum; } const option: vscode.InputBoxOptions = { value: generateRandomHex(), prompt: `Please input Unique Device String (UDS) here.`, ignoreFocusOut: true, validateInput: (UDS: string) => { if (/^([0-9a-f]){64}$/i.test(UDS) === false) { return "The format of the UDS is invalid. Please provide a valid UDS."; } return ""; } }; return option; } /** * Flush device configurations to device * @param configValue config value * @param option device configuration type */ private async setDeviceConfig(configValue: string, option: ConfigDeviceOptions): Promise<boolean> { // Try to close serial monitor try { await vscode.commands.executeCommand(ArduinoCommands.CloseSerialMonitor, null, false); } catch (ignore) { // Ignore error if fail to close serial monitor } // Set selected connection string to device const platform = os.platform(); if (platform === OSPlatform.WIN32) { return await this.flushDeviceConfig(configValue, option); } else { return await this.flushDeviceConfigUnixAndMac(configValue, option); } } private flushDeviceConfigUnixAndMac(configValue: string, option: ConfigDeviceOptions): Promise<boolean> { return new Promise( // eslint-disable-next-line no-async-promise-executor async (resolve: (value: boolean) => void, reject: (value: Error) => void) => { let comPort = ""; let command = ""; try { // Choose COM port that AZ3166 is connected comPort = await this.chooseCOM(); console.log(`Opening ${comPort}.`); } catch (error) { return reject(error); } if (option === ConfigDeviceOptions.ConnectionString) { command = "set_az_iothub"; } else if (option === ConfigDeviceOptions.DPS) { command = "set_az_iotdps"; } else { command = "set_dps_uds"; } let errorRejected = false; let az3166: Board; try { az3166 = this.board; } catch (error) { return reject(error); } const port = new AZ3166Device.serialport(comPort, { baudRate: az3166.defaultBaudRate, dataBits: 8, stopBits: 1, xon: false, xoff: false, parity: "none" }); const rejectIfError = (err: Error): boolean => { if (errorRejected) return true; if (err) { errorRejected = true; reject(err); try { port.close(); } catch (ignore) { // ignore error if fail to close port. } } return true; }; const executeSetAzIoTHub = async (): Promise<void> => { try { const data = `${command} "${configValue}"\r\n`; let restDataLength = data.length; while (restDataLength > 0) { const start = data.length - restDataLength; const length = Math.min(100, restDataLength); restDataLength -= length; const dataChunk = data.substr(start, length); await this.sendDataViaSerialPort(port, dataChunk); await delay(1000); } port.close(); } catch (ignore) { // Ignore error if fail to close port } if (errorRejected) { return; } else { resolve(true); } }; // Configure serial port callbacks port.on("open", async () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any await vscode.window.showInformationMessage( "Please hold down button A and then push and release the reset button to enter configuration mode. After enter configuration mode, click OK.", "OK" ); executeSetAzIoTHub() .then(() => resolve(true)) .catch(error => reject(error)); }); // eslint-disable-next-line @typescript-eslint/no-explicit-any port.on("error", (error: any) => { if (errorRejected) return; console.log(error); rejectIfError(error); }); } ); } private flushDeviceConfig(configValue: string, option: ConfigDeviceOptions): Promise<boolean> { return new Promise( // eslint-disable-next-line no-async-promise-executor async (resolve: (value: boolean) => void, reject: (value: Error) => void) => { let comPort = ""; let command = ""; try { // Choose COM port that AZ3166 is connected comPort = await this.chooseCOM(); console.log(`Opening ${comPort}.`); } catch (error) { reject(error); } if (option === ConfigDeviceOptions.ConnectionString) { command = "set_az_iothub"; } else if (option === ConfigDeviceOptions.DPS) { command = "set_az_iotdps"; } else { command = "set_dps_uds"; } let configMode = false; let errorRejected = false; let commandExecuted = false; let gotData = false; let az3166: Board; try { az3166 = this.board; } catch (error) { return reject(error); } const port = new AZ3166Device.serialport(comPort, { baudRate: az3166.defaultBaudRate, dataBits: 8, stopBits: 1, xon: false, xoff: false, parity: "none" }); const rejectIfError = (err: Error): boolean => { if (errorRejected) return true; if (err) { errorRejected = true; reject(err); try { port.close(); } catch (ignore) { // Ignore error if fail to close port } } return true; }; const executeSetAzIoTHub = async (): Promise<void> => { try { const data = `${command} "${configValue}"\r\n`; const maxDataLength = 256; await this.sendDataViaSerialPort(port, data.slice(0, maxDataLength)); if (data.length > maxDataLength) { await delay(1000); await this.sendDataViaSerialPort(port, data.slice(maxDataLength)); } await delay(1000); port.close(); } catch (ignore) { // Ignore error if fail to close port } if (errorRejected) { return; } else { resolve(true); } }; // Configure serial port callbacks port.on("open", () => { port.write( "\r\nhelp\r\n", // eslint-disable-next-line @typescript-eslint/no-explicit-any (error: any) => { if (rejectIfError(error)) return; } ); }); // eslint-disable-next-line @typescript-eslint/no-explicit-any port.on("data", (data: any) => { gotData = true; const output = data.toString().trim(); if (commandExecuted) return; if (output.includes("set_")) { commandExecuted = true; configMode = true; executeSetAzIoTHub() .then(() => resolve(true)) .catch(error => reject(error)); } else { configMode = false; } if (configMode) { forEach(output.split("\n"), line => { if (line) { line = trimStart(line.trim(), "#").trim(); if (line && line.length) { console.log("SerialOutput", line); } } }); } }); // eslint-disable-next-line @typescript-eslint/no-explicit-any port.on("error", (error: any) => { if (errorRejected) return; console.log(error); rejectIfError(error); }); setTimeout(() => { if (errorRejected) return; // Prompt user to enter configuration mode if (!gotData || !configMode) { vscode.window .showInformationMessage( "Please hold down button A and then push and release the reset button to enter configuration mode." ) .then(() => { port.write( "\r\nhelp\r\n", // eslint-disable-next-line @typescript-eslint/no-explicit-any (error: any) => { rejectIfError(error); } ); }); } }, 10000); } ); } private async getComList(): Promise<SerialPortInfo[]> { const lists = await AZ3166Device.serialport.list(); return lists; } private async chooseCOM(): Promise<string> { return new Promise(async (resolve: (value: string) => void, reject: (reason: Error) => void) => { const comList = await this.getComList(); let az3166: Board; try { az3166 = this.board; } catch (error) { return reject(error); } const list = _.filter(comList, com => { if ( com.vendorId && com.productId && az3166.vendorId && az3166.productId && com.vendorId.toLowerCase().endsWith(az3166.vendorId) && com.productId.toLowerCase().endsWith(az3166.productId) ) { return true; } else { return false; } }); if (list && list.length) { let comPort = list[0].path; if (list.length > 1) { // TODO: select com port from list when there are multiple AZ3166 // boards connected comPort = list[0].path; } if (!comPort) { reject(new ResourceNotFoundError("choose COM", "avaliable COM port.", "Please check COM port settings.")); } resolve(comPort); } else { reject(new Error("No AZ3166 board connected.")); } }); } private async sendDataViaSerialPort( // eslint-disable-next-line @typescript-eslint/no-explicit-any port: any, data: string ): Promise<boolean> { return new Promise((resolve: (value: boolean) => void, reject: (value: Error) => void) => { try { port.write( data, // eslint-disable-next-line @typescript-eslint/no-explicit-any (err: any) => { if (err) { reject(err); } else { port.drain(() => resolve(true)); } } ); } catch (err) { reject(err); } }); } private async stlinkDriverInstalled(): Promise<boolean> { const platform = os.platform(); if (platform === OSPlatform.WIN32) { try { // The STlink driver would write to the following registry. const pathString = await getRegistryValues( WinReg.HKLM, "\\SYSTEM\\ControlSet001\\Control\\Class\\{88bae032-5a81-49f0-bc3d-a4ff138216d6}", "Class" ); if (pathString) { return true; } else { return false; } } catch (error) { return false; } } // For other OS platform, there is no need to install STLink Driver. return true; } private async generatePlatformLocal(): Promise<void> { const arduinoPackagePath = this.getArduinoPackagePath(); function getHashMacAsync(): Promise<unknown> { return new Promise(resolve => { getmac.getMac((err, macAddress) => { if (err) { reject(err); } const hashMacAddress = crypto .createHash("sha256") .update(macAddress, "utf8") .digest("hex"); resolve(hashMacAddress); }); }); } if (!fs.existsSync(arduinoPackagePath)) { const suggestedOperation = 'Please install it from https://www.arduino.cc/en/main/software and use "Arduino: Board Manager" to install your device packages. Restart VS Code to apply to changes.'; throw new ResourceNotFoundError( `generate ${constants.platformLocalFileName} file`, "Arduino IDE", suggestedOperation ); } const files = fs.readdirSync(arduinoPackagePath); for (let i = files.length - 1; i >= 0; i--) { if (files[i] === ".DS_Store") { files.splice(i, 1); } } if (files.length === 0 || files.length > 1) { throw new FileNotFoundError( `generate ${constants.platformLocalFileName} file`, `files under Arduino package installation path ${arduinoPackagePath}`, "Please clear the path and reinstall the package for Devkit." ); } const directoryName = path.join(arduinoPackagePath, files[0]); if (!fs.isDirectorySync(directoryName)) { throw new DirectoryNotFoundError( `generate ${constants.platformLocalFileName} file`, "Arduino package for MXChip IoT Devkit", "Please follow guide to install the DevKit package." ); } const fileName = path.join(directoryName, constants.platformLocalFileName); if (!fs.existsSync(fileName)) { const enableTrace = 1; const hashMacAddress = await getHashMacAsync(); // Create the file of platform.local.txt const targetFileName = path.join(directoryName, constants.platformLocalFileName); const content = `${constants.cExtraFlag}${hashMacAddress}" ${constants.traceExtraFlag}${enableTrace}\r\n` + `${constants.cppExtraFlag}${hashMacAddress}" ${constants.traceExtraFlag}${enableTrace}\r\n`; fs.writeFileSync(targetFileName, content); } } private getArduinoPackagePath(): string { const platform = os.platform(); // TODO: Currently, we do not support portable Arduino installation. let arduinoPackagePath = ""; const homeDir = os.homedir(); if (platform === OSPlatform.WIN32) { arduinoPackagePath = path.join(homeDir, "AppData", "Local", "Arduino15", "packages"); } else if (platform === OSPlatform.DARWIN) { arduinoPackagePath = path.join(homeDir, "Library", "Arduino15", "packages"); } else if (platform === OSPlatform.LINUX) { arduinoPackagePath = path.join(homeDir, ".arduino15", "packages"); } return path.join(arduinoPackagePath, "AZ3166", "hardware", "stm32f4"); } }
the_stack
import BaseStore from "#SRC/js/stores/BaseStore"; import { REQUEST_ACL_GROUP_SUCCESS, REQUEST_ACL_GROUP_ERROR, REQUEST_ACL_GROUP_PERMISSIONS_SUCCESS, REQUEST_ACL_GROUP_PERMISSIONS_ERROR, REQUEST_ACL_GROUP_SERVICE_ACCOUNTS_SUCCESS, REQUEST_ACL_GROUP_SERVICE_ACCOUNTS_ERROR, REQUEST_ACL_GROUP_USERS_SUCCESS, REQUEST_ACL_GROUP_USERS_ERROR, REQUEST_ACL_GROUP_CREATE_SUCCESS, REQUEST_ACL_GROUP_CREATE_ERROR, REQUEST_ACL_LDAP_GROUP_CREATE_SUCCESS, REQUEST_ACL_LDAP_GROUP_CREATE_PARTIAL_SUCCESS, REQUEST_ACL_LDAP_GROUP_CREATE_ERROR, REQUEST_ACL_GROUP_UPDATE_SUCCESS, REQUEST_ACL_GROUP_UPDATE_ERROR, REQUEST_ACL_GROUP_DELETE_SUCCESS, REQUEST_ACL_GROUP_DELETE_ERROR, REQUEST_ACL_GROUP_ADD_USER_SUCCESS, REQUEST_ACL_GROUP_ADD_USER_ERROR, REQUEST_ACL_GROUP_REMOVE_USER_SUCCESS, REQUEST_ACL_GROUP_REMOVE_USER_ERROR, } from "../constants/ActionTypes"; import { ACL_GROUP_SET_GROUPS, ACL_GROUP_SET_GROUPS_FETCHING, ACL_GROUP_DETAILS_FETCHED_SUCCESS, ACL_GROUP_DETAILS_FETCHED_ERROR, ACL_GROUP_DETAILS_GROUP_CHANGE, ACL_GROUP_DETAILS_GROUP_ERROR, ACL_GROUP_DETAILS_PERMISSIONS_CHANGE, ACL_GROUP_DETAILS_PERMISSIONS_ERROR, ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_CHANGE, ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_ERROR, ACL_GROUP_DETAILS_USERS_CHANGE, ACL_GROUP_DETAILS_USERS_ERROR, ACL_GROUP_CREATE_SUCCESS, ACL_GROUP_CREATE_ERROR, ACL_LDAP_GROUP_CREATE_SUCCESS, ACL_LDAP_GROUP_CREATE_PARTIAL_SUCCESS, ACL_LDAP_GROUP_CREATE_ERROR, ACL_GROUP_UPDATE_SUCCESS, ACL_GROUP_UPDATE_ERROR, ACL_GROUP_DELETE_SUCCESS, ACL_GROUP_DELETE_ERROR, ACL_GROUP_USERS_CHANGED, ACL_GROUP_ADD_USER_ERROR, ACL_GROUP_REMOVE_USER_SUCCESS, ACL_GROUP_REMOVE_USER_ERROR, } from "../constants/EventTypes"; import ACLGroupsActions from "../actions/ACLGroupsActions"; import Group from "../structs/Group"; import ServiceAccountList from "../../service-accounts/structs/ServiceAccountList"; import User from "../../users/structs/User"; const SDK = require("../../../SDK"); SDK.getSDK().Hooks.addFilter("serverErrorModalListeners", (listeners) => { listeners.push({ name: "aclGroup", events: ["updateError", "deleteError"] }); return listeners; }); /** * This store will keep track of groups and their details */ class ACLGroupStore extends BaseStore { constructor(...args) { super(...args); SDK.getSDK().addStoreConfig({ store: this, storeID: "aclGroup", events: { success: ACL_GROUP_DETAILS_GROUP_CHANGE, error: ACL_GROUP_DETAILS_GROUP_ERROR, addUserSuccess: ACL_GROUP_USERS_CHANGED, addUserError: ACL_GROUP_ADD_USER_ERROR, createSuccess: ACL_GROUP_CREATE_SUCCESS, createError: ACL_GROUP_CREATE_ERROR, createLDAPSuccess: ACL_LDAP_GROUP_CREATE_SUCCESS, createLDAPPartialSuccess: ACL_LDAP_GROUP_CREATE_PARTIAL_SUCCESS, createLDAPError: ACL_LDAP_GROUP_CREATE_ERROR, updateError: ACL_GROUP_UPDATE_ERROR, updateSuccess: ACL_GROUP_UPDATE_SUCCESS, permissionsSuccess: ACL_GROUP_DETAILS_PERMISSIONS_CHANGE, permissionsError: ACL_GROUP_DETAILS_PERMISSIONS_ERROR, serviceAccountsSuccess: ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_CHANGE, serviceAccountsError: ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_ERROR, usersSuccess: ACL_GROUP_DETAILS_USERS_CHANGE, usersError: ACL_GROUP_DETAILS_USERS_ERROR, fetchedDetailsSuccess: ACL_GROUP_DETAILS_FETCHED_SUCCESS, fetchedDetailsError: ACL_GROUP_DETAILS_FETCHED_ERROR, deleteUserSuccess: ACL_GROUP_REMOVE_USER_SUCCESS, deleteUserError: ACL_GROUP_REMOVE_USER_ERROR, deleteSuccess: ACL_GROUP_DELETE_SUCCESS, deleteError: ACL_GROUP_DELETE_ERROR, }, unmountWhen: () => false, }); SDK.getSDK().onDispatch((action) => { switch (action.type) { // Get group details case REQUEST_ACL_GROUP_SUCCESS: this.processGroup(action.data); break; case REQUEST_ACL_GROUP_ERROR: this.processGroupError(action.data, action.groupID); break; // Get ACL permissions of group case REQUEST_ACL_GROUP_PERMISSIONS_SUCCESS: this.processGroupPermissions(action.data, action.groupID); break; case REQUEST_ACL_GROUP_PERMISSIONS_ERROR: this.processGroupPermissionsError(action.data, action.groupID); break; case REQUEST_ACL_GROUP_SERVICE_ACCOUNTS_SUCCESS: this.processGroupServiceAccounts(action.data, action.groupID); break; case REQUEST_ACL_GROUP_SERVICE_ACCOUNTS_ERROR: this.processGroupServiceAccountsError(action.data, action.groupID); break; // Get users members of group case REQUEST_ACL_GROUP_USERS_SUCCESS: this.processGroupUsers(action.data, action.groupID); break; case REQUEST_ACL_GROUP_USERS_ERROR: this.processGroupUsersError(action.data, action.groupID); break; // Create group case REQUEST_ACL_GROUP_CREATE_SUCCESS: this.emit(ACL_GROUP_CREATE_SUCCESS, action.groupID); break; case REQUEST_ACL_GROUP_CREATE_ERROR: this.emit(ACL_GROUP_CREATE_ERROR, action.data, action.groupID); break; // Import LDAP Group case REQUEST_ACL_LDAP_GROUP_CREATE_SUCCESS: this.emit(ACL_LDAP_GROUP_CREATE_SUCCESS, action.groupID); break; case REQUEST_ACL_LDAP_GROUP_CREATE_PARTIAL_SUCCESS: this.emit( ACL_LDAP_GROUP_CREATE_PARTIAL_SUCCESS, action.data, action.groupID ); break; case REQUEST_ACL_LDAP_GROUP_CREATE_ERROR: this.emit(ACL_LDAP_GROUP_CREATE_ERROR, action.data, action.groupID); break; // Update group case REQUEST_ACL_GROUP_UPDATE_SUCCESS: this.emit(ACL_GROUP_UPDATE_SUCCESS, action.groupID); break; case REQUEST_ACL_GROUP_UPDATE_ERROR: this.emit(ACL_GROUP_UPDATE_ERROR, action.data, action.groupID); break; // Delete group case REQUEST_ACL_GROUP_DELETE_SUCCESS: this.emit(ACL_GROUP_DELETE_SUCCESS, action.groupID); break; case REQUEST_ACL_GROUP_DELETE_ERROR: this.emit(ACL_GROUP_DELETE_ERROR, action.data, action.groupID); break; // Add user to group case REQUEST_ACL_GROUP_ADD_USER_SUCCESS: this.emit(ACL_GROUP_USERS_CHANGED, action.groupID, action.userID); break; case REQUEST_ACL_GROUP_ADD_USER_ERROR: this.emit( ACL_GROUP_ADD_USER_ERROR, action.data, action.groupID, action.userID ); break; // Remove user from group case REQUEST_ACL_GROUP_REMOVE_USER_SUCCESS: this.emit( ACL_GROUP_REMOVE_USER_SUCCESS, action.groupID, action.userID ); break; case REQUEST_ACL_GROUP_REMOVE_USER_ERROR: this.emit( ACL_GROUP_REMOVE_USER_ERROR, action.data, action.groupID, action.userID ); break; } }); } get(prop) { return SDK.getSDK().Store.getOwnState().groups[prop]; } getGroupRaw(groupID) { return this.get("groupDetail")[groupID]; } getGroup(groupID) { return new Group(this.getGroupRaw(groupID)); } getServiceAccounts(groupID) { const items = (this.getGroupRaw(groupID).serviceAccounts || []).map( (user) => user.user ); return new ServiceAccountList({ items }); } getUsers(groupID) { return (this.getGroupRaw(groupID).users || []).map( ({ user }) => new User(user) ); } setGroup(groupID, group) { const groups = this.get("groupDetail"); groups[groupID] = group; SDK.getSDK().dispatch({ type: ACL_GROUP_SET_GROUPS, groups, }); } fetchGroup(...args) { return ACLGroupsActions.fetchGroup(...args); } addGroup(...args) { return ACLGroupsActions.addGroup(...args); } addLDAPGroup(...args) { return ACLGroupsActions.addLDAPGroup(...args); } updateGroup(...args) { return ACLGroupsActions.updateGroup(...args); } deleteGroup(...args) { return ACLGroupsActions.deleteGroup(...args); } addUser(...args) { return ACLGroupsActions.addUser(...args); } deleteUser(...args) { return ACLGroupsActions.deleteUser(...args); } /** * Will fetch a group and their details. * Will make a request to various different endpoints to get all details * * @param {Number} groupID */ fetchGroupWithDetails(groupID) { const groupsFetching = this.get("groupsFetching"); groupsFetching[groupID] = { group: false, serviceAccounts: false, users: false, permissions: false, }; SDK.getSDK().dispatch({ type: ACL_GROUP_SET_GROUPS_FETCHING, groupsFetching, }); ACLGroupsActions.fetchGroup(groupID); ACLGroupsActions.fetchGroupPermissions(groupID); ACLGroupsActions.fetchGroupServiceAccounts(groupID); ACLGroupsActions.fetchGroupUsers(groupID); } /** * Validates if the details for a group have been successfully fetched * * @param {Number} groupID * @param {String} type The type of detail that has been successfully * received */ validateGroupWithDetailsFetch(groupID, type) { const groupsFetching = this.get("groupsFetching"); if (groupsFetching[groupID] == null) { return; } groupsFetching[groupID][type] = true; let fetchedAll = true; Object.keys(groupsFetching[groupID]).forEach((key) => { if (groupsFetching[groupID][key] === false) { fetchedAll = false; } }); if (fetchedAll) { delete groupsFetching[groupID]; SDK.getSDK().dispatch({ type: ACL_GROUP_SET_GROUPS_FETCHING, groupsFetching, }); this.emit(ACL_GROUP_DETAILS_FETCHED_SUCCESS, groupID); } } /** * Emits error if we're in the process of fetching details for a group * but one of the requests fails. * * @param {Number} groupID */ invalidateGroupWithDetailsFetch(groupID) { const groupsFetching = this.get("groupsFetching"); if (groupsFetching[groupID] == null) { return; } delete groupsFetching[groupID]; SDK.getSDK().dispatch({ type: ACL_GROUP_SET_GROUPS_FETCHING, groupsFetching, }); this.emit(ACL_GROUP_DETAILS_FETCHED_ERROR, groupID); } /** * Process a group response * * @param {Object} groupData see /acl/groups/group schema */ processGroup(groupData) { let group = this.getGroupRaw(groupData.gid) || {}; group = { ...group, ...groupData }; this.setGroup(group.gid, group); this.emit(ACL_GROUP_DETAILS_GROUP_CHANGE, group.gid); this.validateGroupWithDetailsFetch(group.gid, "group"); } processGroupError(data, groupID) { this.emit(ACL_GROUP_DETAILS_GROUP_ERROR, data, groupID); this.invalidateGroupWithDetailsFetch(groupID); } /** * Process a group permissions response * * @param {Object} permissions see /acl/groups/group/permissions schema * @param {Object} groupID */ processGroupPermissions(permissions, groupID) { const group = this.getGroupRaw(groupID) || {}; group.permissions = permissions; // Use groupID throughout as the group may not have been previously set this.setGroup(groupID, group); this.emit(ACL_GROUP_DETAILS_PERMISSIONS_CHANGE, groupID); this.validateGroupWithDetailsFetch(groupID, "permissions"); } processGroupPermissionsError(data, groupID) { this.emit(ACL_GROUP_DETAILS_PERMISSIONS_ERROR, data, groupID); this.invalidateGroupWithDetailsFetch(groupID); } processGroupServiceAccounts(serviceAccounts, groupID) { const group = this.getGroupRaw(groupID) || {}; group.serviceAccounts = serviceAccounts; // Use groupID throughout as the group may not have been previously set this.setGroup(groupID, group); this.emit(ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_CHANGE, groupID); this.validateGroupWithDetailsFetch(groupID, "serviceAccounts"); } processGroupServiceAccountsError(data, groupID) { this.emit(ACL_GROUP_DETAILS_SERVICE_ACCOUNTS_ERROR, data, groupID); this.invalidateGroupWithDetailsFetch(groupID); } /** * Process a group users response * * @param {Object} users see /acl/groups/group/users schema * @param {Object} groupID */ processGroupUsers(users, groupID) { const group = this.getGroupRaw(groupID) || {}; group.users = users; // Use groupID throughout as the group may not have been previously set this.setGroup(groupID, group); this.emit(ACL_GROUP_DETAILS_USERS_CHANGE, groupID); this.validateGroupWithDetailsFetch(groupID, "users"); } processGroupUsersError(data, groupID) { this.emit(ACL_GROUP_DETAILS_USERS_ERROR, data, groupID); this.invalidateGroupWithDetailsFetch(groupID); } } export default new ACLGroupStore();
the_stack
import * as React from "react"; import { ContextMenu, ContextMenuDirection, ContextMenuItem, ContextMenuItemProps, ContextSubMenu, GlobalContextMenu, Icon, Popup, PopupContextMenu, useRefState } from "@itwin/core-react"; import { RelativePosition } from "@itwin/appui-abstract"; import { Popover } from "@itwin/itwinui-react/cjs/core/utils"; import { Button, DropdownMenu, IconButton, Menu, MenuItem } from "@itwin/itwinui-react"; import { SvgMore } from "@itwin/itwinui-icons-react"; export function SamplePopupContextMenu({ label, position }: { label?: string, position?: RelativePosition }) { const [targetRef, target] = useRefState<HTMLButtonElement>(); const [isMenuOpen, setIsMenuOpen] = React.useState(false); const toggleMenu = React.useCallback(() => { const show = !isMenuOpen; setIsMenuOpen(show); }, [isMenuOpen]); const onCloseMenu = React.useCallback(() => { setIsMenuOpen(false); }, []); return ( <div> {label ? <Button size="small" ref={targetRef} onClick={(e) => { e.preventDefault(); toggleMenu(); }}> {label} </Button> : <IconButton size="small" ref={targetRef} onClick={(e) => { e.preventDefault(); toggleMenu(); }} ><SvgMore /></IconButton> } <PopupContextMenu isOpen={isMenuOpen} position={position ?? RelativePosition.BottomLeft} target={target} offset={1} onClose={onCloseMenu} onSelect={onCloseMenu} selectedIndex={0} autoflip={false}> <ContextSubMenu label="Item ~1" icon="icon-placeholder"> <ContextMenuItem icon="icon-placeholder" iconRight="icon-checkmark">SubMenu Item ~1</ContextMenuItem> <ContextMenuItem icon="icon-placeholder">SubMenu Item ~2</ContextMenuItem> </ContextSubMenu> <ContextMenuItem icon="icon-placeholder" iconRight="icon-checkmark">Item ~2</ContextMenuItem> <ContextMenuItem>Item ~3</ContextMenuItem> <ContextSubMenu label="Item ~4"> <ContextMenuItem icon="icon-placeholder">SubMenu Item ~1</ContextMenuItem> <ContextMenuItem icon="icon-placeholder">SubMenu Item ~2</ContextMenuItem> </ContextSubMenu> </PopupContextMenu> </div> ); } export function ButtonWithContextMenu({ label, direction }: { label?: string, direction?: ContextMenuDirection }) { const [isMenuOpen, setIsMenuOpen] = React.useState(false); const toggleMenu = React.useCallback(() => { const show = !isMenuOpen; setIsMenuOpen(show); }, [isMenuOpen]); return ( <div> {label ? <Button size="small" onClick={(e) => { e.preventDefault(); toggleMenu(); }}> {label} </Button> : <IconButton size="small" onClick={(e) => { e.preventDefault(); toggleMenu(); }} ><SvgMore /></IconButton> } <ContextMenu direction={direction} style={{ width: "100%" }} opened={isMenuOpen} edgeLimit={false} selectedIndex={0} floating={true} autoflip={false} onEsc={() => setIsMenuOpen(false)} onOutsideClick={(e) => { e.preventDefault(); setIsMenuOpen(false); }} > {["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"].map((listItem, index) => { return ( <ContextMenuItem key={index} hideIconContainer onSelect={(event) => { event.stopPropagation(); setIsMenuOpen(false); }}> {listItem} </ContextMenuItem> ); })} </ContextMenu> </div > ); } export function ButtonWithDropdownMenu({ label, placement}: { label?: string, placement?: "top-start"|"top-end"|"bottom-start"|"bottom-end" }) { const [isMenuOpen, setIsMenuOpen] = React.useState(false); const toggleMenu = React.useCallback(() => { const show = !isMenuOpen; setIsMenuOpen(show); }, [isMenuOpen]); const createMenuItemNodes = React.useCallback((close: () => void): JSX.Element[] => { const itemNodes = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"].map((listItem, index) => { return ( <MenuItem key={index} onClick={() => { close(); }}> {listItem} </MenuItem> ); }); return itemNodes; }, []); return ( <div> <DropdownMenu appendTo="parent" placement={placement??"bottom-start"} menuItems={createMenuItemNodes}> {label ? <Button size="small" onClick={(e) => { e.preventDefault(); toggleMenu(); }}> {label} </Button> : <IconButton size="small" onClick={(e) => { e.preventDefault(); toggleMenu(); }} ><SvgMore /></IconButton> } </DropdownMenu> </div > ); } export function ContextMenuInPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const togglePopup = React.useCallback(() => { const show = !showPopup; setShowPopup(show); }, [showPopup]); return ( <div> <Button size="small" ref={buttonRef} onClick={(e) => { e.preventDefault(); togglePopup(); }}> {showPopup ? "Close" : "Open"} </Button> <Popup isOpen={showPopup} position={RelativePosition.Bottom} target={buttonRef.current} onClose={() => setShowPopup(false)} showArrow={true} showShadow={true} closeOnNestedPopupOutsideClick={false}> <div style={{ width: "150px", height: "200px", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}> <div style={{ display: "flex" }}> <ButtonWithContextMenu label="TR" direction={ContextMenuDirection.TopRight} /> <ButtonWithContextMenu label="TL" direction={ContextMenuDirection.TopLeft} /> </div> <div style={{ display: "flex" }}> <ButtonWithContextMenu label="BR" direction={ContextMenuDirection.BottomRight} /> <ButtonWithContextMenu label="BL" direction={ContextMenuDirection.BottomLeft} /> </div> </div> </Popup > </div > ); } export function DropdownMenuInPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const togglePopup = React.useCallback(() => { const show = !showPopup; setShowPopup(show); }, [showPopup]); return ( <div> <Button size="small" ref={buttonRef} onClick={(e) => { e.preventDefault(); togglePopup(); }}> {showPopup ? "Close" : "Open"} </Button> <Popup isOpen={showPopup} position={RelativePosition.Bottom} target={buttonRef.current} onClose={() => setShowPopup(false)} showArrow={true} showShadow={true} closeOnNestedPopupOutsideClick={false}> <div style={{ width: "150px", height: "200px", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}> <div style={{ display: "flex" }}> <ButtonWithDropdownMenu label="TR" placement="top-end"/> <ButtonWithDropdownMenu label="TL" placement="top-start" /> </div> <div style={{ display: "flex" }}> <ButtonWithDropdownMenu label="BR" placement="bottom-end" /> <ButtonWithDropdownMenu label="BL" placement="bottom-start" /> </div> </div> </Popup > </div > ); } export function PopupContextMenuInPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const togglePopup = React.useCallback(() => { const show = !showPopup; setShowPopup(show); }, [showPopup]); return ( <div> <Button size="small" ref={buttonRef} onClick={(e) => { e.preventDefault(); togglePopup(); }}> {showPopup ? "Close" : "Open"} </Button> <Popup isOpen={showPopup} position={RelativePosition.Bottom} target={buttonRef.current} onClose={() => setShowPopup(false)} showArrow={true} showShadow={true} closeOnNestedPopupOutsideClick={false}> <div style={{ width: "150px", height: "200px", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}> <div style={{ display: "flex" }}> <SamplePopupContextMenu label="TR" position={RelativePosition.TopRight} /> <SamplePopupContextMenu label="TL" position={RelativePosition.TopLeft} /> </div> <div style={{ display: "flex" }}> <SamplePopupContextMenu label="BR" position={RelativePosition.BottomRight} /> <SamplePopupContextMenu label="BL" position={RelativePosition.BottomLeft} /> </div> </div> </Popup > </div > ); } export type ContextMenuItemInfo = ContextMenuItemProps & React.Attributes & { label: string }; export function GlobalItwinContextMenuInPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const xRef = React.useRef<number>(0); const yRef = React.useRef<number>(0); const onSelect = React.useCallback(() => setShowPopup(false), []); const togglePopup = React.useCallback(() => { const show = !showPopup; setShowPopup(show); }, [showPopup]); return ( <div> <IconButton size="small" onClick={(e) => { xRef.current = e.clientX + 10; yRef.current = e.clientY + 10; e.preventDefault(); togglePopup(); }} ref={buttonRef}><SvgMore /></IconButton> <Popover appendTo={document.body} zIndex={99999} content={ <Menu> {["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"].map((label, index) => <MenuItem key={index} onClick={onSelect} title={label} icon={<Icon className="core-menuitem-icon" iconSpec="icon-placeholder" />} > {label} </MenuItem> )} </Menu> } visible={showPopup} onClickOutside={() => setShowPopup(false)} getReferenceClientRect={() => ({ width: 0, height: 0, top: yRef.current, bottom: yRef.current, left: xRef.current, right: xRef.current, x: xRef.current, y: yRef.current, toJSON: () => { }, })} placement="bottom-start" onHide={() => setShowPopup(false)} /> </div > ); } export function GlobalContextMenuInPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const xRef = React.useRef<number>(0); const yRef = React.useRef<number>(0); const togglePopup = React.useCallback(() => { const show = !showPopup; setShowPopup(show); }, [showPopup]); return ( <div> <IconButton size="small" ref={buttonRef} onClick={(e) => { xRef.current = e.clientX; yRef.current = e.clientY; e.preventDefault(); togglePopup(); }} ><SvgMore /></IconButton> <GlobalContextMenu opened={showPopup} onOutsideClick={() => setShowPopup(false)} onEsc={() => setShowPopup(false)} identifier="ui-test-app:ComponentExampleMenu" x={xRef.current + 10} y={yRef.current + 10} > {["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"].map((listItem, index) => { return ( <ContextMenuItem key={index} icon="icon-placeholder" onSelect={(event) => { event.stopPropagation(); setShowPopup(false); }}> {listItem} </ContextMenuItem> ); })} </GlobalContextMenu> </div > ); }
the_stack
import { ServiceClient } from "@azure/core-client"; import { expect } from "chai"; import { env, isPlaybackMode, Recorder } from "../src"; import { isRecordMode, RecorderError, TestMode } from "../src/utils/utils"; import { getTestServerUrl, makeRequestAndVerifyResponse, setTestMode } from "./utils/utils"; // These tests require the following to be running in parallel // - utils/server.ts (to serve requests to act as a service) // - proxy-tool (to save/mock the responses) (["record", "playback", "live"] as TestMode[]).forEach((mode) => { describe(`proxy tool - sanitizers`, () => { let recorder: Recorder; let client: ServiceClient; before(() => { setTestMode(mode); }); beforeEach(async function() { recorder = new Recorder(this.currentTest); client = new ServiceClient({ baseUri: getTestServerUrl() }); recorder.configureClient(client); }); afterEach(async () => { await recorder.stop(); }); describe("Sanitizers - functionalities", () => { it("GeneralRegexSanitizer", async () => { env.SECRET_INFO = "abcdef"; const fakeSecretInfo = "fake_secret_info"; await recorder.start({ envSetupForPlayback: { SECRET_INFO: fakeSecretInfo } }); // Adds generalRegexSanitizers by default based on envSetupForPlayback await makeRequestAndVerifyResponse( client, { path: `/sample_response/${env.SECRET_INFO}`, method: "GET" }, { val: "I am the answer!" } ); }); it("RemoveHeaderSanitizer", async () => { await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { removeHeaderSanitizer: { headersForRemoval: ["ETag", "Date"] } } }); await makeRequestAndVerifyResponse( client, { path: `/sample_response`, method: "GET" }, { val: "abc" } ); }); it("BodyKeySanitizer", async () => { const secretValue = "ab12cd34ef"; const fakeSecretValue = "fake_secret_info"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { bodyKeySanitizers: [ { jsonPath: "$.secret_info", // Handles the request body regex: secretValue, value: fakeSecretValue }, { jsonPath: "$.bodyProvided.secret_info", // Handles the response body regex: secretValue, value: fakeSecretValue } ] } }); const reqBody = { secret_info: isPlaybackMode() ? fakeSecretValue : secretValue }; await makeRequestAndVerifyResponse( client, { path: `/api/sample_request_body`, body: JSON.stringify(reqBody), method: "POST", headers: [{ headerName: "Content-Type", value: "application/json" }] }, { bodyProvided: reqBody } ); }); it("BodyRegexSanitizer", async () => { const secretValue = "ab12cd34ef"; const fakeSecretValue = "fake_secret_info"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { bodyRegexSanitizers: [ { regex: "(.*)&SECRET=(?<secret_content>[^&]*)&(.*)", value: fakeSecretValue, groupForReplace: "secret_content" } ] } }); const reqBody = `non_secret=i'm_no_secret&SECRET=${ isPlaybackMode() ? fakeSecretValue : secretValue }&random=random`; await makeRequestAndVerifyResponse( client, { path: `/api/sample_request_body`, body: reqBody, method: "POST", headers: [{ headerName: "Content-Type", value: "text/plain" }] }, { bodyProvided: reqBody } ); }); it("UriRegexSanitizer", async () => { const secretEndpoint = "host.docker.internal"; const fakeEndpoint = "fake_endpoint"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { uriRegexSanitizers: [ { regex: secretEndpoint, value: fakeEndpoint } ] } }); const pathToHit = `/api/sample_request_body`; await makeRequestAndVerifyResponse( client, { url: isPlaybackMode() ? getTestServerUrl().replace(secretEndpoint, fakeEndpoint) + pathToHit : undefined, path: pathToHit, method: "POST" }, { bodyProvided: {} } ); }); it("UriSubscriptionIdSanitizer", async () => { const id = "73c83158-bd73-4cda-aa11-a0c2a34e2544"; const fakeId = "00000000-0000-0000-0000-000000000000"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { uriSubscriptionIdSanitizer: { value: fakeId } } }); await makeRequestAndVerifyResponse( client, { path: `/subscriptions/${isPlaybackMode() ? fakeId : id}`, method: "GET" }, { val: "I am the answer!" } ); }); it.skip("ContinuationSanitizer", async () => { // Skipping since the test is failing in the browser await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { continuationSanitizers: [ { key: "your_uuid", method: "guid", // What is this method exactly? resetAfterFirst: false } ] } }); // What if the id is part of the response body and not response headers? const firstResponse = await makeRequestAndVerifyResponse( client, { path: `/api/sample_uuid_in_header`, method: "GET" }, undefined ); await makeRequestAndVerifyResponse( client, { path: `/sample_response`, method: "GET", headers: [ { headerName: "your_uuid", value: firstResponse.headers.get("your_uuid") || "" } ] }, { val: "abc" } ); }); it("HeaderRegexSanitizer", async () => { const sanitizedValue = "Sanitized"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { headerRegexSanitizers: [ { key: "your_uuid", value: sanitizedValue } ] } }); await makeRequestAndVerifyResponse( client, { path: `/api/sample_uuid_in_header`, method: "GET" }, undefined ); // TODO: Add more tests to cover groupForReplace }); // it("OAuthResponseSanitizer", async () => { // await recorder.start({}); // await recorder.addSanitizers({ // oAuthResponseSanitizer: true // }); // await makeRequestAndVerifyResponse(client, // { // path: `/api/sample_uuid_in_header`, // method: "GET" // }, // undefined // ); // // TODO: Add more tests to cover groupForReplace // }); it.skip("ResetSanitizer (uses BodyRegexSanitizer as example)", async () => { const secretValue = "ab12cd34ef"; const fakeSecretValue = "fake_secret_info"; await recorder.start({ envSetupForPlayback: {}, sanitizerOptions: { bodyRegexSanitizers: [ { regex: "(.*)&SECRET=(?<secret_content>[^&]*)&(.*)", value: fakeSecretValue, groupForReplace: "secret_content" } ] } }); const reqBody = `non_secret=i'm_no_secret&SECRET=${ isPlaybackMode() ? fakeSecretValue : secretValue }&random=random`; await makeRequestAndVerifyResponse( client, { path: `/api/sample_request_body`, body: reqBody, method: "POST", headers: [{ headerName: "Content-Type", value: "text/plain" }] }, { bodyProvided: reqBody } ); await recorder.addSanitizers({ resetSanitizer: true }); const reqBodyAfterReset = `non_secret=i'm_no_secret&SECRET=${secretValue}&random=random`; // TODO: BUG OBSERVED - The following request should not be sanitized, but is sanitized await makeRequestAndVerifyResponse( client, { path: `/api/sample_request_body`, body: reqBodyAfterReset, method: "POST", headers: [{ headerName: "Content-Type", value: "text/plain" }] }, { bodyProvided: reqBodyAfterReset } ); }); }); describe("Sanitizers - handling undefined", () => { beforeEach(async () => { await recorder.start({ envSetupForPlayback: {} }); }); const cases = [ { options: { connectionStringSanitizers: [ { actualConnString: undefined, fakeConnString: "a=b;c=d" } ], generalRegexSanitizers: [{ regex: undefined, value: "fake-value" }] }, title: "all sanitizers are undefined", type: "negative" }, { options: { connectionStringSanitizers: [ { actualConnString: undefined, fakeConnString: "a=b;c=d" }, { actualConnString: "1=2,3=4", fakeConnString: "a=b;c=d" } ], generalRegexSanitizers: [{ regex: undefined, value: "fake-value" }] }, title: "partial sanitizers are undefined", type: "negative" }, { options: { connectionStringSanitizers: [ { actualConnString: "1=2,3=4", fakeConnString: "a=b;c=d" } ], generalRegexSanitizers: [{ regex: "value", value: "fake-value" }] }, title: "all sanitizers are defined", type: "positive" } ]; cases.forEach((testCase) => { it(`case - ${testCase.title}`, async () => { try { await recorder.addSanitizers(testCase.options); throw new Error("error was not thrown from addSanitizers call"); } catch (error) { if (isRecordMode() && testCase.type === "negative") { expect((error as RecorderError).message).includes( `Attempted to add an invalid sanitizer` ); } else { expect((error as RecorderError).message).includes( `error was not thrown from addSanitizers call` ); } } }); }); }); }); });
the_stack
import { Animated } from "react-native"; import { IAnimationProvider } from "../Types/IAnimationProvider"; import { runTiming } from "./Implementation/runTiming"; import { createValue } from "./Implementation/createValue"; import { IAnimationNode, IAnimationValue } from "../Types"; import { getProcessedColor } from "./Implementation/getProcessedColor"; import { getColorDisplayValue } from "./Implementation/getColorDisplayValue"; import { getProcessedRotation } from "./Implementation/getProcessedRotation"; import { isAnimatedNode } from "./Implementation/utils"; import { bezier } from "./Implementation/bezier"; import { RadNode } from "./Implementation/RadNode"; const { event } = Animated; export type AnimatedNode = { name: string; evaluate: () => AnimatedNode; children: IAnimationNode[]; }; type AnimationValue = { __getValue: () => any; }; type StackItem = { name: string; children: IAnimationNode[]; }; const stackTrace: Array<StackItem> = []; const stackTraceToString = () => stackTrace.map(s => s.name); const gestureConfiguration = {}; const evalNode = (input: IAnimationNode) => { let retVal: any; if (isNode(input)) { retVal = (input as AnimatedNode).evaluate(); } else if (isAnimatedNode(input)) { retVal = (input as AnimationValue).__getValue(); } else if (typeof input === "function") { retVal = (input as Function)(); } else { if (typeof input === "string") { retVal = parseFloat(input as string); } else { retVal = input; } } return retVal; }; const createBlockFunc = (items: ReadonlyArray<IAnimationNode>) => createNode( "block", () => { const nodes = items.map((f: IAnimationNode) => evalNode(f)); const last = nodes[nodes.length - 1]; return last; }, items, ); const createProxyNode = () => { const _argStack = new Array<IAnimationNode>(); let cache: { [key: number]: any } = {}; return { _argStack, beginCall: (value: IAnimationNode) => { _argStack.push(value); }, endCall: () => { cache[_argStack.length] = undefined; _argStack.pop(); }, setValue: (value: IAnimationNode) => { // Cast and allow exception if not IAnimationNode (_argStack[_argStack.length - 1] as IAnimationValue).setValue(value); }, __getValue: () => { if (!cache[_argStack.length]) { if (typeof _argStack[_argStack.length - 1] === "function") { cache[_argStack.length] = (_argStack[ _argStack.length - 1 ] as Function)(); } else if (isProxyNode(_argStack[_argStack.length - 1])) { cache[_argStack.length] = (_argStack[ _argStack.length - 1 ] as AnimationValue).__getValue(); } else { cache[_argStack.length] = _argStack[_argStack.length - 1]; } } return evalNode(cache[_argStack.length]); }, }; }; export function isProxyNode(value: Object): boolean { return ( value && Object.keys(value).find(k => k.startsWith("_argStack")) !== undefined ); } const createNode = ( name: string, evaluate: () => IAnimationNode, ...children: IAnimationNode[] ): AnimatedNode => { return { name, evaluate: () => { stackTrace.push({ name, children: children || [] }); const node = evaluate(); const retVal = evalNode(node); stackTrace.pop(); return retVal; }, children: children || [], }; }; const isNode = (node: IAnimationNode) => node && node.hasOwnProperty("evaluate"); const ReactNativeAnimationProvider: IAnimationProvider = { getColorDisplayValue, getDisplayValue: (input: IAnimationValue) => input, getRadianDisplayValue: (input: IAnimationNode) => { return new RadNode(input as Animated.Value); }, createAnimatedComponent: Animated.createAnimatedComponent, runTiming, createValue, isAnimatedNode, getNumericColor: getProcessedColor, getNumericRotation: getProcessedRotation, configuration: { gestureConfiguration, }, Types: { View: Animated.View, Image: Animated.Image, ScrollView: Animated.ScrollView, Text: Animated.Text, }, Animated: { event, /* Operators */ add: (...args: IAnimationNode[]): IAnimationNode => createNode( "add", () => { return args.reduce((a, b) => evalNode(a) + evalNode(b), 0); }, ...args, ), multiply: (...args: IAnimationNode[]): IAnimationNode => createNode( "multiply", () => args.reduce((a, b) => evalNode(a) * evalNode(b), 1), ...args, ), divide: (a: IAnimationNode, b: IAnimationNode): IAnimationNode => createNode("divide", () => evalNode(a) / evalNode(b), a, b), pow: (a: IAnimationNode, b: IAnimationNode): IAnimationNode => createNode("pow", () => Math.pow(evalNode(a), evalNode(b)), a, b), exp: (a: IAnimationNode): IAnimationNode => createNode("exp", () => Math.exp(evalNode(a)), a), sqrt: (a: IAnimationNode): IAnimationNode => createNode("sqrt", () => Math.sqrt(evalNode(a)), a), sin: (a: IAnimationNode): IAnimationNode => createNode("sin", () => Math.sin(evalNode(a)), a), cos: (a: IAnimationNode): IAnimationNode => createNode("cos", () => Math.cos(evalNode(a)), a), sub: (a: IAnimationNode, b: IAnimationNode): IAnimationNode => createNode("sub", () => evalNode(a) - evalNode(b), a, b), round: (input: IAnimationNode): IAnimationNode => createNode("round", () => Math.round(evalNode(input)), input), eq: (left: IAnimationNode, right: IAnimationNode) => createNode("eq", () => evalNode(left) === evalNode(right), left, right), neq: (left: IAnimationNode, right: IAnimationNode) => createNode("neq", () => evalNode(left) !== evalNode(right), left, right), abs: (a: IAnimationNode) => Math.abs(evalNode(a)), and: ( left: IAnimationNode, right: IAnimationNode, // @ts-ignore ...others: IAnimationNode[] ) => createNode( "and", () => { const nodes = [left, right, ...others]; let retVal = evalNode(left); for (let i = 1; i < nodes.length; i++) { retVal = retVal && evalNode(nodes[i]); } return retVal; }, ...[left, right, ...others], ), greaterOrEq: (left: IAnimationNode, right: IAnimationNode) => createNode( "greaterOrEq", () => evalNode(left) >= evalNode(right), left, right, ), lessThan: (left: IAnimationNode, right: IAnimationNode) => createNode( "lessThan", () => evalNode(left) < evalNode(right), left, right, ), greaterThan: (left: IAnimationNode, right: IAnimationNode) => createNode( "greaterThan", () => evalNode(left) > evalNode(right), left, right, ), lessOrEq: (left: IAnimationNode, right: IAnimationNode) => createNode( "lessOrEq", () => evalNode(left) <= evalNode(right), left, right, ), /* Statements */ set: (target: IAnimationValue, source: IAnimationNode) => createNode( "set", () => { const v = evalNode(source); if (Number.isNaN(v)) { const s = stackTrace; throw new Error( "Value is not a number\n" + stackTraceToString() + "\n" + s, ); } target.setValue(v); return v; }, target, source, ), block: (items: ReadonlyArray<IAnimationNode>) => createBlockFunc(items), cond: ( expression: IAnimationNode, ifNode: IAnimationNode, elseNode?: IAnimationNode, ) => { const ifNodeResolved = ifNode instanceof Array ? createBlockFunc(ifNode) : ifNode; const elseNodeResolved = elseNode instanceof Array ? createBlockFunc(elseNode) : elseNode; return createNode( "cond", () => { const expr = evalNode(expression); const exec = expr ? ifNodeResolved : elseNodeResolved || 0; const retVal = evalNode(exec); return retVal; }, ...(elseNode ? [expression, ifNode, elseNode] : [expression, ifNode]), ); }, call: ( args: ReadonlyArray<IAnimationNode>, callback: (args: ReadonlyArray<number>) => void, ) => createNode( "call", () => { callback(args.map(a => evalNode(a))); return 0; }, ...args, ), /* Helpers */ proc: ( name: string, callback: (...params: Array<IAnimationNode>) => IAnimationNode, ) => { // Create argument nodes const params = new Array(callback.length); for (let i = 0; i < params.length; i++) { params[i] = createProxyNode(); } const func = callback(...params); return (...args: Array<IAnimationNode>) => createNode( `proc-(${name})`, () => { if (args.length !== params.length) { throw Error( `Expected ${params.length} arguments, got ${args.length}.`, ); } params.forEach((p, i) => p.beginCall(args[i])); const retVal = (func as AnimatedNode).evaluate(); params.forEach(p => p.endCall()); return retVal; }, ...args, ); }, always: (cb: (node: IAnimationNode) => IAnimationNode) => createNode("always", () => { // We'll just return the node in RN Animated - since it // doesn't have to be marked for evaluation. // @ts-ignore return cb(); }), attach: (source: IAnimationValue, node: IAnimationNode) => { // Add listener const id = (source as Animated.Value).addListener(() => evalNode(node)); listeners[id] = node; }, detach: (source: IAnimationValue, node: IAnimationNode) => { // Remove listener Object.keys(listeners).forEach(key => { if (listeners[key] === node) { (source as Animated.Value).removeListener(key); } }); }, debug: (msg: string, value: any) => function debug() { console.log(`****** ${msg}: ${evalNode(value)}`); return evalNode(value); }, bezier: (x1: number, y1: number, x2: number, y2: number) => { const bezierFunc = bezier(x1, y1, x2, y2); return (t: IAnimationNode): IAnimationNode => createNode( "bezier", () => { return bezierFunc(evalNode(t)); }, t, ); }, }, }; const listeners: { [key: string]: IAnimationNode } = {}; export { ReactNativeAnimationProvider };
the_stack
import { Design } from '../../src/nodes/design' import { ok, strictEqual } from 'assert' describe('Design', () => { function createOctopus() { const width = Math.round(Math.random() * 400) const height = Math.round(Math.random() * 400) return { 'frame': { 'x': Math.round(Math.random() * 400), 'y': Math.round(Math.random() * 400), }, 'bounds': { 'left': 0, 'top': 0, 'right': width, 'bottom': height, 'width': width, 'height': height, }, 'layers': [], } } it('should return an added artboard by ID', () => { const design = new Design() design.addArtboard('a', createOctopus()) const artboard = design.getArtboardById('a') ok(artboard) strictEqual(artboard.id, 'a') }) it('should not return a removed artboard by ID', () => { const design = new Design() design.addArtboard('a', createOctopus()) design.removeArtboard('a') const artboard = design.getArtboardById('a') strictEqual(artboard, null) }) describe('artboard list', () => { it('should return an empty artboard list by default', () => { const design = new Design() strictEqual(design.getArtboards().length, 0) }) it('should include an added artboard in the artboard list', () => { const design = new Design() design.addArtboard('a', createOctopus()) const artboards = design.getArtboards() strictEqual(artboards.length, 1) ok(artboards[0]) strictEqual(artboards[0].id, 'a') }) it('should not include newly added artboards in a previously returned artboard list', () => { const design = new Design() const prevArtboards = design.getArtboards() design.addArtboard('a', createOctopus()) strictEqual(prevArtboards.length, 0) }) it('should include newly added artboards in the current artboard list', () => { const design = new Design() // eslint-disable-next-line @typescript-eslint/no-unused-vars const prevArtboards = design.getArtboards() design.addArtboard('a', createOctopus()) const nextArtboards = design.getArtboards() strictEqual(nextArtboards.length, 1) ok(nextArtboards[0]) strictEqual(nextArtboards[0].id, 'a') }) it('should keep newly removed artboards in a previously returned artboard list', () => { const design = new Design() design.addArtboard('a', createOctopus()) const prevArtboards = design.getArtboards() design.removeArtboard('a') strictEqual(prevArtboards.length, 1) ok(prevArtboards[0]) strictEqual(prevArtboards[0].id, 'a') }) it('should not include newly removed artboards in the current artboard list', () => { const design = new Design() design.addArtboard('a', createOctopus()) // eslint-disable-next-line @typescript-eslint/no-unused-vars const prevArtboards = design.getArtboards() design.removeArtboard('a') const nextArtboards = design.getArtboards() strictEqual(nextArtboards.length, 0) }) }) describe('page-specific artboard lists', () => { it('should return empty page artboard lists by default', () => { const design = new Design() strictEqual(design.getPageArtboards('p1').length, 0) }) it('should include added artboards in their respective page artboard lists', () => { const design = new Design() design.addArtboard('a', createOctopus(), { pageId: 'p1' }) design.addArtboard('b', createOctopus(), { pageId: 'p2' }) const pageArtboards1 = design.getPageArtboards('p1') strictEqual(pageArtboards1.length, 1) ok(pageArtboards1[0]) strictEqual(pageArtboards1[0].id, 'a') const pageArtboards2 = design.getPageArtboards('p2') strictEqual(pageArtboards2.length, 1) ok(pageArtboards2[0]) strictEqual(pageArtboards2[0].id, 'b') }) it('should not include newly added artboards in a previously returned page artboard list', () => { const design = new Design() const prevArtboards = design.getPageArtboards('p1') design.addArtboard('a', createOctopus(), { pageId: 'p1' }) strictEqual(prevArtboards.length, 0) }) it('should include newly added artboards in the current artboard list', () => { const design = new Design() // eslint-disable-next-line @typescript-eslint/no-unused-vars const prevArtboards = design.getPageArtboards('p1') design.addArtboard('a', createOctopus(), { pageId: 'p1' }) const nextArtboards = design.getPageArtboards('p1') strictEqual(nextArtboards.length, 1) ok(nextArtboards[0]) strictEqual(nextArtboards[0].id, 'a') }) }) describe('master component artboards', () => { it('should return an added master component artboard by component ID', () => { const design = new Design() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) const artboard = design.getArtboardByComponentId('abc') ok(artboard) strictEqual(artboard.id, 'a') }) it('should not return a removed master component artboard by component ID', () => { const design = new Design() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) design.removeArtboard('a') const artboard = design.getArtboardByComponentId('abc') strictEqual(artboard, null) }) }) describe('master component artboard list', () => { it('should return an empty master component artboard list by default', () => { const design = new Design() strictEqual(design.getComponentArtboards().length, 0) }) it('should include an added artboard in the master component artboard list', () => { const design = new Design() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) const artboards = design.getComponentArtboards() strictEqual(artboards.length, 1) ok(artboards[0]) strictEqual(artboards[0].id, 'a') }) it('should not include newly added artboards in a previously returned master component artboard list', () => { const design = new Design() const prevArtboards = design.getComponentArtboards() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) strictEqual(prevArtboards.length, 0) }) it('should include newly added artboards in the current master component artboard list', () => { const design = new Design() // eslint-disable-next-line @typescript-eslint/no-unused-vars const prevArtboards = design.getComponentArtboards() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) const nextArtboards = design.getComponentArtboards() strictEqual(nextArtboards.length, 1) ok(nextArtboards[0]) strictEqual(nextArtboards[0].id, 'a') }) it('should keep newly removed artboards in a previously returned master component artboard list', () => { const design = new Design() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) const prevArtboards = design.getComponentArtboards() design.removeArtboard('a') strictEqual(prevArtboards.length, 1) ok(prevArtboards[0]) strictEqual(prevArtboards[0].id, 'a') }) it('should not include newly removed artboards in the current master component artboard list', () => { const design = new Design() design.addArtboard('a', { ...createOctopus(), 'symbolID': 'abc' }) // eslint-disable-next-line @typescript-eslint/no-unused-vars const prevArtboards = design.getComponentArtboards() design.removeArtboard('a') const nextArtboards = design.getComponentArtboards() strictEqual(nextArtboards.length, 0) }) }) describe('artboard info', () => { it('should not configure the artboard name by default', () => { const design = new Design() design.addArtboard('a', createOctopus()) const artboard = design.getArtboardById('a') ok(artboard) strictEqual(artboard.name, null) }) it('should configure the artboard name when specified', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Hello' }) const artboard = design.getArtboardById('a') ok(artboard) strictEqual(artboard.name, 'Hello') }) it('should not configure the artboard page ID by default', () => { const design = new Design() design.addArtboard('a', createOctopus()) const artboard = design.getArtboardById('a') ok(artboard) strictEqual(artboard.pageId, null) }) it('should configure the artboard page ID when specified', () => { const design = new Design() design.addArtboard('a', createOctopus(), { pageId: 'p1' }) const artboard = design.getArtboardById('a') ok(artboard) strictEqual(artboard.pageId, 'p1') }) }) describe('single artboard lookup', () => { it('should look up an added artboard by exact name match', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) const artboard = design.findArtboard({ name: 'Abc' }) ok(artboard) strictEqual(artboard.id, 'a') }) it('should look up the first added artboard exactly matching one of the listed names', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Def' }) const artboard = design.findArtboard({ name: ['Abc', 'Def'] }) ok(artboard) strictEqual(artboard.id, 'a') }) it('should look up the first added artboard matching a name pattern', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Def' }) const artboard = design.findArtboard({ name: /Abc|Def/ }) ok(artboard) strictEqual(artboard.id, 'a') }) it('should not look up any of the added artboards when neither matches the name', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) const artboard = design.findArtboard({ name: 'Unknown' }) strictEqual(artboard, null) }) it('should not look up a removed artboard when matching by name', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.removeArtboard('a') const artboard = design.findArtboard({ name: 'Abc' }) strictEqual(artboard, null) }) }) describe('multi-artboard lookup', () => { it('should look up added artboards by exact name match sorted by addition order', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Def' }) design.addArtboard('c', createOctopus(), { name: 'Abc' }) const artboards = design.findArtboards({ name: 'Abc' }) strictEqual(artboards.length, 2) ok(artboards[0]) ok(artboards[1]) strictEqual(artboards[0].id, 'a') strictEqual(artboards[1].id, 'c') }) it('should look up added artboards exactly matching one of the listed names', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Xyz' }) design.addArtboard('c', createOctopus(), { name: 'Def' }) const artboards = design.findArtboards({ name: ['Abc', 'Def'] }) strictEqual(artboards.length, 2) ok(artboards[0]) ok(artboards[1]) strictEqual(artboards[0].id, 'a') strictEqual(artboards[1].id, 'c') }) it('should look up the first added artboard matching a name pattern', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Xyz' }) design.addArtboard('c', createOctopus(), { name: 'Def' }) const artboards = design.findArtboards({ name: /Abc|Def/ }) strictEqual(artboards.length, 2) ok(artboards[0]) ok(artboards[1]) strictEqual(artboards[0].id, 'a') strictEqual(artboards[1].id, 'c') }) it('should not look up any of the added artboards when neither matches the name', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Def' }) const artboards = design.findArtboards({ name: 'Unknown' }) strictEqual(artboards.length, 0) }) it('should not look up removed artboards when matching by name', () => { const design = new Design() design.addArtboard('a', createOctopus(), { name: 'Abc' }) design.addArtboard('b', createOctopus(), { name: 'Abc' }) design.removeArtboard('a') const artboards = design.findArtboards({ name: 'Abc' }) strictEqual(artboards.length, 1) ok(artboards[0]) strictEqual(artboards[0].id, 'b') }) }) describe('layer lookup defaults', () => { it('should not return any individual layers based on an ID by default', () => { const design = new Design() strictEqual(design.findLayerById('abc'), null) }) it('should not return any layers based on an ID by default', () => { const design = new Design() strictEqual(design.findLayersById('abc').length, 0) }) it('should not return any individual layers based on a selector by default', () => { const design = new Design() strictEqual(design.findLayer({ name: 'abc' }), null) }) it('should not return any layers based on a selector by default', () => { const design = new Design() strictEqual(design.findLayers({ name: 'abc' }).length, 0) }) }) describe('artboard data aggregation defaults', () => { it('should not return any bitmap assets by default', () => { const design = new Design() strictEqual(design.getBitmapAssets().length, 0) }) it('should not return any fonts by default', () => { const design = new Design() strictEqual(design.getFonts().length, 0) }) it('should return an empty flattened layer list by default', () => { const design = new Design() strictEqual(design.getFlattenedLayers().length, 0) }) }) })
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { environment } from './../../../../../../../environments/environment'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { UtilsService } from '../../../../../../shared/services/utils.service'; import { LoggerService } from '../../../../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../../../../shared/services/error-handling.service'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/pairwise'; import { WorkflowService } from '../../../../../../core/services/workflow.service'; import { RouterUtilityService } from '../../../../../../shared/services/router-utility.service'; import { AdminService } from '../../../../../services/all-admin.service'; @Component({ selector: 'app-admin-create-update-domain', templateUrl: './create-update-domain.component.html', styleUrls: ['./create-update-domain.component.css'], providers: [ LoggerService, ErrorHandlingService, AdminService ] }) export class CreateUpdateDomainComponent implements OnInit, OnDestroy { pageTitle = ''; breadcrumbArray: any = ['Admin', 'Domains']; breadcrumbLinks: any = ['policies', 'domains']; breadcrumbPresent: any; outerArr: any = []; filters: any = []; domainName = ''; isCreate = false; successTitle = ''; failedTitle = ''; successSubTitle = ''; isDomainCreationUpdationFailed = false; isDomainCreationUpdationSuccess = false; loadingContent = ''; domainId = ''; isDomainNameValid: any = -1; paginatorSize = 25; isLastPage: boolean; isFirstPage: boolean; totalPages: number; pageNumber = 0; showLoader = true; domainLoader = false; errorMessage: any; domain: any = { name: '', desc: '', config: '' }; hideContent = false; filterText: any = {}; errorValue = 0; FullQueryParams: any; queryParamsWithoutFilter: any; urlToRedirect: any = ''; mandatory: any; public labels: any; private previousUrl: any = ''; private pageLevel = 0; public backButtonRequired; private routeSubscription: Subscription; private getKeywords: Subscription; private previousUrlSubscription: Subscription; constructor( private router: Router, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private workflowService: WorkflowService, private routerUtilityService: RouterUtilityService, private adminService: AdminService ) { this.routerParam(); this.updateComponent(); } ngOnInit() { this.urlToRedirect = this.router.routerState.snapshot.url; this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently( this.pageLevel ); } nextPage() { try { if (!this.isLastPage) { this.pageNumber++; this.showLoader = true; // this.getPolicyDetails(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } prevPage() { try { if (!this.isFirstPage) { this.pageNumber--; this.showLoader = true; // this.getPolicyDetails(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } createDomain(domain) { domain.name = domain.name.trim(); domain.desc = domain.desc.trim(); domain.config = domain.config.trim(); this.loadingContent = 'creating'; this.hideContent = true; this.domainLoader = true; this.isDomainCreationUpdationFailed = false; this.isDomainCreationUpdationSuccess = false; const url = environment.createDomain.url; const method = environment.createDomain.method; this.domainName = domain.name; this.adminService.executeHttpAction(url, method, domain, {}).subscribe(reponse => { this.successTitle = 'Domain Created'; this.isDomainCreationUpdationSuccess = true; this.domainLoader = false; this.domain.name = ''; this.domain.desc = ''; this.domain.config = ''; }, error => { this.failedTitle = 'Creation Failed'; this.domainLoader = false; this.isDomainCreationUpdationFailed = true; }); } updateDomain(domain) { domain.name = domain.name.trim(); domain.desc = domain.desc.trim(); domain.config = domain.config.trim(); this.loadingContent = 'updating'; this.hideContent = true; this.domainLoader = true; this.isDomainCreationUpdationFailed = false; this.isDomainCreationUpdationSuccess = false; const url = environment.updateDomain.url; const method = environment.updateDomain.method; this.domainName = domain.name; this.adminService.executeHttpAction(url, method, domain, {}).subscribe(reponse => { this.successTitle = 'Domain Updated'; this.isDomainCreationUpdationSuccess = true; this.domainLoader = false; this.domain.name = ''; this.domain.desc = ''; this.domain.config = ''; }, error => { this.failedTitle = 'Updation Failed'; this.domainLoader = false; this.isDomainCreationUpdationFailed = true; }); } closeErrorMessage() { if (this.failedTitle === 'Loading Failed') { this.getDomainDetails(this.domainName); } else { this.hideContent = false; } this.isDomainCreationUpdationFailed = false; this.isDomainCreationUpdationSuccess = false; } /* * This function gets the urlparameter and queryObj *based on that different apis are being hit with different queryparams */ routerParam() { try { // this.filterText saves the queryparam const currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root); if (currentQueryParams) { this.FullQueryParams = currentQueryParams; this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams)); this.domainName = this.queryParamsWithoutFilter.domainName; delete this.queryParamsWithoutFilter['filter']; if (this.domainName) { this.pageTitle = 'Edit Domain'; this.breadcrumbPresent = 'Edit Domain'; this.isCreate = false; this.getDomainDetails(this.domainName); } else { this.pageTitle = 'Create New Domain'; this.breadcrumbPresent = 'Create Domain'; this.isCreate = true; this.getAllDomainNames(); } /** * The below code is added to get URLparameter and queryparameter * when the page loads ,only then this function runs and hits the api with the * filterText obj processed through processFilterObj function */ this.filterText = this.utils.processFilterObj( this.FullQueryParams ); // check for mandatory filters. if (this.FullQueryParams.mandatory) { this.mandatory = this.FullQueryParams.mandatory; } } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } domainNames: any = []; isDomainNameAvailable(domainNameKeyword) { if (domainNameKeyword.trim().length == 0) { this.isDomainNameValid = -1; } else { let isKeywordExits = this.domainNames.findIndex(item => domainNameKeyword.trim().toLowerCase() === item.trim().toLowerCase()); if (isKeywordExits === -1) { this.isDomainNameValid = 1; } else { this.isDomainNameValid = 0; } } } getAllDomainNames() { this.hideContent = true; this.domainLoader = true; this.loadingContent = 'loading'; this.isDomainCreationUpdationFailed = false; this.isDomainCreationUpdationSuccess= false; const url = environment.getAllDomainNames.url; const method = environment.getAllDomainNames.method; this.adminService.executeHttpAction(url, method, {}, {domainName: this.domainName}).subscribe(reponse => { this.domainLoader = false; this.hideContent = false; this.domainNames = reponse[0]; }, error => { this.loadingContent = 'loading'; this.failedTitle = 'Loading Failed'; this.domainLoader = false; this.isDomainCreationUpdationFailed = true; }) } getDomainDetails(domainName) { this.hideContent = true; this.domainLoader = true; this.loadingContent = 'loading'; this.isDomainCreationUpdationFailed = false; this.isDomainCreationUpdationSuccess= false; const url = environment.domainDetailsByName.url; const method = environment.domainDetailsByName.method; this.adminService.executeHttpAction(url, method, {}, {domainName: this.domainName}).subscribe(reponse => { this.domainLoader = false; this.hideContent = false; const domainDetails = reponse[0]; this.domain.name = domainDetails.domainName; this.domain.desc = domainDetails.domainDesc; this.domain.config = domainDetails.config; }, error => { this.loadingContent = 'loading'; this.failedTitle = 'Loading Failed'; this.domainLoader = false; this.isDomainCreationUpdationFailed = true; }) } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.showLoader = true; this.errorValue = 0; } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } ngOnDestroy () { try { if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.previousUrlSubscription) { this.previousUrlSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
import React from "react" import Paper from "@material-ui/core/Paper"; import { useHistory, Link } from "react-router-dom" import firebase from "firebase" import { Grid, AppBar, Toolbar, Checkbox, FormControlLabel } from "@material-ui/core"; import { List, ListItem, ListItemText, ListItemIcon, Button } from "@material-ui/core"; import AddIcon from "@material-ui/icons/Add"; import { useUserShippingAddresses, useUser, useCart } from "hooks/commerce" import { useFetchList } from "hooks/stripe" import Loading from "components/Loading" import { Container, ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails, ExpansionPanelActions, Divider, Box } from "@material-ui/core"; import Typography from "@material-ui/core/Typography"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import DataLoading from "components/DataLoading"; import CardBrand from "common/stripe/CardBrand" import * as Commerce from "models/commerce" import { PaymentMethod } from "@stripe/stripe-js"; import { useProcessing } from "components/Processing"; import { useSnackbar } from "components/Snackbar" import { useDialog } from "components/Dialog" import CheckCircleIcon from "@material-ui/icons/CheckCircle"; export default (props: any) => { const { providerID } = props.match.params const history = useHistory() const [user, isUserLoading] = useUser() const [cart] = useCart() const [setProcessing] = useProcessing() const [setMessage] = useSnackbar() const enabled = (user?.defaultCard?.id && user?.defaultShipping) const checkout = async () => { if (!user) return if (!cart) return // customerID // const customerID = user.stripe?.customerID // if (!customerID) return // defaultShipping const defaultShipping = user.defaultShipping if (!defaultShipping) return // paymentMethodID const paymentMethodID = user.defaultCard?.id if (!paymentMethodID) return const cartGroup = cart.groups.find(group => group.providedBy === providerID) if (!cartGroup) return cartGroup.shipping = defaultShipping const data = cart.order(cartGroup) try { setProcessing(true) const checkoutCreate = firebase.functions().httpsCallable("commerce-v1-order-create") const response = await checkoutCreate({ order: data, paymentMethodID: paymentMethodID, // customerID: customerID }) const { error, result } = response.data if (error) { console.error(error) setMessage("error", error.message) setProcessing(false) return } console.log(result) setMessage("success", "Success") history.push(`/checkout/${providerID}/completed`) } catch (error) { setMessage("error", "Error") console.log(error) } setProcessing(false) } if (isUserLoading) { return <Container maxWidth="sm"><Loading /></Container> } return ( <Container maxWidth="sm"> <Grid container spacing={2}> <Grid item xs={12}> <ShippingAddresses user={user!} /> </Grid> <Grid item xs={12}> <PaymentMethods user={user!} /> </Grid> <Grid item xs={12}> <Button fullWidth variant="contained" size="large" color="primary" startIcon={<CheckCircleIcon />} disabled={!enabled} onClick={checkout} > Checkout </Button> </Grid> </Grid> </Container> ) } const ShippingAddresses = ({ user }: { user: Commerce.User }) => { const [shippingAddresses, isLoading] = useUserShippingAddresses() const history = useHistory() const [showDialog, close] = useDialog() if (isLoading) { return ( <Paper> <DataLoading /> </Paper> ) } return ( <Paper> <AppBar position="static" color="transparent" elevation={0}> <Toolbar> <Typography variant="h6"> Shippingg Addresses </Typography> </Toolbar> </AppBar> { shippingAddresses.map(shipping => { return ( <ExpansionPanel key={shipping.id} > <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <FormControlLabel onClick={async (event) => { event.stopPropagation() user.defaultShipping = shipping await user.save() }} onFocus={(event) => event.stopPropagation()} control={<Checkbox checked={user.defaultShipping?.id === shipping.id} />} label={ <Typography>{shipping.format(["postal_code", "line1"])}</Typography> } /> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> {shipping.formatted()} </Typography> </ExpansionPanelDetails> <Divider /> <ExpansionPanelActions> <Button size="small" onClick={async () => { showDialog("Delete", "Do you want to remove it?", [ { title: "Cancel", handler: close }, { title: "OK", handler: async () => { if (user?.defaultShipping?.id === shipping.id) { showDialog("Selected shipping address", "This shipping address is currently selected. To delete this shipping address, please select another shipping address first.", [ { title: "OK" }]) } else { await shipping?.delete() } } }]) }}>Delete</Button> <Button size="small" color="primary" onClick={() => { history.push(`/checkout/shipping/${shipping.id}`) }}> Edit </Button> </ExpansionPanelActions> </ExpansionPanel> ) }) } <List> <ListItem button component={Link} to="/checkout/shipping"> <ListItemIcon> <AddIcon color="secondary" /> </ListItemIcon> <ListItemText primary={`Add new shpping address`} /> </ListItem> </List> </Paper> ) } const PaymentMethods = ({ user }: { user: Commerce.User }) => { const [setProcessing] = useProcessing() const [paymentMethods, isLoading, error, setPaymentMethods] = useFetchList<PaymentMethod>("stripe-v1-paymentMethod-list", { type: "card" }) const [showDialog, close] = useDialog() const [setMessage] = useSnackbar() if (error) { console.error(error) } const setDefaultPaymentMethod = async (paymentMethod: PaymentMethod) => { setProcessing(true) const customerUpdate = firebase.functions().httpsCallable("stripe-v1-customer-update") try { const response = await customerUpdate({ // payment_method: paymentMethod.id, invoice_settings: { default_payment_method: paymentMethod.id } }) const { result, error } = response.data if (error) { console.error(error) setProcessing(false) setMessage("error", error.message) return } const card = new Commerce.Card(paymentMethod.id) card.brand = paymentMethod.card!.brand card.expMonth = paymentMethod.card!.exp_month card.expYear = paymentMethod.card!.exp_year card.last4 = paymentMethod.card!.last4 await user.documentReference.set({ defaultCard: card.convert() }, { merge: true }) console.log("[APP] set default payment method", result) } catch (error) { console.error(error) } setProcessing(false) } const paymentMethodDetach = async (deletePaymentMethod: PaymentMethod) => { if (!deletePaymentMethod) { return } setProcessing(true) try { const detach = firebase.functions().httpsCallable("stripe-v1-paymentMethod-detach") const response = await detach({ paymentMethodID: deletePaymentMethod.id }) const { result, error } = response.data console.log("[APP] detach payment method", result) const data = paymentMethods.filter(method => method.id !== deletePaymentMethod.id) if (deletePaymentMethod.id === user.defaultCard?.id) { if (data.length > 0) { const method = data[0] await setDefaultPaymentMethod(method) } else { await user.documentReference.set({ defaultCard: null }, { merge: true }) } } setPaymentMethods(data) } catch (error) { console.error(error) } setProcessing(false) } if (isLoading) { return ( <Paper> <DataLoading /> </Paper> ) } return ( <Paper> <AppBar position="static" color="transparent" elevation={0}> <Toolbar> <Box fontSize={18} fontWeight={600}> Payments </Box> </Toolbar> </AppBar> { paymentMethods.map(method => { return ( <ExpansionPanel key={method.id} > <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <FormControlLabel onClick={async (event) => { event.stopPropagation() await setDefaultPaymentMethod(method) }} onFocus={(event) => event.stopPropagation()} control={<Checkbox checked={user?.defaultCard?.id === method.id} />} label={ <Box display="flex" alignItems="center" flexGrow={1} style={{ width: "140px" }}> <Box display="flex" alignItems="center" flexGrow={1}> <i className={`pf ${CardBrand[method.card!.brand]}`}></i> </Box> <Box justifySelf="flex-end"> {`โ€ข โ€ข โ€ข โ€ข ${method.card?.last4}`} </Box> </Box> } /> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> expire {`${method.card?.exp_year}/${method.card?.exp_month}`} </Typography> </ExpansionPanelDetails> <Divider /> <ExpansionPanelActions> <Button size="small" onClick={async () => { showDialog("Delete", "Do you want to remove it?", [ { title: "Cancel", handler: close }, { title: "OK", handler: async () => { await paymentMethodDetach(method) } }]) }}>Delete</Button> </ExpansionPanelActions> </ExpansionPanel> ) }) } <List> <ListItem button component={Link} to="/checkout/paymentMethod"> <ListItemIcon> <AddIcon color="secondary" /> </ListItemIcon> <ListItemText primary={`Add new payment method`} /> </ListItem> </List> </Paper> ) }
the_stack
import { LemmingsSprite } from '../resources/lemmings-sprite'; import { TriggerTypes } from '../resources/lemmings/trigger-types'; import { Level } from '../resources/level'; import { MaskProvider } from '../resources/mask-provider'; import { ParticleTable } from '../resources/particle-table'; import { LogHandler } from '../utilities/log-handler'; import { DisplayImage } from '../view/display-image'; import { IActionSystem } from './action-system'; import { ActionBashSystem } from './actions/action-bash-system'; import { ActionBlockerSystem } from './actions/action-blocker-system'; import { ActionBuildSystem } from './actions/action-build-system'; import { ActionClimbSystem } from './actions/action-climb-system'; import { ActionCountdownSystem } from './actions/action-countdown-system'; import { ActionDiggSystem } from './actions/action-digg-system'; import { ActionDrowningSystem } from './actions/action-drowning-system'; import { ActionExitingSystem } from './actions/action-exiting-system'; import { ActionExplodingSystem } from './actions/action-exploding-system'; import { ActionFallSystem } from './actions/action-fall-system'; import { ActionFloatingSystem } from './actions/action-floating-system'; import { ActionHoistSystem } from './actions/action-hoist-system'; import { ActionJumpSystem } from './actions/action-jump-system'; import { ActionMineSystem } from './actions/action-mine-system'; import { ActionOhNoSystem } from './actions/action-ohno-system'; import { ActionShrugSystem } from './actions/action-shrug-system'; import { ActionSplatterSystem } from './actions/action-splatter-system'; import { ActionWalkSystem } from './actions/action-walk-system'; import { GameVictoryCondition } from './game-victory-condition'; import { Lemming } from './lemming'; import { LemmingStateType } from './lemming-state-type'; import { SkillTypes } from './skill-types'; import { TriggerManager } from './trigger-manager'; export class LemmingManager { /** list of all Lemming in the game */ private lemmings: Lemming[] = []; /** list of all Actions a Lemming can do */ private actions: IActionSystem[] = []; private skillActions: IActionSystem[] = []; private releaseTickIndex: number = 0; private logging = new LogHandler("LemmingManager"); /** next lemming index need to explode */ private nextNukingLemmingsIndex: number = -1; constructor(private level: Level, lemmingsSprite: LemmingsSprite, private triggerManager: TriggerManager, private gameVictoryCondition: GameVictoryCondition, masks: MaskProvider, particleTable: ParticleTable) { this.actions[LemmingStateType.WALKING] = new ActionWalkSystem(lemmingsSprite); this.actions[LemmingStateType.FALLING] = new ActionFallSystem(lemmingsSprite); this.actions[LemmingStateType.JUMPING] = new ActionJumpSystem(lemmingsSprite); this.actions[LemmingStateType.DIGGING] = new ActionDiggSystem(lemmingsSprite); this.actions[LemmingStateType.EXITING] = new ActionExitingSystem(lemmingsSprite, gameVictoryCondition); this.actions[LemmingStateType.FLOATING] = new ActionFloatingSystem(lemmingsSprite); this.actions[LemmingStateType.BLOCKING] = new ActionBlockerSystem(lemmingsSprite, triggerManager); this.actions[LemmingStateType.MINEING] = new ActionMineSystem(lemmingsSprite, masks); this.actions[LemmingStateType.CLIMBING] = new ActionClimbSystem(lemmingsSprite); this.actions[LemmingStateType.HOISTING] = new ActionHoistSystem(lemmingsSprite); this.actions[LemmingStateType.BASHING] = new ActionBashSystem(lemmingsSprite, masks); this.actions[LemmingStateType.BUILDING] = new ActionBuildSystem(lemmingsSprite); this.actions[LemmingStateType.SHRUG] = new ActionShrugSystem(lemmingsSprite); this.actions[LemmingStateType.EXPLODING] = new ActionExplodingSystem(lemmingsSprite, masks, triggerManager, particleTable); this.actions[LemmingStateType.OHNO] = new ActionOhNoSystem(lemmingsSprite); this.actions[LemmingStateType.SPLATTING] = new ActionSplatterSystem(lemmingsSprite); this.actions[LemmingStateType.DROWNING] = new ActionDrowningSystem(lemmingsSprite); this.skillActions[SkillTypes.DIGGER] = this.actions[LemmingStateType.DIGGING]; this.skillActions[SkillTypes.FLOATER] = this.actions[LemmingStateType.FLOATING]; this.skillActions[SkillTypes.BLOCKER] = this.actions[LemmingStateType.BLOCKING]; this.skillActions[SkillTypes.MINER] = this.actions[LemmingStateType.MINEING]; this.skillActions[SkillTypes.CLIMBER] = this.actions[LemmingStateType.CLIMBING]; this.skillActions[SkillTypes.BASHER] = this.actions[LemmingStateType.BASHING]; this.skillActions[SkillTypes.BUILDER] = this.actions[LemmingStateType.BUILDING]; this.skillActions[SkillTypes.BOMBER] = new ActionCountdownSystem(masks); /// wait before first lemming is spawn this.releaseTickIndex = this.gameVictoryCondition.getCurrentReleaseRate() - 30; } private processNewAction(lem: Lemming, newAction: LemmingStateType): boolean { if (newAction == LemmingStateType.NO_STATE_TYPE) { return false; } this.setLemmingState(lem, newAction); return true; } /** process all Lemmings to the next time-step */ public tick() { this.addNewLemmings(); let lems = this.lemmings; if (this.isNuking()) { this.doLemmingAction(lems[this.nextNukingLemmingsIndex], SkillTypes.BOMBER); this.nextNukingLemmingsIndex++; } for (let i = 0; i < lems.length; i++) { let lem = lems[i]; if (lem.removed) continue; let newAction = lem.process(this.level); this.processNewAction(lem, newAction); let triggerAction = this.runTrigger(lem); this.processNewAction(lem, triggerAction); } } /** Add a new Lemming to the manager */ private addLemming(x: number, y: number) { let lem = new Lemming(x, y, this.lemmings.length); this.setLemmingState(lem, LemmingStateType.FALLING); this.lemmings.push(lem); } /** let a new lemming arise from an entrance */ private addNewLemmings() { if (this.gameVictoryCondition.getLeftCount() <= 0) { return; } this.releaseTickIndex++; if (this.releaseTickIndex >= (104 - this.gameVictoryCondition.getCurrentReleaseRate())) { this.releaseTickIndex = 0; let entrance = this.level.entrances[0]; this.addLemming(entrance.x + 24, entrance.y + 14); this.gameVictoryCondition.releaseOne(); } } private runTrigger(lem: Lemming): LemmingStateType { if (lem.isRemoved() || (lem.isDisabled())) { return LemmingStateType.NO_STATE_TYPE; } let triggerType = this.triggerManager.trigger(lem.x, lem.y); switch (triggerType) { case TriggerTypes.NO_TRIGGER: return LemmingStateType.NO_STATE_TYPE; case TriggerTypes.DROWN: return LemmingStateType.DROWNING; case TriggerTypes.EXIT_LEVEL: return LemmingStateType.EXITING; case TriggerTypes.KILL: return LemmingStateType.SPLATTING; case TriggerTypes.TRAP: return LemmingStateType.HOISTING; case TriggerTypes.BLOCKER_LEFT: if (lem.lookRight) lem.lookRight = false; return LemmingStateType.NO_STATE_TYPE; case TriggerTypes.BLOCKER_RIGHT: if (!lem.lookRight) lem.lookRight = true; return LemmingStateType.NO_STATE_TYPE; default: this.logging.log("unknown trigger type: " + triggerType); return LemmingStateType.NO_STATE_TYPE; } } /** render all Lemmings to the GameDisplay */ public render(gameDisplay: DisplayImage) { let lems = this.lemmings; for (let i = 0; i < lems.length; i++) { lems[i].render(gameDisplay); } } /** render all Lemmings to the GameDisplay */ public renderDebug(gameDisplay: DisplayImage) { let lems = this.lemmings; for (let i = 0; i < lems.length; i++) { lems[i].renderDebug(gameDisplay); } } /** return the lemming with a given id */ public getLemming(id:number): Lemming { return this.lemmings[id]; } /** return a lemming at a given position */ public getLemmingAt(x: number, y: number): Lemming | null { let lems = this.lemmings; let minDistance = 99999; let minDistanceLem = null; for (let i = 0; i < lems.length; i++) { let lem = lems[i]; let distance = lem.getClickDistance(x, y); //console.log("--> "+ distance); if ((distance < 0) || (distance >= minDistance)) { continue; } minDistance = distance; minDistanceLem = lem; } //console.log("====> "+ (minDistanceLem? minDistanceLem.id : "null")); return minDistanceLem; } /** change the action a Lemming is doing */ private setLemmingState(lem: Lemming, stateType: LemmingStateType) { if (stateType == LemmingStateType.OUT_OFF_LEVEL) { lem.remove(); this.gameVictoryCondition.removeOne(); return; } let actionSystem = this.actions[stateType]; if (actionSystem == null) { lem.remove(); this.logging.log(lem.id + " Action: Error not an action: " + LemmingStateType[stateType]); return; } else { this.logging.debug(lem.id + " Action: " + actionSystem.getActionName()); } lem.setAction(actionSystem); } /** change the action a Lemming is doing */ public doLemmingAction(lem: Lemming, skillType: SkillTypes): boolean { if (lem == null) { return false; } let actionSystem = this.skillActions[skillType]; if (!actionSystem) { this.logging.log(lem.id + " Unknown Action: " + skillType); return false; } return actionSystem.triggerLemAction(lem); } /** return if the game is in nuke state */ public isNuking() { return this.nextNukingLemmingsIndex >= 0; } /** start the nuking of all lemmings */ public doNukeAllLemmings() { this.nextNukingLemmingsIndex = 0; } }
the_stack
import { MarshallerProvider } from "../../MarshallerProvider"; import { JavaArrayList, JavaBigDecimal, JavaBigInteger, JavaBoolean, JavaByte, JavaDate, JavaDouble, JavaFloat, JavaHashMap, JavaHashSet, JavaInteger, JavaLong, JavaOptional, JavaShort, JavaString } from "../../../java-wrappers"; import { JavaHashMapMarshaller } from "../JavaHashMapMarshaller"; import { MarshallingContext } from "../../MarshallingContext"; import { ErraiObjectConstants } from "../../model/ErraiObjectConstants"; import { Portable } from "../../../marshalling/Portable"; import { DefaultMarshaller } from "../DefaultMarshaller"; import { NumValBasedErraiObject } from "../../model/NumValBasedErraiObject"; import { NumberUtils } from "../../../util/NumberUtils"; import { UnmarshallingContext } from "../../UnmarshallingContext"; import { ValueBasedErraiObject } from "../../model/ValueBasedErraiObject"; import { JavaType } from "../../../java-wrappers/JavaType"; describe("marshall", () => { const encodedType = ErraiObjectConstants.ENCODED_TYPE; const objectId = ErraiObjectConstants.OBJECT_ID; const value = ErraiObjectConstants.VALUE; const json = ErraiObjectConstants.JSON; beforeEach(() => { MarshallerProvider.initialize(); }); test("with empty map, should serialize normally", () => { const input = new JavaHashMap(new Map()); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: {} }); }); test("with string key and value, should serialize normally", () => { const input = new JavaHashMap(new Map([["foo1", "bar1"], ["foo2", "bar2"]])); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { foo1: "bar1", foo2: "bar2" } }); }); test("with JavaNumber key and value, should wrap key and value into an errai object", () => { const input = new JavaHashMap( new Map([[new JavaInteger("11"), new JavaInteger("12")], [new JavaInteger("21"), new JavaInteger("22")]]) ); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); const expectedKey1 = `${json + JSON.stringify(new NumValBasedErraiObject(JavaType.INTEGER, 11).asErraiObject())}`; const expectedKey2 = `${json + JSON.stringify(new NumValBasedErraiObject(JavaType.INTEGER, 21).asErraiObject())}`; expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [expectedKey1]: new NumValBasedErraiObject(JavaType.INTEGER, 12).asErraiObject(), [expectedKey2]: new NumValBasedErraiObject(JavaType.INTEGER, 22).asErraiObject() } }); }); test("with JavaBoolean key and value, should wrap key and value into an errai object", () => { const input = new JavaHashMap( new Map([[new JavaBoolean(true), new JavaBoolean(false)], [new JavaBoolean(false), new JavaBoolean(true)]]) ); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); const expectedKey1 = `${json + JSON.stringify(new NumValBasedErraiObject(JavaType.BOOLEAN, true).asErraiObject())}`; const expectedKey2 = `${json + JSON.stringify(new NumValBasedErraiObject(JavaType.BOOLEAN, false).asErraiObject())}`; expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [expectedKey1]: new NumValBasedErraiObject(JavaType.BOOLEAN, false).asErraiObject(), [expectedKey2]: new NumValBasedErraiObject(JavaType.BOOLEAN, true).asErraiObject() } }); }); test("with JavaBigNumber key and value, should wrap key and value into an errai object", () => { const input = new JavaHashMap( new Map([ [new JavaBigInteger("11"), new JavaBigInteger("12")], [new JavaBigInteger("21"), new JavaBigInteger("22")] ]) ); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext())!; // need to assert the keys individually because since it's a string, can't use the regex matcher in the object id :/ const mapKeys = Object.keys(output[value]); expect(mapKeys.length).toBe(2); const key1Str = mapKeys[0]; const key2Str = mapKeys[1]; mapKeys.forEach(k => { // complex objects as map key uses a prefix to indicate that a json must be parsed in the map key expect(k.startsWith(json)).toBeTruthy(); }); const key1Obj = JSON.parse(key1Str.replace(json, "")); const key2Obj = JSON.parse(key2Str.replace(json, "")); expect(key1Obj).toStrictEqual({ [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "11" }); expect(key2Obj).toStrictEqual({ [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "21" }); // assert map values expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [key1Str]: { [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "12" }, [key2Str]: { [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "22" } } }); }); test("with custom object key and value, should wrap key and value into an errai object", () => { const input = new JavaHashMap( new Map([ [new DummyPojo({ foo: "bar11" }), new DummyPojo({ foo: "bar12" })], [new DummyPojo({ foo: "bar21" }), new DummyPojo({ foo: "bar22" })] ]) ); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext())!; // need to assert the keys individually because since it's a string, can't use the regex matcher in the object id :/ const mapKeys = Object.keys(output[value]); expect(mapKeys.length).toBe(2); const key1Str = mapKeys[0]; const key2Str = mapKeys[1]; mapKeys.forEach(k => { // complex objects as map key uses a prefix to indicate that a json must be parsed in the map key expect(k.startsWith(json)).toBeTruthy(); }); const key1Obj = JSON.parse(key1Str.replace(json, "")); const key2Obj = JSON.parse(key2Str.replace(json, "")); expect(key1Obj).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "bar11" }); expect(key2Obj).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "bar21" }); // assert map values expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [key1Str]: { [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "bar12" }, [key2Str]: { [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "bar22" } } }); }); test("with undefined key and value, should set key as null reference and value as null", () => { const input = new JavaHashMap(new Map([[undefined, undefined]])); const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [ErraiObjectConstants.NULL]: null } }); }); test("with custom pojo containing cached key, should reuse it and don't repeat data", () => { const repeatedPojo = new DummyPojo({ foo: "repeatedKey" }); const input = new ComplexPojo({ dummy: repeatedPojo, map: new Map([[repeatedPojo, "value1"], [new DummyPojo({ foo: "uniqueKey" }), "value2"]]) }); const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context)!; // ===== assertions // 1) Assert map content const mapOutput = (output as any).map; const mapKeys = Object.keys(mapOutput[value]); expect(mapKeys.length).toBe(2); const key1Str = mapKeys[0]; const key2Str = mapKeys[1]; mapKeys.forEach(k => { // complex objects as map key uses a prefix to indicate that a json must be parsed in the map key expect(k.startsWith(json)).toBeTruthy(); }); const key1Obj = JSON.parse(key1Str.replace(json, "")); const key2Obj = JSON.parse(key2Str.replace(json, "")); // assert keys contents const key1ObjectId = key1Obj[objectId]; // this is the cached object's id expect(key1ObjectId).toMatch(NumberUtils.nonNegativeIntegerRegex); expect(key1Obj).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: key1ObjectId // without object's content }); expect(key2Obj).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "uniqueKey" }); // assert map values contents expect(mapOutput).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { [key1Str]: "value1", [key2Str]: "value2" } }); // 2) Assert full object content expect(output).toStrictEqual({ [encodedType]: "com.app.my.ComplexPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), dummy: { [encodedType]: "com.app.my.DummyPojo", [objectId]: key1ObjectId, // same object id than the one used as map key foo: "repeatedKey" }, map: mapOutput // already asserted }); // do not cache repeated object's data expect(context.getCached(repeatedPojo)).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: key1ObjectId }); }); test("with map containing repeated value, should reuse it and don't repeat data", () => { const repeatedValue = new DummyPojo({ foo: "repeatedValue" }); const uniqueValue = new DummyPojo({ foo: "uniqueValue" }); const input = new JavaHashMap(new Map([["key1", repeatedValue], ["key2", repeatedValue], ["key3", uniqueValue]])); const context = new MarshallingContext(); const output = new JavaHashMapMarshaller().marshall(input, context); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { key1: { [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "repeatedValue" }, key2: { [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex) // missing data }, key3: { [encodedType]: "com.app.my.DummyPojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "uniqueValue" } } }); // same object id const repeatedObjIdFirstAppearance = (output as any)[value].key1[objectId]; const repeatedObjIdSecondAppearance = (output as any)[value].key2[objectId]; expect(repeatedObjIdFirstAppearance).toEqual(repeatedObjIdSecondAppearance); // do not cache repeated object's data expect(context.getCached(repeatedValue)).toStrictEqual({ [encodedType]: "com.app.my.DummyPojo", [objectId]: repeatedObjIdFirstAppearance }); }); test("with root null object, should serialize to null", () => { const input = null as any; const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); expect(output).toBeNull(); }); test("with root undefined object, should serialize to null", () => { const input = undefined as any; const output = new JavaHashMapMarshaller().marshall(input, new MarshallingContext()); expect(output).toBeNull(); }); }); describe("unmarshall", () => { beforeEach(() => { MarshallerProvider.initialize(); }); test("with empty map, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap<string, string>(new Map<string, string>()); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map()); }); test("with string key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const stringInput = new JavaHashMap(new Map([["foo1", "bar1"]])); const javaStringInput = new JavaHashMap(new Map([[new JavaString("foo1"), new JavaString("bar1")]])); [stringInput, javaStringInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([["foo1", "bar1"]])); }); }); test("with Array key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const arrayInput = new JavaHashMap(new Map([[["foo1"], ["bar1"]]])); const arrayListInput = new JavaHashMap(new Map([[new JavaArrayList(["foo1"]), new JavaArrayList(["bar1"])]])); [arrayInput, arrayListInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[["foo1"], ["bar1"]]])); }); }); test("with Set key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const setInput = new JavaHashMap(new Map([[new Set(["foo1"]), new Set(["bar1"])]])); const hashSetInput = new JavaHashMap( new Map([[new JavaHashSet(new Set(["foo1"])), new JavaHashSet(new Set(["bar1"]))]]) ); [setInput, hashSetInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new Set(["foo1"]), new Set(["bar1"])]])); }); }); test("with Map key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const mapInput = new JavaHashMap(new Map([[new Map([["kfoo1", "kbar1"]]), new Map([["vfoo1", "vbar1"]])]])); const hashMapInput = new JavaHashMap( new Map([[new JavaHashMap(new Map([["kfoo1", "kbar1"]])), new JavaHashMap(new Map([["vfoo1", "vbar1"]]))]]) ); [mapInput, hashMapInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new Map([["kfoo1", "kbar1"]]), new Map([["vfoo1", "vbar1"]])]])); }); }); test("with Date key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const baseDateKey = new Date(); const baseDateValue = new Date(); const dateInput = new JavaHashMap(new Map([[baseDateKey, baseDateValue]])); const javaDateInput = new JavaHashMap(new Map([[new JavaDate(baseDateKey), new JavaDate(baseDateValue)]])); [dateInput, javaDateInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[baseDateKey, baseDateValue]])); }); }); test("with Boolean key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const booleanInput = new JavaHashMap(new Map([[false, true]])); const javaBooleanInput = new JavaHashMap(new Map([[new JavaBoolean(false), new JavaBoolean(true)]])); [booleanInput, javaBooleanInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[false, true]])); }); }); test("with String key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const stringInput = new JavaHashMap(new Map([["foo", "bar"]])); const javaStringInput = new JavaHashMap(new Map([[new JavaString("foo"), new JavaString("bar")]])); [stringInput, javaStringInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([["foo", "bar"]])); }); }); test("with JavaOptional key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaOptional("foo"), new JavaOptional("bar")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaOptional("foo"), new JavaOptional("bar")]])); }); test("with JavaBigDecimal key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaBigDecimal("1.1"), new JavaBigDecimal("1.1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaBigDecimal("1.1"), new JavaBigDecimal("1.1")]])); }); test("with JavaBigInteger key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaBigInteger("1"), new JavaBigInteger("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaBigInteger("1"), new JavaBigInteger("1")]])); }); test("with JavaLong key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaLong("1"), new JavaLong("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaLong("1"), new JavaLong("1")]])); }); test("with JavaByte key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaByte("1"), new JavaByte("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaByte("1"), new JavaByte("1")]])); }); test("with JavaDouble key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaDouble("1.1"), new JavaDouble("1.1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaDouble("1.1"), new JavaDouble("1.1")]])); }); test("with JavaFloat key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaFloat("1.1"), new JavaFloat("1.1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaFloat("1.1"), new JavaFloat("1.1")]])); }); test("with JavaInteger key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaInteger("1"), new JavaInteger("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaInteger("1"), new JavaInteger("1")]])); }); test("with JavaShort key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaShort("1"), new JavaShort("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaShort("1"), new JavaShort("1")]])); }); test("with JavaShort key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[new JavaShort("1"), new JavaShort("1")]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[new JavaShort("1"), new JavaShort("1")]])); }); test("with custom object key and value, should unmarshall correctly", () => { const oracle = new Map([["com.app.my.DummyPojo", () => new DummyPojo({} as any)]]); const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap( new Map([ [new DummyPojo({ foo: "bar11" }), new DummyPojo({ foo: "bar12" })], [new DummyPojo({ foo: "bar21" }), new DummyPojo({ foo: "bar22" })] ]) ); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(oracle)); expect(output).toEqual( new Map([ [new DummyPojo({ foo: "bar11" }), new DummyPojo({ foo: "bar12" })], [new DummyPojo({ foo: "bar21" }), new DummyPojo({ foo: "bar22" })] ]) ); }); test("with undefined key and value, should unmarshall correctly", () => { const marshaller = new JavaHashMapMarshaller(); const input = new JavaHashMap(new Map([[undefined, undefined]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([[undefined, undefined]])); }); test("with custom pojo containing cached key, should reuse cached objects and don't recreate data", () => { const marshaller = new DefaultMarshaller(); const oracle: Map<string, () => Portable<any>> = new Map([ ["com.app.my.DummyPojo", () => new DummyPojo({} as any) as any], ["com.app.my.ComplexPojo", () => new ComplexPojo({} as any) as any] ]); const repeatedPojo = new DummyPojo({ foo: "repeatedKey" }); const input = new ComplexPojo({ dummy: repeatedPojo, map: new Map([[repeatedPojo, "value1"], [new DummyPojo({ foo: "uniqueKey" }), "value2"]]) }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle))! as ComplexPojo; // ===== assertions // successfully unmarshalled expect(output).toEqual(input); // same object for the cached one const repeatedPojoFromKey = output.map.keys().next().value; expect(output.dummy).toBe(repeatedPojoFromKey); }); test("with map containing repeated value, should reuse cached objects and don't recreate data", () => { const marshaller = new JavaHashMapMarshaller(); const oracle: Map<string, () => Portable<any>> = new Map([ ["com.app.my.DummyPojo", () => new DummyPojo({} as any)] ]); const repeatedPojo = new DummyPojo({ foo: "repeatedKey" }); const input = new JavaHashMap(new Map([["k1", repeatedPojo], ["k2", repeatedPojo]])); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle))!; // ===== assertions // successfully unmarshalled expect(output).toEqual(new Map([["k1", repeatedPojo], ["k2", repeatedPojo]])); // same objects for the values expect(output.get("k1")!).toBe(output.get("k2")!); }); test("with null inside ErraiObject's value, should throw error", () => { const context = new UnmarshallingContext(new Map()); const marshaller = new JavaHashMapMarshaller(); const marshalledInput = new ValueBasedErraiObject(JavaType.HASH_MAP, null as any).asErraiObject(); expect(() => marshaller.unmarshall(marshalledInput!, context)).toThrowError(); }); }); class DummyPojo implements Portable<DummyPojo> { private readonly _fqcn = "com.app.my.DummyPojo"; public readonly foo: string; constructor(self: { foo: string }) { Object.assign(this, self); } } class ComplexPojo implements Portable<ComplexPojo> { private readonly _fqcn = "com.app.my.ComplexPojo"; public dummy: DummyPojo; public map: Map<DummyPojo, string>; constructor(self: { dummy: DummyPojo; map: Map<DummyPojo, string> }) { Object.assign(this, self); } }
the_stack
import * as d3 from 'd3'; import * as Plottable from 'plottable'; import * as _ from 'lodash'; import {PointerInteraction} from '../vz_chart_helpers/plottable-interactions'; import * as vz_chart_helpers from '../vz_chart_helpers/vz-chart-helpers'; import { SymbolFn, XComponents, TooltipColumn, } from '../vz_chart_helpers/vz-chart-helpers'; import '../vz_chart_helpers/vz-chart-tooltip'; import {LinearScale} from './linear-scale'; import {LogScale} from './log-scale'; import {ITfScale} from './tf-scale'; import {PanZoomDragLayer} from './panZoomDragLayer'; /** * An interface that describes a fill area to visualize. The fill area is * visualized with a less intense version of the color for a given series. */ export interface FillArea { // The lower end of the fill area. lowerAccessor: Plottable.IAccessor<number>; // The higher end of the fill area. higherAccessor: Plottable.IAccessor<number>; } enum TooltipColumnEvalType { TEXT, DOM, } export enum YScaleType { LOG = 'log', LINEAR = 'linear', } export type LineChartStatus = { smoothingEnabled: boolean; }; /** * Adds private APIs for default swatch column on the first column. */ interface LineChartTooltipColumn extends TooltipColumn { evalType: TooltipColumnEvalType; enter: () => void; } export type Metadata = { name: string; meta: any; }; /** * The maximum number of marker symbols within any line for a data series. Too * many markers clutter the chart. */ const _MAX_MARKERS = 20; export class LineChart { private name2datasets: { [name: string]: Plottable.Dataset; }; private seriesNames: string[]; private xAccessor: Plottable.IAccessor<number | Date>; private xScale: Plottable.QuantitativeScale<number | Date>; private yScale: ITfScale; private gridlines: Plottable.Components.Gridlines; private center: Plottable.Components.Group; private xAxis: Plottable.Axes.Numeric | Plottable.Axes.Time; private yAxis: Plottable.Axes.Numeric; private outer: Plottable.Components.Table; private colorScale: Plottable.Scales.Color; private symbolFunction: SymbolFn; private tooltipColumns: Array< LineChartTooltipColumn | LineChartTooltipColumn >; // VzChartTooltip; strong type removed to work around legacy element mixin export issue private tooltip: any; private tooltipInteraction: Plottable.Interactions.Pointer; private tooltipPointsComponent: Plottable.Component; private linePlot: Plottable.Plots.Line<number | Date>; private smoothLinePlot: Plottable.Plots.Line<number | Date>; private marginAreaPlot?: Plottable.Plots.Area<number | Date>; private scatterPlot: Plottable.Plots.Scatter<number | Date, Number>; private nanDisplay: Plottable.Plots.Scatter<number | Date, Number>; private markersScatterPlot: Plottable.Plots.Scatter<number | Date, number>; private yValueAccessor: Plottable.IAccessor<number>; private smoothedAccessor: Plottable.IAccessor<number>; private lastPointsDataset: Plottable.Dataset; private fillArea?: FillArea; private datasets: Plottable.Dataset[]; private nanDataset: Plottable.Dataset; private smoothingWeight: number; private smoothingEnabled: boolean; private tooltipSortingMethod: string; private _ignoreYOutliers: boolean; private _lastMousePosition: Plottable.Point; private _lastDrawBBox: DOMRect; private _redrawRaf: number; private _invalidateLayoutRaf: number; // An optional list of 2 numbers. private _defaultXRange: number[]; // An optional list of 2 numbers. private _defaultYRange: number[]; private _tooltipUpdateAnimationFrame: number; private targetSVG: d3.Selection<any, any, any, any>; constructor( xComponentsCreationMethod: () => XComponents, yValueAccessor: Plottable.IAccessor<number>, yScaleType: YScaleType, colorScale: Plottable.Scales.Color, tooltip: any, // VzChartTooltip tooltipColumns: TooltipColumn[], fillArea: FillArea, defaultXRange?: number[], defaultYRange?: number[], symbolFunction?: SymbolFn, xAxisFormatter?: (number) => string ) { this.seriesNames = []; this.name2datasets = {}; this.colorScale = colorScale; this.tooltip = tooltip; this.datasets = []; this._ignoreYOutliers = false; // lastPointDataset is a dataset that contains just the last point of // every dataset we're currently drawing. this.lastPointsDataset = new Plottable.Dataset(); this.nanDataset = new Plottable.Dataset(); this.yValueAccessor = yValueAccessor; // The symbol function maps series to marker. It uses a special dataset that // varies based on whether smoothing is enabled. this.symbolFunction = symbolFunction; this._defaultXRange = defaultXRange; this._defaultYRange = defaultYRange; this.tooltipColumns = tooltipColumns as any; this.buildChart( xComponentsCreationMethod, yValueAccessor, yScaleType, fillArea, xAxisFormatter ); } private buildChart( xComponentsCreationMethod: () => XComponents, yValueAccessor: Plottable.IAccessor<number>, yScaleType: YScaleType, fillArea: FillArea, xAxisFormatter: (number) => string ) { this.destroy(); const xComponents = xComponentsCreationMethod(); this.xAccessor = xComponents.accessor; this.xScale = xComponents.scale; this.xAxis = xComponents.axis; // Default margin is 15 pixels but we do not need it. Setting it to zero // makes space calculation a bit too tight and hide axis label by mistake. // To workaround the tight tolerance issue, we add 1px of margin. // See https://github.com/tensorflow/tensorboard/issues/5077. (this.xAxis.margin(1) as Plottable.Axes.Numeric).tickLabelPadding(3); if (xAxisFormatter) { this.xAxis.formatter(xAxisFormatter); } this.yScale = LineChart.getYScaleFromType(yScaleType); this.yScale.setValueProviderForDomain(() => this.getValuesForYAxisDomainCompute() ); this.yAxis = new Plottable.Axes.Numeric(this.yScale, 'left'); let yFormatter = vz_chart_helpers.multiscaleFormatter( vz_chart_helpers.Y_AXIS_FORMATTER_PRECISION ); (this.yAxis.margin(0) as Plottable.Axes.Numeric) .tickLabelPadding(5) .formatter(yFormatter); this.yAxis.usesTextWidthApproximation(true); this.fillArea = fillArea; const panZoomLayer = new PanZoomDragLayer(this.xScale, this.yScale, () => this.resetDomain() ); this.tooltipInteraction = this.createTooltipInteraction(panZoomLayer); this.tooltipPointsComponent = new Plottable.Component(); const plot = this.buildPlot(this.xScale, this.yScale, fillArea); this.gridlines = new Plottable.Components.Gridlines( this.xScale, this.yScale ); let xZeroLine = null; if (yScaleType !== YScaleType.LOG) { xZeroLine = new Plottable.Components.GuideLineLayer('horizontal'); xZeroLine.scale(this.yScale).value(0); } let yZeroLine = new Plottable.Components.GuideLineLayer('vertical'); yZeroLine.scale(this.xScale).value(0); this.center = new Plottable.Components.Group([ this.gridlines, xZeroLine, yZeroLine, plot, this.tooltipPointsComponent, panZoomLayer, ]); this.center.addClass('main'); this.outer = new Plottable.Components.Table([ [this.yAxis, this.center], [null, this.xAxis], ]); } private buildPlot(xScale, yScale, fillArea): Plottable.Component { if (fillArea) { this.marginAreaPlot = new Plottable.Plots.Area<number | Date>(); this.marginAreaPlot.x(this.xAccessor, xScale); this.marginAreaPlot.y(fillArea.higherAccessor, yScale); this.marginAreaPlot.y0(fillArea.lowerAccessor); this.marginAreaPlot.attr( 'fill', (d: vz_chart_helpers.Datum, i: number, dataset: Plottable.Dataset) => this.colorScale.scale(dataset.metadata().name) ); this.marginAreaPlot.attr('fill-opacity', 0.3); this.marginAreaPlot.attr('stroke-width', 0); } this.smoothedAccessor = (d: vz_chart_helpers.ScalarDatum) => d.smoothed; let linePlot = new Plottable.Plots.Line<number | Date>(); linePlot.x(this.xAccessor, xScale); linePlot.y(this.yValueAccessor, yScale); linePlot.attr( 'stroke', (d: vz_chart_helpers.Datum, i: number, dataset: Plottable.Dataset) => this.colorScale.scale(dataset.metadata().name) ); this.linePlot = linePlot; this.setupTooltips(linePlot); let smoothLinePlot = new Plottable.Plots.Line<number | Date>(); smoothLinePlot.x(this.xAccessor, xScale); smoothLinePlot.y(this.smoothedAccessor, yScale); smoothLinePlot.attr( 'stroke', (d: vz_chart_helpers.Datum, i: number, dataset: Plottable.Dataset) => this.colorScale.scale(dataset.metadata().name) ); this.smoothLinePlot = smoothLinePlot; if (this.symbolFunction) { const markersScatterPlot = new Plottable.Plots.Scatter< number | Date, number >(); markersScatterPlot.x(this.xAccessor, xScale); markersScatterPlot.y(this.yValueAccessor, yScale); markersScatterPlot.attr( 'fill', (d: vz_chart_helpers.Datum, i: number, dataset: Plottable.Dataset) => this.colorScale.scale(dataset.metadata().name) ); markersScatterPlot.attr('opacity', 1); markersScatterPlot.size(vz_chart_helpers.TOOLTIP_CIRCLE_SIZE * 2); markersScatterPlot.symbol( (d: vz_chart_helpers.Datum, i: number, dataset: Plottable.Dataset) => { return this.symbolFunction(dataset.metadata().name); } ); // Use a special dataset because this scatter plot should use the accesor // that depends on whether smoothing is enabled. this.markersScatterPlot = markersScatterPlot; } // The scatterPlot will display the last point for each dataset. // This way, if there is only one datum for the series, it is still // visible. We hide it when tooltips are active to keep things clean. let scatterPlot = new Plottable.Plots.Scatter<number | Date, number>(); scatterPlot.x(this.xAccessor, xScale); scatterPlot.y(this.yValueAccessor, yScale); scatterPlot.attr('fill', (d: any) => this.colorScale.scale(d.name)); scatterPlot.attr('opacity', 1); scatterPlot.size(vz_chart_helpers.TOOLTIP_CIRCLE_SIZE * 2); scatterPlot.datasets([this.lastPointsDataset]); this.scatterPlot = scatterPlot; let nanDisplay = new Plottable.Plots.Scatter<number | Date, number>(); nanDisplay.x(this.xAccessor, xScale); nanDisplay.y((x) => x.displayY, yScale); nanDisplay.attr('fill', (d: any) => this.colorScale.scale(d.name)); nanDisplay.attr('opacity', 1); nanDisplay.size(vz_chart_helpers.NAN_SYMBOL_SIZE * 2); nanDisplay.datasets([this.nanDataset]); nanDisplay.symbol(Plottable.SymbolFactories.triangle); this.nanDisplay = nanDisplay; const groups = [nanDisplay, scatterPlot, smoothLinePlot, linePlot]; if (this.marginAreaPlot) { groups.push(this.marginAreaPlot); } if (this.markersScatterPlot) { groups.push(this.markersScatterPlot); } return new Plottable.Components.Group(groups); } public ignoreYOutliers(ignoreYOutliers: boolean) { if (ignoreYOutliers !== this._ignoreYOutliers) { this._ignoreYOutliers = ignoreYOutliers; this.updateSpecialDatasets(); this.yScale.ignoreOutlier(ignoreYOutliers); this.resetYDomain(); } } private getValuesForYAxisDomainCompute(): number[] { const accessors = this.getAccessorsForComputingYRange(); let datasetToValues: (d: Plottable.Dataset) => number[][] = (d) => { return accessors.map((accessor) => d.data().map((x) => accessor(x, -1, d)) ); }; return _.flattenDeep(this.datasets.map(datasetToValues)).filter(isFinite); } /** Constructs special datasets. Each special dataset contains exceptional * values from all of the regular datasets, e.g. last points in series, or * NaN values. Those points will have a `name` and `relative` property added * (since usually those are context in the surrounding dataset). */ private updateSpecialDatasets() { const accessor = this.getYAxisAccessor(); let lastPointsData = this.datasets .map((d) => { let datum = null; // filter out NaNs to ensure last point is a clean one let nonNanData = d.data().filter((x) => !isNaN(accessor(x, -1, d))); if (nonNanData.length > 0) { let idx = nonNanData.length - 1; datum = nonNanData[idx]; datum.name = d.metadata().name; datum.relative = vz_chart_helpers.relativeAccessor(datum, -1, d); } return datum; }) .filter((x) => x != null); this.lastPointsDataset.data(lastPointsData); if (this.markersScatterPlot) { this.markersScatterPlot.datasets( this.datasets.map(this.createSampledDatasetForMarkers) ); } // Take a dataset, return an array of NaN data points // the NaN points will have a "displayY" property which is the // y-value of a nearby point that was not NaN (0 if all points are NaN) let datasetToNaNData = (d: Plottable.Dataset) => { let displayY = null; let data = d.data(); let i = 0; while (i < data.length && displayY == null) { if (!isNaN(accessor(data[i], -1, d))) { displayY = accessor(data[i], -1, d); } i++; } if (displayY == null) { displayY = 0; } let nanData = []; for (i = 0; i < data.length; i++) { if (!isNaN(accessor(data[i], -1, d))) { displayY = accessor(data[i], -1, d); } else { data[i].name = d.metadata().name; data[i].displayY = displayY; data[i].relative = vz_chart_helpers.relativeAccessor(data[i], -1, d); nanData.push(data[i]); } } return nanData; }; let nanData = _.flatten(this.datasets.map(datasetToNaNData)); this.nanDataset.data(nanData); } public resetDomain() { this.resetXDomain(); this.resetYDomain(); } private resetXDomain() { let xDomain; if (this._defaultXRange != null) { // Use the range specified by the caller. xDomain = this._defaultXRange; } else { // (Copied from vz_line_chart.DragZoomLayer.unzoom.) const xScale = this.xScale as any; xScale._domainMin = null; xScale._domainMax = null; xDomain = xScale._getExtent(); } this.xScale.domain(xDomain); } private resetYDomain() { if (this._defaultYRange != null) { // Use the range specified by the caller. this.yScale.domain(this._defaultYRange); } else { // TfScale has all the logics for scaling and we manually trigger it with // `autoDomain`. However, this enables the autoDomain mode which updates // the domain on any dataset change and this is not desirably especially // when a run is not finished yet; we don't want the graph to change in // scale while user is inspecting the graph. By setting the `domain` // explicitly, we can turn the feature off. this.yScale.autoDomain(); this.yScale.domain(this.yScale.domain()); } } private getAccessorsForComputingYRange(): Plottable.IAccessor<number>[] { const accessors = [this.getYAxisAccessor()]; if (this.fillArea) { // Make the Y domain take margins into account. accessors.push(this.fillArea.lowerAccessor, this.fillArea.higherAccessor); } return accessors; } private getYAxisAccessor() { return this.smoothingEnabled ? this.smoothedAccessor : this.yValueAccessor; } private createTooltipInteraction( pzdl: PanZoomDragLayer ): Plottable.Interactions.Pointer { const pi = new PointerInteraction(); // Disable interaction while drag zooming. const disableTooltipUpdate = () => { pi.enabled(false); this.hideTooltips(); }; const enableTooltipUpdate = () => pi.enabled(true); pzdl.onPanStart(disableTooltipUpdate); pzdl.onDragZoomStart(disableTooltipUpdate); pzdl.onPanEnd(enableTooltipUpdate); pzdl.onDragZoomEnd(enableTooltipUpdate); // When using wheel, cursor position does not change. Redraw the tooltip // using the last known mouse position. pzdl.onScrollZoom(() => this.updateTooltipContent(this._lastMousePosition)); pi.onPointerMove((p: Plottable.Point) => { this._lastMousePosition = p; this.updateTooltipContent(p); }); pi.onPointerExit(() => this.hideTooltips()); return pi; } private updateTooltipContent(p: Plottable.Point): void { // Line plot must be initialized to draw. if (!this.linePlot) return; window.cancelAnimationFrame(this._tooltipUpdateAnimationFrame); this._tooltipUpdateAnimationFrame = window.requestAnimationFrame(() => { let target: vz_chart_helpers.Point = { x: p.x, y: p.y, datum: null, dataset: null, }; let bbox: SVGRect = (<any>this.gridlines.content().node()).getBBox(); // pts is the closets point to the tooltip for each dataset let pts = this.linePlot .datasets() .map((dataset) => this.findClosestPoint(target, dataset)) .filter(Boolean); let intersectsBBox = Plottable.Utils.DOM.intersectsBBox; // We draw tooltips for points that are NaN, or are currently visible let ptsForTooltips = pts.filter( (p) => intersectsBBox(p.x, p.y, bbox) || isNaN(this.yValueAccessor(p.datum, 0, p.dataset)) ); // Only draw little indicator circles for the non-NaN points let ptsToCircle = ptsForTooltips.filter( (p) => !isNaN(this.yValueAccessor(p.datum, 0, p.dataset)) ); if (pts.length !== 0) { this.scatterPlot.attr('display', 'none'); const ptsSelection: any = this.tooltipPointsComponent .content() .selectAll('.point') .data( ptsToCircle, (p: vz_chart_helpers.Point) => p.dataset.metadata().name ); ptsSelection.enter().append('circle').classed('point', true); ptsSelection .attr('r', vz_chart_helpers.TOOLTIP_CIRCLE_SIZE) .attr('cx', (p) => p.x) .attr('cy', (p) => p.y) .style('stroke', 'none') .attr('fill', (p) => this.colorScale.scale(p.dataset.metadata().name) ); ptsSelection.exit().remove(); this.drawTooltips(ptsForTooltips, target, this.tooltipColumns); } else { this.hideTooltips(); } }); } private hideTooltips(): void { window.cancelAnimationFrame(this._tooltipUpdateAnimationFrame); this.tooltip.hide(); this.scatterPlot.attr('display', 'block'); this.tooltipPointsComponent.content().selectAll('.point').remove(); } private setupTooltips(plot: Plottable.XYPlot<number | Date, number>): void { plot.onDetach(() => { this.tooltipInteraction.detachFrom(plot); this.tooltipInteraction.enabled(false); }); plot.onAnchor(() => { this.tooltipInteraction.attachTo(plot); this.tooltipInteraction.enabled(true); }); } private drawTooltips( points: vz_chart_helpers.Point[], target: vz_chart_helpers.Point, tooltipColumns: TooltipColumn[] ) { if (!points.length) { this.tooltip.hide(); return; } const {colorScale} = this; const swatchCol = { title: '', static: false, evalType: TooltipColumnEvalType.DOM, evaluate(d: vz_chart_helpers.Point) { d3.select(this) .select('span') .style('background-color', () => colorScale.scale(d.dataset.metadata().name) ); return ''; }, enter(d: vz_chart_helpers.Point) { d3.select(this) .append('span') .classed('swatch', true) .style('background-color', () => colorScale.scale(d.dataset.metadata().name) ); }, }; tooltipColumns = [swatchCol, ...tooltipColumns]; // Formatters for value, step, and wall_time let valueFormatter = vz_chart_helpers.multiscaleFormatter( vz_chart_helpers.Y_TOOLTIP_FORMATTER_PRECISION ); const dist = (p: vz_chart_helpers.Point) => Math.pow(p.x - target.x, 2) + Math.pow(p.y - target.y, 2); const closestDist = _.min(points.map(dist)); const valueSortMethod = this.smoothingEnabled ? this.smoothedAccessor : this.yValueAccessor; if (this.tooltipSortingMethod === 'ascending') { points = _.sortBy(points, (d) => valueSortMethod(d.datum, -1, d.dataset)); } else if (this.tooltipSortingMethod === 'descending') { points = _.sortBy(points, (d) => valueSortMethod(d.datum, -1, d.dataset) ).reverse(); } else if (this.tooltipSortingMethod === 'nearest') { points = _.sortBy(points, dist); } else { // The 'default' sorting method maintains the order of names passed to // setVisibleSeries(). However we reverse that order when defining the // datasets. So we must call reverse again to restore the order. points = points.slice(0).reverse(); } const self = this; const table = d3.select(this.tooltip.content()).select('table'); const header = table .select('thead') .selectAll('th') .data(tooltipColumns, (column: TooltipColumn, _, __) => { return column.title; }); header .enter() .append('th') .text((col) => col.title) .nodes(); header.exit().remove(); const rows = table .select('tbody') .selectAll('tr') .data(points, (pt: vz_chart_helpers.Point, _, __) => { return pt.dataset.metadata().name; }); rows .classed('distant', (d) => { // Grey out the point if any of the following are true: // - The cursor is outside of the x-extent of the dataset // - The point's y value is NaN let firstPoint = d.dataset.data()[0]; let lastPoint = _.last(d.dataset.data()); let firstX = this.xScale.scale( this.xAccessor(firstPoint, 0, d.dataset) ); let lastX = this.xScale.scale(this.xAccessor(lastPoint, 0, d.dataset)); let s = this.smoothingEnabled ? d.datum.smoothed : this.yValueAccessor(d.datum, 0, d.dataset); return target.x < firstX || target.x > lastX || isNaN(s); }) .classed('closest', (p) => dist(p) === closestDist) .each(function (point) { self.drawTooltipRow(this, tooltipColumns, point); }) // reorders DOM to match the ordering of the `data`. .order(); rows.exit().remove(); rows .enter() .append('tr') .each(function (point) { self.drawTooltipRow(this, tooltipColumns, point); }) .nodes(); this.tooltip.updateAndPosition(this.targetSVG.node()); } private drawTooltipRow( row: d3.BaseType, tooltipColumns: TooltipColumn[], point: vz_chart_helpers.Point ) { const self = this; const columns = d3.select(row).selectAll('td').data(tooltipColumns); columns.each(function (col: TooltipColumn) { // Skip column value update when the column is static. if (col.static) return; self.drawTooltipColumn.call(self, this, col, point); }); columns.exit().remove(); columns .enter() .append('td') .each(function (col: TooltipColumn | LineChartTooltipColumn) { if ('enter' in col && col.enter) { const customTooltip = col as LineChartTooltipColumn; customTooltip.enter.call(this, point); } self.drawTooltipColumn.call(self, this, col, point); }); } private drawTooltipColumn( column: d3.BaseType, tooltipCol: TooltipColumn | LineChartTooltipColumn, point: vz_chart_helpers.Point ) { const {smoothingEnabled} = this; if ( 'evalType' in tooltipCol && tooltipCol.evalType == TooltipColumnEvalType.DOM ) { tooltipCol.evaluate.call(column, point, {smoothingEnabled}); } else { d3.select(column).text( tooltipCol.evaluate.call(column, point, {smoothingEnabled}) ); } } private findClosestPoint( target: vz_chart_helpers.Point, dataset: Plottable.Dataset ): vz_chart_helpers.Point | null { const xPoints: number[] = dataset .data() .map((d, i) => this.xScale.scale(this.xAccessor(d, i, dataset))); let idx: number = _.sortedIndex(xPoints, target.x); if (xPoints.length == 0) return null; if (idx === xPoints.length) { idx = idx - 1; } else if (idx !== 0) { const prevDist = Math.abs(xPoints[idx - 1] - target.x); const nextDist = Math.abs(xPoints[idx] - target.x); idx = prevDist < nextDist ? idx - 1 : idx; } const datum = dataset.data()[idx]; const y = this.smoothingEnabled ? this.smoothedAccessor(datum, idx, dataset) : this.yValueAccessor(datum, idx, dataset); return { x: xPoints[idx], y: this.yScale.scale(y), datum, dataset, }; } private resmoothDataset(dataset: Plottable.Dataset) { let data = dataset.data(); const smoothingWeight = this.smoothingWeight; // 1st-order IIR low-pass filter to attenuate the higher- // frequency components of the time-series. let last = data.length > 0 ? 0 : NaN; let numAccum = 0; const yValues = data.map((d, i) => this.yValueAccessor(d, i, dataset)); // See #786. const isConstant = yValues.every((v) => v == yValues[0]); data.forEach((d, i) => { const nextVal = yValues[i]; if (isConstant || !Number.isFinite(nextVal)) { d.smoothed = nextVal; } else { last = last * smoothingWeight + (1 - smoothingWeight) * nextVal; numAccum++; // The uncorrected moving average is biased towards the initial value. // For example, if initialized with `0`, with smoothingWeight `s`, where // every data point is `c`, after `t` steps the moving average is // ``` // EMA = 0*s^(t) + c*(1 - s)*s^(t-1) + c*(1 - s)*s^(t-2) + ... // = c*(1 - s^t) // ``` // If initialized with `0`, dividing by (1 - s^t) is enough to debias // the moving average. We count the number of finite data points and // divide appropriately before storing the data. let debiasWeight = 1; if (smoothingWeight !== 1) { debiasWeight = 1 - Math.pow(smoothingWeight, numAccum); } d.smoothed = last / debiasWeight; } }); } private getDataset(name: string) { if (this.name2datasets[name] === undefined) { this.name2datasets[name] = new Plottable.Dataset([], { name, meta: null, }); } return this.name2datasets[name]; } static getYScaleFromType(yScaleType: string): ITfScale { if (yScaleType === YScaleType.LOG) { return new LogScale(); } else if (yScaleType === YScaleType.LINEAR) { return new LinearScale(); } else { throw new Error('Unrecognized yScale type ' + yScaleType); } } /** * Stages update of visible series on the chart. * * Please call `commitChanges` for the changes to be reflected on the chart * after making all the changes. */ public setVisibleSeries(names: string[]) { this.disableChanges(); names = names.sort(); names.reverse(); // draw first series on top this.seriesNames = names; } private dirtyDatasets = new Set<string>(); private disableChanges() { if (!this.dirtyDatasets.size) { // Prevent plots from reacting to the dataset changes. this.linePlot.datasets([]); if (this.smoothLinePlot) { this.smoothLinePlot.datasets([]); } if (this.marginAreaPlot) { this.marginAreaPlot.datasets([]); } } } public commitChanges() { this.datasets = this.seriesNames.map((r) => this.getDataset(r)); [...this.dirtyDatasets].forEach((d) => { if (this.smoothingEnabled) { this.resmoothDataset(this.getDataset(d)); } }); this.updateSpecialDatasets(); this.linePlot.datasets(this.datasets); if (this.smoothingEnabled) { this.smoothLinePlot.datasets(this.datasets); } if (this.marginAreaPlot) { this.marginAreaPlot.datasets(this.datasets); } this.measureBBoxAndMaybeInvalidateLayoutInRaf(); this.dirtyDatasets.clear(); } /** * Samples a dataset so that it contains no more than _MAX_MARKERS number of * data points. This function returns the original dataset if it does not * exceed that many points. */ public createSampledDatasetForMarkers( original: Plottable.Dataset ): Plottable.Dataset { const originalData = original.data(); if (originalData.length <= _MAX_MARKERS) { // This dataset is small enough. Do not sample. return original; } // Downsample the data. Otherwise, too many markers clutter the chart. const skipLength = Math.ceil(originalData.length / _MAX_MARKERS); const data = new Array(Math.floor(originalData.length / skipLength)); for (let i = 0, j = 0; i < data.length; i++, j += skipLength) { data[i] = originalData[j]; } return new Plottable.Dataset(data, original.metadata()); } /** * Stages a data change of a series on the chart. * * Please call `commitChanges` for the changes to be reflected on the chart * after making all the changes. */ public setSeriesData(name: string, data: vz_chart_helpers.ScalarDatum[]) { this.disableChanges(); this.getDataset(name).data(data); this.dirtyDatasets.add(name); } /** * Sets a metadata change of a series on the chart. * * Please call `commitChanges` for the changes to be reflected on the chart * after making all the changes. */ public setSeriesMetadata(name: string, meta: any) { this.disableChanges(); this.getDataset(name).metadata({ ...this.getDataset(name).metadata(), meta, }); this.dirtyDatasets.add(name); } public smoothingUpdate(weight: number) { this.smoothingWeight = weight; this.datasets.forEach((d) => this.resmoothDataset(d)); if (!this.smoothingEnabled) { this.linePlot.addClass('ghost'); this.scatterPlot.y(this.smoothedAccessor, this.yScale); this.smoothingEnabled = true; this.smoothLinePlot.datasets(this.datasets); } if (this.markersScatterPlot) { // Use the correct accessor for marker positioning. this.markersScatterPlot.y(this.getYAxisAccessor(), this.yScale); } this.updateSpecialDatasets(); } public smoothingDisable() { if (this.smoothingEnabled) { this.linePlot.removeClass('ghost'); this.scatterPlot.y(this.yValueAccessor, this.yScale); this.smoothLinePlot.datasets([]); this.smoothingEnabled = false; this.updateSpecialDatasets(); } if (this.markersScatterPlot) { // Use the correct accessor (which depends on whether smoothing is // enabled) for marker positioning. this.markersScatterPlot.y(this.getYAxisAccessor(), this.yScale); } } public setColorScale(colorScale: Plottable.Scales.Color) { this.colorScale = colorScale; } public setTooltipColumns(tooltipColumns: TooltipColumn[]) { this.tooltipColumns = tooltipColumns as any; } public setTooltipSortingMethod(method: string) { this.tooltipSortingMethod = method; } public renderTo(targetSVG: d3.Selection<any, any, any, any>) { this.targetSVG = targetSVG; this.outer.renderTo(targetSVG); if (this._defaultXRange != null) { // A higher-level component provided a default range for the X axis. // Start with that range. this.resetXDomain(); } if (this._defaultYRange != null) { // A higher-level component provided a default range for the Y axis. // Start with that range. this.resetYDomain(); } this.measureBBoxAndMaybeInvalidateLayoutInRaf(); } public redraw() { window.cancelAnimationFrame(this._redrawRaf); this._redrawRaf = window.requestAnimationFrame(() => { this.measureBBoxAndMaybeInvalidateLayout(); this.outer.redraw(); }); } private measureBBoxAndMaybeInvalidateLayoutInRaf() { window.cancelAnimationFrame(this._invalidateLayoutRaf); this._invalidateLayoutRaf = window.requestAnimationFrame(() => { this.measureBBoxAndMaybeInvalidateLayout(); }); } /** * Measures bounding box of the anchor node and determines whether the layout * needs to be re-done with measurement cache invalidated. Plottable improved * performance of rendering by caching expensive DOM measurement but this * cache can be poisoned in case the anchor node is in a wrong state -- namely * `display: none` where all dimensions are 0. */ private measureBBoxAndMaybeInvalidateLayout() { if (this._lastDrawBBox) { const {width: prevWidth} = this._lastDrawBBox; const {width} = this.targetSVG.node().getBoundingClientRect(); if (prevWidth == 0 && prevWidth < width) this.outer.invalidateCache(); } this._lastDrawBBox = this.targetSVG.node().getBoundingClientRect(); } public destroy() { // Destroying outer destroys all subcomponents recursively. window.cancelAnimationFrame(this._redrawRaf); window.cancelAnimationFrame(this._invalidateLayoutRaf); if (this.outer) this.outer.destroy(); } public onAnchor(fn: () => void) { if (this.outer) this.outer.onAnchor(fn); } /** * Returns whether the extent of rendered data values fits the current * chart viewport domain (includes smoothing and outlier detection). * * This is true when there is no data, and false when the domain has been * transformed from the extent via transformations (pan, zoom). */ public isDataFitToDomain(): boolean { return ( isDataFitToDomain(this.xAxis.getScale()) && isDataFitToDomain(this.yAxis.getScale()) ); function isDataFitToDomain(scale) { /** * Domain represents the currently displayed region, possibly a zoomed * in or zoomed out view of the data. * * Extent represents the extent of the data, the range of all provided * datum values. */ const domain = scale.getTransformationDomain(); const extent = scale.getTransformationExtent(); return extent[0] === domain[0] && extent[1] === domain[1]; } } }
the_stack
import { Server, Client, NodeClientOptions, ServerSocketStatus, ClientSocketStatus } from '../dist/index'; import * as test from 'tape'; import { create } from '../dist/lib/Util/Header'; import { get, createServer } from 'http'; import { serialize } from 'binarytf'; import { URL } from 'url'; import { readFileSync } from 'fs'; let port = 8000; test('Basic Server', { timeout: 5000 }, async t => { t.plan(5); const nodeServer = new Server('Server'); try { await nodeServer.listen(++port); } catch (error) { t.error(error, 'Server should not crash.'); } // Connected t.equal(nodeServer.sockets.size, 0, 'The server should not have a connected client.'); t.equal(nodeServer.name, 'Server', 'The server should be named after the node.'); try { await nodeServer.listen(++port); t.fail('This call should definitely crash.'); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Listen method has been called more than once without closing.', 'The error message should match.'); } // Disconnected t.true(await nodeServer.close(), 'The disconnection should be successful.'); }); test('Basic Socket', { timeout: 5000 }, async t => { t.plan(16); const nodeServer = new Server('Server'); const nodeSocket = new Client('Socket'); // Open server try { await nodeServer.listen(++port); } catch (error) { t.error(error, 'Server should not crash.'); } try { await nodeSocket.connectTo(port); t.equal(nodeSocket.servers.size, 1); const myServer = nodeSocket.servers.get('Server')!; t.notEqual(myServer, undefined, 'The node should exist.'); t.notEqual(myServer.socket, null, 'The socket should not be null.'); t.equal(myServer.name, 'Server', 'The name of the node must be the name of the server.'); t.equal(myServer.status, ClientSocketStatus.Ready, 'The socket should have a status of ready.'); t.equal(nodeSocket.get('Server'), myServer, 'Node#get should return the same instance.'); t.equal(nodeSocket.get(myServer), myServer, 'When passing a NodeSocket, Node#get should return it.'); await new Promise(resolve => { nodeServer.once('connect', resolve); }); const mySocket = nodeServer.sockets.get('Socket')!; t.notEqual(mySocket, undefined, 'The node should exist.'); t.notEqual(mySocket.socket, null, 'The socket should not be null.'); t.equal(mySocket.name, 'Socket', 'The name of the node must be the name of the socket that connected to this server.'); t.equal(mySocket.status, ServerSocketStatus.Connected, 'The socket should have a status of ready.'); t.equal(nodeServer.get('Socket'), mySocket, 'Node#get should return the same instance.'); t.equal(nodeServer.get(mySocket), mySocket, 'When passing a NodeSocket, Node#get should return it.'); } catch (error) { t.error(error, 'Connection should not error.'); } t.equal(nodeServer.get('Unknown'), null, 'Node#get should return null on unknown nodes.'); t.equal(nodeSocket.get('Unknown'), null, 'Node#get should return null on unknown nodes.'); try { await nodeServer.close(); t.true(nodeSocket.disconnectFrom('Server'), 'Successful disconnections should return true.'); } catch (error) { t.error(error, 'Disconnection should not error.'); } }); test('Socket Unknown Server Disconnection (Invalid)', { timeout: 5000 }, async t => { t.plan(1); const nodeSocket = new Client('Socket'); try { nodeSocket.disconnectFrom('Unknown'); } catch (error) { t.equal(error.message, 'The socket Unknown is not connected to this one.', 'Disconnecting from unconnected sockets should always throw an error.'); } }); test('Socket Events', { timeout: 5000 }, async t => { t.plan(11); const nodeServer = new Server('Server'); const nodeSocket = new Client('Socket', { maximumRetries: 0 }); await nodeServer.listen(++port); // socket.connect and socket.ready are called when connecting nodeSocket.on('connect', client => { t.equal(client.name, null, 'Connect is done before the identify step, it is not available until ready.'); t.equal(client.status, ClientSocketStatus.Connected, 'When this event fires, the status should be "Connected".'); t.equal(client.queue.size, 0, 'The queue must be empty during connection.'); t.notEqual(client.socket, null, 'The socket must not be null during connection.'); }); nodeSocket.on('ready', client => { t.equal(client.name, 'Server', 'Ready is emitted after the identify step, the name should be available.'); t.equal(client.status, ClientSocketStatus.Ready, 'When this event fires, the status should be "Ready".'); t.equal(client.queue.size, 0, 'The queue must be empty after connection.'); t.notEqual(client.socket, null, 'The socket must not be null after connection.'); }); await nodeSocket.connectTo(port); await new Promise(resolve => { nodeServer.once('connect', resolve); }); // Test a server outage nodeSocket.on('disconnect', client => { t.equal(client.name, 'Server', 'The name should always be available, even after being disconnected.'); t.equal(client.status, ClientSocketStatus.Disconnected, 'When this event fires, the status should be "Disconnected".'); t.equal(client.queue.size, 0, 'The queue must be empty during a disconnection.'); }); await nodeServer.close(); }); test('Client Events', { timeout: 5000 }, async t => { t.plan(6); const nodeServer = new Server('Server'); const nodeSocket = new Client('Socket'); await nodeServer.listen(++port); // client.connect is called when connecting nodeServer.on('connect', client => { t.equal(client.name, 'Socket', 'Connect is done after the identify step, the name should be available.'); t.equal(client.status, ServerSocketStatus.Connected, 'When this event fires, the status should be "Connected".'); t.equal(client.queue.size, 0, 'The queue must be empty during connection.'); }); // Connect the socket to the server await nodeSocket.connectTo(port); nodeServer.on('disconnect', async client => { t.equal(client.name, 'Socket', 'The name should always be available, even after being disconnected.'); t.equal(client.status, ServerSocketStatus.Disconnected, 'When this event fires, the status should be "Disconnected".'); t.equal(client.queue.size, 0, 'The queue must be empty during a disconnection.'); await nodeServer.close(); }); nodeSocket.disconnectFrom('Server'); }); test('Server Events', { timeout: 5000 }, async t => { t.plan(4); const nodeServer = new Server('Server'); nodeServer.on('open', () => { t.equal(nodeServer.sockets.size, 0, 'The amount of clients at start-up should be 0.'); t.equal(nodeServer.name, 'Server', 'The name of the server should be the same as the Node itself.'); }); await nodeServer.listen(++port); nodeServer.on('close', () => { t.equal(nodeServer.sockets.size, 0, 'The amount of clients at start-up should be 0.'); t.equal(nodeServer.name, 'Server', 'The name of the server should be the same as the Node itself.'); }); await nodeServer.close(); }); test('Socket Double Disconnection', { timeout: 5000 }, async t => { t.plan(2); const [nodeServer, nodeSocket] = await setup(t, ++port); const server = nodeSocket.get('Server')!; try { t.true(server.disconnect(), 'Successful disconnections should return true.'); t.false(server.disconnect(), 'A repeated disconnection should return false.'); } catch (error) { t.error(error, 'Disconnections from NodeSocket should never throw an error.'); } await nodeServer.close(); }); test('Server Double Disconnection', { timeout: 5000 }, async t => { t.plan(2); const [nodeServer, nodeSocket] = await setup(t, ++port); const server = nodeServer; try { t.true(await server.close(), 'Successful disconnections should return true.'); t.false(await server.close(), 'A repeated disconnection should return false.'); } catch (error) { t.error(error, 'Disconnections from NodeSocket should never throw an error.'); } try { nodeSocket.disconnectFrom('Server'); } catch (error) { t.error(error, 'Disconnection should not error.'); } }); test('Socket Connection Retries', { timeout: 7500 }, async t => { t.plan(4); const [nodeServer, nodeSocket] = await setup(t, ++port, { maximumRetries: 3, retryTime: 0 }); await nodeServer.close(); let attempts = nodeSocket.maximumRetries; nodeSocket.on('connecting', () => { t.true(--attempts >= 0, 'This should reconnect exactly 3 times.'); }); nodeSocket.on('disconnect', () => { t.pass('The client successfully disconnected.'); }); }); test('Socket Connection No Retries', { timeout: 5000 }, async t => { t.plan(1); const [nodeServer, nodeSocket] = await setup(t, ++port, { maximumRetries: 0 }); await nodeServer.close(); nodeSocket.on('connecting', () => { t.fail('The socket should not try to connect.'); }); nodeSocket.on('disconnect', () => { t.pass('The client successfully disconnected.'); }); }); test('Socket Connection Retries (Successful Reconnect)', { timeout: 7500 }, async t => { t.plan(4); const [nodeServer, nodeSocket] = await setup(t, ++port, { maximumRetries: 3, retryTime: 200 }); await nodeServer.close(); nodeSocket.once('connecting', () => { t.pass('Reconnecting event fired.'); next(); }); async function next() { nodeSocket .once('connect', () => t.pass('Socket fired connect')) .once('ready', () => t.pass('Socket fired Ready')); await nodeServer.listen(port); await new Promise(resolve => { nodeServer.once('connect', resolve); }); t.pass('Successfully reconnected the server.'); await nodeServer.close(); nodeSocket.disconnectFrom('Server'); } }); test('Socket Connection Retries (Successful Reconnect | Different Name)', { timeout: 7500 }, async t => { t.plan(8); const [nodeServerFirst, nodeSocket] = await setup(t, ++port, { maximumRetries: 3, retryTime: 200 }); const socketServer = nodeSocket.get('Server')!; t.equal(socketServer.name, 'Server', 'The Server should be "Server".'); // Disconnect and set up a second server with a different name await nodeServerFirst.close(); const nodeServerSecond = new Server('NewServer'); nodeSocket.once('connecting', async () => { t.pass('Reconnecting event fired.'); nodeSocket .once('connect', () => t.pass('Socket fired connect')) .once('ready', () => t.pass('Socket fired Ready')); await nodeServerSecond.listen(port); await new Promise(resolve => { nodeServerSecond.once('connect', resolve); }); t.pass('Successfully reconnected the server.'); t.equal(nodeSocket.get('Server'), null, 'Since the name of the server has changed, the key "Server" should be null.'); t.equal(nodeSocket.get('NewServer'), socketServer, 'The socket should be available under the key "NewServer".'); t.equal(socketServer.name, 'NewServer', 'The name for the socket should be changed to "NewServer".'); await nodeServerSecond.close(); nodeSocket.disconnectFrom('NewServer'); }); }); test('Socket Connection Retries (Abrupt Close)', { timeout: 7500 }, async t => { t.plan(3); const [nodeServer, nodeSocket] = await setup(t, ++port, { maximumRetries: -1, retryTime: 200 }); await nodeServer.close(); let firedConnecting = false; nodeSocket.on('connecting', () => { t.false(firedConnecting, 'This should fire only once.'); firedConnecting = true; t.true(nodeSocket.disconnectFrom('Server'), 'Disconnection should be successful.'); }); let firedDestroy = false; nodeSocket.on('disconnect', () => { t.false(firedDestroy, 'The socket has been disconnected.'); firedDestroy = true; }); }); test('Server Connection Close', { timeout: 5000 }, async t => { t.plan(1); const [nodeServer, nodeSocket] = await setup(t, ++port, undefined); nodeServer.on('disconnect', async socket => { t.equal(socket.name, 'Socket', 'The name of the disconnected socket should be "Socket".'); await nodeServer.close(); }); nodeSocket.disconnectFrom('Server'); }); test('HTTP Socket', { timeout: 5000 }, async t => { t.plan(1); const nodeServer = new Server('Server'); await nodeServer.listen(++port); try { await new Promise((resolve, reject) => { get(new URL(`http://localhost:${port}`), resolve) .on('close', resolve) .on('error', reject); }); t.fail('This should not be called.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); } await nodeServer.close(); }); test('HTTP Server', { timeout: 5000 }, async t => { t.plan(5); const nodeSocket = new Client('Socket', { handshakeTimeout: 250 }); const server = createServer(() => { t.fail('This should not be called - in Veza, the server sends the message, and the socket replies.'); }); server .on('connection', () => t.pass('A connection should be able to be made.')) .on('close', () => t.pass('A connection should be closed.')); await new Promise(resolve => server.listen(++port, resolve)); try { await nodeSocket.connectTo(port); t.fail('The connection should not be successful.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); t.equal(error.message, 'Connection Timed Out.', 'Servers like HTTP ones do not send a message upon connection, so a server that does not send anything is expected to time out.'); } server.close(error => { t.equal(error, undefined, 'There should not be an error with closing the server.'); }); }); test('HTTP Server (Incorrect Handshake)', { timeout: 5000 }, async t => { t.plan(5); const nodeSocket = new Client('Socket', { handshakeTimeout: -1 }); const server = createServer(() => { t.fail('This should not be called - in Veza, the server sends the message, and the socket replies.'); }); server .on('close', () => t.pass('A connection should be closed.')) .on('connection', socket => { t.pass('A connection should be able to be made.'); socket.write(Buffer.from('Hello World!')); }); await new Promise(resolve => server.listen(++port, resolve)); try { await nodeSocket.connectTo(port); t.fail('The connection should not be successful.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); t.equal(error.message, 'Unexpected response from the server.', 'The message sent by the HTTP server is not binaryTF, therefore this should fail.'); } server.close(error => { t.equal(error, undefined, 'There should not be an error with closing the server.'); }); }); test('HTTP Server (Malicious Forged Handshake)', { timeout: 5000 }, async t => { t.plan(5); const nodeSocket = new Client('Socket', { handshakeTimeout: -1 }); const server = createServer(() => { t.fail('This should not be called - in Veza, the server sends the message, and the socket replies.'); }); server .on('close', () => t.pass('A connection should be closed.')) .on('connection', socket => { t.pass('A connection should be able to be made.'); const serialized = serialize(420); const message = new Uint8Array(11 + serialized.byteLength); message[6] = 1; message.set(serialized, 11); socket.write(message); }); await new Promise(resolve => server.listen(++port, resolve)); try { await nodeSocket.connectTo(port); t.fail('The connection should not be successful.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); t.equal(error.message, 'Unexpected response from the server.', 'The message sent by the HTTP server is not binaryTF, therefore this should fail.'); } server.close(error => { t.equal(error, undefined, 'There should not be an error with closing the server.'); }); }); test('ClientSocket Socket Retrieval', { timeout: 5000 }, async t => { t.plan(6); const [nodeServer, nodeSocket] = await setup(t, ++port); const server = nodeSocket.get('Server')!; t.equal(nodeSocket.get('Server'), server, 'The socket is called "Server", and got found.'); t.equal(nodeSocket.get(server), server, 'Retrieving the NodeServerClient instance itself should return it.'); t.true(nodeSocket.has('Server'), 'The socket "Server" is connected to this server.'); t.false(nodeSocket.has('Foo'), 'The socket "Foo" is not connected to this server.'); try { // TypeScript ignoring since this is an assertion for JavaScript users // @ts-ignore nodeSocket.get(0); t.fail('This should not run, as the previous statement throws'); } catch (error) { t.true(error instanceof TypeError, 'The error should be an instance of TypeError.'); t.equal(error.message, 'Expected a string or a ClientSocket instance.', 'An invalid NodeServer#get throws a TypeError explaining what was wrong.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('NodeServer Socket Retrieval', { timeout: 5000 }, async t => { t.plan(6); const [nodeServer, nodeSocket] = await setup(t, ++port); const socket = nodeServer.get('Socket')!; t.equal(nodeServer.get('Socket'), socket, 'The socket is called "Socket", and got found.'); t.equal(nodeServer.get(socket), socket, 'Retrieving the NodeServerClient instance itself should return it.'); t.true(nodeServer.has('Socket'), 'The socket "Socket" is connected to this server.'); t.false(nodeServer.has('Foo'), 'The socket "Foo" is not connected to this server.'); try { // TypeScript ignoring since this is an assertion for JavaScript users // @ts-ignore nodeServer.get(0); t.fail('This should not run, as the previous statement throws'); } catch (error) { t.true(error instanceof TypeError, 'The error should be an instance of TypeError.'); t.equal(error.message, 'Expected a string or a ServerClient instance.', 'An invalid NodeServer#get throws a TypeError explaining what was wrong.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Socket Message', { timeout: 5000 }, async t => { t.plan(14); const [nodeServer, nodeSocket] = await setup(t, ++port); // Test receptive (default) message delivery { nodeServer.once('message', message => { t.true(message.receptive, 'The message was sent as receptive.'); t.equal(message.data, 'Hello'); message.reply('World'); const json = message.toJSON(); t.equal(json.id, message.id, 'The values from NodeMessage#toJSON and the ones from NodeMessage must be the same.'); t.equal(json.data, message.data, 'The values from NodeMessage#toJSON and the ones from NodeMessage must be the same.'); t.equal(json.receptive, message.receptive, 'The values from NodeMessage#toJSON and the ones from NodeMessage must be the same.'); t.equal(message.toString(), `NodeMessage<${message.id}>`); }); const response = await nodeSocket.sendTo('Server', 'Hello') as string; t.equal(response, 'World'); } // Test non-receptive message delivery { nodeServer.once('message', message => { t.false(message.receptive, 'The message was sent as not receptive.'); t.equal(message.data, 'Foo'); message.reply('Bar'); // Finish the tests finish(); }); const response = await nodeSocket.sendTo('Server', 'Foo', { receptive: false }) as undefined; t.equal(response, undefined); } async function finish() { const server = nodeSocket.get('Server')!; const socket = nodeServer.get('Socket')!; await nodeServer.close(); nodeSocket.disconnectFrom('Server'); try { await server.send('Foo', { receptive: false }); t.fail('Messages to a disconnected socket should fail.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); t.equal(error.message, 'Cannot send a message to a missing socket.'); } try { await socket.send('Foo', { receptive: false }); t.fail('Messages to a disconnected socket should fail.'); } catch (error) { t.true(error instanceof Error, 'The error thrown should be an instance of Error.'); t.equal(error.message, 'Cannot send a message to a missing socket.'); } } }); test('Socket Unknown Server Message Sending (Invalid)', { timeout: 5000 }, async t => { t.plan(1); const nodeSocket = new Client('Socket'); try { await nodeSocket.sendTo('Unknown', 'Foo'); } catch (error) { t.equal(error.message, 'Failed to send to the socket: It is not connected to this client.', 'Sending messages to unconnected sockets should always throw an error.'); } }); test('Server Messages', { timeout: 5000 }, async t => { t.plan(5); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeSocket.on('message', message => { t.equal(message.receptive, true, 'The message was sent as receptive.'); t.equal(message.data, 'Foo', 'The message should match with the value.'); message.reply('Bar'); }); try { const response = await nodeServer.sendTo('Socket', 'Foo', { timeout: 250 }); t.equal(response, 'Bar'); } catch (error) { t.error(error, 'This should not fail.'); } try { await nodeServer.sendTo('Unknown', 'Hello'); t.fail('This should not run, as the previous statement throws'); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Failed to send to the socket: It is not connected to this server.', 'Trying to send a message to an unknown socket sends this message.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Server Message (Large Buffer)', { timeout: 5000 }, async t => { t.plan(5); const [nodeServer, nodeSocket] = await setup(t, ++port); const buffer = readFileSync('./static/logo.png'); nodeSocket.on('message', message => { t.equal(message.receptive, true, 'The message was sent as receptive.'); t.same(message.data, buffer, 'The message should match with the value.'); message.reply(message.data.byteLength); }); try { const response = await nodeServer.sendTo('Socket', buffer, { timeout: 250 }); t.equal(response, buffer.byteLength); } catch (error) { t.error(error, 'This should not fail.'); } try { await nodeServer.sendTo('Unknown', 'Hello'); t.fail('This should not run, as the previous statement throws'); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Failed to send to the socket: It is not connected to this server.', 'Trying to send a message to an unknown socket sends this message.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Server Message (Multiple Large Buffer)', { timeout: 5000 }, async t => { t.plan(8); const [nodeServer, nodeSocket] = await setup(t, ++port); const bufferLogo = readFileSync('./static/logo.png'); const bufferTest = readFileSync('./test/test.png'); let receivedFirst = false; nodeSocket.on('message', message => { t.equal(message.receptive, true, 'The message was sent as receptive.'); if (receivedFirst) { t.same(message.data, bufferTest, 'The message should match with the value.'); } else { t.same(message.data, bufferLogo, 'The message should match with the value.'); receivedFirst = true; } message.reply(message.data.byteLength); }); try { const [responseLogo, responseTest] = await Promise.all([ nodeServer.sendTo('Socket', bufferLogo, { timeout: 250 }), nodeServer.sendTo('Socket', bufferTest, { timeout: 250 }) ]); t.equal(responseLogo, bufferLogo.byteLength); t.equal(responseTest, bufferTest.byteLength); } catch (error) { t.error(error, 'This should not fail.'); } try { await nodeServer.sendTo('Unknown', 'Hello'); t.fail('This should not run, as the previous statement throws'); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Failed to send to the socket: It is not connected to this server.', 'Trying to send a message to an unknown socket sends this message.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Server Message (Spam)', { timeout: 10000 }, async t => { t.plan(1); const [nodeServer, nodeSocket] = await setup(t, ++port); const AMOUNT_OF_MESSAGES = 10000; let pendingMessages = AMOUNT_OF_MESSAGES; nodeSocket.on('message', message => { --pendingMessages; message.reply(message.data); if (pendingMessages < 0) t.fail('Received too many messages'); }); try { const numbers = new Array(AMOUNT_OF_MESSAGES); for (let i = 0; i < numbers.length; ++i) numbers[i] = i; const socket = nodeServer.get('Socket')!; await Promise.all(numbers.map(n => socket.send(n, { timeout: 10000 }).then(r => { if (n !== r) t.fail(`Mismatching response. Expected ${n} but received ${r}`); }))); } catch (error) { t.error(error, 'This should not fail.'); } t.equal(pendingMessages, 0, 'It should have decreased its pending messages to 0.'); await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Socket Faulty Message', { timeout: 5000 }, async t => { t.plan(3); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeServer.on('error', async (error, socket) => { t.equal(socket!.name, 'Socket'); t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Failed to parse message: Unknown type received: 255 [UnknownType]', 'Faulty messages after having connected fire the error event, but does not disconnect.'); await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); // Send faulty message nodeSocket.get('Server')!.socket!.write(create(false, new Uint8Array([0xFF, 0xFF]))); }); test('Server Faulty Message', { timeout: 5000 }, async t => { t.plan(3); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeSocket.on('error', async (error, socket) => { t.equal(socket!.name, 'Server'); t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Failed to parse message: Unknown type received: 255 [UnknownType]', 'Faulty messages after having connected fire the error event, but does not disconnect.'); await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); // Send faulty message nodeServer.get('Socket')!.socket!.write(create(false, new Uint8Array([0xFF, 0xFF]))); }); test('Socket Concurrent Messages', { timeout: 5000 }, async t => { t.plan(6); const [nodeServer, nodeSocket] = await setup(t, ++port); const messages = ['Hello', 'High']; const replies = ['World', 'Five!']; nodeServer.on('message', message => { t.equal(message.receptive, true, 'The message was sent as receptive.'); t.equal(message.data, messages.shift(), 'The message should match with the value.'); message.reply(replies.shift()); }); const [first, second] = await Promise.all([ nodeSocket.sendTo('Server', messages[0]), nodeSocket.sendTo('Server', messages[1]) ]); t.equal(first, 'World'); t.equal(second, 'Five!'); await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Message Broadcast', { timeout: 5000 }, async t => { t.plan(9); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeSocket.once('message', message => { t.equal(message.data, 'Foo', 'Message is exactly the one sent'); t.equal(message.receptive, true, 'Message keeps its receptive value'); message.reply('Bar'); }); try { const response = await nodeServer.broadcast('Foo'); t.true(Array.isArray(response), 'The response for a broadcast must always be an array.'); t.equal(response.length, 1, 'There is only one connected socket, therefore it should be an array with one value.'); t.equal(response[0], 'Bar', 'The socket responded with "Bar", therefore the first entry should be the same.'); } catch (error) { t.error(error, 'Message broadcast failed'); } try { const response = await nodeServer.broadcast('Foo', { filter: /NothingMatches/ }); t.true(Array.isArray(response), 'The response for a broadcast must always be an array.'); t.equal(response.length, 0, 'There is only one connected socket, but the filter does not match any one.'); } catch (error) { t.error(error, 'Message broadcast failed'); } try { // TypeScript ignoring since this is an assertion for JavaScript users // @ts-ignore await nodeServer.broadcast('Foo', { filter: 'HelloWorld' }); } catch (error) { t.true(error instanceof TypeError, 'The error should be an instance of TypeError.'); t.equal(error.message, 'filter must be a RegExp instance.', 'An invalid Node#broadcast filter option throws a TypeError explaining what was wrong.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Message Broadcast (From Server)', { timeout: 5000 }, async t => { t.plan(9); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeSocket.once('message', message => { t.equal(message.data, 'Foo', 'Message is exactly the one sent'); t.equal(message.receptive, true, 'Message keeps its receptive value'); message.reply('Bar'); }); try { const response = await nodeServer.broadcast('Foo'); t.true(Array.isArray(response), 'The response for a broadcast must always be an array.'); t.equal(response.length, 1, 'There is only one connected socket, therefore it should be an array with one value.'); t.equal(response[0], 'Bar', 'The socket responded with "Bar", therefore the first entry should be the same.'); } catch (error) { t.error(error, 'Message broadcast failed'); } try { const response = await nodeServer.broadcast('Foo', { filter: /NothingMatches/ }); t.true(Array.isArray(response), 'The response for a broadcast must always be an array.'); t.equal(response.length, 0, 'There is only one connected socket, but the filter does not match any one.'); } catch (error) { t.error(error, 'Message broadcast failed'); } try { // TypeScript ignoring since this is an assertion for JavaScript users // @ts-ignore await nodeServer.broadcast('Foo', { filter: 'HelloWorld' }); } catch (error) { t.true(error instanceof TypeError, 'The error should be an instance of TypeError.'); t.equal(error.message, 'filter must be a RegExp instance.', 'An invalid Node#broadcast filter option throws a TypeError explaining what was wrong.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Message Timeout', { timeout: 5000 }, async t => { t.plan(4); const [nodeServer, nodeSocket] = await setup(t, ++port); try { await nodeSocket.sendTo('Server', 'Foo', { timeout: 250 }); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Timed out.', 'The server does not reply this one on purpose.'); } nodeServer.on('message', message => { message.reply('Bar'); }); try { const response = await nodeSocket.sendTo('Server', 'Foo', { timeout: 250 }); t.equal(response, 'Bar', 'The server replied with "Bar", so this should be "Bar".'); } catch (error) { t.error(error, 'The socket should not error.'); } try { // Timeout -1 means no timeout const response = await nodeSocket.sendTo('Server', 'Foo', { timeout: -1 }); t.equal(response, 'Bar', 'The server replied with "Bar", so this should be "Bar".'); } catch (error) { t.error(error, 'The socket should not error.'); } await nodeServer.close(); nodeSocket.disconnectFrom('Server'); }); test('Abrupt Disconnection (Disconnected Without Clearing Messages)', { timeout: 5000 }, async t => { t.plan(3); const [nodeServer, nodeSocket] = await setup(t, ++port); nodeServer.on('message', message => { message.reply('Bar'); }); try { const promise = nodeSocket.sendTo('Server', 'Foo'); t.true(nodeSocket.disconnectFrom('Server'), 'Successful disconnections should return true.'); await promise; t.fail('The message should fail due to the server connection being cut.'); } catch (error) { t.true(error instanceof Error, 'The error should be an instance of Error.'); t.equal(error.message, 'Socket has been disconnected.', 'The error message is thrown from NodeSocket.'); } await nodeServer.close(); }); test('Duplicated Socket', { timeout: 5000 }, async t => { t.plan(1); const [nodeServer, nodeSocketFirst] = await setup(t, ++port, undefined); const nodeSocketSecond = new Client('Socket'); nodeSocketFirst.once('disconnect', async () => { t.pass('The socket has been disconnected.'); await nodeServer.close(); nodeSocketSecond.disconnectFrom('Server'); }); await nodeSocketSecond.connectTo(port); }); async function setup(t: test.Test, port: number, socketNodeOptions?: NodeClientOptions): Promise<[Server, Client]> { const nodeServer = new Server('Server'); const nodeSocket = new Client('Socket', socketNodeOptions); try { // Open server await nodeServer.listen(port); await nodeSocket.connectTo(port); await new Promise(resolve => { nodeServer.once('connect', resolve); }); } catch { await nodeServer.close(); nodeSocket.disconnectFrom('Server'); t.end('Unable to test: TCP Connection Failed.'); } return [nodeServer, nodeSocket]; }
the_stack
import { addRule, removeRule, rule, updateRule, } from '@/services/ant-design-pro/api'; import { PlusOutlined } from '@ant-design/icons'; import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions'; import ProDescriptions from '@ant-design/pro-descriptions'; import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form'; import { FooterToolbar, PageContainer } from '@ant-design/pro-layout'; import type { ActionType, ProColumns } from '@ant-design/pro-table'; import ProTable from '@ant-design/pro-table'; import { Button, Drawer, Input, message } from 'antd'; import React, { useRef, useState } from 'react'; import { FormattedMessage, useIntl } from 'umi'; import type { FormValueType } from './components/UpdateForm'; import UpdateForm from './components/UpdateForm'; /** * @en-US Add node * @zh-CN ๆทปๅŠ ่Š‚็‚น * @param fields */ const handleAdd = async (fields: API.RuleListItem) => { const hide = message.loading('ๆญฃๅœจๆทปๅŠ '); try { await addRule({ ...fields }); hide(); message.success('Added successfully'); return true; } catch (error) { hide(); message.error('Adding failed, please try again!'); return false; } }; /** * @en-US Update node * @zh-CN ๆ›ดๆ–ฐ่Š‚็‚น * * @param fields */ const handleUpdate = async (fields: FormValueType) => { const hide = message.loading('Configuring'); try { await updateRule({ name: fields.name, desc: fields.desc, key: fields.key, }); hide(); message.success('Configuration is successful'); return true; } catch (error) { hide(); message.error('Configuration failed, please try again!'); return false; } }; /** * Delete node * @zh-CN ๅˆ ้™ค่Š‚็‚น * * @param selectedRows */ const handleRemove = async (selectedRows: API.RuleListItem[]) => { const hide = message.loading('ๆญฃๅœจๅˆ ้™ค'); if (!selectedRows) return true; try { await removeRule({ key: selectedRows.map((row) => row.key), }); hide(); message.success('Deleted successfully and will refresh soon'); return true; } catch (error) { hide(); message.error('Delete failed, please try again'); return false; } }; const TableList: React.FC = () => { /** * @en-US Pop-up window of new window * @zh-CN ๆ–ฐๅปบ็ช—ๅฃ็š„ๅผน็ช— * */ const [createModalVisible, handleModalVisible] = useState<boolean>(false); /** * @en-US The pop-up window of the distribution update window * @zh-CN ๅˆ†ๅธƒๆ›ดๆ–ฐ็ช—ๅฃ็š„ๅผน็ช— * */ const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); const [showDetail, setShowDetail] = useState<boolean>(false); const actionRef = useRef<ActionType>(); const [currentRow, setCurrentRow] = useState<API.RuleListItem>(); const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]); /** * @en-US International configuration * @zh-CN ๅ›ฝ้™…ๅŒ–้…็ฝฎ * */ const intl = useIntl(); const columns: ProColumns<API.RuleListItem>[] = [ { title: ( <FormattedMessage id="pages.searchTable.updateForm.ruleName.nameLabel" defaultMessage="Rule name" /> ), dataIndex: 'name', tip: 'The rule name is the unique key', render: (dom, entity) => { return ( <a onClick={() => { setCurrentRow(entity); setShowDetail(true); }} > {dom} </a> ); }, }, { title: ( <FormattedMessage id="pages.searchTable.titleDesc" defaultMessage="Description" /> ), dataIndex: 'desc', valueType: 'textarea', }, { title: ( <FormattedMessage id="pages.searchTable.titleCallNo" defaultMessage="Number of service calls" /> ), dataIndex: 'callNo', sorter: true, hideInForm: true, renderText: (val: string) => `${val}${intl.formatMessage({ id: 'pages.searchTable.tenThousand', defaultMessage: ' ไธ‡ ', })}`, }, { title: ( <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" /> ), dataIndex: 'status', hideInForm: true, valueEnum: { 0: { text: ( <FormattedMessage id="pages.searchTable.nameStatus.default" defaultMessage="Shut down" /> ), status: 'Default', }, 1: { text: ( <FormattedMessage id="pages.searchTable.nameStatus.running" defaultMessage="Running" /> ), status: 'Processing', }, 2: { text: ( <FormattedMessage id="pages.searchTable.nameStatus.online" defaultMessage="Online" /> ), status: 'Success', }, 3: { text: ( <FormattedMessage id="pages.searchTable.nameStatus.abnormal" defaultMessage="Abnormal" /> ), status: 'Error', }, }, }, { title: ( <FormattedMessage id="pages.searchTable.titleUpdatedAt" defaultMessage="Last scheduled time" /> ), sorter: true, dataIndex: 'updatedAt', valueType: 'dateTime', renderFormItem: (item, { defaultRender, ...rest }, form) => { const status = form.getFieldValue('status'); if (`${status}` === '0') { return false; } if (`${status}` === '3') { return ( <Input {...rest} placeholder={intl.formatMessage({ id: 'pages.searchTable.exception', defaultMessage: 'Please enter the reason for the exception!', })} /> ); } return defaultRender(item); }, }, { title: ( <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" /> ), dataIndex: 'option', valueType: 'option', render: (_, record) => [ <a key="config" onClick={() => { handleUpdateModalVisible(true); setCurrentRow(record); }} > <FormattedMessage id="pages.searchTable.config" defaultMessage="Configuration" /> </a>, <a key="subscribeAlert" href="https://procomponents.ant.design/"> <FormattedMessage id="pages.searchTable.subscribeAlert" defaultMessage="Subscribe to alerts" /> </a>, ], }, ]; return ( <PageContainer> <ProTable<API.RuleListItem, API.PageParams> headerTitle={intl.formatMessage({ id: 'pages.searchTable.title', defaultMessage: 'Enquiry form', })} actionRef={actionRef} rowKey="key" search={{ labelWidth: 120, }} toolBarRender={() => [ <Button type="primary" key="primary" onClick={() => { handleModalVisible(true); }} > <PlusOutlined />{' '} <FormattedMessage id="pages.searchTable.new" defaultMessage="New" /> </Button>, ]} request={rule} columns={columns} rowSelection={{ onChange: (_, selectedRows) => { setSelectedRows(selectedRows); }, }} /> {selectedRowsState?.length > 0 && ( <FooterToolbar extra={ <div> <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '} <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '} <FormattedMessage id="pages.searchTable.item" defaultMessage="้กน" /> &nbsp;&nbsp; <span> <FormattedMessage id="pages.searchTable.totalServiceCalls" defaultMessage="Total number of service calls" />{' '} {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '} <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="ไธ‡" /> </span> </div> } > <Button onClick={async () => { await handleRemove(selectedRowsState); setSelectedRows([]); actionRef.current?.reloadAndRest?.(); }} > <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="Batch deletion" /> </Button> <Button type="primary"> <FormattedMessage id="pages.searchTable.batchApproval" defaultMessage="Batch approval" /> </Button> </FooterToolbar> )} <ModalForm title={intl.formatMessage({ id: 'pages.searchTable.createForm.newRule', defaultMessage: 'New rule', })} width="400px" visible={createModalVisible} onVisibleChange={handleModalVisible} onFinish={async (value) => { const success = await handleAdd(value as API.RuleListItem); if (success) { handleModalVisible(false); if (actionRef.current) { actionRef.current.reload(); } } }} > <ProFormText rules={[ { required: true, message: ( <FormattedMessage id="pages.searchTable.ruleName" defaultMessage="Rule name is required" /> ), }, ]} width="md" name="name" /> <ProFormTextArea width="md" name="desc" /> </ModalForm> <UpdateForm onSubmit={async (value) => { const success = await handleUpdate(value); if (success) { handleUpdateModalVisible(false); setCurrentRow(undefined); if (actionRef.current) { actionRef.current.reload(); } } }} onCancel={() => { handleUpdateModalVisible(false); if (!showDetail) { setCurrentRow(undefined); } }} updateModalVisible={updateModalVisible} values={currentRow || {}} /> <Drawer width={600} visible={showDetail} onClose={() => { setCurrentRow(undefined); setShowDetail(false); }} closable={false} > {currentRow?.name && ( <ProDescriptions<API.RuleListItem> column={2} title={currentRow?.name} request={async () => ({ data: currentRow || {}, })} params={{ id: currentRow?.name, }} columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]} /> )} </Drawer> </PageContainer> ); }; export default TableList;
the_stack
import { Writable } from 'stream'; export = xmlbuilder; /** * Type definitions for [xmlbuilder](https://github.com/oozcitak/xmlbuilder-js) * * Original definitions on [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) by: * - Wallymathieu <https://github.com/wallymathieu> * - GaikwadPratik <https://github.com/GaikwadPratik> */ declare namespace xmlbuilder { /** * Creates a new XML document and returns the root element node. * * @param nameOrObject - name of the root element or a JS object to be * converted to an XML tree * @param xmldecOrOptions - XML declaration or create options * @param doctypeOrOptions - Doctype declaration or create options * @param options - create options */ function create(nameOrObject: string | { [name: string]: Object }, xmldecOrOptions?: CreateOptions, doctypeOrOptions?: CreateOptions, options?: CreateOptions): XMLElement; /** * Defines the options used while creating an XML document with the `create` * function. */ interface CreateOptions { /** * A version number string, e.g. `1.0` */ version?: string; /** * Encoding declaration, e.g. `UTF-8` */ encoding?: string; /** * Standalone document declaration: `true` or `false` */ standalone?: boolean; /** * Public identifier of the DTD */ pubID?: string; /** * System identifier of the DTD */ sysID?: string; /** * Whether XML declaration and doctype will be included */ headless?: boolean; /** * Whether nodes with `null` values will be kept or ignored */ keepNullNodes?: boolean; /** * Whether attributes with `null` values will be kept or ignored */ keepNullAttributes?: boolean; /** * Whether decorator strings will be ignored when converting JS * objects */ ignoreDecorators?: boolean; /** * Whether array items are created as separate nodes when passed * as an object value */ separateArrayItems?: boolean; /** * Whether existing html entities are encoded */ noDoubleEncoding?: boolean; /** * Whether values will be validated and escaped or returned as is */ noValidation?: boolean; /** * A character to replace invalid characters in all values. This also * disables character validation. */ invalidCharReplacement?: string; /** * A set of functions to use for converting values to strings */ stringify?: XMLStringifier; /** * The default XML writer to use for converting nodes to string. * If the default writer is not set, the built-in `XMLStringWriter` * will be used instead. */ writer?: XMLWriter; } /** * Defines the functions used for converting values to strings. */ interface XMLStringifier { /** * Converts an element or attribute name to string */ name?: (v: any) => string; /** * Converts the contents of a text node to string */ text?: (v: any) => string; /** * Converts the contents of a CDATA node to string */ cdata?: (v: any) => string; /** * Converts the contents of a comment node to string */ comment?: (v: any) => string; /** * Converts the contents of a raw text node to string */ raw?: (v: any) => string; /** * Converts attribute value to string */ attValue?: (v: any) => string; /** * Converts processing instruction target to string */ insTarget?: (v: any) => string; /** * Converts processing instruction value to string */ insValue?: (v: any) => string; /** * Converts XML version to string */ xmlVersion?: (v: any) => string; /** * Converts XML encoding to string */ xmlEncoding?: (v: any) => string; /** * Converts standalone document declaration to string */ xmlStandalone?: (v: any) => string; /** * Converts DocType public identifier to string */ dtdPubID?: (v: any) => string; /** * Converts DocType system identifier to string */ dtdSysID?: (v: any) => string; /** * Converts `!ELEMENT` node content inside Doctype to string */ dtdElementValue?: (v: any) => string; /** * Converts `!ATTLIST` node type inside DocType to string */ dtdAttType?: (v: any) => string; /** * Converts `!ATTLIST` node default value inside DocType to string */ dtdAttDefault?: (v: any) => string; /** * Converts `!ENTITY` node content inside Doctype to string */ dtdEntityValue?: (v: any) => string; /** * Converts `!NOTATION` node content inside Doctype to string */ dtdNData?: (v: any) => string; /** * When prepended to a JS object key, converts the key-value pair * to an attribute. */ convertAttKey?: string; /** * When prepended to a JS object key, converts the key-value pair * to a processing instruction node. */ convertPIKey?: string; /** * When prepended to a JS object key, converts its value to a text node. * * _Note:_ Since JS objects cannot contain duplicate keys, multiple text * nodes can be created by adding some unique text after each object * key. For example: `{ '#text1': 'some text', '#text2': 'more text' };` */ convertTextKey?: string; /** * When prepended to a JS object key, converts its value to a CDATA * node. */ convertCDataKey?: string; /** * When prepended to a JS object key, converts its value to a * comment node. */ convertCommentKey?: string; /** * When prepended to a JS object key, converts its value to a raw * text node. */ convertRawKey?: string; /** * Escapes special characters in text. */ textEscape?: (v: string) => string; /** * Escapes special characters in attribute values. */ attEscape?: (v: string) => string; } /** * Represents a writer which outputs an XML document. */ interface XMLWriter { /** * Writes the indentation string for the given level. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ indent?: (node: XMLNode, options: WriterOptions, level: number) => any /** * Writes the newline string. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ endline?: (node: XMLNode, options: WriterOptions, level: number) => any /** * Writes an attribute. * * @param att - current attribute * @param options - writer options and state information * @param level - current depth of the XML tree */ attribute?: (att: XMLAttribute, options: WriterOptions, level: number) => any /** * Writes a CDATA node. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ cdata?: (node: XMLCData, options: WriterOptions, level: number) => any /** * Writes a comment node. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ comment?: (node: XMLComment, options: WriterOptions, level: number) => any /** * Writes the XML declaration (e.g. `<?xml version="1.0"?>`). * * @param node - XML declaration node * @param options - writer options and state information * @param level - current depth of the XML tree */ declaration?: (node: XMLDeclaration, options: WriterOptions, level: number) => any /** * Writes the DocType node and its children. * * _Note:_ Be careful when overriding this function as this function * is also responsible for writing the internal subset of the DTD. * * @param node - DOCTYPE node * @param options - writer options and state information * @param level - current depth of the XML tree */ docType?: (node: XMLDocType, options: WriterOptions, level: number) => any /** * Writes an element node. * * _Note:_ Be careful when overriding this function as this function * is also responsible for writing the element attributes and child * nodes. * * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ element?: (node: XMLElement, options: WriterOptions, level: number) => any /** * Writes a processing instruction node. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ processingInstruction?: (node: XMLProcessingInstruction, options: WriterOptions, level: number) => any /** * Writes a raw text node. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ raw?: (node: XMLRaw, options: WriterOptions, level: number) => any /** * Writes a text node. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ text?: (node: XMLText, options: WriterOptions, level: number) => any /** * Writes an attribute node (`!ATTLIST`) inside the DTD. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ dtdAttList?: (node: XMLDTDAttList, options: WriterOptions, level: number) => any /** * Writes an element node (`!ELEMENT`) inside the DTD. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ dtdElement?: (node: XMLDTDElement, options: WriterOptions, level: number) => any /** * Writes an entity node (`!ENTITY`) inside the DTD. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ dtdEntity?: (node: XMLDTDEntity, options: WriterOptions, level: number) => any /** * Writes a notation node (`!NOTATION`) inside the DTD. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ dtdNotation?: (node: XMLDTDNotation, options: WriterOptions, level: number) => any /** * Called right after starting writing a node. This function does not * produce any output, but can be used to alter the state of the writer. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ openNode?: (node: XMLNode, options: WriterOptions, level: number) => void /** * Called right before completing writing a node. This function does not * produce any output, but can be used to alter the state of the writer. * * @param node - current node * @param options - writer options and state information * @param level - current depth of the XML tree */ closeNode?: (node: XMLNode, options: WriterOptions, level: number) => void /** * Called right after starting writing an attribute. This function does * not produce any output, but can be used to alter the state of the * writer. * * @param node - current attribute * @param options - writer options and state information * @param level - current depth of the XML tree */ openAttribute?: (att: XMLAttribute, options: WriterOptions, level: number) => void /** * Called right before completing writing an attribute. This function * does not produce any output, but can be used to alter the state of * the writer. * * @param node - current attribute * @param options - writer options and state information * @param level - current depth of the XML tree */ closeAttribute?: (att: XMLAttribute, options: WriterOptions, level: number) => void } /** * Defines the options passed to the XML writer. */ interface WriterOptions { /** * Pretty print the XML tree */ pretty?: boolean; /** * Indentation string for pretty printing */ indent?: string; /** * Newline string for pretty printing */ newline?: string; /** * A fixed number of indents to offset strings */ offset?: number; /** * Maximum column width */ width?: number; /** * Whether to output closing tags for empty element nodes */ allowEmpty?: boolean; /** * Whether to pretty print text nodes */ dontPrettyTextNodes?: boolean; /** * A string to insert before closing slash character */ spaceBeforeSlash?: string | boolean; /** * User state object that is saved between writer functions */ user?: any; /** * The current state of the writer */ state?: WriterState; /** * Writer function overrides */ writer?: XMLWriter; } /** * Defines the state of the writer. */ enum WriterState { /** * Writer state is unknown */ None = 0, /** * Writer is at an opening tag, e.g. `<node>` */ OpenTag = 1, /** * Writer is inside an element */ InsideTag = 2, /** * Writer is at a closing tag, e.g. `</node>` */ CloseTag = 3 } /** * Creates a new XML document and returns the document node. * This function creates an empty document without the XML prolog or * a root element. * * @param options - create options */ function begin(options?: BeginOptions): XMLDocument; /** * Defines the options used while creating an XML document with the `begin` * function. */ interface BeginOptions { /** * Whether nodes with null values will be kept or ignored */ keepNullNodes?: boolean; /** * Whether attributes with null values will be kept or ignored */ keepNullAttributes?: boolean; /** * Whether decorator strings will be ignored when converting JS * objects */ ignoreDecorators?: boolean; /** * Whether array items are created as separate nodes when passed * as an object value */ separateArrayItems?: boolean; /** * Whether existing html entities are encoded */ noDoubleEncoding?: boolean; /** * Whether values will be validated and escaped or returned as is */ noValidation?: boolean; /** * A character to replace invalid characters in all values. This also * disables character validation. */ invalidCharReplacement?: string; /** * A set of functions to use for converting values to strings */ stringify?: XMLStringifier; /** * The default XML writer to use for converting nodes to string. * If the default writer is not set, the built-in XMLStringWriter * will be used instead. */ writer?: XMLWriter | WriterOptions; } /** * A function to be called when a chunk of XML is written. * * @param chunk - a chunk of string that was written * @param level - current depth of the XML tree */ type OnDataCallback = (chunk: string, level: number) => void; /** * A function to be called when the XML doucment is completed. */ type OnEndCallback = () => void; /** * Creates a new XML document in callback mode and returns the document * node. * * @param options - create options * @param onData - the function to be called when a new chunk of XML is * output. The string containing the XML chunk is passed to `onData` as * its first argument and the current depth of the tree is passed as its * second argument. * @param onEnd - the function to be called when the XML document is * completed with `end`. `onEnd` does not receive any arguments. */ function begin(options?: BeginOptions | OnDataCallback, onData?: OnDataCallback | OnEndCallback, onEnd?: OnEndCallback): XMLDocumentCB; /** * Creates and returns a default string writer. * * @param options - writer options */ function stringWriter(options?: WriterOptions): XMLWriter /** * Creates and returns a default stream writer. * * @param stream - a writeable stream * @param options - writer options */ function streamWriter(stream: Writable, options?: WriterOptions): XMLWriter /** * Defines the type of a node in the XML document. */ enum NodeType { /** * An element node */ Element = 1, /** * An attribute node */ Attribute = 2, /** * A text node */ Text = 3, /** * A CDATA node */ CData = 4, /** * An entity reference node inside DocType */ EntityReference = 5, /** * An entity declaration node inside DocType */ EntityDeclaration = 6, /** * A processing instruction node */ ProcessingInstruction = 7, /** * A comment node */ Comment = 8, /** * A document node */ Document = 9, /** * A Doctype node */ DocType = 10, /** * A document fragment node */ DocumentFragment = 11, /** * A notation declaration node inside DocType */ NotationDeclaration = 12, /** * An XML declaration node */ Declaration = 201, /** * A raw text node */ Raw = 202, /** * An attribute declaraiton node inside DocType */ AttributeDeclaration = 203, /** * An element declaration node inside DocType */ ElementDeclaration = 204 } /** * Defines the type of a node in the XML document. */ export import nodeType = NodeType; /** * Defines the state of the writer. */ export import writerState = WriterState; /** * Defines the settings used when converting the XML document to string. */ interface XMLToStringOptions { /** * Pretty print the XML tree */ pretty?: boolean; /** * Indentation string for pretty printing */ indent?: string; /** * Newline string for pretty printing */ newline?: string; /** * A fixed number of indents to offset strings */ offset?: number; /** * Maximum column width */ width?: number; /** * Whether to output closing tags for empty element nodes */ allowEmpty?: boolean; /** * Whether to pretty print text nodes */ dontPrettyTextNodes?: boolean; /** * A string to insert before closing slash character */ spaceBeforeSlash?: string | boolean; /** * The default XML writer to use for converting nodes to string. * If the default writer is not set, the built-in `XMLStringWriter` * will be used instead. */ writer?: XMLWriter; } /** * Represents the XML document. */ class XMLDocument extends XMLNode { /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents an XML attribute. */ class XMLAttribute { /** * Type of the node */ type: NodeType; /** * Parent element node */ parent: XMLElement; /** * Attribute name */ name: string; /** * Attribute value */ value: string; /** * Creates a clone of this node */ clone(): XMLAttribute; /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents the base class of XML nodes. */ abstract class XMLNode { /** * Type of the node */ type: NodeType; /** * Parent element node */ parent: XMLElement; /** * Child nodes */ children: XMLNode[] /** * Creates a new child node and appends it to the list of child nodes. * * _Aliases:_ `ele` and `e` * * @param name - node name or a JS object defining the nodes to insert * @param attributes - node attributes * @param text - node text * * @returns the last top level node created */ element(name: any, attributes?: Object, text?: any): XMLElement; ele(name: any, attributes?: Object, text?: any): XMLElement; e(name: any, attributes?: Object, text?: any): XMLElement; /** * Adds or modifies an attribute. * * _Aliases:_ `att`, `a` * * @param name - attribute name * @param value - attribute value * * @returns the parent element node */ attribute(name: any, value?: any): XMLElement; att(name: any, value?: any): XMLElement; a(name: any, value?: any): XMLElement; /** * Creates a new sibling node and inserts it before this node. * * @param name - node name or a JS object defining the nodes to insert * @param attributes - node attributes * @param text - node text * * @returns the new node */ insertBefore(name: any, attributes?: Object, text?: any): XMLElement; /** * Creates a new sibling node and inserts it after this node. * * @param name - node name or a JS object defining the nodes to insert * @param attributes - node attributes * @param text - node text * * @returns the new node */ insertAfter(name: any, attributes?: Object, text?: any): XMLElement; /** * Removes this node from the tree. * * @returns the parent node */ remove(): XMLElement; /** * Creates a new element node and appends it to the list of child nodes. * * _Aliases:_ `nod` and `n` * * @param name - element node name * @param attributes - node attributes * @param text - node text * * @returns the node created */ node(name: string, attributes?: Object, text?: any): XMLElement; nod(name: string, attributes?: Object, text?: any): XMLElement; n(name: string, attributes?: Object, text?: any): XMLElement; /** * Creates a new text node and appends it to the list of child nodes. * * _Aliases:_ `txt` and `t` * * @param value - node value * * @returns the parent node */ text(value: string): XMLElement; txt(value: string): XMLElement; t(value: string): XMLElement; /** * Creates a new CDATA node and appends it to the list of child nodes. * * _Aliases:_ `dat` and `d` * * @param value - node value * * @returns the parent node */ cdata(value: string): XMLElement; dat(value: string): XMLElement; d(value: string): XMLElement; /** * Creates a new comment node and appends it to the list of child nodes. * * _Aliases:_ `com` and `c` * * @param value - node value * * @returns the parent node */ comment(value: string): XMLElement; com(value: string): XMLElement; c(value: string): XMLElement; /** * Creates a comment node before the current node * * @param value - node value * * @returns the parent node */ commentBefore(value: string): XMLElement; /** * Creates a comment node after the current node * * @param value - node value * * @returns the parent node */ commentAfter(value: string): XMLElement; /** * Creates a new raw text node and appends it to the list of child * nodes. * * _Alias:_ `r` * * @param value - node value * * @returns the parent node */ raw(value: string): XMLElement; r(value: string): XMLElement; /** * Creates a new processing instruction node and appends it to the list * of child nodes. * * _Aliases:_ `ins` and `i` * * @param target - node target * @param value - node value * * @returns the parent node */ instruction(target: string, value: any): XMLElement; instruction(array: Array<any>): XMLElement; instruction(obj: Object): XMLElement; ins(target: string, value: any): XMLElement; ins(array: Array<any>): XMLElement; ins(obj: Object): XMLElement; i(target: string, value: any): XMLElement; i(array: Array<any>): XMLElement; i(obj: Object): XMLElement; /** * Creates a processing instruction node before the current node. * * @param target - node target * @param value - node value * * @returns the parent node */ instructionBefore(target: string, value: any): XMLElement; /** * Creates a processing instruction node after the current node. * * @param target - node target * @param value - node value * * @returns the parent node */ instructionAfter(target: string, value: any): XMLElement; /** * Creates the XML declaration. * * _Alias:_ `dec` * * @param version - version number string, e.g. `1.0` * @param encoding - encoding declaration, e.g. `UTF-8` * @param standalone - standalone document declaration: `true` or `false` * * @returns the root element node */ declaration(version?: string | { version?: string, encoding?: string, standalone?: boolean }, encoding?: string, standalone?: boolean): XMLElement; dec(version?: string | { version?: string, encoding?: string, standalone?: boolean }, encoding?: string, standalone?: boolean): XMLElement; /** * Creates the document type definition. * * _Alias:_ `dtd` * * @param pubID - public identifier of the DTD * @param sysID - system identifier of the DTD * * @returns the DOCTYPE node */ doctype(pubID?: string | { pubID?: string, sysID?: string }, sysID?: string): XMLDocType; dtd(pubID?: string | { pubID?: string, sysID?: string }, sysID?: string): XMLDocType; /** * Takes the root node of the given XML document and appends it * to child nodes. * * @param doc - the document whose root node to import * * @returns the current node */ importDocument(doc: XMLNode): XMLElement; /** * Converts the XML document to string. * * @param options - conversion options */ end(options?: XMLWriter | XMLToStringOptions): string; /** * Returns the previous sibling node. */ prev(): XMLNode; /** * Returns the next sibling node. */ next(): XMLNode; /** * Returns the parent node. * * _Alias:_ `u` */ up(): XMLElement; u(): XMLElement; /** * Returns the document node. * * _Alias:_ `doc` */ document(): XMLDocument; doc(): XMLDocument; /** * Returns the root element node. */ root(): XMLElement; } /** * Represents the base class of character data nodes. */ abstract class XMLCharacterData extends XMLNode { /** * Node value */ value: string; } /** * Represents a CDATA node. */ class XMLCData extends XMLCharacterData { /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node */ clone(): XMLCData; } /** * Represents a comment node. */ class XMLComment extends XMLCharacterData { /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node */ clone(): XMLComment; } /** * Represents a processing instruction node. */ class XMLProcessingInstruction extends XMLCharacterData { /** Instruction target */ target: string; /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node */ clone(): XMLProcessingInstruction; } /** * Represents a raw text node. */ class XMLRaw extends XMLCharacterData { /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node */ clone(): XMLRaw; } /** * Represents a text node. */ class XMLText extends XMLCharacterData { /** * Converts the node to string * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node */ clone(): XMLText; } /** * Represents the XML declaration. */ class XMLDeclaration { /** * A version number string, e.g. `1.0` */ version: string; /** * Encoding declaration, e.g. `UTF-8` */ encoding: string; /** * Standalone document declaration: `true` or `false` */ standalone: boolean; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents the document type definition. */ class XMLDocType { /** * Type of the node */ type: NodeType; /** * Parent element node */ parent: XMLElement; /** * Child nodes */ children: XMLNode[] /** * Public identifier of the DTD */ pubID: string; /** * System identifier of the DTD */ sysID: string; /** * Creates an element type declaration. * * _Alias:_ `ele` * * @param name - element name * @param value - element content (defaults to `#PCDATA`) * * @returns the DOCTYPE node */ element(name: string, value?: Object): XMLDocType; ele(name: string, value?: Object): XMLDocType; /** * Creates an attribute declaration. * * _Alias:_ `att` * * @param elementName - the name of the element containing this attribute * @param attributeName - attribute name * @param attributeType - type of the attribute * @param defaultValueType - default value type (either `#REQUIRED`, * `#IMPLIED`, `#FIXED` or `#DEFAULT`) * @param defaultValue - default value of the attribute (only used * for `#FIXED` or `#DEFAULT`) * * @returns the DOCTYPE node */ attList(elementName: string, attributeName: string, attributeType: string, defaultValueType: string, defaultValue?: any): XMLDocType; att(elementName: string, attributeName: string, attributeType: string, defaultValueType: string, defaultValue?: any): XMLDocType; /** * Creates a general entity declaration. * * _Alias:_ `ent` * * @param name - the name of the entity * @param value - entity parameters * * @returns the DOCTYPE node */ entity(name: string, value: string | { pubID?: string, sysID?: string, nData?: string }): XMLDocType; ent(name: string, value: string | { pubID?: string, sysID?: string, nData?: string }): XMLDocType; /** * Creates a parameter entity declaration. * * _Alias:_ `pent` * * @param name - the name of the entity * @param value - entity parameters * * @returns the DOCTYPE node */ pEntity(name: string, value: string | { pubID?: string, sysID?: string }): XMLDocType; pent(name: string, value: string | { pubID?: string, sysID?: string }): XMLDocType; /** * Creates a notation declaration. * * _Alias:_ `not` * * @param name - the name of the entity * @param value - entity parameters * * @returns the DOCTYPE node */ notation(name: string, value: { pubID?: string, sysID?: string }): XMLDocType; not(name: string, value: { pubID?: string, sysID?: string }): XMLDocType; /** * Creates a new CDATA node and appends it to the list of child nodes. * * _Alias:_ `dat` * * @param value - node value * * @returns the DOCTYPE node */ cdata(value: string): XMLDocType; dat(value: string): XMLDocType; /** * Creates a new comment child and appends it to the list of child * nodes. * * _Alias:_ `com` * * @param value - node value * * @returns the DOCTYPE node */ comment(value: string): XMLDocType; com(value: string): XMLDocType; /** * Creates a new processing instruction node and appends it to the list * of child nodes. * * _Alias:_ `ins` * * @param target - node target * @param value - node value * * @returns the DOCTYPE node */ instruction(target: string, value: any): XMLDocType; instruction(array: Array<any>): XMLDocType; instruction(obj: Object): XMLDocType; ins(target: string, value: any): XMLDocType; ins(array: Array<any>): XMLDocType; ins(obj: Object): XMLDocType; /** * Returns the root element node. * * _Alias:_ `up` */ root(): XMLElement; up(): XMLElement; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; /** * Creates a clone of this node. */ clone(): XMLDocType; /** * Returns the document node. * * _Alias:_ `doc` */ document(): XMLDocument; doc(): XMLDocument; /** * Converts the XML document to string. * * @param options - conversion options */ end(options?: XMLWriter | XMLToStringOptions): string; } /** * Represents an attribute list in the DTD. */ class XMLDTDAttList { /** * The name of the element containing this attribute */ elementName: string; /** * Attribute name */ attributeName: string; /** * Type of the attribute */ attributeType: string; /** * Default value type (either `#REQUIRED`, `#IMPLIED`, `#FIXED` * or `#DEFAULT`) */ defaultValueType: string; /** * Default value of the attribute (only used for `#FIXED` or * `#DEFAULT`) */ defaultValue: string; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents an element in the DTD. */ class XMLDTDElement { /** * The name of the element */ name: string; /** * Element content */ value: string; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents an entity in the DTD. */ class XMLDTDEntity { /** * Determines whether this is a parameter entity (`true`) or a * general entity (`false`). */ pe: boolean; /** * The name of the entity */ name: string; /** * Public identifier */ pubID: string; /** * System identifier */ sysID: string; /** * Notation declaration */ nData: string; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents a notation in the DTD. */ class XMLDTDNotation { /** * The name of the notation */ name: string; /** * Public identifier */ pubID: string; /** * System identifier */ sysID: string; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents an element node. */ class XMLElement extends XMLNode { /** * Element node name */ name: string; /** * Element attributes */ attribs: { string: XMLAttribute }; /** * Creates a clone of this node */ clone(): XMLElement; /** * Adds or modifies an attribute. * * _Aliases:_ `att`, `a` * * @param name - attribute name * @param value - attribute value * * @returns the parent element node */ attribute(name: any, value?: any): XMLElement; att(name: any, value?: any): XMLElement; a(name: any, value?: any): XMLElement; /** * Removes an attribute. * * @param name - attribute name * * @returns the parent element node */ removeAttribute(name: string | string[]): XMLElement; /** * Converts the node to string. * * @param options - conversion options */ toString(options?: XMLToStringOptions): string; } /** * Represents an XML document builder used in callback mode with the * `begin` function. */ class XMLDocumentCB { /** * Creates a new child node and appends it to the list of child nodes. * * _Aliases:_ `nod` and `n` * * @param name - element node name * @param attributes - node attributes * @param text - node text * * @returns the document builder object */ node(name: string, attributes?: Object, text?: any): XMLDocumentCB; nod(name: string, attributes?: Object, text?: any): XMLDocumentCB; n(name: string, attributes?: Object, text?: any): XMLDocumentCB; /** * Creates a child element node. * * _Aliases:_ `ele` and `e` * * @param name - element node name or a JS object defining the nodes * to insert * @param attributes - node attributes * @param text - node text * * @returns the document builder object */ element(name: any, attributes?: Object, text?: any): XMLDocumentCB; ele(name: any, attributes?: Object, text?: any): XMLDocumentCB; e(name: any, attributes?: Object, text?: any): XMLDocumentCB; /** * Adds or modifies an attribute. * * _Aliases:_ `att` and `a` * * @param name - attribute name * @param value - attribute value * * @returns the document builder object */ attribute(name: any, value?: any): XMLDocumentCB; att(name: any, value?: any): XMLDocumentCB; a(name: any, value?: any): XMLDocumentCB; /** * Creates a new text node and appends it to the list of child nodes. * * _Aliases:_ `txt` and `t` * * @param value - node value * * @returns the document builder object */ text(value: string): XMLDocumentCB; txt(value: string): XMLDocumentCB; t(value: string): XMLDocumentCB; /** * Creates a new CDATA node and appends it to the list of child nodes. * * _Aliases:_ `dat` and `d` * * @param value - node value * * @returns the document builder object */ cdata(value: string): XMLDocumentCB; dat(value: string): XMLDocumentCB; d(value: string): XMLDocumentCB; /** * Creates a new comment node and appends it to the list of child nodes. * * _Aliases:_ `com` and `c` * * @param value - node value * * @returns the document builder object */ comment(value: string): XMLDocumentCB; com(value: string): XMLDocumentCB; c(value: string): XMLDocumentCB; /** * Creates a new raw text node and appends it to the list of child * nodes. * * _Alias:_ `r` * * @param value - node value * * @returns the document builder object */ raw(value: string): XMLDocumentCB; r(value: string): XMLDocumentCB; /** * Creates a new processing instruction node and appends it to the list * of child nodes. * * _Aliases:_ `ins` and `i` * * @param target - node target * @param value - node value * * @returns the document builder object */ instruction(target: string, value: any): XMLDocumentCB; instruction(array: Array<any>): XMLDocumentCB; instruction(obj: Object): XMLDocumentCB; ins(target: string, value: any): XMLDocumentCB; ins(array: Array<any>): XMLDocumentCB; ins(obj: Object): XMLDocumentCB; i(target: string, value: any): XMLDocumentCB; i(array: Array<any>): XMLDocumentCB; i(obj: Object): XMLDocumentCB; /** * Creates the XML declaration. * * _Alias:_ `dec` * * @param version - version number string, e.g. `1.0` * @param encoding - encoding declaration, e.g. `UTF-8` * @param standalone - standalone document declaration: `true` or `false` * * @returns the document builder object */ declaration(version?: string, encoding?: string, standalone?: boolean): XMLDocumentCB; dec(version?: string, encoding?: string, standalone?: boolean): XMLDocumentCB; /** * Creates the document type definition. * * _Alias:_ `dtd` * * @param root - the name of the root node * @param pubID - public identifier of the DTD * @param sysID - system identifier of the DTD * * @returns the document builder object */ doctype(root: string, pubID?: string, sysID?: string): XMLDocumentCB; dtd(root: string, pubID?: string, sysID?: string): XMLDocumentCB; /** * Creates an element type declaration. * * _Aliases:_ `element` and `ele` * * @param name - element name * @param value - element content (defaults to `#PCDATA`) * * @returns the document builder object */ dtdElement(name: string, value?: Object): XMLDocumentCB; element(name: string, value?: Object): XMLDocumentCB; ele(name: string, value?: Object): XMLDocumentCB; /** * Creates an attribute declaration. * * _Alias:_ `att` * * @param elementName - the name of the element containing this attribute * @param attributeName - attribute name * @param attributeType - type of the attribute (defaults to `CDATA`) * @param defaultValueType - default value type (either `#REQUIRED`, * `#IMPLIED`, `#FIXED` or `#DEFAULT`) (defaults to `#IMPLIED`) * @param defaultValue - default value of the attribute (only used * for `#FIXED` or `#DEFAULT`) * * @returns the document builder object */ attList(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocumentCB; att(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocumentCB; a(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocumentCB; /** * Creates a general entity declaration. * * _Alias:_ `ent` * * @param name - the name of the entity * @param value - entity parameters * * @returns the document builder object */ entity(name: string, value: string | { pubID?: string, sysID?: string, nData?: string }): XMLDocumentCB; ent(name: string, value: string | { pubID?: string, sysID?: string, nData?: string }): XMLDocumentCB; /** * Creates a parameter entity declaration. * * _Alias:_ `pent` * * @param name - the name of the entity * @param value - entity parameters * * @returns the document builder object */ pEntity(name: string, value: string | { pubID?: string, sysID?: string }): XMLDocumentCB; pent(name: string, value: string | { pubID?: string, sysID?: string }): XMLDocumentCB; /** * Creates a notation declaration. * * _Alias:_ `not` * * @param name - the name of the entity * @param value - entity parameters * * @returns the document builder object */ notation(name: string, value: { pubID?: string, sysID?: string }): XMLDocumentCB; not(name: string, value: { pubID?: string, sysID?: string }): XMLDocumentCB; /** * Ends the document and calls the `onEnd` callback function. */ end(): void; /** * Moves up to the parent node. * * _Alias:_ `u` * * @returns the document builder object */ up(): XMLDocumentCB; u(): XMLDocumentCB; } }
the_stack
import moment from 'moment'; import * as _ from 'underscore'; import { combineIndexWithDefaultViewIndex, ensureIndex } from '../../collectionUtils'; import { forumTypeSetting } from '../../instanceSettings'; import { hideUnreviewedAuthorCommentsSettings } from '../../publicSettings'; import { ReviewYear } from '../../reviewUtils'; import { viewFieldNullOrMissing } from '../../vulcan-lib'; import { Comments } from './collection'; declare global { interface CommentsViewTerms extends ViewTermsBase { view?: CommentsViewName, postId?: string, userId?: string, tagId?: string, parentCommentId?: string, parentAnswerId?: string, topLevelCommentId?: string, legacyId?: string, authorIsUnreviewed?: boolean|null, sortBy?: string, before?: Date|string|null, after?: Date|string|null, reviewYear?: ReviewYear } } Comments.addDefaultView((terms: CommentsViewTerms) => { const validFields = _.pick(terms, 'userId', 'authorIsUnreviewed'); const alignmentForum = forumTypeSetting.get() === 'AlignmentForum' ? {af: true} : {} // We set `{$ne: true}` instead of `false` to allow for comments that haven't // had the default value set yet (ie: those created by the frontend // immediately prior to appearing) const hideUnreviewedAuthorComments = hideUnreviewedAuthorCommentsSettings.get() ? {authorIsUnreviewed: {$ne: true}} : {} return ({ selector: { $or: [{$and: [{deleted: true}, {deletedPublic: true}]}, {deleted: false}], hideAuthor: terms.userId ? false : undefined, ...alignmentForum, ...hideUnreviewedAuthorComments, ...validFields, }, options: { sort: {postedAt: -1}, } }); }) const sortings = { "top" : { baseScore: -1}, "groupByPost" : {postId: 1}, "new" : { postedAt: -1} } export function augmentForDefaultView(indexFields) { return combineIndexWithDefaultViewIndex({ viewFields: indexFields, prefix: {}, suffix: {authorIsUnreviewed: 1, deleted:1, deletedPublic:1, hideAuthor:1, userId:1, af:1}, }); } // Most common case: want to get all the comments on a post, filter fields and // `limit` affects it only minimally. Best handled by a hash index on `postId`. ensureIndex(Comments, { postId: "hashed" }); // For the user profile page ensureIndex(Comments, { userId:1, postedAt:-1 }); Comments.addView("commentReplies", (terms: CommentsViewTerms) => { return { selector: { parentCommentId: terms.parentCommentId, }, options: { sort: {postedAt: -1} } } }) ensureIndex(Comments, { parentCommentId: "hashed" }); Comments.addView("postCommentsDeleted", (terms: CommentsViewTerms) => { return { selector: { $or: null, deleted: null, postId: terms.postId }, options: {sort: {deletedDate: -1, baseScore: -1, postedAt: -1}} }; }); Comments.addView("allCommentsDeleted", (terms: CommentsViewTerms) => { return { selector: { $or: null, deleted: true, }, options: {sort: {deletedDate: -1, postedAt: -1, baseScore: -1 }} }; }); Comments.addView("postCommentsTop", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, parentAnswerId: viewFieldNullOrMissing, answer: false, }, options: {sort: {promoted: -1, deleted: 1, baseScore: -1, postedAt: -1}}, }; }); ensureIndex(Comments, augmentForDefaultView({ postId:1, parentAnswerId:1, answer:1, deleted:1, baseScore:-1, postedAt:-1 }), { name: "comments.top_comments" } ); Comments.addView("afPostCommentsTop", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, parentAnswerId: viewFieldNullOrMissing, answer: false, }, options: {sort: {promoted: -1, deleted: 1, afBaseScore: -1, postedAt: -1}}, }; }); ensureIndex(Comments, augmentForDefaultView({ postId:1, parentAnswerId:1, answer:1, deleted:1, afBaseScore:-1, postedAt:-1 }), { name: "comments.af_top_comments" } ); Comments.addView("postCommentsOld", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, parentAnswerId: viewFieldNullOrMissing, answer: false, }, options: {sort: {deleted: 1, postedAt: 1}}, parentAnswerId: viewFieldNullOrMissing }; }); // Uses same index as postCommentsNew Comments.addView("postCommentsNew", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, parentAnswerId: viewFieldNullOrMissing, answer: false, }, options: {sort: {deleted: 1, postedAt: -1}} }; }); ensureIndex(Comments, augmentForDefaultView({ postId:1, parentAnswerId:1, answer:1, deleted:1, postedAt:-1 }), { name: "comments.new_comments" } ); Comments.addView("postCommentsBest", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, parentAnswerId: viewFieldNullOrMissing, answer: false, }, options: {sort: {promoted: -1, deleted: 1, baseScore: -1}, postedAt: -1} }; }); // Same as postCommentsTop Comments.addView("postLWComments", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, af: null, answer: false, parentAnswerId: viewFieldNullOrMissing }, options: {sort: {promoted: -1, deleted: 1, baseScore: -1, postedAt: -1}} }; }) Comments.addView("allRecentComments", (terms: CommentsViewTerms) => { return { selector: {deletedPublic: false}, options: {sort: {postedAt: -1}, limit: terms.limit || 5}, }; }); Comments.addView("recentComments", (terms: CommentsViewTerms) => { return { selector: { score:{$gt:0}, deletedPublic: false}, options: {sort: {postedAt: -1}, limit: terms.limit || 5}, }; }); ensureIndex(Comments, augmentForDefaultView({ postedAt: -1 })); Comments.addView("afSubmissions", (terms: CommentsViewTerms) => { return { selector: { af: false, suggestForAlignmentUserIds: terms.userId, deletedPublic: false}, options: {sort: {postedAt: -1}, limit: terms.limit || 5}, }; }); // As of 2021-10, JP is unsure if this is used Comments.addView("recentDiscussionThread", (terms: CommentsViewTerms) => { // The forum has fewer comments, and so wants a more expansive definition of // "recent" const eighteenHoursAgo = moment().subtract(forumTypeSetting.get() === 'EAForum' ? 36 : 18, 'hours').toDate(); return { selector: { postId: terms.postId, score: {$gt:0}, deletedPublic: false, postedAt: {$gt: eighteenHoursAgo} }, options: {sort: {postedAt: -1}, limit: terms.limit || 5} }; }) // Uses same index as postCommentsNew Comments.addView("afRecentDiscussionThread", (terms: CommentsViewTerms) => { const sevenDaysAgo = moment().subtract(7, 'days').toDate(); return { selector: { postId: terms.postId, score: {$gt:0}, deletedPublic: false, postedAt: {$gt: sevenDaysAgo}, af: true, }, options: {sort: {postedAt: -1}, limit: terms.limit || 5} }; }) Comments.addView("postsItemComments", (terms: CommentsViewTerms) => { return { selector: { postId: terms.postId, deleted: false, score: {$gt: 0}, postedAt: terms.after ? {$gt: new Date(terms.after)} : null }, options: {sort: {postedAt: -1}, limit: terms.limit || 15}, }; }); Comments.addView("sunshineNewCommentsList", (terms: CommentsViewTerms) => { return { selector: { $or: [ {$and: []}, {needsReview: true}, {baseScore: {$lte:0}} ], reviewedByUserId: {$exists:false}, deleted: false, }, options: {sort: {postedAt: -1}, limit: terms.limit || 5}, }; }); export const questionAnswersSort = {promoted: -1, baseScore: -1, postedAt: -1} Comments.addView('questionAnswers', (terms: CommentsViewTerms) => { return { selector: {postId: terms.postId, answer: true}, options: {sort: questionAnswersSort} }; }); // Used in legacy routes Comments.addView("legacyIdComment", (terms: CommentsViewTerms) => { if (!terms.legacyId) throw new Error("Missing view argument: legacyId"); const legacyId = parseInt(terms.legacyId, 36) if (isNaN(legacyId)) throw new Error("Invalid view argument: legacyId must be base36, was "+terms.legacyId); return { selector: { legacyId: ""+legacyId }, options: { limit: 1 } }; }); ensureIndex(Comments, {legacyId: "hashed"}); // Used in scoring cron job ensureIndex(Comments, {inactive:1,postedAt:1}); Comments.addView("sunshineNewUsersComments", (terms: CommentsViewTerms) => { return { selector: { userId: terms.userId, // Don't hide deleted $or: null, // Don't hide unreviewed comments authorIsUnreviewed: null }, options: {sort: {postedAt: -1}}, }; }); ensureIndex(Comments, augmentForDefaultView({userId:1, postedAt:1})); Comments.addView("defaultModeratorResponses", (terms: CommentsViewTerms) => { return { selector: { tagId: terms.tagId, } }; }); ensureIndex(Comments, augmentForDefaultView({tagId:1})); Comments.addView('repliesToAnswer', (terms: CommentsViewTerms) => { return { selector: {parentAnswerId: terms.parentAnswerId}, options: {sort: {baseScore: -1}} }; }); ensureIndex(Comments, augmentForDefaultView({parentAnswerId:1, baseScore:-1})); // Used in moveToAnswers ensureIndex(Comments, {topLevelCommentId:1}); // Used in findCommentByLegacyAFId ensureIndex(Comments, {agentFoundationsId:1}); Comments.addView('topShortform', (terms: CommentsViewTerms) => { const timeRange = ((terms.before || terms.after) ? { postedAt: { ...(terms.before && {$lt: new Date(terms.before)}), ...(terms.after && {$gte: new Date(terms.after)}) } } : null ); return { selector: { shortform: true, parentCommentId: viewFieldNullOrMissing, deleted: false, ...timeRange }, options: {sort: {baseScore: -1, postedAt: -1}} }; }); Comments.addView('shortform', (terms: CommentsViewTerms) => { return { selector: { shortform: true, deleted: false, parentCommentId: viewFieldNullOrMissing, }, options: {sort: {lastSubthreadActivity: -1, postedAt: -1}} }; }); Comments.addView('repliesToCommentThread', (terms: CommentsViewTerms) => { return { selector: { topLevelCommentId: terms.topLevelCommentId }, options: {sort: {baseScore: -1}} } }); // Will be used for experimental shortform display on AllPosts page ensureIndex(Comments, {shortform:1, topLevelCommentId: 1, lastSubthreadActivity:1, postedAt: 1, baseScore:1}); Comments.addView('shortformLatestChildren', (terms: CommentsViewTerms) => { return { selector: { topLevelCommentId: terms.topLevelCommentId} , options: {sort: {postedAt: -1}, limit: 500} }; }); // Will be used for experimental shortform display on AllPosts page ensureIndex(Comments, { topLevelCommentId: 1, postedAt: 1, baseScore:1}); Comments.addView('nominations2018', ({userId, postId, sortBy="top"}: CommentsViewTerms) => { return { selector: { userId, postId, nominatedForReview: "2018", deleted: false }, options: { sort: { ...sortings[sortBy], top: -1, postedAt: -1 } } }; }); Comments.addView('nominations2019', function ({userId, postId, sortBy="top"}) { return { selector: { userId, postId, nominatedForReview: "2019", deleted: false }, options: { sort: { ...sortings[sortBy], top: -1, postedAt: -1 } } }; }); // Filtering comments down to ones that include "nominated for Review" so further sort indexes not necessary ensureIndex(Comments, augmentForDefaultView({ nominatedForReview: 1, userId: 1, postId: 1 }), { name: "comments.nominations2018" } ); Comments.addView('reviews2018', ({userId, postId, sortBy="top"}: CommentsViewTerms) => { return { selector: { userId, postId, reviewingForReview: "2018", deleted: false }, options: { sort: { ...sortings[sortBy], top: -1, postedAt: -1 } } }; }); Comments.addView('reviews2019', function ({userId, postId, sortBy="top"}) { return { selector: { userId, postId, reviewingForReview: "2019", deleted: false }, options: { sort: { ...sortings[sortBy], top: -1, postedAt: -1 } } }; }); // TODO: try to refactor this Comments.addView('reviews', function ({userId, postId, reviewYear, sortBy="top"}) { return { selector: { userId, postId, reviewingForReview: reviewYear+"", deleted: false }, options: { sort: { ...sortings[sortBy], top: -1, postedAt: -1 } } }; }); // Filtering comments down to ones that include "reviewing for review" so further sort indexes not necessary ensureIndex(Comments, augmentForDefaultView({ reviewingForReview: 1, userId: 1, postId: 1 }), { name: "comments.reviews2018" } ); Comments.addView('commentsOnTag', (terms: CommentsViewTerms) => ({ selector: { tagId: terms.tagId, }, })); ensureIndex(Comments, augmentForDefaultView({tagId: 1}), { name: "comments.tagId" } ); Comments.addView('moderatorComments', (terms: CommentsViewTerms) => ({ selector: { moderatorHat: true, }, options: { sort: {postedAt: -1}, }, })); ensureIndex(Comments, augmentForDefaultView({moderatorHat: 1}), { name: "comments.moderatorHat" } );
the_stack
import type Printer from "../printer"; import type * as t from "@babel/types"; export function TSTypeAnnotation(this: Printer, node: t.TSTypeAnnotation) { this.token(":"); this.space(); // @ts-expect-error todo(flow->ts) can this be removed? `.optional` looks to be not existing property if (node.optional) this.token("?"); this.print(node.typeAnnotation, node); } export function TSTypeParameterInstantiation( this: Printer, node: t.TSTypeParameterInstantiation, ): void { this.token("<"); this.printList(node.params, node, {}); this.token(">"); } export { TSTypeParameterInstantiation as TSTypeParameterDeclaration }; export function TSTypeParameter(this: Printer, node: t.TSTypeParameter) { this.word( !process.env.BABEL_8_BREAKING ? (node.name as unknown as string) : (node.name as unknown as t.Identifier).name, ); if (node.constraint) { this.space(); this.word("extends"); this.space(); this.print(node.constraint, node); } if (node.default) { this.space(); this.token("="); this.space(); this.print(node.default, node); } } export function TSParameterProperty( this: Printer, node: t.TSParameterProperty, ) { if (node.accessibility) { this.word(node.accessibility); this.space(); } if (node.readonly) { this.word("readonly"); this.space(); } this._param(node.parameter); } export function TSDeclareFunction(this: Printer, node: t.TSDeclareFunction) { if (node.declare) { this.word("declare"); this.space(); } this._functionHead(node); this.token(";"); } export function TSDeclareMethod(this: Printer, node: t.TSDeclareMethod) { this._classMethodHead(node); this.token(";"); } export function TSQualifiedName(this: Printer, node: t.TSQualifiedName) { this.print(node.left, node); this.token("."); this.print(node.right, node); } export function TSCallSignatureDeclaration( this: Printer, node: t.TSCallSignatureDeclaration, ) { this.tsPrintSignatureDeclarationBase(node); this.token(";"); } export function TSConstructSignatureDeclaration( this: Printer, node: t.TSConstructSignatureDeclaration, ) { this.word("new"); this.space(); this.tsPrintSignatureDeclarationBase(node); this.token(";"); } export function TSPropertySignature( this: Printer, node: t.TSPropertySignature, ) { const { readonly, initializer } = node; if (readonly) { this.word("readonly"); this.space(); } this.tsPrintPropertyOrMethodName(node); this.print(node.typeAnnotation, node); if (initializer) { this.space(); this.token("="); this.space(); this.print(initializer, node); } this.token(";"); } export function tsPrintPropertyOrMethodName(this: Printer, node) { if (node.computed) { this.token("["); } this.print(node.key, node); if (node.computed) { this.token("]"); } if (node.optional) { this.token("?"); } } export function TSMethodSignature(this: Printer, node: t.TSMethodSignature) { const { kind } = node; if (kind === "set" || kind === "get") { this.word(kind); this.space(); } this.tsPrintPropertyOrMethodName(node); this.tsPrintSignatureDeclarationBase(node); this.token(";"); } export function TSIndexSignature(this: Printer, node: t.TSIndexSignature) { const { readonly, static: isStatic } = node; if (isStatic) { this.word("static"); this.space(); } if (readonly) { this.word("readonly"); this.space(); } this.token("["); this._parameters(node.parameters, node); this.token("]"); this.print(node.typeAnnotation, node); this.token(";"); } export function TSAnyKeyword(this: Printer) { this.word("any"); } export function TSBigIntKeyword(this: Printer) { this.word("bigint"); } export function TSUnknownKeyword(this: Printer) { this.word("unknown"); } export function TSNumberKeyword(this: Printer) { this.word("number"); } export function TSObjectKeyword(this: Printer) { this.word("object"); } export function TSBooleanKeyword(this: Printer) { this.word("boolean"); } export function TSStringKeyword(this: Printer) { this.word("string"); } export function TSSymbolKeyword(this: Printer) { this.word("symbol"); } export function TSVoidKeyword(this: Printer) { this.word("void"); } export function TSUndefinedKeyword(this: Printer) { this.word("undefined"); } export function TSNullKeyword(this: Printer) { this.word("null"); } export function TSNeverKeyword(this: Printer) { this.word("never"); } export function TSIntrinsicKeyword() { this.word("intrinsic"); } export function TSThisType(this: Printer) { this.word("this"); } export function TSFunctionType(this: Printer, node: t.TSFunctionType) { this.tsPrintFunctionOrConstructorType(node); } export function TSConstructorType(this: Printer, node: t.TSConstructorType) { if (node.abstract) { this.word("abstract"); this.space(); } this.word("new"); this.space(); this.tsPrintFunctionOrConstructorType(node); } export function tsPrintFunctionOrConstructorType( this: Printer, // todo: missing type FunctionOrConstructorType node: any, ) { const { typeParameters, parameters } = node; this.print(typeParameters, node); this.token("("); this._parameters(parameters, node); this.token(")"); this.space(); this.token("=>"); this.space(); this.print(node.typeAnnotation.typeAnnotation, node); } export function TSTypeReference(this: Printer, node: t.TSTypeReference) { this.print(node.typeName, node); this.print(node.typeParameters, node); } export function TSTypePredicate(this: Printer, node: t.TSTypePredicate) { if (node.asserts) { this.word("asserts"); this.space(); } this.print(node.parameterName); if (node.typeAnnotation) { this.space(); this.word("is"); this.space(); this.print(node.typeAnnotation.typeAnnotation); } } export function TSTypeQuery(this: Printer, node: t.TSTypeQuery) { this.word("typeof"); this.space(); this.print(node.exprName); } export function TSTypeLiteral(this: Printer, node: t.TSTypeLiteral) { this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); } export function tsPrintTypeLiteralOrInterfaceBody( this: Printer, members, node, ) { this.tsPrintBraced(members, node); } export function tsPrintBraced(this: Printer, members, node) { this.token("{"); if (members.length) { this.indent(); this.newline(); for (const member of members) { this.print(member, node); //this.token(sep); this.newline(); } this.dedent(); this.rightBrace(); } else { this.token("}"); } } export function TSArrayType(this: Printer, node: t.TSArrayType) { this.print(node.elementType, node); this.token("[]"); } export function TSTupleType(this: Printer, node: t.TSTupleType) { this.token("["); this.printList(node.elementTypes, node); this.token("]"); } export function TSOptionalType(this: Printer, node: t.TSOptionalType) { this.print(node.typeAnnotation, node); this.token("?"); } export function TSRestType(this: Printer, node: t.TSRestType) { this.token("..."); this.print(node.typeAnnotation, node); } export function TSNamedTupleMember(this: Printer, node: t.TSNamedTupleMember) { this.print(node.label, node); if (node.optional) this.token("?"); this.token(":"); this.space(); this.print(node.elementType, node); } export function TSUnionType(this: Printer, node: t.TSUnionType) { this.tsPrintUnionOrIntersectionType(node, "|"); } export function TSIntersectionType(this: Printer, node: t.TSIntersectionType) { this.tsPrintUnionOrIntersectionType(node, "&"); } export function tsPrintUnionOrIntersectionType(this: Printer, node: any, sep) { this.printJoin(node.types, node, { separator() { this.space(); this.token(sep); this.space(); }, }); } export function TSConditionalType(this: Printer, node: t.TSConditionalType) { this.print(node.checkType); this.space(); this.word("extends"); this.space(); this.print(node.extendsType); this.space(); this.token("?"); this.space(); this.print(node.trueType); this.space(); this.token(":"); this.space(); this.print(node.falseType); } export function TSInferType(this: Printer, node: t.TSInferType) { this.token("infer"); this.space(); this.print(node.typeParameter); } export function TSParenthesizedType( this: Printer, node: t.TSParenthesizedType, ) { this.token("("); this.print(node.typeAnnotation, node); this.token(")"); } export function TSTypeOperator(this: Printer, node: t.TSTypeOperator) { this.word(node.operator); this.space(); this.print(node.typeAnnotation, node); } export function TSIndexedAccessType( this: Printer, node: t.TSIndexedAccessType, ) { this.print(node.objectType, node); this.token("["); this.print(node.indexType, node); this.token("]"); } export function TSMappedType(this: Printer, node: t.TSMappedType) { const { nameType, optional, readonly, typeParameter } = node; this.token("{"); this.space(); if (readonly) { tokenIfPlusMinus(this, readonly); this.word("readonly"); this.space(); } this.token("["); this.word( !process.env.BABEL_8_BREAKING ? (typeParameter.name as unknown as string) : (typeParameter.name as unknown as t.Identifier).name, ); this.space(); this.word("in"); this.space(); this.print(typeParameter.constraint, typeParameter); if (nameType) { this.space(); this.word("as"); this.space(); this.print(nameType, node); } this.token("]"); if (optional) { tokenIfPlusMinus(this, optional); this.token("?"); } this.token(":"); this.space(); this.print(node.typeAnnotation, node); this.space(); this.token("}"); } function tokenIfPlusMinus(self, tok) { if (tok !== true) { self.token(tok); } } export function TSLiteralType(this: Printer, node: t.TSLiteralType) { this.print(node.literal, node); } export function TSExpressionWithTypeArguments( this: Printer, node: t.TSExpressionWithTypeArguments, ) { this.print(node.expression, node); this.print(node.typeParameters, node); } export function TSInterfaceDeclaration( this: Printer, node: t.TSInterfaceDeclaration, ) { const { declare, id, typeParameters, extends: extendz, body } = node; if (declare) { this.word("declare"); this.space(); } this.word("interface"); this.space(); this.print(id, node); this.print(typeParameters, node); if (extendz?.length) { this.space(); this.word("extends"); this.space(); this.printList(extendz, node); } this.space(); this.print(body, node); } export function TSInterfaceBody(this: Printer, node: t.TSInterfaceBody) { this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); } export function TSTypeAliasDeclaration( this: Printer, node: t.TSTypeAliasDeclaration, ) { const { declare, id, typeParameters, typeAnnotation } = node; if (declare) { this.word("declare"); this.space(); } this.word("type"); this.space(); this.print(id, node); this.print(typeParameters, node); this.space(); this.token("="); this.space(); this.print(typeAnnotation, node); this.token(";"); } export function TSAsExpression(this: Printer, node: t.TSAsExpression) { const { expression, typeAnnotation } = node; this.print(expression, node); this.space(); this.word("as"); this.space(); this.print(typeAnnotation, node); } export function TSTypeAssertion(this: Printer, node: t.TSTypeAssertion) { const { typeAnnotation, expression } = node; this.token("<"); this.print(typeAnnotation, node); this.token(">"); this.space(); this.print(expression, node); } export function TSEnumDeclaration(this: Printer, node: t.TSEnumDeclaration) { const { declare, const: isConst, id, members } = node; if (declare) { this.word("declare"); this.space(); } if (isConst) { this.word("const"); this.space(); } this.word("enum"); this.space(); this.print(id, node); this.space(); this.tsPrintBraced(members, node); } export function TSEnumMember(this: Printer, node: t.TSEnumMember) { const { id, initializer } = node; this.print(id, node); if (initializer) { this.space(); this.token("="); this.space(); this.print(initializer, node); } this.token(","); } export function TSModuleDeclaration( this: Printer, node: t.TSModuleDeclaration, ) { const { declare, id } = node; if (declare) { this.word("declare"); this.space(); } if (!node.global) { this.word(id.type === "Identifier" ? "namespace" : "module"); this.space(); } this.print(id, node); if (!node.body) { this.token(";"); return; } let body = node.body; while (body.type === "TSModuleDeclaration") { this.token("."); this.print(body.id, body); body = body.body; } this.space(); this.print(body, node); } export function TSModuleBlock(this: Printer, node: t.TSModuleBlock) { this.tsPrintBraced(node.body, node); } export function TSImportType(this: Printer, node: t.TSImportType) { const { argument, qualifier, typeParameters } = node; this.word("import"); this.token("("); this.print(argument, node); this.token(")"); if (qualifier) { this.token("."); this.print(qualifier, node); } if (typeParameters) { this.print(typeParameters, node); } } export function TSImportEqualsDeclaration( this: Printer, node: t.TSImportEqualsDeclaration, ) { const { isExport, id, moduleReference } = node; if (isExport) { this.word("export"); this.space(); } this.word("import"); this.space(); this.print(id, node); this.space(); this.token("="); this.space(); this.print(moduleReference, node); this.token(";"); } export function TSExternalModuleReference( this: Printer, node: t.TSExternalModuleReference, ) { this.token("require("); this.print(node.expression, node); this.token(")"); } export function TSNonNullExpression( this: Printer, node: t.TSNonNullExpression, ) { this.print(node.expression, node); this.token("!"); } export function TSExportAssignment(this: Printer, node: t.TSExportAssignment) { this.word("export"); this.space(); this.token("="); this.space(); this.print(node.expression, node); this.token(";"); } export function TSNamespaceExportDeclaration( this: Printer, node: t.TSNamespaceExportDeclaration, ) { this.word("export"); this.space(); this.word("as"); this.space(); this.word("namespace"); this.space(); this.print(node.id, node); } export function tsPrintSignatureDeclarationBase(this: Printer, node: any) { const { typeParameters, parameters } = node; this.print(typeParameters, node); this.token("("); this._parameters(parameters, node); this.token(")"); this.print(node.typeAnnotation, node); } export function tsPrintClassMemberModifiers(this: Printer, node: any, isField) { if (isField && node.declare) { this.word("declare"); this.space(); } if (node.accessibility) { this.word(node.accessibility); this.space(); } if (node.static) { this.word("static"); this.space(); } if (node.override) { this.word("override"); this.space(); } if (node.abstract) { this.word("abstract"); this.space(); } if (isField && node.readonly) { this.word("readonly"); this.space(); } }
the_stack
import * as tf from '@tensorflow/tfjs-core'; import {InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor} from '@tensorflow/tfjs-core'; import * as tensorflow from '../data/compiled_api'; import {NamedTensorsMap, TensorInfo} from '../data/types'; import {getRegisteredOp, registerOp} from '../operations/custom_op/register'; import {OperationMapper} from '../operations/operation_mapper'; import {GraphExecutor} from './graph_executor'; export const TFHUB_SEARCH_PARAM = '?tfjs-format=file'; export const DEFAULT_MODEL_NAME = 'model.json'; /** * A `tf.GraphModel` is a directed, acyclic graph of built from * SavedModel GraphDef and allows inference exeuction. * * A `tf.GraphModel` can only be created by loading from a model converted from * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using * the command line converter tool and loaded via `tf.loadGraphModel`. */ /** @doc {heading: 'Models', subheading: 'Classes'} */ export class GraphModel implements InferenceModel { private executor: GraphExecutor; private version = 'n/a'; private handler: io.IOHandler; // Returns the version information for the tensorflow model GraphDef. get modelVersion(): string { return this.version; } get inputNodes(): string[] { return this.executor.inputNodes; } get outputNodes(): string[] { return this.executor.outputNodes; } get inputs(): TensorInfo[] { return this.executor.inputs; } get outputs(): TensorInfo[] { return this.executor.outputs; } get weights(): NamedTensorsMap { return this.executor.weightMap; } /** * @param modelUrl url for the model, or an `io.IOHandler`. * @param weightManifestUrl url for the weight file generated by * scripts/convert.py script. * @param requestOption options for Request, which allows to send credentials * and custom headers. * @param onProgress Optional, progress callback function, fired periodically * before the load is completed. */ constructor( private modelUrl: string|io.IOHandler, private loadOptions: io.LoadOptions = {}) { if (loadOptions == null) { this.loadOptions = {}; } } /** * There's no native PRelu op in TensorFlow, so Keras generates the following * structure which does the equivalent calculation: * f(x) = Relu(x) + (-alpha * Relu(-x)) * Since tfjs-core has a prelu op, this method will fuse the TensorFlow * generated ops into prelu op. It will also try to register a custom op that * supports prelu op. */ public fusePrelu() { this.executor.fusePrelu(); if (getRegisteredOp('Prelu') == null) { registerOp('Prelu', (node) => { const x = node.inputs[0]; const alpha = node.inputs[1]; return tf.prelu(x, alpha); }); } } private findIOHandler() { const path = this.modelUrl; if ((path as io.IOHandler).load != null) { // Path is an IO Handler. this.handler = path as io.IOHandler; } else if (this.loadOptions.requestInit != null) { this.handler = io.browserHTTPRequest(path as string, this.loadOptions); } else { const handlers = io.getLoadHandlers(path as string, this.loadOptions.onProgress); if (handlers.length === 0) { // For backward compatibility: if no load handler can be found, // assume it is a relative http path. handlers.push(io.browserHTTPRequest(path as string, this.loadOptions)); } else if (handlers.length > 1) { throw new Error( `Found more than one (${handlers.length}) load handlers for ` + `URL '${[path]}'`); } this.handler = handlers[0]; } } /** * Loads the model and weight files, construct the in memory weight map and * compile the inference graph. */ async load(): Promise<boolean> { this.findIOHandler(); if (this.handler.load == null) { throw new Error( 'Cannot proceed with model loading because the IOHandler provided ' + 'does not have the `load` method implemented.'); } const artifacts = await this.handler.load(); const graph = artifacts.modelTopology as tensorflow.IGraphDef; this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`; const weightMap = io.decodeWeights(artifacts.weightData, artifacts.weightSpecs); this.executor = new GraphExecutor(OperationMapper.Instance.transformGraph(graph)); this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap); return true; } /** * Execute the inference for the input tensors. * * @param input The input tensors, when there is single input for the model, * inputs param should be a `tf.Tensor`. For models with mutliple inputs, * inputs params should be in either `tf.Tensor`[] if the input order is * fixed, or otherwise NamedTensorMap format. * * For model with multiple inputs, we recommend you use NamedTensorMap as the * input type, if you use `tf.Tensor`[], the order of the array needs to * follow the * order of inputNodes array. @see {@link GraphModel.inputNodes} * * You can also feed any intermediate nodes using the NamedTensorMap as the * input type. For example, given the graph * InputNode => Intermediate => OutputNode, * you can execute the subgraph Intermediate => OutputNode by calling * model.execute('IntermediateNode' : tf.tensor(...)); * * This is useful for models that uses tf.dynamic_rnn, where the intermediate * state needs to be fed manually. * * For batch inference execution, the tensors for each input need to be * concatenated together. For example with mobilenet, the required input shape * is [1, 244, 244, 3], which represents the [batch, height, width, channel]. * If we are provide a batched data of 100 images, the input tensor should be * in the shape of [100, 244, 244, 3]. * * @param config Prediction configuration for specifying the batch size and * output node names. Currently the batch size option is ignored for graph * model. * * @returns Inference result tensors. The output would be single `tf.Tensor` * if model has single output node, otherwise Tensor[] or NamedTensorMap[] * will be returned for model with multiple outputs. */ /** @doc {heading: 'Models', subheading: 'Classes'} */ predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig): Tensor|Tensor[]|NamedTensorMap { return this.execute(inputs, this.outputNodes); } private normalizeInputs(inputs: Tensor|Tensor[]| NamedTensorMap): NamedTensorMap { if (!(inputs instanceof Tensor) && !Array.isArray(inputs)) { // The input is already a NamedTensorMap. return inputs; } inputs = Array.isArray(inputs) ? inputs : [inputs]; if (inputs.length !== this.inputNodes.length) { throw new Error( 'Input tensor count mismatch,' + `the graph model has ${this.inputNodes.length} placeholders, ` + `while there are ${inputs.length} input tensors.`); } return this.inputNodes.reduce((map, inputName, i) => { map[inputName] = (inputs as Tensor[])[i]; return map; }, {} as NamedTensorMap); } private normalizeOutputs(outputs: string|string[]): string[] { outputs = outputs || this.outputNodes; return !Array.isArray(outputs) ? [outputs] : outputs; } /** * Executes inference for the model for given input tensors. * @param inputs tensor, tensor array or tensor map of the inputs for the * model, keyed by the input node names. * @param outputs output node name from the Tensorflow model, if no * outputs are specified, the default outputs of the model would be used. * You can inspect intermediate nodes of the model by adding them to the * outputs array. * * @returns A single tensor if provided with a single output or no outputs * are provided and there is only one default output, otherwise return a * tensor array. The order of the tensor array is the same as the outputs * if provided, otherwise the order of outputNodes attribute of the model. */ /** @doc {heading: 'Models', subheading: 'Classes'} */ execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs?: string|string[]): Tensor|Tensor[] { inputs = this.normalizeInputs(inputs); outputs = this.normalizeOutputs(outputs); const result = this.executor.execute(inputs, outputs); return result.length > 1 ? result : result[0]; } /** * Executes inference for the model for given input tensors in async * fashion, use this method when your model contains control flow ops. * @param inputs tensor, tensor array or tensor map of the inputs for the * model, keyed by the input node names. * @param outputs output node name from the Tensorflow model, if no outputs * are specified, the default outputs of the model would be used. You can * inspect intermediate nodes of the model by adding them to the outputs * array. * * @returns A Promise of single tensor if provided with a single output or * no outputs are provided and there is only one default output, otherwise * return a tensor map. */ /** @doc {heading: 'Models', subheading: 'Classes'} */ async executeAsync( inputs: Tensor|Tensor[]|NamedTensorMap, outputs?: string|string[]): Promise<Tensor|Tensor[]> { inputs = this.normalizeInputs(inputs); outputs = this.normalizeOutputs(outputs); const result = await this.executor.executeAsync(inputs, outputs); return result.length > 1 ? result : result[0]; } private convertTensorMapToTensorsMap(map: NamedTensorMap): NamedTensorsMap { return Object.keys(map).reduce((newMap: NamedTensorsMap, key) => { newMap[key] = [map[key]]; return newMap; }, {}); } /** * Releases the memory used by the weight tensors. */ /** @doc {heading: 'Models', subheading: 'Classes'} */ dispose() { this.executor.dispose(); } } /** * Load a graph model given a URL to the model definition. * * Example of loading MobileNetV2 from a URL and making a prediction with a * zeros input: * * ```js * const modelUrl = * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json'; * const model = await tf.loadGraphModel(modelUrl); * const zeros = tf.zeros([1, 224, 224, 3]); * model.predict(zeros).print(); * ``` * * Example of loading MobileNetV2 from a TF Hub URL and making a prediction with * a zeros input: * * ```js * const modelUrl = * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2'; * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true}); * const zeros = tf.zeros([1, 224, 224, 3]); * model.predict(zeros).print(); * ``` * @param modelUrl The url or an `io.IOHandler` that loads the model. * @param options Options for the HTTP request, which allows to send credentials * and custom headers. */ /** @doc {heading: 'Models', subheading: 'Loading'} */ export async function loadGraphModel( modelUrl: string|io.IOHandler, options: io.LoadOptions = {}): Promise<GraphModel> { if (modelUrl == null) { throw new Error( 'modelUrl in loadGraphModel() cannot be null. Please provide a url ' + 'or an IOHandler that loads the model'); } if (options == null) { options = {}; } if (options.fromTFHub) { if ((modelUrl as io.IOHandler).load == null) { if (!(modelUrl as string).endsWith('/')) { modelUrl = (modelUrl as string) + '/'; } modelUrl = `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`; } } const model = new GraphModel(modelUrl, options); await model.load(); return model; }
the_stack
import { prop,propObject,propArray,required,maxLength,range } from "@rxweb/reactive-form-validators" import { gridColumn } from "@rxweb/grid" export class SpecItemBase { //#region specItemId Prop @prop() specItemId : number; //#endregion specItemId Prop //#region specificationDetailId Prop @range({minimumNumber:1,maximumNumber:2147483647}) @required() specificationDetailId : number; //#endregion specificationDetailId Prop //#region parentSpecItemId Prop @prop() parentSpecItemId : number; //#endregion parentSpecItemId Prop //#region componentId Prop @range({minimumNumber:1,maximumNumber:2147483647}) @required() componentId : number; //#endregion componentId Prop //#region name Prop @maxLength({value:4000}) name : string; //#endregion name Prop //#region identifier Prop @maxLength({value:4000}) identifier : string; //#endregion identifier Prop //#region prepress Prop @maxLength({value:4000}) prepress : string; //#endregion prepress Prop //#region proofs Prop @maxLength({value:4000}) proofs : string; //#endregion proofs Prop //#region proofsets Prop @prop() proofsets : number; //#endregion proofsets Prop //#region pages Prop @prop() pages : number; //#endregion pages Prop //#region qualityId Prop @prop() qualityId : any; //#endregion qualityId Prop //#region quantityFilm Prop @prop() quantityFilm : number; //#endregion quantityFilm Prop //#region quantitySamples Prop @prop() quantitySamples : number; //#endregion quantitySamples Prop //#region sizeWidthFinish Prop @prop() sizeWidthFinish : number; //#endregion sizeWidthFinish Prop //#region sizeLengthFinish Prop @prop() sizeLengthFinish : number; //#endregion sizeLengthFinish Prop //#region sizeWidthFlat Prop @prop() sizeWidthFlat : number; //#endregion sizeWidthFlat Prop //#region sizeLengthFlat Prop @prop() sizeLengthFlat : number; //#endregion sizeLengthFlat Prop //#region ink Prop @maxLength({value:4000}) ink : string; //#endregion ink Prop //#region inkLayoutId Prop @prop() inkLayoutId : any; //#endregion inkLayoutId Prop //#region inkInstructions Prop @maxLength({value:4000}) inkInstructions : string; //#endregion inkInstructions Prop //#region inkProcessIn1Pass Prop @prop() inkProcessIn1Pass : any; //#endregion inkProcessIn1Pass Prop //#region inkOil Prop @prop() inkOil : any; //#endregion inkOil Prop //#region inkRegistration Prop @prop() inkRegistration : any; //#endregion inkRegistration Prop //#region inkMatch Prop @prop() inkMatch : any; //#endregion inkMatch Prop //#region inkLaser Prop @prop() inkLaser : any; //#endregion inkLaser Prop //#region stockManufacturer Prop @maxLength({value:4000}) stockManufacturer : string; //#endregion stockManufacturer Prop //#region stockGrade Prop @maxLength({value:4000}) stockGrade : string; //#endregion stockGrade Prop //#region stockColor Prop @maxLength({value:4000}) stockColor : string; //#endregion stockColor Prop //#region stockBasisWeight Prop @prop() stockBasisWeight : number; //#endregion stockBasisWeight Prop //#region stockBasisWidth Prop @prop() stockBasisWidth : number; //#endregion stockBasisWidth Prop //#region stockBasisLength Prop @prop() stockBasisLength : number; //#endregion stockBasisLength Prop //#region stockInstructions Prop @maxLength({value:4000}) stockInstructions : string; //#endregion stockInstructions Prop //#region stockType Prop @maxLength({value:4000}) stockType : string; //#endregion stockType Prop //#region stockFinish Prop @maxLength({value:4000}) stockFinish : string; //#endregion stockFinish Prop //#region stockWaste Prop @prop() stockWaste : number; //#endregion stockWaste Prop //#region stockSubstitutes Prop @prop() stockSubstitutes : any; //#endregion stockSubstitutes Prop //#region stockRecycledPaper Prop @prop() stockRecycledPaper : any; //#endregion stockRecycledPaper Prop //#region envelopeStyle Prop @maxLength({value:4000}) envelopeStyle : string; //#endregion envelopeStyle Prop //#region envelopeWindows Prop @maxLength({value:4000}) envelopeWindows : string; //#endregion envelopeWindows Prop //#region envelopeMarks Prop @maxLength({value:4000}) envelopeMarks : string; //#endregion envelopeMarks Prop //#region envelopeOther Prop @maxLength({value:4000}) envelopeOther : string; //#endregion envelopeOther Prop //#region labelAdhesiveId Prop @prop() labelAdhesiveId : any; //#endregion labelAdhesiveId Prop //#region labelAdhesiveFormula Prop @maxLength({value:4000}) labelAdhesiveFormula : string; //#endregion labelAdhesiveFormula Prop //#region labelPerSheet Prop @prop() labelPerSheet : number; //#endregion labelPerSheet Prop //#region labelStyleId Prop @prop() labelStyleId : any; //#endregion labelStyleId Prop //#region labelLinerWidth Prop @prop() labelLinerWidth : number; //#endregion labelLinerWidth Prop //#region labelLinerLength Prop @prop() labelLinerLength : number; //#endregion labelLinerLength Prop //#region labelVerticalSpacing Prop @prop() labelVerticalSpacing : number; //#endregion labelVerticalSpacing Prop //#region labelHorizontalSpacing Prop @prop() labelHorizontalSpacing : number; //#endregion labelHorizontalSpacing Prop //#region labelShape Prop @maxLength({value:4000}) labelShape : string; //#endregion labelShape Prop //#region marginalWords Prop @maxLength({value:4000}) marginalWords : string; //#endregion marginalWords Prop //#region marginalWordColor Prop @maxLength({value:4000}) marginalWordColor : string; //#endregion marginalWordColor Prop //#region carbon Prop @maxLength({value:4000}) carbon : string; //#endregion carbon Prop //#region carbonColor Prop @maxLength({value:4000}) carbonColor : string; //#endregion carbonColor Prop //#region rollCoreDiameter Prop @prop() rollCoreDiameter : number; //#endregion rollCoreDiameter Prop //#region rollOutsideDiameter Prop @prop() rollOutsideDiameter : number; //#endregion rollOutsideDiameter Prop //#region rollOrientationId Prop @prop() rollOrientationId : any; //#endregion rollOrientationId Prop //#region rollWarningStripe Prop @prop() rollWarningStripe : any; //#endregion rollWarningStripe Prop //#region variableImage Prop @maxLength({value:4000}) variableImage : string; //#endregion variableImage Prop //#region perforate Prop @maxLength({value:4000}) perforate : string; //#endregion perforate Prop //#region score Prop @maxLength({value:4000}) score : string; //#endregion score Prop //#region fold Prop @maxLength({value:4000}) fold : string; //#endregion fold Prop //#region drill Prop @maxLength({value:4000}) drill : string; //#endregion drill Prop //#region numbering Prop @maxLength({value:4000}) numbering : string; //#endregion numbering Prop //#region diecut Prop @maxLength({value:4000}) diecut : string; //#endregion diecut Prop //#region productApp Prop @maxLength({value:4000}) productApp : string; //#endregion productApp Prop //#region tab Prop @maxLength({value:4000}) tab : string; //#endregion tab Prop //#region corner Prop @maxLength({value:4000}) corner : string; //#endregion corner Prop //#region emboss Prop @maxLength({value:4000}) emboss : string; //#endregion emboss Prop //#region foilStamp Prop @maxLength({value:4000}) foilStamp : string; //#endregion foilStamp Prop //#region coat Prop @maxLength({value:4000}) coat : string; //#endregion coat Prop //#region fasten Prop @maxLength({value:4000}) fasten : string; //#endregion fasten Prop //#region pad Prop @maxLength({value:4000}) pad : string; //#endregion pad Prop //#region bind Prop @maxLength({value:4000}) bind : string; //#endregion bind Prop //#region other Prop @maxLength({value:4000}) other : string; //#endregion other Prop //#region stockCaliper Prop @maxLength({value:4000}) stockCaliper : string; //#endregion stockCaliper Prop //#region staticInkTypeId Prop @prop() staticInkTypeId : any; //#endregion staticInkTypeId Prop //#region variableInkTypeId Prop @prop() variableInkTypeId : any; //#endregion variableInkTypeId Prop //#region componentList Prop @maxLength({value:4000}) componentList : string; //#endregion componentList Prop //#region insertionInstructions Prop @maxLength({value:4000}) insertionInstructions : string; //#endregion insertionInstructions Prop //#region specialInstructions Prop @maxLength({value:4000}) specialInstructions : string; //#endregion specialInstructions Prop //#region affixingInstructions Prop @maxLength({value:4000}) affixingInstructions : string; //#endregion affixingInstructions Prop //#region matchComponents Prop @prop() matchComponents : any; //#endregion matchComponents Prop //#region recordCount Prop @maxLength({value:4000}) recordCount : string; //#endregion recordCount Prop //#region mailTypeId Prop @maxLength({value:40}) mailTypeId : string; //#endregion mailTypeId Prop //#region mailFileName Prop @maxLength({value:4000}) mailFileName : string; //#endregion mailFileName Prop //#region seedListName Prop @maxLength({value:4000}) seedListName : string; //#endregion seedListName Prop //#region stateForeignSuppressions Prop @prop() stateForeignSuppressions : any; //#endregion stateForeignSuppressions Prop //#region suppressionFile Prop @maxLength({value:4000}) suppressionFile : string; //#endregion suppressionFile Prop //#region fileTransmissionMethod Prop @maxLength({value:4000}) fileTransmissionMethod : string; //#endregion fileTransmissionMethod Prop //#region totalFilesSubmitted Prop @maxLength({value:4000}) totalFilesSubmitted : string; //#endregion totalFilesSubmitted Prop //#region dataLayout Prop @maxLength({value:4000}) dataLayout : string; //#endregion dataLayout Prop //#region caseConversion Prop @prop() caseConversion : any; //#endregion caseConversion Prop //#region additionMailServices Prop @prop() additionMailServices : any; //#endregion additionMailServices Prop //#region mailForeign Prop @prop() mailForeign : any; //#endregion mailForeign Prop //#region mailInvalid Prop @prop() mailInvalid : any; //#endregion mailInvalid Prop //#region dedupe Prop @prop() dedupe : any; //#endregion dedupe Prop //#region cassDpvNcoa Prop @prop() cassDpvNcoa : any; //#endregion cassDpvNcoa Prop //#region household Prop @prop() household : any; //#endregion household Prop //#region simplexDuplexId Prop @prop() simplexDuplexId : number; //#endregion simplexDuplexId Prop //#region generalInstructions Prop @maxLength({value:4000}) generalInstructions : string; //#endregion generalInstructions Prop //#region preprintedStockProvided Prop @prop() preprintedStockProvided : any; //#endregion preprintedStockProvided Prop //#region preprintedStockDetails Prop @maxLength({value:4000}) preprintedStockDetails : string; //#endregion preprintedStockDetails Prop //#region stockRequirements Prop @maxLength({value:4000}) stockRequirements : string; //#endregion stockRequirements Prop //#region salutation Prop @maxLength({value:4000}) salutation : string; //#endregion salutation Prop //#region address Prop @maxLength({value:4000}) address : string; //#endregion address Prop //#region iMBBarcode Prop @prop() iMBBarcode : any; //#endregion iMBBarcode Prop //#region tipped Prop @prop() tipped : any; //#endregion tipped Prop //#region colorInkForTipping Prop @maxLength({value:4000}) colorInkForTipping : string; //#endregion colorInkForTipping Prop //#region rowId Prop @required() rowId : any; //#endregion rowId Prop //#region createdBy Prop @prop() createdBy : number; //#endregion createdBy Prop //#region createdDateTime Prop @prop() createdDateTime : any; //#endregion createdDateTime Prop //#region updatedBy Prop @prop() updatedBy : number; //#endregion updatedBy Prop //#region updatedDateTime Prop @prop() updatedDateTime : any; //#endregion updatedDateTime Prop }
the_stack
import React, { useEffect, useMemo, useState, useRef } from 'react'; import { useSelector } from 'react-redux'; import { Customizer, ICustomizations, ChoiceGroup, IChoiceGroupOption, PrimaryButton, DetailsList, IColumn, TextField, Dropdown, SelectionMode, DetailsListLayoutMode, FontIcon, CheckboxVisibility, IContextualMenuItem, CommandBar, Selection, Separator, IObjectWithKey, ActionButton } from "@fluentui/react"; import { getPrimaryGreyTheme, getPrimaryGreenTheme, getRightPaneDefaultButtonTheme, getGreenWithWhiteBackgroundTheme, getPrimaryBlueTheme, getDefaultTheme } from '../../../../common/themes'; import { FieldFormat, FieldType, IApplicationState, ITableRegion, ITableTag, ITag, TableElements, TagInputMode, TableVisualizationHint } from '../../../../models/applicationState'; import { filterFormat, getTagCategory, useDebounce } from "../../../../common/utils"; import { toast } from "react-toastify"; import "./tableTagConfig.scss"; import { interpolate, strings } from "../../../../common/strings"; import _ from "lodash"; interface ITableTagConfigProps { setTagInputMode: (addTableMode: TagInputMode, selectedTableTagToLabel?: ITableTag, selectedTableTagBody?: ITableRegion[][][]) => void; addTableTag: (table: any) => void; splitPaneWidth: number; tableTag?: ITableTag; reconfigureTableConfirm?: (originalTagName: string, tagName: string, tagType: FieldType.Array | FieldType.Object, tagFormat: FieldFormat, visualizationHint: TableVisualizationHint, deletedColumns: ITableConfigItem[], deletedRows: ITableConfigItem[], newRows: ITableConfigItem[], newColumns: ITableConfigItem[]) => void; selectedTableBody: ITableRegion[][][]; } interface ITableTagConfigState { rows?: ITableConfigItem[], columns: ITableConfigItem[], name: { tableName: string, originalTableName?: string; }, type: FieldType.Object | FieldType.Array, format: FieldFormat.NotSpecified, headerTypeAndFormat: TableElements.columns | TableElements.rows; originalName?: string; deletedRows?: ITableConfigItem[], deletedColumns?: ITableConfigItem[], } interface ITableConfigItem { name: string, format: string, type: string; originalName?: string; originalFormat?: string, originalType?: string; documentCount?: number } const tableFormatOptions: IChoiceGroupOption[] = [ { key: FieldType.Object, text: 'Fixed sized', iconProps: { iconName: 'Table' } }, { key: FieldType.Array, text: 'Row dynamic', iconProps: { iconName: 'InsertRowsBelow' } }, ]; const headersFormatAndTypeOptions: IChoiceGroupOption[] = [ { key: TableElements.columns, text: 'Column\n fields', iconProps: { iconName: 'TableHeaderRow' } }, { key: TableElements.rows, text: 'Row\n fields', iconProps: { iconName: 'TableFirstColumn' } }, ]; const dark: ICustomizations = { settings: { theme: getRightPaneDefaultButtonTheme(), }, scopedSettings: {}, }; const defaultTheme: ICustomizations = { settings: { theme: getDefaultTheme(), }, scopedSettings: {}, }; const formatOptions = (type = FieldType.String) => { const options = []; const formats = filterFormat(type) Object.entries(formats).forEach(([key, value]) => { options.push({ key, text: value }) }); return options; }; const typeOptions = () => { const options = []; Object.entries(FieldType).forEach(([key, value]) => { if (value !== FieldType.Object && value !== FieldType.Array) { options.push({ key, text: value }); } }); return options; }; const defaultRowOrColumn = { name: "", type: FieldType.String, format: FieldFormat.NotSpecified, documentCount: 0 }; /** * @name - Table tag configuration * @description - Configures table tag (assigns row's/column's headers and their respective data types and formats) */ export default function TableTagConfig(props: ITableTagConfigProps) { const { setTagInputMode = null, addTableTag = null, splitPaneWidth = null } = props; const containerWidth = splitPaneWidth > 520 ? splitPaneWidth - 10 : 510; const inputTableName = useRef(null); const lastColumnInputRef = useRef(null); const lastRowInputRef = useRef(null); // Initial state let table: ITableTagConfigState; if (props.tableTag) { if (props.tableTag?.type === FieldType.Object) { if (props.tableTag.visualizationHint === TableVisualizationHint.Vertical) { table = { name: { tableName: props.tableTag.name, originalTableName: props.tableTag.name }, type: FieldType.Object, format: FieldFormat.NotSpecified, rows: props.tableTag.fields?.map(row => ({ name: row.fieldKey, type: row.fieldType, format: row.fieldFormat, originalName: row.fieldKey, originalFormat: row.fieldFormat, originalType: row.fieldType })) || [defaultRowOrColumn], columns: props.tableTag?.definition?.fields?.map(col => ({ name: col.fieldKey, type: col.fieldType, format: col.fieldFormat, originalName: col.fieldKey, originalFormat: col.fieldFormat, originalType: col.fieldType })) || [defaultRowOrColumn], headerTypeAndFormat: TableElements.columns, deletedColumns: [], deletedRows: [], } } else { table = { name: { tableName: props.tableTag.name, originalTableName: props.tableTag.name }, type: FieldType.Object, format: FieldFormat.NotSpecified, rows: props.tableTag?.definition?.fields?.map(row => ({ name: row.fieldKey, type: row.fieldType, format: row.fieldFormat, originalName: row.fieldKey, originalFormat: row.fieldFormat, originalType: row.fieldType })) || [defaultRowOrColumn], columns: props.tableTag?.fields?.map(col => ({ name: col.fieldKey, type: col.fieldType, format: col.fieldFormat, originalName: col.fieldKey, originalFormat: col.fieldFormat, originalType: col.fieldType })) || [defaultRowOrColumn], headerTypeAndFormat: TableElements.rows, deletedColumns: [], deletedRows: [], } } } else { table = { name: { tableName: props.tableTag.name, originalTableName: props.tableTag.name }, type: FieldType.Array, format: FieldFormat.NotSpecified, rows: [defaultRowOrColumn], columns: props.tableTag?.definition?.fields?.map(col => ({ name: col.fieldKey, type: col.fieldType, format: col.fieldFormat, originalName: col.fieldKey, originalFormat: col.fieldFormat, originalType: col.fieldType })), headerTypeAndFormat: TableElements.columns, deletedColumns: [], } } } else { table = { name: { tableName: "" }, type: FieldType.Object, format: FieldFormat.NotSpecified, rows: [defaultRowOrColumn], columns: [defaultRowOrColumn], headerTypeAndFormat: TableElements.columns, }; } const currentProjectTags = useSelector<ITag[]>((state: IApplicationState) => state.currentProject.tags); const [tableTagName, setTableTagName] = useState(table.name); const [type, setType] = useState<FieldType.Object | FieldType.Array>(table.type); const [columns, setColumns] = useState(table.columns); const [rows, setRows] = useState<ITableConfigItem[]>(table.rows); const [notUniqueNames, setNotUniqueNames] = useState<{ columns: [], rows: [], tags: boolean }>({ columns: [], rows: [], tags: false }); const [headersFormatAndType, setHeadersFormatAndType] = useState<TableElements.columns | TableElements.rows>(table.headerTypeAndFormat); const [selectedColumn, setSelectedColumn] = useState<IObjectWithKey>(undefined); const [selectedRow, setSelectedRow] = useState<IObjectWithKey>(undefined); const [deletedColumns, setDeletedColumns] = useState(table.deletedColumns); const [deletedRows, setDeletedRows] = useState<ITableConfigItem[]>(table.deletedRows); // const [headerTypeAndFormat, setHeaderTypeAndFormat] = useState<string>(table.headerTypeAndFormat); const [shouldAutoFocus, setShouldAutoFocus] = useState(null); const isCompatibleWithType = (documentCount: number, type: string, newType: string) => { return documentCount <= 0 ? true : getTagCategory(type) === getTagCategory(newType); } function selectColumnType(idx: number, type: string, docCount: number) { setColumns(columns.map((col, currIdx) => { if (idx === currIdx) { if (isCompatibleWithType(docCount, col.originalType, type)) return { ...col, type, format: FieldFormat.NotSpecified } else { toast.warn(_.capitalize(interpolate(strings.tags.regionTableTags.configureTag.errors.notCompatibleTableColOrRowType, { kind: "column" }))); return col; } } else { return col } })); } function selectRowType(idx: number, type: string, docCount: number) { setRows(rows.map((row, currIdx) => { if (idx === currIdx) { if (isCompatibleWithType(docCount, row.originalType, type)) return { ...row, type, format: FieldFormat.NotSpecified } else { toast.warn(_.capitalize(interpolate(strings.tags.regionTableTags.configureTag.errors.notCompatibleTableColOrRowType, { kind: "row" }))); return row; } } else { return row } })); } function selectColumnFormat(idx: number, format: string) { setColumns(columns.map((col, currIdx) => idx === currIdx ? { ...col, format } : col )); } function selectRowFormat(idx: number, format: string) { setRows(rows.map((row, currIdx) => idx === currIdx ? { ...row, format } : row )); } const detailListWidth = { nameInput: containerWidth * 0.45, typeInput: containerWidth * 0.176, formatInput: containerWidth * 0.176, } const columnListColumns: IColumn[] = [ { key: "name", name: "name", fieldName: "name", minWidth: detailListWidth.nameInput, isResizable: false, onRender: (row, index) => { return ( <TextField componentRef={(index === columns.length - 1 && index !== 0) ? lastColumnInputRef : null} className={"column-name_input"} theme={getGreenWithWhiteBackgroundTheme()} onChange={(e) => handleTextInput(e.target["value"], TableElements.column, index)} value={row.name} errorMessage={getTextInputError(notUniqueNames.columns, row.name.trim(), index)} onRenderLabel={() => { return row.originalName ? <div className={"input-label-original-name original-value"}> Original name: {row.originalName} </div> : null; }} /> ) }, }, { key: "type", name: "type", fieldName: "type", minWidth: detailListWidth.typeInput, isResizable: false, onRender: (row, index) => headersFormatAndType === TableElements.columns ? <Customizer {...defaultTheme}> <Dropdown style={{ marginTop: 16 }} className="type_dropdown" placeholder={row.type} defaultSelectedKey={FieldType.String} options={typeOptions()} theme={getGreenWithWhiteBackgroundTheme()} onChange={(e, val) => selectColumnType(index, val.text, row.documentCount)} /> </Customizer> : <></> }, { key: "format", name: "format", fieldName: "format", minWidth: detailListWidth.formatInput, isResizable: false, onRender: (row, index) => headersFormatAndType === TableElements.columns ? <Customizer {...defaultTheme}> <Dropdown style={{ marginTop: 16 }} className="format_dropdown" placeholder={row.format} selectedKey={row.format} options={formatOptions(row.type)} theme={getGreenWithWhiteBackgroundTheme()} onChange={(e, val) => { selectColumnFormat(index, val.text); }} /> </Customizer> : <></> }, ]; const rowListColumns: IColumn[] = [ { key: "name", name: "name", fieldName: "name", minWidth: detailListWidth.nameInput, isResizable: false, onRender: (row, index) => { return ( <TextField componentRef={(index === rows.length - 1 && index !== 0) ? lastRowInputRef : null} className="row-name_input" theme={getGreenWithWhiteBackgroundTheme()} onChange={(e) => handleTextInput(e.target["value"], TableElements.row, index)} value={row.name} errorMessage={getTextInputError(notUniqueNames.rows, row.name, index)} onRenderLabel={() => { return row.originalName ? <div className={"input-label-original-name original-value"}> Original name: {row.originalName} </div> : null; }} /> ) }, }, { key: "type", name: "type", fieldName: "type", minWidth: detailListWidth.typeInput, isResizable: false, onRender: (row, index) => headersFormatAndType === TableElements.rows ? <Customizer {...defaultTheme}> <Dropdown className="type_dropdown" style={{ marginTop: 16 }} placeholder={row.type} defaultSelectedKey={FieldType.String} options={typeOptions()} theme={getGreenWithWhiteBackgroundTheme()} onChange={(e, val) => selectRowType(index, val.text, row.documentCount)} /> </Customizer> : <></> }, { key: "format", name: "format", fieldName: "format", minWidth: detailListWidth.formatInput, isResizable: false, onRender: (row, index) => headersFormatAndType === TableElements.rows ? <Customizer {...defaultTheme}> <Dropdown className="format_dropdown" style={{ marginTop: 16 }} placeholder={row.format} selectedKey={row.format} options={formatOptions(row.type)} theme={getGreenWithWhiteBackgroundTheme()} onChange={(e, val) => { selectRowFormat(index, val.text); }} /> </Customizer> : <></> }, ]; function addColumn() { setColumns([...columns, defaultRowOrColumn]); setShouldAutoFocus(TableElements.column); } function addRow() { setRows([...rows, defaultRowOrColumn]); setShouldAutoFocus(TableElements.row); } function handleTextInput(name: string, role: string, index: number) { if (role === TableElements.column) { setColumns( columns.map((column, currIndex) => (index === currIndex) ? { ...column, name } : column) ); } else { setRows( rows.map((row, currIndex) => (index === currIndex) ? { ...row, name } : row) ); }; } function setTableName(name: string) { setTableTagName({ ...tableTagName, tableName: name }); } // Row/Column headers command bar (reorder, delete) function getRowsHeaderItems(): IContextualMenuItem[] { const currSelectionIndex = rowSelection.getSelectedIndices()[0]; return [ { key: 'Name', text: 'Name', className: "list-headers_name", style: { width: detailListWidth.nameInput - 122 }, disabled: true, }, { key: 'moveUp', text: 'Move up', iconOnly: true, iconProps: { iconName: 'Up' }, onClick: (e) => { onReOrder(-1, TableElements.rows) }, disabled: !selectedRow || currSelectionIndex === 0, }, { key: 'moveDown', text: 'Move down', iconOnly: true, iconProps: { iconName: 'Down' }, onClick: (e) => { onReOrder(1, TableElements.rows) }, disabled: !selectedRow! || currSelectionIndex === rows.length - 1, }, { key: 'deleteRow', text: 'Delete row', iconOnly: true, iconProps: { iconName: 'Delete' }, onClick: () => { const selectedRowIndex = rowSelection.getSelectedIndices()[0]; if (props.tableTag && rows[selectedRowIndex].originalName) { const deletedRow = Object.assign({}, rows[selectedRowIndex]); deletedRow.name = deletedRow.originalName; deletedRow.format = deletedRow.originalFormat; deletedRow.type = deletedRow.originalType; setDeletedRows([...deletedRows, deletedRow]); } setRows(rows.filter((i, idx) => idx !== rowSelection.getSelectedIndices()[0])) }, disabled: !selectedRow! || rows.length === 1, }, { key: 'type', text: 'Type', className: "list-headers_type", style: { width: detailListWidth.typeInput }, disabled: true, }, { key: 'format', text: 'Format', className: "list-headers_format", disabled: true, }, ]; }; function getColumnsHeaderItems(): IContextualMenuItem[] { const currSelectionIndex = columnSelection.getSelectedIndices()[0]; return [ { key: 'Name', text: 'Name', className: "list-headers_name", style: { width: detailListWidth.nameInput - 120 }, disabled: true, resizable: true, }, { key: 'moveUp', text: 'Move up', iconOnly: true, iconProps: { iconName: 'Up' }, onClick: (e) => { onReOrder(-1, TableElements.columns) }, disabled: !selectedColumn || currSelectionIndex === 0, }, { key: 'moveDown', text: 'Move down', iconOnly: true, iconProps: { iconName: 'Down' }, onClick: (e) => { onReOrder(1, TableElements.columns) }, disabled: !selectedColumn || currSelectionIndex === columns.length - 1, }, { key: 'deleteColumn', text: 'Delete column', iconOnly: true, iconProps: { iconName: 'Delete', }, onClick: () => { const selectedColumnIndex = columnSelection.getSelectedIndices()[0]; if (props.tableTag && columns[selectedColumnIndex].originalName) { const deletedColumn = Object.assign({}, columns[selectedColumnIndex]); deletedColumn.name = deletedColumn.originalName deletedColumn.format = deletedColumn.originalFormat; deletedColumn.type = deletedColumn.originalType; setDeletedColumns([...deletedColumns, deletedColumn]) } setColumns(columns.filter((i, idx) => idx !== selectedColumnIndex)); }, disabled: !selectedColumn || columns.length === 1, }, { key: 'type', text: 'Type', className: "list-headers_type", style: { width: detailListWidth.typeInput }, disabled: true, }, { key: 'format', text: 'Format', className: "list-headers_format", disabled: true, }, ]; }; // Validation // function getTextInputError(array: any[], rowName: string, index: number) { if (!rowName?.length) { return strings.tags.regionTableTags.configureTag.errors.emptyName } else if (array.length && array.findIndex((item) => (item === index)) !== -1) { return strings.tags.regionTableTags.configureTag.errors.notUniqueName; } else { return undefined; } }; function checkNameUniqueness(array: ITableConfigItem[], arrayName: string) { const namesMap = {}; let notUniques = []; array.forEach((item, idx) => { if (item.name && item.name.length) { const name = item.name.trim(); namesMap[name] = namesMap[name] || []; namesMap[name].push(idx) } }); for (const name in namesMap) { if (namesMap[name].length > 1) { notUniques = namesMap[name]; } } setNotUniqueNames({ ...notUniqueNames, [arrayName]: notUniques }) } // Check names uniqueness for rows and columns as you type , with a delay const delay = 400; const debouncedColumns = useDebounce(columns, delay); const debouncedRows = useDebounce(rows, delay); useEffect(() => { if (columns) { checkNameUniqueness(debouncedColumns, TableElements.columns) } // eslint-disable-next-line }, [debouncedColumns]); useEffect(() => { if (rows) { checkNameUniqueness(debouncedRows, TableElements.rows); } // eslint-disable-next-line }, [debouncedRows]); // Check tableName uniqueness as type const debouncedTableTagName = useDebounce(tableTagName, delay); useEffect(() => { if (tableTagName) { const existingTagName = currentProjectTags.find((item: ITag) => item.name === tableTagName.tableName.trim()); setNotUniqueNames({ ...notUniqueNames, tags: existingTagName !== undefined ? true : false }) } // eslint-disable-next-line }, [debouncedTableTagName, currentProjectTags]); function trimFieldNames(array: ITableConfigItem[]) { return array.map(i => ({ ...i, name: i.name.trim() })); } function save(cleanTableName: string, cleanRows: ITableConfigItem[], cleanColumns: ITableConfigItem[]) { const [firstLayerFieldsInput, secondLayerFieldsInput] = getFieldsLayersInput(headersFormatAndType, cleanRows, cleanColumns); const definition = getDefinitionLayer(cleanTableName, secondLayerFieldsInput); const fieldsLayer = getFieldsLayer(cleanTableName, firstLayerFieldsInput); const itemType = getItemType(cleanTableName); const visualizationHint = getVisualizationHint(headersFormatAndType); const tableTagToAdd = { name: cleanTableName, type, columns: cleanColumns, format: FieldFormat.NotSpecified, itemType, fields: fieldsLayer, definition, visualizationHint, } if (type === FieldType.Object) { tableTagToAdd[TableElements.rows] = cleanRows; } addTableTag(tableTagToAdd); setTagInputMode(TagInputMode.Basic, null, null); toast.success(`Successfully ${props.tableTag ? "reconfigured" : "saved"} "${tableTagName.tableName}" table tag.`, { autoClose: 8000 }); } function getItemType(cleanTableName) { if (type === FieldType.Object) { return null; } else { return cleanTableName + "_object"; } } function getFieldsLayersInput(headersFormatAndType, cleanRows, cleanColumns) { if (type === FieldType.Object) { if (headersFormatAndType === TableElements.columns) { return [cleanRows, cleanColumns]; } else { return [cleanColumns, cleanRows]; } } else { return [cleanRows, cleanColumns]; } } function getDefinitionLayer(cleanTableName, secondLayerFieldsInput) { return { fieldKey: cleanTableName + "_object", fieldType: FieldType.Object, fieldFormat: FieldFormat.NotSpecified, itemType: null, fields: secondLayerFieldsInput.map((field) => { return { fieldKey: field.name, fieldType: field.type, fieldFormat: field.format, itemType: null, fields: null, } }) } } function getVisualizationHint(headersFormatAndType) { if (type === FieldType.Object) { if (headersFormatAndType === TableElements.columns) { return TableVisualizationHint.Vertical; } else { return TableVisualizationHint.Horizontal; } } else { return null; } } function getFieldsLayer(cleanTableName, firstLayerFieldsInput) { if (type === FieldType.Object) { return firstLayerFieldsInput.map((field) => { return { fieldKey: field.name, fieldType: cleanTableName + "_object", fieldFormat: FieldFormat.NotSpecified, itemType: null, fields: null, } }); } else { return null; } } function hasEmptyNames(array: ITableConfigItem[]) { return array.find((i) => !i.name.length) !== undefined ? true : false } function getCleanTable() { let cleanRows = rows; let cleanColumns = columns; if (headersFormatAndType === TableElements.columns) { cleanRows = rows.map((row) => { return { ...row, type: FieldType.String, format: FieldFormat.NotSpecified, } }); } else if (headersFormatAndType === TableElements.rows) { cleanColumns = columns.map((col) => ({ ...col, type: FieldType.String, format: FieldFormat.NotSpecified })); } cleanColumns = trimFieldNames(columns); if (type === FieldType.Object) { cleanRows = trimFieldNames(rows); } const cleanTableName = tableTagName.tableName.trim(); // const cleanOriginalTableName = tableTagName?.originalTableName?.trim(); return { cleanTableName, cleanRows, cleanColumns }; } function validateInput() { return !( notUniqueNames.rows.length > 0 || notUniqueNames.columns.length > 0 || (props.tableTag && notUniqueNames.tags && (tableTagName.tableName !== tableTagName.originalTableName)) || (notUniqueNames.tags && !props.tableTag) || !tableTagName.tableName.length || hasEmptyNames(columns) || (type === FieldType.Object && hasEmptyNames(rows)) ); } // Row selection const rowSelection = useMemo(() => new Selection({ onSelectionChanged: () => { setSelectedRow(rowSelection.getSelection()[0]) }, selectionMode: SelectionMode.single, }), [] ); const columnSelection = useMemo(() => new Selection({ onSelectionChanged: () => { setSelectedColumn(columnSelection.getSelection()[0]) }, selectionMode: SelectionMode.single, }), [] ); // Reorder items function onReOrder(displacement: number, role: string) { const items = role === TableElements.rows ? [...rows] : [...columns]; const selection = role === TableElements.rows ? rowSelection : columnSelection; const selectedIndex = selection.getSelectedIndices()[0]; const itemToBeMoved = items[selectedIndex]; const newIndex = selectedIndex + displacement; if (newIndex < 0 || newIndex > items.length - 1) { return; } items.splice(selectedIndex, 1); items.splice(newIndex, 0, itemToBeMoved); if (role === TableElements.rows) { rowSelection.setIndexSelected(newIndex, true, false); setRows(items); } else { columnSelection.setIndexSelected(newIndex, true, true); setColumns(items); } } function restoreDeletedField(fieldType: TableElements, index: number) { let fields; let deletedFields; let setFields; let setDeletedFields; switch (fieldType) { case TableElements.row: fields = rows; deletedFields = [...deletedRows]; setFields = setRows; setDeletedFields = setDeletedRows; break; case TableElements.column: fields = columns; deletedFields = [...deletedColumns]; setFields = setColumns; setDeletedFields = setDeletedColumns; break; } setFields([...fields, deletedFields[index]]); setDeletedFields([...deletedFields].slice(0, index).concat([...deletedFields].slice(index + 1, deletedFields.length))); } function getDeletedFieldsTable(fieldType: TableElements) { let deletedFields; switch (fieldType) { case TableElements.row: deletedFields = deletedRows; break; case TableElements.column: deletedFields = deletedColumns; break; } const tableBody = [[ <tr className="compact-row" key={"row-h"}> <th key={"row-h-0"} className=""> <div className="mr-4"> {fieldType.charAt(0).toUpperCase() + fieldType.slice(1) + " fields that'll be deleted"} </div> </th> <th key={"row-h-1"} className=""></th> </tr> ]]; for (let i = 0; i < deletedFields.length; i++) { tableBody.push([ <tr className="compact-row" key={`row-${i}`}> <td key={`cell-${i}-0`} className=""> <div className="flex-center"> {deletedFields[i].originalName} </div> </td> <td key={`cell-${i}-1`} className=""> <ActionButton className="restore-button flex-center" onClick={() => { restoreDeletedField(fieldType, i) }}> <FontIcon className="restore-icon mr-1" iconName="UpdateRestore" /> Restore </ActionButton> </td> </tr> ]) } return tableBody; } // Table preview function getTableBody() { let tableBody = null; const isRowDynamic = type === FieldType.Array; if (table.rows.length !== 0 && table.columns.length !== 0) { tableBody = []; for (let i = 0; i < (isRowDynamic ? 2 : rows.length + 1); i++) { const tableRow = []; for (let j = 0; j < columns.length + 1; j++) { if (i === 0 && j !== 0) { const columnHeaderWasRenamed = props.tableTag && columns[j - 1].name !== columns[j - 1].originalName; tableRow.push( <th key={`col-h-${j}`} className="header_column"> {columnHeaderWasRenamed && <div className="renamed-value">{columns[j - 1].originalName}</div> } <div className="original-value"> {columns[j - 1].name} </div> </th>); } else if (j === 0 && i !== 0) { if (!isRowDynamic) { const rowHeaderWasRenamed = props.tableTag && rows[i - 1].name !== rows[i - 1].originalName; tableRow.push( <th key={`row-h-${j}`} className="header_row"> {rowHeaderWasRenamed && <div className="renamed-value"> {rows[i - 1].originalName} </div> } <div className="original-value"> {rows[i - 1].name} </div> </th> ); } } else if (j === 0 && i === 0) { if (!isRowDynamic) { tableRow.push(<th key={"ignore"} className="header_empty" ></th>); } } else { tableRow.push(<td key={`cell-${i}-${j}`} className="table-cell" />); } } tableBody.push(<tr key={`row-${i}`}>{tableRow}</tr>); } } return tableBody }; function getTableTagNameErrorMessage(): string { if (props.tableTag && tableTagName.tableName.trim() === props.tableTag.name) { return ""; } else if (!tableTagName.tableName.trim().length) { return strings.tags.regionTableTags.configureTag.errors.assignTagName } else if (notUniqueNames.tags) { return strings.tags.regionTableTags.configureTag.errors.notUniqueTagName; } return ""; } const [tableChanged, setTableChanged] = useState<boolean>(false); useEffect(() => { setTableChanged( (_.isEqual(columns, table.columns) && _.isEqual(rows, table.rows)) ? false : true) }, [columns, rows, table.columns, table.rows]); // Focus once on table name input when the component loads useEffect(() => { inputTableName.current.focus(); }, []); // Sets focus on last added input useEffect(() => { if (shouldAutoFocus === TableElements.column && lastColumnInputRef.current) { lastColumnInputRef.current.focus(); } else if (shouldAutoFocus === TableElements.row && lastRowInputRef.current) { lastRowInputRef.current.focus(); } setShouldAutoFocus(null); }, [shouldAutoFocus]); // Render return ( <Customizer {...dark}> <div className="config-view_container"> <h4 className="header mt-2">{props.tableTag ? "Reconfigure table tag" : "Configure table tag"}</h4> <a className="document-link mb-1" href="https://aka.ms/form-recognizer/docs/table-labeling" target="_blnck" rel="noopeber bireferrer">Learn more about how to use table tags.</a> <h5 className="mt-3 mb-1">Name</h5> {tableTagName.originalTableName && <div className={"original-table-name"}> Original name: {tableTagName.originalTableName} </div> } <TextField componentRef={inputTableName} className="table-name_input ml-12px" theme={getGreenWithWhiteBackgroundTheme()} onChange={(event) => setTableName(event.target["value"])} value={tableTagName.tableName} errorMessage={getTableTagNameErrorMessage()} /> {!props.tableTag && <> <h5 className="mt-4">Type</h5> <ChoiceGroup className="ml-12px" onChange={(event, option) => { if (option.key === FieldType.Object) { setType(FieldType.Object); } else { setType(FieldType.Array) setHeadersFormatAndType(TableElements.columns); } }} defaultSelectedKey={FieldType.Object} options={tableFormatOptions} theme={getRightPaneDefaultButtonTheme()} /> {type === FieldType.Object && <> <h5 className="mt-4" >Configure type and format for:</h5> <ChoiceGroup className="ml-12px type-format" defaultSelectedKey={TableElements.columns} options={headersFormatAndTypeOptions} onChange={(e, option) => { if (option.key === TableElements.columns) { setHeadersFormatAndType(TableElements.columns) } else { setHeadersFormatAndType(TableElements.rows) } }} required={false} /> </> } </> } <div className="columns_container mb-4 ml-12px"> <h5 className="mt-3">Column fields</h5> <div className="columns-list_container"> <DetailsList className="columns" items={columns} columns={columnListColumns} isHeaderVisible={true} theme={getRightPaneDefaultButtonTheme()} compact={false} setKey="none" selection={columnSelection} layoutMode={DetailsListLayoutMode.justified} checkboxVisibility={CheckboxVisibility.always} onRenderDetailsHeader={() => ( <div className="list_header"> <CommandBar items={getColumnsHeaderItems()} /> <Separator styles={{ root: { height: 2, padding: 0 } }} /> </div> )} /> </div> <PrimaryButton theme={getPrimaryBlueTheme()} className="add_button ml-12px" onClick={addColumn}> <FontIcon iconName="Add" className="mr-2" /> Add column </PrimaryButton> {deletedColumns?.length > 0 && <div className="mt-3"> <table className=""> <tbody> {getDeletedFieldsTable(TableElements.column)} </tbody> </table> </div> } </div> {((props.tableTag?.type === FieldType.Object) || type === FieldType.Object) && <div className="rows_container mb-4 ml-12px"> <h5 className="">Row fields</h5> <div className="rows-list_container"> <DetailsList className="rows" items={rows} columns={rowListColumns} isHeaderVisible={true} theme={getRightPaneDefaultButtonTheme()} compact={false} setKey="none" selection={rowSelection} layoutMode={DetailsListLayoutMode.justified} checkboxVisibility={CheckboxVisibility.always} selectionPreservedOnEmptyClick={true} onRenderDetailsHeader={() => ( <div className="list_header"> <CommandBar items={getRowsHeaderItems()} /> <Separator styles={{ root: { height: 2, padding: 0 } }} /> </div> )} /> </div> <PrimaryButton theme={getPrimaryBlueTheme()} className="add_button" onClick={addRow}> <FontIcon iconName="Add" className="mr-2" /> Add row </PrimaryButton> {deletedRows?.length > 0 && <div className="mt-3"> <table className=""> <tbody> {getDeletedFieldsTable(TableElements.row)} </tbody> </table> </div> } </div> } { (tableChanged || props.tableTag) && <div className="preview_container ml-12px"> <h5 className="mt-3 mb-1">Preview</h5> {tableTagName.tableName && <> {props.tableTag && tableTagName.originalTableName !== tableTagName.tableName && <div className="tableName-original original-value"> Table name: {tableTagName.originalTableName} </div> } <span className="tableName-current" style={{ borderBottom: props.tableTag ? `4px solid ${props.tableTag.color}` : null }}> <span>Table name: </span> <span className="table-name-preview">{tableTagName.tableName}</span> </span> </> } { type === FieldType.Array && <div className="rowDynamic_message">The number of rows is specified when labeling each document.</div> } <div className="table_container"> <table className="table"> <tbody> {getTableBody()} </tbody> </table> </div> </div> } <div className="control-buttons_container"> <PrimaryButton className="cancel" theme={getPrimaryGreyTheme()} onClick={() => { if (props.tableTag) { if (props.selectedTableBody) { if (!props.selectedTableBody[0].length || props.selectedTableBody.length !== 0) setTagInputMode(TagInputMode.LabelTable, props.tableTag, props.selectedTableBody); } else { setTagInputMode(TagInputMode.Basic, null, null); } } else { setTagInputMode(TagInputMode.Basic, null, null); } }}>Cancel</PrimaryButton> <PrimaryButton className="save" theme={getPrimaryGreenTheme()} onClick={() => { if (!validateInput()) { toast.error(strings.tags.regionTableTags.configureTag.errors.checkFields, { autoClose: 8000 }); return; } else { const { cleanTableName, cleanRows, cleanColumns } = getCleanTable(); if (props.tableTag) { const tableTagToReconfigure = { name: cleanTableName, columns: cleanColumns, deletedColumns, headersFormatAndType, visualizationHint: props.tableTag.visualizationHint, } if (type === FieldType.Object) { tableTagToReconfigure[TableElements.rows] = cleanRows; tableTagToReconfigure["deletedRows"] = deletedRows; tableTagToReconfigure["type"] = FieldType.Object; } else { tableTagToReconfigure[TableElements.rows] = null; tableTagToReconfigure["deletedRows"] = null; tableTagToReconfigure["type"] = FieldType.Array; } props.reconfigureTableConfirm(tableTagName?.originalTableName?.trim(), tableTagName?.tableName?.trim(), tableTagToReconfigure["type"], tableTagToReconfigure["format"], tableTagToReconfigure.visualizationHint, deletedColumns, deletedRows, tableTagToReconfigure["rows"], tableTagToReconfigure.columns); } else { save(cleanTableName, cleanRows, cleanColumns); } } } }>Save</PrimaryButton> </div> </div> </Customizer> ); };
the_stack
import { ColorHSV, ColorRGBA64, hsvToRGB, parseColor, rgbToHSV, } from "@microsoft/fast-colors"; import { attr, DOM, observable } from "@microsoft/fast-element"; import { isNullOrWhiteSpace } from "@microsoft/fast-web-utilities"; import { FormAssociatedColorPicker } from "./color-picker.form-associated"; /** * This is currently experimental, any use of the color picker must include the following * imports and register with the DesignSystem * * import { fastTextField } from "@microsoft/fast-components"; * import { DesignSystem } from "@microsoft/fast-foundation"; * DesignSystem.getOrCreate().register(fastTextField()); */ /** * Simple class for storing all of the color picker UI observable values. */ class ColorPickerUI { public RGBColor: ColorRGBA64; public HSVColor: ColorHSV; public HueCSSColor: string; public HuePosition: number; public SatValTopPos: number; public SatValLeftPos: number; public AlphaPos: number; constructor(rgbColor: ColorRGBA64, hsvColor: ColorHSV) { this.RGBColor = rgbColor; this.HSVColor = hsvColor; this.HueCSSColor = hsvToRGB(new ColorHSV(this.HSVColor.h, 1, 1)).toStringHexRGB(); this.HuePosition = (this.HSVColor.h / 360) * 100; this.SatValLeftPos = this.HSVColor.s * 100; this.SatValTopPos = 100 - this.HSVColor.v * 100; this.AlphaPos = this.RGBColor.a * 100; } } /** * A Color Picker Custom HTML Element. * * @public */ export class ColorPicker extends FormAssociatedColorPicker { /** * When true, the control will be immutable by user interaction. See {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly | readonly HTML attribute} for more information. * @public * @remarks * HTML Attribute: readonly */ @attr({ attribute: "readonly", mode: "boolean" }) public readOnly: boolean; private readOnlyChanged(): void { if (this.proxy instanceof HTMLElement) { this.proxy.readOnly = this.readOnly; } } /** * Indicates that this element should get focus after the page finishes loading. See {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautofocus | autofocus HTML attribute} for more information. * @public * @remarks * HTML Attribute: autofocus */ @attr({ mode: "boolean" }) public autofocus: boolean; private autofocusChanged(): void { if (this.proxy instanceof HTMLElement) { this.proxy.autofocus = this.autofocus; } } /** * Sets the placeholder value of the element, generally used to provide a hint to the user. * @public * @remarks * HTML Attribute: placeholder * Using this attribute does is not a valid substitute for a labeling element. */ @attr public placeholder: string; private placeholderChanged(): void { if (this.proxy instanceof HTMLElement) { this.proxy.placeholder = this.placeholder; } } /** * Flag indicating that the color UI is visible. */ @observable public open: boolean; /** * Flag indicating that the color UI is activily listening for mouse move and up events. */ @observable public mouseActive: boolean = false; /** * Object containing all of the properties displayed in the color picker UI. */ @observable public uiValues: ColorPickerUI = new ColorPickerUI( new ColorRGBA64(1, 0, 0), new ColorHSV(0, 1, 1) ); /** * A reference to the internal input element * @internal */ public control: HTMLInputElement; /** * A reference to the HTMLElement that is the current target of mouse move events. */ private currentMouseTarget: HTMLElement = null; /** * A string indicating which of the three graphical elements is the current mouse target. ['sv','h','a'] */ private currentMouseParam: string; /** * The ColorRGBA64 representation of the current color value. */ private currentRGBColor: ColorRGBA64; /** * The ColorHSV representation of the current color value. */ private currentHSVColor: ColorHSV; /** * @internal */ public connectedCallback(): void { super.connectedCallback(); this.open = false; this.initColorValues(); this.proxy.setAttribute("type", "color"); if (this.autofocus) { DOM.queueUpdate(() => { this.focus(); }); } } /** * Handles the focus event. When the template has focus the color UI will be visable. * @internal */ public handleFocus(): void { // Re-init colors in case the value changed externally since the UI was last visible. this.initColorValues(); this.open = true; } /** * Handles the blur event. Hides the color UI when the template loses focus. * @internal */ public handleBlur(): void { this.open = false; } /** * Handles the internal control's `input` event. This event is fired whenever a user types directly into the primary text field. * @internal */ public handleTextInput(): void { this.initialValue = this.control.value; if (this.isValideCSSColor(this.value)) { this.currentRGBColor = parseColor(this.value); this.currentHSVColor = rgbToHSV(this.currentRGBColor); this.updateUIValues(false); this.$emit("change"); } } /** * Handles the mouse down event on the Sat/Val square and Hue and Alpha sliders. Sets the current targeted element and begins listening for mouse move events. * @param param ['sv','h','a'] - string specifying which color property is being modified with the mouse. * @param e - A reference to the mouse event. */ public handleMouseDown(param: string, e: MouseEvent) { this.currentMouseTarget = e.composedPath()[0] as HTMLElement; this.currentMouseParam = param; this.updateFromMouseEvent(e.pageX, e.pageY); this.mouseActive = true; } /** * Handles the mouse move event within the color UI. Is only called once the mouseActive is set to true. * @param e - Reference to the Mouse Event */ public handleMouseMove(e: MouseEvent) { this.updateFromMouseEvent(e.pageX, e.pageY); } /** * Handles the mouse up event within the color UI. Disables listening for mouse move events. * @param e - Reference to the Mouse Event */ public handleMouseUp(e: MouseEvent) { this.updateFromMouseEvent(e.pageX, e.pageY); this.currentMouseTarget = null; this.currentMouseParam = null; this.mouseActive = false; } /** * Handles changes to any of the color property text inputs typed by the user. * @param param ['r','g','b','a','h','s','v'] - String specifying which color value is being modified. * @param e - Reference to the event. */ public handleTextValueInput(param: string, e: Event) { const inputVal = (e.composedPath()[0] as HTMLInputElement).value; if (isNullOrWhiteSpace(inputVal) || Number.isNaN(inputVal)) { return; } const newVal: number = parseInt(inputVal, 10); if (["r", "g", "b", "a"].includes(param)) { if ( (param !== "a" && this.isValidRGB(newVal)) || (param === "a" && this.isValidAlpha(newVal)) ) { this.currentRGBColor = new ColorRGBA64( param === "r" ? newVal / 255 : this.currentRGBColor.r, param === "g" ? newVal / 255 : this.currentRGBColor.g, param === "b" ? newVal / 255 : this.currentRGBColor.b, param === "a" ? newVal / 100 : this.currentRGBColor.a ); this.currentHSVColor = rgbToHSV(this.currentRGBColor); this.updateUIValues(true); } } else if (["h", "s", "v"].includes(param)) { if ( (param !== "h" && this.isValidSaturationValue(newVal)) || (param === "h" && this.isValidHue(newVal)) ) { this.updateHSV( param === "h" ? newVal : this.currentHSVColor.h, param === "s" ? newVal / 100 : this.currentHSVColor.s, param === "v" ? newVal / 100 : this.currentHSVColor.v ); } } } /** * Change event handler for inner control. * @remarks * "Change" events are not `composable` so they will not * permeate the shadow DOM boundary. This fn effectively proxies * the change event, emitting a `change` event whenever the internal * control emits a `change` event * @internal */ public handleChange(): void { this.$emit("change"); } /** * Initialize internal color values based on input value and set the UI elements * to the correct positions / values. */ private initColorValues(): void { if (!isNullOrWhiteSpace(this.value)) { this.currentRGBColor = parseColor(this.value); } else { this.currentRGBColor = new ColorRGBA64(1, 0, 0, 1); } this.currentHSVColor = rgbToHSV(this.currentRGBColor); this.updateUIValues(false); } /** * Determines if a number value is within the valid range for an R, G, or B color channel. * @param val - Number to be evaluated. */ private isValidRGB(val: number): boolean { return val >= 0 && val <= 255; } /** * Determines if a number value is within the valid range for the alpha channel. * @param val - Number to be evaluated. */ private isValidAlpha(val: number): boolean { return val >= 0 && val <= 100; } /** * Determines if a number value is within the valid range for the saturation or value color channels. * @param val - Number to be evaluated. */ private isValidSaturationValue(val: number): boolean { return val >= 0 && val <= 100; } /** * Determines if a number value is within the valid range for the hue color channel. * @param val - Number to be evaluated. */ private isValidHue(val: number): boolean { return val >= 0 && val <= 359; } /** * Checks if input is a valid CSS color. * After placing an invalid css color value into a color style property the value will be an empty string when read back. * @internal */ private isValideCSSColor(testValue: string): boolean { /* Set the background color of the proxy element since it is not visible in the UI. */ this.proxy.style.backgroundColor = ""; this.proxy.style.backgroundColor = testValue; /* Read the value back out. If it was not a valid color value then it will be an empty string when read back out. */ return this.proxy.style.backgroundColor !== ""; } /** * Update the current color values to a new HSV color. * @param hue The new Hue value. * @param sat The new saturation value. * @param val The new Value value. */ private updateHSV(hue: number, sat: number, val: number) { this.currentHSVColor = new ColorHSV(hue, sat, val); this.currentRGBColor = hsvToRGB(this.currentHSVColor, this.currentRGBColor.a); this.updateUIValues(true); } /** * Update the current color values based on the mouse position over one of the three UI elements (hue, saturation/value, or alpha). * @param pageX The pageX position of the mouse. * @param pageY The pageY position of the mouse. */ private updateFromMouseEvent(pageX: number, pageY: number) { const pos: DOMRect = this.currentMouseTarget.getBoundingClientRect(); let x = pageX - pos.left; let y = pageY - pos.top; const width = pos.width; const height = pos.height; if (x > width) x = width; if (y > height) y = height; if (x < 0) x = 0; if (y < 0) y = 0; if (this.currentMouseParam === "h") { this.updateHSV( (359 * x) / width, this.currentHSVColor.s, this.currentHSVColor.v ); } else if (this.currentMouseParam === "sv") { this.updateHSV( this.currentHSVColor.h, Math.round((x * 100) / width) / 100, Math.round(100 - (y * 100) / height) / 100 ); } else if (this.currentMouseParam === "a") { this.currentRGBColor = new ColorRGBA64( this.currentRGBColor.r, this.currentRGBColor.g, this.currentRGBColor.b, Math.round((x * 100) / width) / 100 ); this.updateUIValues(true); } } /** * Update the UI values with the current color. This updates the position of the indicators over the Sat/Val, Hue and Alpha elements * and the values in all of the text fields at once. * @param updateValue - Flag to trigger updating of the main text field value and emitting the change event. */ private updateUIValues(updateValue: boolean) { this.uiValues = new ColorPickerUI(this.currentRGBColor, this.currentHSVColor); if (updateValue) { this.initialValue = this.currentRGBColor.a !== 1 ? this.currentRGBColor.toStringWebRGBA() : this.currentRGBColor.toStringHexRGB(); this.$emit("change"); } } }
the_stack
import { Fragment, useCallback, useEffect, useMemo } from "react" import { useTranslation } from "react-i18next" import { useFieldArray, useForm } from "react-hook-form" import AddIcon from "@mui/icons-material/Add" import RemoveIcon from "@mui/icons-material/Remove" import { AccAddress, Coins, MsgSubmitProposal } from "@terra-money/terra.js" import { TextProposal, CommunityPoolSpendProposal } from "@terra-money/terra.js" import { ParameterChangeProposal, ParamChange } from "@terra-money/terra.js" import { readAmount, readDenom, toAmount } from "@terra.kitchen/utils" import { SAMPLE_ADDRESS } from "config/constants" import { getAmount } from "utils/coin" import { has } from "utils/num" import { queryKey } from "data/query" import { useAddress } from "data/wallet" import { useBankBalance } from "data/queries/bank" import { Grid } from "components/layout" import { Form, FormGroup, FormItem } from "components/form" import { FormHelp, FormWarning } from "components/form" import { Input, TextArea, Select } from "components/form" import { getPlaceholder, toInput } from "../utils" import validate from "../validate" import Tx, { getInitialGasDenom } from "../Tx" enum ProposalType { TEXT = "Text proposal", SPEND = "Community pool spend", PARAMS = "Parameter change", } interface DefaultValues { title: string description: string input?: number } interface TextProposalValues extends DefaultValues { type: ProposalType.TEXT } interface CommunityPoolSpendProposalValues extends DefaultValues { type: ProposalType.SPEND spend: { input?: number; denom: CoinDenom; recipient: AccAddress } } interface ParameterChangeProposalValues extends DefaultValues { type: ProposalType.PARAMS changes: ParamChange[] } type TxValues = | TextProposalValues | CommunityPoolSpendProposalValues | ParameterChangeProposalValues const DEFAULT_PAREMETER_CHANGE = { subspace: "", key: "", value: "" } interface Props { communityPool: Coins minDeposit: Amount } const SubmitProposalForm = ({ communityPool, minDeposit }: Props) => { const { t } = useTranslation() const address = useAddress() const bankBalance = useBankBalance() const balance = getAmount(bankBalance, "uluna") /* tx context */ const initialGasDenom = getInitialGasDenom(bankBalance) /* form */ const form = useForm<TxValues>({ mode: "onChange", defaultValues: { input: toInput(minDeposit) }, }) const { register, trigger, control, watch, setValue, handleSubmit } = form const { errors } = form.formState const { input, ...values } = watch() const amount = toAmount(input) const { fields, append, remove } = useFieldArray({ control, name: "changes" }) /* effect: ParameterChangeProposal */ const shouldAppendChange = values.type === ProposalType.PARAMS && !values.changes.length useEffect(() => { if (shouldAppendChange) append(DEFAULT_PAREMETER_CHANGE) }, [append, shouldAppendChange]) /* tx */ const createTx = useCallback( ({ input, title, description, ...values }: TxValues) => { if (!address) return const amount = toAmount(input) const deposit = has(amount) ? new Coins({ uluna: amount }) : [] const getContent = () => { if (values.type === ProposalType.SPEND) { const { input, denom, recipient } = values.spend const coins = new Coins({ [denom]: toAmount(input) }) return new CommunityPoolSpendProposal( title, description, recipient, coins ) } if (values.type === ProposalType.PARAMS) { const { changes } = values return new ParameterChangeProposal(title, description, changes) } return new TextProposal(title, description) } const msgs = [new MsgSubmitProposal(getContent(), deposit, address)] return { msgs } }, [address] ) /* fee */ const estimationTxValues = useMemo( (): TextProposalValues => ({ type: ProposalType.TEXT, title: ESTIMATE.TITLE, description: ESTIMATE.DESCRIPTION, input: toInput(balance), }), [balance] ) const onChangeMax = useCallback( async (input: number) => { setValue("input", input) await trigger("input") }, [setValue, trigger] ) const token = "uluna" const tx = { token, amount, balance, initialGasDenom, estimationTxValues, createTx, onChangeMax, onSuccess: { label: t("Gov"), path: "/gov" }, queryKeys: [queryKey.gov.proposals], } const render = () => { if (values.type === ProposalType.SPEND) { const max = values.spend && getAmount(communityPool, values.spend.denom) const placeholder = readAmount(max, { integer: true }) return ( <> <FormItem label={t("Recipient")} error={ "spend" in errors ? errors.spend?.recipient?.message : undefined } > <Input {...register("spend.recipient", { validate: validate.address(), })} placeholder={SAMPLE_ADDRESS} /> </FormItem> <FormItem label={t("Amount")} error={"spend" in errors ? errors.spend?.input?.message : undefined} > <Input {...register("spend.input", { valueAsNumber: true, validate: validate.input(toInput(max)), })} inputMode="decimal" placeholder={placeholder} selectBefore={ <Select {...register("spend.denom")} before> {["uluna", "uusd"].map((denom) => ( <option value={denom} key={denom}> {readDenom(denom)} </option> ))} </Select> } /> </FormItem> </> ) } if (values.type === ProposalType.PARAMS) { const length = fields.length return ( <FormItem label={t("Changes")}> {fields.map(({ id }, index) => ( <FormGroup button={ length - 1 === index ? { onClick: () => append(DEFAULT_PAREMETER_CHANGE), children: <AddIcon style={{ fontSize: 18 }} />, } : { onClick: () => remove(index), children: <RemoveIcon style={{ fontSize: 18 }} />, } } key={id} > {/* do not translate labels here */} <FormItem label="subspace"> <Input {...register(`changes.${index}.subspace`, { required: "`subspace` is required", })} placeholder="staking" /> </FormItem> <FormItem label="key"> <Input {...register(`changes.${index}.key`, { required: "`key` is required", })} placeholder="MaxValidators" /> </FormItem> <FormItem label="value"> <Input {...register(`changes.${index}.value`, { required: "`value` is required", })} placeholder="100" /> </FormItem> </FormGroup> ))} </FormItem> ) } } return ( <Tx {...tx}> {({ max, fee, submit }) => ( <Form onSubmit={handleSubmit(submit.fn)}> <Grid gap={4}> <FormHelp>{t("Upload proposal after forum discussion")}</FormHelp> <FormWarning> {t( "Proposal deposits will not be refunded if the proposal fails to reach the quorum or the result is NO_WITH_VETO" )} </FormWarning> {values.type === ProposalType.TEXT && ( <FormWarning> {t("Parameters cannot be changed by text proposals")} </FormWarning> )} </Grid> <FormItem label={t("Proposal type")} error={errors.type?.message}> <Select {...register("type")}> {Object.values(ProposalType).map((type) => ( <option value={type} key={type}> {t(type)} </option> ))} </Select> </FormItem> <FormItem label={t("Title")} error={errors.title?.message}> <Input {...register("title", { required: "Title is required" })} placeholder={t("Burn community pool")} autoFocus /> </FormItem> <FormItem label={t("Description")} error={errors.description?.message} > <TextArea {...register("description", { required: "Description is required", })} placeholder={t( "Weโ€™re proposing to initiate the burn of 100,000,000 LUNA from the Community Pool to mint UST" )} /> </FormItem> <FormItem label={`${t("Initial deposit")} (${t("optional")})`} extra={max.render()} error={errors.input?.message} > <Input {...register("input", { valueAsNumber: true, validate: validate.input( toInput(max.amount), undefined, "Initial deposit", true ), })} token="uluna" onFocus={max.reset} inputMode="decimal" placeholder={getPlaceholder()} /> </FormItem> {render()} {fee.render()} {submit.button} </Form> )} </Tx> ) } export default SubmitProposalForm /* fee estimation */ const ESTIMATE = { TITLE: "Lorem ipsum", DESCRIPTION: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", }
the_stack
import { BaseRegExpVisitor } from "regexp-to-ast" import { IRegExpExec, Lexer, LexerDefinitionErrorType } from "./lexer_public" import { compact, contains, defaults, difference, filter, find, first, flatten, forEach, has, indexOf, isArray, isEmpty, isFunction, isRegExp, isString, isUndefined, keys, map, mapValues, packArray, PRINT_ERROR, reduce, reject } from "@chevrotain/utils" import { canMatchCharCode, failedOptimizationPrefixMsg, getOptimizedStartCodesIndices } from "./reg_exp" import { ILexerDefinitionError, ILineTerminatorsTester, IMultiModeLexerDefinition, IToken, TokenType } from "@chevrotain/types" import { getRegExpAst } from "./reg_exp_parser" const PATTERN = "PATTERN" export const DEFAULT_MODE = "defaultMode" export const MODES = "modes" export interface IPatternConfig { pattern: IRegExpExec longerAlt: number[] canLineTerminator: boolean isCustom: boolean short: number | boolean group: any push: string pop: boolean tokenTypeIdx: number } export interface IAnalyzeResult { patternIdxToConfig: IPatternConfig[] charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] } emptyGroups: { [groupName: string]: IToken[] } hasCustom: boolean canBeOptimized: boolean } export let SUPPORT_STICKY = typeof (<any>new RegExp("(?:)")).sticky === "boolean" export function disableSticky() { SUPPORT_STICKY = false } export function enableSticky() { SUPPORT_STICKY = true } export function analyzeTokenTypes( tokenTypes: TokenType[], options: { positionTracking?: "full" | "onlyStart" | "onlyOffset" ensureOptimizations?: boolean lineTerminatorCharacters?: (number | string)[] // TODO: should `useSticky` be an argument here? useSticky?: boolean safeMode?: boolean tracer?: (msg: string, action: Function) => void } ): IAnalyzeResult { options = defaults(options, { useSticky: SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", "\n"], tracer: (msg, action) => action() }) const tracer = options.tracer tracer("initCharCodeToOptimizedIndexMap", () => { initCharCodeToOptimizedIndexMap() }) let onlyRelevantTypes tracer("Reject Lexer.NA", () => { onlyRelevantTypes = reject(tokenTypes, (currType) => { return currType[PATTERN] === Lexer.NA }) }) let hasCustom = false let allTransformedPatterns tracer("Transform Patterns", () => { hasCustom = false allTransformedPatterns = map(onlyRelevantTypes, (currType) => { const currPattern = currType[PATTERN] /* istanbul ignore else */ if (isRegExp(currPattern)) { const regExpSource = currPattern.source if ( regExpSource.length === 1 && // only these regExp meta characters which can appear in a length one regExp regExpSource !== "^" && regExpSource !== "$" && regExpSource !== "." && !currPattern.ignoreCase ) { return regExpSource } else if ( regExpSource.length === 2 && regExpSource[0] === "\\" && // not a meta character !contains( [ "d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W" ], regExpSource[1] ) ) { // escaped meta Characters: /\+/ /\[/ // or redundant escaping: /\a/ // without the escaping "\" return regExpSource[1] } else { return options.useSticky ? addStickyFlag(currPattern) : addStartOfInput(currPattern) } } else if (isFunction(currPattern)) { hasCustom = true // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object return { exec: currPattern } } else if (has(currPattern, "exec")) { hasCustom = true // ICustomPattern return currPattern } else if (typeof currPattern === "string") { if (currPattern.length === 1) { return currPattern } else { const escapedRegExpString = currPattern.replace( /[\\^$.*+?()[\]{}|]/g, "\\$&" ) const wrappedRegExp = new RegExp(escapedRegExpString) return options.useSticky ? addStickyFlag(wrappedRegExp) : addStartOfInput(wrappedRegExp) } } else { throw Error("non exhaustive match") } }) }) let patternIdxToType let patternIdxToGroup let patternIdxToLongerAltIdxArr let patternIdxToPushMode let patternIdxToPopMode tracer("misc mapping", () => { patternIdxToType = map( onlyRelevantTypes, (currType) => currType.tokenTypeIdx ) patternIdxToGroup = map(onlyRelevantTypes, (clazz: any) => { const groupName = clazz.GROUP /* istanbul ignore next */ if (groupName === Lexer.SKIPPED) { return undefined } else if (isString(groupName)) { return groupName } else if (isUndefined(groupName)) { return false } else { throw Error("non exhaustive match") } }) patternIdxToLongerAltIdxArr = map(onlyRelevantTypes, (clazz: any) => { const longerAltType = clazz.LONGER_ALT if (longerAltType) { const longerAltIdxArr = isArray(longerAltType) ? map(longerAltType, (type: any) => indexOf(onlyRelevantTypes, type)) : [indexOf(onlyRelevantTypes, longerAltType)] return longerAltIdxArr } }) patternIdxToPushMode = map( onlyRelevantTypes, (clazz: any) => clazz.PUSH_MODE ) patternIdxToPopMode = map(onlyRelevantTypes, (clazz: any) => has(clazz, "POP_MODE") ) }) let patternIdxToCanLineTerminator tracer("Line Terminator Handling", () => { const lineTerminatorCharCodes = getCharCodes( options.lineTerminatorCharacters ) patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => false) if (options.positionTracking !== "onlyOffset") { patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => { if (has(tokType, "LINE_BREAKS")) { return tokType.LINE_BREAKS } else { if ( checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false ) { return canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN) } } }) } }) let patternIdxToIsCustom let patternIdxToShort let emptyGroups let patternIdxToConfig tracer("Misc Mapping #2", () => { patternIdxToIsCustom = map(onlyRelevantTypes, isCustomPattern) patternIdxToShort = map(allTransformedPatterns, isShortPattern) emptyGroups = reduce( onlyRelevantTypes, (acc, clazz: any) => { const groupName = clazz.GROUP if (isString(groupName) && !(groupName === Lexer.SKIPPED)) { acc[groupName] = [] } return acc }, {} ) patternIdxToConfig = map(allTransformedPatterns, (x, idx) => { return { pattern: allTransformedPatterns[idx], longerAlt: patternIdxToLongerAltIdxArr[idx], canLineTerminator: patternIdxToCanLineTerminator[idx], isCustom: patternIdxToIsCustom[idx], short: patternIdxToShort[idx], group: patternIdxToGroup[idx], push: patternIdxToPushMode[idx], pop: patternIdxToPopMode[idx], tokenTypeIdx: patternIdxToType[idx], tokenType: onlyRelevantTypes[idx] } }) }) let canBeOptimized = true let charCodeToPatternIdxToConfig = [] if (!options.safeMode) { tracer("First Char Optimization", () => { charCodeToPatternIdxToConfig = reduce( onlyRelevantTypes, (result, currTokType, idx) => { if (typeof currTokType.PATTERN === "string") { const charCode = currTokType.PATTERN.charCodeAt(0) const optimizedIdx = charCodeToOptimizedIndex(charCode) addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]) } else if (isArray(currTokType.START_CHARS_HINT)) { let lastOptimizedIdx forEach(currTokType.START_CHARS_HINT, (charOrInt) => { const charCode = typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt const currOptimizedIdx = charCodeToOptimizedIndex(charCode) // Avoid adding the config multiple times /* istanbul ignore else */ // - Difficult to check this scenario effects as it is only a performance // optimization that does not change correctness if (lastOptimizedIdx !== currOptimizedIdx) { lastOptimizedIdx = currOptimizedIdx addToMapOfArrays( result, currOptimizedIdx, patternIdxToConfig[idx] ) } }) } else if (isRegExp(currTokType.PATTERN)) { if (currTokType.PATTERN.unicode) { canBeOptimized = false if (options.ensureOptimizations) { PRINT_ERROR( `${failedOptimizationPrefixMsg}` + `\tUnable to analyze < ${currTokType.PATTERN.toString()} > pattern.\n` + "\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" + "\tThis will disable the lexer's first char optimizations.\n" + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE" ) } } else { const optimizedCodes = getOptimizedStartCodesIndices( currTokType.PATTERN, options.ensureOptimizations ) /* istanbul ignore if */ // start code will only be empty given an empty regExp or failure of regexp-to-ast library // the first should be a different validation and the second cannot be tested. if (isEmpty(optimizedCodes)) { // we cannot understand what codes may start possible matches // The optimization correctness requires knowing start codes for ALL patterns. // Not actually sure this is an error, no debug message canBeOptimized = false } forEach(optimizedCodes, (code) => { addToMapOfArrays(result, code, patternIdxToConfig[idx]) }) } } else { if (options.ensureOptimizations) { PRINT_ERROR( `${failedOptimizationPrefixMsg}` + `\tTokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.\n` + "\tThis will disable the lexer's first char optimizations.\n" + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE" ) } canBeOptimized = false } return result }, [] ) }) } tracer("ArrayPacking", () => { charCodeToPatternIdxToConfig = packArray(charCodeToPatternIdxToConfig) }) return { emptyGroups: emptyGroups, patternIdxToConfig: patternIdxToConfig, charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig, hasCustom: hasCustom, canBeOptimized: canBeOptimized } } export function validatePatterns( tokenTypes: TokenType[], validModesNames: string[] ): ILexerDefinitionError[] { let errors = [] const missingResult = findMissingPatterns(tokenTypes) errors = errors.concat(missingResult.errors) const invalidResult = findInvalidPatterns(missingResult.valid) const validTokenTypes = invalidResult.valid errors = errors.concat(invalidResult.errors) errors = errors.concat(validateRegExpPattern(validTokenTypes)) errors = errors.concat(findInvalidGroupType(validTokenTypes)) errors = errors.concat( findModesThatDoNotExist(validTokenTypes, validModesNames) ) errors = errors.concat(findUnreachablePatterns(validTokenTypes)) return errors } function validateRegExpPattern( tokenTypes: TokenType[] ): ILexerDefinitionError[] { let errors = [] const withRegExpPatterns = filter(tokenTypes, (currTokType) => isRegExp(currTokType[PATTERN]) ) errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)) errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)) errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)) errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)) errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)) return errors } export interface ILexerFilterResult { errors: ILexerDefinitionError[] valid: TokenType[] } export function findMissingPatterns( tokenTypes: TokenType[] ): ILexerFilterResult { const tokenTypesWithMissingPattern = filter(tokenTypes, (currType) => { return !has(currType, PATTERN) }) const errors = map(tokenTypesWithMissingPattern, (currType) => { return { message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property", type: LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [currType] } }) const valid = difference(tokenTypes, tokenTypesWithMissingPattern) return { errors, valid } } export function findInvalidPatterns( tokenTypes: TokenType[] ): ILexerFilterResult { const tokenTypesWithInvalidPattern = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN] return ( !isRegExp(pattern) && !isFunction(pattern) && !has(pattern, "exec") && !isString(pattern) ) }) const errors = map(tokenTypesWithInvalidPattern, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' can only be a RegExp, a" + " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [currType] } }) const valid = difference(tokenTypes, tokenTypesWithInvalidPattern) return { errors, valid } } const end_of_input = /[^\\][\$]/ export function findEndOfInputAnchor( tokenTypes: TokenType[] ): ILexerDefinitionError[] { class EndAnchorFinder extends BaseRegExpVisitor { found = false visitEndAnchor(node) { this.found = true } } const invalidRegex = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN] try { const regexpAst = getRegExpAst(pattern) const endAnchorVisitor = new EndAnchorFinder() endAnchorVisitor.visit(regexpAst) return endAnchorVisitor.found } catch (e) { // old behavior in case of runtime exceptions with regexp-to-ast. /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ return end_of_input.test(pattern.source) } }) const errors = map(invalidRegex, (currType) => { return { message: "Unexpected RegExp Anchor Error:\n" + "\tToken Type: ->" + currType.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n" + "\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + "\tfor details.", type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [currType] } }) return errors } export function findEmptyMatchRegExps( tokenTypes: TokenType[] ): ILexerDefinitionError[] { const matchesEmptyString = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN] return pattern.test("") }) const errors = map(matchesEmptyString, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string", type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [currType] } }) return errors } const start_of_input = /[^\\[][\^]|^\^/ export function findStartOfInputAnchor( tokenTypes: TokenType[] ): ILexerDefinitionError[] { class StartAnchorFinder extends BaseRegExpVisitor { found = false visitStartAnchor(node) { this.found = true } } const invalidRegex = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN] try { const regexpAst = getRegExpAst(pattern) const startAnchorVisitor = new StartAnchorFinder() startAnchorVisitor.visit(regexpAst) return startAnchorVisitor.found } catch (e) { // old behavior in case of runtime exceptions with regexp-to-ast. /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ return start_of_input.test(pattern.source) } }) const errors = map(invalidRegex, (currType) => { return { message: "Unexpected RegExp Anchor Error:\n" + "\tToken Type: ->" + currType.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n" + "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + "\tfor details.", type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [currType] } }) return errors } export function findUnsupportedFlags( tokenTypes: TokenType[] ): ILexerDefinitionError[] { const invalidFlags = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN] return pattern instanceof RegExp && (pattern.multiline || pattern.global) }) const errors = map(invalidFlags, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [currType] } }) return errors } // This can only test for identical duplicate RegExps, not semantically equivalent ones. export function findDuplicatePatterns( tokenTypes: TokenType[] ): ILexerDefinitionError[] { const found = [] let identicalPatterns = map(tokenTypes, (outerType: any) => { return reduce( tokenTypes, (result, innerType: any) => { if ( outerType.PATTERN.source === innerType.PATTERN.source && !contains(found, innerType) && innerType.PATTERN !== Lexer.NA ) { // this avoids duplicates in the result, each Token Type may only appear in one "set" // in essence we are creating Equivalence classes on equality relation. found.push(innerType) result.push(innerType) return result } return result }, [] ) }) identicalPatterns = compact(identicalPatterns) const duplicatePatterns = filter(identicalPatterns, (currIdenticalSet) => { return currIdenticalSet.length > 1 }) const errors = map(duplicatePatterns, (setOfIdentical: any) => { const tokenTypeNames = map(setOfIdentical, (currType: any) => { return currType.name }) const dupPatternSrc = (<any>first(setOfIdentical)).PATTERN return { message: `The same RegExp pattern ->${dupPatternSrc}<-` + `has been used in all of the following Token Types: ${tokenTypeNames.join( ", " )} <-`, type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: setOfIdentical } }) return errors } export function findInvalidGroupType( tokenTypes: TokenType[] ): ILexerDefinitionError[] { const invalidTypes = filter(tokenTypes, (clazz: any) => { if (!has(clazz, "GROUP")) { return false } const group = clazz.GROUP return group !== Lexer.SKIPPED && group !== Lexer.NA && !isString(group) }) const errors = map(invalidTypes, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [currType] } }) return errors } export function findModesThatDoNotExist( tokenTypes: TokenType[], validModes: string[] ): ILexerDefinitionError[] { const invalidModes = filter(tokenTypes, (clazz: any) => { return ( clazz.PUSH_MODE !== undefined && !contains(validModes, clazz.PUSH_MODE) ) }) const errors = map(invalidModes, (tokType) => { const msg = `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-` + `which does not exist` return { message: msg, type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [tokType] } }) return errors } export function findUnreachablePatterns( tokenTypes: TokenType[] ): ILexerDefinitionError[] { const errors = [] const canBeTested = reduce( tokenTypes, (result, tokType, idx) => { const pattern = tokType.PATTERN if (pattern === Lexer.NA) { return result } // a more comprehensive validation for all forms of regExps would require // deeper regExp analysis capabilities if (isString(pattern)) { result.push({ str: pattern, idx, tokenType: tokType }) } else if (isRegExp(pattern) && noMetaChar(pattern)) { result.push({ str: pattern.source, idx, tokenType: tokType }) } return result }, [] ) forEach(tokenTypes, (tokType, testIdx) => { forEach(canBeTested, ({ str, idx, tokenType }) => { if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { const msg = `Token: ->${tokenType.name}<- can never be matched.\n` + `Because it appears AFTER the Token Type ->${tokType.name}<-` + `in the lexer's definition.\n` + `See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE` errors.push({ message: msg, type: LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [tokType, tokenType] }) } }) }) return errors } function testTokenType(str: string, pattern: any): boolean { /* istanbul ignore else */ if (isRegExp(pattern)) { const regExpArray = pattern.exec(str) return regExpArray !== null && regExpArray.index === 0 } else if (isFunction(pattern)) { // maintain the API of custom patterns return pattern(str, 0, [], {}) } else if (has(pattern, "exec")) { // maintain the API of custom patterns return pattern.exec(str, 0, [], {}) } else if (typeof pattern === "string") { return pattern === str } else { throw Error("non exhaustive match") } } function noMetaChar(regExp: RegExp): boolean { //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp const metaChars = [ ".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{" ] return ( find(metaChars, (char) => regExp.source.indexOf(char) !== -1) === undefined ) } export function addStartOfInput(pattern: RegExp): RegExp { const flags = pattern.ignoreCase ? "i" : "" // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) return new RegExp(`^(?:${pattern.source})`, flags) } export function addStickyFlag(pattern: RegExp): RegExp { const flags = pattern.ignoreCase ? "iy" : "y" // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) return new RegExp(`${pattern.source}`, flags) } export function performRuntimeChecks( lexerDefinition: IMultiModeLexerDefinition, trackLines: boolean, lineTerminatorCharacters: (number | string)[] ): ILexerDefinitionError[] { const errors = [] // some run time checks to help the end users. if (!has(lexerDefinition, DEFAULT_MODE)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + DEFAULT_MODE + "> property in its definition\n", type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }) } if (!has(lexerDefinition, MODES)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + MODES + "> property in its definition\n", type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }) } if ( has(lexerDefinition, MODES) && has(lexerDefinition, DEFAULT_MODE) && !has(lexerDefinition.modes, lexerDefinition.defaultMode) ) { errors.push({ message: `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>` + `which does not exist\n`, type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }) } if (has(lexerDefinition, MODES)) { forEach(lexerDefinition.modes, (currModeValue, currModeName) => { forEach(currModeValue, (currTokType, currIdx) => { if (isUndefined(currTokType)) { errors.push({ message: `A Lexer cannot be initialized using an undefined Token Type. Mode:` + `<${currModeName}> at index: <${currIdx}>\n`, type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }) } }) }) } return errors } export function performWarningRuntimeChecks( lexerDefinition: IMultiModeLexerDefinition, trackLines: boolean, lineTerminatorCharacters: (number | string)[] ): ILexerDefinitionError[] { const warnings = [] let hasAnyLineBreak = false const allTokenTypes = compact( flatten(mapValues(lexerDefinition.modes, (tokTypes) => tokTypes)) ) const concreteTokenTypes = reject( allTokenTypes, (currType) => currType[PATTERN] === Lexer.NA ) const terminatorCharCodes = getCharCodes(lineTerminatorCharacters) if (trackLines) { forEach(concreteTokenTypes, (tokType) => { const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes) if (currIssue !== false) { const message = buildLineBreakIssueMessage(tokType, currIssue) const warningDescriptor = { message, type: currIssue.issue, tokenType: tokType } warnings.push(warningDescriptor) } else { // we don't want to attempt to scan if the user explicitly specified the line_breaks option. if (has(tokType, "LINE_BREAKS")) { if (tokType.LINE_BREAKS === true) { hasAnyLineBreak = true } } else { if (canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) { hasAnyLineBreak = true } } } }) } if (trackLines && !hasAnyLineBreak) { warnings.push({ message: "Warning: No LINE_BREAKS Found.\n" + "\tThis Lexer has been defined to track line and column information,\n" + "\tBut none of the Token Types can be identified as matching a line terminator.\n" + "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" + "\tfor details.", type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }) } return warnings } export function cloneEmptyGroups(emptyGroups: { [groupName: string]: IToken }): { [groupName: string]: IToken } { const clonedResult: any = {} const groupKeys = keys(emptyGroups) forEach(groupKeys, (currKey) => { const currGroupValue = emptyGroups[currKey] /* istanbul ignore else */ if (isArray(currGroupValue)) { clonedResult[currKey] = [] } else { throw Error("non exhaustive match") } }) return clonedResult } // TODO: refactor to avoid duplication export function isCustomPattern(tokenType: any): boolean { const pattern = tokenType.PATTERN /* istanbul ignore else */ if (isRegExp(pattern)) { return false } else if (isFunction(pattern)) { // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object return true } else if (has(pattern, "exec")) { // ICustomPattern return true } else if (isString(pattern)) { return false } else { throw Error("non exhaustive match") } } export function isShortPattern(pattern: any): number | boolean { if (isString(pattern) && pattern.length === 1) { return pattern.charCodeAt(0) } else { return false } } /** * Faster than using a RegExp for default newline detection during lexing. */ export const LineTerminatorOptimizedTester: ILineTerminatorsTester = { // implements /\n|\r\n?/g.test test: function (text) { const len = text.length for (let i = this.lastIndex; i < len; i++) { const c = text.charCodeAt(i) if (c === 10) { this.lastIndex = i + 1 return true } else if (c === 13) { if (text.charCodeAt(i + 1) === 10) { this.lastIndex = i + 2 } else { this.lastIndex = i + 1 } return true } } return false }, lastIndex: 0 } function checkLineBreaksIssues( tokType: TokenType, lineTerminatorCharCodes: number[] ): | { issue: | LexerDefinitionErrorType.IDENTIFY_TERMINATOR | LexerDefinitionErrorType.CUSTOM_LINE_BREAK errMsg?: string } | false { if (has(tokType, "LINE_BREAKS")) { // if the user explicitly declared the line_breaks option we will respect their choice // and assume it is correct. return false } else { /* istanbul ignore else */ if (isRegExp(tokType.PATTERN)) { try { // TODO: why is the casting suddenly needed? canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN as RegExp) } catch (e) { /* istanbul ignore next - to test this we would have to mock <canMatchCharCode> to throw an error */ return { issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: e.message } } return false } else if (isString(tokType.PATTERN)) { // string literal patterns can always be analyzed to detect line terminator usage return false } else if (isCustomPattern(tokType)) { // custom token types return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK } } else { throw Error("non exhaustive match") } } } export function buildLineBreakIssueMessage( tokType: TokenType, details: { issue: | LexerDefinitionErrorType.IDENTIFY_TERMINATOR | LexerDefinitionErrorType.CUSTOM_LINE_BREAK errMsg?: string } ): string { /* istanbul ignore else */ if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { return ( "Warning: unable to identify line terminator usage in pattern.\n" + `\tThe problem is in the <${tokType.name}> Token Type\n` + `\t Root cause: ${details.errMsg}.\n` + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR" ) } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { return ( "Warning: A Custom Token Pattern should specify the <line_breaks> option.\n" + `\tThe problem is in the <${tokType.name}> Token Type\n` + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK" ) } else { throw Error("non exhaustive match") } } function getCharCodes(charsOrCodes: (number | string)[]): number[] { const charCodes = map(charsOrCodes, (numOrString) => { if (isString(numOrString) && numOrString.length > 0) { return numOrString.charCodeAt(0) } else { return numOrString } }) return charCodes } function addToMapOfArrays(map, key, value): void { if (map[key] === undefined) { map[key] = [value] } else { map[key].push(value) } } export const minOptimizationVal = 256 /** * We ae mapping charCode above ASCI (256) into buckets each in the size of 256. * This is because ASCI are the most common start chars so each one of those will get its own * possible token configs vector. * * Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford" * to place these into buckets of possible token configs, What we gain from * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig' * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario). * Our 'charCodeToPatternIdxToConfig' max size will now be: * 256 + (2^16 / 2^8) - 1 === 511 * * note the hack for fast division integer part extraction * See: https://stackoverflow.com/a/4228528 */ let charCodeToOptimizedIdxMap = [] export function charCodeToOptimizedIndex(charCode) { return charCode < minOptimizationVal ? charCode : charCodeToOptimizedIdxMap[charCode] } /** * This is a compromise between cold start / hot running performance * Creating this array takes ~3ms on a modern machine, * But if we perform the computation at runtime as needed the CSS Lexer benchmark * performance degrades by ~10% * * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used. */ function initCharCodeToOptimizedIndexMap() { if (isEmpty(charCodeToOptimizedIdxMap)) { charCodeToOptimizedIdxMap = new Array(65536) for (let i = 0; i < 65536; i++) { /* tslint:disable */ charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i /* tslint:enable */ } } }
the_stack
import * as Tp from "thingpedia"; import * as fs from "fs"; import xmlbuilder from "xmlbuilder"; import * as http from "http"; import * as https from "https"; import WebSocket from "ws"; import { AudioInputStream, ResultReason, AudioConfig, SpeechConfig, SpeechRecognizer, } from "microsoft-cognitiveservices-speech-sdk"; import * as wav from "wav"; import * as Config from "../../config"; class SpeechToTextFailureError extends Error { status : number; code : string; constructor(status : number, code : string, message : string) { super(message); this.status = status; this.code = code; } } class SpeechToText { private _locale : string; constructor(locale : string) { this._locale = locale; } private _initRecognizer(sdkInputStream : AudioInputStream) { const audioConfig = AudioConfig.fromStreamInput(sdkInputStream); const speechConfig = SpeechConfig.fromSubscription( Config.MS_SPEECH_SUBSCRIPTION_KEY!, Config.MS_SPEECH_SERVICE_REGION! ); speechConfig.speechRecognitionLanguage = this._locale; // Recognizer settings return new SpeechRecognizer(speechConfig, audioConfig); } async recognizeOnce(wavFilename : string) : Promise<string> { const sdkAudioInputStream = AudioInputStream.createPushStream(); const recognizer = this._initRecognizer(sdkAudioInputStream); return new Promise((resolve, reject) => { recognizer.recognized = (_, e) => { // Indicates that recognizable speech was not detected, and that // recognition is done. if (e.result.reason === ResultReason.NoMatch) { reject( new SpeechToTextFailureError( 400, "E_NO_MATCH", "Speech unrecognizable." ) ); } }; recognizer.recognizeOnceAsync( (result) => { resolve(result.text); recognizer.close(); }, () => { reject( new SpeechToTextFailureError( 500, "E_INTERNAL_ERROR", "Speech recognition failed due to internal error." ) ); recognizer.close(); } ); const fileStream = fs.createReadStream(wavFilename); const wavReader = new wav.Reader(); wavReader.on("format", (format) => { wavReader .on("data", (data) => { sdkAudioInputStream.write(data); }) .on("end", () => { sdkAudioInputStream.close(); }); }); wavReader.on("error", reject); fileStream.pipe(wavReader); }); } async recognizeStream(stream : WebSocket) { const sdkAudioInputStream = AudioInputStream.createPushStream(); const recognizer = this._initRecognizer(sdkAudioInputStream); return new Promise((resolve, reject) => { let fullText = "", lastFC = 0, timerLastFrame : NodeJS.Timeout, _ended = false; function stopRecognizer() { if (timerLastFrame) clearInterval(timerLastFrame); sdkAudioInputStream.close(); _ended = true; } recognizer.recognized = (_, e) => { const result = e.result; const reason = result.reason; // Indicates that recognizable speech was not detected if (reason === ResultReason.NoMatch) recognizer.sessionStopped(_, e); // Add recognized text to fullText if (reason === ResultReason.RecognizedSpeech) fullText += result.text; }; // Signals that the speech service has detected that speech has // stopped. recognizer.sessionStopped = (_, e) => { if (timerLastFrame) clearInterval(timerLastFrame); recognizer.stopContinuousRecognitionAsync( () => { // Recognition stopped if (fullText) { resolve(fullText); } else { reject( new SpeechToTextFailureError( 400, "E_NO_MATCH", "Speech unrecognizable." ) ); } recognizer.close(); }, () => { reject( new SpeechToTextFailureError( 500, "E_INTERNAL_ERROR", "Speech recognition failed due to internal error." ) ); } ); }; recognizer.startContinuousRecognitionAsync( () => { // Recognition started timerLastFrame = setInterval(() => { if (lastFC >= 2) stopRecognizer(); lastFC++; }, 500); }, () => { reject( new SpeechToTextFailureError( 500, "E_INTERNAL_ERROR", "Speech recognition failed due to internal error." ) ); recognizer.close(); } ); stream .on("message", (data : Buffer) => { if (data.length) { if (!_ended) sdkAudioInputStream.write(data); lastFC = 0; } else { stopRecognizer(); } }) .on("end", () => { stopRecognizer(); }); }); } } const VOICES : Record<string, { male : string; female : string }> = { "en-us": { male: "GuyNeural", female: "AriaNeural", }, }; /** * Default period between TTS access token refreshes, in milliseconds. Access * tokens are good for 10 minutes: * * https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/rest-text-to-speech#authentication * * So I've chosen 8 minutes. */ const TTS_DEFAULT_TOKEN_REFRESH_MS = 8 * 60 * 1000; class TextToSpeech { public readonly URL = `https://${Config.MS_SPEECH_SERVICE_REGION}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`; private _accessToken : null | string; private _accessTokenPromise : Promise<string>; private _tokenRefresh_ms : number; constructor({ tokenRefresh_ms = TTS_DEFAULT_TOKEN_REFRESH_MS, } : { tokenRefresh_ms ?: number; } = {}) { this._accessToken = null; this._accessTokenPromise = this.retrieveAccessToken(); this._tokenRefresh_ms = tokenRefresh_ms; } retrieveAccessToken() : Promise<string> { console.log(`TextToSpeech.retrieveAccessToken() START`); return Tp.Helpers.Http.post(this.URL, "", { extraHeaders: { "Ocp-Apim-Subscription-Key": Config.MS_SPEECH_SUBSCRIPTION_KEY!, }, }).then((accessToken : string) => { console.log(`TextToSpeech.retrieveAccessToken() DONE`); this._accessToken = accessToken; console.log(`Scheduling refresh in ${this._tokenRefresh_ms} ms...`); setTimeout( this.retrieveAccessToken.bind(this), this._tokenRefresh_ms ); return accessToken; }); } async getAccessToken() : Promise<string> { console.log(`TextToSpeech.getAccessToken() START`); if (typeof this._accessToken === "string") { console.log(`this._accessToken present, returning (FAST)`); return this._accessToken; } console.log(`this._accessToken absent, awaiting promise (SLOW)`); return this._accessTokenPromise; } async request( locale : string, gender : "male" | "female" = "male", text : string ) { const accessToken = await this.getAccessToken(); // Create the SSML request. const xmlBody = xmlbuilder .create("speak") .att("version", "1.0") .att("xml:lang", locale) .ele("voice") .att("xml:lang", locale) .att("name", locale + "-" + VOICES[locale.toLowerCase()][gender]) .txt(text) .end(); // Convert the XML into a string to send in the TTS request. const body = xmlBody.toString(); return new Promise<http.IncomingMessage>((resolve, reject) => { const options = { protocol: "https:", hostname: `${Config.MS_SPEECH_SERVICE_REGION}.tts.speech.microsoft.com`, port: 443, headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/ssml+xml", "User-Agent": "YOUR_RESOURCE_NAME", "X-Microsoft-OutputFormat": "riff-24khz-16bit-mono-pcm", "cache-control": "no-cache", }, method: "POST", path: "/cognitiveservices/v1", }; const req = https.request(options, (res) => { if (res.statusCode !== 200) { // this error will be logged, and the client will see a 500 // error reject( new Error(`Unexpected HTTP error ${res.statusCode}`) ); return; } resolve(res); }); req.on("error", reject); req.end(body); }); } } export { SpeechToText, TextToSpeech };
the_stack
import { fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { MockExpiry } from '../testing/mockexpiry'; import { MockInterruptSource } from '../testing/mockinterruptsource'; import { MockKeepaliveSvc } from '../testing/mockkeepalivesvc'; import { AutoResume, Idle } from './idle'; import { LocalStorageExpiry } from './localstorageexpiry'; import { LocalStorage } from './localstorage'; import { IdleExpiry } from './idleexpiry'; import { KeepaliveSvc } from './keepalivesvc'; describe('core/Idle', () => { describe('with LocalStorageExpiry', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ LocalStorageExpiry, LocalStorage, { provide: IdleExpiry, useExisting: LocalStorageExpiry }, Idle ] }); }); it('setIdleName() should set idle name', inject( [Idle, LocalStorageExpiry], (idle: Idle, exp: LocalStorageExpiry) => { idle.setIdleName('demo'); expect((exp as LocalStorageExpiry).getIdleName()).toBe('demo'); } )); }); describe('without KeepaliveSvc integration', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ MockExpiry, { provide: IdleExpiry, useExisting: MockExpiry }, Idle ] }); }); let instance: Idle; let expiry: MockExpiry; beforeEach(inject([Idle, MockExpiry], (idle: Idle, exp: MockExpiry) => { instance = idle; expiry = exp; })); describe('runtime config', () => { it('getKeepaliveEnabled() should be false', () => { expect(instance.getKeepaliveEnabled()).toBe(false); }); it('setKeepaliveEnabled() should throw', () => { expect(() => { instance.setKeepaliveEnabled(true); }).toThrowError( 'Cannot enable keepalive integration because no KeepaliveSvc has been provided.' ); }); it('getIdle() should return current value', () => { expect(instance.getIdle()).toEqual(20 * 60); }); it('setIdle() should set and return the current value', () => { const expected = 500; const actual = instance.setIdle(expected); expect(actual).toEqual(expected); }); it('setIdleName() when expiry is not instance of LocalStorageExpiry should throw error', () => { expect(() => { instance.setIdleName('demo'); }).toThrowError( 'Cannot set expiry key name because no LocalStorageExpiry has been provided.' ); }); it('setIdle() should throw if argument is less than or equal to zero', () => { const expected = new Error("'seconds' must be greater zero"); expect(() => { instance.setIdle(0); }).toThrow(expected); expect(() => { instance.setIdle(-1); }).toThrow(expected); }); it('getTimeout() should return current value', () => { expect(instance.getTimeout()).toEqual(30); }); it('setTimeout() should set and return the current value', () => { const expected = 10 * 60; const actual = instance.setTimeout(expected); expect(actual).toEqual(expected); }); it('setTimeout() should set timeout to 0 if false is specified', () => { const expected = 0; const actual = instance.setTimeout(false); expect(actual).toEqual(expected); }); it('setTimeout() should throw if argument is less than zero', () => { expect(() => { instance.setTimeout(-1); }).toThrow( new Error("'seconds' can only be 'false' or a positive number.") ); }); it("setTimeout() should throw if argument 'true'", () => { expect(() => { instance.setTimeout(true); }).toThrow( new Error("'seconds' can only be 'false' or a positive number.") ); }); it('getAutoResume() should return current value', () => { expect(instance.getAutoResume()).toEqual(AutoResume.idle); }); it('setAutoResume() should set and return current value', () => { const expected = AutoResume.disabled; const actual = instance.setAutoResume(expected); expect(actual).toEqual(expected); }); it('setInterrupts() should create interrupt subscriptions', () => { const source = new MockInterruptSource(); spyOn(source.onInterrupt, 'subscribe').and.callThrough(); spyOn(source, 'attach').and.callThrough(); const subs = instance.setInterrupts([source]); expect(subs.length).toBe(1); const actual = subs[0]; expect(actual.source).toBe(source); expect(source.onInterrupt.subscribe).toHaveBeenCalled(); expect(source.attach).not.toHaveBeenCalled(); }); it('getInterrupts() should return current subscriptions', () => { const source = new MockInterruptSource(); instance.setInterrupts([source]); const subs = instance.getInterrupts(); expect(subs.length).toBe(1); const actual = subs[0]; expect(actual.source).toBe(source); }); it('clearInterrupts() should unsubscribe and clear all subscriptions', () => { const source = new MockInterruptSource(); spyOn(source, 'detach').and.callThrough(); instance.setInterrupts([source]); instance.clearInterrupts(); expect(instance.getInterrupts().length).toBe(0); expect(source.detach).toHaveBeenCalled(); }); }); describe('watching', () => { beforeEach(() => { instance.setIdle(3); }); it('stop() should clear timeouts and stop running', fakeAsync(() => { spyOn(window, 'clearInterval').and.callThrough(); instance.watch(); instance.stop(); expect(instance.isRunning()).toBe(false); expect(window.clearInterval).toHaveBeenCalledTimes(1); })); it('stop() should clear last expiry', () => { instance.watch(); expect(expiry.last()).not.toBeNull(); instance.stop(); expect(expiry.last()).toBeNull(); }); it('watch() should clear timeouts and start running', fakeAsync(() => { spyOn(window, 'setInterval').and.callThrough(); instance.watch(); expect(instance.isRunning()).toBe(true); expect(window.setInterval).toHaveBeenCalledTimes(1); instance.stop(); })); it('watch() should set expiry', () => { const now = new Date(); expiry.mockNow = now; instance.watch(); expect(expiry.last()).toEqual( new Date( now.getTime() + (instance.getIdle() + instance.getTimeout()) * 1000 ) ); instance.stop(); }); it('watch() should attach all interrupts', () => { const source = new MockInterruptSource(); instance.setInterrupts([source]); expect(source.isAttached).toBe(false); instance.watch(); expect(source.isAttached).toBe(true); instance.stop(); }); it('watch() should detach all interrupts', () => { const source = new MockInterruptSource(); instance.setInterrupts([source]); instance.watch(); expect(source.isAttached).toBe(true); instance.stop(); expect(source.isAttached).toBe(false); }); it('watch() should not idle after IdleInterval has fired if timeout has not elapsed', fakeAsync(() => { const source = new MockInterruptSource(); instance.setTimeout(3); instance.setInterrupts([source]); expiry.mockNow = new Date(); instance.watch(); expect(source.isAttached).toBe(true); expiry.mockNow = new Date(expiry.now().getTime() + 30000); expiry.last(new Date(expiry.now().getTime() + 33000)); tick(30000); console.log(`${expiry.last()}`); expect(instance.isIdling()).toBe(false); expect(source.isAttached).toBe(true); instance.stop(); })); it('watch() should attach all interrupts when resuming after timeout', fakeAsync(() => { const source = new MockInterruptSource(); instance.setTimeout(3); instance.setInterrupts([source]); expiry.mockNow = new Date(); instance.watch(); expect(source.isAttached).toBe(true); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(30000); tick(1000); tick(1000); tick(1000); expect(instance.isIdling()).toBe(true); expect(source.isAttached).toBe(false); instance.watch(); expect(source.isAttached).toBe(true); instance.stop(); })); it('timeout() should detach all interrupts', () => { const source = new MockInterruptSource(); instance.setInterrupts([source]); instance.watch(); expect(source.isAttached).toBe(true); instance.stop(); expect(source.isAttached).toBe(false); }); it('watch(true) should not set expiry', () => { instance.watch(true); expect(expiry.last()).toBeUndefined(); instance.stop(); }); it('isIdle() should return true when idle interval elapses, and false after stop() is called', fakeAsync(() => { expiry.mockNow = new Date(); instance.watch(); expect(instance.isIdling()).toBe(false); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.stop(); expect(instance.isIdling()).toBe(false); })); it('should NOT pause interrupts when idle', fakeAsync(() => { const source = new MockInterruptSource(); instance.setInterrupts([source]); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); expect(source.isAttached).toBe(true); instance.stop(); })); it('emits an onIdleStart event when the user becomes idle', fakeAsync(() => { spyOn(instance.onIdleStart, 'emit').and.callThrough(); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.onIdleStart.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('emits an onIdleStart event if there was no "last" expiry set.', fakeAsync(() => { spyOn(instance.onIdleStart, 'emit').and.callThrough(); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); expiry.last(null); tick(3000); expect(instance.onIdleStart.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('emits an onIdleEnd event when the user returns from idle', fakeAsync(() => { spyOn(instance.onIdleEnd, 'emit').and.callThrough(); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.watch(); expect(instance.onIdleEnd.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('emits an onTimeoutWarning every second during the timeout duration', fakeAsync(() => { spyOn(instance.onTimeoutWarning, 'emit').and.callThrough(); spyOn(instance.onTimeout, 'emit').and.callThrough(); instance.setTimeout(3); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); expect(instance.onTimeoutWarning.emit).toHaveBeenCalledTimes(1); tick(1000); expect(instance.onTimeoutWarning.emit).toHaveBeenCalledTimes(2); tick(1000); expect(instance.onTimeoutWarning.emit).toHaveBeenCalledTimes(3); expect(instance.onTimeout.emit).not.toHaveBeenCalled(); instance.stop(); })); it('emits an onTimeout event when the countdown reaches 0', fakeAsync(() => { spyOn(instance.onTimeout, 'emit').and.callThrough(); instance.setTimeout(3); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); tick(1000); // going once tick(1000); // going twice tick(1000); // going thrice expect(instance.onTimeout.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('emits an onInterrupt event when the countdown ticks and expiry last has been updated', fakeAsync(() => { spyOn(instance.onInterrupt, 'emit').and.callThrough(); instance.setTimeout(3); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); tick(1000); // going once tick(1000); // going twice expiry.last(new Date(expiry.now().getTime() + 6000)); tick(1000); // going thrice expect(instance.onInterrupt.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('does not emit an onTimeoutWarning when timeout is disabled', fakeAsync(() => { spyOn(instance.onTimeoutWarning, 'emit').and.callThrough(); instance.setTimeout(false); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); tick(1000); tick(1000); expect(instance.onTimeoutWarning.emit).not.toHaveBeenCalled(); instance.stop(); })); it('does not emit an onTimeoutWarning if idle state is changed between intervals', fakeAsync(() => { spyOn(instance.onTimeoutWarning, 'emit').and.callThrough(); instance.setTimeout(3); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); // we're going to check that it's idling, then force it to not be expect(instance.isIdling()).toBe(true); // tslint:disable-next-line: no-string-literal instance['idling'] = false; expect(instance.isIdling()).toBe(false); tick(1000); tick(1000); // countdown gets called immediately when transitioning to idle, so our event will be raised // once. it shouldn't get raised after that because we forced idling to false. expect(instance.onTimeoutWarning.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('does not emit an onTimeout event timeout is disabled', fakeAsync(() => { spyOn(instance.onTimeout, 'emit').and.callThrough(); instance.setTimeout(false); expiry.mockNow = new Date(); instance.watch(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); tick(3000); expect(instance.onTimeout.emit).not.toHaveBeenCalled(); instance.stop(); })); it('interrupt() does not call watch() or emit onInterrupt if not running', () => { spyOn(instance, 'watch').and.callThrough(); spyOn(instance.onInterrupt, 'emit').and.callThrough(); instance.interrupt(); expect(instance.watch).not.toHaveBeenCalled(); expect(instance.onInterrupt.emit).not.toHaveBeenCalled(); instance.stop(); }); it('interrupt() emits onInterrupt event and include event arguments', () => { spyOn(instance.onInterrupt, 'emit').and.callThrough(); instance.watch(); const expected = { test: true }; instance.interrupt(false, expected); expect(instance.onInterrupt.emit).toHaveBeenCalledWith(expected); instance.stop(); }); it('interrupt() with the force parameter set to true calls watch()', fakeAsync(() => { instance.setAutoResume(AutoResume.disabled); instance.setIdle(3); const now = new Date(); expiry.mockNow = now; instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.interrupt(true); expect(instance.watch).toHaveBeenCalled(); instance.stop(); })); it('interrupt() with AutoResume.disabled should not call watch() when state is idle', fakeAsync(() => { instance.setAutoResume(AutoResume.disabled); instance.setIdle(3); const now = new Date(); expiry.mockNow = now; instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.interrupt(); expect(instance.watch).not.toHaveBeenCalled(); instance.stop(); })); it('interrupt() with AutoResume.disabled should not call watch() when state is not idle', fakeAsync(() => { instance.setAutoResume(AutoResume.disabled); instance.setIdle(3); instance.watch(); spyOn(instance, 'watch').and.callThrough(); tick(2000); expect(instance.isIdling()).toBe(false); instance.interrupt(); expect(instance.watch).not.toHaveBeenCalled(); instance.stop(); })); it('interrupt() with AutoResume.idle should call watch when state is idle', fakeAsync(() => { instance.setAutoResume(AutoResume.idle); instance.setIdle(3); const now = new Date(); expiry.mockNow = now; instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.interrupt(); expect(instance.watch).toHaveBeenCalled(); instance.stop(); })); it('interrupt() with AutoResume.notIdle should call watch() when state is not idle', fakeAsync(() => { instance.setAutoResume(AutoResume.notIdle); instance.setIdle(3); const now = new Date(); expiry.mockNow = now; instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(2000); expect(instance.isIdling()).toBe(false); instance.interrupt(); expect(instance.watch).toHaveBeenCalled(); instance.stop(); })); it('interrupt() with AutoResume.notIdle should not call watch() when state is idle', fakeAsync(() => { instance.setAutoResume(AutoResume.notIdle); instance.setIdle(3); expiry.mockNow = new Date(); instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); instance.interrupt(); expect(instance.watch).not.toHaveBeenCalled(); instance.stop(); })); it('interrupt() should not call watch if expiry has expired', () => { instance.setTimeout(3); instance.setIdle(3); instance.watch(); spyOn(instance, 'watch').and.callThrough(); expiry.mockNow = new Date(expiry.last().getTime() + 7000); instance.interrupt(); expect(instance.watch).not.toHaveBeenCalled(); instance.stop(); }); it('interrupt(true) should call watch(true)', () => { instance.watch(); spyOn(instance, 'watch').and.callThrough(); instance.interrupt(true); expect(instance.watch).toHaveBeenCalledWith(true); instance.stop(); }); it('triggering an interrupt source should call interrupt()', fakeAsync(() => { spyOn(instance.onInterrupt, 'emit').and.callThrough(); const source = new MockInterruptSource(); instance.setInterrupts([source]); instance.watch(); source.trigger(); // not sure why I have to pad the call with a tick for onInterrupt to be called // possibly because of RxJS throttling tick(1); expect(instance.onInterrupt.emit).toHaveBeenCalledTimes(1); instance.stop(); })); it('ngOnDestroy calls stop() and clearInterrupts()', () => { spyOn(instance, 'stop').and.callThrough(); spyOn(instance, 'clearInterrupts').and.callThrough(); instance.ngOnDestroy(); expect(instance.stop).toHaveBeenCalled(); expect(instance.clearInterrupts).toHaveBeenCalled(); }); }); }); describe('with KeepaliveSvc integration', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ MockExpiry, { provide: IdleExpiry, useExisting: MockExpiry }, { provide: KeepaliveSvc, useClass: MockKeepaliveSvc }, Idle ] }); }); let instance: Idle; let svc: MockKeepaliveSvc; let expiry: MockExpiry; beforeEach(inject( [Idle, KeepaliveSvc, MockExpiry], (idle: Idle, keepaliveSvc: MockKeepaliveSvc, mockExpiry: MockExpiry) => { instance = idle; svc = keepaliveSvc; expiry = mockExpiry; instance.setIdle(3); instance.setTimeout(3); } )); describe('runtime config', () => { it('getKeepaliveEnabled() should return true by default when service is injected.', () => { expect(instance.getKeepaliveEnabled()).toBe(true); }); it('setKeepaliveEnabled() should set and return current value.', () => { expect(instance.setKeepaliveEnabled(false)).toBe(false); }); it('setKeepaliveEnabled() should NOT stop the keepalive service when value is false', () => { spyOn(svc, 'stop').and.callThrough(); instance.setKeepaliveEnabled(false); expect(svc.stop).not.toHaveBeenCalled(); }); }); describe('watching', () => { it('should start keepalive when watch() is called', fakeAsync(() => { instance.watch(); expect(svc.isRunning).toBe(true); instance.stop(); })); it('should stop keepalive when stop() is called', fakeAsync(() => { instance.watch(); expect(svc.isRunning).toBe(true); instance.stop(); expect(svc.isRunning).toBe(false); })); it('should stop keepalive when idle', fakeAsync(() => { expiry.mockNow = new Date(); instance.watch(); expect(svc.isRunning).toBe(true); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); expect(instance.isRunning()).toBe(true); expect(svc.isRunning).toBe(false); instance.stop(); })); it('should stop keepalive when timed out', fakeAsync(() => { expiry.mockNow = new Date(); instance.watch(); expect(svc.isRunning).toBe(true); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); tick(1000); tick(1000); tick(1000); expect(instance.isIdling()).toBe(true); expect(instance.isRunning()).toBe(false); expect(svc.isRunning).toBe(false); instance.stop(); })); it('should immediately ping and restart keepalive when user returns from idle', fakeAsync(() => { spyOn(svc, 'ping').and.callThrough(); const now = new Date(); expiry.mockNow = now; instance.watch(); expect(svc.isRunning).toBe(true); expiry.mockNow = new Date( expiry.now().getTime() + instance.getIdle() * 1000 ); tick(3000); expect(instance.isIdling()).toBe(true); expect(instance.isRunning()).toBe(true); expect(svc.isRunning).toBe(false); instance.interrupt(); expect(instance.isIdling()).toBe(false); expect(instance.isRunning()).toBe(true); expect(svc.isRunning).toBe(true); expect(svc.ping).toHaveBeenCalled(); instance.stop(); })); }); }); });
the_stack
import { getAlignmentAsPoint, isNotNullish, mod } from '../Utils'; import mxClient from '../../mxClient'; import { ABSOLUTE_LINE_HEIGHT, ALIGN_BOTTOM, ALIGN_CENTER, ALIGN_LEFT, ALIGN_MIDDLE, ALIGN_RIGHT, ALIGN_TOP, DEFAULT_FONTFAMILY, DEFAULT_FONTSIZE, DIRECTION_EAST, DIRECTION_NORTH, DIRECTION_SOUTH, DIRECTION_WEST, FONT_BOLD, FONT_ITALIC, FONT_STRIKETHROUGH, FONT_UNDERLINE, LINE_HEIGHT, NONE, NS_SVG, NS_XLINK, WORD_WRAP, } from '../Constants'; import Rectangle from '../../view/geometry/Rectangle'; import AbstractCanvas2D from './AbstractCanvas2D'; import { getXml } from '../XmlUtils'; import { importNodeImplementation, isNode, write } from '../DomUtils'; import { htmlEntities, trim } from '../StringUtils'; import { AlignValue, ColorValue, DirectionValue, Gradient, GradientMap, OverflowValue, TextDirectionValue, VAlignValue, } from '../../types'; // Activates workaround for gradient ID resolution if base tag is used. const useAbsoluteIds = typeof DOMParser === 'function' && !mxClient.IS_CHROMEAPP && !mxClient.IS_EDGE && document.getElementsByTagName('base').length > 0; /** * Extends {@link mxAbstractCanvas2D} to implement a canvas for SVG. This canvas writes all calls as SVG output to the * given SVG root node. * * @example * ```javascript * var svgDoc = mxUtils.createXmlDocument(); * var root = (svgDoc.createElementNS != null) ? * svgDoc.createElementNS(mxConstants.NS_SVG, 'svg') : svgDoc.createElement('svg'); * * if (svgDoc.createElementNS == null) * { * root.setAttribute('xmlns', mxConstants.NS_SVG); * root.setAttribute('xmlns:xlink', mxConstants.NS_XLINK); * } * else * { * root.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', mxConstants.NS_XLINK); * } * * var bounds = graph.getGraphBounds(); * root.setAttribute('width', (bounds.x + bounds.width + 4) + 'px'); * root.setAttribute('height', (bounds.y + bounds.height + 4) + 'px'); * root.setAttribute('version', '1.1'); * * svgDoc.appendChild(root); * * var svgCanvas = new mxSvgCanvas2D(root); * ``` * * * To disable anti-aliasing in the output, use the following code. * @example * ```javascript * graph.view.canvas.ownerSVGElement.setAttribute('shape-rendering', 'crispEdges'); * ``` * Or set the respective attribute in the SVG element directly. */ class SvgCanvas2D extends AbstractCanvas2D { constructor(root: SVGElement, styleEnabled: boolean) { super(); /** * Variable: root * * Reference to the container for the SVG content. */ this.root = root; /** * Variable: gradients * * Local cache of gradients for quick lookups. */ this.gradients = {}; /** * Variable: defs * * Reference to the defs section of the SVG document. Only for export. */ this.defs = null; /** * Variable: styleEnabled * * Stores the value of styleEnabled passed to the constructor. */ this.styleEnabled = styleEnabled != null ? styleEnabled : false; let svg = null; // Adds optional defs section for export if (root.ownerDocument !== document) { let node: HTMLElement | SVGElement | null = root; // Finds owner SVG element in XML DOM while (node && node.nodeName !== 'svg') { node = node.parentElement; } svg = node; } if (svg) { // Tries to get existing defs section const tmp = svg.getElementsByTagName('defs'); if (tmp.length > 0) { this.defs = svg.getElementsByTagName('defs')[0]; } // Adds defs section if none exists if (!this.defs) { this.defs = this.createElement('defs') as SVGDefsElement; if (svg.firstChild != null) { svg.insertBefore(this.defs, svg.firstChild); } else { svg.appendChild(this.defs); } } // Adds stylesheet if (this.styleEnabled) { this.defs.appendChild(this.createStyle()); } } } root: SVGElement | null; gradients: GradientMap; defs: SVGDefsElement | null = null; styleEnabled = true; /** * Holds the current DOM node. */ node: SVGElement | null = null; /** * Specifies if plain text output should match the vertical HTML alignment. * @default true. */ matchHtmlAlignment = true; /** * Specifies if text output should be enabled. * @default true */ textEnabled = true; /** * Specifies if use of foreignObject for HTML markup is allowed. * @default true */ foEnabled = true; /** * Specifies the fallback text for unsupported foreignObjects in exported documents. * If this is set to `null` then no fallback text is added to the exported document. * @default [Object] */ foAltText = '[Object]'; /** * Offset to be used for foreignObjects. * @default 0 */ foOffset = 0; /** * Offset to be used for text elements. * @default 0 */ textOffset = 0; /** * Offset to be used for image elements. * @default 0 */ imageOffset = 0; /** * Adds transparent paths for strokes. * @default 0 */ strokeTolerance = 0; /** * Minimum stroke width for output. * @default 1 */ minStrokeWidth = 1; /** * Local counter for references in SVG export. * @default 0 */ refCount = 0; /** * Correction factor for {@link mxConstants.LINE_HEIGHT} in HTML output. * @default 1 */ lineHeightCorrection = 1; /** * Default value for active pointer events. * @default all */ pointerEventsValue = 'all'; /** * Padding to be added for text that is not wrapped to account for differences in font metrics on different platforms in pixels. * @default 10. */ fontMetricsPadding = 10; /** * Specifies if offsetWidth and offsetHeight should be cached. This is used to speed up repaint of text in {@link updateText}. * @default true */ cacheOffsetSize = true; originalRoot: SVGElement | null = null; /** * Updates existing DOM nodes for text rendering. */ static createCss = ( w: number, h: number, align: AlignValue, valign: string, wrap: boolean, overflow: string, clip: boolean, bg: ColorValue | null, border: ColorValue | null, flex: string, block: string, scale: number, callback: ( dx: number, dy: number, flex: string, item: string, block: string, ofl: string ) => void ) => { let item = `box-sizing: border-box; font-size: 0; text-align: ${ align === ALIGN_LEFT ? 'left' : align === ALIGN_RIGHT ? 'right' : 'center' }; `; const pt = getAlignmentAsPoint(align, valign); let ofl = 'overflow: hidden; '; let fw = 'width: 1px; '; let fh = 'height: 1px; '; let dx = pt.x * w; let dy = pt.y * h; if (clip) { fw = `width: ${Math.round(w)}px; `; item += `max-height: ${Math.round(h)}px; `; dy = 0; } else if (overflow === 'fill') { fw = `width: ${Math.round(w)}px; `; fh = `height: ${Math.round(h)}px; `; block += 'width: 100%; height: 100%; '; item += fw + fh; } else if (overflow === 'width') { fw = `width: ${Math.round(w)}px; `; block += 'width: 100%; '; item += fw; dy = 0; if (h > 0) { item += `max-height: ${Math.round(h)}px; `; } } else { ofl = ''; dy = 0; } let bgc = ''; if (bg) { bgc += `background-color: ${bg}; `; } if (border) { bgc += `border: 1px solid ${border}; `; } if (ofl == '' || clip) { block += bgc; } else { item += bgc; } if (wrap && w > 0) { block += `white-space: normal; word-wrap: ${WORD_WRAP}; `; fw = `width: ${Math.round(w)}px; `; if (ofl !== '' && overflow !== 'fill') { dy = 0; } } else { block += 'white-space: nowrap; '; if (ofl === '') { dx = 0; } } callback(dx, dy, flex + fw + fh, item + ofl, block, ofl); }; /** * Rounds all numbers to 2 decimal points. */ format(value: number) { return parseFloat(value.toFixed(2)); } /** * Returns the URL of the page without the hash part. This needs to use href to * include any search part with no params (ie question mark alone). This is a * workaround for the fact that window.location.search is empty if there is * no search string behind the question mark. */ getBaseUrl() { let { href } = window.location; const hash = href.lastIndexOf('#'); if (hash > 0) { href = href.substring(0, hash); } return href; } /** * Returns any offsets for rendering pixels. */ reset() { super.reset(); this.gradients = {}; } /** * Creates the optional style section. */ createStyle() { const style = this.createElement('style'); style.setAttribute('type', 'text/css'); write( style, `svg{font-family:${DEFAULT_FONTFAMILY};font-size:${DEFAULT_FONTSIZE};fill:none;stroke-miterlimit:10}` ); return style; } /** * Private helper function to create SVG elements */ createElement(tagName: string, namespace?: string) { return this.root?.ownerDocument.createElementNS( namespace || NS_SVG, tagName ) as SVGElement; } /** * Function: getAlternateText * * Returns the alternate text string for the given foreignObject. */ getAlternateText( fo: SVGForeignObjectElement, x: number, y: number, w: number, h: number, str: Element | string, align: AlignValue, valign: VAlignValue, wrap: boolean, format: string, overflow: OverflowValue, clip: boolean, rotation: number ) { return isNotNullish(str) ? this.foAltText : null; } /** * Function: getAlternateContent * * Returns the alternate content for the given foreignObject. */ createAlternateContent( fo: SVGForeignObjectElement, x: number, y: number, w: number, h: number, str: string, align: AlignValue, valign: VAlignValue, wrap: boolean, format: string, overflow: OverflowValue, clip: boolean, rotation: number ) { const text = this.getAlternateText( fo, x, y, w, h, str, align, valign, wrap, format, overflow, clip, rotation ); const s = this.state; if (isNotNullish(text) && s.fontSize > 0) { const dy = valign === ALIGN_TOP ? 1 : valign === ALIGN_BOTTOM ? 0 : 0.3; const anchor = align === ALIGN_RIGHT ? 'end' : align === ALIGN_LEFT ? 'start' : 'middle'; const alt = this.createElement('text'); alt.setAttribute('x', String(Math.round(x + s.dx))); alt.setAttribute('y', String(Math.round(y + s.dy + dy * s.fontSize))); alt.setAttribute('fill', s.fontColor || 'black'); alt.setAttribute('font-family', s.fontFamily); alt.setAttribute('font-size', `${Math.round(s.fontSize)}px`); // Text-anchor start is default in SVG if (anchor !== 'start') { alt.setAttribute('text-anchor', anchor); } if ((s.fontStyle & FONT_BOLD) === FONT_BOLD) { alt.setAttribute('font-weight', 'bold'); } if ((s.fontStyle & FONT_ITALIC) === FONT_ITALIC) { alt.setAttribute('font-style', 'italic'); } const txtDecor = []; if ((s.fontStyle & FONT_UNDERLINE) === FONT_UNDERLINE) { txtDecor.push('underline'); } if ((s.fontStyle & FONT_STRIKETHROUGH) === FONT_STRIKETHROUGH) { txtDecor.push('line-through'); } if (txtDecor.length > 0) { alt.setAttribute('text-decoration', txtDecor.join(' ')); } write(alt, text); return alt; } return null; } /** * Private helper function to create SVG elements */ // createGradientId(start: string, end: string, alpha1: string, alpha2: string, direction: string): string; createGradientId( start: string, end: string, alpha1: number, alpha2: number, direction: DirectionValue ) { // Removes illegal characters from gradient ID if (start.charAt(0) === '#') { start = start.substring(1); } if (end.charAt(0) === '#') { end = end.substring(1); } // Workaround for gradient IDs not working in Safari 5 / Chrome 6 // if they contain uppercase characters start = `${start.toLowerCase()}-${alpha1}`; end = `${end.toLowerCase()}-${alpha2}`; // Wrong gradient directions possible? let dir = null; if (direction == null || direction === DIRECTION_SOUTH) { dir = 's'; } else if (direction === DIRECTION_EAST) { dir = 'e'; } else { const tmp = start; start = end; end = tmp; if (direction === DIRECTION_NORTH) { dir = 's'; } else if (direction === DIRECTION_WEST) { dir = 'e'; } } return `mx-gradient-${start}-${end}-${dir}`; } /** * Private helper function to create SVG elements */ getSvgGradient( start: string, end: string, alpha1: number, alpha2: number, direction: DirectionValue ) { if (!this.root) return; const id = this.createGradientId(start, end, alpha1, alpha2, direction); let gradient: Gradient | null = this.gradients[id]; if (!gradient) { const svg = this.root.ownerSVGElement; let counter = 0; let tmpId = `${id}-${counter}`; if (svg) { gradient = <Gradient>(<unknown>svg.ownerDocument.getElementById(tmpId)); while (gradient && gradient.ownerSVGElement !== svg) { tmpId = `${id}-${counter++}`; gradient = <Gradient>(<unknown>svg.ownerDocument.getElementById(tmpId)); } } else { // Uses shorter IDs for export tmpId = `id${++this.refCount}`; } if (!gradient) { gradient = this.createSvgGradient(start, end, alpha1, alpha2, direction); gradient.setAttribute('id', tmpId); if (this.defs) { this.defs.appendChild(gradient); } else if (svg) { svg.appendChild(gradient); } } this.gradients[id] = gradient; } return gradient.getAttribute('id'); } /** * Creates the given SVG gradient. */ createSvgGradient( start: string, end: string, alpha1: number, alpha2: number, direction: DirectionValue ) { const gradient = <Gradient>this.createElement('linearGradient'); gradient.setAttribute('x1', '0%'); gradient.setAttribute('y1', '0%'); gradient.setAttribute('x2', '0%'); gradient.setAttribute('y2', '0%'); if (direction == null || direction === DIRECTION_SOUTH) { gradient.setAttribute('y2', '100%'); } else if (direction === DIRECTION_EAST) { gradient.setAttribute('x2', '100%'); } else if (direction === DIRECTION_NORTH) { gradient.setAttribute('y1', '100%'); } else if (direction === DIRECTION_WEST) { gradient.setAttribute('x1', '100%'); } let op = alpha1 < 1 ? `;stop-opacity:${alpha1}` : ''; let stop = this.createElement('stop'); stop.setAttribute('offset', '0%'); stop.setAttribute('style', `stop-color:${start}${op}`); gradient.appendChild(stop); op = alpha2 < 1 ? `;stop-opacity:${alpha2}` : ''; stop = this.createElement('stop'); stop.setAttribute('offset', '100%'); stop.setAttribute('style', `stop-color:${end}${op}`); gradient.appendChild(stop); return gradient; } /** * Private helper function to create SVG elements */ addNode(filled: boolean, stroked: boolean) { if (!this.root) return; const { node } = this; const s = this.state; if (node) { if (node.nodeName === 'path') { // Checks if the path is not empty if (this.path && this.path.length > 0) { node.setAttribute('d', this.path.join(' ')); } else { return; } } if (filled && s.fillColor !== NONE) { this.updateFill(); } else if (!this.styleEnabled) { // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=814952 if (node.nodeName === 'ellipse' && mxClient.IS_FF) { node.setAttribute('fill', 'transparent'); } else { node.setAttribute('fill', NONE); } // Sets the actual filled state for stroke tolerance filled = false; } if (stroked && s.strokeColor !== NONE) { this.updateStroke(); } else if (!this.styleEnabled) { node.setAttribute('stroke', NONE); } if (s.transform && s.transform.length > 0) { node.setAttribute('transform', s.transform); } if (s.shadow) { this.root.appendChild(this.createShadow(node)); } // Adds stroke tolerance if (this.strokeTolerance > 0 && !filled) { this.root.appendChild(this.createTolerance(node)); } // Adds pointer events if (this.pointerEvents) { node.setAttribute('pointer-events', this.pointerEventsValue); } // Enables clicks for nodes inside a link element else if (!this.pointerEvents && !this.originalRoot) { node.setAttribute('pointer-events', NONE); } // Removes invisible nodes from output if they don't handle events if ( (node.nodeName !== 'rect' && node.nodeName !== 'path' && node.nodeName !== 'ellipse') || (node.getAttribute('fill') !== NONE && node.getAttribute('fill') !== 'transparent') || node.getAttribute('stroke') !== NONE || node.getAttribute('pointer-events') !== NONE ) { // LATER: Update existing DOM for performance this.root.appendChild(node); } this.node = null; } } /** * Transfers the stroke attributes from <state> to <node>. */ updateFill() { if (!this.node) return; const s = this.state; if (s.alpha < 1 || s.fillAlpha < 1) { this.node.setAttribute('fill-opacity', String(s.alpha * s.fillAlpha)); } if (s.fillColor !== NONE) { if (s.gradientColor !== NONE) { const id = this.getSvgGradient( s.fillColor, s.gradientColor, s.gradientFillAlpha, s.gradientAlpha, s.gradientDirection ); if (this.root?.ownerDocument === document && useAbsoluteIds) { // Workaround for no fill with base tag in page (escape brackets) const base = this.getBaseUrl().replace(/([\(\)])/g, '\\$1'); this.node.setAttribute('fill', `url(${base}#${id})`); } else { this.node.setAttribute('fill', `url(#${id})`); } } else { this.node.setAttribute('fill', s.fillColor.toLowerCase()); } } } /** * Returns the current stroke width (>= 1), ie. max(1, this.format(this.state.strokeWidth * this.state.scale)). */ // getCurrentStrokeWidth(): number; getCurrentStrokeWidth() { return Math.max( this.minStrokeWidth, Math.max(0.01, this.format(this.state.strokeWidth * this.state.scale)) ); } /** * Transfers the stroke attributes from {@link mxAbstractCanvas2D.state} to {@link node}. */ updateStroke() { if (!this.node) return; const s = this.state; if (s.strokeColor !== NONE) this.node.setAttribute('stroke', s.strokeColor.toLowerCase()); if (s.alpha < 1 || s.strokeAlpha < 1) { this.node.setAttribute('stroke-opacity', String(s.alpha * s.strokeAlpha)); } const sw = this.getCurrentStrokeWidth(); if (sw !== 1) { this.node.setAttribute('stroke-width', String(sw)); } if (this.node.nodeName === 'path') { this.updateStrokeAttributes(); } if (s.dashed) { this.node.setAttribute( 'stroke-dasharray', this.createDashPattern((s.fixDash ? 1 : s.strokeWidth) * s.scale) ); } } /** * Transfers the stroke attributes from {@link mxAbstractCanvas2D.state} to {@link node}. */ updateStrokeAttributes() { if (!this.node) return; const s = this.state; // Linejoin miter is default in SVG if (s.lineJoin && s.lineJoin !== 'miter') { this.node.setAttribute('stroke-linejoin', s.lineJoin); } if (s.lineCap) { // flat is called butt in SVG let value = s.lineCap; if (value === 'flat') { value = 'butt'; } // Linecap butt is default in SVG if (value !== 'butt') { this.node.setAttribute('stroke-linecap', value); } } // Miterlimit 10 is default in our document if (s.miterLimit != null && (!this.styleEnabled || s.miterLimit !== 10)) { this.node.setAttribute('stroke-miterlimit', String(s.miterLimit)); } } /** * Creates the SVG dash pattern for the given state. */ createDashPattern(scale: number) { const pat = []; if (typeof this.state.dashPattern === 'string') { const dash = this.state.dashPattern.split(' '); if (dash.length > 0) { for (let i = 0; i < dash.length; i += 1) { pat[i] = Number(dash[i]) * scale; } } } return pat.join(' '); } /** * Creates a hit detection tolerance shape for the given node. */ // createTolerance(node: Element): Element; createTolerance(node: SVGElement) { const tol = node.cloneNode(true) as SVGElement; const sw = parseFloat(tol.getAttribute('stroke-width') || '1') + this.strokeTolerance; tol.setAttribute('pointer-events', 'stroke'); tol.setAttribute('visibility', 'hidden'); tol.removeAttribute('stroke-dasharray'); tol.setAttribute('stroke-width', String(sw)); tol.setAttribute('fill', 'none'); tol.setAttribute('stroke', 'white'); return tol; } /** * Creates a shadow for the given node. */ createShadow(node: SVGElement) { const shadow = node.cloneNode(true) as SVGElement; const s = this.state; // Firefox uses transparent for no fill in ellipses if ( shadow.getAttribute('fill') !== 'none' && (!mxClient.IS_FF || shadow.getAttribute('fill') !== 'transparent') ) { shadow.setAttribute('fill', s.shadowColor); } if (shadow.getAttribute('stroke') !== 'none' && s.shadowColor !== NONE) { shadow.setAttribute('stroke', s.shadowColor); } shadow.setAttribute( 'transform', `translate(${this.format(s.shadowDx * s.scale)},${this.format( s.shadowDy * s.scale )})${s.transform || ''}` ); shadow.setAttribute('opacity', String(s.shadowAlpha)); return shadow; } /** * Experimental implementation for hyperlinks. */ setLink(link: string) { if (!this.root) return; if (!link) { this.root = this.originalRoot; } else { this.originalRoot = this.root; const node = this.createElement('a'); // Workaround for implicit namespace handling in HTML5 export, IE adds NS1 namespace so use code below // in all IE versions except quirks mode. KNOWN: Adds xlink namespace to each image tag in output. if (node.setAttributeNS == null || this.root.ownerDocument !== document) { node.setAttribute('xlink:href', link); } else { node.setAttributeNS(NS_XLINK, 'xlink:href', link); } this.root.appendChild(node); this.root = node; } } /** * Sets the rotation of the canvas. Note that rotation cannot be concatenated. */ rotate(theta: number, flipH: boolean, flipV: boolean, cx: number, cy: number) { if (theta !== 0 || flipH || flipV) { const s = this.state; cx += s.dx; cy += s.dy; cx *= s.scale; cy *= s.scale; s.transform = s.transform || ''; // This implementation uses custom scale/translate and built-in rotation // Rotation state is part of the AffineTransform in state.transform if (flipH && flipV) { theta += 180; } else if (flipH !== flipV) { const tx = flipH ? cx : 0; const sx = flipH ? -1 : 1; const ty = flipV ? cy : 0; const sy = flipV ? -1 : 1; s.transform += `translate(${this.format(tx)},${this.format(ty)})` + `scale(${this.format(sx)},${this.format(sy)})` + `translate(${this.format(-tx)},${this.format(-ty)})`; } if (flipH ? !flipV : flipV) { theta *= -1; } if (theta !== 0) { s.transform += `rotate(${this.format(theta)},${this.format(cx)},${this.format( cy )})`; } s.rotation += theta; s.rotationCx = cx; s.rotationCy = cy; } } /** * Extends superclass to create path. */ // begin(): void; begin() { super.begin(); this.node = this.createElement('path'); } /** * Private helper function to create SVG elements */ rect(x: number, y: number, w: number, h: number) { const s = this.state; const n = this.createElement('rect'); n.setAttribute('x', String(this.format((x + s.dx) * s.scale))); n.setAttribute('y', String(this.format((y + s.dy) * s.scale))); n.setAttribute('width', String(this.format(w * s.scale))); n.setAttribute('height', String(this.format(h * s.scale))); this.node = n; } /** * Private helper function to create SVG elements */ roundrect(x: number, y: number, w: number, h: number, dx: number, dy: number) { if (!this.node) return; this.rect(x, y, w, h); if (dx > 0) { this.node.setAttribute('rx', String(this.format(dx * this.state.scale))); } if (dy > 0) { this.node.setAttribute('ry', String(this.format(dy * this.state.scale))); } } /** * Private helper function to create SVG elements */ ellipse(x: number, y: number, w: number, h: number) { const s = this.state; const n = this.createElement('ellipse'); // No rounding for consistent output with 1.x n.setAttribute('cx', String(this.format((x + w / 2 + s.dx) * s.scale))); n.setAttribute('cy', String(this.format((y + h / 2 + s.dy) * s.scale))); n.setAttribute('rx', String((w / 2) * s.scale)); n.setAttribute('ry', String((h / 2) * s.scale)); this.node = n; } /** * Function: image * * Private helper function to create SVG elements */ image( x: number, y: number, w: number, h: number, src: string, aspect = true, flipH = false, flipV = false ) { if (!this.root) return; src = this.converter.convert(src); const s = this.state; x += s.dx; y += s.dy; const node = this.createElement('image'); node.setAttribute('x', String(this.format(x * s.scale) + this.imageOffset)); node.setAttribute('y', String(this.format(y * s.scale) + this.imageOffset)); node.setAttribute('width', String(this.format(w * s.scale))); node.setAttribute('height', String(this.format(h * s.scale))); // Workaround for missing namespace support if (!node.setAttributeNS) { node.setAttribute('xlink:href', src); } else { node.setAttributeNS(NS_XLINK, 'xlink:href', src); } if (!aspect) { node.setAttribute('preserveAspectRatio', 'none'); } if (s.alpha < 1 || s.fillAlpha < 1) { node.setAttribute('opacity', String(s.alpha * s.fillAlpha)); } let tr = this.state.transform || ''; if (flipH || flipV) { let sx = 1; let sy = 1; let dx = 0; let dy = 0; if (flipH) { sx = -1; dx = -w - 2 * x; } if (flipV) { sy = -1; dy = -h - 2 * y; } // Adds image tansformation to existing transform tr += `scale(${sx},${sy})translate(${dx * s.scale},${dy * s.scale})`; } if (tr.length > 0) { node.setAttribute('transform', tr); } if (!this.pointerEvents) { node.setAttribute('pointer-events', 'none'); } this.root.appendChild(node); } /** * Converts the given HTML string to XHTML. */ convertHtml(val: string) { const doc = new DOMParser().parseFromString(val, 'text/html'); if (doc != null) { val = new XMLSerializer().serializeToString(doc.body); // Extracts body content from DOM if (val.substring(0, 5) === '<body') { val = val.substring(val.indexOf('>', 5) + 1); } if (val.substring(val.length - 7, val.length) === '</body>') { val = val.substring(0, val.length - 7); } } return val; } /** * Private helper function to create SVG elements * Note: signature changed in mxgraph 4.1.0 */ createDiv(str: string | HTMLElement) { if (!this.root) return; let val = str; if (!isNode(val)) { val = `<div><div>${this.convertHtml(val as string)}</div></div>`; } if (document.createElementNS) { const div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); if (isNode(val)) { const n = val as HTMLElement; const div2 = document.createElement('div'); const div3 = div2.cloneNode(false); // Creates a copy for export if (this.root.ownerDocument !== document) { div2.appendChild(n.cloneNode(true)); } else { div2.appendChild(n); } div3.appendChild(div2); div.appendChild(div3); } else { div.innerHTML = val as string; } return div; } if (isNode(val)) { val = `<div><div>${getXml(val)}</div></div>`; } val = `<div xmlns="http://www.w3.org/1999/xhtml">${val}</div>`; // NOTE: FF 3.6 crashes if content CSS contains "height:100%" return new DOMParser().parseFromString(val, 'text/xml').documentElement; } /** * Updates existing DOM nodes for text rendering. LATER: Merge common parts with text function below. */ updateText( x: number, y: number, w: number, h: number, align: AlignValue, valign: VAlignValue, wrap: boolean, overflow: OverflowValue, clip: boolean, rotation: number, node: SVGElement ) { if (node && node.firstChild && node.firstChild.firstChild) { this.updateTextNodes( x, y, w, h, align, valign, wrap, overflow, clip, rotation, node.firstChild as SVGElement ); } } /** * Function: addForeignObject * * Creates a foreignObject for the given string and adds it to the given root. */ addForeignObject( x: number, y: number, w: number, h: number, str: string, align: AlignValue, valign: VAlignValue, wrap: boolean, format: string, overflow: OverflowValue, clip: boolean, rotation: number, dir: TextDirectionValue, div: HTMLElement, root: SVGElement ) { const group = this.createElement('g'); const fo = this.createElement('foreignObject') as SVGForeignObjectElement; // Workarounds for print clipping and static position in Safari fo.setAttribute('style', 'overflow: visible; text-align: left;'); fo.setAttribute('pointer-events', 'none'); // Import needed for older versions of IE if (div.ownerDocument !== document) { div = importNodeImplementation(fo.ownerDocument, div, true); } fo.appendChild(div); group.appendChild(fo); this.updateTextNodes( x, y, w, h, align, valign, wrap, overflow, clip, rotation, group ); // Alternate content if foreignObject not supported if (this.root?.ownerDocument !== document) { const alt = this.createAlternateContent( fo, x, y, w, h, str, align, valign, wrap, format, overflow, clip, rotation ); if (alt != null) { fo.setAttribute( 'requiredFeatures', 'http://www.w3.org/TR/SVG11/feature#Extensibility' ); const sw = this.createElement('switch'); sw.appendChild(fo); sw.appendChild(alt); group.appendChild(sw); } } root.appendChild(group); } /** * Updates existing DOM nodes for text rendering. */ updateTextNodes( x: number, y: number, w: number, h: number, align: AlignValue, valign: VAlignValue, wrap: boolean, overflow: OverflowValue, clip: boolean, rotation: number, g: SVGElement ) { const s = this.state.scale; SvgCanvas2D.createCss( w + 2, h, align, valign, wrap, overflow, clip, this.state.fontBackgroundColor != null ? this.state.fontBackgroundColor : null, this.state.fontBorderColor != null ? this.state.fontBorderColor : null, `display: flex; align-items: unsafe ${ valign === ALIGN_TOP ? 'flex-start' : valign === ALIGN_BOTTOM ? 'flex-end' : 'center' }; ` + `justify-content: unsafe ${ align === ALIGN_LEFT ? 'flex-start' : align === ALIGN_RIGHT ? 'flex-end' : 'center' }; `, this.getTextCss(), s, (dx, dy, flex, item, block) => { x += this.state.dx; y += this.state.dy; const fo = g.firstChild as SVGElement; const div = fo.firstChild as SVGElement; const box = div.firstChild as SVGElement; const text = box.firstChild as SVGElement; const r = (this.rotateHtml ? this.state.rotation : 0) + (rotation != null ? rotation : 0); let t = (this.foOffset !== 0 ? `translate(${this.foOffset} ${this.foOffset})` : '') + (s !== 1 ? `scale(${s})` : ''); text.setAttribute('style', block); box.setAttribute('style', item); // Workaround for clipping in Webkit with scrolling and zoom fo.setAttribute('width', `${Math.ceil((1 / Math.min(1, s)) * 100)}%`); fo.setAttribute('height', `${Math.ceil((1 / Math.min(1, s)) * 100)}%`); const yp = Math.round(y + dy); // Allows for negative values which are causing problems with // transformed content where the top edge of the foreignObject // limits the text box being moved further up in the diagram. // KNOWN: Possible clipping problems with zoom and scrolling // but this is normally not used with scrollbars as the // coordinates are always positive with scrollbars. // Margin-top is ignored in Safari and no negative values allowed // for padding. if (yp < 0) { fo.setAttribute('y', String(yp)); } else { fo.removeAttribute('y'); flex += `padding-top: ${yp}px; `; } div.setAttribute('style', `${flex}margin-left: ${Math.round(x + dx)}px;`); t += r !== 0 ? `rotate(${r} ${x} ${y})` : ''; // Output allows for reflow but Safari cannot use absolute position, // transforms or opacity. https://bugs.webkit.org/show_bug.cgi?id=23113 if (t !== '') { g.setAttribute('transform', t); } else { g.removeAttribute('transform'); } if (this.state.alpha !== 1) { g.setAttribute('opacity', String(this.state.alpha)); } else { g.removeAttribute('opacity'); } } ); } /** * Private helper function to create SVG elements */ // getTextCss(): string; getTextCss() { const s = this.state; const lh = ABSOLUTE_LINE_HEIGHT ? `${s.fontSize * LINE_HEIGHT}px` : LINE_HEIGHT * this.lineHeightCorrection; let css = `display: inline-block; font-size: ${s.fontSize}px; ` + `font-family: ${s.fontFamily}; color: ${ s.fontColor }; line-height: ${lh}; pointer-events: ${ this.pointerEvents ? this.pointerEventsValue : 'none' }; `; if ((s.fontStyle & FONT_BOLD) === FONT_BOLD) { css += 'font-weight: bold; '; } if ((s.fontStyle & FONT_ITALIC) === FONT_ITALIC) { css += 'font-style: italic; '; } const deco = []; if ((s.fontStyle & FONT_UNDERLINE) === FONT_UNDERLINE) { deco.push('underline'); } if ((s.fontStyle & FONT_STRIKETHROUGH) === FONT_STRIKETHROUGH) { deco.push('line-through'); } if (deco.length > 0) { css += `text-decoration: ${deco.join(' ')}; `; } return css; } /** * Function: text * * Paints the given text. Possible values for format are empty string for plain * text and html for HTML markup. Note that HTML markup is only supported if * foreignObject is supported and <foEnabled> is true. (This means IE9 and later * does currently not support HTML text as part of shapes.) */ text( x: number, y: number, w: number, h: number, str: string, align: AlignValue, valign: VAlignValue, wrap: boolean, format: string, overflow: OverflowValue, clip: boolean, rotation = 0, dir: TextDirectionValue ) { if (!this.root) return; if (this.textEnabled && str != null) { rotation = rotation != null ? rotation : 0; if (this.foEnabled && format === 'html') { const div = this.createDiv(str); // Ignores invalid XHTML labels if (div != null) { if (dir != null) { div.setAttribute('dir', dir); } this.addForeignObject( x, y, w, h, str, align, valign, wrap, format, overflow, clip, rotation, dir, div, this.root ); } } else { this.plainText( x + this.state.dx, y + this.state.dy, w, h, str, align, valign, wrap, overflow, clip, rotation, dir ); } } } /** * Creates a clip for the given coordinates. */ createClip(x: number, y: number, w: number, h: number) { x = Math.round(x); y = Math.round(y); w = Math.round(w); h = Math.round(h); const id = `mx-clip-${x}-${y}-${w}-${h}`; let counter = 0; let tmp = `${id}-${counter}`; // Resolves ID conflicts while (document.getElementById(tmp) != null) { tmp = `${id}-${++counter}`; } const clip = this.createElement('clipPath'); clip.setAttribute('id', tmp); const rect = this.createElement('rect'); rect.setAttribute('x', String(x)); rect.setAttribute('y', String(y)); rect.setAttribute('width', String(w)); rect.setAttribute('height', String(h)); clip.appendChild(rect); return clip; } /** * Function: plainText * * Paints the given text. Possible values for format are empty string for * plain text and html for HTML markup. */ plainText( x: number, y: number, w: number, h: number, str: string, align: AlignValue, valign: VAlignValue, wrap: boolean, overflow: OverflowValue, clip: boolean, rotation = 0, dir: TextDirectionValue ) { if (!this.root) return; const s = this.state; const size = s.fontSize; const node = this.createElement('g'); let tr = s.transform || ''; this.updateFont(node); // Ignores pointer events if (!this.pointerEvents && this.originalRoot == null) { node.setAttribute('pointer-events', 'none'); } // Non-rotated text if (rotation !== 0) { tr += `rotate(${rotation},${this.format(x * s.scale)},${this.format(y * s.scale)})`; } if (dir != null) { node.setAttribute('direction', dir); } if (clip && w > 0 && h > 0) { let cx = x; let cy = y; if (align === ALIGN_CENTER) { cx -= w / 2; } else if (align === ALIGN_RIGHT) { cx -= w; } if (overflow !== 'fill') { if (valign === ALIGN_MIDDLE) { cy -= h / 2; } else if (valign === ALIGN_BOTTOM) { cy -= h; } } // LATER: Remove spacing from clip rectangle const c = this.createClip( cx * s.scale - 2, cy * s.scale - 2, w * s.scale + 4, h * s.scale + 4 ); if (this.defs != null) { this.defs.appendChild(c); } else { // Makes sure clip is removed with referencing node this.root.appendChild(c); } if ( !mxClient.IS_CHROMEAPP && !mxClient.IS_EDGE && this.root.ownerDocument === document ) { // Workaround for potential base tag const base = this.getBaseUrl().replace(/([\(\)])/g, '\\$1'); node.setAttribute('clip-path', `url(${base}#${c.getAttribute('id')})`); } else { node.setAttribute('clip-path', `url(#${c.getAttribute('id')})`); } } // Default is left const anchor = align === ALIGN_RIGHT ? 'end' : align === ALIGN_CENTER ? 'middle' : 'start'; // Text-anchor start is default in SVG if (anchor !== 'start') { node.setAttribute('text-anchor', anchor); } if (!this.styleEnabled || size !== DEFAULT_FONTSIZE) { node.setAttribute('font-size', `${size * s.scale}px`); } if (tr.length > 0) { node.setAttribute('transform', tr); } if (s.alpha < 1) { node.setAttribute('opacity', String(s.alpha)); } const lines = str.split('\n'); const lh = Math.round(size * LINE_HEIGHT); const textHeight = size + (lines.length - 1) * lh; let cy = y + size - 1; if (valign === ALIGN_MIDDLE) { if (overflow === 'fill') { cy -= h / 2; } else { const dy = (this.matchHtmlAlignment && clip && h > 0 ? Math.min(textHeight, h) : textHeight) / 2; cy -= dy; } } else if (valign === ALIGN_BOTTOM) { if (overflow === 'fill') { cy -= h; } else { const dy = this.matchHtmlAlignment && clip && h > 0 ? Math.min(textHeight, h) : textHeight; cy -= dy + 1; } } for (let i = 0; i < lines.length; i += 1) { const line = trim(lines[i]); // Workaround for bounding box of empty lines and spaces if (line) { const text = this.createElement('text'); // LATER: Match horizontal HTML alignment text.setAttribute('x', String(this.format(x * s.scale) + this.textOffset)); text.setAttribute('y', String(this.format(cy * s.scale) + this.textOffset)); write(text, line); node.appendChild(text); } cy += lh; } this.root.appendChild(node); this.addTextBackground( node, str, x, y, w, overflow === 'fill' ? h : textHeight, align, valign, overflow ); } /** * Updates the text properties for the given node. (NOTE: For this to work in * IE, the given node must be a text or tspan element.) */ updateFont(node: SVGElement) { const s = this.state; if (s.fontColor !== NONE) node.setAttribute('fill', s.fontColor); if (!this.styleEnabled || s.fontFamily !== DEFAULT_FONTFAMILY) { node.setAttribute('font-family', s.fontFamily); } if ((s.fontStyle & FONT_BOLD) === FONT_BOLD) { node.setAttribute('font-weight', 'bold'); } if ((s.fontStyle & FONT_ITALIC) === FONT_ITALIC) { node.setAttribute('font-style', 'italic'); } const txtDecor = []; if ((s.fontStyle & FONT_UNDERLINE) === FONT_UNDERLINE) { txtDecor.push('underline'); } if ((s.fontStyle & FONT_STRIKETHROUGH) === FONT_STRIKETHROUGH) { txtDecor.push('line-through'); } if (txtDecor.length > 0) { node.setAttribute('text-decoration', txtDecor.join(' ')); } } /** * Function: addTextBackground * * Background color and border */ addTextBackground( node: SVGElement, str: string, x: number, y: number, w: number, h: number, align: AlignValue, valign: VAlignValue, overflow: OverflowValue ) { const s = this.state; if (s.fontBackgroundColor != null || s.fontBorderColor != null) { let bbox = null; if (overflow === 'fill' || overflow === 'width') { if (align === ALIGN_CENTER) { x -= w / 2; } else if (align === ALIGN_RIGHT) { x -= w; } if (valign === ALIGN_MIDDLE) { y -= h / 2; } else if (valign === ALIGN_BOTTOM) { y -= h; } bbox = new Rectangle( (x + 1) * s.scale, y * s.scale, (w - 2) * s.scale, (h + 2) * s.scale ); // @ts-ignore check for getBBox } else if (node.getBBox != null && this.root.ownerDocument === document) { // Uses getBBox only if inside document for correct size try { // @ts-ignore getBBox exists bbox = node.getBBox(); bbox = new Rectangle(bbox.x, bbox.y + 1, bbox.width, bbox.height + 0); } catch (e) { // Ignores NS_ERROR_FAILURE in FF if container display is none. } } if (bbox == null || bbox.width === 0 || bbox.height === 0) { // Computes size if not in document or no getBBox available const div = document.createElement('div'); // Wrapping and clipping can be ignored here div.style.lineHeight = ABSOLUTE_LINE_HEIGHT ? `${s.fontSize * LINE_HEIGHT}px` : String(LINE_HEIGHT); div.style.fontSize = `${s.fontSize}px`; div.style.fontFamily = s.fontFamily; div.style.whiteSpace = 'nowrap'; div.style.position = 'absolute'; div.style.visibility = 'hidden'; div.style.display = 'inline-block'; if ((s.fontStyle & FONT_BOLD) === FONT_BOLD) { div.style.fontWeight = 'bold'; } if ((s.fontStyle & FONT_ITALIC) === FONT_ITALIC) { div.style.fontStyle = 'italic'; } str = htmlEntities(str, false); div.innerHTML = str.replace(/\n/g, '<br/>'); document.body.appendChild(div); const w = div.offsetWidth; const h = div.offsetHeight; document.body.removeChild(div); if (align === ALIGN_CENTER) { x -= w / 2; } else if (align === ALIGN_RIGHT) { x -= w; } if (valign === ALIGN_MIDDLE) { y -= h / 2; } else if (valign === ALIGN_BOTTOM) { y -= h; } bbox = new Rectangle( (x + 1) * s.scale, (y + 2) * s.scale, w * s.scale, (h + 1) * s.scale ); } if (bbox != null) { const n = this.createElement('rect'); n.setAttribute('fill', s.fontBackgroundColor || 'none'); n.setAttribute('stroke', s.fontBorderColor || 'none'); n.setAttribute('x', String(Math.floor(bbox.x - 1))); n.setAttribute('y', String(Math.floor(bbox.y - 1))); n.setAttribute('width', String(Math.ceil(bbox.width + 2))); n.setAttribute('height', String(Math.ceil(bbox.height))); const sw = s.fontBorderColor ? Math.max(1, this.format(s.scale)) : 0; n.setAttribute('stroke-width', String(sw)); // Workaround for crisp rendering - only required if not exporting if (this.root?.ownerDocument === document && mod(sw, 2) === 1) { n.setAttribute('transform', 'translate(0.5, 0.5)'); } node.insertBefore(n, node.firstChild); } } } /** * Paints the outline of the current path. */ stroke() { this.addNode(false, true); } /** * Fills the current path. */ fill() { this.addNode(true, false); } /** * Fills and paints the outline of the current path. */ fillAndStroke() { this.addNode(true, true); } } export default SvgCanvas2D;
the_stack
// Models import { Tab } from "../model/tab"; import { WidgetGroup } from "../model/widget_group"; import { Widget } from "../model/widget"; import { WidgetInstance } from "../model/widget_instance"; import { currentWorkspace } from "../model/workspace"; // Super classes import { Names } from "./names"; import { Trigger } from "./trigger"; // types import { Geometry } from "../types/Geometry"; declare var MyApp: any; interface TypeDef { examples: string[], fieldarraylen: number[], fieldnames: string[], fieldtypes: string[], type: string } export class Frontend { public tabContainerId: string; public tabContentContainerId: string; private Names: Names; public Trigger: Trigger; private ActiveTabId: number; constructor() { this.tabContainerId = "header2"; this.tabContentContainerId = "tabs"; this.Names = new Names(); this.Trigger = new Trigger(); } public InsertWidgetsTags(): void { currentWorkspace.getList<Widget>().forEach((value: Widget, index: number, array: Widget[]) => { $("body").append("<script type='text/javascript' src='" + value.url.slice(2) + "/main.js" + "'></script>"); // $("body").append("<link rel='stylesheet' type='text/css' href='" + value.url.slice(2) + "/main.css" + "' />"); }); } public LoadingLink(element: Element, disabled: Boolean = true) { if (disabled) { $(element).addClass("disabled"); } else { $(element).removeClass("disabled"); } } public ReleaseLink(element: Element) { this.LoadingLink(element, false); } public formTab(tab?: Tab): Tab { if (tab) { tab.name = "tab #" + tab.id; return tab; } return new Tab(); } public closeTab(tab_id: number): void { $(".jsTab[data-tab-id='" + tab_id + "']").remove(); $(".jsTabContent[data-tab-id='" + tab_id + "']").remove(); } public selectTab(tab: Tab): void { let parentClassName = this.Names.classTabParent; $("." + parentClassName).removeClass("jsActive"); $("." + parentClassName + "[data-tab-id=" + tab.id + "]").addClass("jsActive"); let className = this.Names.eventsClassPrefix + "Tab"; $("." + className).removeClass("jsActive"); $("." + className + "[data-tab-id=" + tab.id + "]").addClass("jsActive"); let tabClassName = this.Names.classTabContent; $("." + tabClassName).removeClass("jsShow").addClass("jsHide"); $("." + tabClassName + "[data-tab-id=" + tab.id + "]").removeClass("jsHide").addClass("jsShow"); this.ActiveTabId = tab.id; } public LoadWidgetContentAndInsert(widgetInstance: WidgetInstance, afterContentCallback: any): void { this._loadWidgetContentAndInsert(widgetInstance, afterContentCallback); } private _loadWidgetContentAndInsert(widgetInstance: WidgetInstance, afterContentCallback: any): void { let tabId: number = widgetInstance.tab_id != undefined ? widgetInstance.tab_id : this._getForcedCurrentTabId(); let fn = this._insertWidget; let widget: Widget = currentWorkspace.get<Widget>(widgetInstance.widget_id, "Widget"); $.ajax({ url: widget.url.slice(2) + "/index.hbs", beforeSend: function () { }, success: function (data: string) { MyApp.templates._widgetsTemplates[widget.alias] = Handlebars.compile(data); fn(widgetInstance, tabId, afterContentCallback); }, error: function (e1: any, e2: any) { throw "Widget file not found!"; } }); } public insertWidgetInstance(widgetInstance: WidgetInstance, afterContentCallback: any): void { let widget: Widget = currentWorkspace.get<Widget>(widgetInstance.widget_id, "Widget"); if (MyApp.templates._widgetsTemplates === undefined) { MyApp.templates._widgetsTemplates = []; } if (MyApp.templates._widgetsTemplates[widget.alias] === undefined) { this._loadWidgetContentAndInsert(widgetInstance, afterContentCallback); } else { let tabId: number = widgetInstance.tab_id != undefined ? widgetInstance.tab_id : this._getForcedCurrentTabId(); this._insertWidget(widgetInstance, tabId, afterContentCallback); } } private _insertWidget(widgetInstance: WidgetInstance, currentTabId: number, afterContentCallback: any): void { let content: string, html: string; let widget: Widget = currentWorkspace.get<Widget>(widgetInstance.widget_id, "Widget"); content = MyApp.templates._widgetsTemplates[widget.alias](widgetInstance); let width: number = parseInt($(content).attr("data-width")); let height: number = parseInt($(content).attr("data-height")); let left: number = $(".jsTabContent.jsShow").width() / 2; let top: number = $(".jsTabContent.jsShow").height() / 2; if (widgetInstance.position.x == 0 && widgetInstance.position.y == 0) { widgetInstance.position = { x: left, y: top }; } if (widgetInstance.size.x == 0 && widgetInstance.size.y == 0) { widgetInstance.size = { x: width, y: height }; } html = MyApp.templates.widget({ WidgetInstance: widgetInstance, content: content, left: widgetInstance.position.x + "px", top: widgetInstance.position.y + "px", width: widgetInstance.size.x + "px", height: widgetInstance.size.y + "px" }); $("div.jsTabContent[data-tab-id=" + currentTabId + "]").append(html); let trigger = new Trigger(); trigger.widgetSettings(widgetInstance.id); if (afterContentCallback != undefined) { afterContentCallback(); } } // Widget Instance properties public setWidgetInstancePosition(widgetInstance: WidgetInstance, position: Geometry.Point2D): void { $(".jsWidgetContainer[data-widget-instance-id=" + widgetInstance.id + "]").css({ top: position.y, left: position.x }); }; public setWidgetInstanceSize(widgetInstance: WidgetInstance, size: Geometry.Point2D): void { $(".jsWidgetContainer[data-widget-instance-id=" + widgetInstance.id + "]").css({ height: size.y, width: size.x }); }; private _getForcedCurrentTabId(): number { let currentTabId: number = this._getCurrentTabId(); if (currentTabId === 0) { this.Trigger.newTab(); } return this._getCurrentTabId(); } private _getCurrentTabId(): number { let tabIdStr: string = $("div.jsTab.jsActive").attr("data-tab-id"); if (tabIdStr === undefined) { return 0; } let tabId: number = parseInt(tabIdStr); return tabId; } // Show menu methods public showWidgetsMenu(): void { $(".balloon").not("." + this.Names.classWidgetsContainer).hide(); $("." + this.Names.classWidgetsContainer).animate({ height: 'toggle' }); } public ShowWidgetSettings(): void { $(".jsMenuWidgetsSettings").animate({ right: 0 }); } public HideWidgetSettings(): void { $(".jsMenuWidgetsSettings").animate({ right: -300 }); $(".jsWidgetContainer").attr("data-widget-conf", "0"); $(".jsToggleMovable").removeClass("active"); } public ShowConfiguration(): void { $(".balloon").not("." + this.Names.classConfiguration).hide(); $("." + this.Names.classConfiguration).animate({ height: 'toggle' }); } // Update Selector Methods public UpdateRosTopicSelectors(response: { topics: string[], types: string[], details: TypeDef[] }): void { $(".jsRosTopicSelector").html(""); var html = ''; $(".jsRosTopicSelector").each((i: number, element: Element) => { let elementWidgetInstance = $(".jsWidgetContainer[data-widget-instance-id=" + $(element).attr("data-widget-instance-id") + "]"); let elementMeta = $(elementWidgetInstance).find("meta[data-ros-topic-id='" + $(element).attr("data-ros-topic-id") + "']"); let subscribedTopic: string = $(elementMeta).attr("data-ros-topic-slctd"); html = MyApp.templates.rosTopicSelectorOptions({ name: '-- Select a topic to subscribe --', value: "" }); let strTypes: string = $(element).attr("data-ros-topic-type"); let types = (strTypes == "") ? [] : strTypes.split("|"); response.topics.forEach((value: string, index: number) => { let selected: boolean = (value == subscribedTopic) ? true : false; if ((types.indexOf(response.types[index]) > -1) || types.length == 0) { html += MyApp.templates.rosTopicSelectorOptions({ name: value, value: value, type: response.types[index], selected: selected }); } }); $(element).append(html); }); } public UpdateRosParamSelectors(response: string[]): void { $(".jsRosParamSelector").html(""); var html = ''; $(".jsRosParamSelector").each((i: number, element: Element) => { let elementWidgetInstance = $(".jsWidgetContainer[data-widget-instance-id=" + $(element).attr("data-widget-instance-id") + "]"); let elementMeta = $(elementWidgetInstance).find("meta[data-ros-param-id='" + $(element).attr("data-ros-param-id") + "']"); let selectedParam: string = $(elementMeta).attr("data-ros-param-slctd"); html = MyApp.templates.rosParamSelectorOptions({ name: '-- Select a param to manage --', value: "" }); response.forEach((value: string, index: number) => { let selected: boolean = (value == selectedParam) ? true : false; html += MyApp.templates.rosParamSelectorOptions({ name: value, value: value, selected: selected }); }); $(element).append(html); }); } public UpdateRosServiceSelectors(response: string[]): void { $(".jsRosServiceSelector").html(""); var html = ''; $(".jsRosServiceSelector").each((i: number, element: Element) => { let elementWidgetInstance = $(".jsWidgetContainer[data-widget-instance-id=" + $(element).attr("data-widget-instance-id") + "]"); let elementMeta = $(elementWidgetInstance).find("meta[data-ros-service-id='" + $(element).attr("data-ros-service-id") + "']"); let selectedService: string = $(elementMeta).attr("data-ros-service-slctd"); html = MyApp.templates.rosServiceSelectorOptions({ name: '-- Select a service --', value: "" }); response.forEach((value: string, index: number) => { let selected: boolean = (value == selectedService) ? true : false; html += MyApp.templates.rosServiceSelectorOptions({ name: value, value: value, selected: selected }); }); $(element).append(html); }); } public UpdateActionServerSelectors(response: string[]): void { $(".jsRosActionServerSelector").html(""); var html = ''; $(".jsRosActionServerSelector").each((i: number, element: Element) => { let elementWidgetInstance = $(".jsWidgetContainer[data-widget-instance-id=" + $(element).attr("data-widget-instance-id") + "]"); let elementMeta = $(elementWidgetInstance).find("meta[data-ros-actionserver-id='" + $(element).attr("data-ros-actionserver-id") + "']"); let selectedActionServer: string = $(elementMeta).attr("data-ros-actionserver-slctd"); html = MyApp.templates.rosActionServerSelectorOptions({ name: '-- Select an action server to subscribe --', value: "" }); let strTypes: string = $(element).attr("data-ros-actionserver-type"); let types = (strTypes == "") ? [] : strTypes.split("|"); response.forEach((value: string, index: number) => { let selected: boolean = (value == selectedActionServer) ? true : false; if ((types.indexOf(response[index]) > -1) || types.length == 0) { html += MyApp.templates.rosActionServerSelectorOptions({ name: value, value: value, selected: selected }); } }); $(element).append(html); }); } // Update Workspace Methods public ClearWorkspace() { $(".jsWidgetGroups").html(""); $(".jsTab").remove(); $("#tabs").html(""); } // Model frontend public newTab(tab: Tab): void { var tabHtml = MyApp.templates.tab(tab); var tabContentHtml = MyApp.templates.tabContent(tab); // insert tab $(tabHtml).insertBefore("#" + this.tabContainerId + " > .clearfix"); //document.getElementById(this.tabContainerId).innerHTML += tabHtml; // insert tab content document.getElementById(this.tabContentContainerId).innerHTML += tabContentHtml; } public newWidgetGroup(widgetGroup: WidgetGroup) { let html: string = MyApp.templates.widgetGroup(widgetGroup); $(".jsWidgetGroups").append(html); } public newWidget(widget: Widget) { let html = MyApp.templates.widgetItem(widget); $("#jsWidgetGroup" + widget.widget_group_id + " .jsWidgets").append(html); $("body").append("<script type='text/javascript' src='" + widget.url.slice(2) + "/main.js'></script>"); } public newWidgetInstance(widgetInstance: WidgetInstance) { this.insertWidgetInstance(widgetInstance, () => { }); } } export var frontend: Frontend = new Frontend();
the_stack
import { invariant, InvariantError } from '../../utilities/globals'; import { InlineFragmentNode, FragmentDefinitionNode, SelectionSetNode, FieldNode, } from 'graphql'; import { FragmentMap, storeKeyNameFromField, StoreValue, StoreObject, argumentsObjectFromField, Reference, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from '../../utilities'; import { IdGetter, MergeInfo, NormalizedCache, ReadMergeModifyContext, } from "./types"; import { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, } from './helpers'; import { cacheSlot } from './reactiveVars'; import { InMemoryCache } from './inMemoryCache'; import { SafeReadonly, FieldSpecifier, ToReferenceFunction, ReadFieldFunction, ReadFieldOptions, CanReadFunction, } from '../core/types/common'; import { WriteContext } from './writeToStore'; // Upgrade to a faster version of the default stable JSON.stringify function // used by getStoreKeyName. This function is used when computing storeFieldName // strings (when no keyArgs has been configured for a field). import { canonicalStringify } from './object-canon'; import { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier } from './key-extractor'; getStoreKeyName.setStringify(canonicalStringify); export type TypePolicies = { [__typename: string]: TypePolicy; } // TypeScript 3.7 will allow recursive type aliases, so this should work: // type KeySpecifier = (string | KeySpecifier)[] export type KeySpecifier = (string | KeySpecifier)[]; export type KeyFieldsContext = { // The __typename of the incoming object, even if the __typename field was // aliased to another name in the raw result object. May be undefined when // dataIdFromObject is called for objects without __typename fields. typename: string | undefined; // The object to be identified, after processing to remove aliases and // normalize identifiable child objects with references. storeObject: StoreObject; // Handy tool for reading additional fields from context.storeObject, either // readField("fieldName") to read storeObject[fieldName], or readField("name", // objectOrReference) to read from another object or Reference. If you read a // field with a read function, that function will be invoked. readField: ReadFieldFunction; // If you are writing a custom keyFields function, and you plan to use the raw // result object passed as the first argument, you may also need access to the // selection set and available fragments for this object, just in case any // fields have aliases. Since this logic is tricky to get right, and these // context properties are not even always provided (for example, they are // omitted when calling cache.identify(object), where object is assumed to be // a StoreObject), we recommend you use context.storeObject (which has already // been de-aliased) and context.readField (which can read from references as // well as objects) instead of the raw result object in your keyFields // functions, or just rely on the internal implementation of keyFields:[...] // syntax to get these details right for you. selectionSet?: SelectionSetNode; fragmentMap?: FragmentMap; // Internal. May be set by the KeyFieldsFunction to report fields that were // involved in computing the ID. Never passed in by the caller. keyObject?: Record<string, any>; }; export type KeyFieldsFunction = ( object: Readonly<StoreObject>, context: KeyFieldsContext, ) => KeySpecifier | false | ReturnType<IdGetter>; type KeyFieldsResult = Exclude<ReturnType<KeyFieldsFunction>, KeySpecifier>; // TODO Should TypePolicy be a generic type, with a TObject or TEntity // type parameter? export type TypePolicy = { // Allows defining the primary key fields for this type, either using an // array of field names or a function that returns an arbitrary string. keyFields?: KeySpecifier | KeyFieldsFunction | false; // Allows defining a merge function (or merge:true/false shorthand) to // be used for merging objects of this type wherever they appear, unless // the parent field also defines a merge function/boolean (that is, // parent field merge functions take precedence over type policy merge // functions). In many cases, defining merge:true for a given type // policy can save you from specifying merge:true for all the field // policies where that type might be encountered. merge?: FieldMergeFunction | boolean; // In the rare event that your schema happens to use a different // __typename for the root Query, Mutation, and/or Schema types, you can // express your deviant preferences by enabling one of these options. queryType?: true, mutationType?: true, subscriptionType?: true, fields?: { [fieldName: string]: | FieldPolicy<any> | FieldReadFunction<any>; } }; export type KeyArgsFunction = ( args: Record<string, any> | null, context: { typename: string; fieldName: string; field: FieldNode | null; variables?: Record<string, any>; }, ) => KeySpecifier | false | ReturnType<IdGetter>; export type FieldPolicy< // The internal representation used to store the field's data in the // cache. Must be JSON-serializable if you plan to serialize the result // of cache.extract() using JSON. TExisting = any, // The type of the incoming parameter passed to the merge function, // typically matching the GraphQL response format, but with Reference // objects substituted for any identifiable child objects. Often the // same as TExisting, but not necessarily. TIncoming = TExisting, // The type that the read function actually returns, using TExisting // data and options.args as input. Usually the same as TIncoming. TReadResult = TIncoming, // Allows FieldFunctionOptions definition to be overwritten by the // developer TOptions extends FieldFunctionOptions = FieldFunctionOptions > = { keyArgs?: KeySpecifier | KeyArgsFunction | false; read?: FieldReadFunction<TExisting, TReadResult, TOptions>; merge?: FieldMergeFunction<TExisting, TIncoming, TOptions> | boolean; }; export type StorageType = Record<string, any>; function argsFromFieldSpecifier(spec: FieldSpecifier) { return spec.args !== void 0 ? spec.args : spec.field ? argumentsObjectFromField(spec.field, spec.variables) : null; } export interface FieldFunctionOptions< TArgs = Record<string, any>, TVars = Record<string, any>, > { args: TArgs | null; // The name of the field, equal to options.field.name.value when // options.field is available. Useful if you reuse the same function for // multiple fields, and you need to know which field you're currently // processing. Always a string, even when options.field is null. fieldName: string; // The full field key used internally, including serialized key arguments. storeFieldName: string; // The FieldNode object used to read this field. Useful if you need to // know about other attributes of the field, such as its directives. This // option will be null when a string was passed to options.readField. field: FieldNode | null; variables?: TVars; // Utilities for dealing with { __ref } objects. isReference: typeof isReference; toReference: ToReferenceFunction; // A handy place to put field-specific data that you want to survive // across multiple read function calls. Useful for field-level caching, // if your read function does any expensive work. storage: StorageType; cache: InMemoryCache; // Helper function for reading other fields within the current object. // If a foreign object or reference is provided, the field will be read // from that object instead of the current object, so this function can // be used (together with isReference) to examine the cache outside the // current object. If a FieldNode is passed instead of a string, and // that FieldNode has arguments, the same options.variables will be used // to compute the argument values. Note that this function will invoke // custom read functions for other fields, if defined. Always returns // immutable data (enforced with Object.freeze in development). readField: ReadFieldFunction; // Returns true for non-normalized StoreObjects and non-dangling // References, indicating that readField(name, objOrRef) has a chance of // working. Useful for filtering out dangling references from lists. canRead: CanReadFunction; // Instead of just merging objects with { ...existing, ...incoming }, this // helper function can be used to merge objects in a way that respects any // custom merge functions defined for their fields. mergeObjects: MergeObjectsFunction; } type MergeObjectsFunction = <T extends StoreObject | Reference>( existing: T, incoming: T, ) => T; export type FieldReadFunction< TExisting = any, TReadResult = TExisting, TOptions extends FieldFunctionOptions = FieldFunctionOptions > = ( // When reading a field, one often needs to know about any existing // value stored for that field. If the field is read before any value // has been written to the cache, this existing parameter will be // undefined, which makes it easy to use a default parameter expression // to supply the initial value. This parameter is positional (rather // than one of the named options) because that makes it possible for the // developer to annotate it with a type, without also having to provide // a whole new type for the options object. existing: SafeReadonly<TExisting> | undefined, options: TOptions, ) => TReadResult | undefined; export type FieldMergeFunction< TExisting = any, TIncoming = TExisting, // Passing the whole FieldFunctionOptions makes the current definition // independent from its implementation TOptions extends FieldFunctionOptions = FieldFunctionOptions > = ( existing: SafeReadonly<TExisting> | undefined, // The incoming parameter needs to be positional as well, for the same // reasons discussed in FieldReadFunction above. incoming: SafeReadonly<TIncoming>, options: TOptions, ) => SafeReadonly<TExisting>; const nullKeyFieldsFn: KeyFieldsFunction = () => void 0; const simpleKeyArgsFn: KeyArgsFunction = (_args, context) => context.fieldName; // These merge functions can be selected by specifying merge:true or // merge:false in a field policy. const mergeTrueFn: FieldMergeFunction<any> = (existing, incoming, { mergeObjects }) => mergeObjects(existing, incoming); const mergeFalseFn: FieldMergeFunction<any> = (_, incoming) => incoming; export type PossibleTypesMap = { [supertype: string]: string[]; }; export class Policies { private typePolicies: { [__typename: string]: { keyFn?: KeyFieldsFunction; merge?: FieldMergeFunction<any>; fields: { [fieldName: string]: { keyFn?: KeyArgsFunction; read?: FieldReadFunction<any>; merge?: FieldMergeFunction<any>; }; }; }; } = Object.create(null); private toBeAdded: { [__typename: string]: TypePolicy[]; } = Object.create(null); // Map from subtype names to sets of supertype names. Note that this // representation inverts the structure of possibleTypes (whose keys are // supertypes and whose values are arrays of subtypes) because it tends // to be much more efficient to search upwards than downwards. private supertypeMap = new Map<string, Set<string>>(); // Any fuzzy subtypes specified by possibleTypes will be converted to // RegExp objects and recorded here. Every key of this map can also be // found in supertypeMap. In many cases this Map will be empty, which // means no fuzzy subtype checking will happen in fragmentMatches. private fuzzySubtypes = new Map<string, RegExp>(); public readonly cache: InMemoryCache; public readonly rootIdsByTypename: Record<string, string> = Object.create(null); public readonly rootTypenamesById: Record<string, string> = Object.create(null); public readonly usingPossibleTypes = false; constructor(private config: { cache: InMemoryCache; dataIdFromObject?: KeyFieldsFunction; possibleTypes?: PossibleTypesMap; typePolicies?: TypePolicies; }) { this.config = { dataIdFromObject: defaultDataIdFromObject, ...config, }; this.cache = this.config.cache; this.setRootTypename("Query"); this.setRootTypename("Mutation"); this.setRootTypename("Subscription"); if (config.possibleTypes) { this.addPossibleTypes(config.possibleTypes); } if (config.typePolicies) { this.addTypePolicies(config.typePolicies); } } public identify( object: StoreObject, partialContext?: Partial<KeyFieldsContext>, ): [string?, StoreObject?] { const policies = this; const typename = partialContext && ( partialContext.typename || partialContext.storeObject?.__typename ) || object.__typename; // It should be possible to write root Query fields with writeFragment, // using { __typename: "Query", ... } as the data, but it does not make // sense to allow the same identification behavior for the Mutation and // Subscription types, since application code should never be writing // directly to (or reading directly from) those root objects. if (typename === this.rootTypenamesById.ROOT_QUERY) { return ["ROOT_QUERY"]; } // Default context.storeObject to object if not otherwise provided. const storeObject = partialContext && partialContext.storeObject || object; const context: KeyFieldsContext = { ...partialContext, typename, storeObject, readField: partialContext && partialContext.readField || function () { const options = normalizeReadFieldOptions(arguments, storeObject); return policies.readField(options, { store: policies.cache["data"], variables: options.variables, }); }, }; let id: KeyFieldsResult; const policy = typename && this.getTypePolicy(typename); let keyFn = policy && policy.keyFn || this.config.dataIdFromObject; while (keyFn) { const specifierOrId = keyFn(object, context); if (Array.isArray(specifierOrId)) { keyFn = keyFieldsFnFromSpecifier(specifierOrId); } else { id = specifierOrId; break; } } id = id ? String(id) : void 0; return context.keyObject ? [id, context.keyObject] : [id]; } public addTypePolicies(typePolicies: TypePolicies) { Object.keys(typePolicies).forEach(typename => { const { queryType, mutationType, subscriptionType, ...incoming } = typePolicies[typename]; // Though {query,mutation,subscription}Type configurations are rare, // it's important to call setRootTypename as early as possible, // since these configurations should apply consistently for the // entire lifetime of the cache. Also, since only one __typename can // qualify as one of these root types, these three properties cannot // be inherited, unlike the rest of the incoming properties. That // restriction is convenient, because the purpose of this.toBeAdded // is to delay the processing of type/field policies until the first // time they're used, allowing policies to be added in any order as // long as all relevant policies (including policies for supertypes) // have been added by the time a given policy is used for the first // time. In other words, since inheritance doesn't matter for these // properties, there's also no need to delay their processing using // the this.toBeAdded queue. if (queryType) this.setRootTypename("Query", typename); if (mutationType) this.setRootTypename("Mutation", typename); if (subscriptionType) this.setRootTypename("Subscription", typename); if (hasOwn.call(this.toBeAdded, typename)) { this.toBeAdded[typename].push(incoming); } else { this.toBeAdded[typename] = [incoming]; } }); } private updateTypePolicy(typename: string, incoming: TypePolicy) { const existing = this.getTypePolicy(typename); const { keyFields, fields } = incoming; function setMerge( existing: { merge?: FieldMergeFunction | boolean; }, merge?: FieldMergeFunction | boolean, ) { existing.merge = typeof merge === "function" ? merge : // Pass merge:true as a shorthand for a merge implementation // that returns options.mergeObjects(existing, incoming). merge === true ? mergeTrueFn : // Pass merge:false to make incoming always replace existing // without any warnings about data clobbering. merge === false ? mergeFalseFn : existing.merge; } // Type policies can define merge functions, as an alternative to // using field policies to merge child objects. setMerge(existing, incoming.merge); existing.keyFn = // Pass false to disable normalization for this typename. keyFields === false ? nullKeyFieldsFn : // Pass an array of strings to use those fields to compute a // composite ID for objects of this typename. Array.isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields) : // Pass a function to take full control over identification. typeof keyFields === "function" ? keyFields : // Leave existing.keyFn unchanged if above cases fail. existing.keyFn; if (fields) { Object.keys(fields).forEach(fieldName => { const existing = this.getFieldPolicy(typename, fieldName, true)!; const incoming = fields[fieldName]; if (typeof incoming === "function") { existing.read = incoming; } else { const { keyArgs, read, merge } = incoming; existing.keyFn = // Pass false to disable argument-based differentiation of // field identities. keyArgs === false ? simpleKeyArgsFn : // Pass an array of strings to use named arguments to // compute a composite identity for the field. Array.isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs) : // Pass a function to take full control over field identity. typeof keyArgs === "function" ? keyArgs : // Leave existing.keyFn unchanged if above cases fail. existing.keyFn; if (typeof read === "function") { existing.read = read; } setMerge(existing, merge); } if (existing.read && existing.merge) { // If we have both a read and a merge function, assume // keyArgs:false, because read and merge together can take // responsibility for interpreting arguments in and out. This // default assumption can always be overridden by specifying // keyArgs explicitly in the FieldPolicy. existing.keyFn = existing.keyFn || simpleKeyArgsFn; } }); } } private setRootTypename( which: "Query" | "Mutation" | "Subscription", typename: string = which, ) { const rootId = "ROOT_" + which.toUpperCase(); const old = this.rootTypenamesById[rootId]; if (typename !== old) { invariant(!old || old === which, `Cannot change root ${which} __typename more than once`); // First, delete any old __typename associated with this rootId from // rootIdsByTypename. if (old) delete this.rootIdsByTypename[old]; // Now make this the only __typename that maps to this rootId. this.rootIdsByTypename[typename] = rootId; // Finally, update the __typename associated with this rootId. this.rootTypenamesById[rootId] = typename; } } public addPossibleTypes(possibleTypes: PossibleTypesMap) { (this.usingPossibleTypes as boolean) = true; Object.keys(possibleTypes).forEach(supertype => { // Make sure all types have an entry in this.supertypeMap, even if // their supertype set is empty, so we can return false immediately // from policies.fragmentMatches for unknown supertypes. this.getSupertypeSet(supertype, true); possibleTypes[supertype].forEach(subtype => { this.getSupertypeSet(subtype, true)!.add(supertype); const match = subtype.match(TypeOrFieldNameRegExp); if (!match || match[0] !== subtype) { // TODO Don't interpret just any invalid typename as a RegExp. this.fuzzySubtypes.set(subtype, new RegExp(subtype)); } }); }); } private getTypePolicy(typename: string): Policies["typePolicies"][string] { if (!hasOwn.call(this.typePolicies, typename)) { const policy: Policies["typePolicies"][string] = this.typePolicies[typename] = Object.create(null); policy.fields = Object.create(null); // When the TypePolicy for typename is first accessed, instead of // starting with an empty policy object, inherit any properties or // fields from the type policies of the supertypes of typename. // // Any properties or fields defined explicitly within the TypePolicy // for typename will take precedence, and if there are multiple // supertypes, the properties of policies whose types were added // later via addPossibleTypes will take precedence over those of // earlier supertypes. TODO Perhaps we should warn about these // conflicts in development, and recommend defining the property // explicitly in the subtype policy? // // Field policy inheritance is atomic/shallow: you can't inherit a // field policy and then override just its read function, since read // and merge functions often need to cooperate, so changing only one // of them would be a recipe for inconsistency. // // Once the TypePolicy for typename has been accessed, its // properties can still be updated directly using addTypePolicies, // but future changes to supertype policies will not be reflected in // this policy, because this code runs at most once per typename. const supertypes = this.supertypeMap.get(typename); if (supertypes && supertypes.size) { supertypes.forEach(supertype => { const { fields, ...rest } = this.getTypePolicy(supertype); Object.assign(policy, rest); Object.assign(policy.fields, fields); }); } } const inbox = this.toBeAdded[typename]; if (inbox && inbox.length) { // Merge the pending policies into this.typePolicies, in the order they // were originally passed to addTypePolicy. inbox.splice(0).forEach(policy => { this.updateTypePolicy(typename, policy); }); } return this.typePolicies[typename]; } private getFieldPolicy( typename: string | undefined, fieldName: string, createIfMissing: boolean, ): { keyFn?: KeyArgsFunction; read?: FieldReadFunction<any>; merge?: FieldMergeFunction<any>; } | undefined { if (typename) { const fieldPolicies = this.getTypePolicy(typename).fields; return fieldPolicies[fieldName] || ( createIfMissing && (fieldPolicies[fieldName] = Object.create(null))); } } private getSupertypeSet( subtype: string, createIfMissing: boolean, ): Set<string> | undefined { let supertypeSet = this.supertypeMap.get(subtype); if (!supertypeSet && createIfMissing) { this.supertypeMap.set(subtype, supertypeSet = new Set<string>()); } return supertypeSet; } public fragmentMatches( fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string | undefined, result?: Record<string, any>, variables?: Record<string, any>, ): boolean { if (!fragment.typeCondition) return true; // If the fragment has a type condition but the object we're matching // against does not have a __typename, the fragment cannot match. if (!typename) return false; const supertype = fragment.typeCondition.name.value; // Common case: fragment type condition and __typename are the same. if (typename === supertype) return true; if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) { const typenameSupertypeSet = this.getSupertypeSet(typename, true)!; const workQueue = [typenameSupertypeSet]; const maybeEnqueue = (subtype: string) => { const supertypeSet = this.getSupertypeSet(subtype, false); if (supertypeSet && supertypeSet.size && workQueue.indexOf(supertypeSet) < 0) { workQueue.push(supertypeSet); } }; // We need to check fuzzy subtypes only if we encountered fuzzy // subtype strings in addPossibleTypes, and only while writing to // the cache, since that's when selectionSetMatchesResult gives a // strong signal of fragment matching. The StoreReader class calls // policies.fragmentMatches without passing a result object, so // needToCheckFuzzySubtypes is always false while reading. let needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size); let checkingFuzzySubtypes = false; // It's important to keep evaluating workQueue.length each time through // the loop, because the queue can grow while we're iterating over it. for (let i = 0; i < workQueue.length; ++i) { const supertypeSet = workQueue[i]; if (supertypeSet.has(supertype)) { if (!typenameSupertypeSet.has(supertype)) { if (checkingFuzzySubtypes) { invariant.warn(`Inferring subtype ${typename} of supertype ${supertype}`); } // Record positive results for faster future lookup. // Unfortunately, we cannot safely cache negative results, // because new possibleTypes data could always be added to the // Policies class. typenameSupertypeSet.add(supertype); } return true; } supertypeSet.forEach(maybeEnqueue); if (needToCheckFuzzySubtypes && // Start checking fuzzy subtypes only after exhausting all // non-fuzzy subtypes (after the final iteration of the loop). i === workQueue.length - 1 && // We could wait to compare fragment.selectionSet to result // after we verify the supertype, but this check is often less // expensive than that search, and we will have to do the // comparison anyway whenever we find a potential match. selectionSetMatchesResult(fragment.selectionSet, result!, variables)) { // We don't always need to check fuzzy subtypes (if no result // was provided, or !this.fuzzySubtypes.size), but, when we do, // we only want to check them once. needToCheckFuzzySubtypes = false; checkingFuzzySubtypes = true; // If we find any fuzzy subtypes that match typename, extend the // workQueue to search through the supertypes of those fuzzy // subtypes. Otherwise the for-loop will terminate and we'll // return false below. this.fuzzySubtypes.forEach((regExp, fuzzyString) => { const match = typename.match(regExp); if (match && match[0] === typename) { maybeEnqueue(fuzzyString); } }); } } } return false; } public hasKeyArgs(typename: string | undefined, fieldName: string) { const policy = this.getFieldPolicy(typename, fieldName, false); return !!(policy && policy.keyFn); } public getStoreFieldName(fieldSpec: FieldSpecifier): string { const { typename, fieldName } = fieldSpec; const policy = this.getFieldPolicy(typename, fieldName, false); let storeFieldName: Exclude<ReturnType<KeyArgsFunction>, KeySpecifier>; let keyFn = policy && policy.keyFn; if (keyFn && typename) { const context: Parameters<KeyArgsFunction>[1] = { typename, fieldName, field: fieldSpec.field || null, variables: fieldSpec.variables, }; const args = argsFromFieldSpecifier(fieldSpec); while (keyFn) { const specifierOrString = keyFn(args, context); if (Array.isArray(specifierOrString)) { keyFn = keyArgsFnFromSpecifier(specifierOrString); } else { // If the custom keyFn returns a falsy value, fall back to // fieldName instead. storeFieldName = specifierOrString || fieldName; break; } } } if (storeFieldName === void 0) { storeFieldName = fieldSpec.field ? storeKeyNameFromField(fieldSpec.field, fieldSpec.variables) : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec)); } // Returning false from a keyArgs function is like configuring // keyArgs: false, but more dynamic. if (storeFieldName === false) { return fieldName; } // Make sure custom field names start with the actual field.name.value // of the field, so we can always figure out which properties of a // StoreObject correspond to which original field names. return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName : fieldName + ":" + storeFieldName; } public readField<V = StoreValue>( options: ReadFieldOptions, context: ReadMergeModifyContext, ): SafeReadonly<V> | undefined { const objectOrReference = options.from; if (!objectOrReference) return; const nameOrField = options.field || options.fieldName; if (!nameOrField) return; if (options.typename === void 0) { const typename = context.store.getFieldValue<string>(objectOrReference, "__typename"); if (typename) options.typename = typename; } const storeFieldName = this.getStoreFieldName(options); const fieldName = fieldNameFromStoreName(storeFieldName); const existing = context.store.getFieldValue<V>(objectOrReference, storeFieldName); const policy = this.getFieldPolicy(options.typename, fieldName, false); const read = policy && policy.read; if (read) { const readOptions = makeFieldFunctionOptions( this, objectOrReference, options, context, context.store.getStorage( isReference(objectOrReference) ? objectOrReference.__ref : objectOrReference, storeFieldName, ), ); // Call read(existing, readOptions) with cacheSlot holding this.cache. return cacheSlot.withValue( this.cache, read, [existing, readOptions], ) as SafeReadonly<V>; } return existing; } public getReadFunction( typename: string | undefined, fieldName: string, ): FieldReadFunction | undefined { const policy = this.getFieldPolicy(typename, fieldName, false); return policy && policy.read; } public getMergeFunction( parentTypename: string | undefined, fieldName: string, childTypename: string | undefined, ): FieldMergeFunction | undefined { let policy: | Policies["typePolicies"][string] | Policies["typePolicies"][string]["fields"][string] | undefined = this.getFieldPolicy(parentTypename, fieldName, false); let merge = policy && policy.merge; if (!merge && childTypename) { policy = this.getTypePolicy(childTypename); merge = policy && policy.merge; } return merge; } public runMergeFunction( existing: StoreValue, incoming: StoreValue, { field, typename, merge }: MergeInfo, context: WriteContext, storage?: StorageType, ) { if (merge === mergeTrueFn) { // Instead of going to the trouble of creating a full // FieldFunctionOptions object and calling mergeTrueFn, we can // simply call mergeObjects, as mergeTrueFn would. return makeMergeObjectsFunction( context.store, )(existing as StoreObject, incoming as StoreObject); } if (merge === mergeFalseFn) { // Likewise for mergeFalseFn, whose implementation is even simpler. return incoming; } // If cache.writeQuery or cache.writeFragment was called with // options.overwrite set to true, we still call merge functions, but // the existing data is always undefined, so the merge function will // not attempt to combine the incoming data with the existing data. if (context.overwrite) { existing = void 0; } return merge(existing, incoming, makeFieldFunctionOptions( this, // Unlike options.readField for read functions, we do not fall // back to the current object if no foreignObjOrRef is provided, // because it's not clear what the current object should be for // merge functions: the (possibly undefined) existing object, or // the incoming object? If you think your merge function needs // to read sibling fields in order to produce a new value for // the current field, you might want to rethink your strategy, // because that's a recipe for making merge behavior sensitive // to the order in which fields are written into the cache. // However, readField(name, ref) is useful for merge functions // that need to deduplicate child objects and references. void 0, { typename, fieldName: field.name.value, field, variables: context.variables }, context, storage || Object.create(null), )); } } function makeFieldFunctionOptions( policies: Policies, objectOrReference: StoreObject | Reference | undefined, fieldSpec: FieldSpecifier, context: ReadMergeModifyContext, storage: StorageType, ): FieldFunctionOptions { const storeFieldName = policies.getStoreFieldName(fieldSpec); const fieldName = fieldNameFromStoreName(storeFieldName); const variables = fieldSpec.variables || context.variables; const { toReference, canRead } = context.store; return { args: argsFromFieldSpecifier(fieldSpec), field: fieldSpec.field || null, fieldName, storeFieldName, variables, isReference, toReference, storage, cache: policies.cache, canRead, readField<T>() { return policies.readField<T>( normalizeReadFieldOptions(arguments, objectOrReference, context), context, ); }, mergeObjects: makeMergeObjectsFunction(context.store), }; } export function normalizeReadFieldOptions( readFieldArgs: IArguments, objectOrReference: StoreObject | Reference | undefined, variables?: ReadMergeModifyContext["variables"], ): ReadFieldOptions { const { 0: fieldNameOrOptions, 1: from, length: argc, } = readFieldArgs; let options: ReadFieldOptions; if (typeof fieldNameOrOptions === "string") { options = { fieldName: fieldNameOrOptions, // Default to objectOrReference only when no second argument was // passed for the from parameter, not when undefined is explicitly // passed as the second argument. from: argc > 1 ? from : objectOrReference, }; } else { options = { ...fieldNameOrOptions }; // Default to objectOrReference only when fieldNameOrOptions.from is // actually omitted, rather than just undefined. if (!hasOwn.call(options, "from")) { options.from = objectOrReference; } } if (__DEV__ && options.from === void 0) { invariant.warn(`Undefined 'from' passed to readField with arguments ${ stringifyForDisplay(Array.from(readFieldArgs)) }`); } if (void 0 === options.variables) { options.variables = variables; } return options; } function makeMergeObjectsFunction( store: NormalizedCache, ): MergeObjectsFunction { return function mergeObjects(existing, incoming) { if (Array.isArray(existing) || Array.isArray(incoming)) { throw new InvariantError("Cannot automatically merge arrays"); } // These dynamic checks are necessary because the parameters of a // custom merge function can easily have the any type, so the type // system cannot always enforce the StoreObject | Reference parameter // types of options.mergeObjects. if (isNonNullObject(existing) && isNonNullObject(incoming)) { const eType = store.getFieldValue(existing, "__typename"); const iType = store.getFieldValue(incoming, "__typename"); const typesDiffer = eType && iType && eType !== iType; if (typesDiffer) { return incoming; } if (isReference(existing) && storeValueIsStoreObject(incoming)) { // Update the normalized EntityStore for the entity identified by // existing.__ref, preferring/overwriting any fields contributed by the // newer incoming StoreObject. store.merge(existing.__ref, incoming); return existing; } if (storeValueIsStoreObject(existing) && isReference(incoming)) { // Update the normalized EntityStore for the entity identified by // incoming.__ref, taking fields from the older existing object only if // those fields are not already present in the newer StoreObject // identified by incoming.__ref. store.merge(existing, incoming.__ref); return incoming; } if (storeValueIsStoreObject(existing) && storeValueIsStoreObject(incoming)) { return { ...existing, ...incoming }; } } return incoming; }; }
the_stack
export class Bytes extends ByteArray { } /** An Ethereum address (20 bytes). */ export class Address extends Bytes { static fromString(s: string): Address { return typeConversion.stringToH160(s) as Address } } // Sequence of 20 `u8`s. // export type Address = Uint8Array; // Sequence of 32 `u8`s. export type Uint8 = Uint8Array; // Sequences of `u8`s. export type FixedBytes = Uint8Array; // export type Bytes = Uint8Array; /** * Enum for supported value types. */ export enum ValueKind { STRING = 0, INT = 1, BIG_DECIMAL = 2, BOOL = 3, ARRAY = 4, NULL = 5, BYTES = 6, BIG_INT = 7, } // Big enough to fit any pointer or native `this.data`. export type Payload = u64 /** * A dynamically typed value. */ export class Value { kind: ValueKind data: Payload toAddress(): Address { assert(this.kind == ValueKind.BYTES, 'Value is not an address.') return changetype<Address>(this.data as u32) } toBoolean(): boolean { if (this.kind == ValueKind.NULL) { return false; } assert(this.kind == ValueKind.BOOL, 'Value is not a boolean.') return this.data != 0 } toBytes(): Bytes { assert(this.kind == ValueKind.BYTES, 'Value is not a byte array.') return changetype<Bytes>(this.data as u32) } toI32(): i32 { if (this.kind == ValueKind.NULL) { return 0; } assert(this.kind == ValueKind.INT, 'Value is not an i32.') return this.data as i32 } toString(): string { assert(this.kind == ValueKind.STRING, 'Value is not a string.') return changetype<string>(this.data as u32) } toBigInt(): BigInt { assert(this.kind == ValueKind.BIGINT, 'Value is not a BigInt.') return changetype<BigInt>(this.data as u32) } toBigDecimal(): BigDecimal { assert(this.kind == ValueKind.BIGDECIMAL, 'Value is not a BigDecimal.') return changetype<BigDecimal>(this.data as u32) } toArray(): Array<Value> { assert(this.kind == ValueKind.ARRAY, 'Value is not an array.') return changetype<Array<Value>>(this.data as u32) } toBooleanArray(): Array<boolean> { let values = this.toArray() let output = new Array<boolean>(values.length) for (let i: i32; i < values.length; i++) { output[i] = values[i].toBoolean() } return output } toBytesArray(): Array<Bytes> { let values = this.toArray() let output = new Array<Bytes>(values.length) for (let i: i32 = 0; i < values.length; i++) { output[i] = values[i].toBytes() } return output } toStringArray(): Array<string> { let values = this.toArray() let output = new Array<string>(values.length) for (let i: i32 = 0; i < values.length; i++) { output[i] = values[i].toString() } return output } toI32Array(): Array<i32> { let values = this.toArray() let output = new Array<i32>(values.length) for (let i: i32 = 0; i < values.length; i++) { output[i] = values[i].toI32() } return output } toBigIntArray(): Array<BigInt> { let values = this.toArray() let output = new Array<BigInt>(values.length) for (let i: i32 = 0; i < values.length; i++) { output[i] = values[i].toBigInt() } return output } toBigDecimalArray(): Array<BigDecimal> { let values = this.toArray() let output = new Array<BigDecimal>(values.length) for (let i: i32 = 0; i < values.length; i++) { output[i] = values[i].toBigDecimal() } return output } static fromBooleanArray(input: Array<boolean>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromBoolean(input[i]) } return Value.fromArray(output) } static fromBytesArray(input: Array<Bytes>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromBytes(input[i]) } return Value.fromArray(output) } static fromI32Array(input: Array<i32>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromI32(input[i]) } return Value.fromArray(output) } static fromBigIntArray(input: Array<BigInt>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromBigInt(input[i]) } return Value.fromArray(output) } static fromBigDecimalArray(input: Array<BigDecimal>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromBigDecimal(input[i]) } return Value.fromArray(output) } static fromStringArray(input: Array<string>): Value { let output = new Array<Value>(input.length) for (let i: i32 = 0; i < input.length; i++) { output[i] = Value.fromString(input[i]) } return Value.fromArray(output) } static fromArray(input: Array<Value>): Value { let value = new Value() value.kind = ValueKind.ARRAY value.data = input as u64 return value } static fromBigInt(n: BigInt): Value { let value = new Value() value.kind = ValueKind.BIGINT value.data = n as u64 return value } static fromBoolean(b: boolean): Value { let value = new Value() value.kind = ValueKind.BOOL value.data = b ? 1 : 0 return value } static fromBytes(bytes: Bytes): Value { let value = new Value() value.kind = ValueKind.BYTES value.data = bytes as u64 return value } static fromNull(): Value { let value = new Value() value.kind = ValueKind.NULL return value } static fromI32(n: i32): Value { let value = new Value() value.kind = ValueKind.INT value.data = n as u64 return value } static fromString(s: string): Value { let value = new Value() value.kind = ValueKind.STRING value.data = changetype<u32>(s) return value } static fromBigDecimal(n: BigDecimal): Value { let value = new Value() value.kind = ValueKind.BIGDECIMAL value.data = n as u64 return value } } /** An arbitrary size integer represented as an array of bytes. */ export class BigInt extends Uint8Array { toHex(): string { return typeConversion.bigIntToHex(this) } toHexString(): string { return typeConversion.bigIntToHex(this) } toString(): string { return typeConversion.bigIntToString(this) } static fromI32(x: i32): BigInt { return typeConversion.i32ToBigInt(x) as BigInt } toI32(): i32 { return typeConversion.bigIntToI32(this) } @operator('+') plus(other: BigInt): BigInt { return bigInt.plus(this, other) } @operator('-') minus(other: BigInt): BigInt { return bigInt.minus(this, other) } @operator('*') times(other: BigInt): BigInt { return bigInt.times(this, other) } @operator('/') div(other: BigInt): BigInt { return bigInt.dividedBy(this, other) } divDecimal(other: BigDecimal): BigDecimal { return bigInt.dividedByDecimal(this, other) } @operator('%') mod(other: BigInt): BigInt { return bigInt.mod(this, other) } @operator('==') equals(other: BigInt): boolean { if (this.length !== other.length) { return false; } for (let i = 0; i < this.length; i++) { if (this[i] !== other[i]) { return false; } } return true; } toBigDecimal(): BigDecimal { return new BigDecimal(this) } } export class BigDecimal { exp!: BigInt digits!: BigInt constructor(bigInt: BigInt) { this.digits = bigInt this.exp = BigInt.fromI32(0) } static fromString(s: string): BigDecimal { return bigDecimal.fromString(s) } toString(): string { return bigDecimal.toString(this) } truncate(decimals: i32): BigDecimal { let digitsRightOfZero = this.digits.toString().length + this.exp.toI32() let newDigitLength = decimals + digitsRightOfZero let truncateLength = this.digits.toString().length - newDigitLength if (truncateLength < 0) { return this } else { for (let i = 0; i < truncateLength; i++) { this.digits = this.digits.div(BigInt.fromI32(10)) } this.exp = BigInt.fromI32(decimals* -1) return this } } @operator('+') plus(other: BigDecimal): BigDecimal { return bigDecimal.plus(this, other) } @operator('-') minus(other: BigDecimal): BigDecimal { return bigDecimal.minus(this, other) } @operator('*') times(other: BigDecimal): BigDecimal { return bigDecimal.times(this, other) } @operator('/') div(other: BigDecimal): BigDecimal { return bigDecimal.dividedBy(this, other) } @operator('==') equals(other: BigDecimal): boolean { return bigDecimal.equals(this, other) } } export enum TokenKind { ADDRESS = 0, FIXED_BYTES = 1, BYTES = 2, INT = 3, UINT = 4, BOOL = 5, STRING = 6, FIXED_ARRAY = 7, ARRAY = 8 } export class Token { kind: TokenKind data: Payload } // Sequence of 4 `u64`s. export type Int64 = Uint64Array; export type Uint64 = Uint64Array; /** * TypedMap entry. */ export class TypedMapEntry<K, V> { key: K value: V constructor(key: K, value: V) { this.key = key this.value = value } } /** Typed map */ export class TypedMap<K, V> { entries: Array<TypedMapEntry<K, V>> constructor() { this.entries = new Array<TypedMapEntry<K, V>>(0) } set(key: K, value: V): void { let entry = this.getEntry(key) if (entry !== null) { entry.value = value } else { let entry = new TypedMapEntry<K, V>(key, value) this.entries.push(entry) } } getEntry(key: K): TypedMapEntry<K, V> | null { for (let i: i32 = 0; i < this.entries.length; i++) { if (this.entries[i].key == key) { return this.entries[i] } } return null } get(key: K): V | null { for (let i: i32 = 0; i < this.entries.length; i++) { if (this.entries[i].key == key) { return this.entries[i].value } } return null } isSet(key: K): bool { for (let i: i32 = 0; i < this.entries.length; i++) { if (this.entries[i].key == key) { return true } } return false } } /** * Common representation for entity data, storing entity attributes * as `string` keys and the attribute values as dynamically-typed * `Value` objects. */ export class Entity extends TypedMap<string, Value> { unset(key: string): void { this.set(key, Value.fromNull()) } /** Assigns properties from sources to this Entity in right-to-left order */ merge(sources: Array<Entity>): Entity { var target = this for (let i = 0; i < sources.length; i++) { let entries = sources[i].entries for (let j = 0; j < entries.length; j++) { target.set(entries[j].key, entries[j].value) } } return target } } /** Type hint for JSON values. */ export enum JSONValueKind { NULL = 0, BOOL = 1, NUMBER = 2, STRING = 3, ARRAY = 4, OBJECT = 5, } /** * Pointer type for JSONValue data. * * Big enough to fit any pointer or native `this.data`. */ export type JSONValuePayload = u64 export class JSONValue { kind: JSONValueKind data: JSONValuePayload toString(): string { assert(this.kind == JSONValueKind.STRING, 'JSON value is not a string.') return changetype<string>(this.data as u32) } toObject(): TypedMap<string, JSONValue> { assert(this.kind == JSONValueKind.OBJECT, 'JSON value is not an object.') return changetype<TypedMap<string, JSONValue>>(this.data as u32) } } export class Wrapped<T> { inner: T; constructor(inner: T) { this.inner = inner; } } export class Result<V, E> { _value: Wrapped<V> | null; _error: Wrapped<E> | null; get isOk(): boolean { return this._value !== null; } get isError(): boolean { return this._error !== null; } get value(): V { assert(this._value != null, "Trying to get a value from an error result"); return (this._value as Wrapped<V>).inner; } get error(): E { assert( this._error != null, "Trying to get an error from a successful result" ); return (this._error as Wrapped<E>).inner; } } /** * Byte array */ class ByteArray extends Uint8Array { toHex(): string { return typeConversion.bytesToHex(this) } toHexString(): string { return typeConversion.bytesToHex(this) } toString(): string { return typeConversion.bytesToString(this) } toBase58(): string { return typeConversion.bytesToBase58(this) } }
the_stack
import { Match, Route, RouteHooks, QContext, NavigateOptions, ResolveOptions, GenerateOptions, Handler, RouterOptions, } from "../index"; import NavigoRouter from "../index"; import { pushStateAvailable, matchRoute, parseQuery, extractGETParameters, isFunction, isString, clean, parseNavigateOptions, windowAvailable, getCurrentEnvURL, accumulateHooks, extractHashFromURL, } from "./utils"; import Q from "./Q"; import setLocationPath from "./middlewares/setLocationPath"; import matchPathToRegisteredRoutes from "./middlewares/matchPathToRegisteredRoutes"; import checkForDeprecationMethods from "./middlewares/checkForDeprecationMethods"; import checkForForceOp from "./middlewares/checkForForceOp"; import updateBrowserURL from "./middlewares/updateBrowserURL"; import processMatches from "./middlewares/processMatches"; import waitingList from "./middlewares/waitingList"; import { notFoundLifeCycle } from "./lifecycles"; const DEFAULT_LINK_SELECTOR = "[data-navigo]"; export default function Navigo(appRoute?: string, options?: RouterOptions) { let DEFAULT_RESOLVE_OPTIONS: RouterOptions = options || { strategy: "ONE", hash: false, noMatchWarning: false, linksSelector: DEFAULT_LINK_SELECTOR, }; let self: NavigoRouter = this; let root = "/"; let current: Match[] = null; let routes: Route[] = []; let destroyed = false; let genericHooks: RouteHooks; const isPushStateAvailable = pushStateAvailable(); const isWindowAvailable = windowAvailable(); if (!appRoute) { console.warn( 'Navigo requires a root path in its constructor. If not provided will use "/" as default.' ); } else { root = clean(appRoute); } function _checkForAHash(url: string): string { if (url.indexOf("#") >= 0) { if (DEFAULT_RESOLVE_OPTIONS.hash === true) { url = url.split("#")[1] || "/"; } else { url = url.split("#")[0]; } } return url; } function composePathWithRoot(path: string) { return clean(`${root}/${clean(path)}`); } function createRoute( path: string | RegExp, handler: Handler, hooks: RouteHooks[], name?: string ): Route { path = isString(path) ? composePathWithRoot(path as string) : path; return { name: name || clean(String(path)), path, handler, hooks: accumulateHooks(hooks), }; } // public APIs function on( path: string | Function | Object | RegExp, handler?: Handler, hooks?: RouteHooks ) { if (typeof path === "object" && !(path instanceof RegExp)) { Object.keys(path).forEach((p) => { if (typeof path[p] === "function") { this.on(p, path[p]); } else { const { uses: handler, as: name, hooks } = path[p]; routes.push(createRoute(p, handler, [genericHooks, hooks], name)); } }); return this; } else if (typeof path === "function") { hooks = handler as RouteHooks; handler = path as Handler; path = root; } routes.push( createRoute(path as string | RegExp, handler, [genericHooks, hooks]) ); return this; } function resolve(to?: string, options?: ResolveOptions): false | Match[] { if (self.__dirty) { self.__waiting.push(() => self.resolve(to, options)); return; } else { self.__dirty = true; } to = to ? `${clean(root)}/${clean(to)}` : undefined; // console.log("-- resolve --> " + to, self.__dirty); const context: QContext = { instance: self, to, currentLocationPath: to, navigateOptions: {}, resolveOptions: { ...DEFAULT_RESOLVE_OPTIONS, ...options }, }; Q( [ setLocationPath, matchPathToRegisteredRoutes, Q.if( ({ matches }: QContext) => matches && matches.length > 0, processMatches, notFoundLifeCycle ), ], context, waitingList ); return context.matches ? context.matches : false; } function navigate(to: string, navigateOptions?: NavigateOptions): void { // console.log("-- navigate --> " + to, self.__dirty); if (self.__dirty) { self.__waiting.push(() => self.navigate(to, navigateOptions)); return; } else { self.__dirty = true; } to = `${clean(root)}/${clean(to)}`; const context: QContext = { instance: self, to, navigateOptions: navigateOptions || {}, resolveOptions: navigateOptions && navigateOptions.resolveOptions ? navigateOptions.resolveOptions : DEFAULT_RESOLVE_OPTIONS, currentLocationPath: _checkForAHash(to), }; Q( [ checkForDeprecationMethods, checkForForceOp, matchPathToRegisteredRoutes, Q.if( ({ matches }: QContext) => matches && matches.length > 0, processMatches, notFoundLifeCycle ), updateBrowserURL, waitingList, ], context, waitingList ); } function navigateByName( name: string, data?: Object, options?: NavigateOptions ): boolean { const url = generate(name, data); if (url !== null) { navigate(url.replace(new RegExp(`^\/?${root}`), ""), options); return true; } return false; } function off(what: string | RegExp | Function) { this.routes = routes = routes.filter((r) => { if (isString(what)) { return clean(r.path as string) !== clean(what as string); } else if (isFunction(what)) { return what !== r.handler; } return String(r.path) !== String(what); }); return this; } function listen() { if (isPushStateAvailable) { this.__popstateListener = () => { if (!self.__freezeListening) { resolve(); } }; window.addEventListener("popstate", this.__popstateListener); } } function destroy() { this.routes = routes = []; if (isPushStateAvailable) { window.removeEventListener("popstate", this.__popstateListener); } this.destroyed = destroyed = true; } function notFound(handler, hooks?: RouteHooks) { self._notFoundRoute = createRoute( "*", handler, [genericHooks, hooks], "__NOT_FOUND__" ); return this; } function updatePageLinks() { if (!isWindowAvailable) return; findLinks().forEach((link) => { if ( "false" === link.getAttribute("data-navigo") || "_blank" === link.getAttribute("target") ) { if (link.hasListenerAttached) { link.removeEventListener("click", link.navigoHandler); } return; } if (!link.hasListenerAttached) { link.hasListenerAttached = true; link.navigoHandler = function (e) { if ( (e.ctrlKey || e.metaKey) && e.target.tagName.toLowerCase() === "a" ) { return false; } let location = link.getAttribute("href"); if (typeof location === "undefined" || location === null) { return false; } // handling absolute paths if (location.match(/^(http|https)/) && typeof URL !== "undefined") { try { const u = new URL(location); location = u.pathname + u.search; } catch (err) {} } const options = parseNavigateOptions( link.getAttribute("data-navigo-options") ); if (!destroyed) { e.preventDefault(); e.stopPropagation(); self.navigate(clean(location), options); } }; link.addEventListener("click", link.navigoHandler); } }); return self; } function findLinks() { if (isWindowAvailable) { return [].slice.call( document.querySelectorAll( DEFAULT_RESOLVE_OPTIONS.linksSelector || DEFAULT_LINK_SELECTOR ) ); } return []; } function link(path: string) { return `/${root}/${clean(path)}`; } function setGenericHooks(hooks: RouteHooks) { genericHooks = hooks; return this; } function lastResolved(): Match[] | null { return current; } function generate( name: string, data?: Object, options?: GenerateOptions ): string { const route = routes.find((r) => r.name === name); let result = null; if (route) { result = route.path as string; if (data) { for (let key in data) { result = result.replace(":" + key, data[key]); } } result = !result.match(/^\//) ? `/${result}` : result; } if (result && options && !options.includeRoot) { result = result.replace(new RegExp(`^/${root}`), ""); } return result; } function getLinkPath(link) { return link.getAttribute("href"); } function pathToMatchObject(path: string): Match { const [url, queryString] = extractGETParameters(clean(path)); const params = queryString === "" ? null : parseQuery(queryString); const hashString = extractHashFromURL(path); const route = createRoute(url, () => {}, [genericHooks], url); return { url, queryString, hashString, route, data: null, params: params, }; } function getCurrentLocation(): Match { return pathToMatchObject( clean(getCurrentEnvURL(root)).replace(new RegExp(`^${root}`), "") ); } function directMatchWithRegisteredRoutes(path: string): false | Match[] { const context: QContext = { instance: self, currentLocationPath: path, to: path, navigateOptions: {}, resolveOptions: DEFAULT_RESOLVE_OPTIONS, }; matchPathToRegisteredRoutes(context, () => {}); return context.matches ? context.matches : false; } function directMatchWithLocation( path: string | RegExp, currentLocation?: string, annotatePathWithRoot?: boolean ): false | Match { if ( typeof currentLocation !== "undefined" && (typeof annotatePathWithRoot === "undefined" || annotatePathWithRoot) ) { currentLocation = composePathWithRoot(currentLocation); } const context: QContext = { instance: self, to: currentLocation, currentLocationPath: currentLocation, }; setLocationPath(context, () => {}); if (typeof path === "string") { path = typeof annotatePathWithRoot === "undefined" || annotatePathWithRoot ? composePathWithRoot(path) : path; } const match = matchRoute(context, { name: String(path), path, handler: () => {}, hooks: {}, }); return match ? match : false; } function addHook( type: string, route: Route | string, func: Function ): Function { if (typeof route === "string") { route = getRoute(route); } if (route) { if (!route.hooks[type]) route.hooks[type] = []; route.hooks[type].push(func); return () => { (route as Route).hooks[type] = (route as Route).hooks[type].filter( (f) => f !== func ); }; } else { console.warn(`Route doesn't exists: ${route}`); } return () => {}; } function getRoute(nameOrHandler: string | Function): Route | undefined { if (typeof nameOrHandler === "string") { return routes.find((r) => r.name === composePathWithRoot(nameOrHandler)); } return routes.find((r) => r.handler === nameOrHandler); } function __markAsClean(context: QContext) { context.instance.__dirty = false; if (context.instance.__waiting.length > 0) { context.instance.__waiting.shift()(); } } this.root = root; this.routes = routes; this.destroyed = destroyed; this.current = current; this.__freezeListening = false; this.__waiting = []; this.__dirty = false; this.__markAsClean = __markAsClean; this.on = on; this.off = off; this.resolve = resolve; this.navigate = navigate; this.navigateByName = navigateByName; this.destroy = destroy; this.notFound = notFound; this.updatePageLinks = updatePageLinks; this.link = link; this.hooks = setGenericHooks; this.extractGETParameters = (url) => extractGETParameters(_checkForAHash(url)); this.lastResolved = lastResolved; this.generate = generate; this.getLinkPath = getLinkPath; this.match = directMatchWithRegisteredRoutes; this.matchLocation = directMatchWithLocation; this.getCurrentLocation = getCurrentLocation; this.addBeforeHook = addHook.bind(this, "before"); this.addAfterHook = addHook.bind(this, "after"); this.addAlreadyHook = addHook.bind(this, "already"); this.addLeaveHook = addHook.bind(this, "leave"); this.getRoute = getRoute; this._pathToMatchObject = pathToMatchObject; this._clean = clean; this._checkForAHash = _checkForAHash; this._setCurrent = (c) => (current = self.current = c); listen.call(this); updatePageLinks.call(this); }
the_stack
import { observable, action, toJS, computed } from "mobx"; import moment from "moment"; import ILanguage from "../interface/ILanguage"; import ICategory from "../interface/ICategory"; import GroupType from "../enum/GroupType"; import SearchType from "../enum/SearchType"; import OrderBy from "../enum/OrderBy"; import { IGroupConditionState, ISearchConditionState, IOrderConditionState, IFilterConditionState } from "../interface/IConditional"; import GlobalStore from "../store/GlobalStore"; import DBHandler from "../rxdb/dbHandler"; import logger from "../utils/logger"; import IRepo from "../interface/IRepo"; import GithubClient from "../utils/githubClient"; import ITag from "renderer/interface/ITag"; import IContributor from "renderer/interface/IContributor"; export default class MainStore { private globalStore: GlobalStore; constructor(globalStore: GlobalStore) { this.globalStore = globalStore; } private getDbHandler = () => { return this.globalStore.getDb().then(db => { return new DBHandler(db); }); }; public startup = () => { return this.globalStore.restore().then(() => { this.updateCategoryList(); this.updateLanguageList(); this.updateRepoList(); return this.fetchRemoteRepos(); }); }; /** * Fetch status */ @observable fetching: boolean = false; /** * Languages */ @observable languages: ILanguage[] = []; @action updateLanguageList = () => { return this.getDbHandler() .then(dbHandler => dbHandler.initDB()) .then(dbHandler => dbHandler.getLanguages()) .then(languages => { this.languages = languages; return languages; }) .catch(error => { logger.log(error.message || error.toString()); }); }; /** * Categories */ @observable categories: ICategory[] = []; @action updateCategoryList = () => { return this.getDbHandler() .then(dbHandler => dbHandler.initDB()) .then(dbHandler => dbHandler.getCategories()) .then(categories => { this.categories = categories; return categories; }) .catch(error => { logger.log(error.message || error.toString()); }); }; @action addNewCategory = (name: string) => { const { categories } = this; return this.getDbHandler() .then(dbHandler => dbHandler.initDB()) .then(dbHandler => dbHandler.upsertCategory(name)) .then(categoryDoc => { this.categories = new Array().concat(categories).concat(categoryDoc.toJSON()); return categoryDoc; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action delCategory = (id: number) => { return this.getDbHandler() .then(dbHandler => dbHandler.initDB()) .then(dbHandler => dbHandler.deleteCategory(id)) .then(() => { this.updateCategoryList(); return true; }) .catch(error => { logger.log(error.message || error.toString()); }); }; /** * Search condition */ @observable search: ISearchConditionState = { key: "", field: SearchType.SEARCH_FIELD_ALL }; @action onUpdateSearchCondition = (key: string, field: SearchType) => { const { search, repos } = this; if (key !== search.key || field !== search.field) { this.search = { key, field }; return this.updateRepoList(); } return Promise.resolve(toJS(repos)); }; /** * Order condition */ @observable order: IOrderConditionState = { by: OrderBy.ORDER_BY_DEFAULT, desc: true }; @action onUpdateOrderCondition = (desc: boolean, by: OrderBy) => { logger.log(`Sort: ${by} ${desc ? "DESC" : "ASC"}`); const { order, repos } = this; if (order.desc !== desc || order.by !== by) { this.order = { desc, by }; return this.updateRepoList(); } return Promise.resolve(toJS(repos)); }; /** * filter condition */ @observable filter: IFilterConditionState = { hasFlag: false, hasNote: false, unread: false }; @action onUpdateFilterCondition = (newFilter: IFilterConditionState) => { logger.log(`Filter: ${newFilter}`); const { filter, repos } = this; if ( filter.hasFlag !== newFilter.hasFlag || filter.hasNote !== newFilter.hasNote || filter.unread !== newFilter.unread ) { this.filter = newFilter; return this.updateRepoList(); } return Promise.resolve(toJS(repos)); }; /** * Group condition */ @observable group: IGroupConditionState = { id: GroupType.GROUP_TYPE_ALL, type: GroupType.GROUP_TYPE_ALL }; @observable openNavMenus: GroupType[] = [GroupType.GROUP_TYPE_ALL]; @action onClickNavMenuItem = ({ key, keyPath }) => { if (this.fetching) { return; // not available when fetching data } let group; if (keyPath.length === 1) { group = { id: key, type: key }; } else { group = { id: key, type: keyPath[1] }; } if (group.id === this.group.id) { return; } this.group = group; this.updateRepoList(); }; @action onToggleNavMenus = (openKeys: GroupType[]) => { const { openNavMenus } = this; const latestOpenKey = openKeys.find(key => !(openNavMenus.indexOf(key) > -1)); let nextOpenKeys: GroupType[] = []; if (latestOpenKey) { nextOpenKeys = new Array().concat(latestOpenKey); } this.openNavMenus = nextOpenKeys; }; /** * Repos */ @observable repos: IRepo[] = []; @observable reposMap: { [key: string]: IRepo } = {}; @action updateRepoList = () => { logger.log("Update repo list"); const { group, search, order, filter } = this; const conditions = { group, search, order, filter }; return this.getDbHandler() .then(dbHandler => dbHandler.getRepos(conditions)) .then(repos => { // for easily replace one specified item of list // we need convert the array to key-value pairs let keyedRepos: { [key: string]: IRepo } = {}; repos.forEach(repo => { keyedRepos[repo.id] = repo; }); this.repos = repos; this.reposMap = keyedRepos; const total = repos.length; const maxPage = Math.ceil(total / this.pageSize); this.total = total; if (this.page > maxPage) { this.page = 1; } return repos; }) .catch(error => { logger.log(error.message || error.toString()); // throw error; }); }; @action fetchRemoteRepos = () => { if (this.fetching) { return Promise.reject(false); } const client = new GithubClient(this.globalStore.credentials); this.fetching = true; return client .getStarredRepos() .then(ret => ret.data) .then(repos => { return this.getDbHandler() .then(dbHandler => { return Promise.all([ dbHandler.upsertRepos(repos), dbHandler.upsertOwners(repos), dbHandler.upsertLanguages(repos), dbHandler.recordReposCount(repos.length) ]); }) .then(ret => { this.updateLanguageList(); this.updateRepoList(); // return repo count change return ret[3]; }); }) .catch(error => { logger.log(error.message || error.toString()); this.updateRepoList(); throw error; }) .finally(() => { this.fetching = false; }); }; /** * Selected repo */ @observable selectedRepo: IRepo; @action onSelectRepo = (id: number) => { logger.log(`Select repo: ${id}`); const { reposMap, selectedRepo } = this; if (selectedRepo && selectedRepo.id === id) { return; } const newRepo = reposMap[id]; this.selectedRepo = newRepo; this.selectRepoTags = []; this.selectRepoCategories = []; this.selectRepoContributors = []; if (newRepo && !newRepo._contributors) { logger.log(`Fetch and get repo contributors for selected repo ${newRepo.id}`); this.onFetchRepoContributors(newRepo); this.onGetSelectRepoContributors(newRepo.id); this.onGetTagsForRepo(newRepo.id); this.onGetSelectRepoCategories(newRepo.id); } }; @action onRateRepo = (id: number, score: number) => { logger.log(`Rate repo: ${id}`); const updateObj = { id, score }; return this.getDbHandler() .then(dbHandler => dbHandler.updateRepo(updateObj)) .then(repo => { // also replace new repo into repos list this.replaceOneRepoInList(repo); return repo; }) .catch(error => { logger.log(error.message || error.toString()); // throw error; }); }; /** * Star StarCabinet */ onStarStarCabinet = () => { const client = new GithubClient(this.globalStore.credentials); return client .starStarCabinet() .then(ret => { return ret; }) .catch(error => { logger.log(error.message || error.toString()); throw new Error(error); }); }; /** * Replace one repo in list */ @action replaceOneRepoInList = (repo: IRepo) => { let { repos, reposMap } = this; reposMap[repo.id] = repo; repos = repos.map(item => reposMap[item.id]); this.repos = Array.from(repos); this.reposMap = Object.assign({}, reposMap); }; /** * Update select repo(flag, read status, note...) */ @action onUpdateSelectedRepo = (id: number, properties: { [key: string]: any }) => { const { selectedRepo } = this; if (!selectedRepo || id !== selectedRepo.id) { return Promise.reject(false); } properties.id = id; return this.getDbHandler() .then(dbHandler => dbHandler.updateRepo(properties)) .then(repo => { // also replace the repo in repos list repo._hotChange = Object.keys(properties); // mark the repo that its readme etc.. has fetched, do not fetch again this.replaceOneRepoInList(repo); this.selectedRepo = Object.assign({}, selectedRepo, repo); return repo; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; /** * Update repo categories */ @action onUpdateRepoCategories = (id: number, catIds: number[]) => { return this.getDbHandler() .then(dbHandler => dbHandler.updateRepoCategories(id, catIds)) .then(repo => { // also replace the repo in repos list this.replaceOneRepoInList(repo); // if it has same id with selectedRepo, also replace selectedRepo this.onUpdateSelectedRepo(id, { rxChange: Math.floor(moment.now().valueOf() / 1000) }); if (this.selectedRepo.id === id) { this.selectRepoCategories = repo._categories; } // update all categories list, for updating the nav category node this.updateCategoryList(); return repo; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; /** * Update repo contributors */ @action onUpdateRepoContributors = (id: number, contributors) => { return this.getDbHandler() .then(dbHandler => dbHandler.upsertContributors(id, contributors)) .then(_contributors => { // also replace the repo in repos list let repo = this.reposMap[id]; if (repo) { repo._contributors = _contributors; repo._hotChange = ["contributors"]; this.replaceOneRepoInList(repo); if (repo.id === this.selectedRepo.id) { this.selectRepoContributors = _contributors; } } // if it has same id with selectedRepo, also replace selectedRepo this.onUpdateSelectedRepo(id, { rxChange: Math.floor(moment.now().valueOf() / 1000) }); return repo; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action onAddTagForRepo = (id: number, tagName: string) => { logger.log(`Adding tag: ${tagName} for repo: ${id}`); return this.getDbHandler() .then(dbHandler => dbHandler.addRepoTag(id, tagName)) .then(repo => { // also replace the repo in repos list this.replaceOneRepoInList(repo); if (this.selectedRepo.id === id) { this.selectRepoTags = repo._tags; } // if it has same id with selectedRepo, also replace selectedRepo this.onUpdateSelectedRepo(id, { rxChange: Math.floor(moment.now().valueOf() / 1000) }); return repo; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action onRemoveTagForRepo = (id: number, tagName: string) => { return this.getDbHandler() .then(dbHandler => dbHandler.removeRepoTag(id, tagName)) .then(repo => { // also replace the repo in repos list this.replaceOneRepoInList(repo); if (this.selectedRepo.id === id) { this.selectRepoTags = repo._tags; } // if it has same id with selectedRepo, also replace selectedRepo this.onUpdateSelectedRepo(id, { rxChange: Math.floor(moment.now().valueOf() / 1000) }); return repo; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action onGetTagsForRepo = (id: number) => { return this.getDbHandler() .then(dbHandler => dbHandler.getRepoTags(id)) .then(tags => { // also add tags to the repo and replace the repo in repos list let repo = this.reposMap[id]; if (repo) { repo._tags = tags; this.replaceOneRepoInList(repo); if (this.selectedRepo.id === repo.id) { this.selectRepoTags = tags; } } return tags; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action onFetchRepoReadMe = (repo: IRepo) => { const client = new GithubClient(this.globalStore.credentials); return client .getRepoReadMe(repo.fullName, repo.defaultBranch) .then(readme => { if (repo.readme !== readme) { this.onUpdateSelectedRepo(repo.id, { readme }); } return readme; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; @action onFetchRepoContributors = (repo: IRepo) => { const client = new GithubClient(this.globalStore.credentials); return client .getRepoContributors(repo.fullName) .then(contributors => { // save contributors to db this.onUpdateRepoContributors(repo.id, contributors); return contributors; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; /** * Get contributors for selected repo */ @action onGetSelectRepoContributors = (id: number) => { const { selectedRepo } = this; if (!selectedRepo || selectedRepo.id !== id) { return Promise.reject(false); } return this.getDbHandler() .then(dbHandler => dbHandler.getRepoContributors(id)) .then(contributors => { // also add contributors to the repo and replace the repo in repos list let repo = this.reposMap[id]; if (repo) { repo._contributors = contributors; repo._hotChange = ["contributors"]; this.replaceOneRepoInList(repo); if (repo.id === this.selectedRepo.id) { this.selectRepoContributors = contributors; } } // if it has same id with selectedRepo, also replace selectedRepo this.onUpdateSelectedRepo(id, { rxChange: Math.floor(moment.now().valueOf() / 1000) }); return contributors; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; /** * Get categories for selected repo */ @action onGetSelectRepoCategories = (id: number) => { const { selectedRepo } = this; if (!selectedRepo || selectedRepo.id !== id) { return Promise.reject(false); } return this.getDbHandler() .then(dbHandler => dbHandler.getRepoCategories(id)) .then(categories => { // also add categories to the repo and replace the repo in repos list let repo = this.reposMap[id]; if (repo) { repo._categories = categories; this.replaceOneRepoInList(repo); if (this.selectedRepo.id === repo.id) { this.selectRepoCategories = categories; } } return categories; }) .catch(error => { logger.log(error.message || error.toString()); throw error; }); }; /** * Ext properties for selected repo */ @observable selectRepoTags: ITag[] = []; @observable selectRepoContributors: IContributor[] = []; @observable selectRepoCategories: ICategory[] = []; /** * Pagination */ @observable page: number = 1; @observable pageSize: number = 20; @observable total: number = 0; @computed get pageRepos() { const { page, pageSize, repos } = this; const list = repos.slice((page - 1) * pageSize, page * pageSize); return list; } @action onPageChange = (page: number) => { logger.log(`Change page to: ${page}`); this.page = page; }; @action resetPagination = () => { this.page = 1; this.pageSize = 20; }; }
the_stack
import {IsReferencedOptions} from "./is-referenced-options"; import {ReferenceVisitorOptions} from "./reference-visitor-options"; import {checkClassDeclaration} from "./visitor/check-class-declaration"; import {checkIdentifier} from "./visitor/check-identifier"; import {checkClassExpression} from "./visitor/check-class-expression"; import {checkInterfaceDeclaration} from "./visitor/check-interface-declaration"; import {checkEnumDeclaration} from "./visitor/check-enum-declaration"; import {checkTypeAliasDeclaration} from "./visitor/check-type-alias-declaration"; import {checkFunctionDeclaration} from "./visitor/check-function-declaration"; import {checkFunctionExpression} from "./visitor/check-function-expression"; import {checkVariableDeclaration} from "./visitor/check-variable-declaration"; import {checkExportSpecifier} from "./visitor/check-export-specifier"; import {NodeToReferencedIdentifiersCache} from "../cache/reference-cache"; import {checkArrayBindingPattern} from "./visitor/check-array-binding-pattern"; import {checkObjectBindingPattern} from "./visitor/check-object-binding-pattern"; import {checkBindingElement} from "./visitor/check-binding-element"; import {checkMethodDeclaration} from "./visitor/check-method-declaration"; import {checkMethodSignature} from "./visitor/check-method-signature"; import {checkPropertyDeclaration} from "./visitor/check-property-declaration"; import {checkPropertySignature} from "./visitor/check-property-signature"; import {checkGetAccessorDeclaration} from "./visitor/check-get-accessor-declaration"; import {checkSetAccessorDeclaration} from "./visitor/check-set-accessor-declaration"; import {checkParameterDeclaration} from "./visitor/check-parameter-declaration"; import {checkVariableDeclarationList} from "./visitor/check-variable-declaration-list"; import {checkVariableStatement} from "./visitor/check-variable-statement"; import {checkExportDeclaration} from "./visitor/check-export-declaration"; import {checkExportAssignment} from "./visitor/check-export-assignment"; import {checkModuleDeclaration} from "./visitor/check-module-declaration"; import {checkIndexedAccessTypeNode} from "./visitor/check-indexed-access-type-node"; import {checkPropertyAccessExpression} from "./visitor/check-property-access-expression"; import {checkQualifiedName} from "./visitor/check-qualified-name"; import {TS} from "../../../../../../type/ts"; import {nodeContainsChild} from "../../../util/node-contains-child"; import {hasExportModifier} from "../../../util/modifier-util"; import {traceIdentifiers} from "../../trace-identifiers/trace-identifiers"; import {checkTemplateLiteralTypeNode} from "./visitor/check-template-literal-type-node"; import {isTemplateLiteralTypeNode} from "../../../../../../util/predicates/predicates"; import {checkTemplateLiteralTypeSpan} from "./visitor/check-template-literal-type-span"; import {checkTypeReferenceNode} from "./visitor/check-type-reference-node"; /** * Visits the given node. Returns true if it references the node to check for references, and false otherwise */ function checkNode({node, originalNode, ...options}: ReferenceVisitorOptions): string[] { if (options.typescript.isArrayBindingPattern(node)) { return checkArrayBindingPattern({node, originalNode, ...options}); } else if (options.typescript.isObjectBindingPattern(node)) { return checkObjectBindingPattern({node, originalNode, ...options}); } else if (options.typescript.isParameter(node)) { return checkParameterDeclaration({node, originalNode, ...options}); } else if (options.typescript.isQualifiedName(node)) { return checkQualifiedName({node, originalNode, ...options}); } else if (options.typescript.isBindingElement(node)) { return checkBindingElement({node, originalNode, ...options}); } else if (options.typescript.isMethodDeclaration(node)) { return checkMethodDeclaration({node, originalNode, ...options}); } else if (options.typescript.isMethodSignature(node)) { return checkMethodSignature({node, originalNode, ...options}); } else if (options.typescript.isGetAccessorDeclaration(node)) { return checkGetAccessorDeclaration({node, originalNode, ...options}); } else if (options.typescript.isSetAccessorDeclaration(node)) { return checkSetAccessorDeclaration({node, originalNode, ...options}); } else if (options.typescript.isPropertyAccessExpression(node)) { return checkPropertyAccessExpression({node, originalNode, ...options}); } else if (options.typescript.isPropertyDeclaration(node)) { return checkPropertyDeclaration({node, originalNode, ...options}); } else if (options.typescript.isPropertySignature(node)) { return checkPropertySignature({node, originalNode, ...options}); } else if (options.typescript.isClassDeclaration(node)) { return checkClassDeclaration({node, originalNode, ...options}); } else if (options.typescript.isClassExpression(node)) { return checkClassExpression({node, originalNode, ...options}); } else if (options.typescript.isFunctionDeclaration(node)) { return checkFunctionDeclaration({node, originalNode, ...options}); } else if (options.typescript.isFunctionExpression(node)) { return checkFunctionExpression({node, originalNode, ...options}); } else if (options.typescript.isInterfaceDeclaration(node)) { return checkInterfaceDeclaration({node, originalNode, ...options}); } else if (options.typescript.isEnumDeclaration(node)) { return checkEnumDeclaration({node, originalNode, ...options}); } else if (options.typescript.isTypeAliasDeclaration(node)) { return checkTypeAliasDeclaration({node, originalNode, ...options}); } else if (options.typescript.isIndexedAccessTypeNode(node)) { return checkIndexedAccessTypeNode({node, originalNode, ...options}); } else if (options.typescript.isVariableStatement(node)) { return checkVariableStatement({node, originalNode, ...options}); } else if (options.typescript.isVariableDeclarationList(node)) { return checkVariableDeclarationList({node, originalNode, ...options}); } else if (options.typescript.isVariableDeclaration(node)) { return checkVariableDeclaration({node, originalNode, ...options}); } else if (options.typescript.isExportDeclaration(node)) { return checkExportDeclaration({node, originalNode, ...options}); } else if (options.typescript.isExportAssignment(node)) { return checkExportAssignment({node, originalNode, ...options}); } else if (options.typescript.isExportSpecifier(node)) { return checkExportSpecifier({node, originalNode, ...options}); } else if (options.typescript.isModuleDeclaration(node)) { return checkModuleDeclaration({node, originalNode, ...options}); } else if (options.typescript.isIdentifier(node)) { return checkIdentifier({node, originalNode, ...options}); } else if (isTemplateLiteralTypeNode(node, options.typescript)) { return checkTemplateLiteralTypeNode({node, originalNode, ...options}); } else if (options.typescript.isTemplateLiteralTypeSpan?.(node)) { return checkTemplateLiteralTypeSpan({node, originalNode, ...options}); } else if (options.typescript.isTypeReferenceNode(node)) { return checkTypeReferenceNode({node, originalNode, ...options}); } else { return options.childContinuation(node); } } /** * Visits the given node. Returns true if it references the node to check for references, and false otherwise */ function getReferencingNodes(originalNode: TS.Node, identifiers: Set<string>, cache: NodeToReferencedIdentifiersCache): TS.Node[] { // TODO: Can all of this be replaced by typescript.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); ? const referencingNodes = new Set<TS.Node>(); for (const identifier of identifiers) { const nodesReferencingIdentifier = cache.get(identifier); if (nodesReferencingIdentifier != null) { for (const node of nodesReferencingIdentifier) { if (node === originalNode || nodeContainsChild(originalNode, node)) continue; referencingNodes.add(node); } } } return [...referencingNodes]; } /** * Returns true if the given Node is referenced within the given options */ export function isReferenced<T extends TS.Node>({seenNodes = new Set(), ...options}: IsReferencedOptions<T>): boolean { // Exports are always referenced and should never be removed if ( options.typescript.isExportDeclaration(options.node) || options.typescript.isExportSpecifier(options.node) || options.typescript.isExportAssignment(options.node) || hasExportModifier(options.node, options.typescript) || options.typescript.isModuleDeclaration(options.node) ) { return true; } // If it has been computed previously, use the cached result if (options.referenceCache.has(options.node)) { return options.referenceCache.get(options.node)!; } // Assume that the node is referenced if the received node has been visited before in the recursive stack if (seenNodes.has(options.node)) { return true; } else { // Otherwise, add the node to the Set of seen nodes seenNodes.add(options.node); } // Collect the identifier for the node const identifiers = traceIdentifiers(options); // If there are no identifiers for the node, include it since it cannot be referenced. if (identifiers.size === 0) { return true; } // Collect all nodes that references the given node const referencingNodes = collectReferences(options, identifiers); // Compute the result const result = referencingNodes.length > 0 && referencingNodes.some(referencingNode => isReferenced({...options, seenNodes, node: referencingNode})); // Cache the result options.referenceCache.set(options.node, result); return result; } function collectReferences<T extends TS.Node>(options: IsReferencedOptions<T>, identifiers: Set<string>): TS.Node[] { let nodeToReferencedIdentifiersCache = options.sourceFileToNodeToReferencedIdentifiersCache.get(options.sourceFile.fileName); // If it has been computed for the SourceFile previously, use it. if (nodeToReferencedIdentifiersCache == null) { // Otherwise, compute it nodeToReferencedIdentifiersCache = new Map(); options.sourceFileToNodeToReferencedIdentifiersCache.set(options.sourceFile.fileName, nodeToReferencedIdentifiersCache); const visitorOptions = { ...options, originalNode: options.node, markIdentifiersAsReferenced(fromNode: TS.Node, ...referencedIdentifiers: string[]) { for (const identifier of referencedIdentifiers) { let matchingSet = nodeToReferencedIdentifiersCache!.get(identifier); if (matchingSet == null) { matchingSet = new Set(); nodeToReferencedIdentifiersCache!.set(identifier, matchingSet); } matchingSet.add(fromNode); } }, childContinuation: (node: TS.Node): string[] => { const referencedIdentifiers: string[] = []; options.typescript.forEachChild<void>(node, nextNode => { referencedIdentifiers.push(...checkNode({...visitorOptions, node: nextNode})); }); return referencedIdentifiers; }, continuation: (node: TS.Node): string[] => checkNode({...visitorOptions, node}) }; options.typescript.forEachChild<void>(options.sourceFile, node => { checkNode({...visitorOptions, node}); }); } return getReferencingNodes(options.node, identifiers, nodeToReferencedIdentifiersCache); }
the_stack
import { computed, defineComponent, nextTick, onBeforeUnmount, onMounted, ref, Transition, watch } from 'vue'; import { CloseIcon, InfoCircleFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue-next'; import TButton from '../button'; import { DialogCloseContext, TdDialogProps } from './type'; import props from './props'; import TransferDom from '../utils/transfer-dom'; import { addClass, removeClass } from '../utils/dom'; import { useConfig, usePrefixClass } from '../hooks/useConfig'; import { useAction } from './hooks'; import { useTNodeJSX, useContent } from '../hooks/tnode'; import useDestroyOnClose from '../hooks/useDestroyOnClose'; function GetCSSValue(v: string | number) { return Number.isNaN(Number(v)) ? v : `${Number(v)}px`; } let mousePosition: { x: number; y: number } | null; const getClickPosition = (e: MouseEvent) => { mousePosition = { x: e.clientX, y: e.clientY, }; setTimeout(() => { mousePosition = null; }, 100); }; if (typeof window !== 'undefined' && window.document && window.document.documentElement) { document.documentElement.addEventListener('click', getClickPosition, true); } // ๆณจๅ†Œๅ…ƒ็ด ็š„ๆ‹–ๆ‹ฝไบ‹ไปถ function InitDragEvent(dragBox: HTMLElement) { const target = dragBox; target.addEventListener('mousedown', (targetEvent: MouseEvent) => { // ็ฎ—ๅ‡บ้ผ ๆ ‡็›ธๅฏนๅ…ƒ็ด ็š„ไฝ็ฝฎ const disX = targetEvent.clientX - target.offsetLeft; const disY = targetEvent.clientY - target.offsetTop; function mouseMoverHandler(documentEvent: MouseEvent) { // ็”จ้ผ ๆ ‡็š„ไฝ็ฝฎๅ‡ๅŽป้ผ ๆ ‡็›ธๅฏนๅ…ƒ็ด ็š„ไฝ็ฝฎ๏ผŒๅพ—ๅˆฐๅ…ƒ็ด ็š„ไฝ็ฝฎ const left = documentEvent.clientX - disX; const top = documentEvent.clientY - disY; // ็งปๅŠจๅฝ“ๅ‰ๅ…ƒ็ด  target.style.left = `${left}px`; target.style.top = `${top}px`; } function mouseUpHandler() { // ้ผ ๆ ‡ๅผน่ตทๆฅ็š„ๆ—ถๅ€™ไธๅ†็งปๅŠจ document.removeEventListener('mousemove', mouseMoverHandler); // ้ข„้˜ฒ้ผ ๆ ‡ๅผน่ตทๆฅๅŽ่ฟ˜ไผšๅพช็Žฏ๏ผˆๅณ้ข„้˜ฒ้ผ ๆ ‡ๆ”พไธŠๅŽป็š„ๆ—ถๅ€™่ฟ˜ไผš็งปๅŠจ๏ผ‰ document.removeEventListener('mouseup', mouseUpHandler); } // ๅ…ƒ็ด ๆŒ‰ไธ‹ๆ—ถๆณจๅ†Œdocument้ผ ๆ ‡็›‘ๅฌไบ‹ไปถ document.addEventListener('mousemove', mouseMoverHandler); // ้ผ ๆ ‡ๅผน่ตทๆฅ็งป้™คdocument้ผ ๆ ‡็›‘ๅฌไบ‹ไปถ document.addEventListener('mouseup', mouseUpHandler); // ๆ‹–ๆ‹ฝ็ป“ๆŸ็งป้™ค้ผ ๆ ‡็›‘ๅฌไบ‹ไปถ๏ผŒ่งฃๅ†ณๆ–‡ๅญ—ๆ‹–ๆ‹ฝ็ป“ๆŸไบ‹ไปถๆœช่งฃ็ป‘้—ฎ้ข˜ document.addEventListener('dragend', mouseUpHandler); }); } export default defineComponent({ name: 'TDialog', components: { CloseIcon, InfoCircleFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon, TButton, Transition, }, // ๆณจๅ†Œv-draggableๆŒ‡ไปค,ไผ ๅ…ฅtrueๆ—ถๅ€™ๅˆๅง‹ๅŒ–ๆ‹–ๆ‹ฝไบ‹ไปถ directives: { TransferDom, draggable(el, binding) { // el ๆŒ‡ไปค็ป‘ๅฎš็š„ๅ…ƒ็ด  if (el && binding && binding.value) { InitDragEvent(el); } }, }, props, emits: ['update:visible'], setup(props: TdDialogProps, context) { const COMPONENT_NAME = usePrefixClass('dialog'); const LOCK_CLASS = usePrefixClass('dialog--lock'); const classPrefix = usePrefixClass(); const renderContent = useContent(); const renderTNodeJSX = useTNodeJSX(); const dialogEle = ref<HTMLElement | null>(null); const { global } = useConfig('dialog'); const confirmBtnAction = (e: MouseEvent) => { props.onConfirm?.({ e }); }; const cancelBtnAction = (e: MouseEvent) => { props.onCancel?.({ e }); emitCloseEvent({ trigger: 'cancel', e, }); }; const { getConfirmBtn, getCancelBtn } = useAction({ confirmBtnAction, cancelBtnAction }); useDestroyOnClose(); const scrollWidth = ref(0); // ๆ˜ฏๅฆๆจกๆ€ๅฝขๅผ็š„ๅฏน่ฏๆก† const isModal = computed(() => props.mode === 'modal'); // ๆ˜ฏๅฆ้žๆจกๆ€ๅฏน่ฏๆก† const isModeless = computed(() => props.mode === 'modeless'); const maskClass = computed(() => [ `${COMPONENT_NAME.value}__mask`, !props.showOverlay && `${classPrefix.value}-is-hidden`, ]); const dialogClass = computed(() => { const dialogClass = [ `${COMPONENT_NAME.value}`, `${COMPONENT_NAME.value}--default`, `${COMPONENT_NAME.value}--${props.placement}`, `${COMPONENT_NAME.value}__modal-${props.theme}`, ]; if (['modeless', 'modal'].includes(props.mode)) { dialogClass.push(`${COMPONENT_NAME.value}--fixed`); if (isModal.value && props.showInAttachedElement) { dialogClass.push(`${COMPONENT_NAME.value}--absolute`); } } return dialogClass; }); const dialogStyle = computed(() => { const { top, placement } = props; let topStyle = {}; // ่ฎพ็ฝฎไบ†topๅฑžๆ€ง if (top) { const topValue = GetCSSValue(top); topStyle = { top: topValue, transform: 'translate(-50%, 0)', maxHeight: `calc(100% - ${topValue})`, }; } else if (placement === 'top') { topStyle = { maxHeight: 'calc(100% - 20%)', }; } return { width: GetCSSValue(props.width), ...topStyle }; }); watch( () => props.visible, (value) => { if (value) { if (isModal.value && !props.showInAttachedElement) { if (scrollWidth.value > 0) { const bodyCssText = `position: relative;width: calc(100% - ${scrollWidth.value}px);`; document.body.style.cssText = bodyCssText; } !isModeless.value && addClass(document.body, LOCK_CLASS.value); nextTick(() => { if (mousePosition && dialogEle.value) { dialogEle.value.style.transformOrigin = `${mousePosition.x - dialogEle.value.offsetLeft}px ${ mousePosition.y - dialogEle.value.offsetTop }px`; } }); } } else { document.body.style.cssText = ''; removeClass(document.body, LOCK_CLASS.value); } addKeyboardEvent(value); }, ); const addKeyboardEvent = (status: boolean) => { if (status) { document.addEventListener('keydown', keyboardEvent); } else { document.removeEventListener('keydown', keyboardEvent); } }; const keyboardEvent = (e: KeyboardEvent) => { if (e.code === 'Escape') { props.onEscKeydown?.({ e }); // ๆ นๆฎcloseOnEscKeydownๅˆคๆ–ญๆŒ‰ไธ‹ESCๆ—ถๆ˜ฏๅฆ่งฆๅ‘closeไบ‹ไปถ if (props.closeOnEscKeydown) { emitCloseEvent({ trigger: 'esc', e, }); } } }; const overlayAction = (e: MouseEvent) => { props.onOverlayClick?.({ e }); // ๆ นๆฎcloseOnClickOverlayๅˆคๆ–ญ็‚นๅ‡ป่’™ๅฑ‚ๆ—ถๆ˜ฏๅฆ่งฆๅ‘closeไบ‹ไปถ if (props.closeOnOverlayClick) { emitCloseEvent({ trigger: 'overlay', e, }); } }; const closeBtnAction = (e: MouseEvent) => { props.onCloseBtnClick?.({ e }); emitCloseEvent({ trigger: 'close-btn', e, }); }; // ๆ‰“ๅผ€ๅผน็ช—ๅŠจ็”ป็ป“ๆŸๆ—ถไบ‹ไปถ const afterEnter = () => { props.onOpened?.(); }; // ๅ…ณ้—ญๅผน็ช—ๅŠจ็”ป็ป“ๆŸๆ—ถไบ‹ไปถ const afterLeave = () => { props.onClosed?.(); }; const emitCloseEvent = (ctx: DialogCloseContext) => { props.onClose?.(ctx); // ้ป˜่ฎคๅ…ณ้—ญๅผน็ช— context.emit('update:visible', false); }; // Vueๅœจๅผ•ๅ…ฅ้˜ถๆฎตๅฏนไบ‹ไปถ็š„ๅค„็†่ฟ˜ๅšไบ†ๅ“ชไบ›ๅˆๅง‹ๅŒ–ๆ“ไฝœใ€‚Vueๅœจๅฎžไพ‹ไธŠ็”จไธ€ไธช_eventsๅฑžๆ€งๅญ˜่ดฎ็ฎก็†ไบ‹ไปถ็š„ๆดพๅ‘ๅ’Œๆ›ดๆ–ฐ๏ผŒ // ๆšด้œฒๅ‡บ$on, $once, $off, $emitๆ–นๆณ•็ป™ๅค–้ƒจ็ฎก็†ไบ‹ไปถๅ’Œๆดพๅ‘ๆ‰ง่กŒไบ‹ไปถ // ๆ‰€ไปฅ้€š่ฟ‡ๅˆคๆ–ญ_eventsๆŸไธชไบ‹ไปถไธ‹็›‘ๅฌๅ‡ฝๆ•ฐๆ•ฐ็ป„ๆ˜ฏๅฆ่ถ…่ฟ‡ไธ€ไธช๏ผŒๅฏไปฅๅˆคๆ–ญๅ‡บ็ป„ไปถๆ˜ฏๅฆ็›‘ๅฌไบ†ๅฝ“ๅ‰ไบ‹ไปถ const hasEventOn = (name: string) => { // _events ๅ› ๆฒกๆœ‰่ขซๆšด้œฒๅœจvueๅฎžไพ‹ๆŽฅๅฃไธญ๏ผŒๅช่ƒฝๆŠŠ่ฟ™ไธช่ง„ๅˆ™ๆณจ้‡Šๆމ // eslint-disable-next-line dot-notation const eventFuncs = this['_events']?.[name]; return !!eventFuncs?.length; }; const getIcon = () => { const icon = { info: <InfoCircleFilledIcon class="t-is-info" />, warning: <ErrorCircleFilledIcon class="t-is-warning" />, danger: <ErrorCircleFilledIcon class="t-is-error" />, success: <CheckCircleFilledIcon class="t-is-success" />, }; return icon[props.theme]; }; const renderDialog = () => { // header ๅ€ผไธบ true ๆ˜พ็คบ็ฉบ็™ฝๅคด้ƒจ const defaultHeader = <h5 class="title"></h5>; const defaultCloseBtn = <CloseIcon />; const body = renderContent('default', 'body'); const defaultFooter = ( <div> {getCancelBtn({ cancelBtn: props.cancelBtn, globalCancel: global.value.cancel, className: `${COMPONENT_NAME.value}__cancel`, })} {getConfirmBtn({ theme: props.theme, confirmBtn: props.confirmBtn, globalConfirm: global.value.confirm, globalConfirmBtnTheme: global.value.confirmBtnTheme, className: `${COMPONENT_NAME.value}__confirm`, })} </div> ); const bodyClassName = props.theme === 'default' ? `${COMPONENT_NAME.value}__body` : `${COMPONENT_NAME.value}__body__icon`; return ( // /* ้žๆจกๆ€ๅฝขๆ€ไธ‹draggableไธบtrueๆ‰ๅ…่ฎธๆ‹–ๆ‹ฝ */ <div key="dialog" class={dialogClass.value} style={dialogStyle.value} v-draggable={isModeless.value && props.draggable} ref="dialogEle" > <div class={`${COMPONENT_NAME.value}__header`}> {getIcon()} {renderTNodeJSX('header', defaultHeader)} </div> {props.closeBtn ? ( <span class={`${COMPONENT_NAME.value}__close`} onClick={closeBtnAction}> {renderTNodeJSX('closeBtn', defaultCloseBtn)} </span> ) : null} <div class={bodyClassName}>{body}</div> <div class={`${COMPONENT_NAME.value}__footer`}>{renderTNodeJSX('footer', defaultFooter)}</div> </div> ); }; onMounted(() => { scrollWidth.value = window.innerWidth - document.body.offsetWidth; }); onBeforeUnmount(() => { addKeyboardEvent(false); }); return { COMPONENT_NAME, scrollWidth, isModal, isModeless, maskClass, dialogClass, dialogStyle, dialogEle, afterEnter, afterLeave, hasEventOn, renderDialog, overlayAction, }; }, render() { const { COMPONENT_NAME } = this; const maskView = this.isModal && <div key="mask" class={this.maskClass} onClick={this.overlayAction}></div>; const dialogView = this.renderDialog(); const view = [maskView, dialogView]; const ctxStyle = { zIndex: this.zIndex }; const ctxClass = [ `${COMPONENT_NAME}__ctx`, { 't-dialog__ctx--fixed': this.mode === 'modal', [`${COMPONENT_NAME}__ctx--absolute`]: this.isModal && this.showInAttachedElement, }, ]; return ( <transition duration={300} name={`${COMPONENT_NAME}-zoom__vue`} onAfterEnter={this.afterEnter} onAfterLeave={this.afterLeave} > {(!this.destroyOnClose || this.visible) && ( <div v-show={this.visible} class={ctxClass} style={ctxStyle} v-transfer-dom={this.attach}> {view} </div> )} </transition> ); }, });
the_stack
import { ethers, network } from 'hardhat'; import { BigNumber, Signer } from 'ethers'; import { expect } from 'chai'; import { EthereumFeeProxy, BatchPayments } from '../../src/types'; import { batchPaymentsArtifact } from '../../src/lib'; import { ethereumFeeProxyArtifact } from '../../src/lib'; import { HttpNetworkConfig } from 'hardhat/types'; const logGasInfos = false; describe('contract: BatchPayments: Ethereum', () => { let payee1: string; let payee2: string; let feeAddress: string; let batchAddress: string; let owner: Signer; let payee1Sig: Signer; let beforeEthBalance1: BigNumber; let beforeEthBalance2: BigNumber; let afterEthBalance1: BigNumber; let afterEthBalance2: BigNumber; const referenceExample1 = '0xaaaa'; const referenceExample2 = '0xbbbb'; let ethFeeProxy: EthereumFeeProxy; let batch: BatchPayments; const networkConfig = network.config as HttpNetworkConfig; const provider = new ethers.providers.JsonRpcProvider(networkConfig.url); before(async () => { [, payee1, payee2, feeAddress] = (await ethers.getSigners()).map((s) => s.address); [owner, payee1Sig] = await ethers.getSigners(); ethFeeProxy = ethereumFeeProxyArtifact.connect(network.name, owner); batch = batchPaymentsArtifact.connect(network.name, owner); batchAddress = batch.address; await batch.connect(owner).setBatchFee(10); }); after(async () => { await batch.connect(owner).setBatchFee(10); }); describe('Batch Eth normal flow', () => { it('Should pay 2 payments and contract do not keep funds of ethers', async function () { const beforeEthBalanceFee = await provider.getBalance(feeAddress); beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [2000, 3000], [referenceExample1, referenceExample2], [100, 200], feeAddress, { value: BigNumber.from('6000'), }, ), ) .to.emit(ethFeeProxy, 'TransferWithReferenceAndFee') .withArgs(payee1, '2000', ethers.utils.keccak256(referenceExample1), '100', feeAddress) .to.emit(ethFeeProxy, 'TransferWithReferenceAndFee') .withArgs(payee2, '3000', ethers.utils.keccak256(referenceExample2), '200', feeAddress); const afterEthBalanceFee = await provider.getBalance(feeAddress); expect(afterEthBalanceFee).to.be.equal(beforeEthBalanceFee.add(100 + 20 + 200 + 30)); afterEthBalance1 = await provider.getBalance(payee1); expect(afterEthBalance1).to.be.equal(beforeEthBalance1.add(2000)); afterEthBalance2 = await provider.getBalance(payee2); expect(afterEthBalance2).to.be.equal(beforeEthBalance2.add(3000)); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); it('Should pay 2 payments with the exact amount', async function () { beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); const totalAmount = BigNumber.from('535'); // amount: 500, fee: 10+20, batchFee: 2+3 const tx = await batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [200, 300], [referenceExample1, referenceExample2], [10, 20], feeAddress, { value: totalAmount, }, ); await tx.wait(); afterEthBalance1 = await provider.getBalance(payee1); expect(afterEthBalance1).to.be.equal(beforeEthBalance1.add(200)); afterEthBalance2 = await provider.getBalance(payee2); expect(afterEthBalance2).to.be.equal(beforeEthBalance2.add(300)); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); it('Should pay 10 Ethereum payments', async function () { beforeEthBalance2 = await provider.getBalance(payee2); const amount = 2; const feeAmount = 1; const nbTxs = 10; // to compare gas optim, go to 100. const [_, recipients, amounts, paymentReferences, feeAmounts] = getBatchPaymentsInputs( nbTxs, '_noTokenAddress', payee2, amount, referenceExample1, feeAmount, ); const totalAmount = BigNumber.from(((amount + feeAmount) * nbTxs).toString()); const tx = await batch .connect(owner) .batchEthPaymentsWithReference( recipients, amounts, paymentReferences, feeAmounts, feeAddress, { value: totalAmount, }, ); const receipt = await tx.wait(); if (logGasInfos) { console.log(`nbTxs= ${nbTxs}, gas consumption: `, receipt.gasUsed.toString()); } afterEthBalance2 = await provider.getBalance(payee2); expect(afterEthBalance2).to.be.equal(beforeEthBalance2.add(amount * nbTxs)); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); }); describe('Batch revert, issues with: args, or funds', () => { it('Should revert batch if not enough funds', async function () { beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); const totalAmount = BigNumber.from('400'); await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [200, 300], [referenceExample1, referenceExample2], [10, 20], feeAddress, { value: totalAmount, }, ), ).revertedWith('not enough funds'); afterEthBalance1 = await provider.getBalance(payee1); expect(afterEthBalance1).to.be.equal(beforeEthBalance1); afterEthBalance2 = await provider.getBalance(payee2); expect(afterEthBalance2).to.be.equal(beforeEthBalance2); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); it('Should revert batch if not enough funds for the batch fee', async function () { beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); const totalAmount = BigNumber.from('530'); // missing 5 (= (200+300) * 1%) await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [200, 300], [referenceExample1, referenceExample2], [10, 20], feeAddress, { value: totalAmount, }, ), ).revertedWith('not enough funds for batch fee'); afterEthBalance1 = await provider.getBalance(payee1); expect(afterEthBalance1).to.be.equal(beforeEthBalance1); afterEthBalance2 = await provider.getBalance(payee2); expect(afterEthBalance2).to.be.equal(beforeEthBalance2); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); it('Should revert batch if input s arrays do not have same size', async function () { await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [5, 30], [referenceExample1, referenceExample2], [1], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1], [5, 30], [referenceExample1, referenceExample2], [1, 2], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [5], [referenceExample1, referenceExample2], [1, 2], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [5, 30], [referenceExample1], [1, 2], feeAddress, ), ).revertedWith('the input arrays must have the same length'); expect(await provider.getBalance(batchAddress)).to.be.equal(0); }); }); describe('Function allowed only to the owner', () => { it('Should allow the owner to update batchFee', async function () { const beforeBatchFee = await batch.batchFee.call({ from: owner }); let tx = await batch.connect(owner).setBatchFee(beforeBatchFee.add(10)); await tx.wait(); const afterBatchFee = await batch.batchFee.call({ from: owner }); expect(afterBatchFee).to.be.equal(beforeBatchFee.add(10)); }); it('Should applied the new batchFee', async function () { // check if batch fee applied are the one updated const beforeFeeAddress = await provider.getBalance(feeAddress); const tx = await batch .connect(owner) .batchEthPaymentsWithReference( [payee1, payee2], [200, 300], [referenceExample1, referenceExample2], [10, 20], feeAddress, { value: BigNumber.from('1000'), }, ); await tx.wait(); const afterFeeAddress = await provider.getBalance(feeAddress); expect(afterFeeAddress).to.be.equal(beforeFeeAddress.add(10 + 20 + (4 + 6))); // fee: (10+20), batch fee: (4+6) }); it('Should revert if it is not the owner that try to update batchFee', async function () { await expect(batch.connect(payee1Sig).setBatchFee(30)).revertedWith( 'revert Ownable: caller is not the owner', ); }); }); }); // Allow to create easly BatchPayments input, especially for gas optimization. const getBatchPaymentsInputs = function ( nbTxs: number, tokenAddress: string, recipient: string, amount: number, referenceExample1: string, feeAmount: number, ): [Array<string>, Array<string>, Array<number>, Array<string>, Array<number>] { let tokenAddresses = []; let recipients = []; let amounts = []; let paymentReferences = []; let feeAmounts = []; for (let i = 0; i < nbTxs; i++) { tokenAddresses.push(tokenAddress); recipients.push(recipient); amounts.push(amount); paymentReferences.push(referenceExample1); feeAmounts.push(feeAmount); } return [tokenAddresses, recipients, amounts, paymentReferences, feeAmounts]; };
the_stack
import { redirect, SubPath } from '../../utils/routeUtils'; import Router from '../../utils/Router'; import { Env, RouteType } from '../../utils/types'; import { AppContext } from '../../utils/types'; import { bodyFields } from '../../utils/requestUtils'; import globalConfig from '../../config'; import { ErrorBadRequest, ErrorForbidden, ErrorNotFound } from '../../utils/errors'; import { Stripe } from 'stripe'; import Logger from '@joplin/lib/Logger'; import getRawBody = require('raw-body'); import { AccountType } from '../../models/UserModel'; import { betaUserTrialPeriodDays, cancelSubscription, initStripe, isBetaUser, priceIdToAccountType, stripeConfig } from '../../utils/stripe'; import { Subscription, User, UserFlagType } from '../../services/database/types'; import { findPrice, PricePeriod } from '@joplin/lib/utils/joplinCloud'; import { Models } from '../../models/factory'; import { confirmUrl } from '../../utils/urlUtils'; import { msleep } from '../../utils/time'; const logger = Logger.create('/stripe'); const router: Router = new Router(RouteType.Web); router.public = true; async function stripeEvent(stripe: Stripe, req: any): Promise<Stripe.Event> { if (!stripeConfig().webhookSecret) throw new Error('webhookSecret is required'); const body = await getRawBody(req); return stripe.webhooks.constructEvent( body, req.headers['stripe-signature'], stripeConfig().webhookSecret ); } interface CreateCheckoutSessionFields { priceId: string; coupon: string; promotionCode: string; email: string; } type StripeRouteHandler = (stripe: Stripe, path: SubPath, ctx: AppContext)=> Promise<any>; interface PostHandlers { createCheckoutSession: Function; webhook: Function; } interface SubscriptionInfo { sub: Subscription; stripeSub: Stripe.Subscription; } async function getSubscriptionInfo(event: Stripe.Event, ctx: AppContext): Promise<SubscriptionInfo> { const stripeSub = event.data.object as Stripe.Subscription; const sub = await ctx.joplin.models.subscription().byStripeSubscriptionId(stripeSub.id); if (!sub) throw new Error(`No subscription with ID: ${stripeSub.id}`); return { sub, stripeSub }; } export const handleSubscriptionCreated = async (stripe: Stripe, models: Models, customerName: string, userEmail: string, accountType: AccountType, stripeUserId: string, stripeSubscriptionId: string) => { const existingUser = await models.user().loadByEmail(userEmail); if (existingUser) { const sub = await models.subscription().byUserId(existingUser.id); if (!sub) { logger.info(`Setting up subscription for existing user: ${existingUser.email}`); // First set the account type correctly (in case the // user also upgraded or downgraded their account). await models.user().save({ id: existingUser.id, account_type: accountType, }); // Also clear any payment and subscription related flags // since if we're here it means payment was successful await models.userFlag().removeMulti(existingUser.id, [ UserFlagType.FailedPaymentWarning, UserFlagType.FailedPaymentFinal, UserFlagType.SubscriptionCancelled, UserFlagType.AccountWithoutSubscription, ]); // Then save the subscription await models.subscription().save({ user_id: existingUser.id, stripe_user_id: stripeUserId, stripe_subscription_id: stripeSubscriptionId, last_payment_time: Date.now(), }); } else { if (sub.stripe_subscription_id === stripeSubscriptionId) { // Stripe probably dispatched a "customer.subscription.created" // event after "checkout.session.completed", so we already have // save the subscription and can skip processing. } else { // The user already has a subscription. Most likely // they accidentally created a second one, so cancel // it. logger.info(`User ${existingUser.email} already has a subscription: ${sub.stripe_subscription_id} - cancelling duplicate`); await cancelSubscription(stripe, stripeSubscriptionId); } } } else { logger.info(`Creating subscription for new user: ${userEmail}`); await models.subscription().saveUserAndSubscription( userEmail, customerName, accountType, stripeUserId, stripeSubscriptionId ); } }; // For some reason, after checkout Stripe redirects to success_url immediately, // without waiting for the "checkout.session.completed" event to be completed. // It may be because they expect the webhook to immediately return code 200, // which is not how it's currently implemented here. // https://stripe.com/docs/payments/checkout/fulfill-orders#fulfill // // It means that by the time success_url is called, the user hasn't been created // yet. So here we wait for the user to be available and return it. It shouldn't // wait for more than 2-3 seconds. const waitForUserCreation = async (models: Models, userEmail: string): Promise<User | null> => { for (let i = 0; i < 10; i++) { const user = await models.user().loadByEmail(userEmail); if (user) return user; await msleep(1000); } return null; }; export const postHandlers: PostHandlers = { createCheckoutSession: async (stripe: Stripe, __path: SubPath, ctx: AppContext) => { const fields = await bodyFields<CreateCheckoutSessionFields>(ctx.req); const priceId = fields.priceId; const checkoutSession: Stripe.Checkout.SessionCreateParams = { mode: 'subscription', // Stripe supports many payment method types but it seems only // "card" is supported for recurring subscriptions. payment_method_types: ['card'], line_items: [ { price: priceId, // For metered billing, do not pass quantity quantity: 1, }, ], subscription_data: { trial_period_days: 14, }, allow_promotion_codes: true, // {CHECKOUT_SESSION_ID} is a string literal; do not change it! // the actual Session ID is returned in the query parameter when your customer // is redirected to the success page. success_url: `${globalConfig().baseUrl}/stripe/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${globalConfig().baseUrl}/stripe/cancel`, }; if (fields.coupon) { checkoutSession.discounts = [ { coupon: fields.coupon.trim(), }, ]; } else if (fields.promotionCode) { const p = await stripe.promotionCodes.list({ code: fields.promotionCode }); const codes = p.data; if (!codes.length) throw new ErrorBadRequest(`Could not find promotion code: ${fields.promotionCode}`); // Should not be possible in our setup since a unique code is // created for each customer. if (codes.length > 1) console.warn(`Found more than one promotion code: ${fields.promotionCode}`); checkoutSession.discounts = [ { promotion_code: codes[0].id, }, ]; } // "You may only specify one of these parameters: allow_promotion_codes, discounts" if (checkoutSession.discounts) delete checkoutSession.allow_promotion_codes; if (fields.email) { checkoutSession.customer_email = fields.email.trim(); // If it's a Beta user, we set the trial end period to the end of // the beta period. So for example if there's 7 weeks left on the // Beta period, the trial will be 49 days. This is so Beta users can // setup the subscription at any time without losing the free beta // period. const existingUser = await ctx.joplin.models.user().loadByEmail(checkoutSession.customer_email); if (existingUser && await isBetaUser(ctx.joplin.models, existingUser.id)) { checkoutSession.subscription_data.trial_period_days = betaUserTrialPeriodDays(existingUser.created_time); } } // See https://stripe.com/docs/api/checkout/sessions/create // for additional parameters to pass. const session = await stripe.checkout.sessions.create(checkoutSession); logger.info('Created checkout session', session.id); // Somehow Stripe doesn't send back the price ID to the hook when the // subscription is created, so we keep a map of sessions to price IDs so that we // can create the right account, either Basic or Pro. await ctx.joplin.models.keyValue().setValue(`stripeSessionToPriceId::${session.id}`, priceId); return { sessionId: session.id }; }, webhook: async (stripe: Stripe, _path: SubPath, ctx: AppContext, event: Stripe.Event = null, logErrors: boolean = true) => { event = event ? event : await stripeEvent(stripe, ctx.req); const models = ctx.joplin.models; // Webhook endpoints might occasionally receive the same event more than // once. // https://stripe.com/docs/webhooks/best-practices#duplicate-events const eventDoneKey = `stripeEventDone::${event.id}`; if (await models.keyValue().value<number>(eventDoneKey)) { logger.info(`Skipping event that has already been done: ${event.id}`); return; } await models.keyValue().setValue(eventDoneKey, 1); const hooks: any = { 'checkout.session.completed': async () => { // Payment is successful and the subscription is created. // // For testing: `stripe trigger checkout.session.completed` // Or use /checkoutTest URL. const checkoutSession: Stripe.Checkout.Session = event.data.object as Stripe.Checkout.Session; const userEmail = checkoutSession.customer_details.email || checkoutSession.customer_email; let customerName = ''; try { const customer = await stripe.customers.retrieve(checkoutSession.customer as string) as Stripe.Customer; customerName = customer.name; } catch (error) { logger.error('Could not fetch customer information:', error); } logger.info('Checkout session completed:', checkoutSession.id); logger.info('User email:', userEmail); logger.info('User name:', customerName); let accountType = AccountType.Basic; try { const priceId: string = await models.keyValue().value(`stripeSessionToPriceId::${checkoutSession.id}`); accountType = priceIdToAccountType(priceId); logger.info('Price ID:', priceId); } catch (error) { // We don't want this part to fail since the user has // already paid at that point, so we just default to Basic // in that case. Normally it shoud not happen anyway. logger.error('Could not determine account type from price ID - defaulting to "Basic"', error); } logger.info('Account type:', accountType); // The Stripe TypeScript object defines "customer" and // "subscription" as various types but they are actually // string according to the documentation. const stripeUserId = checkoutSession.customer as string; const stripeSubscriptionId = checkoutSession.subscription as string; await handleSubscriptionCreated( stripe, models, customerName, userEmail, accountType, stripeUserId, stripeSubscriptionId ); }, 'customer.subscription.created': async () => { const stripeSub: Stripe.Subscription = event.data.object as Stripe.Subscription; const stripeUserId = stripeSub.customer as string; const stripeSubscriptionId = stripeSub.id; const customer = await stripe.customers.retrieve(stripeUserId) as Stripe.Customer; let accountType = AccountType.Basic; try { // Really have to dig out the price ID const priceId = stripeSub.items.data[0].price.id; accountType = priceIdToAccountType(priceId); } catch (error) { logger.error('Could not determine account type from price ID - defaulting to "Basic"', error); } await handleSubscriptionCreated( stripe, models, customer.name, customer.email, accountType, stripeUserId, stripeSubscriptionId ); }, 'invoice.paid': async () => { // Continue to provision the subscription as payments continue // to be made. Store the status in your database and check when // a user accesses your service. This approach helps you avoid // hitting rate limits. // // Note that when the subscription is created, this event is // going to be triggered before "checkout.session.completed" (at // least in tests), which means it won't find the subscription // at this point, but this is fine because the required data is // saved in checkout.session.completed. const invoice = event.data.object as Stripe.Invoice; await models.subscription().handlePayment(invoice.subscription as string, true); }, 'invoice.payment_failed': async () => { // The payment failed or the customer does not have a valid payment method. // The subscription becomes past_due. Notify your customer and send them to the // customer portal to update their payment information. // // For testing: `stripe trigger invoice.payment_failed` const invoice = event.data.object as Stripe.Invoice; const subId = invoice.subscription as string; await models.subscription().handlePayment(subId, false); }, 'customer.subscription.deleted': async () => { // The subscription has been cancelled, either by us or directly // by the user. In that case, we disable the user. const { sub } = await getSubscriptionInfo(event, ctx); await models.subscription().toggleSoftDelete(sub.id, true); await models.userFlag().add(sub.user_id, UserFlagType.SubscriptionCancelled); }, 'customer.subscription.updated': async () => { // The subscription has been updated - we apply the changes from // Stripe to the local account. const { sub, stripeSub } = await getSubscriptionInfo(event, ctx); const newAccountType = priceIdToAccountType(stripeSub.items.data[0].price.id); const user = await models.user().load(sub.user_id, { fields: ['id'] }); if (!user) throw new Error(`No such user: ${user.id}`); logger.info(`Updating subscription of user ${user.id} to ${newAccountType}`); await models.user().save({ id: user.id, account_type: newAccountType }); }, }; if (hooks[event.type]) { logger.info(`Got Stripe event: ${event.type} [Handled]`); try { await hooks[event.type](); } catch (error) { if (logErrors) { logger.error(`Error processing event ${event.type}:`, event, error); } else { throw error; } } } else { logger.info(`Got Stripe event: ${event.type} [Unhandled]`); } }, }; const getHandlers: Record<string, StripeRouteHandler> = { success: async (stripe: Stripe, _path: SubPath, ctx: AppContext) => { try { const models = ctx.joplin.models; const checkoutSession = await stripe.checkout.sessions.retrieve(ctx.query.session_id); const userEmail = checkoutSession.customer_details.email || checkoutSession.customer_email; // customer_email appears to be always null but fallback to it just in case if (!userEmail) throw new Error(`Could not find email from checkout session: ${JSON.stringify(checkoutSession)}`); const user = await waitForUserCreation(models, userEmail); if (!user) throw new Error(`Could not find user from checkout session: ${JSON.stringify(checkoutSession)}`); const validationToken = await ctx.joplin.models.token().generate(user.id); const redirectUrl = encodeURI(confirmUrl(user.id, validationToken, false)); return redirect(ctx, redirectUrl); } catch (error) { logger.error('Could not automatically redirect user to account confirmation page. They will have to follow the link in the confirmation email. Error was:', error); return ` <p>Thank you for signing up for ${globalConfig().appName}! You should receive an email shortly with instructions on how to connect to your account.</p> <p><a href="https://joplinapp.org">Go back to JoplinApp.org</a></p> `; } }, cancel: async (_stripe: Stripe, _path: SubPath, _ctx: AppContext) => { return ` <p>Your payment has been cancelled.</p> <p><a href="https://joplinapp.org">Go back to JoplinApp.org</a></p> `; }, portal: async (stripe: Stripe, _path: SubPath, ctx: AppContext) => { if (!ctx.joplin.owner) throw new ErrorForbidden('Please login to access the subscription portal'); const sub = await ctx.joplin.models.subscription().byUserId(ctx.joplin.owner.id); if (!sub) throw new ErrorNotFound('Could not find subscription'); const billingPortalSession = await stripe.billingPortal.sessions.create({ customer: sub.stripe_user_id as string }); return ` <html> <head> <meta http-equiv = "refresh" content = "1; url = ${billingPortalSession.url}" /> <script>setTimeout(() => { window.location.href = ${JSON.stringify(billingPortalSession.url)}; }, 2000)</script> </head> <body> Redirecting to subscription portal... </body> </html>`; }, checkoutTest: async (_stripe: Stripe, _path: SubPath, ctx: AppContext) => { if (globalConfig().env === Env.Prod) throw new ErrorForbidden(); const basicPrice = findPrice(stripeConfig().prices, { accountType: 1, period: PricePeriod.Monthly }); const proPrice = findPrice(stripeConfig().prices, { accountType: 2, period: PricePeriod.Monthly }); const customPriceId = ctx.request.query.price_id; return ` <head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> <script> var stripe = Stripe(${JSON.stringify(stripeConfig().publishableKey)}); var createCheckoutSession = function(priceId, promotionCode) { return fetch("/stripe/createCheckoutSession", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ priceId, promotionCode, }) }).then(function(result) { return result.json(); }); }; </script> </head> <body> Promotion code: <input id="promotion_code" type="text"/> <br/> <button id="checkout_basic">Subscribe Basic</button> <button id="checkout_pro">Subscribe Pro</button> <button id="checkout_custom">Subscribe Custom</button> <script> var BASIC_PRICE_ID = ${JSON.stringify(basicPrice.id)}; var PRO_PRICE_ID = ${JSON.stringify(proPrice.id)}; var CUSTOM_PRICE_ID = ${JSON.stringify(customPriceId)}; if (!CUSTOM_PRICE_ID) { document.getElementById('checkout_custom').style.display = 'none'; } function handleResult() { console.info('Redirected to checkout'); } function createSessionAndRedirect(priceId) { var promotionCode = document.getElementById('promotion_code').value; createCheckoutSession(priceId, promotionCode).then(function(data) { // Call Stripe.js method to redirect to the new Checkout page stripe .redirectToCheckout({ sessionId: data.sessionId }) .then(handleResult); }); } document.getElementById("checkout_basic").addEventListener("click", function(evt) { evt.preventDefault(); createSessionAndRedirect(BASIC_PRICE_ID); }); document.getElementById("checkout_pro").addEventListener("click", function(evt) { evt.preventDefault(); createSessionAndRedirect(PRO_PRICE_ID); }); document.getElementById("checkout_custom").addEventListener("click", function(evt) { evt.preventDefault(); createSessionAndRedirect(CUSTOM_PRICE_ID); }); </script> </body> `; }, }; router.post('stripe/:id', async (path: SubPath, ctx: AppContext) => { if (!(postHandlers as any)[path.id]) throw new ErrorNotFound(`No such action: ${path.id}`); return (postHandlers as any)[path.id](initStripe(), path, ctx); }); router.get('stripe/:id', async (path: SubPath, ctx: AppContext) => { if (!getHandlers[path.id]) throw new ErrorNotFound(`No such action: ${path.id}`); return getHandlers[path.id](initStripe(), path, ctx); }); export default router;
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>Represents the input of a <code>DescribeStream</code> operation.</p> */ export interface DescribeStreamInput { /** * <p>The Amazon Resource Name (ARN) for the stream.</p> */ StreamArn: string | undefined; /** * <p>The maximum number of shard objects to return. The upper limit is 100.</p> */ Limit?: number; /** * <p>The shard ID of the first item that this operation will evaluate. Use the value that was * returned for <code>LastEvaluatedShardId</code> in the previous operation. </p> */ ExclusiveStartShardId?: string; } export namespace DescribeStreamInput { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStreamInput): any => ({ ...obj, }); } export type KeyType = "HASH" | "RANGE"; /** * <p>Represents <i>a single element</i> of a key schema. A key schema specifies * the attributes that make up the primary key of a table, or the key attributes of an * index.</p> * <p>A <code>KeySchemaElement</code> represents exactly one attribute of the primary key. For * example, a simple primary key would be represented by one <code>KeySchemaElement</code> * (for the partition key). A composite primary key would require one * <code>KeySchemaElement</code> for the partition key, and another * <code>KeySchemaElement</code> for the sort key.</p> * <p>A <code>KeySchemaElement</code> must be a scalar, top-level attribute (not a nested * attribute). The data type must be one of String, Number, or Binary. The attribute cannot * be nested within a List or a Map.</p> */ export interface KeySchemaElement { /** * <p>The name of a key attribute.</p> */ AttributeName: string | undefined; /** * <p>The role that this key attribute will assume:</p> * <ul> * <li> * <p> * <code>HASH</code> - partition key</p> * </li> * <li> * <p> * <code>RANGE</code> - sort key</p> * </li> * </ul> * <note> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of * an internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> * <p>The sort key of an item is also known as its <i>range * attribute</i>. The term "range attribute" derives from the way DynamoDB * stores items with the same partition key physically close together, in sorted order * by the sort key value.</p> * </note> */ KeyType: KeyType | string | undefined; } export namespace KeySchemaElement { /** * @internal */ export const filterSensitiveLog = (obj: KeySchemaElement): any => ({ ...obj, }); } /** * <p>The beginning and ending sequence numbers for the stream records contained within a shard.</p> */ export interface SequenceNumberRange { /** * <p>The first sequence number for the stream records contained within a shard. String contains numeric characters only.</p> */ StartingSequenceNumber?: string; /** * <p>The last sequence number for the stream records contained within a shard. String contains numeric characters only.</p> */ EndingSequenceNumber?: string; } export namespace SequenceNumberRange { /** * @internal */ export const filterSensitiveLog = (obj: SequenceNumberRange): any => ({ ...obj, }); } /** * <p>A uniquely identified group of stream records within a stream.</p> */ export interface Shard { /** * <p>The system-generated identifier for this shard.</p> */ ShardId?: string; /** * <p>The range of possible sequence numbers for the shard.</p> */ SequenceNumberRange?: SequenceNumberRange; /** * <p>The shard ID of the current shard's parent.</p> */ ParentShardId?: string; } export namespace Shard { /** * @internal */ export const filterSensitiveLog = (obj: Shard): any => ({ ...obj, }); } export type StreamStatus = "DISABLED" | "DISABLING" | "ENABLED" | "ENABLING"; export type StreamViewType = "KEYS_ONLY" | "NEW_AND_OLD_IMAGES" | "NEW_IMAGE" | "OLD_IMAGE"; /** * <p>Represents all of the data describing a particular stream.</p> */ export interface StreamDescription { /** * <p>The Amazon Resource Name (ARN) for the stream.</p> */ StreamArn?: string; /** * <p>A timestamp, in ISO 8601 format, for this stream.</p> * <p>Note that <code>LatestStreamLabel</code> is not a unique identifier for the stream, because it is * possible that a stream from another table might have the same timestamp. However, the * combination of the following three elements is guaranteed to be unique:</p> * <ul> * <li> * <p>the AWS customer ID.</p> * </li> * <li> * <p>the table name</p> * </li> * <li> * <p>the <code>StreamLabel</code> * </p> * </li> * </ul> */ StreamLabel?: string; /** * <p>Indicates the current status of the stream:</p> * <ul> * <li> * <p> * <code>ENABLING</code> - Streams is currently being enabled on the DynamoDB table.</p> * </li> * <li> * <p> * <code>ENABLED</code> - the stream is enabled.</p> * </li> * <li> * <p> * <code>DISABLING</code> - Streams is currently being disabled on the DynamoDB table.</p> * </li> * <li> * <p> * <code>DISABLED</code> - the stream is disabled.</p> * </li> * </ul> */ StreamStatus?: StreamStatus | string; /** * <p>Indicates the format of the records within this stream:</p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of items that were modified in the DynamoDB table.</p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - entire items from the table, as they appeared after they were modified.</p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - entire items from the table, as they appeared before they were modified.</p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old images of the items from the table.</p> * </li> * </ul> */ StreamViewType?: StreamViewType | string; /** * <p>The date and time when the request to create this stream was issued.</p> */ CreationRequestDateTime?: Date; /** * <p>The DynamoDB table with which the stream is associated.</p> */ TableName?: string; /** * <p>The key attribute(s) of the stream's DynamoDB table.</p> */ KeySchema?: KeySchemaElement[]; /** * <p>The shards that comprise the stream.</p> */ Shards?: Shard[]; /** * <p>The shard ID of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request.</p> * <p>If <code>LastEvaluatedShardId</code> is empty, then the "last page" of results has been * processed and there is currently no more data to be retrieved.</p> * <p>If <code>LastEvaluatedShardId</code> is not empty, it does not necessarily mean that there is * more data in the result set. The only way to know when you have reached the end of the result * set is when <code>LastEvaluatedShardId</code> is empty.</p> */ LastEvaluatedShardId?: string; } export namespace StreamDescription { /** * @internal */ export const filterSensitiveLog = (obj: StreamDescription): any => ({ ...obj, }); } /** * <p>Represents the output of a <code>DescribeStream</code> operation.</p> */ export interface DescribeStreamOutput { /** * <p>A complete description of the stream, including its creation date and time, the DynamoDB table associated with the stream, the shard IDs within the stream, and the beginning and ending sequence numbers of stream records within the shards.</p> */ StreamDescription?: StreamDescription; } export namespace DescribeStreamOutput { /** * @internal */ export const filterSensitiveLog = (obj: DescribeStreamOutput): any => ({ ...obj, }); } /** * <p>An error occurred on the server side.</p> */ export interface InternalServerError extends __SmithyException, $MetadataBearer { name: "InternalServerError"; $fault: "server"; /** * <p>The server encountered an internal error trying to fulfill the request.</p> */ message?: string; } export namespace InternalServerError { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerError): any => ({ ...obj, }); } /** * <p>The operation tried to access a nonexistent table or index. The resource * might not be specified correctly, or its status might not be * <code>ACTIVE</code>.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The resource which is being requested does not exist.</p> */ message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>The shard iterator has expired and can no longer be used to retrieve stream records. A shard * iterator expires 15 minutes after it is retrieved using the <code>GetShardIterator</code> * action.</p> */ export interface ExpiredIteratorException extends __SmithyException, $MetadataBearer { name: "ExpiredIteratorException"; $fault: "client"; /** * <p>The provided iterator exceeds the maximum age allowed.</p> */ message?: string; } export namespace ExpiredIteratorException { /** * @internal */ export const filterSensitiveLog = (obj: ExpiredIteratorException): any => ({ ...obj, }); } /** * <p>Represents the input of a <code>GetRecords</code> operation.</p> */ export interface GetRecordsInput { /** * <p>A shard iterator that was retrieved from a previous GetShardIterator operation. This iterator can be used to access the stream records in this shard.</p> */ ShardIterator: string | undefined; /** * <p>The maximum number of records to return from the shard. The upper limit is 1000.</p> */ Limit?: number; } export namespace GetRecordsInput { /** * @internal */ export const filterSensitiveLog = (obj: GetRecordsInput): any => ({ ...obj, }); } export type OperationType = "INSERT" | "MODIFY" | "REMOVE"; /** * <p>Contains details about the type of identity that made the request.</p> */ export interface Identity { /** * <p>A unique identifier for the entity that made the call. For Time To Live, the * principalId is "dynamodb.amazonaws.com".</p> */ PrincipalId?: string; /** * <p>The type of the identity. For Time To Live, the type is "Service".</p> */ Type?: string; } export namespace Identity { /** * @internal */ export const filterSensitiveLog = (obj: Identity): any => ({ ...obj, }); } /** * <p>There is no limit to the number of daily on-demand backups that can be * taken.</p> * <p>Up to 50 simultaneous table operations are allowed per account. These operations * include <code>CreateTable</code>, <code>UpdateTable</code>, * <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, * <code>RestoreTableFromBackup</code>, and * <code>RestoreTableToPointInTime</code>.</p> * <p>The only exception is when you are creating a table with one or more secondary * indexes. You can have up to 25 such requests running at a time; however, if the table or * index specifications are complex, DynamoDB might temporarily reduce the number of * concurrent operations.</p> * <p>There is a soft account quota of 256 tables.</p> */ export interface LimitExceededException extends __SmithyException, $MetadataBearer { name: "LimitExceededException"; $fault: "client"; /** * <p>Too many operations for a given subscriber.</p> */ message?: string; } export namespace LimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: LimitExceededException): any => ({ ...obj, }); } /** * <p>The operation attempted to read past the oldest stream record in a shard.</p> * <p>In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream. You might receive a TrimmedDataAccessException if:</p> * <ul> * <li> * <p>You request a shard iterator with a sequence number older than the trim point (24 hours).</p> * </li> * <li> * <p>You obtain a shard iterator, but before you use the iterator in a <code>GetRecords</code> * request, a stream record in the shard exceeds the 24 hour period and is trimmed. This causes * the iterator to access a record that no longer exists.</p> * </li> * </ul> */ export interface TrimmedDataAccessException extends __SmithyException, $MetadataBearer { name: "TrimmedDataAccessException"; $fault: "client"; /** * <p>"The data you are trying to access has been trimmed.</p> */ message?: string; } export namespace TrimmedDataAccessException { /** * @internal */ export const filterSensitiveLog = (obj: TrimmedDataAccessException): any => ({ ...obj, }); } export type ShardIteratorType = "AFTER_SEQUENCE_NUMBER" | "AT_SEQUENCE_NUMBER" | "LATEST" | "TRIM_HORIZON"; /** * <p>Represents the input of a <code>GetShardIterator</code> operation.</p> */ export interface GetShardIteratorInput { /** * <p>The Amazon Resource Name (ARN) for the stream.</p> */ StreamArn: string | undefined; /** * <p>The identifier of the shard. The iterator will be returned for this shard ID.</p> */ ShardId: string | undefined; /** * <p>Determines how the shard iterator is used to start reading stream records from the shard:</p> * <ul> * <li> * <p> * <code>AT_SEQUENCE_NUMBER</code> - Start reading exactly from the position denoted by a * specific sequence number.</p> * </li> * <li> * <p> * <code>AFTER_SEQUENCE_NUMBER</code> - Start reading right after the position denoted by a * specific sequence number.</p> * </li> * <li> * <p> * <code>TRIM_HORIZON</code> - Start reading at the last (untrimmed) stream record, which is * the oldest record in the shard. In DynamoDB Streams, there is a 24 hour limit on data retention. * Stream records whose age exceeds this limit are subject to removal (trimming) from the * stream.</p> * </li> * <li> * <p> * <code>LATEST</code> - Start reading just after the most recent stream record in the * shard, so that you always read the most recent data in the shard.</p> * </li> * </ul> */ ShardIteratorType: ShardIteratorType | string | undefined; /** * <p>The sequence number of a stream record in the shard from which to start reading.</p> */ SequenceNumber?: string; } export namespace GetShardIteratorInput { /** * @internal */ export const filterSensitiveLog = (obj: GetShardIteratorInput): any => ({ ...obj, }); } /** * <p>Represents the output of a <code>GetShardIterator</code> operation.</p> */ export interface GetShardIteratorOutput { /** * <p>The position in the shard from which to start reading stream records sequentially. A shard iterator specifies this position using the sequence number of a stream record in a shard.</p> */ ShardIterator?: string; } export namespace GetShardIteratorOutput { /** * @internal */ export const filterSensitiveLog = (obj: GetShardIteratorOutput): any => ({ ...obj, }); } /** * <p>Represents the input of a <code>ListStreams</code> operation.</p> */ export interface ListStreamsInput { /** * <p>If this parameter is provided, then only the streams associated with this table name are returned.</p> */ TableName?: string; /** * <p>The maximum number of streams to return. The upper limit is 100.</p> */ Limit?: number; /** * <p>The ARN (Amazon Resource Name) of the first item that this operation will evaluate. Use the * value that was returned for <code>LastEvaluatedStreamArn</code> in the previous operation. * </p> */ ExclusiveStartStreamArn?: string; } export namespace ListStreamsInput { /** * @internal */ export const filterSensitiveLog = (obj: ListStreamsInput): any => ({ ...obj, }); } /** * <p>Represents all of the data describing a particular stream.</p> */ export interface _Stream { /** * <p>The Amazon Resource Name (ARN) for the stream.</p> */ StreamArn?: string; /** * <p>The DynamoDB table with which the stream is associated.</p> */ TableName?: string; /** * <p>A timestamp, in ISO 8601 format, for this stream.</p> * <p>Note that <code>LatestStreamLabel</code> is not a unique identifier for the stream, because it is * possible that a stream from another table might have the same timestamp. However, the * combination of the following three elements is guaranteed to be unique:</p> * <ul> * <li> * <p>the AWS customer ID.</p> * </li> * <li> * <p>the table name</p> * </li> * <li> * <p>the <code>StreamLabel</code> * </p> * </li> * </ul> */ StreamLabel?: string; } export namespace _Stream { /** * @internal */ export const filterSensitiveLog = (obj: _Stream): any => ({ ...obj, }); } /** * <p>Represents the output of a <code>ListStreams</code> operation.</p> */ export interface ListStreamsOutput { /** * <p>A list of stream descriptors associated with the current account and endpoint.</p> */ Streams?: _Stream[]; /** * <p>The stream ARN of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request.</p> * <p>If <code>LastEvaluatedStreamArn</code> is empty, then the "last page" of results has been * processed and there is no more data to be retrieved.</p> * <p>If <code>LastEvaluatedStreamArn</code> is not empty, it does not necessarily mean that there * is more data in the result set. The only way to know when you have reached the end of the * result set is when <code>LastEvaluatedStreamArn</code> is empty.</p> */ LastEvaluatedStreamArn?: string; } export namespace ListStreamsOutput { /** * @internal */ export const filterSensitiveLog = (obj: ListStreamsOutput): any => ({ ...obj, }); } /** * <p>Represents the data for an attribute.</p> * <p>Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">Data Types</a> in the * <i>Amazon DynamoDB Developer Guide</i>.</p> */ export type AttributeValue = | AttributeValue.BMember | AttributeValue.BOOLMember | AttributeValue.BSMember | AttributeValue.LMember | AttributeValue.MMember | AttributeValue.NMember | AttributeValue.NSMember | AttributeValue.NULLMember | AttributeValue.SMember | AttributeValue.SSMember | AttributeValue.$UnknownMember; export namespace AttributeValue { /** * <p>An attribute of type String. For example:</p> * <p> * <code>"S": "Hello"</code> * </p> */ export interface SMember { S: string; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Number. For example:</p> * <p> * <code>"N": "123.45"</code> * </p> * <p>Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.</p> */ export interface NMember { S?: never; N: string; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Binary. For example:</p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * </p> */ export interface BMember { S?: never; N?: never; B: Uint8Array; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> */ export interface SSMember { S?: never; N?: never; B?: never; SS: string[]; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Number Set. For example:</p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p>Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.</p> */ export interface NSMember { S?: never; N?: never; B?: never; SS?: never; NS: string[]; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Binary Set. For example:</p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> */ export interface BSMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS: Uint8Array[]; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Map. For example:</p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * </p> */ export interface MMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M: { [key: string]: AttributeValue }; L?: never; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type List. For example:</p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> */ export interface LMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L: AttributeValue[]; NULL?: never; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Null. For example:</p> * <p> * <code>"NULL": true</code> * </p> */ export interface NULLMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL: boolean; BOOL?: never; $unknown?: never; } /** * <p>An attribute of type Boolean. For example:</p> * <p> * <code>"BOOL": true</code> * </p> */ export interface BOOLMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL: boolean; $unknown?: never; } export interface $UnknownMember { S?: never; N?: never; B?: never; SS?: never; NS?: never; BS?: never; M?: never; L?: never; NULL?: never; BOOL?: never; $unknown: [string, any]; } export interface Visitor<T> { S: (value: string) => T; N: (value: string) => T; B: (value: Uint8Array) => T; SS: (value: string[]) => T; NS: (value: string[]) => T; BS: (value: Uint8Array[]) => T; M: (value: { [key: string]: AttributeValue }) => T; L: (value: AttributeValue[]) => T; NULL: (value: boolean) => T; BOOL: (value: boolean) => T; _: (name: string, value: any) => T; } export const visit = <T>(value: AttributeValue, visitor: Visitor<T>): T => { if (value.S !== undefined) return visitor.S(value.S); if (value.N !== undefined) return visitor.N(value.N); if (value.B !== undefined) return visitor.B(value.B); if (value.SS !== undefined) return visitor.SS(value.SS); if (value.NS !== undefined) return visitor.NS(value.NS); if (value.BS !== undefined) return visitor.BS(value.BS); if (value.M !== undefined) return visitor.M(value.M); if (value.L !== undefined) return visitor.L(value.L); if (value.NULL !== undefined) return visitor.NULL(value.NULL); if (value.BOOL !== undefined) return visitor.BOOL(value.BOOL); return visitor._(value.$unknown[0], value.$unknown[1]); }; /** * @internal */ export const filterSensitiveLog = (obj: AttributeValue): any => { if (obj.S !== undefined) return { S: obj.S }; if (obj.N !== undefined) return { N: obj.N }; if (obj.B !== undefined) return { B: obj.B }; if (obj.SS !== undefined) return { SS: obj.SS }; if (obj.NS !== undefined) return { NS: obj.NS }; if (obj.BS !== undefined) return { BS: obj.BS }; if (obj.M !== undefined) return { M: Object.entries(obj.M).reduce( (acc: any, [key, value]: [string, AttributeValue]) => ({ ...acc, [key]: AttributeValue.filterSensitiveLog(value), }), {} ), }; if (obj.L !== undefined) return { L: obj.L.map((item) => AttributeValue.filterSensitiveLog(item)) }; if (obj.NULL !== undefined) return { NULL: obj.NULL }; if (obj.BOOL !== undefined) return { BOOL: obj.BOOL }; if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; }; } /** * <p>A description of a single data modification that was performed on an item in a DynamoDB table.</p> */ export interface StreamRecord { /** * <p>The approximate date and time when the stream record was created, in <a href="http://www.epochconverter.com/">UNIX epoch time</a> format.</p> */ ApproximateCreationDateTime?: Date; /** * <p>The primary key attribute(s) for the DynamoDB item that was modified.</p> */ Keys?: { [key: string]: AttributeValue }; /** * <p>The item in the DynamoDB table as it appeared after it was modified.</p> */ NewImage?: { [key: string]: AttributeValue }; /** * <p>The item in the DynamoDB table as it appeared before it was modified.</p> */ OldImage?: { [key: string]: AttributeValue }; /** * <p>The sequence number of the stream record.</p> */ SequenceNumber?: string; /** * <p>The size of the stream record, in bytes.</p> */ SizeBytes?: number; /** * <p>The type of data from the modified DynamoDB item that was captured in this stream record:</p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item.</p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified.</p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified.</p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item.</p> * </li> * </ul> */ StreamViewType?: StreamViewType | string; } export namespace StreamRecord { /** * @internal */ export const filterSensitiveLog = (obj: StreamRecord): any => ({ ...obj, ...(obj.Keys && { Keys: Object.entries(obj.Keys).reduce( (acc: any, [key, value]: [string, AttributeValue]) => ({ ...acc, [key]: AttributeValue.filterSensitiveLog(value), }), {} ), }), ...(obj.NewImage && { NewImage: Object.entries(obj.NewImage).reduce( (acc: any, [key, value]: [string, AttributeValue]) => ({ ...acc, [key]: AttributeValue.filterSensitiveLog(value), }), {} ), }), ...(obj.OldImage && { OldImage: Object.entries(obj.OldImage).reduce( (acc: any, [key, value]: [string, AttributeValue]) => ({ ...acc, [key]: AttributeValue.filterSensitiveLog(value), }), {} ), }), }); } /** * <p>A description of a unique event within a stream.</p> */ export interface _Record { /** * <p>A globally unique identifier for the event that was recorded in this stream record.</p> */ eventID?: string; /** * <p>The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table.</p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified.</p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table</p> * </li> * </ul> */ eventName?: OperationType | string; /** * <p>The version number of the stream record format. This number is updated whenever the structure of <code>Record</code> is modified.</p> * <p>Client applications must not assume that <code>eventVersion</code> will remain at a particular * value, as this number is subject to change at any time. In general, <code>eventVersion</code> will * only increase as the low-level DynamoDB Streams API evolves.</p> */ eventVersion?: string; /** * <p>The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>.</p> */ eventSource?: string; /** * <p>The region in which the <code>GetRecords</code> request was received.</p> */ awsRegion?: string; /** * <p>The main body of the stream record, containing all of the DynamoDB-specific fields.</p> */ dynamodb?: StreamRecord; /** * <p>Items that are deleted by the Time to Live process after expiration have the following fields: </p> * <ul> * <li> * <p>Records[].userIdentity.type</p> * <p>"Service"</p> * </li> * <li> * <p>Records[].userIdentity.principalId</p> * <p>"dynamodb.amazonaws.com"</p> * </li> * </ul> */ userIdentity?: Identity; } export namespace _Record { /** * @internal */ export const filterSensitiveLog = (obj: _Record): any => ({ ...obj, ...(obj.dynamodb && { dynamodb: StreamRecord.filterSensitiveLog(obj.dynamodb) }), }); } /** * <p>Represents the output of a <code>GetRecords</code> operation.</p> */ export interface GetRecordsOutput { /** * <p>The stream records from the shard, which were retrieved using the shard iterator.</p> */ Records?: _Record[]; /** * <p>The next position in the shard from which to start sequentially reading stream records. If * set to <code>null</code>, the shard has been closed and the requested iterator will not return * any more data.</p> */ NextShardIterator?: string; } export namespace GetRecordsOutput { /** * @internal */ export const filterSensitiveLog = (obj: GetRecordsOutput): any => ({ ...obj, ...(obj.Records && { Records: obj.Records.map((item) => _Record.filterSensitiveLog(item)) }), }); }
the_stack
import {expect} from '@loopback/testlab'; import { Entity, HasManyDefinition, model, ModelDefinition, property, RelationType, } from '../../../..'; import { createTargetConstraintFromThrough, createThroughConstraintFromSource, createThroughConstraintFromTarget, getTargetIdsFromTargetModels, getTargetKeysFromThroughModels, HasManyThroughResolvedDefinition, resolveHasManyThroughMetadata, } from '../../../../relations/has-many/has-many-through.helpers'; describe('HasManyThroughHelpers', () => { context('createThroughConstraintFromSource', () => { it('creates constraint for searching through models', () => { const result = createThroughConstraintFromSource(relationMetaData, 1); expect(result).to.containEql({categoryId: 1}); }); }); context('getTargetKeysFromThroughModels', () => { it('returns the target fk value of a given through instance', () => { const through1 = createCategoryProductLink({ id: 1, categoryId: 2, productId: 9, }); const result = getTargetKeysFromThroughModels(relationMetaData, [ through1, ]); expect(result).to.deepEqual([9]); }); it('returns the target fk values of given through instances', () => { const through1 = createCategoryProductLink({ id: 1, categoryId: 2, productId: 9, }); const through2 = createCategoryProductLink({ id: 2, categoryId: 2, productId: 8, }); const result = getTargetKeysFromThroughModels(relationMetaData, [ through1, through2, ]); expect(result).to.containDeep([9, 8]); }); }); context('createTargetConstraintFromThrough', () => { it('creates constraint for searching target models', () => { const through1 = createCategoryProductLink({ id: 1, categoryId: 2, productId: 9, }); const through2 = createCategoryProductLink({ id: 2, categoryId: 2, productId: 8, }); // single through model let result = createTargetConstraintFromThrough(relationMetaData, [ through1, ]); expect(result).to.containEql({id: 9}); // multiple through models result = createTargetConstraintFromThrough(relationMetaData, [ through1, through2, ]); expect(result).to.containEql({id: {inq: [9, 8]}}); }); it('creates constraint for searching target models with duplicate keys', () => { const through1 = createCategoryProductLink({ id: 1, categoryId: 2, productId: 9, }); const through2 = createCategoryProductLink({ id: 2, categoryId: 3, productId: 9, }); const result = createTargetConstraintFromThrough(relationMetaData, [ through1, through2, ]); expect(result).to.containEql({id: 9}); }); }); context('getTargetIdsFromTargetModels', () => { it('returns an empty array if the given target array is empty', () => { const result = getTargetIdsFromTargetModels(relationMetaData, []); expect(result).to.containDeep([]); }); it('creates constraint with a given fk', () => { const result = getTargetIdsFromTargetModels(relationMetaData, [ createProduct({id: 1}), ]); expect(result).to.containDeep([1]); }); it('creates constraint with given fks', () => { const result = getTargetIdsFromTargetModels(relationMetaData, [ createProduct({id: 1}), createProduct({id: 2}), ]); expect(result).to.containDeep([1, 2]); }); }); context('createThroughConstraintFromTarget', () => { it('creates constraint with a given fk', () => { const result = createThroughConstraintFromTarget(relationMetaData, [1]); expect(result).to.containEql({productId: 1}); }); it('creates constraint with given fks', () => { const result = createThroughConstraintFromTarget( relationMetaData, [1, 2], ); expect(result).to.containEql({productId: {inq: [1, 2]}}); }); it('throws if fkValue is undefined', () => { expect(() => createThroughConstraintFromTarget(relationMetaData, []), ).to.throw(/"fkValue" must be provided/); }); }); context('resolveHasManyThroughMetadata', () => { it('throws if the wrong metadata type is used', async () => { const metadata: unknown = { name: 'category', type: RelationType.hasOne, targetsMany: false, source: Category, target: () => Product, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( /Invalid hasOne definition for Category#category: relation type must be HasMany/, ); }); it('throws if the through is not provided', async () => { const metadata: unknown = { name: 'category', type: RelationType.hasMany, targetsMany: true, source: Category, target: () => Product, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( /Invalid hasMany definition for Category#category: through must be specified/, ); }); it('throws if the through is not resolvable', async () => { const metadata: unknown = { name: 'category', type: RelationType.hasMany, targetsMany: true, source: Category, through: {model: 'random'}, target: () => Product, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( /Invalid hasMany definition for Category#category: through.model must be a type resolver/, ); }); describe('resolves through.keyTo/keyFrom', () => { it('resolves metadata with complete hasManyThrough definition', () => { const metadata = { name: 'products', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => CategoryProductLink, keyFrom: 'categoryId', keyTo: 'productId', }, }; const meta = resolveHasManyThroughMetadata( metadata as HasManyDefinition, ); expect(meta).to.eql(relationMetaData); }); it('infers through.keyFrom if it is not provided', () => { const metadata = { name: 'products', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => CategoryProductLink, // no through.keyFrom keyTo: 'productId', }, }; const meta = resolveHasManyThroughMetadata( metadata as HasManyDefinition, ); expect(meta).to.eql(relationMetaData); }); it('infers through.keyTo if it is not provided', () => { const metadata = { name: 'products', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => CategoryProductLink, keyFrom: 'categoryId', // no through.keyTo }, }; const meta = resolveHasManyThroughMetadata( metadata as HasManyDefinition, ); expect(meta).to.eql(relationMetaData); }); it('throws if through.keyFrom is not provided in through', async () => { const metadata = { name: 'categories', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => InvalidThrough, keyTo: 'productId', }, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( /Invalid hasMany definition for Category#categories: through model InvalidThrough is missing definition of source foreign key/, ); }); it('throws if through.keyTo is not provided in through', async () => { const metadata = { name: 'categories', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => InvalidThrough2, keyFrom: 'categoryId', }, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( /Invalid hasMany definition for Category#categories: through model InvalidThrough2 is missing definition of target foreign key/, ); }); it('throws if the target model does not have the id property', async () => { const metadata = { name: 'categories', type: RelationType.hasMany, targetsMany: true, source: Category, keyFrom: 'id', target: () => InvalidProduct, keyTo: 'id', through: { model: () => CategoryProductLink, keyFrom: 'categoryId', keyTo: 'productId', }, }; expect(() => { resolveHasManyThroughMetadata(metadata as HasManyDefinition); }).to.throw( 'Invalid hasMany definition for Category#categories: target model InvalidProduct does not have any primary key (id property)', ); }); }); }); /****** HELPERS *******/ @model() class Category extends Entity { @property({id: true}) id: number; constructor(data: Partial<Category>) { super(data); } } @model() class Product extends Entity { @property({id: true}) id: number; constructor(data: Partial<Product>) { super(data); } } @model() class InvalidProduct extends Entity { @property({id: false}) random: number; constructor(data: Partial<InvalidProduct>) { super(data); } } @model() class CategoryProductLink extends Entity { @property({id: true}) id: number; @property() categoryId: number; @property() productId: number; constructor(data: Partial<Product>) { super(data); } } const relationMetaData = { name: 'products', type: 'hasMany', targetsMany: true, source: Category, keyFrom: 'id', target: () => Product, keyTo: 'id', through: { model: () => CategoryProductLink, keyFrom: 'categoryId', keyTo: 'productId', }, } as HasManyThroughResolvedDefinition; class InvalidThrough extends Entity {} InvalidThrough.definition = new ModelDefinition('InvalidThrough') .addProperty('id', { type: 'number', id: true, required: true, }) // lack through.keyFrom .addProperty('productId', {type: 'number'}); class InvalidThrough2 extends Entity {} InvalidThrough2.definition = new ModelDefinition('InvalidThrough2') .addProperty('id', { type: 'number', id: true, required: true, }) // lack through.keyTo .addProperty('categoryId', {type: 'number'}); function createCategoryProductLink(properties: Partial<CategoryProductLink>) { return new CategoryProductLink(properties); } function createProduct(properties: Partial<Product>) { return new Product(properties); } });
the_stack
export default [ { firstName: 'Brooke', lastName: 'Heeran', email: 'bheeran0@altervista.org', gender: 'Female', status: 'Failed', // _expanded: { // schema: [ // { name: 'firstName', displayName: 'First Name', width: 200 }, // { name: 'lastName', displayName: 'Last Name', width: 200 }, // ] // }, }, { firstName: 'Frazer', lastName: 'Cathro', email: 'fcathro1@ucla.edu', gender: 'Male', status: 'Failed', // _expanded: { // schema: [ // { name: 'year', displayName: 'Year', width: 100, comparator: (a: Data, b: Data): number => a.year.localeCompare(b.year) }, // { name: 'income', displayName: 'Income', width: 200, comparator: (a: Data, b: Data): number => a.income.localeCompare(b.income) }, // ], // data: [ // { year: 2016, income: "50k" }, // { year: 2018, income: "80k" }, // { year: 2017, income: "60k" }, // { year: 2020, income: "70k" } // ] // } }, { firstName: 'Lemmie', lastName: 'Ciric', email: { title: 'lciric2@dmoz.org', metaList: ['First', 'Second'], }, gender: 'Male', status: 'Completed', }, { firstName: 'Randy', lastName: 'Boatwright', email: 'rboatwright3@arstechnica.com', status: 'Completed', gender: 'Male', // _expanded: { // showHead: false, // data: [ // { // gender: 'Male', // }, // { // gender: 'Male', // }, // { // gender: 'Male', // } // ] // } }, { firstName: 'Rolando', lastName: 'Cyples', email: 'rcyples4@biglobe.ne.jp', gender: 'Male', status: 'Failed', }, { firstName: 'Lem', lastName: 'Males', email: 'lmales5@admin.ch', gender: 'Male', status: 'Failed', }, { firstName: 'Sayres', lastName: 'Adelberg', email: 'sadelberg6@uol.com.br', gender: 'Male', status: 'Completed', }, { firstName: 'Murray', lastName: 'Bravington', email: 'mbravington7@drupal.org', gender: 'Male', status: 'Failed', }, { firstName: 'Jena', lastName: 'Swatheridge', email: 'jswatheridge8@npr.org', gender: 'Female', status: 'Failed', }, { firstName: 'Annabel', lastName: 'Nelsey', email: 'anelsey9@google.com', gender: 'Female', status: 'Completed', }, { firstName: 'Carin', lastName: 'Robiou', email: 'crobioua@skype.com', gender: 'Female', status: 'Completed', }, { firstName: 'Anson', lastName: 'Gamon', email: 'agamonb@economist.com', gender: 'Male', }, { firstName: 'Brina', lastName: 'Pirie', email: 'bpiriec@stumbleupon.com', gender: 'Female', }, { firstName: 'Hermy', lastName: 'Dyett', email: 'hdyettd@boston.com', gender: 'Male', }, { firstName: 'Aime', lastName: 'von Hagt', email: 'avonhagte@nyu.edu', gender: 'Female', }, { firstName: 'Gusti', lastName: 'Haycock', email: 'ghaycockf@virginia.edu', gender: 'Female', }, { firstName: 'Mortimer', lastName: 'Kunneke', email: 'mkunnekeg@weather.com', gender: 'Male', }, { firstName: 'Barnie', lastName: 'Pohls', email: 'bpohlsh@columbia.edu', gender: 'Male', }, { firstName: 'Elliot', lastName: 'Nealey', email: 'enealeyi@cocolog-nifty.com', gender: 'Male', }, { firstName: 'Allsun', lastName: 'Gong', email: 'agongj@discuz.net', gender: 'Female', }, { firstName: 'Harwell', lastName: 'Kegan', email: 'hkegank@domainmarket.com', gender: 'Male', }, { firstName: 'Gilles', lastName: 'Sandell', email: 'gsandelll@apache.org', gender: 'Male', }, { firstName: 'Hilliard', lastName: 'Beamish', email: 'hbeamishm@shop-pro.jp', gender: 'Male', }, { firstName: 'Charley', lastName: 'Kuschek', email: 'ckuschekn@dropbox.com', gender: 'Male', }, { firstName: 'Danny', lastName: 'Churchin', email: 'dchurchino@bbc.co.uk', gender: 'Female', }, { firstName: 'Ervin', lastName: 'Chatelain', email: 'echatelainp@mac.com', gender: 'Male', }, { firstName: 'Milli', lastName: 'Joseph', email: 'mjosephq@merriam-webster.com', gender: 'Female', }, { firstName: 'Greer', lastName: "O'Doherty", email: 'godohertyr@homestead.com', gender: 'Female', }, { firstName: 'Haroun', lastName: 'Martensen', email: 'hmartensens@skype.com', gender: 'Male', }, { firstName: 'Desiree', lastName: 'Colwell', email: 'dcolwellt@businessinsider.com', gender: 'Female', }, { firstName: 'Almeda', lastName: 'Jowsey', email: 'ajowseyu@ask.com', gender: 'Female', }, { firstName: 'Cinderella', lastName: 'Dunnet', email: 'cdunnetv@mac.com', gender: 'Female', }, { firstName: 'Hubert', lastName: 'Legion', email: 'hlegionw@ameblo.jp', gender: 'Male', }, { firstName: 'Costa', lastName: 'Adamovsky', email: 'cadamovskyx@joomla.org', gender: 'Male', }, { firstName: 'Kristan', lastName: 'Bielfeld', email: 'kbielfeldy@live.com', gender: 'Female', }, { firstName: 'Sammy', lastName: 'Shermore', email: 'sshermorez@washington.edu', gender: 'Female', }, { firstName: 'Kathi', lastName: 'Dowyer', email: 'kdowyer10@bluehost.com', gender: 'Female', }, { firstName: 'Kennith', lastName: 'Whitehouse', email: 'kwhitehouse11@cornell.edu', gender: 'Male', }, { firstName: 'Brianna', lastName: 'Garland', email: 'bgarland12@wikipedia.org', gender: 'Female', }, { firstName: 'Cristobal', lastName: 'Mapholm', email: 'cmapholm13@constantcontact.com', gender: 'Male', }, { firstName: 'Zia', lastName: 'Harrowing', email: 'zharrowing14@huffingtonpost.com', gender: 'Female', }, { firstName: 'Zabrina', lastName: 'Gravener', email: 'zgravener15@ameblo.jp', gender: 'Female', }, { firstName: 'Gregoor', lastName: 'Cruz', email: 'gcruz16@uol.com.br', gender: 'Male', }, { firstName: 'Julita', lastName: 'Gemeau', email: 'jgemeau17@bandcamp.com', gender: 'Female', }, { firstName: 'Gilbert', lastName: 'Sallier', email: 'gsallier18@dailymail.co.uk', gender: 'Male', }, { firstName: 'Bride', lastName: 'Boniface', email: 'bboniface19@howstuffworks.com', gender: 'Female', }, { firstName: 'Rodolph', lastName: 'Mattussevich', email: 'rmattussevich1a@nymag.com', gender: 'Male', }, { firstName: 'Rowan', lastName: 'Rizon', email: 'rrizon1b@thetimes.co.uk', gender: 'Male', }, { firstName: 'Avie', lastName: 'Nicolls', email: 'anicolls1c@nbcnews.com', gender: 'Female', }, { firstName: 'Bram', lastName: 'Kleinhaut', email: 'bkleinhaut1d@imdb.com', gender: 'Male', }, { firstName: 'Carmita', lastName: 'Costin', email: 'ccostin1e@hibu.com', gender: 'Female', }, { firstName: 'Wash', lastName: 'Vannuchi', email: 'wvannuchi1f@japanpost.jp', gender: 'Male', }, { firstName: 'Nikki', lastName: 'Faye', email: 'nfaye1g@feedburner.com', gender: 'Female', }, { firstName: 'Aron', lastName: 'Scimonelli', email: 'ascimonelli1h@nationalgeographic.com', gender: 'Male', }, { firstName: 'Smitty', lastName: 'Giacomello', email: 'sgiacomello1i@google.co.uk', gender: 'Male', }, { firstName: 'Staci', lastName: "D'Elias", email: 'sdelias1j@paginegialle.it', gender: 'Female', }, { firstName: 'Radcliffe', lastName: 'Garbutt', email: 'rgarbutt1k@thetimes.co.uk', gender: 'Male', }, { firstName: 'Maxwell', lastName: 'Krikorian', email: 'mkrikorian1l@ask.com', gender: 'Male', }, { firstName: 'Dunstan', lastName: 'Chansonne', email: 'dchansonne1m@posterous.com', gender: 'Male', }, { firstName: 'Isaak', lastName: 'Faherty', email: 'ifaherty1n@who.int', gender: 'Male', }, { firstName: 'Sawyere', lastName: 'Ede', email: 'sede1o@drupal.org', gender: 'Male', }, { firstName: 'Perren', lastName: 'Daddow', email: 'pdaddow1p@indiegogo.com', gender: 'Male', }, { firstName: 'Brendis', lastName: 'Napier', email: 'bnapier1q@multiply.com', gender: 'Male', }, { firstName: 'Francene', lastName: 'Godbold', email: 'fgodbold1r@joomla.org', gender: 'Female', }, { firstName: 'Moll', lastName: 'Fludgate', email: 'mfludgate1s@who.int', gender: 'Female', }, { firstName: 'Allayne', lastName: 'Medhurst', email: 'amedhurst1t@is.gd', gender: 'Male', }, { firstName: 'Genvieve', lastName: 'Mellows', email: 'gmellows1u@stumbleupon.com', gender: 'Female', }, { firstName: 'Rebe', lastName: 'Durnford', email: 'rdurnford1v@biglobe.ne.jp', gender: 'Female', }, { firstName: 'Thalia', lastName: 'Joerning', email: 'tjoerning1w@netscape.com', gender: 'Female', }, { firstName: 'Beckie', lastName: 'Lammin', email: 'blammin1x@gnu.org', gender: 'Female', }, { firstName: 'Kassandra', lastName: 'Furney', email: 'kfurney1y@surveymonkey.com', gender: 'Female', }, { firstName: 'Libbie', lastName: 'Gladyer', email: 'lgladyer1z@dropbox.com', gender: 'Female', }, { firstName: 'Kai', lastName: 'Goldsbury', email: 'kgoldsbury20@census.gov', gender: 'Female', }, { firstName: 'Arielle', lastName: 'De Bell', email: 'adebell21@addthis.com', gender: 'Female', }, { firstName: 'Ellary', lastName: 'Warnock', email: 'ewarnock22@ted.com', gender: 'Male', }, { firstName: 'Skelly', lastName: 'Blakes', email: 'sblakes23@reddit.com', gender: 'Male', }, { firstName: 'Roanne', lastName: 'Stanyforth', email: 'rstanyforth24@com.com', gender: 'Female', }, { firstName: 'Cash', lastName: 'Fettis', email: 'cfettis25@go.com', gender: 'Male', }, { firstName: 'Farleigh', lastName: 'McDavid', email: 'fmcdavid26@sbwire.com', gender: 'Male', }, { firstName: 'Holly', lastName: 'Barfford', email: 'hbarfford27@wsj.com', gender: 'Female', }, { firstName: 'Hurley', lastName: 'Benaine', email: 'hbenaine28@sun.com', gender: 'Male', }, { firstName: 'Maryjo', lastName: 'Gilhooly', email: 'mgilhooly29@tripod.com', gender: 'Female', }, { firstName: 'Annis', lastName: 'Linkie', email: 'alinkie2a@wp.com', gender: 'Female', }, { firstName: 'Mariel', lastName: 'Husher', email: 'mhusher2b@etsy.com', gender: 'Female', }, { firstName: 'Niels', lastName: 'Klimontovich', email: 'nklimontovich2c@surveymonkey.com', gender: 'Male', }, { firstName: 'Udall', lastName: 'Linfitt', email: 'ulinfitt2d@toplist.cz', gender: 'Male', }, { firstName: 'Isidore', lastName: 'Kuhn', email: 'ikuhn2e@cdc.gov', gender: 'Male', }, { firstName: 'Rosemonde', lastName: 'Kettle', email: 'rkettle2f@techcrunch.com', gender: 'Female', }, { firstName: 'Cass', lastName: 'Boot', email: 'cboot2g@furl.net', gender: 'Male', }, { firstName: 'Montague', lastName: 'Rossey', email: 'mrossey2h@goo.gl', gender: 'Male', }, { firstName: 'Geno', lastName: 'Jenkyn', email: 'gjenkyn2i@opensource.org', gender: 'Male', }, { firstName: 'Esdras', lastName: 'Skivington', email: 'eskivington2j@answers.com', gender: 'Male', }, { firstName: 'Gabriello', lastName: 'Luce', email: 'gluce2k@nydailynews.com', gender: 'Male', }, { firstName: 'Magdalene', lastName: 'Ilyunin', email: 'milyunin2l@prweb.com', gender: 'Female', }, { firstName: 'Isidro', lastName: 'Fawson', email: 'ifawson2m@squidoo.com', gender: 'Male', }, { firstName: 'Blinny', lastName: 'Palfrey', email: 'bpalfrey2n@networksolutions.com', gender: 'Female', }, { firstName: 'Justen', lastName: 'Kordas', email: 'jkordas2o@symantec.com', gender: 'Male', }, { firstName: 'Damien', lastName: 'Hallede', email: 'dhallede2p@unicef.org', gender: 'Male', }, { firstName: 'Jaquelyn', lastName: 'Rockhall', email: 'jrockhall2q@vkontakte.ru', gender: 'Female', }, { firstName: 'Garrek', lastName: 'Matignon', email: 'gmatignon2r@noaa.gov', gender: 'Male', }, ];
the_stack
import { Calculate, FormulaError, CalcSheetFamilyItem } from './index'; import { CommonErrors, FailureEventArgs, FormulasErrorsStrings, isExternalFileLink } from '../common/index'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; export class Parser { private parent: Calculate; constructor(parent?: Calculate) { this.parent = parent; } private emptyStr: string = ''; private storedStringText: string = this.emptyStr; private sheetToken: string = '!'; /** @hidden */ public tokenAdd: string = 'a'; /** @hidden */ public tokenSubtract: string = 's'; /** @hidden */ public tokenMultiply: string = 'm'; /** @hidden */ public tokenDivide: string = 'd'; /** @hidden */ public tokenLess: string = 'l'; private charEm: string = 'r'; private charEp: string = 'x'; /** @hidden */ public tokenGreater: string = 'g'; /** @hidden */ public tokenEqual: string = 'e'; /** @hidden */ public tokenLessEq: string = 'k'; /** @hidden */ public tokenGreaterEq: string = 'j'; /** @hidden */ public tokenNotEqual: string = 'o'; /** @hidden */ public tokenAnd: string = 'c'; private tokenEm: string = 'v'; private tokenEp: string = 't'; /** @hidden */ public tokenOr: string = String.fromCharCode(126); private charAnd: string = 'i'; private charLess: string = '<'; private charGreater: string = '>'; private charEqual: string = '='; private charLessEq: string = 'f'; private charGreaterEq: string = 'h'; private charNoEqual: string = 'z'; private stringGreaterEq: string = '>='; private stringLessEq: string = '<='; private stringNoEqual: string = '<>'; private stringAnd: string = '&'; private stringOr: string = '^'; private charOr: string = 'w'; private charAdd: string = '+'; private charSubtract: string = '-'; private charMultiply: string = '*'; private charDivide: string = '/'; private fixedReference: string = '$'; private spaceString: string = ' '; private ignoreBracet: boolean = false; /** @hidden */ public isError: boolean = false; /** @hidden */ public isFormulaParsed: boolean = false; private findNamedRange: boolean = false; private stringsColl: Map<string, string> = new Map<string, string>(); private tokens: string[] = [ this.tokenAdd, this.tokenSubtract, this.tokenMultiply, this.tokenDivide, this.tokenLess, this.tokenGreater, this.tokenEqual, this.tokenLessEq, this.tokenGreaterEq, this.tokenNotEqual, this.tokenAnd, this.tokenOr]; private charNOTop: string = String.fromCharCode(167); private specialSym: string[] = ['~', '@', '#', '?']; private isFailureTriggered: boolean = false; /** * @hidden * @param {string} text - specify the text * @param {string} fkey - specify the formula key * @returns {string} - returns parse. */ public parse(text: string, fkey?: string): string { if (this.parent.isTextEmpty(text)) { return text; } if (isExternalFileLink(text)) { return this.parent.getErrorStrings()[CommonErrors.ref]; } if (this.parent.getFormulaCharacter() !== String.fromCharCode(0) && this.parent.getFormulaCharacter() === text[0]) { text = text.substring(1); } if (this.parent.namedRanges.size > 0 || this.parent.storedData.size > 0) { text = this.checkForNamedRangeAndKeyValue(text); this.findNamedRange = false; } text = text.split('-+').join('-'); text = text.split('--').join('+'); text = text.split('+-').join('-'); text = text.split('-' + '(' + '-').join('('); const formulaString: Map<string, string> = this.storeStrings(text); text = this.storedStringText; let i: number = 0; if (isNullOrUndefined(formulaString)) { text = text.split(' ').join(''); } text = text.split('=>').join('>='); text = text.split('=<').join('<='); if (text[text.length - 1] !== this.parent.arithMarker || this.indexOfAny(text, this.tokens) !== (text.length - 2)) { text = text.toUpperCase(); } if (text.indexOf(this.sheetToken) > -1) { const family: CalcSheetFamilyItem = this.parent.getSheetFamilyItem(this.parent.grid); if (family.sheetNameToParentObject != null && family.sheetNameToParentObject.size > 0) { if (text[0] !== this.sheetToken.toString()) { text = this.parent.setTokensForSheets(text); } const sheetToken: string = this.parent.getSheetToken(text.split(this.parent.tic).join(this.emptyStr)); const scopedRange: string = this.checkScopedRange(text.split('"').join(this.emptyStr).split(this.sheetToken).join('')); if (isNullOrUndefined(sheetToken) && sheetToken !== '' && this.parent.namedRanges.size > 0 && scopedRange !== '') { text = scopedRange; } } } text = this.markLibraryFormulas(text); try { text = this.formulaAutoCorrection(text); } catch (ex) { const args: FailureEventArgs = { message: ex.message, exception: ex, isForceCalculable: ex.formulaCorrection, computeForceCalculate: false }; if (!args.isForceCalculable) { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.invalid_expression]; } if (!this.isFailureTriggered) { this.parent.trigger('onFailure', args); this.isFailureTriggered = true; } if (args.isForceCalculable && args.computeForceCalculate) { text = this.formulaAutoCorrection(text, args); this.parent.storedData.get(fkey).formulaText = '=' + text; } else { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.invalid_expression]; } } if (!this.ignoreBracet) { i = text.indexOf(')'); while (i > -1) { const k: number = text.substring(0, i).lastIndexOf('('); if (k === -1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.mismatched_parentheses]); } if (k === i - 1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.empty_expression]); } let s: string = this.emptyStr; if (this.ignoreBracet) { s = this.parent.substring(text, k, i - k + 1); } else { s = this.parent.substring(text, k + 1, i - k - 1); } try { text = text.substring(0, k) + this.parseSimple(s) + text.substring(i + 1); } catch (ex) { const args: FailureEventArgs = this.exceptionArgs(ex); if (!this.isFailureTriggered) { this.parent.trigger('onFailure', args); this.isFailureTriggered = true; } const errorMessage: string = (typeof args.exception === 'string') ? args.exception : args.message; return (this.parent.getErrorLine(ex) ? '' : '#' + this.parent.getErrorLine(ex) + ': ') + errorMessage; } i = text.indexOf(')'); } } if (!this.ignoreBracet && text.indexOf('(') > -1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.mismatched_parentheses]); } text = this.parseSimple(text); if (formulaString !== null && formulaString.size > 0) { text = this.setStrings(text, formulaString); } return text; } /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ private exceptionArgs(ex: any): FailureEventArgs { return { message: ex.message, exception: ex, isForceCalculable: ex.formulaCorrection, computeForceCalculate: false }; } private formulaAutoCorrection(formula: string, args?: FailureEventArgs): string { const arithemeticArr: string[] = ['*', '+', '-', '/', '^', '&']; const logicalSym: string[] = ['>', '=', '<']; let i: number = 0; let form: string = ''; let op: string = ''; let firstOp: string = ''; let secondprevOp: string = ''; let secondnextOp: string = ''; let firstDigit: string = ''; let secondDigit: string = ''; let countDigit: number = 0; if (this.parent.formulaErrorStrings.indexOf(formula) > -1) { return formula; } else { if (this.indexOfAny(formula, this.specialSym) > -1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.invalid_expression], false); } while (i < formula.length) { formula = formula.split('-*').join('-').split('/*').join('/').split('*/').join('*').split('-/').join('-'). split('*+').join('*').split('+*').join('+'); if ((this.parent.isDigit(formula[i]) && ((formula.length > i + 1) && (this.indexOfAny(formula[i + 1], arithemeticArr) > -1)) && ((formula.length > i + 2) && (!isNullOrUndefined(formula[i + 2]) && this.indexOfAny(formula[i + 2], arithemeticArr) > -1))) && (formula[i + 2] !== '-' || (formula[i + 1] !== '*' && formula[i + 1] !== '/'))) { if (isNullOrUndefined(args)) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.invalid_expression], true); } if (args.computeForceCalculate) { if (this.parent.isDigit(formula[i])) { if (countDigit < 1) { firstDigit = formula[i]; firstOp = formula[i + 1]; if (isNullOrUndefined(firstOp)) { firstOp = this.emptyStr; } firstOp = firstOp === '&' ? '' : firstOp; countDigit = countDigit + 1; form = form + firstDigit + firstOp; } else if (countDigit < 2) { secondDigit = formula[i]; secondprevOp = formula[i - 1]; secondnextOp = formula[i + 1]; countDigit = 0; if (secondprevOp === '-') { secondnextOp = isNullOrUndefined(secondnextOp) ? this.emptyStr : secondnextOp; secondnextOp = secondnextOp === '&' ? '' : secondnextOp; form = form + secondprevOp + secondDigit + secondnextOp; } else { secondnextOp = isNullOrUndefined(secondnextOp) ? this.emptyStr : secondnextOp; form = form + secondDigit + secondnextOp; } } i = i + 2; } else { form = (formula[i] === '-') ? form + formula[i] : form; i = i + 1; } } else { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.improper_formula]; } /* eslint-disable-next-line */ } else if ((this.parent.isDigit(formula[i]) || formula[i] === this.parent.rightBracket || this.parent.storedData.has(formula[i].toUpperCase())) && (isNullOrUndefined(formula[i + 1]) || this.indexOfAny(formula[i + 1], arithemeticArr)) > -1) { op = isNullOrUndefined(formula[i + 1]) ? this.emptyStr : formula[i + 1]; op = op === '&' ? '' : op; form = formula[i - 1] === '-' ? form + formula[i - 1] + formula[i] + op : form + formula[i] + op; i = i + 2; /* eslint-disable-next-line */ } else if (this.indexOfAny(formula[i], logicalSym) > -1 && !isNullOrUndefined(formula[i - 1]) && !isNullOrUndefined(formula[i + 1])) { form = form + formula[i]; i = i + 1; } else if (formula[i] === 'q') { while (formula[i] !== this.parent.leftBracket) { form = form + formula[i]; i = i + 1; } } else if (formula[i] === this.parent.leftBracket || formula[i] === this.parent.rightBracket || formula[i] === '{' || formula[i] === '}' || formula[i] === '(' || formula[i] === ')') { form = form + formula[i]; i = i + 1; } else if (this.parent.isUpperChar(formula[i]) || formula[i].indexOf(':') > -1 || formula[i] === this.parent.getParseArgumentSeparator() || ((formula[i] === '%') && (this.parent.isDigit(formula[i - 1])))) { form = form + formula[i]; i = i + 1; } else if (formula[i] === this.parent.tic || formula[i] === ' ' || formula[i] === '.' || formula[i] === this.sheetToken || formula[i] === '$') { form = form + formula[i]; i = i + 1; } else { if (this.parent.isDigit(formula[i])) { form = formula[i - 1] === '-' ? form + formula[i - 1] + formula[i] : form + formula[i]; } if (formula[i] === '-' || formula[i] === '+') { form = form + formula[i]; form = form.split('++').join('+').split('+-').join('-').split('-+').join('-'); } if (formula[i] === '/' || formula[i] === '*') { form = form + formula[i]; } i = i + 1; } } } form = form === this.emptyStr ? formula : form; if (this.indexOfAny(form[form.length - 1], arithemeticArr) > -1) { form = form.substring(0, form.length - 1); } form = form.split('--').join('-').split('-+').join('-').split('+-').join('-'); return form; } private checkScopedRange(text: string): string { let scopedRange: string = this.emptyStr; let b: string = 'NaN'; let id: number = this.parent.getSheetID(this.parent.grid); const sheet: CalcSheetFamilyItem = this.parent.getSheetFamilyItem(this.parent.grid); if (text[0] === this.sheetToken.toString()) { const i: number = text.indexOf(this.sheetToken, 1); const v: number = parseInt(text.substr(1, i - 1), 10); if (i > 1 && !this.parent.isNaN(v)) { text = text.substring(i + 1); id = v; } } const token: string = '!' + id.toString() + '!'; if (sheet === null || sheet.sheetNameToToken == null) { return b; } sheet.sheetNameToToken.forEach((value: string, key: string) => { if (sheet.sheetNameToToken.get(key).toString() === token) { let s: string = this.emptyStr; this.parent.namedRanges.forEach((value: string, key: string) => { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ if (!isNullOrUndefined(this.parent.parentObject as any)) { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ s = ((this.parent.parentObject as any).getActiveSheet().name + this.sheetToken + text).toUpperCase(); } else { s = sheet.sheetNameToToken.get(key).toUpperCase(); } if (this.parent.getNamedRanges().has(s)) { scopedRange = (this.parent.getNamedRanges().get(s)).toUpperCase(); b = scopedRange; } }); } }); return b; } private storeStrings(tempString: string): Map<string, string> { let i: number = 0; let j: number = 0; let id: number = 0; let key: string = ''; let storedString: Map<string, string> = null; let condition: string; const ticLoc: number = tempString.indexOf(this.parent.tic); if (ticLoc > -1) { i = tempString.indexOf(this.parent.tic); while (i > -1 && tempString.length > 0) { if (storedString === null) { storedString = this.stringsColl; } j = i + 1 < tempString.length ? tempString.indexOf(this.parent.tic, i + 1) : -1; if (j === -1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.mismatched_tics]); } condition = this.parent.substring(tempString, i, j - i + 1); key = this.parent.tic + this.spaceString + id.toString() + this.parent.tic; storedString = storedString.set(key, condition); tempString = tempString.substring(0, i) + key + tempString.substring(j + 1); i = i + key.length; if (i <= tempString.length) { i = tempString.indexOf(this.parent.tic, i); } id++; } } this.storedStringText = tempString; return storedString; } private setStrings(text: string, formulaString: Map<string, string>): string { for (let i: number = 0; i < formulaString.size; i++) { formulaString.forEach((value: string, key: string) => { text = text.split(key).join(value); }); } return text; } /** * @hidden * @param {string} formulaText - specify the formula text * @returns {string} - parse simple. */ public parseSimple(formulaText: string): string { let needToContinue: boolean = true; let text: string = formulaText; if (text.length > 0 && text[0] === '+') { text = text.substring(1); } if (text === '#DIV/0!') { return '#DIV/0!'; } if (text === '#NAME?') { return '#NAME?'; } if (text === '') { return text; } if (this.parent.formulaErrorStrings.indexOf(text) > -1) { return text; } text = text.split(this.stringLessEq).join(this.charLessEq); text = text.split(this.stringGreaterEq).join(this.charGreaterEq); text = text.split(this.stringNoEqual).join(this.charNoEqual); text = text.split(this.stringAnd).join(this.charAnd); text = text.split(this.stringOr).join(this.charOr); text = text.split(this.fixedReference).join(this.emptyStr); needToContinue = true; const expTokenArray: string[] = [this.tokenEp, this.tokenEm]; const mulTokenArray: string[] = [this.tokenMultiply, this.tokenDivide]; const addTokenArray: string[] = [this.tokenAdd, this.tokenSubtract]; const mulCharArray: string[] = [this.charMultiply, this.charDivide]; const addCharArray: string[] = [this.charAdd, this.charSubtract]; const compareTokenArray: string[] = [this.tokenLess, this.tokenGreater, this.tokenEqual, this.tokenLessEq, this.tokenGreaterEq, this.tokenNotEqual]; const compareCharArray: string[] = [this.charLess, this.charGreater, this.charEqual, this.charLessEq, this.charGreaterEq, this.charNoEqual]; const expCharArray: string[] = [this.charEp, this.charEm]; const andTokenArray: string[] = [this.tokenAnd]; const andCharArray: string[] = [this.charAnd]; const orCharArray: string[] = [this.charOr]; const orTokenArray: string[] = [this.tokenOr]; text = this.parseSimpleOperators(text, expTokenArray, expCharArray); text = this.parseSimpleOperators(text, orTokenArray, orCharArray); if (needToContinue) { text = this.parseSimpleOperators(text, mulTokenArray, mulCharArray); } if (needToContinue) { text = this.parseSimpleOperators(text, addTokenArray, addCharArray); } if (needToContinue) { text = this.parseSimpleOperators(text, compareTokenArray, compareCharArray); } if (needToContinue) { text = this.parseSimpleOperators(text, andTokenArray, andCharArray); } return text; } /** * @hidden * @param {string} formulaText - specify the formula text * @param {string[]} markers - specify the markers * @param {string[]} operators - specify the operators * @returns {string} - parse Simple Operators */ public parseSimpleOperators(formulaText: string, markers: string[], operators: string[]): string { if (this.parent.getErrorStrings().indexOf(formulaText) > -1) { return formulaText; } let text: string = formulaText; let i: number = 0; let op: string = ''; for (let c: number = 0; c < operators.length; c++) { op = op + operators[c]; } /* eslint-disable */ text = text.split("---").join("-").split("--").join("+").split(this.parent.getParseArgumentSeparator() + "-").join(this.parent.getParseArgumentSeparator() + "u").split(this.parent.leftBracket + "-").join(this.parent.leftBracket + "u").split("=-").join("=u"); text = text.split(',+').join(',').split(this.parent.leftBracket + '+').join(this.parent.leftBracket).split('=+').join('=').split('>+').join('>').split('<+').join('<').split('/+').join('/').split('*+').join('*').split('++').join('+').split("*-").join("*u").toString();; /* eslint-enable */ if (text.length > 0 && text[0] === '-') { text = text.substring(1).split('-').join(this.tokenOr); text = '0-' + text; text = this.parseSimpleOperators(text, [this.tokenSubtract], [this.charSubtract]); text = text.split(this.tokenOr).join('-'); } else if (text.length > 0 && text[0] === '+') { text = text.substring(1); } else if (text.length > 0 && text[text.length - 1] === '+') { text = text.substring(0, text.length - 1); } try { if (this.indexOfAny(text, operators) > -1) { i = this.indexOfAny(text, operators); while (i > -1) { let left: string = ''; let right: string = ''; let leftIndex: number = 0; let rightIndex: number = 0; const isNotOperator: boolean = text[i] === this.charNOTop; let j: number = 0; if (!isNotOperator) { j = i - 1; if (text[j] === this.parent.arithMarker) { const k: number = this.findLeftMarker(text.substring(0, j - 1)); if (k < 0) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]); } left = this.parent.substring(text, k + 1, j - k - 1); leftIndex = k + 1; } else if (text[j] === this.parent.rightBracket) { let bracketCount: number = 0; let k: number = j - 1; while (k > 0 && (text[k] !== 'q' || bracketCount !== 0)) { if (text[k] === 'q') { bracketCount--; } else if (text[k] === this.parent.rightBracket) { bracketCount++; } k--; } if (k < 0) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]); } left = this.parent.substring(text, k, j - k + 1); leftIndex = k; } else if (text[j] === this.parent.tic[0]) { const l: number = text.substring(0, j - 1).lastIndexOf(this.parent.tic); if (l < 0) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]); } left = this.parent.substring(text, l, j - l + 1); leftIndex = l; } else { let period: boolean = false; while (j > -1 && (this.parent.isDigit(text[j]) || (!period && text[j] === this.parent.getParseDecimalSeparator()))) { if (text[j] === this.parent.getParseDecimalSeparator()) { period = true; } j = j - 1; } if (j > -1 && period && text[j] === this.parent.getParseDecimalSeparator()) { /* eslint-disable-next-line */ throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.number_contains_2_decimal_points]); } j = j + 1; if (j === 0 || (j > 0 && !this.parent.isUpperChar(text[j - 1]))) { left = 'n' + this.parent.substring(text, j, i - j); leftIndex = j; } else { j = j - 1; while (j > -1 && (this.parent.isUpperChar(text[j]) || this.parent.isDigit(text[j]))) { j = j - 1; } if (j > -1 && text[j] === this.sheetToken) { j = j - 1; while (j > -1 && text[j] !== this.sheetToken) { j = j - 1; } if (j > -1 && text[j] === this.sheetToken) { j = j - 1; } } if (j > -1 && text[j] === ':') { //// handle range operands j = j - 1; while (j > -1 && this.parent.isDigit(text[j])) { j = j - 1; } while (j > -1 && this.parent.isUpperChar(text[j])) { j = j - 1; } if (j > -1 && text[j] === this.sheetToken) { j--; while (j > -1 && text[j] !== this.sheetToken) { j--; } if (j > -1 && text[j] === this.sheetToken) { j--; } } j = j + 1; left = this.parent.substring(text, j, i - j); left = this.parent.getCellFrom(left); } else { j = j + 1; left = this.parent.substring(text, j, i - j); } this.parent.updateDependentCell(left); leftIndex = j; } if ((this.parent.namedRanges.size > 0 && this.parent.namedRanges.has(left.toUpperCase())) || (this.parent.storedData.has(left.toUpperCase()))) { left = 'n' + this.checkForNamedRangeAndKeyValue(left); } } } else { leftIndex = i; } if (i === text.length - 1) { /* eslint-disable-next-line */ throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.expression_cannot_end_with_an_operator]); } else { j = i + 1; let uFound: boolean = text[j] === 'u'; // for 3*-2 if (uFound) { j = j + 1; } if (text[j] === this.parent.tic[0]) { const k: number = text.substring(j + 1).indexOf(this.parent.tic); if (k < 0) { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]; } right = this.parent.substring(text, j, k + 2); rightIndex = k + j + 2; } else if (text[j] === this.parent.arithMarker) { const k: number = this.findRightMarker(text.substring(j + 1)); if (k < 0) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]); } right = this.parent.substring(text, j + 1, k); rightIndex = k + j + 2; } else if (text[j] === 'q') { let bracketCount: number = 0; let k: number = j + 1; while (k < text.length && (text[k] !== this.parent.rightBracket || bracketCount !== 0)) { if (text[k] === this.parent.rightBracket) { bracketCount++; } else if (text[k] === 'q') { bracketCount--; } k++; } if (k === text.length) { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.cannot_parse]; } right = this.parent.substring(text, j, k - j + 1); if (uFound) { right = 'u' + right; } rightIndex = k + 1; } else if (this.parent.isDigit(text[j]) || text[j] === this.parent.getParseDecimalSeparator()) { let period: boolean = (text[j] === this.parent.getParseDecimalSeparator()); j = j + 1; /* eslint-disable-next-line */ while (j < text.length && (this.parent.isDigit(text[j]) || (!period && text[j] === this.parent.getParseDecimalSeparator()))) { if (text[j] === this.parent.getParseDecimalSeparator()) { period = true; } j = j + 1; } if (j < text.length && text[j] === '%') { j += 1; } if (period && j < text.length && text[j] === this.parent.getParseDecimalSeparator()) { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.number_contains_2_decimal_points]; } right = 'n' + this.parent.substring(text, i + 1, j - i - 1); rightIndex = j; } else if (this.parent.isUpperChar(text[j]) || text[j] === this.sheetToken || text[j] === 'u') { if (text[j] === this.sheetToken) { j = j + 1; while (j < text.length && text[j] !== this.sheetToken) { j = j + 1; } } j = j + 1; let jTemp: number = 0; let inbracket: boolean = false; while (j < text.length && (this.parent.isUpperChar(text[j]) || text[j] === '_' || text[j] === '.' || text[j] === '[' || text[j] === ']' || text[j] === '#' || text[j] === ' ' || text[j] === '%' || text[j] === this.parent.getParseDecimalSeparator() && inbracket)) { if (j !== text.length - 1 && text[j] === '[' && text[j + 1] === '[') { inbracket = true; } if (j !== text.length - 1 && text[j] === ']' && text[j + 1] === ']') { inbracket = false; } j++; jTemp++; } let noCellReference: boolean = (j === text.length) || !this.parent.isDigit(text[j]); if (jTemp > 1) { while (j < text.length && (this.parent.isUpperChar(text[j]) || this.parent.isDigit(text[j]) || text[j] === ' ' || text[j] === '_')) { j++; } noCellReference = true; } while (j < text.length && this.parent.isDigit(text[j])) { j = j + 1; } if (j < text.length && text[j] === ':') { j = j + 1; if (j < text.length && text[j] === this.sheetToken) { j++; while (j < text.length && text[j] !== this.sheetToken) { j = j + 1; } if (j < text.length && text[j] === this.sheetToken) { j++; } } while (j < text.length && this.parent.isUpperChar(text[j])) { j = j + 1; } while (j < text.length && this.parent.isDigit(text[j])) { j = j + 1; } j = j - 1; right = this.parent.substring(text, i + 1, j - i); right = this.parent.getCellFrom(right); } else { j = j - 1; right = this.parent.substring(text, i + 1, j - i); uFound = text[j] === 'u'; if (uFound) { right = 'u' + right; } } if (noCellReference && right.startsWith(this.sheetToken)) { noCellReference = !this.parent.isCellReference(right); } if (!noCellReference) { this.parent.updateDependentCell(right); } if ((this.parent.namedRanges.size > 0 && this.parent.namedRanges.has(right.toUpperCase())) || (this.parent.storedData.has(right.toUpperCase()))) { right = 'n' + this.checkForNamedRangeAndKeyValue(right); } rightIndex = j + 1; } } const p: number = op.indexOf(text[i]); let s: string = this.parent.arithMarker + left + right + markers[p] + this.parent.arithMarker; if (leftIndex > 0) { s = text.substring(0, leftIndex) + s; } if (rightIndex < text.length) { s = s + text.substring(rightIndex); } s = s.split(this.parent.arithMarker2).join(this.parent.arithMarker.toString()); text = s; i = this.indexOfAny(text, operators); } } else { if (text.length > 0 && (this.parent.isUpperChar(text[0]) || text[0] === this.sheetToken)) { let isCharacter: boolean = true; let checkLetter: boolean = true; let oneTokenFound: boolean = false; const textLen: number = text.length; for (let k: number = 0; k < textLen; ++k) { if (text[k] === this.sheetToken) { if (k > 0 && !oneTokenFound) { throw this.parent.getErrorStrings()[CommonErrors.ref]; } oneTokenFound = true; k++; while (k < textLen && this.parent.isDigit(text[k])) { k++; } if (k === textLen || text[k] !== this.sheetToken) { isCharacter = false; break; } } else { if (!checkLetter && this.parent.isChar(text[k])) { isCharacter = false; break; } if (this.parent.isChar(text[k]) || this.parent.isDigit(text[k]) || text[k] === this.sheetToken) { checkLetter = this.parent.isUpperChar(text[k]); } else { isCharacter = false; break; } } } if (isCharacter) { this.parent.updateDependentCell(text); } } } return text; } catch (ex) { return ex; } } /** * @hidden * @param {string} text - specify the text * @param {string[]} operators - specify the operators * @returns {number} - returns index. */ public indexOfAny(text: string, operators: string[]): number { for (let i: number = 0; i < text.length; i++) { if (operators.indexOf(text[i]) > -1) { return i; } } return -1; } /** * @hidden * @param {string} text - specify the text * @returns {number} - find Left Marker. */ public findLeftMarker(text: string): number { let ret: number = -1; if (text.indexOf(this.parent.arithMarker) > -1) { let bracketLevel: number = 0; for (let i: number = text.length - 1; i >= 0; --i) { if (text[i] === this.parent.rightBracket) { bracketLevel--; } else if (text[i] === this.parent.leftBracket) { bracketLevel++; } else if (text[i] === this.parent.arithMarker && bracketLevel === 0) { ret = i; break; } } } return ret; } /** * @hidden * @param {string} text - specify the text. * @returns {number} - find Right Marker. */ public findRightMarker(text: string): number { let ret: number = -1; if (text.indexOf(this.parent.arithMarker) > -1) { let bracketLevel: number = 0; for (let j: number = 0; j < text.length; ++j) { if (text[j] === this.parent.rightBracket) { bracketLevel--; } else if (text[j] === this.parent.leftBracket) { bracketLevel++; } else if (text[j] === this.parent.arithMarker && bracketLevel === 0) { ret = j; break; } } } return ret; } /** * @hidden * @param {string} formula - specify the formula * @param {string} fKey - specify the formula key. * @returns {string} - parse formula. */ public parseFormula(formula: string, fKey?: string): string { if (formula.length > 0 && formula[0] === this.parent.getFormulaCharacter()) { formula = formula.substring(1); } if (formula.indexOf('#REF!') > -1) { return this.parent.getErrorStrings()[CommonErrors.ref]; } if (formula.length > 0 && formula[0] === '+') { formula = formula.substring(1); } try { this.isFailureTriggered = false; this.isError = false; formula = this.parse(formula.trim(), fKey); this.isFormulaParsed = true; } catch (ex) { const args: FailureEventArgs = this.exceptionArgs(ex); if (!this.isFailureTriggered) { this.parent.trigger('onFailure', args); this.isFailureTriggered = true; } const errorMessage: string = (typeof args.exception === 'string') ? args.exception : args.message; formula = (isNullOrUndefined(this.parent.getErrorLine(ex)) ? '' : '#' + this.parent.getErrorLine(ex) + ': ') + errorMessage; this.isError = true; } return formula; } /** * @hidden * @param {string} formula - specify the formula * @returns {string} - mark library formulas. */ public markLibraryFormulas(formula: string): string { let bracCount: number = 0; let rightParens: number = formula.indexOf(')'); if (rightParens === -1) { formula = this.markNamedRanges(formula); } else { while (rightParens > -1) { let parenCount: number = 0; let leftParens: number = rightParens - 1; while (leftParens > -1 && (formula[leftParens] !== '(' || parenCount !== 0)) { if (formula[leftParens] === ')') { parenCount++; } // else if (formula[leftParens] === ')') { // parenCount--; // } leftParens--; } if (leftParens === -1) { throw new FormulaError(this.parent.formulaErrorStrings[FormulasErrorsStrings.mismatched_parentheses]); } let i: number = leftParens - 1; while (i > -1 && (this.parent.isChar(formula[i]))) { i--; } const len: number = leftParens - i - 1; const libFormula: string = this.parent.substring(formula, i + 1, len); if (len > 0 && !isNullOrUndefined(this.parent.getFunction(libFormula))) { if (this.parent.substring(formula, i + 1, len) === 'AREAS') { this.ignoreBracet = true; } else { this.ignoreBracet = false; } let substr: string = this.parent.substring(formula, leftParens, rightParens - leftParens + 1); try { let args: FailureEventArgs; substr = substr.split('(').join('').split(')').join(''); substr = '(' + this.formulaAutoCorrection(substr, args) + ')'; } catch (ex) { const args: FailureEventArgs = { message: ex.message, exception: ex, isForceCalculable: ex.formulaCorrection, computeForceCalculate: false }; if (!args.isForceCalculable) { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.improper_formula]; } if (!this.isFailureTriggered) { this.parent.trigger('onFailure', args); this.isFailureTriggered = true; bracCount = bracCount + 1; } args.computeForceCalculate = bracCount > 0 ? true : args.computeForceCalculate; if (args.isForceCalculable) { if (args.computeForceCalculate) { substr = substr.split('(').join('').split(')').join(''); substr = '(' + this.formulaAutoCorrection(substr, args) + ')'; } else { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.improper_formula]; } } else { throw this.parent.formulaErrorStrings[FormulasErrorsStrings.improper_formula]; } } substr = this.markNamedRanges(substr); substr = this.swapInnerParens(substr); substr = this.addParensToArgs(substr); const id: number = substr.lastIndexOf(this.parent.getParseArgumentSeparator()); if (id === -1) { if (substr.length > 2 && substr[0] === '(' && substr[substr.length - 1] === ')') { if (substr[1] !== '{' && substr[1] !== '(') { substr = substr.substring(0, substr.length - 1) + '}' + substr.substring(substr.length - 1); substr = substr[0] + '{' + substr.substring(1); } } } formula = formula.substring(0, i + 1) + 'q' + this.parent.substring(formula, i + 1, len) + (substr.split('(').join(this.parent.leftBracket)) .split(')').join(this.parent.rightBracket) + formula.substring(rightParens + 1); } else if (len > 0) { return this.parent.getErrorStrings()[CommonErrors.name]; } else { let s: string = this.emptyStr; if (leftParens > 0) { s = formula.substring(0, leftParens); } s = s + '{' + this.parent.substring(formula, leftParens + 1, rightParens - leftParens - 1) + '}'; if (rightParens < formula.length) { s = s + formula.substring(rightParens + 1); } s = this.markNamedRanges(s); formula = s; } rightParens = formula.indexOf(')'); } } formula = (formula.split('{').join('(')).split('}').join(')'); return formula; } /** * @hidden * @param {string} fSubstr - specify the string * @returns {string} - swap inner parens. */ public swapInnerParens(fSubstr: string): string { if (fSubstr.length > 2) { fSubstr = fSubstr[0] + fSubstr.substr(1, fSubstr.length - 2).split('(').join('{').split(')').join('}') + fSubstr[fSubstr.length - 1]; } return fSubstr; } /** * @hidden * @param {string} fSubstr - specify the string * @returns {string} - add parens to args. */ public addParensToArgs(fSubstr: string): string { if (fSubstr.length === 0) { return this.emptyStr; } const rightSides: string[] = []; rightSides.push(this.parent.getParseArgumentSeparator()); rightSides.push(this.parent.rightBracket); let id: number = fSubstr.lastIndexOf(this.parent.getParseArgumentSeparator()); let k: number = 0; if (id === -1) { if (fSubstr.length > 2 && fSubstr[0] === '(' && fSubstr[fSubstr.length - 1] === ')') { if (fSubstr[1] !== '{' && fSubstr[1] !== '(') { fSubstr = fSubstr.substring(0, fSubstr.length - 1) + '}' + fSubstr.substring(fSubstr.length - 1); fSubstr = fSubstr[0] + '{' + fSubstr.substring(1); } else { const marker: string[] = ['+', '-', '*', '/']; id = this.lastIndexOfAny(fSubstr, marker); if (k === 0 && fSubstr[fSubstr.length - 1] === ')') { k = fSubstr.length - 1; } if (k > 0) { if (fSubstr[id + 1] !== '{' && fSubstr[id - 1] === '}') { fSubstr = fSubstr.substr(0, k) + '}' + fSubstr.substr(k); fSubstr = fSubstr.substr(0, id + 1) + '{' + fSubstr.substr(id + 1); } } } } } else { let oneTimeOnly: boolean = true; while (id > -1) { let j: number = this.indexOfAny(fSubstr.substring(id + 1, fSubstr.length), rightSides); if (j >= 0) { j = id + j + 1; } else if (j === -1 && fSubstr[fSubstr.length - 1] === ')') { j = fSubstr.length - 1; } if (j > 0) { if (fSubstr[id + 1] !== '{' && fSubstr[j - 1] !== '}') { fSubstr = fSubstr.substr(0, j) + '}' + fSubstr.substr(j); fSubstr = fSubstr.substr(0, id + 1) + '{' + fSubstr.substr(id + 1); } } id = fSubstr.substr(0, id).lastIndexOf(this.parent.getParseArgumentSeparator()); if (oneTimeOnly && id === -1 && fSubstr[0] === '(') { id = 0; oneTimeOnly = false; } } } fSubstr = fSubstr.split('{}').join(this.emptyStr); return fSubstr; } /** * @hidden * @param {string} text - specify the text * @param {string[]} operators - specify the operators * @returns {number} - returns last Index Of Any. */ private lastIndexOfAny(text: string, operators: string[]): number { for (let i: number = text.length - 1; i > -1; i--) { if (operators.indexOf(text[i]) > -1) { return i; } } return -1; } /** * @hidden * @param {string} formula - specify the formula * @returns {string} - mark Named Ranges. */ public markNamedRanges(formula: string): string { const markers: string[] = [')', this.parent.getParseArgumentSeparator(), '}', '+', '-', '*', '/', '<', '>', '=', '&']; let i: number = (formula.length > 0 && (formula[0] === '(' || formula[0] === '{')) ? 1 : 0; if (formula.indexOf('#N/A') > -1) { formula = formula.split('#N/A').join('#N~A'); } if (formula.indexOf('#DIV/0!') > -1) { formula = formula.split('#DIV/0!').join('#DIV~0!'); } let end: number = this.indexOfAny(formula.substring(i), markers); while (end > -1 && end + i < formula.length) { let scopedRange: string = this.emptyStr; let s: string = null; if ((this.parent.substring(formula, i, end)).indexOf('[') > -1) { s = this.getTableRange(this.parent.substring(formula, i, end)); } else if (this.parent.storedData.has(this.parent.substring(formula, i, end))) { s = this.checkForNamedRangeAndKeyValue(this.parent.substring(formula, i, end)); } else if (this.parent.namedRanges.has(this.parent.substring(formula, i, end))) { s = this.checkForNamedRangeAndKeyValue(this.parent.substring(formula, i, end)); } if (isNullOrUndefined(s)) { scopedRange = this.checkScopedRange(this.parent.substring(formula, i, end)); if (scopedRange !== 'NaN') { this.findNamedRange = true; s = scopedRange; } else if (this.parent.substring(formula, i, end).startsWith(this.sheetToken.toString())) { //let formulaStr: number = this.parent.substring(formula, i, end).indexOf(this.sheetToken, 1); // if (formulaStr > 1) { // s = this.parent.namedRanges.get(this.parent.substring // (formula.substring(i), formulaStr + 1, end - formulaStr - 1)); // } } if (!isNullOrUndefined(s) && this.findNamedRange) { if (s.indexOf(this.fixedReference) > -1) { s = s.split(this.fixedReference).join(this.emptyStr); } } } if (!isNullOrUndefined(s)) { s = s.toUpperCase(); s = this.parent.setTokensForSheets(s); s = this.markLibraryFormulas(s); } if (!isNullOrUndefined(s) && s !== this.emptyStr) { formula = formula.substring(0, i) + s + formula.substring(i + end); i += s.length + 1; } else { i += end + 1; while (i < formula.length && !this.parent.isUpperChar(formula[i]) && formula[i] !== this.sheetToken) { i++; } } end = i; if (i < formula.length - 1 && formula[i] === '{') { i = i + 1; } end = this.indexOfAny(formula.substring(i), markers); while (end === 0 && i < formula.length - 1) { i++; end = this.indexOfAny(formula.substring(i), markers); } if ((end === -1 || formula.substring(i).indexOf('[') > -1) && i < formula.length) { if (formula.substring(i).indexOf('[') > -1) { s = this.getTableRange(formula.substring(i)); } else { if (this.parent.storedData.has(formula.substring(i))) { s = this.parent.storedData.size > 0 ? this.checkForNamedRangeAndKeyValue(formula.substring(i)) : s; } else { s = this.parent.namedRanges.size > 0 ? this.checkForNamedRangeAndKeyValue(formula.substring(i)) : s; } } if (isNullOrUndefined(s)) { scopedRange = this.checkScopedRange(formula.substring(i)); if (scopedRange !== 'NaN') { s = scopedRange; } } if (!isNullOrUndefined(s) && s !== this.emptyStr) { s = s.toUpperCase(); s = this.parent.setTokensForSheets(s); s = this.markLibraryFormulas(s); if (s != null) { const val: string = formula.substring(i); if (val[val.length - 1] === ')') { formula = formula.substring(0, i) + s + ')'; } else { formula = formula.substring(0, i) + s; } i += s.toString().length + 1; } } end = (i < formula.length) ? this.indexOfAny(formula.substring(i), markers) : -1; } } if (formula.indexOf('#N~A') > -1) { formula = formula.split('#N~A').join('#N/A'); } if (formula.indexOf('#DIV~0!') > -1) { formula = formula.split('#DIV~0!').join('#DIV/0!'); } return formula; } /** * @hidden * @param {string} text - specify the text. * @returns {string} - check For Named Range And Key Value */ public checkForNamedRangeAndKeyValue(text: string): string { let scopedRange: string = this.emptyStr; if (text.indexOf('[') > -1) { const namerangeValue: string = this.getTableRange(text); if (!isNullOrUndefined(namerangeValue)) { this.findNamedRange = true; text = namerangeValue; } } scopedRange = this.checkScopedRange(text); if (scopedRange !== 'NaN') { this.findNamedRange = true; text = scopedRange; } else { if (text.indexOf(this.sheetToken) > -1) { const sheet: CalcSheetFamilyItem = this.parent.getSheetFamilyItem(this.parent.grid); let value: string = text.split('"').join(this.emptyStr); value = value.substr(0, value.indexOf(this.sheetToken)); if (sheet.sheetNameToToken.has(value.toUpperCase())) { /* eslint-disable */ let sheetIndex: number = parseInt(sheet.sheetNameToToken.get(value.toUpperCase()).split(this.sheetToken).join(this.emptyStr)); // if (!ej.isNullOrUndefined(this.parentObject) && this.parentObject.pluginName == "ejSpreadsheet") { // var name = text.replace(value, this.parentObject.model.sheets[(sheetIndex + 1)].sheetInfo.text.toUpperCase()).split("'").join(this._string_empty); // if (this.getNamedRanges().length > 0 && this.getNamedRanges().contains(name.toUpperCase())) { // text = name; // } // } /* tslint-enable */ } } if (this.parent.storedData.size > 0 && this.parent.storedData.has(text)) { text = 'A' + this.parent.colIndex(text); } if (this.parent.namedRanges.size > 0 && this.parent.namedRanges.has(text.toUpperCase())) { if (!isNullOrUndefined(this.parent.parentObject as any)) { text = this.parse(this.parent.namedRanges.get(text.toUpperCase())); } else { text = this.parse(this.parent.namedRanges.get(text.toUpperCase())); text = this.parent.setTokensForSheets(text); if (text.indexOf(this.fixedReference) > -1) { text.split(this.fixedReference).join(this.emptyStr); } this.findNamedRange = true; } } if (this.findNamedRange) { if (text[0] !== '!' && text[0] !== 'q' && text[0] !== 'bq') { text = this.parent.setTokensForSheets(text); if (text.indexOf(this.fixedReference) > -1) { text = text.split(this.fixedReference).join(this.emptyStr); } } } } return text; } private getTableRange(text: string): string { text = text.replace(' ', this.emptyStr).toUpperCase(); let name: string = text.replace(']', this.emptyStr).replace('#DATA', this.emptyStr); let tableName: string = name; if (name.indexOf(this.parent.getParseArgumentSeparator()) > -1) { tableName = name.substring(0, name.indexOf(this.parent.getParseArgumentSeparator())).replace('[', this.emptyStr); name = name.replace('[', this.emptyStr).replace(this.parent.getParseArgumentSeparator(), '_'); } let range: string = this.emptyStr; return name.toUpperCase(); } private findNextEndIndex(formula: string, loc: number): number { let count: number = 0; let l: number = loc; let found: boolean = false; while (!found && loc < formula.length) { if (formula[l] === '[') { count++; } else if (formula[l] === ']') { count--; if (count === 0) { found = true; } } loc++; } loc = loc - l; return loc; }; }
the_stack
import { Token } from '@aws-cdk/core'; import { StandardAttributeNames } from './private/attr-names'; /** * The set of standard attributes that can be marked as required or mutable. * * @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#cognito-user-pools-standard-attributes */ export interface StandardAttributes { /** * The user's postal address. * @default - see the defaults under `StandardAttribute` */ readonly address?: StandardAttribute; /** * The user's birthday, represented as an ISO 8601:2004 format. * @default - see the defaults under `StandardAttribute` */ readonly birthdate?: StandardAttribute; /** * The user's e-mail address, represented as an RFC 5322 [RFC5322] addr-spec. * @default - see the defaults under `StandardAttribute` */ readonly email?: StandardAttribute; /** * The surname or last name of the user. * @default - see the defaults under `StandardAttribute` */ readonly familyName?: StandardAttribute; /** * The user's gender. * @default - see the defaults under `StandardAttribute` */ readonly gender?: StandardAttribute; /** * The user's first name or give name. * @default - see the defaults under `StandardAttribute` */ readonly givenName?: StandardAttribute; /** * The user's locale, represented as a BCP47 [RFC5646] language tag. * @default - see the defaults under `StandardAttribute` */ readonly locale?: StandardAttribute; /** * The user's middle name. * @default - see the defaults under `StandardAttribute` */ readonly middleName?: StandardAttribute; /** * The user's full name in displayable form, including all name parts, titles and suffixes. * @default - see the defaults under `StandardAttribute` */ readonly fullname?: StandardAttribute; /** * The user's nickname or casual name. * @default - see the defaults under `StandardAttribute` */ readonly nickname?: StandardAttribute; /** * The user's telephone number. * @default - see the defaults under `StandardAttribute` */ readonly phoneNumber?: StandardAttribute; /** * The URL to the user's profile picture. * @default - see the defaults under `StandardAttribute` */ readonly profilePicture?: StandardAttribute; /** * The user's preffered username, different from the immutable user name. * @default - see the defaults under `StandardAttribute` */ readonly preferredUsername?: StandardAttribute; /** * The URL to the user's profile page. * @default - see the defaults under `StandardAttribute` */ readonly profilePage?: StandardAttribute; /** * The user's time zone. * @default - see the defaults under `StandardAttribute` */ readonly timezone?: StandardAttribute; /** * The time, the user's information was last updated. * @default - see the defaults under `StandardAttribute` */ readonly lastUpdateTime?: StandardAttribute; /** * The URL to the user's web page or blog. * @default - see the defaults under `StandardAttribute` */ readonly website?: StandardAttribute; /** * DEPRECATED * @deprecated this is not a standard attribute and was incorrectly added to the CDK. * It is a Cognito built-in attribute and cannot be controlled as part of user pool creation. * @default - see the defaults under `StandardAttribute` */ readonly emailVerified?: StandardAttribute; /** * DEPRECATED * @deprecated this is not a standard attribute and was incorrectly added to the CDK. * It is a Cognito built-in attribute and cannot be controlled as part of user pool creation. * @default - see the defaults under `StandardAttribute` */ readonly phoneNumberVerified?: StandardAttribute; } /** * Standard attribute that can be marked as required or mutable. * * @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#cognito-user-pools-standard-attributes */ export interface StandardAttribute { /** * Specifies whether the value of the attribute can be changed. * For any user pool attribute that's mapped to an identity provider attribute, this must be set to `true`. * Amazon Cognito updates mapped attributes when users sign in to your application through an identity provider. * If an attribute is immutable, Amazon Cognito throws an error when it attempts to update the attribute. * * @default true */ readonly mutable?: boolean; /** * Specifies whether the attribute is required upon user registration. * If the attribute is required and the user does not provide a value, registration or sign-in will fail. * * @default false */ readonly required?: boolean; } /** * Represents a custom attribute type. */ export interface ICustomAttribute { /** * Bind this custom attribute type to the values as expected by CloudFormation */ bind(): CustomAttributeConfig; } /** * Configuration that will be fed into CloudFormation for any custom attribute type. */ export interface CustomAttributeConfig { /** * The data type of the custom attribute. * * @see https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SchemaAttributeType.html#CognitoUserPools-Type-SchemaAttributeType-AttributeDataType */ readonly dataType: string; /** * The constraints for a custom attribute of 'String' data type. * @default - None. */ readonly stringConstraints?: StringAttributeConstraints; /** * The constraints for a custom attribute of the 'Number' data type. * @default - None. */ readonly numberConstraints?: NumberAttributeConstraints; /** * Specifies whether the value of the attribute can be changed. * For any user pool attribute that's mapped to an identity provider attribute, you must set this parameter to true. * Amazon Cognito updates mapped attributes when users sign in to your application through an identity provider. * If an attribute is immutable, Amazon Cognito throws an error when it attempts to update the attribute. * * @default false */ readonly mutable?: boolean; } /** * Constraints that can be applied to a custom attribute of any type. */ export interface CustomAttributeProps { /** * Specifies whether the value of the attribute can be changed. * For any user pool attribute that's mapped to an identity provider attribute, you must set this parameter to true. * Amazon Cognito updates mapped attributes when users sign in to your application through an identity provider. * If an attribute is immutable, Amazon Cognito throws an error when it attempts to update the attribute. * * @default false */ readonly mutable?: boolean } /** * Constraints that can be applied to a custom attribute of string type. */ export interface StringAttributeConstraints { /** * Minimum length of this attribute. * @default 0 */ readonly minLen?: number; /** * Maximum length of this attribute. * @default 2048 */ readonly maxLen?: number; } /** * Props for constructing a StringAttr */ export interface StringAttributeProps extends StringAttributeConstraints, CustomAttributeProps { } /** * The String custom attribute type. */ export class StringAttribute implements ICustomAttribute { private readonly minLen?: number; private readonly maxLen?: number; private readonly mutable?: boolean; constructor(props: StringAttributeProps = {}) { if (props.minLen && !Token.isUnresolved(props.minLen) && props.minLen < 0) { throw new Error(`minLen cannot be less than 0 (value: ${props.minLen}).`); } if (props.maxLen && !Token.isUnresolved(props.maxLen) && props.maxLen > 2048) { throw new Error(`maxLen cannot be greater than 2048 (value: ${props.maxLen}).`); } this.minLen = props?.minLen; this.maxLen = props?.maxLen; this.mutable = props?.mutable; } public bind(): CustomAttributeConfig { let stringConstraints: StringAttributeConstraints | undefined; if (this.minLen || this.maxLen) { stringConstraints = { minLen: this.minLen, maxLen: this.maxLen, }; } return { dataType: 'String', stringConstraints, mutable: this.mutable, }; } } /** * Constraints that can be applied to a custom attribute of number type. */ export interface NumberAttributeConstraints { /** * Minimum value of this attribute. * @default - no minimum value */ readonly min?: number; /** * Maximum value of this attribute. * @default - no maximum value */ readonly max?: number; } /** * Props for NumberAttr */ export interface NumberAttributeProps extends NumberAttributeConstraints, CustomAttributeProps { } /** * The Number custom attribute type. */ export class NumberAttribute implements ICustomAttribute { private readonly min?: number; private readonly max?: number; private readonly mutable?: boolean; constructor(props: NumberAttributeProps = {}) { this.min = props?.min; this.max = props?.max; this.mutable = props?.mutable; } public bind(): CustomAttributeConfig { let numberConstraints: NumberAttributeConstraints | undefined; if (this.min || this.max) { numberConstraints = { min: this.min, max: this.max, }; } return { dataType: 'Number', numberConstraints, mutable: this.mutable, }; } } /** * The Boolean custom attribute type. */ export class BooleanAttribute implements ICustomAttribute { private readonly mutable?: boolean; constructor(props: CustomAttributeProps = {}) { this.mutable = props?.mutable; } public bind(): CustomAttributeConfig { return { dataType: 'Boolean', mutable: this.mutable, }; } } /** * The DateTime custom attribute type. */ export class DateTimeAttribute implements ICustomAttribute { private readonly mutable?: boolean; constructor(props: CustomAttributeProps = {}) { this.mutable = props?.mutable; } public bind(): CustomAttributeConfig { return { dataType: 'DateTime', mutable: this.mutable, }; } } /** * This interface contains standard attributes recognized by Cognito * from https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html * including built-in attributes `email_verified` and `phone_number_verified` */ export interface StandardAttributesMask { /** * The user's postal address. * @default false */ readonly address?: boolean; /** * The user's birthday, represented as an ISO 8601:2004 format. * @default false */ readonly birthdate?: boolean; /** * The user's e-mail address, represented as an RFC 5322 [RFC5322] addr-spec. * @default false */ readonly email?: boolean; /** * The surname or last name of the user. * @default false */ readonly familyName?: boolean; /** * The user's gender. * @default false */ readonly gender?: boolean; /** * The user's first name or give name. * @default false */ readonly givenName?: boolean; /** * The user's locale, represented as a BCP47 [RFC5646] language tag. * @default false */ readonly locale?: boolean; /** * The user's middle name. * @default false */ readonly middleName?: boolean; /** * The user's full name in displayable form, including all name parts, titles and suffixes. * @default false */ readonly fullname?: boolean; /** * The user's nickname or casual name. * @default false */ readonly nickname?: boolean; /** * The user's telephone number. * @default false */ readonly phoneNumber?: boolean; /** * The URL to the user's profile picture. * @default false */ readonly profilePicture?: boolean; /** * The user's preffered username, different from the immutable user name. * @default false */ readonly preferredUsername?: boolean; /** * The URL to the user's profile page. * @default false */ readonly profilePage?: boolean; /** * The user's time zone. * @default false */ readonly timezone?: boolean; /** * The time, the user's information was last updated. * @default false */ readonly lastUpdateTime?: boolean; /** * The URL to the user's web page or blog. * @default false */ readonly website?: boolean; /** * Whether the email address has been verified. * @default false */ readonly emailVerified?: boolean; /** * Whether the phone number has been verified. * @default false */ readonly phoneNumberVerified?: boolean; } /** * A set of attributes, useful to set Read and Write attributes */ export class ClientAttributes { /** * The set of attributes */ private attributesSet: Set<string>; /** * Creates a ClientAttributes with the specified attributes * * @default - a ClientAttributes object without any attributes */ constructor() { this.attributesSet = new Set<string>(); } /** * Creates a custom ClientAttributes with the specified attributes * @param attributes a list of standard attributes to add to the set */ public withStandardAttributes(attributes: StandardAttributesMask): ClientAttributes { let attributesSet = new Set(this.attributesSet); // iterate through key-values in the `StandardAttributeNames` constant // to get the value for all attributes for (const attributeKey in StandardAttributeNames) { if ((attributes as any)[attributeKey] === true) { const attributeName = (StandardAttributeNames as any)[attributeKey]; attributesSet.add(attributeName); } } let aux = new ClientAttributes(); aux.attributesSet = attributesSet; return aux; } /** * Creates a custom ClientAttributes with the specified attributes * @param attributes a list of custom attributes to add to the set */ public withCustomAttributes(...attributes: string[]): ClientAttributes { let attributesSet: Set<string> = new Set(this.attributesSet); for (let attribute of attributes) { // custom attributes MUST begin with `custom:`, so add the string if not present if (!attribute.startsWith('custom:')) { attribute = 'custom:' + attribute; } attributesSet.add(attribute); } let aux = new ClientAttributes(); aux.attributesSet = attributesSet; return aux; } /** * The list of attributes represented by this ClientAttributes */ public attributes(): string[] { // sorting is unnecessary but it simplify testing return Array.from(this.attributesSet).sort(); } }
the_stack
'use strict'; import * as assert from 'assert'; import { WhitespaceComputer } from 'vs/editor/common/viewLayout/whitespaceComputer'; suite('Editor ViewLayout - WhitespaceComputer', () => { test('WhitespaceComputer', () => { var whitespaceComputer = new WhitespaceComputer(); // Insert a whitespace after line number 2, of height 10 var a = whitespaceComputer.insertWhitespace(2, 0, 10); // whitespaces: a(2, 10) assert.equal(whitespaceComputer.getCount(), 1); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10); assert.equal(whitespaceComputer.getTotalHeight(), 10); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 10); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 10); // Insert a whitespace again after line number 2, of height 20 var b = whitespaceComputer.insertWhitespace(2, 0, 20); // whitespaces: a(2, 10), b(2, 20) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 30); assert.equal(whitespaceComputer.getTotalHeight(), 30); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 30); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30); // Change last inserted whitespace height to 30 whitespaceComputer.changeWhitespaceHeight(b, 30); // whitespaces: a(2, 10), b(2, 30) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 30); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 40); assert.equal(whitespaceComputer.getTotalHeight(), 40); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 40); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 40); // Remove last inserted whitespace whitespaceComputer.removeWhitespace(b); // whitespaces: a(2, 10) assert.equal(whitespaceComputer.getCount(), 1); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10); assert.equal(whitespaceComputer.getTotalHeight(), 10); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 10); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 10); // Add a whitespace before the first line of height 50 b = whitespaceComputer.insertWhitespace(0, 0, 50); // whitespaces: b(0, 50), a(2, 10) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60); assert.equal(whitespaceComputer.getTotalHeight(), 60); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 60); // Add a whitespace after line 4 of height 20 whitespaceComputer.insertWhitespace(4, 0, 20); // whitespaces: b(0, 50), a(2, 10), c(4, 20) assert.equal(whitespaceComputer.getCount(), 3); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60); assert.equal(whitespaceComputer.getAccumulatedHeight(2), 80); assert.equal(whitespaceComputer.getTotalHeight(), 80); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 60); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 80); // Add a whitespace after line 3 of height 30 whitespaceComputer.insertWhitespace(3, 0, 30); // whitespaces: b(0, 50), a(2, 10), d(3, 30), c(4, 20) assert.equal(whitespaceComputer.getCount(), 4); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(3), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(3), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60); assert.equal(whitespaceComputer.getAccumulatedHeight(2), 90); assert.equal(whitespaceComputer.getAccumulatedHeight(3), 110); assert.equal(whitespaceComputer.getTotalHeight(), 110); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 90); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 110); // Change whitespace after line 2 to height of 100 whitespaceComputer.changeWhitespaceHeight(a, 100); // whitespaces: b(0, 50), a(2, 100), d(3, 30), c(4, 20) assert.equal(whitespaceComputer.getCount(), 4); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 100); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(3), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(3), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 150); assert.equal(whitespaceComputer.getAccumulatedHeight(2), 180); assert.equal(whitespaceComputer.getAccumulatedHeight(3), 200); assert.equal(whitespaceComputer.getTotalHeight(), 200); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 150); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 180); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 200); // Remove whitespace after line 2 whitespaceComputer.removeWhitespace(a); // whitespaces: b(0, 50), d(3, 30), c(4, 20) assert.equal(whitespaceComputer.getCount(), 3); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 80); assert.equal(whitespaceComputer.getAccumulatedHeight(2), 100); assert.equal(whitespaceComputer.getTotalHeight(), 100); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 80); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 100); // Remove whitespace before line 1 whitespaceComputer.removeWhitespace(b); // whitespaces: d(3, 30), c(4, 20) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50); assert.equal(whitespaceComputer.getTotalHeight(), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50); // Delete line 1 whitespaceComputer.onLinesDeleted(1, 1); // whitespaces: d(2, 30), c(3, 20) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50); assert.equal(whitespaceComputer.getTotalHeight(), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 30); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50); // Insert a line before line 1 whitespaceComputer.onLinesInserted(1, 1); // whitespaces: d(3, 30), c(4, 20) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 4); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50); assert.equal(whitespaceComputer.getTotalHeight(), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50); // Delete line 4 whitespaceComputer.onLinesDeleted(4, 4); // whitespaces: d(3, 30), c(3, 20) assert.equal(whitespaceComputer.getCount(), 2); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30); assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20); assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30); assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50); assert.equal(whitespaceComputer.getTotalHeight(), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 50); assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50); }); test('WhitespaceComputer findInsertionIndex', () => { var makeArray = (size: number, fillValue: number) => { var r: number[] = []; for (var i = 0; i < size; i++) { r[i] = fillValue; } return r; }; var arr: number[]; var ordinals: number[]; arr = []; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 0); arr = [1]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); arr = [1, 3]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); arr = [1, 3, 5]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); arr = [1, 3, 5]; ordinals = makeArray(arr.length, 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); arr = [1, 3, 5, 7]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4); arr = [1, 3, 5, 7, 9]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5); arr = [1, 3, 5, 7, 9, 11]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6); arr = [1, 3, 5, 7, 9, 11, 13]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 13, ordinals, 0), 7); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 14, ordinals, 0), 7); arr = [1, 3, 5, 7, 9, 11, 13, 15]; ordinals = makeArray(arr.length, 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 13, ordinals, 0), 7); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 14, ordinals, 0), 7); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 15, ordinals, 0), 8); assert.equal(WhitespaceComputer.findInsertionIndex(arr, 16, ordinals, 0), 8); }); test('WhitespaceComputer changeWhitespaceAfterLineNumber & getFirstWhitespaceIndexAfterLineNumber', () => { var whitespaceComputer = new WhitespaceComputer(); var a = whitespaceComputer.insertWhitespace(0, 0, 1); var b = whitespaceComputer.insertWhitespace(7, 0, 1); var c = whitespaceComputer.insertWhitespace(3, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- // Do not really move a whitespaceComputer.changeWhitespaceAfterLineNumber(a, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 1 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- // Do not really move a whitespaceComputer.changeWhitespaceAfterLineNumber(a, 2); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 2 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- // Change a to conflict with c => a gets placed after c whitespaceComputer.changeWhitespaceAfterLineNumber(a, 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), c); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), a); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- // Make a no-op whitespaceComputer.changeWhitespaceAfterLineNumber(c, 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), c); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), a); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // c assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- // Conflict c with b => c gets placed after b whitespaceComputer.changeWhitespaceAfterLineNumber(c, 7); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 3 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), b); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 7); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 7 assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7); assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // a assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 1); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 1); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 1); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 1); // b assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // -- }); test('WhitespaceComputer Bug', () => { var whitespaceComputer = new WhitespaceComputer(); var a = whitespaceComputer.insertWhitespace(0, 0, 1); var b = whitespaceComputer.insertWhitespace(7, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), b); // 7 var c = whitespaceComputer.insertWhitespace(3, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7 var d = whitespaceComputer.insertWhitespace(2, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7 var e = whitespaceComputer.insertWhitespace(8, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8 var f = whitespaceComputer.insertWhitespace(11, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), f); // 11 var g = whitespaceComputer.insertWhitespace(10, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), g); // 10 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(6), f); // 11 var h = whitespaceComputer.insertWhitespace(0, 0, 1); assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), h); // 0 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), d); // 2 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), c); // 3 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), b); // 7 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), e); // 8 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(6), g); // 10 assert.equal(whitespaceComputer.getIdForWhitespaceIndex(7), f); // 11 }); });
the_stack
import { PuppetBridge } from "./puppetbridge"; import { RetDataFn, IRetData, IRemoteRoom, IPuppetData } from "./interfaces"; import { Provisioner } from "./provisioner"; import { PuppetType, PUPPET_TYPES } from "./db/puppetstore"; import { Log } from "./log"; import { TimedCache } from "./structures/timedcache"; import * as MarkdownIt from "markdown-it"; import { MatrixClient, MessageEvent, TextualMessageEventContent } from "@sorunome/matrix-bot-sdk"; const md = new MarkdownIt(); // tslint:disable-next-line:no-magic-numbers const MESSAGE_COLLECT_TIMEOUT = 1000 * 60; const MAX_MSG_SIZE = 4000; const log = new Log("BotProvisioner"); interface IFnCollect { fn: RetDataFn; puppetId: number; } export type SendMessageFn = (s: string) => Promise<void>; export type PidCommandFn = (pid: number, param: string, sendMessage: SendMessageFn) => Promise<void>; type FullCommandFnSingle = (sender: string, param: string, sendMessage: SendMessageFn) => Promise<void>; type FullCommandFnRoom = (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => Promise<void>; export type FullCommandFn = FullCommandFnSingle | FullCommandFnRoom; export interface ICommand { fn: PidCommandFn | FullCommandFn; help: string; withPid?: boolean; inRoom?: boolean; } export class BotProvisioner { private provisioner: Provisioner; private fnCollectListeners: TimedCache<string, IFnCollect>; private commands: {[key: string]: ICommand} = {}; constructor( private bridge: PuppetBridge, ) { this.provisioner = this.bridge.provisioner; this.fnCollectListeners = new TimedCache(MESSAGE_COLLECT_TIMEOUT); this.registerDefaultCommands(); } public async processEvent(roomId: string, event: MessageEvent<TextualMessageEventContent>) { if (event.type !== "m.room.message") { return; // not ours to handle } const msg = event.textBody; if (msg.startsWith("!")) { // check if we actually have a normal room event if (msg.startsWith(`!${this.bridge.protocol.id}`)) { await this.processRoomEvent(roomId, event); } return; } const sender = event.sender; // update the status room entry, if needed const senderInfo = await this.bridge.puppetStore.getOrCreateMxidInfo(sender); if (senderInfo.statusRoom !== roomId) { // let's verify that the new status room is emtpy const members = await this.bridge.botIntent.underlyingClient.getRoomMembers(roomId); const DM_MEMBERS_LENGTH = 2; if (members.length !== DM_MEMBERS_LENGTH) { return; // not our stuff to bother with } senderInfo.statusRoom = roomId; await this.bridge.puppetStore.setMxidInfo(senderInfo); } // parse the argument and parameters of the message const [, arg, param] = event.textBody.split(/([^ ]*)(?: (.*))?/); log.info(`Got message to process with arg=${arg}`); const fnCollect = this.fnCollectListeners.get(sender); switch (fnCollect ? "link" : arg) { case "relink": case "link": { let puppetId = -1; let parseParam = param; if (fnCollect) { puppetId = fnCollect.puppetId; parseParam = event.textBody; } else if (arg === "relink") { const [, pidStr, p] = (param || "").split(/([^ ]*)(?: (.*))?/); const pid = parseInt(pidStr, 10); // now we need to check if that pid is ours const d = await this.provisioner.get(pid); if (!d || d.puppetMxid !== sender) { await this.sendMessage(roomId, "ERROR: PuppetID not found"); break; } puppetId = pid; parseParam = p; } if (!parseParam) { parseParam = ""; } if (!this.provisioner.canCreate(sender)) { await this.sendMessage(roomId, "ERROR: You don't have permission to use this bridge"); break; } if (!this.bridge.hooks.getDataFromStr) { await this.sendMessage(roomId, "ERROR: The bridge is still starting up, please try again shortly"); break; } let retData: IRetData; if (fnCollect) { retData = await fnCollect.fn(event.textBody); this.fnCollectListeners.delete(sender); } else { retData = await this.bridge.hooks.getDataFromStr(parseParam); } if (!retData.success) { const print = retData.fn || retData.data ? retData.error : `ERROR: ${retData.error}`; await this.sendMessage(roomId, print || ""); if (retData.fn) { this.fnCollectListeners.set(sender, { fn: retData.fn, puppetId, }); } if (!retData.data) { break; } } let data: IPuppetData; try { data = (await retData.data) || {}; } catch (err) { log.warn("Failed to create/update link", err); await this.sendMessage(roomId, `ERROR: ${err}`); break; } if (puppetId === -1) { // we need to create a new link puppetId = await this.provisioner.new(sender, data, retData.userId); await this.sendMessage(roomId, `Created new link with ID ${puppetId}`); } else { // we need to update an existing link await this.provisioner.update(sender, puppetId, data, retData.userId); await this.sendMessage(roomId, `Updated link with ID ${puppetId}`); } break; } case "unlink": { if (!param || !param.trim()) { await this.sendMessage(roomId, `ERROR: You need to specify an index to unlink`); return; } const puppetId = Number(param.trim()); if (isNaN(puppetId)) { await this.sendMessage(roomId, `ERROR: The index must be a number`); return; } const data = await this.provisioner.get(puppetId); if (!data || data.puppetMxid !== sender) { await this.sendMessage(roomId, `ERROR: You must own the index`); return; } await this.provisioner.delete(sender, puppetId); await this.sendMessage(roomId, `Removed link with ID ${puppetId}`); break; } default: { let handled = false; for (const name in this.commands) { if (this.commands.hasOwnProperty(name) && name === arg) { handled = true; const sendMessage: SendMessageFn = async (s: string) => { await this.sendMessage(roomId, s); }; if (this.commands[name].withPid) { const [, pidStr, p] = (param || "").split(/([^ ]*)(?: (.*))?/); const pid = parseInt(pidStr, 10); const d = isNaN(pid) ? null : await this.provisioner.get(pid); if (!d || d.puppetMxid !== sender) { await this.sendMessage(roomId, "ERROR: PuppetID not found"); break; } await (this.commands[name].fn as PidCommandFn)(pid, p, sendMessage); } else { await (this.commands[name].fn as FullCommandFn)(sender, param || "", sendMessage); } break; } } if (!handled) { await this.sendMessage(roomId, "Command not found! Please type `help` to see a list of" + " all commands or `help <command>` to get help on a specific command."); } } } } public async processRoomEvent(roomId: string, event: MessageEvent<TextualMessageEventContent>) { if (event.type !== "m.room.message") { return; // not ours to handle } const sender = event.sender; const prefix = `!${this.bridge.protocol.id} `; if (!event.textBody.startsWith(prefix)) { return; // not ours to handle, either } const [, arg, param] = event.textBody.substr(prefix.length).split(/([^ ]*)(?: (.*))?/); let handled = false; const client = await this.bridge.roomSync.getRoomOp(roomId); for (const name in this.commands) { if (this.commands.hasOwnProperty(name) && name === arg && this.commands[name].inRoom) { handled = true; const sendMessage: SendMessageFn = async (s: string) => { await this.sendMessage(roomId, s, client); }; await (this.commands[name].fn as FullCommandFn)(sender, param || "", sendMessage, roomId); break; } } if (!handled) { await this.sendMessage(roomId, `Command not found! Please type \`${prefix}help\` to see a list of` + ` all commands or \`${prefix}help <command>\` to get help on a specific command.`, client); } } public async sendStatusMessage(room: number | IRemoteRoom, msg: string) { let puppetId = -1; if (isNaN(room as number)) { puppetId = (room as IRemoteRoom).puppetId; } else { puppetId = room as number; } log.info(`Sending status message for puppetId ${puppetId}...`); const mxid = await this.provisioner.getMxid(puppetId); let roomMxid: string = ""; let sendStr = "[Status] "; let client: MatrixClient | undefined; if (isNaN(room as number)) { const maybeRoomMxid = await this.bridge.roomSync.maybeGetMxid(room as IRemoteRoom); if (!maybeRoomMxid) { log.error("Room MXID is not found, this is very odd"); return; } roomMxid = maybeRoomMxid; const ghost = (await this.bridge.puppetStore.getGhostsInRoom(roomMxid))[0]; if (ghost) { client = this.bridge.AS.getIntentForUserId(ghost).underlyingClient; } } else { const info = await this.bridge.puppetStore.getOrCreateMxidInfo(mxid); if (!info.statusRoom) { // no status room present, nothing to do log.info("No status room found"); return; } roomMxid = info.statusRoom; const desc = await this.provisioner.getDesc(mxid, puppetId); if (!desc) { // something went wrong log.error("Description is not found, this is very odd"); return; } sendStr += `${puppetId}: ${desc.desc}: `; } sendStr += msg; await this.sendMessage(roomMxid, sendStr, client); } public registerCommand(name: string, command: ICommand) { if (command.withPid === undefined) { command.withPid = true; } if (command.withPid || command.inRoom === undefined) { command.inRoom = false; } this.commands[name] = command; } private registerDefaultCommands() { this.registerCommand("help", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { param = param.trim(); if (!param) { const commands = roomId ? [] : ["`link`", "`unlink`", "`relink`"]; for (const name in this.commands) { if (this.commands.hasOwnProperty(name) && ((roomId && this.commands[name].inRoom) || !roomId)) { commands.push(`\`${name}\``); } } const helpCmd = roomId ? `!${this.bridge.protocol.id} help <command>` : "help <command>"; const msg = `Available commands: ${commands.join(", ")}\n\nType \`${helpCmd}\` to get more help on them.`; await sendMessage(msg); return; } // alright, let's display some help! if (!this.commands[param]) { await sendMessage(`Command \`${param}\` not found!`); return; } await sendMessage(this.commands[param].help); }, help: `List all commands and optionally get help on specific ones. Usage: \`help\`, \`help <command>\``, withPid: false, inRoom: true, }); this.registerCommand("list", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { const descs = await this.provisioner.getDescMxid(sender); if (descs.length === 0) { await sendMessage("Nothing linked yet!"); return; } let sendStr = "Links:\n"; for (const d of descs) { let sendStrPart = ` - ${d.puppetId}: ${d.desc}`; if (d.type !== "puppet") { sendStrPart += ` (type: ${d.type})`; } if (d.isPublic) { sendStrPart += " **public!**"; } sendStrPart += "\n"; if (sendStr.length + sendStrPart.length > MAX_MSG_SIZE) { await sendMessage(sendStr); sendStr = ""; } sendStr += sendStrPart; } await sendMessage(sendStr); }, help: `List all set links along with their information. Usage: \`list\``, withPid: false, }); this.registerCommand("setmatrixtoken", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { if (!param || !param.trim()) { await this.provisioner.setToken(sender, null); await sendMessage(`Removed matrix token!`); return; } const token = param.trim(); const hsUrl = await this.provisioner.getHsUrl(sender); const client = await this.bridge.userSync.getClientFromTokenCallback({ token, hsUrl, mxid: sender, }); if (!client) { await sendMessage("ERROR: Invalid matrix token"); return; } await this.provisioner.setToken(sender, token); await sendMessage(`Set matrix token`); }, help: `Sets a matrix token to enable double-puppeting. Usage: \`setmatrixtoken <token>\``, withPid: false, }); this.registerCommand("adminme", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { // Set the user to admin try { await this.provisioner.setAdmin(sender, param || roomId); await sendMessage("Admin level set."); } catch (err) { await sendMessage(err.message); } }, help: `Sets you as admin for a certain room. Usage: \`adminme <room resolvable>\``, withPid: false, inRoom: true, }); this.registerCommand("listusers", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { if (!this.bridge.hooks.listUsers) { await sendMessage("Feature not implemented!"); return; } const descs = await this.provisioner.getDescMxid(sender); if (descs.length === 0) { await sendMessage("Nothing linked yet!"); return; } let reply = ""; for (const d of descs) { const users = await this.bridge.hooks.listUsers(d.puppetId); reply += `## ${d.puppetId}: ${d.desc}:\n\n`; for (const u of users) { let replyPart = ""; if (u.category) { replyPart = `\n### ${u.name}:\n\n`; } else { const mxid = await this.bridge.getMxidForUser({ puppetId: d.puppetId, userId: u.id!, }, false); replyPart = ` - ${u.name}: [${u.name}](https://matrix.to/#/${mxid})\n`; } if (reply.length + replyPart.length > MAX_MSG_SIZE) { await sendMessage(reply); reply = ""; } reply += replyPart; } } await sendMessage(reply); }, help: `Lists all users that are linked currently, from all links. Usage: \`listusers\``, withPid: false, }); this.registerCommand("listrooms", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { if (!this.bridge.hooks.listRooms) { await sendMessage("Feature not implemented!"); return; } const descs = await this.provisioner.getDescMxid(sender); if (descs.length === 0) { await sendMessage("Nothing linked yet!"); return; } let reply = ""; for (const d of descs) { const rooms = await this.bridge.hooks.listRooms(d.puppetId); reply += `## ${d.puppetId}: ${d.desc}:\n\n`; for (const r of rooms) { let replyPart = ""; if (r.category) { replyPart = `\n### ${r.name}:\n\n`; } else { const mxid = await this.bridge.getMxidForRoom({ puppetId: d.puppetId, roomId: r.id!, }); replyPart = ` - ${r.name}: [${r.name}](https://matrix.to/#/${mxid})\n`; } if (reply.length + replyPart.length > MAX_MSG_SIZE) { await sendMessage(reply); reply = ""; } reply += replyPart; } } await sendMessage(reply); }, help: `List all rooms that are linked currently, from all links. Usage: \`listrooms\``, withPid: false, }); this.registerCommand("listgroups", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { if (!this.bridge.hooks.listGroups) { await sendMessage("Feature not implemented!"); return; } else if (!this.bridge.groupSyncEnabled) { await sendMessage("Group sync is not enabled!"); return; } const descs = await this.provisioner.getDescMxid(sender); if (descs.length === 0) { await sendMessage("Nothing linked yet!"); return; } let reply = ""; for (const d of descs) { const groups = await this.bridge.hooks.listGroups(d.puppetId); reply += `### ${d.puppetId}: ${d.desc}:\n\n`; for (const g of groups) { const mxid = await this.bridge.groupSync.getMxid({ puppetId: d.puppetId, groupId: g.id!, }); const replyPart = ` - ${g.name}: [${g.name}](https://matrix.to/#/${mxid})\n`; if (reply.length + replyPart.length > MAX_MSG_SIZE) { await sendMessage(reply); reply = ""; } reply += replyPart; } } await sendMessage(reply); }, help: `Synchronize and list all groups that are linked currently, from all links. Usage: \`listgroups\``, withPid: false, }); this.registerCommand("settype", { fn: async (puppetId: number, param: string, sendMessage: SendMessageFn) => { if (!PUPPET_TYPES.includes(param as PuppetType)) { await sendMessage("ERROR: Invalid type. Valid types are: " + PUPPET_TYPES.map((s) => `\`${s}\``).join(", ")); return; } await this.provisioner.setType(puppetId, param as PuppetType); await sendMessage(`Set puppet type to ${param}`); }, help: `Sets the type of a given puppet. Valid types are "puppet" and "relay". Usage: \`settype <puppetId> <type>\``, }); this.registerCommand("setispublic", { fn: async (puppetId: number, param: string, sendMessage: SendMessageFn) => { const isPublic = param === "1" || param === "true"; await this.provisioner.setIsPublic(puppetId, isPublic); await sendMessage(`Set puppet to ${isPublic ? "public" : "private"}`); }, help: `Sets if the given puppet creates rooms as public or invite-only. Usage: \`setispublic <puppetId> <1/0>`, }); if (this.bridge.protocol.features.globalNamespace) { this.registerCommand("setisglobalnamespace", { fn: async (puppetId: number, param: string, sendMessage: SendMessageFn) => { const isGlobal = param === "1" || param === "true"; await this.provisioner.setIsGlobalNamespace(puppetId, isGlobal); await sendMessage(`Set puppet to ${isGlobal ? "global" : "private"} namespace`); }, help: `Sets if the given puppet creates shared or separate rooms for multiple users accessing the same bridged room. Usage: \`setisglobalnamespace <puppetId> <1/0>\``, }); } this.registerCommand("setautoinvite", { fn: async (puppetId: number, param: string, sendMessage: SendMessageFn) => { const autoinvite = param === "1" || param === "true"; await this.provisioner.setAutoinvite(puppetId, autoinvite); await sendMessage(`Set puppet to ${autoinvite ? "autoinvite" : "ignore"}`); }, help: `Sets if the given puppet should autoinvite you to newly bridged rooms. Usage: \`setautoinvite <puppetId> <1/0>`, }); this.registerCommand("invite", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { const success = await this.provisioner.invite(sender, param); if (success) { await sendMessage("Sent invite to the room!"); } else { await sendMessage("Couldn't send invite to the room. Perhaps you don't have permission to see it?"); } }, help: `Receive an invite to a room. The room resolvable can be a matrix.to link, a room ID, an alias or a user ID. Usage: \`invite <room resolvable>\``, withPid: false, inRoom: true, }); this.registerCommand("groupinvite", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { const success = await this.provisioner.groupInvite(sender, param || roomId); if (success) { await sendMessage("Sent invite to the group!"); } else { await sendMessage("Couldn't send invite to the group. Perhaps you don't have permission to see it?"); } }, help: `Receive an invite to a group. The group resolvable can be a matrix.to link, a room ID or alias. Usage: \`groupinvite <group resolvable>\``, withPid: false, inRoom: true, }); if (this.bridge.protocol.features.globalNamespace) { this.registerCommand("bridge", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { if (!roomId) { await sendMessage("Must send this command in a room!"); return; } try { await this.provisioner.bridgeRoom(sender, roomId, param); await sendMessage("Bridged the room!"); } catch (err) { await sendMessage(err.message); } }, help: `Bridge a room. Usage: \`!${this.bridge.protocol.id} bridge <remote room ID>\``, withPid: false, inRoom: true, }); } this.registerCommand("unbridge", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { const success = await this.provisioner.unbridgeRoom(sender, param || roomId); if (success) { await sendMessage("Unbridged the room!"); } else { await sendMessage("Couldn't unbridge the room. Perhaps it doesn't exist or you aren't the owner of it?"); } }, help: `Unbridge a room. The room resolvable can be a matrix.to link, a room ID, an alias or a user ID. Usage: \`unbridge <room resolvable>\``, withPid: false, inRoom: true, }); this.registerCommand("fixghosts", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { const roomParts = await this.bridge.roomSync.resolve(roomId || param); if (!roomParts) { await sendMessage("Room not resolvable"); return; } const room = await this.bridge.roomSync.maybeGet(roomParts); if (!room) { await sendMessage("Room not found"); return; } if (!(await this.bridge.namespaceHandler.isAdmin(room, sender))) { await sendMessage("Not an admin"); return; } await sendMessage("Fixing the ghosts..."); // tslint:disable-next-line no-floating-promises this.bridge.roomSync.addGhosts(room); }, help: `Fix the ghosts in a room. Usage: \`fixghosts <room resolvable>\``, withPid: false, inRoom: true, }); this.registerCommand("fixmute", { fn: async (sender: string, param: string, sendMessage: SendMessageFn, roomId?: string) => { const roomParts = await this.bridge.roomSync.resolve(roomId || param); if (!roomParts) { await sendMessage("Room not resolvable"); return; } const room = await this.bridge.roomSync.maybeGet(roomParts); if (!room) { await sendMessage("Room not found"); return; } await sendMessage("Fixing muted user..."); await this.provisioner.adjustMuteIfInRoom(sender, room.mxid); }, help: `Fix the power levels according to puppet & relay availability in the bridged room. Usage: \`fixmute <room resolvable>\``, withPid: false, inRoom: true, }); this.registerCommand("resendbridgeinfo", { fn: async (sender: string, param: string, sendMessage: SendMessageFn) => { await sendMessage("Re-sending bridge information state events..."); const puppets = await this.provisioner.getForMxid(sender); const puppetIds = await Promise.all(puppets.map((puppet) => this.bridge.namespaceHandler.getDbPuppetId(puppet.puppetId) .catch((err) => log.warning(`Failed to get DB puppet ID for ${puppet.puppetId}:`, err)))); const uniquePuppetIds = [...new Set(puppetIds)]; const roomLists = await Promise.all(uniquePuppetIds.map((puppetId) => puppetId ? this.bridge.roomStore.getByPuppetId(puppetId) .catch((err) => log.warning(`Failed to find puppet by ID ${puppetId}:`, err)) : Promise.resolve(null))); const rooms = await Promise.all(roomLists.flatMap((roomList) => roomList ? roomList.map((room) => this.bridge.namespaceHandler.getRemoteRoom(room, sender) .catch((err) => log.warning(`Failed to get remote room ${room.puppetId}/${room.roomId}:`, err))) : Promise.resolve(null))); await Promise.all(rooms.map((room) => room && this.bridge.roomSync.updateBridgeInformation(room) .catch((err) => log.warning(`Failed to update bridge info in ${room.roomId}:`, err)))); await sendMessage("Bridge information state event re-sent to all your rooms"); }, help: `Re-send bridge info state events to all rooms.`, withPid: false, inRoom: false, }); } private async sendMessage(roomId: string, message: string, client?: MatrixClient | null) { const html = md.render(message); if (!client) { client = this.bridge.botIntent.underlyingClient; } await client.sendMessage(roomId, { msgtype: "m.notice", body: message, formatted_body: html, format: "org.matrix.custom.html", }); } }
the_stack
import { promises as dns } from 'dns'; import * as path from 'path'; import { parse as urlParse, URL } from 'url'; import Cdp from '../cdp/api'; import { AnyChromiumConfiguration } from '../configuration'; import { BrowserTargetType } from '../targets/browser/browserTargets'; import { MapUsingProjection } from './datastructure/mapUsingProjection'; import { IFsUtils } from './fsUtils'; import { memoize } from './objUtils'; import { fixDriveLetterAndSlashes, forceForwardSlashes } from './pathUtils'; import { escapeRegexSpecialChars, isRegexSpecialChar } from './stringUtils'; let isCaseSensitive = process.platform !== 'win32'; export function resetCaseSensitivePaths() { isCaseSensitive = process.platform !== 'win32'; } export function setCaseSensitivePaths(sensitive: boolean) { isCaseSensitive = sensitive; } export function getCaseSensitivePaths() { return isCaseSensitive; } /** * Lowercases the path if the filesystem is case-insensitive. Warning: this * should only be done for the purposes of comparing paths. Paths returned * through DAP and other protocols should be correctly-cased to avoid incorrect * disambiguation. */ export function lowerCaseInsensitivePath(path: string) { return isCaseSensitive ? path : path.toLowerCase(); } /** * Compares the paths, case-insensitively based on the platform. */ export function comparePathsWithoutCasing(a: string, b: string) { return isCaseSensitive ? a === b : a.toLowerCase() === b.toLowerCase(); } /** * Compares the paths, case-insensitively based on the platform, and * normalizing back- and forward-slashes. */ export function comparePathsWithoutCasingOrSlashes(a: string, b: string) { return comparePathsWithoutCasing(forceForwardSlashes(a), forceForwardSlashes(b)); } export function caseNormalizedMap<V>(): Map<string, V> { return getCaseSensitivePaths() ? new Map() : new MapUsingProjection(lowerCaseInsensitivePath); } /** * Returns the closest parent directory where the predicate returns true. */ export const nearestDirectoryWhere = async ( rootDir: string, predicate: (dir: string) => Promise<boolean>, ): Promise<string | undefined> => { while (true) { if (await predicate(rootDir)) { return rootDir; } const parent = path.dirname(rootDir); if (parent === rootDir) { return undefined; } rootDir = parent; } }; /** * Returns the closest parent directory that contains a file with the given name. */ export const nearestDirectoryContaining = (fsUtils: IFsUtils, rootDir: string, file: string) => nearestDirectoryWhere(rootDir, p => fsUtils.exists(path.join(p, file))); // todo: not super correct, and most node libraries don't handle this accurately const knownLoopbacks = new Set<string>(['localhost', '127.0.0.1', '::1']); const knownMetaAddresses = new Set<string>([ '0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0000:0000', ]); /** * Checks if the given address, well-formed loopback IPs. We don't need exotic * variations like `127.1` because `dns.lookup()` will resolve the proper * version for us. The "right" way would be to parse the IP to an integer * like Go does (https://golang.org/pkg/net/#IP.IsLoopback). */ export const isLoopbackIp = (ipOrLocalhost: string) => knownLoopbacks.has(ipOrLocalhost.toLowerCase()); /** * If given a URL, returns its hostname. */ const getHostnameFromMaybeUrl = (maybeUrl: string) => { try { const url = new URL(maybeUrl); // replace brackets in ipv6 addresses: return url.hostname.replace(/^\[|\]$/g, ''); } catch { return maybeUrl; } }; /** * Gets whether the IP address is a meta-address like 0.0.0.0. */ export const isMetaAddress = (address: string) => knownMetaAddresses.has(getHostnameFromMaybeUrl(address)); /** * Gets whether the IP is a loopback address. */ export const isLoopback = memoize(async (address: string) => { const ipOrHostname = getHostnameFromMaybeUrl(address); if (isLoopbackIp(ipOrHostname)) { return true; } try { const resolved = await dns.lookup(ipOrHostname); return isLoopbackIp(resolved.address); } catch { return false; } }); export function completeUrl(base: string | undefined, relative: string): string | undefined { try { return new URL(relative, base).href; } catch (e) {} } export function removeQueryString(url: string) { try { const parsed = new URL(url); parsed.search = ''; return parsed.toString(); } catch { return url; } } // This function allows relative path to escape the root: // "http://example.com/foo/bar.js" + "../../baz/qux.js" => "http://example.com/../baz/qux.js" // This allows relative source map sources to reference outside of webRoot. export function completeUrlEscapingRoot(base: string | undefined, relative: string): string { try { new URL(relative); return relative; } catch (e) {} let url: URL; try { url = new URL(base || ''); } catch (e) { return relative; } let s = url.protocol + '//'; if (url.username) s += url.username + ':' + url.password + '@'; s += url.host; s += path.dirname(url.pathname); if (s[s.length - 1] !== '/') s += '/'; s += relative; return s; } export function isValidUrl(url: string): boolean { try { new URL(url); return true; } catch (e) { return false; } } export function escapeForRegExp(s: string): string { const chars = '^[]{}()\\.^$*+?|-,'; let foundChar = false; for (let i = 0; i < chars.length; ++i) { if (s.indexOf(chars.charAt(i)) !== -1) { foundChar = true; break; } } if (!foundChar) return s; let result = ''; for (let i = 0; i < s.length; ++i) { if (chars.indexOf(s.charAt(i)) !== -1) result += '\\'; result += s.charAt(i); } return result; } /** * Remove a slash of any flavor from the end of the path */ export function stripTrailingSlash(aPath: string): string { return aPath.replace(/\/$/, '').replace(/\\$/, ''); } const vscodeWebviewResourceSchemeRe = /^https:\/\/([a-z0-9\-]+)\+\.vscode-resource\.vscode-webview\.net\/(.+)/i; /** * If urlOrPath is a file URL, removes the 'file:///', adjusting for platform differences */ export function fileUrlToAbsolutePath(urlOrPath: FileUrl): string; export function fileUrlToAbsolutePath(urlOrPath: string): string | undefined; export function fileUrlToAbsolutePath(urlOrPath: string): string | undefined { const webviewResource = vscodeWebviewResourceSchemeRe.exec(urlOrPath); if (webviewResource) { urlOrPath = `${webviewResource[1]}:///${webviewResource[2]}`; } else if (urlOrPath.startsWith('vscode-webview-resource://')) { // todo@connor4312: is this still in use? const url = new URL(urlOrPath); // Strip off vscode webview url part: vscode-webview-resource://<36-char-guid>/file... urlOrPath = url.pathname .replace(/%2F/gi, '/') .replace(/^\/([a-z0-9\-]+)(\/{1,2})/i, (_: string, scheme: string, sep: string) => { if (sep.length === 1) { return `${scheme}:///`; // Add empty authority. } else { return `${scheme}://`; // Url has own authority. } }); } else if (!isFileUrl(urlOrPath)) { return undefined; } urlOrPath = urlOrPath.replace('file:///', ''); urlOrPath = decodeURIComponent(urlOrPath); if (urlOrPath[0] !== '/' && !urlOrPath.match(/^[A-Za-z]:/)) { // If it has a : before the first /, assume it's a windows path or url. // Ensure unix-style path starts with /, it can be removed when file:/// was stripped. // Don't add if the url still has a protocol urlOrPath = '/' + urlOrPath; } return fixDriveLetterAndSlashes(urlOrPath); } /** * Converts a file URL to a windows network path, if possible. */ export function fileUrlToNetworkPath(urlOrPath: string): string { if (isFileUrl(urlOrPath)) { urlOrPath = urlOrPath.replace('file:///', '\\\\'); urlOrPath = urlOrPath.replace(/\//g, '\\'); urlOrPath = decodeURIComponent(urlOrPath); } return urlOrPath; } // TODO: this does not escape/unescape special characters, but it should. export function absolutePathToFileUrl(absolutePath: string): string { if (process.platform === 'win32') { return 'file:///' + platformPathToUrlPath(absolutePath); } return 'file://' + platformPathToUrlPath(absolutePath); } /** * Returns whether the path is a Windows or posix path. */ export function isAbsolute(_path: string): boolean { return path.posix.isAbsolute(_path) || path.win32.isAbsolute(_path); } /** * Returns whether the uri looks like a data URI. */ export function isDataUri(uri: string): boolean { return /^data:[a-z]+\/[a-z]/.test(uri); } const urlToRegexChar = (char: string, arr: Set<string>, escapeRegex: boolean) => { if (!escapeRegex) { arr.add(char); return; } if (isRegexSpecialChar(char)) { arr.add(`\\${char}`); } else { arr.add(char); } const encoded = encodeURI(char); if (char !== '\\' && encoded !== char) { arr.add(encoded); // will never have any regex special chars } }; const createReGroup = (patterns: ReadonlySet<string>): string => { switch (patterns.size) { case 0: return ''; case 1: return patterns.values().next().value; default: // Prefer the more compacy [aA] form if we're only matching single // characters, produce a non-capturing group otherwise. const arr = [...patterns]; return arr.some(p => p.length > 1) ? `(?:${arr.join('|')})` : `[${arr.join('')}]`; } }; const charToUrlReGroupSet = new Set<string>(); const charRangeToUrlReGroup = (str: string, start: number, end: number, escapeRegex: boolean) => { let re = ''; // Loop through each character of the string. Convert the char to a regex, // creating a group, and then append that to the match. for (let i = start; i < end; i++) { const char = str[i]; if (isCaseSensitive) { urlToRegexChar(char, charToUrlReGroupSet, escapeRegex); } else { urlToRegexChar(char.toLowerCase(), charToUrlReGroupSet, escapeRegex); urlToRegexChar(char.toUpperCase(), charToUrlReGroupSet, escapeRegex); } re += createReGroup(charToUrlReGroupSet); charToUrlReGroupSet.clear(); } return re; }; /** * Converts and escape the file URL to a regular expression. */ export function urlToRegex( aPath: string, [escapeReStart, escapeReEnd]: [number, number] = [0, aPath.length], ) { if (escapeReEnd <= escapeReStart) { return aPath; } const patterns: string[] = []; // Split out the portion of the path that has already been converted to a regex pattern const rePrefix = charRangeToUrlReGroup(aPath, 0, escapeReStart, false); const reSuffix = charRangeToUrlReGroup(aPath, escapeReEnd, aPath.length, false); const unescapedPath = aPath.slice(escapeReStart, escapeReEnd); // aPath will often (always?) be provided as a file URI, or URL. Decode it // --we'll reencode it as we go--and also create a match for its absolute // path. // // This de- and re-encoding is important for special characters, since: // - It comes in like "file:///c:/foo/%F0%9F%92%A9.js" // - We decode it to file:///c:/foo/๐Ÿ’ฉ.js // - For case insensitive systems, we generate a regex like [fF][oO][oO]/(?:๐Ÿ’ฉ|%F0%9F%92%A9).[jJ][sS] // - If we didn't de-encode it, the percent would be case-insensitized as // well and we would not include the original character in the regex for (const str of [decodeURI(unescapedPath), fileUrlToAbsolutePath(unescapedPath)]) { if (!str) { continue; } const re = charRangeToUrlReGroup(str, 0, str.length, true); // If we're on windows but not case sensitive (i.e. we didn't expand a // fancy regex above), replace `file:///c:/` or simple `c:/` patterns with // an insensitive drive letter. patterns.push( `${rePrefix}${re}${reSuffix}`.replace( /^(file:\\\/\\\/\\\/)?([a-z]):/i, (_, file = '', letter) => `${file}[${letter.toUpperCase()}${letter.toLowerCase()}]:`, ), ); } return patterns.join('|'); } /** * Opaque typed used to indicate strings that are file URLs. */ export type FileUrl = string & { __opaque_file_url: true }; /** * Returns whether the string is a file URL */ export function isFileUrl(candidate: string): candidate is FileUrl { return candidate.startsWith('file:///'); } export function maybeAbsolutePathToFileUrl( rootPath: string | undefined, sourceUrl: string, ): string { if ( rootPath && platformPathToPreferredCase(sourceUrl).startsWith(rootPath) && !isValidUrl(sourceUrl) ) return absolutePathToFileUrl(sourceUrl); return sourceUrl; } export function urlPathToPlatformPath(p: string): string { if (process.platform === 'win32') { p = p.replace(/\//g, '\\'); } return decodeURI(p); } export function platformPathToUrlPath(p: string): string { p = platformPathToPreferredCase(p); if (process.platform === 'win32') { p = p.replace(/\\/g, '/'); } return encodeURI(p); } export function platformPathToPreferredCase(p: string): string; export function platformPathToPreferredCase(p: string | undefined): string | undefined; export function platformPathToPreferredCase(p: string | undefined): string | undefined { if (p && process.platform === 'win32' && p[1] === ':') return p[0].toUpperCase() + p.substring(1); return p; } export type TargetFilter = (info: Cdp.Target.TargetInfo) => boolean; /** * Creates a target filter function for the given Chrome configuration. */ export const createTargetFilterForConfig = ( config: AnyChromiumConfiguration, additonalMatches: ReadonlyArray<string> = [], ): ((t: { url: string }) => boolean) => { const filter = config.urlFilter || config.url || ('file' in config && config.file); if (!filter) { return () => true; } const tester = createTargetFilter(filter, ...additonalMatches); return t => tester(t.url); }; /** * Requires that the target is also a 'page'. */ export const requirePageTarget = <T>(filter: (t: T) => boolean): ((t: T & { type: string }) => boolean) => t => t.type === BrowserTargetType.Page && filter(t); /** * The "isURL" from chrome-debug-core. In js-debug we use `new URL()` to see * if a string is a URL, but this is slightly different from url.parse. * @see https://github.com/microsoft/vscode-chrome-debug-core/blob/456318b2a4b2d3394ce8daae1e70d898f55393ea/src/utils.ts#L310 */ function isURLCompat(urlOrPath: string): boolean { return !!urlOrPath && !path.isAbsolute(urlOrPath) && !!urlParse(urlOrPath).protocol; } /** * Creates a function to filter a target URL. */ export const createTargetFilter = ( ...targetUrls: ReadonlyArray<string> ): ((testUrl: string) => boolean) => { const standardizeMatch = (aUrl: string) => { aUrl = aUrl.toLowerCase(); const fileUrl = fileUrlToAbsolutePath(aUrl); if (fileUrl) { // Strip file:///, if present aUrl = fileUrl; } else if (isURLCompat(aUrl) && aUrl.includes('://')) { // Strip the protocol, if present aUrl = aUrl.substr(aUrl.indexOf('://') + 3); } // Remove optional trailing / if (aUrl.endsWith('/')) { aUrl = aUrl.substr(0, aUrl.length - 1); } const hashIndex = aUrl.indexOf('#'); if (hashIndex !== -1) { aUrl = aUrl.slice(0, aUrl[hashIndex - 1] === '/' ? hashIndex - 1 : hashIndex); } return aUrl; }; const escaped = targetUrls.map(url => escapeRegexSpecialChars(standardizeMatch(url), '/*').replace(/(\/\*$)|\*/g, '.*'), ); const targetUrlRegex = new RegExp('^(' + escaped.join('|') + ')$', 'g'); return testUrl => { targetUrlRegex.lastIndex = 0; return targetUrlRegex.test(standardizeMatch(testUrl)); }; };
the_stack
import * as Q from 'q'; import { Timezone, day } from 'chronoshift'; import { $, Executor, basicExecutorFactory, find, Attributes, Dataset, TimeRange } from 'plywood'; import { Logger } from 'logger-tracker'; import { TimeMonitor } from "../../../common/utils/time-monitor/time-monitor"; import { AppSettings, Timekeeper, Cluster, DataCube } from '../../../common/models/index'; import { SettingsStore } from '../settings-store/settings-store'; import { FileManager } from '../file-manager/file-manager'; import { ClusterManager } from '../cluster-manager/cluster-manager'; import { updater } from '../updater/updater'; const PREVIEW_LIMIT = 20; const LOTS_OF_TIME = TimeRange.fromJS({ start: new Date('1000-01-01Z'), end: new Date('4000-01-01Z') }); export interface SettingsManagerOptions { logger: Logger; verbose?: boolean; initialLoadTimeout?: number; anchorPath: string; } export interface GetSettingsOptions { dataCubeOfInterest?: string; timeout?: number; } export interface FullSettings { appSettings: AppSettings; timekeeper: Timekeeper; executors: Lookup<Executor>; } export interface ClusterAndSources { cluster: Cluster; sources: string[]; } export interface ClusterNameAndSource { clusterName: string; source: string; } function flatten<T>(as: T[][]): T[] { return Array.prototype.concat.apply([], as); } export class SettingsManager { public logger: Logger; public verbose: boolean; public anchorPath: string; public settingsStore: SettingsStore; public appSettings: AppSettings; public timeMonitor: TimeMonitor; public executors: Lookup<Executor>; public fileManagers: FileManager[]; public clusterManagers: ClusterManager[]; public currentWork: Q.Promise<any>; public initialLoadTimeout: number; constructor(settingsStore: SettingsStore, options: SettingsManagerOptions) { var logger = options.logger; this.logger = logger; this.verbose = Boolean(options.verbose); this.anchorPath = options.anchorPath; this.timeMonitor = new TimeMonitor(logger); this.executors = {}; this.settingsStore = settingsStore; this.fileManagers = []; this.clusterManagers = []; this.initialLoadTimeout = options.initialLoadTimeout || 30000; this.appSettings = AppSettings.BLANK; // do initial load of initial settings this.currentWork = settingsStore.readSettings() .then((appSettings) => { return this.synchronizeSettings(appSettings); }); // add the auto loader if need after completing initial read if (this.settingsStore.needsAutoLoader) { this.settingsStore.autoLoader = this.autoLoadDataCubes.bind(this); // Reread the settings this.currentWork = this.currentWork .then(() => settingsStore.readSettings()) .then((appSettings) => { return this.synchronizeSettings(appSettings); }); } // log error if something goes wrong this.currentWork = this.currentWork .catch(e => { logger.error(`Fatal settings load error: ${e.message}`); logger.error(e.stack); throw e; }); } public isStateful(): boolean { return Boolean(this.settingsStore.writeSettings); } private getClusterManagerFor(clusterName: string): ClusterManager { return find(this.clusterManagers, (clusterManager) => clusterManager.cluster.name === clusterName); } private getFileManagerFor(uri: string): FileManager { return find(this.fileManagers, (fileManager) => fileManager.uri === uri); } getFullSettings(opts: GetSettingsOptions = {}): Q.Promise<FullSettings> { const { settingsStore } = this; var currentWork = this.currentWork; if (settingsStore.hasUpdateOnLoad) { currentWork = currentWork .then(() => { return settingsStore.hasUpdateOnLoad().then(hasUpdate => { if (!hasUpdate) return null; // There is an update so re-read and sync teh settings return settingsStore.readSettings() .then((appSettings) => { return this.synchronizeSettings(appSettings); }); }); }); } var timeout = opts.timeout || this.initialLoadTimeout; if (timeout !== 0) { currentWork = currentWork.timeout(timeout) .catch(e => { this.logger.error(`Settings load timeout hit, continuing`); }); } return currentWork.then(() => { return { appSettings: this.appSettings, timekeeper: this.timeMonitor.timekeeper, executors: this.executors }; }); } synchronizeSettings(newSettings: AppSettings): Q.Promise<any> { var tasks = [ this.synchronizeClusters(newSettings), this.synchronizeDataCubes(newSettings) ]; this.appSettings = newSettings; return Q.all(tasks); } // === Clusters ============================== private addClusterManager(cluster: Cluster): Q.Promise<any> { const { verbose, logger, anchorPath } = this; var clusterManager = new ClusterManager(cluster, { logger, verbose, anchorPath }); this.clusterManagers.push(clusterManager); return clusterManager.establishInitialConnection(); } private removeClusterManager(cluster: Cluster): void { this.clusterManagers = this.clusterManagers.filter((clusterManager) => { if (clusterManager.cluster.name !== cluster.name) return true; clusterManager.destroy(); return false; }); } synchronizeClusters(newSettings: AppSettings): Q.Promise<any> { const { verbose, logger } = this; var oldSettings = this.appSettings; var tasks: Q.Promise<any>[] = []; updater(oldSettings.clusters, newSettings.clusters, { onExit: (oldCluster) => { logger.log(`Removing cluster manager for '${oldCluster.name}'`); this.removeClusterManager(oldCluster); }, onUpdate: (newCluster, oldCluster) => { logger.log(`Updating cluster manager for '${newCluster.name}'`); this.removeClusterManager(oldCluster); tasks.push(this.addClusterManager(newCluster)); }, onEnter: (newCluster) => { logger.log(`Adding cluster manager for '${newCluster.name}'`); tasks.push(this.addClusterManager(newCluster)); } }); return Q.all(tasks); } // === Cubes ============================== private addExecutor(dataCube: DataCube, executor: Executor): void { this.executors[dataCube.name] = executor; } private removeExecutor(dataCube: DataCube): void { delete this.executors[dataCube.name]; } private addTimeCheckIfNeeded(dataCube: DataCube, executor: Executor): void { if (!dataCube.refreshRule.isQuery()) return; var maxTimeQuery = dataCube.getMaxTimeQuery(); if (!maxTimeQuery) return; this.timeMonitor.addCheck(dataCube.name, () => { return executor(maxTimeQuery).then(DataCube.processMaxTimeQuery); }); } private removeTimeCheck(dataCube: DataCube): void { this.timeMonitor.removeCheck(dataCube.name); } private addNativeCube(dataCube: DataCube): Q.Promise<any> { if (dataCube.clusterName !== 'native') throw new Error(`data cube '${dataCube.name}' must be native to have a file manager`); const { verbose, logger, anchorPath } = this; var fileManager = new FileManager({ logger, verbose, anchorPath, uri: dataCube.source, subsetExpression: dataCube.subsetExpression }); this.fileManagers.push(fileManager); return fileManager.loadDataset().then((dataset) => { var newExecutor = basicExecutorFactory({ datasets: { main: dataset } }); this.addExecutor(dataCube, newExecutor); this.addTimeCheckIfNeeded(dataCube, newExecutor); }); } private removeNativeCube(dataCube: DataCube): void { if (dataCube.clusterName !== 'native') throw new Error(`data cube '${dataCube.name}' must be native to have a file manager`); this.fileManagers = this.fileManagers.filter((fileManager) => { if (fileManager.uri !== dataCube.source) return true; fileManager.destroy(); return false; }); this.removeExecutor(dataCube); this.removeTimeCheck(dataCube); } private addClusterCube(dataCube: DataCube): void { var clusterManager = this.getClusterManagerFor(dataCube.clusterName); if (clusterManager) { var newExecutor = basicExecutorFactory({ datasets: { main: dataCube.toExternal(clusterManager.cluster, clusterManager.requester) } }); this.addExecutor(dataCube, newExecutor); this.addTimeCheckIfNeeded(dataCube, newExecutor); } } private removeClusterCube(dataCube: DataCube): void { this.removeExecutor(dataCube); this.removeTimeCheck(dataCube); } synchronizeDataCubes(newSettings: AppSettings): Q.Promise<any> { const { verbose, logger } = this; var oldSettings = this.appSettings; var tasks: Q.Promise<any>[] = []; updater(oldSettings.dataCubes, newSettings.dataCubes, { onExit: (oldDataCube) => { logger.log(`Removing data cube manager for '${oldDataCube.name}'`); if (oldDataCube.clusterName === 'native') { this.removeNativeCube(oldDataCube); } else { this.removeClusterCube(oldDataCube); } }, onUpdate: (newDataCube, oldDataCube) => { // If native sources are the same, nothing to do. if (newDataCube.clusterName === 'native' && oldDataCube.clusterName === 'native' && newDataCube.source === oldDataCube.source) return; logger.log(`Updating data cube manager for '${newDataCube.name}'`); if (oldDataCube.clusterName === 'native') { this.removeNativeCube(oldDataCube); tasks.push(this.addNativeCube(newDataCube)); } else { this.removeClusterCube(oldDataCube); this.addClusterCube(newDataCube); } }, onEnter: (newDataCube) => { logger.log(`Adding data cube manager for '${newDataCube.name}'`); if (newDataCube.clusterName === 'native') { tasks.push(this.addNativeCube(newDataCube)); } else { this.addClusterCube(newDataCube); } } }); return Q.all(tasks); } updateSettings(newSettings: AppSettings): Q.Promise<any> { if (!this.settingsStore.writeSettings) return Q.reject(new Error('must be writable')); return this.settingsStore.writeSettings(newSettings) .then(() => { this.synchronizeSettings(newSettings); }); } checkClusterConnectionInfo(cluster: Cluster): Q.Promise<ClusterAndSources> { const { verbose, logger, anchorPath } = this; var clusterManager = new ClusterManager(cluster, { logger, verbose, anchorPath }); return clusterManager.establishInitialConnection(0) .then( () => clusterManager.getSources(), (e) => { throw new Error('Unable to connect tp cluster'); } ) .then((sources) => { return { cluster: clusterManager.cluster, sources }; }); } getAllClusterSources(): Q.Promise<ClusterNameAndSource[]> { var clusterSources = this.clusterManagers.map((clusterManager) => { var clusterName = clusterManager.cluster.name; return clusterManager.getSources().then((sources) => { return sources.map((source): ClusterNameAndSource => { return { clusterName, source }; }); }); }); return Q.all(clusterSources).then((things: ClusterNameAndSource[][]) => flatten(things)); } getAllAttributes(source: string, cluster: string | Cluster, templateDataCube: DataCube = null): Q.Promise<Attributes> { const { verbose, logger, anchorPath } = this; var clusterName: string = typeof cluster === 'string' ? cluster : cluster.name; logger.log(`Getting attributes for source '${source}' in cluster '${clusterName}'`); if (cluster === 'native') { return Q.fcall(() => { var fileManager = this.getFileManagerFor(source); if (!fileManager) throw new Error(`no file manager for ${source}`); return fileManager.dataset.attributes; }); } else { return Q.fcall(() => { if (typeof cluster === 'string') { var clusterManager = this.getClusterManagerFor(cluster); if (!clusterManager) throw new Error(`no cluster manager for ${cluster}`); return clusterManager; } else { var clusterManager = new ClusterManager(cluster, { logger, verbose, anchorPath }); return clusterManager.establishInitialConnection().then(() => clusterManager); } }) .then((clusterManager: ClusterManager) => { return (templateDataCube || DataCube.fromClusterAndSource('test_cube', clusterManager.cluster, source)) .toExternal(clusterManager.cluster, clusterManager.requester) .introspect() .then((introspectedExternal) => introspectedExternal.attributes) as any; }); } } preview(dataCube: DataCube): Q.Promise<Dataset> { var clusterName = dataCube.clusterName; if (clusterName === 'native') { return Q.fcall(() => { var fileManager = this.getFileManagerFor(dataCube.source); if (!fileManager) throw new Error(`no file manager for ${dataCube.source}`); var context: any = { temp: fileManager.dataset }; return $('temp').limit(PREVIEW_LIMIT).compute(context) as any; }); } else { return Q.fcall(() => { var clusterManager = this.getClusterManagerFor(clusterName); if (!clusterManager) throw new Error(`no cluster manager for ${clusterName}`); var context: any = { temp: dataCube.toExternal(clusterManager.cluster, clusterManager.requester) }; var primaryTimeExpression = dataCube.getPrimaryTimeExpression(); if (primaryTimeExpression) { return $('temp') .filter(primaryTimeExpression.in(LOTS_OF_TIME)) .max(primaryTimeExpression) .compute(context) .then((maxTime: Date) => { maxTime = new Date(maxTime); if (isNaN(maxTime as any)) throw new Error('invalid maxTime'); var lastTwoWeeks = TimeRange.fromJS({ start: day.move(maxTime, Timezone.UTC, -14), end: maxTime }); return $('temp').filter(primaryTimeExpression.in(lastTwoWeeks)).limit(PREVIEW_LIMIT).compute(context) as any; }); } else { return $('temp').limit(PREVIEW_LIMIT).compute(context) as any; } }); } } private autoLoadDataCubes(initSettings: AppSettings): Q.Promise<AppSettings> { const { verbose, logger } = this; logger.log(`Auto loading`); return this.getAllClusterSources() .then((clusterNameAndSources) => { var dataCubeFillTasks: Q.Promise<any>[] = []; var fullDataCubes: DataCube[] = []; var fullExtraDataCubes: DataCube[] = []; initSettings.getDataCubesByCluster('native').forEach((nativeDataCube) => { dataCubeFillTasks.push( this.getAllAttributes(nativeDataCube.source, 'native') .then( (attributes) => { fullDataCubes.push(nativeDataCube.fillAllFromAttributes(attributes)); }, () => { // fullDataCubes.push(nativeDataCube); } ) ); }); clusterNameAndSources.forEach((clusterNameAndSource, i) => { const { clusterName, source } = clusterNameAndSource; var baseDataCubes = initSettings.getDataCubesByClusterSource(clusterName, source); var isNewDataCube = baseDataCubes.length === 0; if (isNewDataCube) { var newName = `${clusterName}-${source}-${i}`; if (verbose) logger.log(`Adding DataCube '${newName}'`); var cluster = initSettings.getCluster(clusterName); if (cluster.getSourceListScan() === 'auto') { // Respect sourceListScan property baseDataCubes = [DataCube.fromClusterAndSource(newName, cluster, source)]; } } baseDataCubes.forEach(baseDataCube => { dataCubeFillTasks.push( this.getAllAttributes(source, clusterName, baseDataCube) .then( (attributes) => { var fullDataCube = baseDataCube.fillAllFromAttributes(attributes); if (isNewDataCube) { fullExtraDataCubes.push(fullDataCube); } else { fullDataCubes.push(fullDataCube); } }, (e: Error) => { logger.error(`Could get attributes for '${baseDataCube.name}' because: ${e.message}`); // if (!isNewDataCube) fullDataCubes.push(baseDataCube); } ) ); }); }); return Q.all(dataCubeFillTasks).then(() => { return initSettings.changeDataCubes(fullDataCubes.concat(fullExtraDataCubes)); }); }); } }
the_stack
import React from 'react'; import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { _t } from '../../../languageHandler'; import { ensureDMExists } from "../../../createRoom"; import { IDialogProps } from "./IDialogProps"; import { MatrixClientPeg } from "../../../MatrixClientPeg"; import SdkConfig from '../../../SdkConfig'; import Markdown from '../../../Markdown'; import { replaceableComponent } from "../../../utils/replaceableComponent"; import SettingsStore from "../../../settings/SettingsStore"; import StyledRadioButton from "../elements/StyledRadioButton"; import BaseDialog from "./BaseDialog"; import DialogButtons from "../elements/DialogButtons"; import Field from "../elements/Field"; import Spinner from "../elements/Spinner"; interface IProps extends IDialogProps { mxEvent: MatrixEvent; } interface IState { // A free-form text describing the abuse. reason: string; busy: boolean; err?: string; // If we know it, the nature of the abuse, as specified by MSC3215. nature?: ExtendedNature; } const MODERATED_BY_STATE_EVENT_TYPE = [ "org.matrix.msc3215.room.moderation.moderated_by", /** * Unprefixed state event. Not ready for prime time. * * "m.room.moderation.moderated_by" */ ]; const ABUSE_EVENT_TYPE = "org.matrix.msc3215.abuse.report"; // Standard abuse natures. enum Nature { Disagreement = "org.matrix.msc3215.abuse.nature.disagreement", Toxic = "org.matrix.msc3215.abuse.nature.toxic", Illegal = "org.matrix.msc3215.abuse.nature.illegal", Spam = "org.matrix.msc3215.abuse.nature.spam", Other = "org.matrix.msc3215.abuse.nature.other", } enum NonStandardValue { // Non-standard abuse nature. // It should never leave the client - we use it to fallback to // server-wide abuse reporting. Admin = "non-standard.abuse.nature.admin" } type ExtendedNature = Nature | NonStandardValue; type Moderation = { // The id of the moderation room. moderationRoomId: string; // The id of the bot in charge of forwarding abuse reports to the moderation room. moderationBotUserId: string; }; /* * A dialog for reporting an event. * * The actual content of the dialog will depend on two things: * * 1. Is `feature_report_to_moderators` enabled? * 2. Does the room support moderation as per MSC3215, i.e. is there * a well-formed state event `m.room.moderation.moderated_by` * /`org.matrix.msc3215.room.moderation.moderated_by`? */ @replaceableComponent("views.dialogs.ReportEventDialog") export default class ReportEventDialog extends React.Component<IProps, IState> { // If the room supports moderation, the moderation information. private moderation?: Moderation; constructor(props: IProps) { super(props); let moderatedByRoomId = null; let moderatedByUserId = null; if (SettingsStore.getValue("feature_report_to_moderators")) { // The client supports reporting to moderators. // Does the room support it, too? // Extract state events to determine whether we should display const client = MatrixClientPeg.get(); const room = client.getRoom(props.mxEvent.getRoomId()); for (const stateEventType of MODERATED_BY_STATE_EVENT_TYPE) { const stateEvent = room.currentState.getStateEvents(stateEventType, stateEventType); if (!stateEvent) { continue; } if (Array.isArray(stateEvent)) { // Internal error. throw new TypeError(`getStateEvents(${stateEventType}, ${stateEventType}) ` + "should return at most one state event"); } const event = stateEvent.event; if (!("content" in event) || typeof event["content"] != "object") { // The room is improperly configured. // Display this debug message for the sake of moderators. console.debug("Moderation error", "state event", stateEventType, "should have an object field `content`, got", event); continue; } const content = event["content"]; if (!("room_id" in content) || typeof content["room_id"] != "string") { // The room is improperly configured. // Display this debug message for the sake of moderators. console.debug("Moderation error", "state event", stateEventType, "should have a string field `content.room_id`, got", event); continue; } if (!("user_id" in content) || typeof content["user_id"] != "string") { // The room is improperly configured. // Display this debug message for the sake of moderators. console.debug("Moderation error", "state event", stateEventType, "should have a string field `content.user_id`, got", event); continue; } moderatedByRoomId = content["room_id"]; moderatedByUserId = content["user_id"]; } if (moderatedByRoomId && moderatedByUserId) { // The room supports moderation. this.moderation = { moderationRoomId: moderatedByRoomId, moderationBotUserId: moderatedByUserId, }; } } this.state = { // A free-form text describing the abuse. reason: "", busy: false, err: null, // If specified, the nature of the abuse, as specified by MSC3215. nature: null, }; } // The user has written down a freeform description of the abuse. private onReasonChange = ({ target: { value: reason } }): void => { this.setState({ reason }); }; // The user has clicked on a nature. private onNatureChosen = (e: React.FormEvent<HTMLInputElement>): void => { this.setState({ nature: e.currentTarget.value as ExtendedNature }); }; // The user has clicked "cancel". private onCancel = (): void => { this.props.onFinished(false); }; // The user has clicked "submit". private onSubmit = async () => { let reason = this.state.reason || ""; reason = reason.trim(); if (this.moderation) { // This room supports moderation. // We need a nature. // If the nature is `NATURE.OTHER` or `NON_STANDARD_NATURE.ADMIN`, we also need a `reason`. if (!this.state.nature || ((this.state.nature == Nature.Other || this.state.nature == NonStandardValue.Admin) && !reason) ) { this.setState({ err: _t("Please fill why you're reporting."), }); return; } } else { // This room does not support moderation. // We need a `reason`. if (!reason) { this.setState({ err: _t("Please fill why you're reporting."), }); return; } } this.setState({ busy: true, err: null, }); try { const client = MatrixClientPeg.get(); const ev = this.props.mxEvent; if (this.moderation && this.state.nature != NonStandardValue.Admin) { const nature: Nature = this.state.nature; // Report to moderators through to the dedicated bot, // as configured in the room's state events. const dmRoomId = await ensureDMExists(client, this.moderation.moderationBotUserId); await client.sendEvent(dmRoomId, ABUSE_EVENT_TYPE, { event_id: ev.getId(), room_id: ev.getRoomId(), moderated_by_id: this.moderation.moderationRoomId, nature, reporter: client.getUserId(), comment: this.state.reason.trim(), }); } else { // Report to homeserver admin through the dedicated Matrix API. await client.reportEvent(ev.getRoomId(), ev.getId(), -100, this.state.reason.trim()); } this.props.onFinished(true); } catch (e) { this.setState({ busy: false, err: e.message, }); } }; render() { let error = null; if (this.state.err) { error = <div className="error"> { this.state.err } </div>; } let progress = null; if (this.state.busy) { progress = ( <div className="progress"> <Spinner /> </div> ); } const adminMessageMD = SdkConfig.get().reportEvent && SdkConfig.get().reportEvent.adminMessageMD; let adminMessage; if (adminMessageMD) { const html = new Markdown(adminMessageMD).toHTML({ externalLinks: true }); adminMessage = <p dangerouslySetInnerHTML={{ __html: html }} />; } if (this.moderation) { // Display report-to-moderator dialog. // We let the user pick a nature. const client = MatrixClientPeg.get(); const homeServerName = SdkConfig.get()["validated_server_config"].hsName; let subtitle; switch (this.state.nature) { case Nature.Disagreement: subtitle = _t("What this user is writing is wrong.\n" + "This will be reported to the room moderators."); break; case Nature.Toxic: subtitle = _t("This user is displaying toxic behaviour, " + "for instance by insulting other users or sharing " + " adult-only content in a family-friendly room " + " or otherwise violating the rules of this room.\n" + "This will be reported to the room moderators."); break; case Nature.Illegal: subtitle = _t("This user is displaying illegal behaviour, " + "for instance by doxing people or threatening violence.\n" + "This will be reported to the room moderators who may escalate this to legal authorities."); break; case Nature.Spam: subtitle = _t("This user is spamming the room with ads, links to ads or to propaganda.\n" + "This will be reported to the room moderators."); break; case NonStandardValue.Admin: if (client.isRoomEncrypted(this.props.mxEvent.getRoomId())) { subtitle = _t("This room is dedicated to illegal or toxic content " + "or the moderators fail to moderate illegal or toxic content.\n" + "This will be reported to the administrators of %(homeserver)s. " + "The administrators will NOT be able to read the encrypted content of this room.", { homeserver: homeServerName }); } else { subtitle = _t("This room is dedicated to illegal or toxic content " + "or the moderators fail to moderate illegal or toxic content.\n" + " This will be reported to the administrators of %(homeserver)s.", { homeserver: homeServerName }); } break; case Nature.Other: subtitle = _t("Any other reason. Please describe the problem.\n" + "This will be reported to the room moderators."); break; default: subtitle = _t("Please pick a nature and describe what makes this message abusive."); break; } return ( <BaseDialog className="mx_ReportEventDialog" onFinished={this.props.onFinished} title={_t('Report Content')} contentId='mx_ReportEventDialog' > <div> <StyledRadioButton name="nature" value={Nature.Disagreement} checked={this.state.nature == Nature.Disagreement} onChange={this.onNatureChosen} > { _t('Disagree') } </StyledRadioButton> <StyledRadioButton name="nature" value={Nature.Toxic} checked={this.state.nature == Nature.Toxic} onChange={this.onNatureChosen} > { _t('Toxic Behaviour') } </StyledRadioButton> <StyledRadioButton name="nature" value={Nature.Illegal} checked={this.state.nature == Nature.Illegal} onChange={this.onNatureChosen} > { _t('Illegal Content') } </StyledRadioButton> <StyledRadioButton name="nature" value={Nature.Spam} checked={this.state.nature == Nature.Spam} onChange={this.onNatureChosen} > { _t('Spam or propaganda') } </StyledRadioButton> <StyledRadioButton name="nature" value={NonStandardValue.Admin} checked={this.state.nature == NonStandardValue.Admin} onChange={this.onNatureChosen} > { _t('Report the entire room') } </StyledRadioButton> <StyledRadioButton name="nature" value={Nature.Other} checked={this.state.nature == Nature.Other} onChange={this.onNatureChosen} > { _t('Other') } </StyledRadioButton> <p> { subtitle } </p> <Field className="mx_ReportEventDialog_reason" element="textarea" label={_t("Reason")} rows={5} onChange={this.onReasonChange} value={this.state.reason} disabled={this.state.busy} /> { progress } { error } </div> <DialogButtons primaryButton={_t("Send report")} onPrimaryButtonClick={this.onSubmit} focus={true} onCancel={this.onCancel} disabled={this.state.busy} /> </BaseDialog> ); } // Report to homeserver admin. // Currently, the API does not support natures. return ( <BaseDialog className="mx_ReportEventDialog" onFinished={this.props.onFinished} title={_t('Report Content to Your Homeserver Administrator')} contentId='mx_ReportEventDialog' > <div className="mx_ReportEventDialog" id="mx_ReportEventDialog"> <p> { _t("Reporting this message will send its unique 'event ID' to the administrator of " + "your homeserver. If messages in this room are encrypted, your homeserver " + "administrator will not be able to read the message text or view any files " + "or images.") } </p> { adminMessage } <Field className="mx_ReportEventDialog_reason" element="textarea" label={_t("Reason")} rows={5} onChange={this.onReasonChange} value={this.state.reason} disabled={this.state.busy} /> { progress } { error } </div> <DialogButtons primaryButton={_t("Send report")} onPrimaryButtonClick={this.onSubmit} focus={true} onCancel={this.onCancel} disabled={this.state.busy} /> </BaseDialog> ); } }
the_stack
import assert from 'assert'; import * as ThingTalk from 'thingtalk'; import { Ast, Type } from 'thingtalk'; import { Temporal } from '@js-temporal/polyfill'; import * as SentenceGeneratorRuntime from '../sentence-generator/runtime'; import * as SentenceGeneratorTypes from '../sentence-generator/types'; export type AgentReplyRecord = SentenceGeneratorTypes.AgentReplyRecord; import * as ThingTalkUtils from '../utils/thingtalk'; import * as C from './ast_manip'; import * as keyfns from './keyfns'; import { SlotBag } from './slot_bag'; import ThingpediaLoader, { ParsedPlaceholderPhrase } from './load-thingpedia'; // NOTE: this version of arraySubset uses === // the one in array_utils uses .equals() // this one is called on array of strings, so === is appropriate function arraySubset<T>(small : T[], big : T[]) : boolean { for (const element of small) { let good = false; for (const candidate of big) { if (candidate === element) { good = true; break; } } if (!good) return false; } return true; } // Helper classes for info that we extract from the current context // These exist to minimize AST traversals during expansion // NOTE: while ast_manip is mostly just about ThingTalk semantics, with // a few heuristics sprinkled out, this is really only about the "transaction" // dialogue policy // hence we hard-code the policy name here, and check it before doing anything // in the templates // templates can be combined though export const POLICY_NAME = 'org.thingpedia.dialogue.transaction'; const LARGE_RESULT_THRESHOLD = 50; function isLargeResultSet(result : Ast.DialogueHistoryResultList) : boolean { return result.more || !(result.count instanceof Ast.Value.Number) || result.count.value >= LARGE_RESULT_THRESHOLD; } function invertDirection(dir : 'asc'|'desc') : 'asc'|'desc' { if (dir === 'asc') return 'desc'; else return 'asc'; } function getSortName(value : Ast.Value) : string { if (value instanceof Ast.VarRefValue) return value.name; return C.getScalarExpressionName(value); } function getTableArgMinMax(table : Ast.Expression) : [string, string]|null { while (table instanceof Ast.ProjectionExpression) table = table.expression; // either an index of a sort, where the index is exactly 1 or -1 // or a slice of a sort, with a base of 1 or -1, and a limit of 1 // (both are equivalent and get normalized, but sometimes we don't run the normalization) if (table instanceof Ast.IndexExpression && table.expression instanceof Ast.SortExpression && table.indices.length === 1) { const index = table.indices[0]; if (index instanceof Ast.Value.Number && (index.value === 1 || index.value === -1)) return [getSortName(table.expression.value), index.value === -1 ? invertDirection(table.expression.direction) : table.expression.direction]; } if (table instanceof Ast.SliceExpression && table.expression instanceof Ast.SortExpression) { const { base, limit } = table; if (base instanceof Ast.Value.Number && (base.value === 1 || base.value === -1) && limit instanceof Ast.Value.Number && limit.value === 1) return [getSortName(table.expression.value), base.value === -1 ? invertDirection(table.expression.direction) : table.expression.direction]; } return null; } export class ResultInfo { hasStream : boolean; isTable : boolean; isQuestion : boolean; isAggregation : boolean; isList : boolean; argMinMaxField : [string, string]|null; projection : string[]|null; hasError : boolean; hasEmptyResult : boolean; hasSingleResult : boolean; hasLargeResult : boolean; idType : Type|null; constructor(state : Ast.DialogueState, item : Ast.DialogueHistoryItem) { assert(item.results !== null); const stmt = item.stmt; this.hasStream = stmt.stream !== null; this.isTable = stmt.last.schema!.functionType === 'query' && (!this.hasStream || state.dialogueAct === 'notification'); if (this.isTable) { const table = stmt.lastQuery!; this.isQuestion = !!(table instanceof Ast.ProjectionExpression || table instanceof Ast.IndexExpression || table instanceof Ast.AggregationExpression); this.isAggregation = table instanceof Ast.AggregationExpression; this.isList = stmt.expression.schema!.is_list; this.argMinMaxField = getTableArgMinMax(table); assert(this.argMinMaxField === null || this.isQuestion); this.projection = table instanceof Ast.ProjectionExpression ? C.getProjectionArguments(table) : null; if (this.projection) this.projection.sort(); } else { this.isQuestion = false; this.isAggregation = false; this.isList = false; this.argMinMaxField = null; this.projection = null; if (state.dialogueAct === 'action_question') this.projection = state.dialogueActParam as string[]; } this.hasError = item.results.error !== null; this.hasEmptyResult = !this.hasStream && item.results.results.length === 0; this.hasSingleResult = item.results.results.length === 1; this.hasLargeResult = isLargeResultSet(item.results); const id = stmt.last.schema!.getArgument('id'); this.idType = id && !id.is_input ? id.type : null; } } export class NextStatementInfo { isAction : boolean; chainParameter : string|null; chainParameterFilled : boolean; isComplete : boolean; missingSlots : Ast.AbstractSlot[]; constructor(currentItem : Ast.DialogueHistoryItem|null, resultInfo : ResultInfo|null, nextItem : Ast.DialogueHistoryItem) { const nextstmt = nextItem.stmt; this.isAction = !nextstmt.lastQuery; this.chainParameter = null; this.chainParameterFilled = false; this.isComplete = nextItem.isExecutable(); this.missingSlots = []; for (const slot of nextItem.iterateSlots2()) { if (slot instanceof Ast.DeviceSelector) continue; if (slot.get() instanceof Ast.UndefinedValue) this.missingSlots.push(slot); } if (!this.isAction) return; assert(nextItem.stmt.expression.expressions.length === 1); const action = nextItem.stmt.first; assert(action instanceof Ast.InvocationExpression); if (!currentItem || !resultInfo || !resultInfo.isTable) return; const currentstmt = currentItem.stmt; const tableschema = currentstmt.expression.schema!; const idType = tableschema.getArgType('id'); if (!idType) return; const invocation = action.invocation; const actionschema = invocation.schema!; for (const arg of actionschema.iterateArguments()) { if (!arg.is_input) continue; if (arg.type.equals(idType)) { this.chainParameter = arg.name; break; } } if (this.chainParameter === null) return; for (const in_param of invocation.in_params) { if (in_param.name === this.chainParameter && !in_param.value.isUndefined) { this.chainParameterFilled = true; break; } } } } function toID(value : Ast.Value|undefined) { if (value === undefined) return null; const jsValue = value.toJS(); if (typeof jsValue === 'number') return jsValue; else if (jsValue === null || jsValue === undefined) return null; else return String(jsValue); } export class ContextInfo { loader : ThingpediaLoader; contextTable : SentenceGeneratorTypes.ContextTable; state : Ast.DialogueState; currentFunction : Ast.FunctionDef|null; currentTableFunction : Ast.FunctionDef|null; resultInfo : ResultInfo|null; isMultiDomain : boolean; previousDomainIdx : number|null; currentIdx : number|null; nextFunction : Ast.FunctionDef|null; nextIdx : number|null; nextInfo : NextStatementInfo|null; aux : any; key : { currentFunction : string|null; nextFunction : string|null; currentTableFunction : string|null; // type of ID parameter of current result // this is usually the same as currentFunction, but can be null // the current function doesn't return an ID, and can be different // if the current function is not the primary query for this ID type // it is used to match names and contexts idType : Type|null; // IDs of the top 3 results (entity values or numeric IDs) id0 : string|number|null; id1 : string|number|null; id2 : string|number|null; // number of results resultLength : number; // aggregation result (for count) aggregationCount : number|null; is_monitorable : boolean; }; constructor(loader : ThingpediaLoader, contextTable : SentenceGeneratorTypes.ContextTable, state : Ast.DialogueState, currentTableSchema : Ast.FunctionDef|null, currentFunctionSchema : Ast.FunctionDef|null, resultInfo : ResultInfo|null, previousDomainIdx : number|null, currentIdx : number|null, nextIdx : number|null, nextFunctionSchema : Ast.FunctionDef|null, nextInfo : NextStatementInfo|null, aux : any = null) { this.loader = loader; this.contextTable = contextTable; this.state = state; assert(currentFunctionSchema === null || currentFunctionSchema instanceof Ast.FunctionDef); this.currentFunction = currentFunctionSchema; assert(currentTableSchema === null || currentTableSchema instanceof Ast.FunctionDef); this.currentTableFunction = currentTableSchema; this.resultInfo = resultInfo; this.isMultiDomain = previousDomainIdx !== null; this.previousDomainIdx = previousDomainIdx; this.currentIdx = currentIdx; assert(nextFunctionSchema === null || nextFunctionSchema instanceof Ast.FunctionDef); this.nextFunction = nextFunctionSchema; this.nextIdx = nextIdx; this.nextInfo = nextInfo; this.aux = aux; this.key = { currentFunction: this.currentFunction ? this.currentFunction.qualifiedName : null, nextFunction: this.nextFunction ? this.nextFunction.qualifiedName : null, currentTableFunction: this.currentTableFunction ? this.currentTableFunction.qualifiedName : null, idType: null, id0: null, id1: null, id2: null, resultLength: 0, aggregationCount: null, is_monitorable: this.currentFunction ? this.currentFunction.is_monitorable : false }; if (this.resultInfo) { this.key.idType = this.resultInfo.idType; const results = this.results!; this.key.resultLength = results.length; if (results.length > 0) this.key.id0 = toID(results[0].value.id); if (results.length > 1) this.key.id1 = toID(results[1].value.id); if (results.length > 2) this.key.id2 = toID(results[2].value.id); if (this.resultInfo.isAggregation) { const count = results[0].value.count; if (count) this.key.aggregationCount = count.toJS() as number; } } } toString() : string { return `ContextInfo(${this.state.prettyprint()})`; } get results() { if (this.currentIdx !== null) return this.state.history[this.currentIdx].results!.results; return null; } get error() { if (this.currentIdx !== null) return this.state.history[this.currentIdx].results!.error; return null; } get previousDomain() { return this.previousDomainIdx !== null ? this.state.history[this.previousDomainIdx] : null; } get current() { return this.currentIdx !== null ? this.state.history[this.currentIdx] : null; } get next() { return this.nextIdx !== null ? this.state.history[this.nextIdx] : null; } clone() { return new ContextInfo( this.loader, this.contextTable, this.state.clone(), this.currentTableFunction, this.currentFunction, this.resultInfo, this.previousDomainIdx, this.currentIdx, this.nextIdx, this.nextFunction, this.nextInfo, this.aux ); } } export function contextKeyFn(ctx : ContextInfo) { return ctx.key; } export function initialContextInfo(loader : ThingpediaLoader, contextTable : SentenceGeneratorTypes.ContextTable) { return new ContextInfo(loader, contextTable, new Ast.DialogueState(null, POLICY_NAME, 'sys_init', [], []), null, null, null, null, null, null, null, null); } export function getContextInfo(loader : ThingpediaLoader, state : Ast.DialogueState, contextTable : SentenceGeneratorTypes.ContextTable) : ContextInfo { let nextItemIdx = null, nextInfo = null, currentFunction = null, currentTableFunction = null, nextFunction = null, currentDevice = null, currentResultInfo = null, previousDomainItemIdx = null, currentItemIdx = null; let proposedSkip = 0; for (let idx = 0; idx < state.history.length; idx ++) { const item = state.history[idx]; const itemschema = item.stmt.expression.schema!; const device = itemschema.class ? itemschema.class.name : null; if (currentDevice && device && device !== currentDevice) previousDomainItemIdx = currentItemIdx; if (item.confirm === 'proposed') { proposedSkip ++; continue; } if (item.results === null) { nextItemIdx = idx; nextFunction = itemschema; nextInfo = new NextStatementInfo( currentItemIdx !== null ? state.history[currentItemIdx] : null, currentResultInfo, item); break; } // proposed items must come after the current item // (but they can come before or after the next item, depending on what we're proposing) assert(proposedSkip === 0); currentDevice = device; currentFunction = itemschema; const stmt = item.stmt; const lastQuery = stmt.lastQuery; if (lastQuery) currentTableFunction = lastQuery.schema; currentItemIdx = idx; currentResultInfo = new ResultInfo(state, item); } if (nextItemIdx !== null) assert(nextInfo); if (nextItemIdx !== null && currentItemIdx !== null) assert(nextItemIdx === currentItemIdx + 1 + proposedSkip); if (previousDomainItemIdx !== null) assert(currentItemIdx !== null && previousDomainItemIdx <= currentItemIdx); return new ContextInfo(loader, contextTable, state, currentTableFunction, currentFunction, currentResultInfo, previousDomainItemIdx, currentItemIdx, nextItemIdx, nextFunction, nextInfo); } export function isUserAskingResultQuestion(ctx : ContextInfo) : boolean { // is the user asking a question about the result (or a specific element), or refining a search? // we say it's a question if any of the following is true: // - it's a computation question // - there is an id filter // - it's a projection question and the projection was different at the previous turn // we also treat it as a question for all compute questions because that simplifies // writing the templates if (ctx.state.dialogueAct === 'action_question') return true; if (ctx.currentIdx === null) return false; const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.lastQuery; if (!currentTable) return false; if (currentTable instanceof Ast.ProjectionExpression && currentTable.computations.length > 0) return true; const filterTable = C.findFilterExpression(currentStmt.expression); if (filterTable && C.filterUsesParam(filterTable.filter, 'id')) return true; if (ctx.currentIdx === 0) return false; const currentProjection = ctx.resultInfo!.projection; if (!currentProjection) return false; const previous = ctx.state.history[ctx.currentIdx - 1]; // only complete (executed) programs make it to the history, so this must be true assert(previous.results !== null); const previousResultInfo = new ResultInfo(ctx.state, previous); if (!previousResultInfo.projection) return true; // it's a question if the current projection is not a subset of the previous one // (for a search refinement: it might be exactly the same as before, or we might have // lost some parameters because we put a filter on it) return !arraySubset(currentProjection, previousResultInfo.projection); } class CollectDeviceIDVisitor extends Ast.NodeVisitor { collection = new Map<string, string>(); visitDeviceSelector(selector : Ast.DeviceSelector) { if (selector.all) { this.collection.set(selector.kind, 'all'); return false; } if (!selector.id) return false; this.collection.set(selector.kind, selector.id); return false; } } class ApplyDeviceIDVisitor extends Ast.NodeVisitor { constructor(private collection : Map<string, string>) { super(); } visitDeviceSelector(selector : Ast.DeviceSelector) { if (selector.attributes.length > 0 || selector.all) return false; if (selector.id) return false; const existing = this.collection.get(selector.kind); if (existing === 'all') selector.all = true; else if (existing) selector.id = existing; return false; } } function propagateDeviceIDs(ctx : ContextInfo, newHistoryItems : Ast.DialogueHistoryItem[]) { const visitor = new CollectDeviceIDVisitor(); // here we used to traverse the whole state and collect all device IDs from // all turns // this is not correct though: we cannot propagate a device ID older // than MAX_CONTEXT_ITEMS ago because it won't be seen in the neural context // // instead, we only ask the neural model to propagate the current item, if we have // it, and any item newer than that // propagation from older item will happen in prepareForExecution // // we need to have the neural model propagate from the next item and subsequent // because next items are replaced and gone before prepareForExecution so the // info has to be carried forward by the neural model output const currentIdx = ctx.currentIdx ?? -1; if (currentIdx >= 0) ctx.state.history[currentIdx].visit(visitor); for (let i = currentIdx+1; i < ctx.state.history.length; i++) ctx.state.history[i].visit(visitor); const applyVisitor = new ApplyDeviceIDVisitor(visitor.collection); return newHistoryItems.map((item) => { // clone the item just to be sure // FIXME we might be able to skip this clone in some cases item = item.clone(); item.visit(applyVisitor); return item; }); } function addNewItem(ctx : ContextInfo, dialogueAct : string, dialogueActParam : string|null, confirm : 'accepted-query'|'accepted'|'proposed'|'proposed-query'|'confirmed', ...newHistoryItem : Ast.DialogueHistoryItem[]) : Ast.DialogueState { newHistoryItem = propagateDeviceIDs(ctx, newHistoryItem); for (const item of newHistoryItem) { C.adjustDefaultParameters(item); item.results = null; item.confirm = confirm === 'accepted-query' ? 'accepted' : confirm === 'proposed-query' ? 'proposed' : confirm; } const newState = new Ast.DialogueState(null, POLICY_NAME, dialogueAct, dialogueActParam, []); if (confirm === 'proposed') { // find the first item that was not confirmed or accepted, and replace everything after that for (let i = 0; i < ctx.state.history.length; i++) { if (ctx.state.history[i].confirm === 'proposed') break; newState.history.push(ctx.state.history[i]); } newState.history.push(...newHistoryItem); } else if (confirm === 'accepted-query' || confirm === 'proposed-query') { // add the new history item right after the current one, keep // all the accepted items, and remove all proposed items if (ctx.currentIdx !== null) { for (let i = 0; i <= ctx.currentIdx; i++) newState.history.push(ctx.state.history[i]); } newState.history.push(...newHistoryItem); if (ctx.currentIdx !== null) { for (let i = ctx.currentIdx + 1; i < ctx.state.history.length; i++) { if (ctx.state.history[i].confirm === 'proposed') continue; newState.history.push(ctx.state.history[i]); } } } else { // wipe everything from state after the current program // this will remove all previously accepted and/or proposed actions if (ctx.currentIdx !== null) { for (let i = 0; i <= ctx.currentIdx; i++) newState.history.push(ctx.state.history[i]); } newState.history.push(...newHistoryItem); } return newState; } export function addNewStatement(ctx : ContextInfo, dialogueAct : string, dialogueActParam : string|null, confirm : 'accepted'|'proposed'|'confirmed', ...newExpression : Ast.Expression[]) { const newItems = newExpression.map((expr) => new Ast.DialogueHistoryItem(null, new Ast.ExpressionStatement(null, expr), null, confirm)); return addNewItem(ctx, dialogueAct, dialogueActParam, confirm, ...newItems); } export function acceptAllProposedStatements(ctx : ContextInfo) { if (!ctx.state.history.some((item) => item.confirm === 'proposed')) return null; return new Ast.DialogueState(null, POLICY_NAME, 'execute', null, ctx.state.history.map((item) => { if (item.confirm === 'proposed') return new Ast.DialogueHistoryItem(null, item.stmt, null, 'accepted'); else return item; })); } function makeSimpleState(ctx : ContextInfo, dialogueAct : string, dialogueActParam : string[]|null) : Ast.DialogueState { // a "simple state" carries the current executed/confirmed/accepted items, but not the // proposed ones const newState = new Ast.DialogueState(null, POLICY_NAME, dialogueAct, dialogueActParam, []); for (let i = 0; i < ctx.state.history.length; i++) { if (ctx.state.history[i].confirm === 'proposed') break; newState.history.push(ctx.state.history[i]); } return newState; } function sortByName(p1 : Ast.InputParam, p2 : Ast.InputParam) : -1|0|1 { if (p1.name < p2.name) return -1; if (p1.name > p2.name) return 1; return 0; } function setOrAddInvocationParam(newInvocation : Ast.Invocation, pname : string, value : Ast.Value) : void { let found = false; for (const in_param of newInvocation.in_params) { if (in_param.name === pname) { found = true; in_param.value = value; break; } } if (!found) { newInvocation.in_params.push(new Ast.InputParam(null, pname, value)); newInvocation.in_params.sort(sortByName); } } function mergeParameters(toInvocation : Ast.Invocation, fromInvocation : Ast.Invocation) : Ast.Invocation { for (const in_param of fromInvocation.in_params) { if (in_param.value.isUndefined) continue; setOrAddInvocationParam(toInvocation, in_param.name, in_param.value); } return toInvocation; } function addActionParam(ctx : ContextInfo, dialogueAct : string, action : Ast.Invocation, pname : string, value : Ast.Value, confirm : 'accepted' | 'proposed') : Ast.DialogueState { assert(action instanceof Ast.Invocation); assert(['accepted', 'confirmed', 'proposed'].indexOf(confirm) >= 0); let newHistoryItem; if (ctx.nextInfo) { const next = ctx.next; assert(next); const nextInvocation = C.getInvocation(next); const isSameFunction = C.isSameFunction(nextInvocation.schema!, action.schema!); if (isSameFunction) { // we want to modify the existing action in case: // - case 1: we're currently accepting/confirming the action (perhaps with the same or // a different parameter) // - case 2: we're proposing the same action that was proposed before // // to carry over parameters, we actually clone the statement and set the parameter // if confirm == "proposed": // addNewItem() will add at the end, after the currently accepted // item, and we'll have two actions (one "accepted" and one "proposed"), or just one "proposed" action // if confirm == "accepted": // addNewItem() will wipe everything and we'll only one newHistoryItem = next.clone(); const newInvocation = C.getInvocation(newHistoryItem); assert(newInvocation instanceof Ast.Invocation); setOrAddInvocationParam(newInvocation, pname, value); // also add the new parameters from this action, if any for (const param of action.in_params) { if (param.value.isUndefined) continue; setOrAddInvocationParam(newInvocation, param.name, param.value); } newHistoryItem.confirm = confirm; } } if (!newHistoryItem) { const in_params = [new Ast.InputParam(null, pname, value)]; const setparams = new Set; setparams.add(pname); for (const param of action.in_params) { if (param.value.isUndefined) continue; if (param.name !== pname) in_params.push(param.clone()); setparams.add(param.name); } const schema = action.schema!; // make sure we add all $undefined values, otherwise we'll fail // to recognize that the statement is not yet executable, and we'll // crash in the compiler for (const arg of schema.iterateArguments()) { if (arg.is_input && arg.required && !setparams.has(arg.name)) in_params.push(new Ast.InputParam(null, arg.name, new Ast.Value.Undefined(true))); } const newInvocation = new Ast.Invocation(null, action.selector, action.channel, in_params, schema ); const newStmt = new Ast.ExpressionStatement(null, new Ast.InvocationExpression(null, newInvocation, schema)); newHistoryItem = new Ast.DialogueHistoryItem(null, newStmt, null, confirm); } return addNewItem(ctx, dialogueAct, null, confirm, newHistoryItem); } function addAction(ctx : ContextInfo, dialogueAct : string, action : Ast.Invocation, confirm : 'accepted' | 'proposed') : Ast.DialogueState { assert(action instanceof Ast.Invocation); // note: parameters from the action are ignored altogether! let newHistoryItem; if (ctx.nextInfo) { const next = ctx.next; assert(next); const nextInvocation = C.getInvocation(next); if (C.isSameFunction(nextInvocation.schema!, action.schema!)) { assert(next.results === null); // case 1: // - we trying to propose an action that the user has already introduced // earlier // in that case, we want to remember the action as accepted, not proposed // case 2: // - we trying to accept or confirm the action that was previously proposed // in that case, we want to change the action to accepted or confirmed if (confirm === 'proposed' || confirm === next.confirm) return new Ast.DialogueState(null, POLICY_NAME, dialogueAct, null, ctx.state.history); newHistoryItem = new Ast.DialogueHistoryItem(null, next.stmt, null, confirm); } } if (!newHistoryItem) { const newInvocation = new Ast.Invocation(null, action.selector, action.channel, [], action.schema ); const newStmt = new Ast.ExpressionStatement(null, new Ast.InvocationExpression(null, newInvocation, action.schema )); newHistoryItem = new Ast.DialogueHistoryItem(null, newStmt, null, confirm); } return addNewItem(ctx, dialogueAct, null, confirm, newHistoryItem); } function addQuery(ctx : ContextInfo, dialogueAct : string, newTable : Ast.Expression, confirm : 'accepted' | 'proposed') : Ast.DialogueState { newTable = C.adjustDefaultParameters(newTable); const newStmt = new Ast.ExpressionStatement(null, newTable); const newHistoryItem = new Ast.DialogueHistoryItem(null, newStmt, null, confirm); return addNewItem(ctx, dialogueAct, null, confirm === 'accepted' ? 'accepted-query' : 'proposed-query', newHistoryItem); } function addQueryAndAction(ctx : ContextInfo, dialogueAct : string, newTable : Ast.Expression, newAction : Ast.Invocation, confirm : 'accepted' | 'proposed') : Ast.DialogueState { const newTableStmt = new Ast.ExpressionStatement(null, newTable); const newTableHistoryItem = new Ast.DialogueHistoryItem(null, newTableStmt, null, confirm); // add the new table history item right after the current one, and replace everything after that const newActionStmt = new Ast.ExpressionStatement(null, new Ast.InvocationExpression(null, newAction, newAction.schema)); const newActionHistoryItem = new Ast.DialogueHistoryItem(null, newActionStmt, null, confirm); return addNewItem(ctx, dialogueAct, null, confirm, newTableHistoryItem, newActionHistoryItem); } export function makeContextPhrase(symbol : number, value : ContextInfo, utterance : SentenceGeneratorRuntime.ReplacedResult = SentenceGeneratorRuntime.ReplacedResult.EMPTY, priority = 0) : SentenceGeneratorTypes.ContextPhrase { return { symbol, utterance, value, priority, context: value, key: value.key }; } export function makeExpressionContextPhrase(context : ContextInfo, symbol : number, value : Ast.Expression, utterance : SentenceGeneratorRuntime.ReplacedResult = SentenceGeneratorRuntime.ReplacedResult.EMPTY, priority = 0) : SentenceGeneratorTypes.ContextPhrase { return { symbol, utterance, value, priority, context, key: keyfns.expressionKeyFn(value) }; } export function makeValueContextPhrase(context : ContextInfo, symbol : number, value : Ast.Value, utterance : SentenceGeneratorRuntime.ReplacedResult = SentenceGeneratorRuntime.ReplacedResult.EMPTY, priority = 0) : SentenceGeneratorTypes.ContextPhrase { return { symbol, utterance, value, priority, context, key: keyfns.valueKeyFn(value) }; } export interface AgentReplyOptions { end ?: boolean; raw ?: boolean; numResults ?: number; } /** * Construct a full formal reply from the agent. * * The reply contains: * - the agent state (a ThingTalk dialogue state passed to the NLU and NLG networks) * - the agent reply tags (a list of strings that define the context tags on the user side) * - the interaction state (the expected type of the reply, if any, and a boolean indicating raw mode) * - extra information for the new context */ function makeAgentReply(ctx : ContextInfo, state : Ast.DialogueState, aux : unknown = null, expectedType : ThingTalk.Type|null = null, options : AgentReplyOptions = {}) : AgentReplyRecord { const contextTable = ctx.contextTable; assert(state instanceof Ast.DialogueState); assert(state.dialogueAct.startsWith('sys_')); assert(expectedType === null || expectedType instanceof ThingTalk.Type); // show a yes/no thing if we're proposing something if (expectedType === null && state.history.some((item) => item.confirm === 'proposed')) expectedType = Type.Boolean; // if false, the agent is still listening // the agent will continue listening if one of the following is true: // - the agent is eliciting a value (slot fill or search question) // - the agent is proposing a statement // - the agent is asking the user to learn more // - there are more statements left to do (includes the case of confirmations) let end = options.end; if (end === undefined) { end = expectedType === null && state.dialogueActParam === null && !state.dialogueAct.endsWith('_question') && state.history.every((item) => item.results !== null); } if (ctx.loader.flags.inference) { // at inference time, we don't need to compute any of the auxiliary info // necessary to synthesize the new utterance, so we take a shortcut // here and skip a whole bunch of computation return { state, contextPhrases: [], expect: expectedType, end: end, // if true, enter raw mode for this user's turn // (this is used for slot filling free-form strings) raw: !!options.raw, // the number of results we're describing at this turn // (this affects the number of result cards to show) numResults: options.numResults || 0, }; } const newContext = getContextInfo(ctx.loader, state, contextTable); // set the auxiliary information, which is used by the semantic functions of the user // to see if the continuation is compatible with the specific reply from the agent newContext.aux = aux; let mainTag; if (state.dialogueAct === 'sys_generic_search_question') mainTag = contextTable.ctx_sys_search_question; else if (state.dialogueAct.endsWith('_question') && state.dialogueAct !== 'sys_search_question') mainTag = contextTable['ctx_' + state.dialogueAct.substring(0, state.dialogueAct.length - '_question'.length)]; else if (state.dialogueAct.startsWith('sys_recommend_') && state.dialogueAct !== 'sys_recommend_one') mainTag = contextTable.ctx_sys_recommend_many; else if (state.dialogueAct === 'sys_rule_enable_success') mainTag = contextTable.ctx_sys_action_success; else mainTag = contextTable['ctx_' + state.dialogueAct]; return { state, contextPhrases: [ makeContextPhrase(ctx.contextTable.ctx_sys_any, newContext), makeContextPhrase(mainTag, newContext), ...getUserContextPhrases(newContext) ], expect: expectedType, end: end, // if true, enter raw mode for this user's turn // (this is used for slot filling free-form strings) raw: !!options.raw, // the number of results we're describing at this turn // (this affects the number of result cards to show) numResults: options.numResults || 0, }; } function setEndBit(reply : AgentReplyRecord, value : boolean) : AgentReplyRecord { const newReply = {} as AgentReplyRecord; Object.assign(newReply, reply); newReply.end = value; return newReply; } function actionShouldHaveResult(ctx : ContextInfo) : boolean { const schema = ctx.currentFunction!; return C.countInputOutputParams(schema).output > 0; } export function tagContextForAgent(ctx : ContextInfo) : number[] { const contextTable = ctx.contextTable; switch (ctx.state.dialogueAct) { case 'end': // no continuations are possible after explicit "end" (which means the user said // "no thanks" after the agent asked "is there anything else I can do for you") // but we still tag the context to generate something in inference mode return [contextTable.ctx_end]; case 'greet': return [contextTable.ctx_greet]; case 'reinit': return [contextTable.ctx_reinit]; case 'cancel': return [contextTable.ctx_cancel]; case 'action_question': return [contextTable.ctx_completed_action_success]; case 'learn_more': assert(ctx.results); return [contextTable.ctx_learn_more]; case 'notification': assert(ctx.nextInfo === null); assert(ctx.resultInfo, `expected result info`); if (ctx.resultInfo.hasError) return [contextTable.ctx_notification_error]; if (!ctx.resultInfo.isTable) return [contextTable.ctx_action_notification]; else if (ctx.resultInfo.isList) return [contextTable.ctx_list_notification]; else return [contextTable.ctx_nonlist_notification]; case 'init': case 'insist': case 'execute': case 'ask_recommend': // treat an empty execute like greet if (ctx.state.history.length === 0) return [contextTable.ctx_greet]; if (ctx.nextInfo !== null) { // we have an action we want to execute, or a query that needs confirmation if (ctx.nextInfo.chainParameter === null || ctx.nextInfo.chainParameterFilled) { // we don't need to fill any parameter from the current query if (ctx.nextInfo.isComplete) return [contextTable.ctx_confirm_action]; else return [contextTable.ctx_incomplete_action_after_search]; } } // we must have a result assert(ctx.resultInfo, `expected result info`); if (ctx.resultInfo.hasError) return [contextTable.ctx_completed_action_error]; if (ctx.resultInfo.hasStream) return [contextTable.ctx_rule_enable_success]; if (!ctx.resultInfo.isTable) { if (ctx.resultInfo.hasEmptyResult && actionShouldHaveResult(ctx)) return [contextTable.ctx_empty_search_command]; else return [contextTable.ctx_completed_action_success]; } if (ctx.resultInfo.hasEmptyResult) { // note: aggregation cannot be empty (it would be zero) return [contextTable.ctx_empty_search_command]; } if (!ctx.resultInfo.isList) { return [contextTable.ctx_display_nonlist_result]; } else if (ctx.resultInfo.isQuestion) { if (ctx.resultInfo.isAggregation) { // "how many restaurants nearby have more than 500 reviews?" return [contextTable.ctx_aggregation_question]; } else if (ctx.resultInfo.argMinMaxField !== null) { // these are treated as single result questions, but // the context is tagged as ctx_with_result_argminmax instead of // ctx_with_result_noquestion // so the answer is worded differently return [contextTable.ctx_single_result_search_command, contextTable.ctx_complete_search_command]; } else if (ctx.resultInfo.hasSingleResult) { // "what is the rating of Terun?" // FIXME if we want to answer differently, we need to change this one return [contextTable.ctx_single_result_search_command, contextTable.ctx_complete_search_command]; } else if (ctx.resultInfo.hasLargeResult) { // "what's the food and price range of restaurants nearby?" // we treat these the same as "find restaurants nearby", but we make sure // that the necessary fields are computed return [contextTable.ctx_search_command, contextTable.ctx_complete_search_command]; } else { // "what's the food and price range of restaurants nearby?" // we treat these the same as "find restaurants nearby", but we make sure // that the necessary fields are computed return [contextTable.ctx_complete_search_command]; } } else { if (ctx.resultInfo.hasSingleResult) // we can recommend return [contextTable.ctx_single_result_search_command, contextTable.ctx_complete_search_command]; else if (ctx.resultInfo.hasLargeResult && ctx.state.dialogueAct !== 'ask_recommend') // we can refine return [contextTable.ctx_search_command, contextTable.ctx_complete_search_command]; else return [contextTable.ctx_complete_search_command]; } default: throw new Error(`Unexpected user dialogue act ${ctx.state.dialogueAct}`); } } function ctxCanHaveRelatedQuestion(ctx : ContextInfo) : boolean { const currentStmt = ctx.current!.stmt; if (currentStmt.stream !== null) return false; const currentTable = currentStmt.lastQuery; if (!currentTable) return false; if (!(currentTable.schema instanceof Ast.FunctionDef)) // FIXME ExpressionSignature that is not a FunctionDef - not sure how it happens... return false; const related = currentTable.schema.getAnnotation<string[]>('related'); return !!(related && related.length); } function tryReplacePlaceholderPhrase(phrase : ParsedPlaceholderPhrase, getParam : (name : string) => SentenceGeneratorRuntime.PlaceholderReplacement|undefined|null) : SentenceGeneratorRuntime.ReplacedResult|null { const replacements : Array<SentenceGeneratorRuntime.PlaceholderReplacement|undefined> = []; for (const param of phrase.names) { const replacement = getParam(param); if (replacement === null) replacements.push(undefined); else replacements.push(replacement); } const replacementCtx = { replacements, constraints: {} }; return phrase.replaceable.replace(replacementCtx); } function toJS(value : Ast.Value, loader : ThingpediaLoader) { if (value instanceof Ast.DateValue || value instanceof Ast.RecurrentTimeSpecificationValue) value = value.normalize(loader.timezone || Temporal.Now.timeZone().id); return value.toJS(); } function getDeviceName(describer : ThingTalkUtils.Describer, resultItem : Ast.DialogueHistoryResultItem|undefined, invocation : Ast.Invocation|Ast.FunctionCallExpression) { if (resultItem) { // check in the result first // until ThingTalk is fixed, this will be present only if there was no // projection and the compiler did not get in the way // FIXME we should fix the ThingTalk compiler though... if (resultItem.value.__device) { const entity = resultItem.value.__device; const description = describer.describeArg(entity, {}); if (description) return { value: entity, text: description }; } } if (!(invocation instanceof Ast.Invocation)) return undefined; let name; for (const in_param of invocation.selector.attributes) { if (in_param.name === 'name') { name = in_param.value; break; } } if (!name) return undefined; const entity = new Ast.EntityValue(invocation.selector.id, 'tt:device_id', name.toJS() as string); const description = describer.describeArg(entity, {}); if (!description) return undefined; return { value: entity, text: description }; } function makeErrorContextPhrase(ctx : ContextInfo, error : Ast.EnumValue) { const contextTable = ctx.contextTable; const describer = ctx.loader.describer; const currentFunction = ctx.currentFunction!; const phrases = ctx.loader.getErrorMessages(currentFunction.qualifiedName)[error.value]; if (!phrases) return []; const action = C.getInvocation(ctx.current!); const output = []; for (const candidate of phrases) { const bag = new SlotBag(currentFunction); const utterance = tryReplacePlaceholderPhrase(candidate, (param) => { if (param === '__device') return getDeviceName(describer, undefined, action); let value = null; for (const in_param of action.in_params) { if (in_param.name === param) { value = in_param.value; break; } } if (!value) return null; const text = describer.describeArg(value); if (text === null) return null; bag.set(param, value); return { value: value.isConstant() ? toJS(value, ctx.loader) : value, text }; }); if (utterance) { const value : C.ErrorMessage = { code: error.value, bag }; output.push({ symbol: contextTable.ctx_thingpedia_error_message, utterance, value, priority: 0, context: ctx, key: keyfns.errorMessageKeyFn(value) }); // in inference mode, we're done if (ctx.loader.flags.inference) return output; } } return output; } function makeListResultContextPhrase(ctx : ContextInfo, allResults : Ast.DialogueHistoryResultItem[], phrases : ParsedPlaceholderPhrase[]) { const contextTable = ctx.contextTable; const describer = ctx.loader.describer; const currentFunction = ctx.currentFunction!; const action = C.getInvocation(ctx.current!); const output = []; // list result, concatenate all parameters into each placeholder for (const candidate of phrases) { const bag = new SlotBag(currentFunction); const utterance = tryReplacePlaceholderPhrase(candidate, (param) => { if (param === '__device') return getDeviceName(describer, undefined, action); const arg = currentFunction.getArgument(param); // check if the argument was projected out, in which case we can't // use this result phrase if (!arg) return null; if (arg.is_input) { // use the top result value only const topResult = allResults[0]; const value = topResult.value[param]; if (!value) return null; const text = describer.describeArg(value); if (text === null) return null; bag.set(param, value); return { value: value.toJS(), text }; } else { const arrayValue = new Ast.ArrayValue([]); for (const result of allResults) { const value = result.value[param]; if (!value) return null; arrayValue.value.push(value); } const text = describer.describeArg(arrayValue); if (text === null) return null; bag.set(param, arrayValue); return { value: arrayValue.toJS(), text }; } }); if (utterance) { const value = [ctx, bag]; output.push({ symbol: contextTable.ctx_thingpedia_list_result, utterance, value, priority: 0, context: ctx, key: keyfns.slotBagKeyFn(bag) }); // in inference mode, we're done if (ctx.loader.flags.inference) return output; } } return output; } const MAX_LIST_LENGTH = 5; function makeListConcatResultContextPhrase(ctx : ContextInfo, allResults : Ast.DialogueHistoryResultItem[], phrases : ParsedPlaceholderPhrase[]) { const contextTable = ctx.contextTable; const describer = ctx.loader.describer; const currentFunction = ctx.currentFunction!; const action = C.getInvocation(ctx.current!); const output = []; // list_concat result: concatenate phrases made from each result // don't concatenate too many phrases allResults = allResults.slice(0, MAX_LIST_LENGTH); outer: for (const candidate of phrases) { const bag = new SlotBag(currentFunction); const utterance = []; for (let resultIdx = 0; resultIdx < allResults.length; resultIdx++) { const result = allResults[resultIdx]; const piece = tryReplacePlaceholderPhrase(candidate, (param) => { if (param === '__index') return { value: resultIdx+1, text: new SentenceGeneratorRuntime.ReplacedConcatenation([String(resultIdx+1)], {}, {}) }; // FIXME this should be extracted from the result instead // so we can show different names for different devices if (param === '__device') return getDeviceName(describer, result, action); // set the bag to the array value, if we haven't already if (!bag.has(param)) { const arrayValue = new Ast.ArrayValue([]); for (const result of allResults) { const value = result.value[param]; if (!value) return null; arrayValue.value.push(value); } bag.set(param, arrayValue); } // then pick the current result const value = result.value[param]; if (!value) return null; const text = describer.describeArg(value); if (text === null) return null; return { value: value.toJS(), text }; }); if (piece === null) continue outer; utterance.push(piece); } if (utterance) { const value = [ctx, bag]; output.push({ symbol: contextTable.ctx_thingpedia_list_result, utterance: new SentenceGeneratorRuntime.ReplacedList(utterance, ctx.loader.locale, '.'), value, priority: 0, context: ctx, key: keyfns.slotBagKeyFn(bag) }); // in inference mode, we're done if (ctx.loader.flags.inference) return output; } } return output; } function makeTopResultContextPhrase(ctx : ContextInfo, topResult : Ast.DialogueHistoryResultItem, phrases : ParsedPlaceholderPhrase[]) { const contextTable = ctx.contextTable; const describer = ctx.loader.describer; const currentFunction = ctx.currentFunction!; const action = C.getInvocation(ctx.current!); const output = []; // top result for (const candidate of phrases) { const bag = new SlotBag(currentFunction); const utterance = tryReplacePlaceholderPhrase(candidate, (param) => { if (param === '__device') return getDeviceName(describer, topResult, action); const value = topResult.value[param]; if (!value) return null; const text = describer.describeArg(value); if (text === null) return null; bag.set(param, value); return { value: value.toJS(), text }; }); if (utterance) { output.push({ symbol: contextTable.ctx_thingpedia_result, utterance, value: bag, priority: 0, context: ctx, key: keyfns.slotBagKeyFn(bag) }); // in inference mode, we're done if (ctx.loader.flags.inference) return output; } } return output; } // exported for tests export function makeResultContextPhrase(ctx : ContextInfo, topResult : Ast.DialogueHistoryResultItem, allResults : Ast.DialogueHistoryResultItem[]) { // note: this is not the same as ctx.currentFunction (aka ctx.current!.stmt.expression.schema!) // because the value of is_list will be different if the last function is not // a list query but it is invoked in a chain with a list function const currentFunction = ctx.current!.stmt.last.schema!; const phrases = ctx.loader.getResultPhrases(currentFunction.qualifiedName); const output = []; // if we have multiple results, we prefer, in order: // - list result // - list_concat result // - top result // // if we have one result, we prefer, in order: // - top result // - list_concat result // - list result if (allResults.length > 1) { output.push(...makeListResultContextPhrase(ctx, allResults, phrases.list)); if (ctx.loader.flags.inference && output.length > 0) return output; output.push(...makeListConcatResultContextPhrase(ctx, allResults, phrases.list_concat)); if (ctx.loader.flags.inference && output.length > 0) return output; if (!currentFunction.is_list) { // if the function is not a list, but we're getting multiple // results, it means it was invoked over multiple devices, or multiple // times in a row using a chain expression // concatenates all the result phrases as if they were of "list_concat" // type, because "list_concat" does not make sense for a non-list // function output.push(...makeListConcatResultContextPhrase(ctx, allResults, phrases.top)); } else { output.push(...makeTopResultContextPhrase(ctx, topResult, phrases.top)); } } else { output.push(...makeTopResultContextPhrase(ctx, topResult, phrases.top)); if (ctx.loader.flags.inference && output.length > 0) return output; output.push(...makeListConcatResultContextPhrase(ctx, allResults, phrases.list_concat)); if (ctx.loader.flags.inference && output.length > 0) return output; output.push(...makeListResultContextPhrase(ctx, allResults, phrases.list)); } return output; } export function makeEmptyResultContextPhrase(ctx : ContextInfo) { const currentFunction = ctx.currentFunction!; const contextTable = ctx.contextTable; const describer = ctx.loader.describer; const phrases = ctx.loader.getResultPhrases(currentFunction.qualifiedName); const action = C.getInvocation(ctx.current!); const isAction = currentFunction.functionType === 'action'; const output = []; for (const candidate of (isAction ? phrases.top : phrases.empty)) { const bag = new SlotBag(currentFunction); const utterance = tryReplacePlaceholderPhrase(candidate, (param) => { let value = null; for (const in_param of action.in_params) { if (in_param.name === param) { value = in_param.value; break; } } if (!value) return null; const text = describer.describeArg(value); if (text === null) return null; bag.set(param, value); return { value: value.toJS(), text }; }); if (utterance) { output.push({ symbol: isAction ? contextTable.ctx_thingpedia_result : contextTable.ctx_thingpedia_empty_result, utterance, value: bag, priority: 0, context: ctx, key: keyfns.slotBagKeyFn(bag) }); // in inference mode, we're done if (ctx.loader.flags.inference) return output; } } return output; } export interface NameList { ctx : ContextInfo; results : Ast.DialogueHistoryResultItem[]; } export function nameListKeyFn(list : NameList) { const schema = list.ctx.currentFunction!; return { functionName: schema.qualifiedName, idType: schema.getArgType('id')!, length: list.results.length, id0: list.ctx.key.id0, id1: list.ctx.key.id1, id2: list.ctx.key.id2, }; } function makeOneNameListContextPhrase(ctx : ContextInfo, descriptions : SentenceGeneratorRuntime.ReplacedResult[], length : number) { const utterance = new SentenceGeneratorRuntime.ReplacedList(descriptions.slice(0, length), ctx.loader.locale, undefined); const value : NameList = { ctx, results: ctx.results!.slice(0, length) }; return { symbol: ctx.contextTable.ctx_result_name_list, utterance, value, priority: length === 2 || length === 3 ? length : 0, context: ctx, key: nameListKeyFn(value) }; } export interface ContextName { ctx : ContextInfo; name : Ast.Value; } export function contextNameKeyFn(name : ContextName) { return { currentFunction: name.ctx.key.currentFunction }; } function makeNameContextPhrase(ctx : ContextInfo, utterance : SentenceGeneratorRuntime.ReplacedResult, name : Ast.Value) { const value = { ctx, name }; return { symbol: ctx.contextTable.ctx_result_name, utterance, value, priority: 0, context: ctx, key: contextNameKeyFn(value) }; } export function makeNameListContextPhrases(ctx : ContextInfo) : SentenceGeneratorTypes.ContextPhrase[] { const describer = ctx.loader.describer; const phrases : SentenceGeneratorTypes.ContextPhrase[] = []; const descriptions : SentenceGeneratorRuntime.ReplacedResult[] = []; const results = ctx.results!; for (let index = 0; index < results.length; index++) { const value = results[index].value.id; if (!value) break; const description = describer.describeArg(value); if (!description) break; descriptions.push(description); } phrases.push(...descriptions.slice(0, 3).map((d, i) => makeNameContextPhrase(ctx, d, results[i].value.id))); if (descriptions.length <= 1) return phrases; // add a name list of size 2, one of size 3, and one that includes all // names in the list // the last one will be used to support arbitrary slices if (descriptions.length > 2) phrases.push(makeOneNameListContextPhrase(ctx, descriptions, 2)); if (descriptions.length > 3) phrases.push(makeOneNameListContextPhrase(ctx, descriptions, 3)); phrases.push(makeOneNameListContextPhrase(ctx, descriptions, descriptions.length)); return phrases; } function getQuery(expr : Ast.Expression) : Ast.Expression|null { if (expr instanceof Ast.ChainExpression) return getQuery(expr.last); if (expr.schema!.functionType === 'query') return expr; if (expr instanceof Ast.ProjectionExpression || expr instanceof Ast.FilterExpression || expr instanceof Ast.MonitorExpression) return getQuery(expr.expression); return null; } const _warned = new Set<string>(); export function getUserContextPhrases(ctx : ContextInfo) : SentenceGeneratorTypes.ContextPhrase[] { const phrases : SentenceGeneratorTypes.ContextPhrase[] = []; getContextPhrasesCommon(ctx, phrases); return phrases; } export function getAgentContextPhrases(ctx : ContextInfo) : SentenceGeneratorTypes.ContextPhrase[] { const contextTable = ctx.contextTable; const phrases : SentenceGeneratorTypes.ContextPhrase[] = []; const describer = ctx.loader.describer; if (ctx.state.dialogueAct === 'notification') { if (ctx.state.dialogueActParam) { const appName = ctx.state.dialogueActParam[0]; assert(appName instanceof Ast.StringValue); phrases.push(makeValueContextPhrase(ctx, contextTable.ctx_notification_app_name, appName, describer.describeArg(appName)!)); } } // make phrases that describe the current and next action // these are used by the agent to form confirmations const current = ctx.current; if (current) { const description = describer.describeExpressionStatement(current.stmt); if (description !== null) { phrases.push(makeContextPhrase(contextTable.ctx_current_statement, ctx, description)); } else { const code = current.stmt.prettyprint(); if (!_warned.has(code)) { console.error(`WARNING: failed to generate description for ${code}`); _warned.add(code); } } const lastQuery = current.stmt.lastQuery ? getQuery(current.stmt.lastQuery) : null; if (lastQuery) { let description = describer.describeQuery(lastQuery); if (description !== null) description = description.constrain('plural', 'other'); if (description !== null) { phrases.push(makeExpressionContextPhrase(ctx, contextTable.ctx_current_query, lastQuery, description)); } } if (current.results!.error instanceof Ast.EnumValue) { phrases.push(...makeErrorContextPhrase(ctx, current.results!.error)); } else { const results = current.results!.results; if (results.length > 0) { const topResult = results[0]; phrases.push(...makeResultContextPhrase(ctx, topResult, results)); phrases.push(...makeNameListContextPhrases(ctx)); } else if (!current.results!.error) { phrases.push(...makeEmptyResultContextPhrase(ctx)); } } } const next = ctx.next; if (next) { const description = describer.describeExpressionStatement(next.stmt); if (description !== null) phrases.push(makeContextPhrase(contextTable.ctx_next_statement, ctx, description)); } getContextPhrasesCommon(ctx, phrases); return phrases; } function isMissingProjection(ctx : ContextInfo) { if (!ctx.resultInfo!.projection) return false; const topResult = ctx.results![0]; if (!topResult) return false; for (const p of ctx.resultInfo!.projection) { if (!topResult.value[p]) return true; } return false; } function getContextPhrasesCommon(ctx : ContextInfo, phrases : SentenceGeneratorTypes.ContextPhrase[]) { const contextTable = ctx.contextTable; if (ctx.state.dialogueAct === 'notification') phrases.push(makeContextPhrase(contextTable.ctx_with_notification, ctx)); if (ctx.state.dialogueAct === 'init') phrases.push(makeContextPhrase(contextTable.ctx_init, ctx)); if (ctx.isMultiDomain) phrases.push(makeContextPhrase(contextTable.ctx_multidomain, ctx)); if (ctx.nextInfo !== null) { phrases.push(makeContextPhrase(contextTable.ctx_with_action, ctx)); if (!ctx.nextInfo.isComplete) phrases.push(makeContextPhrase(contextTable.ctx_incomplete_action, ctx)); } else { if (ctx.resultInfo && ctx.resultInfo.isTable) phrases.push(makeContextPhrase(contextTable.ctx_without_action, ctx)); } if (!ctx.resultInfo || ctx.resultInfo.hasEmptyResult) return; if (ctx.resultInfo.hasStream && ctx.state.dialogueAct !== 'notification') return; if (isMissingProjection(ctx)) phrases.push(makeContextPhrase(contextTable.ctx_with_missing_projection, ctx)); assert(ctx.results && ctx.results.length > 0); phrases.push(makeContextPhrase(contextTable.ctx_with_result, ctx)); if (ctx.resultInfo.isTable && !ctx.resultInfo.isAggregation) phrases.push(makeContextPhrase(contextTable.ctx_with_table_result, ctx)); if (ctx.resultInfo.isAggregation) phrases.push(makeContextPhrase(contextTable.ctx_with_aggregation_result, ctx)); if (ctxCanHaveRelatedQuestion(ctx)) phrases.push(makeContextPhrase(contextTable.ctx_for_related_question, ctx)); if (isUserAskingResultQuestion(ctx)) { phrases.push(makeContextPhrase(contextTable.ctx_with_result_question, ctx)); } else { if (ctx.resultInfo.argMinMaxField) phrases.push(makeContextPhrase(contextTable.ctx_with_result_argminmax, ctx)); phrases.push(makeContextPhrase(contextTable.ctx_with_result_noquestion, ctx)); if (ctx.nextInfo) phrases.push(makeContextPhrase(contextTable.ctx_with_result_and_action, ctx)); if (ctx.resultInfo.projection === null) phrases.push(makeContextPhrase(contextTable.ctx_without_projection, ctx)); } } export { makeAgentReply, setEndBit, // manipulate states to create new states sortByName, makeSimpleState, addNewItem, addActionParam, addAction, addQuery, addQueryAndAction, mergeParameters, setOrAddInvocationParam, };
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, INodeExecutionData, INodeType, INodeTypeDescription, } from 'n8n-workflow'; import { vonageApiRequest, } from './GenericFunctions'; export class Vonage implements INodeType { description: INodeTypeDescription = { displayName: 'Vonage', name: 'vonage', icon: 'file:vonage.png', group: ['input'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume Vonage API', defaults: { name: 'Vonage', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'vonageApi', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'SMS', value: 'sms', }, ], default: 'sms', description: 'The resource to operate on.', }, { displayName: 'Operation', name: 'operation', type: 'options', options: [ { name: 'Send', value: 'send', }, ], displayOptions: { show: { resource: [ 'sms', ], }, }, default: 'send', description: 'The resource to operate on.', }, { displayName: 'From', name: 'from', type: 'string', displayOptions: { show: { resource: [ 'sms', ], operation: [ 'send', ], }, }, default: '', description: `The name or number the message should be sent from`, }, { displayName: 'To', name: 'to', type: 'string', displayOptions: { show: { resource: [ 'sms', ], operation: [ 'send', ], }, }, default: '', description: `The number that the message should be sent to. Numbers are specified in E.164 format.`, }, // { // displayName: 'Type', // name: 'type', // type: 'options', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // }, // }, // options: [ // { // name: 'Binary', // value: 'binary', // }, // { // name: 'Text', // value: 'text', // }, // { // name: 'Wappush', // value: 'wappush', // }, // { // name: 'Unicode', // value: 'unicode', // }, // { // name: 'VCAL', // value: 'vcal', // }, // { // name: 'VCARD', // value: 'vcard', // }, // ], // default: 'text', // description: 'The format of the message body', // }, // { // displayName: 'Binary Property', // name: 'binaryPropertyName', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'binary', // ], // }, // }, // type: 'string', // default: 'data', // description: 'Object property name which holds binary data.', // required: true, // }, // { // displayName: 'Body', // name: 'body', // type: 'string', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'binary', // ], // }, // }, // default: '', // description: 'Hex encoded binary data', // }, // { // displayName: 'UDH', // name: 'udh', // type: 'string', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'binary', // ], // }, // }, // default: '', // description: 'Your custom Hex encoded User Data Header', // }, // { // displayName: 'Title', // name: 'title', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'wappush', // ], // }, // }, // type: 'string', // default: '', // description: 'The title for a wappush SMS', // }, // { // displayName: 'URL', // name: 'url', // type: 'string', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'wappush', // ], // }, // }, // default: '', // description: 'The URL of your website', // }, // { // displayName: 'Validity (in minutes)', // name: 'validity', // type: 'number', // default: 0, // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'wappush', // ], // }, // }, // description: 'The availability for an SMS in minutes', // }, { displayName: 'Message', name: 'message', type: 'string', displayOptions: { show: { resource: [ 'sms', ], operation: [ 'send', ], // type: [ // 'text', // 'unicode', // ], }, }, default: '', description: `The body of the message being sent`, }, // { // displayName: 'VCard', // name: 'vcard', // type: 'string', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'vcard', // ], // }, // }, // default: '', // description: 'A business card in vCard format', // }, // { // displayName: 'VCal', // name: 'vcal', // type: 'string', // displayOptions: { // show: { // resource: [ // 'sms', // ], // operation: [ // 'send', // ], // type: [ // 'vcal', // ], // }, // }, // default: '', // description: 'A calendar event in vCal format', // }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'sms', ], operation: [ 'send', ], }, }, default: {}, options: [ { displayName: 'Account Ref', name: 'account-ref', type: 'string', default: '', description: 'An optional string used to identify separate accounts using the SMS endpoint for billing purposes. To use this feature, please email support@nexmo.com', }, { displayName: 'Callback', name: 'callback', type: 'string', default: '', description: 'The webhook endpoint the delivery receipt for this sms is sent to. This parameter overrides the webhook endpoint you set in Dashboard.', }, { displayName: 'Client Ref', name: 'client-ref', type: 'string', default: '', description: 'You can optionally include your own reference of up to 40 characters.', }, { displayName: 'Message Class', name: 'message-class', type: 'options', options: [ { name: '0', value: 0, }, { name: '1', value: 1, }, { name: '2', value: 2, }, { name: '3', value: 3, }, ], default: '', description: 'The Data Coding Scheme value of the message', }, { displayName: 'Protocol ID', name: 'protocol-id', type: 'string', default: '', description: 'The value of the protocol identifier to use. Ensure that the value is aligned with udh.', }, { displayName: 'Status Report Req', name: 'status-report-req', type: 'boolean', default: false, description: 'Boolean indicating if you like to receive a Delivery Receipt.', }, { displayName: 'TTL (in minutes)', name: 'ttl', type: 'number', default: 4320, description: 'By default Nexmo attempt delivery for 72 hours', }, ], }, ], }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const length = (items.length as unknown) as number; const qs: IDataObject = {}; let responseData; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; for (let i = 0; i < length; i++) { try { if (resource === 'sms') { if (operation === 'send') { const from = this.getNodeParameter('from', i) as string; const to = this.getNodeParameter('to', i) as string; const type = this.getNodeParameter('type', i, 'text') as string; const body: IDataObject = { from, to, type, }; if (type === 'text' || type === 'unicode') { const message = this.getNodeParameter('message', i) as string; body.text = message; } if (type === 'binary') { const data = this.getNodeParameter('body', i) as string; const udh = this.getNodeParameter('udh', i) as string; body.udh = udh; body.body = data; } if (type === 'wappush') { const title = this.getNodeParameter('title', i) as string; const url = this.getNodeParameter('url', i) as string; const validity = this.getNodeParameter('validity', i) as number; body.title = title; body.url = url; body.validity = validity * 60000; } if (type === 'vcard') { const vcard = this.getNodeParameter('vcard', i) as string; body.vcard = vcard; } if (type === 'vcal') { const vcal = this.getNodeParameter('vcal', i) as string; body.vcal = vcal; } const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); if (body.ttl) { // transform minutes to milliseconds body.ttl = (body.ttl as number) * 60000; } responseData = await vonageApiRequest.call(this, 'POST', '/sms/json', body); responseData = responseData.messages; } } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } if (Array.isArray(responseData)) { returnData.push.apply(returnData, responseData as IDataObject[]); } else if (responseData !== undefined) { returnData.push(responseData as IDataObject); } } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import * as React from 'react'; import {APLRendererWindow, APLRendererWindowState, WebsocketConnectionWrapper} from './components/APLRendererWindow'; import {SampleHome} from './components/SampleHome'; import {NavigationEvent} from './lib/messages/NavigationEvent'; import {Client, IClient, IClientConfig} from './lib/messages/client'; import { AlexaState, CallState, IActivityReportMessage, IAlexaStateChangedMessage, IAPLCoreMessage, IAPLRenderMessage, IAuthorizationChangeMessage, IBaseInboundMessage, IBaseOutboundMessage, ICallStateChangeMessage, IClearDocumentMessage, IDeviceWindowStateMessage, IDoNotDisturbSettingChangedMessage, IFocusAcquireRequestMessage, IFocusReleaseRequestMessage, IFocusResponseMessage, IGuiConfigurationMessage, IInitRequest, IInitResponse, ILocaleChangeMessage, INavigationReportMessage, IOnFocusChangedMessage, IOnFocusChangedReceivedConfirmationMessage, IRenderCaptionsMessage, IRenderPlayerInfoMessage, IRenderStaticDocumentMessage, IRenderTemplateMessage, IRequestAuthorizationMessage, OutboundMessageType } from './lib/messages/messages'; import {PlayerInfoWindow, RENDER_PLAYER_INFO_WINDOW_ID} from './components/PlayerInfoWindow'; import {CommsWindow} from './components/CommsWindow'; import {resolveRenderTemplate} from './lib/displayCards/AVSDisplayCardHelpers'; import {SDKLogTransport} from './lib/messages/sdkLogTransport'; import {ILogger, LoggerFactory} from 'apl-client'; import {FocusManager} from './lib/focus/FocusManager'; import {ActivityTracker} from './lib/activity/ActivityTracker'; import {ActivityEvent} from './lib/activity/ActivityEvent'; import {VoiceChrome} from './components/VoiceChrome'; import {AudioInputInitiator, IDeviceAppConfig} from './lib/config/IDeviceAppConfig'; import {IDisplayPixelDimensions} from './lib/config/visualCharacteristics/IDeviceDisplay'; import {resolveDeviceAppConfig, resolveDeviceWindowState} from './lib/config/GuiConfigHelpers'; import {IWindowState} from './lib/config/visualCharacteristics/IWindowState'; import {UWPWebViewClient} from './lib/messages/UWPClient'; import {CaptionsView} from './components/CaptionsView'; import {LocaleManager} from './lib/utils/localeManager'; const HOST = 'localhost'; const PORT = 8933; /// Maximum APL version supported by the runtime. const APL_MAX_VERSION = '1.7'; /// The minimum SmartScreenSDK version required for this runtime. const SMART_SCREEN_SDK_MIN_VERSION = '2.8'; /// Indicates whether the SDK has built with WebSocket SSL Disabled. declare const DISABLE_WEBSOCKET_SSL : boolean; /// Indicates whether to use the UWP client declare const USE_UWP_CLIENT : boolean; export interface IAppState { alexaState : AlexaState; callStateInfo : ICallStateChangeMessage; targetWindowId : string; playerInfoMessage : IRenderPlayerInfoMessage; updateActiveAPLRendererWindow : boolean; captionsMessage : IRenderCaptionsMessage; doNotDisturbSettingEnabled : boolean; clearWindow : boolean; } export class App extends React.Component<any, IAppState> { protected rootDiv : HTMLElement; protected deviceAppConfig : IDeviceAppConfig; protected windowState : IWindowState; protected client : IClient; protected aplConnection : WebsocketConnectionWrapper; protected logger : ILogger; protected focusManager : FocusManager; protected activityTracker : ActivityTracker; protected talkButtonDownMessage : OutboundMessageType; protected talkButtonUpMessage : OutboundMessageType; protected eventListenersAdded : boolean; private captionFrame : any; private lastCaptionTimeOutId : number; private toggleCaptionsMessage : OutboundMessageType = 'toggleCaptions'; private toggleDoNotDisturbMessage : OutboundMessageType = 'toggleDoNotDisturb'; private lastRenderedWindowId : string; private aplCoreMessageHandlers : Map<string, (message : IAPLCoreMessage) => void> = new Map(); /** * Compare two versions as strings. * * @param v1 First version to compare. * @param v2 Second version to compare. * @return n, where n<0 if v1<v2, n=0 if v1=v2 and n>0 if v1>v2 */ protected compareVersions(v1 : string, v2 : string) : number { if (!v1) { return -1; } if (!v2) { return 1; } const v1Arr : string[] = v1.split('.'); const v2Arr : string[] = v2.split('.'); for (let i = 0; i < Math.min(v1Arr.length, v2Arr.length); i++) { if (Number(v1Arr[i]) < Number(v2Arr[i])) { return -1; } else if (Number(v1Arr[i]) > Number(v2Arr[i])) { return 1; } } // The longest one is bigger return v1Arr.length - v2Arr.length; } protected handleInitRequest(message : IBaseInboundMessage) { const initRequestMessage : IInitRequest = message as IInitRequest; this.logger.debug(`message: ${JSON.stringify(initRequestMessage)}`); let smartScreenSDKVer = initRequestMessage.smartScreenSDKVersion; this.logger.debug(`APL version: ${APL_MAX_VERSION} SDKVer: ${smartScreenSDKVer}`); const isSupported : boolean = (this.compareVersions(SMART_SCREEN_SDK_MIN_VERSION, smartScreenSDKVer) <= 0); this.sendInitResponse(isSupported, APL_MAX_VERSION); } protected handleRenderCaptions(message : IBaseInboundMessage) { this.captionFrame = JSON.parse(JSON.stringify((message as IRenderCaptionsMessage).payload)); clearTimeout(this.lastCaptionTimeOutId); this.setState({ captionsMessage : this.captionFrame }); this.lastCaptionTimeOutId = window.setTimeout(this.clearCaptions, this.captionFrame.duration); } protected handleDoNotDisturbSettingChanged(message : IBaseInboundMessage) { const newDoNotDisturbSettingEnabled = (message as IDoNotDisturbSettingChangedMessage).doNotDisturbSettingEnabled; this.setState({ doNotDisturbSettingEnabled : newDoNotDisturbSettingEnabled }); } protected clearCaptions = () => { this.setState({ captionsMessage : undefined }); } protected handleRenderTemplateMessage(message : IBaseInboundMessage) { const renderTemplateMessage : IRenderTemplateMessage = message as IRenderTemplateMessage; const renderStaticDocumentMessage : IRenderStaticDocumentMessage = resolveRenderTemplate(renderTemplateMessage, this.deviceAppConfig.renderTemplateWindowId); this.client.sendMessage(renderStaticDocumentMessage); } protected handleRenderPlayerInfoMessage(message : IBaseInboundMessage) { const renderPlayerInfoMessage : IRenderPlayerInfoMessage = message as IRenderPlayerInfoMessage; this.setState({ playerInfoMessage : renderPlayerInfoMessage }); } protected handleAPLRender(message : IAPLRenderMessage) { let targetWindowId : string = message.windowId ? message.windowId : this.deviceAppConfig.defaultWindowId; // Setting the token on the displaying window this.setTokenForWindowId(message.token, targetWindowId); this.lastRenderedWindowId = targetWindowId; this.setState((prevState, props) => ({ targetWindowId, updateActiveAPLRendererWindow: true }) ); // Make sure the active window only updates once. this.setState({ updateActiveAPLRendererWindow: false }); } protected handleAPLCore(message : IAPLCoreMessage) { const windowId : string = message.windowId ? message.windowId : this.deviceAppConfig.defaultWindowId; let aplCoreMessageHandler = this.aplCoreMessageHandlers.get(windowId); if (aplCoreMessageHandler !== undefined) { aplCoreMessageHandler(message); } } protected handleAlexaStateChangedMessage(message : IBaseInboundMessage) { const alexaStateChangedMessage : IAlexaStateChangedMessage = message as IAlexaStateChangedMessage; this.setState((prevState, props) => { return { alexaState: alexaStateChangedMessage.state }; }); } protected handleCallStateChangeMessage(message : IBaseInboundMessage) { const callStateChangeMessage : ICallStateChangeMessage = message as ICallStateChangeMessage; this.setState((prevState, props) => { return { callStateInfo: callStateChangeMessage }; }); } protected handleRequestAuthorization(requestAuthorizationMessage : IRequestAuthorizationMessage) { /** * Use to present CBL authorization. * API : * https://developer.amazon.com/docs/alexa-voice-service/code-based-linking-other-platforms.html * Design Guidance : * https://developer.amazon.com/docs/alexa-voice-service/setup-authentication.html#code-based-screens */ } protected handleAuthorizationStateChanged(authStateChangeMessage : IAuthorizationChangeMessage) { // Use to drive app behavior based on authorization state changes. } protected handleFocusResponse(message : IBaseInboundMessage) { const focusResponse : IFocusResponseMessage = message as IFocusResponseMessage; this.focusManager.processFocusResponse(focusResponse.token, focusResponse.result); } protected handleClearPlayerInfoWindow() { this.setState({ targetWindowId : undefined, playerInfoMessage : undefined }); } protected handleClearNonPlayerInfoWindow(message : IClearDocumentMessage) { // Clearing the token on the displaying window this.setTokenForWindowId(null, this.state.targetWindowId); this.setState({ targetWindowId : message.windowId, clearWindow: true }); // Make sure clearWindow only updates once. this.setState({ targetWindowId : undefined, clearWindow: false }); } protected handleOnFocusChanged(message : IBaseInboundMessage) { const focusChanged : IOnFocusChangedMessage = message as IOnFocusChangedMessage; // Message received, notify C++ bridge, then process this.sendOnFocusChangedReceivedConfirmation(focusChanged.token); this.focusManager.processFocusChanged(focusChanged.token, focusChanged.channelState); } protected handleGuiConfigurationMessage(message : IBaseInboundMessage) { const guiConfigurationMessage : IGuiConfigurationMessage = message as IGuiConfigurationMessage; this.deviceAppConfig = resolveDeviceAppConfig( window.innerWidth, window.innerHeight, guiConfigurationMessage.payload, this.logger); this.windowState = resolveDeviceWindowState(this.deviceAppConfig); switch (this.deviceAppConfig.audioInputInitiator) { case AudioInputInitiator.PRESS_AND_HOLD : { this.talkButtonDownMessage = 'holdToTalk'; this.talkButtonUpMessage = 'holdToTalk'; break; } case AudioInputInitiator.TAP : { this.talkButtonDownMessage = 'tapToTalk'; this.talkButtonUpMessage = undefined; break; } default : { break; } } if (!this.eventListenersAdded) { this.eventListenersAdded = true; document.addEventListener('keydown', this.handleKeyDown.bind(this)); document.addEventListener('keyup', this.handleKeyUp.bind(this)); document.addEventListener('touchstart', this.handleUserInterruption.bind(this)); document.addEventListener('mousedown', this.handleUserInterruption.bind(this)); document.addEventListener('wheel', this.handleUserInterruption.bind(this), {capture: true, passive: true}); } this.sendDeviceWindowState(); // Using setState to re render after gathering all necessary device configurations. this.setState({}); } protected handleLocaleChangeMessage(message : ILocaleChangeMessage) { /** * Use to implement UI changes when Alexa locale changes: * https://developer.amazon.com/en-US/docs/alexa/alexa-voice-service/system.html#setlocales */ LocaleManager.setLocales(message.locales); } protected onClientMessage(message : IBaseInboundMessage) { switch (message.type) { case 'initRequest': { this.handleInitRequest(message); break; } case 'guiConfiguration': { this.handleGuiConfigurationMessage(message); break; } case 'requestAuthorization' : { this.handleRequestAuthorization(message as IRequestAuthorizationMessage); break; } case 'authorizationChange' : { this.handleAuthorizationStateChanged(message as IAuthorizationChangeMessage); break; } case 'alexaStateChanged': { this.handleAlexaStateChangedMessage(message); break; } case 'callStateChange': { this.handleCallStateChangeMessage(message); break; } case 'focusResponse': { this.handleFocusResponse(message); break; } case 'onFocusChanged' : { this.handleOnFocusChanged(message); break; } case 'renderTemplate': { this.handleRenderTemplateMessage(message); break; } case 'renderPlayerInfo': { this.handleRenderPlayerInfoMessage(message); break; } case 'clearPlayerInfoCard': { this.handleClearPlayerInfoWindow(); break; } case 'clearDocument': case 'clearTemplateCard': { this.handleClearNonPlayerInfoWindow(message as IClearDocumentMessage); break; } case 'aplRender': { this.handleAPLRender(message as IAPLRenderMessage); break; } case 'aplCore': { this.handleAPLCore(message as IAPLCoreMessage); break; } case 'renderCaptions': { this.handleRenderCaptions(message); break; } case 'doNotDisturbSettingChanged': { this.handleDoNotDisturbSettingChanged(message); break; } case 'localeChange': { this.handleLocaleChangeMessage(message as ILocaleChangeMessage); break; } default: { this.logger.warn('received message with unsupported type. Type: ', message.type); break; } } } constructor(props : any) { super(props); // NOTE: No logging should happen before here! LoggerFactory.initialize('info', SDKLogTransport.logFunction); this.logger = LoggerFactory.getLogger('App'); this.rootDiv = document.getElementById('root'); this.focusManager = new FocusManager({ acquireFocus: this.sendFocusAcquireRequest.bind(this), releaseFocus: this.sendFocusReleaseRequest.bind(this) }); this.activityTracker = new ActivityTracker(this.sendActivityEvent.bind(this)); const clientConfig : IClientConfig = { host : HOST, port : PORT, onMessage : this.onClientMessage.bind(this), insecure : DISABLE_WEBSOCKET_SSL }; if (USE_UWP_CLIENT) { this.client = new UWPWebViewClient(clientConfig); } else { this.client = new Client(clientConfig); } this.aplConnection = new WebsocketConnectionWrapper(this.client); SDKLogTransport.initialize(this.client); const callStateMessage : ICallStateChangeMessage = { type: undefined, callState: CallState.NONE, callType: undefined, previousSipUserAgentState: undefined, currentSipUserAgentState: undefined, displayName: undefined, endpointLabel: undefined, inboundCalleeName: undefined, callProviderType: undefined, inboundRingtoneUrl: undefined, outboundRingbackUrl: undefined, isDropIn: false }; this.state = { alexaState : AlexaState.IDLE, callStateInfo : callStateMessage, playerInfoMessage : undefined, updateActiveAPLRendererWindow : false, targetWindowId : undefined, captionsMessage : undefined, doNotDisturbSettingEnabled : undefined, clearWindow: false }; this.eventListenersAdded = false; } protected sendInitResponse(isSupported : boolean, APLMaxVersion : string) { const message : IInitResponse = { type : 'initResponse', isSupported, APLMaxVersion }; this.client.sendMessage(message); } protected sendFocusAcquireRequest(channelName : string, token : number) { const message : IFocusAcquireRequestMessage = { type : 'focusAcquireRequest', token, channelName }; this.client.sendMessage(message); } protected sendFocusReleaseRequest(channelName : string, token : number) { const message : IFocusReleaseRequestMessage = { type : 'focusReleaseRequest', token, channelName }; this.client.sendMessage(message); } protected sendOnFocusChangedReceivedConfirmation(token : number) { const message : IOnFocusChangedReceivedConfirmationMessage = { type : 'onFocusChangedReceivedConfirmation', token }; this.client.sendMessage(message); } protected sendTalkButtonEvent(type : OutboundMessageType) { if (type === undefined) { return; } const message : IBaseOutboundMessage = { type }; this.client.sendMessage(message); } protected sendToggleCaptionsEvent(type : OutboundMessageType) { if (type === undefined) { return; } const message : IBaseOutboundMessage = { type }; this.client.sendMessage(message); } protected sendToggleDoNotDisturbEvent(type : OutboundMessageType) { if (type === undefined) { return; } const message : IBaseOutboundMessage = { type }; this.client.sendMessage(message); } protected sendActivityEvent(event : ActivityEvent) { if (this.state.targetWindowId === undefined) { return; } const message : IActivityReportMessage = { type : 'activityEvent', event }; this.client.sendMessage(message); } protected sendNavigationEvent(event : NavigationEvent) { const message : INavigationReportMessage = { type : 'navigationEvent', event }; this.client.sendMessage(message); } protected sendDeviceWindowState() { const deviceWindowStateMessage : IDeviceWindowStateMessage = { type : 'deviceWindowState', payload : this.windowState }; this.client.sendMessage(deviceWindowStateMessage); } public render() { if (!this.deviceAppConfig) { return ( <div id='displayContainer'> <SampleHome/> </div> ); } // PlayerInfo Window const playerInfo = <PlayerInfoWindow playerInfoMessage={this.state.playerInfoMessage} targetWindowId={this.state.targetWindowId} refreshRenderer={ this.state.targetWindowId === RENDER_PLAYER_INFO_WINDOW_ID && this.state.updateActiveAPLRendererWindow} windowConfig={this.deviceAppConfig.renderPlayerInfoWindowConfig} client={this.aplConnection} focusManager={this.focusManager} activityTracker={this.activityTracker} aplCoreMessageHandlerCallback={this.setAPLCoreMessageHandler.bind(this)} />; // Comms Window const commsWindow = <CommsWindow callStateInfo = {this.state.callStateInfo} client={this.client} />; // Create APL Renderer Windows from GUI App Config const aplRendererWindows = this.deviceAppConfig.rendererWindowConfigs.map((window) => { return ( <APLRendererWindow id={window.id} key={window.id} windowConfig={window} clearRenderer={ window.id === this.state.targetWindowId && this.state.clearWindow} refreshRenderer={ window.id === this.state.targetWindowId && this.state.updateActiveAPLRendererWindow} client={this.aplConnection} focusManager={this.focusManager} activityTracker={this.activityTracker} aplCoreMessageHandlerCallback={this.setAPLCoreMessageHandler.bind(this)} /> ); }); return ( <div id='displayContainer' style={this.getDisplayStyle()}> <SampleHome deviceAppConfig={this.deviceAppConfig} /> {playerInfo} {commsWindow} {aplRendererWindows} <VoiceChrome deviceAppConfig={this.deviceAppConfig} targetWindowId={this.state.targetWindowId} alexaState={this.state.alexaState} doNotDisturbSettingEnabled={this.state.doNotDisturbSettingEnabled} /> <CaptionsView captionsMessage={this.state.captionsMessage} /> </div> ); } public setAPLCoreMessageHandler(windowId : string, aplCoreMessageHandler : (message : IAPLCoreMessage) => void) { this.aplCoreMessageHandlers.set(windowId, aplCoreMessageHandler); } protected getDisplayStyle() : any { let scale = 1; let height : any = '100%'; let width : any = '100%'; let clipPath : string = 'none'; if (this.deviceAppConfig.emulateDisplayDimensions) { const displayPixelDimensions = this.deviceAppConfig.display.dimensions as IDisplayPixelDimensions; height = displayPixelDimensions.resolution.value.height; width = displayPixelDimensions.resolution.value.width; clipPath = this.deviceAppConfig.display.shape === 'ROUND' ? 'circle(50%)' : clipPath; if (this.deviceAppConfig.scaleToFill) { scale = Math.min(window.innerWidth / width, window.innerHeight / height); } } const displayStyle = { height, width, transform : 'scale(' + scale + ')', clipPath }; return displayStyle; } protected lastKeyDownCode : string; private handleKeyDown(event : any) { if (USE_UWP_CLIENT) { this.convertUwpKeyboardEvent(event); } // Only handle key down events once if (event.code === this.lastKeyDownCode) { return; } switch (event.code) { // Press talk key to start audio recognition case this.deviceAppConfig.deviceKeys.talkKey.code : { this.sendTalkButtonEvent(this.talkButtonDownMessage); break; } // Similar to EXIT button pressed on remote case this.deviceAppConfig.deviceKeys.exitKey.code: this.sendNavigationEvent(NavigationEvent.EXIT); break; // Similar to BACK button pressed on remote case this.deviceAppConfig.deviceKeys.backKey.code: this.sendNavigationEvent(NavigationEvent.BACK); break; // Similar to toggle options setting on remote case this.deviceAppConfig.deviceKeys.toggleCaptionsKey.code: this.sendToggleCaptionsEvent(this.toggleCaptionsMessage); break; // Similar to toggle Do Not Disturb setting on remote case this.deviceAppConfig.deviceKeys.toggleDoNotDisturbKey.code: this.sendToggleDoNotDisturbEvent(this.toggleDoNotDisturbMessage); break; // All KeyDown events trigger user interruption default : { this.handleUserInterruption(); break; } } this.lastKeyDownCode = event.code; } private handleKeyUp(event : any) { if (USE_UWP_CLIENT) { this.convertUwpKeyboardEvent(event); } this.lastKeyDownCode = undefined; switch (event.code) { // Release talk key to stop audio recognition on PRESS_AND_HOLD integrations case this.deviceAppConfig.deviceKeys.talkKey.code: { this.sendTalkButtonEvent(this.talkButtonUpMessage); break; } default : { break; } } } /** * Boolean tracking locked state of user interruption event handling. */ private interruptionLock = false; /** The interrupted event is reported when an user interaction interrupts an activity. * Examples include keyDown events, clicks, touches, and scrolls. * Some of these user interactions results in multiple events per user interaction, such * as scrolling. Even when multiple events are fired, the interrupted event only needs to be * reported once in a set time period. This implementation will report a maximum of one * interrupted activity every 500 ms. */ private handleUserInterruption() { if (!this.interruptionLock) { this.interruptionLock = true; this.activityTracker.reportInterrupted(); window.setTimeout(() => { this.interruptionLock = false; }, 500); } } private setTokenForWindowId(token : string, windowId : string) { for (let window of this.windowState.instances) { if (window.id === windowId) { window.token = token; break; } } this.sendDeviceWindowState(); } public componentDidMount() { this.client.connect(); } private convertUwpKeyboardEvent(event : any) { /** * Since KeyboardEvents emitted by UWP WebView do not have code property populated, * we have to populate them manually */ switch (event.key) { case this.deviceAppConfig.deviceKeys.talkKey.key : event.code = this.deviceAppConfig.deviceKeys.talkKey.code; break; case this.deviceAppConfig.deviceKeys.exitKey.key: event.code = this.deviceAppConfig.deviceKeys.exitKey.code; break; case this.deviceAppConfig.deviceKeys.backKey.key: event.code = this.deviceAppConfig.deviceKeys.backKey.code; break; case this.deviceAppConfig.deviceKeys.toggleCaptionsKey.key: event.code = this.deviceAppConfig.deviceKeys.toggleCaptionsKey.code; break; case this.deviceAppConfig.deviceKeys.toggleDoNotDisturbKey.key: event.code = this.deviceAppConfig.deviceKeys.toggleDoNotDisturbKey.code; break; default : { break; } } } }
the_stack
import * as TKUnit from '../../tk-unit'; import * as helper from '../../ui-helper'; import { Application, Label, Page, StackLayout, WrapLayout, LayoutBase, View, KeyedTemplate, GestureTypes, Repeater, ObservableArray } from '@nativescript/core'; var FEW_ITEMS = [0, 1, 2]; var MANY_ITEMS = []; for (var i = 0; i < 100; i++) { MANY_ITEMS[i] = i; } const ITEM_TEMPLATES_STRING = ` <template key="red"> <Label text='red' style.backgroundColor='red' minHeight='100' maxHeight='100'/> </template> <template key='green'> <Label text='green' style.backgroundColor='green' minHeight='100' maxHeight='100'/> </template> <template key='blue'> <Label text='blue' style.backgroundColor='blue' minHeight='100' maxHeight='100'/> </template> `; export function test_recycling() { const setters = new Map<string, StackLayout>(); setters.set('itemsLayout', new StackLayout()); helper.nativeView_recycling_test(() => new Repeater(), null, null, setters); } export function test_set_items_to_array_loads_all_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { // >> article-repeater-with-array var colors = ['red', 'green', 'blue']; repeater.items = colors; // << article-repeater-with-array TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assert(getChildAtText(repeater, 0) === 'red', 'Item not created for index 0'); TKUnit.assert(getChildAtText(repeater, 1) === 'green', 'Item not created for index 1'); TKUnit.assert(getChildAtText(repeater, 2) === 'blue', 'Item not created for index 2'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_items_to_array_creates_views() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.items = FEW_ITEMS; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), FEW_ITEMS.length, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_refresh_after_adding_items_to_array_loads_new_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { var colors = ['red', 'green', 'blue']; repeater.items = colors; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), colors.length, 'views count.'); // >> artcle-array-push-element colors.push('yellow'); // Manually trigger the update so that the new color is shown. repeater.refresh(); // << artcle-array-push-element // TKUnit.wait(ASYNC); TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), colors.length, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_refresh_reloads_all_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { var testStarted = false; var itemsToBind = <Array<any>>FEW_ITEMS; repeater.items = itemsToBind; TKUnit.waitUntilReady(() => repeater.isLayoutValid); testStarted = true; itemsToBind[0] = 'red'; itemsToBind[1] = 'green'; itemsToBind[2] = 'blue'; repeater.refresh(); TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assert(getChildAtText(repeater, 0) === 'red', 'Item not created for index 0'); TKUnit.assert(getChildAtText(repeater, 1) === 'green', 'Item not created for index 1'); TKUnit.assert(getChildAtText(repeater, 2) === 'blue', 'Item not created for index 2'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_itmes_to_null_clears_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.items = FEW_ITEMS; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), FEW_ITEMS.length, 'views count.'); repeater.items = null; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 0, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_itemsLayout_accepted() { // >> article-repeater-layout var repeater = new Repeater(); var stackLayout = new StackLayout(); stackLayout.orientation = 'horizontal'; repeater.itemsLayout = stackLayout; // << article-repeater-layout function testAction(views: Array<View>) { repeater.items = FEW_ITEMS; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assert((<StackLayout>repeater.itemsLayout).orientation === 'horizontal', 'views count.'); TKUnit.assertEqual(getChildrenCount(repeater), FEW_ITEMS.length, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_itmes_to_undefiend_clears_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.items = FEW_ITEMS; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), FEW_ITEMS.length, 'views count.'); repeater.items = undefined; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 0, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_itmes_to_different_source_loads_new_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.items = [1, 2, 3]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 3, 'views count.'); repeater.items = ['a', 'b', 'c', 'd']; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 4, 'views count.'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_set_items_to_observable_array_loads_all_items() { var repeater = new Repeater(); function testAction(views: Array<View>) { // >> article-repeater-observablearray var colors = new ObservableArray(['red', 'green', 'blue']); repeater.items = colors; // << article-repeater-observablearray TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assert(getChildAtText(repeater, 0) === 'red', 'Item not created for index 0'); TKUnit.assert(getChildAtText(repeater, 1) === 'green', 'Item not created for index 1'); TKUnit.assert(getChildAtText(repeater, 2) === 'blue', 'Item not created for index 2'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_add_to_observable_array_refreshes_the_Repeater() { var repeater = new Repeater(); function testAction(views: Array<View>) { var colors = new ObservableArray(['red', 'green', 'blue']); repeater.items = colors; TKUnit.assertEqual(getChildrenCount(repeater), 3, 'getChildrenCount'); // >> article-push-to-observablearray colors.push('yellow'); // The Repeater will be updated automatically. // << article-push-to-observablearray TKUnit.assertEqual(getChildrenCount(repeater), 4, 'getChildrenCount'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_remove_from_observable_array_refreshes_the_Repeater() { var repeater = new Repeater(); var data = new ObservableArray([1, 2, 3]); function testAction(views: Array<View>) { repeater.items = data; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 3, 'getChildrenCount'); data.pop(); TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 2, 'getChildrenCount'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_splice_observable_array_refreshes_the_Repeater() { var repeater = new Repeater(); var data = new ObservableArray(['a', 'b', 'c']); function testAction(views: Array<View>) { repeater.items = data; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 3, 'getChildrenCount'); // Remove the first 2 elements and add data.splice(0, 2, 'd', 'e', 'f'); TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 4, 'getChildrenCount'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_usingAppLevelConvertersInRepeaterItems() { var repeater = new Repeater(); var dateConverter = function (value, format) { var result = format; var day = value.getDate(); result = result.replace('DD', month < 10 ? '0' + day : day); var month = value.getMonth() + 1; result = result.replace('MM', month < 10 ? '0' + month : month); result = result.replace('YYYY', value.getFullYear()); return result; }; Application.getResources()['dateConverter'] = dateConverter; var data = new ObservableArray(); data.push({ date: new Date() }); function testAction(views: Array<View>) { repeater.itemTemplate = '<Label id="testLabel" text="{{ date, date | dateConverter(\'DD.MM.YYYY\') }}" />'; repeater.items = data; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildAtText(repeater, 0), dateConverter(new Date(), 'DD.MM.YYYY'), 'element'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_BindingRepeaterToASimpleArray() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplate = '<Label id="testLabel" text="{{ $value }}" />'; repeater.items = [1, 2, 3]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildAtText(repeater, 0), '1', 'first element text'); TKUnit.assertEqual(getChildAtText(repeater, 1), '2', 'second element text'); TKUnit.assertEqual(getChildAtText(repeater, 2), '3', 'third element text'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_ItemTemplateFactoryFunction() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplate = () => { var label = new Label(); label.id = 'testLabel'; label.bind({ sourceProperty: '$value', targetProperty: 'text', twoWay: false }); return label; }; repeater.items = [1, 2, 3]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildAtText(repeater, 0), '1', 'first element text'); TKUnit.assertEqual(getChildAtText(repeater, 1), '2', 'second element text'); TKUnit.assertEqual(getChildAtText(repeater, 2), '3', 'third element text'); } helper.buildUIAndRunTest(repeater, testAction); } // Multiple item templates tests export function test_ItemTemplateSelector_WhenWrongTemplateKeyIsSpecified_TheDefaultTemplateIsUsed() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplate = "<Label text='default' minHeight='100' maxHeight='100'/>"; repeater.itemTemplates = ITEM_TEMPLATES_STRING; repeater.itemTemplateSelector = "age == 20 ? 'wrong' : 'green'"; repeater.items = [{ age: 20 }, { age: 25 }]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); const firstElement = getChildAt(repeater, 0); TKUnit.assertEqual((<Label>firstElement).text, 'default', 'first element text'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_ItemTemplateSelector_IsCorrectlyParsedFromString() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplates = ITEM_TEMPLATES_STRING; repeater.itemTemplateSelector = "age < 25 ? 'red' : 'green'"; repeater.items = [{ age: 20 }, { age: 25 }]; let itemTemplateSelectorFunction = <any>repeater.itemTemplateSelector; TKUnit.waitUntilReady(() => repeater.isLayoutValid); let templateKey0 = itemTemplateSelectorFunction(repeater.items[0], 0, repeater.items); TKUnit.assertEqual(templateKey0, 'red', 'itemTemplateSelector result for first item'); let templateKey1 = itemTemplateSelectorFunction(repeater.items[1], 1, repeater.items); TKUnit.assertEqual(templateKey1, 'green', 'itemTemplateSelector result for second item'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_ItemTemplateSelector_IsCorrectlyUsedAsAFunction() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplates = ITEM_TEMPLATES_STRING; repeater.itemTemplateSelector = function (item, index: number, items) { return item.age < 25 ? 'red' : 'green'; }; repeater.items = [{ age: 20 }, { age: 25 }]; let itemTemplateSelectorFunction = <any>repeater.itemTemplateSelector; TKUnit.waitUntilReady(() => repeater.isLayoutValid); let templateKey0 = itemTemplateSelectorFunction(repeater.items[0], 0, repeater.items); TKUnit.assertEqual(templateKey0, 'red', 'itemTemplateSelector result for first item'); let templateKey1 = itemTemplateSelectorFunction(repeater.items[1], 1, repeater.items); TKUnit.assertEqual(templateKey1, 'green', 'itemTemplateSelector result for second item'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_ItemTemplateSelector_ItemTemplatesAreCorrectlyParsedFromString() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplates = ITEM_TEMPLATES_STRING; TKUnit.waitUntilReady(() => repeater.isLayoutValid); let itemTemplatesArray = <any>repeater.itemTemplates; TKUnit.assertEqual(itemTemplatesArray.length, 3, 'itemTemplates array length'); let template0 = <KeyedTemplate>itemTemplatesArray[0]; TKUnit.assertEqual(template0.key, 'red', 'template0.key'); TKUnit.assertEqual((<Label>template0.createView()).text, 'red', 'template0 created view text'); let template1 = <KeyedTemplate>itemTemplatesArray[1]; TKUnit.assertEqual(template1.key, 'green', 'template1.key'); TKUnit.assertEqual((<Label>template1.createView()).text, 'green', 'template1 created view text'); let template2 = <KeyedTemplate>itemTemplatesArray[2]; TKUnit.assertEqual(template2.key, 'blue', 'template2.key'); TKUnit.assertEqual((<Label>template2.createView()).text, 'blue', 'template2 created view text'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_ItemTemplateSelector_CorrectTemplateIsUsed() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplates = ITEM_TEMPLATES_STRING; repeater.itemTemplateSelector = "age == 25 ? 'green' : 'red'"; repeater.items = [{ age: 20 }, { age: 25 }]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); const firstElement = getChildAt(repeater, 0); const secondElement = getChildAt(repeater, 1); TKUnit.assertEqual((<Label>firstElement).text, 'red', 'first element text'); TKUnit.assertEqual((<Label>secondElement).text, 'green', 'second element text'); } helper.buildUIAndRunTest(repeater, testAction); } export function test_BindingRepeaterToASimpleArrayWithExpression() { var repeater = new Repeater(); function testAction(views: Array<View>) { repeater.itemTemplate = '<Label id="testLabel" text="{{ $value, $value + \' some static text\' }}" />'; repeater.items = [1, 2, 3]; TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildAtText(repeater, 0), '1 some static text', 'first element text'); TKUnit.assertEqual(getChildAtText(repeater, 1), '2 some static text', 'second element text'); TKUnit.assertEqual(getChildAtText(repeater, 2), '3 some static text', 'third element text'); } helper.buildUIAndRunTest(repeater, testAction); } export var test_RepeaterItemsGestureBindings = function () { var testFunc = function (page: Page) { var repeater = <Repeater>page.getViewById('repeater'); var hasObservers = false; var eachChildCallback = function (childItem: View) { if (childItem instanceof Label) { var gestureObservers = childItem.getGestureObservers(GestureTypes.tap); hasObservers = gestureObservers ? gestureObservers.length > 0 : false; } else if (childItem instanceof LayoutBase) { childItem.eachChildView(eachChildCallback); } return true; }; repeater.eachChildView(eachChildCallback); TKUnit.assertEqual(hasObservers, true, 'Every item should have tap observer!'); }; helper.navigateToModuleAndRunTest('ui/repeater/repeaterItems-bindingToGestures-page', null, testFunc); }; export var test_RepeaterItemsParentBindingsShouldWork = function () { var testFunc = function (page: Page) { var repeater = <Repeater>page.getViewById('repeater'); var expectedText = page.bindingContext['parentViewProperty']; var testPass = false; var eachChildCallback = function (childItem: View) { if (childItem instanceof Label) { testPass = (<Label>childItem).text === expectedText; if (testPass === false) { return false; } } else if (childItem instanceof LayoutBase) { childItem.eachChildView(eachChildCallback); } return true; }; repeater.eachChildView(eachChildCallback); TKUnit.assertEqual(testPass, true, 'Every item should have text bound to Page binding context!'); }; helper.navigateToModuleAndRunTest('ui/repeater/repeaterItems-bindingToGestures-page', null, testFunc); }; export function test_ChildrenAreNotCreatedUntilTheRepeaterIsLoaded() { var repeater = new Repeater(); repeater.itemsLayout = new WrapLayout(); TKUnit.assertEqual(getChildrenCount(repeater), 0, 'Repeater should not create its children until loaded.'); repeater.itemTemplate = '<Label id="testLabel" text="{{ $value, $value + \' some static text\' }}" />'; TKUnit.assertEqual(getChildrenCount(repeater), 0, 'Repeater should not create its children until loaded.'); repeater.items = [1, 2, 3]; TKUnit.assertEqual(getChildrenCount(repeater), 0, 'Repeater should not create its children until loaded.'); function testAction(views: Array<View>) { TKUnit.waitUntilReady(() => repeater.isLayoutValid); TKUnit.assertEqual(getChildrenCount(repeater), 3, 'Repeater should have created its children when loaded.'); } helper.buildUIAndRunTest(repeater, testAction); } /* export function test_no_memory_leak_when_items_is_regular_array(done) { var createFunc = function (): Repeater { var repeater = new Repeater(); repeater.items = FEW_ITEMS; return repeater; }; helper.buildUIWithWeakRefAndInteract(createFunc,(list) => { TKUnit.assert(list.isLoaded, "Repeater should be loaded here"); }, done); } export function test_no_memory_leak_when_items_is_observable_array(done) { // Keep the reference to the observable array to test the weakEventListener var colors = new ObservableArray(["red", "green", "blue"]); var createFunc = function (): Repeater { var repeater = new Repeater(); repeater.items = colors; return repeater; }; helper.buildUIWithWeakRefAndInteract(createFunc,(list) => { TKUnit.assert(list.isLoaded, "Repeater should be loaded here"); }, done); } */ function getChildrenCount(repeater: Repeater): number { return repeater.itemsLayout.getChildrenCount(); } function getChildAt(repeater: Repeater, index: number): View { return repeater.itemsLayout.getChildAt(index); } function getChildAtText(repeater: Repeater, index: number): string { return (<Label>getChildAt(repeater, index)).text + ''; }
the_stack
import React, { ReactNode } from 'react'; import PropTypes from 'prop-types'; import cls from 'classnames'; import { isEqual, noop } from 'lodash'; import { strings, cssClasses } from '@douyinfe/semi-foundation/autoComplete/constants'; import AutoCompleteFoundation, { AutoCompleteAdapter, StateOptionItem, DataItem } from '@douyinfe/semi-foundation/autoComplete/foundation'; import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants'; import BaseComponent, { ValidateStatus } from '../_base/baseComponent'; import { Position } from '../tooltip'; import Spin from '../spin'; import Popover from '../popover'; import Input from '../input'; import Trigger from '../trigger'; import Option from '../select/option'; import warning from '@douyinfe/semi-foundation/utils/warning'; import '@douyinfe/semi-foundation/autoComplete/autoComplete.scss'; import { Motion } from '../_base/base'; const prefixCls = cssClasses.PREFIX; const sizeSet = strings.SIZE; const positionSet = strings.POSITION; const statusSet = strings.STATUS; /** * AutoComplete is an enhanced Input (candidates suggest that users can choose or not), * and the Select positioning that supports Search is still a selector. * 1. When you click to expand, Select will clear all input values, but AutoComplete will not * 2. AutoComplete's renderSelectedItem only supports simple string returns, while Select's renderSelectedItem can return ReactNode * 3. Select props.value supports incoming object, but autoComplete only supports string (because the value needs to be displayed in Input) */ export interface BaseDataItem extends DataItem { label?: React.ReactNode; } export type AutoCompleteItems = BaseDataItem | string | number; export interface AutoCompleteProps<T extends AutoCompleteItems> { 'aria-describedby'?: React.AriaAttributes['aria-describedby']; 'aria-errormessage'?: React.AriaAttributes['aria-errormessage']; 'aria-invalid'?: React.AriaAttributes['aria-invalid']; 'aria-label'?: React.AriaAttributes['aria-label']; 'aria-labelledby'?: React.AriaAttributes['aria-labelledby']; 'aria-required'?: React.AriaAttributes['aria-required']; autoAdjustOverflow?: boolean; autoFocus?: boolean; className?: string; children?: ReactNode | undefined; data?: T[]; disabled?: boolean; defaultOpen?: boolean; defaultValue?: T; defaultActiveFirstOption?: boolean; dropdownMatchSelectWidth?: boolean; dropdownClassName?: string; dropdownStyle?: React.CSSProperties; emptyContent?: React.ReactNode; getPopupContainer?: () => HTMLElement; insetLabel?: React.ReactNode; insetLabelId?: string; id?: string; loading?: boolean; motion?: Motion; maxHeight?: string | number; mouseEnterDelay?: number; mouseLeaveDelay?: number; onFocus?: (e: React.FocusEvent) => void; onBlur?: (e: React.FocusEvent) => void; onChange?: (value: string | number) => void; onSearch?: (inputValue: string) => void; onSelect?: (value: T) => void; onClear?: () => void; onChangeWithObject?: boolean; onSelectWithObject?: boolean; onDropdownVisibleChange?: (visible: boolean) => void; prefix?: React.ReactNode; placeholder?: string; position?: Position; renderItem?: (option: T) => React.ReactNode; renderSelectedItem?: (option: T) => string; size?: 'small' | 'default' | 'large'; style?: React.CSSProperties; suffix?: React.ReactNode; showClear?: boolean; triggerRender?: (props?: any) => React.ReactNode; stopPropagation?: boolean | string; value?: string | number; validateStatus?: ValidateStatus; zIndex?: number; } interface KeyboardEventType { onKeyDown?: React.KeyboardEventHandler; } interface AutoCompleteState { dropdownMinWidth: null | number; inputValue: string | undefined | number; options: StateOptionItem[]; visible: boolean; focusIndex: number; selection: Map<any, any>; rePosKey: number; keyboardEventSet?: KeyboardEventType; } class AutoComplete<T extends AutoCompleteItems> extends BaseComponent<AutoCompleteProps<T>, AutoCompleteState> { static propTypes = { 'aria-label': PropTypes.string, 'aria-labelledby': PropTypes.string, 'aria-invalid': PropTypes.bool, 'aria-errormessage': PropTypes.string, 'aria-describedby': PropTypes.string, 'aria-required': PropTypes.bool, autoFocus: PropTypes.bool, autoAdjustOverflow: PropTypes.bool, className: PropTypes.string, children: PropTypes.node, data: PropTypes.array, defaultOpen: PropTypes.bool, defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), defaultActiveFirstOption: PropTypes.bool, disabled: PropTypes.bool, dropdownMatchSelectWidth: PropTypes.bool, dropdownClassName: PropTypes.string, dropdownStyle: PropTypes.object, emptyContent: PropTypes.node, id: PropTypes.string, insetLabel: PropTypes.node, insetLabelId: PropTypes.string, onSearch: PropTypes.func, onSelect: PropTypes.func, onClear: PropTypes.func, onBlur: PropTypes.func, onFocus: PropTypes.func, onChange: PropTypes.func, position: PropTypes.oneOf(positionSet), placeholder: PropTypes.string, prefix: PropTypes.node, onChangeWithObject: PropTypes.bool, onSelectWithObject: PropTypes.bool, renderItem: PropTypes.func, renderSelectedItem: PropTypes.func, suffix: PropTypes.node, showClear: PropTypes.bool, size: PropTypes.oneOf(sizeSet), style: PropTypes.object, stopPropagation: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), maxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), mouseEnterDelay: PropTypes.number, mouseLeaveDelay: PropTypes.number, motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]), getPopupContainer: PropTypes.func, triggerRender: PropTypes.func, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), validateStatus: PropTypes.oneOf(statusSet), zIndex: PropTypes.number, }; static Option = Option; static defaultProps = { stopPropagation: true, motion: true, zIndex: popoverNumbers.DEFAULT_Z_INDEX, position: 'bottomLeft' as const, data: [] as [], showClear: false, disabled: false, size: 'default' as const, onFocus: noop, onSearch: noop, onClear: noop, onBlur: noop, onSelect: noop, onChange: noop, onSelectWithObject: false, onDropdownVisibleChange: noop, defaultActiveFirstOption: false, dropdownMatchSelectWidth: true, loading: false, maxHeight: 300, validateStatus: 'default' as const, autoFocus: false, emptyContent: null as null, // onPressEnter: () => undefined, // defaultOpen: false, }; triggerRef: React.RefObject<HTMLDivElement> | null; optionsRef: React.RefObject<HTMLDivElement> | null; private clickOutsideHandler: () => void | null; constructor(props: AutoCompleteProps<T>) { super(props); this.foundation = new AutoCompleteFoundation(this.adapter); const initRePosKey = 1; this.state = { dropdownMinWidth: null, inputValue: '', // option list options: [], // popover visible visible: false, // current focus option index focusIndex: props.defaultActiveFirstOption ? 0 : -1, // current selected options selection: new Map(), rePosKey: initRePosKey, }; this.triggerRef = React.createRef(); this.optionsRef = React.createRef(); this.clickOutsideHandler = null; warning( 'triggerRender' in this.props && typeof this.props.triggerRender === 'function', `[Semi AutoComplete] - If you are using the following props: 'suffix', 'prefix', 'showClear', 'validateStatus', and 'size', please notice that they will be removed in the next major version. Please use 'componentProps' to retrieve these props instead. - If you are using 'onBlur', 'onFocus', please try to avoid using them and look for changes in the future.` ); } get adapter(): AutoCompleteAdapter<AutoCompleteProps<T>, AutoCompleteState> { const keyboardAdapter = { registerKeyDown: (cb: any): void => { const keyboardEventSet = { onKeyDown: cb, }; this.setState({ keyboardEventSet }); }, unregisterKeyDown: (cb: any): void => { this.setState({ keyboardEventSet: {} }); }, updateFocusIndex: (focusIndex: number): void => { this.setState({ focusIndex }); }, }; return { ...super.adapter, ...keyboardAdapter, getTriggerWidth: () => { const el = this.triggerRef.current; return el && el.getBoundingClientRect().width; }, setOptionWrapperWidth: width => { this.setState({ dropdownMinWidth: width }); }, updateInputValue: inputValue => { this.setState({ inputValue }); }, toggleListVisible: isShow => { this.setState({ visible: isShow }); }, updateOptionList: optionList => { this.setState({ options: optionList }); }, updateSelection: selection => { this.setState({ selection }); }, notifySearch: inputValue => { this.props.onSearch(inputValue); }, notifyChange: value => { this.props.onChange(value); }, notifySelect: (option: StateOptionItem | string | number): void => { this.props.onSelect(option as T); }, notifyDropdownVisibleChange: (isVisible: boolean): void => { this.props.onDropdownVisibleChange(isVisible); }, notifyClear: () => { this.props.onClear(); }, notifyFocus: (event: React.FocusEvent) => { this.props.onFocus(event); }, notifyBlur: (event: React.FocusEvent) => { this.props.onBlur(event); }, rePositionDropdown: () => { let { rePosKey } = this.state; rePosKey = rePosKey + 1; this.setState({ rePosKey }); }, }; } componentDidMount() { this.foundation.init(); } componentWillUnmount() { this.foundation.destroy(); } componentDidUpdate(prevProps: AutoCompleteProps<T>, prevState: AutoCompleteState) { if (!isEqual(this.props.data, prevProps.data)) { this.foundation.handleDataChange(this.props.data); } if (this.props.value !== prevProps.value) { this.foundation.handleValueChange(this.props.value); } } onSelect = (option: StateOptionItem, optionIndex: number, e: React.MouseEvent | React.KeyboardEvent): void => { this.foundation.handleSelect(option, optionIndex); }; onSearch = (value: string): void => { this.foundation.handleSearch(value); }; onBlur = (e: React.FocusEvent): void => this.foundation.handleBlur(e); onFocus = (e: React.FocusEvent): void => this.foundation.handleFocus(e); onInputClear = (): void => this.foundation.handleClear(); handleInputClick = (e: React.MouseEvent): void => this.foundation.handleInputClick(e); renderInput(): React.ReactNode { const { size, prefix, insetLabel, insetLabelId, suffix, placeholder, style, className, showClear, disabled, triggerRender, validateStatus, autoFocus, value, id, } = this.props; const { inputValue, keyboardEventSet, selection } = this.state; const useCustomTrigger = typeof triggerRender === 'function'; const outerProps = { style, className: useCustomTrigger ? cls(className) : cls( { [prefixCls]: true, [`${prefixCls}-disabled`]: disabled, }, className ), onClick: this.handleInputClick, ref: this.triggerRef, id, ...keyboardEventSet, }; const innerProps = { disabled, placeholder, autofocus: autoFocus, onChange: this.onSearch, onClear: this.onInputClear, 'aria-label': this.props['aria-label'], 'aria-labelledby': this.props['aria-labelledby'], 'aria-invalid': this.props['aria-invalid'], 'aria-errormessage': this.props['aria-errormessage'], 'aria-describedby': this.props['aria-describedby'], 'aria-required': this.props['aria-required'], // TODO: remove in next major version suffix, prefix: prefix || insetLabel, insetLabelId, showClear, validateStatus, size, onBlur: this.onBlur, onFocus: this.onFocus, }; return ( <div {...outerProps}> {typeof triggerRender === 'function' ? ( <Trigger {...innerProps} inputValue={(typeof value !== 'undefined' ? value : inputValue) as string} value={Array.from(selection.values())} triggerRender={triggerRender} componentName="AutoComplete" componentProps={{ ...this.props }} /> ) : ( <Input {...innerProps} value={typeof value !== 'undefined' ? value : inputValue} /> )} </div> ); } renderLoading() { const loadingWrapperCls = `${prefixCls}-loading-wrapper`; return ( <div className={loadingWrapperCls}> <Spin /> </div> ); } renderOption(option: StateOptionItem, optionIndex: number): React.ReactNode { const { focusIndex } = this.state; const isFocused = optionIndex === focusIndex; return ( <Option showTick={false} onSelect={(v: StateOptionItem, e: React.MouseEvent | React.KeyboardEvent) => this.onSelect(v, optionIndex, e)} // selected={selection.has(option.label)} focused={isFocused} onMouseEnter={() => this.foundation.handleOptionMouseEnter(optionIndex)} key={option.key || option.label + option.value + optionIndex} {...option} > {option.label} </Option> ); } renderOptionList(): React.ReactNode { const { maxHeight, dropdownStyle, dropdownClassName, loading, emptyContent } = this.props; const { options, dropdownMinWidth } = this.state; const listCls = cls( { [`${prefixCls}-option-list`]: true, }, dropdownClassName ); let optionsNode; if (options.length === 0) { optionsNode = emptyContent; } else { optionsNode = options.filter(option => option.show).map((option, i) => this.renderOption(option, i)); } const style = { maxHeight: maxHeight, minWidth: dropdownMinWidth, ...dropdownStyle, }; return ( <div className={listCls} role="listbox" style={style}> {!loading ? optionsNode : this.renderLoading()} </div> ); } render(): React.ReactNode { const { position, motion, zIndex, mouseEnterDelay, mouseLeaveDelay, autoAdjustOverflow, stopPropagation, getPopupContainer, } = this.props; const { visible, rePosKey } = this.state; const input = this.renderInput(); const optionList = this.renderOptionList(); return ( <Popover mouseEnterDelay={mouseEnterDelay} mouseLeaveDelay={mouseLeaveDelay} autoAdjustOverflow={autoAdjustOverflow} trigger="custom" motion={motion} visible={visible} content={optionList} position={position} ref={this.optionsRef as any} // TransformFromCenter TODO: need to confirm zIndex={zIndex} stopPropagation={stopPropagation} getPopupContainer={getPopupContainer} rePosKey={rePosKey} > {input} </Popover> ); } } export default AutoComplete;
the_stack
import type { colorCallback, colorObject } from '../interfaces'; export class Console { static log(...message: unknown[]): void { // eslint-disable-next-line no-console console.log(...message); } static error(...message: unknown[]): void { // eslint-disable-next-line no-console console.error(...message); } static time(label?: string): void { // eslint-disable-next-line no-console console.time(label); } static timeEnd(label?: string): void { // eslint-disable-next-line no-console console.timeEnd(label); } } export type Arrayable<T> = T | T[] export function toArray<T>(v: Arrayable<T>): T[] { if (Array.isArray(v)) return v; return [v]; } export function hash(str: string): string { str = str.replace(/\r/g, ''); let hash = 5381; let i = str.length; while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i); return (hash >>> 0).toString(36); } export function type(val: unknown): string { return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); } export function indent(code: string, tab = 2): string { const spaces = Array(tab).fill(' ').join(''); return code .split('\n') .map((line) => spaces + line) .join('\n'); } export function wrapit( code: string, start = '{', end = '}', tab = 2, minify = false ): string { if (minify) return `${start}${code}${end}`; return `${start}\n${indent(code, tab)}\n${end}`; } export function isNumber( amount: string, start = -Infinity, end = Infinity, type: 'int' | 'float' = 'int' ): boolean { const isInt = /^-?\d+$/.test(amount); if (type === 'int') { if (!isInt) return false; } else { const isFloat = /^-?\d+\.\d+$/.test(amount); if (!(isInt || isFloat)) return false; } const num = parseFloat(amount); return num >= start && num <= end; } export function isFraction(amount: string): boolean { return /^\d+\/\d+$/.test(amount); } export function isSize(amount: string): boolean { return /^-?(\d+(\.\d+)?)+(rem|em|px|rpx|vh|vw|ch|ex)$/.test(amount); } export function isSpace(str: string): boolean { return /^\s*$/.test(str); } export function roundUp(num: number, precision = 0): number { precision = Math.pow(10, precision); return Math.round(num * precision) / precision; } export function fracToPercent(amount: string): string | undefined { const matches = amount.match(/[^/]+/g); if (!matches || matches.length < 2) return; const a = +matches[0]; const b = +matches[1]; return roundUp((a / b) * 100, 6) + '%'; } export function hex2RGB(hex: string): number[] | undefined { const RGB_HEX = /^#?(?:([\da-f]{3})[\da-f]?|([\da-f]{6})(?:[\da-f]{2})?)$/i; const [, short, long] = String(hex).match(RGB_HEX) || []; if (long) { const value = Number.parseInt(long, 16); return [value >> 16, (value >> 8) & 0xff, value & 0xff]; } else if (short) { return Array.from(short, (s) => Number.parseInt(s, 16)).map( (n) => (n << 4) | n ); } } export function camelToDash(str: string): string { // Use exact the same regex as Post CSS return str.replace(/([A-Z])/g, '-$1').replace(/^ms-/, '-ms-').toLowerCase(); } export function dashToCamel(str: string): string { if (!/-/.test(str)) return str; return str.toLowerCase().replace(/-(.)/g, (_, group) => group.toUpperCase()); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function getNestedValue(obj: { [key: string]: any }, key: string): any { const topKey = key.match(/^[^.[]+/); if (!topKey) return; let topValue = obj[topKey[0]]; if (!topValue) return; let index = topKey[0].length; while(index < key.length) { const square = key.slice(index, ).match(/\[[^\s\]]+?\]/); const dot = key.slice(index, ).match(/\.[^.[]+$|\.[^.[]+(?=\.)/); if (( !square && !dot ) || ( square?.index === undefined && dot?.index === undefined )) return topValue; if (typeof topValue !== 'object') return; if (dot && dot.index !== undefined && (square?.index === undefined || dot.index < square.index)) { const arg = dot[0].slice(1,); topValue = topValue[arg]; index += dot.index + dot[0].length; } else if (square && square.index !== undefined) { const arg = square[0].slice(1, -1).trim().replace(/^['"]+|['"]+$/g, ''); topValue = topValue[arg]; index += square.index + square[0].length; } } return topValue; } export function negateValue(value: string): string { if (/(^0\w)|(^-)|(^0$)/.test(value)) return value; return '-' + value; } export function searchFrom( text: string, target: string | RegExp, startIndex = 0, endIndex?: number ): number { // search from partial of string const subText = text.substring(startIndex, endIndex); const relativeIndex = subText.search(target); return relativeIndex === -1 ? -1 : startIndex + relativeIndex; } export function connectList<T = string>(a?: T[], b?: T[], append = true): T[] { return append ? [...(a ?? []), ...(b ?? [])] : [...(b ?? []), ...(a ?? [])]; } export function toType( value: unknown, type: 'object' ): Record<string, unknown>; export function toType(value: unknown, type: 'string'): string | undefined; export function toType(value: unknown, type: 'number'): number | undefined; export function toType( value: unknown, type: 'object' | 'string' | 'number' ): unknown { switch (type) { case 'object': return value && typeof value === 'object' ? value : {}; case 'string': if (typeof value === 'string') return value as string; break; case 'number': if (typeof value === 'number') return value as number; break; } } export function deepCopy<T>(source: T): T { return Array.isArray(source) ? (source as unknown[]).map((item: unknown) => deepCopy(item)) : source instanceof Date ? new Date(source.getTime()) : source && typeof source === 'object' ? Object.getOwnPropertyNames(source).reduce((o, prop) => { const descriptor = Object.getOwnPropertyDescriptor(source, prop); if (descriptor) { Object.defineProperty(o, prop, descriptor); if (source && typeof source === 'object') { o[prop] = deepCopy( ((source as unknown) as { [key: string]: unknown })[prop] ); } } return o; }, Object.create(Object.getPrototypeOf(source))) : (source as T); } export function isTagName(name: string): boolean { return ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embd', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'svg', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr'].includes(name); } export function flatColors(colors: colorObject, head?: string): { [key:string]: string | colorCallback } { let flatten: { [ key:string ]: string | colorCallback } = {}; for (const [key, value] of Object.entries(colors)) { if (typeof value === 'string' || typeof value === 'function') { flatten[(head && key === 'DEFAULT') ? head : head ? `${head}-${key}`: key] = value; } else { flatten = { ...flatten, ...flatColors(value, head ? `${head}-${key}`: key) }; } } return flatten; } export function testRegexr(text: string, expressions: RegExp[]): boolean { for (const exp of expressions) { if (exp.test(text)) return true; } return false; } export function searchPropEnd(text: string, startIndex = 0): number { let index = startIndex; let output = -1; let openSingleQuote = false; let openDoubleQuote = false; let openBracket = false; let isEscaped = false; while (index < text.length) { switch (text.charAt(index)) { case '\\': isEscaped = !isEscaped; break; case '\'': if (!openDoubleQuote && !openBracket && !isEscaped) openSingleQuote = !openSingleQuote; isEscaped = false; break; case '"': if (!openSingleQuote && !openBracket && !isEscaped) openDoubleQuote = !openDoubleQuote; isEscaped = false; break; case '(': if (!openBracket && !openSingleQuote && !openDoubleQuote && !isEscaped) openBracket = true; isEscaped = false; break; case ')': if (openBracket && !isEscaped) openBracket = false; isEscaped = false; break; case ';': if (!isEscaped && !openSingleQuote && !openDoubleQuote && !openBracket) output = index; isEscaped = false; break; default: isEscaped = false; break; } if (output !== -1) break; index++; } return output; } export function searchNotEscape(text:string, chars: string | string[] = ['{']): number { if (!Array.isArray(chars)) chars = [ chars ]; let i = 0; while (i < text.length) { if (chars.includes(text.charAt(i)) && text.charAt(i - 1) !== '\\') { return i; } i ++; } return -1; } export function splitSelectors(selectors: string): string[] { const splitted = []; let parens = 0; let angulars = 0; let soFar = ''; for (let i = 0, len = selectors.length; i < len; i++) { const char = selectors[i]; if (char === '(') { parens += 1; } else if (char === ')') { parens -= 1; } else if (char === '[') { angulars += 1; } else if (char === ']') { angulars -= 1; } else if (char === ',') { if (!parens && !angulars) { splitted.push(soFar.trim()); soFar = ''; continue; } } soFar += char; } splitted.push(soFar.trim()); return splitted; } export function guessClassName(selector: string): { selector: string, isClass: boolean, pseudo?: string } | { selector: string, isClass: boolean, pseudo?: string }[] { if (selector.indexOf(',') >= 0) return splitSelectors(selector).map(i => guessClassName(i) as { selector: string, isClass: boolean }); // not classes, contains attribute selectors, nested selectors - treat as static if (selector.charAt(0) !== '.' || searchNotEscape(selector, ['[', '>', '+', '~']) >= 0 || selector.trim().indexOf(' ') >= 0 || searchNotEscape(selector.slice(1), '.') >=0) return { selector, isClass: false }; const pseudo = searchNotEscape(selector, ':'); const className = (selector.match(/^\.([\w-]|(\\\W))+/)?.[0].slice(1,) || '').replace(/\\/g, ''); if (pseudo === -1) return { selector: className, isClass: true }; return { selector: className, isClass: true, pseudo: selector.slice(pseudo,) }; } /** * Increase string a value with unit * * @example '2px' + 1 = '3px' * @example '15em' + (-2) = '13em' */ export function increaseWithUnit(target: number, delta: number): number export function increaseWithUnit(target: string, delta: number): string export function increaseWithUnit(target: string | number, delta: number): string | number export function increaseWithUnit(target: string | number, delta: number): string | number { if (typeof target === 'number') return target + delta; const value = target.match(/^-?[0-9]+\.?[0-9]*/)?.[0] || ''; const unit = target.slice(value.length); const result = (parseFloat(value) + delta); if (Number.isNaN(result)) return target; return result + unit; } export function splitColorGroup(color: string): [ string, string | undefined ] { const sep = color.indexOf('/'); if (sep === -1) return [ color, undefined ]; return [ color.slice(0, sep), color.slice(sep+1) ]; }
the_stack
import { FieldNode, DocumentNode, FragmentDefinitionNode } from 'graphql'; import { CombinedError } from '@urql/core'; import { getSelectionSet, getName, SelectionSet, getFragmentTypeName, getFieldAlias, getFragments, getMainOperation, normalizeVariables, getFieldArguments, } from '../ast'; import { Variables, Data, DataField, Link, OperationRequest, Dependencies, } from '../types'; import { Store, getCurrentOperation, getCurrentDependencies, initDataState, clearDataState, joinKeys, keyOfField, makeData, ownsData, } from '../store'; import * as InMemoryData from '../store/data'; import { warn, pushDebugNode, popDebugNode } from '../helpers/help'; import { Context, makeSelectionIterator, ensureData, makeContext, updateContext, getFieldError, deferRef, } from './shared'; import { isFieldAvailableOnType, isFieldNullable, isListNullable, } from '../ast'; export interface QueryResult { dependencies: Dependencies; partial: boolean; data: null | Data; } export const query = ( store: Store, request: OperationRequest, data?: Data | null | undefined, error?: CombinedError | undefined, key?: number ): QueryResult => { initDataState('read', store.data, key); const result = read(store, request, data, error); clearDataState(); return result; }; export const read = ( store: Store, request: OperationRequest, input?: Data | null | undefined, error?: CombinedError | undefined ): QueryResult => { const operation = getMainOperation(request.query); const rootKey = store.rootFields[operation.operation]; const rootSelect = getSelectionSet(operation); const ctx = makeContext( store, normalizeVariables(operation, request.variables), getFragments(request.query), rootKey, rootKey, false, error ); if (process.env.NODE_ENV !== 'production') { pushDebugNode(rootKey, operation); } if (!input) input = makeData(); // NOTE: This may reuse "previous result data" as indicated by the // `originalData` argument in readRoot(). This behaviour isn't used // for readSelection() however, which always produces results from // scratch const data = rootKey !== ctx.store.rootFields['query'] ? readRoot(ctx, rootKey, rootSelect, input) : readSelection(ctx, rootKey, rootSelect, input); if (process.env.NODE_ENV !== 'production') { popDebugNode(); } return { dependencies: getCurrentDependencies(), partial: ctx.partial || !data, data: data || null, }; }; const readRoot = ( ctx: Context, entityKey: string, select: SelectionSet, input: Data ): Data => { const typename = ctx.store.rootNames[entityKey] ? entityKey : input.__typename; if (typeof typename !== 'string') { return input; } const iterate = makeSelectionIterator(entityKey, entityKey, select, ctx); let node: FieldNode | void; let hasChanged = false; const output = makeData(input); while ((node = iterate())) { const fieldAlias = getFieldAlias(node); const fieldValue = input[fieldAlias]; // Add the current alias to the walked path before processing the field's value ctx.__internal.path.push(fieldAlias); // We temporarily store the data field in here, but undefined // means that the value is missing from the cache let dataFieldValue: void | DataField; if (node.selectionSet && fieldValue !== null) { dataFieldValue = readRootField( ctx, getSelectionSet(node), ensureData(fieldValue) ); } else { dataFieldValue = fieldValue; } // Check for any referential changes in the field's value hasChanged = hasChanged || dataFieldValue !== fieldValue; if (dataFieldValue !== undefined) output[fieldAlias] = dataFieldValue!; // After processing the field, remove the current alias from the path again ctx.__internal.path.pop(); } return hasChanged ? output : input; }; const readRootField = ( ctx: Context, select: SelectionSet, originalData: Link<Data> ): Link<Data> => { if (Array.isArray(originalData)) { const newData = new Array(originalData.length); let hasChanged = false; for (let i = 0, l = originalData.length; i < l; i++) { // Add the current index to the walked path before reading the field's value ctx.__internal.path.push(i); // Recursively read the root field's value newData[i] = readRootField(ctx, select, originalData[i]); hasChanged = hasChanged || newData[i] !== originalData[i]; // After processing the field, remove the current index from the path ctx.__internal.path.pop(); } return hasChanged ? newData : originalData; } else if (originalData === null) { return null; } // Write entity to key that falls back to the given parentFieldKey const entityKey = ctx.store.keyOfEntity(originalData); if (entityKey !== null) { // We assume that since this is used for result data this can never be undefined, // since the result data has already been written to the cache return readSelection(ctx, entityKey, select, originalData) || null; } else { return readRoot(ctx, originalData.__typename, select, originalData); } }; export const readFragment = ( store: Store, query: DocumentNode, entity: Partial<Data> | string, variables?: Variables ): Data | null => { const fragments = getFragments(query); const names = Object.keys(fragments); const fragment = fragments[names[0]] as FragmentDefinitionNode; if (!fragment) { warn( 'readFragment(...) was called with an empty fragment.\n' + 'You have to call it with at least one fragment in your GraphQL document.', 6 ); return null; } const typename = getFragmentTypeName(fragment); if (typeof entity !== 'string' && !entity.__typename) entity.__typename = typename; const entityKey = store.keyOfEntity(entity as Data); if (!entityKey) { warn( "Can't generate a key for readFragment(...).\n" + 'You have to pass an `id` or `_id` field or create a custom `keys` config for `' + typename + '`.', 7 ); return null; } if (process.env.NODE_ENV !== 'production') { pushDebugNode(typename, fragment); } const ctx = makeContext( store, variables || {}, fragments, typename, entityKey ); const result = readSelection(ctx, entityKey, getSelectionSet(fragment), makeData()) || null; if (process.env.NODE_ENV !== 'production') { popDebugNode(); } return result; }; const readSelection = ( ctx: Context, key: string, select: SelectionSet, input: Data, result?: Data ): Data | undefined => { const { store } = ctx; const isQuery = key === store.rootFields['query']; const entityKey = (result && store.keyOfEntity(result)) || key; if (!isQuery && !!ctx.store.rootNames[entityKey]) { warn( 'Invalid root traversal: A selection was being read on `' + entityKey + '` which is an uncached root type.\n' + 'The `' + ctx.store.rootFields.mutation + '` and `' + ctx.store.rootFields.subscription + '` types are special ' + 'Operation Root Types and cannot be read back from the cache.', 25 ); } const typename = !isQuery ? InMemoryData.readRecord(entityKey, '__typename') || (result && result.__typename) : key; if (typeof typename !== 'string') { return; } else if (result && typename !== result.__typename) { warn( 'Invalid resolver data: The resolver at `' + entityKey + '` returned an ' + 'invalid typename that could not be reconciled with the cache.', 8 ); return; } const iterate = makeSelectionIterator(typename, entityKey, select, ctx); let hasFields = false; let hasPartials = false; let hasChanged = typename !== input.__typename; let node: FieldNode | void; const output = makeData(input); while ((node = iterate()) !== undefined) { // Derive the needed data from our node. const fieldName = getName(node); const fieldArgs = getFieldArguments(node, ctx.variables); const fieldAlias = getFieldAlias(node); const fieldKey = keyOfField(fieldName, fieldArgs); const key = joinKeys(entityKey, fieldKey); const fieldValue = InMemoryData.readRecord(entityKey, fieldKey); const resultValue = result ? result[fieldName] : undefined; const resolvers = store.resolvers[typename]; if (process.env.NODE_ENV !== 'production' && store.schema && typename) { isFieldAvailableOnType(store.schema, typename, fieldName); } // Add the current alias to the walked path before processing the field's value ctx.__internal.path.push(fieldAlias); // We temporarily store the data field in here, but undefined // means that the value is missing from the cache let dataFieldValue: void | DataField; if (fieldName === '__typename') { // We directly assign the typename as it's already available dataFieldValue = typename; } else if (resultValue !== undefined && node.selectionSet === undefined) { // The field is a scalar and can be retrieved directly from the result dataFieldValue = resultValue; } else if ( getCurrentOperation() === 'read' && resolvers && typeof resolvers[fieldName] === 'function' ) { // We have to update the information in context to reflect the info // that the resolver will receive updateContext(ctx, output, typename, entityKey, key, fieldName); // We have a resolver for this field. // Prepare the actual fieldValue, so that the resolver can use it if (fieldValue !== undefined) { output[fieldAlias] = fieldValue; } dataFieldValue = resolvers[fieldName]( output, fieldArgs || ({} as Variables), store, ctx ); if (node.selectionSet) { // When it has a selection set we are resolving an entity with a // subselection. This can either be a list or an object. dataFieldValue = resolveResolverResult( ctx, typename, fieldName, key, getSelectionSet(node), (output[fieldAlias] !== undefined ? output[fieldAlias] : input[fieldAlias]) as Data, dataFieldValue, ownsData(input) ); } if ( store.schema && dataFieldValue === null && !isFieldNullable(store.schema, typename, fieldName) ) { // Special case for when null is not a valid value for the // current field return undefined; } } else if (!node.selectionSet) { // The field is a scalar but isn't on the result, so it's retrieved from the cache dataFieldValue = fieldValue; } else if (resultValue !== undefined) { // We start walking the nested resolver result here dataFieldValue = resolveResolverResult( ctx, typename, fieldName, key, getSelectionSet(node), (output[fieldAlias] !== undefined ? output[fieldAlias] : input[fieldAlias]) as Data, resultValue, ownsData(input) ); } else { // Otherwise we attempt to get the missing field from the cache const link = InMemoryData.readLink(entityKey, fieldKey); if (link !== undefined) { dataFieldValue = resolveLink( ctx, link, typename, fieldName, getSelectionSet(node), (output[fieldAlias] !== undefined ? output[fieldAlias] : input[fieldAlias]) as Data, ownsData(input) ); } else if (typeof fieldValue === 'object' && fieldValue !== null) { // The entity on the field was invalid but can still be recovered dataFieldValue = fieldValue; } } // Now that dataFieldValue has been retrieved it'll be set on data // If it's uncached (undefined) but nullable we can continue assembling // a partial query result if (dataFieldValue === undefined && deferRef.current) { // The field is undelivered and uncached, but is included in a deferred fragment hasFields = true; } else if ( dataFieldValue === undefined && ((store.schema && isFieldNullable(store.schema, typename, fieldName)) || !!getFieldError(ctx)) ) { // The field is uncached or has errored, so it'll be set to null and skipped hasPartials = true; dataFieldValue = null; } else if (dataFieldValue === undefined) { // If the field isn't deferred or partial then we have to abort ctx.__internal.path.pop(); return undefined; } else { // Otherwise continue as usual hasFields = hasFields || fieldName !== '__typename'; } // After processing the field, remove the current alias from the path again ctx.__internal.path.pop(); // Check for any referential changes in the field's value hasChanged = hasChanged || dataFieldValue !== input[fieldAlias]; if (dataFieldValue !== undefined) output[fieldAlias] = dataFieldValue; } ctx.partial = ctx.partial || hasPartials; return isQuery && hasPartials && !hasFields ? undefined : hasChanged ? output : input; }; const resolveResolverResult = ( ctx: Context, typename: string, fieldName: string, key: string, select: SelectionSet, prevData: void | null | Data | Data[], result: void | DataField, skipNull: boolean ): DataField | void => { if (Array.isArray(result)) { const { store } = ctx; // Check whether values of the list may be null; for resolvers we assume // that they can be, since it's user-provided data const _isListNullable = store.schema ? isListNullable(store.schema, typename, fieldName) : false; const data = new Array(result.length); let hasChanged = !Array.isArray(prevData) || result.length !== prevData.length; for (let i = 0, l = result.length; i < l; i++) { // Add the current index to the walked path before reading the field's value ctx.__internal.path.push(i); // Recursively read resolver result const childResult = resolveResolverResult( ctx, typename, fieldName, joinKeys(key, `${i}`), select, prevData != null ? prevData[i] : undefined, result[i], skipNull ); // After processing the field, remove the current index from the path ctx.__internal.path.pop(); // Check the result for cache-missed values if (childResult === undefined && !_isListNullable) { return undefined; } else { ctx.partial = ctx.partial || (childResult === undefined && _isListNullable); data[i] = childResult != null ? childResult : null; hasChanged = hasChanged || data[i] !== prevData![i]; } } return hasChanged ? data : prevData; } else if (result === null || result === undefined) { return result; } else if (skipNull && prevData === null) { return null; } else if (isDataOrKey(result)) { const data = (prevData || makeData()) as Data; return typeof result === 'string' ? readSelection(ctx, result, select, data) : readSelection(ctx, key, select, data, result); } else { warn( 'Invalid resolver value: The field at `' + key + '` is a scalar (number, boolean, etc)' + ', but the GraphQL query expects a selection set for this field.', 9 ); return undefined; } }; const resolveLink = ( ctx: Context, link: Link | Link[], typename: string, fieldName: string, select: SelectionSet, prevData: void | null | Data | Data[], skipNull: boolean ): DataField | undefined => { if (Array.isArray(link)) { const { store } = ctx; const _isListNullable = store.schema ? isListNullable(store.schema, typename, fieldName) : false; const newLink = new Array(link.length); let hasChanged = !Array.isArray(prevData) || newLink.length !== prevData.length; for (let i = 0, l = link.length; i < l; i++) { // Add the current index to the walked path before reading the field's value ctx.__internal.path.push(i); // Recursively read the link const childLink = resolveLink( ctx, link[i], typename, fieldName, select, prevData != null ? prevData[i] : undefined, skipNull ); // After processing the field, remove the current index from the path ctx.__internal.path.pop(); // Check the result for cache-missed values if (childLink === undefined && !_isListNullable) { return undefined; } else { ctx.partial = ctx.partial || (childLink === undefined && _isListNullable); newLink[i] = childLink || null; hasChanged = hasChanged || newLink[i] !== prevData![i]; } } return hasChanged ? newLink : (prevData as Data[]); } else if (link === null || (prevData === null && skipNull)) { return null; } return readSelection(ctx, link, select, (prevData || makeData()) as Data); }; const isDataOrKey = (x: any): x is string | Data => typeof x === 'string' || (typeof x === 'object' && typeof (x as any).__typename === 'string');
the_stack
import { Command, command, param, option, Options } from "clime"; import { lstatSync } from "fs"; import { ModuleHierarchyVerifier } from "../lib/moduleHierarchyVerifier"; import { ModuleVerifier } from "../lib/moduleVerifier"; import * as inquirer from "inquirer"; import * as path from "path"; import { basename } from "path"; import { TrustStore, TestTrustStore } from "../lib/trustStore"; import { queueTelemetryFromModuleVerificationResult } from "../lib/telemetry"; import { createWorkingDirectory, decompress, recursivePromise } from "../lib/util/fsPromise"; import { ModuleVerificationStatus } from "../lib/types"; export class VerifyOptions extends Options { @option({ name: "full", toggle: true, description: "show verification status of individual packages" }) full: boolean = false; @option({ name: "non-interactive", toggle: true, description: "do not prompt to trust packages that are untrusted" }) nonInteractive: boolean = false; @option({ name: "package-name", description: "if verifying a tarball, this is the expected package name" }) packageName: string = ""; @option({ name: "enable-test-trust-store", toggle: true, description: "enables the test trust store, for debugging purposes only" }) enableTestTrustStore: boolean = false; @option({ name: "allow-unsigned-packages", toggle: true, description: "verify doesn't fail on unsigned packages" }) allowUnsignedPackages: boolean = false; } @command({ description: "verify an npm/yarn package directory" }) export default class extends Command { public async execute( @param({ name: "pkgdir|tarball", description: "path to package directory or tarball", required: false }) path: string, options: VerifyOptions ): Promise<void> { if (await this.executeInternal(path, options)) { process.exitCode = 0; } else { process.exitCode = 1; } } public async executeInternal( path: string, options: VerifyOptions ): Promise<boolean> { if (path === undefined) { // Default path to the current directory if not provided. path = "."; } if (path.endsWith(".tgz") && lstatSync(path).isFile()) { return await this.verifyTarball(path, options); } else { return await this.verifyDirectory(path, options); } } private async verifyTarball( tarballPath: string, options: VerifyOptions ): Promise<boolean> { const wd = await createWorkingDirectory(); console.log("extracting unsigned tarball..."); await decompress(tarballPath, wd); console.log("building file list..."); const base = path.join(wd, "package"); const files = (await recursivePromise(base)).map(fullPath => fullPath.substr(base.length + 1).replace(/\\/g, "/") ); console.log("verifying package..."); const moduleVerifier = new ModuleVerifier( options.enableTestTrustStore ? new TestTrustStore() : new TrustStore() ); let result = await moduleVerifier.verify( base, files, options.packageName || "" ); queueTelemetryFromModuleVerificationResult("verify-module", result); // Prompt user to trust package if untrusted. if ( result.status == ModuleVerificationStatus.Untrusted && !options.nonInteractive ) { let identityString = ""; if (result.untrustedIdentity.keybaseUser !== undefined) { identityString = result.untrustedIdentity.keybaseUser + " on keybase.io"; } else { identityString = "public key at " + result.untrustedIdentity.pgpPublicKeyUrl; } const trustResults = await inquirer.prompt([ { name: "pkg", type: "confirm", message: "Package '" + result.packageName + "' is not trusted, but is signed by " + identityString + ". " + "Do you want to trust this identity to sign '" + result.packageName + "' now and forever", default: false } ] as inquirer.ConfirmQuestion<{ pkg: boolean }>[]); let trustStore = new TrustStore(); if (trustResults["pkg"]) { await trustStore.addTrusted( result.untrustedIdentity, result.packageName ); if (!result.isPrivate) { queueTelemetryFromModuleVerificationResult("grant-trust", result); } } else { if (!result.isPrivate) { queueTelemetryFromModuleVerificationResult("not-grant-trust", result); } } result = await moduleVerifier.verify( base, files, options.packageName || "" ); } switch (result.status) { case ModuleVerificationStatus.Compromised: console.log("package is compromised: " + result.reason); return false; case ModuleVerificationStatus.Unsigned: console.log("package is unsigned: " + result.reason); return false; case ModuleVerificationStatus.Untrusted: console.log("package is untrusted"); return false; case ModuleVerificationStatus.Trusted: console.log("package is trusted"); return true; } } private async verifyDirectory( path: string, options: VerifyOptions ): Promise<boolean> { // Telemetry sending is done directly inside ModuleHierarchyVerifier, per package. let moduleHierarchyVerifier = new ModuleHierarchyVerifier( path, options.enableTestTrustStore ? new TestTrustStore() : new TrustStore() ); let results = await moduleHierarchyVerifier.verify(); let prompts: inquirer.ConfirmQuestion<{ [id: string]: boolean }>[] = []; for (let path in results) { let result = results[path]; if (result.status == ModuleVerificationStatus.Untrusted) { let identityString = ""; if (result.untrustedIdentity.keybaseUser !== undefined) { identityString = result.untrustedIdentity.keybaseUser + " on keybase.io"; } else { identityString = "public key at " + result.untrustedIdentity.pgpPublicKeyUrl; } if ( prompts.filter( value => value.name !== undefined && basename(value.name) == result.packageName ).length == 0 ) { prompts.push({ name: Buffer.from(path).toString("base64"), type: "confirm", message: "Package '" + result.packageName + "' is not trusted, but is signed by " + identityString + ". " + "Do you want to trust this identity to sign '" + result.packageName + "' now and forever", default: false } as inquirer.ConfirmQuestion<{ [id: string]: boolean }>); } } } if (prompts.length > 0 && !options.nonInteractive) { let didModify = false; const trustResults = await inquirer.prompt(prompts); let trustStore = new TrustStore(); for (let path in trustResults) { let realpath = Buffer.from(path, "base64").toString("ascii"); const result = results[realpath]; if (result.status == ModuleVerificationStatus.Untrusted) { if (trustResults[path]) { await trustStore.addTrusted( result.untrustedIdentity, result.packageName ); didModify = true; if (!result.isPrivate) { queueTelemetryFromModuleVerificationResult("grant-trust", result); } } else { if (!results[realpath].isPrivate) { queueTelemetryFromModuleVerificationResult( "not-grant-trust", result ); } } } } if (didModify) { // Recalculate results now that trust prompts have been answered. results = await moduleHierarchyVerifier.verify(); } } // Show summary of packages. let compromisedCount = 0; let unsignedCount = 0; let untrustedCount = 0; let trustedCount = 0; for (let path in results) { let result = results[path]; switch (result.status) { case ModuleVerificationStatus.Compromised: compromisedCount++; break; case ModuleVerificationStatus.Unsigned: unsignedCount++; break; case ModuleVerificationStatus.Untrusted: untrustedCount++; break; case ModuleVerificationStatus.Trusted: trustedCount++; break; } } console.log("package verification summary:"); console.log(compromisedCount + " compromised"); console.log(unsignedCount + " unsigned"); console.log(untrustedCount + " untrusted"); console.log(trustedCount + " trusted"); if (options.full) { let targetLength = 0; for (let path in results) { if (results[path].packageName.length > targetLength) { targetLength = results[path].packageName.length; } } targetLength += 2; const padRight = (input: string, len: number) => { while (input.length < len) { input = input + " "; } return input; }; console.log(); for (let path in results) { let result = results[path]; let status = "unknown"; switch (result.status) { case ModuleVerificationStatus.Compromised: status = "compromised!"; break; case ModuleVerificationStatus.Unsigned: status = "unsigned"; break; case ModuleVerificationStatus.Untrusted: status = "untrusted"; break; case ModuleVerificationStatus.Trusted: status = "trusted"; break; } console.log( padRight(results[path].packageName, targetLength) + " " + padRight(status, 25) + " " + (result.reason || "") ); } } if ( compromisedCount > 0 || (!options.allowUnsignedPackages && unsignedCount > 0) || untrustedCount > 0 ) { return false; } else { return true; } } }
the_stack
import { UnreachableCode } from '../../resources/not_reached'; import { callOverlayHandler } from '../../resources/overlay_plugin_api'; import { OopsyMistake } from '../../types/oopsy'; import { DeathReport } from './death_report'; import { MistakeObserver, ViewEvent } from './mistake_observer'; import { GetFormattedTime, ShortNamify, Translate } from './oopsy_common'; import { OopsyOptions } from './oopsy_options'; const kCopiedMessage = { en: 'Copied!', de: 'Kopiert!', fr: 'Copiรฉ !', ja: 'ใ‚ณใƒ”ใƒผใ—ใŸ๏ผ', cn: 'ๅทฒๅคๅˆถ๏ผ', ko: '๋ณต์‚ฌ ์™„๋ฃŒ!', }; const errorMessageEnableACTWS = { en: 'Plugins -> OverlayPlugin WSServer -> Stream/Local Overlay -> Start', de: 'Plugins -> OverlayPlugin WSServer -> Stream/Local Overlay -> Start', ko: 'Plugins -> OverlayPlugin WSServer -> Stream/Local ์˜ค๋ฒ„๋ ˆ์ด -> ์‹œ์ž‘', }; export class DeathReportLive { private reportQueue: DeathReport[] = []; private queueTimeoutHandle = 0; constructor(private options: OopsyOptions, private reportElem: HTMLElement) {} // Briefly shows a death report on screen for a few seconds while in combat. // If one is already showing, queues it up to display after. // TODO: add some CSS animation here to fade it in/out? // TODO: should we show the player's death report with no timer while they are dead? public queue(report: DeathReport): void { const timeoutMs = this.options.TimeToShowDeathReportMs; if (timeoutMs <= 0) return; const isFirstReport = this.reportQueue.length === 0; this.reportQueue.push(report); if (isFirstReport) { this.setDeathReport(report); this.queueTimeoutHandle = window.setTimeout(() => this.handleQueue(), timeoutMs); } } private handleQueue(): void { const r = this.reportQueue.shift(); if (!r) { this.cancelQueue(); this.hide(); return; } this.setDeathReport(r); this.queueTimeoutHandle = window.setTimeout( () => this.handleQueue(), this.options.TimeToShowDeathReportMs, ); } // Cancels the queue of death reports and shows this one immediately. public show(report: DeathReport): void { this.cancelQueue(); this.setDeathReport(report); } public mouseOver(report: DeathReport, inCombat: boolean): void { // While in combat, mouseovers interrupt the queue and temporarily show // TODO: should there be no timer and we just show while mouseovering? if (inCombat) { this.cancelQueue(); this.hide(); this.queue(report); } else { this.show(report); } } public hide(): void { while (this.reportElem.lastChild) this.reportElem.removeChild(this.reportElem.lastChild); } private cancelQueue(): void { this.reportQueue = []; window.clearTimeout(this.queueTimeoutHandle); this.queueTimeoutHandle = 0; } private setDeathReport(report: DeathReport) { this.hide(); const container = document.createElement('div'); container.classList.add('livelist-shadow'); this.reportElem.appendChild(container); const titleDiv = document.createElement('div'); titleDiv.classList.add('death-title'); container.appendChild(titleDiv); const titleIcon = document.createElement('div'); titleIcon.classList.add('death-title-icon', 'mistake-icon', 'death'); titleDiv.appendChild(titleIcon); const titleText = document.createElement('div'); titleText.classList.add('death-title-text'); titleText.innerHTML = report.targetName; titleDiv.appendChild(titleText); const closeButton = document.createElement('div'); closeButton.classList.add('death-title-close', 'mistake-icon', 'icon-entry', 'icon-close'); closeButton.addEventListener('click', () => { // Clicking the close button also cancels the queue. Otherwise, you // close one and then another appears seconds later, which seems incorrect. this.cancelQueue(); this.hide(); }); titleDiv.appendChild(closeButton); const detailsDiv = document.createElement('div'); detailsDiv.classList.add('death-details'); container.appendChild(detailsDiv); for (const event of report.parseReportLines()) { this.AppendDetails( detailsDiv, event.timestampStr, event.currentHp?.toString(), event.amountStr, event.amountClass, event.icon, event.text, ); } } private AppendDetails( detailsDiv: HTMLElement, timestampStr: string, currentHp?: string, amount?: string, amountClass?: string, icon?: string, text?: string, ): void { const hpElem = document.createElement('div'); hpElem.classList.add('death-row-hp'); if (currentHp !== undefined) hpElem.innerText = currentHp; detailsDiv.appendChild(hpElem); const damageElem = document.createElement('div'); damageElem.classList.add('death-row-amount'); if (amountClass) damageElem.classList.add(amountClass); if (amount !== undefined) damageElem.innerText = amount; detailsDiv.appendChild(damageElem); const iconElem = document.createElement('div'); iconElem.classList.add('death-row-icon'); if (icon !== undefined) iconElem.classList.add('mistake-icon', icon); detailsDiv.appendChild(iconElem); const textElem = document.createElement('div'); textElem.classList.add('death-row-text'); if (text !== undefined) textElem.innerHTML = text; detailsDiv.appendChild(textElem); const timeElem = document.createElement('div'); timeElem.classList.add('death-row-time'); timeElem.innerText = timestampStr; detailsDiv.appendChild(timeElem); } } export class OopsyLiveList implements MistakeObserver { private container: Element; private iconContainer: HTMLElement; private inCombat = false; private numItems = 0; private items: HTMLElement[] = []; private baseTime?: number; private deathReport?: DeathReportLive; private itemIdxToListener: { [itemIdx: number]: () => void } = {}; constructor(private options: OopsyOptions, private scroller: HTMLElement) { const container = this.scroller.children[0]; if (!container) throw new UnreachableCode(); this.container = container; const reportDiv = document.getElementById('death-report'); if (!reportDiv) throw new UnreachableCode(); if (this.options.DeathReportSide !== 'disabled') this.deathReport = new DeathReportLive(options, reportDiv); document.body.classList.add(`report-side-${this.options.DeathReportSide}`); const iconContainer = document.getElementById('icon-container'); if (!iconContainer) throw new UnreachableCode(); this.iconContainer = iconContainer; const closeDiv = document.getElementById('icon-close'); if (!closeDiv) throw new UnreachableCode(); closeDiv.addEventListener('click', () => { this.Reset(); }); const summaryDiv = document.getElementById('icon-summary'); if (!summaryDiv) throw new UnreachableCode(); summaryDiv.addEventListener('click', () => { const regex = /\w*.html$/; if (!regex.exec(window.location.href)) { console.error(`Unable to parse location for summary: ${window.location.href}`); return; } const url = window.location.href.replace(regex, 'oopsy_summary.html'); callOverlayHandler({ call: 'openWebsiteWithWS', url: url }).catch(() => { console.error(`Failed to open summary`); this.OnMistakeObj(Date.now(), { type: 'fail', text: errorMessageEnableACTWS, }); }); }); this.Reset(); this.SetInCombat(false); } SetInCombat(inCombat: boolean): void { // For usability sake: // - to avoid dungeon trash starting stopping combat and resetting the // list repeatedly, only reset when ACT starts a new encounter. // - for consistency with DPS meters, fflogs, etc, use ACT's encounter // time as the start time, not when game combat becomes true. // - to make it more readable, show/hide old mistakes out of game // combat, and consider early pulls starting game combat early. This // allows for one long dungeon ACT encounter to have multiple early // or late pulls. if (this.inCombat === inCombat) return; this.inCombat = inCombat; if (inCombat) { document.body.classList.remove('out-of-combat'); this.HideOldItems(); } else { // TODO: Add an X button to hide/clear the list. document.body.classList.add('out-of-combat'); this.ShowAllItems(); } } OnMistakeObj(timestamp: number, m: OopsyMistake): void { const report = m.report ? new DeathReport(m.report) : undefined; if (report) this.deathReport?.queue(report); const iconClass = m.type; const blame = m.name ?? m.blame; const blameText = blame ? ShortNamify(blame, this.options.PlayerNicks) + ': ' : ''; const translatedText = Translate(this.options.DisplayLanguage, m.text); if (!translatedText) return; const time = GetFormattedTime(this.baseTime, timestamp); const text = `${blameText}${translatedText}`; const maxItems = this.options.NumLiveListItemsInCombat; // Get an existing row or create a new one. let rowDiv; const itemIdx = this.numItems; if (itemIdx < this.items.length) rowDiv = this.items[itemIdx]; if (!rowDiv) rowDiv = this.MakeRow(); // Clean up / add any event listeners. const listener = this.itemIdxToListener[itemIdx]; if (listener) { rowDiv.removeEventListener('mousemove', listener); delete this.itemIdxToListener[itemIdx]; } if (report) { const func = () => this.deathReport?.mouseOver(report, this.inCombat); rowDiv.addEventListener('mousemove', func); this.itemIdxToListener[itemIdx] = func; } this.numItems++; const iconDiv = document.createElement('div'); iconDiv.classList.add('mistake-icon'); iconDiv.classList.add(iconClass); rowDiv.appendChild(iconDiv); const textDiv = document.createElement('div'); textDiv.classList.add('mistake-text'); textDiv.innerHTML = text; rowDiv.appendChild(textDiv); const timeDiv = document.createElement('div'); timeDiv.classList.add('mistake-time'); timeDiv.innerHTML = time; rowDiv.appendChild(timeDiv); // Hide anything over the limit from the past. if (this.inCombat) { if (this.numItems > maxItems) this.items[this.numItems - maxItems - 1]?.classList.add('hide'); } // Show and scroll to bottom. this.container.classList.remove('hide'); this.iconContainer.classList.remove('hide'); this.scroller.scrollTop = this.scroller.scrollHeight; } private MakeRow(): HTMLElement { const div = document.createElement('div'); div.classList.add('mistake-row'); // click-to-copy function div.addEventListener('click', () => { const mistakeText = div.childNodes[1]?.textContent ?? ''; const mistakeTime = div.childNodes[2]?.textContent; const str = mistakeTime ? `[${mistakeTime}] ${mistakeText}` : mistakeText; const el = document.createElement('textarea'); el.value = str; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); // copied message const msg = document.createElement('div'); msg.classList.add('copied-msg'); msg.innerText = kCopiedMessage[this.options.DisplayLanguage] || kCopiedMessage['en']; msg.style.width = `${div.clientWidth}px`; msg.style.height = `${div.clientHeight}px`; div.appendChild(msg); window.setTimeout(() => { document.body.removeChild(msg); }, 1000); }); this.items.push(div); this.container.appendChild(div); return div; } private ShowAllItems(): void { for (const item of this.items) item.classList.remove('hide'); this.scroller.scrollTop = this.scroller.scrollHeight; } private HideOldItems(): void { const maxItems = this.options.NumLiveListItemsInCombat; for (let i = 0; i < this.items.length - maxItems; ++i) this.items[i]?.classList.add('hide'); } Reset(): void { this.container.classList.add('hide'); this.iconContainer.classList.add('hide'); this.items = []; this.numItems = 0; this.container.innerHTML = ''; this.itemIdxToListener = {}; this.deathReport?.hide(); } OnEvent(event: ViewEvent): void { if (event.type === 'Mistake') this.OnMistakeObj(event.timestamp, event.mistake); else if (event.type === 'StartEncounter') this.StartEncounter(event.timestamp); else if (event.type === 'ChangeZone') this.OnChangeZone(); } OnSyncEvents(_events: ViewEvent[]): void { // don't bother syncing for the live list } StartEncounter(timestamp: number): void { this.Reset(); this.baseTime = timestamp; } OnChangeZone(): void { this.Reset(); } }
the_stack
import { expect } from '@instructure/ui-test-utils' import { hash } from '../hash' describe('hash', () => { it('should error if supplied value is undefined', () => { let error = false try { expect(hash(undefined)).to.equal('') } catch (err: any) { error = true } expect(error).to.be.true() }) it('should allow specifying a max length', () => { const result = hash('some value', 4) expect(result).to.exist() expect(result.length).to.equal(4) }) describe('strings', () => { it('hashes two identical strings to the same value', () => { const result1 = hash('Some string with3_ distinct$() !_)(* va1ues') const result2 = hash('Some string with3_ distinct$() !_)(* va1ues') expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes different strings to different values', () => { const result1 = hash('Some string with3_ distinct$() !_)(* va1ues') const result2 = hash('Some string with3_ distinct$() !_)(* va1ues ') expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) }) describe('numbers', () => { it('hashes two identical numbers to the same value', () => { const result1 = hash(532) const result2 = hash(532) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two different numbers to different values', () => { const result1 = hash(532) const result2 = hash(5321) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) }) describe('booleans', () => { it('hashes true to the same value', () => { const result1 = hash(true) const result2 = hash(true) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes false to the same value', () => { const result1 = hash(false) const result2 = hash(false) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes true and false to different values', () => { const result1 = hash(true) const result2 = hash(false) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) }) describe('functions', () => { it('hashes two identical arrow function expressions to the same value', () => { const result1 = hash(() => 'foo') const result2 = hash(() => 'foo') expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two different arrow function expressions to different values', () => { const result1 = hash(() => 'foo') const result2 = hash(() => 'bar') expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes two identical functions to the same value', () => { const result1 = hash(function myFunc() { const foo = 1 const bar = 2 return foo + bar }) const result2 = hash(function myFunc() { const foo = 1 const bar = 2 return foo + bar }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two identical functions with different names to different values', () => { const result1 = hash(function myFunc() { const foo = 1 const bar = 2 return foo + bar }) const result2 = hash(function myFunc1() { const foo = 1 const bar = 2 return foo + bar }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes two identical functions with different bodies to different values', () => { const result1 = hash(function myFunc() { const foo = 1 const bar = 2 return foo + bar }) const result2 = hash(function myFunc() { const foo = 1 const baz = 2 return foo + baz }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) }) describe('objects', () => { it('hashes two identical simple objects to the same value', () => { const result1 = hash({ foo: 'foo', bar: 'bar', baz: 'baz' }) const result2 = hash({ foo: 'foo', bar: 'bar', baz: 'baz' }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two identical simple objects with rearranged keys to the same value', () => { const result1 = hash({ foo: 'foo', bar: 'bar', baz: 'baz' }) const result2 = hash({ baz: 'baz', foo: 'foo', bar: 'bar' }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two different simple objects to different values', () => { const result1 = hash({ foo: 'foo', bar: 'bar', baz: 'baz' }) const result2 = hash({ foo: 'foo', bar: 'ba', baz: 'baz' }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes two identical complex objects to the same value', () => { const result1 = hash({ foo: 'foo', bar: [ { qux: 'qux', qang: 'qaz' }, { ['foo-bar']: true } ], baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) const result2 = hash({ foo: 'foo', bar: [ { qux: 'qux', qang: 'qaz' }, { ['foo-bar']: true } ], baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two identical complex objects with rearranged keys to the same value', () => { const result1 = hash({ foo: 'foo', bar: [ { qux: 'qux', qang: 'qaz' }, { ['foo-bar']: true } ], baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) const result2 = hash({ bar: [ { qux: 'qux', qang: 'qaz' }, { ['foo-bar']: true } ], foo: 'foo', baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two different simple objects to different values', () => { const result1 = hash({ foo: 'foo', bar: 'bar', baz: 'baz' }) const result2 = hash({ foo: 'foo', bar: 'ba', baz: 'baz' }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes two different complex objects to the same value', () => { const result1 = hash({ foo: 'foo', bar: [ { qux: 'qux', qang: 'qaz' }, { ['foobar']: true } ], baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) const result2 = hash({ foo: 'foo', bar: [ { qux: 'qux', qang: 'qaz' }, { ['foo-bar']: true } ], baz: () => { const hello = 'hello' const world = 'world' return hello + world } }) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) }) describe('classes', () => { it('hashes two identical classes to the same value', () => { const result1 = hash( class Something { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something' } } ) const result2 = hash( class Something { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something' } } ) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) it('hashes two classes with different content to different values', () => { const result1 = hash( class Something { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something' } } ) const result2 = hash( class Something { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something else' } } ) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes two classes with different names to different values', () => { const result1 = hash( class Something { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something' } } ) const result2 = hash( class Somethin { private _settings: number constructor(settings: number) { this._settings = settings } get settings() { return this._settings } doSomething = () => { return 'doing something' } } ) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.not.equal(result2) }) it('hashes null to the same value', () => { const result1 = hash(null) const result2 = hash(null) expect(result1).to.exist() expect(result2).to.exist() expect(result1).to.equal(result2) }) }) })
the_stack
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react'; import { useCallback } from 'react'; import { Box } from 'reakit/Box'; import { Button } from 'reakit/Button'; import { Group } from 'reakit/Group'; import { Toolbar as ReakitToolbar, ToolbarItem as ReakitToolbarItem, ToolbarSeparator as ReakitToolbarSeparator, ToolbarStateReturn, useToolbarState, } from 'reakit/Toolbar'; import { Tooltip, TooltipReference, useTooltipState } from 'reakit/Tooltip'; import { VisuallyHidden } from 'reakit/VisuallyHidden'; import { AnyExtension, CommandDecoratorMessageProps, cx, ErrorConstant, Except, includes, invariant, } from '@remirror/core'; import { useActive, useChainedCommands, useCommands, useHelpers, useI18n, useRemirrorContext, } from '@remirror/react-core'; import { ComponentsTheme } from '@remirror/theme'; import { CommandIconComponent } from '../components'; import { DropdownComponent } from '../menu'; import { useTheme } from '../providers'; import { BaseButtonItem, ComponentItem, ToolbarButtonItem, ToolbarCommandButtonItem, ToolbarGroupItem, ToolbarItem, ToolbarItemUnion, ToolbarMenuItem, } from '../react-component-types'; import { getCommandOptionValue, getShortcutString, getUiShortcutString, } from '../react-component-utils'; interface BaseToolbarProps extends BaseButtonItem { /** * The toolbar state generated by `Reakit` (the underlying UI library). */ toolbarState: ToolbarStateReturn; } interface ToolbarProps extends Except<ToolbarItem, 'type'> {} /** * This is the menu that can be placed at the top of the editor. */ export const Toolbar = (props: ToolbarProps): JSX.Element => { const { items, loop, label, refocusEditor, focusable } = props; const toolbarState = useToolbarState({ loop }); const focusableProps = focusable === false ? { focusable: false, tabIndex: -1 } : {}; return ( <ReakitToolbar {...toolbarState} {...focusableProps} aria-label={label}> {items.map(getToolbarComponent({ toolbarState, refocusEditor }))} </ReakitToolbar> ); }; interface ToolbarCommandButtonProps extends BaseToolbarProps { /** * The command button item. */ item: ToolbarCommandButtonItem; } const ToolbarCommandButton = (props: ToolbarCommandButtonProps) => { // Gather all the hooks used for this component. const { toolbarState, item } = props; const commands = useCommands(); const chain = useChainedCommands(); const { getCommandOptions } = useHelpers(); const context = useRemirrorContext(); const { t } = useI18n(); const refocusEditor = item.refocusEditor ?? props.refocusEditor ?? false; // Will cause the editor to rerender for each state update. const active = useActive<AnyExtension>(); const { display, commandName: name, attrs, displayShortcut = true } = item; const options = getCommandOptions(name); if (!options) { return <></>; } const enabled = commands[name]?.isEnabled(attrs) ?? false; const isActive = active[options.name]?.(attrs) ?? false; const commandProps: CommandDecoratorMessageProps = { active: isActive, attrs, enabled, t }; const description = getCommandOptionValue(options.description, commandProps); const label = getCommandOptionValue(options.label, commandProps); const icon = getCommandOptionValue(options.icon, commandProps); const shortcutString = displayShortcut && options.shortcut ? ` (${getShortcutString(getUiShortcutString(options.shortcut, attrs ?? {}), { t })})` : ''; const onClick = (event: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => { if (item.onClick) { item.onClick(event, context); return; } if (options.disableChaining) { commands[name]?.(attrs); return; } const command = chain[name]?.(attrs); if (refocusEditor) { command?.focus?.(); } command?.run(); }; switch (display) { case 'icon': { invariant(label && icon, { code: ErrorConstant.REACT_CONTROLLED, message: `Both label and icon are needed for the command: ${name} in extension: ${options.name}`, }); return ( <BaseToolbarButton toolbarState={toolbarState} disabled={!enabled} focusable={enabled} tooltip={`${label}${shortcutString}`} onClick={onClick} active={isActive} > <VisuallyHidden>{label}</VisuallyHidden> <CommandIconComponent icon={icon} /> </BaseToolbarButton> ); } case 'label': { invariant(label && description, { code: ErrorConstant.REACT_CONTROLLED, message: `Both label and description are needed for the command: ${name} in extension: ${options.name}`, }); return ( <BaseToolbarButton toolbarState={toolbarState} disabled={!enabled} focusable={enabled} tooltip={`${description}${shortcutString}`} onClick={onClick} active={isActive} > {label} </BaseToolbarButton> ); } default: { invariant(label && icon, { code: ErrorConstant.REACT_CONTROLLED, message: `Icon, label and description are needed for the command: ${name} in extension: ${options.name}`, }); return ( <BaseToolbarButton toolbarState={toolbarState} disabled={!enabled} focusable={enabled} tooltip={`${label}${shortcutString}`} onClick={onClick} active={isActive} > {display === 'label-icon' && <Box as='span'> {label}</Box>} <CommandIconComponent icon={icon} />{' '} {display === 'icon-label' && <Box as='span'> {label}</Box>} </BaseToolbarButton> ); } } }; interface BaseToolbarButtonProps extends BaseToolbarProps { children: ReactNode; active: boolean; tooltip?: string; tooltipClass?: string; disabled?: boolean; focusable?: boolean; className?: string; onClick: (event: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void; } const BaseToolbarButton = (props: BaseToolbarButtonProps) => { const { toolbarState, children, tooltip, disabled, focusable, onClick, tooltipClass, active, className, } = props; const tooltipState = useTooltipState({ gutter: 5 }); const themeProps = useTheme({ className: tooltipClass }); return ( <> <TooltipReference {...tooltipState}> {(props) => ( <ReakitToolbarItem {...props} {...toolbarState} as={Button} disabled={disabled} focusable={focusable} onClick={onClick} className={cx(className, active && ComponentsTheme.BUTTON_ACTIVE)} > {children} </ReakitToolbarItem> )} </TooltipReference> {tooltip && ( <Tooltip {...tooltipState} style={themeProps.style} className={cx(themeProps.className)}> {tooltip} </Tooltip> )} </> ); }; interface ToolbarSeparatorProps extends BaseToolbarProps {} /** * The divider component */ const ToolbarSeparator = (props: ToolbarSeparatorProps) => { return <ReakitToolbarSeparator {...props.toolbarState} />; }; interface ToolbarGroupProps extends BaseToolbarProps { /** * The group item configuration. */ item: ToolbarGroupItem; } /** * The [[`Group`]] component */ const ToolbarGroup = (props: ToolbarGroupProps) => { const { toolbarState, refocusEditor, item: group } = props; const startSeparator = includes(['start', 'both'], group.separator) && ( <ToolbarSeparator toolbarState={toolbarState} /> ); const endSeparator = includes(['end', 'both'], group.separator) && ( <ToolbarSeparator toolbarState={toolbarState} /> ); return ( <> {startSeparator} <Group aria-label={group.label}> {group.items.map(getToolbarComponent({ toolbarState, refocusEditor }))} </Group> {endSeparator} </> ); }; interface ToolbarButtonProps extends BaseToolbarProps { /** * The command button item. */ item: ToolbarButtonItem; } const ToolbarButton = (props: ToolbarButtonProps) => { const { toolbarState, focusable, item } = props; const context = useRemirrorContext(); const refocusEditor = item.refocusEditor ?? props.refocusEditor ?? false; const { disabled, label, icon, active = false } = item; const onClick = useCallback( (event: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => { item.onClick(event, context); if (refocusEditor) { requestAnimationFrame(() => context.commands.focus()); } }, [refocusEditor, context, item], ); return ( <BaseToolbarButton toolbarState={toolbarState} disabled={disabled} focusable={focusable} onClick={onClick} active={active} > <Box as='span'>{label}</Box> {icon && <CommandIconComponent icon={icon} />} </BaseToolbarButton> ); }; /** * Create a mapping function for generating a toolbar component */ function getToolbarComponent(props: BaseToolbarProps) { // eslint-disable-next-line react/display-name return (item: ToolbarItemUnion, index: number, _: ToolbarItemUnion[]) => { const { toolbarState, refocusEditor } = props; switch (item.type) { case ComponentItem.ToolbarCommandButton: return ( <ToolbarCommandButton item={item} toolbarState={toolbarState} refocusEditor={refocusEditor} key={item.key ?? index} /> ); case ComponentItem.ToolbarButton: return ( <ToolbarButton item={item} toolbarState={toolbarState} refocusEditor={refocusEditor} key={item.key ?? index} /> ); case ComponentItem.ToolbarGroup: return ( <ToolbarGroup item={item} toolbarState={toolbarState} refocusEditor={refocusEditor} key={item.key ?? index} /> ); case ComponentItem.ToolbarSeparator: return <ToolbarSeparator toolbarState={toolbarState} key={item.key ?? index} />; case ComponentItem.ToolbarElement: return item.element; case ComponentItem.ToolbarComponent: return ( <item.Component Wrapper={ReakitToolbarItem} toolbarState={toolbarState} key={item.key ?? index} /> ); case ComponentItem.ToolbarMenu: return <ToolbarMenu item={item} toolbarState={toolbarState} key={item.key ?? index} />; } }; } interface ToolbarMenuProps extends BaseToolbarProps { item: ToolbarMenuItem; } const ToolbarMenu = (props: ToolbarMenuProps): JSX.Element => { const { item, toolbarState } = props; const { items, label, menuLabel } = item; return ( <ReakitToolbarItem {...toolbarState} as={DropdownComponent} menuItems={items} label={label} menuLabel={menuLabel} /> ); };
the_stack
import GraphLayout from './GraphLayout'; import Rectangle from '../../geometry/Rectangle'; import { getNumber, getValue } from '../../../util/Utils'; import { DEFAULT_STARTSIZE } from '../../../util/Constants'; import { Graph } from '../../Graph'; import Cell from '../../cell/datatypes/Cell'; import Geometry from '../../geometry/Geometry'; import CellArray from '../../cell/datatypes/CellArray'; /** * Class: mxStackLayout * * Extends <mxGraphLayout> to create a horizontal or vertical stack of the * child vertices. The children do not need to be connected for this layout * to work. * * Example: * * (code) * let layout = new mxStackLayout(graph, true); * layout.execute(graph.getDefaultParent()); * (end) * * Constructor: mxStackLayout * * Constructs a new stack layout layout for the specified graph, * spacing, orientation and offset. */ class StackLayout extends GraphLayout { constructor( graph: Graph, horizontal: boolean, spacing: number, x0: number, y0: number, border: number ) { super(graph); this.horizontal = horizontal != null ? horizontal : true; this.spacing = spacing != null ? spacing : 0; this.x0 = x0 != null ? x0 : 0; this.y0 = y0 != null ? y0 : 0; this.border = border != null ? border : 0; } /** * Specifies the orientation of the layout. */ horizontal: boolean; /** * Specifies the spacing between the cells. */ spacing: number; /** * Specifies the horizontal origin of the layout. */ x0: number; /** * Specifies the vertical origin of the layout. */ y0: number; /** * Border to be added if fill is true. */ border: number = 0; /** * Top margin for the child area. */ marginTop: number = 0; /** * Top margin for the child area. */ marginLeft: number = 0; /** * Top margin for the child area. */ marginRight: number = 0; /** * Top margin for the child area. */ marginBottom: number = 0; /** * Boolean indicating if the location of the first cell should be kept, that is, it will not be moved to x0 or y0. */ keepFirstLocation: boolean = false; /** * Boolean indicating if dimension should be changed to fill out the parent cell. */ fill: boolean = false; /** * If the parent should be resized to match the width/height of the stack. */ resizeParent: boolean = false; /** * Use maximum of existing value and new value for resize of parent. */ resizeParentMax: boolean = false; /** * If the last element should be resized to fill out the parent. */ resizeLast: boolean = false; /** * Value at which a new column or row should be created. */ wrap: number | null = null; /** * If the strokeWidth should be ignored. */ borderCollapse: boolean = true; /** * If gaps should be allowed in the stack. */ allowGaps: boolean = false; /** * Grid size for alignment of position and size. */ gridSize: number = 0; /** * Returns horizontal. */ isHorizontal(): boolean { return this.horizontal; } /** * Implements mxGraphLayout.moveCell. */ moveCell(cell: Cell, x: number, y: number): void { const model = this.graph.getModel(); const parent = cell.getParent(); const horizontal = this.isHorizontal(); if (cell != null && parent != null) { let i = 0; let last = 0; const childCount = parent.getChildCount(); let value = horizontal ? x : y; const pstate = this.graph.getView().getState(parent); if (pstate != null) { value -= horizontal ? pstate.x : pstate.y; } value /= this.graph.view.scale; for (i = 0; i < childCount; i += 1) { const child = parent.getChildAt(i); if (child !== cell) { const bounds = child.getGeometry(); if (bounds != null) { const tmp = horizontal ? bounds.x + bounds.width / 2 : bounds.y + bounds.height / 2; if (last <= value && tmp > value) { break; } last = tmp; } } } // Changes child order in parent let idx = parent.getIndex(cell); idx = Math.max(0, i - (i > idx ? 1 : 0)); model.add(parent, cell, idx); } } /** * Returns the size for the parent container or the size of the graph container if the parent is a layer or the root of the model. */ getParentSize(parent: Cell): void { const model = this.graph.getModel(); let pgeo = parent.getGeometry(); // Handles special case where the parent is either a layer with no // geometry or the current root of the view in which case the size // of the graph's container will be used. if ( this.graph.container != null && ((pgeo == null && model.isLayer(parent)) || parent === this.graph.getView().currentRoot) ) { const width = this.graph.container.offsetWidth - 1; const height = this.graph.container.offsetHeight - 1; pgeo = new Rectangle(0, 0, width, height); } return pgeo; } /** * Returns the cells to be layouted. */ getLayoutCells(parent: Cell): CellArray { const model = this.graph.getModel(); const childCount = parent.getChildCount(); const cells = new CellArray(); for (let i = 0; i < childCount; i += 1) { const child = parent.getChildAt(i); if (!this.isVertexIgnored(child) && this.isVertexMovable(child)) { cells.push(child); } } if (this.allowGaps) { cells.sort((c1, c2) => { const geo1 = c1.getGeometry(); const geo2 = c2.getGeometry(); return this.horizontal ? geo1.x === geo2.x ? 0 : geo1.x > geo2.x > 0 ? 1 : -1 : geo1.y === geo2.y ? 0 : geo1.y > geo2.y > 0 ? 1 : -1; }); } return cells; } /** * Snaps the given value to the grid size. */ snap(value): void { if (this.gridSize != null && this.gridSize > 0) { value = Math.max(value, this.gridSize); if (value / this.gridSize > 1) { const mod = value % this.gridSize; value += mod > this.gridSize / 2 ? this.gridSize - mod : -mod; } } return value; } /** * Implements mxGraphLayout.execute. */ execute(parent: Cell): void { if (parent != null) { const pgeo = this.getParentSize(parent); const horizontal = this.isHorizontal(); const model = this.graph.getModel(); let fillValue = null; if (pgeo != null) { fillValue = horizontal ? pgeo.height - this.marginTop - this.marginBottom : pgeo.width - this.marginLeft - this.marginRight; } fillValue -= 2 * this.border; let x0 = this.x0 + this.border + this.marginLeft; let y0 = this.y0 + this.border + this.marginTop; // Handles swimlane start size if (this.graph.isSwimlane(parent)) { // Uses computed style to get latest const style = this.graph.getCellStyle(parent); let start = getNumber(style, 'startSize', DEFAULT_STARTSIZE); const horz = getValue(style, 'horizontal', true) == 1; if (pgeo != null) { if (horz) { start = Math.min(start, pgeo.height); } else { start = Math.min(start, pgeo.width); } } if (horizontal === horz) { fillValue -= start; } if (horz) { y0 += start; } else { x0 += start; } } model.beginUpdate(); try { let tmp = 0; let last = null; let lastValue = 0; let lastChild = null; const cells = this.getLayoutCells(parent); for (let i = 0; i < cells.length; i += 1) { const child = cells[i]; let geo = child.getGeometry(); if (geo != null) { geo = geo.clone(); if (this.wrap != null && last != null) { if ( (horizontal && last.x + last.width + geo.width + 2 * this.spacing > this.wrap) || (!horizontal && last.y + last.height + geo.height + 2 * this.spacing > this.wrap) ) { last = null; if (horizontal) { y0 += tmp + this.spacing; } else { x0 += tmp + this.spacing; } tmp = 0; } } tmp = Math.max(tmp, horizontal ? geo.height : geo.width); let sw = 0; if (!this.borderCollapse) { const childStyle = this.graph.getCellStyle(child); sw = getNumber(childStyle, 'strokeWidth', 1); } if (last != null) { const temp = lastValue + this.spacing + Math.floor(sw / 2); if (horizontal) { geo.x = this.snap( (this.allowGaps ? Math.max(temp, geo.x) : temp) - this.marginLeft ) + this.marginLeft; } else { geo.y = this.snap( (this.allowGaps ? Math.max(temp, geo.y) : temp) - this.marginTop ) + this.marginTop; } } else if (!this.keepFirstLocation) { if (horizontal) { geo.x = this.allowGaps && geo.x > x0 ? Math.max(this.snap(geo.x - this.marginLeft) + this.marginLeft, x0) : x0; } else { geo.y = this.allowGaps && geo.y > y0 ? Math.max(this.snap(geo.y - this.marginTop) + this.marginTop, y0) : y0; } } if (horizontal) { geo.y = y0; } else { geo.x = x0; } if (this.fill && fillValue != null) { if (horizontal) { geo.height = fillValue; } else { geo.width = fillValue; } } if (horizontal) { geo.width = this.snap(geo.width); } else { geo.height = this.snap(geo.height); } this.setChildGeometry(child, geo); lastChild = child; last = geo; if (horizontal) { lastValue = last.x + last.width + Math.floor(sw / 2); } else { lastValue = last.y + last.height + Math.floor(sw / 2); } } } if (this.resizeParent && pgeo != null && last != null && !parent.isCollapsed()) { this.updateParentGeometry(parent, pgeo, last); } else if (this.resizeLast && pgeo != null && last != null && lastChild != null) { if (horizontal) { last.width = pgeo.width - last.x - this.spacing - this.marginRight - this.marginLeft; } else { last.height = pgeo.height - last.y - this.spacing - this.marginBottom; } this.setChildGeometry(lastChild, last); } } finally { model.endUpdate(); } } } /** * Function: setChildGeometry * * Sets the specific geometry to the given child cell. * * Parameters: * * child - The given child of <mxCell>. * geo - The specific geometry of <mxGeometry>. */ setChildGeometry(child: Cell, geo: Geometry) { const geo2 = child.getGeometry(); if ( geo2 == null || geo.x !== geo2.x || geo.y !== geo2.y || geo.width !== geo2.width || geo.height !== geo2.height ) { this.graph.getModel().setGeometry(child, geo); } } /** * Function: updateParentGeometry * * Updates the geometry of the given parent cell. * * Parameters: * * parent - The given parent of <mxCell>. * pgeo - The new <mxGeometry> for parent. * last - The last <mxGeometry>. */ updateParentGeometry(parent: Cell, pgeo: Geometry, last: Geometry) { const horizontal = this.isHorizontal(); const model = this.graph.getModel(); const pgeo2 = pgeo.clone(); if (horizontal) { const tmp = last.x + last.width + this.marginRight + this.border; if (this.resizeParentMax) { pgeo2.width = Math.max(pgeo2.width, tmp); } else { pgeo2.width = tmp; } } else { const tmp = last.y + last.height + this.marginBottom + this.border; if (this.resizeParentMax) { pgeo2.height = Math.max(pgeo2.height, tmp); } else { pgeo2.height = tmp; } } if ( pgeo.x !== pgeo2.x || pgeo.y !== pgeo2.y || pgeo.width !== pgeo2.width || pgeo.height !== pgeo2.height ) { model.setGeometry(parent, pgeo2); } } } export default StackLayout;
the_stack
import Alert from '@Bootstrap/Alert'; import Breadcrumb from '@Bootstrap/Breadcrumb'; import Button from '@Bootstrap/Button'; import ButtonGroup from '@Bootstrap/ButtonGroup'; import Layout from '@Components/Shared/Layout'; import PVPreviewKnockout from '@Components/Shared/Partials/Song/PVPreviewKnockout'; import SongTypeLabel from '@Components/Shared/Partials/Song/SongTypeLabel'; import useRouteParamsTracking from '@Components/useRouteParamsTracking'; import useStoreWithUpdateResults from '@Components/useStoreWithUpdateResults'; import useVocaDbTitle from '@Components/useVocaDbTitle'; import SongVoteRating from '@Models/SongVoteRating'; import SongType from '@Models/Songs/SongType'; import SongRepository from '@Repositories/SongRepository'; import UserRepository from '@Repositories/UserRepository'; import EntryUrlMapper from '@Shared/EntryUrlMapper'; import HttpClient from '@Shared/HttpClient'; import UrlMapper from '@Shared/UrlMapper'; import { SearchType } from '@Stores/Search/SearchStore'; import RankingsStore from '@Stores/Song/RankingsStore'; import classNames from 'classnames'; import { runInAction } from 'mobx'; import { observer } from 'mobx-react-lite'; import moment from 'moment'; import qs from 'qs'; import React from 'react'; import { useTranslation } from 'react-i18next'; import { Link } from 'react-router-dom'; const httpClient = new HttpClient(); const urlMapper = new UrlMapper(vdb.values.baseAddress); const songRepo = new SongRepository(httpClient, vdb.values.baseAddress); const userRepo = new UserRepository(httpClient, urlMapper); const rankingsStore = new RankingsStore( httpClient, urlMapper, songRepo, userRepo, vdb.values.languagePreference, ); const SongRankings = observer( (): React.ReactElement => { const { t } = useTranslation(['Resources', 'ViewRes', 'ViewRes.Song']); useVocaDbTitle(vdb.values.rankingsTitle, true); useStoreWithUpdateResults(rankingsStore); useRouteParamsTracking(rankingsStore, true); return ( <Layout title={vdb.values.rankingsTitle} parents={ <> <Breadcrumb.Item linkAs={Link} linkProps={{ to: `/Search?${qs.stringify({ searchType: SearchType.Song })}`, }} > {t('ViewRes:Shared.Songs')} </Breadcrumb.Item> </> } > <ButtonGroup> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.durationHours = 24; }) } className={classNames( rankingsStore.durationHours === 24 && 'active', )} > {t('ViewRes.Song:Rankings.DurationDaily')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.durationHours = 168; }) } className={classNames( rankingsStore.durationHours === 168 && 'active', )} > {t('ViewRes.Song:Rankings.DurationWeekly')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.durationHours = 720; }) } className={classNames( rankingsStore.durationHours === 720 && 'active', )} > {t('ViewRes.Song:Rankings.DurationMonthly')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.durationHours = undefined; }) } className={classNames( rankingsStore.durationHours === undefined && 'active', )} > {t('ViewRes.Song:Rankings.DurationOverall')} </Button> </ButtonGroup>{' '} <ButtonGroup> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.dateFilterType = 'CreateDate'; }) } className={classNames( rankingsStore.dateFilterType === 'CreateDate' && 'active', !rankingsStore.durationHours && 'disabled', )} title={t('ViewRes.Song:Rankings.FilterCreateDateDescription')} > {t('ViewRes.Song:Rankings.FilterCreateDate')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.dateFilterType = 'PublishDate'; }) } className={classNames( rankingsStore.dateFilterType === 'PublishDate' && 'active', !rankingsStore.durationHours && 'disabled', )} title={t('ViewRes.Song:Rankings.FilterPublishDateDescription')} > {t('ViewRes.Song:Rankings.FilterPublishDate')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.dateFilterType = 'Popularity'; }) } className={classNames( rankingsStore.dateFilterType === 'Popularity' && 'active', !rankingsStore.durationHours && 'disabled', )} title={t('ViewRes.Song:Rankings.FilterPopularityDescription')} > {t('ViewRes.Song:Rankings.FilterPopularity')} </Button> </ButtonGroup>{' '} <ButtonGroup> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.vocalistSelection = undefined; }) } className={classNames( rankingsStore.vocalistSelection === undefined && 'active', )} > {t('ViewRes.Song:Rankings.VocalistAll')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.vocalistSelection = 'Vocaloid'; }) } className={classNames( rankingsStore.vocalistSelection === 'Vocaloid' && 'active', )} > {t('ViewRes.Song:Rankings.VocalistVocaloid')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.vocalistSelection = 'UTAU'; }) } className={classNames( rankingsStore.vocalistSelection === 'UTAU' && 'active', )} > {t('ViewRes.Song:Rankings.VocalistUTAU')} </Button> <Button href="#" onClick={(): void => runInAction(() => { rankingsStore.vocalistSelection = 'Other'; }) } className={classNames( rankingsStore.vocalistSelection === 'Other' && 'active', )} > {t('ViewRes.Song:Rankings.VocalistOther')} </Button> </ButtonGroup> {rankingsStore.songs.length === 0 ? ( <Alert variant="alert" className="withMargin"> {t('ViewRes.Song:Rankings.NoSongs')} </Alert> ) : ( <table className="table table-striped"> <thead> <tr> <th></th> <th colSpan={2}>{t('ViewRes.Song:Rankings.ColName')}</th> <th>{t('ViewRes.Song:Rankings.ColPublished')}</th> <th>{t('ViewRes.Song:Rankings.ColTags')}</th> <th>{t('ViewRes.Song:Rankings.ColRating')}</th> </tr> </thead> <tbody> {rankingsStore.songs.map((song, index) => ( <tr key={song.id}> <td style={{ width: '30px' }}> <h1>{index + 1}</h1> </td> <td style={{ width: '80px' }}> {song.thumbUrl && ( <a href={EntryUrlMapper.details_song(song)} title={song.additionalNames} > {/* eslint-disable-next-line jsx-a11y/alt-text */} <img src={song.thumbUrl} title="Cover picture" /* TODO: localize */ className="coverPicThumb img-rounded" referrerPolicy="same-origin" /> </a> )} </td> <td> {song.previewStore && song.previewStore.pvServices && ( <div className="pull-right"> <Button onClick={(): void => song.previewStore?.togglePreview() } className={classNames( 'previewSong', song.previewStore.preview && 'active', )} href="#" > <i className="icon-film" />{' '} {t('ViewRes.Song:Rankings.Preview')} </Button> </div> )} <a href={EntryUrlMapper.details_song(song)} title={song.additionalNames} > {song.name} </a>{' '} <SongTypeLabel songType={ SongType[song.songType as keyof typeof SongType] } />{' '} {rankingsStore .getPVServiceIcons(song.pvServices) .map((icon, index) => ( <React.Fragment key={icon.service}> {index > 0 && ' '} {/* eslint-disable-next-line jsx-a11y/alt-text */} <img src={icon.url} title={icon.service} /> </React.Fragment> ))} {false /* TODO */ && ( <> {' '} <span className="icon heartIcon" title={t( `Resources:SongVoteRatingNames.${SongVoteRating.Favorite}`, )} /> </> )} {false /* TODO */ && ( <> {' '} <span className="icon starIcon" title={t( `Resources:SongVoteRatingNames.${SongVoteRating.Like}`, )} /> </> )} <br /> <small className="extraInfo">{song.artistString}</small> {song.previewStore && song.previewStore.pvServices && ( <PVPreviewKnockout previewStore={song.previewStore} getPvServiceIcons={rankingsStore.getPVServiceIcons} /> )} </td> <td>{moment(song.publishDate).format('l')}</td> <td className="search-tags-column"> {song.tags && song.tags.length > 0 && ( <> <i className="icon icon-tags fix-icon-margin" />{' '} {song.tags.map((tag, index) => ( <React.Fragment key={tag.tag.id}> {index > 0 && <span>, </span>} <a href={rankingsStore.getTagUrl(tag)} title={tag.tag.additionalNames} > {tag.tag.name} </a> </React.Fragment> ))} </> )} </td> <td> <span>{song.ratingScore}</span>{' '} {t('ViewRes.Song:Rankings.TotalScore')} </td> </tr> ))} </tbody> </table> )} </Layout> ); }, ); export default SongRankings;
the_stack
import { memoizeOne } from '@bigcommerce/memoize'; import { omit, values } from 'lodash'; import { Address } from '../address'; import { BillingAddress } from '../billing'; import { Cart } from '../cart'; import { createSelector } from '../common/selector'; import { cloneResult as clone } from '../common/utility'; import { FlashMessage, FlashMessageType, StoreConfig } from '../config'; import { Coupon, GiftCertificate } from '../coupon'; import { Customer } from '../customer'; import { FormField } from '../form'; import { Country } from '../geography'; import { Order } from '../order'; import { PaymentMethod } from '../payment'; import { CardInstrument, PaymentInstrument } from '../payment/instrument'; import { Consignment, ShippingOption } from '../shipping'; import { SignInEmail } from '../signin-email'; import Checkout from './checkout'; import InternalCheckoutSelectors from './internal-checkout-selectors'; export type Instrument = CardInstrument; /** * Responsible for getting the state of the current checkout. * * This object has a set of methods that allow you to get a specific piece of * checkout information, such as shipping and billing details. */ export default interface CheckoutStoreSelector { /** * Gets the current checkout. * * @returns The current checkout if it is loaded, otherwise undefined. */ getCheckout(): Checkout | undefined; /** * Gets the current order. * * @returns The current order if it is loaded, otherwise undefined. */ getOrder(): Order | undefined; /** * Gets the checkout configuration of a store. * * @returns The configuration object if it is loaded, otherwise undefined. */ getConfig(): StoreConfig | undefined; /** * Gets the sign-in email. * * @returns The sign-in email object if sent, otherwise undefined */ getSignInEmail(): SignInEmail | undefined; /** * Gets the shipping address of the current checkout. * * If the address is partially complete, it may not have shipping options * associated with it. * * @returns The shipping address object if it is loaded, otherwise * undefined. */ getShippingAddress(): Address | undefined; /** * Gets a list of shipping options available for the shipping address. * * If there is no shipping address assigned to the current checkout, the * list of shipping options will be empty. * * @returns The list of shipping options if any, otherwise undefined. */ getShippingOptions(): ShippingOption[] | undefined; /** * Gets a list of consignments. * * If there are no consignments created for to the current checkout, the * list will be empty. * * @returns The list of consignments if any, otherwise undefined. */ getConsignments(): Consignment[] | undefined; /** * Gets the selected shipping option for the current checkout. * * @returns The shipping option object if there is a selected option, * otherwise undefined. */ getSelectedShippingOption(): ShippingOption | undefined; /** * Gets a list of countries available for shipping. * * @returns The list of countries if it is loaded, otherwise undefined. */ getShippingCountries(): Country[] | undefined; /** * Gets the billing address of an order. * * @returns The billing address object if it is loaded, otherwise undefined. */ getBillingAddress(): BillingAddress | undefined; /** * Gets a list of countries available for billing. * * @returns The list of countries if it is loaded, otherwise undefined. */ getBillingCountries(): Country[] | undefined; /** * Gets a list of payment methods available for checkout. * * @returns The list of payment methods if it is loaded, otherwise undefined. */ getPaymentMethods(): PaymentMethod[] | undefined; /** * Gets a payment method by an id. * * The method returns undefined if unable to find a payment method with the * specified id, either because it is not available for the customer, or it * is not loaded. * * @param methodId - The identifier of the payment method. * @param gatewayId - The identifier of a payment provider providing the * payment method. * @returns The payment method object if loaded and available, otherwise, * undefined. */ getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined; /** * Gets the payment method that is selected for checkout. * * @returns The payment method object if there is a selected method; * undefined if otherwise. */ getSelectedPaymentMethod(): PaymentMethod | undefined; /** * Gets the available flash messages. * * Flash messages contain messages set by the server, * e.g: when trying to sign in using an invalid email link. * * @param type - The type of flash messages to be returned. Optional * @returns The flash messages if available, otherwise undefined. */ getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined; /** * Gets the current cart. * * @returns The current cart object if it is loaded, otherwise undefined. */ getCart(): Cart | undefined; /** * Gets a list of coupons that are applied to the current checkout. * * @returns The list of applied coupons if there is any, otherwise undefined. */ getCoupons(): Coupon[] | undefined; /** * Gets a list of gift certificates that are applied to the current checkout. * * @returns The list of applied gift certificates if there is any, otherwise undefined. */ getGiftCertificates(): GiftCertificate[] | undefined; /** * Gets the current customer. * * @returns The current customer object if it is loaded, otherwise * undefined. */ getCustomer(): Customer | undefined; /** * Checks if payment data is required or not. * * If payment data is required, customers should be prompted to enter their * payment details. * * ```js * if (state.checkout.isPaymentDataRequired()) { * // Render payment form * } else { * // Render "Payment is not required for this order" message * } * ``` * * @param useStoreCredit - If true, check whether payment data is required * with store credit applied; otherwise, check without store credit. * @returns True if payment data is required, otherwise false. */ isPaymentDataRequired(useStoreCredit?: boolean): boolean; /** * Checks if payment data is submitted or not. * * If payment data is already submitted using a payment method, customers * should not be prompted to enter their payment details again. * * @param methodId - The identifier of the payment method. * @param gatewayId - The identifier of a payment provider providing the * payment method. * @returns True if payment data is submitted, otherwise false. */ isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean; /** * Gets a list of payment instruments associated with the current customer. * * @returns The list of payment instruments if it is loaded, otherwise undefined. */ getInstruments(): Instrument[] | undefined; getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined; /** * Gets a set of form fields that should be presented in order to create a customer. * * @returns The set of customer account form fields if it is loaded, * otherwise undefined. */ getCustomerAccountFields(): FormField[]; /** * Gets a set of form fields that should be presented to customers in order * to capture their billing address for a specific country. * * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2). * @returns The set of billing address form fields if it is loaded, * otherwise undefined. */ getBillingAddressFields(countryCode: string): FormField[]; /** * Gets a set of form fields that should be presented to customers in order * to capture their shipping address for a specific country. * * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2). * @returns The set of shipping address form fields if it is loaded, * otherwise undefined. */ getShippingAddressFields(countryCode: string): FormField[]; } export type CheckoutStoreSelectorFactory = (state: InternalCheckoutSelectors) => CheckoutStoreSelector; export function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory { const getCheckout = createSelector( ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout, getCheckout => clone(getCheckout) ); const getOrder = createSelector( ({ order }: InternalCheckoutSelectors) => order.getOrder, getOrder => clone(getOrder) ); const getConfig = createSelector( ({ config }: InternalCheckoutSelectors) => config.getStoreConfig, getStoreConfig => clone(getStoreConfig) ); const getShippingAddress = createSelector( ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress, ({ config }: InternalCheckoutSelectors) => config.getContextConfig, (getShippingAddress, getContextConfig) => clone(() => { const shippingAddress = getShippingAddress(); const context = getContextConfig(); if (!shippingAddress) { if (!context || !context.geoCountryCode) { return; } return { firstName: '', lastName: '', company: '', address1: '', address2: '', city: '', stateOrProvince: '', stateOrProvinceCode: '', postalCode: '', country: '', phone: '', customFields: [], countryCode: context.geoCountryCode, }; } return shippingAddress; }) ); const getShippingOptions = createSelector( ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments, getConsignments => clone(() => { const consignments = getConsignments(); if (consignments && consignments.length) { return consignments[0].availableShippingOptions; } }) ); const getConsignments = createSelector( ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments, getConsignments => clone(getConsignments) ); const getSelectedShippingOption = createSelector( ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments, getConsignments => clone(() => { const consignments = getConsignments(); if (!consignments || !consignments.length) { return; } return consignments[0].selectedShippingOption; }) ); const getShippingCountries = createSelector( ({ shippingCountries }: InternalCheckoutSelectors) => shippingCountries.getShippingCountries, getShippingCountries => clone(getShippingCountries) ); const getBillingAddress = createSelector( ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress, ({ config }: InternalCheckoutSelectors) => config.getContextConfig, (getBillingAddress, getContextConfig) => clone(() => { const billingAddress = getBillingAddress(); const context = getContextConfig(); const isEmptyBillingAddress = !billingAddress || values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id')) .every(val => !val || !val.length); if (isEmptyBillingAddress) { if (!context || !context.geoCountryCode) { return billingAddress; } return { id: billingAddress ? billingAddress.id : '', firstName: '', lastName: '', company: '', address1: '', address2: '', city: '', email: billingAddress ? billingAddress.email : '', stateOrProvince: '', stateOrProvinceCode: '', postalCode: '', country: '', phone: '', customFields: [], countryCode: context.geoCountryCode, }; } return billingAddress; }) ); const getBillingCountries = createSelector( ({ countries }: InternalCheckoutSelectors) => countries.getCountries, getCountries => clone(getCountries) ); const getPaymentMethods = createSelector( ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods, getPaymentMethods => clone(getPaymentMethods) ); const getPaymentMethod = createSelector( ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod, getPaymentMethod => clone(getPaymentMethod) ); const getSelectedPaymentMethod = createSelector( ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId, ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod, (getPaymentId, getPaymentMethod) => clone(() => { const payment = getPaymentId(); return payment && getPaymentMethod(payment.providerId, payment.gatewayId); }) ); const getCart = createSelector( ({ cart }: InternalCheckoutSelectors) => cart.getCart, getCart => clone(getCart) ); const getCoupons = createSelector( ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons, getCoupons => clone(getCoupons) ); const getGiftCertificates = createSelector( ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates, getGiftCertificates => clone(getGiftCertificates) ); const getCustomer = createSelector( ({ customer }: InternalCheckoutSelectors) => customer.getCustomer, getCustomer => clone(getCustomer) ); const getSignInEmail = createSelector( ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail, getEmail => clone(getEmail) ); const isPaymentDataRequired = createSelector( ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired, isPaymentDataRequired => clone(isPaymentDataRequired) ); const isPaymentDataSubmitted = createSelector( ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted, ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod, (isPaymentDataSubmitted, getPaymentMethod) => clone((methodId: string, gatewayId?: string) => { return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId)); }) ); const getInstruments = createSelector( ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments, ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod, (getInstruments, getInstrumentsByPaymentMethod) => { function getInstrumentsSelector(): Instrument[] | undefined; function getInstrumentsSelector(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined; function getInstrumentsSelector(paymentMethod?: PaymentMethod): PaymentInstrument[] | undefined { return paymentMethod ? getInstrumentsByPaymentMethod(paymentMethod) : getInstruments(); } return clone(getInstrumentsSelector); } ); const getCustomerAccountFields = createSelector( ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields, getCustomerAccountFields => clone(getCustomerAccountFields) ); const getBillingAddressFields = createSelector( ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields, ({ countries }: InternalCheckoutSelectors) => countries.getCountries, (getBillingAddressFields, getCountries) => clone((countryCode: string) => { return getBillingAddressFields(getCountries(), countryCode); }) ); const getShippingAddressFields = createSelector( ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields, ({ shippingCountries }: InternalCheckoutSelectors) => shippingCountries.getShippingCountries, (getShippingAddressFields, getShippingCountries) => clone((countryCode: string) => { return getShippingAddressFields(getShippingCountries(), countryCode); }) ); const getFlashMessages = createSelector( ({ config }: InternalCheckoutSelectors) => config.getFlashMessages, getFlashMessages => clone(getFlashMessages) ); return memoizeOne(( state: InternalCheckoutSelectors ): CheckoutStoreSelector => { return { getCheckout: getCheckout(state), getOrder: getOrder(state), getConfig: getConfig(state), getFlashMessages: getFlashMessages(state), getShippingAddress: getShippingAddress(state), getShippingOptions: getShippingOptions(state), getConsignments: getConsignments(state), getSelectedShippingOption: getSelectedShippingOption(state), getShippingCountries: getShippingCountries(state), getBillingAddress: getBillingAddress(state), getBillingCountries: getBillingCountries(state), getPaymentMethods: getPaymentMethods(state), getPaymentMethod: getPaymentMethod(state), getSelectedPaymentMethod: getSelectedPaymentMethod(state), getCart: getCart(state), getCoupons: getCoupons(state), getGiftCertificates: getGiftCertificates(state), getCustomer: getCustomer(state), isPaymentDataRequired: isPaymentDataRequired(state), isPaymentDataSubmitted: isPaymentDataSubmitted(state), getSignInEmail: getSignInEmail(state), getInstruments: getInstruments(state), getCustomerAccountFields: getCustomerAccountFields(state), getBillingAddressFields: getBillingAddressFields(state), getShippingAddressFields: getShippingAddressFields(state), }; }); }
the_stack
import expressions = require('../src/expression'); import test_utils = require('./test_utils'); import firebase_io = require('./firebase_io'); import compiler = require('../src/compiler'); import async = require('async'); export function testString(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/string.yaml", true).code, test), test_utils.assert_can_write.bind (null, "any", "/", "correct", test), test_utils.assert_cant_write.bind(null, "any", "/", "incorrect", test), //not in enum test_utils.assert_cant_write.bind(null, "any", "/", {"child":"correct"}, test), test_utils.assert_can_read.bind (null, "any", "/", "correct", test) ], test.done.bind(null)); } export function testNumber(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/number.yaml", true).code, test), test_utils.assert_can_write.bind (null, "any", "/plain_number", 4, test), test_utils.assert_can_write.bind (null, "any", "/plain_number", 4.2, test), test_utils.assert_can_write.bind (null, "any", "/plain_number", -5, test), test_utils.assert_cant_write.bind (null, "any", "/plain_number", "str", test), test_utils.assert_cant_write.bind (null, "any", "/plain_number", {"a":5}, test), test_utils.assert_can_write.bind (null, "any", "/min_number", 5, test), test_utils.assert_cant_write.bind (null, "any", "/min_number", 4.9, test), test_utils.assert_can_write.bind (null, "any", "/exclusive_min_number", 5.1, test), test_utils.assert_cant_write.bind (null, "any", "/exclusive_min_number", 5, test), test_utils.assert_can_write.bind (null, "any", "/max_number", 0, test), test_utils.assert_cant_write.bind (null, "any", "/max_number", 0.1, test), test_utils.assert_can_write.bind (null, "any", "/exclusive_max_number", -.1, test), test_utils.assert_cant_write.bind (null, "any", "/exclusive_max_number", 0, test), ], test.done.bind(null)); } export function testFunction_access(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/function_access.yaml", true).code, test), test_utils.assert_cant_write.bind(null, "tom", "/", "string", test), test_utils.assert_can_write.bind (null, "not", "/", "string", test), test_utils.assert_cant_read.bind (null, "not", "/", test), test_utils.assert_can_read.bind (null, "tom", "/", "string", test) ], test.done.bind(null)); } export function testAccess(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/access.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/", {chld1:{grnd1:"1", grnd2:"2"}, chld2:{grnd3:"3", grnd4:"4"}}, test), test_utils.assert_cant_write.bind(null, "red", "/chld2", {}, test), test_utils.assert_cant_write.bind(null, "red", "/chld2", {}, test), test_utils.assert_cant_write.bind(null, "black","/", {}, test), test_utils.assert_cant_write.bind(null, "black","/chld1/grnd1", "string", test), test_utils.assert_cant_write.bind(null, "black","/chld1/grnd2", "string", test), test_utils.assert_can_write_mock.bind(null, "red","/chld1/grnd1", "string", test), test_utils.assert_can_write_mock.bind(null, "red","/chld1/grnd2", "string", test), test_utils.assert_can_write_mock.bind(null, "black","/chld2/grnd3", "string", test), test_utils.assert_can_write_mock.bind(null, "black","/chld2/grnd4", "string", test), test_utils.assert_can_write_mock.bind(null, "red", "/chld1", {}, test), test_utils.assert_can_write_mock.bind(null, "black","/chld2", {}, test), test_utils.assert_cant_write.bind(null, "black","/chld1", {}, test), test_utils.assert_cant_write.bind(null, "red", "/chld2", {}, test), test_utils.assert_cant_write.bind(null, "red", "/", {}, test), test_utils.assert_cant_write.bind(null, "red", "/", {}, test) ], test.done.bind(null)); } export function testCascade(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/cascade.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/",{}, test), test_utils.assert_cant_write.bind(null, "any","/chld1/grnd1", "string", test), test_utils.assert_cant_write.bind(null, "any","/chld1/grnd2", "string", test), test_utils.assert_cant_write.bind(null, "any","/chld2/grnd3", "string", test), test_utils.assert_cant_write.bind(null, "any","/chld2/grnd4", "string", test), test_utils.assert_can_write.bind(null, "any","/", {chld1:{grnd1:"1", grnd2:"2"}, chld2:{grnd3:"3", grnd4:"4"}}, test) ], test.done.bind(null)); } export function testRequired(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/required.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/",{}, test), //should be able to write full try test_utils.assert_can_write_mock.bind(null, "any","/", {chld1:{grnd1:"1", grnd2:"2"}, chld2:{grnd3:"3", grnd4:"4"}}, test), //or the subtree with both required grandchildren test_utils.assert_can_write_mock.bind(null, "any","/chld1", {grnd1:"1", grnd2:"2"}, test), test_utils.assert_can_write_mock.bind(null, "any","/chld2", {grnd3:"3", grnd4:"4"}, test), //or jsut one grandchild of the unrequired tree test_utils.assert_can_write_mock.bind(null, "any","/chld2/grnd3", "3", test), //but not one grandchild of the required subtree test_utils.assert_cant_write.bind(null, "any","/chld1/grnd1", "1", test) ], test.done.bind(null)); } export function testTypes(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/types.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/",{}, test), test_utils.assert_can_write_mock.bind(null, "any","/object", {a:5} , test), test_utils.assert_can_write_mock.bind(null, "any","/string", "string", test), test_utils.assert_can_write_mock.bind(null, "any","/number", 1, test), test_utils.assert_can_write_mock.bind(null, "any","/boolean", true , test), test_utils.assert_cant_write.bind(null, "any","/object", "string" , test), test_utils.assert_cant_write.bind(null, "any","/string", 1 , test), test_utils.assert_cant_write.bind(null, "any","/number", true , test), test_utils.assert_cant_write.bind(null, "any","/boolean", {a:5} , test), test_utils.assert_cant_write.bind(null, "any","/boolean", "true" , test), test_utils.assert_cant_write.bind(null, "any","/extra", true , test), ], test.done.bind(null)); } export function testDefinitions(test:nodeunit.Test): void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/definitions.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/", {}, test), test_utils.assert_can_write.bind(null, "any","/object", {"boolean":true} , test), test_utils.assert_can_write_mock.bind(null, "any","/object/boolean", true , test), test_utils.assert_can_write_mock.bind(null, "any","/string", "string", test), test_utils.assert_can_write_mock.bind(null, "any","/number", 1, test), test_utils.assert_can_write_mock.bind(null, "any","/boolean", true , test), test_utils.assert_cant_write.bind(null, "any","/object", "string" , test), test_utils.assert_cant_write.bind(null, "any","/string", 1 , test), test_utils.assert_cant_write.bind(null, "any","/number", true , test), test_utils.assert_cant_write.bind(null, "any","/boolean", {a:5} , test), test_utils.assert_cant_write.bind(null, "any","/boolean", "true" , test), test_utils.assert_cant_write.bind(null, "any","/extra", true , test), test_utils.assert_can_write_mock.bind(null, "any","/object/string", "string", test), test_utils.assert_can_write_mock.bind(null, "any","/object/number", 1, test), test_utils.assert_can_write_mock.bind(null, "any","/object/boolean", true , test), test_utils.assert_cant_write.bind(null, "any","/object/extra", true , test), ], test.done.bind(null)); } export function testAny(test: nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/any.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/",{}, test), test_utils.assert_can_write_mock.bind(null, "any","/", true , test), test_utils.assert_can_write_mock.bind(null, "any","/", "string" , test), test_utils.assert_can_write_mock.bind(null, "any","/", {chld_str: "a", chld_bool: true}, test), test_utils.assert_cant_write.bind(null, "any","/", {chld_str: false, chld_bool: true} , test), ], test.done.bind(null)); } export function testWildchild(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/wildchild.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/wildchild/",{}, test), test_utils.assert_can_write_mock.bind(null, "any","/wildchild/chld1", "Y", test), test_utils.assert_can_write_mock.bind(null, "any","/wildchild/chld2", "Y", test), test_utils.assert_cant_write.bind(null, "any","/wildchild/chld1", "N", test), test_utils.assert_cant_write.bind(null, "any","/wildchild/chld2", "N", test), test_utils.assert_cant_write.bind(null, "any","/wildchild/", {chld1:"Y", chld2:"Y"}, test), test_utils.assert_can_write.bind(null, "any","/wildchild/extra", "N", test), test_utils.assert_can_write.bind(null, "any", "/wildchild/real", "Y", test), test_utils.assert_cant_write.bind(null, "any", "/wildchild/real", null, test), ], test.done.bind(null)); } export function testWilderchild(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/wildchild.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/wilderchild/",{}, test), test_utils.assert_can_write_mock.bind(null, "any","/wilderchild/chld1", "Y", test), test_utils.assert_can_write_mock.bind(null, "any","/wilderchild/chld2", "Y", test), test_utils.assert_cant_write.bind(null, "any","/wilderchild/chld1", "N", test), test_utils.assert_cant_write.bind(null, "any","/wilderchild/chld2", "N", test), test_utils.assert_can_write.bind (null, "any","/wilderchild/", {chld1:"Y", chld2:"Y"}, test), test_utils.assert_cant_write.bind(null, "any","/wilderchild/", {chld1:"N", chld2:"Y"}, test), test_utils.assert_can_write.bind(null, "any","/wilderchild/extra", "N", test), test_utils.assert_can_write.bind(null, "any", "/wilderchild/real", "Y", test), test_utils.assert_can_write.bind(null, "any", "/wilderchild/real", null, test), //danger introduced by wilder childs ], test.done.bind(null)); } export function testSanitize(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/sanitize.yaml", true).code, test) ], test.done.bind(null)); } export function testNestedWildchilds(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/wildchild.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/nested/",{}, test), //anyone can write to grandchildren test_utils.assert_can_write.bind(null, null,"/nested/a/a/data", "a", test), //no-one can delete because of constraint test_utils.assert_cant_write.bind(null, null,"/nested/a/a/data", null, test), //authenticated have greater permissions (can't do at the moment) //test_utils.assert_can_write.bind(null, "auth", "/nested/a", null, test), ], test.done.bind(null)); } /*TODO export function testWilderChildMixedAccess(test:nodeunit.Test):void{ async.series([ firebase_io.assertSetValidationRules.bind(null, compiler.compile("test/cases/wilderchildHierarchicalAccess.yaml", true).code, test), test_utils.assert_admin_can_write.bind(null, "/",{}, test), //root can write anywhere test_utils.assert_can_write.bind(null, "root","/", "payload", test), test_utils.assert_can_write.bind(null, "root","/a", "payload", test), test_utils.assert_can_write.bind(null, "root","/a/a", "payload", test), //child can write first two level test_utils.assert_cant_write.bind(null, "child","/", "payload", test), test_utils.assert_can_write.bind(null, "child","/a", "payload", test), test_utils.assert_can_write.bind(null, "child","/a/a", "payload", test), //grandchild can write only last level test_utils.assert_cant_write.bind(null, "grandchild","/", "payload", test), test_utils.assert_cant_write.bind(null, "grandchild","/a", "payload", test), test_utils.assert_can_write.bind(null, "grandchild","/a/a", "payload", test), ], test.done.bind(null)); }*/
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [codestar-connections](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodestarconnections.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class CodestarConnections extends PolicyStatement { public servicePrefix = 'codestar-connections'; /** * Statement provider for service [codestar-connections](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodestarconnections.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create a Connection resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifProviderType() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_CreateConnection.html */ public toCreateConnection() { return this.to('CreateConnection'); } /** * Grants permission to create a host resource * * Access Level: Write * * Possible conditions: * - .ifProviderType() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_CreateHost.html */ public toCreateHost() { return this.to('CreateHost'); } /** * Grants permission to delete a Connection resource * * Access Level: Write * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_DeleteConnection.html */ public toDeleteConnection() { return this.to('DeleteConnection'); } /** * Grants permission to delete a host resource * * Access Level: Write * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_DeleteHost.html */ public toDeleteHost() { return this.to('DeleteHost'); } /** * Grants permission to get details about a Connection resource * * Access Level: Read * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_GetConnection.html */ public toGetConnection() { return this.to('GetConnection'); } /** * Grants permission to get details about a host resource * * Access Level: Read * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_GetHost.html */ public toGetHost() { return this.to('GetHost'); } /** * Grants permission to associate a third party, such as a Bitbucket App installation, with a Connection * * Access Level: Read * * Possible conditions: * - .ifProviderType() * * Dependent actions: * - codestar-connections:StartOAuthHandshake * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake */ public toGetIndividualAccessToken() { return this.to('GetIndividualAccessToken'); } /** * Grants permission to associate a third party, such as a Bitbucket App installation, with a Connection * * Access Level: Read * * Possible conditions: * - .ifProviderType() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake */ public toGetInstallationUrl() { return this.to('GetInstallationUrl'); } /** * Grants permission to list Connection resources * * Access Level: List * * Possible conditions: * - .ifProviderTypeFilter() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_ListConnections.html */ public toListConnections() { return this.to('ListConnections'); } /** * Grants permission to list host resources * * Access Level: List * * Possible conditions: * - .ifProviderTypeFilter() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_ListHosts.html */ public toListHosts() { return this.to('ListHosts'); } /** * Grants permission to associate a third party, such as a Bitbucket App installation, with a Connection * * Access Level: List * * Dependent actions: * - codestar-connections:GetIndividualAccessToken * - codestar-connections:StartOAuthHandshake * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake */ public toListInstallationTargets() { return this.to('ListInstallationTargets'); } /** * Gets the set of key-value pairs that are used to manage the resource * * Access Level: List * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to pass a Connection resource to an AWS service that accepts a Connection ARN as input, such as codepipeline:CreatePipeline * * Access Level: Read * * Possible conditions: * - .ifPassedToService() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-passconnection */ public toPassConnection() { return this.to('PassConnection'); } /** * Grants permission to associate a third party server, such as a GitHub Enterprise Server instance, with a Host * * Access Level: Read * * Possible conditions: * - .ifHostArn() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#connections-permissions-actions-host-registration */ public toRegisterAppCode() { return this.to('RegisterAppCode'); } /** * Grants permission to associate a third party server, such as a GitHub Enterprise Server instance, with a Host * * Access Level: Read * * Possible conditions: * - .ifHostArn() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#connections-permissions-actions-host-registration */ public toStartAppRegistrationHandshake() { return this.to('StartAppRegistrationHandshake'); } /** * Grants permission to associate a third party, such as a Bitbucket App installation, with a Connection * * Access Level: Read * * Possible conditions: * - .ifProviderType() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake */ public toStartOAuthHandshake() { return this.to('StartOAuthHandshake'); } /** * Adds to or modifies the tags of the given resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Removes tags from an AWS resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a Connection resource with an installation of the CodeStar Connections App * * Access Level: Write * * Possible conditions: * - .ifInstallationId() * * Dependent actions: * - codestar-connections:GetIndividualAccessToken * - codestar-connections:GetInstallationUrl * - codestar-connections:ListInstallationTargets * - codestar-connections:StartOAuthHandshake * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake */ public toUpdateConnectionInstallation() { return this.to('UpdateConnectionInstallation'); } /** * Grants permission to update a host resource * * Access Level: Write * * https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_UpdateHost.html */ public toUpdateHost() { return this.to('UpdateHost'); } /** * Grants permission to use a Connection resource to call provider actions * * Access Level: Read * * Possible conditions: * - .ifFullRepositoryId() * - .ifProviderAction() * - .ifProviderPermissionsRequired() * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use */ public toUseConnection() { return this.to('UseConnection'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateConnection", "CreateHost", "DeleteConnection", "DeleteHost", "UpdateConnectionInstallation", "UpdateHost" ], "Read": [ "GetConnection", "GetHost", "GetIndividualAccessToken", "GetInstallationUrl", "PassConnection", "RegisterAppCode", "StartAppRegistrationHandshake", "StartOAuthHandshake", "UseConnection" ], "List": [ "ListConnections", "ListHosts", "ListInstallationTargets", "ListTagsForResource" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type Connection to the statement * * https://docs.aws.amazon.com/dtconsole/latest/userguide/connections.html * * @param connectionId - Identifier for the connectionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onConnection(connectionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codestar-connections:${Region}:${Account}:connection/${ConnectionId}'; arn = arn.replace('${ConnectionId}', connectionId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Host to the statement * * https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-hosts.html * * @param hostId - Identifier for the hostId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onHost(hostId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codestar-connections:${Region}:${Account}:host/${HostId}'; arn = arn.replace('${HostId}', hostId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by the branch name that is passed in the request. Applies only to UseConnection requests for access to a specific repository branch * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifBranchName(value: string | string[], operator?: Operator | string) { return this.if(`BranchName`, value, operator || 'StringLike'); } /** * Filters access by the repository that is passed in the request. Applies only to UseConnection requests for access to a specific repository * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use * * Applies to actions: * - .toUseConnection() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFullRepositoryId(value: string | string[], operator?: Operator | string) { return this.if(`FullRepositoryId`, value, operator || 'StringLike'); } /** * Filters access by the host resource associated with the connection used in the request * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-hosts * * Applies to actions: * - .toRegisterAppCode() * - .toStartAppRegistrationHandshake() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifHostArn(value: string | string[], operator?: Operator | string) { return this.if(`HostArn`, value, operator || 'StringLike'); } /** * Filters access by the third-party ID (such as the Bitbucket App installation ID for CodeStar Connections) that is used to update a Connection. Allows you to restrict which third-party App installations can be used to make a Connection * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-handshake * * Applies to actions: * - .toUpdateConnectionInstallation() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifInstallationId(value: string | string[], operator?: Operator | string) { return this.if(`InstallationId`, value, operator || 'StringLike'); } /** * Filters access by the owner of the third-party repository. Applies only to UseConnection requests for access to repositories owned by a specific user * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifOwnerId(value: string | string[], operator?: Operator | string) { return this.if(`OwnerId`, value, operator || 'StringLike'); } /** * Filters access by the service to which the principal is allowed to pass a Connection * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-passconnection * * Applies to actions: * - .toPassConnection() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPassedToService(value: string | string[], operator?: Operator | string) { return this.if(`PassedToService`, value, operator || 'StringLike'); } /** * Filters access by the provider action in a UseConnection request such as ListRepositories. See documentation for all valid values * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-access * * Applies to actions: * - .toUseConnection() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifProviderAction(value: string | string[], operator?: Operator | string) { return this.if(`ProviderAction`, value, operator || 'StringLike'); } /** * Filters access by the write permissions of a provider action in a UseConnection request. Valid types include read_only and read_write * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use * * Applies to actions: * - .toUseConnection() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifProviderPermissionsRequired(value: string | string[], operator?: Operator | string) { return this.if(`ProviderPermissionsRequired`, value, operator || 'StringLike'); } /** * Filters access by the type of third-party provider passed in the request * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-managing * * Applies to actions: * - .toCreateConnection() * - .toCreateHost() * - .toGetIndividualAccessToken() * - .toGetInstallationUrl() * - .toStartOAuthHandshake() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifProviderType(value: string | string[], operator?: Operator | string) { return this.if(`ProviderType`, value, operator || 'StringLike'); } /** * Filters access by the type of third-party provider used to filter results * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-managing * * Applies to actions: * - .toListConnections() * - .toListHosts() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifProviderTypeFilter(value: string | string[], operator?: Operator | string) { return this.if(`ProviderTypeFilter`, value, operator || 'StringLike'); } /** * Filters access by the repository name that is passed in the request. Applies only to UseConnection requests for creating new repositories * * https://docs.aws.amazon.com/dtconsole/latest/userguide/security-iam.html#permissions-reference-connections-use * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRepositoryName(value: string | string[], operator?: Operator | string) { return this.if(`RepositoryName`, value, operator || 'StringLike'); } }
the_stack
import { execSync, spawn } from "node:child_process"; import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs"; import { readdir, readFile, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join, sep } from "node:path"; import { cwd } from "node:process"; import { URL } from "node:url"; import { hash } from "blake3-wasm"; import { watch } from "chokidar"; import { render, Text } from "ink"; import SelectInput from "ink-select-input"; import Spinner from "ink-spinner"; import Table from "ink-table"; import { getType } from "mime"; import prettyBytes from "pretty-bytes"; import React from "react"; import { format as timeagoFormat } from "timeago.js"; import { File, FormData } from "undici"; import { buildPlugin } from "../pages/functions/buildPlugin"; import { buildWorker } from "../pages/functions/buildWorker"; import { generateConfigFromFileTree } from "../pages/functions/filepath-routing"; import { writeRoutesModule } from "../pages/functions/routes"; import { fetchResult } from "./cfetch"; import { getConfigCache, saveToConfigCache } from "./config-cache"; import { prompt } from "./dialogs"; import { FatalError } from "./errors"; import { logger } from "./logger"; import { getRequestContextCheckOptions } from "./miniflare-cli/request-context"; import openInBrowser from "./open-in-browser"; import { toUrlPath } from "./paths"; import { requireAuth } from "./user"; import type { Config } from "../pages/functions/routes"; import type { Headers, Request, fetch } from "@miniflare/core"; import type { BuildResult } from "esbuild"; import type { MiniflareOptions } from "miniflare"; import type { BuilderCallback, CommandModule } from "yargs"; export type Project = { name: string; subdomain: string; domains: Array<string>; source?: { type: string; }; latest_deployment?: { modified_on: string; }; created_on: string; production_branch: string; }; export type Deployment = { id: string; environment: string; deployment_trigger: { metadata: { commit_hash: string; branch: string; }; }; url: string; latest_stage: { status: string; ended_on: string; }; project_name: string; }; interface PagesConfigCache { account_id?: string; project_name?: string; } const PAGES_CONFIG_CACHE_FILENAME = "pages.json"; // Defer importing miniflare until we really need it. This takes ~0.5s // and also modifies some `stream/web` and `undici` prototypes, so we // don't want to do this if pages commands aren't being called. export const pagesBetaWarning = "๐Ÿšง 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"; const isInPagesCI = !!process.env.CF_PAGES; const CLEANUP_CALLBACKS: (() => void)[] = []; const CLEANUP = () => { CLEANUP_CALLBACKS.forEach((callback) => callback()); RUNNING_BUILDERS.forEach((builder) => builder.stop?.()); }; process.on("SIGINT", () => { CLEANUP(); process.exit(); }); process.on("SIGTERM", () => { CLEANUP(); process.exit(); }); function isWindows() { return process.platform === "win32"; } const SECONDS_TO_WAIT_FOR_PROXY = 5; async function sleep(ms: number) { await new Promise((resolve) => setTimeout(resolve, ms)); } function getPids(pid: number) { const pids: number[] = [pid]; let command: string, regExp: RegExp; if (isWindows()) { command = `wmic process where (ParentProcessId=${pid}) get ProcessId`; regExp = new RegExp(/(\d+)/); } else { command = `pgrep -P ${pid}`; regExp = new RegExp(/(\d+)/); } try { const newPids = ( execSync(command) .toString() .split("\n") .map((line) => line.match(regExp)) .filter((line) => line !== null) as RegExpExecArray[] ).map((match) => parseInt(match[1])); pids.push(...newPids.map(getPids).flat()); } catch {} return pids; } function getPort(pid: number) { let command: string, regExp: RegExp; if (isWindows()) { command = "\\windows\\system32\\netstat.exe -nao"; regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`); } else { command = "lsof -nPi"; regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`); } try { const matches = execSync(command) .toString() .split("\n") .map((line) => line.match(regExp)) .filter((line) => line !== null) as RegExpExecArray[]; const match = matches[0]; if (match) return parseInt(match[1]); } catch (thrown) { logger.error( `Error scanning for ports of process with PID ${pid}: ${thrown}` ); } } async function spawnProxyProcess({ port, command, }: { port?: number; command: (string | number)[]; }): Promise<void | number> { if (command.length === 0) { CLEANUP(); throw new FatalError( "Must specify a directory of static assets to serve or a command to run.", 1 ); } logger.log(`Running ${command.join(" ")}...`); const proxy = spawn( command[0].toString(), command.slice(1).map((value) => value.toString()), { shell: isWindows(), env: { BROWSER: "none", ...process.env, }, } ); CLEANUP_CALLBACKS.push(() => { proxy.kill(); }); proxy.stdout.on("data", (data) => { logger.log(`[proxy]: ${data}`); }); proxy.stderr.on("data", (data) => { logger.error(`[proxy]: ${data}`); }); proxy.on("close", (code) => { logger.error(`Proxy exited with status ${code}.`); }); // Wait for proxy process to start... while (!proxy.pid) {} if (port === undefined) { logger.log( `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...` ); logger.log("To skip, specify the proxy port with --proxy."); await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000); port = getPids(proxy.pid) .map(getPort) .filter((port) => port !== undefined)[0]; if (port === undefined) { CLEANUP(); throw new FatalError( "Could not automatically determine proxy port. Please specify the proxy port with --proxy.", 1 ); } else { logger.log(`Automatically determined the proxy port to be ${port}.`); } } return port; } function escapeRegex(str: string) { return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&"); } type Replacements = Record<string, string>; function replacer(str: string, replacements: Replacements) { for (const [replacement, value] of Object.entries(replacements)) { str = str.replace(`:${replacement}`, value); } return str; } function generateRulesMatcher<T>( rules?: Record<string, T>, replacer: (match: T, replacements: Replacements) => T = (match) => match ) { // TODO: How can you test cross-host rules? if (!rules) return () => []; const compiledRules = Object.entries(rules) .map(([rule, match]) => { const crossHost = rule.startsWith("https://"); rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)"); const host_matches = rule.matchAll( /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g ); for (const match of host_matches) { rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`); } const path_matches = rule.matchAll(/:(\w+)/g); for (const match of path_matches) { rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`); } rule = "^" + rule + "$"; try { const regExp = new RegExp(rule); return [{ crossHost, regExp }, match]; } catch {} }) .filter((value) => value !== undefined) as [ { crossHost: boolean; regExp: RegExp }, T ][]; return ({ request }: { request: Request }) => { const { pathname, host } = new URL(request.url); return compiledRules .map(([{ crossHost, regExp }, match]) => { const test = crossHost ? `https://${host}${pathname}` : pathname; const result = regExp.exec(test); if (result) { return replacer(match, result.groups || {}); } }) .filter((value) => value !== undefined) as T[]; }; } function generateHeadersMatcher(headersFile: string) { if (existsSync(headersFile)) { const contents = readFileSync(headersFile).toString(); // TODO: Log errors const lines = contents .split("\n") .map((line) => line.trim()) .filter((line) => !line.startsWith("#") && line !== ""); const rules: Record<string, Record<string, string>> = {}; let rule: { path: string; headers: Record<string, string> } | undefined = undefined; for (const line of lines) { if (/^([^\s]+:\/\/|^\/)/.test(line)) { if (rule && Object.keys(rule.headers).length > 0) { rules[rule.path] = rule.headers; } const path = validateURL(line); if (path) { rule = { path, headers: {}, }; continue; } } if (!line.includes(":")) continue; const [rawName, ...rawValue] = line.split(":"); const name = rawName.trim().toLowerCase(); const value = rawValue.join(":").trim(); if (name === "") continue; if (!rule) continue; const existingValues = rule.headers[name]; rule.headers[name] = existingValues ? `${existingValues}, ${value}` : value; } if (rule && Object.keys(rule.headers).length > 0) { rules[rule.path] = rule.headers; } const rulesMatcher = generateRulesMatcher(rules, (match, replacements) => Object.fromEntries( Object.entries(match).map(([name, value]) => [ name, replacer(value, replacements), ]) ) ); return (request: Request) => { const matches = rulesMatcher({ request, }); if (matches) return matches; }; } else { return () => undefined; } } function generateRedirectsMatcher(redirectsFile: string) { if (existsSync(redirectsFile)) { const contents = readFileSync(redirectsFile).toString(); // TODO: Log errors const lines = contents .split("\n") .map((line) => line.trim()) .filter((line) => !line.startsWith("#") && line !== ""); const rules = Object.fromEntries( lines .map((line) => line.split(" ")) .filter((tokens) => tokens.length === 2 || tokens.length === 3) .map((tokens) => { const from = validateURL(tokens[0], true, false, false); const to = validateURL(tokens[1], false, true, true); let status: number | undefined = parseInt(tokens[2]) || 302; status = [301, 302, 303, 307, 308].includes(status) ? status : undefined; return from && to && status ? [from, { to, status }] : undefined; }) .filter((rule) => rule !== undefined) as [ string, { to: string; status?: number } ][] ); const rulesMatcher = generateRulesMatcher( rules, ({ status, to }, replacements) => ({ status, to: replacer(to, replacements), }) ); return (request: Request) => { const match = rulesMatcher({ request, })[0]; if (match) return match; }; } else { return () => undefined; } } function extractPathname( path = "/", includeSearch: boolean, includeHash: boolean ) { if (!path.startsWith("/")) path = `/${path}`; const url = new URL(`//${path}`, "relative://"); return `${url.pathname}${includeSearch ? url.search : ""}${ includeHash ? url.hash : "" }`; } function validateURL( token: string, onlyRelative = false, includeSearch = false, includeHash = false ) { const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token); if (host && host.groups && host.groups.host) { if (onlyRelative) return; return `https://${host.groups.host}${extractPathname( host.groups.path, includeSearch, includeHash )}`; } else { if (!token.startsWith("/") && onlyRelative) token = `/${token}`; const path = /^\//.exec(token); if (path) { try { return extractPathname(token, includeSearch, includeHash); } catch {} } } return ""; } function hasFileExtension(pathname: string) { return /\/.+\.[a-z0-9]+$/i.test(pathname); } async function generateAssetsFetch(directory: string): Promise<typeof fetch> { // Defer importing miniflare until we really need it const { Headers, Request, Response } = await import("@miniflare/core"); const headersFile = join(directory, "_headers"); const redirectsFile = join(directory, "_redirects"); const workerFile = join(directory, "_worker.js"); const ignoredFiles = [headersFile, redirectsFile, workerFile]; const assetExists = (path: string) => { path = join(directory, path); return ( existsSync(path) && lstatSync(path).isFile() && !ignoredFiles.includes(path) ); }; const getAsset = (path: string) => { if (assetExists(path)) { return join(directory, path); } }; let redirectsMatcher = generateRedirectsMatcher(redirectsFile); let headersMatcher = generateHeadersMatcher(headersFile); watch([headersFile, redirectsFile], { persistent: true, }).on("change", (path) => { switch (path) { case headersFile: { logger.log("_headers modified. Re-evaluating..."); headersMatcher = generateHeadersMatcher(headersFile); break; } case redirectsFile: { logger.log("_redirects modified. Re-evaluating..."); redirectsMatcher = generateRedirectsMatcher(redirectsFile); break; } } }); const serveAsset = (file: string) => { return readFileSync(file); }; const generateResponse = (request: Request) => { const url = new URL(request.url); const deconstructedResponse: { status: number; headers: Headers; body?: Buffer; } = { status: 200, headers: new Headers(), body: undefined, }; const match = redirectsMatcher(request); if (match) { const { status, to } = match; let location = to; let search; if (to.startsWith("/")) { search = new URL(location, "http://fakehost").search; } else { search = new URL(location).search; } location = `${location}${search ? "" : url.search}`; if (status && [301, 302, 303, 307, 308].includes(status)) { deconstructedResponse.status = status; } else { deconstructedResponse.status = 302; } deconstructedResponse.headers.set("Location", location); return deconstructedResponse; } if (!request.method?.match(/^(get|head)$/i)) { deconstructedResponse.status = 405; return deconstructedResponse; } const notFound = () => { let cwd = url.pathname; while (cwd) { cwd = cwd.slice(0, cwd.lastIndexOf("/")); if ((asset = getAsset(`${cwd}/404.html`))) { deconstructedResponse.status = 404; deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } } if ((asset = getAsset(`/index.html`))) { deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } deconstructedResponse.status = 404; return deconstructedResponse; }; let asset; if (url.pathname.endsWith("/")) { if ((asset = getAsset(`${url.pathname}/index.html`))) { deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } else if ( (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`)) ) { deconstructedResponse.status = 301; deconstructedResponse.headers.set( "Location", `${url.pathname.slice(0, -1)}${url.search}` ); return deconstructedResponse; } } if (url.pathname.endsWith("/index")) { deconstructedResponse.status = 301; deconstructedResponse.headers.set( "Location", `${url.pathname.slice(0, -"index".length)}${url.search}` ); return deconstructedResponse; } if ((asset = getAsset(url.pathname))) { if (url.pathname.endsWith(".html")) { const extensionlessPath = url.pathname.slice(0, -".html".length); if (getAsset(extensionlessPath) || extensionlessPath === "/") { deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } else { deconstructedResponse.status = 301; deconstructedResponse.headers.set( "Location", `${extensionlessPath}${url.search}` ); return deconstructedResponse; } } else { deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } } else if (hasFileExtension(url.pathname)) { notFound(); return deconstructedResponse; } if ((asset = getAsset(`${url.pathname}.html`))) { deconstructedResponse.body = serveAsset(asset); deconstructedResponse.headers.set( "Content-Type", getType(asset) || "application/octet-stream" ); return deconstructedResponse; } if ((asset = getAsset(`${url.pathname}/index.html`))) { deconstructedResponse.status = 301; deconstructedResponse.headers.set( "Location", `${url.pathname}/${url.search}` ); return deconstructedResponse; } else { notFound(); return deconstructedResponse; } }; const attachHeaders = ( request: Request, deconstructedResponse: { status: number; headers: Headers; body?: Buffer } ) => { const headers = deconstructedResponse.headers; const newHeaders = new Headers({}); const matches = headersMatcher(request) || []; matches.forEach((match) => { Object.entries(match).forEach(([name, value]) => { newHeaders.append(name, `${value}`); }); }); const combinedHeaders = { ...Object.fromEntries(headers.entries()), ...Object.fromEntries(newHeaders.entries()), }; deconstructedResponse.headers = new Headers({}); Object.entries(combinedHeaders).forEach(([name, value]) => { if (value) deconstructedResponse.headers.set(name, value); }); }; return async (input, init) => { const request = new Request(input, init); const deconstructedResponse = generateResponse(request); attachHeaders(request, deconstructedResponse); const headers = new Headers(); [...deconstructedResponse.headers.entries()].forEach(([name, value]) => { if (value) headers.set(name, value); }); return new Response(deconstructedResponse.body, { headers, status: deconstructedResponse.status, }); }; } const RUNNING_BUILDERS: BuildResult[] = []; async function buildFunctions({ outfile, outputConfigPath, functionsDirectory, minify = false, sourcemap = false, fallbackService = "ASSETS", watch = false, onEnd, plugin = false, buildOutputDirectory, }: { outfile: string; outputConfigPath?: string; functionsDirectory: string; minify?: boolean; sourcemap?: boolean; fallbackService?: string; watch?: boolean; onEnd?: () => void; plugin?: boolean; buildOutputDirectory?: string; }) { RUNNING_BUILDERS.forEach( (runningBuilder) => runningBuilder.stop && runningBuilder.stop() ); const routesModule = join(tmpdir(), "./functionsRoutes.mjs"); const baseURL = toUrlPath("/"); const config: Config = await generateConfigFromFileTree({ baseDir: functionsDirectory, baseURL, }); if (outputConfigPath) { writeFileSync( outputConfigPath, JSON.stringify({ ...config, baseURL }, null, 2) ); } await writeRoutesModule({ config, srcDir: functionsDirectory, outfile: routesModule, }); if (plugin) { RUNNING_BUILDERS.push( await buildPlugin({ routesModule, outfile, minify, sourcemap, watch, onEnd, }) ); } else { RUNNING_BUILDERS.push( await buildWorker({ routesModule, outfile, minify, sourcemap, fallbackService, watch, onEnd, buildOutputDirectory, }) ); } } interface CreateDeploymentArgs { directory: string; projectName?: string; branch?: string; commitHash?: string; commitMessage?: string; commitDirty?: boolean; } const createDeployment: CommandModule< CreateDeploymentArgs, CreateDeploymentArgs > = { describe: "๐Ÿ†™ Publish a directory of static assets as a Pages deployment", builder: (yargs) => { return yargs .positional("directory", { type: "string", demandOption: true, description: "The directory of static files to upload", }) .options({ "project-name": { type: "string", description: "The name of the project you want to deploy to", }, branch: { type: "string", description: "The name of the branch you want to deploy to", }, "commit-hash": { type: "string", description: "The SHA to attach to this deployment", }, "commit-message": { type: "string", description: "The commit message to attach to this deployment", }, "commit-dirty": { type: "boolean", description: "Whether or not the workspace should be considered dirty for this deployment", }, }) .epilogue(pagesBetaWarning); }, handler: async ({ directory, projectName, branch, commitHash, commitMessage, commitDirty, }) => { if (!directory) { throw new FatalError("Must specify a directory.", 1); } const config = getConfigCache<PagesConfigCache>( PAGES_CONFIG_CACHE_FILENAME ); const accountId = await requireAuth(config); projectName ??= config.project_name; const isInteractive = process.stdin.isTTY; if (!projectName && isInteractive) { const projects = (await listProjects({ accountId })).filter( (project) => !project.source ); let existingOrNew: "existing" | "new" = "new"; if (projects.length > 0) { existingOrNew = await new Promise<"new" | "existing">((resolve) => { const { unmount } = render( <> <Text> No project selected. Would you like to create one or use an existing project? </Text> <SelectInput items={[ { key: "new", label: "Create a new project", value: "new", }, { key: "existing", label: "Use an existing project", value: "existing", }, ]} onSelect={async (selected) => { resolve(selected.value as "new" | "existing"); unmount(); }} /> </> ); }); } switch (existingOrNew) { case "existing": { projectName = await new Promise((resolve) => { const { unmount } = render( <> <Text>Select a project:</Text> <SelectInput items={projects.map((project) => ({ key: project.name, label: project.name, value: project, }))} onSelect={async (selected) => { resolve(selected.value.name); unmount(); }} /> </> ); }); break; } case "new": { projectName = await prompt("Enter the name of your new project:"); if (!projectName) { throw new FatalError("Must specify a project name.", 1); } let isGitDir = true; try { execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore", }); } catch (err) { isGitDir = false; } const productionBranch = await prompt( "Enter the production branch name:", "text", isGitDir ? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim() : "production" ); if (!productionBranch) { throw new FatalError("Must specify a production branch.", 1); } await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, { method: "POST", body: JSON.stringify({ name: projectName, production_branch: productionBranch, }), }); saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, { account_id: accountId, project_name: projectName, }); logger.log(`โœจ Successfully created the '${projectName}' project.`); break; } } } if (!projectName) { throw new FatalError("Must specify a project name.", 1); } // We infer git info by default is not passed in let isGitDir = true; try { execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore", }); } catch (err) { isGitDir = false; } let isGitDirty = false; if (isGitDir) { try { isGitDirty = Boolean( execSync(`git status --porcelain`).toString().length ); if (!branch) { branch = execSync(`git rev-parse --abbrev-ref HEAD`) .toString() .trim(); } if (!commitHash) { commitHash = execSync(`git rev-parse HEAD`).toString().trim(); } if (!commitMessage) { commitMessage = execSync(`git show -s --format=%B ${commitHash}`) .toString() .trim(); } } catch (err) {} if (isGitDirty && !commitDirty) { logger.warn( `Warning: Your working directory is a git repo and has uncommitted changes\nTo silense this warning, pass in --commit-dirty=true` ); } if (commitDirty === undefined) { commitDirty = isGitDirty; } } let builtFunctions: string | undefined = undefined; const functionsDirectory = join(cwd(), "functions"); if (existsSync(functionsDirectory)) { const outfile = join(tmpdir(), "./functionsWorker.js"); await new Promise((resolve) => buildFunctions({ outfile, functionsDirectory, onEnd: () => resolve(null), buildOutputDirectory: dirname(outfile), }) ); builtFunctions = readFileSync(outfile, "utf-8"); } type File = { content: Buffer; metadata: Metadata; }; type Metadata = { sizeInBytes: number; hash: string; }; const IGNORE_LIST = [ "_worker.js", "_redirects", "_headers", ".DS_Store", "node_modules", ]; const walk = async ( dir: string, fileMap: Map<string, File> = new Map(), depth = 0 ) => { const files = await readdir(dir); await Promise.all( files.map(async (file) => { const filepath = join(dir, file); const filestat = await stat(filepath); if (IGNORE_LIST.includes(file)) { return; } if (filestat.isSymbolicLink()) { return; } if (filestat.isDirectory()) { fileMap = await walk(filepath, fileMap, depth + 1); } else { let name; if (depth) { name = filepath.split(sep).slice(1).join("/"); } else { name = file; } // TODO: Move this to later so we don't hold as much in memory const fileContent = await readFile(filepath); const base64Content = fileContent.toString("base64"); const extension = name.split(".").length > 1 ? name.split(".").at(-1) || "" : ""; const content = base64Content + extension; if (filestat.size > 25 * 1024 * 1024) { throw new Error( `Error: Pages only supports files up to ${prettyBytes( 25 * 1024 * 1024 )} in size\n${name} is ${prettyBytes(filestat.size)} in size` ); } fileMap.set(name, { content: fileContent, metadata: { sizeInBytes: filestat.size, hash: hash(content).toString("hex").slice(0, 32), }, }); } }) ); return fileMap; }; const fileMap = await walk(directory); const start = Date.now(); const files: Array<Promise<void>> = []; if (fileMap.size > 1000) { throw new Error( `Error: Pages only supports up to 1,000 files in a deployment at the moment.\nTry a smaller project perhaps?` ); } let counter = 0; const { rerender, unmount } = render( <Progress done={counter} total={fileMap.size} /> ); fileMap.forEach((file: File, name: string) => { const form = new FormData(); form.append( "file", new File([new Uint8Array(file.content.buffer)], name) ); // TODO: Consider a retry const promise = fetchResult<{ id: string }>( `/accounts/${accountId}/pages/projects/${projectName}/file`, { method: "POST", body: form, } ).then((response) => { counter++; rerender(<Progress done={counter} total={fileMap.size} />); if (response.id != file.metadata.hash) { throw new Error( `Looks like there was an issue uploading '${name}'. Try again perhaps?` ); } }); files.push(promise); }); await Promise.all(files); unmount(); const uploadMs = Date.now() - start; logger.log( `โœจ Success! Uploaded ${fileMap.size} files ${formatTime(uploadMs)}\n` ); const formData = new FormData(); formData.append( "manifest", JSON.stringify( Object.fromEntries( [...fileMap.entries()].map(([fileName, file]) => [ `/${fileName}`, file.metadata.hash, ]) ) ) ); if (branch) { formData.append("branch", branch); } if (commitMessage) { formData.append("commit_message", commitMessage); } if (commitHash) { formData.append("commit_hash", commitHash); } if (commitDirty !== undefined) { formData.append("commit_dirty", commitDirty); } let _headers: string | undefined, _redirects: string | undefined, _workerJS: string | undefined; try { _headers = readFileSync(join(directory, "_headers"), "utf-8"); } catch {} try { _redirects = readFileSync(join(directory, "_redirects"), "utf-8"); } catch {} try { _workerJS = readFileSync(join(directory, "_worker.js"), "utf-8"); } catch {} if (_headers) { formData.append("_headers", new File([_headers], "_headers")); } if (_redirects) { formData.append("_redirects", new File([_redirects], "_redirects")); } if (builtFunctions) { formData.append("_worker.js", new File([builtFunctions], "_worker.js")); } else if (_workerJS) { formData.append("_worker.js", new File([_workerJS], "_worker.js")); } const deploymentResponse = await fetchResult<Deployment>( `/accounts/${accountId}/pages/projects/${projectName}/deployments`, { method: "POST", body: formData, } ); saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, { account_id: accountId, project_name: projectName, }); logger.log( `โœจ Deployment complete! Take a peek over at ${deploymentResponse.url}` ); }, }; export const pages: BuilderCallback<unknown, unknown> = (yargs) => { return yargs .command( "dev [directory] [-- command]", "๐Ÿง‘โ€๐Ÿ’ป Develop your full-stack Pages application locally", (yargs) => { return yargs .positional("directory", { type: "string", demandOption: undefined, description: "The directory of static assets to serve", }) .positional("command", { type: "string", demandOption: undefined, description: "The proxy command to run", }) .options({ local: { type: "boolean", default: true, description: "Run on my machine", }, port: { type: "number", default: 8788, description: "The port to listen on (serve from)", }, proxy: { type: "number", description: "The port to proxy (where the static assets are served)", }, "script-path": { type: "string", default: "_worker.js", description: "The location of the single Worker script if not using functions", }, binding: { type: "array", description: "Bind variable/secret (KEY=VALUE)", alias: "b", }, kv: { type: "array", description: "KV namespace to bind", alias: "k", }, do: { type: "array", description: "Durable Object to bind (NAME=CLASS)", alias: "o", }, "live-reload": { type: "boolean", default: false, description: "Auto reload HTML pages when change is detected", }, // TODO: Miniflare user options }) .epilogue(pagesBetaWarning); }, async ({ local, directory, port, proxy: requestedProxyPort, "script-path": singleWorkerScriptPath, binding: bindings = [], kv: kvs = [], do: durableObjects = [], "live-reload": liveReload, _: [_pages, _dev, ...remaining], }) => { // Beta message for `wrangler pages <commands>` usage logger.log(pagesBetaWarning); if (!local) { logger.error("Only local mode is supported at the moment."); return; } const functionsDirectory = "./functions"; const usingFunctions = existsSync(functionsDirectory); const command = remaining as (string | number)[]; let proxyPort: number | void; if (directory === undefined) { proxyPort = await spawnProxyProcess({ port: requestedProxyPort, command, }); if (proxyPort === undefined) return undefined; } let miniflareArgs: MiniflareOptions = {}; let scriptReadyResolve: () => void; const scriptReadyPromise = new Promise<void>( (resolve) => (scriptReadyResolve = resolve) ); if (usingFunctions) { const outfile = join(tmpdir(), "./functionsWorker.js"); logger.log(`Compiling worker to "${outfile}"...`); try { await buildFunctions({ outfile, functionsDirectory, sourcemap: true, watch: true, onEnd: () => scriptReadyResolve(), buildOutputDirectory: directory, }); } catch {} watch([functionsDirectory], { persistent: true, ignoreInitial: true, }).on("all", async () => { await buildFunctions({ outfile, functionsDirectory, sourcemap: true, watch: true, onEnd: () => scriptReadyResolve(), buildOutputDirectory: directory, }); }); miniflareArgs = { scriptPath: outfile, }; } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion scriptReadyResolve!(); const scriptPath = directory !== undefined ? join(directory, singleWorkerScriptPath) : singleWorkerScriptPath; if (existsSync(scriptPath)) { miniflareArgs = { scriptPath, }; } else { logger.log("No functions. Shimming..."); miniflareArgs = { // TODO: The fact that these request/response hacks are necessary is ridiculous. // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well) script: ` export default { async fetch(request, env, context) { const response = await env.ASSETS.fetch(request.url, request) return new Response(response.body, response) } }`, }; } } // Defer importing miniflare until we really need it const { Miniflare, Log, LogLevel } = await import("miniflare"); const { Response, fetch } = await import("@miniflare/core"); // Wait for esbuild to finish building before starting Miniflare. // This must be before the call to `new Miniflare`, as that will // asynchronously start loading the script. `await startServer()` // internally just waits for that promise to resolve. await scriptReadyPromise; // `assetsFetch()` will only be called if there is `proxyPort` defined. // We only define `proxyPort`, above, when there is no `directory` defined. const assetsFetch = directory !== undefined ? await generateAssetsFetch(directory) : invalidAssetsFetch; const requestContextCheckOptions = await getRequestContextCheckOptions(); const miniflare = new Miniflare({ port, watch: true, modules: true, log: new Log(LogLevel.ERROR, { prefix: "pages" }), logUnhandledRejections: true, sourceMap: true, kvNamespaces: kvs.map((kv) => kv.toString()), durableObjects: Object.fromEntries( durableObjects.map((durableObject) => durableObject.toString().split("=") ) ), // User bindings bindings: { ...Object.fromEntries( bindings .map((binding) => binding.toString().split("=")) .map(([key, ...values]) => [key, values.join("=")]) ), }, // env.ASSETS.fetch serviceBindings: { async ASSETS(request: Request) { if (proxyPort) { try { const url = new URL(request.url); url.host = `localhost:${proxyPort}`; return await fetch(url, request); } catch (thrown) { logger.error(`Could not proxy request: ${thrown}`); // TODO: Pretty error page return new Response( `[wrangler] Could not proxy request: ${thrown}`, { status: 502 } ); } } else { try { return await assetsFetch(request); } catch (thrown) { logger.error(`Could not serve static asset: ${thrown}`); // TODO: Pretty error page return new Response( `[wrangler] Could not serve static asset: ${thrown}`, { status: 502 } ); } } }, }, kvPersist: true, durableObjectsPersist: true, cachePersist: true, liveReload, ...requestContextCheckOptions, ...miniflareArgs, }); try { // `startServer` might throw if user code contains errors const server = await miniflare.startServer(); logger.log(`Serving at http://localhost:${port}/`); if (process.env.BROWSER !== "none") { await openInBrowser(`http://localhost:${port}/`); } if (directory !== undefined && liveReload) { watch([directory], { persistent: true, ignoreInitial: true, }).on("all", async () => { await miniflare.reload(); }); } CLEANUP_CALLBACKS.push(() => { server.close(); miniflare.dispose().catch((err) => miniflare.log.error(err)); }); } catch (e) { miniflare.log.error(e as Error); CLEANUP(); throw new FatalError("Could not start Miniflare.", 1); } } ) .command("functions", false, (yargs) => // we hide this command from help output because // it's not meant to be used directly right now yargs.command( "build [directory]", "Compile a folder of Cloudflare Pages Functions into a single Worker", (yargs) => yargs .positional("directory", { type: "string", default: "functions", description: "The directory of Pages Functions", }) .options({ outfile: { type: "string", default: "_worker.js", description: "The location of the output Worker script", }, "output-config-path": { type: "string", description: "The location for the output config file", }, minify: { type: "boolean", default: false, description: "Minify the output Worker script", }, sourcemap: { type: "boolean", default: false, description: "Generate a sourcemap for the output Worker script", }, "fallback-service": { type: "string", default: "ASSETS", description: "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.", }, watch: { type: "boolean", default: false, description: "Watch for changes to the functions and automatically rebuild the Worker script", }, plugin: { type: "boolean", default: false, description: "Build a plugin rather than a Worker script", }, "build-output-directory": { type: "string", description: "The directory to output static assets to", }, }) .epilogue(pagesBetaWarning), async ({ directory, outfile, "output-config-path": outputConfigPath, minify, sourcemap, fallbackService, watch, plugin, "build-output-directory": buildOutputDirectory, }) => { if (!isInPagesCI) { // Beta message for `wrangler pages <commands>` usage logger.log(pagesBetaWarning); } buildOutputDirectory ??= dirname(outfile); await buildFunctions({ outfile, outputConfigPath, functionsDirectory: directory, minify, sourcemap, fallbackService, watch, plugin, buildOutputDirectory, }); } ) ) .command("project", "โšก๏ธ Interact with your Pages projects", (yargs) => yargs .command( "list", "List your Cloudflare Pages projects", (yargs) => yargs.epilogue(pagesBetaWarning), async () => { const config = getConfigCache<PagesConfigCache>( PAGES_CONFIG_CACHE_FILENAME ); const accountId = await requireAuth(config); const projects: Array<Project> = await listProjects({ accountId }); const data = projects.map((project) => { return { "Project Name": project.name, "Project Domains": `${project.domains.join(", ")}`, "Git Provider": project.source ? "Yes" : "No", "Last Modified": project.latest_deployment ? timeagoFormat(project.latest_deployment.modified_on) : timeagoFormat(project.created_on), }; }); saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, { account_id: accountId, }); render(<Table data={data}></Table>); } ) .command( "create [project-name]", "Create a new Cloudflare Pages project", (yargs) => yargs .positional("project-name", { type: "string", demandOption: true, description: "The name of your Pages project", }) .options({ "production-branch": { type: "string", description: "The name of the production branch of your project", }, }) .epilogue(pagesBetaWarning), async ({ productionBranch, projectName }) => { const config = getConfigCache<PagesConfigCache>( PAGES_CONFIG_CACHE_FILENAME ); const accountId = await requireAuth(config); const isInteractive = process.stdin.isTTY; if (!projectName && isInteractive) { projectName = await prompt("Enter the name of your new project:"); } if (!projectName) { throw new FatalError("Must specify a project name.", 1); } if (!productionBranch && isInteractive) { let isGitDir = true; try { execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore", }); } catch (err) { isGitDir = false; } productionBranch = await prompt( "Enter the production branch name:", "text", isGitDir ? execSync(`git rev-parse --abbrev-ref HEAD`) .toString() .trim() : "production" ); } if (!productionBranch) { throw new FatalError("Must specify a production branch.", 1); } const { subdomain } = await fetchResult<Project>( `/accounts/${accountId}/pages/projects`, { method: "POST", body: JSON.stringify({ name: projectName, production_branch: productionBranch, }), } ); saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, { account_id: accountId, project_name: projectName, }); logger.log( `โœจ Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.` ); logger.log( `To deploy a folder of assets, run 'wrangler pages publish [directory]'.` ); } ) .epilogue(pagesBetaWarning) ) .command( "deployment", "๐Ÿš€ Interact with the deployments of a project", (yargs) => yargs .command( "list", "List deployments in your Cloudflare Pages project", (yargs) => yargs .options({ "project-name": { type: "string", description: "The name of the project you would like to list deployments for", }, }) .epilogue(pagesBetaWarning), async ({ projectName }) => { const config = getConfigCache<PagesConfigCache>( PAGES_CONFIG_CACHE_FILENAME ); const accountId = await requireAuth(config); projectName ??= config.project_name; const isInteractive = process.stdin.isTTY; if (!projectName && isInteractive) { const projects = await listProjects({ accountId }); projectName = await new Promise((resolve) => { const { unmount } = render( <> <Text>Select a project:</Text> <SelectInput items={projects.map((project) => ({ key: project.name, label: project.name, value: project, }))} onSelect={async (selected) => { resolve(selected.value.name); unmount(); }} /> </> ); }); } if (!projectName) { throw new FatalError("Must specify a project name.", 1); } const deployments: Array<Deployment> = await fetchResult( `/accounts/${accountId}/pages/projects/${projectName}/deployments` ); const titleCase = (word: string) => word.charAt(0).toUpperCase() + word.slice(1); const shortSha = (sha: string) => sha.slice(0, 7); const getStatus = (deployment: Deployment) => { // Return a pretty time since timestamp if successful otherwise the status if (deployment.latest_stage.status === `success`) { return timeagoFormat(deployment.latest_stage.ended_on); } return titleCase(deployment.latest_stage.status); }; const data = deployments.map((deployment) => { return { Environment: titleCase(deployment.environment), Branch: deployment.deployment_trigger.metadata.branch, Source: shortSha( deployment.deployment_trigger.metadata.commit_hash ), Deployment: deployment.url, Status: getStatus(deployment), // TODO: Use a url shortener Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`, }; }); saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, { account_id: accountId, }); render(<Table data={data}></Table>); } ) .command({ command: "create [directory]", ...createDeployment, } as CommandModule) .epilogue(pagesBetaWarning) ) .command({ command: "publish [directory]", ...createDeployment, } as CommandModule); }; const invalidAssetsFetch: typeof fetch = () => { throw new Error( "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode." ); }; const listProjects = async ({ accountId, }: { accountId: string; }): Promise<Array<Project>> => { const pageSize = 10; let page = 1; const results = []; while (results.length % pageSize === 0) { const json: Array<Project> = await fetchResult( `/accounts/${accountId}/pages/projects`, {}, new URLSearchParams({ per_page: pageSize.toString(), page: page.toString(), }) ); page++; results.push(...json); if (json.length < pageSize) { break; } } return results; }; function formatTime(duration: number) { return `(${(duration / 1000).toFixed(2)} sec)`; } function Progress({ done, total }: { done: number; total: number }) { return ( <> <Text> <Spinner type="earth" /> {` Uploading... (${done}/${total})\n`} </Text> </> ); }
the_stack
namespace data { export interface CallNode { id: string; name: string; callsite: string; source: string; start: number; // time finish: number; // time startMetrics: Map<number>; finishMetrics: Map<number>; isFinished: boolean; // have we seen an exit event for this node? inputs: Map<any>; outputs: Map<any>; children: CallNode[]; parent: CallNode; incl: Map<number>; excl: Map<number>; score: number; } export interface ProfileState { metadata: Object; root: CallNode; current: CallNode; idToNode: Map<CallNode>; zeroMetrics: Map<number>; solverCalls: SolverCall[]; streaming: boolean; } export interface SolverCall { type: SolverCallType, start: number; finish: number; sat: boolean; } export enum SolverCallType { SOLVE, ENCODE, FINITIZE }; // events are also a type of message, since they have a type field interface Message { type: string } // buffer messages until document ready var bufferedMessages: Message[] = []; var ready = false; var currentState: ProfileState = { metadata: null, root: null, current: null, idToNode: {}, zeroMetrics: null, solverCalls: [], streaming: false }; // callbacks to invoke when new state data arrives type StateUpdateCallback = (msg: ProfileState) => void; var updateCallbacks: StateUpdateCallback[] = []; export function registerUpdateCallback(cb: StateUpdateCallback): void { updateCallbacks.push(cb); } export function unregisterUpdateCallback(cb: StateUpdateCallback): void { let i = updateCallbacks.indexOf(cb); if (i > -1) updateCallbacks.splice(i, 1); } export function readyForData() { if (!ready) { ready = true; receiveData(bufferedMessages); bufferedMessages = []; } } function diffMetrics(p1: Map<number>, p2: Map<number>): Map<number> { let ret: Map<number> = {}; for (let k in p1) { if (p2.hasOwnProperty(k)) { ret[k] = p2[k] - p1[k]; } } return ret; } function exclMetrics(incl: Map<number>, children: CallNode[]): Map<number> { let ret = {}; for (let k in incl) { ret[k] = incl[k]; } for (let c of children) { for (let k in incl) { ret[k] -= c.incl[k] || 0; } } return ret; } namespace messages { export function receiveMetadataMessage(msg: Message): void { delete msg["type"]; currentState.metadata = msg; } // update the ProfileState using data from the profile message export function receiveCallgraphMessage(msg: Message): void { let evts = msg["events"]; if (evts.length == 0) return; if (!currentState.zeroMetrics) { currentState.zeroMetrics = evts[0].metrics; } for (let e of evts) { if (e.type == "ENTER") { if (!currentState.current && currentState.root) { console.error("multiple root procedure calls"); return; } // e has fields: // id, function, location, inputs, metrics let dm = diffMetrics(currentState.zeroMetrics, e.metrics); let node: CallNode = { id: e.id, name: e.function, callsite: e.callsite, source: e.source, start: dm.time, finish: null, startMetrics: dm, finishMetrics: null, isFinished: false, inputs: e.inputs, outputs: {}, children: [], parent: currentState.current, incl: {}, excl: {}, score: 0 }; if (currentState.current) currentState.current.children.push(node); if (!currentState.root) // might be the first call currentState.root = node; currentState.current = node; currentState.idToNode[e.id] = node; } else if (e.type == "EXIT") { if (!currentState.current) { console.error("unbalanced EXIT event"); } // e has fields: // outputs, metrics let dm = diffMetrics(currentState.zeroMetrics, e.metrics); currentState.current.finish = dm.time; currentState.current.finishMetrics = dm; currentState.current.outputs = e.outputs; currentState.current.isFinished = true; currentState.current.incl = diffMetrics(currentState.current.startMetrics, dm); currentState.current.excl = exclMetrics(currentState.current.incl, currentState.current.children); currentState.current = currentState.current.parent; } } // set fake finish times and metrics for unclosed nodes let fakeFinishMetrics = diffMetrics(currentState.zeroMetrics, evts[evts.length-1].metrics); let fakeFinishTime = fakeFinishMetrics.time; let curr = currentState.current; while (curr) { if (!curr.isFinished) { curr.finish = fakeFinishTime; curr.finishMetrics = fakeFinishMetrics; curr.incl = diffMetrics(curr.startMetrics, fakeFinishMetrics); curr.excl = exclMetrics(curr.incl, curr.children); } curr = curr.parent; } } export function receiveSolverCallsMessage(msg: Message): void { let events = msg["events"]; if (!currentState.zeroMetrics) { console.error("solver-calls expects profile data first"); return; } let startTime = currentState.zeroMetrics.time; for (let e of events) { if (e.type == "start") { let typ = e.part == "solver" ? SolverCallType.SOLVE : (e.part == "encode" ? SolverCallType.ENCODE : SolverCallType.FINITIZE); currentState.solverCalls.push({ type: typ, start: e.time - startTime, finish: undefined, sat: undefined }); } else if (e.type == "finish") { if (currentState.solverCalls.length > 0) { let curr = currentState.solverCalls[currentState.solverCalls.length - 1]; curr.finish = e.time - startTime; if (curr.type == SolverCallType.SOLVE) curr.sat = e.sat; } } } } export function receiveUnusedTermsMessage(msg: Message): void { let data: number[][] = msg["data"]; // list of (call-id, #unused) pairs for (let pair of data) { let id = pair[0].toString(), num = pair[1]; if (currentState.idToNode.hasOwnProperty(id)) { let node = currentState.idToNode[id]; node.excl["unused-terms"] = num; } } } } namespace stream { var webSocket: WebSocket; export function receiveStreamMessage(msg: Message): void { if (msg["event"] == "start") { currentState.streaming = true; webSocket = new WebSocket(msg["url"]); webSocket.onmessage = webSocketMessageCallback; webSocket.onerror = webSocketErrorCallback; } else if (msg["event"] == "finish") { currentState.streaming = false; if (webSocket) webSocket.close(); } else { console.log("unknown stream message:", msg); } } function webSocketMessageCallback(evt: MessageEvent): void { let msgs = JSON.parse(evt.data); // will be a list of messages receiveData(msgs); } function webSocketErrorCallback(evt: Event) { alert("Could not open the WebSocket connection for streaming. This might happen if the profiler is not currently running."); } } // hand messages to their handler functions function receiveMessages(msgs: Message[]): void { for (let msg of msgs) { if (msg.type == "metadata") { messages.receiveMetadataMessage(msg); } else if (msg.type == "callgraph") { messages.receiveCallgraphMessage(msg); } else if (msg.type == "solver-calls") { messages.receiveSolverCallsMessage(msg); } else if (msg.type == "unused-terms") { messages.receiveUnusedTermsMessage(msg); } else if (msg.type === "stream") { stream.receiveStreamMessage(msg); } else { console.log("unknown message:", msg); } } } export function receiveData(msgs: Message[]): void { if (ready) { receiveMessages(msgs); for (let cb of updateCallbacks) { cb(currentState); } } else { bufferedMessages.push(...msgs); } } }
the_stack
import extend from "@yomguithereal/helpers/extend"; import { PlainObject } from "../types"; // TODO: should not ask the quadtree when the camera has the whole graph in // sight. // TODO: a square can be represented as topleft + width, saying for the quad blocks (reduce mem) // TODO: jsdoc // TODO: be sure we can handle cases overcoming boundaries (because of size) or use a maxed size // TODO: filtering unwanted labels beforehand through the filter function // NOTE: this is basically a MX-CIF Quadtree at this point // NOTE: need to explore R-Trees for edges // NOTE: need to explore 2d segment tree for edges // NOTE: probably can do faster using spatial hashing /** * Constants. * * Note that since we are representing a static 4-ary tree, the indices of the * quadrants are the following: * - TOP_LEFT: 4i + b * - TOP_RIGHT: 4i + 2b * - BOTTOM_LEFT: 4i + 3b * - BOTTOM_RIGHT: 4i + 4b */ const BLOCKS = 4, MAX_LEVEL = 5; const OUTSIDE_BLOCK = "outside"; const X_OFFSET = 0, Y_OFFSET = 1, WIDTH_OFFSET = 2, HEIGHT_OFFSET = 3; const TOP_LEFT = 1, TOP_RIGHT = 2, BOTTOM_LEFT = 3, BOTTOM_RIGHT = 4; let hasWarnedTooMuchOutside = false; export interface Boundaries { x: number; y: number; width: number; height: number; } export interface Rectangle { x1: number; y1: number; x2: number; y2: number; height: number; } export interface Vector { x: number; y: number; } /** * Geometry helpers. */ /** * Function returning whether the given rectangle is axis-aligned. * * @param {Rectangle} rect * @return {boolean} */ export function isRectangleAligned(rect: Rectangle): boolean { return rect.x1 === rect.x2 || rect.y1 === rect.y2; } /** * Function returning the smallest rectangle that contains the given rectangle, and that is aligned with the axis. * * @param {Rectangle} rect * @return {Rectangle} */ export function getCircumscribedAlignedRectangle(rect: Rectangle): Rectangle { const width = Math.sqrt(Math.pow(rect.x2 - rect.x1, 2) + Math.pow(rect.y2 - rect.y1, 2)); const heightVector = { x: ((rect.y1 - rect.y2) * rect.height) / width, y: ((rect.x2 - rect.x1) * rect.height) / width, }; // Compute all corners: const tl: Vector = { x: rect.x1, y: rect.y1 }; const tr: Vector = { x: rect.x2, y: rect.y2 }; const bl: Vector = { x: rect.x1 + heightVector.x, y: rect.y1 + heightVector.y, }; const br: Vector = { x: rect.x2 + heightVector.x, y: rect.y2 + heightVector.y, }; const xL = Math.min(tl.x, tr.x, bl.x, br.x); const xR = Math.max(tl.x, tr.x, bl.x, br.x); const yT = Math.min(tl.y, tr.y, bl.y, br.y); const yB = Math.max(tl.y, tr.y, bl.y, br.y); return { x1: xL, y1: yT, x2: xR, y2: yT, height: yB - yT, }; } /** * * @param x1 * @param y1 * @param w * @param qx * @param qy * @param qw * @param qh */ export function squareCollidesWithQuad( x1: number, y1: number, w: number, qx: number, qy: number, qw: number, qh: number, ): boolean { return x1 < qx + qw && x1 + w > qx && y1 < qy + qh && y1 + w > qy; } export function rectangleCollidesWithQuad( x1: number, y1: number, w: number, h: number, qx: number, qy: number, qw: number, qh: number, ): boolean { return x1 < qx + qw && x1 + w > qx && y1 < qy + qh && y1 + h > qy; } function pointIsInQuad(x: number, y: number, qx: number, qy: number, qw: number, qh: number): number { const xmp = qx + qw / 2, ymp = qy + qh / 2, top = y < ymp, left = x < xmp; return top ? (left ? TOP_LEFT : TOP_RIGHT) : left ? BOTTOM_LEFT : BOTTOM_RIGHT; } /** * Helper functions that are not bound to the class so an external user * cannot mess with them. */ function buildQuadrants(maxLevel: number, data: Float32Array): void { // [block, level] const stack: Array<number> = [0, 0]; while (stack.length) { const level = stack.pop() as number, block = stack.pop() as number; const topLeftBlock = 4 * block + BLOCKS, topRightBlock = 4 * block + 2 * BLOCKS, bottomLeftBlock = 4 * block + 3 * BLOCKS, bottomRightBlock = 4 * block + 4 * BLOCKS; const x = data[block + X_OFFSET], y = data[block + Y_OFFSET], width = data[block + WIDTH_OFFSET], height = data[block + HEIGHT_OFFSET], hw = width / 2, hh = height / 2; data[topLeftBlock + X_OFFSET] = x; data[topLeftBlock + Y_OFFSET] = y; data[topLeftBlock + WIDTH_OFFSET] = hw; data[topLeftBlock + HEIGHT_OFFSET] = hh; data[topRightBlock + X_OFFSET] = x + hw; data[topRightBlock + Y_OFFSET] = y; data[topRightBlock + WIDTH_OFFSET] = hw; data[topRightBlock + HEIGHT_OFFSET] = hh; data[bottomLeftBlock + X_OFFSET] = x; data[bottomLeftBlock + Y_OFFSET] = y + hh; data[bottomLeftBlock + WIDTH_OFFSET] = hw; data[bottomLeftBlock + HEIGHT_OFFSET] = hh; data[bottomRightBlock + X_OFFSET] = x + hw; data[bottomRightBlock + Y_OFFSET] = y + hh; data[bottomRightBlock + WIDTH_OFFSET] = hw; data[bottomRightBlock + HEIGHT_OFFSET] = hh; if (level < maxLevel - 1) { stack.push(bottomRightBlock, level + 1); stack.push(bottomLeftBlock, level + 1); stack.push(topRightBlock, level + 1); stack.push(topLeftBlock, level + 1); } } } function insertNode( maxLevel: number, data: Float32Array, containers: PlainObject<string[]>, key: string, x: number, y: number, size: number, ) { const x1 = x - size, y1 = y - size, w = size * 2; let level = 0, block = 0; while (true) { // If we reached max level if (level >= maxLevel) { containers[block] = containers[block] || []; containers[block].push(key); return; } const topLeftBlock = 4 * block + BLOCKS, topRightBlock = 4 * block + 2 * BLOCKS, bottomLeftBlock = 4 * block + 3 * BLOCKS, bottomRightBlock = 4 * block + 4 * BLOCKS; const collidingWithTopLeft = squareCollidesWithQuad( x1, y1, w, data[topLeftBlock + X_OFFSET], data[topLeftBlock + Y_OFFSET], data[topLeftBlock + WIDTH_OFFSET], data[topLeftBlock + HEIGHT_OFFSET], ); const collidingWithTopRight = squareCollidesWithQuad( x1, y1, w, data[topRightBlock + X_OFFSET], data[topRightBlock + Y_OFFSET], data[topRightBlock + WIDTH_OFFSET], data[topRightBlock + HEIGHT_OFFSET], ); const collidingWithBottomLeft = squareCollidesWithQuad( x1, y1, w, data[bottomLeftBlock + X_OFFSET], data[bottomLeftBlock + Y_OFFSET], data[bottomLeftBlock + WIDTH_OFFSET], data[bottomLeftBlock + HEIGHT_OFFSET], ); const collidingWithBottomRight = squareCollidesWithQuad( x1, y1, w, data[bottomRightBlock + X_OFFSET], data[bottomRightBlock + Y_OFFSET], data[bottomRightBlock + WIDTH_OFFSET], data[bottomRightBlock + HEIGHT_OFFSET], ); const collisions: number = [ collidingWithTopLeft, collidingWithTopRight, collidingWithBottomLeft, collidingWithBottomRight, ].reduce((acc: number, current: boolean) => { if (current) return acc + 1; else return acc; }, 0); // If we have no collision at root level, inject node in the outside block if (collisions === 0 && level === 0) { containers[OUTSIDE_BLOCK].push(key); if (!hasWarnedTooMuchOutside && containers[OUTSIDE_BLOCK].length >= 5) { hasWarnedTooMuchOutside = true; console.warn( "sigma/quadtree.insertNode: At least 5 nodes are outside the global quadtree zone. " + "You might have a problem with the normalization function or the custom bounding box.", ); } return; } // If we don't have at least a collision but deeper, there is an issue if (collisions === 0) throw new Error( `sigma/quadtree.insertNode: no collision (level: ${level}, key: ${key}, x: ${x}, y: ${y}, size: ${size}).`, ); // If we have 3 collisions, we have a geometry problem obviously if (collisions === 3) throw new Error( `sigma/quadtree.insertNode: 3 impossible collisions (level: ${level}, key: ${key}, x: ${x}, y: ${y}, size: ${size}).`, ); // If we have more that one collision, we stop here and store the node // in the relevant containers if (collisions > 1) { containers[block] = containers[block] || []; containers[block].push(key); return; } else { level++; } // Else we recurse into the correct quads if (collidingWithTopLeft) block = topLeftBlock; if (collidingWithTopRight) block = topRightBlock; if (collidingWithBottomLeft) block = bottomLeftBlock; if (collidingWithBottomRight) block = bottomRightBlock; } } function getNodesInAxisAlignedRectangleArea( maxLevel: number, data: Float32Array, containers: PlainObject<string[]>, x1: number, y1: number, w: number, h: number, ): string[] { // [block, level] const stack = [0, 0]; const collectedNodes: string[] = []; let container; while (stack.length) { const level = stack.pop() as number, block = stack.pop() as number; // Collecting nodes container = containers[block]; if (container) extend(collectedNodes, container); // If we reached max level if (level >= maxLevel) continue; const topLeftBlock = 4 * block + BLOCKS, topRightBlock = 4 * block + 2 * BLOCKS, bottomLeftBlock = 4 * block + 3 * BLOCKS, bottomRightBlock = 4 * block + 4 * BLOCKS; const collidingWithTopLeft = rectangleCollidesWithQuad( x1, y1, w, h, data[topLeftBlock + X_OFFSET], data[topLeftBlock + Y_OFFSET], data[topLeftBlock + WIDTH_OFFSET], data[topLeftBlock + HEIGHT_OFFSET], ); const collidingWithTopRight = rectangleCollidesWithQuad( x1, y1, w, h, data[topRightBlock + X_OFFSET], data[topRightBlock + Y_OFFSET], data[topRightBlock + WIDTH_OFFSET], data[topRightBlock + HEIGHT_OFFSET], ); const collidingWithBottomLeft = rectangleCollidesWithQuad( x1, y1, w, h, data[bottomLeftBlock + X_OFFSET], data[bottomLeftBlock + Y_OFFSET], data[bottomLeftBlock + WIDTH_OFFSET], data[bottomLeftBlock + HEIGHT_OFFSET], ); const collidingWithBottomRight = rectangleCollidesWithQuad( x1, y1, w, h, data[bottomRightBlock + X_OFFSET], data[bottomRightBlock + Y_OFFSET], data[bottomRightBlock + WIDTH_OFFSET], data[bottomRightBlock + HEIGHT_OFFSET], ); if (collidingWithTopLeft) stack.push(topLeftBlock, level + 1); if (collidingWithTopRight) stack.push(topRightBlock, level + 1); if (collidingWithBottomLeft) stack.push(bottomLeftBlock, level + 1); if (collidingWithBottomRight) stack.push(bottomRightBlock, level + 1); } return collectedNodes; } /** * QuadTree class. * * @constructor * @param {object} boundaries - The graph boundaries. */ export default class QuadTree { data: Float32Array; containers: PlainObject<string[]> = { [OUTSIDE_BLOCK]: [] }; cache: string[] | null = null; lastRectangle: Rectangle | null = null; constructor(params: { boundaries?: Boundaries } = {}) { // Allocating the underlying byte array const L = Math.pow(4, MAX_LEVEL); this.data = new Float32Array(BLOCKS * ((4 * L - 1) / 3)); if (params.boundaries) this.resize(params.boundaries); else this.resize({ x: 0, y: 0, width: 1, height: 1, }); } add(key: string, x: number, y: number, size: number): QuadTree { insertNode(MAX_LEVEL, this.data, this.containers, key, x, y, size); return this; } resize(boundaries: Boundaries): void { this.clear(); // Building the quadrants this.data[X_OFFSET] = boundaries.x; this.data[Y_OFFSET] = boundaries.y; this.data[WIDTH_OFFSET] = boundaries.width; this.data[HEIGHT_OFFSET] = boundaries.height; buildQuadrants(MAX_LEVEL, this.data); } clear(): QuadTree { this.containers = { [OUTSIDE_BLOCK]: [] }; return this; } point(x: number, y: number): string[] { const nodes: string[] = this.containers[OUTSIDE_BLOCK]; let block = 0, level = 0; do { if (this.containers[block]) nodes.push(...this.containers[block]); const quad = pointIsInQuad( x, y, this.data[block + X_OFFSET], this.data[block + Y_OFFSET], this.data[block + WIDTH_OFFSET], this.data[block + HEIGHT_OFFSET], ); block = 4 * block + quad * BLOCKS; level++; } while (level <= MAX_LEVEL); return nodes; } rectangle(x1: number, y1: number, x2: number, y2: number, height: number): string[] { const lr = this.lastRectangle; if (lr && x1 === lr.x1 && x2 === lr.x2 && y1 === lr.y1 && y2 === lr.y2 && height === lr.height) { return this.cache as string[]; } this.lastRectangle = { x1, y1, x2, y2, height, }; // If the rectangle is shifted, we use the smallest aligned rectangle that contains the shifted one: if (!isRectangleAligned(this.lastRectangle)) this.lastRectangle = getCircumscribedAlignedRectangle(this.lastRectangle); this.cache = getNodesInAxisAlignedRectangleArea( MAX_LEVEL, this.data, this.containers, x1, y1, Math.abs(x1 - x2) || Math.abs(y1 - y2), height, ); // Add all the nodes in the outside block, since they might be relevant, and since they should be very few: this.cache.push(...this.containers[OUTSIDE_BLOCK]); return this.cache; } }
the_stack
๏ปฟnamespace EntitySignal { enum EntityState { Detached = 0, Unchanged = 1, Deleted = 2, Modified = 3, Added = 4 }; interface DataContainer<T> { type: string; id: string; object: T; state: EntityState; } interface UserResult { connectionId: string; urls: UserUrlResult[]; } interface UserUrlResult { url: string; data: DataContainer<any>[]; } export enum EntitySignalStatus { Disconnected = 0, Connecting = 1, Connected = 2, WaitingForConnectionId = 3 } interface SyncPost { connectionId: string; } interface SyncSubscription { [key: string]: any[]; } interface PendingHardRefreshes { [key: string]: Promise<any>; } export interface EntitySignalOptions { autoreconnect: boolean; reconnectMinTime: number; reconnectVariance: number; debug: boolean; suppressInternalDataProcessing: boolean; hubUrl: string; maxWaitForConnectionId: number; returnDeepCopy: boolean; defaultId: string; defaultIdAlt: string; spliceModifications: boolean; } type OnStatusChangedCallback = (status: EntitySignalStatus) => void; type OnSyncCallback = (newData: UserResult) => void; type OnUrlDataChangeCallback = (urlData: any) => void; interface UrlCallbackContainer { [key: string]: OnUrlDataChangeCallback[]; } export class Client { subscriptions: SyncSubscription; pendingHardRefreshes: PendingHardRefreshes; hub: any; options: EntitySignalOptions; private connectingDefer: Promise<void>; connectionId: string; private onStatusChangeCallbacks: OnStatusChangedCallback[]; private onSyncCallbacks: OnSyncCallback[]; private onUrlCallbacks: UrlCallbackContainer; private _status: EntitySignalStatus; get status(): EntitySignalStatus { return this._status; } set status(newStatus: EntitySignalStatus) { this._status = newStatus; this.onStatusChangeCallbacks.forEach(callback => { callback(newStatus); }); } constructor(options?: EntitySignalOptions) { this.options = <EntitySignalOptions>{ autoreconnect: true, debug: false, suppressInternalDataProcessing: false, hubUrl: "/dataHub", reconnectMinTime: 4000, reconnectVariance: 3000, maxWaitForConnectionId: 5000, returnDeepCopy: false, defaultId: "id", defaultIdAlt: "Id", spliceModifications: false }; if (options) { Object.assign(this.options, options); } this.onStatusChangeCallbacks = []; this.onSyncCallbacks = []; this.onUrlCallbacks = <UrlCallbackContainer>{}; this.subscriptions = {}; this.pendingHardRefreshes = {}; this.status = EntitySignalStatus.Disconnected; this.hub = new window["signalR"].HubConnectionBuilder().withUrl(this.options.hubUrl, window["signalR"].HttpTransportType.WebSockets).build(); this.hub.onclose(() => { this.onClose(); }); this.hub.on("Sync", (data: UserResult) => { if (!this.options.suppressInternalDataProcessing) { this.processSync(data); } this.onSyncCallbacks.forEach(callback => { callback(data); }); data.urls.forEach(x => { var urlCallbacks = this.onUrlCallbacks[x.url]; if (!urlCallbacks) { return; } urlCallbacks.forEach(callback => { if (this.options.returnDeepCopy) { var deepCopy = JSON.parse(JSON.stringify(this.subscriptions[x.url])); callback(deepCopy); } else { callback(this.subscriptions[x.url]) } }) }) }); } onDataChange(url: string, callback: OnUrlDataChangeCallback) { var urlCallbackArray = this.onUrlCallbacks[url]; if (!urlCallbackArray) { this.onUrlCallbacks[url] = []; urlCallbackArray = this.onUrlCallbacks[url]; } urlCallbackArray.push(callback); return callback; } offDataChange(url: string, callback: OnUrlDataChangeCallback) { var urlCallbackArray = this.onUrlCallbacks[url]; if (!urlCallbackArray) { return; } var callbackIndex = urlCallbackArray.indexOf(callback); if (callbackIndex == -1) { return; } urlCallbackArray.splice(callbackIndex, 1); } onStatusChange(callback: OnStatusChangedCallback) { this.onStatusChangeCallbacks.push(callback); return callback; } offStatusChange(callback: OnStatusChangedCallback) { var callbackIndex = this.onStatusChangeCallbacks.indexOf(callback); if (callbackIndex == -1) { return; } this.onStatusChangeCallbacks.splice(callbackIndex, 1); } onSync(callback: OnSyncCallback) { this.onSyncCallbacks.push(callback); return callback; } offSync(callback: OnSyncCallback) { var callbackIndex = this.onSyncCallbacks.indexOf(callback); if (callbackIndex == -1) { return; } this.onSyncCallbacks.splice(callbackIndex, 1); } private onClose() { this.status = EntitySignalStatus.Disconnected; this.reconnect(); } debugPrint(output: string) { if (this.options.debug) { console.log(output); } } connect(): Promise<void> { if (this.status == EntitySignalStatus.Connected) { return Promise.resolve(); } if (this.status == EntitySignalStatus.Connecting || this.status == EntitySignalStatus.WaitingForConnectionId) { return this.connectingDefer; } this.debugPrint("Connecting"); if (this.status == EntitySignalStatus.Disconnected) { this.status = EntitySignalStatus.Connecting; this.connectingDefer = new Promise( (resolve, reject) => { this.hub.on("ConnectionIdChanged", (connectionId: string) => { //this should be a one shot so just remove handler after first use this.hub.off("ConnectionIdChanged"); this.status = EntitySignalStatus.Connected; this.connectionId = connectionId; this.debugPrint("Connected"); resolve(); }); this.hub.start().then( x => { if (this.status == EntitySignalStatus.Connecting) { this.debugPrint("Connected, waiting for connectionId"); this.status = EntitySignalStatus.WaitingForConnectionId; } setTimeout(() => { if (this.status == EntitySignalStatus.WaitingForConnectionId) { reject() } }, this.options.maxWaitForConnectionId); } ).catch( err => { this.debugPrint("Error Connecting"); this.status = EntitySignal.EntitySignalStatus.Disconnected; reject(err); console.error(err.toString()); } ); } ); return this.connectingDefer; } } reconnect() { if (this.options.autoreconnect == false) { return; } this.debugPrint("Reconnecting"); this.connect().then( () => { this.debugPrint("Reconnect Success"); for (var index in this.subscriptions) { this.hardRefresh(index); } }, x => { this.debugPrint("Reconnect Failed"); var reconnectTime = this.options.reconnectMinTime + (Math.random() * this.options.reconnectVariance); this.debugPrint("Attempting reconnect in " + reconnectTime + "ms"); setTimeout(() => { this.reconnect(); }, reconnectTime); } ); } processSync(data: UserResult) { var changedUrls: string[] = []; data.urls.forEach(url => { changedUrls.push(url.url); url.data.forEach(x => { if (x.state == EntityState.Added || x.state == EntityState.Modified) { var changeCount = 0; //check if already in list this.subscriptions[url.url].forEach((msg, index) => { if (this.idsMatch(x.object, msg)) { if (this.options.spliceModifications) { this.subscriptions[url.url].splice(index, 1, x.object); } else { this.updateObjectWhilePersistingReference(this.subscriptions[url.url][index], x.object); changeCount++; } changeCount++; } }) //if not in the list then add to end of list if (changeCount == 0) { this.subscriptions[url.url].push(x.object); } } else if (x.state == EntityState.Deleted) { for (var i = this.subscriptions[url.url].length - 1; i >= 0; i--) { var currentRow = this.subscriptions[url.url][i]; //check default ID type if (this.idsMatch(x.object, currentRow)) { this.clearArrayItem(this.subscriptions[url.url], i); } } } }) }); return changedUrls; } idsMatch(object1: any, object2: any): boolean { var obj1Id = this.getId(object1); var obj2Id = this.getId(object2); if (obj1Id && obj2Id && obj1Id == obj2Id) { return true; } return false; } getId(obj: any): number { if (obj[this.options.defaultId]) { return obj[this.options.defaultId]; } if (obj[this.options.defaultIdAlt]) { return obj[this.options.defaultIdAlt]; } return null; } updateArrayWhilePersistingObjectReferences(target: any[], source: any[], ) { var targetArrayItemsToRemove: number[] = []; //to make this efficient we need to index the source array //create data structure of indexedSource["idValue"] = arrayIndexValue var indexedSource = {}; source.forEach((sourceValue, index) => { var sourceId = this.getId(sourceValue); if (sourceId) { indexedSource[sourceId] = index; } }) //now that we can do a O(1) lookup we can quickly merge the source into the target target.forEach((targetValue, index) => { var targetId = this.getId(targetValue); var matchingSourceIndex = indexedSource[targetId]; var matchingSourceValue = source[matchingSourceIndex]; //if found then update the reference if (indexedSource[targetId]) { this.updateObjectWhilePersistingReference(targetValue, matchingSourceValue) } else { //if not found mark for deletion targetArrayItemsToRemove.push(index) } }); //go through the items to remove list in reverse and remove them targetArrayItemsToRemove.slice().reverse().forEach(indexToRemove => { this.clearArrayItem(target, indexToRemove); }); } updateObjectWhilePersistingReference(target: any, source: any) { this.clearObject(target); //copy back (to keep the same object reference) Object.assign(target, source); } clearObject(obj: any) { //clear object var objectReference = obj; for (var variableKey in objectReference) { if (variableKey.startsWith("$$")) { continue; } if (objectReference.hasOwnProperty(variableKey)) { delete objectReference[variableKey]; } } } clearArrayItem(array: any[], i: number) { this.clearObject(array[i]) array.splice(i, 1); } desyncFrom(url: string): Promise<void> { var newDefer = new Promise<void>((resolve, reject) => { this.hub.invoke("DeSyncFrom", url) .then( x => { resolve(); }, x => { reject(x); } ); }); return newDefer; } hardRefresh(url: string) { if (this.pendingHardRefreshes[url]) { return this.pendingHardRefreshes[url]; } var hardRefreshPromise = new Promise((resolve, reject) => { this.connect().then(() => { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('x-signalr-connection-id', this.connectionId); xhr.onreadystatechange = () => { if (xhr.readyState == 4) { this.pendingHardRefreshes[url] = null; if (xhr.status == 200) { var data = JSON.parse(xhr.responseText); //update the subscription if (this.subscriptions[url] == null) { this.subscriptions[url] = data; } else { //if return deep dopy then just splice and swap the list if (this.options.returnDeepCopy) { this.subscriptions[url].splice(0); data.forEach(y => { this.subscriptions[url].push(y); }); } else { //if not return deep copy then we must keep the object references this.updateArrayWhilePersistingObjectReferences(data, this.subscriptions[url]); } } //resolve the promise if (this.options.returnDeepCopy) { var deepCopy = JSON.parse(JSON.stringify(this.subscriptions[url])); resolve(deepCopy); } else { resolve(this.subscriptions[url]); } } else if (xhr.status == 204) { if (this.subscriptions[url] == null) { this.subscriptions[url] = data; } resolve(this.subscriptions[url]); } else { reject(xhr); } } } xhr.send(); }); }); this.pendingHardRefreshes[url] = hardRefreshPromise; return hardRefreshPromise; } syncWith(url: string): Promise<any> { //if already subscribed to then return array if (this.subscriptions[url]) { return Promise.resolve(this.subscriptions[url]) } return this.hardRefresh(url); }; } }
the_stack
import webpack from 'webpack'; import WebpackBuildNotifierPlugin from '../src/index'; import getWebpackConfig from './webpack.config'; import notifier from 'node-notifier'; import child_process from 'child_process'; import os from 'os'; import { CompilationStatus } from '../src/types'; // TODO: test for registerSnoreToast describe('Test Webpack build', () => { const platform = process.platform; const arch = process.arch; afterAll(() => { if (platform !== process.platform) { Object.defineProperty(process, 'platform', { value: platform }); Object.defineProperty(process, 'arch', { value: arch }); } }); it('sets the onClick listener', () => { const onClick = jest.fn(); new WebpackBuildNotifierPlugin({ onClick, }); expect(notifier.on).toHaveBeenCalledWith('click', onClick); }); it('sets the onTimeout listener', () => { const onTimeout = jest.fn(); new WebpackBuildNotifierPlugin({ onTimeout, }); expect(notifier.on).toHaveBeenCalledWith('timeout', onTimeout); }); describe.each([['Windows', 'win32'], ['Mac OS', 'darwin']])( 'Platform: %s', (platformName: string, platform: string) => { beforeAll(() => { Object.defineProperty(process, 'platform', { value: platform }); Object.defineProperty(process, 'arch', { value: 'x64' }); jest.spyOn(child_process, 'execFileSync').mockImplementation(jest.fn()); jest.spyOn(os, 'release').mockImplementation(() => '10.0.18362'); }); it('Should not show an initial success notification when suppressSuccess is "initial"', (done) => { expect.assertions(1); webpack(getWebpackConfig({ suppressSuccess: 'initial' }), (err, stats) => { expect(notifier.notify).not.toHaveBeenCalled(); done(); }); }); it('Should activate terminal on error (Mac OS only)', (done) => { const exec = jest.spyOn(child_process, 'exec').mockImplementation(jest.fn()); expect.assertions(1); webpack(getWebpackConfig({ activateTerminalOnError: true }, 'error'), (err, stats) => { if (platformName === 'Windows') { expect(exec).not.toHaveBeenCalled(); } else { expect(exec).toHaveBeenCalled(); } done(); }); }); it('Should show a compiling notification when watching', (done) => { let buildCount = 0; const onCompileStart = jest.fn(); expect.assertions(2); const watcher = webpack(getWebpackConfig({ onCompileStart }, 'success', true), (err, stats) => { buildCount++; if (buildCount === 1) { (notifier.notify as jest.Mock).mockClear(); (watcher as webpack.Compiler.Watching).invalidate(); } else if (buildCount === 2) { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/compile.png'), message: 'Compilation started...', sound: 'Submarine', title: 'Build Notification Test', }); expect(onCompileStart).toHaveBeenCalled(); (watcher as webpack.Compiler.Watching).close(() => { }); done(); } }); }); it('Should show a success notification', (done) => { const onComplete = jest.fn(); expect.assertions(2); webpack(getWebpackConfig({ onComplete }), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Build successful!', sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); expect(onComplete).toHaveBeenCalledWith(expect.any(Object), CompilationStatus.SUCCESS); done(); }); }); it('Should show a success notification with no sound', (done) => { const onComplete = jest.fn(); expect.assertions(2); webpack(getWebpackConfig({ onComplete, sound: false }), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Build successful!', title: 'Build Notification Test - Success', wait: false, }); expect(onComplete).toHaveBeenCalledWith(expect.any(Object), CompilationStatus.SUCCESS); done(); }); }); it('Should show a success notification with duration', (done) => { expect.assertions(1); webpack(getWebpackConfig({ showDuration: true }), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: expect.stringMatching(/^Build successful! \[\d+ ms\]$/), sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); done(); }); }); it('Should show an error notification', (done) => { const onComplete = jest.fn(); expect.assertions(2); webpack(getWebpackConfig({ onComplete }, 'error'), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/failure.png'), message: expect.stringContaining('Module parse failed: Duplicate export \'default\''), sound: 'Submarine', title: 'Build Notification Test - Error', wait: true, }); expect(onComplete).toHaveBeenCalledWith(expect.any(Object), CompilationStatus.ERROR); done(); }); }); it('Should show a warning notification', (done) => { const onComplete = jest.fn(); expect.assertions(2); webpack(getWebpackConfig({ onComplete }, 'warning'), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/warning.png'), message: expect.stringContaining('entrypoint size limit'), sound: 'Submarine', title: 'Build Notification Test - Warning', wait: true, }); expect(onComplete).toHaveBeenCalledWith(expect.any(Object), CompilationStatus.WARNING); done(); }); }); it('Should show a success notification with a custom message', (done) => { const formatSuccess = jest.fn(() => 'Very nice! Great success!'); expect.assertions(2); webpack(getWebpackConfig({ formatSuccess }, 'success'), (err, stats) => { expect(formatSuccess).toHaveBeenCalled(); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Very nice! Great success!', sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); done(); }); }); it('Should show default success notification message when formatSuccess returns undefined', (done) => { const formatSuccess = jest.fn(() => undefined); expect.assertions(2); webpack(getWebpackConfig({ formatSuccess }, 'success'), (err, stats) => { expect(formatSuccess).toHaveBeenCalled(); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Build successful!', sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); done(); }); }); it('Should show an error notification with a custom message', (done) => { const messageFormatter = jest.fn().mockImplementation(() => 'Hello, you have an error!'); expect.assertions(2); webpack(getWebpackConfig({ messageFormatter }, 'error'), (err, stats) => { expect(messageFormatter).toHaveBeenCalledWith(expect.any(Object), require.resolve('./error.js'), 'error', 1); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/failure.png'), message: 'Hello, you have an error!', sound: 'Submarine', title: 'Build Notification Test - Error', wait: true, }); done(); }); }); it('Should show a warning notification with a custom message', (done) => { const messageFormatter = jest.fn().mockImplementation(() => 'Hello, you have a warning!'); expect.assertions(2); webpack(getWebpackConfig({ messageFormatter }, 'warning'), (err, stats) => { expect(messageFormatter).toHaveBeenCalledWith(expect.any(Object), '', 'warning', 2); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/warning.png'), message: 'Hello, you have a warning!', sound: 'Submarine', title: 'Build Notification Test - Warning', wait: true, }); done(); }); }); it('Should show "Unknown" if message is not defined', (done) => { const messageFormatter = jest.fn().mockImplementation(() => undefined); expect.assertions(1); webpack(getWebpackConfig({ messageFormatter }, 'error'), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/failure.png'), message: 'Unknown', sound: 'Submarine', title: 'Build Notification Test - Error', wait: true, }); done(); }); }); it('Should throw if messageFormatter returns invalid type', (done) => { const messageFormatter = jest.fn().mockImplementation(() => 99); expect.assertions(1); webpack(getWebpackConfig({ messageFormatter }, 'error'), (err, stats) => { expect(err).toContain('Invalid message type'); done(); }); }); it('Should handle warning from child compiler', (done) => { const onComplete = jest.fn(); expect.assertions(2); webpack(getWebpackConfig({ onComplete }, 'childWarning'), (err, stats) => { expect(onComplete).toHaveBeenCalledWith(expect.any(Object), CompilationStatus.WARNING); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/warning.png'), message: expect.stringContaining('Second Autoprefixer control comment was ignored'), sound: 'Submarine', title: 'Build Notification Test - Warning', wait: true, }); done(); }); }); it('Should pass extra notifyOptions to node-notifier', (done) => { expect.assertions(1); webpack(getWebpackConfig({ notifyOptions: { open: 'https://example.com' } }), (err, stats) => { expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Build successful!', open: 'https://example.com', sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); done(); }); }); it('Should execute the notifyOptions callback on success', (done) => { // Override notifyOptions on successful compilation only const notifyOptions = jest.fn( (status: CompilationStatus) => status === CompilationStatus.SUCCESS ? { open: 'https://example.com' } : undefined ); expect.assertions(2); webpack(getWebpackConfig({ notifyOptions }), (err, stats) => { expect(notifyOptions).toHaveBeenCalledWith(CompilationStatus.SUCCESS); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/success.png'), message: 'Build successful!', open: 'https://example.com', sound: 'Submarine', title: 'Build Notification Test - Success', wait: false, }); done(); }); }); it('Should execute the notifyOptions callback on error', (done) => { // Override notifyOptions on successful compilation only const notifyOptions = jest.fn( (status: CompilationStatus) => status === CompilationStatus.SUCCESS ? { open: 'https://www.example.com' } : undefined ); expect.assertions(2); webpack(getWebpackConfig({ notifyOptions }, 'error'), (err, stats) => { expect(notifyOptions).toHaveBeenCalledWith(CompilationStatus.ERROR); expect(notifier.notify).toHaveBeenCalledWith({ appName: platformName === 'Windows' ? 'Snore.DesktopToasts' : undefined, contentImage: undefined, icon: require.resolve('../src/icons/failure.png'), message: expect.stringContaining('Module parse failed: Duplicate export \'default\''), // `open` should not be set sound: 'Submarine', title: 'Build Notification Test - Error', wait: true, }); done(); }); }); }); });
the_stack
enum Status { OK, Pending, Stale, } /** * Type for the closure's value equality predicate. * * @typeParam T - Type of the values being compared for * equality. * * @remarks * Conceptually this function should be equivalent * to: `lhs === rhs` * * @param lhs - left hand side value * @param rhs - right hand side value * @returns - `true` if values are considered * equal; `false` otherwise. */ type EqualFn<T> = (lhs: T, rhs: T) => boolean type GetterFn<T> = () => T type SetterFn<T> = (value: T) => T type UnsubscribeFn = () => void type UpdateFn<T> = (value?: T) => T type InputPair<T> = [GetterFn<T>, SetterFn<T>] type Options = { name: string } type ObserverR = { name?: string pure: boolean status: Status subjects: Set<SubjectR> } type ObserverV<T> = { value?: T updateFn: UpdateFn<T> } type Observer<T> = ObserverR & ObserverV<T> type SubjectR = { name?: string observers: Set<ObserverR> } type SubjectV<T> = { value?: T equalFn?: EqualFn<T> } type Subject<T> = SubjectR & SubjectV<T> type ComputedR = ObserverR & SubjectR type Computed<T> = ComputedR & ObserverV<T> & SubjectV<T> function isObserverRComputedR(observer: ObserverR): observer is ComputedR { const computed = observer as ComputedR return computed.observers !== undefined } function isSubjectComputed<T>(subject: Subject<T>): subject is Computed<T> { const computed = subject as Computed<T> return computed.subjects !== undefined } function isObserverComputed<T>(observer: Observer<T>): observer is Computed<T> { const computed = observer as Computed<T> return computed.observers !== undefined } const defaultEqual = <T>(lhs: T, rhs: T): boolean => lhs === rhs function selectEqualFn<T>( equal: boolean | EqualFn<T> | undefined ): EqualFn<T> | undefined { if (typeof equal === 'function') return equal if (equal === true) return defaultEqual return undefined } // module context values let activeObserver: ObserverR let updateQueue: ObserverR[] | undefined let callbackQueue: ObserverR[] | undefined function link(subject: SubjectR, observer: ObserverR): void { observer.subjects.add(subject) subject.observers.add(observer) } function unsubscribe(observer: ObserverR): void { observer.subjects.forEach((sub) => { sub.observers.delete(observer) }) } function makeUnsubscribe(observer: ObserverR | undefined): UnsubscribeFn { return (): void => { if (!observer) return const o = observer observer = undefined unsubscribe(o) } } function prepareForUpdate(observer: ObserverR): void { if (isObserverRComputedR(observer) && observer.status !== Status.Pending) { markDeepObservers(observer) } observer.status = Status.Stale if (observer.pure) updateQueue!.push(observer) else callbackQueue!.push(observer) } function markDeep(observer: ObserverR): void { if (observer.status === Status.OK) { observer.status = Status.Pending if (isObserverRComputedR(observer)) markDeepObservers(observer) } } function markDeepObservers(subject: SubjectR): void { subject.observers.forEach(markDeep) } function runUpdates(prepareUpdates: () => void): void { if (updateQueue) return prepareUpdates() const updates: ObserverR[] = [] updateQueue = updates const [callbacks, delayCallbacks] = callbackQueue ? [callbackQueue, true] : [[], false] callbackQueue = callbacks prepareUpdates() updateQueued(updates) updateQueue = undefined if (delayCallbacks) return updateQueued(callbacks) callbackQueue = undefined } function updateQueued(queued: ObserverR[]): void { for (let i = 0; i < queued.length; i++) { updateViaStatus(queued[i] as Observer<unknown>, true) } } function updateViaStatus<T>( observer: Observer<T>, saveQueue: boolean = false ): void { switch (observer.status) { case Status.Pending: { if (saveQueue !== true) { updateDeepStaleSubjects(observer) } else { const prevUpdate = updateQueue updateQueue = undefined updateDeepStaleSubjects(observer) updateQueue = prevUpdate } break } case Status.Stale: updateObserver(observer) break } } function updateDeep<T>(subject: Subject<T>): void { if (isSubjectComputed(subject)) updateViaStatus(subject) } function updateDeepStaleSubjects<T>(observer: Observer<T>): void { observer.subjects.forEach(updateDeep) } function updateObserver<T>(observer: Observer<T>): void { unsubscribe(observer) const prevObserver = activeObserver activeObserver = observer observer.status = Status.OK const nextValue = observer.updateFn(observer.value) if (isObserverComputed(observer)) writeSubject(observer, nextValue) else observer.value = nextValue activeObserver = prevObserver } function readSubject<T>(subject: Subject<T>): T { if (isSubjectComputed(subject) && subject.status !== Status.OK) { const updates = updateQueue updateQueue = undefined updateViaStatus(subject) updateQueue = updates } if (activeObserver) link(subject, activeObserver) return subject.value! } function writeSubject<T>(subject: Subject<T>, value: T): T { if (subject.equalFn && subject.value && subject.equalFn(subject.value, value)) return value subject.value = value if (subject.observers.size) { runUpdates(() => subject.observers.forEach(prepareForUpdate)) } return subject.value } /** * Creates an input closure. The value is accessed * via the accessor and changed via the * mutator returned as part an `InputPair<T>`. * * @typeParam T - Type of the closure's value. * By extension the type of the return * value of the accessor and the type * of the mutator's single argument. * * @param value - Input closure's initial value. * @param equal - By default the current and previous * values are not compared so invoking * the mutator with identical values * will trigger updates on any * subscribers. When `true` is * specified the * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality | strict equality operator} * is used to compare values and * mutations with unchanging values * **are** suppressed. * When `T` is a structural type * it is necessary to provide a * `(a: T, b: T) => boolean` comparison * predicate instead. * @param options - Holder object for relevant options. * Assigning a `name` to a subject can * be useful during debugging. * @returns - An `InputPair<T>`. The 1st * element is the accessor (getter * function), the 2nd element is * the mutator (setter function). */ function createInput<T>( value: T, equal?: boolean | EqualFn<T>, options?: { name?: string } ): InputPair<T> { const subject: Subject<T> = { name: options?.name, observers: new Set<ObserverR>(), value, equalFn: selectEqualFn(equal), } return [ (): T => readSubject(subject), (next: T): T => writeSubject(subject, next), ] } /** * Creates a computed (derived) closure with the * supplied function which computes the current value * of the closure. * * @typeParam T - Type of the closure's value. * By extension the type of the value * returned by the update function and * of the value * accepted by the function. * * @param updateFn - Update function. This function * references one or more accessors of * other subjects. It **should not** * perform side effects. It is expected * to return a value which will be the * value of the closure until the next * update. The closure's value is * supplied to this update function * on the next update. * @param value - Initial value that is passed to * `updateFn` when it executes for the * first time. * @param equal - By default the current and previous * values are not compared so updates * will be triggered even if the value * doesn't _change_. When `true` is * specified the * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality | strict equality operator} * is used to compare values and updates * with identical values **are** * suppressed. When `T` is a structural * type it is necessary to provide a * `(a: T, b: T) => boolean` comparison * predicate instead. * @param options - Holder object for relevant options. * Assigning a `name` to a subject can * be useful during debugging. * @returns - The accessor to the closure's * value (getter function). Retrieves * the closure's current value. Used by * observers (or more accurately their * update function) to obtain the * value (and to subscribe for * updates). */ function createComputed<T>( updateFn: UpdateFn<T>, value?: T, equal?: boolean | EqualFn<T>, options?: { name?: string } ): GetterFn<T> { const computed: Computed<T> = { name: options?.name, observers: new Set<ObserverR>(), value, equalFn: selectEqualFn(equal), updateFn, status: Status.Stale, pure: true, subjects: new Set<SubjectR>(), } updateObserver(computed) return (): T => readSubject(computed) } /** * Creates a callback closure with the supplied * function which is expected to perform side effects. * * @typeParam T - Type of the closure's value. * By extension the type of the value * returned by the callback function * and of the value accepted by the * function. * * @param updateFn - Callback function. This function * references one or more accessors of * subjects. It may perform side effects. * It will also be passed the * value that it returned the last time it * was invoked. * @param value - Initial value that is passed to * `updateFn` when it executes for * the first time. * @returns - The `unsubscribe` function. Once * invoked the callback closure will * stop receiving updates from the * subjects it subscribed to. */ function createCallback<T>(updateFn: UpdateFn<T>, value?: T): UnsubscribeFn { const o: Observer<T> = { value, updateFn, status: Status.Stale, pure: false, subjects: new Set<SubjectR>(), } if (callbackQueue) callbackQueue.push(o) else updateObserver(o) return makeUnsubscribe(o) } export { createInput, createComputed, createCallback } // ------------------------------------------------------- // // A `Subject<T>` provides its output value **to** // its dependents (`Observer<T>`s). // // An `Observer<T>` gets its input values **from** // its dependencies (`Subject<T>`s). // // A `Computed<T>` merges the _aspects_ of // both `Observer<T>` and `Subject<T>`. // Of the three types `Computed<T>` is the most _general_. // So while `Computed<T>` is composed of both // `Subject<T>` and `Observer<T>`, both // `Subject<T>`, `Observer<T>` could be viewed as // _constrained_ versions of `Computed<T>` (as // opposed to _specialized_ versions). // // Each type is further split into its _value_ aspect // (e.g. `ObserverV<T>`) and _relation_ (or _rest_) // aspect (e.g. `ObserverR`). This tactic helps to // avoid using generic type references with an // explicit _any_ type parameter in the update // routing logic which has no actual dependency // on the type `T` being managed by the // `Subject<T>`/ `Observer<T>`/`Computed<T>` // instance. // // The existence of the value aspect is only // acknowledged in `updateQueued()` where the // `ObserverR` type is asserted to be an // `Observer<unknown>` which from this point on is // then handled by generic functions. // // So `createInput<T>()` internally creates a // `Subject<T>`, `createCallback<T>()` an `Observer<T>`, and // `createComputed<T>()` a `Computed<T>`. // // `createInput<T>()` returns two functions in an // `InputCouple<T>` tuple, a `GetterFn<T>` accessor // and a `SetterFn<T>` mutator. The mutator triggers // the update of all the `Subject<T>`'s dependents // while the accessor returns the `Subject<T>`'s // current value. // // The accessor also has the hidden responsibility // of subscribing the `Observer<T>` that is accessing // the `Subject<T>`. The `Observer<T>` shares its // reference via the module's `activeObserver` context // value. The `Subject<T>` stores that dependency in // its `observers` property. // // `createComputed<T>()` only returns a `GetterFn<T>` // accessor to obtain the internal `Computed<T>`'s // current value. The primary argument to // `createComputed<T>()` is `fn: UpdateFn<T>` - the // function responsible for deriving the // `Computed<T>`'s value from its dependencies // (and the `Computed<T>`'s own previous value). This // function is invoked whenever at least one of the // `Computed<T>`'s dependencies has an updated value. // The function is run before `createComputed<T>()` // exits via `updateObserver<T>()` so that // * the `Computed<T>` can calculate its current value // * the `Computed<T>` subscribes to all its // relevant dependencies. // // To that end `updateObserver<T>()` sets the // module's `activeObserver` context value before // invoking `fn: UpdateFn<T>` so that all the // `Subject<T>`'s being accessed can register the // subscription of the `Observer<T>` (or `Computed<T>`). // // (Note that `updateObserver<T>()` unsubscribes the // `Observer<T>` (or `Computed<T>`) first - this is // essential later so that the `Observer<T>` isn't // updated for irrelevant dependencies - e.g. an // input accessor that is guarded by an `if` condition // that currently evaluates to `false`.) // // `createCallback<T>()` returns an `UnsubscribeFn` // function that deactivates the callback when invoked. // There is no `GetterFn<T>` because the callbacks // act by _side effect_ - i.e. changing values that // exist in their enclosing scope (closure: // https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md // ). Internally a callback is based on a `Observer<T>`. // The primary argument to // `createCallback<T>()` is `fn: UpdateFn<T>` - the // function is responsible for accessing the `Subject<T>` // dependencies (and thereby subscribing to them) // and implementing the side effect(s). This // function is called whenever at least one of the // `Observer<T>`'s dependencies has an updated value. // `updateObserver<T>()` is only invoked if currently no // update is in progress - otherwise the callback is // queued for later invocation. // // All three `create*` functions take a `value: T` // argument - required for `createInput<T>()`, // optional for the others. For `createInput<T>()` // this is the initial value - for the others it is the // argument that is passed to the `fn: UpdateFn<T>` // the first time it executes. // // `createInput<T>()` and `createComputed<T>()` have // an (optional) ` equal?: boolean | EqualFn<T>` // argument. Given the generic implementation of the // capabilities, by default `Subject<T>`s don't // limit updates to occasions when their `value` // _changes_ - as there is no standardized way // to check for equality of `T` in TypeScript // (compared to for example Rust): // https://doc.rust-lang.org/std/cmp/trait.PartialEq.html // https://doc.rust-lang.org/std/cmp/trait.Eq.html // // A value of `true` directs the use of the default // equality function `defaultEqual` which will work // for primitive types and references. Otherwise a // custom equality predicate must be provided // if updates for identical values of `T` are to // be suppressed. // // `createCallback<T>` doesn't have this argument. // Therefore it is necessary to configure the // `Subject<T>`s it depends on to suppress updates // on identical values. // // `createInput<T>()` and `createComputed<T>()` have // an optional `Options` value that may carry a // `name` property. This can come in handy for // debugging. // // The core capability is driven by the // `writeSubject<T>` function which is invoked whenever // an input is set with its `SetterFn<T>` or a // `Computed<T>` has its `value` set by a dependency. // The update of dependents is suppressed for identical // values provided the `Subject<T>` is configured // accordingly. Otherwise all the observers are // prepared for update before the actual updates are // made. // // `prepareForUpdate()` first marks the dependents of a // `Computed<T>` as `Status.Pending` _in depth_. The // observer itself is marked as `Status.Stale` before // being pushed onto `updateQueue` or `callbackQueue`. // // * `Status.Pending` - an `Observer<T>` has this // status when one of its dependencies _descendents_ // is marked as `Status.Stale`. It acts as a // pre-`Status.Stale` status. The `Observer<T>` // instance is "out-of-sync" but not yet ready // for update (so it isn't on `updateQueue`). // * `Status.Stale` - an `Observer<T>` enters this // state when at least one of its direct // dependencies has been updated. The `Observer<T>` // instance is on `updateQueue`. // // `runUpdates` coordinates the current update wave. // The passed `prepareUpdate` function is invoked if an // update wave is already underway. Otherwise an empty // `updateQueue` is set up. If callbacks are already // being queued this particular `runUpdates` invocation // won't be processing callbacks // (`delayCallbacks = true`) - otherwise an empty // `callbackQueue` is set up. // // Finally the passed `prepareUpdates` function is // invoked causing "computeds" to be queued up on // `updateQueue` and "callbacks" to be queued up on // `callbackQueue`. The `updateQueue` is processed // with the `updateQueued()` function. // // Callbacks are only processed if this is the // top-level invocation of `runUpdates()` - this // ensures that callbacks are updated as late as // possible to avoid unnecessary, multiple // updates. // // Updates routed through `updateViaStatus` by // `updateQueued` start a nested (deep) update wave // for an `Observer<T>` in the `Status.Pending` // status - i.e. there are dependencies in need of // update before the `Observer<T>` can perform // a meaningful update of itself. `Observer<T>`'s // in the `Status.Stale` status can immediately update // themselves via their `fn: UpdateFn<T>`. // // `readSubject<T>()` will issue a nested update wave // if it discovers that its `Subject<T>` is currently // **not** in `Status.OK` status as it needs those // updates to complete before an up-to-date `value` // can be returned. // // References: // // Enums // https://www.typescriptlang.org/docs/handbook/enums.html // // Type Aliases // https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases // // Function Types // https://www.typescriptlang.org/docs/handbook/functions.html#function-types // // Generics // https://www.typescriptlang.org/docs/handbook/generics.html // // Optional and Default Types // https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters // // Tuple // https://www.typescriptlang.org/docs/handbook/basic-types.html#tuple // // Optional Properties // https://www.typescriptlang.org/docs/handbook/interfaces.html#optional-properties // // Set // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set // // Intersection Types // https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types // // User-Defined Type Guards // https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards // // Type Assertions // https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions // // Union Types // https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types // // typeof // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof // // Unknown // https://www.typescriptlang.org/docs/handbook/basic-types.html#unknown // // Non-null assertion operator // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator // // Optional chaining (?.) // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining // // -------------------------------------------------------
the_stack
import { Inject, Injectable } from '@nestjs/common'; import { NETDISK_COPY_SUFFIX, NETDISK_DELIMITER, NETDISK_HANDLE_MAX_ITEM, NETDISK_LIMIT, QINIU_CONFIG, } from '../../admin.constants'; import { IQiniuConfig } from '../../admin.interface'; import * as qiniu from 'qiniu'; import { rs, conf, auth } from 'qiniu'; import { UtilService } from 'src/shared/services/util.service'; import { isEmpty } from 'lodash'; import { SFileInfo, SFileInfoDetail, SFileList } from './manage.class'; import { SysUserService } from '../../system/user/user.service'; import { AccountInfo } from '../../system/user/user.class'; import { extname, basename } from 'path'; import { FileOpItem } from './manage.dto'; @Injectable() export class NetDiskManageService { private config: conf.ConfigOptions; private mac: auth.digest.Mac; private bucketManager: rs.BucketManager; constructor( @Inject(QINIU_CONFIG) private qiniuConfig: IQiniuConfig, private userService: SysUserService, private util: UtilService, ) { this.mac = new qiniu.auth.digest.Mac( this.qiniuConfig.accessKey, this.qiniuConfig.secretKey, ); this.config = new qiniu.conf.Config({ zone: this.qiniuConfig.zone, }); // bucket manager this.bucketManager = new qiniu.rs.BucketManager(this.mac, this.config); } /** * ่Žทๅ–ๆ–‡ไปถๅˆ—่กจ * @param prefix ๅฝ“ๅ‰ๆ–‡ไปถๅคน่ทฏๅพ„๏ผŒๆœ็ดขๆจกๅผไธ‹ไผš่ขซๅฟฝ็•ฅ * @param marker ไธ‹ไธ€้กตๆ ‡่ฏ† * @returns iFileListResult */ async getFileList(prefix = '', marker = '', skey = ''): Promise<SFileList> { // ๆ˜ฏๅฆ้œ€่ฆๆœ็ดข const searching = !isEmpty(skey); return new Promise<SFileList>((resolve, reject) => { this.bucketManager.listPrefix( this.qiniuConfig.bucket, { prefix: searching ? '' : prefix, limit: NETDISK_LIMIT, delimiter: searching ? '' : NETDISK_DELIMITER, marker, }, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { // ๅฆ‚ๆžœ่ฟ™ไธชnextMarkerไธไธบ็ฉบ๏ผŒ้‚ฃไนˆ่ฟ˜ๆœ‰ๆœชๅˆ—ไธพๅฎŒๆฏ•็š„ๆ–‡ไปถๅˆ—่กจ๏ผŒไธ‹ๆฌก่ฐƒ็”จlistPrefix็š„ๆ—ถๅ€™๏ผŒ // ๆŒ‡ๅฎšoptions้‡Œ้ข็š„markerไธบ่ฟ™ไธชๅ€ผ const fileList: SFileInfo[] = []; // ๅค„็†็›ฎๅฝ•๏ผŒไฝ†ๅชๆœ‰้žๆœ็ดขๆจกๅผไธ‹ๅฏ็”จ if (!searching && !isEmpty(respBody.commonPrefixes)) { // dir for (const dirPath of respBody.commonPrefixes) { const name = (dirPath as string) .substr(0, dirPath.length - 1) .replace(prefix, ''); if (isEmpty(skey) || name.includes(skey)) { fileList.push({ name: (dirPath as string) .substr(0, dirPath.length - 1) .replace(prefix, ''), type: 'dir', id: this.util.generateRandomValue(10), }); } } } // handle items if (!isEmpty(respBody.items)) { // file for (const item of respBody.items) { // ๆœ็ดขๆจกๅผไธ‹ๅค„็† if (searching) { const pathList: string[] = item.key.split(NETDISK_DELIMITER); // dir is empty stirng, file is key string const name = pathList.pop(); if ( item.key.endsWith(NETDISK_DELIMITER) && pathList[pathList.length - 1].includes(skey) ) { // ็ป“ๆžœๆ˜ฏ็›ฎๅฝ• const ditName = pathList.pop(); fileList.push({ id: this.util.generateRandomValue(10), name: ditName, type: 'dir', belongTo: pathList.join(NETDISK_DELIMITER), }); } else if (name.includes(skey)) { // ๆ–‡ไปถ fileList.push({ id: this.util.generateRandomValue(10), name, type: 'file', fsize: item.fsize, mimeType: item.mimeType, putTime: new Date(parseInt(item.putTime) / 10000), belongTo: pathList.join(NETDISK_DELIMITER), }); } } else { // ๆญฃๅธธ่Žทๅ–ๅˆ—่กจ const fileKey = item.key.replace(prefix, '') as string; if (!isEmpty(fileKey)) { fileList.push({ id: this.util.generateRandomValue(10), name: fileKey, type: 'file', fsize: item.fsize, mimeType: item.mimeType, putTime: new Date(parseInt(item.putTime) / 10000), }); } } } } resolve({ list: fileList, marker: respBody.marker || null, }); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ่Žทๅ–ๆ–‡ไปถไฟกๆฏ */ async getFileInfo(name: string, path: string): Promise<SFileInfoDetail> { return new Promise((resolve, reject) => { this.bucketManager.stat( this.qiniuConfig.bucket, `${path}${name}`, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode == 200) { const detailInfo: SFileInfoDetail = { fsize: respBody.fsize, hash: respBody.hash, md5: respBody.md5, mimeType: respBody.mimeType.split('/x-qn-meta')[0], putTime: new Date(parseInt(respBody.putTime) / 10000), type: respBody.type, uploader: '', mark: respBody?.['x-qn-meta']?.['!mark'] ?? '', }; if (!respBody.endUser) { resolve(detailInfo); } else { this.userService .getAccountInfo(parseInt(respBody.endUser)) .then((user: AccountInfo) => { if (isEmpty(user)) { resolve(detailInfo); } else { detailInfo.uploader = user.name; resolve(detailInfo); } }); } } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ไฟฎๆ”นๆ–‡ไปถMimeType */ async changeFileHeaders( name: string, path: string, headers: { [k: string]: string }, ): Promise<void> { return new Promise((resolve, reject) => { this.bucketManager.changeHeaders( this.qiniuConfig.bucket, `${path}${name}`, headers, (err, _, respInfo) => { if (err) { reject(); return; } if (respInfo.statusCode == 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ๅˆ›ๅปบๆ–‡ไปถๅคน * @returns trueๅˆ›ๅปบๆˆๅŠŸ */ async createDir(dirName: string): Promise<void> { const safeDirName = dirName.endsWith('/') ? dirName : `${dirName}/`; return new Promise((resolve, reject) => { // ไธŠไผ ไธ€ไธช็ฉบๆ–‡ไปถไปฅ็”จไบŽๆ˜พ็คบๆ–‡ไปถๅคนๆ•ˆๆžœ const formUploader = new qiniu.form_up.FormUploader(this.config); const putExtra = new qiniu.form_up.PutExtra(); formUploader.put( this.createUploadToken(''), safeDirName, ' ', putExtra, (respErr, respBody, respInfo) => { if (respErr) { reject(respErr); return; } if (respInfo.statusCode === 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ๆฃ€ๆŸฅๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒๅŒๅฏๆฃ€ๆŸฅ็›ฎๅฝ• */ async checkFileExist(filePath: string): Promise<boolean> { return new Promise((resolve, reject) => { // fix path end must a / // ๆฃ€ๆต‹ๆ–‡ไปถๅคนๆ˜ฏๅฆๅญ˜ๅœจ this.bucketManager.stat( this.qiniuConfig.bucket, filePath, (respErr, respBody, respInfo) => { if (respErr) { reject(respErr); return; } if (respInfo.statusCode === 200) { // ๆ–‡ไปถๅคนๅญ˜ๅœจ resolve(true); } else if (respInfo.statusCode === 612) { // ๆ–‡ไปถๅคนไธๅญ˜ๅœจ resolve(false); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ๅˆ›ๅปบUpload Token, ้ป˜่ฎค่ฟ‡ๆœŸๆ—ถ้—ดไธ€ๅฐๆ—ถ * @returns upload token */ createUploadToken(endUser: string): string { const policy = new qiniu.rs.PutPolicy({ scope: this.qiniuConfig.bucket, insertOnly: 1, endUser, }); const uploadToken = policy.uploadToken(this.mac); return uploadToken; } /** * ้‡ๅ‘ฝๅๆ–‡ไปถ * @param dir ๆ–‡ไปถ่ทฏๅพ„ * @param name ๆ–‡ไปถๅ็งฐ */ async renameFile(dir: string, name: string, toName: string): Promise<void> { const fileName = `${dir}${name}`; const toFileName = `${dir}${toName}`; const op = { force: true, }; return new Promise((resolve, reject) => { this.bucketManager.move( this.qiniuConfig.bucket, fileName, this.qiniuConfig.bucket, toFileName, op, (err, respBody, respInfo) => { if (err) { reject(err); } else { if (respInfo.statusCode === 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } } }, ); }); } /** * ็งปๅŠจๆ–‡ไปถ */ async moveFile(dir: string, toDir: string, name: string): Promise<void> { const fileName = `${dir}${name}`; const toFileName = `${toDir}${name}`; const op = { force: true, }; return new Promise((resolve, reject) => { this.bucketManager.move( this.qiniuConfig.bucket, fileName, this.qiniuConfig.bucket, toFileName, op, (err, respBody, respInfo) => { if (err) { reject(err); } else { if (respInfo.statusCode === 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } } }, ); }); } /** * ๅคๅˆถๆ–‡ไปถ */ async copyFile(dir: string, toDir: string, name: string): Promise<void> { const fileName = `${dir}${name}`; // ๆ‹ผๆŽฅๆ–‡ไปถๅ const ext = extname(name); const bn = basename(name, ext); const toFileName = `${toDir}${bn}${NETDISK_COPY_SUFFIX}${ext}`; const op = { force: true, }; return new Promise((resolve, reject) => { this.bucketManager.copy( this.qiniuConfig.bucket, fileName, this.qiniuConfig.bucket, toFileName, op, (err, respBody, respInfo) => { if (err) { reject(err); } else { if (respInfo.statusCode === 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } } }, ); }); } /** * ้‡ๅ‘ฝๅๆ–‡ไปถๅคน */ async renameDir(path: string, name: string, toName: string): Promise<void> { const dirName = `${path}${name}`; const toDirName = `${path}${toName}`; let hasFile = true; let marker = ''; const op = { force: true, }; const bucketName = this.qiniuConfig.bucket; while (hasFile) { await new Promise<void>((resolve, reject) => { // ๅˆ—ไธพๅฝ“ๅ‰็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ this.bucketManager.listPrefix( this.qiniuConfig.bucket, { prefix: dirName, limit: NETDISK_HANDLE_MAX_ITEM, marker, }, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { const moveOperations = respBody.items.map((item) => { const { key } = item; const destKey = key.replace(dirName, toDirName); return qiniu.rs.moveOp( bucketName, key, bucketName, destKey, op, ); }); this.bucketManager.batch( moveOperations, (err2, respBody2, respInfo2) => { if (err2) { reject(err2); return; } if (respInfo2.statusCode === 200) { if (isEmpty(respBody.marker)) { hasFile = false; } else { marker = respBody.marker; } resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo2.statusCode}, Info: ${respInfo2.statusMessage}`, ), ); } }, ); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } } /** * ่Žทๅ–ไธƒ็‰›ไธ‹่ฝฝ็š„ๆ–‡ไปถurl้“พๆŽฅ * @param key ๆ–‡ไปถ่ทฏๅพ„ * @returns ่ฟžๆŽฅ */ getDownloadLink(key: string): string { if (this.qiniuConfig.access === 'public') { return this.bucketManager.publicDownloadUrl(this.qiniuConfig.domain, key); } else if (this.qiniuConfig.access === 'private') { return this.bucketManager.privateDownloadUrl( this.qiniuConfig.domain, key, Date.now() / 1000 + 36000, ); } throw new Error('qiniu config access type not support'); } /** * ๅˆ ้™คๆ–‡ไปถ * @param dir ๅˆ ้™ค็š„ๆ–‡ไปถๅคน็›ฎๅฝ• * @param name ๆ–‡ไปถๅ */ async deleteFile(dir: string, name: string): Promise<void> { return new Promise((resolve, reject) => { this.bucketManager.delete( this.qiniuConfig.bucket, `${dir}${name}`, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } /** * ๅˆ ้™คๆ–‡ไปถๅคน * @param dir ๆ–‡ไปถๅคนๆ‰€ๅœจ็š„ไธŠ็บง็›ฎๅฝ• * @param name ๆ–‡ไปถ็›ฎๅฝ•ๅ็งฐ */ async deleteMultiFileOrDir( fileList: FileOpItem[], dir: string, ): Promise<void> { const files = fileList.filter((item) => item.type === 'file'); if (files.length > 0) { // ๆ‰นๅค„็†ๆ–‡ไปถ const copyOperations = files.map((item) => { const fileName = `${dir}${item.name}`; return qiniu.rs.deleteOp(this.qiniuConfig.bucket, fileName); }); await new Promise<void>((resolve, reject) => { this.bucketManager.batch(copyOperations, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { resolve(); } else if (respInfo.statusCode === 298) { reject(new Error('ๆ“ไฝœๅผ‚ๅธธ๏ผŒไฝ†้ƒจๅˆ†ๆ–‡ไปถๅคนๅˆ ้™คๆˆๅŠŸ')); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }); }); } // ๅค„็†ๆ–‡ไปถๅคน const dirs = fileList.filter((item) => item.type === 'dir'); if (dirs.length > 0) { // ๅค„็†ๆ–‡ไปถๅคน็š„ๅคๅˆถ for (let i = 0; i < dirs.length; i++) { const dirName = `${dir}${dirs[i].name}/`; let hasFile = true; let marker = ''; while (hasFile) { await new Promise<void>((resolve, reject) => { // ๅˆ—ไธพๅฝ“ๅ‰็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ this.bucketManager.listPrefix( this.qiniuConfig.bucket, { prefix: dirName, limit: NETDISK_HANDLE_MAX_ITEM, marker, }, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { const moveOperations = respBody.items.map((item) => { const { key } = item; return qiniu.rs.deleteOp(this.qiniuConfig.bucket, key); }); this.bucketManager.batch( moveOperations, (err2, respBody2, respInfo2) => { if (err2) { reject(err2); return; } if (respInfo2.statusCode === 200) { if (isEmpty(respBody.marker)) { hasFile = false; } else { marker = respBody.marker; } resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo2.statusCode}, Info: ${respInfo2.statusMessage}`, ), ); } }, ); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } } } } /** * ๅคๅˆถๆ–‡ไปถ๏ผŒๅซๆ–‡ไปถๅคน */ async copyMultiFileOrDir( fileList: FileOpItem[], dir: string, toDir: string, ): Promise<void> { const files = fileList.filter((item) => item.type === 'file'); const op = { force: true, }; if (files.length > 0) { // ๆ‰นๅค„็†ๆ–‡ไปถ const copyOperations = files.map((item) => { const fileName = `${dir}${item.name}`; // ๆ‹ผๆŽฅๆ–‡ไปถๅ const ext = extname(item.name); const bn = basename(item.name, ext); const toFileName = `${toDir}${bn}${NETDISK_COPY_SUFFIX}${ext}`; return qiniu.rs.copyOp( this.qiniuConfig.bucket, fileName, this.qiniuConfig.bucket, toFileName, op, ); }); await new Promise<void>((resolve, reject) => { this.bucketManager.batch(copyOperations, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { resolve(); } else if (respInfo.statusCode === 298) { reject(new Error('ๆ“ไฝœๅผ‚ๅธธ๏ผŒไฝ†้ƒจๅˆ†ๆ–‡ไปถๅคนๅˆ ้™คๆˆๅŠŸ')); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }); }); } // ๅค„็†ๆ–‡ไปถๅคน const dirs = fileList.filter((item) => item.type === 'dir'); if (dirs.length > 0) { // ๅค„็†ๆ–‡ไปถๅคน็š„ๅคๅˆถ for (let i = 0; i < dirs.length; i++) { const dirName = `${dir}${dirs[i].name}/`; const copyDirName = `${toDir}${dirs[i].name}${NETDISK_COPY_SUFFIX}/`; let hasFile = true; let marker = ''; while (hasFile) { await new Promise<void>((resolve, reject) => { // ๅˆ—ไธพๅฝ“ๅ‰็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ this.bucketManager.listPrefix( this.qiniuConfig.bucket, { prefix: dirName, limit: NETDISK_HANDLE_MAX_ITEM, marker, }, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { const moveOperations = respBody.items.map((item) => { const { key } = item; const destKey = key.replace(dirName, copyDirName); return qiniu.rs.copyOp( this.qiniuConfig.bucket, key, this.qiniuConfig.bucket, destKey, op, ); }); this.bucketManager.batch( moveOperations, (err2, respBody2, respInfo2) => { if (err2) { reject(err2); return; } if (respInfo2.statusCode === 200) { if (isEmpty(respBody.marker)) { hasFile = false; } else { marker = respBody.marker; } resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo2.statusCode}, Info: ${respInfo2.statusMessage}`, ), ); } }, ); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } } } } /** * ็งปๅŠจๆ–‡ไปถ๏ผŒๅซๆ–‡ไปถๅคน */ async moveMultiFileOrDir( fileList: FileOpItem[], dir: string, toDir: string, ): Promise<void> { const files = fileList.filter((item) => item.type === 'file'); const op = { force: true, }; if (files.length > 0) { // ๆ‰นๅค„็†ๆ–‡ไปถ const copyOperations = files.map((item) => { const fileName = `${dir}${item.name}`; const toFileName = `${toDir}${item.name}`; return qiniu.rs.moveOp( this.qiniuConfig.bucket, fileName, this.qiniuConfig.bucket, toFileName, op, ); }); await new Promise<void>((resolve, reject) => { this.bucketManager.batch(copyOperations, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { resolve(); } else if (respInfo.statusCode === 298) { reject(new Error('ๆ“ไฝœๅผ‚ๅธธ๏ผŒไฝ†้ƒจๅˆ†ๆ–‡ไปถๅคนๅˆ ้™คๆˆๅŠŸ')); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }); }); } // ๅค„็†ๆ–‡ไปถๅคน const dirs = fileList.filter((item) => item.type === 'dir'); if (dirs.length > 0) { // ๅค„็†ๆ–‡ไปถๅคน็š„ๅคๅˆถ for (let i = 0; i < dirs.length; i++) { const dirName = `${dir}${dirs[i].name}/`; const toDirName = `${toDir}${dirs[i].name}/`; // ็งปๅŠจ็š„็›ฎๅฝ•ไธๆ˜ฏๆ˜ฏ่‡ชๅทฑ if (toDirName.startsWith(dirName)) { continue; } let hasFile = true; let marker = ''; while (hasFile) { await new Promise<void>((resolve, reject) => { // ๅˆ—ไธพๅฝ“ๅ‰็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ this.bucketManager.listPrefix( this.qiniuConfig.bucket, { prefix: dirName, limit: NETDISK_HANDLE_MAX_ITEM, marker, }, (err, respBody, respInfo) => { if (err) { reject(err); return; } if (respInfo.statusCode === 200) { const moveOperations = respBody.items.map((item) => { const { key } = item; const destKey = key.replace(dirName, toDirName); return qiniu.rs.moveOp( this.qiniuConfig.bucket, key, this.qiniuConfig.bucket, destKey, op, ); }); this.bucketManager.batch( moveOperations, (err2, respBody2, respInfo2) => { if (err2) { reject(err2); return; } if (respInfo2.statusCode === 200) { if (isEmpty(respBody.marker)) { hasFile = false; } else { marker = respBody.marker; } resolve(); } else { reject( new Error( `Qiniu Error Code: ${respInfo2.statusCode}, Info: ${respInfo2.statusMessage}`, ), ); } }, ); } else { reject( new Error( `Qiniu Error Code: ${respInfo.statusCode}, Info: ${respInfo.statusMessage}`, ), ); } }, ); }); } } } } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/commitmentAssociationsMappers"; import * as Parameters from "../models/parameters"; import { AzureMLCommitmentPlansManagementClientContext } from "../azureMLCommitmentPlansManagementClientContext"; /** Class representing a CommitmentAssociations. */ export class CommitmentAssociations { private readonly client: AzureMLCommitmentPlansManagementClientContext; /** * Create a CommitmentAssociations. * @param {AzureMLCommitmentPlansManagementClientContext} client Reference to the service client. */ constructor(client: AzureMLCommitmentPlansManagementClientContext) { this.client = client; } /** * Get a commitment association. * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param [options] The optional parameters * @returns Promise<Models.CommitmentAssociationsGetResponse> */ get(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommitmentAssociationsGetResponse>; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param callback The callback */ get(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, callback: msRest.ServiceCallback<Models.CommitmentAssociation>): void; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommitmentAssociation>): void; get(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommitmentAssociation>, callback?: msRest.ServiceCallback<Models.CommitmentAssociation>): Promise<Models.CommitmentAssociationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, commitmentPlanName, commitmentAssociationName, options }, getOperationSpec, callback) as Promise<Models.CommitmentAssociationsGetResponse>; } /** * Get all commitment associations for a parent commitment plan. * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param [options] The optional parameters * @returns Promise<Models.CommitmentAssociationsListResponse> */ list(resourceGroupName: string, commitmentPlanName: string, options?: Models.CommitmentAssociationsListOptionalParams): Promise<Models.CommitmentAssociationsListResponse>; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param callback The callback */ list(resourceGroupName: string, commitmentPlanName: string, callback: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): void; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, commitmentPlanName: string, options: Models.CommitmentAssociationsListOptionalParams, callback: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): void; list(resourceGroupName: string, commitmentPlanName: string, options?: Models.CommitmentAssociationsListOptionalParams | msRest.ServiceCallback<Models.CommitmentAssociationListResult>, callback?: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): Promise<Models.CommitmentAssociationsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, commitmentPlanName, options }, listOperationSpec, callback) as Promise<Models.CommitmentAssociationsListResponse>; } /** * Re-parent a commitment association from one commitment plan to another. * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param movePayload The move request payload. * @param [options] The optional parameters * @returns Promise<Models.CommitmentAssociationsMoveResponse> */ move(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, movePayload: Models.MoveCommitmentAssociationRequest, options?: msRest.RequestOptionsBase): Promise<Models.CommitmentAssociationsMoveResponse>; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param movePayload The move request payload. * @param callback The callback */ move(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, movePayload: Models.MoveCommitmentAssociationRequest, callback: msRest.ServiceCallback<Models.CommitmentAssociation>): void; /** * @param resourceGroupName The resource group name. * @param commitmentPlanName The Azure ML commitment plan name. * @param commitmentAssociationName The commitment association name. * @param movePayload The move request payload. * @param options The optional parameters * @param callback The callback */ move(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, movePayload: Models.MoveCommitmentAssociationRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommitmentAssociation>): void; move(resourceGroupName: string, commitmentPlanName: string, commitmentAssociationName: string, movePayload: Models.MoveCommitmentAssociationRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommitmentAssociation>, callback?: msRest.ServiceCallback<Models.CommitmentAssociation>): Promise<Models.CommitmentAssociationsMoveResponse> { return this.client.sendOperationRequest( { resourceGroupName, commitmentPlanName, commitmentAssociationName, movePayload, options }, moveOperationSpec, callback) as Promise<Models.CommitmentAssociationsMoveResponse>; } /** * Get all commitment associations for a parent commitment plan. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.CommitmentAssociationsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CommitmentAssociationsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommitmentAssociationListResult>, callback?: msRest.ServiceCallback<Models.CommitmentAssociationListResult>): Promise<Models.CommitmentAssociationsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.CommitmentAssociationsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}/commitmentAssociations/{commitmentAssociationName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.commitmentPlanName, Parameters.commitmentAssociationName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommitmentAssociation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}/commitmentAssociations", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.commitmentPlanName ], queryParameters: [ Parameters.skipToken, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommitmentAssociationListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const moveOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/commitmentPlans/{commitmentPlanName}/commitmentAssociations/{commitmentAssociationName}/move", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.commitmentPlanName, Parameters.commitmentAssociationName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "movePayload", mapper: { ...Mappers.MoveCommitmentAssociationRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.CommitmentAssociation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CommitmentAssociationListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
/// <reference types="winjs" /> /// <reference types="winrt" /> declare namespace Microsoft.Live { //#region REST Object Information /** * Sub object of REST objects that contains information about a user. */ interface IUserInfo { /** * The name of the user. */ name: string; /** * The Live ID of the user. */ id: string; } /** * Sub object of REST objects that contains information about who the * item is shared with. */ interface ISharedWith { /** * A localized string that contains info about who can access the * item. The options are: * - People I selected * - Just me * - Everyone (public) * - Friends * - My friends and their friends * - People with a link * The default is Just me. */ access: string; } /** * Convenience interface for when you have a bunch of objects of different * types in a single collection. You discriminate between them using their * 'type' field. */ interface IObject { /** * The object's type. */ type: string; } /** * Contains a collection of one type of object. */ interface IObjectCollection<T> { /** * An array container for objects when a collection of objects is * returned. */ data: T[]; } /** * The Album object contains info about a user's albums in Microsoft * SkyDrive. Albums are stored at the root level of a user's SkyDrive * directory, and can contain combinations of photos, videos, audio, files, * and folders. The Live Connect REST API supports reading Album objects. * Use the wl.photos scope to read a user's Album objects. Use the * wl.skydrive scope to read a user's files. Use the wl.contacts_photos * scope to read any albums, photos, videos, and audio that other users have * shared with the user. */ interface IAlbum { /** * The Album object's ID. */ id: string; /** * Info about the user who authored the album. */ from: IUserInfo; /** * The name of the album. */ name: string; /** * A description of the album, or null if no description is specified. */ description: string; /** * The resource ID of the parent. */ parent_id: string; /** * The URL to upload items to the album, hosted in SkyDrive. Requires * the wl.skydrive scope. */ upload_location: string; /** * A value that indicates whether this album can be embedded. If this * album can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * The total number of items in the album. */ count: number; /** * A URL of the album, hosted in SkyDrive. */ link: string; /** * The type of object; in this case, "album". */ type: string; /** * The object that contains permissions info for the album. Requires the * wl.skydrive scope. */ shared_with: ISharedWith; /** * The time, in ISO 8601 format, at which the album was created. */ created_time: string; /** * The time, in ISO 8601 format, that the system updated the album last. */ updated_time: string; /** * The time, in ISO 8601 format, that the file was last updated. */ client_updated_time: string; } /** * Represents a new album. */ interface INewAlbum { /** * The name of the album. */ name: string; /** * A description of the album. */ description?: string | undefined; } /** * The Audio object contains info about a user's audio in SkyDrive. The Live * Connect REST API supports creating, reading, updating, and deleting Audio * objects. Use the wl.skydrive scope to read Audio objects. Use the * wl.contacts_skydrive scope to read any audio that other users have shared * with the user. Use the wl.skydrive_update scope to create, update, or * delete Audio objects. */ interface IAudio { /** * The Audio object's ID. */ id: string; /** * Info about the user who uploaded the audio. */ from: IUserInfo; /** * The name of the audio. */ name: string; /** * A description of the audio, or null if no description is specified. */ description: string; /** * The id of the folder in which the audio is currently stored. */ parent_id: string; /** * The size, in bytes, of the audio. */ size: number; /** * The URL to use to upload a new audio to overwrite the existing audio. */ upload_location: string; /** * The number of comments associated with the audio. */ comments_count: number; /** * A value that indicates whether comments are enabled for the audio. If * comments can be made, this value is true; otherwise, it is false. */ comments_enabled: boolean; /** * A value that indicates whether this audio can be embedded. If this * audio can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * The URL to use to download the audio from SkyDrive. * Warning * This value is not persistent. Use it immediately after making the * request, and avoid caching. */ source: string; /** * A URL to view the item on SkyDrive. */ link: string; /** * The type of object; in this case, "audio". */ type: string; /** * The audio's title. */ title: string; /** * The audio's artist name. */ artist: string; /** * The audio's album name. */ album: string; /** * The artist name of the audio's album. */ album_artist: string; /** * The audio's genre. */ genre: string; /** * The audio's playing time, in milliseconds. */ duration: number; /** * A URL to view the audio's picture on SkyDrive. */ picture: string; /** * The object that contains permission info. */ shared_with: ISharedWith; /** * The time, in ISO 8601 format, at which the audio was created. */ created_time: string; /** * The time, in ISO 8601 format, at which the audio was last updated. */ updated_time: string; } /** * Represents a new audio item. */ interface INewAudio { /** * The name of the audio. */ name: string; /** * A description of the audio. */ description?: string | undefined; /** * The audio's title. */ title?: string | undefined; /** * The audio's artist name. */ artist?: string | undefined; /** * The audio's album name. */ album?: string | undefined; /** * The artist name of the audio's album. */ album_artist?: string | undefined; /** * The audio's genre. */ genre?: string | undefined; } /** * The Calendar object contains info about a user's Outlook.com calendar. * The Live Connect REST API supports creating, reading, updating, and * deleting calendars. Use the wl.calendars scope to read a user's Calendar * objects. Use the wl.calendars_update scope to create Calendar objects for * a user. Use the wl.contacts_calendars scope to read a user's friends' * Calendar objects. */ interface ICalendar { /** * The Calendar object's ID. */ id: string; /** * Name of the calendar. */ name: string; /** * Description of the calendar. */ description: string; /** * The time, in ISO 8601 format, at which the calendar was created. */ created_time: string; /** * The time, in ISO 8601 format, that the calendar was last updated. */ updated_time: string; /** * Info about the user who owns the calendar. */ from: IUserInfo; /** * A value that indicates whether this calendar is the default calendar. * If this calendar is the default calendar, this value is true; * otherwise, it is false. */ is_default: boolean; /** * A public subscription URL with which Live Connect will synchronize * properties and events periodically for this calendar. A NULL value * indicates that this is not a subscribed calendar. */ subscription_location: string; /** * Role and permissions that are granted to the user for the calendar. * The possible values are: * - free_busy: The user can see only free/busy info. * - limited_details: The user can see a subset of all details. * - read: The user can only read the content of the calendar events. * - read_write: The user can read and write calendar and events. * - co_owner: The user is co-owner of this calendar. * - owner: The user is the owner of this calendar. */ permissions: string; } /** * Represents a new calendar item. */ interface INewCalendar { /** * Name of the calendar. */ name: string; /** * Description of the calendar. */ description?: string | undefined; } /** * Represents a request to create a new calendar that subscribes to the * given iCal calendar. */ interface INewCalendarSubscription { /** * Name of the calendar. */ name: string; /** * A public subscription URL with which Live Connect will synchronize * properties and events periodically for this calendar. */ subscription_location: string; } /** * The Comment object contains info about comments that are associated with * a photo, audio, or video on SkyDrive. The Live Connect REST API supports * reading Comment objects. Use the wl.photos scope to read Comment objects. * Use the wl.contacts_photos scope to read the Comment objects that are * associated with any albums, photos, and videos that other users have * shared with the user. */ interface IComment { /** * The Comment object's id. */ id: string; /** * Info about the user who created the comment. */ from: IUserInfo; /** * The text of the comment. The maximum length of a comment is 10,000 * characters. */ message: string; /** * The time, in ISO 8601 format, at which the comment was created. */ created_time: string; } /** * Represents a new comment. */ interface INewComment { /** * The text of the comment. The maximum length of a comment is 10,000 * characters. */ message: string; } /** * The Contact object contains info about a user's Outlook.com contacts. The * Live Connect REST API supports reading Contact objects. */ interface IContact { /** * The Contact object's ID. */ id: string; /** * The contact's first name, or null if no first name is specified. */ first_name: string; /** * The contact's last name, or null if no last name is specified. */ last_name: string; /** * The contact's full name, formatted for location. */ name: string; /** * A value that indicates whether the contact is set as a friend. If the * contact is a friend, this value is true; otherwise, it is false. */ is_friend: boolean; /** * A value that indicates whether the contact is set as a favorite * contact. If the contact is a favorite, this value is true; otherwise, * it is false. */ is_favorite: boolean; /** * The contact's ID, if the contact has one. If not, this value is null. */ user_id: string; /** * An array containing a SHA-256 hash for each of the contact's email * addresses. For more info, see Friend finder. */ email_hashes: string[]; /** * The time, in ISO 8601 format, at which the user last updated the * data. */ updated_time: string; /** * The day of the contact's birth date, or null if no birth date is * specified. */ birth_day: number; /** * The month of the contact's birth date, or null if no birth date is * specified. */ birth_month: number; } /** * Represents a new contact. */ interface INewContact { /** * The contact's first name. */ first_name?: string | undefined; /** * The contact's last name. */ last_name?: string | undefined; /** * An array that contains the contact's work info. */ work?: { employer: { name: string; } }[] | undefined; /** * The contact's email addresses. */ emails?: { /** * The contact's preferred email address. */ preferred?: string | undefined; /** * The contact's personal email address. */ personal?: string | undefined; /** * The contact's business email address. */ business?: string | undefined; /** * The contact's "alternate" email address. */ other?: string | undefined; } | undefined; } /** * The Error object contains info about an error that is returned by the * Live Connect APIs. */ interface IError { /** * Info about the error. */ error: { /** * The error code. */ code: string; /** * The error message. */ message: string; }; } /** * The Event object contains info about events on a user's Outlook.com * calendars. The Live Connect REST API supports creating Event objects. Use * the wl.events_create scope to create Event objects on the user's default * calendar only. Use the wl.calendars scope to read Event objects on the * user's calendars. Use wl.calendars_update to create Event objects on any * of the user's calendars. Use the wl.contacts_calendars scope to read * Event objects from the user's friend's calendars. */ interface IEvent { /** * The ID of the event. */ id: string; /** * The name of the event, with a maximum length of 255 characters. This * structure is required. */ name: string; /** * The time, in ISO 8601 format, at which the event was created. */ created_time: string; /** * The time, in ISO 8601 format, at which the event was updated. This * structure is visible only in the Event object that is returned if the * event was successfully created. */ updated_time: string; /** * A description of the event, with a maximum length of 32,768 * characters. This structure is required. */ description: string; /** * The ID of the calendar that contains the event. */ calendar_id: string; /** * The object that contains the name and ID of the organizer. */ from: IUserInfo; /** * The start time, in ISO 8601 format, of the event. When the event is * being read, the time will be the user's local time, in ISO 8601 * format. */ start_time: string; /** * The end time, in ISO 8601 format, of the event. If no end time is * specified, the default value is 30 minutes after start_time. This * structure is optional when creating an event. When the event is being * read, the time will be the user's local time, in ISO 8601 format. */ end_time: string; /** * The name of the location at which the event will take place. The * maximum length is 1,000 characters. */ location: string; /** * A value that specifies whether the event is an all-day event. If the * event is an all-day event, this value is true; otherwise, it is * false. If this structure is missing, the default value is false. */ is_all_day_event: boolean; /** * A value that specifies whether the event is recurring. If the event * is recurring, this value is true; otherwise, it is false. */ is_recurrent: boolean; /** * The text description of the recurrence pattern, for example, "Occurs * every week on Tuesday". The value is Null if this is not a recurrent * event. */ recurrence: string; /** * The time, in minutes, before the event for the reminder alarm. */ reminder_time: number; /** * The user's availability status for the event. Valid values are: * - free * - busy * - tentative * - out_of_office * @default "free" */ availability: string; /** * A value that specifies whether the event is publicly visible. Valid * values are: * - public the event is visible to anyone who can view the calendar. * - private the event is visible only to the event owner. * @default "public" */ visibility: string; } /** * Represents a new event. */ interface INewEvent { /** * The name of the event, with a maximum length of 255 characters. This * structure is required. */ name: string; /** * A description of the event, with a maximum length of 32,768 * characters. This structure is required. */ description: string; /** * The start time of the event. When the event is being read, the time * will be the user's local time, in ISO 8601 format. * Can be a date string, or a Date object. */ start_time: any; /** * The end time of the event. If no end time is specified, the default * value is 30 minutes after start_time. This structure is optional when * creating an event. When the event is being read, the time will be the * user's local time, in ISO 8601 format. * Can be a date string, or a Date object. */ end_time?: any; /** * The name of the location at which the event will take place. The * maximum length is 1,000 characters. */ location?: string | undefined; /** * A value that specifies whether the event is an all-day event. If the * event is an all-day event, this value is true; otherwise, it is * false. If this structure is missing, the default value is false. */ is_all_day_event?: boolean | undefined; /** * The time, in minutes, before the event for the reminder alarm. */ reminder_time?: number | undefined; /** * The user's availability status for the event. Valid values are: * - free * - busy * - tentative * - out_of_office * @default "free" */ availability?: string | undefined; /** * A value that specifies whether the event is publicly visible. Valid * values are: * - public the event is visible to anyone who can view the calendar. * - private the event is visible only to the event owner. * @default "public" */ visibility?: string | undefined; } /** * Response received after successfully creating a new event. */ interface INewEventResponse { /** * The name of the event, with a maximum length of 255 characters. This * structure is required. */ name: string; /** * A description of the event, with a maximum length of 32,768 * characters. This structure is required. */ description: string; /** * The start time, in ISO 8601 format, of the event. When the event is * being read, the time will be the user's local time, in ISO 8601 * format. */ start_time: string; /** * The end time, in ISO 8601 format, of the event. If no end time is * specified, the default value is 30 minutes after start_time. This * structure is optional when creating an event. When the event is being * read, the time will be the user's local time, in ISO 8601 format. */ end_time: string; /** * The name of the location at which the event will take place. The * maximum length is 1,000 characters. */ location: string; /** * A value that specifies whether the event is an all-day event. If the * event is an all-day event, this value is true; otherwise, it is * false. If this structure is missing, the default value is false. */ is_all_day_event: boolean; /** * A value that specifies whether the event is recurring. If the event * is recurring, this value is true; otherwise, it is false. */ is_recurrent: boolean; /** * The text description of the recurrence pattern, for example, "Occurs * every week on Tuesday". The value is Null if this is not a recurrent * event. */ recurrence: string; /** * The time, in minutes, before the event for the reminder alarm. */ reminder_time: number; /** * The user's availability status for the event. Valid values are: * - free * - busy * - tentative * - out_of_office * @default "free" */ availability: string; /** * A value that specifies whether the event is publicly visible. Valid * values are: * - public the event is visible to anyone who can view the calendar. * - private the event is visible only to the event owner. * @default "public" */ visibility: string; /** * The time, in ISO 8601 format, at which the event was updated. This * structure is visible only in the Event object that is returned if the * event was successfully created. */ updated_time: string; } /** * The File object contains info about a user's files in SkyDrive. The Live * Connect REST API supports creating, reading, updating, and deleting File * objects. Use the wl.skydrive scope to read File objects. Use the * wl.contacts_skydrive scope to read any files that other users have shared * with the user. Use the wl.skydrive_update scope to create, update, or * delete File objects. */ interface IFile { /** * The File object's ID. */ id: string; /** * Info about the user who uploaded the file. */ from: IUserInfo; /** * The name of the file. */ name: string; /** * A description of the file, or null if no description is specified. */ description: string; /** * The ID of the folder the file is currently stored in. */ parent_id: string; /** * The size, in bytes, of the file. */ size: number; /** * The URL to upload file content hosted in SkyDrive. * Note: This structure is not available if the file is an Microsoft * Office OneNote notebook. */ upload_location: string; /** * The number of comments that are associated with the file. */ comments_count: number; /** * A value that indicates whether comments are enabled for the file. If * comments can be made, this value is true; otherwise, it is false. */ comments_enabled: boolean; /** * A value that indicates whether this file can be embedded. If this * file can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * The URL to use to download the file from SkyDrive. * Warning: This value is not persistent. Use it immediately after * making the request, and avoid caching. * Note: This structure is not available if the file is an Office * OneNote notebook. */ source: string; /** * A URL to view the item on SkyDrive. */ link: string; /** * The type of object; in this case, "file". * Note: If the file is a Office OneNote notebook, the type structure is * set to "notebook". */ type: string; /** * Object that contains permission info. */ shared_with: ISharedWith; /** * The time, in ISO 8601 format, at which the file was created. */ created_time: string; /** * The time, in ISO 8601 format, that the system updated the file last. */ updated_time: string; /** * The time, in ISO 8601 format, that the client machine updated the * file last. */ client_updated_time: string; /** * Sorts the items to specify the following criteria: updated, name, * size, or default. */ sort_by: string; } /** * Success response to a new file creation request. */ interface INewFileResponse { /** * ID of the new item. */ id: string; /** * The file's name and file extension. */ name: string; /** * URL where the item can be downloaded from. */ source: string; } /** * Returns when you perform a GET request to /FILE_ID/content. */ interface IFileDownloadLink { /** * A URL download link for the file. */ location: string; } /** * The Folder object contains info about a user's folders in SkyDrive. * Folders can contain combinations of photos, videos, audio, and * subfolders. The Live Connect REST API supports reading Folder objects. * Use the wl.photos scope to read Folder objects. Use the * wl.contacts_photos scope to read any albums, photos, videos, and audio * that other users have shared with the user. */ interface IFolder { /** * The Folder object's ID. */ id: string; /** * Info about the user who created the folder. */ from: IUserInfo; /** * The name of the folder. */ name: string; /** * A description of the folder, or null if no description is specified. */ description: string; /** * The total number of items in the folder. */ count: number; /** * The URL of the folder, hosted in SkyDrive. */ link: string; /** * The resource ID of the parent. */ parent_id: string; /** * The URL to upload items to the folder hosted in SkyDrive. Requires * the wl.skydrive scope. */ upload_location: string; /** * A value that indicates whether this folder can be embedded. If this * folder can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * The type of object; in this case, "folder". */ type: string; /** * The time, in ISO 8601 format, at which the folder was created. */ created_time: string; /** * The time, in ISO 8601 format, that the system updated the file last. */ updated_time: string; /** * The time, in ISO 8601 format, that the client machine updated the * file last. */ client_updated_time: string; /** * Permissions info for the folder. Requires the wl.skydrive scope. */ shared_with: ISharedWith; /** * Sorts the items to specify the following criteria: updated, name, * size, or default. */ sort_by: string; } /** * Represents a new folder. */ interface INewFolder { /** * The name of the folder. */ name: string; /** * A description of the folder. */ description?: string | undefined; /** * Sorts the items to specify the following criteria: updated, name, * size, or default. */ sort_by?: string | undefined; } /** * The Friend object contains info about a user's friends. A Friend object * represents a user's contact whose is_friend value is set to true. The * Live Connect REST API supports reading Friend objects. */ interface IFriend { /** * The friend's ID. */ id: string; /** * The friend's full name, formatted for locale. */ name: string; } /** * The Permissions object contains a list of scopes, showing those scopes to * which the user has consented. The response body contains a JSON object * that lists all consented scopes as a name/value pair. Each scope to which * the user consented is present as a key. */ interface IPermissions { [scope: string]: number; } /** * Information about an image. */ interface IImageInfo { /** * The height, in pixels, of this image of this particular size. */ height: number; /** * The width, in pixels, of this image of this particular size. */ width: number; /** * The width, in pixels, of this image of this particular size. */ source: string; /** * The type of this image of this particular size. Valid values are: * full (maximum size: 2048 x 2048 pixels) * - normal (maximum size 800 x 800 pixels) * - album (maximum size 176 x 176 pixels) * - small (maximum size 96 x 96 pixels) */ type: string; } /** * Represents location information. */ interface ILocation { /** * The latitude portion of the location, expressed as positive (north) * or negative (south) degrees relative to the equator. */ latitude: number; /** * The longitude portion of the location expressed as positive (east) or * negative (west) degrees relative to the Prime Meridian. */ longitude: number; /** * The altitude portion of the location, expressed as positive (above) * or negative (below) values relative to sea level, in units of * measurement as determined by the camera. */ altitude: number; } /** * The Photo object contains info about a user's photos on SkyDrive. The * Live Connect REST API supports creating, reading, updating, and deleting * Photo objects. Use the wl.photos scope to read Photo objects. Use the * wl.contacts_photos scope to read any albums, photos, videos, and audio * that other users have shared with the user. Use the wl.skydrive_update * scope to create, update, or delete Photo objects. */ interface IPhoto { /** * The Photo object's ID. */ id: string; /** * Info about the user who uploaded the photo. */ from: IUserInfo; /** * The file name of the photo. */ name: string; /** * A description of the photo, or null if no description is specified. */ description: string; /** * The ID of the folder where the item is stored. */ parent_id: string; /** * The size, in bytes, of the photo. */ size: number; /** * The number of comments associated with the photo. */ comments_count: number; /** * A value that indicates whether comments are enabled for the photo. If * comments can be made, this value is true; otherwise, it is false. */ comments_enabled: boolean; /** * The number of tags on the photo. */ tags_count: number; /** * A value that indicates whether tags are enabled for the photo. If * users can tag the photo, this value is true; otherwise, it is false. */ tags_enabled: boolean; /** * A value that indicates whether this photo can be embedded. If this * photo can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * A URL of the photo's picture. */ picture: string; /** * The download URL for the photo. * Warning: This value is not persistent. Use it immediately after * making the request, and avoid caching. */ source: string; /** * The URL to upload photo content hosted in SkyDrive. This value is * returned only if the wl.skydrive scope is present. */ upload_location: string; /** * Info about various sizes of the photo. */ images: IImageInfo[]; /** * A URL of the photo, hosted in SkyDrive. */ link: string; /** * The date, in ISO 8601 format, on which the photo was taken, or null * if no date is specified. */ when_taken: string; /** * The height, in pixels, of the photo. */ height: number; /** * The width, in pixels, of the photo. */ width: number; /** * The type of object; in this case, "photo". */ type: string; /** * The location where the photo was taken. * Note: The location object is not available for shared photos. */ location: ILocation; /** * The manufacturer of the camera that took the photo. */ camera_make: string; /** * The brand and model number of the camera that took the photo. */ camera_model: string; /** * The f-number that the photo was taken at. */ focal_ratio: number; /** * The focal length that the photo was taken at, typically expressed in * millimeters for newer lenses. */ focal_length: number; /** * The numerator of the shutter speed (for example, the "1" in "1/15 s") * that the photo was taken at. */ exposure_numerator: number; /** * The denominator of the shutter speed (for example, the "15" in "1/15 * s") that the photo was taken at. */ exposure_denominator: number; /** * The object that contains permissions info for the photo. */ shared_with: ISharedWith; /** * The time, in ISO 8601 format, at which the photo was created. */ created_time: string; /** * The time, in ISO 8601 format, at which the photo was last updated. */ updated_time: string; } /** * The Search object contains info about the objects found in a user's * SkyDrive that match the search query. See Search query parameters for * info about formatting a search query request. */ interface ISearch { /** * An array of file and folder objects found in a user's SkyDrive that * match the search query. */ data: IObject[]; /** * The path strings that reference the next and previous sets in a * paginated response. */ paging?: { /** * Path string for the next set of results. */ next?: string | undefined; /** * Path string for the previous set of results. */ previous?: string | undefined; } | undefined; } /** * The Tag object contains info about tags that are associated with a photo * or a video on SkyDrive. The Live Connect REST API supports reading Tag * objects. Use the wl.photos, and wl.skydrive scopes to read Tag objects. * Use the wl.contacts_photos and wl.contacts_skydrive scopes to read the * Tag objects that are associated with any photos that other users have * shared with the user. */ interface ITag { /** * The Tag object's ID. */ id: string; /** * The user object for the tagged person. */ user: IUserInfo; /** * The center of the tag's horizontal position, measured as a * floating-point percentage from 0 to 100, from the left edge of the * photo. This value is not returned for Video objects. */ x: number; /** * The center of the tag's vertical position, measured as a * floating-point percentage from 0 to 100, from the top edge of the * photo. This value is not returned for Video objects. */ y: number; /** * The time, in ISO 8601 format, at which the tag was created. */ created_time: string; } /** * Contains work information for one employer. */ interface IWorkInfo { /** * Info about the user's employer. */ employer: { /** * The name of the user's employer, or null if the employer's name * is not specified. */ name: string; }; /** * Info about the user's work position. */ position: { /** * The name of the user's work position, or null if the name of the * work position is not specified. */ name: string; }; } /** * Information about one postal address. */ interface IPostalAddress { /** * The street address, or null if one is not specified. */ street: string; /** * The second line of the street address, or null if one is not * specified. */ street_2: string; /** * The city of the address, or null if one is not specified. */ city: string; /** * The state of the address, or null if one is not specified. */ state: string; /** * The postal code of the address, or null if one is not specified. */ postal_code: string; /** * The region of the address, or null if one is not specified. */ region: string; } /** * The User object contains info about a user. The Live Connect REST API * supports reading User objects. */ interface IUser { /** * The user's ID. */ id: string; /** * The user's full name. */ name: string; /** * The user's first name. */ first_name: string; /** * The user's last name. */ last_name: string; /** * The user's gender, or null if no gender is specified. */ gender: string; /** * The URL of the user's profile page. */ link: string; /** * The day of the user's birth date, or null if no birth date is * specified. */ birth_day: number; /** * The month of the user's birth date, or null if no birth date is * specified. */ birth_month: number; /** * The year of the user's birth date, or null if no birth date is * specified. */ birth_year: number; /** * An array that contains the user's work info. */ work: IWorkInfo[]; /** * The user's email addresses. */ emails: { /** * The user's preferred email address, or null if one is not * specified. */ preferred: string; /** * The email address that is associated with the account. */ account: string; /** * The user's personal email address, or null if one is not * specified. */ personal: string; /** * The user's business email address, or null if one is not * specified. */ business: string; /** * The user's "alternate" email address, or null if one is not * specified. */ other: string; }; /** * The user's postal addresses. */ addresses: { /** * The user's personal postal address. */ personal: IPostalAddress; /** * The user's business postal address. */ business: IPostalAddress; }; /** * The user's phone numbers. */ phones: { /** * The user's personal phone number, or null if one is not * specified. */ personal: string; /** * The user's business phone number, or null if one is not * specified. */ business: string; /** * The user's mobile phone number, or null if one is not specified. */ mobile: string; }; /** * The user's locale code. */ locale: string; /** * The time, in ISO 8601 format, at which the user last updated the * object. */ updated_time: string; } /** * The Video object contains info about a user's videos on SkyDrive. The * Live Connect REST API supports creating, reading, updating, and deleting * Video objects. Use the wl.photos scope to read Video objects. Use the * wl.contacts_photos scope to read albums, photos, and videos that other * users have shared with the user. Use the wl.skydrive_update scope to * create, update, or delete Video objects. */ interface IVideo { /** * The Video object's ID. */ id: string; /** * Info about the user who uploaded the video. */ from: IUserInfo; /** * The file name of the video. */ name: string; /** * A description of the video, or null if no description is specified. */ description: string; /** * The id of the folder where the item is stored. */ parent_id: string; /** * The size, in bytes, of the video. */ size: number; /** * The number of comments that are associated with the video. */ comments_count: number; /** * A value that indicates whether comments are enabled for the video. If * comments can be made, this value is true; otherwise, it is false. */ comments_enabled: boolean; /** * The number of tags on the video. */ tags_count: number; /** * A value that indicates whether tags are enabled for the video. If * tags can be set, this value is true; otherwise, it is false. */ tags_enabled: boolean; /** * A value that indicates whether this video can be embedded. If this * video can be embedded, this value is true; otherwise, it is false. */ is_embeddable: boolean; /** * A URL of a picture that represents the video. */ picture: string; /** * The download URL for the video. * Warning: This value is not persistent. Use it immediately after * making the request, and avoid caching. */ source: string; /** * The URL to upload video content, hosted in SkyDrive. This value is * returned only if the wl.skydrive scope is present. */ upload_location: string; /** * A URL of the video, hosted in SkyDrive. */ link: string; /** * The height, in pixels, of the video. */ height: number; /** * The width, in pixels, of the video. */ width: number; /** * The duration, in milliseconds, of the video run time. */ duration: number; /** * The bit rate, in bits per second, of the video. */ bitrate: number; /** * The type of object; in this case, "video". */ type: string; /** * The object that contains permission info. */ shared_with: ISharedWith; /** * The time, in ISO 8601 format, at which the video was created. */ created_time: string; /** * The time, in ISO 8601 format, at which the video was last updated. */ updated_time: string; } //#endregion REST Object Information //#region API Properties Interfaces /** * 'Properties' object passed into the WL.api method. */ interface IAPIProperties { /** * Contains the path to the REST API object. For information on * specifying paths for REST objects, see REST reference. * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx */ path: string; /** * An HTTP method that specifies the action required for the API call. * These actions are standard REST API actions: "COPY", "GET", "MOVE", * "PUT", "POST", and "DELETE". * @default "GET" */ method?: string | undefined; /** * A JSON object that specifies the REST API request body. The body * property is used only for "POST" and "PUT" requests. */ body?: any; } /** * 'Properties' object passed into the WL.backgroundDownload method. */ interface IBackgroundDownloadProperties { /** * The path to the file to download. For information on specifying paths * for REST objects, see REST reference. * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx */ path: string; /** * The file output object to which the downloaded file data is written. */ file_output?: Windows.Storage.StorageFile | undefined; } /** * 'Properties' object passed into the WL.backgroundUpload method. */ interface IBackgroundUploadProperties { /** * The path to the file to upload. */ path: string; /** * The name of the file to upload. */ file_name?: string | undefined; /** * The file input object to read the file from. Can be a * Windows.Storage.StorageFile or an IFile. */ file_input?: any; /** * The file input stream to read the file from. */ stream_input?: Windows.Storage.Streams.IInputStream | undefined; /** * Indicates whether the uploaded file should overwrite an existing * copy. Specify "true" to overwrite, "false" to not overwrite and for * the WL.backgroundUpload method call to fail, or "rename" to not * overwrite and enable SkyDrive to assign a new name to the uploaded * file. * @default "false". */ overwrite?: string | undefined; } /** * 'Properties' object passed into the WL.download method. */ interface IDownloadProperties { /** * The path to the file to download. For information on specifying paths * for REST objects, see REST reference. * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx */ path: string; } /** * 'Properties' object passed into the WL.fileDialog method. */ interface IFileDialogProperties { /** * Specifies the type of SkyDrive file picker to display. Specify "open" * to display the download version of the file picker. Specify "save" * to display the upload version of the file picker. */ mode: string; /** * Specify only if the mode property is set to "open". Specifies how * many files the user can select to download. Specify "single" for a * single file. Specify "multi" for multiple files. * @default "single" */ select?: string | undefined; /** * The color pallette to use for the file picker. Specify "white", * "grey", or "transparent". * @default "white" */ lightbox?: string | undefined; } /** * 'Properties' object passed into the WL.init method. */ interface IInitProperties { /** * Web apps: Required. * Specifies your app's OAuth client ID for web apps. * * Windows Store apps using JavaScript: not needed. */ client_id?: string | undefined; /** * Contains the default redirect URI to be used for OAuth * authentication. For web apps, the OAuth server redirects to this URI * during the OAuth flow. * * For Windows Store apps using JavaScript, specifying this value will * enable the library to return the authentication token. */ redirect_uri?: string | undefined; /** * The scope values used to determine which portions of user data the * app has access to, if the user consents. * * For a single scope, use this format: scope: "wl.signin". For multiple * scopes, use this format: scope: ["wl.signin", "wl.basic"]. */ scope?: any; /** * If set to "true", the library logs error info to the web browser * console and notifies your app by means of the wl.log event. * @default true */ logging?: boolean | undefined; /** * Web apps: optional. * Windows Store apps using JavaScript: not applicable. * If set to "true", the library attempts to retrieve the user's sign-in * status from Live Connect. * @default true */ status?: boolean | undefined; /** * Web apps: optional. * Windows Store apps using JavaScript: not applicable. * Specifies the OAuth response type value. If set to "token", the * client receives the access token directly. If set to "code", the * client receives an authorization code, and the app server that serves * the redirect_uri page should retrieve the access_token from the OAuth * server by using the authorization code and client secret. * * You can only set response_type to "code" for web apps. * @default "token" */ response_type?: string | undefined; /** * Web apps: optional. * Windows Store apps using JavaScript: not applicable. * If set to "true", the library specifies a secure attribute when * writing a cookie on an HTTPS page. * @default "false" */ secure_cookie?: string | undefined; } /** * 'Properties' object passed into the WL.login method. */ interface ILoginProperties { /** * This parameter only applies to web apps. * Contains the redirect URI to be used for OAuth authentication. This * value overrides the default redirect URI that is provided in the call * to WL.init. */ redirect_uri?: string | undefined; /** * Specifies the scopes to which the user who is signing in consents. * * For a single scope, use this format: scope: "wl.signin". For multiple * scopes, use this format: scope: ["wl.signin", "wl.basic"]. * * If no scope is provided, the scope value of WL.init is used. If no * scope is provided in WL.init or WL.login, WL.login returns an error. * * Note WL.login can request the "wl.offline_access" scope, but it * requires a server-side implementation, and the WL.init function must * set its response_type property to "code". For more info, see * Server-side scenarios. * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx */ scope: any; /** * Windows Store apps using JavaScript: not applicable. * Web apps: Optional. If the WL.init function's response_type object is * set to "code" and the app uses server-flow authentication, the state * object here can be used to track the web app's calling state on the * web app server side. For more info, see the description of the state * query parameter in the Server-side scenarios topic's "Getting an * authorization code" section. * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx */ state?: string | undefined; } /** * 'Properties' object passed into the WL.ui method. */ interface IUIProperties { /** * Specifies the type of button to display. Specify "signin" to display * the Live Connect sign-in button. Specify "skydrivepicker" to display * the SkyDrive button. */ name: string; /** * The value of the id attribute of the <div> tag to display the button * in. */ element: string; /** * Windows Store apps using JavaScript: not applicable. * Web apps: Optional. If the name property is set to "signin", the * WL.init function's response_type property is set to "code", and the * app uses server-flow authentication, the state object here can be * used to track the web app's calling state on the web app server side. * For more info, see the description of the state query parameter in * the Server-side scenarios topic's "Getting an authorization code" * section. * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx */ state?: string | undefined; } /** * 'Properties' object passed into the WL.ui method when 'name' is set to * 'skydrivepicker'. */ interface ISkyDrivePickerProperies extends IUIProperties { /** * The type of SkyDrive file picker button to display. Specify "save" to * display the upload button. Specify "open" to display the download * button. */ mode: string; /** * Required if the mode property is set to "open". Specifies how many * files the user can select to download. Specify "single" for a single * file. Specify "multi" for multiple files. * @default "single" */ select?: string | undefined; /** * Defines the color pallette used for the file picker button. Valid * values are "white" and "blue". * @default "white" */ theme?: string | undefined; /** * Defines the color pallette used for the file picker dialog box. Valid * values are "white", "gray", and "transparent". * @default "white" */ lightbox?: string | undefined; /** * If the mode property is set to "save", specifies the function to call * after the user clicks either Save or Cancel in the file picker. If * the mode property is set to "open", specifies the function to call * after the user clicks either Open or Cancel in the file picker. */ onselected?: Function | undefined; /** * Specifies the function to call if the selected files cannot be * successfully uploaded or downloaded. */ onerror?: Function | undefined; } /** * 'Properties' object passed into the WL.ui method when 'name' is set to * 'signin'. */ interface ISignInProperties extends IUIProperties { /** * Defines the brand, or type of icon, to be used with the Live Connect * sign-in button. * @default "windows" */ brand?: string | undefined; /** * Defines the color pallette used for the sign-in button. For Windows * Store apps using JavaScript, valid values are "dark" and "light". * For web apps, valid values are "blue" and "white". */ theme?: string | undefined; /** * Defines the type of button. * @default "signin" */ type?: string | undefined; /** * If the value of the type property is set to "custom", this value * specifies the sign-in text to be displayed in the button. */ sign_in_text?: string | undefined; /** * If the value of the type property is "custom", this value specifies * the sign-out text to be displayed in the button. */ sign_out_text?: string | undefined; /** * Specifies the function to call after the user completes the sign-in * process. */ onloggedin?: Function | undefined; /** * Specifies the function to call after the user completes the sign-out * process. */ onloggedout?: Function | undefined; /** * Specifies the function to call whenever there is any error while the * sign-in control is initializing or while the user is signing in. */ onerror?: Function | undefined; } /** * 'Properties' object passed into the WL.upload method. */ interface IUploadProperties { /** * The path to the file to upload. */ path: string; /** * The id attribute of the <input> tag containing info about the file to * upload. */ element: string; /** * Indicates whether the uploaded file should overwrite an existing * copy. Specify true or "true" to overwrite, false or "false" to not * overwrite and for the WL.upload method call to fail, or "rename" to * not overwrite and enable SkyDrive to assign a new name to the * uploaded file. * @default "false" */ overwrite?: string | undefined; } //#endregion API Properties Interfaces /** * Represents the user's session. */ interface ISession { /** * The user's access token. */ access_token: string; /** * The authentication token. */ authentication_token: string; /** * A list of scopes that the app has requested and that the user has * consented to. * * Note: This property is not available for Windows Store apps using * JavaScript. */ scope?: string[] | undefined; /** * The amount of time remaining, in seconds, until the user's access * token expires. * * Note: This property is not available for Windows Store apps using * JavaScript. */ expires_in?: number | undefined; /** * The exact time when the session will expire. This time is expressed * in the number of seconds since 1 January, 1970. * * Note: This property is not available for Windows Store apps using * JavaScript. */ expires?: number | undefined; } /** * Represents the user's login status. */ interface ILoginStatus { /** * The sign-in status of the user. Valid values are "connected", * "notConnected", or "unknown". */ status: string; /** * A JSON object that contains the properties of the current session. */ session: ISession; } /** * Represents the Microsoft.Live.API.Event object. */ interface IEventAPI { /** * Adds a handler to an event. * @param event Required. The name of the event to which to add a * handler. * @param callback Required. Specifies the name of the callback function * to handle the event. * @returns This function can return the following errors: * WL.Event.subscribe: The input parameter/property 'callback' must be * included. * WL.Event.subscribe: The input value for parameter/property 'event' * is not valid. */ subscribe(event: string, callback: Function): void; /** * Removes a handler from an event. * @param event Required. The name of the event from which to remove a * handler. * @param callback Optional. Removes the callback function from the * event. If this parameter is omitted or is null, all callback * functions that are registered to the event are removed. Removes the * callback function from the specified event. */ unsubscribe(event: string, callback?: Function): void; } /** * Returned from a successful file picker operation. */ interface IFilePickerResult { /** * Contains data concerning the user's picked files. */ data: { /** * Information on files choden in the picker. */ files?: IFile[] | undefined; /** * Information on folders chosen in the picker. */ folders?: IFolder[] | undefined; } } /** * The promise API implemented by this library. */ interface IPromise<T> { /** * Adds event listeners for particular events. * @param onSuccess Called when the promised event successfully occurs. * @param onError Called when the promised event fails to occur. Could * be an IError or an IJSError. * @param onProgress Called to indicate that the promised event is * making progress toward completion. */ then(onSuccess: (response: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise<T>; /** * Cancels the pending request represented by the Promise, and triggers * the error callback if the promised event has not yet occurred. */ cancel(): void; } /** * An error returned by the JavaScript library, as opposed to an error * object from the REST API (which we represent with IError). */ interface IJSError { /** * The error code. */ error: string; /** * A description of the error. */ error_description: string; } /** * The Live Connect JavaScript API (Windows 8 and web), together with the * REST API, enables apps to read, update, and share user data by using the * JavaScript programming language. The JavaScript API (Windows 8 and web) * provides methods for signing users in and out, getting user status, * subscribing to events, creating UI controls, and calling the * Representational State Transfer (REST) API. */ interface API { /** * Makes a call to the Live Connect Representational State Transfer * (REST) API. This method encapsulates a REST API request, and then * calls a callback function to process the response. * @param properties Required. A JSON object that contains properties * that are necessary to make the REST API call. * @param callback Specifies a callback function that is executed when * the REST API call is complete. The callback function takes the API * response object as a parameter. The response object exposes the * data returned from Live Connect, or, if an error occurs, an error * property that contains the error code. * @returns Returns a Promise object. This object's then method provides * the onSuccess, onError, and onProgress parameters to enable your * code to handle a successful, failed, and in-progress call to the * corresponding WL.api method, respectively. */ api<T>(properties: IAPIProperties, callback?: (response: any) => void): IPromise<T>; /** * Makes a call to download a file from Microsoft SkyDrive. * * **Important**: WL.backgroundDownload is supported only for use with * Windows Store apps using JavaScript. If you are writing a web app, * use WL.download instead. * @param properties Required. A JSON object that contains properties * that are necessary to make the REST API call. * @param Optional. Specifies a callback function that is executed when * the REST API call is complete. The callback function takes the API * response object as a parameter. The response object exposes the * data that is returned from Live Connect, or, if an error occurs, an * error property that contains the error code. * @returns Returns a Promise object. This object's then method accepts * callback functions for onSuccess, onError, and onProgress to enable * your code to handle a successful, failed, and in-progress call to * the corresponding WL.download method, respectively. * The onSuccess callback is passed a response object that contains * content_type and stream properties, representing the downloaded * file's content type and file stream, respectively. */ backgroundDownload<T>(properties: IBackgroundDownloadProperties, callback?: (response: any) => void): IPromise<T>; /** * Makes a call to upload a file to Microsoft SkyDrive. * * **Important**: WL.backgroundUpload is supported only for use with * Windows Store apps using JavaScript. If you are writing a web app, * use WL.upload instead. * @param properties Required. A JSON object that contains properties * that are necessary to make the REST API call. * @param callback Optional. Specifies a callback function that is * executed when the REST API call is complete. The callback function * takes the API response object as a parameter. The response object * exposes the data returned from Live Connect, or if an error occurs, * an error property that contains the error code. * @returns Returns a Promise object. For Windows Store apps using * JavaScript, this object's then method accepts callback functions * for onSuccess, onError, and onProgress to enable your code to * handle a successful, failed, and in-progress call to the * corresponding WL.backgroudUpload method, respectively. */ backgroundUpload<T>(properties: IBackgroundUploadProperties, callback?: (response: any) => void): IPromise<T>; /** * Specifies whether the current user can be signed out of their * Microsoft account. * * For Windows Store apps using JavaScript, you can use this function to * determine whether you should display a control to the user to enable * them to sign out of their Microsoft account. If this * function returns true, you should display the control. However, if * this function returns false, you should not display this control, as * attempting to sign out the user in this case will have no effect. * * For web apps, this function always returns true. * @returns Returns true if the user can be signed out; otherwise, * returns false if the user can't be signed out. */ canLogout(): boolean; /** * Makes a call to download a file from Microsoft SkyDrive. * * **Important**: WL.download is supported only for use with web apps. * If you are writing a Windows Store app using JavaScript, use * WL.backgroundDownload instead. * @param properties Required. A JSON object that contains properties * that are necessary to make the REST API call. * @param callback Specifies a callback function that is executed when * the REST API call is complete. The callback function takes the API * response object as a parameter. The response object exposes the * data that is returned from Live Connect, or, if an error occurs, an * error property that contains the error code. * @returns Returns a Promise object. This object's then method provides * the onError parameter to enable your code to handle a failed call * to the corresponding WL.download method. */ download(properties: IDownloadProperties, callback?: (response: any) => void): IPromise<void>; Event: IEventAPI; /** * Displays the Microsoft SkyDrive file picker, which enables * JavaScript-based web apps to display a pre-built, consistent user * interface that enables a user to select files to upload and download * to and from their SkyDrive storage location. * @param properties Required. A JSON object containing properties for * displaying the button. * @param callback Optional. A callback function that is executed after * the user finishes interacting with the SkyDrive file picker. * @returns Returns a Promise object. This object's then method provides * the onSuccess and onError parameters to enable your code to handle * a successful and failed call to the corresponding WL.fileDialog * method, respectively. */ fileDialog(properties: IFileDialogProperties, callback?: (response: any) => void): IPromise<IFilePickerResult>; /** * Returns the sign-in status of the current user. If the user is signed * in and connected to your app, this function returns the session * object. This is an asynchronous function that returns the user's * status by contacting the Live Connect authentication web service. * @param callback Returns the sign-in status of the current user. If * the user is signed in and connected to your app, this function * returns the session object. This is an asynchronous function that * returns the user's status by contacting the Live Connect * authentication web service. * @param force Optional. If set to "true", the function contacts the * Live Connect authentication web service to determine the user's * status. If set to "false" (the default), the function can return * the user status that is currently in memory, if there is one. If * the user's status has already been retrieved, the library can * return the cached value. However, you can force the library to * retrieve current status by setting the force parameter to "true". * @returns Returns a Promise object. This object's then method provides * the onSuccess and onError parameters to enable your code to handle * a successful and failed call to the corresponding WL.getLoginStatus * method, respectively. * In the body of the onSuccess function, a status object is returned, * which contains the user's sign-in status and the session object. */ getLoginStatus(callback?: (status: ILoginStatus) => void, force?: boolean): IPromise<ILoginStatus>; /** * Retrieves the current session object synchronously, if a session * object exists. For situations in which performance is critical, such * as page loads, use the asynchronous WL.getLoginStatus method instead. * @returns Returns the current session as a session object instance. */ getSession(): ISession; /** * Initializes the JavaScript library. An app must call this function on * every page before making other function calls in the library. The app * should call this function before making function calls that subscribe * to events. If the JavaScript library has already been initialized on * the page, calling this function succeeds silently; the client_id and * redirect_uri parameters are not validated. * @param properties Required. A JSON object with initialization * properties. * @returns Returns a Promise object. This object's then method provides * the onSuccess and onError parameters to enable your code to handle * a successful and failed call to the corresponding WL.init method, * respectively. * When the onSuccess callback is invoked, a login status object is * passed in as parameter that indicates the current user's login * status. */ init(properties: IInitProperties): IPromise<ILoginStatus>; /** * Signs in the user or expands the user's list of scopes. Because this * function can result in launching the consent page prompt, you should * call it only in response to a user action, such as clicking a button. * Otherwise, the user's web browser might block the popup. * * Typically, this function is used by apps that define their own * sign-in controls, or by apps that ask users to grant additional * permissions during an activity. For example, to enable a user to post * their status to Live Connect, your app may have to prompt the * user for permission and call this function with an expanded scope. * * If you call this function when the user has already consented to the * requested scope and is already signed in, the callback function is * invoked immediately with the current session. * This function logs errors to the web browser console. * @param properties Required. A JSON object with login properties. * @param callback Optional. Specifies a callback function to execute * when sign-in is complete. The callback function takes the status * object as a parameter. For a description of the status object, see * WL.getLoginStatus. If you do not specify a callback function, your * app can still get the sign-in callback info by listening for an * auth.sessionChange or auth.statusChange event. * @returns Returns a Promise object. This object's then method provides * the onSuccess, onError, and onProgress parameters to enable your * code to handle a successful, failed, and in-progress call to the * corresponding WL.login method, respectively. */ login(properties: ILoginProperties, callback?: (status: any) => void): IPromise<ILoginStatus>; /** * Signs the user out of Live Connect and clears any user state that is * maintained by the JavaScript library, such as cookies. If the user * account is connected, this function logs out the user from the app, * but not from the PC. This function is useful primarily for websites * that do not use the sign-in control. * @param callback Optional. Specifies a callback function that is * executed when sign-out is complete. The callback function takes the * status object as a parameter. For a description of the status * object, see WL.getLoginStatus. If you do not specify a callback * function, your app can still get the sign-out callback info by * listening for an auth.sessionChange or auth.statusChange event. * @returns Returns a Promise object. This object's then method provides * the onSuccess, onError, and onProgress parameters to enable your * code to handle a successful, failed, and in-progress call to the * corresponding WL.logout method, respectively. */ logout(callback?: (status: ILoginStatus) => void): IPromise<ILoginStatus>; /** * Displays either the Live Connect sign-in button or the Microsoft * SkyDrive file picker button. The sign-in button either prompts the * user for their Microsoft account credentials if they are not * signed in or else signs out the user if they are signed in. The * file picker button displays the SkyDrive file picker to help the user * select files to upload or download to or from their SkyDrive * storage location. * @param properties Required. A JSON object containing properties for * displaying the button. * @param callback Optional. A callback function that is executed after * the sign-in button or file picker button is displayed. * Note: Do not use the callback parameter to run code after the user * finishes interacting with the sign-in button or file picker. Use a * combination of the onselected, onloggedin, onloggedout, and onerror * properties as previously described. */ ui(properties: IUIProperties, callback?: () => void): void; /** * Makes a call to upload a file to Microsoft SkyDrive. * * **Important**: WL.upload is supported only for use with web apps. If * you are writing a Windows Store app using JavaScript, use * WL.backgroundUpload instead. * @param properties Required. A JSON object that contains properties * that are necessary to make the REST API call. * @param callback Optional. Specifies a callback function that is * executed when the REST API call is complete. The callback function * takes the API response object as a parameter. The response object * exposes the data returned from Live Connect, or if an error occurs, * an error property that contains the error code. * @returns Returns a Promise object. This object's then method provides * the onSuccess, onError, and onProgress parameters to enable your * code to handle a successful, failed, and in-progress call to the * corresponding WL.upload method, respectively; however, the * onProgress parameter applies to newer web browsers such as Internet * Explorer 10 only. */ upload<T>(properties: IUploadProperties, callback?: (response: any) => void): IPromise<T>; } } /** * The WL object is a global object that encapsulates all functions of the * JavaScript API (Windows 8 and web). Your app uses the WL object to call all * of the JavaScript API (Windows 8 and web) functions. */ declare var WL: Microsoft.Live.API;
the_stack
import chalk from "chalk" import { existsSync } from "fs" import path, { basename, relative } from "path" import { performance } from "perf_hooks" import Shellwords from "shellwords-ts" import { ChangeType, needsBuild } from "./build" import { CommandFormatter } from "./formatter" import { defaults, RunnerOptions } from "./options" import { PackageJson, findUp, getPackage } from "./package" import { Command, CommandParser, CommandType } from "./parser" import { Spawner } from "./spawn" import { OutputSpinner, Spinner } from "./spinner" import { getWorkspace, Workspace } from "./workspace" import { WorkspaceProviderType } from "./workspace.providers" import { createCommand } from "./concurrency" export class Runner { spinner = new OutputSpinner() options: RunnerOptions workspace?: Workspace buildCmd = "build" constructor(public _options: Partial<RunnerOptions> = {}) { this.options = { ...defaults, ..._options } } formatStart(cmd: Command, level: number, parentSpinner?: Spinner) { if (this.options.raw) return const title = this.formatCommand(cmd) if (!this.options.pretty) { const prefix = cmd.packageName ? `${chalk.grey.dim(` (${cmd.packageName})`)}` : "" if (cmd.type == CommandType.script) console.log(`โฏ ${title}${prefix}`) else console.log(title + prefix) } else return this.spinner.start(title, level, parentSpinner) } // TODO: refactor the method below. Move to its own class async runCommand(cmd: Command, level = -2, parentSpinner?: Spinner) { if (cmd.type == CommandType.op) return const isBuildScript = cmd.type == CommandType.script && cmd.name == this.buildCmd const changes = isBuildScript ? await needsBuild( cmd.cwd || process.cwd(), this.workspace, this.options.rebuild ) : undefined await cmd.beforeRun() let spinner: Spinner | undefined if (cmd.type == CommandType.script) { if (level >= 0) spinner = this.formatStart(cmd, level, parentSpinner) } else { if (cmd.args.length) { const args = Shellwords.split(cmd.args.join(" ")) if (cmd.bin) args[0] = cmd.bin const cmdSpinner = this.formatStart(cmd, level, parentSpinner) try { if (!this.options.dryRun) { const formatter = new CommandFormatter( args[0], level, cmdSpinner, this.options, cmd.packageName ) await this.spawn( args[0], args.slice(1), formatter, cmd.cwd, cmd.env ) } if (cmdSpinner) { if (/warning/iu.test(cmdSpinner.output)) this.spinner.warning(cmdSpinner) else this.spinner.success(cmdSpinner) } } catch (error) { if (cmdSpinner) this.spinner.error(cmdSpinner) throw error } } } const formatter = new CommandFormatter( cmd.name, level, spinner, this.options, cmd.packageName ) if (isBuildScript) { if (!changes) formatter.write("No changes. Skipping build...") else if (!changes.isGitRepo) { formatter.write( `${chalk.red( "warning " )}Not a Git repository, so build change detection is disabled. Forcing full rebuild.` ) } else { formatter.write( chalk.blue("changes:\n") + changes.changes .map((c) => { let str = " " if (c.type == ChangeType.added) str += chalk.green("+") else if (c.type == ChangeType.deleted) str += chalk.red("-") else if (c.type == ChangeType.modified) str += chalk.green("+") return `${str} ${c.file}` }) .join("\n") ) // formatter.write(chalk.red("\nWaiting for\n")) } } try { if (!isBuildScript || changes) { const promises = [] for (const child of cmd.children) { if (child.isPostScript()) await Promise.all(promises) const promise = this.runCommand(child, level + 1, spinner) promises.push(promise) if (!cmd.concurrent || child.isPreScript()) await promise else if (promises.length >= this.options.concurrency) { await Promise.all(promises) promises.length = 0 } } if (cmd.concurrent) await Promise.all(promises) } spinner && this.spinner.success(spinner) cmd.afterRun() if (changes) await changes.onBuild() } catch (error) { if (spinner) this.spinner.error(spinner) throw error } } formatCommand(cmd: Command) { if (cmd.type == CommandType.script) return chalk.white.bold(`${cmd.name}`) return `${chalk.grey(`$ ${cmd.args[0]}`)} ${cmd.args .slice(1) .map((x) => { if (x.startsWith("-")) return chalk.cyan(x) if (existsSync(x)) return chalk.magenta(x) if (x.includes("*")) return chalk.yellow(x) return x }) .join(" ")}` } // cached pnpFile location private pnpFile: string | undefined findPnpJsFile(cwd: string = process.cwd()): string | undefined { if (this.pnpFile) { return this.pnpFile } const dir1 = findUp(".pnp.js", cwd) if (dir1) { this.pnpFile = path.resolve(dir1, ".pnp.js") } const dir2 = findUp(".pnp.cjs", cwd) if (dir2) { this.pnpFile = path.resolve(dir2, ".pnp.cjs") } return this.pnpFile } spawn( cmd: string, args: string[], formatter: CommandFormatter, cwd?: string, env?: Record<string, string> ) { // Special handling for yarn pnp binaries if (cmd.startsWith("yarn:")) { cmd = cmd.slice(5) const pnpFile = this.findPnpJsFile(cwd) if (!pnpFile) { throw new Error(`cannot find .pnp.js file`) } args = ["-r", pnpFile, cmd, ...args] // will fail with non js binaries, but yarn PnP already does not support them https://github.com/yarnpkg/berry/issues/882 cmd = "node" } const spawner = new Spawner(cmd, args, cwd, env) if (this.options.pretty) spawner.onData = (line: string) => formatter.write(line) else spawner.onLine = (line: string) => formatter.write(line) spawner.onError = (err: Error) => new Error( `${chalk.red("error")} Command ${chalk.white.dim( basename(cmd) )} failed with ${chalk.red(err)}. Is the command on your path?` ) spawner.onExit = (code: number) => new Error( `${this.options.silent ? formatter.output : ""}\n${chalk.red( "error" )} Command ${chalk.white.dim( basename(cmd) )} failed with exit code ${chalk.red(code)}` ) return spawner.spawn(this.options.raw) } formatDuration(duration: number) { if (duration < 1) return `${(duration * 1000).toFixed(0)}ms` return `${duration.toFixed(3)}s` } async list() { const workspace = await getWorkspace({ includeRoot: this.options.root, type: this.options.recursive ? undefined : WorkspaceProviderType.single, }) if (!workspace) throw new Error("Cannot find package.json") let counter = 0 workspace?.getPackages(this.options.filter).forEach((p) => { console.log( `${chalk.bgGray.cyanBright(` ${counter++} `)} ${chalk.green( `${p.name}` )} at ${chalk.whiteBright(relative(workspace.root, p.root))}` ) Object.keys(p.scripts || {}) .sort() .forEach((s) => { console.log(` โฏ ${chalk.grey(s)}`) }) }) } async run(cmd: string, pkg?: PackageJson) { if (!pkg) { const root = findUp("package.json") if (root) pkg = getPackage(root) } if (!pkg) pkg = { name: "" } if (pkg) { const parser = new CommandParser(pkg) return await this._run(parser.parse(cmd)) } throw new Error(`Could not find package`) } async info() { const types = await Workspace.detectWorkspaceProviders() if (!types.length) throw new Error("No workspaces found") if (types.length > 1) console.log( chalk.blue("Detected workspaces: ") + chalk.magenta(types.join(", ")) ) const workspace = await getWorkspace({ includeRoot: true }) if (workspace) { console.log( `${ chalk.blue("Workspace ") + chalk.magenta(workspace.type) } with ${chalk.magenta(workspace.getPackageManager())}` ) let counter = 0 workspace.getPackages(this.options.filter).forEach((p) => { let at = relative(workspace.root, p.root) if (!at.length) at = "." console.log( `${chalk.bgGray.cyanBright(` ${counter++} `)} ${chalk.green( `${p.name}` )} at ${chalk.whiteBright(at)}` ) workspace.getDeps(p.name).forEach((s) => { console.log(` โฏ ${chalk.grey(s)}`) }) }) } } deps = new Map<string | undefined, Promise<void>>() async runRecursive(cmd: string) { this.workspace = await getWorkspace({ includeRoot: this.options.root }) const workspace = this.workspace if (this.options.build) this.buildCmd = cmd if (!workspace || !workspace?.packages?.size) throw new Error( "Could not find packages in your workspace. Supported: yarn, pnpm, lerna" ) const command = createCommand(workspace, cmd, this.options) return await this._run(command, -1) } async _run(command: Command, level = -1) { try { await this.runCommand(command, level) this.spinner._stop() if (!this.options.silent) { console.log( chalk.green("success"), "โœจ", this.options.dryRun ? "Dry-run done" : "Done", `in ${this.formatDuration(performance.nodeTiming.duration / 1000)}` ) } } finally { this.spinner._stop() } } }
the_stack
import * as PropTypes from "prop-types"; import * as React from "react"; import { functor, identity } from "./utils"; import { ICanvasContexts } from "./CanvasContainer"; const aliases = { mouseleave: "mousemove", // to draw interactive after mouse exit panend: "pan", pinchzoom: "pan", mousedown: "mousemove", click: "mousemove", contextmenu: "mousemove", dblclick: "mousemove", dragstart: "drag", dragend: "drag", dragcancel: "drag", zoom: "zoom", }; interface GenericComponentProps { readonly svgDraw?: (moreProps: any) => React.ReactNode; readonly canvasDraw?: (ctx: CanvasRenderingContext2D, moreProps: any) => void; readonly canvasToDraw?: (contexts: ICanvasContexts) => CanvasRenderingContext2D | undefined; readonly clip?: boolean; readonly disablePan?: boolean; readonly drawOn: string[]; readonly edgeClip?: boolean; readonly enableDragOnHover?: boolean; readonly interactiveCursorClass?: string; readonly isHover?: (moreProps: any, e: React.MouseEvent) => boolean; readonly onClick?: (e: React.MouseEvent, moreProps: any) => void; readonly onClickWhenHover?: (e: React.MouseEvent, moreProps: any) => void; readonly onClickOutside?: (e: React.MouseEvent, moreProps: any) => void; readonly onPan?: (e: React.MouseEvent, moreProps: any) => void; readonly onPanEnd?: (e: React.MouseEvent, moreProps: any) => void; readonly onDragStart?: (e: React.MouseEvent, moreProps: any) => void; readonly onDrag?: (e: React.MouseEvent, moreProps: any) => void; readonly onDragComplete?: (e: React.MouseEvent, moreProps: any) => void; readonly onDoubleClick?: (e: React.MouseEvent, moreProps: any) => void; readonly onDoubleClickWhenHover?: (e: React.MouseEvent, moreProps: any) => void; readonly onContextMenu?: (e: React.MouseEvent, moreProps: any) => void; readonly onContextMenuWhenHover?: (e: React.MouseEvent, moreProps: any) => void; readonly onMouseMove?: (e: React.MouseEvent, moreProps: any) => void; readonly onMouseDown?: (e: React.MouseEvent, moreProps: any) => void; readonly onHover?: (e: React.MouseEvent, moreProps: any) => void; readonly onUnHover?: (e: React.MouseEvent, moreProps: any) => void; readonly selected?: boolean; } interface GenericComponentState { updateCount: number; } export class GenericComponent extends React.Component<GenericComponentProps, GenericComponentState> { public static defaultProps = { svgDraw: functor(null), draw: [], canvasToDraw: (contexts: ICanvasContexts) => contexts.mouseCoord, clip: true, edgeClip: false, selected: false, disablePan: false, enableDragOnHover: false, }; public static contextTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, margin: PropTypes.object.isRequired, chartId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), getCanvasContexts: PropTypes.func, xScale: PropTypes.func.isRequired, xAccessor: PropTypes.func.isRequired, displayXAccessor: PropTypes.func.isRequired, plotData: PropTypes.array.isRequired, fullData: PropTypes.array.isRequired, chartConfig: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired, morePropsDecorator: PropTypes.func, generateSubscriptionId: PropTypes.func, getMutableState: PropTypes.func.isRequired, amIOnTop: PropTypes.func.isRequired, subscribe: PropTypes.func.isRequired, unsubscribe: PropTypes.func.isRequired, setCursorClass: PropTypes.func.isRequired, }; public moreProps: any = {}; private dragInProgress = false; private evaluationInProgress = false; private iSetTheCursorClass = false; private suscriberId: number; public constructor(props: GenericComponentProps, context: any) { super(props, context); this.drawOnCanvas = this.drawOnCanvas.bind(this); this.getMoreProps = this.getMoreProps.bind(this); this.draw = this.draw.bind(this); this.updateMoreProps = this.updateMoreProps.bind(this); this.evaluateType = this.evaluateType.bind(this); this.isHover = this.isHover.bind(this); this.preCanvasDraw = this.preCanvasDraw.bind(this); this.postCanvasDraw = this.postCanvasDraw.bind(this); this.getPanConditions = this.getPanConditions.bind(this); this.shouldTypeProceed = this.shouldTypeProceed.bind(this); this.preEvaluate = this.preEvaluate.bind(this); const { generateSubscriptionId } = context; this.suscriberId = generateSubscriptionId(); this.state = { updateCount: 0, }; } public updateMoreProps(moreProps: any) { Object.keys(moreProps).forEach((key) => { this.moreProps[key] = moreProps[key]; }); } public shouldTypeProceed(type: string, moreProps: any) { return true; } public preEvaluate(type: string, moreProps: any, e: any) { /// empty } public listener = (type: string, moreProps: any, state: any, e: any) => { if (moreProps !== undefined) { this.updateMoreProps(moreProps); } this.evaluationInProgress = true; this.evaluateType(type, e); this.evaluationInProgress = false; }; public evaluateType(type: string, e: any) { // @ts-ignore const newType = aliases[type] || type; const proceed = this.props.drawOn.indexOf(newType) > -1; if (!proceed) { return; } this.preEvaluate(type, this.moreProps, e); if (!this.shouldTypeProceed(type, this.moreProps)) { return; } switch (type) { case "zoom": case "mouseenter": // DO NOT DRAW FOR THESE EVENTS break; case "mouseleave": { this.moreProps.hovering = false; if (this.props.onUnHover) { this.props.onUnHover(e, this.getMoreProps()); } break; } case "contextmenu": { if (this.props.onContextMenu) { this.props.onContextMenu(e, this.getMoreProps()); } if (this.moreProps.hovering && this.props.onContextMenuWhenHover) { this.props.onContextMenuWhenHover(e, this.getMoreProps()); } break; } case "mousedown": { if (this.props.onMouseDown) { this.props.onMouseDown(e, this.getMoreProps()); } break; } case "click": { const { onClick, onClickOutside, onClickWhenHover } = this.props; const moreProps = this.getMoreProps(); if (moreProps.hovering && onClickWhenHover !== undefined) { onClickWhenHover(e, moreProps); } else if (onClickOutside !== undefined) { onClickOutside(e, moreProps); } if (onClick !== undefined) { onClick(e, moreProps); } break; } case "mousemove": { const prevHover = this.moreProps.hovering; this.moreProps.hovering = this.isHover(e); const { amIOnTop, setCursorClass } = this.context; if ( this.moreProps.hovering && !this.props.selected && /* && !prevHover */ amIOnTop(this.suscriberId) && this.props.onHover !== undefined ) { setCursorClass("react-financial-charts-pointer-cursor"); this.iSetTheCursorClass = true; } else if (this.moreProps.hovering && this.props.selected && amIOnTop(this.suscriberId)) { setCursorClass(this.props.interactiveCursorClass); this.iSetTheCursorClass = true; } else if (prevHover && !this.moreProps.hovering && this.iSetTheCursorClass) { this.iSetTheCursorClass = false; setCursorClass(null); } const moreProps = this.getMoreProps(); if (this.moreProps.hovering && !prevHover) { if (this.props.onHover) { this.props.onHover(e, moreProps); } } if (prevHover && !this.moreProps.hovering) { if (this.props.onUnHover) { this.props.onUnHover(e, moreProps); } } if (this.props.onMouseMove) { this.props.onMouseMove(e, moreProps); } break; } case "dblclick": { const moreProps = this.getMoreProps(); if (this.props.onDoubleClick) { this.props.onDoubleClick(e, moreProps); } if (this.moreProps.hovering && this.props.onDoubleClickWhenHover) { this.props.onDoubleClickWhenHover(e, moreProps); } break; } case "pan": { this.moreProps.hovering = false; if (this.props.onPan) { this.props.onPan(e, this.getMoreProps()); } break; } case "panend": { if (this.props.onPanEnd) { this.props.onPanEnd(e, this.getMoreProps()); } break; } case "dragstart": { if (this.getPanConditions().draggable) { const { amIOnTop } = this.context; if (amIOnTop(this.suscriberId)) { this.dragInProgress = true; if (this.props.onDragStart !== undefined) { this.props.onDragStart(e, this.getMoreProps()); } } } break; } case "drag": { if (this.dragInProgress && this.props.onDrag) { this.props.onDrag(e, this.getMoreProps()); } break; } case "dragend": { if (this.dragInProgress && this.props.onDragComplete) { this.props.onDragComplete(e, this.getMoreProps()); } this.dragInProgress = false; break; } case "dragcancel": { if (this.dragInProgress || this.iSetTheCursorClass) { const { setCursorClass } = this.context; setCursorClass(null); } break; } } } public isHover(e: React.MouseEvent) { const { isHover } = this.props; if (isHover === undefined) { return false; } return isHover(this.getMoreProps(), e); } public getPanConditions() { const draggable = !!(this.props.selected && this.moreProps.hovering) || (this.props.enableDragOnHover && this.moreProps.hovering); return { draggable, panEnabled: !this.props.disablePan, }; } // @ts-ignore public draw({ trigger, force }: { force: boolean; trigger: string } = { force: false }) { // @ts-ignore const type = aliases[trigger] || trigger; const proceed = this.props.drawOn.indexOf(type) > -1; if (proceed || this.props.selected /* this is to draw as soon as you select */ || force) { const { canvasDraw } = this.props; if (canvasDraw === undefined) { const { updateCount } = this.state; this.setState({ updateCount: updateCount + 1, }); } else { this.drawOnCanvas(); } } } public UNSAFE_componentWillMount() { const { subscribe, chartId } = this.context; const { clip, edgeClip } = this.props; subscribe(this.suscriberId, { chartId, clip, edgeClip, listener: this.listener, draw: this.draw, getPanConditions: this.getPanConditions, }); this.UNSAFE_componentWillReceiveProps(this.props, this.context); } public componentWillUnmount() { const { unsubscribe } = this.context; unsubscribe(this.suscriberId); if (this.iSetTheCursorClass) { const { setCursorClass } = this.context; setCursorClass(null); } } public componentDidMount() { this.componentDidUpdate(this.props); } public componentDidUpdate(prevProps: GenericComponentProps) { const { canvasDraw, selected, interactiveCursorClass } = this.props; if (prevProps.selected !== selected) { const { setCursorClass } = this.context; if (selected && this.moreProps.hovering) { this.iSetTheCursorClass = true; setCursorClass(interactiveCursorClass); } else { this.iSetTheCursorClass = false; setCursorClass(null); } } if (canvasDraw !== undefined && !this.evaluationInProgress) { this.updateMoreProps(this.moreProps); this.drawOnCanvas(); } } public UNSAFE_componentWillReceiveProps(nextProps: GenericComponentProps, nextContext: any) { const { xScale, plotData, chartConfig, getMutableState } = nextContext; this.moreProps = { ...this.moreProps, ...getMutableState(), /* ^ this is so mouseXY, currentCharts, currentItem are available to newly created components like MouseHoverText which is created right after a new interactive object is drawn */ xScale, plotData, chartConfig, }; } public getMoreProps() { const { xScale, plotData, chartConfig, morePropsDecorator, xAccessor, displayXAccessor, width, height, } = this.context; const { chartId, fullData } = this.context; const moreProps = { xScale, plotData, chartConfig, xAccessor, displayXAccessor, width, height, chartId, fullData, ...this.moreProps, }; return (morePropsDecorator || identity)(moreProps); } public preCanvasDraw(ctx: CanvasRenderingContext2D, moreProps: any) { // do nothing } public postCanvasDraw(ctx: CanvasRenderingContext2D, moreProps: any) { // empty } public drawOnCanvas() { const { canvasDraw, canvasToDraw } = this.props; if (canvasDraw === undefined || canvasToDraw === undefined) { return; } const { getCanvasContexts } = this.context; const moreProps = this.getMoreProps(); const contexts = getCanvasContexts(); const ctx = canvasToDraw(contexts); if (ctx !== undefined) { this.preCanvasDraw(ctx, moreProps); canvasDraw(ctx, moreProps); this.postCanvasDraw(ctx, moreProps); } } public render() { const { canvasDraw, clip, svgDraw } = this.props; if (canvasDraw !== undefined || svgDraw === undefined) { return null; } const { chartId } = this.context; const suffix = chartId !== undefined ? "-" + chartId : ""; const style = clip ? { clipPath: `url(#chart-area-clip${suffix})` } : undefined; return <g style={style}>{svgDraw(this.getMoreProps())}</g>; } } export const getAxisCanvas = (contexts: ICanvasContexts) => { return contexts.axes; }; export const getMouseCanvas = (contexts: ICanvasContexts) => { return contexts.mouseCoord; };
the_stack
import {BigAmount, CreateAmount} from '@emeraldpay/bigamount'; import { amountDecoder, amountFactory, BalanceUtxo, BlockchainCode, blockchainCodeToId, blockchainIdToCode, CurrencyAmount, isBitcoin, isEthereum } from '@emeraldwallet/core'; import {registry} from '@emeraldwallet/erc20'; import {createSelector} from 'reselect'; import {settings, tokens} from '../index'; import {IState} from '../types'; import {BalanceValueConverted, IBalanceValue, moduleName} from './types'; import * as accounts from "./index"; import { EntryId, EntryIdOp, EthereumEntry, isBitcoinEntry, isEthereumEntry, SeedDescription, Uuid, Wallet, WalletEntry, WalletOp } from "@emeraldpay/emerald-vault-core"; import { BitcoinEntry, isIdSeedReference, isLedger, isSeedReference, SeedReference } from "@emeraldpay/emerald-vault-core/lib/types"; function sum<T extends BigAmount>(a: T | undefined, b: T | undefined): T { if (typeof a == 'undefined') { return b!; } if (typeof b == 'undefined') { return a; } return b.plus(a); } export function zeroAmountFor<T extends BigAmount>(blockchain: BlockchainCode): T { const amountCreate = amountFactory(blockchain) as CreateAmount<T>; return amountCreate(0) } export const allWallets = (state: IState): Wallet[] => state[moduleName].wallets; /** * Returns all accounts from all wallets as flat array * @param state */ export const allEntries = createSelector( [allWallets], (wallets) => { return wallets.reduce((a: WalletEntry[], w) => a.concat(w.entries), []); } ); export const allEntriesByBlockchain = (state: IState, code: BlockchainCode) => { const accounts: WalletEntry[] = allEntries(state); return accounts.filter((a: WalletEntry) => blockchainIdToCode(a.blockchain) === code); }; export function findWallet(state: IState, id: Uuid): Wallet | undefined { return allWallets(state).find((w) => w.id === id); } export function findWalletByEntryId(state: IState, id: EntryId): Wallet | undefined { const walletId = EntryIdOp.asOp(id).extractWalletId() return findWallet(state, walletId); } export function findEntry(state: IState, id: EntryId): WalletEntry | undefined { const wallet = findWalletByEntryId(state, id); if (wallet == null) { return undefined; } return wallet.entries.find((entry) => entry.id === id) } export function allAsArray(state: IState): Wallet[] { return (state[moduleName].wallets || []) .filter((value: any) => typeof value !== 'undefined'); } export const isLoading = (state: any): boolean => state[moduleName].loading; export function findWalletByAddress(state: any, address: string, blockchain: BlockchainCode): Wallet | undefined { if (!address) { return undefined; } return allWallets(state).find( (wallet: Wallet) => WalletOp.of(wallet).findEntryByAddress(address, blockchainCodeToId(blockchain)) ); } export function findAccountByAddress(state: any, address: string, chain: BlockchainCode): WalletEntry | undefined { return allEntries(state).find((e) => { if (blockchainCodeToId(chain) != e.blockchain) { return false } if (isEthereumEntry(e)) { return e.address?.value == address } else if (isBitcoinEntry(e)) { //TODO would not find old address return e.addresses.some((a) => a.address == address) } return false }); } export function getBalance<T extends BigAmount>(state: IState, entryId: string, defaultValue?: T): T | undefined { const entry = findEntry(state, entryId); if (!entry) { console.warn("Unknown entry", entryId); return defaultValue; } const amountDecode = amountDecoder<T>(blockchainIdToCode(entry.blockchain)); const zero = zeroAmountFor<T>(blockchainIdToCode(entry.blockchain)); const entryDetails = (state[moduleName].details || []) .filter((b) => b.entryId === entryId); if (entryDetails.length == 0) { return defaultValue || zero; } if (isEthereumEntry(entry)) { return entryDetails .filter((b) => typeof b.balance === 'string' && b.balance !== '') .map((b) => b.balance) .map((b) => b as string) .map(amountDecode) .reduce(sum) || defaultValue; } else if (isBitcoinEntry(entry)) { return entryDetails .filter((b) => typeof b.utxo != "undefined") .map((b) => b.utxo!) .reduce((a, b) => a.concat(...b)) .map((u) => u.value) .map(amountDecode) .reduce(sum) || defaultValue } else { console.warn("Invalid entry", entry); } } export function balanceByChain<T extends BigAmount>(state: IState, blockchain: BlockchainCode): T { const zero = zeroAmountFor<T>(blockchain); return allEntriesByBlockchain(state, blockchain) .map((account: WalletEntry) => getBalance(state, account.id, zero)!) .reduce(sum, zero); } /** * Balances of all assets summarized by wallet * @param state */ export function allBalances (state: IState): IBalanceValue[] { const assets: IBalanceValue[] = []; state[moduleName].wallets.forEach((wallet) => getWalletBalances(state, wallet, false) .forEach((asset) => assets.push(asset)) ); return assets; } /** * Returns summary of all current assets for the specified wallet * * @param state * @param wallet * @param includeEmpty include zero balances */ export function getWalletBalances (state: IState, wallet: Wallet, includeEmpty: boolean): IBalanceValue[] { const assets: IBalanceValue[] = []; if (typeof wallet == "undefined") { return assets; } const ethereumAccounts = wallet.entries.filter((e) => isEthereumEntry(e)) as EthereumEntry[]; [BlockchainCode.ETH, BlockchainCode.ETC, BlockchainCode.Kovan, BlockchainCode.Goerli] .forEach((code) => { const zero = zeroAmountFor<BigAmount>(code); const blockchainAccounts = ethereumAccounts .filter((account: EthereumEntry) => account.blockchain === blockchainCodeToId(code)); const balance = blockchainAccounts .map((account) => getBalance(state, account.id, zero)!) .reduce((a, b) => a.plus(b), zero); // show only assets that have at least one address in the wallet if (typeof balance !== 'undefined' && (includeEmpty || blockchainAccounts.length > 0)) { assets.push({ balance }); } const supportedTokens = registry.all()[code]; if (typeof supportedTokens === 'undefined') { return; } supportedTokens.forEach((token) => { blockchainAccounts.forEach((account: WalletEntry) => { const balance = tokens.selectors.selectBalance(state, token.address, account.address!.value, code); if (balance && (includeEmpty || !balance.isZero())) { assets.push({ balance }); } }); }); }); const bitcoinAccounts = wallet.entries.filter((e) => isBitcoinEntry(e)) as BitcoinEntry[]; bitcoinAccounts.forEach((entry) => { const code = blockchainIdToCode(entry.blockchain); const zero = zeroAmountFor<BigAmount>(code); const balance = getBalance(state, entry.id, zero) || zero; assets.push({ balance }) }); return aggregateByAsset(assets); } /** * Calculate total balance in currently selected fiat currency. Returns undefined if source is empty of if * some of the input assets doesn't have an exchange rate defined yet * * @param state * @param assets */ export function fiatTotalBalance (state: IState, assets: IBalanceValue[]): IBalanceValue | undefined { const converted = assets .map((asset) => { const rate = settings.selectors.fiatRate(asset.balance.units.top.code, state) || 0; return asset.balance.getNumberByUnit(asset.balance.units.top).multipliedBy(rate) }); if (converted.length === 0) { return undefined; } const total = converted.reduce((a, b) => a.plus(b)); return { balance: new CurrencyAmount(total.multipliedBy(100), state.settings.localeCurrency), }; } /** * Aggregate multiple similar assets into one, by summing all values * * @param assets */ export function aggregateByAsset (assets: IBalanceValue[]): IBalanceValue[] { const group: {[key: string]: IBalanceValue[]} = {}; assets.forEach((asset) => { let token = asset.balance.units.top.code; let current = group[token]; if (typeof current === 'undefined') { current = []; } current.push(asset); group[token] = current; }); const result: IBalanceValue[] = []; Object.values(group) .map((g) => g.reduce((a: IBalanceValue, b: IBalanceValue) => { let balance = a.balance.plus(b.balance); return { balance } as IBalanceValue; })) .forEach((g) => result.push(g)); return result; } /** * Convert assets to fiat, plus return details about source asset * @param state * @param assets */ export function withFiatConversion (state: IState, assets: IBalanceValue[]): BalanceValueConverted[] { return assets .map((asset) => { return { source: asset, converted: fiatTotalBalance(state, [asset]), rate: settings.selectors.fiatRate(asset.balance.units.top.code, state) } as BalanceValueConverted; }) .filter((value) => typeof value.converted !== 'undefined' && typeof value.rate !== 'undefined'); } export function getSeeds(state: IState): SeedDescription[] { return state[accounts.moduleName].seeds || [] } export function getSeed(state: IState, id: Uuid): SeedDescription | undefined { return getSeeds(state).find((seed) => seed.id === id) } export function getUtxo(state: IState, entryId: EntryId): BalanceUtxo[] { return state[accounts.moduleName].details .filter((d) => d.entryId == entryId) .reduce((result, x) => { return result.concat(x.utxo || []) }, [] as BalanceUtxo[]) } export function findLedgerSeed(state: IState): SeedDescription | undefined { return getSeeds(state).find((s) => s.type == "ledger") } export function isHardwareSeed(state: IState, seed: SeedReference): boolean { if (isLedger(seed)) { return true; } if (isIdSeedReference(seed)) { return getSeed(state, seed.value)?.type === "ledger"; } return false }
the_stack
import * as React from 'react'; // Custom styles import styles from './RecentFilesTab.module.scss'; // Office Fabric import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/components/Button'; import { Spinner } from 'office-ui-fabric-react/lib/Spinner'; import { FocusZone } from 'office-ui-fabric-react/lib/FocusZone'; import { List } from 'office-ui-fabric-react/lib/List'; import { IRectangle } from 'office-ui-fabric-react/lib/Utilities'; import { css } from "@uifabric/utilities/lib/css"; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { Selection, SelectionMode, SelectionZone } from 'office-ui-fabric-react/lib/Selection'; import { Image, ImageFit } from 'office-ui-fabric-react/lib/Image'; import { Check } from 'office-ui-fabric-react/lib/Check'; // Custom props and states import { IRecentFilesTabProps, IRecentFilesTabState, IRecentFile } from './RecentFilesTab.types'; import { ItemType } from '../IPropertyPaneFilePicker'; // Localized resources import * as strings from 'PropertyPaneFilePickerStrings'; // PnP import { sp, SearchResults, SearchResult } from "@pnp/sp"; /** * Rows per page */ const ROWS_PER_PAGE = 3; /** * Maximum row height */ const MAX_ROW_HEIGHT = 250; export default class RecentFilesTab extends React.Component<IRecentFilesTabProps, IRecentFilesTabState> { private _columnCount: number; private _columnWidth: number; private _rowHeight: number; private _selection: Selection; private _listElem: List = undefined; constructor(props: IRecentFilesTabProps) { super(props); this._selection = new Selection( { selectionMode: SelectionMode.single, onSelectionChanged: () => { // Get the selected item const selectedItems = this._selection.getSelection(); if (selectedItems && selectedItems.length > 0) { //Get the selected key const selectedKey: IRecentFile = selectedItems[0] as IRecentFile; // Save the selected file this.setState({ fileUrl: selectedKey.fileUrl }); } else { // Remove any selected file this.setState({ fileUrl: undefined }); } if (this._listElem) { // Force the list to update to show the selection check this._listElem.forceUpdate(); } } }); this.state = { isLoading: true, results: [] }; } /** * Gets the most recently used files */ public componentDidMount(): void { const { absoluteUrl } = this.props.context.pageContext.web; // Build a filter criteria for each accepted file type, if applicable const fileFilter: string = this._getFileFilter(); // // This is how you make two promises at once and wait for both results to return // // TODO: research to see if there is a way to get this info in one call. Perhaps as context info? sp.setup({ sp: { baseUrl: absoluteUrl } }); const getContext: [Promise<any[]>, Promise<any[]>] = [sp.web.select("Id").get(), sp.site.select("Id").get()]; Promise.all(getContext).then((results: any[]) => { // retrieve site id and web id const webId: string = results[0].Id; const siteId: string = results[1].Id; // build a query template const queryTemplate: string = `((SiteID:${siteId} OR SiteID: {${siteId}}) AND (WebId: ${webId} OR WebId: {${webId}})) AND LastModifiedTime < {Today} AND -Title:OneNote_DeletedPages AND -Title:OneNote_RecycleBin${fileFilter}`; // search for recent changes with accepted file types sp.search({ QueryTemplate: queryTemplate, RowLimit: 20, SelectProperties: [ "Title", "Path", "Filename", "FileExtension", "FileType", "Created", "Author", "LastModifiedTime", "EditorOwsUser", "ModifiedBy", "LinkingUrl", "SiteTitle", "ParentLink", "DocumentPreviewMetadata", "ListID", "ListItemID", "SPSiteURL", "SiteID", "WebId", "UniqueID", "SPWebUrl", "DefaultEncodingURL", "PictureThumbnailURL", ], SortList: [ { "Property": "LastModifiedTime", "Direction": 1 } ] }).then((r: SearchResults) => { const recentFilesResult: IRecentFile[] = r.PrimarySearchResults.map((result: SearchResult) => { const recentFile: IRecentFile = { key: result["UniqueID"], name: result.Title, fileUrl: result["DefaultEncodingURL"], editedBy: result["ModifiedBy"] }; return recentFile; }); this._selection.setItems(recentFilesResult, true); this.setState({ isLoading: false, results: recentFilesResult }); }); }); } /** * Render the tab */ public render(): React.ReactElement<IRecentFilesTabProps> { const imageType: boolean = this.props.itemType === ItemType.Images; const { results, isLoading } = this.state; return ( <span className={styles.tabContainer}> <span className={styles.tabHeaderContainer}> <h2 className={styles.tabHeader}>{imageType ? strings.RecentImagesHeader : strings.RecentDocumentsHeader}</h2> </span> <span className={styles.tab}> {isLoading ? this._renderSpinner() : results === undefined || results.length < 1 ? this._renderPlaceholder() : this._renderGridList() } </span> <span className={styles.actionButtonsContainer}> <span className={styles.actionButtons}> <PrimaryButton disabled={!this.state.fileUrl} onClick={() => this._handleSave()} className={styles.actionButton} >{strings.OpenButtonLabel}</PrimaryButton> <DefaultButton onClick={() => this._handleClose()} className={styles.actionButton}>{strings.CancelButtonLabel}</DefaultButton> </span> </span> </span> ); } /** * Calculates how many items there should be in the page */ private _getItemCountForPage = (itemIndex: number, surfaceRect: IRectangle): number => { if (itemIndex === 0) { this._columnCount = Math.ceil(surfaceRect.width / MAX_ROW_HEIGHT); this._columnWidth = Math.floor(surfaceRect.width / this._columnCount); this._rowHeight = this._columnWidth; } return this._columnCount * ROWS_PER_PAGE; } /** Calculates the list "page" height (a.k.a. row) */ private _getPageHeight = (): number => { return this._rowHeight * ROWS_PER_PAGE; } /** * Renders a "please wait" spinner while we're loading */ private _renderSpinner = (): JSX.Element => { return <Spinner label={strings.Loading} />; } /** * Renders a message saying that there are no recent files */ private _renderPlaceholder = (): JSX.Element => { return <Placeholder iconName='OpenFolderHorizontal' iconText={strings.NoRecentFiles} description={strings.NoRecentFilesDescription} />; } /** * Renders a grid list containing results */ private _renderGridList = (): JSX.Element => { return <span className={styles.recentGridList} role="grid"> <FocusZone> <SelectionZone selection={this._selection} onItemInvoked={(item: IRecentFile) => this._handleItemInvoked(item)}> <List ref={this._linkElement} items={this.state.results} onRenderCell={this._onRenderCell} getItemCountForPage={this._getItemCountForPage} getPageHeight={this._getPageHeight} renderedWindowsAhead={4} /> </SelectionZone> </FocusZone> </span>; } /** * Renders each result in its own cell */ private _onRenderCell = (item: IRecentFile, index: number | undefined): JSX.Element => { let isSelected: boolean = false; if (this._selection && index !== undefined) { isSelected = this._selection.isIndexSelected(index); } return ( <div className={styles.gridListCell} role={"gridCell"}> <div className={css(styles.itemTile, styles.isFile, styles.hasThumbnail, isSelected ? styles.isSelected : undefined)} role="link" aria-selected={isSelected} data-is-draggable="false" data-is-focusable="true" data-selection-index={index} data-selection-invoke="true" data-item-index={index} data-automationid="ItemTile" style={{ width: this._columnWidth, height: this._rowHeight }} > <div className={styles.itemTileContent}> <div className={styles.itemTileFile}> <div className={styles.itemTileFileContainer}> <div className={styles.itemTileThumbnail}> {/* <div className={styles.image}> */} <Image src={item.fileUrl} width={this._columnWidth} height={this._rowHeight} imageFit={ImageFit.cover} /> {/* </div> */} </div> <div className={styles.itemTileCheckCircle} role='checkbox' aria-checked={isSelected} data-item-index={index} data-selection-toggle={true} data-automationid='CheckCircle'> <Check checked={isSelected} /> </div> <div className={styles.itemTileNamePlate}> <div className={styles.itemTileName}>{item.name}</div> <div className={styles.itemTileSubText}> <span>{strings.EditedByNamePlate}{item.editedBy}</span> </div> </div> </div> </div> </div> </div> </div> ); } /** * Gets called what a file is selected. */ private _handleItemInvoked = (item: IRecentFile) => { this._selection.setKeySelected(item.key, true, true); } /** * Gets called when it is time to save the currently selected item */ private _handleSave = () => { this.props.onSave(encodeURI(this.state.fileUrl)); } /** * Gets called when it is time to close (without saving) */ private _handleClose = () => { this.props.onClose(); } /** * Builds a file filter using the accepted file extensions */ private _getFileFilter() { let fileFilter: string = undefined; if (this.props.itemType === ItemType.Images && this.props.accepts) { fileFilter = " AND ("; this.props.accepts.split(",").forEach((fileType: string, index: number) => { fileType = fileType.replace(".", ""); if (index > 0) { fileFilter = fileFilter + " OR "; } fileFilter = fileFilter + `FileExtension:${fileType} OR SecondaryFileExtension:${fileType}`; }); fileFilter = fileFilter + ")"; } return fileFilter; } /** * Creates a ref to the list */ private _linkElement = (e: any) => { this._listElem = e; } }
the_stack
import axios, { AxiosError } from "axios"; import type { AxiosResponse, ResponseType, Method } from "axios"; import { uploadFile, uploadLargeFile, uploadDirectory, uploadDirectoryRequest, uploadSmallFile, uploadSmallFileRequest, uploadLargeFileRequest, } from "./upload"; import { downloadFile, downloadFileHns, getSkylinkUrl, getHnsUrl, getHnsresUrl, getMetadata, getFileContent, getFileContentRequest, getFileContentHns, openFile, openFileHns, resolveHns, } from "./download"; import { getJSONEncrypted, getEntryData as fileGetEntryData, getEntryLink as fileGetEntryLink, getJSON as fileGetJSON, } from "./file"; import { pinSkylink } from "./pin"; import { getEntry, getEntryLinkAsync, getEntryUrl, setEntry, postSignedEntry } from "./registry"; import { RevisionNumberCache } from "./revision_cache"; import { deleteJSON, getJSON, setJSON, setDataLink, getRawBytes, getEntryData, setEntryData, deleteEntryData, } from "./skydb"; import { defaultPortalUrl } from "./utils/url"; import { loadMySky } from "./mysky"; import { extractDomain, getFullDomainUrl } from "./mysky/utils"; import { buildRequestHeaders, buildRequestUrl, ExecuteRequestError, Headers } from "./request"; /** * Custom client options. * * @property [APIKey] - Authentication password to use. * @property [customUserAgent] - Custom user agent header to set. * @property [customCookie] - Custom cookie header to set. * @property [onDownloadProgress] - Optional callback to track download progress. * @property [onUploadProgress] - Optional callback to track upload progress. */ export type CustomClientOptions = { APIKey?: string; customUserAgent?: string; customCookie?: string; onDownloadProgress?: (progress: number, event: ProgressEvent) => void; onUploadProgress?: (progress: number, event: ProgressEvent) => void; }; /** * Config options for a single request. * * @property endpointPath - The endpoint to contact. * @property [data] - The data for a POST request. * @property [url] - The full url to contact. Will be computed from the portalUrl and endpointPath if not provided. * @property [method] - The request method. * @property [headers] - Any request headers to set. * @property [subdomain] - An optional subdomain to add to the URL. * @property [query] - Query parameters. * @property [extraPath] - An additional path to append to the URL, e.g. a 46-character skylink. * @property [responseType] - The response type. * @property [transformRequest] - A function that allows manually transforming the request. * @property [transformResponse] - A function that allows manually transforming the response. */ export type RequestConfig = CustomClientOptions & { endpointPath?: string; data?: FormData | Record<string, unknown>; url?: string; method?: Method; headers?: Headers; subdomain?: string; query?: { [key: string]: string | undefined }; extraPath?: string; responseType?: ResponseType; transformRequest?: (data: unknown) => string; transformResponse?: (data: string) => Record<string, unknown>; }; // Add a response interceptor so that we always return an error of type // `ExecuteResponseError`. axios.interceptors.response.use( function (response) { // Any status code that lie within the range of 2xx cause this function to trigger. // Do something with response data. return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error. return Promise.reject(ExecuteRequestError.From(error as AxiosError)); } ); /** * The Skynet Client which can be used to access Skynet. */ export class SkynetClient { customOptions: CustomClientOptions; // The initial portal URL, the value of `defaultPortalUrl()` if `new // SkynetClient` is called without a given portal. This initial URL is used to // resolve the final portal URL. protected initialPortalUrl: string; // The resolved API portal URL. The request won't be made until needed, or // `initPortalUrl()` is called. The request is only made once, for all Skynet // Clients. protected static resolvedPortalUrl?: Promise<string>; // The custom portal URL, if one was passed in to `new SkynetClient()`. protected customPortalUrl?: string; // Set methods (defined in other files). // Upload uploadFile = uploadFile; protected uploadSmallFile = uploadSmallFile; protected uploadSmallFileRequest = uploadSmallFileRequest; protected uploadLargeFile = uploadLargeFile; protected uploadLargeFileRequest = uploadLargeFileRequest; uploadDirectory = uploadDirectory; protected uploadDirectoryRequest = uploadDirectoryRequest; // Download downloadFile = downloadFile; downloadFileHns = downloadFileHns; getSkylinkUrl = getSkylinkUrl; getHnsUrl = getHnsUrl; getHnsresUrl = getHnsresUrl; getMetadata = getMetadata; getFileContent = getFileContent; protected getFileContentRequest = getFileContentRequest; getFileContentHns = getFileContentHns; openFile = openFile; openFileHns = openFileHns; resolveHns = resolveHns; // Pin pinSkylink = pinSkylink; // MySky extractDomain = extractDomain; getFullDomainUrl = getFullDomainUrl; loadMySky = loadMySky; // File API file = { getJSON: fileGetJSON.bind(this), getEntryData: fileGetEntryData.bind(this), getEntryLink: fileGetEntryLink.bind(this), getJSONEncrypted: getJSONEncrypted.bind(this), }; // SkyDB db = { deleteJSON: deleteJSON.bind(this), getJSON: getJSON.bind(this), setJSON: setJSON.bind(this), getRawBytes: getRawBytes.bind(this), setDataLink: setDataLink.bind(this), getEntryData: getEntryData.bind(this), setEntryData: setEntryData.bind(this), deleteEntryData: deleteEntryData.bind(this), // Holds the cached revision numbers, protected by mutexes to prevent // concurrent access. revisionNumberCache: new RevisionNumberCache(), }; // Registry registry = { getEntry: getEntry.bind(this), getEntryUrl: getEntryUrl.bind(this), getEntryLink: getEntryLinkAsync.bind(this), setEntry: setEntry.bind(this), postSignedEntry: postSignedEntry.bind(this), }; /** * The Skynet Client which can be used to access Skynet. * * @class * @param [initialPortalUrl] The initial portal URL to use to access Skynet, if specified. A request will be made to this URL to get the actual portal URL. To use the default portal while passing custom options, pass "". * @param [customOptions] Configuration for the client. */ constructor(initialPortalUrl = "", customOptions: CustomClientOptions = {}) { if (initialPortalUrl === "") { // Portal was not given, use the default portal URL. We'll still make a request for the resolved portal URL. initialPortalUrl = defaultPortalUrl(); } else { // Portal was given, don't make the request for the resolved portal URL. this.customPortalUrl = initialPortalUrl; } this.initialPortalUrl = initialPortalUrl; this.customOptions = customOptions; } /* istanbul ignore next */ /** * Make the request for the API portal URL. * * @returns - A promise that resolves when the request is complete. */ async initPortalUrl(): Promise<void> { if (this.customPortalUrl) { // Tried to make a request for the API portal URL when a custom URL was already provided. return; } // Try to resolve the portal URL again if it's never been called or if it // previously failed. if (!SkynetClient.resolvedPortalUrl) { SkynetClient.resolvedPortalUrl = this.resolvePortalUrl(); } else { try { await SkynetClient.resolvedPortalUrl; } catch (e) { SkynetClient.resolvedPortalUrl = this.resolvePortalUrl(); } } // Wait on the promise and throw if it fails. await SkynetClient.resolvedPortalUrl; return; } /* istanbul ignore next */ /** * Returns the API portal URL. Makes the request to get it if not done so already. * * @returns - the portal URL. */ async portalUrl(): Promise<string> { if (this.customPortalUrl) { return this.customPortalUrl; } // Make the request if needed and not done so. await this.initPortalUrl(); return await SkynetClient.resolvedPortalUrl!; // eslint-disable-line } /** * Creates and executes a request. * * @param config - Configuration for the request. * @returns - The response from axios. * @throws - Will throw `ExecuteRequestError` if the request fails. This error contains the original Axios error. */ async executeRequest(config: RequestConfig): Promise<AxiosResponse> { const url = await buildRequestUrl(this, { baseUrl: config.url, endpointPath: config.endpointPath, subdomain: config.subdomain, extraPath: config.extraPath, query: config.query, }); // Build headers. const headers = buildRequestHeaders(config.headers, config.customUserAgent, config.customCookie); const auth = config.APIKey ? { username: "", password: config.APIKey } : undefined; let onDownloadProgress = undefined; if (config.onDownloadProgress) { onDownloadProgress = function (event: ProgressEvent) { // Avoid NaN for 0-byte file. /* istanbul ignore next: Empty file test doesn't work yet. */ const progress = event.total ? event.loaded / event.total : 1; // @ts-expect-error TS complains even though we've ensured this is defined. config.onDownloadProgress(progress, event); }; } let onUploadProgress = undefined; if (config.onUploadProgress) { onUploadProgress = function (event: ProgressEvent) { // Avoid NaN for 0-byte file. /* istanbul ignore next: event.total is always 0 in Node. */ const progress = event.total ? event.loaded / event.total : 1; // @ts-expect-error TS complains even though we've ensured this is defined. config.onUploadProgress(progress, event); }; } // NOTE: The error type will be ExecuteRequestError as we set up a response // interceptor above. return await axios({ url, method: config.method, data: config.data, headers, auth, onDownloadProgress, onUploadProgress, responseType: config.responseType, transformRequest: config.transformRequest, transformResponse: config.transformResponse, maxContentLength: Infinity, maxBodyLength: Infinity, // Allow cross-site cookies. withCredentials: true, }); } // =============== // Private Methods // =============== protected async resolvePortalUrl(): Promise<string> { const response = await this.executeRequest({ ...this.customOptions, method: "head", url: this.initialPortalUrl, endpointPath: "/", }); if (!response.headers) { throw new Error( "Did not get 'headers' in response despite a successful request. Please try again and report this issue to the devs if it persists." ); } const portalUrl = response.headers["skynet-portal-api"]; if (!portalUrl) { throw new Error("Could not get portal URL for the given portal"); } return portalUrl; } }
the_stack
import Big, { BigSource } from "big.js" import { api, BncClient } from ".." import * as crypto from "../../crypto" import { Coin, AminoPrefix, IssueMiniTokenMsg, IssueTinyTokenMsg, SetTokenUriMsg, } from "../../types" import HttpRequest from "../../utils/request" import { validateSymbol, checkCoins } from "../../utils/validateHelper" const MAXTOTALSUPPLY = 9000000000000000000 const MINI_TOKEN_MAX_TOTAL_SUPPAY = 1000000 const TINY_TOKEN_MAX_TOTAL_SUPPAY = 10000 const validateNonZeroAmount = async ( amountParam: BigSource, symbol: string, fromAddress: string, httpClient: HttpRequest, type = "free" ) => { const amount = new Big(amountParam) if (amount.lte(0) || amount.gt(MAXTOTALSUPPLY)) { throw new Error("invalid amount") } try { const { result } = await httpClient.request( "get", `${api.getAccount}/${fromAddress}` ) const balance = result.balances.find( (b: { symbol: string }) => b.symbol.toUpperCase() === symbol.toUpperCase() ) if (!balance) { throw new Error(`the account doesn't have ${symbol}`) } if (amount.gte(balance[type])) { throw new Error(`the account doesn't have enougth balance`) } } catch (err) { //if get account failed. still broadcast } } export const validateMiniTokenSymbol = (symbol: string) => { if (!symbol) { throw new Error("suffixed token symbol cannot be empty") } const splitedSymbol = symbol.split("-") if (splitedSymbol.length != 2) { throw new Error("suffixed mini-token symbol must contain a hyphen ('-')") } if (!splitedSymbol[1]) { throw new Error( `suffixed mini-token symbol must contain just one hyphen (" - ")` ) } if (!/^[a-zA-z\d]{3,8}$/.test(splitedSymbol[0])) { throw new Error( "symbol should be alphanumeric and length is limited to 3~8" ) } if (!splitedSymbol[1].endsWith("M")) { throw new Error("mini-token symbol suffix must end with M") } } /** * issue or view tokens */ class TokenManagement { private _bncClient!: BncClient /** * @param {Object} bncClient */ constructor(bncClient: BncClient) { this._bncClient = bncClient } /** * create a new asset on Binance Chain * @param {String} - senderAddress * @param {String} - tokenName * @param {String} - symbol * @param {Number} - totalSupply * @param {Boolean} - mintable * @returns {Promise} resolves with response (success or fail) */ async issue( senderAddress: string, tokenName: string, symbol: string, totalSupply = 0, mintable = false ) { if (!senderAddress) { throw new Error("sender address cannot be empty") } if (tokenName.length > 32) { throw new Error("token name is limited to 32 characters") } if (!/^[a-zA-z\d]{3,8}$/.test(symbol)) { throw new Error( "symbol should be alphanumeric and length is limited to 3~8" ) } if (totalSupply <= 0 || totalSupply > MAXTOTALSUPPLY) { throw new Error("invalid supply amount") } totalSupply = Number(new Big(totalSupply).mul(Math.pow(10, 8)).toString()) const issueMsg = { from: crypto.decodeAddress(senderAddress), name: tokenName, symbol, total_supply: totalSupply, mintable, aminoPrefix: AminoPrefix.IssueMsg, } const signIssueMsg = { from: senderAddress, name: tokenName, symbol, total_supply: totalSupply, mintable, } const signedTx = await this._bncClient._prepareTransaction( issueMsg, signIssueMsg, senderAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * issue a new mini-token, total supply should be less than 1M * @param {String} - senderAddress * @param {String} - tokenName * @param {String} - symbol * @param {Number} - totalSupply * @param {Boolean} - mintable * @param {string} - token_uri * @returns {Promise} resolves with response (success or fail) */ async issueMiniToken( senderAddress: string, tokenName: string, symbol: string, totalSupply = 0, mintable = false, tokenUri?: string ) { if (!senderAddress) { throw new Error("sender address cannot be empty") } if (tokenName.length > 32) { throw new Error("token name is limited to 32 characters") } if (!/^[a-zA-z\d]{3,8}$/.test(symbol)) { throw new Error( "symbol should be alphanumeric and length is limited to 3~8" ) } if (totalSupply <= 0 || totalSupply > MINI_TOKEN_MAX_TOTAL_SUPPAY) { throw new Error("invalid supply amount") } totalSupply = Number(new Big(totalSupply).mul(Math.pow(10, 8)).toString()) const issueMiniMsg = new IssueMiniTokenMsg({ name: tokenName, symbol, total_supply: totalSupply, mintable, token_uri: tokenUri, from: senderAddress, }) const signedTx = await this._bncClient._prepareTransaction( issueMiniMsg.getMsg(), issueMiniMsg.getSignMsg(), senderAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * issue a new tiny-token, total supply should be less than 10K * @param {String} - senderAddress * @param {String} - tokenName * @param {String} - symbol * @param {Number} - totalSupply * @param {Boolean} - mintable * @param {string} - token_uri * @returns {Promise} resolves with response (success or fail) */ async issueTinyToken( senderAddress: string, tokenName: string, symbol: string, totalSupply = 0, mintable = false, tokenUri?: string ) { if (!senderAddress) { throw new Error("sender address cannot be empty") } if (tokenName.length > 32) { throw new Error("token name is limited to 32 characters") } if (!/^[a-zA-z\d]{3,8}$/.test(symbol)) { throw new Error( "symbol should be alphanumeric and length is limited to 3~8" ) } if (totalSupply <= 0 || totalSupply > TINY_TOKEN_MAX_TOTAL_SUPPAY) { throw new Error("invalid supply amount") } totalSupply = Number(new Big(totalSupply).mul(Math.pow(10, 8)).toString()) const issueMiniMsg = new IssueTinyTokenMsg({ name: tokenName, symbol, total_supply: totalSupply, mintable, token_uri: tokenUri, from: senderAddress, }) const signedTx = await this._bncClient._prepareTransaction( issueMiniMsg.getMsg(), issueMiniMsg.getSignMsg(), senderAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * set token URI of mini-token */ async setTokenUri({ fromAddress, tokenUri, symbol, }: { fromAddress: string tokenUri: string symbol: string }) { validateMiniTokenSymbol(symbol) if (tokenUri.length > 2048) { throw new Error("uri cannot be longer than 2048 characters") } if (!fromAddress) { throw new Error("address cannot be empty") } const setUriMsg = new SetTokenUriMsg({ from: fromAddress, token_uri: tokenUri, symbol, }) const signedTx = await this._bncClient._prepareTransaction( setUriMsg.getMsg(), setUriMsg.getSignMsg(), fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * freeze some amount of token * @param {String} fromAddress * @param {String} symbol * @param {String} amount * @returns {Promise} resolves with response (success or fail) */ async freeze(fromAddress: string, symbol: string, amount: BigSource) { validateSymbol(symbol) validateNonZeroAmount( amount, symbol, fromAddress, this._bncClient._httpClient, "free" ) amount = +Number(new Big(amount).mul(Math.pow(10, 8)).toString()) const freezeMsg = { from: crypto.decodeAddress(fromAddress), symbol, amount: amount, aminoPrefix: AminoPrefix.FreezeMsg, } const freezeSignMsg = { amount: amount, from: fromAddress, symbol, } const signedTx = await this._bncClient._prepareTransaction( freezeMsg, freezeSignMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * unfreeze some amount of token * @param {String} fromAddress * @param {String} symbol * @param {String} amount * @returns {Promise} resolves with response (success or fail) */ async unfreeze(fromAddress: string, symbol: string, amount: BigSource) { validateSymbol(symbol) validateNonZeroAmount( amount, symbol, fromAddress, this._bncClient._httpClient, "frozen" ) amount = +Number(new Big(amount).mul(Math.pow(10, 8)).toString()) const unfreezeMsg = { from: crypto.decodeAddress(fromAddress), symbol, amount: amount, aminoPrefix: AminoPrefix.UnfreezeMsg, } const unfreezeSignMsg = { amount: amount, from: fromAddress, symbol, } const signedTx = await this._bncClient._prepareTransaction( unfreezeMsg, unfreezeSignMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * burn some amount of token * @param {String} fromAddress * @param {String} symbol * @param {Number} amount * @returns {Promise} resolves with response (success or fail) */ async burn(fromAddress: string, symbol: string, amount: BigSource) { validateSymbol(symbol) validateNonZeroAmount( amount, symbol, fromAddress, this._bncClient._httpClient ) amount = +Number(new Big(amount).mul(Math.pow(10, 8)).toString()) const burnMsg = { from: crypto.decodeAddress(fromAddress), symbol, amount: amount, aminoPrefix: AminoPrefix.BurnMsg, } const burnSignMsg = { amount: amount, from: fromAddress, symbol, } const signedTx = await this._bncClient._prepareTransaction( burnMsg, burnSignMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * mint tokens for an existing token * @param {String} fromAddress * @param {String} symbol * @param {Number} amount * @returns {Promise} resolves with response (success or fail) */ async mint(fromAddress: string, symbol: string, amount: BigSource) { validateSymbol(symbol) if (amount <= 0 || amount > MAXTOTALSUPPLY) { throw new Error("invalid amount") } amount = Number(new Big(amount).mul(Math.pow(10, 8)).toString()) const mintMsg = { from: crypto.decodeAddress(fromAddress), symbol, amount: amount, aminoPrefix: AminoPrefix.MintMsg, } const mintSignMsg = { amount: amount, from: fromAddress, symbol, } const signedTx = await this._bncClient._prepareTransaction( mintMsg, mintSignMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * lock token for a while * @param {String} fromAddress * @param {String} description * @param {Array} amount * @param {Number} lockTime * @returns {Promise} resolves with response (success or fail) */ async timeLock( fromAddress: string, description: string, amount: Coin[], lockTime: number ) { checkCoins(amount) if (description.length > 128) { throw new Error("description is too long") } if (lockTime < 60 || lockTime > 253402300800) { throw new Error("timeTime must be in [60, 253402300800]") } const timeLockMsg = { from: crypto.decodeAddress(fromAddress), description, amount, lock_time: lockTime, aminoPrefix: AminoPrefix.TimeLockMsg, } const signTimeLockMsg = { from: fromAddress, description: description, amount, lock_time: lockTime, } const signedTx = await this._bncClient._prepareTransaction( timeLockMsg, signTimeLockMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * lock more token or increase locked period * @param {String} fromAddress * @param {Number} id * @param {String} description * @param {Array} amount * @param {Number} lockTime * @returns {Promise} resolves with response (success or fail) */ async timeRelock( fromAddress: string, id: number, description: string, amount: Coin[], lockTime: number ) { checkCoins(amount) if (description.length > 128) { throw new Error("description is too long") } if (lockTime < 60 || lockTime > 253402300800) { throw new Error("timeTime must be in [60, 253402300800]") } const timeRelockMsg = { from: crypto.decodeAddress(fromAddress), time_lock_id: id, description, amount, lock_time: lockTime, aminoPrefix: AminoPrefix.TimeRelockMsg, } const signTimeRelockMsg = { from: fromAddress, time_lock_id: id, description: description, amount, lock_time: lockTime, } const signedTx = await this._bncClient._prepareTransaction( timeRelockMsg, signTimeRelockMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } /** * unlock locked tokens * @param {String} fromAddress * @param {Number} id * @returns {Promise} resolves with response (success or fail) */ async timeUnlock(fromAddress: string, id: number) { const timeUnlockMsg = { from: crypto.decodeAddress(fromAddress), time_lock_id: id, aminoPrefix: AminoPrefix.TimeUnlockMsg, } const signTimeUnlockMsg = { from: fromAddress, time_lock_id: id, } const signedTx = await this._bncClient._prepareTransaction( timeUnlockMsg, signTimeUnlockMsg, fromAddress ) return this._bncClient._broadcastDelegate(signedTx) } } export default TokenManagement
the_stack
import './index.less'; import browser from './../../../browser'; // import { ActionSheet, ActionSheetOpts, } from '../../component/action-sheet/index'; import { Progress, ProcessOnChangeData } from './../../component/progress'; import { Loading } from './../../component/loading/index'; import { Panel, PanelOpts, } from '../panel/index'; import cacheHub from './../../service/cache-hub'; import eventHub from './../../service/event-hub'; import schemaParser from './../../service/schema-parser'; import { WorkerConfig } from './../../service/worker'; import { asyncWorker } from './../../service/worker'; import { getAdjustMenuConfig, AdjustMenuConfigType, AdjustMenuItemType } from '../../config/adjust'; import { getEffectMenuConfig, EffectMenuConfigType, EffectMenuItemType } from '../../config/effect'; import { getProcessMenuConfig, ProcessMenuConfigType, ProcessMenuItemType } from '../../config/process'; import { getLanguage, LanguageType } from './../../language/index'; interface ReigisterEventType { processMenuConfig: ProcessMenuConfigType, effectMenuConfig: EffectMenuConfigType, adjustMenuConfig: AdjustMenuConfigType } export interface DashboardOpts { zIndex: number; language?: string; workerConfig: WorkerConfig; } export class Dashboard { private _mount: HTMLElement|null; private _opts: DashboardOpts; private _hasRendered: boolean = false; constructor(mount: HTMLElement, opts: DashboardOpts) { this._mount = mount; this._opts = opts; this._render(); } private _render() { if (this._hasRendered === true) { return; } const options: DashboardOpts|null = this._opts; if (!options || !this._mount) { return; } const { zIndex, language, } = options; const lang: LanguageType = getLanguage(language); const processMenuConfig = getProcessMenuConfig(lang); const effectMenuConfig = getEffectMenuConfig(lang); const adjustMenuConfig = getAdjustMenuConfig(lang); const html = ` <div class="pictool-module-dashboard" style="z-index:${zIndex};"> <div class="pictool-dashboard-navlist"> <div class="pictool-dashboard-nav-btn dashboard-process" data-nav-action="process" > <span>${processMenuConfig.title}</span> </div> <div class="pictool-dashboard-nav-btn dashboard-adjust" data-nav-action="adjust" > <span>${adjustMenuConfig.title}</span> </div> <div class="pictool-dashboard-nav-btn dashboard-effect" data-nav-action="effect" > <span>${effectMenuConfig.title}</span> </div> </div> </div> `; this._mount.innerHTML = html; this._registerEvent({ processMenuConfig, effectMenuConfig, adjustMenuConfig }); this._hasRendered = true; } private _registerEvent(configMap: ReigisterEventType) { if (this._hasRendered === true) { return; } const options: DashboardOpts|null = this._opts; if (!options || !this._mount) { return; } const { zIndex, workerConfig, } = options; const btnEffect = this._mount.querySelector('[data-nav-action="effect"]'); const btnAdjust = this._mount.querySelector('[data-nav-action="adjust"]'); const btnProcess = this._mount.querySelector('[data-nav-action="process"]'); // const opts : ActionSheetOpts = { // mount: this._mount, // height: 120, // zIndex: zIndex + 1, // }; const processPanel = this._initProcessPanel(configMap.processMenuConfig); btnProcess && btnProcess.addEventListener('click', function() { processPanel && processPanel.show(); }); const filterEffect = this._initEffectPanel(configMap.effectMenuConfig); btnEffect && btnEffect.addEventListener('click', function() { filterEffect && filterEffect.show(); }); const adjustPanel = this._initAdjustPanel(configMap.adjustMenuConfig); btnAdjust && btnAdjust.addEventListener('click', function() { adjustPanel && adjustPanel.show(); }); const progress = new Progress({ mount: this._mount, percent: 40, max: 100, min: 0, customStyle: { 'z-index': zIndex + 1, 'position': 'fixed', 'bottom': '140px', 'left': '5%', 'right': '5%', 'width': 'auto', }, // TODO onChange(data: ProcessOnChangeData) { console.log('data =', data); } }); progress.hide(); eventHub.on('GlobalEvent.moduleDashboard.progress.show', function(opts: any) { const { percent, onChange, range, } = opts; progress.resetRange(range.min, range.max); progress.resetOnChange(onChange); progress.resetPercent(percent); progress.show(); }); eventHub.on('GlobalEvent.moduleDashboard.progress.hide', function() { progress.resetOnChange(null); progress.resetPercent(50); progress.resetRange(0, 100); progress.hide(); }); const loading = new Loading({ zIndex: zIndex + 1000, }); eventHub.on('GlobalEvent.moduleDashboard.loading.show', function(opts: any) { let timeout: number = -1; if (opts && opts.timeout > 0) { timeout = opts.timeout; } loading.show(timeout); }); eventHub.on('GlobalEvent.moduleDashboard.loading.hide', function() { loading.hide(); }); } private _initProcessPanel(processMenuConfig: ProcessMenuConfigType) { const options: DashboardOpts = this._opts; if (!this._mount) { return null; } const { zIndex, workerConfig, } = options; const panel = new Panel({ title: processMenuConfig.title, mount: this._mount, zIndex: zIndex + 1, navList: processMenuConfig.menu.map(function(conf: ProcessMenuItemType) { return { name: conf.name, feedback() { const sketchSchema = cacheHub.get('Sketch.originSketchSchema'); const originImgData = schemaParser.parseImageData(sketchSchema); const imageData = browser.util.imageData2DigitImageData(originImgData); return new Promise(function(resolve, reject) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.show'); asyncWorker({ key: conf.filter, param: { imageData, options: {} } }, workerConfig).then(function(rs: ImageData) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); const newSchema = schemaParser.parseImageDataToSchema(rs); resolve(newSchema); }).catch(function(err: Error) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); reject(err); }) }); } } }), }); return panel; } private _initEffectPanel(effectMenuConfig: EffectMenuConfigType) { const options: DashboardOpts = this._opts; if (!this._mount) { return null; } const { zIndex, workerConfig, } = options; const panel = new Panel({ title: effectMenuConfig.title, mount: this._mount, zIndex: zIndex + 1, navList: effectMenuConfig.menu.map(function(conf: EffectMenuItemType) { return { name: conf.name, feedback() { const sketchSchema = cacheHub.get('Sketch.originSketchSchema'); const originImgData = schemaParser.parseImageData(sketchSchema); const imageData = browser.util.imageData2DigitImageData(originImgData); return new Promise(function(resolve, reject) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.show'); asyncWorker({ key: conf.filter, param: { imageData, options: {} } }, workerConfig).then(function(rs: ImageData) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); const newSchema = schemaParser.parseImageDataToSchema(rs); resolve(newSchema); }).catch(function(err: Error) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); reject(err); }) }); } } }), }); return panel; } private _initAdjustPanel(adjustMenuConfig: AdjustMenuConfigType): Panel|null|undefined { const options: DashboardOpts|null = this._opts; if (!options) { return; } const { zIndex, workerConfig, } = options; if (!this._mount) { return; } const panel = new Panel({ title: adjustMenuConfig.title, mount: this._mount, zIndex: zIndex + 1, navList: adjustMenuConfig.menu.map(function(conf: AdjustMenuItemType) { return { name: conf.name, feedback() { const sketchSchema = cacheHub.get('Sketch.originSketchSchema'); const originImgData = schemaParser.parseImageData(sketchSchema); const imageData = browser.util.imageData2DigitImageData(originImgData); eventHub.trigger('GlobalEvent.moduleDashboard.progress.show', { percent: conf.percent, range: {max: conf.range.max, min: conf.range.min }, onChange: function(data: any) { eventHub.trigger('GlobalEvent.moduleDashboard.loading.show'); asyncWorker({ key: conf.filter, param: { imageData, options: conf.parseOptions(data), } }, workerConfig).then(function(rs: ImageData) { const newSchema = schemaParser.parseImageDataToSchema(rs); eventHub.trigger('GlobalEvent.moduleSketch.renderImage', newSchema); eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); }).catch(function(err: Error) { console.log(err); eventHub.trigger('GlobalEvent.moduleDashboard.loading.hide'); }) } }); return null; } } }), }); return panel; } }
the_stack
import { Fragment, useRef, useState } from "react"; import { useSnackbar } from "notistack"; import Navigation from "components/Navigation"; import { useTheme, Container, Stack, Grid, Table, TableHead, TableRow, TableBody, TableCell, Typography, Button, IconButton, Fab, Chip, Paper, MenuList, MenuItem, ListItemIcon, ListItemText, Divider, ListSubheader, Slider, Tooltip, FormControlLabel, Checkbox, RadioGroup, Radio, Switch, TextField, Tabs, Tab, CircularProgress, LinearProgress, } from "@mui/material"; import SparkIcon from "@mui/icons-material/OfflineBoltOutlined"; import { useConfirmation } from "components/ConfirmationDialog"; import SnackbarProgress, { ISnackbarProgressRef, } from "components/SnackbarProgress"; const typographyVariants = [ "h1", "h2", "h3", "h4", "h5", "h6", "subtitle1", "subtitle2", "body1", "body2", "button", "caption", "overline", ]; export default function TestView() { const theme = useTheme(); const { requestConfirmation } = useConfirmation(); const { enqueueSnackbar, closeSnackbar } = useSnackbar(); const [tab, setTab] = useState(0); const handleTabChange = (_, newTab) => setTab(newTab); const snackbarProgressRef = useRef<ISnackbarProgressRef>(); return ( <Navigation title="Theme Test"> <Container style={{ margin: "24px 0 200px", width: "100%" }}> <Stack spacing={8}> <Table stickyHeader style={{ overflowX: "auto", display: "block", width: "100%" }} > <TableHead> <TableRow> <TableCell>Variant</TableCell> <TableCell align="right">Font Weight</TableCell> <TableCell align="right">Font Size</TableCell> <TableCell align="right">Letter Spacing</TableCell> <TableCell align="right">Line Height</TableCell> </TableRow> </TableHead> <TableBody> {typographyVariants.map((variant) => { const fontWeight = theme.typography[variant].fontWeight; const fontSizeRem = Number( theme.typography[variant].fontSize.replace("rem", "") ).toFixed(5); const fontSizePx = Number(fontSizeRem) * 16; const letterSpacingEm = Number( (theme.typography[variant].letterSpacing ?? "0").replace( "em", "" ) ).toFixed(5); const letterSpacingPx = ( Number(letterSpacingEm) * fontSizePx ).toFixed(5); const lineHeight = Number( theme.typography[variant].lineHeight ).toFixed(5); const lineHeightPx = (Number(lineHeight) * fontSizePx).toFixed( 5 ); return ( <Fragment key={variant}> <TableRow> <TableCell colSpan={5} style={{ borderBottom: 0, paddingBottom: 0, letterSpacing: 0, paddingRight: 0, }} > <Typography variant={variant as any} noWrap style={{ width: `calc(100vw - 80px + 16px)`, textOverflow: "clip", display: "block", }} > Sphinx of black quartz, judge my vow! 1234567890 SPHINX OF BLACK QUARTZ, JUDGE MY VOW! </Typography> <Typography variant={variant as any} noWrap style={{ width: `calc(100vw - 80px + 16px)`, textOverflow: "clip", display: "block", }} > Judge my vow, sphinx of black quartz! 1234567890 JUDGE MY VOW, SPHINX OF BLACK QUARTZ! </Typography> </TableCell> </TableRow> <TableRow sx={{ "& .MuiTableCell-root": { fontFamily: theme.typography.fontFamilyMono, color: theme.palette.text.secondary, }, }} > <TableCell> <br /> {variant} </TableCell> <TableCell align="right"> <br /> {fontWeight} </TableCell> <TableCell align="right"> {fontSizeRem}&nbsp;rem <br /> {fontSizePx}&nbsp;px&nbsp; </TableCell> <TableCell align="right"> {letterSpacingEm}&nbsp;em <br /> {letterSpacingPx}&nbsp;px </TableCell> <TableCell align="right"> {lineHeight}&nbsp;&nbsp;&nbsp; <br /> {lineHeightPx}&nbsp;px </TableCell> </TableRow> </Fragment> ); })} </TableBody> </Table> <Stack spacing={1} direction="row" alignItems="center"> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="text" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="text" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="text" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="text" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="text" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="text" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="text" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="text" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="text" size="large" > Button </Button> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="outlined" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="outlined" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="outlined" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="outlined" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="outlined" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="outlined" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="outlined" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="outlined" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="outlined" size="large" > Button </Button> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="contained" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="contained" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="primary" variant="contained" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="contained" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="contained" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} color="secondary" variant="contained" size="large" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="contained" size="small" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="contained" size="medium" > Button </Button> <Button // startIcon={<SparkIcon />} // endIcon={<SparkIcon />} disabled variant="contained" size="large" > Button </Button> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <IconButton size="small"> <SparkIcon /> </IconButton> <IconButton size="medium"> <SparkIcon /> </IconButton> <IconButton size="large"> <SparkIcon /> </IconButton> <IconButton color="primary" size="small"> <SparkIcon /> </IconButton> <IconButton color="primary" size="medium"> <SparkIcon /> </IconButton> <IconButton color="primary" size="large"> <SparkIcon /> </IconButton> <IconButton color="secondary" size="small"> <SparkIcon /> </IconButton> <IconButton color="secondary" size="medium"> <SparkIcon /> </IconButton> <IconButton color="secondary" size="large"> <SparkIcon /> </IconButton> <IconButton disabled size="small"> <SparkIcon /> </IconButton> <IconButton disabled size="medium"> <SparkIcon /> </IconButton> <IconButton disabled size="large"> <SparkIcon /> </IconButton> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Fab size="small"> <SparkIcon /> </Fab> <Fab size="medium"> <SparkIcon /> </Fab> <Fab size="large"> <SparkIcon /> </Fab> <Fab color="primary" size="small"> <SparkIcon /> </Fab> <Fab color="primary" size="medium"> <SparkIcon /> </Fab> <Fab color="primary" size="large"> <SparkIcon /> </Fab> <Fab color="secondary" size="small"> <SparkIcon /> </Fab> <Fab color="secondary" size="medium"> <SparkIcon /> </Fab> <Fab color="secondary" size="large"> <SparkIcon /> </Fab> <Fab disabled size="small"> <SparkIcon /> </Fab> <Fab disabled size="medium"> <SparkIcon /> </Fab> <Fab disabled size="large"> <SparkIcon /> </Fab> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Chip clickable variant="filled" size="small" label="Main" /> <Chip clickable variant="filled" size="medium" label="Main" /> <Chip clickable variant="filled" size="medium" label={ <> Main <br /> Multiline </> } /> <Chip clickable variant="filled" color="primary" size="small" label="Main" /> <Chip clickable variant="filled" color="primary" size="medium" label="Main" /> <Chip clickable variant="filled" color="primary" size="medium" label={ <> Main <br /> Multiline </> } /> <Chip clickable variant="filled" color="secondary" size="small" label="Main" /> <Chip clickable variant="filled" color="secondary" size="medium" label="Main" /> <Chip clickable variant="filled" color="secondary" size="medium" label={ <> Main <br /> Multiline </> } /> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Chip clickable variant="outlined" size="small" label="Main" /> <Chip clickable variant="outlined" size="medium" label="Main" /> <Chip clickable variant="outlined" size="medium" label={ <> Main <br /> Multiline </> } /> <Chip clickable variant="outlined" color="primary" size="small" label="Main" /> <Chip clickable variant="outlined" color="primary" size="medium" label="Main" /> <Chip clickable variant="outlined" color="primary" size="medium" label={ <> Main <br /> Multiline </> } /> <Chip clickable variant="outlined" color="secondary" size="small" label="Main" /> <Chip clickable variant="outlined" color="secondary" size="medium" label="Main" /> <Chip clickable variant="outlined" color="secondary" size="medium" label={ <> Main <br /> Multiline </> } /> </Stack> <Stack spacing={1} direction="row" alignItems="flex-start"> <TextField id="1" label="Label" placeholder="Placeholder" /> <TextField id="2" label="Label" defaultValue="Default Value" /> <TextField id="3" label="Hidden Label" placeholder="Placeholder" hiddenLabel /> <TextField id="4" label="Label" /> <TextField id="5" label="Label" error helperText="Helper Text" /> <TextField id="6" label="Disabled" disabled /> <TextField id="long" label="Label" placeholder="Placeholder" multiline /> </Stack> <TextField id="longLabel" label="Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label Long Label" placeholder="Placeholder" fullWidth /> <Paper elevation={8} style={{ width: "min-content" }}> <MenuList sx={{ pt: 0.5, pb: 0.5 }}> <MenuItem>Profile</MenuItem> <MenuItem>My account</MenuItem> <MenuItem selected>Selected</MenuItem> <Divider variant="middle" /> <ListSubheader>Subheader</ListSubheader> <MenuItem>Profile</MenuItem> <MenuItem>My account</MenuItem> <MenuItem> <ListItemIcon> <SparkIcon /> </ListItemIcon> <ListItemText primary="With Icon" /> </MenuItem> <Divider variant="middle" /> <MenuItem>Logout</MenuItem> </MenuList> </Paper> <div> <Grid container spacing={4}> {new Array(24).fill(undefined).map((_, i) => ( <Grid item key={i}> <Paper elevation={i + 1} style={{ width: 200, height: 200, display: "grid", placeItems: "center", }} > {i + 1} </Paper> </Grid> ))} </Grid> </div> <Tooltip open title="Tooltip"> <Slider valueLabelDisplay="on" // valueLabelFormat={(v) => `${v} label`} marks={[ { value: 20, label: 20 }, { value: 40, label: 40 }, ]} defaultValue={30} /> </Tooltip> <Slider valueLabelDisplay="on" // valueLabelFormat={(v) => `${v} label`} marks={[ { value: 20, label: 20 }, { value: 40, label: 40 }, ]} defaultValue={30} disabled /> <Stack> <FormControlLabel control={<Checkbox />} label="Label" /> <FormControlLabel control={<Checkbox indeterminate />} label="Label indeterminate" /> <RadioGroup> <FormControlLabel control={<Radio />} value="1" label="Label 1" /> <FormControlLabel control={<Radio />} value="2" label="Label 2" /> </RadioGroup> </Stack> <div> <FormControlLabel control={<Switch />} label="Label" sx={{ alignItems: "center", "& .MuiFormControlLabel-label": { mt: 0 }, }} /> <FormControlLabel control={<Switch size="medium" />} label="Label" /> <FormControlLabel labelPlacement="start" control={<Switch />} label="Label" sx={{ alignItems: "center", "& .MuiFormControlLabel-label": { mt: 0 }, }} /> <FormControlLabel labelPlacement="start" control={<Switch size="medium" />} label="Label" /> </div> <Stack spacing={1} direction="row" alignItems="center"> <Switch size="medium" color="primary" /> <Switch size="medium" color="secondary" /> <Switch size="medium" color="success" /> <Switch size="small" color="primary" /> <Switch size="small" color="secondary" /> <Switch size="small" color="success" /> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Switch size="medium" checked color="primary" /> <Switch size="medium" checked color="secondary" /> <Switch size="medium" checked color="success" /> <Switch size="small" checked color="primary" /> <Switch size="small" checked color="secondary" /> <Switch size="small" checked color="success" /> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Switch size="medium" disabled color="primary" /> <Switch size="medium" disabled color="secondary" /> <Switch size="medium" disabled color="success" /> <Switch size="small" disabled color="primary" /> <Switch size="small" disabled color="secondary" /> <Switch size="small" disabled color="success" /> </Stack> <Stack spacing={1} direction="row" alignItems="center"> <Switch size="medium" checked disabled color="primary" /> <Switch size="medium" checked disabled color="secondary" /> <Switch size="medium" checked disabled color="success" /> <Switch size="small" checked disabled color="primary" /> <Switch size="small" checked disabled color="secondary" /> <Switch size="small" checked disabled color="success" /> </Stack> <Tabs value={tab} onChange={handleTabChange}> <Tab label="Item One" /> <Tab label="Item Two" /> <Tab label="Item Three" /> </Tabs> <div style={{ width: 100 }}> <Tabs orientation="vertical" value={tab} onChange={handleTabChange}> <Tab label="Item One" /> <Tab label="Item Two" /> <Tab label="Item Three" /> </Tabs> </div> <div> <Button onClick={() => requestConfirmation({ body: "Additional information here", handleConfirm: () => alert("Confirmed!"), }) } > Confirmation </Button> </div> <Stack spacing={1} direction="row" flexWrap="wrap"> <Button onClick={() => enqueueSnackbar("Message")}>Snackbar</Button> <Button onClick={() => enqueueSnackbar( "You do not have the permissions to make this change.", { variant: "error", action: ( <Button variant="contained" color="secondary"> OK </Button> ), } ) } > Error </Button> <Button onClick={() => enqueueSnackbar("Message", { variant: "info" })} > Info </Button> <Button onClick={() => enqueueSnackbar("Message", { variant: "success" })} > Success </Button> <Button onClick={() => enqueueSnackbar("Message", { variant: "warning" })} > Warning </Button> <Button onClick={() => { const snackId = enqueueSnackbar("Downloading files", { action: <SnackbarProgress stateRef={snackbarProgressRef} />, persist: true, }); const interval = setInterval( () => snackbarProgressRef.current?.setProgress((p) => { if (p === 100) { clearInterval(interval); setTimeout(() => closeSnackbar(snackId), 1000); } return p + 1; }), 100 ); }} > Progress </Button> </Stack> <CircularProgress /> <LinearProgress /> </Stack> </Container> </Navigation> ); }
the_stack
/// <reference path="../metricsPlugin.ts"/> module HawkularMetrics { class WebTabType { public static ACTIVE_SESSIONS = new WebTabType('Aggregated Active Web Sessions', 'Active Sessions', '#49a547'); public static EXPIRED_SESSIONS = new WebTabType('Aggregated Expired Web Sessions', 'Expired Sessions', '#f57f20'); public static REJECTED_SESSIONS = new WebTabType('Aggregated Rejected Web Sessions', 'Rejected Sessions', '#e12226'); public static SERVLET_REQUEST_TIME = new WebTabType('Aggregated Servlet Request Time'); public static SERVLET_REQUEST_COUNT = new WebTabType('Aggregated Servlet Request Count'); private _key: string; private _metricName: string; private _color: IColor; constructor(metricName: string, key?: string, color?: IColor) { this._metricName = metricName; this._key = key; this._color = color; } public getKey() { return this._key; } public getFullWildflyMetricName() { return 'WildFly Aggregated Web Metrics~' + this._metricName; } public getMetricName() { return this._metricName; } public getColor() { return this._color; } } export class AppServerWebDetailsController implements IRefreshable { //public static MAX_ACTIVE_COLOR = '#1884c7'; /// blue public static DEFAULT_MIN_SESSIONS = 20; public static DEFAULT_MAX_SESSIONS = 5000; public static DEFAULT_EXPIRED_SESSIONS_THRESHOLD = 15; public static DEFAULT_REJECTED_SESSIONS_THRESHOLD = 15; public alertList: any[] = []; public activeWebSessions: number = 0; public requestTime: number = 0; public requestCount: number = 0; public startTimeStamp: TimestampInMillis; public endTimeStamp: TimestampInMillis; public chartWebSessionData: IMultiDataPoint[] = []; public contextChartActiveWebSessionData: IContextChartDataPoint[]; // will contain in the format: 'metric name' : true | false public skipChartData = {}; private feedId: FeedId; private resourceId: ResourceId; constructor(private $scope: any, private $rootScope: IHawkularRootScope, private $interval: ng.IIntervalService, private $log: ng.ILogService, private $routeParams: any, private HawkularNav: any, private HawkularAlertRouterManager: IHawkularAlertRouterManager, private $q: ng.IQService, private MetricsService: IMetricsService) { $scope.vm = this; this.feedId = this.$routeParams.feedId; this.resourceId = this.$routeParams.resourceId + '~~'; this.startTimeStamp = +moment().subtract(($routeParams.timeOffset || 3600000), 'milliseconds'); this.endTimeStamp = +moment(); if ($rootScope.currentPersona) { this.refresh(); } else { // currentPersona hasn't been injected to the rootScope yet, wait for it.. $rootScope.$watch('currentPersona', (currentPersona) => currentPersona && this.refresh()); } // handle drag ranges on charts to change the time range this.$scope.$on(EventNames.CHART_TIMERANGE_CHANGED, (event, timeRange: Date[]) => { this.startTimeStamp = timeRange[0].getTime(); this.endTimeStamp = timeRange[1].getTime(); this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp); this.refresh(); }); // handle drag ranges on charts to change the time range this.$scope.$on(EventNames.CONTEXT_CHART_TIMERANGE_CHANGED, (event, timeRange: Date[]) => { this.$log.debug('Received ContextChartTimeRangeChanged event' + timeRange); this.changeTimeRange(timeRange); }); this.HawkularAlertRouterManager.registerForAlerts( this.$routeParams.feedId + '/' + this.$routeParams.resourceId, 'web', _.bind(this.filterAlerts, this) ); this.autoRefresh(20); } private autoRefreshPromise: ng.IPromise<number>; private autoRefresh(intervalInSeconds: number): void { this.autoRefreshPromise = this.$interval(() => { this.refresh(); }, intervalInSeconds * 1000); this.$scope.$on('$destroy', () => { this.$interval.cancel(this.autoRefreshPromise); }); } private changeTimeRange(timeRange: Date[]): void { this.startTimeStamp = timeRange[0].getTime(); this.endTimeStamp = timeRange[1].getTime(); this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp); this.refresh(); } public filterAlerts(alertData: IHawkularAlertQueryResult) { let webAlerts = alertData.alertList.slice(); _.remove(webAlerts, (item: IAlert) => { switch (item.context.alertType) { case 'ACTIVE_SESSIONS': case 'EXPIRED_SESSIONS': case 'REJECTED_SESSIONS': item.alertType = item.context.alertType; return false; default: return true; // ignore non-web alert } }); this.alertList = webAlerts; } public refresh(): void { this.endTimeStamp = this.$routeParams.endTime || +moment(); this.startTimeStamp = this.endTimeStamp - (this.$routeParams.timeOffset || 3600000); this.getWebData(); this.getWebChartData(); this.getAlerts(); this.$rootScope.lastUpdateTimestamp = new Date(); } private getAlerts(): void { this.HawkularAlertRouterManager.getAlertsForCurrentResource( this.startTimeStamp, this.endTimeStamp ); } public getWebData(): void { this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.ACTIVE_SESSIONS.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 1).then((resource) => { this.activeWebSessions = resource[0].avg; }); this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.SERVLET_REQUEST_TIME.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 1).then((resource) => { this.requestTime = resource[0].max - resource[0].min; }); this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.SERVLET_REQUEST_COUNT.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 1).then((resource) => { this.requestCount = resource[0].max - resource[0].min; }); } //private getWebSessionContextChartData(): void { // // because the time range is so much greater here we need more points of granularity // const contextStartTimestamp = +moment(this.endTimeStamp).subtract(1, globalContextChartTimePeriod); // // this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id, // MetricsService.getMetricId('M', this.feedId, this.resourceId, // WebTabType.ACTIVE_SESSIONS.getFullWildflyMetricName()), // contextStartTimestamp, this.endTimeStamp, globalNumberOfContextChartDataPoints).then((contextData) => { // this.contextChartActiveWebSessionData = MetricsService.formatContextChartOutput(contextData); // }); // //} public getWebChartData(): void { let tmpChartWebSessionData = []; let promises = []; if (!this.skipChartData[WebTabType.ACTIVE_SESSIONS.getKey()]) { let activeSessionsPromise = this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.ACTIVE_SESSIONS.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 60); promises.push(activeSessionsPromise); activeSessionsPromise.then((data) => { tmpChartWebSessionData[tmpChartWebSessionData.length] = { key: WebTabType.ACTIVE_SESSIONS.getKey(), color: WebTabType.ACTIVE_SESSIONS.getColor(), values: MetricsService.formatBucketedChartOutput(data) }; }); } if (!this.skipChartData[WebTabType.EXPIRED_SESSIONS.getKey()]) { let expSessionsPromise = this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.EXPIRED_SESSIONS.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 60); promises.push(expSessionsPromise); expSessionsPromise.then((data) => { tmpChartWebSessionData[tmpChartWebSessionData.length] = { key: WebTabType.EXPIRED_SESSIONS.getKey(), color: WebTabType.EXPIRED_SESSIONS.getColor(), values: MetricsService.formatBucketedChartOutput(data) }; }); } if (!this.skipChartData[WebTabType.EXPIRED_SESSIONS.getKey()]) { let rejSessionsPromise = this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id, MetricsService.getMetricId('M', this.feedId, this.resourceId, WebTabType.REJECTED_SESSIONS.getFullWildflyMetricName()), this.startTimeStamp, this.endTimeStamp, 60); promises.push(rejSessionsPromise); rejSessionsPromise.then((data) => { tmpChartWebSessionData[tmpChartWebSessionData.length] = { key: WebTabType.EXPIRED_SESSIONS.getKey(), color: WebTabType.REJECTED_SESSIONS.getColor(), values: MetricsService.formatBucketedChartOutput(data) }; }); } /* FIXME: Currently this is always returning negative values, as WFLY returns -1 per webapp. is it config value? this.HawkularMetric.CounterMetricData(this.$rootScope.currentPersona.id).queryMetrics({ counterId: 'MI~R~[' + this.resourceId + '~~]~MT~WildFly Aggregated Web Metrics~Aggregated Max Active Web Sessions', start: this.startTimeStamp, end: this.endTimeStamp, buckets:60}, (data) => { this.chartWebSessionData[3] = { key: 'Max Active Sessions', color: AppServerWebDetailsController.MAX_ACTIVE_COLOR, values: this.formatBucketedChartOutput(data) }; }, this); */ /* this.HawkularMetric.CounterMetricData(this.$rootScope.currentPersona.id).queryMetrics({ counterId: 'MI~R~[' + this.resourceId + '~~]~MT~WildFly Aggregated Web Metrics~Aggregated Servlet Request Time', start: this.startTimeStamp, end: this.endTimeStamp, buckets:60}, (data) => { this.chartWebData[4] = { key: 'NonHeap Committed', color: AppServerWebDetailsController.COMMITTED_COLOR, values: this.formatCounterChartOutput(data) }; }, this); this.HawkularMetric.CounterMetricData(this.$rootScope.currentPersona.id).queryMetrics({ counterId: 'MI~R~[' + this.resourceId + '~~]~MT~WildFly Aggregated Web Metrics~Aggregated Servlet Request Count', start: this.startTimeStamp, end: this.endTimeStamp, buckets:60}, (data) => { this.chartWebData[5] = { key: 'NonHeap Used', color: AppServerWebDetailsController.USED_COLOR, values: this.formatCounterChartOutput(data) }; }, this); */ this.$q.all(promises).finally(() => { this.chartWebSessionData = tmpChartWebSessionData; }); } public toggleChartData(name): void { this.skipChartData[name] = !this.skipChartData[name]; this.getWebChartData(); } } _module.controller('AppServerWebDetailsController', AppServerWebDetailsController); }
the_stack
import Transaction from '../src/main' import * as mongoose from 'mongoose' const options: any = { useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, useUnifiedTopology: true } // @ts-ignore mongoose.Promise = global.Promise mongoose.connection // .once('open', () => { }) .on('error', err => console.warn('Warning', err)) const personSchema = new mongoose.Schema({ age: Number, contact: { email: { alias: 'email', index: true, sparse: true, type: String, unique: true } }, name: String }) const carSchema = new mongoose.Schema({ age: Number, name: String }) const Person = mongoose.model('Person', personSchema) const Car = mongoose.model('Car', carSchema) const transaction = new Transaction() async function dropCollections() { await Person.deleteMany({}) await Car.deleteMany({}) } describe('Transaction run ', () => { // Read more about fake timers: http://facebook.github.io/jest/docs/en/timer-mocks.html#content // jest.useFakeTimers(); beforeAll(async () => { await mongoose.connect( `mongodb://localhost/mongoose-transactions`, options ) }) // afterAll(async () => { // await dropCollections(); // }); beforeEach(async () => { await dropCollections() transaction.clean() }) test('insert', async () => { const person: string = 'Person' const jonathanObject: any = { age: 18, name: 'Jonathan' } transaction.insert(person, jonathanObject) const final = await transaction.run().catch(console.error) const jonathan: any = await Person.findOne(jonathanObject).exec() expect(jonathan.name).toBe(jonathanObject.name) expect(jonathan.age).toBe(jonathanObject.age) expect(final).toBeInstanceOf(Array) expect(final.length).toBe(1) }) test('it should raise a duplicate key error', async () => { const person: string = 'Person' const jonathanObject: any = { age: 18, email: 'myemail@blabla.com', name: 'Jonathan' } const tonyObject: any = { age: 29, email: 'myemail@blabla.com', name: 'tony' } transaction.insert(person, jonathanObject) transaction.insert(person, tonyObject) try { const final = await transaction.run() expect(final).toBeFalsy() } catch (error) { expect(error).toBeTruthy() expect(error.error.code).toBe(11000) } }) test('update', async () => { const person: string = 'Person' const tonyObject: any = { age: 28, name: 'Tony' } const nicolaObject: any = { age: 32, name: 'Nicola' } const personId = transaction.insert(person, tonyObject) transaction.update(person, personId, nicolaObject) const final = await transaction.run() const nicola: any = await Person.findOne(nicolaObject).exec() expect(nicola.name).toBe(nicolaObject.name) expect(nicola.age).toBe(nicolaObject.age) expect(final).toBeInstanceOf(Array) expect(final.length).toBe(2) }) test('remove', async () => { const person: string = 'Person' const bobObject: any = { age: 45, name: 'Bob' } const aliceObject: any = { age: 23, name: 'Alice' } const personId = transaction.insert(person, bobObject) transaction.update(person, personId, aliceObject) transaction.remove(person, personId) const final = await transaction.run() const bob: any = await Person.findOne(bobObject).exec() const alice: any = await Person.findOne(aliceObject).exec() expect(final).toBeInstanceOf(Array) expect(final.length).toBe(3) expect(alice).toBeNull() expect(bob).toBeNull() }) test('Fail remove', async () => { const person: string = 'Person' const bobObject: any = { age: 45, name: 'Bob' } const aliceObject: any = { age: 23, name: 'Alice' } const personId = transaction.insert(person, bobObject) transaction.update(person, personId, aliceObject) const failObjectId = new mongoose.Types.ObjectId() transaction.remove(person, failObjectId) expect(personId).not.toEqual(failObjectId) try { const final = await transaction.run() } catch (error) { expect(error.executedTransactions).toEqual(2) expect(error.remainingTransactions).toEqual(1) expect(error.error.message).toBe('Entity not found') expect(error.data).toEqual(failObjectId) } }) test('Fail remove with rollback', async () => { const person: string = 'Person' const bobObject: any = { age: 45, name: 'Bob' } const aliceObject: any = { age: 23, name: 'Alice' } const personId = transaction.insert(person, bobObject) transaction.update(person, personId, aliceObject) const failObjectId = new mongoose.Types.ObjectId() transaction.remove(person, failObjectId) expect(personId).not.toEqual(failObjectId) try { const final = await transaction.run() } catch (error) { expect(error.executedTransactions).toEqual(2) expect(error.remainingTransactions).toEqual(1) expect(error.error.message).toBe('Entity not found') expect(error.data).toEqual(failObjectId) const rollbackObj = await transaction .rollback() .catch(console.error) // First revert update of bob object to alice expect(rollbackObj[0].name).toBe(aliceObject.name) expect(rollbackObj[0].age).toBe(aliceObject.age) // Then revert the insert of bob object expect(rollbackObj[1].name).toBe(bobObject.name) expect(rollbackObj[1].age).toBe(bobObject.age) } }) test('Fail remove with rollback and clean, multiple update, run and insert', async () => { const person: string = 'Person' const bobObject: any = { age: 45, name: 'Bob' } const aliceObject: any = { age: 23, name: 'Alice' } const bobId = transaction.insert(person, bobObject) const insertRun = await transaction.run() const bobFind: any = await Person.findOne({ _id: bobId }).exec() expect(bobFind.name).toBe(bobObject.name) expect(bobFind.age).toBe(bobObject.age) expect(insertRun).toBeInstanceOf(Array) expect(insertRun.length).toBe(1) transaction.clean() const aliceId = transaction.insert(person, aliceObject) expect(bobId).not.toEqual(aliceId) // Invert bob and alice transaction.update(person, bobId, { name: 'Maria' }) transaction.update(person, aliceId, { name: 'Giuseppe' }) const failObjectId = new mongoose.Types.ObjectId() // ERROR REMOVE transaction.remove(person, failObjectId) expect(bobId).not.toEqual(failObjectId) expect(aliceId).not.toEqual(failObjectId) try { const final = await transaction.run() } catch (error) { // expect(error).toBeNaN() expect(error.executedTransactions).toEqual(3) expect(error.remainingTransactions).toEqual(1) expect(error.error.message).toBe('Entity not found') expect(error.data).toEqual(failObjectId) const rollbacks = await transaction.rollback().catch(console.error) // expect(rollbacks).toBeNaN() // First revert update of bob object to alice expect(rollbacks[0].name).toBe('Giuseppe') expect(rollbacks[0].age).toBe(aliceObject.age) // Then revert the insert of bob object expect(rollbacks[1].name).toBe('Maria') expect(rollbacks[1].age).toBe(bobObject.age) const bob: any = await Person.findOne({ _id: bobId }).exec() expect(bob.name).toBe(bobObject.name) expect(bob.age).toBe(bobObject.age) const alice: any = await Person.findOne(aliceObject).exec() expect(alice).toBeNull() } }) test('Fail update with rollback and clean, multiple update, run and remove', async () => { const person: string = 'Person' const bobObject: any = { age: 45, name: 'Bob' } const aliceObject: any = { age: 23, name: 'Alice' } const mariaObject: any = { age: 43, name: 'Maria' } const giuseppeObject: any = { age: 33, name: 'Giuseppe' } const bobId = transaction.insert(person, bobObject) const insertRun = await transaction.run() const bobFind: any = await Person.findOne({ _id: bobId }).exec() expect(bobFind.name).toBe(bobObject.name) expect(bobFind.age).toBe(bobObject.age) expect(insertRun).toBeInstanceOf(Array) expect(insertRun.length).toBe(1) transaction.clean() const aliceId = transaction.insert(person, aliceObject) expect(bobId).not.toEqual(aliceId) transaction.remove(person, bobId) transaction.remove(person, aliceId) const mariaId = transaction.insert(person, mariaObject) expect(mariaId).not.toEqual(bobId) expect(mariaId).not.toEqual(aliceId) // Update maria transaction.update(person, mariaId, giuseppeObject) // ERROR UPDATE transaction.update(person, aliceId, { name: 'Error' }) // unreachable transactions transaction.update(person, mariaId, { name: 'unreachable' }) transaction.insert(person, { name: 'unreachable' }) try { const final = await transaction.run() } catch (error) { // expect(error).toBeNaN() expect(error.executedTransactions).toEqual(5) expect(error.remainingTransactions).toEqual(3) expect(error.error.message).toBe('Entity not found') expect(error.data.id).toEqual(aliceId) expect(error.data.data.name).toEqual('Error') const rollbacks = await transaction.rollback().catch(console.error) expect(rollbacks[0].name).toEqual(giuseppeObject.name) expect(rollbacks[0].age).toEqual(giuseppeObject.age) expect(rollbacks[1].name).toEqual(mariaObject.name) expect(rollbacks[1].age).toEqual(mariaObject.age) expect(rollbacks[2].name).toEqual(aliceObject.name) expect(rollbacks[2].age).toEqual(aliceObject.age) expect(rollbacks[3].name).toEqual(bobObject.name) expect(rollbacks[3].age).toEqual(bobObject.age) expect(rollbacks[4].name).toEqual(aliceObject.name) expect(rollbacks[4].age).toEqual(aliceObject.age) const results: any = await Person.find({}) .lean() .exec() expect(results.length).toBe(1) expect(results[0].name).toEqual(bobObject.name) expect(results[0].age).toEqual(bobObject.age) } }) })
the_stack
import type * as d from '../../declarations'; import { basename, dirname, relative } from 'path'; import { isIterable, normalizePath, isString } from '@utils'; export const createInMemoryFs = (sys: d.CompilerSystem) => { const items: d.FsItems = new Map(); const outputTargetTypes = new Map<string, string>(); const accessData = async (filePath: string) => { const item = getItem(filePath); if (typeof item.exists === 'boolean') { return { exists: item.exists, isDirectory: item.isDirectory, isFile: item.isFile, }; } const data = { exists: false, isDirectory: false, isFile: false, }; const s = await stat(filePath); if (s) { item.exists = s.exists; item.isDirectory = s.isDirectory; item.isFile = s.isFile; data.exists = item.exists; data.isDirectory = item.isDirectory; data.isFile = item.isFile; } else { item.exists = false; } return data; }; const access = async (filePath: string) => { const data = await accessData(filePath); return data.exists; }; /** * Synchronous!!! Do not use!!! * (Only typescript transpiling is allowed to use) * @param filePath */ const accessSync = (filePath: string) => { const item = getItem(filePath); if (typeof item.exists !== 'boolean') { const s = statSync(filePath); item.exists = s.exists; item.isDirectory = s.isDirectory; item.isFile = s.isFile; } return item.exists; }; const copyFile = async (src: string, dest: string) => { const item = getItem(src); item.queueCopyFileToDest = dest; }; const emptyDirs = async (dirs: string[]) => { dirs = dirs .filter(isString) .map(normalizePath) .reduce((dirs, dir) => { if (!dirs.includes(dir)) { dirs.push(dir); } return dirs; }, [] as string[]); const allFsItems = await Promise.all(dirs.map((dir) => readdir(dir, { recursive: true }))); const reducedItems: string[] = []; for (const fsItems of allFsItems) { for (const f of fsItems) { if (!reducedItems.includes(f.absPath)) { reducedItems.push(f.absPath); } } } reducedItems.sort((a, b) => { const partsA = a.split('/').length; const partsB = b.split('/').length; if (partsA < partsB) return 1; if (partsA > partsB) return -1; return 0; }); await Promise.all(reducedItems.map(removeItem)); dirs.forEach((dir) => { const item = getItem(dir); item.isFile = false; item.isDirectory = true; item.queueWriteToDisk = true; item.queueDeleteFromDisk = false; }); }; const readdir = async (dirPath: string, opts: d.FsReaddirOptions = {}) => { dirPath = normalizePath(dirPath); const collectedPaths: d.FsReaddirItem[] = []; if (opts.inMemoryOnly === true) { let inMemoryDir = dirPath; if (!inMemoryDir.endsWith('/')) { inMemoryDir += '/'; } const inMemoryDirs = dirPath.split('/'); items.forEach((d, filePath) => { if (!filePath.startsWith(dirPath)) { return; } const parts = filePath.split('/'); if (parts.length === inMemoryDirs.length + 1 || (opts.recursive && parts.length > inMemoryDirs.length)) { if (d.exists) { const item: d.FsReaddirItem = { absPath: filePath, relPath: parts[inMemoryDirs.length], isDirectory: d.isDirectory, isFile: d.isFile, }; if (!shouldExcludeFromReaddir(opts, item)) { collectedPaths.push(item); } } } }); } else { // always a disk read await readDirectory(dirPath, dirPath, opts, collectedPaths); } return collectedPaths.sort((a, b) => { if (a.absPath < b.absPath) return -1; if (a.absPath > b.absPath) return 1; return 0; }); }; const readDirectory = async ( initPath: string, dirPath: string, opts: d.FsReaddirOptions, collectedPaths: d.FsReaddirItem[] ) => { // used internally only so we could easily recursively drill down // loop through this directory and sub directories // always a disk read!!removeDir const dirItems = await sys.readDir(dirPath); if (dirItems.length > 0) { // cache some facts about this path const item = getItem(dirPath); item.exists = true; item.isFile = false; item.isDirectory = true; await Promise.all( dirItems.map(async (dirItem) => { // let's loop through each of the files we've found so far // create an absolute path of the item inside of this directory const absPath = normalizePath(dirItem); const relPath = normalizePath(relative(initPath, absPath)); // get the fs stats for the item, could be either a file or directory const stats = await stat(absPath); const childItem: d.FsReaddirItem = { absPath: absPath, relPath: relPath, isDirectory: stats.isDirectory, isFile: stats.isFile, }; if (shouldExcludeFromReaddir(opts, childItem)) { return; } collectedPaths.push(childItem); if (opts.recursive === true && stats.isDirectory === true) { // looks like it's yet another directory // let's keep drilling down await readDirectory(initPath, absPath, opts, collectedPaths); } }) ); } }; const shouldExcludeFromReaddir = (opts: d.FsReaddirOptions, item: d.FsReaddirItem) => { if (item.isDirectory) { if (Array.isArray(opts.excludeDirNames)) { const base = basename(item.absPath); if (opts.excludeDirNames.some((dir) => base === dir)) { return true; } } } else { if (Array.isArray(opts.excludeExtensions)) { const p = item.relPath.toLowerCase(); if (opts.excludeExtensions.some((ext) => p.endsWith(ext))) { return true; } } } return false; }; const readFile = async (filePath: string, opts?: d.FsReadOptions) => { if (opts == null || opts.useCache === true || opts.useCache === undefined) { const item = getItem(filePath); if (item.exists && typeof item.fileText === 'string') { return item.fileText; } } const fileText = await sys.readFile(filePath); const item = getItem(filePath); if (typeof fileText === 'string') { if (fileText.length < MAX_TEXT_CACHE) { item.exists = true; item.isFile = true; item.isDirectory = false; item.fileText = fileText; } } else { item.exists = false; } return fileText; }; /** * Synchronous!!! Do not use!!! * (Only typescript transpiling is allowed to use) * @param filePath */ const readFileSync = (filePath: string, opts?: d.FsReadOptions) => { if (opts == null || opts.useCache === true || opts.useCache === undefined) { const item = getItem(filePath); if (item.exists && typeof item.fileText === 'string') { return item.fileText; } } const fileText = sys.readFileSync(filePath); const item = getItem(filePath); if (typeof fileText === 'string') { if (fileText.length < MAX_TEXT_CACHE) { item.exists = true; item.isFile = true; item.isDirectory = false; item.fileText = fileText; } } else { item.exists = false; } return fileText; }; const remove = async (itemPath: string) => { const stats = await stat(itemPath); if (stats.isDirectory === true) { await removeDir(itemPath); } else if (stats.isFile === true) { await removeItem(itemPath); } }; const removeDir = async (dirPath: string) => { const item = getItem(dirPath); item.isFile = false; item.isDirectory = true; if (!item.queueWriteToDisk) { item.queueDeleteFromDisk = true; } try { const dirItems = await readdir(dirPath, { recursive: true }); await Promise.all( dirItems.map((item) => { if (item.relPath.endsWith('.gitkeep')) { return null; } return removeItem(item.absPath); }) ); } catch (e) { // do not throw error if the directory never existed } }; const removeItem = async (filePath: string) => { const item = getItem(filePath); if (!item.queueWriteToDisk) { item.queueDeleteFromDisk = true; } }; const stat = async (itemPath: string) => { const item = getItem(itemPath); if (typeof item.isDirectory !== 'boolean' || typeof item.isFile !== 'boolean') { const stat = await sys.stat(itemPath); if (!stat.error) { item.exists = true; if (stat.isFile) { item.isFile = true; item.isDirectory = false; item.size = stat.size; } else if (stat.isDirectory) { item.isFile = false; item.isDirectory = true; item.size = stat.size; } else { item.isFile = false; item.isDirectory = false; item.size = null; } } else { item.exists = false; } } return { exists: !!item.exists, isFile: !!item.isFile, isDirectory: !!item.isDirectory, size: typeof item.size === 'number' ? item.size : 0, }; }; /** * Synchronous!!! Do not use!!! * Always returns an object, does not throw errors. * (Only typescript transpiling is allowed to use) * @param itemPath */ const statSync = (itemPath: string) => { const item = getItem(itemPath); if (typeof item.isDirectory !== 'boolean' || typeof item.isFile !== 'boolean') { const stat = sys.statSync(itemPath); if (!stat.error) { item.exists = true; if (stat.isFile) { item.isFile = true; item.isDirectory = false; item.size = stat.size; } else if (stat.isDirectory) { item.isFile = false; item.isDirectory = true; item.size = stat.size; } else { item.isFile = false; item.isDirectory = false; item.size = null; } } else { item.exists = false; } } return { exists: !!item.exists, isFile: !!item.isFile, isDirectory: !!item.isDirectory, }; }; const writeFile = async (filePath: string, content: string, opts?: d.FsWriteOptions) => { if (typeof filePath !== 'string') { throw new Error(`writeFile, invalid filePath: ${filePath}`); } if (typeof content !== 'string') { throw new Error(`writeFile, invalid content: ${filePath}`); } const results: d.FsWriteResults = { ignored: false, changedContent: false, queuedWrite: false, }; if (shouldIgnore(filePath) === true) { results.ignored = true; return results; } const item = getItem(filePath); item.exists = true; item.isFile = true; item.isDirectory = false; item.queueDeleteFromDisk = false; if (typeof item.fileText === 'string') { // compare strings but replace Windows CR to rule out any // insignificant new line differences results.changedContent = item.fileText.replace(/\r/g, '') !== content.replace(/\r/g, ''); } else { results.changedContent = true; } item.fileText = content; results.queuedWrite = false; if (opts != null) { if (typeof opts.outputTargetType === 'string') { outputTargetTypes.set(filePath, opts.outputTargetType); } if (opts.useCache === false) { item.useCache = false; } } if (opts != null && opts.inMemoryOnly === true) { // we don't want to actually write this to disk // just keep it in memory if (item.queueWriteToDisk) { // we already queued this file to write to disk // in that case we still need to do it results.queuedWrite = true; } else { // we only want this in memory and // it wasn't already queued to be written item.queueWriteToDisk = false; } // ensure in-memory directories are created await ensureDir(filePath, true); } else if (opts != null && opts.immediateWrite === true) { // if this is an immediate write then write the file // now and do not add it to the queue if (results.changedContent || opts.useCache !== true) { // writing the file to disk is a big deal and kicks off fs watchers // so let's just double check that the file is actually different first const existingFile = await sys.readFile(filePath); if (typeof existingFile === 'string') { results.changedContent = item.fileText.replace(/\r/g, '') !== existingFile.replace(/\r/g, ''); } if (results.changedContent) { await ensureDir(filePath, false); await sys.writeFile(filePath, item.fileText); } } } else { // we want to write this to disk (eventually) // but only if the content is different // from our existing cached content if (!item.queueWriteToDisk && results.changedContent === true) { // not already queued to be written // and the content is different item.queueWriteToDisk = true; results.queuedWrite = true; } } return results; }; const writeFiles = (files: { [filePath: string]: string } | Map<string, string>, opts?: d.FsWriteOptions) => { const writes: Promise<d.FsWriteResults>[] = []; if (isIterable(files)) { files.forEach((content, filePath) => { writes.push(writeFile(filePath, content, opts)); }); } else { Object.keys(files).map((filePath) => { writes.push(writeFile(filePath, files[filePath], opts)); }); } return Promise.all(writes); }; const commit = async () => { const instructions = getCommitInstructions(items); // ensure directories we need exist const dirsAdded = await commitEnsureDirs(instructions.dirsToEnsure, false); // write all queued the files const filesWritten = await commitWriteFiles(instructions.filesToWrite); // write all queued the files to copy const filesCopied = await commitCopyFiles(instructions.filesToCopy); // remove all the queued files to be deleted const filesDeleted = await commitDeleteFiles(instructions.filesToDelete); // remove all the queued dirs to be deleted const dirsDeleted = await commitDeleteDirs(instructions.dirsToDelete); instructions.filesToDelete.forEach(clearFileCache); instructions.dirsToDelete.forEach(clearDirCache); // return only the files that were return { filesCopied, filesWritten, filesDeleted, dirsDeleted, dirsAdded, }; }; const ensureDir = async (p: string, inMemoryOnly: boolean) => { const allDirs: string[] = []; while (true) { p = dirname(p); if ( typeof p === 'string' && p.length > 0 && p !== '/' && p.endsWith(':/') === false && p.endsWith(':\\') === false ) { allDirs.push(p); } else { break; } } allDirs.reverse(); await commitEnsureDirs(allDirs, inMemoryOnly); }; const commitEnsureDirs = async (dirsToEnsure: string[], inMemoryOnly: boolean) => { const dirsAdded: string[] = []; for (const dirPath of dirsToEnsure) { const item = getItem(dirPath); if (item.exists === true && item.isDirectory === true) { // already cached that this path is indeed an existing directory continue; } try { // cache that we know this is a directory on disk item.exists = true; item.isDirectory = true; item.isFile = false; if (!inMemoryOnly) { await sys.createDir(dirPath); } dirsAdded.push(dirPath); } catch (e) {} } return dirsAdded; }; const commitCopyFiles = (filesToCopy: string[][]) => { const copiedFiles = Promise.all( filesToCopy.map(async (data) => { const src = data[0]; const dest = data[1]; await sys.copyFile(src, dest); return [src, dest]; }) ); return copiedFiles; }; const commitWriteFiles = (filesToWrite: string[]) => { const writtenFiles = Promise.all( filesToWrite.map(async (filePath) => { if (typeof filePath !== 'string') { throw new Error(`unable to writeFile without filePath`); } return commitWriteFile(filePath); }) ); return writtenFiles; }; const commitWriteFile = async (filePath: string) => { const item = getItem(filePath); if (item.fileText == null) { throw new Error(`unable to find item fileText to write: ${filePath}`); } await sys.writeFile(filePath, item.fileText); if (item.useCache === false) { clearFileCache(filePath); } return filePath; }; const commitDeleteFiles = async (filesToDelete: string[]) => { const deletedFiles = await Promise.all( filesToDelete.map(async (filePath) => { if (typeof filePath !== 'string') { throw new Error(`unable to unlink without filePath`); } await sys.removeFile(filePath); return filePath; }) ); return deletedFiles; }; const commitDeleteDirs = async (dirsToDelete: string[]) => { const dirsDeleted: string[] = []; for (const dirPath of dirsToDelete) { await sys.removeDir(dirPath); dirsDeleted.push(dirPath); } return dirsDeleted; }; const clearDirCache = (dirPath: string) => { dirPath = normalizePath(dirPath); items.forEach((_, f) => { const filePath = relative(dirPath, f).split('/')[0]; if (!filePath.startsWith('.') && !filePath.startsWith('/')) { clearFileCache(f); } }); }; const clearFileCache = (filePath: string) => { filePath = normalizePath(filePath); const item = items.get(filePath); if (item != null && !item.queueWriteToDisk) { items.delete(filePath); } }; const cancelDeleteFilesFromDisk = (filePaths: string[]) => { for (const filePath of filePaths) { const item = getItem(filePath); if (item.isFile === true && item.queueDeleteFromDisk === true) { item.queueDeleteFromDisk = false; } } }; const cancelDeleteDirectoriesFromDisk = (dirPaths: string[]) => { for (const dirPath of dirPaths) { const item = getItem(dirPath); if (item.queueDeleteFromDisk === true) { item.queueDeleteFromDisk = false; } } }; const getItem = (itemPath: string): d.FsItem => { itemPath = normalizePath(itemPath); let item = items.get(itemPath); if (item != null) { return item; } items.set( itemPath, (item = { exists: null, fileText: null, size: null, mtimeMs: null, isDirectory: null, isFile: null, queueCopyFileToDest: null, queueDeleteFromDisk: null, queueWriteToDisk: null, useCache: null, }) ); return item; }; const clearCache = () => items.clear(); const keys = () => Array.from(items.keys()).sort(); const getMemoryStats = () => `data length: ${items.size}`; const getBuildOutputs = () => { const outputs: d.BuildOutput[] = []; outputTargetTypes.forEach((outputTargetType, filePath) => { const output = outputs.find((o) => o.type === outputTargetType); if (output) { output.files.push(filePath); } else { outputs.push({ type: outputTargetType, files: [filePath], }); } }); outputs.forEach((o) => o.files.sort()); return outputs.sort((a, b) => { if (a.type < b.type) return -1; if (a.type > b.type) return 1; return 0; }); }; // only cache if it's less than 5MB-ish (using .length as a rough guess) // why 5MB? idk, seems like a good number for source text // it's pretty darn large to cover almost ALL legitimate source files // and anything larger is probably a REALLY large file and a rare case // which we don't need to eat up memory for const MAX_TEXT_CACHE = 5242880; const fs: d.InMemoryFileSystem = { access, accessSync, accessData, cancelDeleteDirectoriesFromDisk, cancelDeleteFilesFromDisk, clearCache, clearDirCache, clearFileCache, commit, copyFile, emptyDirs, getBuildOutputs, getItem, getMemoryStats, keys, readFile, readFileSync, readdir, remove, stat, statSync, sys, writeFile, writeFiles, }; return fs; }; export const getCommitInstructions = (items: d.FsItems) => { const instructions = { filesToDelete: [] as string[], filesToWrite: [] as string[], filesToCopy: [] as string[][], dirsToDelete: [] as string[], dirsToEnsure: [] as string[], }; items.forEach((item, itemPath) => { if (item.queueWriteToDisk === true) { if (item.isFile === true) { instructions.filesToWrite.push(itemPath); const dir = normalizePath(dirname(itemPath)); if (!instructions.dirsToEnsure.includes(dir)) { instructions.dirsToEnsure.push(dir); } const dirDeleteIndex = instructions.dirsToDelete.indexOf(dir); if (dirDeleteIndex > -1) { instructions.dirsToDelete.splice(dirDeleteIndex, 1); } const fileDeleteIndex = instructions.filesToDelete.indexOf(itemPath); if (fileDeleteIndex > -1) { instructions.filesToDelete.splice(fileDeleteIndex, 1); } } else if (item.isDirectory === true) { if (!instructions.dirsToEnsure.includes(itemPath)) { instructions.dirsToEnsure.push(itemPath); } const dirDeleteIndex = instructions.dirsToDelete.indexOf(itemPath); if (dirDeleteIndex > -1) { instructions.dirsToDelete.splice(dirDeleteIndex, 1); } } } else if (item.queueDeleteFromDisk === true) { if (item.isDirectory && !instructions.dirsToEnsure.includes(itemPath)) { instructions.dirsToDelete.push(itemPath); } else if (item.isFile && !instructions.filesToWrite.includes(itemPath)) { instructions.filesToDelete.push(itemPath); } } else if (typeof item.queueCopyFileToDest === 'string') { const src = itemPath; const dest = item.queueCopyFileToDest; instructions.filesToCopy.push([src, dest]); const dir = normalizePath(dirname(dest)); if (!instructions.dirsToEnsure.includes(dir)) { instructions.dirsToEnsure.push(dir); } const dirDeleteIndex = instructions.dirsToDelete.indexOf(dir); if (dirDeleteIndex > -1) { instructions.dirsToDelete.splice(dirDeleteIndex, 1); } const fileDeleteIndex = instructions.filesToDelete.indexOf(dest); if (fileDeleteIndex > -1) { instructions.filesToDelete.splice(fileDeleteIndex, 1); } } item.queueDeleteFromDisk = false; item.queueWriteToDisk = false; }); // add all the ancestor directories for each directory too for (let i = 0, ilen = instructions.dirsToEnsure.length; i < ilen; i++) { const segments = instructions.dirsToEnsure[i].split('/'); for (let j = 2; j < segments.length; j++) { const dir = segments.slice(0, j).join('/'); if (instructions.dirsToEnsure.includes(dir) === false) { instructions.dirsToEnsure.push(dir); } } } // sort directories so shortest paths are ensured first instructions.dirsToEnsure.sort((a, b) => { const segmentsA = a.split('/').length; const segmentsB = b.split('/').length; if (segmentsA < segmentsB) return -1; if (segmentsA > segmentsB) return 1; if (a.length < b.length) return -1; if (a.length > b.length) return 1; return 0; }); // sort directories so longest paths are removed first instructions.dirsToDelete.sort((a, b) => { const segmentsA = a.split('/').length; const segmentsB = b.split('/').length; if (segmentsA < segmentsB) return 1; if (segmentsA > segmentsB) return -1; if (a.length < b.length) return 1; if (a.length > b.length) return -1; return 0; }); for (const dirToEnsure of instructions.dirsToEnsure) { const i = instructions.dirsToDelete.indexOf(dirToEnsure); if (i > -1) { instructions.dirsToDelete.splice(i, 1); } } instructions.dirsToDelete = instructions.dirsToDelete.filter((dir) => { if (dir === '/' || dir.endsWith(':/') === true) { return false; } return true; }); instructions.dirsToEnsure = instructions.dirsToEnsure.filter((dir) => { const item = items.get(dir); if (item != null && item.exists === true && item.isDirectory === true) { return false; } if (dir === '/' || dir.endsWith(':/')) { return false; } return true; }); return instructions; }; export const shouldIgnore = (filePath: string) => { filePath = filePath.trim().toLowerCase(); return IGNORE.some((ignoreFile) => filePath.endsWith(ignoreFile)); }; const IGNORE = ['.ds_store', '.gitignore', 'desktop.ini', 'thumbs.db'];
the_stack
import * as assert from 'power-assert'; import {dtsmake} from '../src/dtsmake'; import fs = require('fs'); describe("TypeScript d.ts file output tests,", ()=>{ let dg = new dtsmake.DTSMake(); context("tsObjToDTS()", ()=>{ it("shoud be replace ternjs Class instance path",()=>{ const p = [ { type:dtsmake.TSObjType.CLASS, name:"param", class:"+Klass" } ]; let out = dg.tsObjToDTS(p[0]); let answer = "param : Klass" assert(out === answer, `out strings should be ${answer}.`); }); it("should be replace ternjs array",()=>{ const to = { type:dtsmake.TSObjType.ARRAY, arrayType:[ { type:dtsmake.TSObjType.ANY } ] }; let out = dg.tsObjToDTS(to); let answer = "Array<any>"; assert(out === answer, `out strings ${out} should be ${answer}.`); }); it.skip("shoud be replace ternjs !ret",()=>{ const p = [ { type:dtsmake.TSObjType.OBJECT, name:"param", class:"!ret" } ]; let out = dg.tsObjToDTS(p[0]); let answer = "param : /* !ret */" assert(out === answer, `out strings should be ${answer}.`); }); it("should convert JS native global objects",()=>{ const g = [ "Object", "Function", "Boolean", "Symbol", "Error", "EvalError", "InternalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "Number", "Math", "Date", "String", "RegExp", "Array", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "JSON", "Promise", "Generator", "GeneratorFunction", "Reflect", "Proxy" ]; let p:dtsmake.TSObj[] = []; let answer:string[] = []; let out:string[] = []; for(let i in g){ let o:dtsmake.TSObj = {type:9, name:"a"+i, class:""}; o.class = g[i]; p.push(o); answer.push(`a${i} : ${g[i]}`); out.push(dg.tsObjToDTS(p[p.length-1])); } assert.deepEqual(out, answer); }) }); context("paramsToDTS()", ()=>{ it("should be able to replace ternjs Class instance path", ()=>{ const p = [ { type:dtsmake.TSObjType.CLASS, name:"param", class:"+Klass" } ]; let out = dg.paramsToDTS(p); let answer = "param : Klass" assert(out === answer); }) }); context("convertTSObjToString()", ()=>{ beforeEach(()=>{ dg["depth"] = 0; }) it("should convert simple function", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ {type:dtsmake.TSObjType.NUMBER}, {type:dtsmake.TSObjType.STRING}, ], params:null } ]; const defName = "example"; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * * @return */ declare function ${defName}(): number | string; `; assert.deepEqual(out, answer); }); it("should convert constructor without return type annotation", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ {type:dtsmake.TSObjType.VOID} ], params:null } ]; const defName = "new "; dg.option.isAnnotateTypeInstance = false; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * */ declare function ${defName}(); `; assert.deepEqual(out, answer); }); it("should convert constructor with return type annotation", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ {type:dtsmake.TSObjType.VOID} ], params:null } ]; const defName = "new "; dg.option.isAnnotateTypeInstance = true; dg.option.isOutVoidAsAny = false; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * */ declare function ${defName}(): void; `; assert.deepEqual(out, answer); }); it("should convert constructor with return type annotation void as any", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ {type:dtsmake.TSObjType.VOID} ], params:null } ]; const defName = "new "; dg.option.isAnnotateTypeInstance = true; dg.option.isOutVoidAsAny = true; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * */ declare function ${defName}(): /* void */ any; `; assert.deepEqual(out, answer); }); it("should not output ret name prop", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ { type:dtsmake.TSObjType.NUMBER, name:"notOutput" }, { type:dtsmake.TSObjType.STRING, name:"notOutput" }, ], params:null } ]; const defName = "example"; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * * @return */ declare function ${defName}(): number | string; `; assert.deepEqual(out, answer); }); it("should wrap fn() return type", ()=>{ const def:dtsmake.TSObj[] = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ { type:dtsmake.TSObjType.OBJECT, class:"sinon.collection.stub.!ret" }, { type:dtsmake.TSObjType.FUNCTION, params:null, ret:[ {type:dtsmake.TSObjType.VOID} ] }, ], params:null } ]; const defName = "example"; dg.option.isOutVoidAsAny = false; const out = dg.convertTSObjToString(defName,def); const answer = ` /** * * @return */ declare function ${defName}(): /* sinon.collection.stub.!ret */ any | (() => void); `; assert.deepEqual(out, answer); }); it("should wrap fn() return type2", ()=>{ const def = [ { type:dtsmake.TSObjType.FUNCTION, ret:[ { type:dtsmake.TSObjType.OBJECT, class:"!0" } ], params:[ [ {"type":9,"name":"fake","class":"sinon.collection.stub.!ret"}, {"type":5,"name":"fake","ret":[{"type":1}], "params":<any>null} ] ] } ]; const defName = "add"; dg.option.isOutVoidAsAny = false; const out = dg.convertTSObjToString(defName,<any>def); const answer = ` /** * * @param fake * @return */ declare function ${defName}(fake : /* sinon.collection.stub.!ret */ any | (() => void)): /* sinon.collection.stub.!ret */ any | (() => void); `; assert.deepEqual(out, answer); }); }); context("parseToDTS()", ()=>{ it("should convert !type only interface",()=>{ const def = { "!define":{ "!node.``/node_modules/tern/lib/tern`js.Server.prototype.flush.!0": { "!type": [ { "type": 5, "ret": [ { "type": 1 } ], "params": <any>null } ], "!span": [ { "type": 9, "class": "6371[214:6]-6643[223:7]" } ], "!!!dtsinterface!!!": "Flush0", "!!!dtsnamespace!!!": "tern" } } }; dg.option.isOutVoidAsAny = false; const out = dg.parseToDTS(def); const st = "!node.``/node_modules/tern/lib/tern`js.Server.prototype.flush.!0"; const ans = `declare namespace tern{ // ${st} /** * */ interface Flush0 { /** * */ (): void; } } `; assert.deepEqual(out,ans); }); it("should not convert <!> prop (maybe ternjs internal def)",()=>{ const def = { "!define":{ "passes": { "<i>": { "!type": [ { "type": 6, "arrayType": [ { "type": 0 } ] } ], "!span": [ { "type": 9, "class": "3425[113:43]-3429[113:47]" } ] }, "!span": [ { "type": 9, "class": "2904[103:9]-2910[103:15]" } ] } } }; dg.option.isOutVoidAsAny = false; dg["isInInterfaceOrClass"] = true; const out = dg.parseToDTS(def); const ans = `// passes /** * */ declare interface passes { } `; assert.deepEqual(out, ans); }); it("should convert node.js node correctly",()=>{ let def = { "!define": { "!modules": { "gulpHeader": { "!type": [ { "type": 5, "ret": [ { "type": 0 } ], "params": [ { "name": "headerText", "type": 4 }, { "name": "data", "type": 7, "class": "GulpHeader1" } ] }, { "type": 5, "ret": [ { "type": 0 } ], "params": [ { "name": "override", "type": 0 } ] } ], "!doc": "gulp-header plugin" } } } }; dg.option.isOutVoidAsAny = false; const out = dg.parseToDTS(def); const ans = ` /** * gulp-header plugin * @param headerText * @param data * @return */ declare function gulpHeader(headerText : string, data : GulpHeader1): any; /** * gulp-header plugin * @param override * @return */ declare function gulpHeader(override : any): any; `; assert.deepEqual(out, ans); }); }); context("outJSDoc()", ()=>{ beforeEach(()=>{ dg["depth"] = 0; }) it("should output simple jsdoc",()=>{ const c = "COMMENT"; const u = "http://example.jp/"; const p = ["hoge","fuga"]; const r = "RETURN"; const out = dg.outJSDoc(c,u,p,r); const answer = ` /** * ${c} * @param ${p[0]} * @param ${p[1]} * @return ${r} * @url ${u} */ `; assert.deepEqual(out, answer); }); it("should output multiline jsdoc",()=>{ dg["depth"] = 1; const c = "COMMENT\nMULTILINE\nSAMPLE"; const u = "http://example.jp/"; const p = ["hoge","fuga"]; const r = "RETURN"; const out = dg.outJSDoc(c,u,p,r); const answer = ` /** * COMMENT * MULTILINE * SAMPLE * @param ${p[0]} * @param ${p[1]} * @return ${r} * @url ${u} */ `; assert.deepEqual(out, answer); dg["depth"]--; }) }); context("outFuncJsDocs()", ()=>{ beforeEach(()=>{ dg["depth"] = 0; }) it("should output simple function jsdoc",()=>{ const t:dtsmake.TSObj = { type:dtsmake.TSObjType.FUNCTION, params:[ { type:dtsmake.TSObjType.NUMBER, name:"hoge" }, { type:dtsmake.TSObjType.STRING, name:"fuga" } ], ret:[ { type:dtsmake.TSObjType.NUMBER }, { type:dtsmake.TSObjType.STRING } ] }; const out = dg.outFuncJsDocs(t); const answer = ` /** * * @param hoge * @param fuga * @return */ `; assert.deepEqual(out, answer); }); }); context("addDeclare()", ()=>{ beforeEach(()=>{ dg["depth"] = 0; }) it("should out 'declare' when this.depth === 0", ()=>{ const out = dg.addDeclare(); const answer = "declare "; assert.deepEqual(out, answer); }); }); context("resolveNamespace()", ()=>{ it("should resolve !ret containing path",()=>{ const path = "sinon.spy.reset.!ret.named.!ret"; const out = dg.resolveNamespace(path.split(".")); const ans = "sinon.spy.ResetRet"; assert.deepEqual(out, ans); }) it("should resolve !node containing path",()=>{ const path = "!node.``/node_modules/tern/lib/tern`js.Server.prototype.flush.!0"; const out = dg.resolveNamespace(path.split(".")); //dg.option.isOutExport = true; //dg.nodeModuleName = "``/node_modules/tern/lib/tern`js"; //dg.userDefinedModuleName = "tern"; const ans = "Server.prototype"; assert.deepEqual(out, ans); }); it("should resolve !node containing path with replacing",()=>{ const path = "!node.``/node_modules/tern/lib/tern`js.Server.prototype.flush.!0"; dg.option.isOutExport = true; dg["nodeModuleName"] = path.split(".")[1]; dg.userDefinedModuleName = "tern"; const out = dg.resolveNamespace(path.split(".")); const ans = "tern.Server.prototype"; //console.log("dg[nodeModuleName]:"+dg["nodeModuleName"]); assert.deepEqual(path.split(".")[1], dg.nodeModuleName); assert.deepEqual(out, ans); }); }); context("resolvePathToDTSName", ()=>{ it("should resolve DTSName", ()=>{ const path = "sinon.Event.prototype.initEvent.!3"; const out = dg.resolvePathToDTSName(path.split(".")); const ans = "InitEvent3"; assert.deepEqual(out, ans); }); it("should resolve tern def node only path DTSName",()=>{ const path = "!modules.node_modules/gulp-header/index`js.!1"; dg.nodeModuleName = "node_modules/gulp-header/index`js"; dg.option.isOutExport = true; dg.option.exportModuleName = "gulp-header"; dg.userDefinedModuleName = "gulpHeader"; const out = dg.resolvePathToDTSName(path.split(".")); const ans = "GulpHeader1"; assert.deepEqual(out, ans); }); }); });
the_stack
import { Node } from "@ff/graph/Component"; import CVTask, { types } from "./CVTask"; import ToursTaskView from "../ui/story/ToursTaskView"; import CVDocument from "./CVDocument"; import CVTours from "./CVTours"; import CVSnapshots, { EEasingCurve } from "./CVSnapshots"; import { ELanguageStringType, ELanguageType, DEFAULT_LANGUAGE } from "client/schema/common"; //////////////////////////////////////////////////////////////////////////////// let _nextTourIndex = 0; let _nextStepIndex = 0; export default class CVToursTask extends CVTask { static readonly typeName: string = "CVToursTask"; static readonly text: string = "Tours"; static readonly icon: string = "globe"; protected static readonly ins = { createTour: types.Event("Tours.Create"), deleteTour: types.Event("Tours.Delete"), moveTourUp: types.Event("Tours.MoveUp"), moveTourDown: types.Event("Tours.MoveDown"), tourTitle: types.String("Tour.Title"), tourLead: types.String("Tour.Lead"), tourTags: types.String("Tour.Tags"), updateStep: types.Event("Step.Update"), createStep: types.Event("Step.Create"), deleteStep: types.Event("Step.Delete"), moveStepUp: types.Event("Step.MoveUp"), moveStepDown: types.Event("Step.MoveDown"), stepTitle: types.String("Step.Title"), stepCurve: types.Enum("Step.Curve", EEasingCurve), stepDuration: types.Number("Step.Duration", 1), stepThreshold: types.Percent("Step.Threshold", 0.5), language: types.Option("Task.Language", Object.keys(ELanguageStringType).map(key => ELanguageStringType[key]), ELanguageStringType[ELanguageType.EN]), }; protected static readonly outs = { }; ins = this.addInputs<CVTask, typeof CVToursTask.ins>(CVToursTask.ins); outs = this.addOutputs<CVTask, typeof CVToursTask.outs>(CVToursTask.outs); tours: CVTours = null; machine: CVSnapshots = null; constructor(node: Node, id: string) { super(node, id); const configuration = this.configuration; configuration.bracketsVisible = false; } create() { super.create(); this.startObserving(); } dispose() { this.stopObserving(); super.dispose(); } update(context) { const ins = this.ins; const tours = this.tours; const machine = this.machine; if (!tours || !this.activeDocument) { return false; } const tourList = tours.tours; const tourIndex = tours.outs.tourIndex.value; const tour = tourList[tourIndex]; const languageManager = this.activeDocument.setup.language; if(ins.language.changed) { const newLanguage = ELanguageType[ELanguageType[ins.language.value]]; languageManager.addLanguage(newLanguage); // add in case this is a currently inactive language languageManager.ins.language.setValue(newLanguage); //outs.language.setValue(newLanguage); } if (tour) { const stepList = tour.steps; const stepIndex = tours.outs.stepIndex.value; const step = stepList[stepIndex]; // tour step actions if (ins.createStep.changed) { const id = machine.setState({ values: machine.getCurrentValues(), curve: EEasingCurve.EaseOutQuad, duration: 1.5, threshold: 0.5, }); stepList.splice(stepIndex + 1, 0, { title: "", titles: {}, id }); stepList[stepIndex + 1].titles[DEFAULT_LANGUAGE] = "New Step #" + _nextStepIndex++; tours.ins.stepIndex.setValue(stepIndex + 1); return true; } if (step) { if (ins.stepTitle.changed || ins.stepCurve.changed || ins.stepDuration.changed || ins.stepThreshold.changed) { tours.stepTitle = ins.stepTitle.value; machine.ins.curve.setValue(ins.stepCurve.value); machine.ins.duration.setValue(ins.stepDuration.value); machine.ins.threshold.setValue(ins.stepThreshold.value); tours.ins.stepIndex.setValue(stepIndex); return true; } if (ins.updateStep.changed) { machine.ins.store.set(); return true; } if (ins.deleteStep.changed) { stepList.splice(stepIndex, 1); machine.ins.delete.set(); tours.ins.stepIndex.setValue(stepIndex); return true; } if (stepIndex > 0 && ins.moveStepUp.changed) { stepList[stepIndex] = stepList[stepIndex - 1]; stepList[stepIndex - 1] = step; tours.ins.stepIndex.setValue(stepIndex - 1); return true; } if (stepIndex < stepList.length - 1 && ins.moveStepDown.changed) { stepList[stepIndex] = stepList[stepIndex + 1]; stepList[stepIndex + 1] = step; tours.ins.stepIndex.setValue(stepIndex + 1); return true; } } // tour actions if (ins.tourTitle.changed || ins.tourLead.changed || ins.tourTags.changed) { tours.title = ins.tourTitle.value; tours.lead = ins.tourLead.value; tours.taglist = ins.tourTags.value.split(",").map(tag => tag.trim()).filter(tag => !!tag); tours.ins.tourIndex.set(); return true; } if (ins.deleteTour.changed) { tour.steps.forEach(step => machine.deleteState(step.id)); tourList.splice(tourIndex, 1); tours.ins.tourIndex.setValue(tourIndex); tours.outs.count.setValue(tourList.length); return true; } if (tourIndex > 0 && ins.moveTourUp.changed) { tourList[tourIndex] = tourList[tourIndex - 1]; tourList[tourIndex - 1] = tour; tours.ins.tourIndex.setValue(tourIndex - 1); return true; } if (tourIndex < tourList.length - 1 && ins.moveTourDown.changed) { tourList[tourIndex] = tourList[tourIndex + 1]; tourList[tourIndex + 1] = tour; tours.ins.tourIndex.setValue(tourIndex + 1); return true; } } if (ins.createTour.changed) { tourList.splice(tourIndex + 1, 0, { title: "", titles: {}, lead: "", leads: {}, tags: [], taglist: {}, steps: [] }); tourList[tourIndex + 1].titles[DEFAULT_LANGUAGE] = "New Tour #" + _nextTourIndex++; tours.ins.tourIndex.setValue(tourIndex + 1); tours.outs.count.setValue(tourList.length); languageManager.ins.language.setValue(ELanguageType[DEFAULT_LANGUAGE]); return true; } return true; } createView() { return new ToursTaskView(this); } activateTask() { super.activateTask(); if (this.tours) { this.tours.ins.enabled.setValue(true); } this.synchLanguage(); } deactivateTask() { if (this.tours && this.tours.outs.count.value === 0) { this.tours.ins.enabled.setValue(false); } super.deactivateTask(); } protected onActiveDocument(previous: CVDocument, next: CVDocument) { if (previous) { if (this.isActiveTask) { this.tours.ins.enabled.setValue(false); } this.tours.outs.tourIndex.off("value", this.onTourChange, this); this.tours.outs.stepIndex.off("value", this.onStepChange, this); previous.setup.language.outs.language.off("value", this.onDocumentLanguageChange, this); this.tours = null; this.machine = null; } if (next) { this.tours = next.setup.tours; this.machine = this.tours.getComponent(CVSnapshots); this.tours.outs.tourIndex.on("value", this.onTourChange, this); this.tours.outs.stepIndex.on("value", this.onStepChange, this); next.setup.language.outs.language.on("value", this.onDocumentLanguageChange, this); if (this.isActiveTask) { this.tours.ins.enabled.setValue(true); } } this.changed = true; } protected onTourChange() { const ins = this.ins; const tours = this.tours; const tour = tours.activeTour; ins.tourTitle.setValue(tour ? tours.title : "", true); ins.tourLead.setValue(tour ? tours.lead : "", true); ins.tourTags.setValue(tour ? tours.taglist.join(", ") : "", true); } protected onStepChange() { const ins = this.ins; const step = this.tours.activeStep; const state = step ? this.machine.getState(step.id) : null; ins.stepTitle.setValue(step ? this.tours.stepTitle : "", true); ins.stepCurve.setValue(state ? state.curve : EEasingCurve.Linear, true); ins.stepDuration.setValue(state ? state.duration : 1, true); ins.stepThreshold.setValue(state ? state.threshold : 0.5, true); } protected onDocumentLanguageChange() { const tours = this.tours; this.onTourChange(); this.onStepChange(); tours.ins.tourIndex.setValue(tours.outs.tourIndex.value); // trigger UI refresh this.synchLanguage(); } // Make sure this task language matches document protected synchLanguage() { const {ins} = this; const languageManager = this.activeDocument.setup.language; if(ins.language.value !== languageManager.outs.language.value) { ins.language.setValue(languageManager.outs.language.value, true); } } }
the_stack
import React, { Component } from 'react' import { testable } from '@instructure/ui-testable' import { withStyle, jsx } from '@instructure/emotion' import { safeCloneElement } from '@instructure/ui-react-utils' import { TreeButton } from '../TreeButton' import generateStyles from './styles' import generateComponentTheme from './theme' import type { TreeBrowserCollectionProps } from './props' import { allowedProps, propTypes } from './props' /** --- parent: TreeBrowser id: TreeBrowser.Collection --- **/ @withStyle(generateStyles, generateComponentTheme) @testable() class TreeCollection extends Component<TreeBrowserCollectionProps> { static readonly componentId = 'TreeBrowser.Collection' static allowedProps = allowedProps static propTypes = propTypes static defaultProps = { collections: [], items: [], expanded: false, selection: '', size: 'medium', variant: 'folderTree', onItemClick: function () {}, onCollectionClick: function () {}, onKeyDown: function () {}, id: undefined, name: undefined, descriptor: undefined, collectionIconExpanded: undefined, collectionIcon: undefined, itemIcon: undefined, // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'props' implicitly has an 'any' type. getItemProps: (props) => props, // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'props' implicitly has an 'any' type. getCollectionProps: (props) => props, numChildren: undefined, level: undefined, position: undefined, renderBeforeItems: null, renderAfterItems: null, containerRef: function () {}, isCollectionFlattened: false, renderContent: undefined } ref: Element | null = null // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'props' implicitly has an 'any' type. constructor(props) { super(props) this.state = { focused: '' } } componentDidMount() { this.props.makeStyles?.() } componentDidUpdate() { this.props.makeStyles?.() } get itemsLevel() { const { level, isCollectionFlattened } = this.props // @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. return isCollectionFlattened ? level : level + 1 } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'e' implicitly has an 'any' type. handleFocus = (e, item) => { e.stopPropagation() this.setState({ focused: `${item.type}_${item.id}` }) } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'e' implicitly has an 'any' type. handleBlur = (e, item) => { e.stopPropagation() this.setState({ focused: '' }) } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'e' implicitly has an 'any' type. handleCollectionClick = (e) => { const { id, onCollectionClick, expanded } = this.props const collection = { id, expanded: !expanded, type: 'collection' } if (onCollectionClick && typeof onCollectionClick === 'function') { onCollectionClick(e, collection) } } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'e' implicitly has an 'any' type. handleCollectionKeyDown = (e) => { const { id, onKeyDown, expanded } = this.props const collection = { id, expanded: !expanded, type: 'collection' } if (onKeyDown && typeof onKeyDown === 'function') { onKeyDown(e, collection) } } get collectionsCount() { const collections = this.props.collections return collections && collections.length > 0 ? collections.length : 0 } get itemsCount() { const items = this.props.items return items && items.length > 0 ? items.length : 0 } get childCount() { return ( this.collectionsCount + this.itemsCount + (this.props.renderBeforeItems ? 1 : 0) + (this.props.renderAfterItems ? 1 : 0) ) } renderChildren() { const { collections, items, id, renderBeforeItems, renderAfterItems } = this.props let position = 1 return ( <> {renderBeforeItems && this.renderCollectionChildren( id, renderBeforeItems, position++, 'before' )} {/* @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. */} {collections.map((collection) => { return this.renderCollectionNode(collection, position++) })} {/* @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. */} {items.map((item) => { return this.renderItemNode(item, position++) })} {renderAfterItems && this.renderCollectionChildren( id, renderAfterItems, position++, 'after' )} </> ) } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'collectionId' implicitly has an 'any' t... Remove this comment to see the full error message renderCollectionChildren(collectionId, child, position, keyword) { const { selection, onKeyDown, getItemProps, styles } = this.props const key = `${collectionId}_${keyword}` const ariaSelected = {} if (selection) { // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message ariaSelected['aria-selected'] = selection === `child_${key}` } const itemHash = { id: key, type: 'child' } // @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. const itemProps = getItemProps({ key: key, selected: selection === `child_${key}`, // @ts-expect-error ts-migrate(2339) FIXME: Property 'focused' does not exist on type 'Readonl... Remove this comment to see the full error message focused: this.state.focused === `child_${key}`, level: this.itemsLevel }) return ( <li id={key} role="treeitem" css={styles?.item} // @ts-expect-error ts-migrate(2322) FIXME: Type 'string' is not assignable to type 'number | ... Remove this comment to see the full error message tabIndex="-1" key={key} aria-posinset={position} aria-setsize={this.childCount} aria-level={this.itemsLevel} {...ariaSelected} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onClick={(e, n) => { if (typeof child.props.onClick === 'function') { child.props.onClick(e, n) } else { e.stopPropagation() } }} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onFocus={(e, n) => this.handleFocus(e, itemHash)} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onKeyDown={(e, n) => { if (typeof child.props.onKeyDown === 'function') { child.props.onKeyDown(e, n) } else { // @ts-expect-error ts-migrate(2722) FIXME: Cannot invoke an object which is possibly 'undefin... Remove this comment to see the full error message onKeyDown(e, itemHash) } }} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onBlur={(e, n) => this.handleBlur(e, itemHash)} > {safeCloneElement(child, itemProps)} </li> ) } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'collection' implicitly has an 'any' typ... Remove this comment to see the full error message renderCollectionNode(collection, position) { return ( <TreeCollection {...this.props} key={`c${position}`} id={collection.id} name={collection.name} descriptor={collection.descriptor} expanded={collection.expanded} items={collection.items} collections={collection.collections} numChildren={this.childCount} level={this.itemsLevel} containerRef={collection.containerRef} position={position} renderBeforeItems={collection.renderBeforeItems} renderAfterItems={collection.renderAfterItems} isCollectionFlattened={false} // only the root needs to be flattened /> ) } // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'item' implicitly has an 'any' type. renderItemNode(item, position) { const { selection, onItemClick, onKeyDown, getItemProps, styles } = this.props const ariaSelected = {} if (selection) { // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message ariaSelected['aria-selected'] = selection === `item_${item.id}` } const itemHash = { id: item.id, type: 'item' } // @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. const itemProps = getItemProps({ ...this.getCommonButtonProps(), id: item.id, name: item.name, descriptor: item.descriptor, thumbnail: item.thumbnail, selected: selection === `item_${item.id}`, // @ts-expect-error ts-migrate(2339) FIXME: Property 'focused' does not exist on type 'Readonl... Remove this comment to see the full error message focused: this.state.focused === `item_${item.id}`, type: 'item' }) return ( <li key={`i${position}`} // @ts-expect-error ts-migrate(2322) FIXME: Type 'string' is not assignable to type 'number | ... Remove this comment to see the full error message tabIndex="-1" role="treeitem" aria-label={item.name} css={styles?.item} aria-level={this.itemsLevel} aria-posinset={position} aria-setsize={this.childCount} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => any' is not assignable t... Remove this comment to see the full error message onClick={(e, n) => onItemClick(e, itemHash)} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => any' is not assignable t... Remove this comment to see the full error message onKeyDown={(e, n) => onKeyDown(e, itemHash)} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onFocus={(e, n) => this.handleFocus(e, itemHash)} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onBlur={(e, n) => this.handleBlur(e, itemHash)} {...ariaSelected} > <TreeButton {...itemProps} /> </li> ) } getCommonButtonProps() { return { id: this.props.id, name: this.props.name, descriptor: this.props.descriptor, size: this.props.size, variant: this.props.variant, itemIcon: this.props.itemIcon, level: this.itemsLevel, renderContent: this.props.renderContent } } render() { const { id, name, expanded, collectionIcon, collectionIconExpanded, isCollectionFlattened, getCollectionProps, level, position, styles } = this.props // @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. const collectionProps = getCollectionProps({ ...this.getCommonButtonProps(), expanded: expanded, collectionIcon: collectionIcon, collectionIconExpanded: collectionIconExpanded, type: 'collection', containerRef: this.props.containerRef, selected: this.props.selection === `collection_${id}`, // @ts-expect-error ts-migrate(2339) FIXME: Property 'focused' does not exist on type 'Readonl... Remove this comment to see the full error message focused: this.state.focused === `collection_${id}`, level }) const ariaSelected = {} if (this.props.selection) // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message ariaSelected['aria-selected'] = this.props.selection === `collection_${id}` return isCollectionFlattened ? ( this.renderChildren() ) : ( <li ref={(el) => { this.ref = el }} css={styles?.treeCollection} // @ts-expect-error ts-migrate(2322) FIXME: Type 'string' is not assignable to type 'number | ... Remove this comment to see the full error message tabIndex="-1" role="treeitem" aria-label={this.props.name} aria-level={level} aria-posinset={position} aria-setsize={this.props.numChildren} aria-expanded={expanded} onClick={this.handleCollectionClick} onKeyDown={this.handleCollectionKeyDown} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onFocus={(e, n) => this.handleFocus(e, { id: id, type: 'collection' })} // @ts-expect-error ts-migrate(2322) FIXME: Type '(e: any, n: any) => void' is not assignable ... Remove this comment to see the full error message onBlur={(e, n) => this.handleBlur(e, { id: id, type: 'collection' })} {...ariaSelected} > <TreeButton {...collectionProps} /> {expanded && this.childCount > 0 && ( <ul aria-label={name} css={styles?.list} role="group"> {this.renderChildren()} </ul> )} </li> ) } } export default TreeCollection export { TreeCollection }
the_stack
import { Directionality } from '@angular/cdk/bidi'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { SelectionModel } from '@angular/cdk/collections'; import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, DoCheck, ElementRef, EventEmitter, Inject, Input, OnDestroy, OnInit, Optional, Output, QueryList, Self, ViewEncapsulation } from '@angular/core'; import { ControlValueAccessor, FormControlName, FormGroupDirective, NG_VALIDATORS, NgControl, NgForm, NgModel, Validator } from '@angular/forms'; import { FocusKeyManager } from '@ptsecurity/cdk/a11y'; import { BACKSPACE, END, HOME } from '@ptsecurity/cdk/keycodes'; import { CanUpdateErrorState, CanUpdateErrorStateCtor, ErrorStateMatcher, MC_VALIDATION, McValidationOptions, mixinErrorState, setMosaicValidation } from '@ptsecurity/mosaic/core'; import { McCleaner, McFormFieldControl } from '@ptsecurity/mosaic/form-field'; import { merge, Observable, Subject, Subscription } from 'rxjs'; import { startWith, takeUntil } from 'rxjs/operators'; import { McTagTextControl } from './tag-text-control'; import { McTag, McTagEvent, McTagSelectionChange } from './tag.component'; export class McTagListBase { constructor( public defaultErrorStateMatcher: ErrorStateMatcher, public parentForm: NgForm, public parentFormGroup: FormGroupDirective, public ngControl: NgControl ) {} } // tslint:disable-next-line:naming-convention export const McTagListMixinBase: CanUpdateErrorStateCtor & typeof McTagListBase = mixinErrorState(McTagListBase); // Increasing integer for generating unique ids for tag-list components. let nextUniqueId = 0; /** Change event object that is emitted when the tag list value has changed. */ export class McTagListChange { constructor(public source: McTagList, public value: any) {} } @Component({ selector: 'mc-tag-list', exportAs: 'mcTagList', templateUrl: 'tag-list.partial.html', styleUrls: ['tag-list.scss'], host: { class: 'mc-tag-list', '[class.mc-disabled]': 'disabled', '[class.mc-invalid]': 'errorState', '[attr.tabindex]': 'disabled ? null : tabIndex', '[id]': 'uid', '(focus)': 'focus()', '(blur)': 'blur()', '(keydown)': 'keydown($event)' }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [{ provide: McFormFieldControl, useExisting: McTagList }] }) export class McTagList extends McTagListMixinBase implements McFormFieldControl<any>, ControlValueAccessor, AfterContentInit, DoCheck, OnInit, OnDestroy, CanUpdateErrorState { readonly controlType: string = 'tag-list'; /** Combined stream of all of the child tags' selection change events. */ get tagSelectionChanges(): Observable<McTagSelectionChange> { return merge(...this.tags.map((tag) => tag.selectionChange)); } /** Combined stream of all of the child tags' focus change events. */ get tagFocusChanges(): Observable<McTagEvent> { return merge(...this.tags.map((tag) => tag.onFocus)); } /** Combined stream of all of the child tags' blur change events. */ get tagBlurChanges(): Observable<McTagEvent> { return merge(...this.tags.map((tag) => tag.onBlur)); } /** Combined stream of all of the child tags' remove change events. */ get tagRemoveChanges(): Observable<McTagEvent> { return merge(...this.tags.map((tag) => tag.destroyed)); } /** The array of selected tags inside tag list. */ get selected(): McTag[] | McTag { return this.multiple ? this.selectionModel.selected : this.selectionModel.selected[0]; } get canShowCleaner(): boolean { return this.cleaner && this.tags.length > 0; } /** Whether the user should be allowed to select multiple tags. */ @Input() get multiple(): boolean { return this._multiple; } set multiple(value: boolean) { this._multiple = coerceBooleanProperty(value); } /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. */ @Input() get compareWith(): (o1: any, o2: any) => boolean { return this._compareWith; } set compareWith(fn: (o1: any, o2: any) => boolean) { this._compareWith = fn; if (this.selectionModel) { // A different comparator means the selection could change. this.initializeSelection(); } } /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get value(): any { return this._value; } set value(value: any) { this.writeValue(value); this._value = value; } /** * Implemented as part of McFormFieldControl. * @docs-private */ get id(): string { return this.tagInput ? this.tagInput.id : this.uid; } /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get required(): boolean { return this._required; } set required(value: boolean) { this._required = coerceBooleanProperty(value); this.stateChanges.next(); } /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get placeholder(): string { return this.tagInput ? this.tagInput.placeholder : this._placeholder; } set placeholder(value: string) { this._placeholder = value; this.stateChanges.next(); } /** Whether any tags or the mcTagInput inside of this tag-list has focus. */ get focused(): boolean { return (this.tagInput && this.tagInput.focused) || this.hasFocusedTag(); } /** * Implemented as part of McFormFieldControl. * @docs-private */ get empty(): boolean { return (!this.tagInput || this.tagInput.empty) && this.tags.length === 0; } /** * Implemented as part of McFormFieldControl. * @docs-private */ get shouldLabelFloat(): boolean { return !this.empty || this.focused; } /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get disabled(): boolean { return this.ngControl ? !!this.ngControl.disabled : this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); this.syncTagsDisabledState(); } /** * Whether or not this tag list is selectable. When a tag list is not selectable, * the selected states for all the tags inside the tag list are always ignored. */ @Input() get selectable(): boolean { return this._selectable; } set selectable(value: boolean) { this._selectable = coerceBooleanProperty(value); if (this.tags) { this.tags.forEach((tag) => tag.tagListSelectable = this._selectable); } } @Input() get tabIndex(): number { return this._tabIndex; } set tabIndex(value: number) { this.userTabIndex = value; this._tabIndex = value; } private _tabIndex = 0; /** * Event that emits whenever the raw value of the tag-list changes. This is here primarily * to facilitate the two-way binding for the `value` input. * @docs-private */ @Output() readonly valueChange: EventEmitter<any> = new EventEmitter<any>(); uid: string = `mc-tag-list-${nextUniqueId++}`; /** * User defined tab index. * When it is not null, use user defined tab index. Otherwise use tabIndex */ userTabIndex: number | null = null; keyManager: FocusKeyManager<McTag>; selectionModel: SelectionModel<McTag>; tagChanges = new EventEmitter<any>(); /** An object used to control when error messages are shown. */ @Input() errorStateMatcher: ErrorStateMatcher; /** Orientation of the tag list. */ @Input('orientation') orientation: 'horizontal' | 'vertical' = 'horizontal'; /** Event emitted when the selected tag list value has been changed by the user. */ @Output() readonly change: EventEmitter<McTagListChange> = new EventEmitter<McTagListChange>(); @ContentChild('mcTagListCleaner', { static: true }) cleaner: McCleaner; /** The tag components contained within this tag list. */ @ContentChildren(McTag, { // Need to use `descendants: true`, // Ivy will no longer match indirect descendants if it's left as false. descendants: true }) tags: QueryList<McTag>; private _value: any; private _required: boolean = false; private _placeholder: string; private _disabled: boolean = false; private _selectable: boolean = true; /** The tag input to add more tags */ private tagInput: McTagTextControl; private _multiple: boolean = false; /** * When a tag is destroyed, we store the index of the destroyed tag until the tags * query list notifies about the update. This is necessary because we cannot determine an * appropriate tag that should receive focus until the array of tags updated completely. */ private lastDestroyedTagIndex: number | null = null; /** Subject that emits when the component has been destroyed. */ private destroyed = new Subject<void>(); /** Subscription to focus changes in the tags. */ private tagFocusSubscription: Subscription | null; /** Subscription to blur changes in the tags. */ private tagBlurSubscription: Subscription | null; /** Subscription to selection changes in tags. */ private tagSelectionSubscription: Subscription | null; /** Subscription to remove changes in tags. */ private tagRemoveSubscription: Subscription | null; constructor( protected elementRef: ElementRef<HTMLElement>, private changeDetectorRef: ChangeDetectorRef, defaultErrorStateMatcher: ErrorStateMatcher, @Optional() @Inject(NG_VALIDATORS) public rawValidators: Validator[], @Optional() @Inject(MC_VALIDATION) private mcValidation: McValidationOptions, @Optional() private dir: Directionality, @Optional() parentForm: NgForm, @Optional() parentFormGroup: FormGroupDirective, @Optional() @Self() ngControl: NgControl, @Optional() @Self() public ngModel: NgModel, @Optional() @Self() public formControlName: FormControlName ) { super(defaultErrorStateMatcher, parentForm, parentFormGroup, ngControl); if (this.ngControl) { this.ngControl.valueAccessor = this; } } ngAfterContentInit() { if (this.mcValidation.useValidation) { setMosaicValidation(this); } this.keyManager = new FocusKeyManager<McTag>(this.tags) .withVerticalOrientation() .withHorizontalOrientation(this.dir ? this.dir.value : 'ltr'); if (this.dir) { this.dir.change .pipe(takeUntil(this.destroyed)) .subscribe((dir) => this.keyManager.withHorizontalOrientation(dir)); } // Prevents the tag list from capturing focus and redirecting // it back to the first tag when the user tabs out. this.keyManager.tabOut .pipe(takeUntil(this.destroyed)) .subscribe(() => { this._tabIndex = -1; setTimeout(() => { this._tabIndex = this.userTabIndex || 0; this.changeDetectorRef.markForCheck(); }); }); // When the list changes, re-subscribe this.tags.changes .pipe(startWith(null), takeUntil(this.destroyed)) .subscribe(() => { if (this.disabled) { // Since this happens after the content has been // checked, we need to defer it to the next tick. Promise.resolve().then(() => { this.syncTagsDisabledState(); }); } this.resetTags(); // Reset tags selected/deselected status this.initializeSelection(); // Check to see if we need to update our tab index this.updateTabIndex(); // Check to see if we have a destroyed tag and need to refocus this.updateFocusForDestroyedTags(); // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { this.tagChanges.emit(this.tags.toArray()); this.stateChanges.next(); this.propagateTagsChanges(); }); }); } ngOnInit() { this.selectionModel = new SelectionModel<McTag>(this.multiple, undefined, false); this.stateChanges.next(); } ngDoCheck() { if (this.ngControl) { // We need to re-evaluate this on every change detection cycle, because there are some // error triggers that we can't subscribe to (e.g. parent form submissions). This means // that whatever logic is in here has to be super lean or we risk destroying the performance. this.updateErrorState(); } } ngOnDestroy() { this.destroyed.next(); this.destroyed.complete(); this.stateChanges.complete(); this.dropSubscriptions(); } // tslint:disable-next-line:no-empty onTouched = () => {}; // tslint:disable-next-line:no-empty onChange: (value: any) => void = () => {}; /** Associates an HTML input element with this tag list. */ registerInput(inputElement: McTagTextControl): void { this.tagInput = inputElement; // todo need rethink about it if (this.ngControl && inputElement.ngControl?.statusChanges) { inputElement.ngControl.statusChanges .subscribe(() => this.ngControl.control!.setErrors(inputElement.ngControl!.errors)); } } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { if (this.tags) { this.setSelectionByValue(value, false); } } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void): void { this.onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => void): void { this.onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this.stateChanges.next(); } /** * Implemented as part of McFormFieldControl. * @docs-private */ onContainerClick(event: MouseEvent) { if (!this.originatesFromTag(event)) { this.focus(); } } /** * Focuses the first non-disabled tag in this tag list, or the associated input when there * are no eligible tags. */ focus(): void { if (this.disabled) { return; } // TODO: ARIA says this should focus the first `selected` tag if any are selected. // Focus on first element if there's no tagInput inside tag-list if (this.tagInput && this.tagInput.focused) { // do nothing } else if (this.tags.length > 0) { this.keyManager.setFirstItemActive(); this.stateChanges.next(); } else { this.focusInput(); this.stateChanges.next(); } } /** Attempt to focus an input if we have one. */ focusInput() { if (this.tagInput) { this.tagInput.focus(); } } /** * Pass events to the keyboard manager. Available here for tests. */ keydown(event: KeyboardEvent) { const target = event.target as HTMLElement; // If they are on an empty input and hit backspace, focus the last tag // tslint:disable-next-line: deprecation if (event.keyCode === BACKSPACE && this.isInputEmpty(target)) { this.keyManager.setLastItemActive(); event.preventDefault(); } else if (target && target.classList.contains('mc-tag')) { // tslint:disable-next-line: deprecation if (event.keyCode === HOME) { this.keyManager.setFirstItemActive(); event.preventDefault(); // tslint:disable-next-line: deprecation } else if (event.keyCode === END) { this.keyManager.setLastItemActive(); event.preventDefault(); } else { this.keyManager.onKeydown(event); } this.stateChanges.next(); } } setSelectionByValue(value: any, isUserInput: boolean = true) { this.clearSelection(); this.tags.forEach((tag) => tag.deselect()); if (Array.isArray(value)) { value.forEach((currentValue) => this.selectValue(currentValue, isUserInput)); this.sortValues(); } else { const correspondingTag = this.selectValue(value, isUserInput); // Shift focus to the active item. Note that we shouldn't do this in multiple // mode, because we don't know what tag the user interacted with last. if (correspondingTag && isUserInput) { this.keyManager.setActiveItem(correspondingTag); } } } /** When blurred, mark the field as touched when focus moved outside the tag list. */ blur() { if (!this.hasFocusedTag()) { this.keyManager.setActiveItem(-1); } if (!this.disabled) { if (this.tagInput) { // If there's a tag input, we should check whether the focus moved to tag input. // If the focus is not moved to tag input, mark the field as touched. If the focus moved // to tag input, do nothing. // Timeout is needed to wait for the focus() event trigger on tag input. setTimeout(() => { if (!this.focused) { this.markAsTouched(); } }); } else { // If there's no tag input, then mark the field as touched. this.markAsTouched(); } } } /** Mark the field as touched */ markAsTouched() { this.onTouched(); this.changeDetectorRef.markForCheck(); this.stateChanges.next(); } /** * Check the tab index as you should not be allowed to focus an empty list. */ protected updateTabIndex(): void { // If we have 0 tags, we should not allow keyboard focus this._tabIndex = this.userTabIndex || (this.tags.length === 0 ? -1 : 0); } /** * If the amount of tags changed, we need to update the * key manager state and focus the next closest tag. */ protected updateFocusForDestroyedTags() { if (this.lastDestroyedTagIndex != null) { if (this.tags.length) { const newTagIndex = Math.min(this.lastDestroyedTagIndex, this.tags.length - 1); this.keyManager.setActiveItem(newTagIndex); } else { this.focusInput(); } } this.lastDestroyedTagIndex = null; } private _compareWith = (o1: any, o2: any) => o1 === o2; /** * Utility to ensure all indexes are valid. * * @param index The index to be checked. * @returns True if the index is valid for our list of tags. */ private isValidIndex(index: number): boolean { return index >= 0 && index < this.tags.length; } private isInputEmpty(element: HTMLElement): boolean { if (element && element.nodeName.toLowerCase() === 'input') { const input = element as HTMLInputElement; return !input.value; } return false; } /** * Finds and selects the tag based on its value. * @returns Tag that has the corresponding value. */ private selectValue(value: any, isUserInput: boolean = true): McTag | undefined { const correspondingTag = this.tags.find((tag) => { return tag.value != null && this._compareWith(tag.value, value); }); if (correspondingTag) { if (isUserInput) { correspondingTag.selectViaInteraction(); } else { correspondingTag.select(); } this.selectionModel.select(correspondingTag); } return correspondingTag; } private initializeSelection(): void { // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { if (this.ngControl || this._value) { this.setSelectionByValue(this.ngControl ? this.ngControl.value : this._value, false); this.stateChanges.next(); } }); } /** * Deselects every tag in the list. * @param skip Tag that should not be deselected. */ private clearSelection(skip?: McTag): void { this.selectionModel.clear(); this.tags.forEach((tag) => { if (tag !== skip) { tag.deselect(); } }); this.stateChanges.next(); } /** * Sorts the model values, ensuring that they keep the same * order that they have in the panel. */ private sortValues(): void { if (this._multiple) { this.selectionModel.clear(); this.tags.forEach((tag) => { if (tag.selected) { this.selectionModel.select(tag); } }); this.stateChanges.next(); } } /** Emits change event to set the model value. */ // todo need rethink this method and selection logic private propagateChanges(fallbackValue?: any): void { let valueToEmit: any = null; if (Array.isArray(this.selected)) { valueToEmit = this.selected.map((tag) => tag.value); } else { valueToEmit = this.selected ? this.selected.value : fallbackValue; } this._value = valueToEmit; this.change.emit(new McTagListChange(this, valueToEmit)); this.valueChange.emit(valueToEmit); this.onChange(valueToEmit); this.changeDetectorRef.markForCheck(); } private propagateTagsChanges(): void { const valueToEmit: any = this.tags.map((tag) => tag.value); this._value = valueToEmit; this.change.emit(new McTagListChange(this, valueToEmit)); this.valueChange.emit(valueToEmit); this.onChange(valueToEmit); this.changeDetectorRef.markForCheck(); } private resetTags() { this.dropSubscriptions(); this.listenToTagsFocus(); this.listenToTagsSelection(); this.listenToTagsRemoved(); } private dropSubscriptions() { if (this.tagFocusSubscription) { this.tagFocusSubscription.unsubscribe(); this.tagFocusSubscription = null; } if (this.tagBlurSubscription) { this.tagBlurSubscription.unsubscribe(); this.tagBlurSubscription = null; } if (this.tagSelectionSubscription) { this.tagSelectionSubscription.unsubscribe(); this.tagSelectionSubscription = null; } if (this.tagRemoveSubscription) { this.tagRemoveSubscription.unsubscribe(); this.tagRemoveSubscription = null; } } /** Listens to user-generated selection events on each tag. */ private listenToTagsSelection(): void { this.tagSelectionSubscription = this.tagSelectionChanges.subscribe((event) => { if (event.source.selected) { this.selectionModel.select(event.source); } else { this.selectionModel.deselect(event.source); } // For single selection tag list, make sure the deselected value is unselected. if (!this.multiple) { this.tags.forEach((tag) => { if (!this.selectionModel.isSelected(tag) && tag.selected) { tag.deselect(); } }); } if (event.isUserInput) { this.propagateChanges(); } }); } /** Listens to user-generated selection events on each tag. */ private listenToTagsFocus(): void { this.tagFocusSubscription = this.tagFocusChanges .subscribe((event) => { const tagIndex: number = this.tags.toArray().indexOf(event.tag); if (this.isValidIndex(tagIndex)) { this.keyManager.updateActiveItem(tagIndex); } this.stateChanges.next(); }); this.tagBlurSubscription = this.tagBlurChanges .subscribe(() => { this.blur(); this.stateChanges.next(); }); } private listenToTagsRemoved(): void { this.tagRemoveSubscription = this.tagRemoveChanges .subscribe((event) => { const tag = event.tag; const tagIndex = this.tags.toArray().indexOf(event.tag); // In case the tag that will be removed is currently focused, we temporarily store // the index in order to be able to determine an appropriate sibling tag that will // receive focus. if (this.isValidIndex(tagIndex) && tag.hasFocus) { this.lastDestroyedTagIndex = tagIndex; } }); } /** Checks whether an event comes from inside a tag element. */ private originatesFromTag(event: Event): boolean { let currentElement = event.target as HTMLElement | null; while (currentElement && currentElement !== this.elementRef.nativeElement) { if (currentElement.classList.contains('mc-tag')) { return true; } currentElement = currentElement.parentElement; } return false; } /** Checks whether any of the tags is focused. */ private hasFocusedTag() { return this.tags.some((tag) => tag.hasFocus); } /** Syncs the list's disabled state with the individual tags. */ private syncTagsDisabledState() { if (this.tags) { this.tags.forEach((tag) => { tag.disabled = this._disabled; }); } } }
the_stack
import { assert } from "chai"; import * as crypto from "crypto"; import * as fs from "fs-extra"; import nock from "nock"; import * as path from "path"; import { AsyncMutex, BeEvent } from "@itwin/core-bentley"; import { CancelRequest, ProgressInfo } from "@bentley/itwin-client"; import { AzureFileHandler } from "../itwin-client/AzureFileHandler"; const testValidUrl = "https://example.com/"; const testErrorUrl = "http://bad.example.com/"; // NB: This is not automatically mocked - each test should use nock as-needed. const blobSizeInBytes = 1024 * 10; const blockSize = 1024; const enableMd5 = true; const ECONNRESET: any = new Error("socket hang up"); ECONNRESET.code = "ECONNRESET"; const testOutputDir = path.join(__dirname, "output"); const targetFile = path.join(testOutputDir, "downloadedFile"); function createHandler() { return new AzureFileHandler(undefined, undefined, { blockSize, simultaneousDownloads: 1, progressReportAfter: 100, checkMD5AfterDownload: enableMd5 }); } describe("AzureFileHandler", async () => { const createCancellation = (): CancelRequest => ({ cancel: () => false }); const randomBuffer = crypto.randomBytes(blobSizeInBytes); let onDataReceived: () => Promise<void>; let bytesRead = 0; const bytesReadChanged = new BeEvent(); beforeEach(async () => { bytesReadChanged.clear(); bytesRead = 0; fs.emptyDirSync(testOutputDir); nock(testValidUrl).persist().get("/").reply(200, async function (this: nock.ReplyFnContext) { const rangeStr = this.req.getHeader("range") as string; const range = rangeStr.replace("bytes=", "").split("-"); const startOffset = Number(range[0]); const stopOffset = Number(range[1]); const length = stopOffset - startOffset; bytesRead += length; bytesReadChanged.raiseEvent(); const block = new Uint8Array(length + 1); randomBuffer.copy(block, 0, startOffset, stopOffset + 1); return Buffer.from(block); }); const md5 = crypto.createHash("md5").update(randomBuffer).digest("base64"); const header = { "content-length": blobSizeInBytes.toString(), "accept-ranges": "bytes", "content-md5": md5 }; nock(testValidUrl).head("/").reply(200, undefined, header); onDataReceived = async () => { if (bytesRead < blobSizeInBytes) return new Promise((resolve) => bytesReadChanged.addOnce(resolve)); }; }); afterEach(async () => { nock.cleanAll(); }); it("downloads a file", async () => { const handler = new AzureFileHandler(); await handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes); assert(fs.readFileSync(targetFile).compare(randomBuffer) === 0, "Downloaded file contents do not match expected contents."); }); it("supports canceling a file", async () => { const handler = createHandler(); const signal = createCancellation(); const promise = handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes, undefined, signal); await onDataReceived(); assert.isTrue(signal.cancel()); try { await promise; } catch (error: any) { assert.equal(error.name, "User cancelled operation"); assert.equal(error.message, "User cancelled download"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); assert.isFalse(signal.cancel()); // FIXME: This is fixed in nock 13 // await Promise.race([ // new Promise((resolve) => setTimeout(resolve)), // onDataReceived().then(() => assert.fail("Should not read after cancellation!")), // ]); return; } assert.fail("Expected an error to be thrown!"); }); it("supports progress callbacks", async () => { const handler = createHandler(); const progressArgs: ProgressInfo[] = []; const progressCb = (arg: any) => progressArgs.push(arg); const promise = handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes, progressCb); assert.isEmpty(progressArgs); while (progressArgs.length === 0) await onDataReceived(); assert.isAbove(progressArgs.length, 0); assert.isBelow(progressArgs.length, 8); await promise; assert.isAtLeast(progressArgs.length, 2); for (const { loaded, total, percent } of progressArgs) { assert.equal(total, blobSizeInBytes); assert.equal(percent, 100 * loaded / total!); } assert.equal(progressArgs[progressArgs.length - 1].percent, 100); }); it("should stop progress callbacks after cancellation", async () => { const handler = createHandler(); const signal = createCancellation(); const progressArgs: any[] = []; const firstEvent = new AsyncMutex(); const unlock = await firstEvent.lock(); const progressCb = (arg: any) => { progressArgs.push(arg); if (progressArgs.length === 1) { unlock(); } }; const promise = handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes, progressCb, signal); assert.isEmpty(progressArgs); (await firstEvent.lock())(); assert.isAbove(progressArgs.length, 0); assert.isBelow(progressArgs.length, 8); const lastProgressLength = progressArgs.length; assert.isTrue(signal.cancel()); try { await promise; } catch (error: any) { assert.equal(error.name, "User cancelled operation"); assert.equal(error.message, "User cancelled download"); assert.isTrue(progressArgs.length >= lastProgressLength); return; } assert.fail("Expected an error to be thrown!"); }); it("should return false for cancel request after download is complete", async () => { const handler = new AzureFileHandler(); const signal = createCancellation(); await handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes, undefined, signal); assert.isFalse(signal.cancel()); assert(fs.readFileSync(targetFile).compare(randomBuffer) === 0, "Downloaded file contents do not match expected contents."); }); it("should retry on HTTP 503", async () => { nock.cleanAll(); nock(testErrorUrl).get("/").twice().reply(503, "Service Unavailable"); nock(testErrorUrl).head("/").thrice().reply(503, "Service Unavailable"); nock(testErrorUrl).persist().get("/").reply(200, async function (this: nock.ReplyFnContext) { const rangeStr = this.req.getHeader("range") as string; const range = rangeStr.replace("bytes=", "").split("-"); const startOffset = Number(range[0]); const stopOffset = Number(range[1]); const length = stopOffset - startOffset; bytesRead += length; bytesReadChanged.raiseEvent(); const block = new Uint8Array(length + 1); randomBuffer.copy(block, 0, startOffset, stopOffset + 1); return Buffer.from(block); }); const md5 = crypto.createHash("md5").update(randomBuffer).digest("base64"); const header = { "content-length": blobSizeInBytes.toString(), "accept-ranges": "bytes", "content-md5": md5 }; nock(testErrorUrl).head("/").reply(200, undefined, header); const handler = new AzureFileHandler(undefined, undefined, { blockSize }); await handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes); assert.isTrue(nock.isDone()); assert(fs.readFileSync(targetFile).compare(randomBuffer) === 0, "Downloaded file contents do not match expected contents."); }); it("should eventually throw for HTTP 503", async () => { nock(testErrorUrl).persist().get("/").reply(503, "Service Unavailable"); nock(testErrorUrl).persist().head("/").reply(503, "Service Unavailable"); const handler = new AzureFileHandler(); try { await handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes); } catch (error: any) { assert.equal(error.name, "HTTPError"); assert.equal(error.message, "Response code 503 (Service Unavailable)"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); return; } assert.fail("Expected an error to be thrown!"); }); it("should not retry HTTP 403", async () => { nock(testErrorUrl).get("/").twice().reply(403, "Forbidden"); nock(testErrorUrl).head("/").twice().reply(403, "Forbidden"); const handler = new AzureFileHandler(); try { await handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes); } catch (error: any) { assert.equal(error.name, "HTTPError"); assert.equal(error.message, "Response code 403 (Forbidden)"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); assert.isFalse(nock.isDone(), "Should have only requested once!"); return; } assert.fail("Expected an error to be thrown!"); }); it("should retry on ECONNRESET", async () => { nock.cleanAll(); nock(testErrorUrl).get("/").replyWithError(ECONNRESET); nock(testErrorUrl).head("/").replyWithError(ECONNRESET); nock(testErrorUrl).persist().get("/").reply(200, async function (this: nock.ReplyFnContext) { const rangeStr = this.req.getHeader("range") as string; const range = rangeStr.replace("bytes=", "").split("-"); const startOffset = Number(range[0]); const stopOffset = Number(range[1]); const length = stopOffset - startOffset; bytesRead += length; bytesReadChanged.raiseEvent(); const block = new Uint8Array(length + 1); randomBuffer.copy(block, 0, startOffset, stopOffset + 1); return Buffer.from(block); }); const md5 = crypto.createHash("md5").update(randomBuffer).digest("base64"); const header = { "content-length": blobSizeInBytes.toString(), "accept-ranges": "bytes", "content-md5": md5 }; nock(testErrorUrl).head("/").reply(200, undefined, header); const handler = new AzureFileHandler(); await handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes); assert.isTrue(nock.isDone()); assert(fs.readFileSync(targetFile).compare(randomBuffer) === 0, "Downloaded file contents do not match expected contents."); }); it("should eventually throw for ECONNRESET", async () => { nock.cleanAll(); nock(testErrorUrl).persist().head("/").replyWithError(ECONNRESET); const handler = new AzureFileHandler(); const promise = handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes); try { await promise; } catch (error: any) { assert.equal(error.code, "ECONNRESET"); assert.equal(error.message, "socket hang up"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); return; } assert.fail("Expected an error to be thrown!"); }).timeout("30s"); // ###TODO khanaffan This tends to hang on linux. it.skip("should throw when tempfile is deleted", async () => { const handler = new AzureFileHandler(); const promise = handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes); await onDataReceived(); fs.emptyDirSync(testOutputDir); try { await promise; } catch (error: any) { assert.oneOf(error.code, ["EPERM", "ENOENT"]); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); return; } assert.fail("Expected an error to be thrown!"); }); it.skip("should return false for cancel request after disk error", async () => { const handler = new AzureFileHandler(); const signal = createCancellation(); const promise = handler.downloadFile("", testValidUrl, targetFile, blobSizeInBytes, undefined, signal); await onDataReceived(); fs.emptyDirSync(testOutputDir); try { await promise; } catch (error: any) { assert.equal(error.name, "ENOENT"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); assert.isFalse(signal.cancel()); return; } assert.fail("Expected an error to be thrown!"); }); it("should return false for cancel request after network error", async () => { nock(testErrorUrl).persist().head("/").replyWithError(ECONNRESET); const handler = new AzureFileHandler(); const signal = createCancellation(); const promise = handler.downloadFile("", testErrorUrl, targetFile, blobSizeInBytes, undefined, signal); try { await promise; } catch (error: any) { assert.equal(error.code, "ECONNRESET"); assert.equal(error.message, "socket hang up"); assert.isFalse(fs.existsSync(targetFile), "Should not have written anything to disk after failure!"); assert.isFalse(signal.cancel()); return; } assert.fail("Expected an error to be thrown!"); }); });
the_stack
import { ethers } from 'hardhat' import { assert, expect } from 'chai' import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers' import { Contract, ContractFactory } from 'ethers' const encodeTokenInitData = ( name: string, symbol: string, decimals: number | string ) => { return ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes', 'bytes'], [ ethers.utils.defaultAbiCoder.encode(['string'], [name]), ethers.utils.defaultAbiCoder.encode(['string'], [symbol]), ethers.utils.defaultAbiCoder.encode(['uint8'], [decimals]), ] ) } describe('Bridge peripherals layer 2', () => { let accounts: SignerWithAddress[] let TestBridge: ContractFactory let testBridge: Contract let erc20Proxy: string before(async function () { // constructor(uint256 _gasPrice, uint256 _maxGas, address erc777Template, address erc20Template) accounts = await ethers.getSigners() TestBridge = await ethers.getContractFactory('L2ERC20Gateway') const StandardArbERC20 = await ethers.getContractFactory('StandardArbERC20') const standardArbERC20Logic = await StandardArbERC20.deploy() const UpgradeableBeacon = await ethers.getContractFactory( 'UpgradeableBeacon' ) const beacon = await UpgradeableBeacon.deploy(standardArbERC20Logic.address) const BeaconProxyFactory = await ethers.getContractFactory( 'BeaconProxyFactory' ) const beaconProxyFactory = await BeaconProxyFactory.deploy() await beaconProxyFactory.initialize(beacon.address) testBridge = await TestBridge.deploy() await testBridge.initialize( accounts[0].address, accounts[3].address, beaconProxyFactory.address ) }) it('should deploy erc20 tokens correctly', async function () { const l1ERC20 = '0x6100000000000000000000000000000000000001' const sender = '0x6300000000000000000000000000000000000002' const amount = '10' const dest = sender const name = 'ArbToken' const symbol = 'ATKN' const decimals = '18' const deployData = encodeTokenInitData(name, symbol, decimals) // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const preTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.equal(preTokenCode, '0x', 'Something already deployed to address') const data = ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes'], [deployData, '0x'] ) const tx = await testBridge.finalizeInboundTransfer( l1ERC20, sender, dest, amount, data ) const postTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.notEqual( postTokenCode, '0x', 'Token not deployed to correct address' ) const Erc20 = await ethers.getContractFactory('StandardArbERC20') const erc20 = await Erc20.attach(l2ERC20Address) assert.equal(await erc20.name(), name, 'Tokens not named correctly') assert.equal(await erc20.symbol(), symbol, 'Tokens symbol set correctly') assert.equal( (await erc20.decimals()).toString(), decimals, 'Tokens decimals set incorrectly' ) }) it('should mint erc20 tokens correctly', async function () { const l1ERC20 = '0x0000000000000000000000000000000000000001' const sender = '0x0000000000000000000000000000000000000002' const dest = sender const amount = '1' const initializeData = encodeTokenInitData('ArbToken', 'ATKN', '18') // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const preTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.equal(preTokenCode, '0x', 'Something already deployed to address') const data = ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes'], [initializeData, '0x'] ) const tx = await testBridge.finalizeInboundTransfer( l1ERC20, sender, dest, amount, data ) const postTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.notEqual( postTokenCode, '0x', 'Token not deployed to correct address' ) const Erc20 = await ethers.getContractFactory('StandardArbERC20') const erc20 = await Erc20.attach(l2ERC20Address) const balance = await erc20.balanceOf(dest) assert.equal(balance.toString(), amount, 'Tokens not minted correctly') }) it('should revert post mint call correctly in outbound', async function () { const l1ERC20 = '0x0000000000000000000000000000000000000325' const sender = '0x0000000000000000000000000000000000000005' const amount = '1' // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const L2Called = await ethers.getContractFactory('L2Called') const l2Called = await L2Called.deploy() const dest = l2Called.address // 7 is revert() const num = 7 const callHookData = ethers.utils.defaultAbiCoder.encode(['uint256'], [num]) const data = ethers.utils.defaultAbiCoder.encode(['bytes'], [callHookData]) await expect( testBridge['outboundTransfer(address,address,uint256,bytes)']( l1ERC20, dest, amount, data ) ).to.be.revertedWith('EXTRA_DATA_DISABLED') }) it.skip('should reserve gas in post mint call to ensure rest of function can be executed', async function () { // test case skipped since post mint call is disabled const l1ERC20 = '0x0000000000000000000000000000000000001325' const sender = '0x0000000000000000000000000000000000000015' const amount = '1' const initializeData = encodeTokenInitData('ArbToken', 'ATKN', '18') // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const preTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.equal(preTokenCode, '0x', 'Something already deployed to address') const L2Called = await ethers.getContractFactory('L2Called') const l2Called = await L2Called.deploy() const dest = l2Called.address // 9 is assert(false) const num = 9 const callHookData = ethers.utils.defaultAbiCoder.encode(['uint256'], [num]) const data = ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes'], [initializeData, callHookData] ) // we need to hardcode this value as you can only send 63/64 of your remaining // gas into a call a high gas limit makes the test pass artificially const gasLimit = ethers.BigNumber.from(900000) const tx = await testBridge.finalizeInboundTransfer( l1ERC20, sender, dest, amount, data, { gasLimit, } ) const receipt = await tx.wait() const gasUsed = receipt.gasUsed const diff = gasLimit.sub(gasUsed) // expect to save enough gas for subsequent mint, with at most a 10% margin assert( diff.mul(10).lte(gasLimit), 'Did not reserve the correct amount of gas' ) // TransferAndCallTriggered(bool,address,address,uint256,bytes) const eventTopic = '0x11ff8525c5d96036231ee652c108808dee4c40728a6117830a75029298bb7de6' const filteredEvents: Array<any> = receipt.events.filter( (event: any) => event.topics[0] === eventTopic ) assert.equal( filteredEvents.length, 1, 'Token post mint hook should have emitted event' ) const success: boolean = filteredEvents[0].args.success assert.equal(success, false, 'Token post mint hook should have reverted') // dest should hold not hold amount when reverted const Erc20 = await ethers.getContractFactory('aeERC20') const erc20 = await Erc20.attach(l2ERC20Address) assert.equal( (await erc20.balanceOf(dest)).toString(), '0', 'L2Called contract should not be holding coins' ) assert.equal( (await erc20.balanceOf(sender)).toString(), amount, 'Sender should hold coins' ) }) it.skip('should revert post mint call if sent to EOA', async function () { // test case skipped since post mint call is disabled const l1ERC20 = '0x0000000000000000000000000000000000000326' const sender = '0x0000000000000000000000000000000000000005' const amount = '1' const initializeData = encodeTokenInitData('ArbToken', 'ATKN', '18') // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const preTokenCode = await ethers.provider.getCode(l2ERC20Address) assert.equal(preTokenCode, '0x', 'Something already deployed to address') const dest = accounts[1].address const data = ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes'], [initializeData, '0x01'] ) const tx = await testBridge.finalizeInboundTransfer( l1ERC20, sender, dest, amount, data ) const receipt = await tx.wait() // TransferAndCallTriggered(bool,address,address,uint256,bytes) const eventTopic = '0x11ff8525c5d96036231ee652c108808dee4c40728a6117830a75029298bb7de6' const filteredEvents: Array<any> = receipt.events.filter( (event: any) => event.topics[0] === eventTopic ) assert.equal( filteredEvents.length, 1, 'Token post mint hook should have emitted event' ) const success: boolean = filteredEvents[0].args.success assert.equal(success, false, 'Token post mint hook should have reverted') }) it('should burn on withdraw', async function () { const l1ERC20 = '0x0000000000000003000000000000000000000001' const sender = accounts[0].address const dest = sender const amount = '10' const initializeData = encodeTokenInitData('ArbToken', 'ATKN', '18') // connect to account 3 to query as if gateway router const l2ERC20Address = await testBridge .connect(accounts[3]) .calculateL2TokenAddress(l1ERC20) const data = ethers.utils.defaultAbiCoder.encode( ['bytes', 'bytes'], [initializeData, '0x'] ) const tx = await testBridge.finalizeInboundTransfer( l1ERC20, sender, dest, amount, data ) const Erc20 = await ethers.getContractFactory('StandardArbERC20') const erc20 = await Erc20.attach(l2ERC20Address) const balance = await erc20.balanceOf(dest) assert.equal(balance.toString(), amount, 'Tokens not minted correctly') await testBridge.functions[ 'outboundTransfer(address,address,uint256,bytes)' ](l1ERC20, accounts[1].address, balance, '0x') const newBalance = await erc20.balanceOf(dest) assert.equal(newBalance.toString(), '0', 'Tokens not minted correctly') }) it('should map L1 to L2 addresses correctly', async function () { const TestMessenger = await ethers.getContractFactory('AddressMappingTest') const testMessenger = await TestMessenger.deploy() const testCases = [ { input: '0x1111000000000000000000000000000000001110', expectedOutput: '0xffffffffffffffffffffffffffffffffffffffff', }, { input: '0x1111000000000000000000000000081759a885c4', expectedOutput: '0x0000000000000000000000000000081759a874b3', }, ] for (const { input, expectedOutput } of testCases) { const res = await testMessenger.getL1AddressTest(input) expect(res.toLowerCase()).to.equal(expectedOutput.toLowerCase()) } }) })
the_stack
import {Injectable} from '@angular/core'; import {dia} from 'jointjs'; import {Flo} from 'spring-flo'; import {Utils as SharedUtils} from '../shared/support/utils'; import {ApplicationType} from '../../shared/model/app.model'; import {UrlUtilities} from '../../url-utilities.service'; import * as _joint from 'jointjs'; const joint: any = _joint; export const PORT_RADIUS = 7; const HANDLE_SHAPE_SPACING = 10; const BETWEEN_HANDLE_SPACING = 5; // Default icons (unicode chars) for each group member, unless they override const GROUP_ICONS = new Map<string, string>() .set('app', UrlUtilities.calculateAssetUrl() + 'img/app.svg') // U+2338 (Quad equal symbol) .set('source', UrlUtilities.calculateAssetUrl() + 'img/source.svg') // 21D2 .set('processor', UrlUtilities.calculateAssetUrl() + 'img/processor.svg') // 3bb //flux capacitor? 1D21B .set('sink', UrlUtilities.calculateAssetUrl() + 'img/sink.svg') // 21D2 .set('task', UrlUtilities.calculateAssetUrl() + 'img/unknown.svg') // 2609 โš™=2699 gear (rubbish) .set('other', UrlUtilities.calculateAssetUrl() + 'img/tap.svg') // 2982 .set('unresolved', UrlUtilities.calculateAssetUrl() + 'img/unknown.svg'); // 2982 /** * Node Helper for Flo based Stream Definition graph editor. * Static utility method for creating joint model objects. * * @author Alex Boyko */ @Injectable() export class NodeHelper { createNode(metadata: Flo.ElementMetadata): dia.Element { let node: dia.Element = null; switch (metadata.group) { case ApplicationType[ApplicationType.app]: node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eef4ee' }, '.shape': { class: 'shape app-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); break; case ApplicationType[ApplicationType.source]: node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eef4ee' }, '.shape': { class: 'shape source-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); break; case ApplicationType[ApplicationType.processor]: node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eef4ee' }, '.shape': { class: 'shape processor-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) }, '.stream-label': { display: 'none' } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); break; case ApplicationType[ApplicationType.sink]: node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eef4ee' }, '.shape': { class: 'shape sink-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) }, '.stream-label': { display: 'none' } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); break; case ApplicationType[ApplicationType.task]: node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eef4ee' }, '.shape': { class: 'shape task-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) }, '.stream-label': { display: 'none' } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); break; default: if (metadata.name === 'tap') { node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eeeeff', stroke: '#0000ff' }, '.shape': { class: 'shape other-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); } else if (metadata.name === 'destination') { node = new joint.shapes.flo.DataFlowApp( joint.util.deepSupplement( { attrs: { '.box': { fill: '#eeeeff', stroke: '#0000ff' }, '.shape': { class: 'shape other-module' }, // '.type-label': { // text: metadata.group.toUpperCase() // }, '.type-icon': { 'xlink:href': GROUP_ICONS.get(metadata.group) } } }, joint.shapes.flo.DataFlowApp.prototype.defaults ) ); } else { node = new joint.shapes.flo.DataFlowApp(); } } node.attr('.palette-entry-name-label/text', metadata.name); node.attr('.name-label/text', metadata.name); node.attr('.type-label/text', metadata.name.toUpperCase()); this.createHandles(node, metadata); return node; } createHandles(node: dia.Element, metadata: Flo.ElementMetadata): void { if (!metadata || SharedUtils.isUnresolvedMetadata(metadata)) { node.attr('.delete-handle', { text: 'Delete', ref: '.box', refX: '50%', refY: -HANDLE_SHAPE_SPACING, yAlignment: 'bottom', xAlignment: 'middle' }); } else { node.attr('.options-handle', { text: 'Options', ref: '.box', refX: '50%', refX2: -BETWEEN_HANDLE_SPACING, refY: -HANDLE_SHAPE_SPACING, yAlignment: 'bottom', textAnchor: 'end' }); node.attr('.handle-separator', { text: '|', ref: '.box', refX: '50%', refY: -HANDLE_SHAPE_SPACING, yAlignment: 'bottom', xAlignment: 'middle' }); node.attr('.delete-handle', { text: 'Delete', ref: '.box', refX: '50%', refX2: BETWEEN_HANDLE_SPACING, refY: -HANDLE_SHAPE_SPACING, yAlignment: 'bottom' }); } } createPorts(node: dia.Element, metadata: Flo.ElementMetadata): void { switch (metadata.group) { case ApplicationType[ApplicationType.source]: this.createCommonOutputPort(node); break; case ApplicationType[ApplicationType.processor]: this.createCommonOutputPort(node); this.createCommonInputPort(node); break; case ApplicationType[ApplicationType.sink]: this.createCommonInputPort(node); break; case 'other': switch (metadata.name) { case 'tap': this.createCommonOutputPort(node); break; case 'destination': this.createCommonOutputPort(node); this.createCommonInputPort(node); break; } break; } } protected createCommonOutputPort(node: dia.Element): void { node.attr('.output-port', { port: 'output', magnet: true, 'joint-selector': '.output-port' }); node.attr('.port-outer-circle-output', { ref: '.box', refCx: 1, refCy: 0.5, r: PORT_RADIUS, class: 'port-outer-circle-output flo-port' }); node.attr('.port-inner-circle-output', { ref: '.box', refCx: 1, refCy: 0.5, r: PORT_RADIUS - 4, class: 'port-inner-circle-output flo-port-inner-circle' }); } protected createCommonInputPort(node: dia.Element): void { node.attr('.input-port', { port: 'input', magnet: true, 'joint-selector': '.input-port' }); node.attr('.port-outer-circle-input', { ref: '.box', refCx: 0, refCy: 0.5, r: PORT_RADIUS, class: 'port-outer-circle-input flo-port' }); node.attr('.port-inner-circle-input', { ref: '.box', refCx: 0, refCy: 0.5, r: PORT_RADIUS - 4, class: 'port-inner-circle-input flo-port-inner-circle' }); } }
the_stack