text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
export default { // Theme Color reference. // https://code.visualstudio.com/docs/getstarted/theme-color-reference $schema: 'vscode://schemas/color-theme', name: 'Shades of Purple', type: 'dark', colors: { // Activity Bar. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_activity-bar 'activityBar.background': '#28284e', 'activityBar.border': '#292952', 'activityBar.dropBackground': '#222145', // "activityBar.foreground": "#A599E9", 'activityBar.foreground': '#FFFFFF', 'activityBarBadge.background': '#FAD000', 'activityBarBadge.foreground': '#28284e', // Sidebar. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_side-bar 'sideBar.background': '#222244', 'sideBar.border': '#25254b', 'sideBar.foreground': '#A599E9', 'sideBarSectionHeader.background': '#1E1E3F', 'sideBarSectionHeader.foreground': '#A599E9', 'sideBarTitle.foreground': '#A599E9', // Badge. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_badge 'badge.background': '#FAD000', 'badge.foreground': '#222244', // Button. // https: //code.visualstudio.com/docs/getstarted/theme-color-reference#_button-control 'button.background': '#FAD000', 'button.foreground': '#222244', 'button.hoverBackground': '#A599E9', // Contrast. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_contrast-colors contrastActiveBorder: null, contrastBorder: '#ffffff00', // Base Colors. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_base-colors // Foreground color for description text providing additional information, for example for a label. descriptionForeground: '#A599E9', // @TODO aaa 'selection.background': '#b362ff', // Dropdown. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_dropdown-control 'dropdown.background': '#1E1E3F', 'dropdown.border': '#1E1E3F', 'dropdown.foreground': '#FFFFFF', // ——— Editor ——— // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_editor-colors 'editor.background': '#2D2B55', // Editor background color. 'editor.foreground': '#FFFFFF', // Editor default foreground color. 'editorLineNumber.foreground': '#A599E9', // Color of editor line numbers. 'editorCursor.foreground': '#FAD000', // Color of the editor cursor. // The slection color battle starts here. 'editor.selectionBackground': '#b362ff88', // Color of the editor selection. 'editor.inactiveSelectionBackground': '#7580b8c0', // Color of the selection in an inactive editor. The color must not be opaque to not hide underlying decorations. 'editor.selectionHighlightBackground': '#7e46df46', // Color for regions with the same content as the selection. The color must not be opaque to not hide underlying decorations. 'editor.wordHighlightBackground': '#FFFFFF0D', // Same words other places. 'editor.wordHighlightStrongBackground': '#FFFFFF0D', // Cursor inside current vairable. 'editor.findMatchBackground': '#FF7200', // Color of the current search match. 'editor.findMatchHighlightBackground': '#ff730056', // Color of the other search matches.The color must not be opaque to not hide underlying decorations. 'editor.findRangeHighlightBackground': '#ff730056', // No idea. Color the range limiting the search (Enable 'Find in Selection' in the find widget). The color must not be opaque to not hide underlying decorations. 'editor.hoverHighlightBackground': '#ff730056', // Highlight below the word for which a hover is shown. The color must not be opaque to not hide underlying decorations 'editor.lineHighlightBackground': '#1F1F41', // Current line of code. Background color for the highlight of line at the cursor position. 'editor.lineHighlightBorder': '#1F1F41', 'editor.rangeHighlightBackground': '#1F1F41', 'editorLink.activeForeground': '#A599E9', 'editorIndentGuide.background': '#a599e90f', 'editorIndentGuide.activeBackground': '#a599e942', 'editorRuler.foreground': '#a599e91c', // Editor Ruler. 'editorOverviewRuler.border': '#a599e91c', 'editorCodeLens.foreground': '#A599E9', 'editorBracketMatch.background': '#ad70fc46', 'editorBracketMatch.border': '#ad70fc46', // Overview ruler is located beneath the scroll bar on the right edge of the editor and gives an overview of the decorations in the editor. 'editorOverviewRuler.commonContentForeground': '#ffc60055', 'editorOverviewRuler.currentContentForeground': '#ee3a4355', 'editorOverviewRuler.incomingContentForeground': '#3ad90055', // Errors and warnings: // "editorError.border": "#ec3a37f5", 'editorError.foreground': '#ec3a37f5', 'editorWarning.border': '#ffffff00', 'editorWarning.foreground': '#FAD000', // Gutter: The gutter contains the glyph margins and the line numbers: 'editorGutter.background': '#28284e', 'editorGutter.addedBackground': '#35ad68', 'editorGutter.deletedBackground': '#ec3a37f5', 'editorGutter.modifiedBackground': '#ad70fc46', // Diff Editor. // https: //code.visualstudio.com/docs/getstarted/theme-color-reference#_diff-editor-colors 'diffEditor.insertedTextBackground': '#00ff000e', 'diffEditor.insertedTextBorder': '#00ff009a', 'diffEditor.removedTextBackground': '#ff000d1a', 'diffEditor.removedTextBorder': '#ff000d81', // Editor Groups & Tabs. // "editorGroup.background": "#ec3a37f5", // Deprecated in v1.25 'editorGroup.border': '#222244', 'editorGroup.dropBackground': '#222244d0', // The editorGroupHeader. 'editorGroupHeader.noTabsBackground': '#2D2B55', 'editorGroupHeader.tabsBackground': '#2D2B55', 'editorGroupHeader.tabsBorder': '#1F1F41', // The tabs 'tab.activeBackground': '#222244', 'tab.activeForeground': '#FFFFFF', 'tab.border': '#1E1E3F', 'tab.activeBorder': '#FAD000', 'tab.inactiveBackground': '#2D2B55', 'tab.inactiveForeground': '#A599E9', 'tab.unfocusedActiveForeground': '#A599E9', 'tab.unfocusedInactiveForeground': '#A599E9', // The Editor widget is shown in front of the editor content. Examples are the Find/Replace dialog, the suggestion widget, and the editor hover. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_editor-widget-colors 'editorWidget.background': '#222244', 'editorWidget.border': '#1F1F41', 'editorHoverWidget.background': '#1F1F41', 'editorHoverWidget.border': '#1F1F41', 'editorSuggestWidget.background': '#1F1F41', 'editorSuggestWidget.border': '#1F1F41', 'editorSuggestWidget.foreground': '#A599E9', 'editorSuggestWidget.highlightForeground': '#FAD000', 'editorSuggestWidget.selectedBackground': '#2D2B55', // Debug. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_debug 'debugToolBar.background': '#1E1E3F', // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_editor-widget-colors 'debugExceptionWidget.background': '#1E1E3F', 'debugExceptionWidget.border': '#A599E9', // The editor marker view shows when navigating to errors and warnings in the editor (Go to Next Error or Warning command). 'editorMarkerNavigation.background': '#3B536433', 'editorMarkerNavigationError.background': '#ec3a37f5', 'editorMarkerNavigationWarning.background': '#FAD000', // To see the editor white spaces, enable Toggle Render Whitespace. 'editorWhitespace.foreground': '#ffffff1a', errorForeground: '#ec3a37f5', // Extensions. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_extensions 'extensionButton.prominentBackground': '#5D37F0', 'extensionButton.prominentForeground': '#FFFFFF', 'extensionButton.prominentHoverBackground': '#ff9d00', focusBorder: '#1E1E3F', foreground: '#A599E9', // Input Control. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_input-control 'input.background': '#2D2B55', 'input.border': '#1E1E3F', 'input.foreground': '#FAD000', 'input.placeholderForeground': '#A599E9', 'inputOption.activeBorder': '#A599E9', 'inputValidation.errorBackground': '#2D2B55', 'inputValidation.errorBorder': '#FAD000', 'inputValidation.infoBackground': '#2D2B55', 'inputValidation.infoBorder': '#2D2B55', 'inputValidation.warningBackground': '#2D2B55', 'inputValidation.warningBorder': '#FAD000', // Lists and Trees. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_lists-and-trees 'list.activeSelectionBackground': '#1E1E3F', 'list.activeSelectionForeground': '#FFFFFF', 'list.dropBackground': '#1E1E3F', 'list.focusBackground': '#1E1E3F', 'list.focusForeground': '#FFFFFF', 'list.highlightForeground': '#FAD000', 'list.hoverBackground': '#2D2B55', 'list.hoverForeground': '#cec5ff', 'list.inactiveSelectionBackground': '#2D2B55', 'list.inactiveSelectionForeground': '#aaa', // Merge Conflicts. 'merge.border': '#ffffff00', 'merge.commonContentBackground': '#ffffff00', 'merge.commonHeaderBackground': '#ffffff00', 'merge.currentContentBackground': '#ffffff00', 'merge.currentHeaderBackground': '#ffffff00', 'merge.incomingContentBackground': '#ffffff00', 'merge.incomingHeaderBackground': '#ffffff00', // Notification Colors. 'notificationCenter.border': '#1E1E3F', // Notification Center border color. 'notificationCenterHeader.foreground': '#ffffff', // Notification Center header foreground color. 'notificationCenterHeader.background': '#6943ff', // Notification Center header background color. 'notificationToast.border': '#1E1E3F', // Notification toast border color. 'notifications.foreground': '#cec5ff', // Notification foreground color. 'notifications.background': '#1E1E3F', // Notification background color. 'notifications.border': '#2D2B55', // Notification border color separating from other notifications in the Notification Center. 'notificationLink.foreground': '#ffffff', // Notification links foreground color. // Panel. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_panel-colors 'panel.background': '#1E1E3F', 'panel.border': '#FAD000', 'panelTitle.activeBorder': '#FAD000', 'panelTitle.activeForeground': '#FAD000', 'panelTitle.inactiveForeground': '#A599E9', // Peek View Colors. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_peek-view-colors 'peekView.border': '#FAD000', 'peekViewEditor.background': '#1E1E3F', 'peekViewEditor.matchHighlightBackground': '#19354900', 'peekViewEditorGutter.background': '#191935', 'peekViewResult.background': '#1E1E3F', 'peekViewResult.fileForeground': '#aaa', 'peekViewResult.lineForeground': '#FFFFFF', 'peekViewResult.matchHighlightBackground': '#2D2B55', 'peekViewResult.selectionBackground': '#2D2B55', 'peekViewResult.selectionForeground': '#FFFFFF', 'peekViewTitle.background': '#1F1F41', 'peekViewTitleDescription.foreground': '#aaa', 'peekViewTitleLabel.foreground': '#FAD000', // Quick Picker. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_quick-picker 'pickerGroup.border': '#1E1E3F', 'pickerGroup.foreground': '#A599E9', // Progress Bar. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_progress-bar 'progressBar.background': '#FAD000', // Scroll Bar Control. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_scroll-bar-control 'scrollbar.shadow': '#00000000', 'scrollbarSlider.activeBackground': '#1e1e3fda', 'scrollbarSlider.background': '#1e1e3f9d', 'scrollbarSlider.hoverBackground': '#1e1e3fd7', // Status Bar Colors. // The Status Bar is shown in the bottom of the workbench. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_status-bar-colors 'statusBar.background': '#1E1E3F', 'statusBar.border': '#1E1E3F', 'statusBar.debuggingBackground': '#1E1E3F', 'statusBar.debuggingForeground': '#1E1E3F', 'statusBar.foreground': '#A599E9', 'statusBar.noFolderBackground': '#1E1E3F', 'statusBar.noFolderForeground': '#A599E9', 'statusBarItem.activeBackground': '#4d21fc', 'statusBarItem.hoverBackground': '#2D2B55', 'statusBarItem.prominentBackground': '#1E1E3F', 'statusBarItem.prominentHoverBackground': '#2D2B55', // Integrated Terminal Colors. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_integrated-terminal-colors 'terminal.ansiBlack': '#000000', 'terminal.ansiRed': '#ec3a37f5', 'terminal.ansiGreen': '#3ad900', 'terminal.ansiYellow': '#FAD000', 'terminal.ansiBlue': '#6943ff', 'terminal.ansiMagenta': '#ff2c70', 'terminal.ansiCyan': '#80fcff', 'terminal.ansiWhite': '#ffffff', 'terminal.ansiBrightBlack': '#5C5C61', 'terminal.ansiBrightRed': '#ec3a37f5', 'terminal.ansiBrightGreen': '#3ad900', 'terminal.ansiBrightYellow': '#FAD000', 'terminal.ansiBrightBlue': '#6943ff', 'terminal.ansiBrightMagenta': '#fb94ff', 'terminal.ansiBrightCyan': '#80fcff', 'terminal.ansiBrightWhite': '#2D2B55', 'terminal.background': '#1E1E3F', 'terminal.foreground': '#ffffff', 'terminalCursor.background': '#FAD000', 'terminalCursor.foreground': '#FAD000', // Git VS Code theme Colors used for file labels and the SCM viewlet. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_git-colors 'gitDecoration.modifiedResourceForeground': '#FAD000', // Color for modified git resources. 'gitDecoration.deletedResourceForeground': '#ec3a37f5', // Color for deleted git resources. 'gitDecoration.untrackedResourceForeground': '#3ad900', // Color for untracked git resources. 'gitDecoration.ignoredResourceForeground': '#a599e981', // Color for ignored git resources. 'gitDecoration.conflictingResourceForeground': '#FF7200', // Color for conflicting git resources. // Text Colors — Colors inside a text document, such as the welcome page. // https://code.visualstudio.com/docs/getstarted/theme-color-reference#_text-colors 'textBlockQuote.background': '#1E1E3F', 'textBlockQuote.border': '#6943ff', 'textCodeBlock.background': '#1E1E3F', 'textLink.activeForeground': '#b362ff', 'textLink.foreground': '#b362ff', 'textPreformat.foreground': '#FAD000', 'textSeparator.foreground': '#1E1E3F', // Title bar. 'titleBar.activeBackground': '#1E1E3F', 'titleBar.activeForeground': '#FFFFFF', 'titleBar.inactiveBackground': '#1E1E3F', 'titleBar.inactiveForeground': '#A599E9', 'walkThrough.embeddedEditorBackground': '#1E1E3F', 'welcomePage.buttonBackground': '#1E1E3F', 'welcomePage.buttonHoverBackground': '#1E1E3F', 'widget.shadow': '#00000026', }, // Token Colors are heavily inspired by several themes // Including but not limited to Material Palenight, Cobalt // theme's syntax and several custom setup via Dev scope ext. tokenColors: [ { name: '[COMMENTS] — The main comments color', scope: ['comment', 'punctuation.definition.comment'], settings: { fontStyle: 'italic', foreground: '#b362ff', }, }, { name: '[Entity] — The main Entity color', scope: 'entity', settings: { foreground: '#FAD000', }, }, { name: '[Constant] — The main constants color', scope: 'constant', settings: { foreground: '#ff628c', }, }, { name: '[Keyword] — The main color for Keyword', scope: 'keyword, storage.type.class.js', settings: { foreground: '#ff9d00', }, }, { name: '[Meta] — The main color for Meta', scope: 'meta', settings: { foreground: '#9effff', }, }, { name: '[invalid] — The main color for invalid', scope: 'invalid', settings: { foreground: '#ec3a37f5', }, }, { name: '[Meta Brace] — The main color for Meta Brace', scope: 'meta.brace', settings: { foreground: '#e1efff', }, }, { name: '[Punctuation] — The main color for Punctuation', scope: 'punctuation', settings: { foreground: '#e1efff', }, }, { name: '[Punctuation] — Color for Punctuation Parameters', scope: 'punctuation.definition.parameters', settings: { foreground: '#ffee80', }, }, { name: '[Punctuation] — Color for Punctuation Template Expression', scope: 'punctuation.definition.template-expression', settings: { foreground: '#ffee80', }, }, { name: '[Storage] — The main color for Storage', scope: 'storage', settings: { foreground: '#FAD000', }, }, { name: '[Storage] — The color for Storage Type Arrow Function', scope: 'storage.type.function.arrow', settings: { foreground: '#FAD000', }, }, { name: '[String]', scope: ['string', 'punctuation.definition.string'], settings: { foreground: '#a5ff90', }, }, { name: '[String] Template Color', scope: ['string.template', 'punctuation.definition.string.template'], settings: { foreground: '#3ad900', }, }, { name: '[Support]', scope: 'support', settings: { foreground: '#80ffbb', }, }, { name: '[Support] Function Colors', scope: 'support.function', settings: { foreground: '#ff9d00', }, }, { name: '[Support] Variable Property DOM Colors', scope: 'support.variable.property.dom', settings: { foreground: '#e1efff', }, }, { name: '[Variable]', scope: 'variable', settings: { foreground: '#e1efff', }, }, { name: '[INI] - Color for Entity', scope: 'source.ini entity', settings: { foreground: '#e1efff', }, }, { name: '[INI] - Color for Keyword', scope: 'source.ini keyword', settings: { foreground: '#FAD000', }, }, { name: '[INI] - Color for Punctuation Definition', scope: 'source.ini punctuation.definition', settings: { foreground: '#ffee80', }, }, { name: '[INI] - Color for Punctuation Separator', scope: 'source.ini punctuation.separator', settings: { foreground: '#ff9d00', }, }, { name: '[CSS] - Color for Entity', scope: ['source.css entity', 'source.stylus entity'], settings: { foreground: '#3ad900', }, }, { name: '[CSS] - Color for ID Selector', scope: 'entity.other.attribute-name.id.css', settings: { foreground: '#FFB454', }, }, { name: '[CSS] - Color for Element Selector', scope: 'entity.name.tag', settings: { foreground: '#9EFFFF', }, }, { name: '[CSS] - Color for Support', scope: ['source.css support', 'source.stylus support'], settings: { foreground: '#a5ff90', }, }, { name: '[CSS] - Color for Constant', scope: [ 'source.css constant', 'source.css support.constant', 'source.stylus constant', 'source.stylus support.constant', ], settings: { foreground: '#ffee80', }, }, { name: '[CSS] - Color for String', scope: [ 'source.css string', 'source.css punctuation.definition.string', 'source.stylus string', 'source.stylus punctuation.definition.string', ], settings: { foreground: '#ffee80', }, }, { name: '[CSS] - Color for Variable', scope: ['source.css variable', 'source.stylus variable'], settings: { foreground: '#9effff', }, }, { name: '[HTML] - Color for Entity Name', scope: 'text.html.basic entity.name', settings: { foreground: '#9effff', }, }, { name: '[HTML] - Color for ID value', scope: 'meta.toc-list.id.html', settings: { foreground: '#A5FF90', }, }, { name: '[HTML] - Color for Entity Other', scope: 'text.html.basic entity.other', settings: { fontStyle: 'italic', foreground: '#FAD000', }, }, { name: '[HTML] - Color for Script Tag', scope: 'meta.tag.metadata.script.html entity.name.tag.html', settings: { foreground: '#FAD000', }, }, { name: '[HTML] - Quotes. Different color to handle expanded selection', scope: 'punctuation.definition.string.begin, punctuation.definition.string.end', settings: { foreground: '#92fc79', }, }, { name: '[JSON] - Color for Support', scope: 'source.json support', settings: { foreground: '#FAD000', }, }, { name: '[JSON] - Color for String', scope: [ 'source.json string', 'source.json punctuation.definition.string', ], settings: { // "foreground": "#ex1efff" // remove x. foreground: '#92fc79', }, }, { name: '[JAVASCRIPT] - Color for Storage Type Function', scope: 'source.js storage.type.function', settings: { foreground: '#fb94ff', }, }, { name: '[JAVASCRIPT] - Color for Variable Language', scope: 'variable.language, entity.name.type.class.js', settings: { foreground: '#fb94ff', }, }, { name: '[JAVASCRIPT] - Color for Inherited Component', scope: 'entity.other.inherited-class.js', settings: { foreground: '#ccc', }, }, { name: '[JAVASCRIPT] - Color for React Extends keyword', scope: 'storage.type.extends.js', settings: { foreground: '#ff9d00', }, }, { name: '[JAVASCRIPT] — Typescript/React Attributes', scope: [ 'entity.other.attribute-name.tsx', 'entity.other.attribute-name.jsx', ], settings: { fontStyle: 'italic', }, }, { name: 'Typescript React Assignment Operator', scope: [ 'keyword.operator.assignment.tsx', 'keyword.operator.assignment.jsx', ], settings: { foreground: '#9effff', }, }, { name: '[JAVASCRIPT] Typescript/React Children', scope: 'meta.jsx.children.tsx', settings: { foreground: '#ffffff', }, }, { name: 'Typescript/React Classnames and Modules', scope: [ 'entity.name.type.class.tsx', 'entity.name.type.class.jsx', 'entity.name.type.module.tsx', 'entity.name.type.module.jsx', 'entity.other.inherited-class.tsx', 'entity.other.inherited-class.jsx', 'variable.other.readwrite.alias.tsx', 'variable.other.readwrite.alias.jsx', 'variable.other.object.tsx', 'variable.other.object.jsx', 'support.class.component.tsx', 'support.class.component.jsx', 'entity.name.type.tsx', 'entity.name.type.jsx', 'variable.other.readwrite.js', 'variable.other.object.js', 'variable.other.property.js', ], settings: { foreground: '#9effff', }, }, { name: '[JAVASCRIPT] - Color for Text inside JSX', scope: 'JSXNested', settings: { foreground: '#ffffff', }, }, { name: '[PYTHON] - Color for Self Argument', scope: 'variable.parameter.function.language.special.self.python', settings: { foreground: '#fb94ff', }, }, { name: '[TYPESCRIPT] - Color for Entity Name Type', scope: 'source.ts entity.name.type', settings: { foreground: '#80ffbb', }, }, { name: '[TYPESCRIPT] - Color for Keyword', scope: 'source.ts keyword', settings: { foreground: '#FAD000', }, }, { name: '[TYPESCRIPT] - Color for Punctuation Parameters', scope: 'source.ts punctuation.definition.parameters', settings: { foreground: '#e1efff', }, }, { name: '[TYPESCRIPT] - Color for Punctuation Arrow Parameters', scope: 'meta.arrow.ts punctuation.definition.parameters', settings: { foreground: '#ffee80', }, }, { name: '[TYPESCRIPT] - Color for Storage', scope: 'source.ts storage', settings: { foreground: '#9effff', }, }, { name: '[MARKDOWN] - Color for Heading Name Section', scope: [ 'entity.name.section.markdown', 'markup.heading.setext.1.markdown', 'markup.heading.setext.2.markdown', ], settings: { foreground: '#FAD000', fontStyle: 'bold', }, }, { name: '[MARKDOWN] - Color for Paragraph', scope: 'meta.paragraph.markdown', settings: { foreground: '#ffffff', }, }, { name: '[MARKDOWN] - Color for Text inside inline code block `code`', scope: 'markup.inline.raw.string.markdown', settings: { foreground: '#A599E9', }, }, { name: '[MARKDOWN] - Color for Quote Punctuation', scope: 'beginning.punctuation.definition.quote.markdown', settings: { foreground: '#FAD000', }, }, { name: '[MARKDOWN] - Color for Quote Paragraph', scope: 'markup.quote.markdown meta.paragraph.markdown', settings: { fontStyle: 'italic', foreground: '#A599E9', }, }, { name: '[MARKDOWN] - Color for Separator', scope: 'meta.separator.markdown', settings: { foreground: '#FAD000', }, }, { name: '[MARKDOWN] - Color for Emphasis Bold', scope: 'markup.bold.markdown', settings: { fontStyle: 'bold', foreground: '#A599E9', }, }, { name: '[MARKDOWN] - Color for Emphasis Italic', scope: 'markup.italic.markdown', settings: { fontStyle: 'italic', foreground: '#A599E9', }, }, { name: '[MARKDOWN] - Color for Lists', scope: 'beginning.punctuation.definition.list.markdown', settings: { foreground: '#FAD000', }, }, { name: '[MARKDOWN] - Color for Link Title', scope: 'string.other.link.title.markdown', settings: { foreground: '#a5ff90', }, }, { name: '[MARKDOWN] - Color for Link/Image Title', scope: [ 'string.other.link.title.markdown', 'string.other.link.description.markdown', 'string.other.link.description.title.markdown', ], settings: { foreground: '#a5ff90', }, }, { name: '[MARKDOWN] - Color for Link Address', scope: [ 'markup.underline.link.markdown', 'markup.underline.link.image.markdown', ], settings: { foreground: '#9effff', }, }, { name: '[MARKDOWN] - Color for Inline Code', scope: ['fenced_code.block.language', 'markup.inline.raw.markdown'], settings: { foreground: '#9effff', }, }, { name: '[MARKDOWN] - Color for Punctuation — Heading, `Code` and fenced ```code blocks```, **Bold**', scope: [ // "markup.fenced_code.block.markdown", // FIXME: Issue with fenced code and CSS. 'punctuation.definition.markdown', 'punctuation.definition.raw.markdown', 'punctuation.definition.heading.markdown', 'punctuation.definition.bold.markdown', ], settings: { foreground: '#494685', }, }, { name: '[MARKDOWN] - Color for Code Block', scope: ['fenced_code.block.language', 'markup.inline.raw.markdown'], settings: { foreground: '#9effff', }, }, { name: '[PUG] - Color for Entity Name', scope: 'text.jade entity.name', settings: { foreground: '#9effff', }, }, { name: '[PUG] - Color for Entity Attribute Name', scope: 'text.jade entity.other.attribute-name.tag', settings: { fontStyle: 'italic', }, }, { name: '[PUG] - Color for String Interpolated', scope: 'text.jade string.interpolated', settings: { foreground: '#ffee80', }, }, { name: '[C#] - Color for Annotations', scope: 'storage.type.cs', settings: { foreground: '#9effff', }, }, { name: '[C#] - Color for Properties', scope: 'entity.name.variable.property.cs', settings: { foreground: '#9effff', }, }, { name: '[C#] - Color for Storage modifiers', scope: 'storage.modifier.cs', settings: { foreground: '#80ffbb', }, }, { name: '[PHP] - Color for Entity', scope: 'source.php entity', settings: { foreground: '#9effff', }, }, { name: '[PHP] - Color for Variables', scope: 'variable.other.php', settings: { foreground: '#FAD000', }, }, { name: '[PHP] - Color for Storage Modifiers', scope: 'storage.modifier.php', settings: { foreground: '#ff9d00', }, }, { name: 'Operator Mono font has awesome itallics', scope: [ 'modifier', 'this', 'comment', 'storage.modifier.js', 'entity.other.attribute-name.js', 'entity.other.attribute-name.html', ], settings: { fontStyle: 'italic', }, }, ], };
the_stack
import {Mutable, Class, Equals, Values, Domain, Range, AnyTiming, LinearRange, ContinuousScale} from "@swim/util"; import {Affinity, MemberFastenerClass, Property, Animator} from "@swim/component"; import type {R2Box} from "@swim/math"; import {AnyFont, Font, AnyColor, Color} from "@swim/style"; import {ThemeAnimator} from "@swim/theme"; import {ViewContextType, ViewFlags, View, ViewSet} from "@swim/view"; import {GraphicsView, CanvasContext, CanvasRenderer} from "@swim/graphics"; import {AnyDataPointView, DataPointView} from "../data/DataPointView"; import {ContinuousScaleAnimator} from "../scaled/ContinuousScaleAnimator"; import type {PlotViewInit, PlotViewDataPointExt, PlotView} from "./PlotView"; import type {ScatterPlotViewObserver} from "./ScatterPlotViewObserver"; /** @public */ export type AnyScatterPlotView<X = unknown, Y = unknown> = ScatterPlotView<X, Y> | ScatterPlotViewInit<X, Y>; /** @public */ export interface ScatterPlotViewInit<X = unknown, Y = unknown> extends PlotViewInit<X, Y> { } /** @public */ export abstract class ScatterPlotView<X = unknown, Y = unknown> extends GraphicsView implements PlotView<X, Y> { constructor() { super(); this.xDataDomain = null; this.yDataDomain = null; this.xDataRange = null; this.yDataRange = null; } override readonly observerType?: Class<ScatterPlotViewObserver<X, Y>>; @ThemeAnimator({type: Font, value: null, inherits: true}) readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>; @ThemeAnimator({type: Color, value: null, inherits: true}) readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @Animator<ScatterPlotView<X, Y>, ContinuousScale<X, number> | null>({ extends: ContinuousScaleAnimator, type: ContinuousScale, inherits: true, value: null, updateFlags: View.NeedsLayout, willSetValue(newXScale: ContinuousScale<X, number> | null, oldXScale: ContinuousScale<X, number> | null): void { this.owner.callObservers("viewWillSetXScale", newXScale, oldXScale, this.owner); }, didSetValue(newXScale: ContinuousScale<X, number> | null, oldXScale: ContinuousScale<X, number> | null): void { this.owner.updateXDataRange(); this.owner.callObservers("viewDidSetXScale", newXScale, oldXScale, this.owner); }, }) readonly xScale!: ContinuousScaleAnimator<this, X, number>; @Animator<ScatterPlotView<X, Y>, ContinuousScale<Y, number> | null>({ extends: ContinuousScaleAnimator, type: ContinuousScale, inherits: true, value: null, updateFlags: View.NeedsLayout, willSetValue(newYScale: ContinuousScale<Y, number> | null, oldYScale: ContinuousScale<Y, number> | null): void { this.owner.callObservers("viewWillSetYScale", newYScale, oldYScale, this.owner); }, didSetValue(newYScale: ContinuousScale<Y, number> | null, oldYScale: ContinuousScale<Y, number> | null): void { this.owner.updateYDataRange(); this.owner.callObservers("viewDidSetYScale", newYScale, oldYScale, this.owner); }, }) readonly yScale!: ContinuousScaleAnimator<this, Y, number>; xDomain(): Domain<X> | null; xDomain(xDomain: Domain<X> | string | null, timing?: AnyTiming | boolean): this; xDomain(xMin: X, xMax: X, timing?: AnyTiming | boolean): this; xDomain(xMin?: Domain<X> | X | string | null, xMax?: X | AnyTiming | boolean, timing?: AnyTiming | boolean): Domain<X> | null | this { if (arguments.length === 0) { const xScale = this.xScale.value; return xScale !== null ? xScale.domain : null; } else { this.xScale.setDomain(xMin as any, xMax as any, timing); return this; } } yDomain(): Domain<Y> | null; yDomain(yDomain: Domain<Y> | string | null, timing?: AnyTiming | boolean): this; yDomain(yMin: Y, yMax: Y, timing: AnyTiming | boolean): this; yDomain(yMin?: Domain<Y> | Y | string | null, yMax?: Y | AnyTiming | boolean, timing?: AnyTiming | boolean): Domain<Y> | null | this { if (arguments.length === 0) { const yScale = this.yScale.value; return yScale !== null ? yScale.domain : null; } else { this.yScale.setDomain(yMin as any, yMax as any, timing); return this; } } xRange(): Range<number> | null { const xScale = this.xScale.value; return xScale !== null ? xScale.range : null; } yRange(): Range<number> | null { const yScale = this.yScale.value; return yScale !== null ? yScale.range : null; } @Property<ScatterPlotView<X, Y>, readonly [number, number]>({ initValue(): readonly [number, number] { return [0, 0]; }, willSetValue(newXRangePadding: readonly [number, number], oldXRangePadding: readonly [number, number]): void { this.owner.callObservers("viewWillSetXRangePadding", newXRangePadding, oldXRangePadding, this.owner); }, didSetValue(newXRangePadding: readonly [number, number], oldXRangePadding: readonly [number, number]): void { this.owner.callObservers("viewDidSetXRangePadding", newXRangePadding, oldXRangePadding, this.owner); }, }) readonly xRangePadding!: Property<this, readonly [number, number]> @Property<ScatterPlotView<X, Y>, readonly [number, number]>({ initValue(): readonly [number, number] { return [0, 0]; }, willSetValue(newYRangePadding: readonly [number, number], oldYRangePadding: readonly [number, number]): void { this.owner.callObservers("viewWillSetYRangePadding", newYRangePadding, oldYRangePadding, this.owner); }, didSetValue(newYRangePadding: readonly [number, number], oldYRangePadding: readonly [number, number]): void { this.owner.callObservers("viewDidSetYRangePadding", newYRangePadding, oldYRangePadding, this.owner); }, }) readonly yRangePadding!: Property<this, readonly [number, number]> readonly xDataDomain: Domain<X> | null; protected setXDataDomain(newXDataDomain: Domain<X> | null): void { const oldXDataDomain = this.xDataDomain; if (!Equals(newXDataDomain, oldXDataDomain)) { this.willSetXDataDomain(newXDataDomain, oldXDataDomain); (this as Mutable<this>).xDataDomain = newXDataDomain; this.onSetXDataDomain(newXDataDomain, oldXDataDomain); this.didSetXDataDomain(newXDataDomain, oldXDataDomain); } } protected willSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void { this.callObservers("viewWillSetXDataDomain", newXDataDomain, oldXDataDomain, this); } protected onSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void { this.updateXDataRange(); this.requireUpdate(View.NeedsLayout); } protected didSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void { this.callObservers("viewDidSetXDataDomain", newXDataDomain, oldXDataDomain, this); } protected updateXDataDomain(dataPointView: DataPointView<X, Y>): void { const x: X = dataPointView.x.getValue(); let xDataDomain = this.xDataDomain; if (xDataDomain === null) { xDataDomain = Domain(x, x); } else { if (Values.compare(x, xDataDomain[0]) < 0) { xDataDomain = Domain(x, xDataDomain[1]); } else if (Values.compare(xDataDomain[1], x) < 0) { xDataDomain = Domain(xDataDomain[0], x); } } this.setXDataDomain(xDataDomain); } readonly yDataDomain: Domain<Y> | null; protected setYDataDomain(newYDataDomain: Domain<Y> | null): void { const oldYDataDomain = this.yDataDomain; if (!Equals(newYDataDomain, oldYDataDomain)) { this.willSetYDataDomain(newYDataDomain, oldYDataDomain); (this as Mutable<this>).yDataDomain = newYDataDomain; this.onSetYDataDomain(newYDataDomain, oldYDataDomain); this.didSetYDataDomain(newYDataDomain, oldYDataDomain); } } protected willSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void { this.callObservers("viewWillSetYDataDomain", newYDataDomain, oldYDataDomain, this); } protected onSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void { this.updateYDataRange(); this.requireUpdate(View.NeedsLayout); } protected didSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void { this.callObservers("viewDidSetYDataDomain", newYDataDomain, oldYDataDomain, this); } protected updateYDataDomain(dataPointView: DataPointView<X, Y>): void { const y = dataPointView.y.value; const y2 = dataPointView.y2.value; let yDataDomain = this.yDataDomain; if (yDataDomain === null) { yDataDomain = Domain(y, y); } else { if (Values.compare(y, yDataDomain[0]) < 0) { yDataDomain = Domain(y, yDataDomain[1]); } else if (Values.compare(yDataDomain[1], y) < 0) { yDataDomain = Domain(yDataDomain[0], y); } if (y2 !== void 0) { if (Values.compare(y2, yDataDomain[0]) < 0) { yDataDomain = Domain(y2, yDataDomain[1]); } else if (Values.compare(yDataDomain[1], y2) < 0) { yDataDomain = Domain(yDataDomain[0], y2); } } } this.setYDataDomain(yDataDomain); } readonly xDataRange: Range<number> | null; protected setXDataRange(xDataRange: Range<number> | null): void { (this as Mutable<this>).xDataRange = xDataRange; } protected updateXDataRange(): void { const xDataDomain = this.xDataDomain; if (xDataDomain !== null) { const xScale = this.xScale.value; if (xScale !== null) { this.setXDataRange(LinearRange(xScale(xDataDomain[0]), xScale(xDataDomain[1]))); } else { this.setXDataRange(null); } } } readonly yDataRange: Range<number> | null; protected setYDataRange(yDataRange: Range<number> | null): void { (this as Mutable<this>).yDataRange = yDataRange; } protected updateYDataRange(): void { const yDataDomain = this.yDataDomain; if (yDataDomain !== null) { const yScale = this.yScale.value; if (yScale !== null) { this.setYDataRange(LinearRange(yScale(yDataDomain[0]), yScale(yDataDomain[1]))); } else { this.setYDataRange(null); } } } @ViewSet<ScatterPlotView, DataPointView, PlotViewDataPointExt>({ implements: true, type: DataPointView, binds: true, observes: true, willAttachView(newDataPointView: DataPointView, targetView: View | null): void { this.owner.callObservers("viewWillAttachDataPoint", newDataPointView, targetView, this.owner); }, didAttachView(dataPointView: DataPointView): void { this.owner.updateXDataDomain(dataPointView); this.owner.updateYDataDomain(dataPointView); const labelView = dataPointView.label.view; if (labelView !== null) { this.attachDataPointLabelView(labelView); } }, willDetachView(dataPointView: DataPointView): void { const labelView = dataPointView.label.view; if (labelView !== null) { this.detachDataPointLabelView(labelView); } // xDataDomain and yDataDomain will be recomputed next layout pass }, didDetachView(newDataPointView: DataPointView): void { this.owner.callObservers("viewDidDetachDataPoint", newDataPointView, this.owner); }, viewDidSetDataPointX(newX: unknown | undefined, oldX: unknown | undefined, dataPointView: DataPointView): void { this.owner.updateXDataDomain(dataPointView); this.owner.requireUpdate(View.NeedsLayout); }, viewDidSetDataPointY(newY: unknown | undefined, oldY: unknown | undefined, dataPointView: DataPointView): void { this.owner.updateYDataDomain(dataPointView); this.owner.requireUpdate(View.NeedsLayout); }, viewDidSetDataPointY2(newY2: unknown | undefined, oldY2: unknown | undefined, dataPointView: DataPointView): void { this.owner.updateYDataDomain(dataPointView); this.owner.requireUpdate(View.NeedsLayout); }, viewWillAttachDataPointLabel(labelView: GraphicsView): void { this.attachDataPointLabelView(labelView); }, viewDidDetachDataPointLabel(labelView: GraphicsView): void { this.detachDataPointLabelView(labelView); }, attachDataPointLabelView(labelView: GraphicsView): void { this.owner.requireUpdate(View.NeedsLayout); }, detachDataPointLabelView(labelView: GraphicsView): void { // hook }, }) readonly dataPoints!: ViewSet<this, DataPointView<X, Y>>; static readonly dataPoints: MemberFastenerClass<ScatterPlotView, "dataPoints">; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.xScale.recohere(viewContext.updateTime); this.yScale.recohere(viewContext.updateTime); this.resizeScales(this.viewFrame); } /** * Updates own scale ranges to project onto view frame. */ protected resizeScales(frame: R2Box): void { const xScale = !this.xScale.inherited ? this.xScale.value : null; if (xScale !== null && xScale.range[1] !== frame.width) { this.xScale.setRange(0, frame.width); } const yScale = !this.yScale.inherited ? this.yScale.value : null; if (yScale !== null && yScale.range[1] !== frame.height) { this.yScale.setRange(0, frame.height); } } protected override displayChildren(displayFlags: ViewFlags, viewContext: ViewContextType<this>, displayChild: (this: this, childView: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { let xScale: ContinuousScale<X, number> | null; let yScale: ContinuousScale<Y, number> | null; if ((displayFlags & View.NeedsLayout) !== 0 && (xScale = this.xScale.value, xScale !== null) && (yScale = this.yScale.value, yScale !== null)) { this.layoutChildViews(xScale, yScale, displayFlags, viewContext, displayChild); } else { super.displayChildren(displayFlags, viewContext, displayChild); } } protected layoutChildViews(xScale: ContinuousScale<X, number>, yScale: ContinuousScale<Y, number>, displayFlags: ViewFlags, viewContext: ViewContextType<this>, displayChild: (this: this, childView: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { // Recompute extrema when laying out child views. const frame = this.viewFrame; const size = Math.min(frame.width, frame.height); let xDataDomainMin: X | undefined; let xDataDomainMax: X | undefined; let yDataDomainMin: Y | undefined; let yDataDomainMax: Y | undefined; let xRangePaddingMin = 0; let xRangePaddingMax = 0; let yRangePaddingMin = 0; let yRangePaddingMax = 0; let point0 = null as DataPointView<X, Y> | null; type self = this; function layoutChildView(this: self, point1: View, displayFlags: ViewFlags, viewContext: ViewContextType<self>): void { if (point1 instanceof DataPointView) { const x1 = point1.x.getValue(); const y1 = point1.y.getValue(); const dy1 = point1.y2.value; const r1 = point1.radius.value; const sx1 = xScale(x1); const sy1 = yScale(y1); point1.setXCoord(frame.xMin + sx1); point1.setYCoord(frame.yMin + sy1); if (point0 !== null) { // update extrema if (Values.compare(x1, xDataDomainMin) < 0) { xDataDomainMin = x1; } else if (Values.compare(xDataDomainMax, x1) < 0) { xDataDomainMax = x1; } if (Values.compare(y1, yDataDomainMin) < 0) { yDataDomainMin = y1; } else if (Values.compare(yDataDomainMax, y1) < 0) { yDataDomainMax = y1; } if (dy1 !== void 0) { if (Values.compare(dy1, yDataDomainMin) < 0) { yDataDomainMin = dy1; } else if (Values.compare(yDataDomainMax, dy1) < 0) { yDataDomainMax = dy1; } } } else { xDataDomainMin = x1; xDataDomainMax = x1; yDataDomainMin = y1; yDataDomainMax = y1; } if (r1 !== null) { const radius = r1.pxValue(size); xRangePaddingMin = Math.max(radius, xRangePaddingMin); xRangePaddingMax = Math.max(radius, xRangePaddingMax); yRangePaddingMin = Math.max(radius, yRangePaddingMin); yRangePaddingMax = Math.max(radius, yRangePaddingMax); } point0 = point1; } displayChild.call(this, point1, displayFlags, viewContext); } super.displayChildren(displayFlags, viewContext, layoutChildView); this.setXDataDomain(point0 !== null ? Domain<X>(xDataDomainMin!, xDataDomainMax!) : null); this.setYDataDomain(point0 !== null ? Domain<Y>(yDataDomainMin!, yDataDomainMax!) : null); this.xRangePadding.setValue([xRangePaddingMin, xRangePaddingMax], Affinity.Intrinsic); this.yRangePadding.setValue([yRangePaddingMin, yRangePaddingMax], Affinity.Intrinsic); } protected override didRender(viewContext: ViewContextType<this>): void { const renderer = viewContext.renderer; if (renderer instanceof CanvasRenderer && !this.hidden && !this.culled) { this.renderPlot(renderer.context, this.viewFrame); } super.didRender(viewContext); } protected abstract renderPlot(context: CanvasContext, frame: R2Box): void; override init(init: ScatterPlotViewInit<X, Y>): void { super.init(init); if (init.xScale !== void 0) { this.xScale(init.xScale); } if (init.yScale !== void 0) { this.yScale(init.yScale); } const data = init.data; if (data !== void 0) { for (let i = 0, n = data.length; i < n; i += 1) { this.appendChild(DataPointView.fromAny(data[i]! as AnyDataPointView)); } } if (init.font !== void 0) { this.font(init.font); } if (init.textColor !== void 0) { this.textColor(init.textColor); } } }
the_stack
import { using } from 'using-statement'; import { createDocumentForEntity } from '../../../Cdm/CdmCollection/CdmCollectionHelperFunctions'; import { CdmCorpusDefinition, CdmDataPartitionPatternDefinition, CdmEntityDefinition, cdmIncrementalPartitionType, CdmLocalEntityDeclarationDefinition, CdmManifestDefinition, cdmObjectType, cdmStatusLevel, constants, copyOptions, enterScope, resolveContext, resolveOptions } from '../../../../internal'; import { CdmFolder } from '../../../../Persistence'; import { DataPartitionPattern, EntityDeclarationDefinition, ManifestContent, TraitReference } from '../../../../Persistence/CdmFolder/types'; import { testHelper } from '../../../testHelper'; describe('Persistence.CdmFolder.DataPartitionPattern', () => { /// <summary> /// The path between TestDataPath and TestName. /// </summary> const testsSubpath: string = 'Persistence/CdmFolder/DataPartitionPattern'; /** * Testing for folder with local entity declaration with data partition patterns. */ it('TestLoadLocalEntityWithDataPartitionPattern', () => { const readFile: string = testHelper.getInputFileContent( testsSubpath, 'TestLoadLocalEntityWithDataPartitionPattern', 'entities.manifest.cdm.json'); const cdmManifest: CdmManifestDefinition = CdmFolder.ManifestPersistence.fromObject( new resolveContext(new CdmCorpusDefinition(), undefined), '', '', '', JSON.parse(readFile)); expect(cdmManifest.entities.length) .toBe(2); const entity1: CdmLocalEntityDeclarationDefinition = cdmManifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity1.getObjectType()) .toBe(cdmObjectType.localEntityDeclarationDef); expect(entity1.dataPartitionPatterns.length) .toBe(1); const pattern1: CdmDataPartitionPatternDefinition = entity1.dataPartitionPatterns.allItems[0]; expect(pattern1.name) .toBe('testPattern'); expect(pattern1.explanation) .toBe('test explanation'); expect(pattern1.rootLocation) .toBe('test location'); expect(pattern1.regularExpression) .toBe('\\s*'); expect(pattern1.parameters.length) .toBe(2); expect(pattern1.parameters[0]) .toBe('testParam1'); expect(pattern1.parameters[1]) .toBe('testParam2'); expect(pattern1.specializedSchema) .toBe('test special schema'); expect(pattern1.exhibitsTraits.length) .toBe(1); const entity2: CdmLocalEntityDeclarationDefinition = cdmManifest.entities.allItems[1] as CdmLocalEntityDeclarationDefinition; expect(entity2.getObjectType()) .toBe(cdmObjectType.localEntityDeclarationDef); expect(entity2.dataPartitionPatterns.length) .toBe(1); const pattern2: CdmDataPartitionPatternDefinition = entity2.dataPartitionPatterns.allItems[0]; expect(pattern2.name) .toBe('testPattern2'); expect(pattern2.rootLocation) .toBe('test location2'); expect(pattern2.globPattern) .toBe('/*.csv'); const manifestData: ManifestContent = CdmFolder.ManifestPersistence.toData(cdmManifest, new resolveOptions(), new copyOptions()); expect(manifestData.entities.length) .toBe(2); const entityData1: EntityDeclarationDefinition = manifestData.entities[0]; expect(entityData1.dataPartitionPatterns.length) .toBe(1); const patternData1: DataPartitionPattern = entityData1.dataPartitionPatterns[0]; expect(patternData1.name) .toBe('testPattern'); expect(patternData1.explanation) .toBe('test explanation'); expect(patternData1.rootLocation) .toBe('test location'); expect(patternData1.regularExpression) .toBe('\\s*'); expect(patternData1.parameters.length) .toBe(2); expect(patternData1.parameters[0]) .toBe('testParam1'); expect(patternData1.parameters[1]) .toBe('testParam2'); expect(patternData1.specializedSchema) .toBe('test special schema'); expect(patternData1.exhibitsTraits.length) .toBe(1); const entityData2: EntityDeclarationDefinition = manifestData.entities[1]; expect(entityData2.dataPartitionPatterns.length) .toBe(1); const patternData2: DataPartitionPattern = entityData2.dataPartitionPatterns[0]; expect(patternData2.name) .toBe('testPattern2'); expect(patternData2.rootLocation) .toBe('test location2'); expect(patternData2.globPattern) .toBe('/*.csv'); }); /** * Testing loading manifest with local entity declaration having an incremental partition pattern without incremental trait. */ it('TestFromIncrementalPartitionPatternWithoutTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestFromIncrementalPartitionPatternWithoutTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'DeletePattern\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitionPatterns\'. | fromData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('local:/entities.manifest.cdm.json'); expect(manifest.entities.length) .toBe(1); expect(manifest.entities.allItems[0].objectType) .toBe(cdmObjectType.localEntityDeclarationDef); const entity: CdmLocalEntityDeclarationDefinition = manifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity.incrementalPartitionPatterns.length) .toBe(1); const incrementalPartitionPattern = entity.incrementalPartitionPatterns.allItems[0] expect(incrementalPartitionPattern.name) .toBe('UpsertPattern'); expect(incrementalPartitionPattern.exhibitsTraits.length) .toBe(1); expect(incrementalPartitionPattern.exhibitsTraits.allItems[0].fetchObjectDefinitionName()) .toBe(constants.INCREMENTAL_TRAIT_NAME); expect(errorMessageVerified) .toBeTruthy(); done(); }); /** * Testing loading manifest with local entity declaration having a data partition pattern with incremental trait. */ it('TestFromDataPartitionPatternWithIncrementalTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestFromDataPartitionPatternWithIncrementalTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'UpsertPattern\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitionPatterns\'. | fromData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('local:/entities.manifest.cdm.json'); expect(manifest.entities.length) .toBe(1); expect(manifest.entities.allItems[0].objectType) .toBe(cdmObjectType.localEntityDeclarationDef); const entity: CdmLocalEntityDeclarationDefinition = manifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity.dataPartitionPatterns.length) .toBe(1); expect(entity.dataPartitionPatterns.allItems[0].name) .toBe('TestingPattern'); expect(errorMessageVerified) .toBeTruthy(); done(); }); /* * Testing saving manifest with local entity declaration having an incremental partition pattern without incremental trait. */ it('TestToIncrementalPartitionPatternWithoutTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestToIncrementalPartitionPatternWithoutTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'DeletePartitionPattern\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitionPatterns\'. | toData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = new CdmManifestDefinition(corpus.ctx, 'manifest'); corpus.storage.fetchRootFolder('local').documents.push(manifest); const entity: CdmEntityDefinition = new CdmEntityDefinition(corpus.ctx, 'entityName', undefined); createDocumentForEntity(corpus, entity); const localizedEntityDeclaration = manifest.entities.push(entity); const upsertIncrementalPartitionPattern = corpus.MakeObject<CdmDataPartitionPatternDefinition>(cdmObjectType.dataPartitionPatternDef, 'UpsertPattern', false); upsertIncrementalPartitionPattern.rootLocation = '/IncrementalData'; upsertIncrementalPartitionPattern.specializedSchema = 'csv'; upsertIncrementalPartitionPattern.regularExpression = '/(.*)/(.*)/(.*)/Upserts/upsert(\\d+)\\.csv$'; upsertIncrementalPartitionPattern.parameters = ['year', 'month', 'day', 'upsertPartitionNumber' ]; upsertIncrementalPartitionPattern.exhibitsTraits.push(constants.INCREMENTAL_TRAIT_NAME, [['type', cdmIncrementalPartitionType[cdmIncrementalPartitionType.Upsert]]]); const deletePartitionPattern = corpus.MakeObject<CdmDataPartitionPatternDefinition>(cdmObjectType.dataPartitionPatternDef, 'DeletePartitionPattern', false); deletePartitionPattern.rootLocation = '/IncrementalData'; deletePartitionPattern.specializedSchema = 'csv'; deletePartitionPattern.regularExpression = '/(.*)/(.*)/(.*)/Delete/delete(\\d+)\\.csv$'; deletePartitionPattern.parameters = ['year', 'month', 'day', 'detelePartitionNumber' ]; localizedEntityDeclaration.incrementalPartitionPatterns.push(upsertIncrementalPartitionPattern); localizedEntityDeclaration.incrementalPartitionPatterns.push(deletePartitionPattern); using(enterScope('DataPartitionPatternTest', corpus.ctx, 'TestToIncrementalPartitionPatternWithoutTrait'), _ => { const manifestData = CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined); expect(manifestData.entities.length) .toBe(1); const entityData: EntityDeclarationDefinition = manifestData.entities[0]; expect(entityData.incrementalPartitionPatterns.length) .toBe(1); const patternData: DataPartitionPattern = entityData.incrementalPartitionPatterns[0]; expect(patternData.name) .toBe('UpsertPattern'); expect(patternData.exhibitsTraits.length) .toBe(1); expect((patternData.exhibitsTraits[0] as TraitReference).traitReference) .toBe(constants.INCREMENTAL_TRAIT_NAME); }); expect(errorMessageVerified) .toBeTruthy(); done(); }); /* * Testing saving manifest with local entity declaration having a data partition pattern with incremental trait. */ it('TestToDataPartitionPatternWithIncrementalTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestToDataPartitionPatternWithIncrementalTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'UpsertPartitionPattern\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitionPatterns\'. | toData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = new CdmManifestDefinition(corpus.ctx, 'manifest'); corpus.storage.fetchRootFolder('local').documents.push(manifest); const entity: CdmEntityDefinition = new CdmEntityDefinition(corpus.ctx, 'entityName', undefined); createDocumentForEntity(corpus, entity); const localizedEntityDeclaration = manifest.entities.push(entity); const upsertIncrementalPartitionPattern = corpus.MakeObject<CdmDataPartitionPatternDefinition>(cdmObjectType.dataPartitionPatternDef, 'UpsertPartitionPattern', false); upsertIncrementalPartitionPattern.rootLocation = '/IncrementalData'; upsertIncrementalPartitionPattern.specializedSchema = 'csv'; upsertIncrementalPartitionPattern.exhibitsTraits.push(constants.INCREMENTAL_TRAIT_NAME, [['type', cdmIncrementalPartitionType[cdmIncrementalPartitionType.Upsert]]]); const deletePartitionPattern = corpus.MakeObject<CdmDataPartitionPatternDefinition>(cdmObjectType.dataPartitionPatternDef, 'TestingPartitionPattern', false); deletePartitionPattern.rootLocation = '/IncrementalData'; deletePartitionPattern.specializedSchema = 'csv'; localizedEntityDeclaration.dataPartitionPatterns.push(upsertIncrementalPartitionPattern); localizedEntityDeclaration.dataPartitionPatterns.push(deletePartitionPattern); using(enterScope('DataPartitionPatternTest', corpus.ctx, 'TestToDataPartitionPatternWithIncrementalTrait'), _ => { const manifestData = CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined); expect(manifestData.entities.length) .toBe(1); const entityData: EntityDeclarationDefinition = manifestData.entities[0]; expect(entityData.dataPartitionPatterns.length) .toBe(1); const patternData: DataPartitionPattern = entityData.dataPartitionPatterns[0]; expect(patternData.name) .toBe('TestingPartitionPattern'); }); expect(errorMessageVerified) .toBeTruthy(); done(); }); });
the_stack
import * as ethers from 'ethers'; import { TxEthSignature, EthSignerType, PubKeyHash, Address, Ratio } from './types'; import { getSignedBytesFromMessage, signMessagePersonalAPI, getChangePubkeyMessage, serializeAddress, serializeAccountId } from './utils'; /** * Wrapper around `ethers.Signer` which provides convenient methods to get and sign messages required for zkSync. */ export class EthMessageSigner { constructor(private ethSigner: ethers.Signer, private ethSignerType?: EthSignerType) {} async getEthMessageSignature(message: ethers.utils.BytesLike): Promise<TxEthSignature> { if (this.ethSignerType == null) { throw new Error('ethSignerType is unknown'); } const signedBytes = getSignedBytesFromMessage(message, !this.ethSignerType.isSignedMsgPrefixed); const signature = await signMessagePersonalAPI(this.ethSigner, signedBytes); return { type: this.ethSignerType.verificationMethod === 'ECDSA' ? 'EthereumSignature' : 'EIP1271Signature', signature }; } getTransferEthSignMessage(transfer: { stringAmount: string; stringToken: string; stringFee: string; to: string; nonce: number; accountId: number; }): string { let humanReadableTxInfo = this.getTransferEthMessagePart(transfer); if (humanReadableTxInfo.length != 0) { humanReadableTxInfo += '\n'; } humanReadableTxInfo += `Nonce: ${transfer.nonce}`; return humanReadableTxInfo; } async ethSignTransfer(transfer: { stringAmount: string; stringToken: string; stringFee: string; to: string; nonce: number; accountId: number; }): Promise<TxEthSignature> { const message = this.getTransferEthSignMessage(transfer); return await this.getEthMessageSignature(message); } async ethSignSwap(swap: { fee: string; feeToken: string; nonce: number }): Promise<TxEthSignature> { const message = this.getSwapEthSignMessage(swap); return await this.getEthMessageSignature(message); } async ethSignOrder(order: { tokenSell: string; tokenBuy: string; recipient: string; amount: string; ratio: Ratio; nonce: number; }): Promise<TxEthSignature> { const message = this.getOrderEthSignMessage(order); return await this.getEthMessageSignature(message); } getSwapEthSignMessagePart(swap: { fee: string; feeToken: string }): string { if (swap.fee != '0' && swap.fee) { return `Swap fee: ${swap.fee} ${swap.feeToken}`; } return ''; } getSwapEthSignMessage(swap: { fee: string; feeToken: string; nonce: number }): string { let message = this.getSwapEthSignMessagePart(swap); if (message != '') { message += '\n'; } message += `Nonce: ${swap.nonce}`; return message; } getOrderEthSignMessage(order: { tokenSell: string; tokenBuy: string; recipient: string; amount: string; ratio: Ratio; nonce: number; }): string { let message: string; if (order.amount == '0' || order.amount == null) { message = `Limit order for ${order.tokenSell} -> ${order.tokenBuy}\n`; } else { message = `Order for ${order.amount} ${order.tokenSell} -> ${order.tokenBuy}\n`; } message += `Ratio: ${order.ratio[0].toString()}:${order.ratio[1].toString()}\n` + `Address: ${order.recipient.toLowerCase()}\n` + `Nonce: ${order.nonce}`; return message; } async ethSignForcedExit(forcedExit: { stringToken: string; stringFee: string; target: string; nonce: number; }): Promise<TxEthSignature> { const message = this.getForcedExitEthSignMessage(forcedExit); return await this.getEthMessageSignature(message); } getMintNFTEthMessagePart(mintNFT: { stringFeeToken: string; stringFee: string; recipient: string; contentHash: string; }): string { let humanReadableTxInfo = `MintNFT ${mintNFT.contentHash} for: ${mintNFT.recipient.toLowerCase()}`; if (mintNFT.stringFee != null) { humanReadableTxInfo += `\nFee: ${mintNFT.stringFee} ${mintNFT.stringFeeToken}`; } return humanReadableTxInfo; } getMintNFTEthSignMessage(mintNFT: { stringFeeToken: string; stringFee: string; recipient: string; contentHash: string; nonce: number; }): string { let humanReadableTxInfo = this.getMintNFTEthMessagePart(mintNFT); humanReadableTxInfo += `\nNonce: ${mintNFT.nonce}`; return humanReadableTxInfo; } getWithdrawNFTEthMessagePart(withdrawNFT: { token: number; to: string; stringFee: string; stringFeeToken: string; }): string { let humanReadableTxInfo = `WithdrawNFT ${withdrawNFT.token} to: ${withdrawNFT.to.toLowerCase()}`; if (withdrawNFT.stringFee != null) { humanReadableTxInfo += `\nFee: ${withdrawNFT.stringFee} ${withdrawNFT.stringFeeToken}`; } return humanReadableTxInfo; } getWithdrawNFTEthSignMessage(withdrawNFT: { token: number; to: string; stringFee: string; stringFeeToken: string; nonce: number; }): string { let humanReadableTxInfo = this.getWithdrawNFTEthMessagePart(withdrawNFT); humanReadableTxInfo += `\nNonce: ${withdrawNFT.nonce}`; return humanReadableTxInfo; } getWithdrawEthSignMessage(withdraw: { stringAmount: string; stringToken: string; stringFee: string; ethAddress: string; nonce: number; accountId: number; }): string { let humanReadableTxInfo = this.getWithdrawEthMessagePart(withdraw); if (humanReadableTxInfo.length != 0) { humanReadableTxInfo += '\n'; } humanReadableTxInfo += `Nonce: ${withdraw.nonce}`; return humanReadableTxInfo; } getForcedExitEthSignMessage(forcedExit: { stringToken: string; stringFee: string; target: string; nonce: number; }): string { let humanReadableTxInfo = this.getForcedExitEthMessagePart(forcedExit); humanReadableTxInfo += `\nNonce: ${forcedExit.nonce}`; return humanReadableTxInfo; } getTransferEthMessagePart(tx: { stringAmount: string; stringToken: string; stringFee: string; ethAddress?: string; to?: string; }): string { let txType: string, to: string; if (tx.ethAddress != undefined) { txType = 'Withdraw'; to = tx.ethAddress; } else if (tx.to != undefined) { txType = 'Transfer'; to = tx.to; } else { throw new Error('Either to or ethAddress field must be present'); } let message = ''; if (tx.stringAmount != null) { message += `${txType} ${tx.stringAmount} ${tx.stringToken} to: ${to.toLowerCase()}`; } if (tx.stringFee != null) { if (message.length != 0) { message += '\n'; } message += `Fee: ${tx.stringFee} ${tx.stringToken}`; } return message; } getWithdrawEthMessagePart(tx: { stringAmount: string; stringToken: string; stringFee: string; ethAddress?: string; to?: string; }): string { return this.getTransferEthMessagePart(tx); } getChangePubKeyEthMessagePart(changePubKey: { pubKeyHash: PubKeyHash; stringToken: string; stringFee: string; }): string { let message = ''; message += `Set signing key: ${changePubKey.pubKeyHash.replace('sync:', '').toLowerCase()}`; if (changePubKey.stringFee != null) { message += `\nFee: ${changePubKey.stringFee} ${changePubKey.stringToken}`; } return message; } getForcedExitEthMessagePart(forcedExit: { stringToken: string; stringFee: string; target: string }): string { let message = `ForcedExit ${forcedExit.stringToken} to: ${forcedExit.target.toLowerCase()}`; if (forcedExit.stringFee != null) { message += `\nFee: ${forcedExit.stringFee} ${forcedExit.stringToken}`; } return message; } async ethSignMintNFT(mintNFT: { stringFeeToken: string; stringFee: string; recipient: string; contentHash: string; nonce: number; }): Promise<TxEthSignature> { const message = this.getMintNFTEthSignMessage(mintNFT); return await this.getEthMessageSignature(message); } async ethSignWithdrawNFT(withdrawNFT: { token: number; to: string; stringFee: string; stringFeeToken: string; nonce: number; }): Promise<TxEthSignature> { const message = this.getWithdrawNFTEthSignMessage(withdrawNFT); return await this.getEthMessageSignature(message); } async ethSignWithdraw(withdraw: { stringAmount: string; stringToken: string; stringFee: string; ethAddress: string; nonce: number; accountId: number; }): Promise<TxEthSignature> { const message = this.getWithdrawEthSignMessage(withdraw); return await this.getEthMessageSignature(message); } getChangePubKeyEthSignMessage(changePubKey: { pubKeyHash: PubKeyHash; nonce: number; accountId: number; }): Uint8Array { return getChangePubkeyMessage(changePubKey.pubKeyHash, changePubKey.nonce, changePubKey.accountId); } async ethSignChangePubKey(changePubKey: { pubKeyHash: PubKeyHash; nonce: number; accountId: number; }): Promise<TxEthSignature> { const message = this.getChangePubKeyEthSignMessage(changePubKey); return await this.getEthMessageSignature(message); } async ethSignRegisterFactoryMessage(factoryAddress: Address, accountId: number, accountAddress: Address) { const factoryAddressHex = ethers.utils.hexlify(serializeAddress(factoryAddress)).substr(2); const accountAddressHex = ethers.utils.hexlify(serializeAddress(accountAddress)).substr(2); const msgAccId = ethers.utils.hexlify(serializeAccountId(accountId)).substr(2); const message = `\nCreator's account ID in zkSync: ${msgAccId}\n` + `Creator: ${accountAddressHex}\n` + `Factory: ${factoryAddressHex}`; const msgBytes = ethers.utils.toUtf8Bytes(message); return await this.getEthMessageSignature(msgBytes); } }
the_stack
import GoDBTable from './table'; import { indexedDB } from './global/window'; import { GoDBConfig, GoDBTableSchema, GoDBTableDict, GetDBCallback, GoDBSchema } from './global/types'; export default class GoDB { name: string; version: number; idb: IDBDatabase; tables: GoDBTableDict; private _closed: boolean; private _connection: IDBOpenDBRequest; private _callbackQueue: Array<Function>; // defined by user: // TODO: DBChangeFunction onOpened: Function; onClosed: Function; constructor(name: string, schema?: GoDBSchema, config?: GoDBConfig) { // init params this.version = 0; this.tables = {}; this._callbackQueue = []; // save database's name this.name = name; // settings if (config) { const { version } = config; if (version) this.version = version; } // init tables, `this.idb` is null when init this.updateSchema(schema); // open connection to the IndexedDB this.getDB(); } table(table: string, tableSchema?: GoDBTableSchema): GoDBTable { if (!this.tables[table]) { this.tables[table] = new GoDBTable(this, table, tableSchema); this.updateSchema(); } else if (tableSchema) { this.tables[table] = new GoDBTable(this, table, tableSchema); if (this._shouldUpgrade()) this.updateSchema(); } return this.tables[table]; } updateSchema(schema?: GoDBSchema): void { if (schema) { this.tables = {}; for (let table in schema) this.tables[table] = new GoDBTable(this, table, schema[table]); } if (this.idb) { // create new objectStores when database is already opened console.log(`Updating Schema of Database['${this.name}']`); this.idb.close(); // activate callbackQueue in getDB() // and avoid repeating calling _openDB() before db's opening this.idb = null; // triger `onupgradeneeded` event in _openDB() to update objectStores this._openDB(++this.version, true); } } close(): void { if (this.idb) { this.idb.close(); this.idb = null; this._connection = null; this._closed = true; console.log(`A connection to Database['${this.name}'] is closed`); } else { console.warn(`Unable to close Database['${this.name}']: it is not opened yet`); } } // drop a database drop(): Promise<Event> { return new Promise((resolve, reject) => { const database = this.name; this.close(); // no need to handle Exception according to MDN const deleteRequest = indexedDB.deleteDatabase(database); deleteRequest.onsuccess = (ev) => { this.version = 0; console.log(`Database['${database}'] is successfully dropped`); if (this.onClosed) { if (typeof this.onClosed === 'function') this.onClosed(); else console.warn(`'onClosed' should be a function, not ${typeof this.onClosed}`); this.onClosed = null; } resolve(ev); }; deleteRequest.onerror = (ev) => { const { error } = ev.target as IDBOpenDBRequest; const { name, message } = error; console.warn( `Unable to drop Database['${database}']\ \n- ${name}: ${message}` ); reject(`${name}: ${message}`); }; }); } getDBState(): string { if (this._closed) return 'closed'; if (this.idb) return 'opened'; if (this._connection) return 'connecting'; return 'init'; } /** * It is necessary to get `IDBDatabase` instance (`this.idb`) before * table operations like table.add(), table.get(), etc. * that's why a `getDB` function was needed in this class * * There are 4 possible states when calling `getDB`: * * State `closed`: database is closed or dropped by user * Operation: warning user in console, not calling callback * Where: After invoking `this.close()` or `this.drop()` * * State `init`: no connection yet (`this.connection` is undefined) * Operation: open connection to the IndexedDB database * Where: Constructor's `this.getDB()`, only executed once * * State `connecting`: connection opened, but db is not opened yet (`this.idb` is undefined) * Operation: push the table operations to a queue, executing them when db is opened * Where: Table operations that are in the same macrotask as `new GoDB()` * * State `opened`: The database is opened * Operation: Invoking the callback synchronously with `this.idb` * Where: Table operations when the db is opened, * mention that the db's opening only takes a few milliseconds, * and normally most of user's table operations will happen after db's opening * * State sequence: * init -> connecting -> opened -> closed * * Attention: callback is async-called in state `init` and `connecting`, * but being sync-called in state `opened` */ getDB(callback?: GetDBCallback): void { // State `opened`: db is opened, calling callback synchronously with IDBDatabase instance if (this.idb) { if (callback && typeof callback === 'function') callback(this.idb); return; } // State `closed`: db is closed if (this._closed) { console.warn(`Database['${this.name}'] is closed, operations will not be executed`); return; } // State `connecting`: connection is opened, but db is not opened yet if (this._connection) { if (callback && typeof callback === 'function') this._callbackQueue.push(callback); return; } // State `init`: opening connection to IndexedDB // In case user has set a version in GoDBConfig if (this.version) this._openDB(this.version); else this._openDB(); } private _openDB(version?: number, stopUpgrade?: boolean): void { const database = this.name; const tables = this.tables; this._connection = version ? indexedDB.open(database, version) : indexedDB.open(database); this._connection.onsuccess = (ev) => { const result = this._connection.result || (ev.target as IDBOpenDBRequest).result; this.version = result.version; // triggered when 'onupgradeneeded' was not called // meaning that the database was already existed in browser if (!this.idb) { this.idb = result; console.log(`Database['${database}'] with version (${result.version}) is exisiting`); } // @ts-ignore for (let name of this.idb.objectStoreNames) { if (!this.tables[name]) this.tables[name] = new GoDBTable(this, name); } // `stopUpgrade` is used to avoid infinite recursion if (this._shouldUpgrade() && !stopUpgrade) { // make sure the objectStores structure are matching with the Schema this.updateSchema(); } else { console.log(`A connection to Database['${database}'] is opening`); // executing Table operations invoked by user at State `connecting` if (this._callbackQueue.length) { this._callbackQueue.forEach(fn => fn(this.idb)); this._callbackQueue = []; } // call onOpened if it is defined by user if (this.onOpened) { if (typeof this.onOpened === 'function') this.onOpened(this.idb); else console.warn(`'onOpened' should be a function, not ${typeof this.onOpened}`); this.onOpened = null; } } }; // called when db version is changing // it is called before `onsuccess` this._connection.onupgradeneeded = (ev) => { const { oldVersion, newVersion, target } = ev; const { transaction } = target as IDBOpenDBRequest; // get IndexedDB database instance this.idb = (target as IDBOpenDBRequest).result; this.version = newVersion; if (oldVersion === 0) console.log(`Creating Database['${database}'] with version (${newVersion})`); // make sure the IDB objectStores structure are matching with GoDB Tables' Schema for (let table in tables) this._updateObjectStore(table, tables[table].schema, transaction); if (oldVersion !== 0) console.log(`Database['${database}'] version changed from (${oldVersion}) to (${newVersion})`); }; this._connection.onerror = (ev) => { const { error } = ev.target as IDBOpenDBRequest; const { name, message } = error; throw Error( `Failed to open Database['${database}']` + `\n- ${name}: ${message}` ); }; this._connection.onblocked = (ev) => { const { newVersion, oldVersion } = ev as IDBVersionChangeEvent; console.warn( `Database['${database}'] is opening somewhere with version (${oldVersion}),`, `thus new opening request to version (${newVersion}) was blocked.` ); }; } // check if it is needed to update the objectStores in a existing database // return true when objectStores structure are not matching with the schema // - objectStore (table) is not existing // - table schema has one or more index that objectStore do not have // - index properties are different from which defined in schema private _shouldUpgrade(): boolean { const idb = this.idb; if (!idb) return false; const tables = this.tables; for (let table in tables) { // check if objectStores is existing if (idb.objectStoreNames.contains(table)) { const transaction = idb.transaction(table, 'readonly'); const { indexNames, keyPath, autoIncrement } = transaction.objectStore(table); // if the keyPath is not 'id', or it is not autoIncrement if (keyPath !== 'id' || !autoIncrement) { this.close(); throw Error( `The current existing objectStore '${table}' in IndexedDB '${this.name}'` + ` has a ${autoIncrement ? '' : 'non-'}autoIncrement keyPath \`${keyPath}\`,` + ` while GoDB requires an autoIncrement keyPath \`id\`,` + ` thus GoDB can not open Database['${this.name}']` ); } for (let index in tables[table].schema) { // check if the objectStore has the index if (indexNames.contains(index)) { // TODO: check properties like `unique` } else { // closing the transaction to avoid db's `blocked` event when upgrading transaction.abort(); return true; } } transaction.abort(); } else { return true; } } return false; } // applying the schema to corresponding IndexedDB objectStores to setup indexes // require IDBTransaction `versionchange` // it can only be called in `onupgradeneeded` private _updateObjectStore(table: string, schema: GoDBTableSchema, transaction: IDBTransaction): void { const idb = this.idb; if (!idb) return; const putIndex = (index: string, store: IDBObjectStore, update?: boolean) => { if (index === 'id') return; if (update) store.deleteIndex(index); store.createIndex(index, index, { unique: !!schema[index]['unique'], multiEntry: !!schema[index]['multiEntry'] }); console.log( `${update ? 'Updating' : 'Creating'} Index['${index}']`, `in Table['${table}'], Database['${idb.name}']` ); } if (idb.objectStoreNames.contains(table)) { // objectStore is existing, update its indexes const store = transaction.objectStore(table); const { indexNames } = store; // if the objectStore contains an index, update the index // if not, create a new index in the objectStore for (let index in this.tables[table].schema) putIndex(index, store, indexNames.contains(index)); } else { // create objectStore if not exist const store = idb.createObjectStore(table, { keyPath: 'id', autoIncrement: true }); console.log(`Creating Table['${table}'] in Database['${idb.name}']`); for (let index in schema) putIndex(index, store); } } }
the_stack
import 'jest' import { ComponentsRepositoryV2 } from '../../../../app/v2/api/deployments/repository' import { ConsoleLoggerService } from '../../../../app/v2/core/logs/console' import { DeploymentRepositoryV2 } from '../../../../app/v2/api/deployments/repository/deployment.repository' import { createDeployComponent, getDeploymentWithManifestAndPreviousFixture, getDeploymentWithManifestFixture } from '../../fixtures/deployment-entity.fixture' import { HookParams } from '../../../../app/v2/operator/interfaces/params.interface' import { ReconcileDeploymentUsecase } from '../../../../app/v2/operator/use-cases/reconcile-deployment.usecase' import { K8sClient } from '../../../../app/v2/core/integrations/k8s/client' import IEnvConfiguration from '../../../../app/v2/core/configuration/interfaces/env-configuration.interface' import { MooveService } from '../../../../app/v2/core/integrations/moove' import { ExecutionRepository } from '../../../../app/v2/api/deployments/repository/execution.repository' import { HttpService } from '@nestjs/common' import { Execution } from '../../../../app/v2/api/deployments/entity/execution.entity' import { ExecutionTypeEnum } from '../../../../app/v2/api/deployments/enums' import { DeploymentStatusEnum } from '../../../../app/v2/api/deployments/enums/deployment-status.enum' describe('Reconcile deployment usecase spec', () => { const butlerNamespace = 'butler-namespace' const consoleLoggerService = new ConsoleLoggerService() const envConfiguration = { butlerNamespace: butlerNamespace } as IEnvConfiguration const deploymentRepository = new DeploymentRepositoryV2() const componentsRepository = new ComponentsRepositoryV2() const executionRepository = new ExecutionRepository(consoleLoggerService) const mooveService = new MooveService(new HttpService(), consoleLoggerService) const k8sClient = new K8sClient(consoleLoggerService, envConfiguration) let hookParamsWithNothingCreated: HookParams let hookParamsWithDeploymentNotReady: HookParams beforeEach(() => { hookParamsWithNothingCreated = { 'controller': { 'kind': 'CompositeController', 'apiVersion': 'metacontroller.k8s.io/v1alpha1', 'metadata': { 'name': 'charlesdeployments-controller', 'uid': '67a4c2e9-4a27-4c8c-8c99-735c96ead809', 'resourceVersion': '834', 'generation': 1, 'creationTimestamp': '2021-01-18T13:29:13Z', 'labels': { 'app.kubernetes.io/managed-by': 'Helm' }, 'annotations': { 'meta.helm.sh/release-name': 'charlescd', 'meta.helm.sh/release-namespace': 'default' } }, 'spec': { 'parentResource': { 'apiVersion': 'charlescd.io/v1', 'resource': 'charlesdeployments' }, 'childResources': [ { 'apiVersion': 'v1', 'resource': 'services', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } }, { 'apiVersion': 'apps/v1', 'resource': 'deployments', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } } ], 'hooks': { 'sync': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/reconcile' } }, 'finalize': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/finalize' } } }, 'generateSelector': true }, 'status': {} }, 'parent': { 'apiVersion': 'charlescd.io/v1', 'kind': 'CharlesDeployment', 'metadata': { 'creationTimestamp': '2021-01-18T13:33:14Z', 'finalizers': [ 'metacontroller.app/compositecontroller-charlesdeployments-controller' ], 'generation': 1, 'labels': { // this key is used to fetch the deployment 'deployment_id': 'b7d08a07-f29d-452e-a667-7a39820f3262' }, 'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'namespace': 'default', 'resourceVersion': '1368', 'uid': 'aeb60d21-75d8-40d5-8639-9c5623c35921' }, 'spec': { 'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'components': [ { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'batata', 'tag': 'latest' }, { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'jilo', 'tag': 'latest' } ], 'deploymentId': 'b1e16c7d-15dd-4e4d-8d4b-d8c73ddf847c' } }, 'children': { 'Deployment.apps/v1': {}, 'Service.v1': {} }, 'finalizing': false } hookParamsWithDeploymentNotReady = { 'controller': { 'kind': 'CompositeController', 'apiVersion': 'metacontroller.k8s.io/v1alpha1', 'metadata': { 'name': 'charlesdeployments-controller', 'uid': '67a4c2e9-4a27-4c8c-8c99-735c96ead809', 'resourceVersion': '834', 'generation': 1, 'creationTimestamp': '2021-01-18T13:29:13Z', 'labels': { 'app.kubernetes.io/managed-by': 'Helm' }, 'annotations': { 'meta.helm.sh/release-name': 'charlescd', 'meta.helm.sh/release-namespace': 'default' } }, 'spec': { 'parentResource': { 'apiVersion': 'charlescd.io/v1', 'resource': 'charlesdeployments' }, 'childResources': [ { 'apiVersion': 'v1', 'resource': 'services', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } }, { 'apiVersion': 'apps/v1', 'resource': 'deployments', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } } ], 'hooks': { 'sync': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/reconcile' } }, 'finalize': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/finalize' } } }, 'generateSelector': true }, 'status': {} }, 'parent': { 'apiVersion': 'charlescd.io/v1', 'kind': 'CharlesDeployment', 'metadata': { 'creationTimestamp': '2021-01-18T13:33:14Z', 'finalizers': [ 'metacontroller.app/compositecontroller-charlesdeployments-controller' ], 'generation': 1, 'labels': { // this key is used to fetch the deployment 'deployment_id': 'b7d08a07-f29d-452e-a667-7a39820f3262' }, 'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'namespace': 'default', 'resourceVersion': '1368', 'uid': 'aeb60d21-75d8-40d5-8639-9c5623c35921' }, 'spec': { 'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'components': [ { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'batata', 'tag': 'latest' }, { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'jilo', 'tag': 'latest' } ], 'deploymentId': 'b1e16c7d-15dd-4e4d-8d4b-d8c73ddf847c' } }, 'children': { 'Deployment.apps/v1': { 'hello-kubernetes-build-image-tag-b46fd548-0082-4021-ba80-a50703c44a3b': { 'apiVersion': 'apps/v1', 'kind': 'Deployment', 'metadata': { 'creationTimestamp': '2021-01-15T21:01:22Z', 'generation': 1, 'labels': { 'app': 'hello-kubernetes', 'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b', // this key is used to match the deployment 'deploymentId': 'e728a072-b0aa-4459-88ba-0f4a9b71ae54', 'version': 'hello-kubernetes' }, 'name': 'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'namespace': 'default', 'ownerReferences': [ { 'apiVersion': 'charlescd.io/v1', 'blockOwnerDeletion': true, 'controller': true, 'kind': 'CharlesDeployment', 'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b' } ], 'resourceVersion': '6755', 'uid': '1127f97a-4288-4dfc-8cc3-6c9a039b26cf' }, 'spec': { 'progressDeadlineSeconds': 600, 'replicas': 1, 'revisionHistoryLimit': 10, 'selector': { 'matchLabels': { 'app': 'batata', 'version': 'batata' } }, 'strategy': { 'rollingUpdate': { 'maxSurge': '25%', 'maxUnavailable': '25%' }, 'type': 'RollingUpdate' }, 'template': { 'metadata': { 'annotations': { 'sidecar.istio.io/inject': 'true' }, 'creationTimestamp': null, 'labels': { 'app': 'batata', 'version': 'batata' } }, 'spec': { 'containers': [ { 'args': [ '-text', 'hello' ], 'image': 'hashicorp/http-echo', 'imagePullPolicy': 'Always', 'livenessProbe': { 'failureThreshold': 3, 'httpGet': { 'path': '/', 'port': 5678, 'scheme': 'HTTP' }, 'initialDelaySeconds': 30, 'periodSeconds': 20, 'successThreshold': 1, 'timeoutSeconds': 1 }, 'name': 'batata', 'readinessProbe': { 'failureThreshold': 3, 'httpGet': { 'path': '/', 'port': 5678, 'scheme': 'HTTP' }, 'initialDelaySeconds': 30, 'periodSeconds': 20, 'successThreshold': 1, 'timeoutSeconds': 1 }, 'resources': { 'limits': { 'cpu': '128m', 'memory': '128Mi' }, 'requests': { 'cpu': '64m', 'memory': '64Mi' } }, 'terminationMessagePath': '/dev/termination-log', 'terminationMessagePolicy': 'File' } ], 'dnsPolicy': 'ClusterFirst', 'restartPolicy': 'Always', 'schedulerName': 'default-scheduler', 'securityContext': {}, 'terminationGracePeriodSeconds': 30 } } }, 'status': { 'availableReplicas': 1, 'conditions': [ { 'lastTransitionTime': '2021-01-15T21:01:22Z', 'lastUpdateTime': '2021-01-15T21:02:06Z', 'message': 'ReplicaSet "batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60-7f7dfc545f" has successfully progressed.', 'reason': 'NewReplicaSetAvailable', 'status': 'True', 'type': 'Progressing' } ], 'observedGeneration': 1, 'readyReplicas': 1, 'replicas': 1, 'updatedReplicas': 1 } }, }, 'Service.v1': {} }, 'finalizing': false } }) it('should generate the reconcile deployment object with the correct metadata changes', async() => { const componentsCircle1 = [ createDeployComponent('A', 'v1', 'circle-1', true, 'noManifest', 'namespace', true) ] jest.spyOn(deploymentRepository, 'findOneOrFail').mockImplementation(async() => getDeploymentWithManifestFixture('simple')) jest.spyOn(executionRepository, 'findOneOrFail').mockImplementation(async() => new Execution(getDeploymentWithManifestFixture('simple'), ExecutionTypeEnum.DEPLOYMENT, null, DeploymentStatusEnum.CREATED) ) jest.spyOn(componentsRepository, 'findActiveComponents').mockImplementation(async() => componentsCircle1) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262' } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } } ], resyncAfterSeconds: 5 } const reconcileDeploymentUsecase = new ReconcileDeploymentUsecase( k8sClient, deploymentRepository, componentsRepository, consoleLoggerService, executionRepository, mooveService ) const reconcileObj = await reconcileDeploymentUsecase.execute(hookParamsWithNothingCreated) expect(reconcileObj).toEqual(expectedReconcileObj) }) it('should generate the correct desired state with different deployment manifests when a override happens', async() => { jest.spyOn(deploymentRepository, 'findOneOrFail') .mockImplementationOnce(async() => getDeploymentWithManifestAndPreviousFixture('simple')) .mockImplementationOnce(async() => getDeploymentWithManifestFixture('simple')) jest.spyOn(executionRepository, 'findOneOrFail').mockImplementation(async() => new Execution(getDeploymentWithManifestAndPreviousFixture('simple'), ExecutionTypeEnum.DEPLOYMENT, null, DeploymentStatusEnum.CREATED) ) // this won't change the test outcome jest.spyOn(componentsRepository, 'findActiveComponents').mockImplementation(async() => []) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } }, { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-2-e728a072-b0aa-4459-88ba-0f4a9b71ae54', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'e728a072-b0aa-4459-88ba-0f4a9b71ae54', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'e728a072-b0aa-4459-88ba-0f4a9b71ae54' } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url-2.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } } ], resyncAfterSeconds: 5 } const reconcileDeploymentUsecase = new ReconcileDeploymentUsecase( k8sClient, deploymentRepository, componentsRepository, consoleLoggerService, executionRepository, mooveService ) const reconcileObj = await reconcileDeploymentUsecase.execute(hookParamsWithDeploymentNotReady) expect(reconcileObj).toEqual(expectedReconcileObj) }) it('should generate the correct desired state without manifest repetition when a override happens', async() => { jest.spyOn(deploymentRepository, 'findOneOrFail') .mockImplementationOnce(async() => getDeploymentWithManifestAndPreviousFixture('complex')) .mockImplementationOnce(async() => getDeploymentWithManifestFixture('complex')) jest.spyOn(executionRepository, 'findOneOrFail').mockImplementation(async() => new Execution(getDeploymentWithManifestAndPreviousFixture('complex'), ExecutionTypeEnum.DEPLOYMENT, null, DeploymentStatusEnum.CREATED) ) // this won't change the test outcome jest.spyOn(componentsRepository, 'findActiveComponents').mockImplementation(async() => []) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262' } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } }, { apiVersion: 'v1', data: { 'secret-data': 'dGVzdA==' }, kind: 'Secret', metadata: { labels: { app: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', component: 'hello-kubernetes', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', version: 'hello-kubernetes' }, name: 'custom-secret', namespace: 'namespace' }, type: 'Opaque' }, { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-2-e728a072-b0aa-4459-88ba-0f4a9b71ae54', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'e728a072-b0aa-4459-88ba-0f4a9b71ae54', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'e728a072-b0aa-4459-88ba-0f4a9b71ae54' } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url-2.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } } ], resyncAfterSeconds: 5 } const reconcileDeploymentUsecase = new ReconcileDeploymentUsecase( k8sClient, deploymentRepository, componentsRepository, consoleLoggerService, executionRepository, mooveService ) const reconcileObj = await reconcileDeploymentUsecase.execute(hookParamsWithDeploymentNotReady) expect(reconcileObj).toEqual(expectedReconcileObj) }) it('should return the desired manifests of the new deployment when there is no previous and it is not ready yet', async() => { jest.spyOn(deploymentRepository, 'findOneOrFail') .mockImplementation(async() => getDeploymentWithManifestFixture('complex')) jest.spyOn(executionRepository, 'findOneOrFail').mockImplementation(async() => new Execution(getDeploymentWithManifestAndPreviousFixture('complex'), ExecutionTypeEnum.DEPLOYMENT, null, DeploymentStatusEnum.CREATED) ) // this won't change the test outcome jest.spyOn(componentsRepository, 'findActiveComponents').mockImplementation(async() => []) const reconcileDeploymentUsecase = new ReconcileDeploymentUsecase( k8sClient, deploymentRepository, componentsRepository, consoleLoggerService, executionRepository, mooveService ) const reconcileObj = await reconcileDeploymentUsecase.execute(hookParamsWithDeploymentNotReady) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'namespace', labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', component: 'hello-kubernetes', tag: 'tag-example' } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes', version: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'hello-kubernetes', version: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } }, { apiVersion: 'v1', data: { 'secret-data': 'dGVzdA==' }, kind: 'Secret', metadata: { labels: { app: 'hello-kubernetes', circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', component: 'hello-kubernetes', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', version: 'hello-kubernetes' }, name: 'custom-secret', namespace: 'namespace' }, type: 'Opaque' }, ], resyncAfterSeconds: 5 } expect(reconcileObj).toEqual(expectedReconcileObj) }) it('should create the correct medatada labels/namespace fields when the manifests dont have it', async() => { const componentsCircle1 = [ createDeployComponent('A', 'v1', 'circle-1', true, 'noManifest', 'namespace', true) ] jest.spyOn(deploymentRepository, 'findOneOrFail').mockImplementation(async() => getDeploymentWithManifestFixture('noLabels')) jest.spyOn(executionRepository, 'findOneOrFail').mockImplementation(async() => new Execution(getDeploymentWithManifestFixture('noLabels'), ExecutionTypeEnum.DEPLOYMENT, null, DeploymentStatusEnum.CREATED) ) jest.spyOn(componentsRepository, 'findActiveComponents').mockImplementation(async() => componentsCircle1) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'hello-kubernetes-build-image-tag-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'namespace', labels: { circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', } }, spec: { replicas: 1, selector: { matchLabels: { app: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262' } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, imagePullPolicy: 'Always', resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } }, { apiVersion: 'apps/v1', kind: 'StatefulSet', metadata: { name: 'hello-kubernetes', namespace: 'namespace', labels: { circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', } }, spec: { serviceName: 'helm-test-chart', replicas: 2, selector: { matchLabels: { app: 'hello-kubernetes' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { circleId: 'b46fd548-0082-4021-ba80-a50703c44a3b', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', } }, spec: { containers: [ { name: 'hello-kubernetes', image: 'build-image-url.com', ports: [ { containerPort: 80, name: 'web' } ], volumeMounts: [ { name: 'www', mountPath: '/usr/share/helm-test/html' } ] } ] } }, volumeClaimTemplates: [ { metadata: { name: 'www' }, spec: { accessModes: [ 'ReadWriteOnce' ], resources: { requests: { storage: '1Gi' } } } } ] } } ], resyncAfterSeconds: 5 } const reconcileDeploymentUsecase = new ReconcileDeploymentUsecase( k8sClient, deploymentRepository, componentsRepository, consoleLoggerService, executionRepository, mooveService ) const reconcileObj = await reconcileDeploymentUsecase.execute(hookParamsWithNothingCreated) expect(reconcileObj).toEqual(expectedReconcileObj) }) })
the_stack
import { assertWorkletCreator, clamp, useAnimatedGestureHandler, vectors, workletNoop, } from '@gallery-toolkit/common'; import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { Dimensions, Image, ImageRequireSource, StyleSheet, ViewStyle, } from 'react-native'; import { PanGestureHandler, PanGestureHandlerGestureEvent, PinchGestureHandler, PinchGestureHandlerGestureEvent, State, TapGestureHandler, TapGestureHandlerGestureEvent, } from 'react-native-gesture-handler'; import Animated, { cancelAnimation, Easing, runOnJS, useAnimatedReaction, useAnimatedStyle, useDerivedValue, useSharedValue, withDecay, withSpring, withTiming, useWorkletCallback, } from 'react-native-reanimated'; const assertWorklet = assertWorkletCreator( '@gallery-toolkit/image-transformer', ); const styles = StyleSheet.create({ fill: { ...StyleSheet.absoluteFillObject, }, wrapper: { ...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center', }, container: { flex: 1, }, }); const defaultSpringConfig = { stiffness: 1000, damping: 500, mass: 3, overshootClamping: true, restDisplacementThreshold: 0.01, restSpeedThreshold: 0.01, }; const defaultTimingConfig = { duration: 250, easing: Easing.bezier(0.33, 0.01, 0, 1), }; export interface RenderImageProps { width: number; height: number; source: { uri: string } | ImageRequireSource; onLoad: () => void; } export type InteractionType = 'scale' | 'pan'; export interface ImageTransformerReusableProps { renderImage?: (props: RenderImageProps) => JSX.Element; ImageComponent?: React.ComponentType<any>; DOUBLE_TAP_SCALE?: number; MAX_SCALE?: number; MIN_SCALE?: number; OVER_SCALE?: number; onTap?: (isScaled: boolean) => void; onDoubleTap?: (isScaled: boolean) => void; onInteraction?: (type: InteractionType) => void; } export interface ImageTransformerProps extends ImageTransformerReusableProps { outerGestureHandlerRefs?: React.Ref<any>[]; source?: ImageRequireSource | string; width: number; height: number; windowDimensions: { width: number; height: number; }; onStateChange?: (isActive: boolean) => void; isActive?: Animated.SharedValue<boolean>; outerGestureHandlerActive?: Animated.SharedValue<boolean>; springConfig?: Animated.WithSpringConfig; timingConfig?: Animated.WithTimingConfig; style?: ViewStyle; enabled?: boolean; } function checkIsNotUsed(handlerState: Animated.SharedValue<State>) { 'worklet'; return ( handlerState.value !== State.UNDETERMINED && handlerState.value !== State.END ); } export const ImageTransformer = React.memo<ImageTransformerProps>( ({ outerGestureHandlerRefs = [], source, width, height, onStateChange = workletNoop, renderImage, windowDimensions = Dimensions.get('window'), isActive, outerGestureHandlerActive, style, onTap = workletNoop, onDoubleTap = workletNoop, onInteraction = workletNoop, DOUBLE_TAP_SCALE = 3, MAX_SCALE = 3, MIN_SCALE = 0.7, OVER_SCALE = 0.5, timingConfig = defaultTimingConfig, springConfig = defaultSpringConfig, enabled = true, ImageComponent = Image, }) => { // fixGestureHandler(); assertWorklet(onStateChange); assertWorklet(onTap); assertWorklet(onDoubleTap); assertWorklet(onInteraction); if (typeof source === 'undefined') { throw new Error( 'ImageTransformer: either source or uri should be passed to display an image', ); } const imageSource = useMemo( () => typeof source === 'string' ? { uri: source, } : source, [source], ); const interactionsEnabled = useSharedValue(false); const setInteractionsEnabled = useCallback((value: boolean) => { interactionsEnabled.value = value; }, []); const onLoadImageSuccess = useCallback(() => { setInteractionsEnabled(true); }, []); // HACK ALERT // we disable pinch handler in order to trigger onFinish // in case user releases one finger const [pinchEnabled, setPinchEnabledState] = useState(true); useEffect(() => { if (!pinchEnabled) { setPinchEnabledState(true); } }, [pinchEnabled]); const disablePinch = useCallback(() => { setPinchEnabledState(false); }, []); // HACK ALERT END const pinchRef = useRef(null); const panRef = useRef(null); const tapRef = useRef(null); const doubleTapRef = useRef(null); const panState = useSharedValue<State>(State.UNDETERMINED); const pinchState = useSharedValue<State>(State.UNDETERMINED); const scale = useSharedValue(1); const scaleOffset = useSharedValue(1); const translation = vectors.useSharedVector(0, 0); const panVelocity = vectors.useSharedVector(0, 0); const scaleTranslation = vectors.useSharedVector(0, 0); const offset = vectors.useSharedVector(0, 0); const canvas = useMemo( () => vectors.create( windowDimensions.width, windowDimensions.height, ), [windowDimensions.width, windowDimensions.height], ); const targetWidth = windowDimensions.width; const scaleFactor = width / targetWidth; const targetHeight = height / scaleFactor; const image = useMemo( () => vectors.create(targetWidth, targetHeight), [targetHeight, targetWidth], ); const canPanVertically = useDerivedValue(() => { return windowDimensions.height < targetHeight * scale.value; }, []); const resetSharedState = useWorkletCallback( (animated?: boolean) => { 'worklet'; if (animated) { scale.value = withTiming(1, timingConfig); scaleOffset.value = 1; vectors.set(offset, () => withTiming(0, timingConfig)); } else { scale.value = 1; scaleOffset.value = 1; vectors.set(translation, 0); vectors.set(scaleTranslation, 0); vectors.set(offset, 0); } }, [timingConfig], ); const maybeRunOnEnd = useWorkletCallback(() => { 'worklet'; const target = vectors.create(0, 0); const fixedScale = clamp(MIN_SCALE, scale.value, MAX_SCALE); const scaledImage = image.y * fixedScale; const rightBoundary = (canvas.x / 2) * (fixedScale - 1); let topBoundary = 0; if (canvas.y < scaledImage) { topBoundary = Math.abs(scaledImage - canvas.y) / 2; } const maxVector = vectors.create(rightBoundary, topBoundary); const minVector = vectors.invert(maxVector); if (!canPanVertically.value) { offset.y.value = withSpring(target.y, springConfig); } // we should handle this only if pan or pinch handlers has been used already if ( (checkIsNotUsed(panState) || checkIsNotUsed(pinchState)) && pinchState.value !== State.CANCELLED ) { return; } if ( vectors.eq(offset, 0) && vectors.eq(translation, 0) && vectors.eq(scaleTranslation, 0) && scale.value === 1 ) { // we don't need to run any animations return; } if (scale.value <= 1) { // just center it vectors.set(offset, () => withTiming(0, timingConfig)); return; } vectors.set( target, vectors.clamp(offset, minVector, maxVector), ); const deceleration = 0.9915; const isInBoundaryX = target.x === offset.x.value; const isInBoundaryY = target.y === offset.y.value; if (isInBoundaryX) { if ( Math.abs(panVelocity.x.value) > 0 && scale.value <= MAX_SCALE ) { offset.x.value = withDecay({ velocity: panVelocity.x.value, clamp: [minVector.x, maxVector.x], deceleration, }); } } else { offset.x.value = withSpring(target.x, springConfig); } if (isInBoundaryY) { if ( Math.abs(panVelocity.y.value) > 0 && scale.value <= MAX_SCALE && offset.y.value !== minVector.y && offset.y.value !== maxVector.y ) { offset.y.value = withDecay({ velocity: panVelocity.y.value, clamp: [minVector.y, maxVector.y], deceleration, }); } } else { offset.y.value = withSpring(target.y, springConfig); } }, [ MIN_SCALE, MAX_SCALE, image, canvas, springConfig, timingConfig, ]); const onPanEvent = useAnimatedGestureHandler< PanGestureHandlerGestureEvent, { panOffset: vectors.Vector<number>; pan: vectors.Vector<number>; } >({ onInit: (_, ctx) => { ctx.panOffset = vectors.create(0, 0); }, shouldHandleEvent: () => { return ( scale.value > 1 && (typeof outerGestureHandlerActive !== 'undefined' ? !outerGestureHandlerActive.value : true) && interactionsEnabled.value ); }, beforeEach: (evt, ctx) => { ctx.pan = vectors.create(evt.translationX, evt.translationY); const velocity = vectors.create(evt.velocityX, evt.velocityY); vectors.set(panVelocity, velocity); }, onStart: (_, ctx) => { cancelAnimation(offset.x); cancelAnimation(offset.y); ctx.panOffset = vectors.create(0, 0); onInteraction('pan'); }, onActive: (evt, ctx) => { panState.value = evt.state; if (scale.value > 1) { if (evt.numberOfPointers > 1) { // store pan offset during the pan with two fingers (during the pinch) vectors.set(ctx.panOffset, ctx.pan); } else { // subtract the offset and assign fixed pan const nextTranslate = vectors.add( ctx.pan, vectors.invert(ctx.panOffset), ); translation.x.value = nextTranslate.x; if (canPanVertically.value) { translation.y.value = nextTranslate.y; } } } }, onEnd: (evt, ctx) => { panState.value = evt.state; vectors.set(ctx.panOffset, 0); vectors.set(offset, vectors.add(offset, translation)); vectors.set(translation, 0); maybeRunOnEnd(); vectors.set(panVelocity, 0); }, }); useAnimatedReaction( () => { if (typeof isActive === 'undefined') { return true; } return isActive.value; }, (currentActive) => { if (!currentActive) { resetSharedState(); } }, ); const onScaleEvent = useAnimatedGestureHandler< PinchGestureHandlerGestureEvent, { origin: vectors.Vector<number>; adjustFocal: vectors.Vector<number>; gestureScale: number; nextScale: number; } >({ onInit: (_, ctx) => { ctx.origin = vectors.create(0, 0); ctx.gestureScale = 1; ctx.adjustFocal = vectors.create(0, 0); }, shouldHandleEvent: (evt) => { return ( evt.numberOfPointers === 2 && (typeof outerGestureHandlerActive !== 'undefined' ? !outerGestureHandlerActive.value : true) && interactionsEnabled.value ); }, beforeEach: (evt, ctx) => { // calculate the overall scale value // also limits this.event.scale ctx.nextScale = clamp( evt.scale * scaleOffset.value, MIN_SCALE, MAX_SCALE + OVER_SCALE, ); if ( ctx.nextScale > MIN_SCALE && ctx.nextScale < MAX_SCALE + OVER_SCALE ) { ctx.gestureScale = evt.scale; } // this is just to be able to use with vectors const focal = vectors.create(evt.focalX, evt.focalY); const CENTER = vectors.divide(canvas, 2); // since it works even when you release one finger if (evt.numberOfPointers === 2) { // focal with translate offset // it alow us to scale into different point even then we pan the image ctx.adjustFocal = vectors.sub( focal, vectors.add(CENTER, offset), ); } else if ( evt.state === State.ACTIVE && evt.numberOfPointers !== 2 ) { runOnJS(disablePinch)(); } }, afterEach: (evt, ctx) => { if ( evt.state === State.END || evt.state === State.CANCELLED ) { return; } scale.value = ctx.nextScale; }, onStart: (_, ctx) => { onInteraction('scale'); cancelAnimation(offset.x); cancelAnimation(offset.y); vectors.set(ctx.origin, ctx.adjustFocal); }, onActive: (evt, ctx) => { pinchState.value = evt.state; const pinch = vectors.sub(ctx.adjustFocal, ctx.origin); const nextTranslation = vectors.add( pinch, ctx.origin, vectors.multiply(-1, ctx.gestureScale, ctx.origin), ); vectors.set(scaleTranslation, nextTranslation); }, onFinish: (evt, ctx) => { // reset gestureScale value ctx.gestureScale = 1; pinchState.value = evt.state; // store scale value scaleOffset.value = scale.value; vectors.set(offset, vectors.add(offset, scaleTranslation)); vectors.set(scaleTranslation, 0); if (scaleOffset.value < 1) { // make sure we don't add stuff below the 1 scaleOffset.value = 1; // this runs the timing animation scale.value = withTiming(1, timingConfig); } else if (scaleOffset.value > MAX_SCALE) { scaleOffset.value = MAX_SCALE; scale.value = withTiming(MAX_SCALE, timingConfig); } maybeRunOnEnd(); }, }); const onTapEvent = useAnimatedGestureHandler({ shouldHandleEvent: (evt) => { return ( evt.numberOfPointers === 1 && (typeof outerGestureHandlerActive !== 'undefined' ? !outerGestureHandlerActive.value : true) && interactionsEnabled.value ); }, onStart: () => { cancelAnimation(offset.x); cancelAnimation(offset.y); }, onActive: () => { onTap(scale.value > 1); }, onEnd: () => { maybeRunOnEnd(); }, }); const handleScaleTo = useWorkletCallback( (x: number, y: number) => { 'worklet'; scale.value = withTiming(DOUBLE_TAP_SCALE, timingConfig); scaleOffset.value = DOUBLE_TAP_SCALE; const targetImageSize = vectors.multiply( image, DOUBLE_TAP_SCALE, ); const CENTER = vectors.divide(canvas, 2); const imageCenter = vectors.divide(image, 2); const focal = vectors.create(x, y); const origin = vectors.multiply( -1, vectors.sub(vectors.divide(targetImageSize, 2), CENTER), ); const koef = vectors.sub( vectors.multiply(vectors.divide(1, imageCenter), focal), 1, ); const target = vectors.multiply(origin, koef); if (targetImageSize.y < canvas.y) { target.y = 0; } offset.x.value = withTiming(target.x, timingConfig); offset.y.value = withTiming(target.y, timingConfig); }, [DOUBLE_TAP_SCALE, timingConfig, image, canvas], ); const onDoubleTapEvent = useAnimatedGestureHandler< TapGestureHandlerGestureEvent, {} >({ shouldHandleEvent: (evt) => { return ( evt.numberOfPointers === 1 && (typeof outerGestureHandlerActive !== 'undefined' ? !outerGestureHandlerActive.value : true) && interactionsEnabled.value ); }, onActive: ({ x, y }) => { onDoubleTap(scale.value > 1); if (scale.value > 1) { resetSharedState(true); } else { handleScaleTo(x, y); } }, }); const animatedStyles = useAnimatedStyle<ViewStyle>(() => { const noOffset = offset.x.value === 0 && offset.y.value === 0; const noTranslation = translation.x.value === 0 && translation.y.value === 0; const noScaleTranslation = scaleTranslation.x.value === 0 && scaleTranslation.y.value === 0; const isInactive = scale.value === 1 && noOffset && noTranslation && noScaleTranslation; onStateChange(isInactive); return { transform: [ { translateX: scaleTranslation.x.value + translation.x.value + offset.x.value, }, { translateY: scaleTranslation.y.value + translation.y.value + offset.y.value, }, { scale: scale.value }, ], }; }, []); return ( <Animated.View style={[styles.container, { width: targetWidth }, style]} > <PinchGestureHandler enabled={enabled && pinchEnabled} ref={pinchRef} onGestureEvent={onScaleEvent} simultaneousHandlers={[ panRef, tapRef, ...outerGestureHandlerRefs, ]} > <Animated.View style={styles.fill}> <PanGestureHandler enabled={enabled} ref={panRef} minDist={4} avgTouches simultaneousHandlers={[ pinchRef, tapRef, ...outerGestureHandlerRefs, ]} onGestureEvent={onPanEvent} > <Animated.View style={styles.fill}> <TapGestureHandler enabled={enabled} ref={tapRef} numberOfTaps={1} maxDeltaX={8} maxDeltaY={8} simultaneousHandlers={[ pinchRef, panRef, ...outerGestureHandlerRefs, ]} waitFor={doubleTapRef} onGestureEvent={onTapEvent} > <Animated.View style={[styles.fill]}> <Animated.View style={styles.fill}> <Animated.View style={styles.wrapper}> <TapGestureHandler enabled={enabled} ref={doubleTapRef} numberOfTaps={2} maxDelayMs={140} maxDeltaX={16} maxDeltaY={16} simultaneousHandlers={[ pinchRef, panRef, ...outerGestureHandlerRefs, ]} onGestureEvent={onDoubleTapEvent} > <Animated.View style={animatedStyles}> {typeof renderImage === 'function' ? ( renderImage({ source: imageSource, width: targetWidth, height: targetHeight, onLoad: onLoadImageSuccess, }) ) : ( <ImageComponent onLoad={onLoadImageSuccess} source={imageSource} style={{ width: targetWidth, height: targetHeight, }} /> )} </Animated.View> </TapGestureHandler> </Animated.View> </Animated.View> </Animated.View> </TapGestureHandler> </Animated.View> </PanGestureHandler> </Animated.View> </PinchGestureHandler> </Animated.View> ); }, );
the_stack
imgSrcToDataURL, imgSrcToBlob, arrayBufferToBlob, blobToArrayBuffer */ /** @private */ declare var BlobBuilder: any /** @private */ declare var MozBlobBuilder: any /** @private */ declare var MSBlobBuilder: any /** @private */ declare var WebKitBlobBuilder: any /** @private */ declare var webkitURL: any import { loadImage, imgToCanvas } from './private' /** * Shim for * [`new Blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob) * to support * [older browsers that use the deprecated `BlobBuilder` API](http://caniuse.com/blob). * * Example: * * ```js * var myBlob = blobUtil.createBlob(['hello world'], {type: 'text/plain'}); * ``` * * @param parts - content of the Blob * @param properties - usually `{type: myContentType}`, * you can also pass a string for the content type * @returns Blob */ export function createBlob (parts: Array<any>, properties?: BlobPropertyBag | string): Blob { parts = parts || [] properties = properties || {} if (typeof properties === 'string') { properties = { type: properties } // infer content type } try { return new Blob(parts, properties) } catch (e) { if (e.name !== 'TypeError') { throw e } var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder var builder = new Builder() for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]) } return builder.getBlob(properties.type) } } /** * Shim for * [`URL.createObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL) * to support browsers that only have the prefixed * `webkitURL` (e.g. Android <4.4). * * Example: * * ```js * var myUrl = blobUtil.createObjectURL(blob); * ``` * * @param blob * @returns url */ export function createObjectURL (blob: Blob): string { return (typeof URL !== 'undefined' ? URL : webkitURL).createObjectURL(blob) } /** * Shim for * [`URL.revokeObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL) * to support browsers that only have the prefixed * `webkitURL` (e.g. Android <4.4). * * Example: * * ```js * blobUtil.revokeObjectURL(myUrl); * ``` * * @param url */ export function revokeObjectURL (url: string): void { return (typeof URL !== 'undefined' ? URL : webkitURL).revokeObjectURL(url) } /** * Convert a `Blob` to a binary string. * * Example: * * ```js * blobUtil.blobToBinaryString(blob).then(function (binaryString) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param blob * @returns Promise that resolves with the binary string */ export function blobToBinaryString (blob: Blob): Promise<string> { return new Promise(function (resolve, reject) { var reader = new FileReader() var hasBinaryString = typeof reader.readAsBinaryString === 'function' reader.onloadend = function () { var result = reader.result || '' if (hasBinaryString) { return resolve(result) } resolve(arrayBufferToBinaryString(result)) } reader.onerror = reject if (hasBinaryString) { reader.readAsBinaryString(blob) } else { reader.readAsArrayBuffer(blob) } }) } /** * Convert a base64-encoded string to a `Blob`. * * Example: * * ```js * var blob = blobUtil.base64StringToBlob(base64String); * ``` * @param base64 - base64-encoded string * @param type - the content type (optional) * @returns Blob */ export function base64StringToBlob (base64: string, type?: string): Blob { var parts = [binaryStringToArrayBuffer(atob(base64))] return type ? createBlob(parts, { type: type }) : createBlob(parts) } /** * Convert a binary string to a `Blob`. * * Example: * * ```js * var blob = blobUtil.binaryStringToBlob(binaryString); * ``` * * @param binary - binary string * @param type - the content type (optional) * @returns Blob */ export function binaryStringToBlob (binary: string, type?: string): Blob { return base64StringToBlob(btoa(binary), type) } /** * Convert a `Blob` to a binary string. * * Example: * * ```js * blobUtil.blobToBase64String(blob).then(function (base64String) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param blob * @returns Promise that resolves with the binary string */ export function blobToBase64String (blob: Blob): Promise<string> { return blobToBinaryString(blob).then(btoa) } /** * Convert a data URL string * (e.g. `'data:image/png;base64,iVBORw0KG...'`) * to a `Blob`. * * Example: * * ```js * var blob = blobUtil.dataURLToBlob(dataURL); * ``` * * @param dataURL - dataURL-encoded string * @returns Blob */ export function dataURLToBlob (dataURL: string): Blob { var type = dataURL.match(/data:([^;]+)/)[1] var base64 = dataURL.replace(/^[^,]+,/, '') var buff = binaryStringToArrayBuffer(atob(base64)) return createBlob([buff], { type: type }) } /** * Convert a `Blob` to a data URL string * (e.g. `'data:image/png;base64,iVBORw0KG...'`). * * Example: * * ```js * var dataURL = blobUtil.blobToDataURL(blob); * ``` * * @param blob * @returns Promise that resolves with the data URL string */ export function blobToDataURL (blob: Blob): Promise<string> { return blobToBase64String(blob).then(function (base64String) { return 'data:' + blob.type + ';base64,' + base64String }) } /** * Convert an image's `src` URL to a data URL by loading the image and painting * it to a `canvas`. * * Note: this will coerce the image to the desired content type, and it * will only paint the first frame of an animated GIF. * * Examples: * * ```js * blobUtil.imgSrcToDataURL('http://mysite.com/img.png').then(function (dataURL) { * // success * }).catch(function (err) { * // error * }); * ``` * * ```js * blobUtil.imgSrcToDataURL('http://some-other-site.com/img.jpg', 'image/jpeg', * 'Anonymous', 1.0).then(function (dataURL) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param src - image src * @param type - the content type (optional, defaults to 'image/png') * @param crossOrigin - for CORS-enabled images, set this to * 'Anonymous' to avoid "tainted canvas" errors * @param quality - a number between 0 and 1 indicating image quality * if the requested type is 'image/jpeg' or 'image/webp' * @returns Promise that resolves with the data URL string */ export function imgSrcToDataURL (src: string, type?: string, crossOrigin?: string, quality?: number): Promise<string> { type = type || 'image/png' return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) { return canvas.toDataURL(type, quality) }) } /** * Convert a `canvas` to a `Blob`. * * Examples: * * ```js * blobUtil.canvasToBlob(canvas).then(function (blob) { * // success * }).catch(function (err) { * // error * }); * ``` * * Most browsers support converting a canvas to both `'image/png'` and `'image/jpeg'`. You may * also want to try `'image/webp'`, which will work in some browsers like Chrome (and in other browsers, will just fall back to `'image/png'`): * * ```js * blobUtil.canvasToBlob(canvas, 'image/webp').then(function (blob) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param canvas - HTMLCanvasElement * @param type - the content type (optional, defaults to 'image/png') * @param quality - a number between 0 and 1 indicating image quality * if the requested type is 'image/jpeg' or 'image/webp' * @returns Promise that resolves with the `Blob` */ export function canvasToBlob (canvas: HTMLCanvasElement, type?: string, quality?: number): Promise<Blob> { if (typeof canvas.toBlob === 'function') { return new Promise(function (resolve) { canvas.toBlob(resolve, type, quality) }) } return Promise.resolve(dataURLToBlob(canvas.toDataURL(type, quality))) } /** * Convert an image's `src` URL to a `Blob` by loading the image and painting * it to a `canvas`. * * Note: this will coerce the image to the desired content type, and it * will only paint the first frame of an animated GIF. * * Examples: * * ```js * blobUtil.imgSrcToBlob('http://mysite.com/img.png').then(function (blob) { * // success * }).catch(function (err) { * // error * }); * ``` * * ```js * blobUtil.imgSrcToBlob('http://some-other-site.com/img.jpg', 'image/jpeg', * 'Anonymous', 1.0).then(function (blob) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param src - image src * @param type - the content type (optional, defaults to 'image/png') * @param crossOrigin - for CORS-enabled images, set this to * 'Anonymous' to avoid "tainted canvas" errors * @param quality - a number between 0 and 1 indicating image quality * if the requested type is 'image/jpeg' or 'image/webp' * @returns Promise that resolves with the `Blob` */ export function imgSrcToBlob (src: string, type?: string, crossOrigin?: string, quality?: number): Promise<Blob> { type = type || 'image/png' return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) { return canvasToBlob(canvas, type, quality) }) } /** * Convert an `ArrayBuffer` to a `Blob`. * * Example: * * ```js * var blob = blobUtil.arrayBufferToBlob(arrayBuff, 'audio/mpeg'); * ``` * * @param buffer * @param type - the content type (optional) * @returns Blob */ export function arrayBufferToBlob (buffer: ArrayBuffer, type?: string): Blob { return createBlob([buffer], type) } /** * Convert a `Blob` to an `ArrayBuffer`. * * Example: * * ```js * blobUtil.blobToArrayBuffer(blob).then(function (arrayBuff) { * // success * }).catch(function (err) { * // error * }); * ``` * * @param blob * @returns Promise that resolves with the `ArrayBuffer` */ export function blobToArrayBuffer (blob: Blob): Promise<ArrayBuffer> { return new Promise(function (resolve, reject) { var reader = new FileReader() reader.onloadend = function () { var result = reader.result || new ArrayBuffer(0) resolve(result) } reader.onerror = reject reader.readAsArrayBuffer(blob) }) } /** * Convert an `ArrayBuffer` to a binary string. * * Example: * * ```js * var myString = blobUtil.arrayBufferToBinaryString(arrayBuff) * ``` * * @param buffer - array buffer * @returns binary string */ export function arrayBufferToBinaryString (buffer: ArrayBuffer): string { var binary = '' var bytes = new Uint8Array(buffer) var length = bytes.byteLength var i = -1 while (++i < length) { binary += String.fromCharCode(bytes[i]) } return binary } /** * Convert a binary string to an `ArrayBuffer`. * * ```js * var myBuffer = blobUtil.binaryStringToArrayBuffer(binaryString) * ``` * * @param binary - binary string * @returns array buffer */ export function binaryStringToArrayBuffer (binary: string): ArrayBuffer { var length = binary.length var buf = new ArrayBuffer(length) var arr = new Uint8Array(buf) var i = -1 while (++i < length) { arr[i] = binary.charCodeAt(i) } return buf }
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as TimelineModel from '../../models/timeline_model/timeline_model.js'; import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import * as UI from '../../ui/legacy/legacy.js'; import type {PerformanceModel, WindowChangedEvent} from './PerformanceModel.js'; import {Events} from './PerformanceModel.js'; import type {TimelineModeViewDelegate} from './TimelinePanel.js'; const UIStrings = { /** *@description Text for a heap profile type */ jsHeap: 'JS Heap', /** *@description Text for documents, a type of resources */ documents: 'Documents', /** *@description Text in Counters Graph of the Performance panel */ nodes: 'Nodes', /** *@description Text in Counters Graph of the Performance panel */ listeners: 'Listeners', /** *@description Text in Counters Graph of the Performance panel */ gpuMemory: 'GPU Memory', /** *@description Range text content in Counters Graph of the Performance panel *@example {2} PH1 *@example {10} PH2 */ ss: '[{PH1} – {PH2}]', }; const str_ = i18n.i18n.registerUIStrings('panels/timeline/CountersGraph.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class CountersGraph extends UI.Widget.VBox { private readonly delegate: TimelineModeViewDelegate; private readonly calculator: Calculator; private model!: PerformanceModel|null; private readonly header: UI.Widget.HBox; readonly toolbar: UI.Toolbar.Toolbar; private graphsContainer: UI.Widget.VBox; canvasContainer: UI.Widget.WidgetElement; private canvas: HTMLCanvasElement; private readonly timelineGrid: PerfUI.TimelineGrid.TimelineGrid; private readonly counters: Counter[]; private readonly counterUI: CounterUI[]; private readonly countersByName: Map<string, Counter>; private readonly gpuMemoryCounter: Counter; private track?: TimelineModel.TimelineModel.Track|null; currentValuesBar?: HTMLElement; private markerXPosition?: number; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.id = 'memory-graphs-container'; this.delegate = delegate; this.calculator = new Calculator(); // Create selectors this.header = new UI.Widget.HBox(); this.header.element.classList.add('timeline-memory-header'); this.header.show(this.element); this.toolbar = new UI.Toolbar.Toolbar('timeline-memory-toolbar'); this.header.element.appendChild(this.toolbar.element); this.graphsContainer = new UI.Widget.VBox(); this.graphsContainer.show(this.element); const canvasWidget = new UI.Widget.VBoxWithResizeCallback(this.resize.bind(this)); canvasWidget.show(this.graphsContainer.element); this.createCurrentValuesBar(); this.canvasContainer = canvasWidget.element; this.canvasContainer.id = 'memory-graphs-canvas-container'; this.canvas = document.createElement('canvas'); this.canvasContainer.appendChild(this.canvas); this.canvas.id = 'memory-counters-graph'; this.canvasContainer.addEventListener('mouseover', this.onMouseMove.bind(this), true); this.canvasContainer.addEventListener('mousemove', this.onMouseMove.bind(this), true); this.canvasContainer.addEventListener('mouseleave', this.onMouseLeave.bind(this), true); this.canvasContainer.addEventListener('click', this.onClick.bind(this), true); // We create extra timeline grid here to reuse its event dividers. this.timelineGrid = new PerfUI.TimelineGrid.TimelineGrid(); this.canvasContainer.appendChild(this.timelineGrid.dividersElement); this.counters = []; this.counterUI = []; this.countersByName = new Map(); this.countersByName.set( 'jsHeapSizeUsed', this.createCounter(i18nString(UIStrings.jsHeap), 'hsl(220, 90%, 43%)', Platform.NumberUtilities.bytesToString)); this.countersByName.set('documents', this.createCounter(i18nString(UIStrings.documents), 'hsl(0, 90%, 43%)')); this.countersByName.set('nodes', this.createCounter(i18nString(UIStrings.nodes), 'hsl(120, 90%, 43%)')); this.countersByName.set( 'jsEventListeners', this.createCounter(i18nString(UIStrings.listeners), 'hsl(38, 90%, 43%)')); this.gpuMemoryCounter = this.createCounter( i18nString(UIStrings.gpuMemory), 'hsl(300, 90%, 43%)', Platform.NumberUtilities.bytesToString); this.countersByName.set('gpuMemoryUsedKB', this.gpuMemoryCounter); } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { if (this.model !== model) { if (this.model) { this.model.removeEventListener(Events.WindowChanged, this.onWindowChanged, this); } this.model = model; if (this.model) { this.model.addEventListener(Events.WindowChanged, this.onWindowChanged, this); } } this.calculator.setZeroTime(model ? model.timelineModel().minimumRecordTime() : 0); for (let i = 0; i < this.counters.length; ++i) { this.counters[i].reset(); this.counterUI[i].reset(); } this.scheduleRefresh(); this.track = track; if (!track) { return; } const events = track.syncEvents(); for (let i = 0; i < events.length; ++i) { const event = events[i]; if (event.name !== TimelineModel.TimelineModel.RecordType.UpdateCounters) { continue; } const counters = event.args.data; if (!counters) { return; } for (const name in counters) { const counter = this.countersByName.get(name); if (counter) { counter.appendSample(event.startTime, counters[name]); } } const gpuMemoryLimitCounterName = 'gpuMemoryLimitKB'; if (gpuMemoryLimitCounterName in counters) { this.gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]); } } } private createCurrentValuesBar(): void { this.currentValuesBar = this.graphsContainer.element.createChild('div'); this.currentValuesBar.id = 'counter-values-bar'; } private createCounter(uiName: string, color: string, formatter?: ((arg0: number) => string)): Counter { const counter = new Counter(); this.counters.push(counter); this.counterUI.push(new CounterUI(this, uiName, color, counter, formatter)); return counter; } resizerElement(): Element|null { return this.header.element; } private resize(): void { const parentElement = (this.canvas.parentElement as HTMLElement); this.canvas.width = parentElement.clientWidth * window.devicePixelRatio; this.canvas.height = parentElement.clientHeight * window.devicePixelRatio; this.calculator.setDisplayWidth(this.canvas.width); this.refresh(); } private onWindowChanged(event: Common.EventTarget.EventTargetEvent<WindowChangedEvent>): void { const window = event.data.window; this.calculator.setWindow(window.left, window.right); this.scheduleRefresh(); } scheduleRefresh(): void { UI.UIUtils.invokeOnceAfterBatchUpdate(this, this.refresh); } draw(): void { this.clear(); for (const counter of this.counters) { counter.calculateVisibleIndexes(this.calculator); counter.calculateXValues(this.canvas.width); } for (const counterUI of this.counterUI) { counterUI.drawGraph(this.canvas); } } private onClick(event: Event): void { const x = (event as MouseEvent).x - this.canvasContainer.totalOffsetLeft(); let minDistance: number = Infinity; let bestTime; for (const counterUI of this.counterUI) { if (!counterUI.counter.times.length) { continue; } const index = counterUI.recordIndexAt(x); const distance = Math.abs(x * window.devicePixelRatio - counterUI.counter.x[index]); if (distance < minDistance) { minDistance = distance; bestTime = counterUI.counter.times[index]; } } if (bestTime !== undefined && this.track) { this.delegate.selectEntryAtTime(this.track.events.length ? this.track.events : this.track.asyncEvents, bestTime); } } private onMouseLeave(_event: Event): void { delete this.markerXPosition; this.clearCurrentValueAndMarker(); } private clearCurrentValueAndMarker(): void { for (let i = 0; i < this.counterUI.length; i++) { this.counterUI[i].clearCurrentValueAndMarker(); } } private onMouseMove(event: Event): void { const x = (event as MouseEvent).x - this.canvasContainer.totalOffsetLeft(); this.markerXPosition = x; this.refreshCurrentValues(); } private refreshCurrentValues(): void { if (this.markerXPosition === undefined) { return; } for (let i = 0; i < this.counterUI.length; ++i) { this.counterUI[i].updateCurrentValue(this.markerXPosition); } } refresh(): void { this.timelineGrid.updateDividers(this.calculator); this.draw(); this.refreshCurrentValues(); } private clear(): void { const ctx = this.canvas.getContext('2d'); if (!ctx) { throw new Error('Unable to get canvas context'); } ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); } } export class Counter { times: number[]; values: number[]; x: number[]; minimumIndex: number; maximumIndex: number; private maxTime: number; private minTime: number; limitValue?: number; constructor() { this.times = []; this.values = []; this.x = []; this.minimumIndex = 0; this.maximumIndex = 0; this.maxTime = 0; this.minTime = 0; } appendSample(time: number, value: number): void { if (this.values.length && this.values[this.values.length - 1] === value) { return; } this.times.push(time); this.values.push(value); } reset(): void { this.times = []; this.values = []; } setLimit(value: number): void { this.limitValue = value; } calculateBounds(): { min: number, max: number, } { let maxValue; let minValue; for (let i = this.minimumIndex; i <= this.maximumIndex; i++) { const value = this.values[i]; if (minValue === undefined || value < minValue) { minValue = value; } if (maxValue === undefined || value > maxValue) { maxValue = value; } } minValue = minValue || 0; maxValue = maxValue || 1; if (this.limitValue) { if (maxValue > this.limitValue * 0.5) { maxValue = Math.max(maxValue, this.limitValue); } minValue = Math.min(minValue, this.limitValue); } return {min: minValue, max: maxValue}; } calculateVisibleIndexes(calculator: Calculator): void { const start = calculator.minimumBoundary(); const end = calculator.maximumBoundary(); // Maximum index of element whose time <= start. this.minimumIndex = Platform.NumberUtilities.clamp( Platform.ArrayUtilities.upperBound(this.times, start, Platform.ArrayUtilities.DEFAULT_COMPARATOR) - 1, 0, this.times.length - 1); // Minimum index of element whose time >= end. this.maximumIndex = Platform.NumberUtilities.clamp( Platform.ArrayUtilities.lowerBound(this.times, end, Platform.ArrayUtilities.DEFAULT_COMPARATOR), 0, this.times.length - 1); // Current window bounds. this.minTime = start; this.maxTime = end; } calculateXValues(width: number): void { if (!this.values.length) { return; } const xFactor = width / (this.maxTime - this.minTime); this.x = new Array(this.values.length); for (let i = this.minimumIndex + 1; i <= this.maximumIndex; i++) { this.x[i] = xFactor * (this.times[i] - this.minTime); } } } export class CounterUI { private readonly countersPane: CountersGraph; counter: Counter; private readonly formatter: (arg0: number) => string; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly setting: Common.Settings.Setting<any>; private filter: UI.Toolbar.ToolbarSettingCheckbox; private range: HTMLElement; private value: HTMLElement; graphColor: string; limitColor: string|null|undefined; graphYValues: number[]; private readonly verticalPadding: number; private currentValueLabel: string; private marker: HTMLElement; constructor( countersPane: CountersGraph, title: string, graphColor: string, counter: Counter, formatter?: (arg0: number) => string) { this.countersPane = countersPane; this.counter = counter; this.formatter = formatter || Platform.NumberUtilities.withThousandsSeparator; this.setting = Common.Settings.Settings.instance().createSetting('timelineCountersGraph-' + title, true); this.setting.setTitle(title); this.filter = new UI.Toolbar.ToolbarSettingCheckbox(this.setting, title); this.filter.inputElement.classList.add('-theme-preserve-input'); const parsedColor = Common.Color.Color.parse(graphColor); if (parsedColor) { const colorWithAlpha = parsedColor.setAlpha(0.5).asString(Common.Color.Format.RGBA); const htmlElement = (this.filter.element as HTMLElement); if (colorWithAlpha) { htmlElement.style.backgroundColor = colorWithAlpha; } htmlElement.style.borderColor = 'transparent'; } this.filter.inputElement.addEventListener('click', this.toggleCounterGraph.bind(this)); countersPane.toolbar.appendToolbarItem(this.filter); this.range = this.filter.element.createChild('span', 'range'); this.value = (countersPane.currentValuesBar as HTMLElement).createChild('span', 'memory-counter-value'); this.value.style.color = graphColor; this.graphColor = graphColor; if (parsedColor) { this.limitColor = parsedColor.setAlpha(0.3).asString(Common.Color.Format.RGBA); } this.graphYValues = []; this.verticalPadding = 10; this.currentValueLabel = title; this.marker = countersPane.canvasContainer.createChild('div', 'memory-counter-marker'); this.marker.style.backgroundColor = graphColor; this.clearCurrentValueAndMarker(); } reset(): void { this.range.textContent = ''; } setRange(minValue: number, maxValue: number): void { const min = this.formatter(minValue); const max = this.formatter(maxValue); this.range.textContent = i18nString(UIStrings.ss, {PH1: min, PH2: max}); } private toggleCounterGraph(): void { this.value.classList.toggle('hidden', !this.filter.checked()); this.countersPane.refresh(); } recordIndexAt(x: number): number { return Platform.ArrayUtilities.upperBound( this.counter.x, x * window.devicePixelRatio, Platform.ArrayUtilities.DEFAULT_COMPARATOR, this.counter.minimumIndex + 1, this.counter.maximumIndex + 1) - 1; } updateCurrentValue(x: number): void { if (!this.visible() || !this.counter.values.length || !this.counter.x) { return; } const index = this.recordIndexAt(x); const value = Platform.NumberUtilities.withThousandsSeparator(this.counter.values[index]); this.value.textContent = `${this.currentValueLabel}: ${value}`; const y = this.graphYValues[index] / window.devicePixelRatio; this.marker.style.left = x + 'px'; this.marker.style.top = y + 'px'; this.marker.classList.remove('hidden'); } clearCurrentValueAndMarker(): void { this.value.textContent = ''; this.marker.classList.add('hidden'); } drawGraph(canvas: HTMLCanvasElement): void { const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Unable to get canvas context'); } const width = canvas.width; const height = canvas.height - 2 * this.verticalPadding; if (height <= 0) { this.graphYValues = []; return; } const originY = this.verticalPadding; const counter = this.counter; const values = counter.values; if (!values.length) { return; } const bounds = counter.calculateBounds(); const minValue = bounds.min; const maxValue = bounds.max; this.setRange(minValue, maxValue); if (!this.visible()) { return; } const yValues = this.graphYValues; const maxYRange = maxValue - minValue; const yFactor = maxYRange ? height / (maxYRange) : 1; ctx.save(); ctx.lineWidth = window.devicePixelRatio; if (ctx.lineWidth % 2) { ctx.translate(0.5, 0.5); } ctx.beginPath(); let value: number = values[counter.minimumIndex]; let currentY = Math.round(originY + height - (value - minValue) * yFactor); ctx.moveTo(0, currentY); let i = counter.minimumIndex; for (; i <= counter.maximumIndex; i++) { const x = Math.round(counter.x[i]); ctx.lineTo(x, currentY); const currentValue = values[i]; if (typeof currentValue !== 'undefined') { value = currentValue; } currentY = Math.round(originY + height - (value - minValue) * yFactor); ctx.lineTo(x, currentY); yValues[i] = currentY; } yValues.length = i; ctx.lineTo(width, currentY); ctx.strokeStyle = this.graphColor; ctx.stroke(); if (counter.limitValue) { const limitLineY = Math.round(originY + height - (counter.limitValue - minValue) * yFactor); ctx.moveTo(0, limitLineY); ctx.lineTo(width, limitLineY); if (this.limitColor) { ctx.strokeStyle = this.limitColor; } ctx.stroke(); } ctx.closePath(); ctx.restore(); } visible(): boolean { return this.filter.checked(); } } export class Calculator implements PerfUI.TimelineGrid.Calculator { private minimumBoundaryInternal: number; private maximumBoundaryInternal: number; private workingArea: number; private zeroTimeInternal: number; constructor() { this.minimumBoundaryInternal = 0; this.maximumBoundaryInternal = 0; this.workingArea = 0; this.zeroTimeInternal = 0; } setZeroTime(time: number): void { this.zeroTimeInternal = time; } computePosition(time: number): number { return (time - this.minimumBoundaryInternal) / this.boundarySpan() * this.workingArea; } setWindow(minimumBoundary: number, maximumBoundary: number): void { this.minimumBoundaryInternal = minimumBoundary; this.maximumBoundaryInternal = maximumBoundary; } setDisplayWidth(clientWidth: number): void { this.workingArea = clientWidth; } formatValue(value: number, precision?: number): string { return i18n.TimeUtilities.preciseMillisToString(value - this.zeroTime(), precision); } maximumBoundary(): number { return this.maximumBoundaryInternal; } minimumBoundary(): number { return this.minimumBoundaryInternal; } zeroTime(): number { return this.zeroTimeInternal; } boundarySpan(): number { return this.maximumBoundaryInternal - this.minimumBoundaryInternal; } }
the_stack
import * as fs from "fs"; import * as request from "request-promise-native"; import * as yargs from "yargs"; import * as updateNotifier from "update-notifier"; import { clientUrl, outcomesUrl } from "../schemas/ClientAPI"; import { CreateAppKeyRequest, CreateAppKeyResponse, GetCountsRequest } from "../common/CLIAPI"; import { User, Application } from "./Query"; import chalk from "chalk"; import { table, getBorderCharacters } from "table"; import * as moment from "moment"; import { tryGetUserInfo, setUserInfo, getUserInfo, getIDToken, cognito, clientID, authenticate } from "./Authentication"; import { Outcome, Tree } from "../common/ClientConfig"; import { Count, ExperimentCounts } from "../common/ExperimentCounts"; import { lookupBestOption } from "../client/DecisionTree"; const treeify = require("treeify"); const { red, yellow, blue, magenta, cyan, dim, bold } = chalk; const star = yellow("★"); async function cmdSignup(_args: yargs.Arguments, email: string, password: string): Promise<void> { let response; try { response = await cognito .signUp({ ClientId: clientID, Username: email, Password: password, UserAttributes: [{ Name: "email", Value: email }] }) .promise(); } catch (e) { if (e.code === "UsernameExistsException") { console.error(`An account already exists for ${email}`); } else { console.error(`Could not sign up: ${e.message}`); } return; } if (response.UserConfirmed) { console.log("User creation confirmed"); } else { console.log(`Confirmation code sent to ${response.CodeDeliveryDetails!.Destination}`); console.log('Please use the "confirm" command with the code'); } await setUserInfo({ username: email, password }); } async function createDemoApp() { const appKey = await createApp("My sample autotune app"); console.log(""); console.log("We've created a sample app for you to start with! Add this script tag:"); console.log(""); console.log(` <script src="${clientUrl(appKey)}"></script>`); console.log(""); console.log("Then create an experiment:"); console.log(""); console.log(` <autotune>`); console.log(` <h1>The glass is half full</h1>`); console.log(` <h1>The glass is half empty</h1>`); console.log(` </autotune>`); console.log(""); console.log("Finally, add the autotune attribute to links that you want users to click:"); console.log(""); console.log(` <a href="/buy" autotune>Buy now</a>`); console.log(""); } async function cmdConfirm(_args: yargs.Arguments, email: string | undefined, code: string): Promise<void> { let password: string | undefined = undefined; if (email === undefined) { const userInfo = await getUserInfo(); email = userInfo.username; password = userInfo.password; } await cognito .confirmSignUp({ ClientId: clientID, Username: email, ConfirmationCode: code }) .promise(); console.log("User creation confirmed"); if (password !== undefined) { await authenticateWithPassword(email, password); await createDemoApp(); } else { console.log("Please login to start using autotune"); } } async function authenticateWithPassword(email: string, password: string): Promise<void> { await authenticate(email, "USER_PASSWORD_AUTH", { USERNAME: email, PASSWORD: password }); } async function cmdLogin(_args: yargs.Arguments, email: string, password: string): Promise<void> { await authenticateWithPassword(email, password); console.log("You're now logged in."); } async function makeAuthHeaders(): Promise<{ [name: string]: string }> { return { "Cache-Control": "no-cache", "Content-Type": "application/json", Authorization: await getIDToken() }; } async function requestWithAuth<T>(endpoint: string, body: T): Promise<any> { let url: string; if (endpoint.startsWith("https://")) { url = endpoint; } else { url = "https://2vyiuehl9j.execute-api.us-east-2.amazonaws.com/prod/" + endpoint; } const requestOptions = { method: "POST", url, headers: await makeAuthHeaders(), body, json: true }; return await request(requestOptions).promise(); } async function createApp(name: string): Promise<string> { const body: CreateAppKeyRequest = { name }; const result: CreateAppKeyResponse = await requestWithAuth("createAppKey", body); return result.appKey; } async function cmdCreateApp(_args: yargs.Arguments, name: string): Promise<void> { const appKey = await createApp(name); console.log(`✓ Created app '${magenta(name)}' with key ${bold(appKey)}`); console.log(); console.log("Add this code to your web page:"); console.log(); console.log( [blue("<script"), " ", yellow("src"), blue("="), red(`"${clientUrl(appKey)}"`), blue("></script>")].join("") ); } const graphQLQueryAll = "query {\n viewer {\n username\n applications {\n name\n key\n experiments {\n name\n started\n options {\n name\n completed\n payoff\n }\n }\n }\n }\n}"; const graphQLQueryApplication = "query($key: String!) {\n getApplication(key: $key) {\n name\n key\n experiments {\n name\n started\n options {\n name\n completed\n payoff\n }\n }\n }\n}"; async function queryGraphQL<T>( query: string, queryName: string, variables?: { [name: string]: any } | undefined ): Promise<T> { const body = { query, variables }; const result = await requestWithAuth( "https://wnzihyd3zndg3i3zdo6ijwslze.appsync-api.us-west-2.amazonaws.com/graphql", body ); if (result.errors !== undefined) { throw new Error(`Errors from server: ${JSON.stringify(result)}`); } if (result.data === null) { throw new Error(`No data returned from server`); } return result.data[queryName] as T; } async function getApp(keyOrName: string): Promise<Application | undefined> { const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(keyOrName); if (isUUID) { const app = await queryGraphQL<Application | null>(graphQLQueryApplication, "getApplication", { key: keyOrName }); if (app !== null) return app; } // If the it's a UUID it could still be a name - the user might use // UUIDs as app names. const user = await queryGraphQL<User>(graphQLQueryAll, "viewer"); return user.applications.find(a => a.name === keyOrName); } async function listApps(_args: yargs.Arguments): Promise<void> { const user = await queryGraphQL<User>(graphQLQueryAll, "viewer"); const apps = user.applications .sort((a, b) => a.name.localeCompare(b.name)) .map(app => [magenta(app.name), app.key]); logTable([[bold("App Name"), bold("Key")], ...apps]); } async function cmdListExperiments(_args: yargs.Arguments, appKey: string): Promise<void> { const app = await getApp(appKey); if (app === undefined) { throw new Error("Application not found"); } if (app.experiments.length === 0) { console.log( "Experiments for app not found. Data is processed in batches and may take a while to be ready. Please try again later." ); return; } for (const experiment of app.experiments) { const rows: string[][] = []; const ago = moment(experiment.started).fromNow(); rows.push([bold(magenta(experiment.name)), `Since ${ago}`, "Conversion"]); const options = experiment.options .map(o => ({ ...o, result: o.payoff / o.completed })) .sort((a, b) => b.result - a.result); let first = true; for (const o of options) { const conversionRate = (Math.floor(o.result * 1000) / 10).toString(); const conversion = first ? bold(conversionRate) : conversionRate; const name = first ? bold(o.name + " " + star) : o.name; rows.push([name, dim(`${o.completed} instances`), `${conversion}%`]); first = false; } logTable(rows); } } type PrintTree = string | { [name: string]: PrintTree }; function makePrintTree(outcome: Outcome): PrintTree { const options = outcome.options; function convert(t: Tree): any { if (t.best !== undefined) { return `${bold(options[t.best])} - epsilon: ${t.eps}`; } const { op, neg } = t.op === "lt" ? { op: "<", neg: ">=" } : { op: "=", neg: "!=" }; const result: PrintTree = {}; result[`${t.at} ${op} ${t.v}`] = convert(t.l!); result[`${t.at} ${neg} ${t.v}`] = convert(t.r!); return result; } return convert(outcome.tree); } async function getOutcomesForApp(app: Application): Promise<{ [key: string]: Outcome }> { const requestOptions = { method: "GET", url: outcomesUrl(app.key), json: true }; return await request(requestOptions).promise(); } async function getOutcomesForAppKeyOrFilename(appKey: string): Promise<{ [key: string]: Outcome }> { let outcomes: { [key: string]: Outcome }; let app: Application | undefined = undefined; try { app = await getApp(appKey); } catch {} if (app !== undefined) { outcomes = await getOutcomesForApp(app); } else if (fs.existsSync(appKey)) { outcomes = JSON.parse(fs.readFileSync(appKey, "utf-8")); } else { throw new Error("Application not found"); } return outcomes; } async function cmdShowTrees(appKey: string): Promise<void> { const outcomes = await getOutcomesForAppKeyOrFilename(appKey); for (const experimentKey of Object.getOwnPropertyNames(outcomes)) { console.log(bold(magenta(experimentKey))); console.log(treeify.asTree(makePrintTree(outcomes[experimentKey]), true)); } } type PickedCounts = { [experiment: string]: { [pick: string]: { best: Count; others: { [pick: string]: Count }; }; }; }; function relativePayoffForCount(c: Count): number { return c.payoff / c.completed; } type PickAlternative = { option: string; payoff: number; }; type PickStatistics = { pick: string; audience: number; payoff: number; alternatives: PickAlternative[]; }; type AppStatistics = { experiments: { [name: string]: PickStatistics[] }; }; function makeAppStatistics( outcomes: { [key: string]: Outcome }, counts: { [key: string]: ExperimentCounts } ): AppStatistics { const countsByPick: PickedCounts = {}; for (const experiment of Object.getOwnPropertyNames(counts)) { const outcome = outcomes[experiment]; if (outcome === undefined) continue; const cts = counts[experiment]; const optionNames = new Set<string>(); for (const d of cts.data) { for (const option of Object.getOwnPropertyNames(d.counts)) { optionNames.add(option); } } countsByPick[experiment] = {}; for (const d of cts.data) { const pick = lookupBestOption(d.clientContext as any, outcome).option; if (pick === undefined) { console.log("no best option found"); continue; } let c = countsByPick[experiment][pick]; if (c === undefined) { c = { best: { completed: 0, payoff: 0 }, others: {} }; countsByPick[experiment][pick] = c; } const othersCount = (option: string): Count => { if (c.others[option] === undefined) { c.others[option] = { completed: 0, payoff: 0 }; } return c.others[option]; }; const pickCounts = d.counts[pick]; if (pickCounts === undefined || pickCounts === null) { const keys = Object.getOwnPropertyNames(d.counts); let totalPayoff = 0; for (const k of keys) { const ck = d.counts[k]; if (ck === null) continue; totalPayoff += ck.payoff; } if (totalPayoff === 0) { continue; } // console.log(`we have counts for ${JSON.stringify(keys)}`); // console.log(`best pick ${pick} is not in counts for ${contextString}`); continue; // throw new Error(`best pick ${pick} is not in counts for ${contextString}`); } const relativePayoffForPick = relativePayoffForCount(pickCounts); c.best.completed += pickCounts.completed; c.best.payoff += pickCounts.payoff; const optionsSet = new Set<string>(); let minPayoff = relativePayoffForPick; for (const option of Object.getOwnPropertyNames(d.counts)) { const countsForOption = d.counts[option]; if (countsForOption === null) continue; optionsSet.add(option); const relativePayoff = relativePayoffForCount(countsForOption); /* console.log( `best: ${option === pick} ${countsForOption.completed} in ${contextString} - ${relativePayoff * 100} ${option}` ); */ if (option === pick) { continue; } /* if (relativePayoff > relativePayoffForPick) { throw new Error("non-pick has higher payoff than pick"); } */ const oc = othersCount(option); oc.completed += pickCounts.completed; oc.payoff += relativePayoff * pickCounts.completed; if (relativePayoff < minPayoff) { minPayoff = relativePayoff; } } // This is maybe stupid. If we don't have any information // for an option and a particular context we count it as the // same as the worst option. for (const option of Array.from(optionNames)) { if (optionsSet.has(option) || option === pick) { continue; } const oc = othersCount(option); oc.completed += pickCounts.completed; oc.payoff += minPayoff * pickCounts.completed; } } } const appStatistics: AppStatistics = { experiments: {} }; for (const experiment of Object.getOwnPropertyNames(countsByPick)) { const stats: PickStatistics[] = []; let totalCompleted = 0; for (const pick of Object.getOwnPropertyNames(countsByPick[experiment])) { totalCompleted += countsByPick[experiment][pick].best.completed; } for (const pick of Object.getOwnPropertyNames(countsByPick[experiment])) { const cts = countsByPick[experiment][pick]; const alternatives: PickAlternative[] = []; for (const option of Object.getOwnPropertyNames(cts.others)) { const otherCount = cts.others[option]; if (otherCount.completed !== cts.best.completed) { throw new Error("we counted completed incorrectly"); } alternatives.push({ option, payoff: relativePayoffForCount(otherCount) }); } alternatives.sort((a, b) => b.payoff - a.payoff); const audience = cts.best.completed / totalCompleted; const payoff = relativePayoffForCount(cts.best); stats.push({ pick, audience, payoff, alternatives }); } stats.sort((a, b) => b.audience - a.audience); appStatistics.experiments[experiment] = stats; } return appStatistics; } function formatPercentage(p: number, decimalPlaces: number): string { return `${(p * 100).toFixed(decimalPlaces)}%`; } async function getCountsForApp(app: Application): Promise<{ [key: string]: ExperimentCounts }> { const body: GetCountsRequest = { appKey: app.key }; const result = await requestWithAuth("getCounts", body); return result as { [key: string]: ExperimentCounts }; } async function cmdShowStats(appKey: string, alternatives: boolean): Promise<void> { const app = await getApp(appKey); if (app === undefined) { throw new Error(`App ${appKey} does not exist`); } const outcomes = await getOutcomesForApp(app); const counts = await getCountsForApp(app); const stats = makeAppStatistics(outcomes, counts); for (const experiment of Object.getOwnPropertyNames(stats.experiments)) { const rows: string[][] = [[bold("Option"), bold("Audience"), bold("Payoff")]]; for (const pickStat of stats.experiments[experiment]) { rows.push([ bold(pickStat.pick + " " + star), formatPercentage(pickStat.audience, 2), formatPercentage(pickStat.payoff, 2) ]); if (!alternatives) { continue; } for (const altStat of pickStat.alternatives) { rows.push([altStat.option, "", formatPercentage(altStat.payoff, 2)]); } } console.log(bold(magenta(experiment))); logTable(rows); } } async function graphQL(_args: yargs.Arguments): Promise<void> { console.log(JSON.stringify(await queryGraphQL<User>(graphQLQueryAll, "viewer"), undefined, 4)); } function notifyIfCLIUpdatesAvailable() { try { const pkg = require("../../package.json"); const notifier = updateNotifier({ pkg }); notifier.notify(); } catch (e) {} } async function main(): Promise<void> { let didSomething = false; function cmd(p: Promise<void>): void { p.catch(e => { console.error(e); process.exit(1); }); didSomething = true; } const argv = yargs .usage(`Usage: ${cyan("$0")} <command> ${dim("[options]")}`) .command( "signup <email> <password>", dim("Create a new account"), ya => ya.positional("email", { type: "string" }).positional("password", { type: "string" }), args => cmd(cmdSignup(args, args.email, args.password)) ) .command( "confirm <code>", dim("Confirm a new account"), ya => ya.positional("email", { type: "string" }).positional("code", { type: "string" }), args => cmd(cmdConfirm(args, args.email, args.code)) ) .command( "login <email> <password>", dim("Login"), ya => ya.positional("email", { type: "string" }).positional("password", { type: "string" }), args => cmd(cmdLogin(args, args.email, args.password)) ) .command( "new <name>", dim("Create a new app"), ya => ya.positional("name", { type: "string" }), args => cmd(cmdCreateApp(args, args.name)) ) .command( "ls [key|name]", dim("List apps or experiments for an app"), ya => ya.positional("key", { type: "string" }), args => { if (args.key !== undefined) { cmd(cmdListExperiments(args, args.key)); } else { cmd(listApps(args)); } } ) .command( "trees <key|name|filename>", dim("Show decision trees for experiments in an app"), ya => ya.positional("key", { type: "string" }), args => cmd(cmdShowTrees(args.key)) ) .command( "stats [--alternatives] <key|name>", dim("Show statistics"), ya => ya.positional("key", { type: "string" }).boolean("alternatives"), args => cmd(cmdShowStats(args.key, args.alternatives)) ) .command("graphql", false, {}, args => cmd(graphQL(args))) .wrap(yargs.terminalWidth()).argv; if (!didSomething || argv.help) { if ((await tryGetUserInfo()) === undefined) { console.error("You're not logged in to autotune."); console.error(""); console.error(" Create account: tune signup EMAIL PASSWORD"); console.error(" Log in: tune login EMAIL PASSWORD"); console.error(""); } yargs.showHelp(); } notifyIfCLIUpdatesAvailable(); } function removeWhitespace(data: any): any { if (Array.isArray(data)) { return data.map(removeWhitespace); } if (typeof data === "string") { return data.replace(/\s+/g, " ").trim(); } return data; } function logTable(rows: any[], style: "void" | "norc" = "norc") { rows = removeWhitespace(rows); console.log( table(rows, { border: getBorderCharacters(style), columnDefault: { truncate: 80 } }) ); } main().catch(e => console.error(e));
the_stack
import bigInt from 'big-integer' import { assert } from 'chai' import { XrplNetwork } from 'xpring-common-js' import TransactionStatus from '../../src/XRP/shared/transaction-status' import XrpClient from '../../src/XRP/xrp-client' import XRPTestUtils, { iForgotToPickUpCarlMemo, noDataMemo, noFormatMemo, noTypeMemo, } from './helpers/xrp-test-utils' import { AccountRootFlag } from '../../src/XRP/shared' // A timeout for these tests. // eslint-disable-next-line @typescript-eslint/no-magic-numbers -- 1 minute in milliseconds const timeoutMs = 60 * 1000 // An address on TestNet that has a balance. const recipientAddress = 'X7cBcY4bdTTzk3LHmrKAK6GyrirkXfLHGFxzke5zTmYMfw4' // An XrpClient that makes requests. Sends the requests to an HTTP envoy emulating how the browser would behave. const grpcWebUrl = 'https://envoy.test.xrp.xpring.io' const xrpWebClient = new XrpClient(grpcWebUrl, XrplNetwork.Test, true) // An XrpClient that makes requests. Uses rippled's gRPC implementation. const rippledUrl = 'test.xrp.xpring.io:50051' const xrpClient = new XrpClient(rippledUrl, XrplNetwork.Test) // Some amount of XRP to send. const amount = bigInt('1') describe('XrpClient Integration Tests', function (): void { // Retry integration tests on failure. this.retries(3) // A Wallet with some balance on Testnet. let wallet before(async function () { wallet = await XRPTestUtils.randomWalletFromFaucet() }) it('Get Transaction Status - Web Shim', async function (): Promise<void> { this.timeout(timeoutMs) const transactionResult = await xrpWebClient.sendXrp( amount, recipientAddress, wallet, ) assert.deepEqual(transactionResult.status, TransactionStatus.Succeeded) }) it('Get Transaction Status - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const transactionResult = await xrpClient.sendXrp( amount, recipientAddress, wallet, ) assert.deepEqual(transactionResult.status, TransactionStatus.Succeeded) }) it('Send XRP - Web Shim', async function (): Promise<void> { this.timeout(timeoutMs) const result = await xrpWebClient.sendXrp(amount, recipientAddress, wallet) assert.exists(result) }) it('Send XRP with memo - Web Shim', async function (): Promise<void> { this.timeout(timeoutMs) const memoList = [ iForgotToPickUpCarlMemo, noDataMemo, noFormatMemo, noTypeMemo, ] const transactionResult = await xrpWebClient.sendXrpWithDetails({ amount, destination: recipientAddress, sender: wallet, memoList, }) assert.exists(transactionResult) const transaction = await xrpClient.getPayment(transactionResult.hash) assert.deepEqual(transaction?.memos, [ iForgotToPickUpCarlMemo, noDataMemo, noFormatMemo, noTypeMemo, ]) }) it('Send XRP - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const result = await xrpClient.sendXrp(amount, recipientAddress, wallet) assert.exists(result) }) it('Send XRP with memo - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const memoList = [ iForgotToPickUpCarlMemo, noDataMemo, noFormatMemo, noTypeMemo, ] const transactionResult = await xrpClient.sendXrpWithDetails({ amount, destination: recipientAddress, sender: wallet, memoList, }) assert.exists(transactionResult) const transaction = await xrpClient.getPayment(transactionResult.hash) assert.deepEqual(transaction?.memos, [ iForgotToPickUpCarlMemo, noDataMemo, noFormatMemo, noTypeMemo, ]) }) it('Check if Account Exists - true - Web Shim', async function (): Promise<void> { this.timeout(timeoutMs) const doesExist = await xrpWebClient.accountExists(recipientAddress) assert.equal(doesExist, true) }) it('Check if Account Exists - true - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const doesExist = await xrpClient.accountExists(recipientAddress) assert.equal(doesExist, true) }) it('Check if Account Exists - false - rippled', async function (): Promise<void> { this.timeout(timeoutMs) // This is a valid address, but it should NOT show up on Testnet, so should resolve to false const coinbaseMainnet = 'XVYUQ3SdUcVnaTNVanDYo1NamrUukPUPeoGMnmvkEExbtrj' const doesExist = await xrpClient.accountExists(coinbaseMainnet) assert.equal(doesExist, false) }) it('Payment History - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const payments = await xrpClient.paymentHistory(recipientAddress) assert.isTrue(payments.length > 0) }) it('Get Transaction - rippled', async function (): Promise<void> { this.timeout(timeoutMs) const transactionResult = await xrpClient.sendXrp( amount, recipientAddress, wallet, ) const transaction = await xrpClient.getPayment(transactionResult.hash) assert.exists(transaction) }) it('Enable Deposit Auth - rippled', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account // WHEN enableDepositAuth is called const result = await xrpClient.enableDepositAuth(wallet) // THEN the transaction was successfully submitted and the correct flag was set on the account. await XRPTestUtils.verifyFlagModification( wallet, rippledUrl, result, AccountRootFlag.LSF_DEPOSIT_AUTH, ) }) it('Enable Deposit Auth - sending by unauthorized account fails after enabled', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account with DepositAuth enabled await xrpClient.enableDepositAuth(wallet) // WHEN an account that is not authorized sends XRP const sendingWallet = await XRPTestUtils.randomWalletFromFaucet() const transactionResult = await xrpClient.sendXrp( amount, wallet.getAddress(), sendingWallet, ) // THEN the transaction fails. assert.deepEqual( transactionResult.status, TransactionStatus.ClaimedCostOnly, ) }) it('Authorize Sending Account - failure on authorizing self', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account // WHEN authorizeSendingAccount is called with the account's own address const result = await xrpClient.authorizeSendingAccount( wallet.getAddress(), wallet, ) // THEN the transaction fails due to a malformed transaction. const transactionHash = result.hash const transactionStatus = result.status assert.exists(transactionHash) assert.deepEqual(transactionStatus, TransactionStatus.MalformedTransaction) }) it('Authorize Sending Account - failure on authorizing already authorized account', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account that has authorized another account to send funds to it const sendingWallet = await XRPTestUtils.randomWalletFromFaucet() await xrpClient.enableDepositAuth(wallet) await xrpClient.authorizeSendingAccount(sendingWallet.getAddress(), wallet) // WHEN authorizeSendingAccount is called on the already authorized account const result = await xrpClient.authorizeSendingAccount( sendingWallet.getAddress(), wallet, ) // THEN the transaction fails and the cost of the transaction is claimed by the network. const transactionHash = result.hash const transactionStatus = result.status assert.exists(transactionHash) assert.deepEqual(transactionStatus, TransactionStatus.ClaimedCostOnly) }) it('Authorize Sending Account - can send funds after authorize', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account that has authorized another account to send XRP to it const sendingWallet = await XRPTestUtils.randomWalletFromFaucet() await xrpClient.enableDepositAuth(wallet) await xrpClient.authorizeSendingAccount(sendingWallet.getAddress(), wallet) // WHEN the authorized account sends XRP const transactionResult = await xrpClient.sendXrp( amount, wallet.getAddress(), sendingWallet, ) // THEN the transaction succeeds. assert.deepEqual(transactionResult.status, TransactionStatus.Succeeded) }) it('Unauthorize Sending Account - failure on unauthorizing self', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account // WHEN unauthorizeSendingAccount is called with the account's own address const result = await xrpClient.unauthorizeSendingAccount( wallet.getAddress(), wallet, ) // THEN the transaction fails due to a malformed transaction. const transactionHash = result.hash const transactionStatus = result.status assert.exists(transactionHash) // Note that this is different from what the docs suggest: https://xrpl.org/depositpreauth.html // The code being returned in this case is actually a `tecNO_ENTRY`, which is what // should be returned if the account to unauthorize was never authorized in the first place. // This seems literally true, so we're resting for that. // Note, however, that authorizing self above does in fact return a TransactionStatus.MalformedTransaction. assert.equal(transactionStatus, TransactionStatus.ClaimedCostOnly) }) it('Unauthorize Sending Account - failure on unauthorizing account that is not authorized', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account that has not authorized any accounts await xrpClient.enableDepositAuth(wallet) // WHEN unauthorizeSendingAccount is called on an account that is not authorized const sendingWallet = await XRPTestUtils.randomWalletFromFaucet() const result = await xrpClient.unauthorizeSendingAccount( sendingWallet.getAddress(), wallet, ) // THEN the transaction fails and the cost of the transaction is claimed by the network. const transactionHash = result.hash const transactionStatus = result.status assert.exists(transactionHash) assert.equal(transactionStatus, TransactionStatus.ClaimedCostOnly) }) it('Unauthorize Sending Account - cannot send funds after an authorized account is unauthorized', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an existing testnet account that has authorized another account to send XRP to it const sendingWallet = await XRPTestUtils.randomWalletFromFaucet() await xrpClient.enableDepositAuth(wallet) await xrpClient.authorizeSendingAccount(sendingWallet.getAddress(), wallet) // WHEN the sender's account is unauthorized and a payment is sent. await xrpClient.unauthorizeSendingAccount( sendingWallet.getAddress(), wallet, ) const transactionResult = await xrpClient.sendXrp( amount, wallet.getAddress(), sendingWallet, ) // THEN the transaction fails. assert.deepEqual( transactionResult.status, TransactionStatus.ClaimedCostOnly, ) }) })
the_stack
import { Editor, action, makeObservable } from '@alilc/lowcode-editor-core'; import { DockConfig, PanelConfig, WidgetConfig, IWidgetBaseConfig, PanelDockConfig, DialogDockConfig, isDockConfig, isPanelDockConfig, isPanelConfig, DividerConfig, isDividerConfig, IWidgetConfigArea, } from './types'; import Panel, { isPanel } from './widget/panel'; import WidgetContainer from './widget/widget-container'; import Area from './area'; import Widget, { isWidget, IWidget } from './widget/widget'; import PanelDock from './widget/panel-dock'; import Dock from './widget/dock'; import { Stage, StageConfig } from './widget/stage'; import { isValidElement } from 'react'; import { isPlainObject, uniqueId } from '@alilc/lowcode-utils'; import { Divider } from '@alifd/next'; import { EditorConfig, PluginClassSet } from '@alilc/lowcode-types'; export enum SkeletonEvents { PANEL_DOCK_ACTIVE = 'skeleton.panel-dock.active', PANEL_DOCK_UNACTIVE = 'skeleton.panel-dock.unactive', PANEL_SHOW = 'skeleton.panel.show', PANEL_HIDE = 'skeleton.panel.hide', WIDGET_SHOW = 'skeleton.widget.show', WIDGET_HIDE = 'skeleton.widget.hide', WIDGET_DISABLE = 'skeleton.widget.disable', WIDGET_ENABLE = 'skeleton.widget.enable', } export class Skeleton { private panels = new Map<string, Panel>(); private containers = new Map<string, WidgetContainer<any>>(); readonly leftArea: Area<DockConfig | PanelDockConfig | DialogDockConfig>; readonly topArea: Area<DockConfig | DividerConfig | PanelDockConfig | DialogDockConfig>; readonly toolbar: Area<DockConfig | DividerConfig | PanelDockConfig | DialogDockConfig>; readonly leftFixedArea: Area<PanelConfig, Panel>; readonly leftFloatArea: Area<PanelConfig, Panel>; readonly rightArea: Area<PanelConfig, Panel>; readonly mainArea: Area<WidgetConfig | PanelConfig, Widget | Panel>; readonly bottomArea: Area<PanelConfig, Panel>; readonly stages: Area<StageConfig, Stage>; constructor(readonly editor: Editor) { makeObservable(this); this.leftArea = new Area( this, 'leftArea', (config) => { if (isWidget(config)) { return config; } return this.createWidget(config); }, false, ); this.topArea = new Area( this, 'topArea', (config) => { if (isWidget(config)) { return config; } return this.createWidget(config); }, false, ); this.toolbar = new Area( this, 'toolbar', (config) => { if (isWidget(config)) { return config; } return this.createWidget(config); }, false, ); this.leftFixedArea = new Area( this, 'leftFixedArea', (config) => { if (isPanel(config)) { return config; } return this.createPanel(config); }, true, ); this.leftFloatArea = new Area( this, 'leftFloatArea', (config) => { if (isPanel(config)) { return config; } return this.createPanel(config); }, true, ); this.rightArea = new Area( this, 'rightArea', (config) => { if (isPanel(config)) { return config; } return this.createPanel(config); }, false, true, ); this.mainArea = new Area( this, 'mainArea', (config) => { if (isWidget(config)) { return config as Widget; } return this.createWidget(config) as Widget; }, true, true, ); this.bottomArea = new Area( this, 'bottomArea', (config) => { if (isPanel(config)) { return config; } return this.createPanel(config); }, true, ); this.stages = new Area(this, 'stages', (config) => { if (isWidget(config)) { return config; } return new Stage(this, config); }); this.setupPlugins(); this.setupEvents(); } /** * setup events * * @memberof Skeleton */ setupEvents() { // adjust pinned status when panel shown this.editor.on('skeleton.panel.show', (panelName, panel) => { const panelNameKey = `${panelName}-pinned-status-isFloat`; const isInFloatAreaPreferenceExists = this.editor?.getPreference()?.contains(panelNameKey, 'skeleton'); if (isInFloatAreaPreferenceExists) { const isInFloatAreaFromPreference = this.editor?.getPreference()?.get(panelNameKey, 'skeleton'); const isCurrentInFloatArea = panel?.isChildOfFloatArea(); if (isInFloatAreaFromPreference !== isCurrentInFloatArea) { this.toggleFloatStatus(panel); } } }); } /** * set isFloat status for panel * * @param {*} panel * @memberof Skeleton */ @action toggleFloatStatus(panel: Panel) { const isFloat = panel?.parent?.name === 'leftFloatArea'; if (isFloat) { this.leftFloatArea.remove(panel); this.leftFixedArea.add(panel); this.leftFixedArea.container.active(panel); } else { this.leftFixedArea.remove(panel); this.leftFloatArea.add(panel); this.leftFloatArea.container.active(panel); } this.editor?.getPreference()?.set(`${panel.name}-pinned-status-isFloat`, !isFloat, 'skeleton'); } buildFromConfig(config?: EditorConfig, components: PluginClassSet = {}) { if (config) { this.editor.init(config, components); } this.setupPlugins(); } private setupPlugins() { const { config, components = {} } = this.editor; if (!config) { return; } const { plugins } = config; if (!plugins) { return; } Object.keys(plugins).forEach((area) => { plugins[area].forEach((item) => { const { pluginKey, type, props = {}, pluginProps } = item; const config: Partial<IWidgetBaseConfig> = { area: area as IWidgetConfigArea, type: 'Widget', name: pluginKey, contentProps: pluginProps, }; const { dialogProps, balloonProps, panelProps, linkProps, ...restProps } = props; config.props = restProps; if (dialogProps) { config.dialogProps = dialogProps; } if (balloonProps) { config.balloonProps = balloonProps; } if (panelProps) { config.panelProps = panelProps; } if (linkProps) { config.linkProps = linkProps; } if (type === 'TabPanel') { config.type = 'Panel'; } else if (/Icon$/.test(type)) { config.type = type.replace('Icon', 'Dock'); } if (pluginKey in components) { config.content = components[pluginKey]; } this.add(config as IWidgetBaseConfig); }); }); } postEvent(event: SkeletonEvents, ...args: any[]) { this.editor.emit(event, ...args); } readonly widgets: IWidget[] = []; createWidget(config: IWidgetBaseConfig | IWidget) { if (isWidget(config)) { return config; } config = this.parseConfig(config); let widget: IWidget; if (isDockConfig(config)) { if (isPanelDockConfig(config)) { widget = new PanelDock(this, config); } else if (false) { // DialogDock // others... } else { widget = new Dock(this, config); } } else if (isDividerConfig(config)) { widget = new Widget(this, { ...config, type: 'Widget', content: Divider, }); } else if (isPanelConfig(config)) { widget = this.createPanel(config); } else { widget = new Widget(this, config as WidgetConfig); } this.widgets.push(widget); return widget; } getWidget(name: string): IWidget | undefined { return this.widgets.find(widget => widget.name === name); } createPanel(config: PanelConfig) { const parsedConfig = this.parseConfig(config); const panel = new Panel(this, parsedConfig as PanelConfig); this.panels.set(panel.name, panel); return panel; } getPanel(name: string): Panel | undefined { return this.panels.get(name); } getStage(name: string) { return this.stages.container.get(name); } createStage(config: any) { const stage = this.add({ name: uniqueId('stage'), area: 'stages', ...config, }); return stage?.getName?.(); } createContainer( name: string, handle: (item: any) => any, exclusive = false, checkVisible: () => boolean = () => true, defaultSetCurrent = false, ) { const container = new WidgetContainer(name, handle, exclusive, checkVisible, defaultSetCurrent); this.containers.set(name, container); return container; } private parseConfig(config: IWidgetBaseConfig) { if (config.parsed) { return config; } const { content, ...restConfig } = config; if (content) { if (isPlainObject(content) && !isValidElement(content)) { Object.keys(content).forEach((key) => { if (/props$/i.test(key) && restConfig[key]) { restConfig[key] = { ...restConfig[key], ...content[key], }; } else { restConfig[key] = content[key]; } }); } else { restConfig.content = content; } } restConfig.pluginKey = restConfig.name; restConfig.parsed = true; return restConfig; } add(config: IWidgetBaseConfig, extraConfig?: Record<string, any>) { const parsedConfig = { ...this.parseConfig(config), ...extraConfig, }; let { area } = parsedConfig; if (!area) { if (parsedConfig.type === 'Panel') { area = 'leftFloatArea'; } else if (parsedConfig.type === 'Widget') { area = 'mainArea'; } else { area = 'leftArea'; } } switch (area) { case 'leftArea': case 'left': return this.leftArea.add(parsedConfig as PanelDockConfig); case 'rightArea': case 'right': return this.rightArea.add(parsedConfig as PanelConfig); case 'topArea': case 'top': return this.topArea.add(parsedConfig as PanelDockConfig); case 'toolbar': return this.toolbar.add(parsedConfig as PanelDockConfig); case 'mainArea': case 'main': case 'center': case 'centerArea': return this.mainArea.add(parsedConfig as PanelConfig); case 'bottomArea': case 'bottom': return this.bottomArea.add(parsedConfig as PanelConfig); case 'leftFixedArea': return this.leftFixedArea.add(parsedConfig as PanelConfig); case 'leftFloatArea': return this.leftFloatArea.add(parsedConfig as PanelConfig); case 'stages': return this.stages.add(parsedConfig as StageConfig); default: // do nothing } } }
the_stack
const LANGUAGES: Record<string, any> = { "aa": { "name": "Afar", "nativeName": "Afaraf" }, "ab": { "name": "Abkhaz", "nativeName": "аҧсуа бызшәа" }, "ae": { "name": "Avestan", "nativeName": "avesta" }, "af": { "name": "Afrikaans", "nativeName": "Afrikaans" }, "ak": { "name": "Akan", "nativeName": "Akan" }, "am": { "name": "Amharic", "nativeName": "አማርኛ" }, "an": { "name": "Aragonese", "nativeName": "aragonés" }, "ar": { "name": "Arabic", "nativeName": "اللغة العربية" }, "as": { "name": "Assamese", "nativeName": "অসমীয়া" }, "av": { "name": "Avaric", "nativeName": "авар мацӀ" }, "ay": { "name": "Aymara", "nativeName": "aymar aru" }, "az": { "name": "Azerbaijani", "nativeName": "azərbaycan dili" }, "ba": { "name": "Bashkir", "nativeName": "башҡорт теле" }, "be": { "name": "Belarusian", "nativeName": "беларуская мова" }, "bg": { "name": "Bulgarian", "nativeName": "български език" }, "bh": { "name": "Bihari", "nativeName": "भोजपुरी" }, "bi": { "name": "Bislama", "nativeName": "Bislama" }, "bm": { "name": "Bambara", "nativeName": "bamanankan" }, "bn": { "name": "Bengali", "nativeName": "বাংলা" }, "bo": { "name": "Tibetan", "nativeName": "བོད་ཡིག" }, "br": { "name": "Breton", "nativeName": "brezhoneg" }, "bs": { "name": "Bosnian", "nativeName": "bosanski jezik" }, "ca": { "name": "Catalan", "nativeName": "Català" }, "ce": { "name": "Chechen", "nativeName": "нохчийн мотт" }, "ch": { "name": "Chamorro", "nativeName": "Chamoru" }, "co": { "name": "Corsican", "nativeName": "corsu" }, "cr": { "name": "Cree", "nativeName": "ᓀᐦᐃᔭᐍᐏᐣ" }, "cs": { "name": "Czech", "nativeName": "čeština" }, "cu": { "name": "Old Church Slavonic", "nativeName": "ѩзыкъ словѣньскъ" }, "cv": { "name": "Chuvash", "nativeName": "чӑваш чӗлхи" }, "cy": { "name": "Welsh", "nativeName": "Cymraeg" }, "da": { "name": "Danish", "nativeName": "dansk" }, "de": { "name": "German", "nativeName": "Deutsch" }, "dv": { "name": "Divehi", "nativeName": "Dhivehi" }, "dz": { "name": "Dzongkha", "nativeName": "རྫོང་ཁ" }, "ee": { "name": "Ewe", "nativeName": "Eʋegbe" }, "el": { "name": "Greek", "nativeName": "Ελληνικά" }, "en": { "name": "English", "nativeName": "English" }, "eo": { "name": "Esperanto", "nativeName": "Esperanto" }, "es": { "name": "Spanish", "nativeName": "Español" }, "et": { "name": "Estonian", "nativeName": "eesti" }, "eu": { "name": "Basque", "nativeName": "euskara" }, "fa": { "name": "Persian", "nativeName": "فارسی" }, "ff": { "name": "Fula", "nativeName": "Fulfulde" }, "fi": { "name": "Finnish", "nativeName": "suomi" }, "fj": { "name": "Fijian", "nativeName": "Vakaviti" }, "fo": { "name": "Faroese", "nativeName": "føroyskt" }, "fr": { "name": "French", "nativeName": "Français" }, "fy": { "name": "Western Frisian", "nativeName": "Frysk" }, "ga": { "name": "Irish", "nativeName": "Gaeilge" }, "gd": { "name": "Scottish Gaelic", "nativeName": "Gàidhlig" }, "gl": { "name": "Galician", "nativeName": "galego" }, "gn": { "name": "Guaraní", "nativeName": "Avañe'ẽ" }, "gu": { "name": "Gujarati", "nativeName": "ગુજરાતી" }, "gv": { "name": "Manx", "nativeName": "Gaelg" }, "ha": { "name": "Hausa", "nativeName": "هَوُسَ" }, "he": { "name": "Hebrew", "nativeName": "עברית" }, "hi": { "name": "Hindi", "nativeName": "हिन्दी" }, "ho": { "name": "Hiri Motu", "nativeName": "Hiri Motu" }, "hr": { "name": "Croatian", "nativeName": "Hrvatski" }, "ht": { "name": "Haitian", "nativeName": "Kreyòl ayisyen" }, "hu": { "name": "Hungarian", "nativeName": "magyar" }, "hy": { "name": "Armenian", "nativeName": "Հայերեն" }, "hz": { "name": "Herero", "nativeName": "Otjiherero" }, "ia": { "name": "Interlingua", "nativeName": "Interlingua" }, "id": { "name": "Indonesian", "nativeName": "Bahasa Indonesia" }, "ie": { "name": "Interlingue", "nativeName": "Interlingue" }, "ig": { "name": "Igbo", "nativeName": "Asụsụ Igbo" }, "ii": { "name": "Nuosu", "nativeName": "ꆈꌠ꒿ Nuosuhxop" }, "ik": { "name": "Inupiaq", "nativeName": "Iñupiaq" }, "io": { "name": "Ido", "nativeName": "Ido" }, "is": { "name": "Icelandic", "nativeName": "Íslenska" }, "it": { "name": "Italian", "nativeName": "Italiano" }, "iu": { "name": "Inuktitut", "nativeName": "ᐃᓄᒃᑎᑐᑦ" }, "ja": { "name": "Japanese", "nativeName": "日本語" }, "jv": { "name": "Javanese", "nativeName": "basa Jawa" }, "ka": { "name": "Georgian", "nativeName": "ქართული" }, "kg": { "name": "Kongo", "nativeName": "Kikongo" }, "ki": { "name": "Kikuyu", "nativeName": "Gĩkũyũ" }, "kj": { "name": "Kwanyama", "nativeName": "Kuanyama" }, "kk": { "name": "Kazakh", "nativeName": "қазақ тілі" }, "kl": { "name": "Kalaallisut", "nativeName": "kalaallisut" }, "km": { "name": "Khmer", "nativeName": "ខេមរភាសា" }, "kn": { "name": "Kannada", "nativeName": "ಕನ್ನಡ" }, "ko": { "name": "Korean", "nativeName": "한국어" }, "kr": { "name": "Kanuri", "nativeName": "Kanuri" }, "ks": { "name": "Kashmiri", "nativeName": "कश्मीरी" }, "ku": { "name": "Kurdish", "nativeName": "Kurdî" }, "kv": { "name": "Komi", "nativeName": "коми кыв" }, "kw": { "name": "Cornish", "nativeName": "Kernewek" }, "ky": { "name": "Kyrgyz", "nativeName": "Кыргызча" }, "la": { "name": "Latin", "nativeName": "latine" }, "lb": { "name": "Luxembourgish", "nativeName": "Lëtzebuergesch" }, "lg": { "name": "Ganda", "nativeName": "Luganda" }, "li": { "name": "Limburgish", "nativeName": "Limburgs" }, "ln": { "name": "Lingala", "nativeName": "Lingála" }, "lo": { "name": "Lao", "nativeName": "ພາສາ" }, "lt": { "name": "Lithuanian", "nativeName": "lietuvių kalba" }, "lu": { "name": "Luba-Katanga", "nativeName": "Tshiluba" }, "lv": { "name": "Latvian", "nativeName": "latviešu valoda" }, "mg": { "name": "Malagasy", "nativeName": "fiteny malagasy" }, "mh": { "name": "Marshallese", "nativeName": "Kajin M̧ajeļ" }, "mi": { "name": "Māori", "nativeName": "te reo Māori" }, "mk": { "name": "Macedonian", "nativeName": "македонски јазик" }, "ml": { "name": "Malayalam", "nativeName": "മലയാളം" }, "mn": { "name": "Mongolian", "nativeName": "Монгол хэл" }, "mr": { "name": "Marathi", "nativeName": "मराठी" }, "ms": { "name": "Malay", "nativeName": "Bahasa Malaysia" }, "mt": { "name": "Maltese", "nativeName": "Malti" }, "my": { "name": "Burmese", "nativeName": "ဗမာစာ" }, "na": { "name": "Nauru", "nativeName": "Ekakairũ Naoero" }, "nb": { "name": "Norwegian Bokmål", "nativeName": "Norsk bokmål" }, "nd": { "name": "Northern Ndebele", "nativeName": "isiNdebele" }, "ne": { "name": "Nepali", "nativeName": "नेपाली" }, "ng": { "name": "Ndonga", "nativeName": "Owambo" }, "nl": { "name": "Dutch", "nativeName": "Nederlands" }, "nn": { "name": "Norwegian Nynorsk", "nativeName": "Norsk nynorsk" }, "no": { "name": "Norwegian", "nativeName": "Norsk" }, "nr": { "name": "Southern Ndebele", "nativeName": "isiNdebele" }, "nv": { "name": "Navajo", "nativeName": "Diné bizaad" }, "ny": { "name": "Chichewa", "nativeName": "chiCheŵa" }, "oc": { "name": "Occitan", "nativeName": "occitan" }, "oj": { "name": "Ojibwe", "nativeName": "ᐊᓂᔑᓈᐯᒧᐎᓐ" }, "om": { "name": "Oromo", "nativeName": "Afaan Oromoo" }, "or": { "name": "Oriya", "nativeName": "ଓଡ଼ିଆ" }, "os": { "name": "Ossetian", "nativeName": "ирон æвзаг" }, "pa": { "name": "Panjabi", "nativeName": "ਪੰਜਾਬੀ" }, "pi": { "name": "Pāli", "nativeName": "पाऴि" }, "pl": { "name": "Polish", "nativeName": "język polski" }, "ps": { "name": "Pashto", "nativeName": "پښتو" }, "pt": { "name": "Portuguese", "nativeName": "Português" }, "qu": { "name": "Quechua", "nativeName": "Runa Simi" }, "rm": { "name": "Romansh", "nativeName": "rumantsch grischun" }, "rn": { "name": "Kirundi", "nativeName": "Ikirundi" }, "ro": { "name": "Romanian", "nativeName": "Română" }, "ru": { "name": "Russian", "nativeName": "Русский" }, "rw": { "name": "Kinyarwanda", "nativeName": "Ikinyarwanda" }, "sa": { "name": "Sanskrit", "nativeName": "संस्कृतम्" }, "sc": { "name": "Sardinian", "nativeName": "sardu" }, "sd": { "name": "Sindhi", "nativeName": "सिन्धी" }, "se": { "name": "Northern Sami", "nativeName": "Davvisámegiella" }, "sg": { "name": "Sango", "nativeName": "yângâ tî sängö" }, "si": { "name": "Sinhala", "nativeName": "සිංහල" }, "sk": { "name": "Slovak", "nativeName": "slovenčina" }, "sl": { "name": "Slovenian", "nativeName": "slovenski jezik" }, "sm": { "name": "Samoan", "nativeName": "gagana fa'a Samoa" }, "sn": { "name": "Shona", "nativeName": "chiShona" }, "so": { "name": "Somali", "nativeName": "Soomaaliga" }, "sq": { "name": "Albanian", "nativeName": "Shqip" }, "sr": { "name": "Serbian", "nativeName": "српски језик" }, "ss": { "name": "Swati", "nativeName": "SiSwati" }, "st": { "name": "Southern Sotho", "nativeName": "Sesotho" }, "su": { "name": "Sundanese", "nativeName": "Basa Sunda" }, "sv": { "name": "Swedish", "nativeName": "Svenska" }, "sw": { "name": "Swahili", "nativeName": "Kiswahili" }, "ta": { "name": "Tamil", "nativeName": "தமிழ்" }, "te": { "name": "Telugu", "nativeName": "తెలుగు" }, "tg": { "name": "Tajik", "nativeName": "тоҷикӣ" }, "th": { "name": "Thai", "nativeName": "ไทย" }, "ti": { "name": "Tigrinya", "nativeName": "ትግርኛ" }, "tk": { "name": "Turkmen", "nativeName": "Türkmen" }, "tl": { "name": "Tagalog", "nativeName": "Wikang Tagalog" }, "tn": { "name": "Tswana", "nativeName": "Setswana" }, "to": { "name": "Tonga", "nativeName": "faka Tonga" }, "tr": { "name": "Turkish", "nativeName": "Türkçe" }, "ts": { "name": "Tsonga", "nativeName": "Xitsonga" }, "tt": { "name": "Tatar", "nativeName": "татар теле" }, "tw": { "name": "Twi", "nativeName": "Twi" }, "ty": { "name": "Tahitian", "nativeName": "Reo Tahiti" }, "ug": { "name": "Uyghur", "nativeName": "ئۇيغۇرچە‎" }, "uk": { "name": "Ukrainian", "nativeName": "Українська" }, "ur": { "name": "Urdu", "nativeName": "اردو" }, "uz": { "name": "Uzbek", "nativeName": "Ўзбек" }, "ve": { "name": "Venda", "nativeName": "Tshivenḓa" }, "vi": { "name": "Vietnamese", "nativeName": "Tiếng Việt" }, "vo": { "name": "Volapük", "nativeName": "Volapük" }, "wa": { "name": "Walloon", "nativeName": "walon" }, "wo": { "name": "Wolof", "nativeName": "Wollof" }, "xh": { "name": "Xhosa", "nativeName": "isiXhosa" }, "yi": { "name": "Yiddish", "nativeName": "ייִדיש" }, "yo": { "name": "Yoruba", "nativeName": "Yorùbá" }, "za": { "name": "Zhuang", "nativeName": "Saɯ cueŋƅ" }, "zh": { "name": "Chinese", "nativeName": "中文" }, "zu": { "name": "Zulu", "nativeName": "isiZulu" }, "ach": { "name": "Acoli" }, "bcl": { "name": "Central Bikol" }, "crs": { "name": "Seselwa Creole French" }, "gaa": { "name": "Ga" }, "guw": { "name": "Gun" }, "niu": { "name": "Niuean" }, "nso": { "name": "Pedi" }, "bzs": { "name": "Brazilian Sign Language" }, "efi": { "name": "Efik" }, "gil": { "name": "Gilbertese" }, "ilo": { "name": "Iloko" }, "iso": { "name": "Isoko" }, "lua": { "name": "Luba-Lulua" }, "pag": { "name": "Pangasinan" }, "pap": { "name": "Papiamento" }, "pis": { "name": "Pijin" }, "pon": { "name": "Pohnpeian" }, "ceb": { "name": "Cebuano" }, "loz": { "name": "Lozi" }, "lus": { "name": "Lushai" }, "swc": { "name": "Congo Swahili" }, "tll": { "name": "Tetela" }, "tvl": { "name": "Tuvalua" }, "ase": { "name": "American Sign Language" }, "bem": { "name": "Bemba" }, "hil": { "name": "Hiligaynon" }, "lue": { "name": "Luvale" }, "kqn": { "name": "Kaonde" }, "toi": { "name": "Tonga (Zambia)" }, "srn": { "name": "Sranan Tongo" }, "war": { "name": "Waray" }, "run": { "name": "Rundi" }, "tiv": { "name": "Tiv" }, "tpi": { "name": "Tok Pisin" }, "wls": { "name": "Wallisian" }, "zne": { "name": "Zande (individual language)" }, "ber": { "name": "Berber languages" }, "chk": { "name": "Chuukese" }, "kwy": { "name": "San Salvador Kongo" }, "mfe": { "name": "Morisyen" }, "rnd": { "name": "Ruund" }, "yap": { "name": "Yapese" }, "tum": { "name": "Tumbuka" }, "mos": { "name": "Mossi" }, "yue": { "name": "Yue Chinese" }, "umb": { "name": "Umbundu" }, "roa": { "name": "Romance languages" }, "aed": { "name": "Argentine Sign Language" }, "csg": { "name": "Chilean Sign Language" }, "csn": { "name": "Colombian Sign Language" }, "kwn": { "name": "Kwangali" }, "lun": { "name": "Lunda" }, "luo": { "name": "Luo" }, "nyk": { "name": "Nyaneka" }, "mfs": { "name": "Mexican Sign Language" }, "prl": { "name": "Peruvian Sign Language" }, "tzo": { "name": "Tzotzil" }, "zai": { "name": "Isthmus Zapotec" }, "fse": { "name": "Finnish Sign Language" }, "cel": { "name": "Celtic languages" }, "tdt": { "name": "Tetun Dili" }, "yua": { "name": "Yucateco" }, "kab": { "name": "Kabyle" }, "ssp": { "name": "Spanish Sign Language" }, "vsl": { "name": "Venezuelan Sign Language" }, "wal": { "name": "Wolaitta" }, "fon": { "name": "Fon" } }; export class Language { code: string; name: string; nativeName?: string; /** * Hydrated */ numModels?: number; numDatasets?: number; constructor(o: any) { return Object.assign(this, o); } /** * Works with all different parts of ISO 639. */ get wikiLink() { return `https://en.wikipedia.org/wiki/ISO_639:${this.code}`; } /** * List of languages used in huggingface.co/languages */ static all(): Map<string, Language> { const all = new Map<string, Language>(); for (const [code, v] of Object.entries(LANGUAGES)) { all.set( code, new Language({ code, ...v }) ); } return all; } }
the_stack
import { Node, Identifier, BlockStatement, CallExpression, ObjectPattern, ArrayPattern, Program, VariableDeclarator, Expression } from '@babel/types' import MagicString, { SourceMap } from 'magic-string' import { walk } from 'estree-walker' import { extractIdentifiers, isFunctionType, isInDestructureAssignment, isReferencedIdentifier, isStaticProperty, walkFunctionParams } from '@vue/compiler-core' import { parse, ParserPlugin } from '@babel/parser' import { hasOwn, isArray, isString } from '@vue/shared' const CONVERT_SYMBOL = '$' const ESCAPE_SYMBOL = '$$' const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'] const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/ export function shouldTransform(src: string): boolean { return transformCheckRE.test(src) } type Scope = Record<string, boolean | 'prop'> export interface RefTransformOptions { filename?: string sourceMap?: boolean parserPlugins?: ParserPlugin[] importHelpersFrom?: string } export interface RefTransformResults { code: string map: SourceMap | null rootRefs: string[] importedHelpers: string[] } export function transform( src: string, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' }: RefTransformOptions = {} ): RefTransformResults { const plugins: ParserPlugin[] = parserPlugins || [] if (filename) { if (/\.tsx?$/.test(filename)) { plugins.push('typescript') } if (filename.endsWith('x')) { plugins.push('jsx') } } const ast = parse(src, { sourceType: 'module', plugins }) const s = new MagicString(src) const res = transformAST(ast.program, s, 0) // inject helper imports if (res.importedHelpers.length) { s.prepend( `import { ${res.importedHelpers .map(h => `${h} as _${h}`) .join(', ')} } from '${importHelpersFrom}'\n` ) } return { ...res, code: s.toString(), map: sourceMap ? s.generateMap({ source: filename, hires: true, includeContent: true }) : null } } export function transformAST( ast: Program, s: MagicString, offset = 0, knownRefs?: string[], knownProps?: Record< string, // public prop key { local: string // local identifier, may be different default?: any } > ): { rootRefs: string[] importedHelpers: string[] } { // TODO remove when out of experimental warnExperimental() let convertSymbol = CONVERT_SYMBOL let escapeSymbol = ESCAPE_SYMBOL // macro import handling for (const node of ast.body) { if ( node.type === 'ImportDeclaration' && node.source.value === 'vue/macros' ) { // remove macro imports s.remove(node.start! + offset, node.end! + offset) // check aliasing for (const specifier of node.specifiers) { if (specifier.type === 'ImportSpecifier') { const imported = (specifier.imported as Identifier).name const local = specifier.local.name if (local !== imported) { if (imported === ESCAPE_SYMBOL) { escapeSymbol = local } else if (imported === CONVERT_SYMBOL) { convertSymbol = local } else { error( `macro imports for ref-creating methods do not support aliasing.`, specifier ) } } } } } } const importedHelpers = new Set<string>() const rootScope: Scope = {} const scopeStack: Scope[] = [rootScope] let currentScope: Scope = rootScope let escapeScope: CallExpression | undefined // inside $$() const excludedIds = new WeakSet<Identifier>() const parentStack: Node[] = [] const propsLocalToPublicMap = Object.create(null) if (knownRefs) { for (const key of knownRefs) { rootScope[key] = true } } if (knownProps) { for (const key in knownProps) { const { local } = knownProps[key] rootScope[local] = 'prop' propsLocalToPublicMap[local] = key } } function isRefCreationCall(callee: string): string | false { if (callee === convertSymbol) { return convertSymbol } if (callee[0] === '$' && shorthands.includes(callee.slice(1))) { return callee } return false } function error(msg: string, node: Node) { const e = new Error(msg) ;(e as any).node = node throw e } function helper(msg: string) { importedHelpers.add(msg) return `_${msg}` } function registerBinding(id: Identifier, isRef = false) { excludedIds.add(id) if (currentScope) { currentScope[id.name] = isRef } else { error( 'registerBinding called without active scope, something is wrong.', id ) } } const registerRefBinding = (id: Identifier) => registerBinding(id, true) let tempVarCount = 0 function genTempVar() { return `__$temp_${++tempVarCount}` } function snip(node: Node) { return s.original.slice(node.start! + offset, node.end! + offset) } function walkScope(node: Program | BlockStatement, isRoot = false) { for (const stmt of node.body) { if (stmt.type === 'VariableDeclaration') { if (stmt.declare) continue for (const decl of stmt.declarations) { let refCall const isCall = decl.init && decl.init.type === 'CallExpression' && decl.init.callee.type === 'Identifier' if ( isCall && (refCall = isRefCreationCall((decl as any).init.callee.name)) ) { processRefDeclaration(refCall, decl.id, decl.init as CallExpression) } else { const isProps = isRoot && isCall && (decl as any).init.callee.name === 'defineProps' for (const id of extractIdentifiers(decl.id)) { if (isProps) { // for defineProps destructure, only exclude them since they // are already passed in as knownProps excludedIds.add(id) } else { registerBinding(id) } } } } } else if ( stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' ) { if (stmt.declare || !stmt.id) continue registerBinding(stmt.id) } } } function processRefDeclaration( method: string, id: VariableDeclarator['id'], call: CallExpression ) { excludedIds.add(call.callee as Identifier) if (method === convertSymbol) { // $ // remove macro s.remove(call.callee.start! + offset, call.callee.end! + offset) if (id.type === 'Identifier') { // single variable registerRefBinding(id) } else if (id.type === 'ObjectPattern') { processRefObjectPattern(id, call) } else if (id.type === 'ArrayPattern') { processRefArrayPattern(id, call) } } else { // shorthands if (id.type === 'Identifier') { registerRefBinding(id) // replace call s.overwrite( call.start! + offset, call.start! + method.length + offset, helper(method.slice(1)) ) } else { error(`${method}() cannot be used with destructure patterns.`, call) } } } function processRefObjectPattern( pattern: ObjectPattern, call: CallExpression, tempVar?: string, path: PathSegment[] = [] ) { if (!tempVar) { tempVar = genTempVar() // const { x } = $(useFoo()) --> const __$temp_1 = useFoo() s.overwrite(pattern.start! + offset, pattern.end! + offset, tempVar) } for (const p of pattern.properties) { let nameId: Identifier | undefined let key: Expression | string | undefined let defaultValue: Expression | undefined if (p.type === 'ObjectProperty') { if (p.key.start! === p.value.start!) { // shorthand { foo } nameId = p.key as Identifier if (p.value.type === 'Identifier') { // avoid shorthand value identifier from being processed excludedIds.add(p.value) } else if ( p.value.type === 'AssignmentPattern' && p.value.left.type === 'Identifier' ) { // { foo = 1 } excludedIds.add(p.value.left) defaultValue = p.value.right } } else { key = p.computed ? p.key : (p.key as Identifier).name if (p.value.type === 'Identifier') { // { foo: bar } nameId = p.value } else if (p.value.type === 'ObjectPattern') { processRefObjectPattern(p.value, call, tempVar, [...path, key]) } else if (p.value.type === 'ArrayPattern') { processRefArrayPattern(p.value, call, tempVar, [...path, key]) } else if (p.value.type === 'AssignmentPattern') { if (p.value.left.type === 'Identifier') { // { foo: bar = 1 } nameId = p.value.left defaultValue = p.value.right } else if (p.value.left.type === 'ObjectPattern') { processRefObjectPattern(p.value.left, call, tempVar, [ ...path, [key, p.value.right] ]) } else if (p.value.left.type === 'ArrayPattern') { processRefArrayPattern(p.value.left, call, tempVar, [ ...path, [key, p.value.right] ]) } else { // MemberExpression case is not possible here, ignore } } } } else { // rest element { ...foo } error(`reactivity destructure does not support rest elements.`, p) } if (nameId) { registerRefBinding(nameId) // inject toRef() after original replaced pattern const source = pathToString(tempVar, path) const keyStr = isString(key) ? `'${key}'` : key ? snip(key) : `'${nameId.name}'` const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : `` s.appendLeft( call.end! + offset, `,\n ${nameId.name} = ${helper( 'toRef' )}(${source}, ${keyStr}${defaultStr})` ) } } } function processRefArrayPattern( pattern: ArrayPattern, call: CallExpression, tempVar?: string, path: PathSegment[] = [] ) { if (!tempVar) { // const [x] = $(useFoo()) --> const __$temp_1 = useFoo() tempVar = genTempVar() s.overwrite(pattern.start! + offset, pattern.end! + offset, tempVar) } for (let i = 0; i < pattern.elements.length; i++) { const e = pattern.elements[i] if (!e) continue let nameId: Identifier | undefined let defaultValue: Expression | undefined if (e.type === 'Identifier') { // [a] --> [__a] nameId = e } else if (e.type === 'AssignmentPattern') { // [a = 1] nameId = e.left as Identifier defaultValue = e.right } else if (e.type === 'RestElement') { // [...a] error(`reactivity destructure does not support rest elements.`, e) } else if (e.type === 'ObjectPattern') { processRefObjectPattern(e, call, tempVar, [...path, i]) } else if (e.type === 'ArrayPattern') { processRefArrayPattern(e, call, tempVar, [...path, i]) } if (nameId) { registerRefBinding(nameId) // inject toRef() after original replaced pattern const source = pathToString(tempVar, path) const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : `` s.appendLeft( call.end! + offset, `,\n ${nameId.name} = ${helper( 'toRef' )}(${source}, ${i}${defaultStr})` ) } } } type PathSegmentAtom = Expression | string | number type PathSegment = | PathSegmentAtom | [PathSegmentAtom, Expression /* default value */] function pathToString(source: string, path: PathSegment[]): string { if (path.length) { for (const seg of path) { if (isArray(seg)) { source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})` } else { source += segToString(seg) } } } return source } function segToString(seg: PathSegmentAtom): string { if (typeof seg === 'number') { return `[${seg}]` } else if (typeof seg === 'string') { return `.${seg}` } else { return snip(seg) } } function rewriteId( scope: Scope, id: Identifier, parent: Node, parentStack: Node[] ): boolean { if (hasOwn(scope, id.name)) { const bindingType = scope[id.name] if (bindingType) { const isProp = bindingType === 'prop' if (isStaticProperty(parent) && parent.shorthand) { // let binding used in a property shorthand // skip for destructure patterns if ( !(parent as any).inPattern || isInDestructureAssignment(parent, parentStack) ) { if (isProp) { if (escapeScope) { // prop binding in $$() // { prop } -> { prop: __prop_prop } registerEscapedPropBinding(id) s.appendLeft( id.end! + offset, `: __props_${propsLocalToPublicMap[id.name]}` ) } else { // { prop } -> { prop: __prop.prop } s.appendLeft( id.end! + offset, `: __props.${propsLocalToPublicMap[id.name]}` ) } } else { // { foo } -> { foo: foo.value } s.appendLeft(id.end! + offset, `: ${id.name}.value`) } } } else { if (isProp) { if (escapeScope) { // x --> __props_x registerEscapedPropBinding(id) s.overwrite( id.start! + offset, id.end! + offset, `__props_${propsLocalToPublicMap[id.name]}` ) } else { // x --> __props.x s.overwrite( id.start! + offset, id.end! + offset, `__props.${propsLocalToPublicMap[id.name]}` ) } } else { // x --> x.value s.appendLeft(id.end! + offset, '.value') } } } return true } return false } const propBindingRefs: Record<string, true> = {} function registerEscapedPropBinding(id: Identifier) { if (!propBindingRefs.hasOwnProperty(id.name)) { propBindingRefs[id.name] = true const publicKey = propsLocalToPublicMap[id.name] s.prependRight( offset, `const __props_${publicKey} = ${helper( `toRef` )}(__props, '${publicKey}')\n` ) } } // check root scope first walkScope(ast, true) ;(walk as any)(ast, { enter(node: Node, parent?: Node) { parent && parentStack.push(parent) // function scopes if (isFunctionType(node)) { scopeStack.push((currentScope = {})) walkFunctionParams(node, registerBinding) if (node.body.type === 'BlockStatement') { walkScope(node.body) } return } // non-function block scopes if (node.type === 'BlockStatement' && !isFunctionType(parent!)) { scopeStack.push((currentScope = {})) walkScope(node) return } if ( parent && parent.type.startsWith('TS') && parent.type !== 'TSAsExpression' && parent.type !== 'TSNonNullExpression' && parent.type !== 'TSTypeAssertion' ) { return this.skip() } if ( node.type === 'Identifier' && // if inside $$(), skip unless this is a destructured prop binding !(escapeScope && rootScope[node.name] !== 'prop') && isReferencedIdentifier(node, parent!, parentStack) && !excludedIds.has(node) ) { // walk up the scope chain to check if id should be appended .value let i = scopeStack.length while (i--) { if (rewriteId(scopeStack[i], node, parent!, parentStack)) { return } } } if (node.type === 'CallExpression' && node.callee.type === 'Identifier') { const callee = node.callee.name const refCall = isRefCreationCall(callee) if (refCall && (!parent || parent.type !== 'VariableDeclarator')) { return error( `${refCall} can only be used as the initializer of ` + `a variable declaration.`, node ) } if (callee === escapeSymbol) { s.remove(node.callee.start! + offset, node.callee.end! + offset) escapeScope = node } // TODO remove when out of experimental if (callee === '$raw') { error( `$raw() has been replaced by $$(). ` + `See ${RFC_LINK} for latest updates.`, node ) } if (callee === '$fromRef') { error( `$fromRef() has been replaced by $(). ` + `See ${RFC_LINK} for latest updates.`, node ) } } }, leave(node: Node, parent?: Node) { parent && parentStack.pop() if ( (node.type === 'BlockStatement' && !isFunctionType(parent!)) || isFunctionType(node) ) { scopeStack.pop() currentScope = scopeStack[scopeStack.length - 1] || null } if (node === escapeScope) { escapeScope = undefined } } }) return { rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true), importedHelpers: [...importedHelpers] } } const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369` const hasWarned: Record<string, boolean> = {} function warnExperimental() { // eslint-disable-next-line if (typeof window !== 'undefined') { return } warnOnce( `Reactivity transform is an experimental feature.\n` + `Experimental features may change behavior between patch versions.\n` + `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` + `You can follow the proposal's status at ${RFC_LINK}.` ) } function warnOnce(msg: string) { const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production' if (!isNodeProd && !__TEST__ && !hasWarned[msg]) { hasWarned[msg] = true warn(msg) } } function warn(msg: string) { console.warn( `\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n` ) }
the_stack
import Vue from 'vue' import VueRouter, { RouteConfig } from 'vue-router' /* Layout */ import Layout from '@/layout/index.vue' /* Router modules */ import componentsRouter from './modules/components' import chartsRouter from './modules/charts' import tableRouter from './modules/table' import nestedRouter from './modules/nested' Vue.use(VueRouter) /* Note: sub-menu only appear when children.length>=1 Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html */ /* name:'router-name' the name field is required when using <keep-alive>, it should also match its component's name property detail see : https://vuejs.org/v2/guide/components-dynamic-async.html#keep-alive-with-Dynamic-Components redirect: if set to 'noredirect', no redirect action will be trigger when clicking the breadcrumb meta: { roles: ['admin', 'editor'] will control the page roles (allow setting multiple roles) title: 'title' the name showed in subMenu and breadcrumb (recommend set) icon: 'svg-name' the icon showed in the sidebar hidden: true if true, this route will not show in the sidebar (default is false) alwaysShow: true if true, will always show the root menu (default is false) if false, hide the root menu when has less or equal than one children route breadcrumb: false if false, the item will be hidden in breadcrumb (default is true) noCache: true if true, the page will not be cached (default is false) affix: true if true, the tag will affix in the tags-view activeMenu: '/example/list' if set path, the sidebar will highlight the path you set } */ /** ConstantRoutes a base page that does not have permission requirements all roles can be accessed */ export const constantRoutes: RouteConfig[] = [ { path: '/redirect', component: Layout, meta: { hidden: true }, children: [ { path: '/redirect/:path(.*)', component: () => import(/* webpackChunkName: "redirect" */ '@/views/redirect/index.vue') } ] }, { path: '/login', component: () => import(/* webpackChunkName: "login" */ '@/views/login/index.vue'), meta: { hidden: true } }, { path: '/auth-redirect', component: () => import(/* webpackChunkName: "auth-redirect" */ '@/views/login/auth-redirect.vue'), meta: { hidden: true } }, { path: '/404', component: () => import(/* webpackChunkName: "404" */ '@/views/error-page/404.vue'), meta: { hidden: true } }, { path: '/401', component: () => import(/* webpackChunkName: "401" */ '@/views/error-page/401.vue'), meta: { hidden: true } }, { path: '/', component: Layout, redirect: '/dashboard', children: [ { path: 'dashboard', component: () => import(/* webpackChunkName: "dashboard" */ '@/views/dashboard/index.vue'), name: 'Dashboard', meta: { title: 'dashboard', icon: 'dashboard', affix: true } } ] }, // { // path: '/documentation', // component: Layout, // children: [ // { // path: 'index', // component: () => import(/* webpackChunkName: "documentation" */ '@/views/documentation/index.vue'), // name: 'Documentation', // meta: { title: 'documentation', icon: 'documentation', affix: true } // } // ] // }, { path: '/guide', component: Layout, redirect: '/guide/index', children: [ { path: 'index', component: () => import(/* webpackChunkName: "guide" */ '@/views/guide/index.vue'), name: 'Guide', meta: { title: 'guide', icon: 'guide', noCache: true } } ] }, { path: '/profile', component: Layout, redirect: '/profile/index', meta: { hidden: true }, children: [ { path: 'index', component: () => import(/* webpackChunkName: "profile" */ '@/views/profile/index.vue'), name: 'Profile', meta: { title: 'profile', icon: 'user', noCache: true } } ] } ] /** * asyncRoutes * the routes that need to be dynamically loaded based on user roles */ export const asyncRoutes: RouteConfig[] = [ { path: '/permission', component: Layout, redirect: '/permission/directive', meta: { title: 'permission', icon: 'lock', roles: ['admin', 'editor'], // you can set roles in root nav alwaysShow: true // will always show the root menu }, children: [ { path: 'page', component: () => import(/* webpackChunkName: "permission-page" */ '@/views/permission/page.vue'), name: 'PagePermission', meta: { title: 'pagePermission', roles: ['admin'] // or you can only set roles in sub nav } }, { path: 'directive', component: () => import(/* webpackChunkName: "permission-directive" */ '@/views/permission/directive.vue'), name: 'DirectivePermission', meta: { title: 'directivePermission' // if do not set roles, means: this page does not require permission } }, { path: 'role', component: () => import(/* webpackChunkName: "permission-role" */ '@/views/permission/role.vue'), name: 'RolePermission', meta: { title: 'rolePermission', roles: ['admin'] } } ] }, { path: '/icon', component: Layout, children: [ { path: 'index', component: () => import(/* webpackChunkName: "icons" */ '@/views/icons/index.vue'), name: 'Icons', meta: { title: 'icons', icon: 'icon', noCache: true } } ] }, /** when your routing map is too long, you can split it into small modules **/ componentsRouter, chartsRouter, nestedRouter, tableRouter, { path: '/example', component: Layout, redirect: '/example/list', meta: { title: 'example', icon: 'example' }, children: [ { path: 'create', component: () => import(/* webpackChunkName: "example-create" */ '@/views/example/create.vue'), name: 'CreateArticle', meta: { title: 'createArticle', icon: 'edit' } }, { path: 'edit/:id(\\d+)', component: () => import(/* webpackChunkName: "example-edit" */ '@/views/example/edit.vue'), name: 'EditArticle', meta: { title: 'editArticle', noCache: true, activeMenu: '/example/list', hidden: true } }, { path: 'list', component: () => import(/* webpackChunkName: "example-list" */ '@/views/example/list.vue'), name: 'ArticleList', meta: { title: 'articleList', icon: 'list' } } ] }, { path: '/tab', component: Layout, children: [ { path: 'index', component: () => import(/* webpackChunkName: "tab" */ '@/views/tab/index.vue'), name: 'Tab', meta: { title: 'tab', icon: 'tab' } } ] }, { path: '/error', component: Layout, redirect: 'noredirect', meta: { title: 'errorPages', icon: '404' }, children: [ { path: '401', component: () => import(/* webpackChunkName: "error-page-401" */ '@/views/error-page/401.vue'), name: 'Page401', meta: { title: 'page401', noCache: true } }, { path: '404', component: () => import(/* webpackChunkName: "error-page-404" */ '@/views/error-page/404.vue'), name: 'Page404', meta: { title: 'page404', noCache: true } } ] }, { path: '/error-log', component: Layout, redirect: 'noredirect', children: [ { path: 'log', component: () => import(/* webpackChunkName: "error-log" */ '@/views/error-log/index.vue'), name: 'ErrorLog', meta: { title: 'errorLog', icon: 'bug' } } ] }, { path: '/excel', component: Layout, redirect: '/excel/export-excel', meta: { title: 'excel', icon: 'excel' }, children: [ { path: 'export-excel', component: () => import(/* webpackChunkName: "export-excel" */ '@/views/excel/export-excel.vue'), name: 'ExportExcel', meta: { title: 'exportExcel' } }, { path: 'export-selected-excel', component: () => import(/* webpackChunkName: "select-excel" */ '@/views/excel/select-excel.vue'), name: 'SelectExcel', meta: { title: 'selectExcel' } }, { path: 'export-merge-header', component: () => import(/* webpackChunkName: "merge-header" */ '@/views/excel/merge-header.vue'), name: 'MergeHeader', meta: { title: 'mergeHeader' } }, { path: 'upload-excel', component: () => import(/* webpackChunkName: "upload-excel" */ '@/views/excel/upload-excel.vue'), name: 'UploadExcel', meta: { title: 'uploadExcel' } } ] }, { path: '/zip', component: Layout, redirect: '/zip/download', meta: { title: 'zip', icon: 'zip', alwaysShow: true // will always show the root menu }, children: [ { path: 'download', component: () => import(/* webpackChunkName: "zip" */ '@/views/zip/index.vue'), name: 'ExportZip', meta: { title: 'exportZip' } } ] }, { path: '/pdf', component: Layout, redirect: '/pdf/index', children: [ { path: 'index', component: () => import(/* webpackChunkName: "pdf" */ '@/views/pdf/index.vue'), name: 'PDF', meta: { title: 'pdf', icon: 'pdf' } } ] }, { path: '/pdf-download-example', component: () => import(/* webpackChunkName: "pdf-download-example" */ '@/views/pdf/download.vue'), meta: { hidden: true } }, { path: '/theme', component: Layout, redirect: 'noredirect', children: [ { path: 'index', component: () => import(/* webpackChunkName: "theme" */ '@/views/theme/index.vue'), name: 'Theme', meta: { title: 'theme', icon: 'theme' } } ] }, { path: '/clipboard', component: Layout, redirect: 'noredirect', children: [ { path: 'index', component: () => import(/* webpackChunkName: "clipboard" */ '@/views/clipboard/index.vue'), name: 'Clipboard', meta: { title: 'clipboard', icon: 'clipboard' } } ] }, { path: '/i18n', component: Layout, children: [ { path: 'index', component: () => import(/* webpackChunkName: "i18n-demo" */ '@/views/i18n-demo/index.vue'), name: 'I18n', meta: { title: 'i18n', icon: 'international' } } ] }, { path: 'https://github.com/Armour/vue-typescript-admin-template', meta: { title: 'externalLink', icon: 'link' } }, { path: '*', redirect: '/404', meta: { hidden: true } } ] const createRouter = () => new VueRouter({ // mode: 'history', // Disabled due to Github Pages doesn't support this, enable this if you need. scrollBehavior: (to, from, savedPosition) => { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }, base: process.env.BASE_URL, routes: constantRoutes }) const router = createRouter() // Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465 export function resetRouter() { const newRouter = createRouter(); (router as any).matcher = (newRouter as any).matcher // reset router } export default router
the_stack
import {GoldenSun} from "./GoldenSun"; /** GBA buttons */ export enum AdvanceButton { A, B, L, R, START, SELECT, LEFT, RIGHT, UP, DOWN, } /** GBA button list, for mapping */ const AdvanceButtons = ["A", "B", "L", "R", "START", "SELECT", "LEFT", "RIGHT", "UP", "DOWN"]; /** Other hardware controller buttons */ export enum ControllerButton { LB = AdvanceButton.L, RB = AdvanceButton.R, X = AdvanceButton.DOWN + 1, Y, LS, RS, L2, R2, LT = ControllerButton.L2, RT = ControllerButton.R2, // LX, LY, RX, RY, LLEFT, LRIGHT, LUP, LDOWN, RLEFT, RRIGHT, RUP, RDOWN, } /** Other hardware controller buttons, for mapping */ const ControllerButtons = [ "LB", "RB", "X", "Y", "LS", "RS", // "L2", "R2", "LT", "RT", // "LX", "LY", "RX", "RY", "LLEFT", "LRIGHT", "LUP", "LDOWN", "RLEFT", "RRIGHT", "RUP", "RDOWN", ]; /** Custom engine buttons */ export enum EngineButton { STICK_DASHING = ControllerButton.RDOWN + 1, PSY1, PSY2, PSY3, PSY4, ZOOM1, ZOOM2, ZOOM3, MUTE, VOL_UP, VOL_DOWN, DEBUG_PHYSICS, DEBUG_GRID, DEBUG_KEYS, DEBUG_STATS, DEBUG_FPS, DEBUG_SLIDERS, DEBUG_CAM_MINUS, DEBUG_CAM_PLUS, } /** Custom engine button list, for mapping */ const EngineButtons = [ "STICK_DASHING", "PSY1", "PSY2", "PSY3", "PSY4", "ZOOM1", "ZOOM2", "ZOOM3", "MUTE", "VOL_UP", "VOL_DOWN", "DEBUG_PHYSICS", "DEBUG_GRID", "DEBUG_KEYS", "DEBUG_STATS", "DEBUG_FPS", "DEBUG_SLIDERS", "DEBUG_CAM_MINUS", "DEBUG_CAM_PLUS", ]; // export type Button = AdvanceButton | EngineButton; // export type Button = typeof AdvanceButton & typeof EngineButton; // export type Button = typeof Button; /** Enum regrouping GBA and engine buttons */ export const Button = {...EngineButton, ...AdvanceButton}; /** Any buttons recognized by the engine */ export type Button = AdvanceButton | EngineButton; /** A real controller or an engine button */ export type AnyButton = Button | ControllerButton; /** Used to map a real button/key to an emulated controller */ type KeyMap = { /** Game button */ game_button: AnyButton; /** Game button group that triggers the game button */ game_buttons?: AnyButton[]; /** For multi-button name chaining (reflect) */ name?: string; /** For multi-buttons, raw button combinaison */ as?: string; /** Button code of the controller button that triggers the game button */ button_code?: number; /** Button codes of the controller buttons that trigger the game button, should match {@link KeyMap#game_buttons} */ button_codes?: number[]; /** Keycode of the keyboard key that triggers the game button */ key_code?: number; /** Modifiers needed along the {@link KeyMap#key_code} */ key_modifiers?: {alt?: boolean; ctrl?: boolean; shift?: boolean}; }; export class GamepadButton { /** Emulated gamepad controller */ gamepad: Gamepad; /** Game button that will trigger */ button: AnyButton; /** Debug purpose */ name: string = undefined; /** Whether the gamepad button is held down */ is_down: boolean = false; /** Signal to trigger when that button is pressed */ on_down = new Phaser.Signal(); /** Signal to trigger when that button is release */ on_up = new Phaser.Signal(); constructor(gamepad: Gamepad, button: AnyButton) { this.gamepad = gamepad; this.button = button; this.name = Button[this.button] ?? ControllerButton[this.button]; } /** Whether the gamepad button is up */ get is_up() { return !this.is_down; } set is_up(v: boolean) { this.is_down = !v; } } /** * An emulated gamepad. */ export class Gamepad { /** Controller gamepad buttons configuration */ static gamepad_mapping: KeyMap[]; /** Controller gamepad sticks configuration */ static gamepad_stick_mapping: KeyMap[]; /** Keyboard gamepad keys configuration */ static keyboard_mapping: KeyMap[]; /** * Loads the gamepad and keyboard configuration. * @param {GoldenSun} data - Master game data object * @param {string} [input_type=default_inputs] - Keyboard key mapping configuration name */ static initialize(data: GoldenSun, input_type: string = "default_inputs") { // Load default gamepad buttons configuration const gamepad_mapping = Object.entries(data.dbs.init_db.gamepad_rinputs as {[code: string]: string}).map( ([button_code, game_button]): KeyMap => ({ name: game_button, game_button: Button[game_button] ?? ControllerButton[game_button], button_code: Phaser.Gamepad[button_code], }) ); // Load custom gamepad buttons configuration const gamepad_custom_mapping = Object.entries(data.dbs.init_db.gamepad_inputs as {[code: string]: string}).map( ([game_button, button_code]): KeyMap => { const matches = button_code.match(/^(?:(?:(\w+) *\+ *)?(\w+) *\+ *)?(\w+)$/); if (!matches) console.error("Input not recognized " + button_code); const get_button_code = (code: string): number => gamepad_mapping.find(km => km.name === code)?.button_code ?? Phaser.Gamepad[code]; const get_game_button = (code: string): number => gamepad_mapping.find(km => km.name === code || km.button_code === Phaser.Gamepad[code]) ?.game_button; const km: KeyMap = {name: game_button, as: button_code, game_button: EngineButton[game_button]}; if (matches[matches.length - 2]) { const buttons = matches.filter((m, i) => i && m); km.button_codes = buttons.map(get_button_code).filter(bc => bc !== undefined); km.game_buttons = buttons.map(get_game_button).filter(bc => bc !== undefined); if (km.button_codes.length !== km.game_buttons.length) console.warn(`${button_code} not well recognized!`); } else km.button_code = get_button_code(matches[matches.length - 1]); return km; } ); // Load gamepad stick configuration const gamepad_stick_mapping = Object.entries( data.dbs.init_db.gamepad_rsticks as {[code: string]: [string, string]} ).map( ([button_code, game_buttons]): KeyMap => ({ game_button: null, game_buttons: game_buttons.map(gb => ControllerButton[gb]), button_code: Phaser.Gamepad[button_code], }) ); Gamepad.gamepad_stick_mapping = gamepad_stick_mapping; Gamepad.gamepad_mapping = gamepad_mapping.concat(gamepad_custom_mapping); // Load keyboard keys configuration Gamepad.keyboard_mapping = Object.entries(data.dbs.init_db[input_type] as {[code: string]: string}).map( ([game_button, key_code]): KeyMap => { const matches = key_code.match( /^(?:(?:(?:(ALT|CTRL|SHIFT) *\+ *)?(ALT|CTRL|SHIFT) *\+ *)?(ALT|CTRL|SHIFT) *\+ *)?(\w+)$/ ); if (!matches) console.error("Input not recognized " + key_code); const km: KeyMap = { name: game_button, as: key_code, game_button: Button[game_button], key_code: Phaser.Keyboard[matches[matches.length - 1]], }; if (matches[matches.length - 2]) { const modifiers = matches.filter((m, i) => i && m); km.key_modifiers = {}; if (modifiers.includes("ALT")) km.key_modifiers.alt = true; if (modifiers.includes("CTRL")) km.key_modifiers.ctrl = true; if (modifiers.includes("SHIFT")) km.key_modifiers.shift = true; } return km; } ); } /** * Gets the GBA button(s) attached to the controller button. * @param {number} button_code - Controller button code. * @return {AnyButton[]} - GBA (custom) button(s) */ static transcode_gamepad_button(button_code: number): AnyButton[] { // return Gamepad.keyboard_mapping.find(km => km.button_code === button_code)?.game_button; return Gamepad.gamepad_mapping.filter(km => km.button_code === button_code).map(km => km.game_button); } /** * Gets the GBA button(s) attached to the Phaser keyboard key. * @param {number} key_code - Phaser keyboard key code. * @return {AnyButton[]} - GBA (custom) button(s) */ static transcode_keyboard_key(key_code: number): AnyButton[] { // Use a single array Gamepad.keyboard_fast_mapping[key_code]? return Gamepad.keyboard_mapping.filter(km => km.key_code === key_code).map(km => km.game_button); } /** * Gets the oppposite button. * @param {Button} game_button - GBA button * @return {?Button} - Opposite GBA button */ static get_opposite_button(game_button: Button): Button { switch (game_button) { // Advance buttons case Button.LEFT: return Button.RIGHT; case Button.RIGHT: return Button.LEFT; case Button.UP: return Button.DOWN; case Button.DOWN: return Button.UP; case Button.L: return Button.R; case Button.R: return Button.L; // Engine buttons case Button.VOL_UP: return Button.VOL_DOWN; case Button.VOL_DOWN: return Button.VOL_UP; default: return null; } } /** Every game buttons of the emulated gamepad */ buttons: {[button in AnyButton]?: GamepadButton} = []; /** The stick dead zone */ stick_dead_zone: number; /** The trigger dead zone */ trigger_dead_zone: number; /** Whether the last button pressed comes from the keybord or the controller */ is_last_input_gamepad: boolean; /** * @param {GoldenSun} data - Master game data object */ constructor(data: GoldenSun) { Gamepad.initialize(data, navigator.language === "fr-FR" ? "azerty_inputs" : "default_inputs"); this.register_handle_events(data.game); // Create a state for every buttons AdvanceButtons.forEach(button_name => { this.buttons[Button[button_name]] = new GamepadButton(this, Button[button_name]); }); ControllerButtons.forEach(button_name => { this.buttons[ControllerButton[button_name]] = new GamepadButton(this, ControllerButton[button_name]); }); EngineButtons.filter(bn => bn).forEach(button_name => { this.buttons[EngineButton[button_name]] = new GamepadButton(this, EngineButton[button_name]); }); /** Triggers another button along a specific button */ const mirror_button = (button: ControllerButton, to: AdvanceButton) => { this.buttons[button].on_down.add(() => this.on_gamepad_down(to)); this.buttons[button].on_up.add(() => this.on_gamepad_up(to)); }; if (data.dbs.init_db.gamepad?.use_trigger_as_button === true) { mirror_button(ControllerButton.LT, Button.L); mirror_button(ControllerButton.RT, Button.R); } if (data.dbs.init_db.gamepad?.left_stick_as_dpad === true) { mirror_button(ControllerButton.LLEFT, Button.LEFT); mirror_button(ControllerButton.LRIGHT, Button.RIGHT); mirror_button(ControllerButton.LUP, Button.UP); mirror_button(ControllerButton.LDOWN, Button.DOWN); } if (data.dbs.init_db.gamepad?.right_stick_as_dpad === true) { mirror_button(ControllerButton.RLEFT, Button.LEFT); mirror_button(ControllerButton.RRIGHT, Button.RIGHT); mirror_button(ControllerButton.RUP, Button.UP); mirror_button(ControllerButton.RDOWN, Button.DOWN); } this.stick_dead_zone = data.dbs.init_db.gamepad?.stick_dead_zone ?? 0.5; this.trigger_dead_zone = data.dbs.init_db.gamepad?.trigger_dead_zone ?? 0.6; this.is_last_input_gamepad = false; } /** * Press the game button if it is up then triggers the listeners. * @param {AnyButton} game_button - The game button to press * @param {?KeyboardEvent} event - The keyboard event if any */ private _on_down(game_button: AnyButton, event?: KeyboardEvent): GamepadButton { const btn = this.buttons[game_button]; if (btn.is_down) return; btn.is_down = true; btn.on_down.dispatch(event); return btn; } /** * Releases the game button if it is held down then triggers the listeners. * @param {AnyButton} game_button - The game button to release * @param {?KeyboardEvent} event - The keyboard event if any */ private _on_up(game_button: AnyButton, event?: KeyboardEvent): GamepadButton { const btn = this.buttons[game_button]; if (btn.is_up) return; btn.is_up = true; btn.on_up.dispatch(event); return btn; } /** * Press any multi-buttons involved if none the button itself. * @param {AnyButton} game_button - The game button getting pressed */ on_gamepad_down(game_button: AnyButton) { const group_game_buttons = Gamepad.gamepad_mapping.filter( km => km.game_button && // Check if it's the LAST button of any combo km.game_buttons?.[km.game_buttons.length - 1] === game_button && // Check if it's any button of any combo // km.game_buttons?.includes(game_button) && // Then if the others buttons are held down km.game_buttons.every(gb => gb === game_button || this.is_down(gb)) // .filter(gb => gb !== game_button) // .every(gb => this.is_down(gb)) ); if (group_game_buttons.length) return group_game_buttons.forEach(km => this._on_down(km.game_button)); this._on_down(game_button); } /** * Releases any multi-buttons involved and the button itself. * @param {AnyButton} game_button - The game button getting released */ on_gamepad_up(game_button: AnyButton) { const group_game_buttons = Gamepad.gamepad_mapping.filter( km => km.game_button && km.game_buttons?.includes(game_button) ); group_game_buttons.forEach(km => this._on_up(km.game_button)); this._on_up(game_button); } /** * Registers internal listeners on the gamepad and the keyboard to trigger emulated game button. * @param {Phaser.Game} game - Phaser game */ register_handle_events(game: Phaser.Game) { game.input.gamepad.start(); game.input.gamepad.onDownCallback = (button_code: number) => { this.is_last_input_gamepad = true; const game_buttons = Gamepad.transcode_gamepad_button(button_code); game_buttons.forEach(game_button => this.on_gamepad_down(game_button)); }; game.input.gamepad.onUpCallback = (button_code: number) => { this.is_last_input_gamepad = true; const game_buttons = Gamepad.transcode_gamepad_button(button_code); game_buttons.forEach(game_button => this.on_gamepad_up(game_button)); }; game.input.gamepad.onAxisCallback = (pad: Phaser.SinglePad, index: number, value: number) => { this.is_last_input_gamepad = true; const game_buttons = Gamepad.gamepad_stick_mapping.filter(km => km.button_code === index); game_buttons.forEach(km => { if (value < -this.stick_dead_zone) this.on_gamepad_down(km.game_buttons[0]); else if (value > this.stick_dead_zone) this.on_gamepad_down(km.game_buttons[1]); else { this.on_gamepad_up(km.game_buttons[0]); this.on_gamepad_up(km.game_buttons[1]); } }); }; game.input.gamepad.onFloatCallback = (button_code: number, value: number) => { this.is_last_input_gamepad = true; const game_buttons = Gamepad.transcode_gamepad_button(button_code); game_buttons.forEach(game_button => value > this.trigger_dead_zone ? this.on_gamepad_down(game_button) : this.on_gamepad_up(game_button) ); }; // Not using .onPressCallback since it triggers with a char, not a key game.input.keyboard.onDownCallback = (event: KeyboardEvent) => { this.is_last_input_gamepad = false; const game_buttons = Gamepad.keyboard_mapping .filter( km => km.key_code === event.keyCode && (km.key_modifiers?.alt != undefined ? km.key_modifiers.alt === event.altKey : true) && (km.key_modifiers?.ctrl != undefined ? km.key_modifiers.ctrl === event.ctrlKey : true) && (km.key_modifiers?.shift != undefined ? km.key_modifiers.shift === event.shiftKey : true) ) .map(km => km.game_button); game_buttons.forEach(game_button => this._on_down(game_button, event)); }; game.input.keyboard.onUpCallback = (event: KeyboardEvent) => { this.is_last_input_gamepad = true; const game_buttons = Gamepad.transcode_keyboard_key(event.keyCode); game_buttons.forEach(game_button => this._on_up(game_button, event)); }; } /** * Returns a gamepad button state with its signal attached. * @param {AnyButton} button - GBA (custom) button * @return {GamepadButton} - GBA button state */ get_button(button: AnyButton): GamepadButton { return this.buttons[button]; } /** * Checks if a gamepad button is currently down. * @param {AnyButton} button - GBA (custom) button * @return {boolean} - Whether the gamepad button is held down */ is_down(button: AnyButton): boolean { return this.buttons[button].is_down; } /** * Checks if a gamepad button is currently up. * @param {AnyButton} button - GBA (custom) button * @return {boolean} - Whether the gamepad button is up */ is_up(button: AnyButton): boolean { return this.buttons[button].is_up; } }
the_stack
import { $TSContext, JSONUtilities, pathManager, ResourceName, stateManager } from 'amplify-cli-core'; import { removeSecret, retainSecret, SecretDeltas, SecretName, setSecret } from 'amplify-function-plugin-interface'; import * as path from 'path'; import * as fs from 'fs-extra'; import { categoryName } from '../../../constants'; import { prePushMissingSecretsWalkthrough } from '../service-walkthroughs/secretValuesWalkthrough'; import { getFunctionCloudFormationTemplate, setFunctionCloudFormationTemplate } from '../utils/cloudformationHelpers'; import { functionParametersFileName, ServiceName } from '../utils/constants'; import { isFunctionPushed } from '../utils/funcionStateUtils'; import { createParametersFile } from '../utils/storeResources'; import { tryPrependSecretsUsageExample } from '../utils/updateTopLevelComment'; import { getExistingSecrets, hasExistingSecrets, secretNamesToSecretDeltas } from './secretDeltaUtilities'; import { getAppId, getEnvSecretPrefix, getFullyQualifiedSecretName, getFunctionSecretPrefix, secretsPathAmplifyAppIdKey, } from './secretName'; import { updateSecretsInCfnTemplate } from './secretsCfnModifier'; import { SSMClientWrapper } from './ssmClientWrapper'; import _ from 'lodash'; let secretsPendingRemoval: Record<ResourceName, SecretName[]> = {}; /** * Manages the state of function secrets in AWS ParameterStore as well as local state in the CFN template and function-parameters.json * * Note: Local and cloud removal are separate operations because a secret cannot be removed in the cloud before the push. * The expected way to handle this is: * 1. During CLI workflows, call syncSecretDeltas * 2. Before pushing, call storeSecretsPendingRemoval * 3. After the push completes, call syncSecretsPendingRemoval */ export class FunctionSecretsStateManager { private static instance: FunctionSecretsStateManager; static getInstance = async (context: $TSContext) => { if (!FunctionSecretsStateManager.instance) { FunctionSecretsStateManager.instance = new FunctionSecretsStateManager(context, await SSMClientWrapper.getInstance(context)); } return FunctionSecretsStateManager.instance; }; private constructor(private readonly context: $TSContext, private readonly ssmClientWrapper: SSMClientWrapper) {} /** * This is the main entry point to ensure secret state is in sync. * It will update deltas in SSM as well as make calls to update the CFN template and other local state. * * @param secretDeltas describes changes that should be made to the secrets state * @param functionName the function name to apply the delta * @param envName the environment name. If not specified, the current environment is assumed * @returns resolved promise when all updates are complete */ syncSecretDeltas = async (secretDeltas: SecretDeltas, functionName: string, envName?: string): Promise<void> => { if (!secretDeltas) { return; } // update values in Parameter Store await Promise.all( Object.entries(secretDeltas).map(async ([secretName, secretDelta]) => { const fullyQualifiedSecretName = getFullyQualifiedSecretName(secretName, functionName, envName); switch (secretDelta.operation) { case 'remove': if (this.doRemoveSecretsInCloud(functionName)) { await this.ssmClientWrapper.deleteSecret(fullyQualifiedSecretName); } break; case 'set': await this.ssmClientWrapper.setSecret(fullyQualifiedSecretName, secretDelta.value); } }), ); try { const origTemplate = await getFunctionCloudFormationTemplate(functionName); const newTemplate = await updateSecretsInCfnTemplate(origTemplate, secretDeltas, functionName); await setFunctionCloudFormationTemplate(functionName, newTemplate); } catch (err) { if (hasExistingSecrets(secretDeltas)) { throw err; } } await tryPrependSecretsUsageExample(functionName, Object.keys(getExistingSecrets(secretDeltas))); await setLocalFunctionSecretState(functionName, secretDeltas); }; /** * Checks that all locally defined secrets for the function are present in the cloud. If any are missing, it prompts for values */ ensureNewLocalSecretsSyncedToCloud = async (functionName: string) => { const localSecretNames = getLocalFunctionSecretNames(functionName); if (!localSecretNames.length) { return; } const cloudSecretNames = await this.getCloudFunctionSecretNames(functionName); const addedSecrets = localSecretNames.filter(name => !cloudSecretNames.includes(name)); if (!addedSecrets.length) { return; } if (!this.isInteractive()) { throw new Error( `The following secrets in ${functionName} do not have values: [${addedSecrets}]\nRun 'amplify push' interactively to specify values.`, ); } const delta = await prePushMissingSecretsWalkthrough(functionName, addedSecrets); await this.syncSecretDeltas(delta, functionName); }; /** * Deletes all secrets in the cloud for the specified function */ deleteAllFunctionSecrets = async (functionName: string) => { const cloudSecretNames = await this.getCloudFunctionSecretNames(functionName); await this.syncSecretDeltas(secretNamesToSecretDeltas(cloudSecretNames, removeSecret), functionName); }; /** * Syncs secretsPendingRemoval to the cloud. * * It is expected that storeSecretsPendingRemoval has been called before calling this function. If not, this function is a noop. */ syncSecretsPendingRemoval = async () => { await Promise.all( Object.entries(secretsPendingRemoval).map(([functionName, secretNames]) => this.syncSecretDeltas( { ...secretNamesToSecretDeltas(getLocalFunctionSecretNames(functionName)), ...secretNamesToSecretDeltas(secretNames, removeSecret), }, functionName, ), ), ); secretsPendingRemoval = {}; }; /** * Deletes all secrets under an environment prefix (/amplify/appId/envName/) * @param envName The environment to remove */ deleteAllEnvironmentSecrets = async (envName: string) => { const secretNames = await this.ssmClientWrapper.getSecretNamesByPath(getEnvSecretPrefix(envName)); await this.ssmClientWrapper.deleteSecrets(secretNames); }; /** * Returns a SecretDeltas object that can be used to clone the secrets from one environment to another * @param sourceEnv The environment from which to get secrets * @param functionName The function from which to get secrets * @returns SecretDeltas for the function in the environment */ getEnvCloneDeltas = async (sourceEnv: string, functionName: string) => { const destDelta = secretNamesToSecretDeltas(getLocalFunctionSecretNames(functionName), retainSecret); const sourceCloudSecretNames = await this.getCloudFunctionSecretNames(functionName, sourceEnv); const sourceCloudSecrets = await this.ssmClientWrapper.getSecrets( sourceCloudSecretNames.map(name => getFullyQualifiedSecretName(name, functionName, sourceEnv)), ); sourceCloudSecrets.reduce((acc, { secretName, secretValue }) => { const shortName = secretName.slice(getFunctionSecretPrefix(functionName, sourceEnv).length); acc[shortName] = setSecret(secretValue); return acc; }, destDelta); return destDelta; }; /** * Gets all secrets in SSM for the given function * @param functionName The function * @param envName Optional environment. If not specified, the current env is assumed * @returns string[] of all secret names for the function */ private getCloudFunctionSecretNames = async (functionName: string, envName?: string) => { const prefix = getFunctionSecretPrefix(functionName, envName); const parts = path.parse(prefix); const unfilteredSecrets = await this.ssmClientWrapper.getSecretNamesByPath(parts.dir); return unfilteredSecrets.filter(secretName => secretName.startsWith(prefix)).map(secretName => secretName.slice(prefix.length)); }; /** * Secrets should only be removed in the cloud if the function is not yet pushed, or if the CLI operation is 'push'. * This function performs this check. */ private doRemoveSecretsInCloud = (functionName: string): boolean => { const isCommandPush = this.context.parameters.command === 'push'; return !isFunctionPushed(functionName) || isCommandPush; }; private isInteractive = (): boolean => !this.context?.input?.options?.yes; } /** * It is expected that this function will be called before calling syncSecretsPendingRemoval. * * When a secret is removed, it must be removed after the corresponding CFN push is complete. * This function stores the secrets removed for any function in the project. * * Furthermore, functions that are removed must have all corresponding secrets removed after the push. However, once the push is complete, * the local project state has no way of knowing what functions were just removed or if they had secrets configured. * So this function also stores the secret names of all functions marked for removal * * @param context The Amplify context, used to determine which functions will be deleted * @param functionNames A list of all function names in the project */ export const storeSecretsPendingRemoval = async (context: $TSContext, functionNames: string[]) => { functionNames.forEach(functionName => { const cloudSecretNames = getLocalFunctionSecretNames(functionName, { fromCurrentCloudBackend: true }); const localSecretNames = getLocalFunctionSecretNames(functionName); const removed = cloudSecretNames.filter(name => !localSecretNames.includes(name)); if (removed.length) { secretsPendingRemoval[functionName] = removed; } }); await storeToBeRemovedFunctionsWithSecrets(context); }; type LocalSecretsState = { secretNames: string[]; }; const defaultGetFunctionSecretNamesOptions = { fromCurrentCloudBackend: false, }; /** * Gets the secret names stored in function-parameters.json for the given function. * * Optionally, {fromCurrentCloudBackend: true} can be specified to get the secret names stored in #current-cloud-backend */ export const getLocalFunctionSecretNames = ( functionName: string, options: Partial<typeof defaultGetFunctionSecretNamesOptions> = defaultGetFunctionSecretNamesOptions, ): string[] => { options = { ...defaultGetFunctionSecretNamesOptions, ...options }; const parametersFilePath = path.join( options.fromCurrentCloudBackend ? pathManager.getCurrentCloudBackendDirPath() : pathManager.getBackendDirPath(), categoryName, functionName, functionParametersFileName, ); const funcParameters = JSONUtilities.readJson<Partial<LocalSecretsState>>(parametersFilePath, { throwIfNotExist: false }); return funcParameters?.secretNames || []; }; // Below are some private helper functions for managing local secret state /** * Sets the secret state in function-parameters.json. * * DO NOT EXPORT this method. All exported state management should happen through higher-level interfaces */ const setLocalFunctionSecretState = (functionName: string, secretDeltas: SecretDeltas) => { const existingSecrets = Object.keys(getExistingSecrets(secretDeltas)); const secretsParametersContent: LocalSecretsState = { secretNames: existingSecrets, }; const parametersFilePath = path.join(pathManager.getBackendDirPath(), categoryName, functionName, functionParametersFileName); // checking for existance of the file because in the case of function deletion we don't want to create the file again if (fs.existsSync(parametersFilePath)) { createParametersFile(secretsParametersContent, functionName, functionParametersFileName); } if (hasExistingSecrets(secretDeltas)) { setAppIdForFunctionInTeamProvider(functionName); } else { removeAppIdForFunctionInTeamProvider(functionName); } }; const setAppIdForFunctionInTeamProvider = (functionName: string) => { const tpi = stateManager.getTeamProviderInfo(undefined, { throwIfNotExist: false, default: {} }); const env = stateManager.getLocalEnvInfo()?.envName as string; let funcTpi = tpi?.[env]?.categories?.[categoryName]?.[functionName]; if (!funcTpi) { _.set(tpi, [env, 'categories', categoryName, functionName], {}); funcTpi = tpi[env].categories[categoryName][functionName]; } _.assign(funcTpi, { [secretsPathAmplifyAppIdKey]: getAppId() }); stateManager.setTeamProviderInfo(undefined, tpi); }; const removeAppIdForFunctionInTeamProvider = (functionName: string) => { const tpi = stateManager.getTeamProviderInfo(undefined, { throwIfNotExist: false, default: {} }); const env = stateManager.getLocalEnvInfo()?.envName as string; _.unset(tpi, [env, 'categories', categoryName, functionName, secretsPathAmplifyAppIdKey]); stateManager.setTeamProviderInfo(undefined, tpi); }; /** * Iterates over to-be-deleted lambda functions and stores any secret names for deleted functions in secretsPendingRemoval */ const storeToBeRemovedFunctionsWithSecrets = async (context: $TSContext) => { const resourceStatus = await context.amplify.getResourceStatus(categoryName); const resourcesToBeDeleted = (resourceStatus?.resourcesToBeDeleted || []) as { category: string; resourceName: string; service: string; }[]; const deletedLambdas = resourcesToBeDeleted .filter(resource => resource.service === ServiceName.LambdaFunction) .map(resource => resource.resourceName); for (const deletedLambda of deletedLambdas) { const cloudSecretNames = await getLocalFunctionSecretNames(deletedLambda, { fromCurrentCloudBackend: true }); const localSecretNames = await getLocalFunctionSecretNames(deletedLambda); // we need the secret names from #current-cloud-backend as well as /amplify/backend because a customer may have added a secret and then // deleted the function without pushing in between in which case the secret name would only be present in /amplify/backend const secretNames = Array.from(new Set(cloudSecretNames.concat(localSecretNames))); if (secretNames.length) { secretsPendingRemoval[deletedLambda] = secretNames; } } };
the_stack
/* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> module Microsoft.Maps.Search { /** * Contains options for a search request. */ export interface IPoiSearchRequestOptions { /** * The name of the function to call when a successful result is returned from the search request. */ callback: (result: IPoiSearchResponse, userData: any) => void; /** * The maximum number of results to return. The maximum number than can be returned is 25. */ count?: number; /** * The search string, such as “pizza in Seattle, WA”. Either query or what/ where needs to be specified. If both are specified, an error occurs. */ query?: string; /** * An object containing any data that needs to be passed to the callback when the request is completed. */ userData?: any; /** * The business name, category, or other item for which the search is conducted.For example, “pizza” in the search string “pizza in Seattle”. */ what?: string; /** * The address or place name of the area for which the search is conducted.For example, “Seattle” in the search string “pizza in Seattle”. */ where?: string; /** The maximium search radius in miles to look for results. Default: 25 Max value: 250 */ searchRadius?: number; /** The minium desired match confidence of the results. */ matchConfidence?: string | MatchConfidence; /** * If no results are found, try geocoding the query incase it might be a location. * This result will still have no results, but will have search region info. * This allows a single textbox to power both POI and locaiton based searches. Default: true */ geocodeFallback: boolean; } /** * Represents the results of a search request. */ export interface IPoiSearchResponse { /** * An array of alternate search regions. */ alternateSearchRegions?: IPlaceResult[]; /** * The region in which the search was performed. */ searchRegion?: IPlaceResult; /** * A search result array containing the search results. */ searchResults?: IPoiPushpin[]; /** The location rectangle that defines the boundaries of the best map view of the results. */ bestView?: LocationRect; } /** * Represents a search result pushpin. */ export class IPoiPushpin extends Microsoft.Maps.Pushpin { metadata: IPoiMetadata; } /** * Represents a distinct search result. */ export interface IPoiMetadata { /** * The street line of an address. The address property is the most precise, official line of an address, provided by the postal agency servicing the area specified by the location or postalCode property. */ address: string; /** * The city of the search result. */ city: string; /** * The country of the search result. */ country: string; /** * The entity type id of the search result. */ entityTypeId: string; /** * The entity ID of the search result. */ id: number; /** * The name of the entity defined by the search result. */ name: string; /** * The phone number of the search result. */ phone: string; /** * The postal code of the search result. */ postalCode: string; /** * The subdivision name within the country or region for an address. This element is also commonly treated as the first order administrative * subdivision. An example is a US state, such as “Oregon”. */ adminDistrict: string; /** The second, third, or fourth order subdivision within a country, dependency, or region. An example is a US county, such as “King”. */ district: string; /** The match confidence of the best result. */ matchConfidence: string | MatchConfidence; /** Distance from the search location to the result. */ distance: number; } /** * An object that represents an Entity Type */ interface IEntityTypeGroup { /** Entity Type Id */ id: string; /** Arrays of related synonums */ syn: string[][]; } /** * A list of all entity types. * Entity Types as defined here: https://msdn.microsoft.com/en-us/library/hh478191.aspx */ export var _entityTypeSynonyms: IEntityTypeGroup[] = [ //Petrol/Gasoline Station - 5540 { id: '5540', syn: [ ['gasstation', 'servicestation', 'gas', 'petro', 'petrostation', 'gasoline', 'gasolinestation'], ['76'], ['7eleven'], ['chevron'], ['arco'], ['costco'], ['shell'], ['hess'], ['valero'], ['sunoco'], ['bp', 'britishpetrolum'], ['exxonmobil', 'exxon'], ] }, //Restaurant - 5800 { id: '5800', syn: [ ['food', 'restaurant', 'cuisine'], ['beer', 'pub', 'tavern', 'taproom', 'cocktail', 'wine'], ['italian', 'pizza', 'pizzeria', 'trattoria', 'ristorante'], ['sub', 'sandwich', 'deli'], ['mexican', 'taco', 'burrito'], ['bakery', 'bakeries'], ['chinese'], ['thai'], ['bbq', 'barbeque'], ['kfc', 'kentuckyfriedchicken'], ['mcdonalds'], ['burgerking'], ['subway'], ['pizzahut'], ['dominos'], ['tacobell'], ['papajohns'], ['dairyqueen'], ['baskinrobbins'], ['littlecaesars'], ['krispykreme'], ['wendys'], ['chipotle'], ['tacodelmar'] ] }, //Nightlife - 5813 { id: '5813', syn: [ ['beer', 'pub', 'disco', 'cocktaillounge', 'nightclub', 'beerhouse', 'tavern', 'taproom', 'cocktail', 'wine'] ] }, //Shopping - 6512 { id: '5813', syn: [ ['mall', 'shoppingcenter', 'stripmall', 'marketplace', 'store'], ['walmart', 'walmartsuperstore'], ['costco'], ['thehomedepot', 'homedepot'], ['walgreens'], ['cvscaremark'], ['target'], ['lowes'], ['macys'], ['bestbuy'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'], ['gap'] ] }, //Grocery Store - 5400 { id: '5400', syn: [ ['grocerystore', 'groceries', 'food'], ['fredmeyer'], ['safeway'], ['tescos'], ['wholefoods'], ['tescos'], ['aldi'], ['traderjoes'], ['kroger'], ['costco'], ['albertsons'], ['walmart'], ['marksandspencer'] ] }, //Clothing Store - 9537 { id: '9537', syn: [ ['clothingstore', 'store'], ['walmart', 'walmartsuperstore'], ['costco'], ['target'], ['macys'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'], ['gap'] ] }, //Department Store - 9545 { id: '9545', syn: [ ['departmentstore', 'store'], ['walmart', 'walmartsuperstore'], ['target'], ['macys'], ['sears'], ['kohls'], ['meijer'], ['nordstrom'] ] }, //Rental Car Agency - 7510 { id: '7510', syn: [ ['carrentalagency', 'carrental', 'rentalcaragency'], ['hertzrentacar', 'hertzcarrental'], ['enterpriserentacar', 'enterprisecarrental'], ['budgetrentacar', 'budgetcarrental'], ['aviscarrental'], ['alamorentacar'] ] }, //Hotel - 7011 { id: '7011', syn: [ ['motel', 'inn', 'hostel', 'lodging', 'lodge', 'accommodation'], ['marriottinternational', 'marriott'], ['wyndham', 'wyndhamhotel'], ['intercontientalhotel', 'intercontiental'] ] }, //Cinema - 7832 { id: '7832', syn: [ ['cinema', 'movie', 'theater', 'theatre'], ['cineplexodeon', 'cineplex'], ['cinemarktheater', 'cinemark'], ['ipictheater', 'ipic'] ] }, //Auto Service & Maintenance - 7538 { id: '7538', syn: [ ['garage', 'autorepair', 'servicestation', 'autoservice', 'automaintenance'] ] }, //Hospital - 8060 { id: '8060', syn: [ ['medical', 'emergencyroom', 'hospital', 'clinic', 'walkinclinic'] ] }, //Higher Education - 8200 { id: '8200', syn: [ ['university', 'universities', 'college', 'school', 'education'] ] }, //Convenience Store - 9535 { id: '9535', syn: [ ['conveniencestore'], ['7eleven'] ] }, //Pharmacy - 9565 { id: '9565', syn: [ ['pharmacies', 'pharmacy', 'medicine'], ['cvspharmacies', 'cvspharmacy', 'cvs'], ['walgreens'], ['riteaidpharmacies', 'riteaidpharmacy'] ] }, //Place of Worship - 9992 { id: '9992', syn: [ ['churches', 'mosques', 'temples', 'synagogues', 'shrines', 'chapels', 'parhishes'], ['catholic', 'catholicchurch', 'catholicchurches'] ] }, //Coffee Shop - 9996 { id: '9996', syn: [ ['coffee', 'cafe', 'tea', 'caffé', 'coffeeshop', 'donutshop'], ['dunkindonuts'], ['starbucks'], ['timhortons'], ['costacoffeeshops'] ] }, //Winery - 2084 { id: '2084', syn: [['winery', 'wine']] }, //ATM - 3578 { id: '3578', syn: [['atm']] }, //Train Station - 4013 { id: '4013', syn: [['trainstation', 'trains']] }, //Commuter Rail Station - 4100 { id: '4100', syn: [['commuterrailstation']] }, //Bus Station - 4170 { id: '4170', syn: [['busstation', 'busstop']] }, //Named Place - 4444 { id: '4444', syn: [['namedplace']] }, //Ferry Terminal - 4482 { id: '4482', syn: [['ferryterminal']] }, //Marina - 4493 { id: '4493', syn: [['marina']] }, //Public Sports Airport - 4580 { id: '4580', syn: [['publicsportsairport']] }, //Airport - 4581 { id: '4581', syn: [['airport', 'airfield']] }, //Business Facility - 5000 { id: '5000', syn: [['businessfacility']] }, //Auto Dealerships - 5511 { id: '5511', syn: [['autodealerships']] }, //Auto Dealership-Used Cars - 5512 { id: '5512', syn: [['autodealershipusedcars', 'cardealership', 'dealership', 'usedcars', 'usedcardealership']] }, //Motorcycle Dealership - 5571 { id: '5571', syn: [['motorcycledealership']] }, //Historical Monument - 5999 { id: '5999', syn: [['historicalmonument']] }, //Bank - 6000 { id: '6000', syn: [['bank']] }, //Ski Resort - 7012 { id: '7012', syn: [['skiresort']] }, //Other Accommodation - 7013 { id: '7013', syn: [['otheraccommodation']] }, //Ski Lift - 7014 { id: '7014', syn: [['skilift']] }, //Tourist Information - 7389 { id: '7389', syn: [['touristinformation']] }, //Parking Lot - 7520 { id: '7520', syn: [['parkinglot']] }, //Parking Garage/House - 7521 { id: '7521', syn: [['parkinggaragehouse']] }, //Park & Ride - 7522 { id: '7522', syn: [['park&ride']] }, //Rest Area - 7897 { id: '7897', syn: [['restarea']] }, //Performing Arts - 7929 { id: '7929', syn: [['performingarts']] }, //Bowling Centre - 7933 { id: '7933', syn: [['bowlingcentre']] }, //Sports Complex - 7940 { id: '7940', syn: [['sportscomplex']] }, //Park/Recreation Area - 7947 { id: '7947', syn: [['parkrecreationarea']] }, //Casino - 7985 { id: '7985', syn: [['casino']] }, //Convention/Exhibition Centre - 7990 { id: '7990', syn: [['conventionexhibitioncentre']] }, //Golf Course - 7992 { id: '7992', syn: [['golfcourse']] }, //Civic/Community Centre - 7994 { id: '7994', syn: [['civiccommunitycentre', 'communitycentre', 'communitycenter']] }, //Amusement Park - 7996 { id: '7996', syn: [['amusementpark']] }, //Sports Centre - 7997 { id: '7997', syn: [['sportscentre']] }, //Ice Skating Rink - 7998 { id: '7998', syn: [['iceskatingrink']] }, //Tourist Attraction - 7999 { id: '7999', syn: [['touristattraction']] }, //School - 8211 { id: '8211', syn: [['school', 'gradeschool', 'elementaryschool', 'middleschool']] }, //Library - 8231 { id: '8231', syn: [['library', 'books']] }, //Museum - 8410 { id: '8410', syn: [['museum']] }, //Automobile Club - 8699 { id: '8699', syn: [['automobileclub']] }, //City Hall - 9121 { id: '9121', syn: [['cityhall']] }, //Court House - 9211 { id: '9211', syn: [['courthouse']] }, //Police Station - 9221 { id: '9221', syn: [['policestation']] }, //Campground - 9517 { id: '9517', syn: [['campground']] }, //Truck Stop/Plaza - 9522 { id: '9522', syn: [['truckstopplaza', 'truckstop']] }, //Government Office - 9525 { id: '9525', syn: [['governmentoffice']] }, //Post Office - 9530 { id: '9530', syn: [['postoffice']] }, //Home Specialty Store - 9560 { id: '9560', syn: [['homespecialtystore']] }, //Specialty Store - 9567 { id: '9567', syn: [['specialtystore']] }, //Sporting Goods Store - 9568 { id: '9568', syn: [['sportinggoodsstore']] }, //Medical Service - 9583 { id: '9583', syn: [['medicalservice']] }, //Residential Area/Building - 9590 { id: '9590', syn: [['residentialareabuilding']] }, //Cemetery - 9591 { id: '9591', syn: [['cemetery']] }, //Highway Exit - 9592 { id: '9592', syn: [['highwayexit']] }, //Transportation Service - 9593 { id: '9593', syn: [['transportationservice']] }, //Weigh Station - 9710 { id: '9710', syn: [['weighstation']] }, //Cargo Centre - 9714 { id: '9714', syn: [['cargocentre']] }, //Military Base - 9715 { id: '9715', syn: [['militarybase']] }, //Animal Park - 9718 { id: '9718', syn: [['animalpark']] }, //Truck Dealership - 9719 { id: '9719', syn: [['truckdealership', 'truck']] }, //Home Improvement & Hardware Store - 9986 { id: '9986', syn: [['homeimprovement', 'hardwarestore']] }, //Consumer Electronics Store - 9987 { id: '9987', syn: [ ['consumerelectronicsstore', 'electronics'], ['bestbuy'], ['att'] ] }, //Office Supply & Services Store - 9988 { id: '9988', syn: [ ['officesupply', 'officesupplies'], ['staples'] ] }, //Industrial Zone - 9991 { id: '9991', syn: [['industrialzone']] }, //Embassy - 9993 { id: '9993', syn: [['embassy']] }, //County Council - 9994 { id: '9994', syn: [['countycouncil']] }, //Bookstore - 9995 { id: '9995', syn: [['bookstore']] }, //Hamlet - 9998 { id: '9998', syn: [['hamlet']] }, //Border Crossing - 9999 { id: '9999', syn: [['bordercrossing']] } ]; /** * A search manager that performs poi/business search queries. */ export class PoiSearchManager { private _map: Map; private _searchManager: SearchManager; private _sessionKey: string; private _navteqNA = 'https://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/NavteqPOIs'; private _navteqEU = 'https://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs'; //Words used to connect a "what" with a "where". private _connectingWords = [" in ", " near ", " around ", " by ", "nearby"]; private _naPhoneRx = /([0-9]{3}-)([0-9]{3})([0-9]{4})/gi; private _ukPhoneRx = /([0-9]{2}-)([0-9]{4})([0-9]{4})/gi; private _fuzzyRx = /([-,.'\s]|s$)/gi; /** * A search manager that performs business search queries. * @param map A map instance to retreive a session key from and use to perform a query. */ constructor(map: Map) { this._map = map; } /** * A boolean indicating if debugging is enabled. When enabled a lot of details will be written to the console. */ public debug: boolean; /** * Performs a business search based on the specified request options and returns the results to the request options callback function. * @param request The business search request. */ public search(request: IPoiSearchRequestOptions): void { if ((request.query && request.what) || !request.callback) { if (this.debug){ console.log('Invalid request'); } return; } if (!this._searchManager) { this._searchManager = new Microsoft.Maps.Search.SearchManager(this._map); } var self = this; if (!this._sessionKey) { this._map.getCredentials((c) => { self._sessionKey = c; self.search(request); }); return; } request.count = (request.count > 0 && request.count <= 25) ? request.count : 25; request.searchRadius = (request.searchRadius > 0 && request.searchRadius <= 250) ? request.searchRadius : 25; request.matchConfidence = request.matchConfidence || Microsoft.Maps.Search.MatchConfidence.medium; if (request.query) { this._splitQueryString(request); } if (request.what) { request.what = request.what.toLowerCase().replace('-', ' ').replace("'", ''); } if (request.where) { if (request.where === 'me' || request.where === 'my location') { //Request the user's location navigator.geolocation.getCurrentPosition((position) => { var loc = new Microsoft.Maps.Location( position.coords.latitude, position.coords.longitude); self._performPoiSearch(request, [<IPlaceResult>{ address: null, bestView: new Microsoft.Maps.LocationRect(loc, 0.001, 0.001), entityType: 'userLocation', location: loc, locations: null, matchCode: null, matchConfidence: null, name: null }]); }); } else { this._searchManager.geocode({ where: request.where, callback: (r) => { if (r && r.results && r.results.length > 0) { this._performPoiSearch(request, r.results); } else if (request.callback) { request.callback(<IPoiSearchResponse>{ responseSummary: { errorMessage: "No geocode results for 'where'." } }, request.userData); } }, errorCallback: (e) => { request.callback(<IPoiSearchResponse>{ responseSummary: { errorMessage: "No geocode results for 'where'." } }, request.userData); } }); } } else { this._performPoiSearch(request, null); } } /** * Splits a free form query string into a what and where values. * @param request The request containing the free form query string. */ private _splitQueryString(request: IPoiSearchRequestOptions): void { var query = request.query.toLowerCase(); if (query.indexOf('find ') === 0 || query.indexOf('get ') === 0) { query = query.replace('find ', '').replace('get ', ''); } for (var i = 0; i < this._connectingWords.length; i++) { if (query.indexOf(this._connectingWords[i]) > 0) { var vals = query.split(this._connectingWords[i]); if (vals.length >= 2) { request.what = vals[0].trim(); request.where = vals[1].trim(); break; } else if (vals.length == 1) { request.what = vals[0].trim(); break; } } } if (!request.what) { request.what = request.query; } } /** * Searches for business points of interests. * @param request The search request. * @param places An array of geocoded locations based on the "where" value of the request. */ private _performPoiSearch(request: IPoiSearchRequestOptions, places: IPlaceResult[]): void { var searchRegion: IPlaceResult; var alternateSearchRegions: IPlaceResult[]; if (places && places.length > 0) { searchRegion = places[0]; if (places.length > 1) { alternateSearchRegions = places.slice(1); } } else { searchRegion = <IPlaceResult>{ bestView: this._map.getBounds(), entityType: 'map', location: this._map.getCenter() }; } var self = this; var result: IPoiSearchResponse = { alternateSearchRegions: alternateSearchRegions, searchRegion: searchRegion, searchResults: [], bestView: searchRegion.bestView }; var what = null; var whatRx = null; var synonyms = null; var filter = null; if (request.what) { //Remove dashes, single quotes, and trailing "s" from what and name values. what = request.what.replace(this._fuzzyRx, ''); if (what.indexOf('restaurant') > 0) { what = what.replace('restaurant', ''); } if (what.indexOf('cuisine') > 0) { what = what.replace('cuisine', ''); } if (what.indexOf('food') > 0) { what = what.replace('food', ''); } synonyms = this._getSynonums(what); filter = this._createPoiFilter(what, synonyms); whatRx = new RegExp('^(.*\\s)?' + what + '(\\s.*)?$','gi'); } if (this.debug) { console.log('Data source: ' + ((searchRegion.location.longitude < -26) ? 'NavteqNA' : 'NavteqEU')); if (filter) { console.log('Filter: ' + filter.toString()); } } //Request the top 250 results for the query and then filter them down afterwards. Microsoft.Maps.SpatialDataService.QueryAPIManager.search({ top: 250, queryUrl: (searchRegion.location.longitude < -26) ? this._navteqNA : this._navteqEU, inlineCount: true, spatialFilter: { spatialFilterType: 'nearby', location: searchRegion.location, radius: 25 }, filter: filter }, this._map, (r, inlineCount) => { if (r && r.length > 0) { var locs: Microsoft.Maps.Location[] = []; var confidence: MatchConfidence; if (what && this.debug) { console.log('Filtered out results\r\nEntityTypeID\tName'); } for (var i = 0; i < r.length; i++) { var s = <IPoiPushpin>r[i]; if (what) { confidence = this._fuzzyPoiMatch(whatRx, r[i].metadata, synonyms); //Filter results client side. if (confidence === request.matchConfidence || request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.low || request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.unknown || (request.matchConfidence === Microsoft.Maps.Search.MatchConfidence.medium && confidence === Microsoft.Maps.Search.MatchConfidence.high)) { self._convertSearchResult(r[i]); s.metadata.matchConfidence = confidence; result.searchResults.push(s); locs.push(s.getLocation()); } else if (this.debug) { console.log(r[i].metadata.EntityTypeID + '\t' + r[i].metadata.Name); } } else { self._convertSearchResult(r[i]); s.metadata.matchConfidence = Microsoft.Maps.Search.MatchConfidence.unknown; result.searchResults.push(s); locs.push(s.getLocation()); } if (result.searchResults.length >= request.count) { break; } } if (locs.length > 1) { result.bestView = Microsoft.Maps.LocationRect.fromLocations(locs); } else if (locs.length === 1) { result.bestView = new Microsoft.Maps.LocationRect(locs[0], 0.001, 0.001); } } if (result.searchResults.length === 0 && !request.where && request.what) { //If no results where found and a where hasn't been provided, but a what has. Try geocoding the what as ti may be a location. this._searchManager.geocode({ where: request.what, callback: (r) => { if (r && r.results && r.results.length > 0) { result.searchRegion = r.results[0]; result.bestView = r.results[0].bestView; if (r.results.length > 1) { result.alternateSearchRegions = r.results.slice(1); } } if (request.callback) { request.callback(result, request.userData); } }, errorCallback: (e) => { if (request.callback) { request.callback(result, request.userData); } } }); } else if (request.callback) { request.callback(result, request.userData); } }); } /** * Performs a fuzzy match between the "what" parameter of the request and the metadata of a result. * @param what The "what" parameter of the request. * @param metadata The metadata of a result. */ private _fuzzyPoiMatch(whatRx: RegExp, metadata: any, synonyms: IEntityTypeGroup[]): MatchConfidence { //Remove dashes, single quotes, and trailing "s" from name value. var lowerName = (metadata.Name) ? metadata.Name.toLowerCase().replace(this._fuzzyRx, '') : ''; var eid = metadata.EntityTypeID; //Check to see if the name matches the what query. if (whatRx.test(lowerName)) { return Microsoft.Maps.Search.MatchConfidence.high; } if (synonyms) { for (var i = 0; i < synonyms.length; i++) { for (var j = 0; j < synonyms[i].syn.length; j++) { for (var k = 0; k < synonyms[i].syn[j].length; k++) { if (lowerName.indexOf(synonyms[i].syn[j][k]) > -1) { return Microsoft.Maps.Search.MatchConfidence.high; } } } } } return Microsoft.Maps.Search.MatchConfidence.low; } /** * Creates a filter for the Bing Spatial Data Services Query API based on the "what" parameter of the request. * @param what The "what" parameter of the request. */ private _createPoiFilter(what: string, synonyms: IEntityTypeGroup[]): Microsoft.Maps.SpatialDataService.Filter { if (what) { var ids = []; if (synonyms) { for (var i = 0; i < synonyms.length; i++) { ids.push(synonyms[i].id); } } if (ids.length > 0) { return new Microsoft.Maps.SpatialDataService.Filter('EntityTypeID', Microsoft.Maps.SpatialDataService.FilterCompareOperator.isIn, ids); } } return null; } /** * Converts a result from a NAVTEQ data source into a search result. * @param shape The shape result from the NAVTEQ data source. */ private _convertSearchResult(shape: Microsoft.Maps.IPrimitive): void { var m = shape.metadata; var phone = m.Phone || ''; if (this._naPhoneRx.test(m.Phone)) { phone = m.Phone.replace(this._naPhoneRx, '$1$2-$3'); } else if (this._ukPhoneRx.test(m.Phone)) { phone = m.Phone.replace(this._ukPhoneRx, '$1$2-$3'); } var metadata: IPoiMetadata = { id: m.EntityID, entityTypeId: m.EntityTypeID, address: m.AddressLine, adminDistrict: m.AdminDistrict, district: m.AdminDistrict2, city: m.Locality, country: m.CountryRegion, postalCode: m.PostalCode, name: m.DisplayName, phone: phone, matchConfidence: Microsoft.Maps.Search.MatchConfidence.unknown, distance: m.__distance }; shape.metadata = metadata; } /** * Finds all synonums associated with the "what" value. * @param what What the user is looking for. */ private _getSynonums(what: string): IEntityTypeGroup[] { var synonums: IEntityTypeGroup[] = []; var syns = Microsoft.Maps.Search._entityTypeSynonyms; for (var i = 0; i < syns.length; i++) { var synonum = <IEntityTypeGroup>{ id: syns[i].id, syn: [] }; for (var j = 0; j < syns[i].syn.length; j++) { if (syns[i].syn[j].indexOf(what) > -1) { synonum.syn.push(syns[i].syn[j]); } else { for (var k = 0; k < syns[i].syn[j].length; k++) { if (syns[i].syn[j][k].indexOf(what) > -1 && Math.abs(syns[i].syn[j][k].length - what.length) < 2) { synonum.syn.push(syns[i].syn[j]); break; } } } } if (synonum.syn.length > 0) { synonums.push(synonum); } } return synonums; } } } //Load dependancies Microsoft.Maps.loadModule(['Microsoft.Maps.Search', 'Microsoft.Maps.SpatialDataService'], () => { Microsoft.Maps.moduleLoaded('PoiSearchModule'); });
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import { AnyAction, Dispatch } from 'redux'; import { Link, Redirect, Route, Switch } from 'react-router-dom'; import { Divider, Grid, Header, Icon, Loader, Menu, Segment, Table } from 'semantic-ui-react'; import { ConcordKey, Owner, RequestError } from '../../../api/common'; import { SecretEncryptedByType, SecretEntry, SecretType, SecretVisibility, typeToText } from '../../../api/org/secret'; import { actions, selectors, State } from '../../../state/data/secrets'; import { RequestErrorMessage, WithCopyToClipboard } from '../../molecules'; import { AuditLogActivity, PublicKeyPopup, SecretDeleteActivity, SecretOrganizationChangeActivity, SecretOwnerChangeActivity, SecretProjectActivity, SecretRenameActivity, SecretTeamAccessActivity, SecretVisibilityActivity } from '../../organisms'; import { NotFoundPage } from '../../pages'; export type TabLink = 'info' | 'settings' | 'access' | 'audit' | null; interface ExternalProps { activeTab: TabLink; orgName: ConcordKey; secretName: ConcordKey; forceRefresh: any; } interface StateProps { data?: SecretEntry; loading: boolean; error: RequestError; } interface DispatchProps { load: (orgName: ConcordKey, secretName: ConcordKey) => void; } type Props = StateProps & DispatchProps & ExternalProps; const visibilityToText = (v: SecretVisibility) => v === SecretVisibility.PUBLIC ? 'Public' : 'Private'; const encryptedByToText = (t: SecretEncryptedByType) => t === SecretEncryptedByType.SERVER_KEY ? 'Server key' : 'Password'; const renderUser = (e: Owner) => { if (!e.userDomain) { return e.username; } return `${e.username}@${e.userDomain}`; }; class SecretActivity extends React.PureComponent<Props> { static renderPublicKey(data: SecretEntry) { return <PublicKeyPopup orgName={data.orgName} secretName={data.name} />; } static renderInfo(data: SecretEntry) { return ( <Grid columns={2}> <Grid.Column> <Table definition={true}> <Table.Body> <Table.Row> <Table.Cell>Name</Table.Cell> <Table.Cell>{data.name}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Type</Table.Cell> <Table.Cell>{typeToText(data.type)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Owner</Table.Cell> <Table.Cell>{data.owner ? renderUser(data.owner) : '-'}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Actions</Table.Cell> <Table.Cell> {data.type === SecretType.KEY_PAIR && data.encryptedBy === SecretEncryptedByType.SERVER_KEY && SecretActivity.renderPublicKey(data)} </Table.Cell> </Table.Row> </Table.Body> </Table> </Grid.Column> <Grid.Column> <Table definition={true}> <Table.Body> <Table.Row> <Table.Cell>Visibility</Table.Cell> <Table.Cell>{visibilityToText(data.visibility)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Protected by</Table.Cell> <Table.Cell>{encryptedByToText(data.encryptedBy)}</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Restricted to a project</Table.Cell> <Table.Cell> {data.projectName ? ( <Link to={`/org/${data.orgName}/project/${data.projectName}`}> {data.projectName} </Link> ) : ( ' - ' )} </Table.Cell> </Table.Row> </Table.Body> </Table> </Grid.Column> </Grid> ); } static renderSettings(data: SecretEntry) { const disabled = !data; return ( <> <Header as="h5" disabled={true}> <WithCopyToClipboard value={data.id}>ID: {data.id}</WithCopyToClipboard> </Header> <Segment> <Header as="h4">Visibility</Header> <SecretVisibilityActivity orgName={data.orgName} secretId={data.id} visibility={data.visibility} /> </Segment> <Divider horizontal={true} content="Danger Zone" /> <Segment color="red"> <Header as="h4">Project</Header> <SecretProjectActivity orgName={data.orgName} secretName={data.name} projectName={data.projectName} /> <Header as="h4">Secret name</Header> <SecretRenameActivity orgName={data.orgName} secretId={data.id} secretName={data.name} /> <Header as="h4">Secret owner</Header> <SecretOwnerChangeActivity orgName={data.orgName} secretName={data.name} initialOwnerId={data?.owner?.id} disabled={disabled} /> <Header as="h4">Organization</Header> <SecretOrganizationChangeActivity orgName={data.orgName} secretName={data.name} /> <Header as="h4">Delete Secret</Header> <SecretDeleteActivity orgName={data.orgName} secretName={data.name} /> </Segment> </> ); } static renderTeamAccess(data: SecretEntry) { return <SecretTeamAccessActivity orgName={data.orgName} secretName={data.name} />; } static renderAuditLog(e: SecretEntry) { return ( <AuditLogActivity showRefreshButton={false} filter={{ details: { orgName: e.orgName, secretName: e.name } }} /> ); } componentDidMount() { this.init(); } componentDidUpdate(prevProps: Props) { const { orgName: newOrgName, secretName: newSecretName } = this.props; const { orgName: oldOrgName, secretName: oldSecretName } = prevProps; if (oldOrgName !== newOrgName || oldSecretName !== newSecretName) { this.init(); } } init() { const { load, orgName, secretName } = this.props; load(orgName, secretName); } render() { const { error, loading, data } = this.props; if (error) { return <RequestErrorMessage error={error} />; } if (loading || !data) { return <Loader active={true} />; } const { activeTab, orgName, secretName } = this.props; const baseUrl = `/org/${orgName}/secret/${secretName}`; return ( <> <Menu tabular={true} style={{ marginTop: 0 }}> <Menu.Item active={activeTab === 'info'}> <Icon name="file" /> <Link to={`${baseUrl}/info`}>Info</Link> </Menu.Item> <Menu.Item active={activeTab === 'access'}> <Icon name="key" /> <Link to={`${baseUrl}/access`}>Access</Link> </Menu.Item> <Menu.Item active={activeTab === 'settings'}> <Icon name="setting" /> <Link to={`${baseUrl}/settings`}>Settings</Link> </Menu.Item> <Menu.Item active={activeTab === 'audit'}> <Icon name="history" /> <Link to={`${baseUrl}/audit`}>Audit Log</Link> </Menu.Item> </Menu> <Switch> <Route path={baseUrl} exact={true}> <Redirect to={`${baseUrl}/info`} /> </Route> <Route path={`${baseUrl}/info`} exact={true}> {SecretActivity.renderInfo(data)} </Route> <Route path={`${baseUrl}/access`} exact={true}> {SecretActivity.renderTeamAccess(data)} </Route> <Route path={`${baseUrl}/settings`} exact={true}> {SecretActivity.renderSettings(data)} </Route> <Route path={`${baseUrl}/audit`} exact={true}> {SecretActivity.renderAuditLog(data)} </Route> <Route component={NotFoundPage} /> </Switch> </> ); } } const mapStateToProps = ( { secrets }: { secrets: State }, { orgName, secretName }: ExternalProps ): StateProps => ({ data: selectors.secretByName(secrets, orgName, secretName), loading: secrets.listSecrets.running, error: secrets.listSecrets.error }); const mapDispatchToProps = (dispatch: Dispatch<AnyAction>): DispatchProps => ({ load: (orgName: ConcordKey, secretName: ConcordKey) => dispatch(actions.getSecret(orgName, secretName)) }); export default connect(mapStateToProps, mapDispatchToProps)(SecretActivity);
the_stack
import { GaxiosPromise } from 'gaxios'; import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library'; import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common'; export declare namespace libraryagent_v1 { interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API * access, quota, and reports. Required unless you provide an OAuth 2.0 * token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be * any arbitrary string assigned to a user, but should not exceed 40 * characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Library Agent API * * A simple Google Example Library API. * * @example * const {google} = require('googleapis'); * const libraryagent = google.libraryagent('v1'); * * @namespace libraryagent * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Libraryagent */ class Libraryagent { context: APIRequestContext; shelves: Resource$Shelves; constructor(options: GlobalOptions, google?: GoogleConfigurable); } /** * A single book in the library. */ interface Schema$GoogleExampleLibraryagentV1Book { /** * The name of the book author. */ author?: string; /** * The resource name of the book. Book names have the form * `shelves/{shelf_id}/books/{book_id}`. The name is ignored when creating a * book. */ name?: string; /** * Value indicating whether the book has been read. */ read?: boolean; /** * The title of the book. */ title?: string; } /** * Response message for LibraryAgent.ListBooks. */ interface Schema$GoogleExampleLibraryagentV1ListBooksResponse { /** * The list of books. */ books?: Schema$GoogleExampleLibraryagentV1Book[]; /** * A token to retrieve next page of results. Pass this value in the * ListBooksRequest.page_token field in the subsequent call to `ListBooks` * method to retrieve the next page of results. */ nextPageToken?: string; } /** * Response message for LibraryAgent.ListShelves. */ interface Schema$GoogleExampleLibraryagentV1ListShelvesResponse { /** * A token to retrieve next page of results. Pass this value in the * ListShelvesRequest.page_token field in the subsequent call to * `ListShelves` method to retrieve the next page of results. */ nextPageToken?: string; /** * The list of shelves. */ shelves?: Schema$GoogleExampleLibraryagentV1Shelf[]; } /** * A Shelf contains a collection of books with a theme. */ interface Schema$GoogleExampleLibraryagentV1Shelf { /** * Output only. The resource name of the shelf. Shelf names have the form * `shelves/{shelf_id}`. The name is ignored when creating a shelf. */ name?: string; /** * The theme of the shelf */ theme?: string; } class Resource$Shelves { context: APIRequestContext; books: Resource$Shelves$Books; constructor(context: APIRequestContext); /** * libraryagent.shelves.get * @desc Gets a shelf. Returns NOT_FOUND if the shelf does not exist. * @alias libraryagent.shelves.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.name The name of the shelf to retrieve. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Shelves$Get, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1Shelf>; get(params: Params$Resource$Shelves$Get, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Shelf>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Shelf>): void; get(params: Params$Resource$Shelves$Get, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Shelf>): void; get(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Shelf>): void; /** * libraryagent.shelves.list * @desc Lists shelves. The order is unspecified but deterministic. Newly * created shelves will not necessarily be added to the end of this list. * @alias libraryagent.shelves.list * @memberOf! () * * @param {object} params Parameters for request * @param {integer=} params.pageSize Requested page size. Server may return fewer shelves than requested. If unspecified, server will pick an appropriate default. * @param {string=} params.pageToken A token identifying a page of results the server should return. Typically, this is the value of ListShelvesResponse.next_page_token returned from the previous call to `ListShelves` method. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Shelves$List, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1ListShelvesResponse>; list(params: Params$Resource$Shelves$List, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListShelvesResponse>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListShelvesResponse>): void; list(params: Params$Resource$Shelves$List, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListShelvesResponse>): void; list(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListShelvesResponse>): void; } interface Params$Resource$Shelves$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The name of the shelf to retrieve. */ name?: string; } interface Params$Resource$Shelves$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Requested page size. Server may return fewer shelves than requested. If * unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results the server should return. * Typically, this is the value of ListShelvesResponse.next_page_token * returned from the previous call to `ListShelves` method. */ pageToken?: string; } class Resource$Shelves$Books { context: APIRequestContext; constructor(context: APIRequestContext); /** * libraryagent.shelves.books.borrow * @desc Borrow a book from the library. Returns the book if it is borrowed * successfully. Returns NOT_FOUND if the book does not exist in the * library. Returns quota exceeded error if the amount of books borrowed * exceeds allocation quota in any dimensions. * @alias libraryagent.shelves.books.borrow * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.name The name of the book to borrow. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ borrow(params?: Params$Resource$Shelves$Books$Borrow, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1Book>; borrow(params: Params$Resource$Shelves$Books$Borrow, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; borrow(params: Params$Resource$Shelves$Books$Borrow, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; borrow(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; /** * libraryagent.shelves.books.get * @desc Gets a book. Returns NOT_FOUND if the book does not exist. * @alias libraryagent.shelves.books.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.name The name of the book to retrieve. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Shelves$Books$Get, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1Book>; get(params: Params$Resource$Shelves$Books$Get, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; get(params: Params$Resource$Shelves$Books$Get, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; get(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; /** * libraryagent.shelves.books.list * @desc Lists books in a shelf. The order is unspecified but deterministic. * Newly created books will not necessarily be added to the end of this * list. Returns NOT_FOUND if the shelf does not exist. * @alias libraryagent.shelves.books.list * @memberOf! () * * @param {object} params Parameters for request * @param {integer=} params.pageSize Requested page size. Server may return fewer books than requested. If unspecified, server will pick an appropriate default. * @param {string=} params.pageToken A token identifying a page of results the server should return. Typically, this is the value of ListBooksResponse.next_page_token. returned from the previous call to `ListBooks` method. * @param {string} params.parent The name of the shelf whose books we'd like to list. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Shelves$Books$List, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1ListBooksResponse>; list(params: Params$Resource$Shelves$Books$List, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListBooksResponse>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListBooksResponse>): void; list(params: Params$Resource$Shelves$Books$List, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListBooksResponse>): void; list(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1ListBooksResponse>): void; /** * libraryagent.shelves.books.return * @desc Return a book to the library. Returns the book if it is returned to * the library successfully. Returns error if the book does not belong to * the library or the users didn't borrow before. * @alias libraryagent.shelves.books.return * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.name The name of the book to return. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ return(params?: Params$Resource$Shelves$Books$Return, options?: MethodOptions): GaxiosPromise<Schema$GoogleExampleLibraryagentV1Book>; return(params: Params$Resource$Shelves$Books$Return, options: MethodOptions | BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; return(params: Params$Resource$Shelves$Books$Return, callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; return(callback: BodyResponseCallback<Schema$GoogleExampleLibraryagentV1Book>): void; } interface Params$Resource$Shelves$Books$Borrow extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The name of the book to borrow. */ name?: string; } interface Params$Resource$Shelves$Books$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The name of the book to retrieve. */ name?: string; } interface Params$Resource$Shelves$Books$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Requested page size. Server may return fewer books than requested. If * unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results the server should return. * Typically, this is the value of ListBooksResponse.next_page_token. * returned from the previous call to `ListBooks` method. */ pageToken?: string; /** * The name of the shelf whose books we'd like to list. */ parent?: string; } interface Params$Resource$Shelves$Books$Return extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The name of the book to return. */ name?: string; } }
the_stack
import { Match, Template } from '@aws-cdk/assertions'; import { Stack, Duration } from '@aws-cdk/core'; import { OAuthScope, ResourceServerScope, UserPool, UserPoolClient, UserPoolClientIdentityProvider, UserPoolIdentityProvider, ClientAttributes } from '../lib'; describe('User Pool Client', () => { test('default setup', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'Client', { userPool: pool, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { UserPoolId: stack.resolve(pool.userPoolId), AllowedOAuthFlows: ['implicit', 'code'], AllowedOAuthScopes: ['profile', 'phone', 'email', 'openid', 'aws.cognito.signin.user.admin'], CallbackURLs: ['https://example.com'], SupportedIdentityProviders: ['COGNITO'], }); }); test('client name', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN const client1 = new UserPoolClient(stack, 'Client1', { userPool: pool, userPoolClientName: 'myclient', }); const client2 = new UserPoolClient(stack, 'Client2', { userPool: pool, }); // THEN expect(client1.userPoolClientName).toEqual('myclient'); expect(() => client2.userPoolClientName).toThrow(/available only if specified on the UserPoolClient during initialization/); }); test('import', () => { // GIVEN const stack = new Stack(); // WHEN const client = UserPoolClient.fromUserPoolClientId(stack, 'Client', 'client-id-1'); // THEN expect(client.userPoolClientId).toEqual('client-id-1'); }); test('ExplicitAuthFlows is absent by default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client'); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ExplicitAuthFlows: Match.absent(), }); }); test('ExplicitAuthFlows are correctly named', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client', { authFlows: { adminUserPassword: true, custom: true, userPassword: true, userSrp: true, }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ExplicitAuthFlows: [ 'ALLOW_USER_PASSWORD_AUTH', 'ALLOW_ADMIN_USER_PASSWORD_AUTH', 'ALLOW_CUSTOM_AUTH', 'ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH', ], }); }); test('ExplicitAuthFlows makes refreshToken true by default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client', { authFlows: { userSrp: true, }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ExplicitAuthFlows: [ 'ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH', ], }); }); test('AllowedOAuthFlows are correctly named', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { oAuth: { flows: { authorizationCodeGrant: true, implicitCodeGrant: true, }, scopes: [OAuthScope.PHONE], }, }); pool.addClient('Client2', { oAuth: { flows: { clientCredentials: true, }, scopes: [OAuthScope.PHONE], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthFlows: ['implicit', 'code'], AllowedOAuthFlowsUserPoolClient: true, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthFlows: ['client_credentials'], AllowedOAuthFlowsUserPoolClient: true, }); }); test('callbackUrl defaults are correctly chosen', () => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); pool.addClient('Client1', { oAuth: { flows: { clientCredentials: true, }, }, }); pool.addClient('Client2', { oAuth: { flows: { authorizationCodeGrant: true, }, }, }); pool.addClient('Client3', { oAuth: { flows: { implicitCodeGrant: true, }, }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthFlows: ['client_credentials'], CallbackURLs: Match.absent(), }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthFlows: ['implicit'], CallbackURLs: ['https://example.com'], }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthFlows: ['code'], CallbackURLs: ['https://example.com'], }); }); test('callbackUrls are not rendered if OAuth is disabled ', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'PoolClient', { userPool: pool, disableOAuth: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { CallbackURLs: Match.absent(), }); }); test('fails when callbackUrls is empty for codeGrant or implicitGrant', () => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => pool.addClient('Client1', { oAuth: { flows: { implicitCodeGrant: true }, callbackUrls: [], }, })).toThrow(/callbackUrl must not be empty/); expect(() => pool.addClient('Client3', { oAuth: { flows: { authorizationCodeGrant: true }, callbackUrls: [], }, })).toThrow(/callbackUrl must not be empty/); expect(() => pool.addClient('Client4', { oAuth: { flows: { clientCredentials: true }, callbackUrls: [], }, })).not.toThrow(); }); test('logoutUrls can be set', () => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); pool.addClient('Client', { oAuth: { logoutUrls: ['https://example.com'], }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { LogoutURLs: ['https://example.com'], }); }); test('fails when clientCredentials OAuth flow is selected along with codeGrant or implicitGrant', () => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => pool.addClient('Client1', { oAuth: { flows: { authorizationCodeGrant: true, clientCredentials: true, }, scopes: [OAuthScope.PHONE], }, })).toThrow(/clientCredentials OAuth flow cannot be selected/); expect(() => pool.addClient('Client2', { oAuth: { flows: { implicitCodeGrant: true, clientCredentials: true, }, scopes: [OAuthScope.PHONE], }, })).toThrow(/clientCredentials OAuth flow cannot be selected/); }); test('OAuth scopes', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client', { oAuth: { flows: { clientCredentials: true }, scopes: [ OAuthScope.PHONE, OAuthScope.EMAIL, OAuthScope.OPENID, OAuthScope.PROFILE, OAuthScope.COGNITO_ADMIN, OAuthScope.custom('my-resource-server/my-own-scope'), ], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthScopes: [ 'phone', 'email', 'openid', 'profile', 'aws.cognito.signin.user.admin', 'my-resource-server/my-own-scope', ], }); }); test('OAuth scopes - resource server', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); const scope = new ResourceServerScope({ scopeName: 'scope-name', scopeDescription: 'scope-desc' }); const resourceServer = pool.addResourceServer('ResourceServer', { identifier: 'resource-server', scopes: [scope], }); // WHEN pool.addClient('Client', { oAuth: { flows: { clientCredentials: true }, scopes: [ OAuthScope.resourceServer(resourceServer, scope), ], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { AllowedOAuthScopes: [ { 'Fn::Join': [ '', [ stack.resolve(resourceServer.userPoolResourceServerId), '/scope-name', ], ], }, ], }); }); test('OAuthScope - openid is included when email or phone is specified', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', oAuth: { flows: { clientCredentials: true }, scopes: [OAuthScope.PHONE], }, }); pool.addClient('Client2', { userPoolClientName: 'Client2', oAuth: { flows: { clientCredentials: true }, scopes: [OAuthScope.EMAIL], }, }); pool.addClient('Client3', { userPoolClientName: 'Client3', oAuth: { flows: { clientCredentials: true }, scopes: [OAuthScope.PROFILE], }, }); pool.addClient('Client4', { userPoolClientName: 'Client4', oAuth: { flows: { clientCredentials: true }, scopes: [OAuthScope.COGNITO_ADMIN], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', AllowedOAuthScopes: ['phone', 'openid'], }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client2', AllowedOAuthScopes: ['email', 'openid'], }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client3', AllowedOAuthScopes: ['profile', 'openid'], }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client4', AllowedOAuthScopes: ['aws.cognito.signin.user.admin'], }); }); test('enable user existence errors prevention', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'Client', { userPool: pool, preventUserExistenceErrors: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { UserPoolId: stack.resolve(pool.userPoolId), PreventUserExistenceErrors: 'ENABLED', }); }); test('disable user existence errors prevention', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'Client', { userPool: pool, preventUserExistenceErrors: false, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { UserPoolId: stack.resolve(pool.userPoolId), PreventUserExistenceErrors: 'LEGACY', }); }); test('user existence errors prevention is absent by default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'Client', { userPool: pool, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { UserPoolId: stack.resolve(pool.userPoolId), PreventUserExistenceErrors: Match.absent(), }); }); test('default supportedIdentityProviders', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); const idp = UserPoolIdentityProvider.fromProviderName(stack, 'imported', 'userpool-idp'); pool.registerIdentityProvider(idp); // WHEN new UserPoolClient(stack, 'Client', { userPool: pool, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { SupportedIdentityProviders: [ 'userpool-idp', 'COGNITO', ], }); }); test('supportedIdentityProviders', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('AllEnabled', { userPoolClientName: 'AllEnabled', supportedIdentityProviders: [ UserPoolClientIdentityProvider.COGNITO, UserPoolClientIdentityProvider.FACEBOOK, UserPoolClientIdentityProvider.AMAZON, UserPoolClientIdentityProvider.GOOGLE, UserPoolClientIdentityProvider.APPLE, ], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'AllEnabled', SupportedIdentityProviders: ['COGNITO', 'Facebook', 'LoginWithAmazon', 'Google', 'SignInWithApple'], }); }); test('disableOAuth', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('OAuthDisabled', { userPoolClientName: 'OAuthDisabled', disableOAuth: true, }); pool.addClient('OAuthEnabled', { userPoolClientName: 'OAuthEnabled', disableOAuth: false, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'OAuthDisabled', AllowedOAuthFlows: Match.absent(), AllowedOAuthScopes: Match.absent(), AllowedOAuthFlowsUserPoolClient: false, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'OAuthEnabled', AllowedOAuthFlows: ['implicit', 'code'], AllowedOAuthScopes: ['profile', 'phone', 'email', 'openid', 'aws.cognito.signin.user.admin'], AllowedOAuthFlowsUserPoolClient: true, }); }); test('fails when oAuth is specified but is disableOAuth is set', () => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => pool.addClient('Client', { disableOAuth: true, oAuth: { flows: { authorizationCodeGrant: true, }, }, })).toThrow(/disableOAuth is set/); }); test('EnableTokenRevocation is absent by default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client'); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { EnableTokenRevocation: Match.absent(), }); }); test('enableTokenRevocation in addClient', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client', { enableTokenRevocation: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { EnableTokenRevocation: true, }); }); test('enableTokenRevocation in UserPoolClient', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN new UserPoolClient(stack, 'Client1', { userPool: pool, enableTokenRevocation: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { EnableTokenRevocation: true, }); }); describe('token validity', () => { test('default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', accessTokenValidity: Duration.minutes(60), idTokenValidity: Duration.minutes(60), refreshTokenValidity: Duration.days(30), }); pool.addClient('Client2', { userPoolClientName: 'Client2', accessTokenValidity: Duration.minutes(60), }); pool.addClient('Client3', { userPoolClientName: 'Client3', idTokenValidity: Duration.minutes(60), }); pool.addClient('Client4', { userPoolClientName: 'Client4', refreshTokenValidity: Duration.days(30), }); pool.addClient('Client5', { userPoolClientName: 'Client5', }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', AccessTokenValidity: 60, IdTokenValidity: 60, RefreshTokenValidity: 43200, TokenValidityUnits: { AccessToken: 'minutes', IdToken: 'minutes', RefreshToken: 'minutes', }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client2', AccessTokenValidity: 60, IdTokenValidity: Match.absent(), RefreshTokenValidity: Match.absent(), TokenValidityUnits: { AccessToken: 'minutes', IdToken: Match.absent(), RefreshToken: Match.absent(), }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client3', AccessTokenValidity: Match.absent(), IdTokenValidity: 60, RefreshTokenValidity: Match.absent(), TokenValidityUnits: { AccessToken: Match.absent(), IdToken: 'minutes', RefreshToken: Match.absent(), }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client4', AccessTokenValidity: Match.absent(), IdTokenValidity: Match.absent(), RefreshTokenValidity: 43200, TokenValidityUnits: { AccessToken: Match.absent(), IdToken: Match.absent(), RefreshToken: 'minutes', }, }); Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client5', TokenValidityUnits: Match.absent(), IdTokenValidity: Match.absent(), RefreshTokenValidity: Match.absent(), AccessTokenValidity: Match.absent(), }); }); test.each([ Duration.minutes(0), Duration.minutes(4), Duration.days(1).plus(Duration.minutes(1)), Duration.days(2), ])('validates accessTokenValidity is a duration between 5 minutes and 1 day', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => { pool.addClient('Client1', { userPoolClientName: 'Client1', accessTokenValidity: validity, }); }).toThrow(`accessTokenValidity: Must be a duration between 5 minutes and 1 day (inclusive); received ${validity.toHumanString()}.`); }); test.each([ Duration.minutes(0), Duration.minutes(4), Duration.days(1).plus(Duration.minutes(1)), Duration.days(2), ])('validates idTokenValidity is a duration between 5 minutes and 1 day', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => { pool.addClient('Client1', { userPoolClientName: 'Client1', idTokenValidity: validity, }); }).toThrow(`idTokenValidity: Must be a duration between 5 minutes and 1 day (inclusive); received ${validity.toHumanString()}.`); }); test.each([ Duration.hours(1).plus(Duration.minutes(1)), Duration.hours(12), Duration.days(1), ])('validates accessTokenValidity is not greater than refresh token expiration', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => { pool.addClient('Client1', { userPoolClientName: 'Client1', accessTokenValidity: validity, refreshTokenValidity: Duration.hours(1), }); }).toThrow(`accessTokenValidity: Must be a duration between 5 minutes and 1 hour (inclusive); received ${validity.toHumanString()}.`); }); test.each([ Duration.hours(1).plus(Duration.minutes(1)), Duration.hours(12), Duration.days(1), ])('validates idTokenValidity is not greater than refresh token expiration', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => { pool.addClient('Client1', { userPoolClientName: 'Client1', idTokenValidity: validity, refreshTokenValidity: Duration.hours(1), }); }).toThrow(`idTokenValidity: Must be a duration between 5 minutes and 1 hour (inclusive); received ${validity.toHumanString()}.`); }); test.each([ Duration.minutes(0), Duration.minutes(59), Duration.days(10 * 365).plus(Duration.minutes(1)), Duration.days(10 * 365 + 1), ])('validates refreshTokenValidity is a duration between 1 hour and 10 years', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); expect(() => { pool.addClient('Client1', { userPoolClientName: 'Client1', refreshTokenValidity: validity, }); }).toThrow(`refreshTokenValidity: Must be a duration between 1 hour and 3650 days (inclusive); received ${validity.toHumanString()}.`); }); test.each([ Duration.minutes(5), Duration.minutes(60), Duration.days(1), ])('validates accessTokenValidity is a duration between 5 minutes and 1 day (valid)', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', accessTokenValidity: validity, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', AccessTokenValidity: validity.toMinutes(), TokenValidityUnits: { AccessToken: 'minutes', }, }); }); test.each([ Duration.minutes(5), Duration.minutes(60), Duration.days(1), ])('validates idTokenValidity is a duration between 5 minutes and 1 day (valid)', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', idTokenValidity: validity, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', IdTokenValidity: validity.toMinutes(), TokenValidityUnits: { IdToken: 'minutes', }, }); }); test.each([ Duration.minutes(60), Duration.minutes(120), Duration.days(365), Duration.days(10 * 365), ])('validates refreshTokenValidity is a duration between 1 hour and 10 years (valid)', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', refreshTokenValidity: validity, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', RefreshTokenValidity: validity.toMinutes(), TokenValidityUnits: { RefreshToken: 'minutes', }, }); }); test.each([ Duration.minutes(5), Duration.minutes(60), Duration.hours(1), ])('validates accessTokenValidity is not greater than refresh token expiration (valid)', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', accessTokenValidity: validity, refreshTokenValidity: Duration.hours(1), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', AccessTokenValidity: validity.toMinutes(), TokenValidityUnits: { AccessToken: 'minutes', }, }); }); test.each([ Duration.minutes(5), Duration.minutes(60), Duration.hours(1), ])('validates idTokenValidity is not greater than refresh token expiration (valid)', (validity) => { const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client1', { userPoolClientName: 'Client1', idTokenValidity: validity, refreshTokenValidity: Duration.hours(1), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ClientName: 'Client1', IdTokenValidity: validity.toMinutes(), TokenValidityUnits: { IdToken: 'minutes', }, }); }); }); describe('read and write attributes', () => { test('undefined by default', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); // WHEN pool.addClient('Client', {}); // EXPECT Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ReadAttributes: Match.absent(), WriteAttributes: Match.absent(), }); }); test('set attributes', () => { // GIVEN const stack = new Stack(); const pool = new UserPool(stack, 'Pool'); const writeAttributes = (new ClientAttributes()).withCustomAttributes('my_first').withStandardAttributes({ givenName: true, familyName: true }); const readAttributes = (new ClientAttributes()).withStandardAttributes({ address: true, birthdate: true, email: true, emailVerified: true, familyName: true, fullname: true, gender: true, givenName: true, lastUpdateTime: true, locale: true, middleName: true, nickname: true, phoneNumber: true, phoneNumberVerified: true, preferredUsername: true, profilePage: true, profilePicture: true, timezone: true, website: true, }); // WHEN pool.addClient('Client', { readAttributes, writeAttributes, }); // EXPECT Template.fromStack(stack).hasResourceProperties('AWS::Cognito::UserPoolClient', { ReadAttributes: Match.arrayWith(['address', 'birthdate', 'email', 'email_verified', 'family_name', 'gender', 'given_name', 'locale', 'middle_name', 'name', 'nickname', 'phone_number', 'phone_number_verified', 'picture', 'preferred_username', 'profile', 'updated_at', 'website', 'zoneinfo']), WriteAttributes: Match.arrayWith(['custom:my_first', 'family_name', 'given_name']), }); }); }); });
the_stack
import {join} from 'path'; import variables from '../variables.js'; import Context from './Context.js'; import ErrorWithMetadata from './ErrorWithMetadata.js'; import {root} from './index.js'; import {debug, log, setLogLevel} from './console.js'; import dedent from './dedent.js'; import getOptions from './getOptions.js'; import merge from './merge.js'; import path from './path.js'; import prompt from './prompt.js'; import readAspect from './readAspect.js'; import readProject from './readProject.js'; import regExpFromString from './regExpFromString.js'; import stringify from './stringify.js'; import test from './test.js'; import type {Aspect} from './types/Project.js'; async function main() { const start = Date.now(); if (Context.attributes.uid === 0) { if (!process.env.YOLO) { throw new ErrorWithMetadata('Refusing to run as root unless YOLO is set'); } } // Skip first two args (node executable and main.js script). const options = await getOptions(process.argv.slice(2)); setLogLevel(options.logLevel); debug(() => { log.debug('process.argv:\n\n' + stringify(process.argv) + '\n'); log.debug('getOptions():\n\n' + stringify(options) + '\n'); }); if (process.cwd() === root) { log.info(`Working from root: ${path(root).simplify}`); } else { log.notice(`Changing to root: ${path(root).simplify}`); process.chdir(root); } log.info('Running tests'); await test(); if (options.testsOnly) { return; } const project = await readProject(join(root, 'project.json')); const hostname = Context.attributes.hostname; const profiles = project.profiles ?? {}; const [profile] = Object.entries(profiles).find(([, {pattern}]) => regExpFromString(pattern).test(hostname) ) || []; log.info(`Profile: ${profile || 'n/a'}`); log.debug(`Profiles:\n\n${stringify(profiles)}\n`); const profileVariables: {[key: string]: JSONValue} = profile ? profiles[profile]!.variables ?? {} : {}; const {distribution, platform} = Context.attributes; log.info(`Platform: ${platform}`); const platformVariant: | `${typeof platform}.${Exclude<typeof distribution, ''>}` | typeof platform = distribution ? `${platform}.${distribution}` : platform; const {aspects, variables: platformVariables = {}} = project.platforms[ platformVariant ] || project.platforms[platform] || {aspects: []}; // Register tasks. const candidateTasks = []; for (const aspect of aspects) { await loadAspect(aspect); if (options.focused.size && !options.focused.has(aspect)) { continue; } // Check for an exact match of the starting task if `--start-at-task=` was // supplied. for (const [, name] of Context.tasks.get(aspect)) { if (name === options.startAt.literal) { options.startAt.found = true; } else if ( !options.startAt.found && options.startAt.fuzzy && options.startAt.fuzzy.test(name) ) { candidateTasks.push(name); } } } if (!options.startAt.found && candidateTasks.length === 1) { log.notice(`Matching task found: ${candidateTasks[0]}`); log(); if (await prompt.confirm('Start running at this task')) { options.startAt.found = true; options.startAt.literal = candidateTasks[0]; } else { throw new ErrorWithMetadata('User aborted'); } } else if (!options.startAt.found && candidateTasks.length > 1) { log.notice(`${candidateTasks.length} tasks found:\n`); const width = candidateTasks.length.toString().length; while (!options.startAt.found) { candidateTasks.forEach((name, i) => { log(`${(i + 1).toString().padStart(width)}: ${name}`); }); log(); const reply = await prompt('Start at task number: '); const choice = parseInt(reply.trim(), 10); if ( Number.isNaN(choice) || choice < 1 || choice > candidateTasks.length ) { log.warn( `Invalid choice ${stringify( reply )}; try again or press CTRL-C to abort.` ); log(); } else { options.startAt.found = true; options.startAt.literal = candidateTasks[choice - 1]; } } } else if (!options.startAt.found && options.startAt.literal) { throw new ErrorWithMetadata( `Failed to find task matching ${stringify(options.startAt.literal)}` ); } const attributeVariables = { home: Context.attributes.home, hostname: Context.attributes.hostname, platform: Context.attributes.platform, username: Context.attributes.username, }; const defaultVariables = project.variables ?? {}; const baseVariables = merge( {profile: profile || null}, attributeVariables, defaultVariables, profileVariables, platformVariables, variables ); // Execute tasks. try { loopAspects: { for (const aspect of aspects) { const {variables: aspectVariables = {}} = await readAspect( join(root, 'aspects', aspect) ); if (options.focused.size && !options.focused.has(aspect)) { log.info(`Skipping aspect: ${aspect}`); continue; } const mergedVariables = merge(baseVariables, aspectVariables); const variables = merge( mergedVariables, Context.variables.get(aspect)(mergedVariables) ); log.debug(`Variables:\n\n${stringify(variables)}\n`); for (const [callback, name] of Context.tasks.get(aspect)) { if (!options.startAt.found || name === options.startAt.literal) { options.startAt.found = false; log.notice(`Task: ${name}`); if (options.step) { for (;;) { const reply = ( await prompt( `Run task ${name}? [y]es/[n]o/[q]uit]/[c]ontinue/[h]elp: ` ) ) .toLowerCase() .trim(); if ('yes'.startsWith(reply)) { await Context.withContext( { aspect, options, task: name, variables, }, callback ); break; } else if ('no'.startsWith(reply)) { Context.informSkipped(`task ${name}`); break; } else if ('quit'.startsWith(reply)) { break loopAspects; } else if ('continue'.startsWith(reply)) { options.step = false; await Context.withContext( { aspect, options, task: name, variables, }, callback ); break; } else if ('help'.startsWith(reply)) { log( dedent` [y]es: run the task [n]o: skip the task [q]uit: stop running [c]ontinue: run all remaining tasks ` ); } else { log.warn('Invalid choice; try again.'); } } } else { await Context.withContext( {aspect, options, task: name, variables}, callback ); } } } const {callbacks, notifications} = Context.handlers.get(aspect); for (const [callback, name] of callbacks) { if (!options.startAt.found) { log.notice(`Handler: ${name}`); if (notifications.has(name)) { if (options.step) { // TODO: DRY up -- almost same as task handling // above for (;;) { const reply = ( await prompt( `Run handler ${name}? [y]es/[n]o/[q]uit]/[c]ontinue/[h]elp: ` ) ) .toLowerCase() .trim(); if ('yes'.startsWith(reply)) { await Context.withContext( { aspect, options, task: name, variables, }, callback ); break; } else if ('no'.startsWith(reply)) { Context.informSkipped(`task ${name}`); break; } else if ('quit'.startsWith(reply)) { break loopAspects; } else if ('continue'.startsWith(reply)) { options.step = false; await Context.withContext( { aspect, options, task: name, variables, }, callback ); break; } else if ('help'.startsWith(reply)) { log( dedent` [y]es: run the handler [n]o: skip the handler [q]uit: stop running [c]ontinue: run all remaining handlers and tasks ` ); } else { log.warn('Invalid choice; try again.'); } } } else { await Context.withContext( {aspect, options, task: name, variables}, callback ); } } else { Context.informSkipped(`handler ${name}`); } } } } } } finally { const counts = Object.entries(Context.counts) .map(([name, count]) => { return `${name}=${count}`; }) .join(' '); const elapsed = msToHumanReadable(Date.now() - start); log.notice(`Summary: ${counts} elapsed=${elapsed}`); } } /** * Turns `ms` into a human readble string like "1m2s" or "33.2s". * * Doesn't deal with timescales beyond "minutes" because we don't expect to see * those. If we did, it would just return (something like) "125m20s". */ function msToHumanReadable(ms: number): string { let seconds = ms / 1000; const minutes = Math.floor(seconds / 60); if (minutes) { seconds = Math.floor(seconds - minutes * 60); } let result = minutes ? `${minutes}m` : ''; result += seconds ? seconds.toFixed(2).toString().replace(/0+$/, '').replace(/\.$/, '') + 's' : ''; return result; } async function loadAspect(aspect: Aspect): Promise<void> { switch (aspect) { case 'apt': await import('../aspects/apt/index.js'); break; case 'aur': await import('../aspects/aur/index.js'); break; case 'automator': await import('../aspects/automator/index.js'); break; case 'automount': await import('../aspects/automount/index.js'); break; case 'avahi': await import('../aspects/avahi/index.js'); break; case 'backup': await import('../aspects/backup/index.js'); break; case 'codespaces': await import('../aspects/codespaces/index.js'); break; case 'cron': await import('../aspects/cron/index.js'); break; case 'defaults': await import('../aspects/defaults/index.js'); break; case 'dotfiles': await import('../aspects/dotfiles/index.js'); break; case 'fonts': await import('../aspects/fonts/index.js'); break; case 'homebrew': await import('../aspects/homebrew/index.js'); break; case 'interception': await import('../aspects/interception/index.js'); break; case 'iterm': await import('../aspects/iterm/index.js'); break; case 'karabiner': await import('../aspects/karabiner/index.js'); break; case 'launchd': await import('../aspects/launchd/index.js'); break; case 'locale': await import('../aspects/locale/index.js'); break; case 'meta': await import('../aspects/meta/index.js'); break; case 'node': await import('../aspects/node/index.js'); break; case 'pacman': await import('../aspects/pacman/index.js'); break; case 'ruby': await import('../aspects/ruby/index.js'); break; case 'shell': await import('../aspects/shell/index.js'); break; case 'ssh': await import('../aspects/ssh/index.js'); break; case 'sshd': await import('../aspects/sshd/index.js'); break; case 'systemd': await import('../aspects/systemd/index.js'); break; case 'tampermonkey': await import('../aspects/tampermonkey/index.js'); break; case 'terminfo': await import('../aspects/terminfo/index.js'); break; case 'nvim': await import('../aspects/nvim/index.js'); break; default: const unreachable: never = aspect; throw new Error(`Unreachable ${unreachable}`); } } main().catch((error) => { if (error instanceof ErrorWithMetadata) { if (error.metadata) { log.error(`${error.message}\n\n${stringify(error.metadata)}\n`); } else { log.error(error.message); } } else { log.error(error.toString()); } log.debug(String(error.stack)); process.exit(1); });
the_stack
import { GraphQLSchema, GraphQLCompositeType, GraphQLField, FieldNode, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, ASTNode, Kind, NameNode, visit, print, DirectiveNode, SelectionSetNode, DirectiveDefinitionNode, isObjectType, isInterfaceType, isUnionType, FragmentDefinitionNode, InlineFragmentNode, } from "graphql"; import { ExecutionContext } from "graphql/execution/execute"; export function isNode(maybeNode: any): maybeNode is ASTNode { return maybeNode && typeof maybeNode.kind === "string"; } export type NamedNode = ASTNode & { name: NameNode; }; export function isNamedNode(node: ASTNode): node is NamedNode { return "name" in node; } export function isDirectiveDefinitionNode( node: ASTNode ): node is DirectiveDefinitionNode { return node.kind === Kind.DIRECTIVE_DEFINITION; } export function highlightNodeForNode(node: ASTNode): ASTNode { switch (node.kind) { case Kind.VARIABLE_DEFINITION: return node.variable; default: return isNamedNode(node) ? node.name : node; } } /** * Not exactly the same as the executor's definition of getFieldDef, in this * statically evaluated environment we do not always have an Object type, * and need to handle Interface and Union types. */ export function getFieldDef( schema: GraphQLSchema, parentType: GraphQLCompositeType, fieldAST: FieldNode ): GraphQLField<any, any> | undefined { const name = fieldAST.name.value; if ( name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType ) { return SchemaMetaFieldDef; } if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { return TypeMetaFieldDef; } if ( name === TypeNameMetaFieldDef.name && (isObjectType(parentType) || isInterfaceType(parentType) || isUnionType(parentType)) ) { return TypeNameMetaFieldDef; } if (isObjectType(parentType) || isInterfaceType(parentType)) { return parentType.getFields()[name]; } return undefined; } /** * Remove specific directives * * The `ast` param must extend ASTNode. We use a generic to indicate that this function returns the same type * of it's first parameter. */ export function removeDirectives<AST extends ASTNode>( ast: AST, directiveNames: string[] ): AST { if (!directiveNames.length) return ast; return visit(ast, { Directive(node: DirectiveNode): DirectiveNode | null { if (!!directiveNames.find((name) => name === node.name.value)) return null; return node; }, }); } /** * Recursively remove orphaned fragment definitions that have their names included in * `fragmentNamesEligibleForRemoval` * * We expclitily require the fragments to be listed in `fragmentNamesEligibleForRemoval` so we only strip * fragments that were orphaned by an operation, not fragments that started as oprhans * * The `ast` param must extend ASTNode. We use a generic to indicate that this function returns the same type * of it's first parameter. */ function removeOrphanedFragmentDefinitions<AST extends ASTNode>( ast: AST, fragmentNamesEligibleForRemoval: Set<string> ): AST { /** * Flag to keep track of removing any fragments */ let anyFragmentsRemoved = false; // Aquire names of all fragment spreads const fragmentSpreadNodeNames = new Set<string>(); visit(ast, { FragmentSpread(node) { fragmentSpreadNodeNames.add(node.name.value); }, }); // Strip unused fragment definitions. Flag if we've removed any so we know if we need to continue // recursively checking. ast = visit(ast, { FragmentDefinition(node) { if ( fragmentNamesEligibleForRemoval.has(node.name.value) && !fragmentSpreadNodeNames.has(node.name.value) ) { // This definition is not used, remove it. anyFragmentsRemoved = true; return null; } return undefined; }, }); if (anyFragmentsRemoved) { /* Handles the special case where a Fragment was not removed because it was not yet orphaned when being `visit`ed. As an example: ```jsx fragment Two on Node { id } fragment One on Query { hero { ...Two @client } } { ...One } ``` On the first visit, `Two` will not be removed. After `One` is removed, `Two` becomes orphaned. If any nodes were removed on this pass; run another pass to see if there are more nodes that are now orphaned. */ return removeOrphanedFragmentDefinitions( ast, fragmentNamesEligibleForRemoval ); } return ast; } /** * Remove nodes that have zero-length selection sets * * The `ast` param must extend ASTNode. We use a generic to indicate that this function returns the same type * of it's first parameter. */ function removeNodesWithEmptySelectionSets<AST extends ASTNode>(ast: AST): AST { ast = visit(ast, { enter(node) { // If this node _has_ a `selectionSet` and it's zero-length, then remove it. return "selectionSet" in node && node.selectionSet != null && node.selectionSet.selections.length === 0 ? null : undefined; }, }); return ast; } /** * Remove nodes from `ast` when they have a directive in `directiveNames` * * The `ast` param must extend ASTNode. We use a generic to indicate that this function returns the same type * of it's first parameter. */ export function removeDirectiveAnnotatedFields<AST extends ASTNode>( ast: AST, directiveNames: string[] ): AST { print; if (!directiveNames.length) return ast; /** * All fragment definition names we've removed due to a matching directive * * We keep track of these so we can remove associated spreads */ const removedFragmentDefinitionNames = new Set<string>(); /** * All fragment spreads that have been removed * * We can only remove fragment definitions for fragment spreads that we've removed */ const removedFragmentSpreadNames = new Set<string>(); // Remove all nodes with a matching directive in `directiveNames`. Also, remove any operations that now have // no selection set ast = visit(ast, { enter(node) { // Strip all nodes that contain a directive we wish to remove if ( "directives" in node && node.directives && node.directives.find((directive) => directiveNames.includes(directive.name.value) ) ) { /* If we're removing a fragment definition then save the name so we can remove anywhere this fragment was spread. This happens when a fragment definition itself has a matching directive on it, like this (assuming that `@client` is a directive we want to remove): ```graphql fragment SomeFragmentDefinition on SomeType @client { fields } ``` */ if (node.kind === Kind.FRAGMENT_DEFINITION) { removedFragmentDefinitionNames.add(node.name.value); } /* This node is going to be removed. Mark all fragment spreads nested under this node as eligible for removal from the document. For example, assuming `@client` is a directive we want to remove: ```graphql clientObject @client { ...ClientObjectFragment } ``` We're going to remove `clientObject` here, which will also remove `ClientObjectFragment`. If there are no other instances of `ClientObjectFragment`, we're goign to remove it's definition as well. We only remove definitions for spreads we've removed so we don't remove fragment definitions that were never spread; as this is the kind of error `client:check` is inteded to flag. */ visit(node, { FragmentSpread(node) { removedFragmentSpreadNames.add(node.name.value); }, }); // Remove this node return null; } return undefined; }, }); // For all fragment definitions we removed, also remove the fragment spreads ast = visit(ast, { FragmentSpread(node) { if (removedFragmentDefinitionNames.has(node.name.value)) { removedFragmentSpreadNames.add(node.name.value); return null; } return undefined; }, }); // Remove all orphaned fragment definitions ast = removeOrphanedFragmentDefinitions(ast, removedFragmentSpreadNames); // Finally, remove nodes with empty selection sets return removeNodesWithEmptySelectionSets(ast); } const typenameField = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: "__typename" }, }; export function withTypenameFieldAddedWhereNeeded(ast: ASTNode) { return visit(ast, { enter: { SelectionSet(node: SelectionSetNode) { return { ...node, selections: node.selections.filter( (selection) => !( selection.kind === "Field" && selection.name.value === "__typename" ) ), }; }, }, leave(node: ASTNode) { if ( !( node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_DEFINITION || node.kind === Kind.INLINE_FRAGMENT ) ) { return undefined; } if (!node.selectionSet) return undefined; return { ...node, selectionSet: { ...node.selectionSet, selections: [typenameField, ...node.selectionSet.selections], }, }; }, }); } function getFieldEntryKey(node: FieldNode): string { return node.alias ? node.alias.value : node.name.value; } // this is a simplified verison of the collect fields algorithm that the // reference implementation uses during execution // in this case, we don't care about boolean conditions of validating the // type conditions as other validation has done that already export function simpleCollectFields( context: ExecutionContext, selectionSet: SelectionSetNode, fields: Record<string, FieldNode[]>, visitedFragmentNames: Record<string, boolean> ): Record<string, FieldNode[]> { for (const selection of selectionSet.selections) { switch (selection.kind) { case Kind.FIELD: { const name = getFieldEntryKey(selection); if (!fields[name]) { fields[name] = []; } fields[name].push(selection); break; } case Kind.INLINE_FRAGMENT: { simpleCollectFields( context, selection.selectionSet, fields, visitedFragmentNames ); break; } case Kind.FRAGMENT_SPREAD: { const fragName = selection.name.value; if (visitedFragmentNames[fragName]) continue; visitedFragmentNames[fragName] = true; const fragment = context.fragments[fragName]; if (!fragment) continue; simpleCollectFields( context, fragment.selectionSet, fields, visitedFragmentNames ); break; } } } return fields; } export function hasClientDirective( node: FieldNode | InlineFragmentNode | FragmentDefinitionNode ) { return ( node.directives && node.directives.some((directive) => directive.name.value === "client") ); } export interface ClientSchemaInfo { localFields?: string[]; } declare module "graphql/type/definition" { interface GraphQLScalarType { clientSchema?: ClientSchemaInfo; } interface GraphQLObjectType { clientSchema?: ClientSchemaInfo; } interface GraphQLInterfaceType { clientSchema?: ClientSchemaInfo; } interface GraphQLUnionType { clientSchema?: ClientSchemaInfo; } interface GraphQLEnumType { clientSchema?: ClientSchemaInfo; } }
the_stack
export default (runbookUrl: string, grafanaUrl: string) => [ { name: "node-exporter", rules: [ { alert: "NodeFilesystemSpaceFillingUp", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available space left and is filling\nup.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemspacefillingup", summary: "Filesystem is predicted to run out of space within the next 24 hours." }, expr: '(\n node_filesystem_avail_bytes{job="node-exporter",} / node_filesystem_size_bytes{job="node-exporter",} < 0.4\nand\n predict_linear(node_filesystem_avail_bytes{job="node-exporter",}[6h], 24*60*60) < 0\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "warning" } }, { alert: "NodeFilesystemSpaceFillingUp", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available space left and is filling\nup fast.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemspacefillingup", summary: "Filesystem is predicted to run out of space within the next 4 hours." }, expr: '(\n node_filesystem_avail_bytes{job="node-exporter",} / node_filesystem_size_bytes{job="node-exporter",} < 0.2\nand\n predict_linear(node_filesystem_avail_bytes{job="node-exporter",}[6h], 4*60*60) < 0\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "critical" } }, { alert: "NodeFilesystemAlmostOutOfSpace", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available space left.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemalmostoutofspace", summary: "Filesystem has less than 5% space left." }, expr: '(\n node_filesystem_avail_bytes{job="node-exporter",} / node_filesystem_size_bytes{job="node-exporter",} * 100 < 5\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "warning" } }, { alert: "NodeFilesystemAlmostOutOfSpace", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available space left.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemalmostoutofspace", summary: "Filesystem has less than 3% space left." }, expr: '(\n node_filesystem_avail_bytes{job="node-exporter",} / node_filesystem_size_bytes{job="node-exporter",} * 100 < 3\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "critical" } }, { alert: "NodeFilesystemFilesFillingUp", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available inodes left and is filling\nup.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemfilesfillingup", summary: "Filesystem is predicted to run out of inodes within the next 24 hours." }, expr: '(\n node_filesystem_files_free{job="node-exporter",} / node_filesystem_files{job="node-exporter",} < 0.4\nand\n predict_linear(node_filesystem_files_free{job="node-exporter",}[6h], 24*60*60) < 0\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "warning" } }, { alert: "NodeFilesystemFilesFillingUp", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available inodes left and is filling\nup fast.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemfilesfillingup", summary: "Filesystem is predicted to run out of inodes within the next 4 hours." }, expr: '(\n node_filesystem_files_free{job="node-exporter",} / node_filesystem_files{job="node-exporter",} < 0.2\nand\n predict_linear(node_filesystem_files_free{job="node-exporter",}[6h], 4*60*60) < 0\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "critical" } }, { alert: "NodeFilesystemAlmostOutOfFiles", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available inodes left.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemalmostoutoffiles", summary: "Filesystem has less than 5% inodes left." }, expr: '(\n node_filesystem_files_free{job="node-exporter",} / node_filesystem_files{job="node-exporter",} * 100 < 5\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "warning" } }, { alert: "NodeFilesystemAlmostOutOfFiles", annotations: { description: 'Filesystem on {{ $labels.device }} at {{ $labels.instance }}\nhas only {{ printf "%.2f" $value }}% available inodes left.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodefilesystemalmostoutoffiles", summary: "Filesystem has less than 3% inodes left." }, expr: '(\n node_filesystem_files_free{job="node-exporter",} / node_filesystem_files{job="node-exporter",} * 100 < 3\nand\n node_filesystem_readonly{job="node-exporter",} == 0\n)\n', for: "1h", labels: { severity: "critical" } }, { alert: "NodeNetworkReceiveErrs", annotations: { description: '{{ $labels.instance }} interface {{ $labels.device }} has encountered\n{{ printf "%.0f" $value }} receive errors in the last two minutes.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodenetworkreceiveerrs", summary: "Network interface is reporting many receive errors." }, expr: "increase(node_network_receive_errs_total[2m]) > 10\n", for: "1h", labels: { severity: "warning" } }, { alert: "NodeNetworkTransmitErrs", annotations: { description: '{{ $labels.instance }} interface {{ $labels.device }} has encountered\n{{ printf "%.0f" $value }} transmit errors in the last two minutes.', // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodenetworktransmiterrs", summary: "Network interface is reporting many transmit errors." }, expr: "increase(node_network_transmit_errs_total[2m]) > 10\n", for: "1h", labels: { severity: "warning" } } ] }, { name: "kubernetes-absent", rules: [ { alert: "KubeAPIDown", annotations: { message: "KubeAPI has disappeared from Prometheus target discovery." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapidown" }, expr: 'absent(up{job="apiserver"} == 1)\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeStateMetricsDown", annotations: { message: "KubeStateMetrics has disappeared from Prometheus target discovery." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubestatemetricsdown" }, expr: 'absent(up{job="kube-state-metrics"} == 1)\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeletDown", annotations: { message: "Kubelet has disappeared from Prometheus target discovery." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeletdown" }, expr: 'absent(up{job="kubelet"} == 1)\n', for: "15m", labels: { severity: "critical" } }, { alert: "NodeExporterDown", annotations: { message: "NodeExporter has disappeared from Prometheus target discovery." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-nodeexporterdown" }, expr: 'absent(up{job="node-exporter"} == 1)\n', for: "15m", labels: { severity: "critical" } } ] }, { name: "kubernetes-apps", rules: [ { alert: "KubePodCrashLooping", annotations: { message: 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is restarting {{ printf "%.2f" $value }} times / 5 minutes.' // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubepodcrashlooping" }, expr: 'rate(kube_pod_container_status_restarts_total{job="kube-state-metrics"}[15m]) * 60 * 5 > 0\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubePodNotReady", annotations: { message: "Pod {{ $labels.namespace }}/{{ $labels.pod }} has been in a non-ready\nstate for longer than 15 minutes." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubepodnotready" }, expr: 'sum by (namespace, pod) (kube_pod_status_phase{job="kube-state-metrics", phase=~"Failed|Pending|Unknown"}, pod!="opstrace-controller-*") > 0\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeDeploymentGenerationMismatch", annotations: { message: "Deployment generation for {{ $labels.namespace }}/{{ $labels.deployment }} does not match, this indicates that the Deployment has failed but has not been rolled back." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubedeploymentgenerationmismatch" }, expr: 'kube_deployment_status_observed_generation{job="kube-state-metrics"}\n !=\nkube_deployment_metadata_generation{job="kube-state-metrics"}\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeDeploymentReplicasMismatch", annotations: { message: "Deployment {{ $labels.namespace }}/{{ $labels.deployment }} has not\nmatched the expected number of replicas for longer than 15 minutes." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubedeploymentreplicasmismatch" }, expr: 'kube_deployment_spec_replicas{job="kube-state-metrics"}\n !=\nkube_deployment_status_replicas_available{job="kube-state-metrics"}\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeStatefulSetReplicasMismatch", annotations: { message: "StatefulSet {{ $labels.namespace }}/{{ $labels.statefulset }} has\nnot matched the expected number of replicas for longer than 15 minutes." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubestatefulsetreplicasmismatch" }, expr: 'kube_statefulset_status_replicas_ready{job="kube-state-metrics"}\n !=\nkube_statefulset_status_replicas{job="kube-state-metrics"}\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeStatefulSetGenerationMismatch", annotations: { message: "StatefulSet generation for {{ $labels.namespace }}/{{ $labels.statefulset }} does not match, this indicates that the StatefulSet has failed but has not been rolled back." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubestatefulsetgenerationmismatch" }, expr: 'kube_statefulset_status_observed_generation{job="kube-state-metrics"}\n !=\nkube_statefulset_metadata_generation{job="kube-state-metrics"}\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeStatefulSetUpdateNotRolledOut", annotations: { message: "StatefulSet {{ $labels.namespace }}/{{ $labels.statefulset }} update\nhas not been rolled out." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubestatefulsetupdatenotrolledout" }, expr: 'max without (revision) (\n kube_statefulset_status_current_revision{job="kube-state-metrics"}\n unless\n kube_statefulset_status_update_revision{job="kube-state-metrics"}\n)\n *\n(\n kube_statefulset_replicas{job="kube-state-metrics"}\n !=\n kube_statefulset_status_replicas_updated{job="kube-state-metrics"}\n)\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeDaemonSetRolloutStuck", annotations: { message: "Only {{ $value }}% of the desired Pods of DaemonSet {{ $labels.namespace }}/{{ $labels.daemonset }} are scheduled and ready." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubedaemonsetrolloutstuck" }, expr: 'kube_daemonset_status_number_ready{job="kube-state-metrics"}\n /\nkube_daemonset_status_desired_number_scheduled{job="kube-state-metrics"} * 100 < 100\n', for: "15m", labels: { severity: "critical" } }, { alert: "KubeDaemonSetNotScheduled", annotations: { message: "{{ $value }} Pods of DaemonSet {{ $labels.namespace }}/{{ $labels.daemonset }} are not scheduled." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubedaemonsetnotscheduled" }, expr: 'kube_daemonset_status_desired_number_scheduled{job="kube-state-metrics"}\n -\nkube_daemonset_status_current_number_scheduled{job="kube-state-metrics"} > 0\n', for: "10m", labels: { severity: "warning" } }, { alert: "KubeDaemonSetMisScheduled", annotations: { message: "{{ $value }} Pods of DaemonSet {{ $labels.namespace }}/{{ $labels.daemonset }} are running where they are not supposed to run." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubedaemonsetmisscheduled" }, expr: 'kube_daemonset_status_number_misscheduled{job="kube-state-metrics"} > 0\n', for: "10m", labels: { severity: "warning" } }, { alert: "KubeCronJobRunning", annotations: { message: "CronJob {{ $labels.namespace }}/{{ $labels.cronjob }} is taking more\nthan 1h to complete." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubecronjobrunning" }, expr: 'time() - kube_cronjob_next_schedule_time{job="kube-state-metrics"} > 3600\n', for: "1h", labels: { severity: "warning" } }, { alert: "KubeJobCompletion", annotations: { message: "Job {{ $labels.namespace }}/{{ $labels.job_name }} is taking more\nthan one hour to complete." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubejobcompletion" }, expr: 'kube_job_spec_completions{job="kube-state-metrics"} - kube_job_status_succeeded{job="kube-state-metrics"} > 0\n', for: "1h", labels: { severity: "warning" } }, { alert: "KubeJobFailed", annotations: { message: "Job {{ $labels.namespace }}/{{ $labels.job_name }} failed to complete." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubejobfailed" }, expr: 'kube_job_status_failed{job="kube-state-metrics"} > 0\n', for: "15m", labels: { severity: "warning" } } ] }, { name: "kubernetes-resources", rules: [ { alert: "KubeCPUOvercommit", annotations: { message: "Cluster has overcommitted CPU resource requests for Pods and cannot\ntolerate node failure." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubecpuovercommit" }, expr: "sum(namespace:kube_pod_container_resource_requests_cpu_cores:sum)\n /\nsum(kube_node_status_allocatable_cpu_cores)\n >\n(count(kube_node_status_allocatable_cpu_cores)-1) / count(kube_node_status_allocatable_cpu_cores)\n", for: "5m", labels: { severity: "warning" } }, { alert: "KubeMemOvercommit", annotations: { message: "Cluster has overcommitted memory resource requests for Pods and cannot\ntolerate node failure." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubememovercommit" }, expr: "sum(namespace:kube_pod_container_resource_requests_memory_bytes:sum)\n /\nsum(kube_node_status_allocatable_memory_bytes)\n >\n(count(kube_node_status_allocatable_memory_bytes)-1)\n /\ncount(kube_node_status_allocatable_memory_bytes)\n", for: "5m", labels: { severity: "warning" } }, { alert: "KubeCPUOvercommit", annotations: { message: "Cluster has overcommitted CPU resource requests for Namespaces." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubecpuovercommit" }, expr: 'sum(kube_resourcequota{job="kube-state-metrics", type="hard", resource="cpu"})\n /\nsum(kube_node_status_allocatable_cpu_cores)\n > 1.5\n', for: "5m", labels: { severity: "warning" } }, { alert: "KubeMemOvercommit", annotations: { message: "Cluster has overcommitted memory resource requests for Namespaces." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubememovercommit" }, expr: 'sum(kube_resourcequota{job="kube-state-metrics", type="hard", resource="memory"})\n /\nsum(kube_node_status_allocatable_memory_bytes{job="node-exporter"})\n > 1.5\n', for: "5m", labels: { severity: "warning" } }, { alert: "KubeQuotaExceeded", annotations: { message: 'Namespace {{ $labels.namespace }} is using {{ printf "%0.0f" $value }}% of its {{ $labels.resource }} quota.' // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubequotaexceeded" }, expr: '100 * kube_resourcequota{job="kube-state-metrics", type="used"}\n / ignoring(instance, job, type)\n(kube_resourcequota{job="kube-state-metrics", type="hard"} > 0)\n > 90\n', for: "15m", labels: { severity: "warning" } }, { // For this alert, we will ignore all of the kube-system pods, as they are run by // GKE on our instances and routinely get throttled with no (obvious) method to // configure the resource limits. alert: "CPUThrottlingHigh", annotations: { message: '{{ printf "%0.0f" $value }}% throttling of CPU in namespace {{ $labels.namespace }} for container {{ $labels.container }} in pod {{ $labels.pod }}.' // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-cputhrottlinghigh" }, expr: '100 * sum(increase(container_cpu_cfs_throttled_periods_total{namespace!="kube-system", container!~".*config-reloader"\n}[5m])) by (container, pod, namespace)\n /\nsum(increase(container_cpu_cfs_periods_total{}[5m]))\nby (container, pod, namespace)\n > 25 \n', for: "15m", labels: { severity: "critical" } } ] }, { name: "kubernetes-storage", rules: [ { alert: "KubePersistentVolumeUsageCritical", annotations: { message: 'The PersistentVolume claimed by {{ $labels.persistentvolumeclaim }} in Namespace {{ $labels.namespace }} is only {{ printf "%0.2f" $value }}% free.' // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubepersistentvolumeusagecritical" }, expr: '100 * kubelet_volume_stats_available_bytes{job="kubelet"}\n /\nkubelet_volume_stats_capacity_bytes{job="kubelet"}\n < 3\n', for: "1m", labels: { severity: "critical" } }, { alert: "KubePersistentVolumeFullInFourDays", annotations: { message: 'Based on recent sampling, the PersistentVolume claimed by {{ $labels.persistentvolumeclaim }} in Namespace {{ $labels.namespace }} is expected to fill up within four\ndays. Currently {{ printf "%0.2f" $value }}% is available.' // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubepersistentvolumefullinfourdays" }, expr: '100 * (\n kubelet_volume_stats_available_bytes{job="kubelet"}\n /\n kubelet_volume_stats_capacity_bytes{job="kubelet"}\n) < 15\nand\npredict_linear(kubelet_volume_stats_available_bytes{job="kubelet"}[6h], 4 * 24 * 3600) < 0\n', for: "5m", labels: { severity: "critical" } }, { alert: "KubePersistentVolumeErrors", annotations: { message: "The persistent volume {{ $labels.persistentvolume }} has status {{ $labels.phase }}." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubepersistentvolumeerrors" }, expr: 'kube_persistentvolume_status_phase{phase=~"Failed|Pending",job="kube-state-metrics"} > 0\n', for: "5m", labels: { severity: "critical" } } ] }, { name: "kubernetes-system", rules: [ { alert: "KubeNodeNotReady", annotations: { message: "{{ $labels.node }} has been unready for more than an hour." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubenodenotready" }, expr: 'kube_node_status_condition{job="kube-state-metrics",condition="Ready",status="true"} == 0\n', for: "15m", labels: { severity: "warning" } }, { alert: "KubeVersionMismatch", annotations: { message: "There are {{ $value }} different semantic versions of Kubernetes\ncomponents running." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeversionmismatch" }, expr: 'count(count by (gitVersion) (label_replace(kubernetes_build_info{job!~"kube-dns|coredns"},"gitVersion","$1","gitVersion","(v[0-9]*.[0-9]*.[0-9]*).*"))) > 1\n', for: "15m", labels: { severity: "warning" } }, { alert: "KubeClientErrors", annotations: { message: "Kubernetes API server client '{{ $labels.job }}/{{ $labels.instance }}' is experiencing {{ printf \"%0.0f\" $value }}% errors.'" // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeclienterrors" }, expr: '(sum(rate(rest_client_requests_total{code=~"5.."}[5m])) by (instance, job)\n /\nsum(rate(rest_client_requests_total[5m])) by (instance, job))\n* 100 > 1\n', for: "15m", labels: { severity: "warning" } }, { alert: "KubeClientErrors", annotations: { message: "Kubernetes API server client '{{ $labels.job }}/{{ $labels.instance }}' is experiencing {{ printf \"%0.0f\" $value }} errors / second." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeclienterrors" }, expr: 'sum(rate(ksm_scrape_error_total{job="kube-state-metrics"}[5m])) by (instance, job) > 0.1\n', for: "15m", labels: { severity: "warning" } }, { alert: "KubeletTooManyPods", annotations: { message: "Kubelet {{ $labels.instance }} is running {{ $value }} Pods, close\nto the limit of 110." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubelettoomanypods" }, expr: 'kubelet_running_pod_count{job="kubelet"} > 110 * 0.9\n', for: "15m", labels: { severity: "warning" } }, { alert: "KubeAPILatencyHigh", annotations: { message: "The API server has a 99th percentile latency of {{ $value }} seconds\nfor {{ $labels.verb }} {{ $labels.resource }}." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapilatencyhigh" }, expr: 'cluster_quantile:apiserver_request_duration_seconds:histogram_quantile{job="apiserver",quantile="0.99",subresource!="log",verb!~"^(?:LIST|WATCH|WATCHLIST|PROXY|CONNECT)$"} > 1\n', for: "10m", labels: { severity: "warning" } }, { alert: "KubeAPILatencyHigh", annotations: { message: "The API server has a 99th percentile latency of {{ $value }} seconds\nfor {{ $labels.verb }} {{ $labels.resource }}." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapilatencyhigh" }, expr: 'cluster_quantile:apiserver_request_duration_seconds:histogram_quantile{job="apiserver",quantile="0.99",subresource!="log",verb!~"^(?:LIST|WATCH|WATCHLIST|PROXY|CONNECT)$"} > 4\n', for: "10m", labels: { severity: "critical" } }, { alert: "KubeAPIErrorsHigh", annotations: { message: "API server is returning errors for {{ $value }}% of requests." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapierrorshigh" }, expr: 'sum(rate(apiserver_request_total{job="apiserver",code=~"^(?:5..)$"}[5m]))\n /\nsum(rate(apiserver_request_total{job="apiserver"}[5m])) * 100 > 3\n', for: "10m", labels: { severity: "critical" } }, { alert: "KubeAPIErrorsHigh", annotations: { message: "API server is returning errors for {{ $value }}% of requests." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapierrorshigh" }, expr: 'sum(rate(apiserver_request_total{job="apiserver",code=~"^(?:5..)$"}[5m]))\n /\nsum(rate(apiserver_request_total{job="apiserver"}[5m])) * 100 > 1\n', for: "10m", labels: { severity: "warning" } }, { alert: "KubeAPIErrorsHigh", annotations: { message: "API server is returning errors for {{ $value }}% of requests for\n{{ $labels.verb }} {{ $labels.resource }} {{ $labels.subresource }}." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapierrorshigh" }, expr: 'sum(rate(apiserver_request_total{job="apiserver",code=~"^(?:5..)$"}[5m])) by (resource,subresource,verb)\n /\nsum(rate(apiserver_request_total{job="apiserver"}[5m])) by (resource,subresource,verb) * 100 > 10\n', for: "10m", labels: { severity: "critical" } }, { alert: "KubeAPIErrorsHigh", annotations: { message: "API server is returning errors for {{ $value }}% of requests for\n{{ $labels.verb }} {{ $labels.resource }} {{ $labels.subresource }}." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeapierrorshigh" }, expr: 'sum(rate(apiserver_request_total{job="apiserver",code=~"^(?:5..)$"}[5m])) by (resource,subresource,verb)\n /\nsum(rate(apiserver_request_total{job="apiserver"}[5m])) by (resource,subresource,verb) * 100 > 5\n', for: "10m", labels: { severity: "warning" } }, { alert: "KubeClientCertificateExpiration", annotations: { message: "A client certificate used to authenticate to the apiserver is expiring\nin less than 7.0 days." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeclientcertificateexpiration" }, expr: 'apiserver_client_certificate_expiration_seconds_count{job="apiserver"} > 0 and histogram_quantile(0.01, sum by (job, le) (rate(apiserver_client_certificate_expiration_seconds_bucket{job="apiserver"}[5m]))) < 604800\n', labels: { severity: "warning" } }, { alert: "KubeClientCertificateExpiration", annotations: { message: "A client certificate used to authenticate to the apiserver is expiring\nin less than 24.0 hours." // runbook_url: // "https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/runbook.md#alert-name-kubeclientcertificateexpiration" }, expr: 'apiserver_client_certificate_expiration_seconds_count{job="apiserver"} > 0 and histogram_quantile(0.01, sum by (job, le) (rate(apiserver_client_certificate_expiration_seconds_bucket{job="apiserver"}[5m]))) < 86400\n', labels: { severity: "critical" } } ] }, { name: "alertmanager.rules", rules: [ { alert: "AlertmanagerConfigInconsistent", annotations: { message: "The configuration of the instances of the Alertmanager cluster `{{$labels.service}}`\nare out of sync." }, expr: `count_values("config_hash", alertmanager_config_hash{job="alertmanager"}) BY (namespace) / ON(namespace) GROUP_LEFT() label_replace(max(prometheus_operator_spec_replicas{job="prometheus-operator",controller="alertmanager"}) by (name, job, namespace, controller), "service", "alertmanager-$1", "name", "(.*)") != 1`, for: "5m", labels: { severity: "critical" } }, { alert: "AlertmanagerFailedReload", annotations: { message: "Reloading Alertmanager's configuration has failed for {{ $labels.namespace }}/{{ $labels.pod}}." }, expr: `alertmanager_config_last_reload_successful{job="alertmanager"} == 0`, for: "10m", labels: { severity: "warning" } }, { alert: "AlertmanagerMembersInconsistent", annotations: { message: "Alertmanager has not found all other members of the cluster." }, expr: `alertmanager_cluster_members{job="alertmanager"}\n != on (namespace) GROUP_LEFT()\ncount by (namespace) (alertmanager_cluster_members{job="alertmanager"})`, for: "5m", labels: { severity: "critical" } } ] }, { name: "general.rules", rules: [ { alert: "TargetDown", annotations: { message: "{{ $value }}% of the {{ $labels.job }} targets are down." }, expr: // TODO (clambert) put this back to the original value, after figuring out why it doesn't work "100 * (count(up == 0) BY (job, namespace, service) / count(up) BY (job, namespace, service)) > 100", // 10", for: "10m", labels: { severity: "warning" } }, { alert: "Watchdog", annotations: { message: 'This is an alert meant to ensure that the entire alerting pipeline is functional.\nThis alert is always firing, therefore it should always be firing in Alertmanager\nand always fire against a receiver. There are integrations with various notification\nmechanisms that send a notification when this alert is not firing. For example the\n"DeadMansSnitch" integration in PagerDuty.\n' }, expr: "vector(1)", labels: { severity: "none" } } ] }, { name: "node-time", rules: [ { alert: "ClockSkewDetected", annotations: { message: "Clock skew detected on node-exporter {{ $labels.namespace }}/{{ $labels.pod }}. Ensure NTP is configured correctly on this host." }, expr: 'abs(node_timex_offset_seconds{job="node-exporter"}) > 0.05\n', for: "2m", labels: { severity: "warning" } } ] }, { name: "node-network", rules: [ { alert: "NodeNetworkInterfaceFlapping", annotations: { message: 'Network interface "{{ $labels.device }}" changing it\'s up status\noften on node-exporter {{ $labels.namespace }}/{{ $labels.pod }}"' }, expr: 'changes(node_network_up{job="node-exporter",device!~"veth.+"}[2m]) > 2\n', for: "2m", labels: { severity: "warning" } } ] }, { name: "opstrace-system", rules: [ { alert: "NodeCPUUtilizationSevere", annotations: { message: "Node CPU utilization is severe.", // runbook_url: runbookUrl + "/system.md#NodeCPUUtilizationSevere", dashboard: grafanaUrl }, expr: '(\ninstance:node_cpu_utilisation:rate1m{job="node-exporter"}\n *\n instance:node_num_cpu:sum{job="node-exporter"}\n / ignoring (instance) group_left\n sum without (instance) (instance:node_num_cpu:sum{job="node-exporter"}) > 0.8\n)', for: "10m", labels: { severity: "critical" } }, { alert: "NodeCPUUtilizationElevated", annotations: { message: "Node CPU utilization is elevated.", // runbook_url: runbookUrl + "/system.md#NodeCPUUtilizationElevated", dashboard: grafanaUrl }, expr: '(\ninstance:node_cpu_utilisation:rate1m{job="node-exporter"}\n *\n instance:node_num_cpu:sum{job="node-exporter"}\n / ignoring (instance) group_left\n sum without (instance) (instance:node_num_cpu:sum{job="node-exporter"}) > 0.7\n)', for: "10m", labels: { severity: "low" } }, { alert: "NodeMemUtilizationElevated", annotations: { message: "Node memory utilization is elevated.", // runbook_url: runbookUrl + "/system.md#NodeMemUtilizationElevated", dashboard: grafanaUrl }, expr: '(\ninstance:node_memory_utilisation:ratio{job="node-exporter"}\n/ ignoring (instance) group_left\n count without (instance) (instance:node_memory_utilisation:ratio{job="node-exporter"})\n) > 0.65', for: "10m", labels: { severity: "warn" } }, { alert: "NodeNetworkUtilizationElevated", annotations: { message: "Node network RX utilization is elevated.", // runbook_url: runbookUrl + "/system.md#NodeNetworkUtilizationElevated", dashboard: grafanaUrl }, expr: 'instance:node_network_receive_bytes_excluding_lo:rate1m{job="node-exporter"} > 100000000', for: "10m", labels: { severity: "warn" } }, { alert: "NodeNetworkUtilizationElevated", annotations: { message: "Node network TX utilization is elevated.", // runbook_url: runbookUrl + "/system.md#NodeNetworkUtilizationElevated", dashboard: grafanaUrl }, expr: 'instance:node_network_transmit_bytes_excluding_lo:rate1m{job="node-exporter"} < -100000000', for: "10m", labels: { severity: "warn" } }, { alert: "NodeDiskUtilizationElevated", annotations: { message: "Node disk utilization is elevated.", // runbook_url: runbookUrl + "/system.md#NodeDiskUtilizationElevated", dashboard: grafanaUrl }, expr: '(\n sum without (device) (\n max without (fstype, mountpoint) (\n node_filesystem_size_bytes{job="node-exporter", } - node_filesystem_avail_bytes{job="node-exporter", }\n)\n) \n / ignoring (instance) group_left\n sum without (instance, device) (\n max without (fstype, mountpoint) (\n node_filesystem_size_bytes{job="node-exporter", }\n)\n)\n) > .5', for: "10m", labels: { severity: "warn" } }, { alert: "NodeDiskUtilizationSevere", annotations: { message: "Node disk utilization is severe.", // runbook_url: runbookUrl + "/system.md#NodeDiskUtilizationSevere", dashboard: grafanaUrl }, expr: '(\n sum without (device) (\n max without (fstype, mountpoint) (\n node_filesystem_size_bytes{job="node-exporter", } - node_filesystem_avail_bytes{job="node-exporter", }\n)\n) \n / ignoring (instance) group_left\n sum without (instance, device) (\n max without (fstype, mountpoint) (\n node_filesystem_size_bytes{job="node-exporter", }\n)\n)\n) > .8', for: "10m", labels: { severity: "critical" } } ] }, { name: "cortex_alerts", rules: [ { alert: "CortexIngesterUnhealthy", annotations: { message: 'Cortex cluster {{ $labels.cluster }}/{{ $labels.namespace }} has {{ printf "%f" $value }} unhealthy ingester(s).' }, expr: 'min by (cluster, namespace) (cortex_ring_members{state="Unhealthy", name="ingester"}) > 0\n', for: "15m", labels: { severity: "critical" } }, { alert: "CortexRequestErrors", annotations: { message: 'The route {{ $labels.route }} in {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% errors.\n' }, expr: '100 * sum by (cluster, namespace, job, route) (rate(cortex_request_duration_seconds_count{status_code=~"5..",route!~"ready"}[1m]))\n /\nsum by (cluster, namespace, job, route) (rate(cortex_request_duration_seconds_count{route!~"ready"}[1m]))\n > 1\n', for: "15m", labels: { severity: "critical" } }, { alert: "CortexRequestLatency", annotations: { message: '{{ $labels.job }} {{ $labels.route }} is experiencing {{ printf "%.2f" $value }}s 99th percentile latency.\n' }, expr: 'cluster_namespace_job_route:cortex_request_duration_seconds:99quantile{route!~"metrics|/frontend.Frontend/Process|ready|/schedulerpb.SchedulerForFrontend/FrontendLoop|/schedulerpb.SchedulerForQuerier/QuerierLoop"}\n >\n2.5\n', for: "15m", labels: { severity: "warning" } }, { alert: "CortexTableSyncFailure", annotations: { message: '{{ $labels.job }} is experiencing {{ printf "%.2f" $value }}% errors syncing tables.\n' }, expr: '100 * rate(cortex_table_manager_sync_duration_seconds_count{status_code!~"2.."}[15m])\n /\nrate(cortex_table_manager_sync_duration_seconds_count[15m])\n > 10\n', for: "30m", labels: { severity: "critical" } }, { alert: "CortexQueriesIncorrect", annotations: { message: 'The Cortex cluster {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% incorrect query results.\n' }, expr: '100 * sum by (cluster, namespace) (rate(test_exporter_test_case_result_total{result="fail"}[5m]))\n /\nsum by (cluster, namespace) (rate(test_exporter_test_case_result_total[5m])) > 1\n', for: "15m", labels: { severity: "warning" } }, { alert: "CortexInconsistentRuntimeConfig", annotations: { message: "An inconsistent runtime config file is used across cluster {{ $labels.cluster }}/{{ $labels.namespace }}.\n" }, expr: "count(count by(cluster, namespace, job, sha256) (cortex_runtime_config_hash)) without(sha256) > 1\n", for: "1h", labels: { severity: "critical" } }, { alert: "CortexBadRuntimeConfig", annotations: { message: "{{ $labels.job }} failed to reload runtime config.\n" }, expr: "# The metric value is reset to 0 on error while reloading the config at runtime.\ncortex_runtime_config_last_reload_successful == 0\n", for: "5m", labels: { severity: "critical" } }, { alert: "CortexFrontendQueriesStuck", annotations: { message: "There are {{ $value }} queued up queries in {{ $labels.cluster }}/{{ $labels.namespace }} query-frontend.\n" }, expr: "sum by (cluster, namespace) (cortex_query_frontend_queue_length) > 1\n", for: "5m", labels: { severity: "critical" } }, { alert: "CortexSchedulerQueriesStuck", annotations: { message: "There are {{ $value }} queued up queries in {{ $labels.cluster }}/{{ $labels.namespace }} query-scheduler.\n" }, expr: "sum by (cluster, namespace) (cortex_query_scheduler_queue_length) > 1\n", for: "5m", labels: { severity: "critical" } }, { alert: "CortexMemcachedRequestErrors", annotations: { message: 'Memcached {{ $labels.name }} used by Cortex {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% errors for {{ $labels.operation }} operation.\n' }, expr: "(\n sum by(cluster, namespace, name, operation) (rate(thanos_memcached_operation_failures_total[1m])) /\n sum by(cluster, namespace, name, operation) (rate(thanos_memcached_operations_total[1m]))\n) * 100 > 5\n", for: "5m", labels: { severity: "warning" } }, { alert: "CortexIngesterRestarts", annotations: { message: '{{ $labels.job }}/{{ $labels.instance }} has restarted {{ printf "%.2f" $value }} times in the last 30 mins.' }, expr: 'changes(process_start_time_seconds{job=~".+(cortex|ingester.*)"}[30m]) >= 2\n', labels: { severity: "warning" } }, { alert: "CortexTransferFailed", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} transfer failed." }, expr: 'max_over_time(cortex_shutdown_duration_seconds_count{op="transfer",status!="success"}[15m])\n', for: "5m", labels: { severity: "critical" } }, { alert: "CortexOldChunkInMemory", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} has very old unflushed chunk in memory.\n" }, expr: "(time() - cortex_oldest_unflushed_chunk_timestamp_seconds > 36000)\n and\n(cortex_oldest_unflushed_chunk_timestamp_seconds > 0)\n", for: "5m", labels: { severity: "warning" } }, { alert: "CortexMemoryMapAreasTooHigh", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} has a number of mmap-ed areas close to the limit." }, expr: 'process_memory_map_areas{job=~".+(cortex|ingester.*|store-gateway)"} / process_memory_map_areas_limit{job=~".+(cortex|ingester.*|store-gateway)"} > 0.8\n', for: "5m", labels: { severity: "critical" } } ] }, { name: "cortex_ingester_instance_alerts", rules: [ { alert: "CortexIngesterReachingSeriesLimit", annotations: { message: "Ingester {{ $labels.job }}/{{ $labels.instance }} has reached {{ $value | humanizePercentage }} of its series limit.\n" }, expr: '(\n (cortex_ingester_memory_series / ignoring(limit) cortex_ingester_instance_limits{limit="max_series"})\n and ignoring (limit)\n (cortex_ingester_instance_limits{limit="max_series"} > 0)\n) > 0.7\n', for: "3h", labels: { severity: "warning" } }, { alert: "CortexIngesterReachingSeriesLimit", annotations: { message: "Ingester {{ $labels.job }}/{{ $labels.instance }} has reached {{ $value | humanizePercentage }} of its series limit.\n" }, expr: '(\n (cortex_ingester_memory_series / ignoring(limit) cortex_ingester_instance_limits{limit="max_series"})\n and ignoring (limit)\n (cortex_ingester_instance_limits{limit="max_series"} > 0)\n) > 0.85\n', for: "5m", labels: { severity: "critical" } }, { alert: "CortexIngesterReachingTenantsLimit", annotations: { message: "Ingester {{ $labels.job }}/{{ $labels.instance }} has reached {{ $value | humanizePercentage }} of its tenant limit.\n" }, expr: '(\n (cortex_ingester_memory_users / ignoring(limit) cortex_ingester_instance_limits{limit="max_tenants"})\n and ignoring (limit)\n (cortex_ingester_instance_limits{limit="max_tenants"} > 0)\n) > 0.7\n', for: "5m", labels: { severity: "warning" } }, { alert: "CortexIngesterReachingTenantsLimit", annotations: { message: "Ingester {{ $labels.job }}/{{ $labels.instance }} has reached {{ $value | humanizePercentage }} of its tenant limit.\n" }, expr: '(\n (cortex_ingester_memory_users / ignoring(limit) cortex_ingester_instance_limits{limit="max_tenants"})\n and ignoring (limit)\n (cortex_ingester_instance_limits{limit="max_tenants"} > 0)\n) > 0.8\n', for: "5m", labels: { severity: "critical" } } ] }, { name: "cortex_wal_alerts", rules: [ { alert: "CortexWALCorruption", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} has a corrupted WAL or checkpoint.\n" }, expr: "increase(cortex_ingester_wal_corruptions_total[5m]) > 0\n", labels: { severity: "critical" } }, { alert: "CortexCheckpointCreationFailed", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} failed to create checkpoint.\n" }, expr: "increase(cortex_ingester_checkpoint_creations_failed_total[10m]) > 0\n", labels: { severity: "warning" } }, { alert: "CortexCheckpointCreationFailed", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} is failing to create checkpoint.\n" }, expr: "increase(cortex_ingester_checkpoint_creations_failed_total[1h]) > 1\n", labels: { severity: "critical" } }, { alert: "CortexCheckpointDeletionFailed", annotations: { message: "{{ $labels.job }}/{{ $labels.instance }} failed to delete checkpoint.\n" }, expr: "increase(cortex_ingester_checkpoint_deletions_failed_total[10m]) > 0\n", labels: { severity: "warning" } }, { alert: "CortexCheckpointDeletionFailed", annotations: { message: "{{ $labels.instance }} is failing to delete checkpoint.\n" }, expr: "increase(cortex_ingester_checkpoint_deletions_failed_total[2h]) > 1\n", labels: { severity: "critical" } } ] }, { name: "cortex-provisioning", rules: [ { alert: "CortexProvisioningMemcachedTooSmall", annotations: { message: 'Chunk memcached cluster in {{ $labels.cluster }}/{{ $labels.namespace }} is too small, should be at least {{ printf "%.2f" $value }}GB.\n' }, expr: '(\n 4 *\n sum by (cluster, namespace) (cortex_ingester_memory_series * cortex_ingester_chunk_size_bytes_sum / cortex_ingester_chunk_size_bytes_count)\n / 1e9\n)\n >\n(\n sum by (cluster, namespace) (memcached_limit_bytes{job=~".+/memcached"}) / 1e9\n)\n', for: "15m", labels: { severity: "warning" } }, { alert: "CortexProvisioningTooManyActiveSeries", annotations: { message: "The number of in-memory series per ingester in {{ $labels.cluster }}/{{ $labels.namespace }} is too high.\n" }, expr: "avg by (cluster, namespace) (cortex_ingester_memory_series) > 1.6e6\n", for: "2h", labels: { severity: "warning" } } // Disable this alert until we have a method to dyanmically set the threshold based on // instance capacity. Note: this alert should probably be considered 'critical' in the future. // // { // alert: "CortexProvisioningTooManyWrites", // annotations: { // message: // "Ingesters in {{ $labels.cluster }}/{{ $labels.namespace }} ingest too many samples per second.\n" // }, // expr: "avg by (cluster, namespace) (rate(cortex_ingester_ingested_samples_total[1m])) > 80e3\n", // for: "15m", // labels: { // severity: "warning" // } // } // Disable this alert until we enable container memory limits for the ingesters. (Without // limits the denominator resolves to 0.) // // TODO: when reenabling this alert, it would be nice to group by `severity`, so we don't // get 2 alerts—one for warning and one for critical. // // { // alert: "CortexAllocatingTooMuchMemory", // annotations: { // message: // "Ingester {{ $labels.pod }} in {{ $labels.cluster }}/{{ $labels.namespace }} is using too much memory.\n" // }, // expr: '(\n container_memory_working_set_bytes{container="ingester"}\n /\n container_spec_memory_limit_bytes{container="ingester"}\n) > .5\n', // for: "15m", // labels: { // severity: "warning" // } // }, // { // alert: "CortexAllocatingTooMuchMemory", // annotations: { // message: // "Ingester {{ $labels.pod }} in {{ $labels.cluster }}/{{ $labels.namespace }} is using too much memory.\n" // }, // expr: '(\n container_memory_working_set_bytes{container="ingester"}\n /\n container_spec_memory_limit_bytes{container="ingester"}\n) > 0.8\n', // for: "15m", // labels: { // severity: "critical" // } // } ] }, { name: "ruler_alerts", rules: [ { alert: "CortexRulerTooManyFailedPushes", annotations: { message: 'Cortex Ruler {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% write (push) errors.\n' }, expr: "100 * (\nsum by (cluster, namespace, instance) (rate(cortex_ruler_write_requests_failed_total[1m]))\n /\nsum by (cluster, namespace, instance) (rate(cortex_ruler_write_requests_total[1m]))\n) > 1\n", for: "5m", labels: { severity: "critical" } }, { alert: "CortexRulerTooManyFailedQueries", annotations: { message: 'Cortex Ruler {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% errors while evaluating rules.\n' }, expr: "100 * (\nsum by (cluster, namespace, instance) (rate(cortex_ruler_queries_failed_total[1m]))\n /\nsum by (cluster, namespace, instance) (rate(cortex_ruler_queries_total[1m]))\n) > 1\n", for: "5m", labels: { severity: "warning" } }, { alert: "CortexRulerMissedEvaluations", annotations: { message: 'Cortex Ruler {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is experiencing {{ printf "%.2f" $value }}% missed iterations for the rule group {{ $labels.rule_group }}.\n' }, expr: "sum by (cluster, namespace, instance, rule_group) (rate(cortex_prometheus_rule_group_iterations_missed_total[1m]))\n /\nsum by (cluster, namespace, instance, rule_group) (rate(cortex_prometheus_rule_group_iterations_total[1m]))\n > 0.01\n", for: "5m", labels: { severity: "warning" } }, { alert: "CortexRulerFailedRingCheck", annotations: { message: "Cortex Rulers in {{ $labels.cluster }}/{{ $labels.namespace }} are experiencing errors when checking the ring for rule group ownership.\n" }, expr: "sum by (cluster, namespace, job) (rate(cortex_ruler_ring_check_errors_total[1m]))\n > 0\n", for: "5m", labels: { severity: "critical" } } ] }, { name: "gossip_alerts", rules: [ { alert: "CortexGossipMembersMismatch", annotations: { message: "Cortex instance {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} sees incorrect number of gossip members." }, expr: 'memberlist_client_cluster_members_count\n != on (cluster, namespace) group_left\nsum by (cluster, namespace) (up{job=~".+/(admin-api|compactor|store-gateway|distributor|ingester.*|querier|cortex|ruler)"})\n', for: "5m", labels: { severity: "warning" } } ] }, { name: "etcd_alerts", rules: [ { alert: "EtcdAllocatingTooMuchMemory", annotations: { message: "Too much memory being used by {{ $labels.namespace }}/{{ $labels.pod }} - bump memory limit.\n" }, expr: '(\n container_memory_working_set_bytes{container="etcd"}\n /\n container_spec_memory_limit_bytes{container="etcd"}\n) > 0.65\n', for: "15m", labels: { severity: "warning" } }, { alert: "EtcdAllocatingTooMuchMemory", annotations: { message: "Too much memory being used by {{ $labels.namespace }}/{{ $labels.pod }} - bump memory limit.\n" }, expr: '(\n container_memory_working_set_bytes{container="etcd"}\n /\n container_spec_memory_limit_bytes{container="etcd"}\n) > 0.8\n', for: "15m", labels: { severity: "critical" } } ] }, { name: "cortex_blocks_alerts", rules: [ { alert: "CortexIngesterHasNotShippedBlocks", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not shipped any block in the last 4 hours." }, expr: '(min by(cluster, namespace, instance) (time() - thanos_objstore_bucket_last_successful_upload_time{job=~".+/ingester.*"}) > 60 * 60 * 4)\nand\n(max by(cluster, namespace, instance) (thanos_objstore_bucket_last_successful_upload_time{job=~".+/ingester.*"}) > 0)\nand\n# Only if the ingester has ingested samples over the last 4h.\n(max by(cluster, namespace, instance) (rate(cortex_ingester_ingested_samples_total[4h])) > 0)\nand\n# Only if the ingester was ingesting samples 4h ago. This protects from the case the ingester instance\n# had ingested samples in the past, then no traffic was received for a long period and then it starts\n# receiving samples again. Without this check, the alert would fire as soon as it gets back receiving\n# samples, while the a block shipping is expected within the next 4h.\n(max by(cluster, namespace, instance) (rate(cortex_ingester_ingested_samples_total[1h] offset 4h)) > 0)\n', for: "15m", labels: { severity: "critical" } }, { alert: "CortexIngesterHasNotShippedBlocksSinceStart", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not shipped any block in the last 4 hours." }, expr: '(max by(cluster, namespace, instance) (thanos_objstore_bucket_last_successful_upload_time{job=~".+/ingester.*"}) == 0)\nand\n(max by(cluster, namespace, instance) (rate(cortex_ingester_ingested_samples_total[4h])) > 0)\n', for: "4h", labels: { severity: "critical" } }, { alert: "CortexIngesterHasUnshippedBlocks", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has compacted a block {{ $value | humanizeDuration }} ago but it hasn't been successfully uploaded to the storage yet." }, expr: "(time() - cortex_ingester_oldest_unshipped_block_timestamp_seconds > 3600)\nand\n(cortex_ingester_oldest_unshipped_block_timestamp_seconds > 0)\n", for: "15m", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBHeadCompactionFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to compact TSDB head." }, expr: "rate(cortex_ingester_tsdb_compactions_failed_total[5m]) > 0\n", for: "15m", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBHeadTruncationFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to truncate TSDB head." }, expr: "rate(cortex_ingester_tsdb_head_truncations_failed_total[5m]) > 0\n", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBCheckpointCreationFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to create TSDB checkpoint." }, expr: "rate(cortex_ingester_tsdb_checkpoint_creations_failed_total[5m]) > 0\n", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBCheckpointDeletionFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to delete TSDB checkpoint." }, expr: "rate(cortex_ingester_tsdb_checkpoint_deletions_failed_total[5m]) > 0\n", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBWALTruncationFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to truncate TSDB WAL." }, expr: "rate(cortex_ingester_tsdb_wal_truncations_failed_total[5m]) > 0\n", labels: { severity: "warning" } }, { alert: "CortexIngesterTSDBWALCorrupted", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} got a corrupted TSDB WAL." }, expr: "rate(cortex_ingester_tsdb_wal_corruptions_total[5m]) > 0\n", labels: { severity: "critical" } }, { alert: "CortexIngesterTSDBWALWritesFailed", annotations: { message: "Cortex Ingester {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} is failing to write to TSDB WAL." }, expr: "rate(cortex_ingester_tsdb_wal_writes_failed_total[1m]) > 0\n", for: "3m", labels: { severity: "critical" } }, { alert: "CortexQuerierHasNotScanTheBucket", annotations: { message: "Cortex Querier {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not successfully scanned the bucket since {{ $value | humanizeDuration }}." }, expr: "(time() - cortex_querier_blocks_last_successful_scan_timestamp_seconds > 60 * 30)\nand\ncortex_querier_blocks_last_successful_scan_timestamp_seconds > 0\n", for: "5m", labels: { severity: "critical" } }, { alert: "CortexQuerierHighRefetchRate", annotations: { message: 'Cortex Queries in {{ $labels.cluster }}/{{ $labels.namespace }} are refetching series from different store-gateways (because of missing blocks) for the {{ printf "%.0f" $value }}% of queries.' }, expr: '100 * (\n (\n sum by(cluster, namespace) (rate(cortex_querier_storegateway_refetches_per_query_count[5m]))\n -\n sum by(cluster, namespace) (rate(cortex_querier_storegateway_refetches_per_query_bucket{le="0.0"}[5m]))\n )\n /\n sum by(cluster, namespace) (rate(cortex_querier_storegateway_refetches_per_query_count[5m]))\n)\n> 1\n', for: "10m", labels: { severity: "warning" } }, { alert: "CortexStoreGatewayHasNotSyncTheBucket", annotations: { message: "Cortex Store Gateway {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not successfully synched the bucket since {{ $value | humanizeDuration }}." }, expr: '(time() - cortex_bucket_stores_blocks_last_successful_sync_timestamp_seconds{component="store-gateway"} > 60 * 30)\nand\ncortex_bucket_stores_blocks_last_successful_sync_timestamp_seconds{component="store-gateway"} > 0\n', for: "5m", labels: { severity: "critical" } }, { alert: "CortexBucketIndexNotUpdated", annotations: { message: "Cortex bucket index for tenant {{ $labels.user }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not been updated since {{ $value | humanizeDuration }}." }, expr: "min by(cluster, namespace, user) (time() - cortex_bucket_index_last_successful_update_timestamp_seconds) > 7200\n", labels: { severity: "critical" } }, { alert: "CortexTenantHasPartialBlocks", annotations: { message: "Cortex tenant {{ $labels.user }} in {{ $labels.cluster }}/{{ $labels.namespace }} has {{ $value }} partial blocks." }, expr: "max by(cluster, namespace, user) (cortex_bucket_blocks_partials_count) > 0\n", for: "6h", labels: { severity: "warning" } } ] }, { name: "cortex_compactor_alerts", rules: [ { alert: "CortexCompactorHasNotSuccessfullyCleanedUpBlocks", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not successfully cleaned up blocks in the last 6 hours." }, expr: "(time() - cortex_compactor_block_cleanup_last_successful_run_timestamp_seconds > 60 * 60 * 6)\n", for: "1h", labels: { severity: "critical" } }, { alert: "CortexCompactorHasNotSuccessfullyRunCompaction", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not run compaction in the last 24 hours." }, expr: "(time() - cortex_compactor_last_successful_run_timestamp_seconds > 60 * 60 * 24)\nand\n(cortex_compactor_last_successful_run_timestamp_seconds > 0)\n", for: "1h", labels: { severity: "critical" } }, { alert: "CortexCompactorHasNotSuccessfullyRunCompaction", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not run compaction in the last 24 hours." }, expr: "cortex_compactor_last_successful_run_timestamp_seconds == 0\n", for: "24h", labels: { severity: "critical" } }, { alert: "CortexCompactorHasNotSuccessfullyRunCompaction", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} failed to run 2 consecutive compactions." }, expr: "increase(cortex_compactor_runs_failed_total[2h]) >= 2\n", labels: { severity: "critical" } }, { alert: "CortexCompactorHasNotUploadedBlocks", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not uploaded any block in the last 24 hours." }, expr: '(time() - thanos_objstore_bucket_last_successful_upload_time{job=~".+/compactor.*"} > 60 * 60 * 24)\nand\n(thanos_objstore_bucket_last_successful_upload_time{job=~".+/compactor.*"} > 0)\n', for: "15m", labels: { severity: "critical" } }, { alert: "CortexCompactorHasNotUploadedBlocks", annotations: { message: "Cortex Compactor {{ $labels.instance }} in {{ $labels.cluster }}/{{ $labels.namespace }} has not uploaded any block in the last 24 hours." }, expr: 'thanos_objstore_bucket_last_successful_upload_time{job=~".+/compactor.*"} == 0\n', for: "24h", labels: { severity: "critical" } } ] }, { name: "loki_alerts", rules: [ { alert: "LokiRequestErrors", annotations: { message: '{{ $labels.job }} {{ $labels.route }} is experiencing {{ printf "%.2f" $value }}% errors.\n' }, // TODO (clambert) return the threhold of this alert back to the original 18. expr: '100 * sum(rate(loki_request_duration_seconds_count{status_code=~"5.."}[1m])) by (namespace, job, route)\n /\nsum(rate(loki_request_duration_seconds_count[1m])) by (namespace, job, route)\n > 25\n', for: "15m", labels: { severity: "critical" } }, { alert: "LokiRequestLatency", annotations: { message: '{{ $labels.job }} {{ $labels.route }} is experiencing {{ printf "%.2f" $value }}s 99th percentile latency.\n' }, expr: 'namespace_job_route:loki_request_duration_seconds:99quantile{route!~"(?i).*tail.*"} > 2.5\n', for: "15m", labels: { severity: "critical" } } ] } ];
the_stack
import { idb, iterate } from "../db"; import { defaultGameAttributes, g, helpers, processPlayersHallOfFame, } from "../util"; import type { UpdateEvents, Player, ViewInput, MinimalPlayerRatings, } from "../../common/types"; import { groupBy } from "../../common/groupBy"; import { player } from "../core"; import { bySport, PLAYER } from "../../common"; import { getValueStatsRow } from "../core/player/checkJerseyNumberRetirement"; import goatFormula from "../util/goatFormula"; import orderBy from "lodash-es/orderBy"; import addFirstNameShort from "../util/addFirstNameShort"; type Most = { value: number; extra?: Record<string, unknown>; }; type PlayersAll = (Player<MinimalPlayerRatings> & { most: Most; })[]; export const getMostXPlayers = async ({ filter, getValue, after, sortParams, }: { filter?: (p: Player) => boolean; getValue: (p: Player) => Most | undefined; after?: (most: Most) => Promise<Most> | Most; sortParams?: any; }) => { const LIMIT = 100; const playersAll: PlayersAll = []; await iterate( idb.league.transaction("players").store, undefined, undefined, p => { if (filter !== undefined && !filter(p)) { return; } const most = getValue(p); if (most === undefined) { return; } playersAll.push({ ...p, most, }); playersAll.sort((a, b) => b.most.value - a.most.value); if (playersAll.length > LIMIT) { playersAll.pop(); } }, ); const stats = bySport({ basketball: ["gp", "min", "pts", "trb", "ast", "per", "ewa", "ws", "ws48"], football: ["gp", "keyStats", "av"], hockey: ["gp", "keyStats", "ops", "dps", "ps"], }); const players = await idb.getCopies.playersPlus(playersAll, { attrs: [ "pid", "firstName", "lastName", "draft", "retiredYear", "statsTids", "hof", "born", "diedYear", "most", "jerseyNumber", "awards", ], ratings: ["ovr", "pos"], stats: ["season", "abbrev", "tid", ...stats], fuzz: true, }); const ordered = sortParams ? orderBy(players, ...sortParams) : players; for (let i = 0; i < 100; i++) { if (ordered[i]) { ordered[i].rank = i + 1; if (after) { ordered[i].most = await after(ordered[i].most); } } } return { players: addFirstNameShort(processPlayersHallOfFame(ordered)), stats, }; }; const playerValue = (p: Player<MinimalPlayerRatings>) => { let sum = 0; for (const ps of p.stats) { sum += getValueStatsRow(ps); } return { value: sum, }; }; // Should actually be using getTeamInfoBySeason const tidAndSeasonToAbbrev = async (most: Most) => { let abbrev; const { season, tid } = most.extra as any; const teamSeason = await idb.league .transaction("teamSeasons") .store.index("season, tid") .get([season, tid]); if (teamSeason) { abbrev = teamSeason.abbrev; } if (abbrev === undefined) { if (season < g.get("startingSeason")) { const teamSeason = await idb.league .transaction("teamSeasons") .store.index("season, tid") .get([g.get("startingSeason"), tid]); if (teamSeason) { abbrev = teamSeason.abbrev; } } abbrev = g.get("teamInfoCache")[tid]?.abbrev; } return { ...most, extra: { ...most.extra, tid, abbrev, }, }; }; const updatePlayers = async ( { arg, type }: ViewInput<"most">, updateEvents: UpdateEvents, state: any, ) => { // In theory should update more frequently, but the list is potentially expensive to update and rarely changes if ( updateEvents.includes("firstRun") || type !== state.type || (type === "goat" && updateEvents.includes("g.goatFormula")) ) { let filter: Parameters<typeof getMostXPlayers>[0]["filter"]; let getValue: Parameters<typeof getMostXPlayers>[0]["getValue"]; let after: Parameters<typeof getMostXPlayers>[0]["after"]; let sortParams: any; let title: string; let description: string | undefined; const extraCols: { key: string | [string, string] | [string, string, string]; colName: string; }[] = []; let extraProps: any; if (type === "at_pick") { if (arg === undefined) { throw new Error("Pick must be specified in the URL"); } if (arg === "undrafted") { title = "Best Undrafted Players"; } else { title = `Best Players Drafted at Pick ${arg}`; } description = `<a href="${helpers.leagueUrl([ "frivolities", "draft_position", ])}">Other picks</a>`; let round: number; let pick: number; if (arg === "undrafted") { round = 0; pick = 0; } else { const parts = arg.split("-"); round = parseInt(parts[0]); pick = parseInt(parts[1]); if (Number.isNaN(round) || Number.isNaN(pick)) { throw new Error("Invalid pick"); } } filter = p => p.tid !== PLAYER.UNDRAFTED && p.draft.round === round && p.draft.pick === pick; getValue = playerValue; } else if (type === "games_injured") { title = "Most Games Injured"; description = "Players with the most total games missed due to injury."; extraCols.push({ key: ["most", "value"], colName: "Games", }); filter = p => p.injuries.length > 0; getValue = p => { let sum = 0; for (const ps of p.injuries) { sum += ps.games; } return { value: sum }; }; } else if (type === "games_no_playoffs") { title = "Most Games, No Playoffs"; description = "These are the players who played the most career games while never making the playoffs."; filter = p => p.stats.length > 0 && p.stats.filter(ps => ps.playoffs).length === 0; getValue = p => { let sum = 0; for (const ps of p.stats) { sum += ps.gp; } return { value: sum }; }; } else if (type === "goat") { title = "GOAT Lab"; description = "Define your own formula to rank the greatest players of all time."; extraCols.push({ key: ["most", "value"], colName: "GOAT", }); extraProps = { goatFormula: g.get("goatFormula") ?? goatFormula.DEFAULT_FORMULA, awards: goatFormula.AWARD_VARIABLES, stats: goatFormula.STAT_VARIABLES, }; getValue = (p: Player<MinimalPlayerRatings>) => { let value = 0; try { value = goatFormula.evaluate(p); } catch (error) {} return { value, }; }; } else if (type === "teams") { title = "Most Teams"; description = "These are the players who played for the most teams"; extraCols.push({ key: ["most", "value"], colName: "# Teams", }); getValue = p => { const tids = p.stats.filter(s => s.gp > 0).map(s => s.tid); return { value: new Set(tids).size }; }; } else if (type === "oldest_former_players") { title = "Oldest Former Players"; description = "These are the players who lived the longest."; extraCols.push( { key: ["most", "value"], colName: "Age", }, { key: ["born", "year"], colName: "Born", }, { key: "diedYear", colName: "Died", }, ); getValue = p => { const age = typeof p.diedYear === "number" ? p.diedYear - p.born.year : g.get("season") - p.born.year; return { value: age }; }; } else if (type === "no_ring") { title = "Best Players Without a Ring"; description = "These are the best players who never won a league championship."; filter = p => p.awards.every(award => award.type !== "Won Championship"); getValue = playerValue; } else if (type === "no_mvp") { title = "Best Players Without an MVP"; description = "These are the best players who never won an MVP award."; filter = p => p.awards.every(award => award.type !== "Most Valuable Player"); getValue = playerValue; } else if (type === "progs") { title = "Best Progs"; description = "These are the players who had the biggest single season increases in ovr rating."; if (g.get("challengeNoRatings")) { description += ' Because you\'re using the "no visible ratings" challenge mode, only retired players are shown here.'; } extraCols.push( { key: ["most", "extra", "season"], colName: "Season", }, { key: ["most", "extra", "age"], colName: "Age", }, { key: ["most", "value"], colName: "Prog", }, ); filter = p => p.ratings.length > 1 && (!g.get("challengeNoRatings") || p.tid === PLAYER.RETIRED); getValue = p => { let maxProg = -Infinity; let maxSeason = p.ratings[0].season; for (let i = 1; i < p.ratings.length; i++) { const ovr = player.fuzzRating(p.ratings[i].ovr, p.ratings[i].fuzz); const prevOvr = player.fuzzRating( p.ratings[i - 1].ovr, p.ratings[i - 1].fuzz, ); const prog = ovr - prevOvr; if (prog > maxProg) { maxProg = prog; maxSeason = p.ratings[i].season; } } return { value: maxProg, extra: { season: maxSeason, age: maxSeason - p.born.year, }, }; }; } else if (type === "busts") { title = "Biggest Busts"; description = "These are the players drafted with a top 5 pick who had the worst careers."; extraCols.push({ key: ["most", "extra"], colName: "Team", }); filter = p => p.draft.round === 1 && p.draft.pick <= 5 && g.get("season") - p.draft.year >= 5 && p.draft.year >= g.get("startingSeason") - 3; getValue = p => { const value = playerValue(p).value; return { value: -value, extra: { tid: p.draft.tid, season: p.draft.year }, }; }; after = tidAndSeasonToAbbrev; } else if (type === "steals") { title = "Biggest Steals"; description = bySport({ basketball: "These are the undrafted players or second round picks who had the best careers.", football: "These are the undrafted players or 5th+ round picks who had the best careers.", hockey: "These are the undrafted players or 3rd+ round picks who had the best careers.", }); extraCols.push({ key: ["most", "extra"], colName: "Team", }); filter = p => p.draft.round === 0 || bySport({ basketball: p.draft.round >= 2, football: p.draft.round >= 5, hockey: p.draft.round >= 3, }); getValue = p => { const value = playerValue(p).value; return { value, extra: { tid: p.draft.tid, season: p.draft.year }, }; }; after = tidAndSeasonToAbbrev; } else if (type === "earnings") { title = "Career Earnings"; description = "These are the players who made the most money in their careers."; extraCols.push({ key: ["most", "value"], colName: "Amount", }); getValue = p => { let sum = 0; for (const salary of p.salaries) { sum += salary.amount; } return { value: sum }; }; } else if (type === "hall_of_good") { title = "Hall of Good"; description = "These are the best retired players who did not make the Hall of Fame."; filter = p => p.retiredYear < Infinity && !p.hof; getValue = playerValue; } else if (type === "hall_of_shame") { title = "Hall of Shame"; description = "These are the worst players who actually got enough playing time to show it."; getValue = p => { let min = 0; let valueTimesMin = 0; for (const ps of p.stats) { min += ps.min; valueTimesMin += ps.min * ps.per; } if ( min > g.get("numGames") * (g.get("quarterLength") > 0 ? g.get("quarterLength") : defaultGameAttributes.quarterLength) * g.get("numPeriods") && (p.retiredYear === Infinity || p.ratings.length > 3) ) { return { value: -valueTimesMin / min }; } }; } else if (type === "traded") { title = "Most Times Traded"; description = "These are the players who were traded the most number of times in their careers."; extraCols.push({ key: ["most", "value"], colName: "# Trades", }); getValue = p => { if (!p.transactions) { return; } const value = p.transactions.filter(t => t.type === "trade").length; if (value === 0) { return; } return { value }; }; } else if (type === "one_team") { title = "Most Years on One Team"; description = "These are the players who played the most seasons for a single team."; extraCols.push({ key: ["most", "value"], colName: "# Seasons", }); extraCols.push({ key: ["most", "extra", "gp"], colName: "stat:gp", }); extraCols.push({ key: ["most", "extra"], colName: "Team", }); getValue = p => { let maxNumSeasons = 0; let maxTid; let maxGP; let maxSeason; // Last season, for historical abbrev computation const statsByTid = groupBy( p.stats.filter(ps => !ps.playoffs), ps => ps.tid, ); for (const tid of Object.keys(statsByTid)) { const numSeasons = statsByTid[tid].length; if (numSeasons > maxNumSeasons) { maxNumSeasons = numSeasons; // Somehow propagate these through maxTid = parseInt(tid); maxGP = 0; for (const ps of statsByTid[tid]) { maxGP += ps.gp; maxSeason = ps.season; } } } if (maxNumSeasons === 0) { return; } return { value: maxNumSeasons, extra: { gp: maxGP, tid: maxTid, season: maxSeason }, }; }; after = tidAndSeasonToAbbrev; } else if (type === "oldest") { title = "Oldest to Play in a Game"; description = "These are the oldest players who ever played in a game."; extraCols.push({ key: ["most", "value"], colName: "Age", }); extraCols.push({ key: ["most", "extra", "season"], colName: "Season", }); extraCols.push({ key: ["most", "extra"], colName: "Team", }); extraCols.push({ key: ["most", "extra", "ovr"], colName: "Ovr", }); getValue = p => { let maxAge = 0; let season: number | undefined; let tid: number | undefined; for (const ps of p.stats) { if (ps.gp > 0) { const age = ps.season - p.born.year; if (age > maxAge) { maxAge = age; season = ps.season; tid = ps.tid; } } } if (season === undefined) { return; } let ovr: number | undefined; const ratings = p.ratings.find(pr => pr.season === season); if (ratings) { ovr = player.fuzzRating(ratings.ovr, ratings.fuzz); } return { value: maxAge, extra: { season, ovr, tid, }, }; }; after = tidAndSeasonToAbbrev; } else if (type === "oldest_peaks" || type === "youngest_peaks") { const oldest = type === "oldest_peaks"; title = `${oldest ? "Oldest" : "Youngest"} Peaks`; description = `These are the players who peaked in ovr at the ${ oldest ? "oldest" : "youngest" } age (min 5 seasons in career${oldest ? "" : " and 30+ years old"}).`; extraCols.push({ key: ["most", "extra", "age"], colName: "Age", }); extraCols.push({ key: ["most", "extra", "season"], colName: "Season", }); extraCols.push({ key: ["most", "extra"], colName: "Team", }); extraCols.push({ key: ["most", "extra", "ovr"], colName: "Ovr", }); sortParams = [ ["most.value", "most.extra.ovr"], ["desc", "desc"], ]; getValue = p => { if (p.ratings.length < 5) { return; } if (!oldest) { // Skip players who are not yet 30 years old const ratings = p.ratings.at(-1); if (!ratings) { return; } const age = ratings.season - p.born.year; if (age < 30) { return; } } // Skip players who were older than 25 when league started const ratings = p.ratings[0]; if (!ratings) { return; } const age = ratings.season - p.born.year; if (age > 25 && ratings.season === g.get("startingSeason")) { return; } let maxOvr = -Infinity; let season: number | undefined; for (const ratings of p.ratings) { const ovr = player.fuzzRating(ratings.ovr, ratings.fuzz); // gt vs gte makes sense if you think about oldest vs youngest, we're searching in order here if ((oldest && ovr >= maxOvr) || (!oldest && ovr > maxOvr)) { maxOvr = ovr; season = ratings.season; } } if (season === undefined) { return; } const maxAge = season - p.born.year; let tid: number | undefined; for (const ps of p.stats) { if (season === ps.season) { tid = ps.tid; } else if (season < ps.season) { break; } } if (tid === undefined) { return; } return { value: oldest ? maxAge : -maxAge, extra: { age: maxAge, season, ovr: maxOvr, tid, }, }; }; after = tidAndSeasonToAbbrev; } else if (type === "worst_injuries") { title = "Worst Injuries"; description = "These are the players who experienced the largest ovr drops after injuries."; if (g.get("challengeNoRatings")) { description += ' Because you\'re using the "no visible ratings" challenge mode, only retired players are shown here.'; } extraCols.push({ key: ["most", "extra", "type"], colName: "Injury", }); extraCols.push({ key: ["most", "extra", "season"], colName: "Season", }); extraCols.push({ key: ["most", "value"], colName: "Ovr Drop", }); filter = p => p.injuries.length > 0 && (!g.get("challengeNoRatings") || p.tid === PLAYER.RETIRED); getValue = p => { let maxOvrDrop = 0; let injuryType; let injurySeason; for (const injury of p.injuries) { if (injury.ovrDrop !== undefined && injury.ovrDrop > maxOvrDrop) { maxOvrDrop = injury.ovrDrop; // Somehow propagate these through injuryType = injury.type; injurySeason = injury.season; } } if (maxOvrDrop === 0) { return; } return { value: maxOvrDrop, extra: { type: injuryType, season: injurySeason }, }; }; } else if (type === "jersey_number") { if (arg === undefined) { throw new Error("Jersey number must be specified in the URL"); } title = `Best Players With Jersey Number ${arg}`; description = `These are the best players who spent the majority of their career wearing #${arg}. <a href="${helpers.leagueUrl( ["frivolities", "jersey_numbers"], )}">Other jersey numbers.</a>`; filter = p => helpers.getJerseyNumber(p, "mostCommon") === arg; getValue = playerValue; } else if (type === "country") { if (arg === undefined) { throw new Error("Country must be specified in the URL"); } title = `Best Players From ${arg}`; description = `These are the best players from the country ${arg}. <a href="${helpers.leagueUrl( ["frivolities", "countries"], )}">Other countries.</a>`; filter = p => helpers.getCountry(p.born.loc) === arg; getValue = playerValue; } else if (type === "college") { if (arg === undefined) { throw new Error("College must be specified in the URL"); } title = `Best Players From ${arg}`; description = `These are the best players from the college ${arg}. <a href="${helpers.leagueUrl( ["frivolities", "colleges"], )}">Other colleges.</a>`; filter = p => { const college = p.college && p.college !== "" ? p.college : "None"; return college === arg; }; getValue = playerValue; } else { throw new Error(`Unknown type "${type}"`); } const { players, stats } = await getMostXPlayers({ filter, getValue, after, sortParams, }); return { challengeNoRatings: g.get("challengeNoRatings"), description, extraCols, extraProps, players, stats, title, type, userTid: g.get("userTid"), }; } }; export default updatePlayers;
the_stack
* Copyright 2015 Dev Shop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // notice_end import {observeEvent, ObservationStage, DisposableBase, Router} from '../../src'; describe('Decorators', () => { let _router; beforeEach(() => { _router = new Router(); }); let previewInvokeCount = 0; let normalInvokeCount = 0; let normal2InvokeCount = 0; let committedInvokeCount = 0; let finalInvokeCount = 0; let _model, _derivedModel1, _derivedModel2, _derivedModel3, _derivedModel4, _derivedModel5; class Model extends DisposableBase { private _id: string; private _router: Router; private receivedBarEvents: Array<any>; private receivedFruitEvents: Array<any>; private receivedBazzEventsAtAll: Array<any>; private subModel: SubModel; constructor(id, router) { super(); this._id = id; this._router = router; this.receivedBarEvents = []; this.receivedFruitEvents = []; this.receivedBazzEventsAtAll = []; this.subModel = new SubModel(id, router); } observeEvents() { this.addDisposable(this._router.observeEventsOn(this._id, this)); this.subModel.observeEvents(); } //start-non-standard @observeEvent('fooEvent', ObservationStage.preview) _fooEventAtPreview(event, context, model) { previewInvokeCount++; } @observeEvent('fooEvent', ObservationStage.normal) _fooEventAtNormal1(event, context, model) { normalInvokeCount++; context.commit(); } @observeEvent('fooEvent') _fooEventAtNormal2(event, context, model) { normal2InvokeCount++; } @observeEvent('fooEvent', ObservationStage.committed) _fooEventAtCommitted(event, context, model) { committedInvokeCount++; } @observeEvent('fooEvent', ObservationStage.final) _fooEventAtFinal(event, context, model) { finalInvokeCount++; } @observeEvent('barEvent_1') _barEvent_1(event, context, model) { context.commit(); } @observeEvent('barEvent_1', ObservationStage.committed) @observeEvent('barEvent_2') @observeEvent('barEvent_3', ObservationStage.preview) @observeEvent('barEvent_4', ObservationStage.final) _allBarEvents(event, context, model) { this.receivedBarEvents.push({event: event, stage: context.currentStage}); } @observeEvent('fruitEvent', (model, event) => event.type === 'orange') _onFruitEvent(event, context, model) { this.receivedFruitEvents.push(event); } @observeEvent('bazzEvent', ObservationStage.all) _bazzEventAtAll(event, context, model) { this.receivedBazzEventsAtAll.push({ eventType: context.eventType, event: event, model: model, stage: context.currentStage }); if (ObservationStage.isNormal(context.currentStage)) { context.commit(); } } //end-non-standard } class SubModel extends DisposableBase { private _id: string; private _router: Router; private carEvents: Array<any>; private tag: string; constructor(id, router) { super(); this._id = id; this._router = router; this.carEvents = []; this.tag = 'submodel'; } observeEvents() { this.addDisposable(this._router.observeEventsOn(this._id, this)); } @observeEvent('carEvent', (model, event) => { return event.type === 'bmw' && model.tag === 'submodel'; }) _onFruitEvent(event, context, model) { this.carEvents.push({type: event.type, model: model, eventType: context.eventType}); } } class BaseModel extends DisposableBase { protected _id: string; protected _router: Router; private baseEventReveivedCount: number; constructor(id, router) { super(); this._id = id; this._router = router; this.baseEventReveivedCount = 0; } observeEvents() { this.addDisposable(this._router.observeEventsOn(this._id, this)); } @observeEvent('aBaseEvent') _aBaseEvent(event, context, model) { this.baseEventReveivedCount++; } } class DerivedModel1 extends BaseModel { private reveivedCount: number; constructor(id, router) { super(id, router); this.reveivedCount = 0; } @observeEvent('derivedEvent') _derivedEvent(event, context, model) { this.reveivedCount++; } // override observeEvents() { this.addDisposable(this._router.observeEventsOn(this._id, this)); } } class DerivedModel2 extends BaseModel { private reveivedCount: number; constructor(id, router) { super(id, router); this.reveivedCount = 0; } @observeEvent('derivedEvent') _derivedEvent(event, context, model) { this.reveivedCount++; } // override observeEvents() { this.addDisposable(this._router.observeEventsOn(this._id, this)); } } class DerivedModel3 extends BaseModel { private reveivedCount: number; constructor(id, router) { super(id, router); this.reveivedCount = 0; } @observeEvent('derivedEvent') _derivedEvent(event, context, model) { this.reveivedCount++; } // don't override the base observeEvents } class DerivedModel4 extends BaseModel { private reveivedCount: number; constructor(id, router) { super(id, router); this.reveivedCount = 0; } @observeEvent('derivedEvent') _derivedEvent(event, context, model) { this.reveivedCount++; } // don't override the base observeEvents } class DerivedModel5 extends BaseModel { constructor(id, router) { super(id, router); } } class DerivedModel3_1 extends DerivedModel3 { private reveivedCount1: number; constructor(id, router) { super(id, router); this.reveivedCount1 = 0; } @observeEvent('derivedEvent_1') _derivedEvent_1(event, context, model) { this.reveivedCount1++; } } class DerivedModel4_1 extends DerivedModel4 { private reveivedCount1: number; constructor(id, router) { super(id, router); this.reveivedCount1 = 0; } @observeEvent('derivedEvent_1') _derivedEvent_1(event, context, model) { this.reveivedCount1++; } } function getExpectedObserveEventsOnTwiceError(modelId) { return new Error(`observeEventsOn has already been called for model with id '${modelId}' and the given object. Note you can observe the same model with different decorated objects, however you have called observeEventsOn twice with the same object.`); } beforeEach(() => { previewInvokeCount = 0; normalInvokeCount = 0; normal2InvokeCount = 0; committedInvokeCount = 0; finalInvokeCount = 0; _model = new Model('modelId', _router); _router.addModel('modelId', _model); _derivedModel1 = new DerivedModel1('derivedModel1Id', _router); _router.addModel('derivedModel1Id', _derivedModel1); _derivedModel2 = new DerivedModel2('derivedModel2Id', _router); _router.addModel('derivedModel2Id', _derivedModel2); _derivedModel3 = new DerivedModel3_1('derivedModel3Id', _router); _router.addModel('derivedModel3Id', _derivedModel3); _derivedModel4 = new DerivedModel4_1('derivedModel4Id', _router); _router.addModel('derivedModel4Id', _derivedModel4); _derivedModel5 = new DerivedModel5('derivedModel5Id', _router); _router.addModel('derivedModel5Id', _derivedModel5); }); it('should throw if event name is omitted', () => { expect(() => { class Foo { @observeEvent() _anObserveFunction() { } } }).toThrow(new Error('eventType passed to an observeEvent decorator must be a string')); expect(() => { class Foo { @observeEvent(null) _anObserveFunction() { } } }).toThrow(new Error('eventType passed to an observeEvent decorator must be a string')); expect(() => { class Foo { @observeEvent(undefined) _anObserveFunction() { } } }).toThrow(new Error('eventType passed to an observeEvent decorator must be a string')); }); it('should throw if event name is empty', () => { expect(() => { class Foo { @observeEvent('') _anObserveFunction() { } } }).toThrow(new Error('eventType passed to an observeEvent decorator must not be \'\'')); }); it('should throw if event name is an invalid type', () => { expect(() => { class Foo { @observeEvent({}) _anObserveFunction() { } } }).toThrow(new Error('eventType passed to an observeEvent decorator must be a string')); }); it('should observe events by event name and stage', () => { _model.observeEvents(); _router.publishEvent('modelId', 'fooEvent', 1); expect(previewInvokeCount).toBe(1); expect(normalInvokeCount).toBe(1); expect(normal2InvokeCount).toBe(1); expect(committedInvokeCount).toBe(1); expect(finalInvokeCount).toBe(1); }); it('should observe events by event name and stage when using ObservationStage.all', () => { _model.observeEvents(); _router.publishEvent('modelId', 'bazzEvent', 1); expect(_model.receivedBazzEventsAtAll.length).toBe(4); expect(_model.receivedBazzEventsAtAll[0].stage).toEqual(ObservationStage.preview); expect(_model.receivedBazzEventsAtAll[0].eventType).toEqual('bazzEvent'); expect(_model.receivedBazzEventsAtAll[0].event).toEqual(1); expect(_model.receivedBazzEventsAtAll[1].stage).toEqual(ObservationStage.normal); expect(_model.receivedBazzEventsAtAll[1].eventType).toEqual('bazzEvent'); expect(_model.receivedBazzEventsAtAll[1].event).toEqual(1); expect(_model.receivedBazzEventsAtAll[2].stage).toEqual(ObservationStage.committed); expect(_model.receivedBazzEventsAtAll[2].eventType).toEqual('bazzEvent'); expect(_model.receivedBazzEventsAtAll[2].event).toEqual(1); expect(_model.receivedBazzEventsAtAll[3].stage).toEqual(ObservationStage.final); expect(_model.receivedBazzEventsAtAll[3].eventType).toEqual('bazzEvent'); expect(_model.receivedBazzEventsAtAll[3].event).toEqual(1); }); it('should stop observing events when disposable disposed', () => { _model.observeEvents(); _router.publishEvent('modelId', 'fooEvent', 1); _router.publishEvent('modelId', 'fooEvent', 1); _model.dispose(); _router.publishEvent('modelId', 'fooEvent', 1); expect(previewInvokeCount).toBe(2); expect(normalInvokeCount).toBe(2); expect(normal2InvokeCount).toBe(2); expect(committedInvokeCount).toBe(2); }); it('should observe multiple events', () => { _model.observeEvents(); _router.publishEvent('modelId', 'barEvent_1', 1); expect(_model.receivedBarEvents.length).toBe(1); expect(_model.receivedBarEvents[0].event).toBe(1); expect(_model.receivedBarEvents[0].stage).toBe(ObservationStage.committed); _router.publishEvent('modelId', 'barEvent_2', 2); expect(_model.receivedBarEvents.length).toBe(2); expect(_model.receivedBarEvents[1].event).toBe(2); expect(_model.receivedBarEvents[1].stage).toBe(ObservationStage.normal); _router.publishEvent('modelId', 'barEvent_3', 3); expect(_model.receivedBarEvents.length).toBe(3); expect(_model.receivedBarEvents[2].event).toBe(3); expect(_model.receivedBarEvents[2].stage).toBe(ObservationStage.preview); _router.publishEvent('modelId', 'barEvent_4', 4); expect(_model.receivedBarEvents.length).toBe(4); expect(_model.receivedBarEvents[3].event).toBe(4); expect(_model.receivedBarEvents[3].stage).toBe(ObservationStage.final); _model.dispose(); _router.publishEvent('modelId', 'barEvent_1', 1); _router.publishEvent('modelId', 'barEvent_2', 1); _router.publishEvent('modelId', 'barEvent_3', 1); _router.publishEvent('modelId', 'barEvent_4', 1); expect(_model.receivedBarEvents.length).toBe(4); }); it('should observe base events', () => { _derivedModel1.observeEvents(); _router.publishEvent('derivedModel1Id', 'aBaseEvent', {}); expect(_derivedModel1.baseEventReveivedCount).toBe(1); }); it('should observe events in a derived objects inheritance hierarchy', () => { _derivedModel1.observeEvents(); _router.publishEvent('derivedModel1Id', 'derivedEvent', {}); expect(_derivedModel1.reveivedCount).toBe(1); _router.publishEvent('derivedModel1Id', 'aBaseEvent', {}); expect(_derivedModel1.baseEventReveivedCount).toBe(1); _derivedModel2.observeEvents(); _router.publishEvent('derivedModel2Id', 'derivedEvent', {}); expect(_derivedModel1.reveivedCount).toBe(1); expect(_derivedModel2.reveivedCount).toBe(1); _router.publishEvent('derivedModel2Id', 'aBaseEvent', {}); expect(_derivedModel1.baseEventReveivedCount).toBe(1); expect(_derivedModel2.baseEventReveivedCount).toBe(1); }); it('should observe events in a derived objects inheritance hierarchy when observeEvents is called on base model', () => { _derivedModel3.observeEvents(); _derivedModel4.observeEvents(); _router.publishEvent('derivedModel4Id', 'derivedEvent_1', {}); expect(_derivedModel3.reveivedCount1).toBe(0); expect(_derivedModel4.reveivedCount1).toBe(1); }); it('should observe events in a derived object which has no event observations itself', () => { _derivedModel5.observeEvents(); _router.publishEvent('derivedModel5Id', 'aBaseEvent', {}); expect(_derivedModel5.baseEventReveivedCount).toBe(1); }); it('should throw when observeEvents called twice with the same object', () => { _derivedModel1.observeEvents(); expect(() => { _derivedModel1.observeEvents(); }).toThrow(getExpectedObserveEventsOnTwiceError('derivedModel1Id')); }); it('should use observeEvent predicate if provided', () => { _model.observeEvents(); _router.publishEvent('modelId', 'fruitEvent', {type: 'apple'}); expect(_model.receivedFruitEvents.length).toEqual(0); _router.publishEvent('modelId', 'fruitEvent', {type: 'orange'}); expect(_model.receivedFruitEvents.length).toEqual(1); expect(_model.receivedFruitEvents[0].type).toEqual('orange'); }); it('should pass sub model to observeEvent predicate if provided', () => { _model.observeEvents(); _router.publishEvent('modelId', 'carEvent', {type: 'vw'}); expect(_model.subModel.carEvents.length).toEqual(0); _router.publishEvent('modelId', 'carEvent', {type: 'bmw'}); expect(_model.subModel.carEvents.length).toEqual(1); expect(_model.subModel.carEvents[0].type).toEqual('bmw'); expect(_model.subModel.carEvents[0].eventType).toEqual('carEvent'); }); it('should allow multiple registrations for the same modelId against different objects', () => { _router.addModel('m1', {}); class e { @observeEvent('anEvent') _derivedEvent(event, context, model) { } } let eventObserver1 = new e(); let eventObserver2 = new e(); _router.observeEventsOn('m1', eventObserver1); expect(() => { _router.observeEventsOn('m1', eventObserver1); }).toThrow(getExpectedObserveEventsOnTwiceError('m1')); _router.observeEventsOn('m1', eventObserver2); expect(() => { _router.observeEventsOn('m1', eventObserver2); }).toThrow(getExpectedObserveEventsOnTwiceError('m1')); }); it('should not throw when observeEvents called after initial observation disposed', () => { let subscription = _router.observeEventsOn('derivedModel1Id', _derivedModel1); subscription.dispose(); subscription = _router.observeEventsOn('derivedModel1Id', _derivedModel1); _router.publishEvent('derivedModel1Id', 'aBaseEvent', {}); expect(_derivedModel1.baseEventReveivedCount).toBe(1); subscription.dispose(); _router.publishEvent('derivedModel1Id', 'aBaseEvent', {}); expect(_derivedModel1.baseEventReveivedCount).toBe(1); }); });
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type SaleActiveBidItemTestsQueryVariables = {}; export type SaleActiveBidItemTestsQueryResponse = { readonly me: { readonly lotStandings: ReadonlyArray<{ readonly " $fragmentRefs": FragmentRefs<"SaleActiveBidItem_lotStanding">; } | null> | null; } | null; }; export type SaleActiveBidItemTestsQuery = { readonly response: SaleActiveBidItemTestsQueryResponse; readonly variables: SaleActiveBidItemTestsQueryVariables; }; /* query SaleActiveBidItemTestsQuery { me { lotStandings(saleID: "sale-id") { ...SaleActiveBidItem_lotStanding } id } } fragment Lot_saleArtwork on SaleArtwork { lotLabel artwork { artistNames image { url(version: "medium") } id } } fragment SaleActiveBidItem_lotStanding on LotStanding { activeBid { isWinning id } mostRecentBid { maxBid { display } id } saleArtwork { reserveStatus counts { bidderPositions } currentBid { display } artwork { href id } ...Lot_saleArtwork id } sale { liveStartAt id } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "saleID", "value": "sale-id" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], v3 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v4 = { "enumValues": null, "nullable": true, "plural": false, "type": "BidderPosition" }, v5 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "SaleActiveBidItemTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "LotStanding", "kind": "LinkedField", "name": "lotStandings", "plural": true, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "SaleActiveBidItem_lotStanding" } ], "storageKey": "lotStandings(saleID:\"sale-id\")" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "SaleActiveBidItemTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "LotStanding", "kind": "LinkedField", "name": "lotStandings", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "activeBid", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "isWinning", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "mostRecentBid", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPositionMaxBid", "kind": "LinkedField", "name": "maxBid", "plural": false, "selections": (v2/*: any*/), "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "reserveStatus", "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v2/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, (v1/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "medium" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"medium\")" } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "liveStartAt", "storageKey": null }, (v1/*: any*/) ], "storageKey": null } ], "storageKey": "lotStandings(saleID:\"sale-id\")" }, (v1/*: any*/) ], "storageKey": null } ] }, "params": { "id": "9533d72f958050791bff97bfe3c7b62d", "metadata": { "relayTestingSelectionTypeInfo": { "me": { "enumValues": null, "nullable": true, "plural": false, "type": "Me" }, "me.id": (v3/*: any*/), "me.lotStandings": { "enumValues": null, "nullable": true, "plural": true, "type": "LotStanding" }, "me.lotStandings.activeBid": (v4/*: any*/), "me.lotStandings.activeBid.id": (v3/*: any*/), "me.lotStandings.activeBid.isWinning": { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, "me.lotStandings.mostRecentBid": (v4/*: any*/), "me.lotStandings.mostRecentBid.id": (v3/*: any*/), "me.lotStandings.mostRecentBid.maxBid": { "enumValues": null, "nullable": true, "plural": false, "type": "BidderPositionMaxBid" }, "me.lotStandings.mostRecentBid.maxBid.display": (v5/*: any*/), "me.lotStandings.sale": { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, "me.lotStandings.sale.id": (v3/*: any*/), "me.lotStandings.sale.liveStartAt": (v5/*: any*/), "me.lotStandings.saleArtwork": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtwork" }, "me.lotStandings.saleArtwork.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "me.lotStandings.saleArtwork.artwork.artistNames": (v5/*: any*/), "me.lotStandings.saleArtwork.artwork.href": (v5/*: any*/), "me.lotStandings.saleArtwork.artwork.id": (v3/*: any*/), "me.lotStandings.saleArtwork.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "me.lotStandings.saleArtwork.artwork.image.url": (v5/*: any*/), "me.lotStandings.saleArtwork.counts": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCounts" }, "me.lotStandings.saleArtwork.counts.bidderPositions": { "enumValues": null, "nullable": true, "plural": false, "type": "FormattedNumber" }, "me.lotStandings.saleArtwork.currentBid": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCurrentBid" }, "me.lotStandings.saleArtwork.currentBid.display": (v5/*: any*/), "me.lotStandings.saleArtwork.id": (v3/*: any*/), "me.lotStandings.saleArtwork.lotLabel": (v5/*: any*/), "me.lotStandings.saleArtwork.reserveStatus": (v5/*: any*/) } }, "name": "SaleActiveBidItemTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '4e4aa68f80df2d12e54754cfc3ddb666'; export default node;
the_stack
import { Doc, doc, FastPath, ParserOptions } from 'prettier'; import { formattableAttributes, selfClosingTags } from '../lib/elements'; import { extractAttributes } from '../lib/extractAttributes'; import { getText } from '../lib/getText'; import { hasSnippedContent, unsnipContent } from '../lib/snipTagContent'; import { isBracketSameLine, parseSortOrder, SortOrderPart } from '../options'; import { isEmptyDoc, isLine, trim, trimRight } from './doc-helpers'; import { flatten, isASTNode, isPreTagContent, replaceEndOfLineWith } from './helpers'; import { checkWhitespaceAtEndOfSvelteBlock, checkWhitespaceAtStartOfSvelteBlock, doesEmbedStartAfterNode, endsWithLinebreak, getUnencodedText, isBlockElement, isEmptyTextNode, isIgnoreDirective, isInlineElement, isInsideQuotedAttribute, isLoneMustacheTag, isNodeSupportedLanguage, isOrCanBeConvertedToShorthand, isTextNodeEndingWithLinebreak, isTextNodeEndingWithWhitespace, isTextNodeStartingWithLinebreak, isTextNodeStartingWithWhitespace, printRaw, shouldHugEnd, shouldHugStart, startsWithLinebreak, trimChildren, trimTextNodeLeft, trimTextNodeRight, canOmitSoftlineBeforeClosingTag, getNextNode, isIgnoreStartDirective, isIgnoreEndDirective, isNodeTopLevelHTML, } from './node-helpers'; import { ASTNode, AttributeNode, CommentNode, IfBlockNode, Node, OptionsNode, StyleDirectiveNode, TextNode, } from './nodes'; const { concat, join, line, group, indent, dedent, softline, hardline, fill, breakParent, literalline, } = doc.builders; export type PrintFn = (path: FastPath) => Doc; declare module 'prettier' { export namespace doc { namespace builders { interface Line { keepIfLonely?: boolean; } } } } let ignoreNext = false; let ignoreRange = false; let svelteOptionsDoc: Doc | undefined; function groupConcat(contents: doc.builders.Doc[]): doc.builders.Doc { return group(concat(contents)); } export function print(path: FastPath, options: ParserOptions, print: PrintFn): Doc { const bracketSameLine = isBracketSameLine(options); const n = path.getValue(); if (!n) { return ''; } if (isASTNode(n)) { return printTopLevelParts(n, options, path, print); } const [open, close] = options.svelteStrictMode ? ['"{', '}"'] : ['{', '}']; const printJsExpression = () => [ open, printJS(path, print, options.svelteStrictMode, false, false, 'expression'), close, ]; const node = n as Node; if ( (ignoreNext || (ignoreRange && !isIgnoreEndDirective(node))) && (node.type !== 'Text' || !isEmptyTextNode(node)) ) { if (ignoreNext) { ignoreNext = false; } return concat( flatten( options.originalText .slice(options.locStart(node), options.locEnd(node)) .split('\n') .map((o, i) => (i == 0 ? [o] : [literalline, o])), ), ); } switch (node.type) { case 'Fragment': const children = node.children; if (children.length === 0 || children.every(isEmptyTextNode)) { return ''; } if (!isPreTagContent(path)) { trimChildren(node.children, path); const output = trim( [printChildren(path, print, options)], (n) => isLine(n) || (typeof n === 'string' && n.trim() === '') || // Because printChildren may append this at the end and // may hide other lines before it n === breakParent, ); if (output.every((doc) => isEmptyDoc(doc))) { return ''; } return groupConcat([...output, hardline]); } else { return groupConcat(path.map(print, 'children')); } case 'Text': if (!isPreTagContent(path)) { if (isEmptyTextNode(node)) { const hasWhiteSpace = getUnencodedText(node).trim().length < getUnencodedText(node).length; const hasOneOrMoreNewlines = /\n/.test(getUnencodedText(node)); const hasTwoOrMoreNewlines = /\n\r?\s*\n\r?/.test(getUnencodedText(node)); if (hasTwoOrMoreNewlines) { return concat([hardline, hardline]); } if (hasOneOrMoreNewlines) { return hardline; } if (hasWhiteSpace) { return line; } return ''; } /** * For non-empty text nodes each sequence of non-whitespace characters (effectively, * each "word") is joined by a single `line`, which will be rendered as a single space * until this node's current line is out of room, at which `fill` will break at the * most convenient instance of `line`. */ return fill(splitTextToDocs(node)); } else { const rawText = getUnencodedText(node); if (path.getParentNode().type === 'Attribute') { // Direct child of attribute value -> add literallines at end of lines // so that other things don't break in unexpected places return concat(replaceEndOfLineWith(rawText, literalline)); } return rawText; } case 'Element': case 'InlineComponent': case 'Slot': case 'SlotTemplate': case 'Window': case 'Head': case 'Title': { const isSupportedLanguage = !( node.name === 'template' && !isNodeSupportedLanguage(node) ); const isEmpty = node.children.every((child) => isEmptyTextNode(child)); const isSelfClosingTag = isEmpty && (!options.svelteStrictMode || node.type !== 'Element' || selfClosingTags.indexOf(node.name) !== -1); // Order important: print attributes first const attributes = path.map((childPath) => childPath.call(print), 'attributes'); const possibleThisBinding = node.type === 'InlineComponent' && node.expression ? concat([line, 'this=', ...printJsExpression()]) : node.type === 'Element' && node.tag ? concat([ line, 'this=', ...(typeof node.tag === 'string' ? [`"${node.tag}"`] : [ open, printJS( path, print, options.svelteStrictMode, false, false, 'tag', ), close, ]), ]) : ''; if (isSelfClosingTag) { return groupConcat([ '<', node.name, indent( groupConcat([ possibleThisBinding, ...attributes, bracketSameLine ? '' : dedent(line), ]), ), ...[bracketSameLine ? ' ' : '', `/>`], ]); } const children = node.children; const firstChild = children[0]; const lastChild = children[children.length - 1]; // Is a function which is invoked later because printChildren will manipulate child nodes // which would wrongfully change the other checks about hugging etc done beforehand let body: () => Doc; const hugStart = shouldHugStart(node, isSupportedLanguage, options); const hugEnd = shouldHugEnd(node, isSupportedLanguage, options); if (isEmpty) { body = isInlineElement(path, options, node) && node.children.length && isTextNodeStartingWithWhitespace(node.children[0]) && !isPreTagContent(path) ? () => line : () => (bracketSameLine ? softline : ''); } else if (isPreTagContent(path)) { body = () => printPre(node, options.originalText, path, print); } else if (!isSupportedLanguage) { body = () => printRaw(node, options.originalText, true); } else if (isInlineElement(path, options, node) && !isPreTagContent(path)) { body = () => printChildren(path, print, options); } else { body = () => printChildren(path, print, options); } const openingTag = [ '<', node.name, indent( groupConcat([ possibleThisBinding, ...attributes, hugStart ? '' : !bracketSameLine && !isPreTagContent(path) ? dedent(softline) : '', ]), ), ]; if (!isSupportedLanguage && !isEmpty) { // Format template tags so that there's a hardline but no indention. // That way the `lang="X"` and the closing `>` of the start tag stay in one line // which is the 99% use case. return groupConcat([ ...openingTag, '>', groupConcat([hardline, body(), hardline]), `</${node.name}>`, ]); } if (hugStart && hugEnd) { const huggedContent = concat([ softline, groupConcat(['>', body(), `</${node.name}`]), ]); const omitSoftlineBeforeClosingTag = (isEmpty && !bracketSameLine) || canOmitSoftlineBeforeClosingTag(node, path, options); return groupConcat([ ...openingTag, isEmpty ? group(huggedContent) : group(indent(huggedContent)), omitSoftlineBeforeClosingTag ? '' : softline, '>', ]); } // No hugging of content means it's either a block element and/or there's whitespace at the start/end let noHugSeparatorStart: Doc = softline; let noHugSeparatorEnd: Doc = softline; if (isPreTagContent(path)) { noHugSeparatorStart = ''; noHugSeparatorEnd = ''; } else { let didSetEndSeparator = false; if (!hugStart && firstChild && firstChild.type === 'Text') { if ( isTextNodeStartingWithLinebreak(firstChild) && firstChild !== lastChild && (!isInlineElement(path, options, node) || isTextNodeEndingWithWhitespace(lastChild)) ) { noHugSeparatorStart = hardline; noHugSeparatorEnd = hardline; didSetEndSeparator = true; } else if (isInlineElement(path, options, node)) { noHugSeparatorStart = line; } trimTextNodeLeft(firstChild); } if (!hugEnd && lastChild && lastChild.type === 'Text') { if (isInlineElement(path, options, node) && !didSetEndSeparator) { noHugSeparatorEnd = line; } trimTextNodeRight(lastChild); } } if (hugStart) { return groupConcat([ ...openingTag, indent(concat([softline, groupConcat(['>', body()])])), noHugSeparatorEnd, `</${node.name}>`, ]); } if (hugEnd) { return groupConcat([ ...openingTag, '>', indent(concat([noHugSeparatorStart, groupConcat([body(), `</${node.name}`])])), canOmitSoftlineBeforeClosingTag(node, path, options) ? '' : softline, '>', ]); } if (isEmpty) { return groupConcat([...openingTag, '>', body(), `</${node.name}>`]); } return groupConcat([ ...openingTag, '>', indent(concat([noHugSeparatorStart, body()])), noHugSeparatorEnd, `</${node.name}>`, ]); } case 'Options': throw new Error('Options tags should have been handled by prepareChildren'); case 'Body': return groupConcat([ '<', node.name, indent(groupConcat(path.map((childPath) => childPath.call(print), 'attributes'))), ' />', ]); case 'Identifier': return node.name; case 'AttributeShorthand': { return (node.expression as any).name; } case 'Attribute': { if (isOrCanBeConvertedToShorthand(node)) { if (options.svelteStrictMode) { return concat([line, node.name, '="{', node.name, '}"']); } else if (options.svelteAllowShorthand) { return concat([line, '{', node.name, '}']); } else { return concat([line, node.name, '={', node.name, '}']); } } else { if (node.value === true) { return concat([line, node.name]); } const quotes = !isLoneMustacheTag(node.value) || options.svelteStrictMode; const attrNodeValue = printAttributeNodeValue(path, print, quotes, node); if (quotes) { return concat([line, node.name, '=', '"', attrNodeValue, '"']); } else { return concat([line, node.name, '=', attrNodeValue]); } } } case 'MustacheTag': return concat([ '{', printJS( path, print, isInsideQuotedAttribute(path, options), false, false, 'expression', ), '}', ]); case 'IfBlock': { const def: Doc[] = [ '{#if ', printSvelteBlockJS(path, print, 'expression'), '}', printSvelteBlockChildren(path, print, options), ]; if (node.else) { def.push(path.call(print, 'else')); } def.push('{/if}'); return concat([groupConcat(def), breakParent]); } case 'ElseBlock': { // Else if const parent = path.getParentNode() as Node; if ( node.children.length === 1 && node.children[0].type === 'IfBlock' && parent.type !== 'EachBlock' ) { const ifNode = node.children[0] as IfBlockNode; const def: Doc[] = [ '{:else if ', path.map( (ifPath) => printSvelteBlockJS(ifPath, print, 'expression'), 'children', )[0], '}', path.map( (ifPath) => printSvelteBlockChildren(ifPath, print, options), 'children', )[0], ]; if (ifNode.else) { def.push(path.map((ifPath) => ifPath.call(print, 'else'), 'children')[0]); } return concat(def); } return concat(['{:else}', printSvelteBlockChildren(path, print, options)]); } case 'EachBlock': { const def: Doc[] = [ '{#each ', printSvelteBlockJS(path, print, 'expression'), ' as', expandNode(node.context), ]; if (node.index) { def.push(', ', node.index); } if (node.key) { def.push(' (', printSvelteBlockJS(path, print, 'key'), ')'); } def.push('}', printSvelteBlockChildren(path, print, options)); if (node.else) { def.push(path.call(print, 'else')); } def.push('{/each}'); return concat([groupConcat(def), breakParent]); } case 'AwaitBlock': { const hasPendingBlock = node.pending.children.some((n) => !isEmptyTextNode(n)); const hasThenBlock = node.then.children.some((n) => !isEmptyTextNode(n)); const hasCatchBlock = node.catch.children.some((n) => !isEmptyTextNode(n)); let block = []; if (!hasPendingBlock && hasThenBlock) { block.push( groupConcat([ '{#await ', printSvelteBlockJS(path, print, 'expression'), ' then', expandNode(node.value), '}', ]), path.call(print, 'then'), ); } else { block.push( groupConcat(['{#await ', printSvelteBlockJS(path, print, 'expression'), '}']), ); if (hasPendingBlock) { block.push(path.call(print, 'pending')); } if (hasThenBlock) { block.push( groupConcat(['{:then', expandNode(node.value), '}']), path.call(print, 'then'), ); } } if (hasCatchBlock) { block.push( groupConcat(['{:catch', expandNode(node.error), '}']), path.call(print, 'catch'), ); } block.push('{/await}'); return groupConcat(block); } case 'KeyBlock': { const def: Doc[] = [ '{#key ', printSvelteBlockJS(path, print, 'expression'), '}', printSvelteBlockChildren(path, print, options), ]; def.push('{/key}'); return concat([groupConcat(def), breakParent]); } case 'ThenBlock': case 'PendingBlock': case 'CatchBlock': return printSvelteBlockChildren(path, print, options); case 'EventHandler': return concat([ line, 'on:', node.name, node.modifiers && node.modifiers.length ? concat(['|', join('|', node.modifiers)]) : '', node.expression ? concat(['=', ...printJsExpression()]) : '', ]); case 'Binding': return concat([ line, 'bind:', node.name, node.expression.type === 'Identifier' && node.expression.name === node.name ? '' : concat(['=', ...printJsExpression()]), ]); case 'Class': return concat([ line, 'class:', node.name, node.expression.type === 'Identifier' && node.expression.name === node.name ? '' : concat(['=', ...printJsExpression()]), ]); case 'StyleDirective': if (isOrCanBeConvertedToShorthand(node)) { if (options.svelteStrictMode) { return concat([line, 'style:', node.name, '="{', node.name, '}"']); } else if (options.svelteAllowShorthand) { return concat([line, 'style:', node.name]); } else { return concat([line, 'style:', node.name, '={', node.name, '}']); } } else { if (node.value === true) { return concat([line, 'style:', node.name]); } const quotes = !isLoneMustacheTag(node.value) || options.svelteStrictMode; const attrNodeValue = printAttributeNodeValue(path, print, quotes, node); if (quotes) { return concat([line, 'style:', node.name, '=', '"', attrNodeValue, '"']); } else { return concat([line, 'style:', node.name, '=', attrNodeValue]); } } case 'Let': return concat([ line, 'let:', node.name, // shorthand let directives have `null` expressions !node.expression || (node.expression.type === 'Identifier' && node.expression.name === node.name) ? '' : concat(['=', ...printJsExpression()]), ]); case 'DebugTag': return concat([ '{@debug', node.identifiers.length > 0 ? concat([' ', join(', ', path.map(print, 'identifiers'))]) : '', '}', ]); case 'Ref': return concat([line, 'ref:', node.name]); case 'Comment': { const nodeAfterComment = getNextNode(path); if (isIgnoreStartDirective(node) && isNodeTopLevelHTML(node, path)) { ignoreRange = true; } else if (isIgnoreEndDirective(node) && isNodeTopLevelHTML(node, path)) { ignoreRange = false; } else if ( // If there is no sibling node that starts right after us but the parent indicates // that there used to be, that means that node was actually an embedded `<style>` // or `<script>` node that was cut out. // If so, the comment does not refer to the next line we will see. // The `embed` function handles printing the comment in the right place. doesEmbedStartAfterNode(node, path) || (isEmptyTextNode(nodeAfterComment) && doesEmbedStartAfterNode(nodeAfterComment, path)) ) { return ''; } else if (isIgnoreDirective(node)) { ignoreNext = true; } return printComment(node); } case 'Transition': const kind = node.intro && node.outro ? 'transition' : node.intro ? 'in' : 'out'; return concat([ line, kind, ':', node.name, node.modifiers && node.modifiers.length ? concat(['|', join('|', node.modifiers)]) : '', node.expression ? concat(['=', ...printJsExpression()]) : '', ]); case 'Action': return concat([ line, 'use:', node.name, node.expression ? concat(['=', ...printJsExpression()]) : '', ]); case 'Animation': return concat([ line, 'animate:', node.name, node.expression ? concat(['=', ...printJsExpression()]) : '', ]); case 'RawMustacheTag': return concat([ '{@html ', printJS(path, print, false, false, false, 'expression'), '}', ]); case 'Spread': return concat([ line, '{...', printJS(path, print, false, false, false, 'expression'), '}', ]); case 'ConstTag': return concat([ '{@const ', printJS(path, print, false, false, true, 'expression'), '}', ]); } console.error(JSON.stringify(node, null, 4)); throw new Error('unknown node type: ' + node.type); } function printTopLevelParts( n: ASTNode, options: ParserOptions, path: FastPath<any>, print: PrintFn, ): Doc { const parts: Record<SortOrderPart, Doc[]> = { options: [], scripts: [], markup: [], styles: [], }; // scripts if (n.module) { n.module.type = 'Script'; n.module.attributes = extractAttributes(getText(n.module, options)); parts.scripts.push(path.call(print, 'module')); } if (n.instance) { n.instance.type = 'Script'; n.instance.attributes = extractAttributes(getText(n.instance, options)); parts.scripts.push(path.call(print, 'instance')); } // styles if (n.css) { n.css.type = 'Style'; n.css.content.type = 'StyleProgram'; parts.styles.push(path.call(print, 'css')); } // markup const htmlDoc = path.call(print, 'html'); if (htmlDoc) { parts.markup.push(htmlDoc); } if (svelteOptionsDoc) { parts.options.push(svelteOptionsDoc); } const docs = flatten(parseSortOrder(options.svelteSortOrder).map((p) => parts[p])); // Need to reset these because they are global and could affect the next formatting run ignoreNext = false; ignoreRange = false; svelteOptionsDoc = undefined; // If this is invoked as an embed of markdown, remove the last hardline. // The markdown parser tries this, too, but fails because it does not // recurse into concats. Doing this will prevent an empty line // at the end of the embedded code block. if (options.parentParser === 'markdown') { const lastDoc = docs[docs.length - 1]; trimRight([lastDoc], isLine); } return groupConcat([join(hardline, docs)]); } function printAttributeNodeValue( path: FastPath<any>, print: PrintFn, quotes: boolean, node: AttributeNode | StyleDirectiveNode, ) { const valueDocs = path.map((childPath) => childPath.call(print), 'value'); if (!quotes || !formattableAttributes.includes(node.name)) { return concat(valueDocs); } else { return indent(groupConcat(trim(valueDocs, isLine))); } } function printSvelteBlockChildren(path: FastPath, print: PrintFn, options: ParserOptions): Doc { const node = path.getValue(); const children = node.children; if (!children || children.length === 0) { return ''; } const whitespaceAtStartOfBlock = checkWhitespaceAtStartOfSvelteBlock(node, options); const whitespaceAtEndOfBlock = checkWhitespaceAtEndOfSvelteBlock(node, options); const startline = whitespaceAtStartOfBlock === 'none' ? '' : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line' ? hardline : line; const endline = whitespaceAtEndOfBlock === 'none' ? '' : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line' ? hardline : line; const firstChild = children[0]; const lastChild = children[children.length - 1]; if (isTextNodeStartingWithWhitespace(firstChild)) { trimTextNodeLeft(firstChild); } if (isTextNodeEndingWithWhitespace(lastChild)) { trimTextNodeRight(lastChild); } return concat([ indent(concat([startline, group(printChildren(path, print, options))])), endline, ]); } function printPre( node: Parameters<typeof printRaw>[0], originalText: string, path: FastPath, print: PrintFn, ): Doc { const result: Doc = []; const length = node.children.length; for (let i = 0; i < length; i++) { const child = node.children[i]; if (child.type === 'Text') { const lines = originalText.substring(child.start, child.end).split(/\r?\n/); lines.forEach((line, j) => { if (j > 0) result.push(literalline); result.push(line); }); } else { result.push(path.call(print, 'children', i)); } } return concat(result); } function printChildren(path: FastPath, print: PrintFn, options: ParserOptions): Doc { if (isPreTagContent(path)) { return concat(path.map(print, 'children')); } const childNodes: Node[] = prepareChildren(path.getValue().children, path, print); // modify original array because it's accessed later through map(print, 'children', idx) path.getValue().children = childNodes; if (childNodes.length === 0) { return ''; } const childDocs: Doc[] = []; let handleWhitespaceOfPrevTextNode = false; for (let i = 0; i < childNodes.length; i++) { const childNode = childNodes[i]; if (childNode.type === 'Text') { handleTextChild(i, childNode); } else if (isBlockElement(childNode, options)) { handleBlockChild(i); } else if (isInlineElement(path, options, childNode)) { handleInlineChild(i); } else { childDocs.push(printChild(i)); handleWhitespaceOfPrevTextNode = false; } } // If there's at least one block element and more than one node, break content const forceBreakContent = childNodes.length > 1 && childNodes.some((child) => isBlockElement(child, options)); if (forceBreakContent) { childDocs.push(breakParent); } return concat(childDocs); function printChild(idx: number): Doc { return path.call(print, 'children', idx); } /** * Print inline child. Hug whitespace of previous text child if there was one. */ function handleInlineChild(idx: number) { if (handleWhitespaceOfPrevTextNode) { childDocs.push(groupConcat([line, printChild(idx)])); } else { childDocs.push(printChild(idx)); } handleWhitespaceOfPrevTextNode = false; } /** * Print block element. Add softlines around it if needed * so it breaks into a separate line if children are broken up. * Don't add lines at the start/end if it's the first/last child because this * kind of whitespace handling is done in the parent already. */ function handleBlockChild(idx: number) { const prevChild = childNodes[idx - 1]; if ( prevChild && !isBlockElement(prevChild, options) && (prevChild.type !== 'Text' || handleWhitespaceOfPrevTextNode || !isTextNodeEndingWithWhitespace(prevChild)) ) { childDocs.push(softline); } childDocs.push(printChild(idx)); const nextChild = childNodes[idx + 1]; if ( nextChild && (nextChild.type !== 'Text' || // Only handle text which starts with a whitespace and has text afterwards, // or is empty but followed by an inline element. The latter is done // so that if the children break, the inline element afterwards is in a separate line. ((!isEmptyTextNode(nextChild) || (childNodes[idx + 2] && isInlineElement(path, options, childNodes[idx + 2]))) && !isTextNodeStartingWithLinebreak(nextChild))) ) { childDocs.push(softline); } handleWhitespaceOfPrevTextNode = false; } /** * Print text child. First/last child white space handling * is done in parent already. By definition of the Svelte AST, * a text node always is inbetween other tags. Add hardlines * if the users wants to have them inbetween. * If the text is trimmed right, toggle flag telling * subsequent (inline)block element to alter its printing logic * to check if they need to hug or print lines themselves. */ function handleTextChild(idx: number, childNode: TextNode) { handleWhitespaceOfPrevTextNode = false; if (idx === 0 || idx === childNodes.length - 1) { childDocs.push(printChild(idx)); return; } const prevNode = childNodes[idx - 1]; const nextNode = childNodes[idx + 1]; if ( isTextNodeStartingWithWhitespace(childNode) && // If node is empty, go straight through to checking the right end !isEmptyTextNode(childNode) ) { if ( isInlineElement(path, options, prevNode) && !isTextNodeStartingWithLinebreak(childNode) ) { trimTextNodeLeft(childNode); const lastChildDoc = childDocs.pop()!; childDocs.push(groupConcat([lastChildDoc, line])); } if (isBlockElement(prevNode, options) && !isTextNodeStartingWithLinebreak(childNode)) { trimTextNodeLeft(childNode); } } if (isTextNodeEndingWithWhitespace(childNode)) { if ( isInlineElement(path, options, nextNode) && !isTextNodeEndingWithLinebreak(childNode) ) { handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options); trimTextNodeRight(childNode); } if (isBlockElement(nextNode, options) && !isTextNodeEndingWithLinebreak(childNode, 2)) { handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options); trimTextNodeRight(childNode); } } childDocs.push(printChild(idx)); } } /** * `svelte:options` is part of the html part but needs to be snipped out and handled * separately to reorder it as configured. The comment above it should be moved with it. * Do that here. */ function prepareChildren(children: Node[], path: FastPath, print: PrintFn): Node[] { let svelteOptionsComment: Doc | undefined; const childrenWithoutOptions = []; for (let idx = 0; idx < children.length; idx++) { const currentChild = children[idx]; if (currentChild.type === 'Text' && getUnencodedText(currentChild) === '') { continue; } if (isEmptyTextNode(currentChild) && doesEmbedStartAfterNode(currentChild, path)) { continue; } if (isCommentFollowedByOptions(currentChild, idx)) { svelteOptionsComment = printComment(currentChild); const nextChild = children[idx + 1]; idx += nextChild && isEmptyTextNode(nextChild) ? 1 : 0; continue; } if (currentChild.type === 'Options') { printSvelteOptions(currentChild, idx, path, print); continue; } childrenWithoutOptions.push(currentChild); } const mergedChildrenWithoutOptions = []; for (let idx = 0; idx < childrenWithoutOptions.length; idx++) { const currentChild = childrenWithoutOptions[idx]; const nextChild = childrenWithoutOptions[idx + 1]; if (currentChild.type === 'Text' && nextChild && nextChild.type === 'Text') { // A tag was snipped out (f.e. svelte:options). Join text currentChild.raw += nextChild.raw; currentChild.data += nextChild.data; idx++; } mergedChildrenWithoutOptions.push(currentChild); } return mergedChildrenWithoutOptions; function printSvelteOptions( node: OptionsNode, idx: number, path: FastPath, print: PrintFn, ): void { svelteOptionsDoc = groupConcat([ groupConcat([ '<', node.name, indent(groupConcat(path.map(print, 'children', idx, 'attributes'))), ' />', ]), hardline, ]); if (svelteOptionsComment) { svelteOptionsDoc = groupConcat([svelteOptionsComment, hardline, svelteOptionsDoc]); } } function isCommentFollowedByOptions(node: Node, idx: number): node is CommentNode { if (node.type !== 'Comment' || isIgnoreEndDirective(node) || isIgnoreStartDirective(node)) { return false; } const nextChild = children[idx + 1]; if (nextChild) { if (isEmptyTextNode(nextChild)) { const afterNext = children[idx + 2]; return afterNext && afterNext.type === 'Options'; } return nextChild.type === 'Options'; } return false; } } /** * Split the text into words separated by whitespace. Replace the whitespaces by lines, * collapsing multiple whitespaces into a single line. * * If the text starts or ends with multiple newlines, two of those should be kept. */ function splitTextToDocs(node: TextNode): Doc[] { const text = getUnencodedText(node); let docs: Doc[] = text.split(/[\t\n\f\r ]+/); docs = join(line, docs).parts.filter((s) => s !== ''); if (startsWithLinebreak(text)) { docs[0] = hardline; } if (startsWithLinebreak(text, 2)) { docs = [hardline, ...docs]; } if (endsWithLinebreak(text)) { docs[docs.length - 1] = hardline; } if (endsWithLinebreak(text, 2)) { docs = [...docs, hardline]; } return docs; } function printSvelteBlockJS(path: FastPath, print: PrintFn, name: string) { return printJS(path, print, false, true, false, name); } function printJS( path: FastPath, print: PrintFn, forceSingleQuote: boolean, forceSingleLine: boolean, removeParentheses: boolean, name: string, ) { path.getValue()[name].isJS = true; path.getValue()[name].forceSingleQuote = forceSingleQuote; path.getValue()[name].forceSingleLine = forceSingleLine; path.getValue()[name].removeParentheses = removeParentheses; return path.call(print, name); } function expandNode(node: any, parent?: any): string { if (node === null) { return ''; } if (typeof node === 'string') { // pre-v3.20 AST return ' ' + node; } switch (node.type) { case 'ArrayExpression': case 'ArrayPattern': return ' [' + node.elements.map(expandNode).join(',').slice(1) + ']'; case 'AssignmentPattern': return expandNode(node.left) + ' =' + expandNode(node.right); case 'Identifier': return ' ' + node.name; case 'Literal': return ' ' + node.raw; case 'ObjectExpression': return ' {' + node.properties.map((p: any) => expandNode(p, node)).join(',') + ' }'; case 'ObjectPattern': return ' {' + node.properties.map(expandNode).join(',') + ' }'; case 'Property': if (node.value.type === 'ObjectPattern' || node.value.type === 'ArrayPattern') { return ' ' + node.key.name + ':' + expandNode(node.value); } else if ( (node.value.type === 'Identifier' && node.key.name !== node.value.name) || (parent && parent.type === 'ObjectExpression') ) { return expandNode(node.key) + ':' + expandNode(node.value); } else { return expandNode(node.value); } case 'RestElement': return ' ...' + node.argument.name; } console.error(JSON.stringify(node, null, 4)); throw new Error('unknown node type: ' + node.type); } function printComment(node: CommentNode) { let text = node.data; if (hasSnippedContent(text)) { text = unsnipContent(text); } return groupConcat(['<!--', text, '-->']); }
the_stack
import { ModelAuthTransformer } from 'graphql-auth-transformer'; import { ModelConnectionTransformer } from 'graphql-connection-transformer'; import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer'; import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core'; import { GraphQLClient } from './utils/graphql-client'; import { deploy, launchDDBLocal, logDebug, terminateDDB } from './utils/index'; import { signUpAddToGroupAndGetJwtToken } from './utils/cognito-utils'; import 'isomorphic-fetch'; jest.setTimeout(2000000); let GRAPHQL_ENDPOINT = undefined; let ddbEmulator = null; let dbPath = null; let server; /** * Client 1 is logged in and is a member of the Admin group. */ let GRAPHQL_CLIENT_1 = undefined; /** * Client 2 is logged in and is a member of the Devs group. */ let GRAPHQL_CLIENT_2 = undefined; /** * Client 3 is logged in and has no group memberships. */ let GRAPHQL_CLIENT_3 = undefined; const USER_POOL_ID = 'fake_user_pool'; const USERNAME1 = 'user1@test.com'; const USERNAME2 = 'user2@test.com'; const USERNAME3 = 'user3@test.com'; const ADMIN_GROUP_NAME = 'Admin'; const DEVS_GROUP_NAME = 'Devs'; const PARTICIPANT_GROUP_NAME = 'Participant'; const WATCHER_GROUP_NAME = 'Watcher'; const INSTRUCTOR_GROUP_NAME = 'Instructor'; beforeAll(async () => { const validSchema = `# Owners may update their owned records. # Admins may create Employee records. # Any authenticated user may view Employee ids & emails. # Owners and members of "Admin" group may see employee salaries. # Owners of "Admin" group may create and update employee salaries. type Employee @model ( subscriptions: { level: public } ) @auth(rules: [ { allow: owner, ownerField: "email", operations: [update] }, { allow: groups, groups: ["Admin"], operations: [create,update,delete]} ]) { id: ID! # The only field that can be updated by the owner. bio: String # Fields with ownership conditions take precendence to the Object @auth. # That means that both the @auth on Object AND the @auth on the field must # be satisfied. # Owners & "Admin"s may view employee email addresses. Only "Admin"s may create/update. # TODO: { allow: authenticated } would be useful here so that any employee could view. email: String @auth(rules: [ { allow: groups, groups: ["Admin"], operations: [create, update, read]} { allow: owner, ownerField: "email", operations: [read]} ]) # The owner & "Admin"s may view the salary. Only "Admins" may create/update. salary: Int @auth(rules: [ { allow: groups, groups: ["Admin"], operations: [create, update, read]} { allow: owner, ownerField: "email", operations: [read]} ]) # The delete operation means you cannot update the value to "null" or "undefined". # Since delete operations are at the object level, this actually adds auth rules to the update mutation. notes: String @auth(rules: [{ allow: owner, ownerField: "email", operations: [delete] }]) } type Student @model @auth(rules: [ {allow: owner} {allow: groups, groups: ["Instructor"]} ]) { id: String, name: String, bio: String, notes: String @auth(rules: [{allow: owner}]) } type Post @model @auth(rules: [{ allow: groups, groups: ["Admin"] }, { allow: owner, ownerField: "owner1", operations: [read, create] }]) { id: ID! owner1: String! @auth(rules: [{allow: owner, ownerField: "notAllowed", operations: [update]}]) text: String @auth(rules: [{ allow: owner, ownerField: "owner1", operations : [update]}]) } # add auth on a field type Query { someFunction: String @auth(rules: [{ allow: groups, groups: ["Admin"] }]) } `; const transformer = new GraphQLTransform({ transformers: [ new DynamoDBModelTransformer(), new ModelConnectionTransformer(), new ModelAuthTransformer({ authConfig: { defaultAuthentication: { authenticationType: 'AMAZON_COGNITO_USER_POOLS', }, additionalAuthenticationProviders: [], }, }), ], featureFlags: { getBoolean: name => (name === 'improvePluralization' ? true : false), } as FeatureFlagProvider, }); try { const out = transformer.transform(validSchema); let ddbClient; ({ dbPath, emulator: ddbEmulator, client: ddbClient } = await launchDDBLocal()); const result = await deploy(out, ddbClient); server = result.simulator; GRAPHQL_ENDPOINT = server.url + '/graphql'; // Verify we have all the details expect(GRAPHQL_ENDPOINT).toBeTruthy(); // Configure Amplify, create users, and sign in. const idToken = signUpAddToGroupAndGetJwtToken(USER_POOL_ID, USERNAME1, USERNAME1, [ ADMIN_GROUP_NAME, PARTICIPANT_GROUP_NAME, WATCHER_GROUP_NAME, INSTRUCTOR_GROUP_NAME, ]); GRAPHQL_CLIENT_1 = new GraphQLClient(GRAPHQL_ENDPOINT, { Authorization: idToken, }); const idToken2 = signUpAddToGroupAndGetJwtToken(USER_POOL_ID, USERNAME2, USERNAME2, [DEVS_GROUP_NAME, INSTRUCTOR_GROUP_NAME]); GRAPHQL_CLIENT_2 = new GraphQLClient(GRAPHQL_ENDPOINT, { Authorization: idToken2, }); const idToken3 = signUpAddToGroupAndGetJwtToken(USER_POOL_ID, USERNAME3, USERNAME3, []); GRAPHQL_CLIENT_3 = new GraphQLClient(GRAPHQL_ENDPOINT, { Authorization: idToken3, }); // Wait for any propagation to avoid random // "The security token included in the request is invalid" errors await new Promise<void>(res => setTimeout(() => res(), 5000)); } catch (e) { console.error(e); expect(true).toEqual(false); } }); afterAll(async () => { try { if (server) { await server.stop(); } await terminateDDB(ddbEmulator, dbPath); } catch (e) { console.error(e); throw e; } }); /** * Tests */ test('Test that only Admins can create Employee records.', async () => { const createUser1 = await GRAPHQL_CLIENT_1.query( `mutation { createEmployee(input: { email: "user2@test.com", salary: 100 }) { id email salary } }`, {}, ); logDebug(createUser1); expect(createUser1.data.createEmployee.email).toEqual('user2@test.com'); expect(createUser1.data.createEmployee.salary).toEqual(100); const tryToCreateAsNonAdmin = await GRAPHQL_CLIENT_2.query( `mutation { createEmployee(input: { email: "user2@test.com", salary: 101 }) { id email salary } }`, {}, ); logDebug(tryToCreateAsNonAdmin); expect(tryToCreateAsNonAdmin.data.createEmployee).toBeNull(); expect(tryToCreateAsNonAdmin.errors).toHaveLength(1); const tryToCreateAsNonAdmin2 = await GRAPHQL_CLIENT_3.query( `mutation { createEmployee(input: { email: "user2@test.com", salary: 101 }) { id email salary } }`, {}, ); logDebug(tryToCreateAsNonAdmin2); expect(tryToCreateAsNonAdmin2.data.createEmployee).toBeNull(); expect(tryToCreateAsNonAdmin2.errors).toHaveLength(1); }); test('Test that only Admins may update salary & email.', async () => { const createUser1 = await GRAPHQL_CLIENT_1.query( `mutation { createEmployee(input: { email: "user2@test.com", salary: 100 }) { id email salary } }`, {}, ); logDebug(createUser1); const employeeId = createUser1.data.createEmployee.id; expect(employeeId).not.toBeNull(); expect(createUser1.data.createEmployee.email).toEqual('user2@test.com'); expect(createUser1.data.createEmployee.salary).toEqual(100); const tryToUpdateAsNonAdmin = await GRAPHQL_CLIENT_2.query( `mutation { updateEmployee(input: { id: "${employeeId}", salary: 101 }) { id email salary } }`, {}, ); logDebug(tryToUpdateAsNonAdmin); expect(tryToUpdateAsNonAdmin.data.updateEmployee).toBeNull(); expect(tryToUpdateAsNonAdmin.errors).toHaveLength(1); const tryToUpdateAsNonAdmin2 = await GRAPHQL_CLIENT_2.query( `mutation { updateEmployee(input: { id: "${employeeId}", email: "someonelese@gmail.com" }) { id email salary } }`, {}, ); logDebug(tryToUpdateAsNonAdmin2); expect(tryToUpdateAsNonAdmin2.data.updateEmployee).toBeNull(); expect(tryToUpdateAsNonAdmin2.errors).toHaveLength(1); const tryToUpdateAsNonAdmin3 = await GRAPHQL_CLIENT_3.query( `mutation { updateEmployee(input: { id: "${employeeId}", email: "someonelese@gmail.com" }) { id email salary } }`, {}, ); logDebug(tryToUpdateAsNonAdmin3); expect(tryToUpdateAsNonAdmin3.data.updateEmployee).toBeNull(); expect(tryToUpdateAsNonAdmin3.errors).toHaveLength(1); const updateAsAdmin = await GRAPHQL_CLIENT_1.query( `mutation { updateEmployee(input: { id: "${employeeId}", email: "someonelese@gmail.com" }) { id email salary } }`, {}, ); logDebug(updateAsAdmin); expect(updateAsAdmin.data.updateEmployee.email).toEqual('someonelese@gmail.com'); expect(updateAsAdmin.data.updateEmployee.salary).toEqual(100); const updateAsAdmin2 = await GRAPHQL_CLIENT_1.query( `mutation { updateEmployee(input: { id: "${employeeId}", salary: 99 }) { id email salary } }`, {}, ); logDebug(updateAsAdmin2); expect(updateAsAdmin2.data.updateEmployee.email).toEqual('someonelese@gmail.com'); expect(updateAsAdmin2.data.updateEmployee.salary).toEqual(99); }); test('Test that owners may update their bio.', async () => { const createUser1 = await GRAPHQL_CLIENT_1.query( `mutation { createEmployee(input: { email: "user2@test.com", salary: 100 }) { id email salary } }`, {}, ); logDebug(createUser1); const employeeId = createUser1.data.createEmployee.id; expect(employeeId).not.toBeNull(); expect(createUser1.data.createEmployee.email).toEqual('user2@test.com'); expect(createUser1.data.createEmployee.salary).toEqual(100); const tryToUpdateAsNonAdmin = await GRAPHQL_CLIENT_2.query( `mutation { updateEmployee(input: { id: "${employeeId}", bio: "Does cool stuff." }) { id email salary bio } }`, {}, ); logDebug(tryToUpdateAsNonAdmin); expect(tryToUpdateAsNonAdmin.data.updateEmployee.bio).toEqual('Does cool stuff.'); expect(tryToUpdateAsNonAdmin.data.updateEmployee.email).toEqual('user2@test.com'); expect(tryToUpdateAsNonAdmin.data.updateEmployee.salary).toEqual(100); }); test('Test that everyone may view employee bios.', async () => { const createUser1 = await GRAPHQL_CLIENT_1.query( `mutation { createEmployee(input: { email: "user3@test.com", salary: 100, bio: "Likes long walks on the beach" }) { id email salary bio } }`, {}, ); logDebug(createUser1); const employeeId = createUser1.data.createEmployee.id; expect(employeeId).not.toBeNull(); expect(createUser1.data.createEmployee.email).toEqual('user3@test.com'); expect(createUser1.data.createEmployee.salary).toEqual(100); expect(createUser1.data.createEmployee.bio).toEqual('Likes long walks on the beach'); const getAsNonAdmin = await GRAPHQL_CLIENT_2.query( `query { getEmployee(id: "${employeeId}") { id email bio } }`, {}, ); logDebug(getAsNonAdmin); // Should not be able to view the email as the non owner expect(getAsNonAdmin.data.getEmployee.email).toBeNull(); // Should be able to view the bio. expect(getAsNonAdmin.data.getEmployee.bio).toEqual('Likes long walks on the beach'); expect(getAsNonAdmin.errors).toHaveLength(1); const listAsNonAdmin = await GRAPHQL_CLIENT_2.query( `query { listEmployees { items { id bio } } }`, {}, ); logDebug(listAsNonAdmin); expect(listAsNonAdmin.data.listEmployees.items.length).toBeGreaterThan(1); let seenId = false; for (const item of listAsNonAdmin.data.listEmployees.items) { if (item.id === employeeId) { seenId = true; expect(item.bio).toEqual('Likes long walks on the beach'); } } expect(seenId).toEqual(true); }); test('Test that only owners may "delete" i.e. update the field to null.', async () => { const createUser1 = await GRAPHQL_CLIENT_1.query( `mutation { createEmployee(input: { email: "user3@test.com", salary: 200, notes: "note1" }) { id email salary notes } }`, {}, ); logDebug(createUser1); const employeeId = createUser1.data.createEmployee.id; expect(employeeId).not.toBeNull(); expect(createUser1.data.createEmployee.email).toEqual('user3@test.com'); expect(createUser1.data.createEmployee.salary).toEqual(200); expect(createUser1.data.createEmployee.notes).toEqual('note1'); const tryToDeleteUserNotes = await GRAPHQL_CLIENT_2.query( `mutation { updateEmployee(input: { id: "${employeeId}", notes: null }) { id notes } }`, {}, ); logDebug(tryToDeleteUserNotes); expect(tryToDeleteUserNotes.data.updateEmployee).toBeNull(); expect(tryToDeleteUserNotes.errors).toHaveLength(1); const updateNewsWithNotes = await GRAPHQL_CLIENT_3.query( `mutation { updateEmployee(input: { id: "${employeeId}", notes: "something else" }) { id notes } }`, {}, ); expect(updateNewsWithNotes.data.updateEmployee.notes).toEqual('something else'); const updateAsAdmin = await GRAPHQL_CLIENT_1.query( `mutation { updateEmployee(input: { id: "${employeeId}", notes: null }) { id notes } }`, {}, ); expect(updateAsAdmin.data.updateEmployee).toBeNull(); expect(updateAsAdmin.errors).toHaveLength(1); const deleteNotes = await GRAPHQL_CLIENT_3.query( `mutation { updateEmployee(input: { id: "${employeeId}", notes: null }) { id notes } }`, {}, ); expect(deleteNotes.data.updateEmployee.notes).toBeNull(); }); test('Test with auth with subscriptions on default behavior', async () => { /** * client 1 and 2 are in the same user pool though client 1 should * not be able to see notes if they are created by client 2 * */ const secureNote1 = 'secureNote1'; const createStudent2 = await GRAPHQL_CLIENT_2.query( `mutation { createStudent(input: {bio: "bio1", name: "student1", notes: "${secureNote1}"}) { id bio name notes owner } }`, {}, ); logDebug(createStudent2); expect(createStudent2.data.createStudent.id).toBeDefined(); const createStudent1queryID = createStudent2.data.createStudent.id; expect(createStudent2.data.createStudent.bio).toEqual('bio1'); expect(createStudent2.data.createStudent.notes).toBeNull(); // running query as username2 should return value const queryForStudent2 = await GRAPHQL_CLIENT_2.query( `query { getStudent(id: "${createStudent1queryID}") { bio id name notes owner } }`, {}, ); logDebug(queryForStudent2); expect(queryForStudent2.data.getStudent.notes).toEqual(secureNote1); // running query as username3 should return the type though return notes as null const queryAsStudent1 = await GRAPHQL_CLIENT_1.query( `query { getStudent(id: "${createStudent1queryID}") { bio id name notes owner } }`, {}, ); console.log(JSON.stringify(queryAsStudent1)); expect(queryAsStudent1.data.getStudent.notes).toBeNull(); }); test('AND per-field dynamic auth rule test', async () => { const createPostResponse = await GRAPHQL_CLIENT_1.query(`mutation CreatePost { createPost(input: {owner1: "${USERNAME1}", text: "mytext"}) { id text owner1 } }`); logDebug(createPostResponse); const postID1 = createPostResponse.data.createPost.id; expect(postID1).toBeDefined(); expect(createPostResponse.data.createPost.text).toEqual('mytext'); expect(createPostResponse.data.createPost.owner1).toEqual(USERNAME1); const badUpdatePostResponse = await GRAPHQL_CLIENT_1.query(`mutation UpdatePost { updatePost(input: {id: "${postID1}", text: "newText", owner1: "${USERNAME1}"}) { id owner1 text } } `); logDebug(badUpdatePostResponse); expect(badUpdatePostResponse.errors[0].data).toBeNull(); expect(badUpdatePostResponse.errors[0].errorType).toEqual('DynamoDB:ConditionalCheckFailedException'); const correctUpdatePostResponse = await GRAPHQL_CLIENT_1.query(`mutation UpdatePost { updatePost(input: {id: "${postID1}", text: "newText"}) { id owner1 text } }`); logDebug(correctUpdatePostResponse); expect(correctUpdatePostResponse.data.updatePost.owner1).toEqual(USERNAME1); expect(correctUpdatePostResponse.data.updatePost.text).toEqual('newText'); }); test('test field auth on an operation type as user in admin group', async () => { const queryResponse = await GRAPHQL_CLIENT_1.query(` query SomeFunction { someFunction } `); // no errors though it should return null logDebug(queryResponse); expect(queryResponse.data.someFunction).toBeNull(); }); test('test field auth on an operation type as user not in admin group', async () => { const queryResponse = await GRAPHQL_CLIENT_3.query(` query SomeFunction { someFunction } `); // should return an error logDebug(queryResponse); expect(queryResponse.errors).toBeDefined(); expect(queryResponse.errors[0].message).toEqual('Unauthorized'); });
the_stack
import { closest, classList, createElement, remove, addClass, removeClass, isNullOrUndefined, Base, formatUnit, createInstance, detach } from '@syncfusion/ej2-base'; import { Kanban } from '../base/kanban'; import { CardClickEventArgs, ActionEventArgs } from '../base/interface'; import { ColumnsModel } from '../models'; import { Columns } from '../models/columns'; import * as events from '../base/constant'; import * as cls from '../base/css-constant'; /** * Action module is used to perform card actions. */ export class Action { private parent: Kanban; public columnToggleArray: string[]; public selectionArray: string[]; public lastCardSelection: Element; private lastSelectionRow: HTMLTableRowElement; private lastCard: Element; private selectedCardsElement: Element[]; private selectedCardsData: Record<string, any>[]; public hideColumnKeys: string[]; /** * Constructor for action module * * @param {Kanban} parent Accepts the kanban instance * @private */ constructor(parent: Kanban) { this.parent = parent; this.columnToggleArray = []; this.selectionArray = []; this.lastCardSelection = null; this.lastSelectionRow = null; this.lastCard = null; this.selectedCardsElement = []; this.selectedCardsData = []; this.hideColumnKeys = []; } public clickHandler(e: KeyboardEvent): void { const elementSelector: string = '.' + cls.CARD_CLASS + ',.' + cls.HEADER_ICON_CLASS + ',.' + cls.CONTENT_ROW_CLASS + '.' + cls.SWIMLANE_ROW_CLASS + ',.' + cls.SHOW_ADD_BUTTON + ',.' + cls.FROZEN_SWIMLANE_ROW_CLASS + ',.' + cls.CONTENT_ROW_CLASS + ':not(.' + cls.SWIMLANE_ROW_CLASS + ') .' + cls.CONTENT_CELLS_CLASS; const target: Element = closest(e.target as Element, elementSelector); if (!target) { return; } if (target.classList.contains(cls.CARD_CLASS)) { if (this.parent.allowKeyboard) { this.parent.keyboardModule.cardTabIndexRemove(); } this.cardClick(e); } else if (target.classList.contains(cls.HEADER_ICON_CLASS)) { this.columnExpandCollapse(e); } else if (target.classList.contains(cls.CONTENT_ROW_CLASS) && target.classList.contains(cls.SWIMLANE_ROW_CLASS)) { this.rowExpandCollapse(e); } else if (target.classList.contains(cls.SHOW_ADD_BUTTON)) { this.addButtonClick(target); } else if (target.classList.contains(cls.FROZEN_SWIMLANE_ROW_CLASS)) { const swimlaneRows: HTMLElement[] = [].slice.call(this.parent.element.querySelectorAll('.' + cls.SWIMLANE_ROW_CLASS)); let targetIcon: HTMLElement = this.parent.layoutModule.frozenSwimlaneRow.querySelector('.' + cls.ICON_CLASS); this.rowExpandCollapse(e, swimlaneRows[this.parent.layoutModule.frozenOrder]); const isCollapsed: boolean = targetIcon.classList.contains(cls.SWIMLANE_ROW_COLLAPSE_CLASS) ? true : false; if (isCollapsed) { classList(targetIcon, [cls.SWIMLANE_ROW_EXPAND_CLASS], [cls.SWIMLANE_ROW_COLLAPSE_CLASS]); } else { classList(targetIcon, [cls.SWIMLANE_ROW_COLLAPSE_CLASS], [cls.SWIMLANE_ROW_EXPAND_CLASS]); } } } public addButtonClick(target: Element): void { const newData: { [key: string]: string | number } = {}; if (this.parent.kanbanData.length === 0) { newData[this.parent.cardSettings.headerField] = 1; } else if (typeof (this.parent.kanbanData[0])[this.parent.cardSettings.headerField] === 'number') { const id: number[] = this.parent.kanbanData.map((obj: { [key: string]: string }) => parseInt(obj[this.parent.cardSettings.headerField], 10)); newData[this.parent.cardSettings.headerField] = Math.max(...id) + 1; } newData[this.parent.keyField] = closest(target, '.' + cls.CONTENT_CELLS_CLASS).getAttribute('data-key'); if (this.parent.sortSettings.sortBy === 'Index') { newData[this.parent.sortSettings.field] = 1; if (closest(target, '.' + cls.CONTENT_CELLS_CLASS).querySelector('.' + cls.CARD_CLASS)) { const card: Element = this.parent.sortSettings.direction === 'Ascending' ? target.nextElementSibling.lastElementChild : target.nextElementSibling.firstElementChild; const data: Record<string, any> = this.parent.getCardDetails(card) as Record<string, any>; newData[this.parent.sortSettings.field] = data[this.parent.sortSettings.field] as number + 1; } } if (this.parent.kanbanData.length !== 0 && this.parent.swimlaneSettings.keyField && closest(target, '.' + cls.CONTENT_ROW_CLASS).previousElementSibling) { newData[this.parent.swimlaneSettings.keyField] = closest(target, '.' + cls.CONTENT_ROW_CLASS).previousElementSibling.getAttribute('data-key'); } this.parent.openDialog('Add', newData); } public doubleClickHandler(e: MouseEvent): void { const target: Element = closest(e.target as Element, '.' + cls.CARD_CLASS); if (target) { this.cardDoubleClick(e); } } public cardClick(e: KeyboardEvent, selectedCard?: HTMLElement): void { const target: Element = closest((selectedCard) ? selectedCard : e.target as Element, '.' + cls.CARD_CLASS); const cardClickObj: Record<string, any> = this.parent.getCardDetails(target); if (cardClickObj) { this.parent.activeCardData = { data: cardClickObj, element: target }; const args: CardClickEventArgs = { data: cardClickObj, element: target, cancel: false, event: e }; this.parent.trigger(events.cardClick, args, (clickArgs: CardClickEventArgs) => { if (!clickArgs.cancel) { if (target.classList.contains(cls.CARD_SELECTION_CLASS) && e.type === 'click') { removeClass([target], cls.CARD_SELECTION_CLASS); this.parent.layoutModule.disableAttributeSelection(target); } else { let isCtrlKey: boolean = e.ctrlKey; if (this.parent.isAdaptive && this.parent.touchModule) { isCtrlKey = (this.parent.touchModule.mobilePopup && this.parent.touchModule.tabHold) || isCtrlKey; } this.cardSelection(target, isCtrlKey, e.shiftKey); } if (this.parent.isAdaptive && this.parent.touchModule) { this.parent.touchModule.updatePopupContent(); } const cell: Element = closest(target, '.' + cls.CONTENT_CELLS_CLASS); if (this.parent.allowKeyboard) { const element: HTMLElement[] = [].slice.call(cell.querySelectorAll('.' + cls.CARD_CLASS)); element.forEach((e: HTMLElement): void => { e.setAttribute('tabindex', '0'); }); this.parent.keyboardModule.addRemoveTabIndex('Remove'); } } }); } } private cardDoubleClick(e: Event): void { const target: Element = closest(e.target as Element, '.' + cls.CARD_CLASS); const cardDoubleClickObj: Record<string, any> = this.parent.getCardDetails(target); this.parent.activeCardData = { data: cardDoubleClickObj, element: target }; this.cardSelection(target, false, false); const args: CardClickEventArgs = { data: cardDoubleClickObj, element: target, cancel: false, event: e }; this.parent.trigger(events.cardDoubleClick, args, (doubleClickArgs: CardClickEventArgs) => { if (!doubleClickArgs.cancel) { this.parent.dialogModule.openDialog('Edit', args.data); } }); } public rowExpandCollapse(e: Event | HTMLElement, isFrozenElem?: HTMLElement): void { const headerTarget: HTMLElement = (e instanceof HTMLElement) ? e : e.target as HTMLElement; let currentSwimlaneHeader: HTMLElement = !isNullOrUndefined(isFrozenElem) ? isFrozenElem : headerTarget; const args: ActionEventArgs = { cancel: false, target: headerTarget, requestType: 'rowExpandCollapse' }; this.parent.trigger(events.actionBegin, args, (actionArgs: ActionEventArgs) => { if (!actionArgs.cancel) { const target: HTMLTableRowElement = closest(currentSwimlaneHeader as Element, '.' + cls.SWIMLANE_ROW_CLASS) as HTMLTableRowElement; const key: string = target.getAttribute('data-key'); const tgtRow: Element = this.parent.element.querySelector('.' + cls.CONTENT_ROW_CLASS + `:nth-child(${target.rowIndex + 2})`); const targetIcon: Element = target.querySelector(`.${cls.SWIMLANE_ROW_EXPAND_CLASS},.${cls.SWIMLANE_ROW_COLLAPSE_CLASS}`); const isCollapsed: boolean = target.classList.contains(cls.COLLAPSED_CLASS) ? true : false; let tabIndex: string; if (isCollapsed) { removeClass([tgtRow, target], cls.COLLAPSED_CLASS); classList(targetIcon, [cls.SWIMLANE_ROW_EXPAND_CLASS], [cls.SWIMLANE_ROW_COLLAPSE_CLASS]); this.parent.swimlaneToggleArray.splice(this.parent.swimlaneToggleArray.indexOf(key), 1); tabIndex = '0'; } else { addClass([tgtRow, target], cls.COLLAPSED_CLASS); classList(targetIcon, [cls.SWIMLANE_ROW_COLLAPSE_CLASS], [cls.SWIMLANE_ROW_EXPAND_CLASS]); this.parent.swimlaneToggleArray.push(key); tabIndex = '-1'; } targetIcon.setAttribute('aria-label', isCollapsed ? key + ' Expand' : key + ' Collapse'); target.setAttribute('aria-expanded', isCollapsed.toString()); tgtRow.setAttribute('aria-expanded', isCollapsed.toString()); const rows: HTMLElement[] = [].slice.call(tgtRow.querySelectorAll('.' + cls.CONTENT_CELLS_CLASS)); rows.forEach((cell: HTMLElement) => { cell.setAttribute('tabindex', tabIndex); }); this.parent.notify(events.contentReady, {}); this.parent.trigger(events.actionComplete, { target: headerTarget, requestType: 'rowExpandCollapse' }); } }); } public columnExpandCollapse(e: Event | HTMLElement): void { const headerTarget: HTMLElement = (e instanceof HTMLElement) ? e : e.target as HTMLElement; const args: ActionEventArgs = { cancel: false, target: headerTarget as HTMLElement, requestType: 'columnExpandCollapse' }; this.parent.trigger(events.actionBegin, args, (actionArgs: ActionEventArgs) => { if (!actionArgs.cancel) { const target: HTMLElement = closest(headerTarget, '.' + cls.HEADER_CELLS_CLASS) as HTMLElement; const colIndex: number = (target as HTMLTableHeaderCellElement).cellIndex; this.columnToggle(target as HTMLTableHeaderCellElement); const collapsed: number = this.parent.element.querySelectorAll(`.${cls.HEADER_CELLS_CLASS}.${cls.COLLAPSED_CLASS}`).length; if (collapsed === (this.parent.columns.length - this.hideColumnKeys.length)) { const index: number = (colIndex + 1 === collapsed) ? 1 : colIndex + 2; const headerSelector: string = `.${cls.HEADER_CELLS_CLASS}:not(.${cls.STACKED_HEADER_CELL_CLASS}):nth-child(${index})`; const nextCol: Element = this.parent.element.querySelector(headerSelector); addClass([nextCol], cls.COLLAPSED_CLASS); this.columnToggle(nextCol as HTMLTableHeaderCellElement); } this.parent.notify(events.contentReady, {}); this.parent.trigger(events.actionComplete, { target: headerTarget, requestType: 'columnExpandCollapse' }); } }); } public columnToggle(target: HTMLTableHeaderCellElement): void { const colIndex: number = target.cellIndex; const elementSelector: string = `.${cls.CONTENT_ROW_CLASS}:not(.${cls.SWIMLANE_ROW_CLASS})`; const targetRow: HTMLElement[] = [].slice.call(this.parent.element.querySelectorAll(elementSelector)); const colSelector: string = `.${cls.TABLE_CLASS} col:nth-child(${colIndex + 1})`; const targetIcon: Element = target.querySelector(`.${cls.COLUMN_EXPAND_CLASS},.${cls.COLUMN_COLLAPSE_CLASS}`); const colGroup: HTMLElement[] = [].slice.call(this.parent.element.querySelectorAll(colSelector)); if (target.classList.contains(cls.COLLAPSED_CLASS)) { removeClass(colGroup, cls.COLLAPSED_CLASS); if (this.parent.isAdaptive) { colGroup.forEach((col: HTMLElement) => col.style.width = formatUnit(this.parent.layoutModule.getWidth())); } classList(targetIcon, [cls.COLUMN_EXPAND_CLASS], [cls.COLUMN_COLLAPSE_CLASS]); for (const row of targetRow) { const targetCol: Element = row.querySelector(`.${cls.CONTENT_CELLS_CLASS}:nth-child(${colIndex + 1})`); removeClass([targetCol, target], cls.COLLAPSED_CLASS); remove(targetCol.querySelector('.' + cls.COLLAPSE_HEADER_TEXT_CLASS)); target.setAttribute('aria-expanded', 'true'); targetCol.setAttribute('aria-expanded', 'true'); const collapsedCell: HTMLElement[] = [].slice.call(targetCol.parentElement.querySelectorAll('.' + cls.COLLAPSED_CLASS)); collapsedCell.forEach((cell: HTMLElement) => { const collapasedText: HTMLElement = cell.querySelector('.' + cls.COLLAPSE_HEADER_TEXT_CLASS); collapasedText.style.height = 'auto'; if (collapasedText && targetCol.getBoundingClientRect().height < (collapasedText.getBoundingClientRect().height + 10)) { collapasedText.style.height = (targetCol.getBoundingClientRect().height - 4) + 'px'; } }); } this.columnToggleArray.splice(this.columnToggleArray.indexOf(target.getAttribute('data-key')), 1); (this.parent.columns[colIndex] as Base<HTMLElement>).setProperties({ isExpanded: true }, true); target.querySelector('.e-header-icon').setAttribute('aria-label', target.getAttribute('data-key') + ' Expand'); } else { addClass(colGroup, cls.COLLAPSED_CLASS); if (this.parent.isAdaptive) { colGroup.forEach((col: HTMLElement) => col.style.width = formatUnit(events.toggleWidth)); } classList(targetIcon, [cls.COLUMN_COLLAPSE_CLASS], [cls.COLUMN_EXPAND_CLASS]); const key: string = target.getAttribute('data-key'); for (const row of targetRow) { const targetCol: Element = row.querySelector(`.${cls.CONTENT_CELLS_CLASS}[data-key="${key}"]`); const index: number = (targetCol as HTMLTableCellElement).cellIndex; const text: string = (this.parent.columns[index].showItemCount ? '[' + targetCol.querySelectorAll('.' + cls.CARD_CLASS).length + '] ' : '') + this.parent.columns[index].headerText; targetCol.appendChild(createElement('div', { className: cls.COLLAPSE_HEADER_TEXT_CLASS, innerHTML: text })); addClass([targetCol, target], cls.COLLAPSED_CLASS); target.setAttribute('aria-expanded', 'false'); targetCol.setAttribute('aria-expanded', 'false'); const collapsedCell: HTMLElement[] = [].slice.call(targetCol.parentElement.querySelectorAll('.' + cls.COLLAPSED_CLASS)); collapsedCell.forEach((cell: HTMLElement) => { const collapasedText: HTMLElement = cell.querySelector('.' + cls.COLLAPSE_HEADER_TEXT_CLASS); if (collapasedText && targetCol.getBoundingClientRect().height < (collapasedText.getBoundingClientRect().height + 10)) { collapasedText.style.height = (targetCol.getBoundingClientRect().height - 4) + 'px'; } }); } this.columnToggleArray.push(target.getAttribute('data-key')); (this.parent.columns[colIndex] as Base<HTMLElement>).setProperties({ isExpanded: false }, true); target.querySelector('.e-header-icon').setAttribute('aria-label', key + ' Collapse'); } } public cardSelection(target: Element, isCtrl: boolean, isShift: boolean): void { if (!target) { return; } const cards: HTMLElement[] = this.parent.getSelectedCards(); if (this.parent.cardSettings.selectionType !== 'None') { const contentRow: HTMLTableRowElement = closest(target, '.' + cls.CONTENT_ROW_CLASS) as HTMLTableRowElement; const index: number = !isNullOrUndefined(this.lastSelectionRow) ? this.lastSelectionRow.rowIndex : contentRow.rowIndex; if (index !== contentRow.rowIndex && (isCtrl || isShift) && this.parent.cardSettings.selectionType === 'Multiple') { return; } if (cards.length !== 0 && (!isCtrl || this.parent.cardSettings.selectionType === 'Single')) { removeClass(cards, cls.CARD_SELECTION_CLASS); this.parent.layoutModule.disableAttributeSelection(cards); cards.forEach((el: Element) => { this.selectionArray.splice(this.selectionArray.indexOf(el.getAttribute('data-id')), 1); this.selectedCardsElement.splice(this.selectedCardsElement.indexOf(el), 1); this.selectedCardsData.splice(this.selectedCardsData.indexOf(this.parent.getCardDetails(el), 1)); }); } if (cards.length > 0 && isShift && this.parent.cardSettings.selectionType === 'Multiple') { const curCards: string[] = []; let start: number; let end: number; let i: number; const allCards: HTMLElement[] = [].slice.call(contentRow.querySelectorAll('.' + cls.CARD_CLASS)); allCards.forEach((el: Element) => curCards.push(el.getAttribute('data-id'))); const curId: string = target.getAttribute('data-id'); const lastId: string = this.lastCard.getAttribute('data-id'); const curIndex: number = end = curCards.indexOf(curId); const lastIndex: number = start = curCards.indexOf(lastId); const select: string = curIndex > lastIndex ? 'next' : 'prev'; if (select === 'prev') { start = curIndex; end = lastIndex; } for (i = start; i <= end; i++) { const card: HTMLElement = allCards[i]; addClass([card], cls.CARD_SELECTION_CLASS); card.setAttribute('aria-selected', 'true'); card.setAttribute('tabindex', '0'); this.selectionArray.push(card.getAttribute('data-id')); this.selectedCardsElement.push(card); this.selectedCardsData.push(this.parent.getCardDetails(card)); this.lastCardSelection = card; if (select === 'prev') { this.lastCardSelection = allCards[start]; } } } else { addClass([target], cls.CARD_SELECTION_CLASS); target.setAttribute('aria-selected', 'true'); target.setAttribute('tabindex', '0'); this.selectionArray.push(target.getAttribute('data-id')); this.selectedCardsElement.push(target); this.selectedCardsData.push(this.parent.getCardDetails(target)); this.lastCard = this.lastCardSelection = target; this.lastSelectionRow = closest(target, '.' + cls.CONTENT_ROW_CLASS) as HTMLTableRowElement; if (this.lastSelectionRow.previousElementSibling) { const elementSelector: string = `.${cls.SWIMLANE_ROW_EXPAND_CLASS},.${cls.SWIMLANE_ROW_COLLAPSE_CLASS}`; const parentEle: HTMLElement = this.lastSelectionRow.previousElementSibling.querySelector(elementSelector); if (parentEle && parentEle.classList.contains(cls.SWIMLANE_ROW_COLLAPSE_CLASS)) { this.rowExpandCollapse(parentEle); } } } } } public addColumn(columnOptions: ColumnsModel, index: number): void { const addColumn: ColumnsModel = createInstance(Columns, [this.parent, 'columns', columnOptions, true]); this.parent.columns.splice(index, 0, addColumn); this.parent.notify(events.dataReady, { processedData: this.parent.kanbanData }); } public deleteColumn(index: number): void { const listKey: Element = this.parent.element.querySelectorAll('.' + cls.HEADER_CELLS_CLASS).item(index); if (listKey && listKey.classList.contains(cls.HEADER_ROW_TOGGLE_CLASS)) { this.columnToggleArray.splice(this.columnToggleArray.indexOf(listKey.getAttribute('data-key'), 0)); } this.parent.columns.splice(index, 1); if (this.parent.columns.length === 0) { detach(this.parent.element.querySelector('.' + cls.HEADER_CLASS)); detach(this.parent.element.querySelector('.' + cls.CONTENT_CLASS)); } else { this.parent.notify(events.dataReady, { processedData: this.parent.kanbanData }); } } public showColumn(key: string | number): void { const index: number = this.hideColumnKeys.indexOf(key.toString()); if (index !== -1) { this.hideColumnKeys.splice(index, 1); this.parent.notify(events.dataReady, { processedData: this.parent.kanbanData }); } } public hideColumn(key: string | number): void { this.hideColumnKeys.push(key.toString()); this.parent.notify(events.dataReady, { processedData: this.parent.kanbanData }); } /** * Maintain the single card selection * * @param {Record<string, any>} data - Specifies the selected card data. * @returns {void} * @private * @hidden */ public SingleCardSelection(data: Record<string, any>): void { if (this.parent.cardSettings.selectionType !== 'None' && data[this.parent.cardSettings.headerField]) { let card: HTMLElement = this.parent.element.querySelector('.e-card[data-id=\"' + data[this.parent.cardSettings.headerField].toString() + '"\]') if (card) { addClass([card], cls.CARD_SELECTION_CLASS); card.setAttribute('aria-selected', 'true'); card.setAttribute('tabindex', '0'); } } } }
the_stack
import assert from "assert"; import sinon, { match } from "sinon"; import * as Colyseus from "colyseus.js"; import { Schema, type, Context } from "@colyseus/schema"; import { matchMaker, Room, Client, Server, ErrorCode, MatchMakerDriver, Presence } from "@colyseus/core"; import { DummyRoom, DRIVERS, timeout, Room3Clients, PRESENCE_IMPLEMENTATIONS, Room2Clients, Room2ClientsExplicitLock } from "./utils"; import { ServerError } from "@colyseus/core"; import { uWebSocketsTransport } from "@colyseus/uwebsockets-transport"; import WebSocket from "ws"; const TEST_PORT = 8567; const TEST_ENDPOINT = `ws://localhost:${TEST_PORT}`; describe("Integration", () => { for (let i = 0; i < PRESENCE_IMPLEMENTATIONS.length; i++) { for (let j = 0; j < DRIVERS.length; j++) { describe(`Driver => ${DRIVERS[j].name}, Presence => ${PRESENCE_IMPLEMENTATIONS[i].name}`, () => { let driver: MatchMakerDriver; let server: Server; let presence: Presence; const client = new Colyseus.Client(TEST_ENDPOINT); before(async () => { driver = new DRIVERS[j](); presence = new PRESENCE_IMPLEMENTATIONS[i](); server = new Server({ presence, driver, // transport: new uWebSocketsTransport(), }); // setup matchmaker matchMaker.setup(presence, driver, 'dummyIntegrationProcessId') // define a room server.define("dummy", DummyRoom); server.define("room3", Room3Clients); // listen for testing await server.listen(TEST_PORT); }); beforeEach(async() => await driver.clear()); after(async () => { await driver.clear(); await server.gracefullyShutdown(false) }); describe("Room lifecycle", () => { describe("onCreate()", () => { it("sync onCreate()", async () => { let onCreateCalled = false; matchMaker.defineRoomType('oncreate', class _ extends Room { onCreate(options) { assert.deepStrictEqual({ string: "hello", number: 1 }, options); onCreateCalled = true; } }); const connection = await client.joinOrCreate('oncreate', { string: "hello", number: 1 }); assert.ok(onCreateCalled); // assert 'presence' implementation const room = matchMaker.getRoomById(connection.id); assert.strictEqual(presence, room.presence); await connection.leave(); }); it("async onCreate()", async () => { let onCreateCalled = false; matchMaker.defineRoomType('oncreate', class _ extends Room { async onCreate(options) { return new Promise<void>(resolve => setTimeout(() => { onCreateCalled = true; resolve(); }, 100) ); } }); const connection = await client.joinOrCreate('oncreate', { string: "hello", number: 1 }); assert.ok(onCreateCalled); await connection.leave(); }); }); describe("onJoin()", () => { it("sync onJoin()", async () => { let onJoinCalled = false; matchMaker.defineRoomType('onjoin', class _ extends Room { onJoin(client: Client, options: any) { onJoinCalled = true; assert.deepStrictEqual({ string: "hello", number: 1 }, options); } }); const connection = await client.joinOrCreate('onjoin', { string: "hello", number: 1 }); assert.ok(onJoinCalled); await connection.leave(); }); it("async onJoin support", async () => { let onJoinCalled = false; matchMaker.defineRoomType('onjoin', class _ extends Room { async onJoin(client: Client, options: any) { return new Promise<void>(resolve => setTimeout(() => { onJoinCalled = true; resolve(); }, 20)); } }); const connection = await client.joinOrCreate('onjoin'); await timeout(50); assert.ok(onJoinCalled); await connection.leave(); }); it("error during onJoin should reject client-side promise", async () => { matchMaker.defineRoomType('onjoin', class _ extends Room { async onJoin(client: Client, options: any) { throw new Error("not_allowed"); } }); await assert.rejects(async () => await client.joinOrCreate('onjoin')); }); it("should discard connections when early disconnected", async () => { matchMaker.defineRoomType('onjoin', class _ extends Room { async onJoin(client: Client, options: any) { return new Promise<void>((resolve) => setTimeout(resolve, 100)); } }); // keep one active connection to prevent room's disposal const activeConnection = await client.joinOrCreate("onjoin"); const seatReservation = await matchMaker.joinOrCreate('onjoin', {}); const room = matchMaker.getRoomById(seatReservation.room.roomId); const lostConnection = new WebSocket(`${TEST_ENDPOINT}/${seatReservation.room.processId}/${seatReservation.room.roomId}?sessionId=${seatReservation.sessionId}`); // close connection immediatelly after connecting. lostConnection.on("open", () => lostConnection.close()); await timeout(110); const rooms = await matchMaker.query({ name: "onjoin" }); assert.strictEqual(1, room.clients.length); assert.strictEqual(1, rooms[0].clients); await activeConnection.leave(); await timeout(50); }); }); it("onAuth() error should reject join promise", async() => { matchMaker.defineRoomType('onauth', class _ extends Room { async onAuth(client: Client, options: any) { throw new Error("not_allowed"); } }); await assert.rejects(async () => await client.joinOrCreate('onauth')); }); it("onAuth() getting IP address", async() => { matchMaker.defineRoomType('onauth_ip_address', class _ extends Room { async onAuth(client: Client, options: any, request: any) { const ipAddress = request.connection.remoteAddress; client.send("ip", ipAddress); return true; } }); const connection = await client.joinOrCreate('onauth_ip_address'); await new Promise<void>((resolve, reject) => { const rejectionTimeout = setTimeout(reject, 200); connection.onMessage("ip", (address) => { clearInterval(rejectionTimeout); assert.ok(typeof(address) === "string"); resolve(); }); }); }); it("onLeave()", async () => { let onLeaveCalled = false; matchMaker.defineRoomType('onleave', class _ extends Room { onLeave(client: Client, options: any) { onLeaveCalled = true; } }); const connection = await client.joinOrCreate('onleave'); await connection.leave(); await timeout(50); assert.ok(onLeaveCalled); }); it("client.leave() should support custom close code from the server", async () => { const customCode = 4040; matchMaker.defineRoomType('onleave_customcode', class _ extends Room { onJoin(client: Client, options: any) { setTimeout(() => client.leave(customCode), 10); } }); const connection = await client.joinOrCreate('onleave_customcode'); await new Promise<void>((resolve, reject) => { let rejectTimeout = setTimeout(reject, 1000); connection.onLeave((code) => { clearTimeout(rejectTimeout); assert.strictEqual(customCode, code); resolve(); }); }); }); it("async onLeave()", async () => { let onLeaveCalled = false; matchMaker.defineRoomType('onleave', class _ extends Room { async onLeave(client: Client, options: any) { return new Promise<void>(resolve => setTimeout(() => { onLeaveCalled = true; resolve(); }, 100)); } }); const connection = await client.joinOrCreate('onleave'); await connection.leave(); await timeout(150); assert.ok(onLeaveCalled); }); it("onDispose()", async () => { let onDisposeCalled = false; matchMaker.defineRoomType('onleave', class _ extends Room { onDispose() { onDisposeCalled = true; } }); const connection = await client.joinOrCreate('onleave'); await connection.leave(); await timeout(50); assert.ok(!matchMaker.getRoomById(connection.id)) assert.ok(onDisposeCalled); }); it("async onDispose()", async () => { let onDisposeCalled = false; matchMaker.defineRoomType('onleave', class _ extends Room { async onDispose() { return new Promise<void>(resolve => setTimeout(() => { onDisposeCalled = true; resolve(); }, 100)); } }); const connection = await client.joinOrCreate('onleave'); await connection.leave(); await timeout(150); assert.ok(!matchMaker.getRoomById(connection.id)) assert.ok(onDisposeCalled); }); describe("onMessage()", () => { it("should support string key as message type", async () => { const messageToSend = { string: "hello", number: 10, float: Math.PI, array: [1, 2, 3, 4, 5], nested: { string: "hello", number: 10, float: Math.PI, } }; let onMessageCalled = false; let sessionId: string; matchMaker.defineRoomType('onmessage', class _ extends Room { onCreate() { this.onMessage("msgtype", (client, message) => { sessionId = client.sessionId; assert.deepStrictEqual(messageToSend, message); onMessageCalled = true; }); } }); const connection = await client.joinOrCreate('onmessage'); connection.send("msgtype", messageToSend); await timeout(20); await connection.leave(); assert.strictEqual(sessionId, connection.sessionId); assert.ok(onMessageCalled); }); it("should support number key as message type", async () => { enum MessageTypes { REQUEST, RESPONSE } const messageToSend = { string: "hello", number: 10, float: Math.PI, array: [1, 2, 3, 4, 5], nested: { string: "hello", number: 10, float: Math.PI, } }; let onMessageCalled = false; let onMessageReceived = false; let sessionId: string; matchMaker.defineRoomType('onmessage', class _ extends Room { onCreate() { this.onMessage(MessageTypes.REQUEST, (client, message) => { sessionId = client.sessionId; client.send(MessageTypes.RESPONSE, message); assert.deepStrictEqual(messageToSend, message); onMessageCalled = true; }); } }); const connection = await client.joinOrCreate('onmessage'); connection.send(MessageTypes.REQUEST, messageToSend); connection.onMessage(MessageTypes.RESPONSE, (message) => { assert.deepStrictEqual(messageToSend, message); onMessageReceived = true; }); await timeout(20); await connection.leave(); assert.strictEqual(sessionId, connection.sessionId); assert.ok(onMessageCalled); assert.ok(onMessageReceived); }); it("should support send/receive messages by type without payload.", async () => { let onMessageCalled = false; let onMessageReceived = false; let sessionId: string; matchMaker.defineRoomType('onmessage', class _ extends Room { onCreate() { this.onMessage(1, (client) => { sessionId = client.sessionId; onMessageCalled = true; client.send("response"); }); } }); const connection = await client.joinOrCreate('onmessage'); connection.send(1); connection.onMessage("response", (message) => { assert.ok(message === undefined); onMessageReceived = true; }); await timeout(20); await connection.leave(); assert.strictEqual(sessionId, connection.sessionId); assert.ok(onMessageCalled); assert.ok(onMessageReceived); }); }); describe("setPatchRate()", () => { class PatchState extends Schema { @type("number") number: number = 0; } it("should receive patch at every patch rate", async () => { matchMaker.defineRoomType('patchinterval', class _ extends Room { onCreate(options: any) { this.setState(new PatchState()); this.setPatchRate(20); this.setSimulationInterval(() => this.state.number++); } }); const connection = await client.create<PatchState>('patchinterval'); let patchesReceived: number = 0; connection.onStateChange(() => patchesReceived++); await timeout(20 * 25); assert.ok(patchesReceived > 20, "should have received > 20 patches"); assert.ok(connection.state.number >= 20); connection.leave(); await timeout(50); }); it("should not receive any patch if patchRate is nullified", async () => { matchMaker.defineRoomType('patchinterval', class _ extends Room { onCreate(options: any) { this.setState(new PatchState()); this.setPatchRate(null); this.setSimulationInterval(() => this.state.number++); } }); const connection = await client.create<PatchState>('patchinterval'); let stateChangeCount: number = 0; connection.onStateChange(() => stateChangeCount++); await timeout(500); // simulation interval may have run a short amount of cycles for the first ROOM_STATE message assert.strictEqual(1, stateChangeCount); connection.leave(); await timeout(50); }); }); describe("broadcast()", () => { it("all clients should receive broadcast data", async () => { matchMaker.defineRoomType('broadcast', class _ extends Room { maxClients = 3; onCreate() { this.onMessage("*", (_, type, message) => { this.broadcast(type, message); }) } }); const messages: string[] = []; const conn1 = await client.joinOrCreate('broadcast'); conn1.onMessage("num", message => messages.push(message)); const conn2 = await client.joinOrCreate('broadcast'); conn2.onMessage("num", message => messages.push(message)); const conn3 = await client.joinOrCreate('broadcast'); conn3.onMessage("num", message => messages.push(message)); conn1.send("num", "one"); conn2.send("num", "two"); conn3.send("num", "three"); await timeout(200); assert.deepStrictEqual(["one", "one", "one", "three", "three", "three", "two", "two", "two"], messages.sort()); conn1.leave(); conn2.leave(); conn3.leave(); await timeout(50); }); it("should broadcast except to specific client", async () => { matchMaker.defineRoomType('broadcast', class _ extends Room { maxClients = 3; onCreate() { this.onMessage("*", (client, type, message) => { this.broadcast(type, message, { except: client }); }) } }); const messages: string[] = []; const conn1 = await client.joinOrCreate('broadcast'); conn1.onMessage("num", message => messages.push(message)); const conn2 = await client.joinOrCreate('broadcast'); conn2.onMessage("num", message => messages.push(message)); const conn3 = await client.joinOrCreate('broadcast'); conn3.onMessage("num", message => messages.push(message)); conn1.send("num", "one"); conn2.send("num", "two"); conn3.send("num", "three"); await timeout(200); assert.deepStrictEqual(["one", "one", "three", "three", "two", "two"], messages.sort()); conn1.leave(); conn2.leave(); conn3.leave(); await timeout(50); }); it("should allow to send/broadcast during onJoin() for current client", async () => { matchMaker.defineRoomType('broadcast', class _ extends Room { onJoin(client, options) { client.send("send", "hello"); this.broadcast("broadcast", "hello"); } }); const conn = await client.joinOrCreate('broadcast'); let onMessageCalled = false; let broadcastedMessage: any; let sentMessage: any; conn.onMessage("broadcast", (_message) => { onMessageCalled = true; broadcastedMessage = _message; }); conn.onMessage("send", (_message) => { onMessageCalled = true; sentMessage = _message; }); await timeout(300); assert.strictEqual(true, onMessageCalled); assert.strictEqual("hello", broadcastedMessage); assert.strictEqual("hello", sentMessage); conn.leave(); }); it("should broadcast after patch", async () => { class DummyState extends Schema { @type("number") number: number = 0; } matchMaker.defineRoomType('broadcast_afterpatch', class _ extends Room { onCreate() { this.setPatchRate(100); this.setState(new DummyState); } onJoin(client, options) { this.broadcast("startup", "hello", { afterNextPatch: true }); this.state.number = 1; } }); const conn = await client.joinOrCreate('broadcast_afterpatch'); let onMessageCalled = false; let message: any; conn.onMessage("startup", (_message) => { onMessageCalled = true; message = _message; }); await timeout(50); assert.strictEqual(false, onMessageCalled); await timeout(100); assert.strictEqual(true, onMessageCalled); assert.strictEqual("hello", message); conn.leave(); }); }); describe("send()", () => { it("send() schema-encoded instances", async () => { const ctx = new Context(); class State extends Schema { @type("number", ctx) num = 1; } class Message extends Schema { @type("string", ctx) str: string = "Hello world"; } let onMessageCalled = false; matchMaker.defineRoomType('sendschema', class _ extends Room { onCreate() { this.setState(new State()); this.onMessage("ping", (client, message) => { const msg = new Message(); msg.str = message; client.send(msg); }); } }); const connection = await client.joinOrCreate('sendschema', {}, State); let messageReceived: Message; connection.onMessage(Message, (message) => { onMessageCalled = true; messageReceived = message; }); connection.send("ping", "hello!"); await timeout(100); await connection.leave(); assert.ok(onMessageCalled); assert.strictEqual(messageReceived.str, "hello!"); }); it("should send after patch", async () => { class DummyState extends Schema { @type("number") number: number = 0; } matchMaker.defineRoomType('send_afterpatch', class _ extends Room { onCreate() { this.setPatchRate(100); this.setState(new DummyState); } onJoin(client: Client, options) { client.send("startup", "hello", { afterNextPatch: true }); this.state.number = 1; } }); const conn = await client.joinOrCreate('send_afterpatch'); let onMessageCalled = false; let message: any; conn.onMessage("startup", (_message) => { onMessageCalled = true; message = _message; }); await timeout(50); assert.strictEqual(false, onMessageCalled); await timeout(100); assert.strictEqual(true, onMessageCalled); assert.strictEqual("hello", message); conn.leave(); }); }); describe("lock / unlock", () => { before(() => { server.define("room2", Room2Clients); server.define("room_explicit_lock", Room2ClientsExplicitLock); }); it("should lock room automatically when maxClients is reached", async () => { const conn1 = await client.joinOrCreate('room2'); const room = matchMaker.getRoomById(conn1.id); assert.strictEqual(false, room.locked); const conn2 = await client.joinOrCreate('room2'); assert.strictEqual(2, room.clients.length); assert.strictEqual(true, room.locked); const roomListing = (await matchMaker.query({ name: "room2" })); assert.strictEqual(true, roomListing[0].locked); conn1.leave(); conn2.leave(); await timeout(100); }); it("should unlock room automatically when last client leaves", async () => { const conn1 = await client.joinOrCreate('room2'); const conn2 = await client.joinOrCreate('room2'); const room = matchMaker.getRoomById(conn1.id); assert.strictEqual(2, room.clients.length); assert.strictEqual(true, room.locked); conn2.leave(); await timeout(50); assert.strictEqual(1, room.clients.length); assert.strictEqual(false, room.locked); const roomListing = (await matchMaker.query({ name: "room2" }))[0]; assert.strictEqual(false, roomListing.locked); conn1.leave(); }); it("when explicitly locked, should remain locked when last client leaves", async () => { const conn1 = await client.joinOrCreate('room_explicit_lock'); const conn2 = await client.joinOrCreate('room_explicit_lock'); const room = matchMaker.getRoomById(conn1.id); assert.strictEqual(2, room.clients.length); assert.strictEqual(true, room.locked); conn1.send("lock"); // send explicit lock to handler await timeout(50); assert.strictEqual(true, room.locked); conn2.leave(); await timeout(50); assert.strictEqual(1, room.clients.length); assert.strictEqual(true, room.locked); const roomListing = (await matchMaker.query({}))[0]; assert.strictEqual(true, roomListing.locked); conn1.leave(); }); }); describe("disconnect()", () => { it("should disconnect all clients", async() => { matchMaker.defineRoomType('disconnect', class _ extends Room { maxClients = 2; onCreate() { this.clock.setTimeout(() => this.disconnect(), 100); } }); let disconnected: number = 0; const conn1 = await client.joinOrCreate('disconnect'); conn1.onLeave(() => disconnected++); const conn2 = await client.joinOrCreate('disconnect'); conn2.onLeave(() => disconnected++); assert.strictEqual(conn1.id, conn2.id, "should've joined the same room"); await timeout(150); assert.strictEqual(2, disconnected, "both clients should've been disconnected"); }); }); describe("Seat reservation", () => { it("should not exceed maxClients", async() => { // make sure "presence" entry doesn't exist before first client. await presence.hdel("created", "single3"); matchMaker.defineRoomType("single3", class _ extends Room { maxClients = 3; async onCreate() { const hasRoom = await presence.hget("created", "single3"); if (hasRoom) { throw new Error("only_one_room_of_this_type_allowed"); } else { await this.presence.hset("created", "single3", "1"); } } }); let connections: Colyseus.Room[] = []; const promises = [ client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), client.joinOrCreate("single3").then(conn => connections.push(conn)), ]; try { await Promise.all(promises); } catch (e) { // console.log(e); } await timeout(1000); const rooms = await matchMaker.query({ name: "single3" }); const room = rooms[0]; assert.strictEqual(3, connections.length); assert.deepStrictEqual([room.roomId, room.roomId, room.roomId], connections.map(conn => conn.id)); assert.strictEqual(1, rooms.length); assert.strictEqual(room.roomId, rooms[0].roomId); }); it("consumeSeatReservation()", async () => { const seatReservation = await matchMaker.create("dummy", {}); const conn = await client.consumeSeatReservation(seatReservation); assert.strictEqual(conn.id, seatReservation.room.roomId); conn.leave(); }) }); describe("`pingTimeout` / `pingMaxRetries`", () => { it("should terminate unresponsive client after connection is ready", async () => { if (server.transport instanceof uWebSocketsTransport) { console.warn("WARNING: this test is being skipped. (not supported in uWebSocketsTransport)"); assert.ok(true); return; } const conn = await client.joinOrCreate("dummy"); // force websocket client to be unresponsive (conn.connection.transport as any).ws._socket.removeAllListeners(); assert.ok(matchMaker.getRoomById(conn.id)); await timeout(700); assert.ok(!matchMaker.getRoomById(conn.id)); }); it("should remove the room if seat reservation is never fulfiled", async () => { const stub = sinon.stub(client, 'consumeSeatReservation').callsFake(function(response) { return response; }); const seatReservation = await (client as any).createMatchMakeRequest('joinOrCreate', "dummy", {}); await (client as any).createMatchMakeRequest('joinOrCreate', "dummy", {}); assert.ok(matchMaker.getRoomById(seatReservation.room.roomId)); await timeout(500); assert.ok(!matchMaker.getRoomById(seatReservation.room.roomId)); stub.restore(); }); }) describe("Matchmaker queries", () => { const createDummyRooms = async () => { matchMaker.defineRoomType('allroomstest', class _ extends Room {}); matchMaker.defineRoomType('allroomstest2', class _ extends Room {}); await matchMaker.create("allroomstest"); await matchMaker.create("allroomstest2"); } it("client.getAvailableRooms() should recieve all rooms when roomName is undefined", async () => { await createDummyRooms(); const rooms = await client.getAvailableRooms(undefined); assert.strictEqual(2, rooms.length); }); it("client.getAvailableRooms() should recieve the room when roomName is given", async () => { await createDummyRooms(); const rooms = await client.getAvailableRooms("allroomstest"); assert.strictEqual("allroomstest", rooms[0]["name"]); }); it("client.getAvailableRooms() should recieve empty list if no room exists for the given roomName", async () => { await createDummyRooms(); const rooms = await client.getAvailableRooms("incorrectRoomName"); assert.strictEqual(0, rooms.length); }); }) }); describe("Error handling", () => { it("ErrorCode.MATCHMAKE_NO_HANDLER", async () => { try { await client.joinOrCreate('nonexisting') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(ErrorCode.MATCHMAKE_NO_HANDLER, e.code) } }); it("should have reasonable error message when providing an empty room name", async () => { try { await client.joinOrCreate('') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(ErrorCode.MATCHMAKE_NO_HANDLER, e.code) assert.strictEqual('provided room name "" not defined', e.message); } }); it("ErrorCode.AUTH_FAILED", async () => { matchMaker.defineRoomType('onAuthFail', class _ extends Room { async onAuth(client: Client, options: any) { return false; } }); try { await client.joinOrCreate('onAuthFail') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(ErrorCode.AUTH_FAILED, e.code) } }); it("onAuth: custom error", async () => { matchMaker.defineRoomType('onAuthFail', class _ extends Room { async onAuth(client: Client, options: any) { throw new ServerError(1, "invalid token"); } }); try { await client.joinOrCreate('onAuthFail') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(1, e.code); assert.strictEqual("invalid token", e.message); } }); it("onJoin: application error", async () => { matchMaker.defineRoomType('onJoinError', class _ extends Room { async onJoin(client: Client, options: any) { throw new Error("unexpected error"); } }); try { await client.joinOrCreate('onJoinError') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(ErrorCode.APPLICATION_ERROR, e.code) assert.strictEqual("unexpected error", e.message) } }); it("onJoin: application error with custom code", async () => { matchMaker.defineRoomType('onJoinError', class _ extends Room { async onJoin(client: Client, options: any) { throw new ServerError(2, "unexpected error"); } }); try { await client.joinOrCreate('onJoinError') assert.fail("joinOrCreate should have failed."); } catch (e) { assert.strictEqual(2, e.code) assert.strictEqual("unexpected error", e.message) } }); }); }); } } });
the_stack
export type Maybe<T> = T | null export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number DateTime: any /** The `BigDecimal` scalar type represents signed fractional values with arbitrary precision. */ BigDecimal: any /** The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ Long: any } /** Add wishlist items input object */ export type AddWishlistItemsInput = { entityId: Scalars['Int'] items: Array<WishlistItemInput> } /** Add wishlist items */ export type AddWishlistItemsResult = { __typename?: 'AddWishlistItemsResult' result: Wishlist } /** Create wishlist input object */ export type CreateWishlistInput = { name: Scalars['String'] isPublic: Scalars['Boolean'] items?: Maybe<Array<WishlistItemInput>> } /** Create wishlist */ export type CreateWishlistResult = { __typename?: 'CreateWishlistResult' result: Wishlist } /** Delete wishlist items input object */ export type DeleteWishlistItemsInput = { entityId: Scalars['Int'] itemEntityIds: Array<Scalars['Int']> } /** Delete wishlist items */ export type DeleteWishlistItemsResult = { __typename?: 'DeleteWishlistItemsResult' result: Wishlist } /** Delete wishlist */ export type DeleteWishlistResult = { __typename?: 'DeleteWishlistResult' result: Scalars['String'] } /** Delete wishlists input object */ export type DeleteWishlistsInput = { entityIds: Array<Scalars['Int']> } /** Login result */ export type LoginResult = { __typename?: 'LoginResult' /** * The result of a login * @deprecated Use customer node instead. */ result: Scalars['String'] /** The currently logged in customer. */ customer?: Maybe<Customer> } /** Logout result */ export type LogoutResult = { __typename?: 'LogoutResult' /** The result of a logout */ result: Scalars['String'] } export type Mutation = { __typename?: 'Mutation' login: LoginResult logout: LogoutResult /** The wishlist mutations. */ wishlist: WishlistMutations } export type MutationLoginArgs = { email: Scalars['String'] password: Scalars['String'] } /** Update wishlist input object */ export type UpdateWishlistInput = { entityId: Scalars['Int'] data: WishlistUpdateDataInput } /** Update wishlist */ export type UpdateWishlistResult = { __typename?: 'UpdateWishlistResult' result: Wishlist } /** Wishlist item input object */ export type WishlistItemInput = { productEntityId: Scalars['Int'] variantEntityId?: Maybe<Scalars['Int']> } export type WishlistMutations = { __typename?: 'WishlistMutations' createWishlist?: Maybe<CreateWishlistResult> addWishlistItems?: Maybe<AddWishlistItemsResult> deleteWishlistItems?: Maybe<DeleteWishlistItemsResult> updateWishlist?: Maybe<UpdateWishlistResult> deleteWishlists?: Maybe<DeleteWishlistResult> } export type WishlistMutationsCreateWishlistArgs = { input: CreateWishlistInput } export type WishlistMutationsAddWishlistItemsArgs = { input: AddWishlistItemsInput } export type WishlistMutationsDeleteWishlistItemsArgs = { input: DeleteWishlistItemsInput } export type WishlistMutationsUpdateWishlistArgs = { input: UpdateWishlistInput } export type WishlistMutationsDeleteWishlistsArgs = { input: DeleteWishlistsInput } /** Wishlist data to update */ export type WishlistUpdateDataInput = { name?: Maybe<Scalars['String']> isPublic?: Maybe<Scalars['Boolean']> } /** Aggregated */ export type Aggregated = { __typename?: 'Aggregated' /** Number of available products in stock. This can be 'null' if inventory is not set orif the store's Inventory Settings disable displaying stock levels on the storefront. */ availableToSell: Scalars['Long'] /** Indicates a threshold low-stock level. This can be 'null' if the inventory warning level is not set or if the store's Inventory Settings disable displaying stock levels on the storefront. */ warningLevel: Scalars['Int'] } /** Aggregated Product Inventory */ export type AggregatedInventory = { __typename?: 'AggregatedInventory' /** Number of available products in stock. This can be 'null' if inventory is not set orif the store's Inventory Settings disable displaying stock levels on the storefront. */ availableToSell: Scalars['Int'] /** Indicates a threshold low-stock level. This can be 'null' if the inventory warning level is not set or if the store's Inventory Settings disable displaying stock levels on the storefront. */ warningLevel: Scalars['Int'] } /** Author */ export type Author = { __typename?: 'Author' /** Author name. */ name: Scalars['String'] } /** Brand */ export type Brand = Node & { __typename?: 'Brand' /** The ID of an object */ id: Scalars['ID'] /** Id of the brand. */ entityId: Scalars['Int'] /** Name of the brand. */ name: Scalars['String'] /** Default image for brand. */ defaultImage?: Maybe<Image> /** * Page title for the brand. * @deprecated Use SEO details instead. */ pageTitle: Scalars['String'] /** * Meta description for the brand. * @deprecated Use SEO details instead. */ metaDesc: Scalars['String'] /** * Meta keywords for the brand. * @deprecated Use SEO details instead. */ metaKeywords: Array<Scalars['String']> /** Brand SEO details. */ seo: SeoDetails /** Search keywords for the brand. */ searchKeywords: Array<Scalars['String']> /** Path for the brand page. */ path: Scalars['String'] products: ProductConnection /** Metafield data related to a brand. */ metafields: MetafieldConnection } /** Brand */ export type BrandProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> hideOutOfStock?: Maybe<Scalars['Boolean']> } /** Brand */ export type BrandMetafieldsArgs = { namespace: Scalars['String'] keys?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type BrandConnection = { __typename?: 'BrandConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<BrandEdge>>> } /** An edge in a connection. */ export type BrandEdge = { __typename?: 'BrandEdge' /** The item at the end of the edge. */ node: Brand /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Breadcrumb */ export type Breadcrumb = { __typename?: 'Breadcrumb' /** Category id. */ entityId: Scalars['Int'] /** Name of the category. */ name: Scalars['String'] } /** A connection to a list of items. */ export type BreadcrumbConnection = { __typename?: 'BreadcrumbConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<BreadcrumbEdge>>> } /** An edge in a connection. */ export type BreadcrumbEdge = { __typename?: 'BreadcrumbEdge' /** The item at the end of the edge. */ node: Breadcrumb /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Bulk pricing tier that sets a fixed price for the product or variant. */ export type BulkPricingFixedPriceDiscount = BulkPricingTier & { __typename?: 'BulkPricingFixedPriceDiscount' /** This price will override the current product price. */ price: Scalars['BigDecimal'] /** Minimum item quantity that applies to this bulk pricing tier. */ minimumQuantity: Scalars['Int'] /** Maximum item quantity that applies to this bulk pricing tier - if not defined then the tier does not have an upper bound. */ maximumQuantity?: Maybe<Scalars['Int']> } /** Bulk pricing tier that reduces the price of the product or variant by a percentage. */ export type BulkPricingPercentageDiscount = BulkPricingTier & { __typename?: 'BulkPricingPercentageDiscount' /** The percentage that will be removed from the product price. */ percentOff: Scalars['BigDecimal'] /** Minimum item quantity that applies to this bulk pricing tier. */ minimumQuantity: Scalars['Int'] /** Maximum item quantity that applies to this bulk pricing tier - if not defined then the tier does not have an upper bound. */ maximumQuantity?: Maybe<Scalars['Int']> } /** Bulk pricing tier that will subtract an amount from the price of the product or variant. */ export type BulkPricingRelativePriceDiscount = BulkPricingTier & { __typename?: 'BulkPricingRelativePriceDiscount' /** The price of the product/variant will be reduced by this priceAdjustment. */ priceAdjustment: Scalars['BigDecimal'] /** Minimum item quantity that applies to this bulk pricing tier. */ minimumQuantity: Scalars['Int'] /** Maximum item quantity that applies to this bulk pricing tier - if not defined then the tier does not have an upper bound. */ maximumQuantity?: Maybe<Scalars['Int']> } /** A set of bulk pricing tiers that define price discounts which apply when purchasing specified quantities of a product or variant. */ export type BulkPricingTier = { /** Minimum item quantity that applies to this bulk pricing tier. */ minimumQuantity: Scalars['Int'] /** Maximum item quantity that applies to this bulk pricing tier - if not defined then the tier does not have an upper bound. */ maximumQuantity?: Maybe<Scalars['Int']> } /** Product Option */ export type CatalogProductOption = { /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** Product Option Value */ export type CatalogProductOptionValue = { /** Unique ID for the option value. */ entityId: Scalars['Int'] /** Label for the option value. */ label: Scalars['String'] /** Indicates whether this value is the chosen default selected value. */ isDefault: Scalars['Boolean'] } /** Category */ export type Category = Node & { __typename?: 'Category' /** The ID of an object */ id: Scalars['ID'] /** Unique ID for the category. */ entityId: Scalars['Int'] /** Category name. */ name: Scalars['String'] /** Category path. */ path: Scalars['String'] /** Default image for the category. */ defaultImage?: Maybe<Image> /** Category description. */ description: Scalars['String'] /** Category breadcrumbs. */ breadcrumbs: BreadcrumbConnection products: ProductConnection /** Metafield data related to a category. */ metafields: MetafieldConnection /** Category SEO details. */ seo: SeoDetails } /** Category */ export type CategoryBreadcrumbsArgs = { depth: Scalars['Int'] before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Category */ export type CategoryProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> hideOutOfStock?: Maybe<Scalars['Boolean']> sortBy?: Maybe<CategoryProductSort> } /** Category */ export type CategoryMetafieldsArgs = { namespace: Scalars['String'] keys?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type CategoryConnection = { __typename?: 'CategoryConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<CategoryEdge>>> } /** An edge in a connection. */ export type CategoryEdge = { __typename?: 'CategoryEdge' /** The item at the end of the edge. */ node: Category /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Product sorting by categories. */ export enum CategoryProductSort { Default = 'DEFAULT', Featured = 'FEATURED', Newest = 'NEWEST', BestSelling = 'BEST_SELLING', AToZ = 'A_TO_Z', ZToA = 'Z_TO_A', BestReviewed = 'BEST_REVIEWED', LowestPrice = 'LOWEST_PRICE', HighestPrice = 'HIGHEST_PRICE', } /** An item in a tree of categories. */ export type CategoryTreeItem = { __typename?: 'CategoryTreeItem' /** The id category. */ entityId: Scalars['Int'] /** The name of category. */ name: Scalars['String'] /** Path assigned to this category */ path: Scalars['String'] /** The description of this category. */ description: Scalars['String'] /** The number of products in this category. */ productCount: Scalars['Int'] /** The category image. */ image?: Maybe<Image> /** Subcategories of this category */ children: Array<CategoryTreeItem> } /** A simple yes/no question represented by a checkbox. */ export type CheckboxOption = CatalogProductOption & { __typename?: 'CheckboxOption' /** Indicates the default checked status. */ checkedByDefault: Scalars['Boolean'] /** Label of the checkbox option. */ label: Scalars['String'] /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** Contact field */ export type ContactField = { __typename?: 'ContactField' /** Store address line. */ address: Scalars['String'] /** Store country. */ country: Scalars['String'] /** Store address type. */ addressType: Scalars['String'] /** Store email. */ email: Scalars['String'] /** Store phone number. */ phone: Scalars['String'] } /** The page content. */ export type Content = { __typename?: 'Content' renderedRegionsByPageType: RenderedRegionsByPageType renderedRegionsByPageTypeAndEntityId: RenderedRegionsByPageType } /** The page content. */ export type ContentRenderedRegionsByPageTypeArgs = { pageType: PageType } /** The page content. */ export type ContentRenderedRegionsByPageTypeAndEntityIdArgs = { entityId: Scalars['Long'] entityPageType: EntityPageType } export type Currency = { __typename?: 'Currency' /** Currency ID. */ entityId: Scalars['Int'] /** Currency code. */ code: CurrencyCode /** Currency name. */ name: Scalars['String'] /** Flag image URL. */ flagImage?: Maybe<Scalars['String']> /** Indicates whether this currency is active. */ isActive: Scalars['Boolean'] /** Exchange rate relative to default currency. */ exchangeRate: Scalars['Float'] /** Indicates whether this currency is transactional. */ isTransactional: Scalars['Boolean'] /** Currency display settings. */ display: CurrencyDisplay } /** A connection to a list of items. */ export type CurrencyConnection = { __typename?: 'CurrencyConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<CurrencyEdge>>> } export type CurrencyDisplay = { __typename?: 'CurrencyDisplay' /** Currency symbol. */ symbol: Scalars['String'] /** Currency symbol. */ symbolPlacement: CurrencySymbolPosition /** Currency decimal token. */ decimalToken: Scalars['String'] /** Currency thousands token. */ thousandsToken: Scalars['String'] /** Currency decimal places. */ decimalPlaces: Scalars['Int'] } /** An edge in a connection. */ export type CurrencyEdge = { __typename?: 'CurrencyEdge' /** The item at the end of the edge. */ node: Currency /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Currency symbol position */ export enum CurrencySymbolPosition { Left = 'LEFT', Right = 'RIGHT', } /** Custom field */ export type CustomField = { __typename?: 'CustomField' /** Custom field id. */ entityId: Scalars['Int'] /** Name of the custom field. */ name: Scalars['String'] /** Value of the custom field. */ value: Scalars['String'] } /** A connection to a list of items. */ export type CustomFieldConnection = { __typename?: 'CustomFieldConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<CustomFieldEdge>>> } /** An edge in a connection. */ export type CustomFieldEdge = { __typename?: 'CustomFieldEdge' /** The item at the end of the edge. */ node: CustomField /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** A customer that shops on a store */ export type Customer = { __typename?: 'Customer' /** The ID of the customer. */ entityId: Scalars['Int'] /** The company name of the customer. */ company: Scalars['String'] /** The customer group id of the customer. */ customerGroupId: Scalars['Int'] /** The email address of the customer. */ email: Scalars['String'] /** The first name of the customer. */ firstName: Scalars['String'] /** The last name of the customer. */ lastName: Scalars['String'] /** The notes of the customer. */ notes: Scalars['String'] /** The phone number of the customer. */ phone: Scalars['String'] /** The tax exempt category of the customer. */ taxExemptCategory: Scalars['String'] /** Customer addresses count. */ addressCount: Scalars['Int'] /** Customer attributes count. */ attributeCount: Scalars['Int'] /** Customer store credit. */ storeCredit: Array<Money> /** Customer attributes. */ attributes: CustomerAttributes wishlists: WishlistConnection } /** A customer that shops on a store */ export type CustomerWishlistsArgs = { filters?: Maybe<WishlistFiltersInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A custom, store-specific attribute for a customer */ export type CustomerAttribute = { __typename?: 'CustomerAttribute' /** The ID of the custom customer attribute */ entityId: Scalars['Int'] /** The value of the custom customer attribute */ value?: Maybe<Scalars['String']> /** The name of the custom customer attribute */ name: Scalars['String'] } /** Custom, store-specific customer attributes */ export type CustomerAttributes = { __typename?: 'CustomerAttributes' attribute: CustomerAttribute } /** Custom, store-specific customer attributes */ export type CustomerAttributesAttributeArgs = { entityId: Scalars['Int'] } /** A calendar for allowing selection of a date. */ export type DateFieldOption = CatalogProductOption & { __typename?: 'DateFieldOption' /** The default timestamp of date option. */ defaultValue?: Maybe<Scalars['DateTime']> /** The earliest timestamp of date option. */ earliest?: Maybe<Scalars['DateTime']> /** The latest timestamp of date option. */ latest?: Maybe<Scalars['DateTime']> /** Limit date by */ limitDateBy: LimitDateOption /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** Date Time Extended */ export type DateTimeExtended = { __typename?: 'DateTimeExtended' /** ISO-8601 formatted date in UTC */ utc: Scalars['DateTime'] } /** Display field */ export type DisplayField = { __typename?: 'DisplayField' /** Short date format. */ shortDateFormat: Scalars['String'] /** Extended date format. */ extendedDateFormat: Scalars['String'] } /** Distance */ export type Distance = { __typename?: 'Distance' /** Distance in specified length unit */ value: Scalars['Float'] /** Length unit */ lengthUnit: LengthUnit } /** Filter locations by the distance */ export type DistanceFilter = { /** Radius of search in length units specified in lengthUnit argument */ radius: Scalars['Float'] /** Signed decimal degrees without compass direction */ longitude: Scalars['Float'] /** Signed decimal degrees without compass direction */ latitude: Scalars['Float'] lengthUnit: LengthUnit } /** Entity page type */ export enum EntityPageType { BlogPost = 'BLOG_POST', Brand = 'BRAND', Category = 'CATEGORY', ContactUs = 'CONTACT_US', Page = 'PAGE', Product = 'PRODUCT', } /** A form allowing selection and uploading of a file from the user's local computer. */ export type FileUploadFieldOption = CatalogProductOption & { __typename?: 'FileUploadFieldOption' /** The maximum size of the file in kilobytes */ maxFileSize: Scalars['Int'] /** All possible file extensions. Empty means that all files allowed. */ fileTypes: Array<Scalars['String']> /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** Image */ export type Image = { __typename?: 'Image' /** Absolute path to image using store CDN. */ url: Scalars['String'] /** Absolute path to original image using store CDN. */ urlOriginal: Scalars['String'] /** Text description of an image that can be used for SEO and/or accessibility purposes. */ altText: Scalars['String'] /** Indicates whether this is the primary image. */ isDefault: Scalars['Boolean'] } /** Image */ export type ImageUrlArgs = { width: Scalars['Int'] height?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type ImageConnection = { __typename?: 'ImageConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<ImageEdge>>> } /** An edge in a connection. */ export type ImageEdge = { __typename?: 'ImageEdge' /** The item at the end of the edge. */ node: Image /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** An inventory */ export type Inventory = { __typename?: 'Inventory' /** Locations */ locations: LocationConnection } /** An inventory */ export type InventoryLocationsArgs = { entityIds?: Maybe<Array<Scalars['Int']>> codes?: Maybe<Array<Scalars['String']>> typeIds?: Maybe<Array<Scalars['String']>> serviceTypeIds?: Maybe<Array<Scalars['String']>> distanceFilter?: Maybe<DistanceFilter> countryCodes?: Maybe<Array<CountryCode>> states?: Maybe<Array<Scalars['String']>> cities?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Inventory By Locations */ export type InventoryByLocations = { __typename?: 'InventoryByLocations' /** Location id. */ locationEntityId: Scalars['Long'] /** Number of available products in stock. */ availableToSell: Scalars['Long'] /** Indicates a threshold low-stock level. */ warningLevel: Scalars['Int'] /** Indicates whether this product is in stock. */ isInStock: Scalars['Boolean'] /** Distance between location and specified longitude and latitude */ locationDistance?: Maybe<Distance> /** Location type id. */ locationEntityTypeId?: Maybe<Scalars['String']> /** * Location service type ids. * @deprecated Deprecated. Will be substituted with pickup methods. */ locationEntityServiceTypeIds: Array<Scalars['String']> /** Location code. */ locationEntityCode: Scalars['String'] } /** length unit */ export enum LengthUnit { Miles = 'Miles', Kilometres = 'Kilometres', } export enum LimitDateOption { NoLimit = 'NO_LIMIT', EarliestDate = 'EARLIEST_DATE', LatestDate = 'LATEST_DATE', Range = 'RANGE', } export enum LimitInputBy { NoLimit = 'NO_LIMIT', LowestValue = 'LOWEST_VALUE', HighestValue = 'HIGHEST_VALUE', Range = 'RANGE', } /** A connection to a list of items. */ export type LocationConnection = { __typename?: 'LocationConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<LocationEdge>>> } /** An edge in a connection. */ export type LocationEdge = { __typename?: 'LocationEdge' /** The item at the end of the edge. */ node: InventoryByLocations /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Logo field */ export type LogoField = { __typename?: 'LogoField' /** Logo title. */ title: Scalars['String'] /** Store logo image. */ image: Image } /** Measurement */ export type Measurement = { __typename?: 'Measurement' /** Unformatted weight measurement value. */ value: Scalars['Float'] /** Unit of measurement. */ unit: Scalars['String'] } /** A connection to a list of items. */ export type MetafieldConnection = { __typename?: 'MetafieldConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<MetafieldEdge>>> } /** An edge in a connection. */ export type MetafieldEdge = { __typename?: 'MetafieldEdge' /** The item at the end of the edge. */ node: Metafields /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Key/Value pairs of data attached tied to a resource entity (product, brand, category, etc.) */ export type Metafields = { __typename?: 'Metafields' /** The ID of an object */ id: Scalars['ID'] /** The ID of the metafield when referencing via our backend API. */ entityId: Scalars['Int'] /** A label for identifying a metafield data value. */ key: Scalars['String'] /** A metafield value. */ value: Scalars['String'] } /** A money object - includes currency code and a money amount */ export type Money = { __typename?: 'Money' /** Currency code of the current money. */ currencyCode: Scalars['String'] /** The amount of money. */ value: Scalars['BigDecimal'] } /** A min and max pair of money objects */ export type MoneyRange = { __typename?: 'MoneyRange' /** Minimum money object. */ min: Money /** Maximum money object. */ max: Money } /** A multi-line text input field, aka a text box. */ export type MultiLineTextFieldOption = CatalogProductOption & { __typename?: 'MultiLineTextFieldOption' /** Default value of the multiline text field option. */ defaultValue?: Maybe<Scalars['String']> /** The minimum number of characters. */ minLength?: Maybe<Scalars['Int']> /** The maximum number of characters. */ maxLength?: Maybe<Scalars['Int']> /** The maximum number of lines. */ maxLines?: Maybe<Scalars['Int']> /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** An option type that has a fixed list of values. */ export type MultipleChoiceOption = CatalogProductOption & { __typename?: 'MultipleChoiceOption' /** The chosen display style for this multiple choice option. */ displayStyle: Scalars['String'] /** List of option values. */ values: ProductOptionValueConnection /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** An option type that has a fixed list of values. */ export type MultipleChoiceOptionValuesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A simple multiple choice value comprised of an id and a label. */ export type MultipleChoiceOptionValue = CatalogProductOptionValue & { __typename?: 'MultipleChoiceOptionValue' /** Unique ID for the option value. */ entityId: Scalars['Int'] /** Label for the option value. */ label: Scalars['String'] /** Indicates whether this value is the chosen default selected value. */ isDefault: Scalars['Boolean'] } /** An object with an ID */ export type Node = { /** The id of the object. */ id: Scalars['ID'] } /** A single line text input field that only accepts numbers. */ export type NumberFieldOption = CatalogProductOption & { __typename?: 'NumberFieldOption' /** Default value of the text field option. */ defaultValue?: Maybe<Scalars['Float']> /** The bottom limit of possible numbers. */ lowest?: Maybe<Scalars['Float']> /** The top limit of possible numbers. */ highest?: Maybe<Scalars['Float']> /** Allow whole numbers only. */ isIntegerOnly?: Maybe<Scalars['Float']> /** Limit numbers by several options. */ limitNumberBy: LimitInputBy /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** A connection to a list of items. */ export type OptionConnection = { __typename?: 'OptionConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<OptionEdge>>> } /** An edge in a connection. */ export type OptionEdge = { __typename?: 'OptionEdge' /** The item at the end of the edge. */ node: ProductOption /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** A connection to a list of items. */ export type OptionValueConnection = { __typename?: 'OptionValueConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<OptionValueEdge>>> } /** An edge in a connection. */ export type OptionValueEdge = { __typename?: 'OptionValueEdge' /** The item at the end of the edge. */ node: ProductOptionValue /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type OptionValueId = { optionEntityId: Scalars['Int'] valueEntityId: Scalars['Int'] } /** Information about pagination in a connection. */ export type PageInfo = { __typename?: 'PageInfo' /** When paginating forwards, are there more items? */ hasNextPage: Scalars['Boolean'] /** When paginating backwards, are there more items? */ hasPreviousPage: Scalars['Boolean'] /** When paginating backwards, the cursor to continue. */ startCursor?: Maybe<Scalars['String']> /** When paginating forwards, the cursor to continue. */ endCursor?: Maybe<Scalars['String']> } /** Page type */ export enum PageType { AccountAddress = 'ACCOUNT_ADDRESS', AccountAddAddress = 'ACCOUNT_ADD_ADDRESS', AccountAddReturn = 'ACCOUNT_ADD_RETURN', AccountAddWishlist = 'ACCOUNT_ADD_WISHLIST', AccountDownloadItem = 'ACCOUNT_DOWNLOAD_ITEM', AccountEdit = 'ACCOUNT_EDIT', AccountInbox = 'ACCOUNT_INBOX', AccountOrdersAll = 'ACCOUNT_ORDERS_ALL', AccountOrdersCompleted = 'ACCOUNT_ORDERS_COMPLETED', AccountOrdersDetails = 'ACCOUNT_ORDERS_DETAILS', AccountOrdersInvoice = 'ACCOUNT_ORDERS_INVOICE', AccountRecentItems = 'ACCOUNT_RECENT_ITEMS', AccountReturns = 'ACCOUNT_RETURNS', AccountReturnSaved = 'ACCOUNT_RETURN_SAVED', AccountWishlists = 'ACCOUNT_WISHLISTS', AccountWishlistDetails = 'ACCOUNT_WISHLIST_DETAILS', AuthAccountCreated = 'AUTH_ACCOUNT_CREATED', AuthCreateAcc = 'AUTH_CREATE_ACC', AuthForgotPass = 'AUTH_FORGOT_PASS', AuthLogin = 'AUTH_LOGIN', AuthNewPass = 'AUTH_NEW_PASS', Blog = 'BLOG', Brands = 'BRANDS', Cart = 'CART', Compare = 'COMPARE', GiftCertBalance = 'GIFT_CERT_BALANCE', GiftCertPurchase = 'GIFT_CERT_PURCHASE', GiftCertRedeem = 'GIFT_CERT_REDEEM', Home = 'HOME', OrderInfo = 'ORDER_INFO', Search = 'SEARCH', Sitemap = 'SITEMAP', Subscribed = 'SUBSCRIBED', Unsubscribe = 'UNSUBSCRIBE', } /** The min and max range of prices that apply to this product. */ export type PriceRanges = { __typename?: 'PriceRanges' /** Product price min/max range. */ priceRange: MoneyRange /** Product retail price min/max range. */ retailPriceRange?: Maybe<MoneyRange> } export type PriceSearchFilterInput = { minPrice?: Maybe<Scalars['Float']> maxPrice?: Maybe<Scalars['Float']> } /** The various prices that can be set on a product. */ export type Prices = { __typename?: 'Prices' /** Calculated price of the product. Calculated price takes into account basePrice, salePrice, rules (modifier, option, option set) that apply to the product configuration, and customer group discounts. It represents the in-cart price for a product configuration without bulk pricing rules. */ price: Money /** Sale price of the product. */ salePrice?: Maybe<Money> /** Original price of the product. */ basePrice?: Maybe<Money> /** Retail price of the product. */ retailPrice?: Maybe<Money> /** Minimum advertised price of the product. */ mapPrice?: Maybe<Money> /** Product price min/max range. */ priceRange: MoneyRange /** Product retail price min/max range. */ retailPriceRange?: Maybe<MoneyRange> /** The difference between the retail price (MSRP) and the current price, which can be presented to the shopper as their savings. */ saved?: Maybe<Money> /** List of bulk pricing tiers applicable to a product or variant. */ bulkPricing: Array<BulkPricingTier> } /** Product */ export type Product = Node & { __typename?: 'Product' /** The ID of an object */ id: Scalars['ID'] /** Id of the product. */ entityId: Scalars['Int'] /** Default product variant when no options are selected. */ sku: Scalars['String'] /** Relative URL path to product page. */ path: Scalars['String'] /** Name of the product. */ name: Scalars['String'] /** Description of the product. */ description: Scalars['String'] /** Description of the product in plain text. */ plainTextDescription: Scalars['String'] /** Warranty information of the product. */ warranty: Scalars['String'] /** Minimum purchasable quantity for this product in a single order. */ minPurchaseQuantity?: Maybe<Scalars['Int']> /** Maximum purchasable quantity for this product in a single order. */ maxPurchaseQuantity?: Maybe<Scalars['Int']> /** Absolute URL path for adding a product to cart. */ addToCartUrl: Scalars['String'] /** * Absolute URL path for adding a product to customer's wishlist. * @deprecated Deprecated. */ addToWishlistUrl: Scalars['String'] /** Prices object determined by supplied product ID, variant ID, and selected option IDs. */ prices?: Maybe<Prices> /** * The minimum and maximum price of this product based on variant pricing and/or modifier price rules. * @deprecated Use priceRanges inside prices node instead. */ priceRanges?: Maybe<PriceRanges> /** Weight of the product. */ weight?: Maybe<Measurement> /** Height of the product. */ height?: Maybe<Measurement> /** Width of the product. */ width?: Maybe<Measurement> /** Depth of the product. */ depth?: Maybe<Measurement> /** * Product options. * @deprecated Use productOptions instead. */ options: OptionConnection /** Product options. */ productOptions: ProductOptionConnection /** Summary of the product reviews, includes the total number of reviews submitted and summation of the ratings on the reviews (ratings range from 0-5 per review). */ reviewSummary: Reviews /** Type of product, ex: physical, digital */ type: Scalars['String'] /** * The availability state of the product. * @deprecated Use status inside availabilityV2 instead. */ availability: Scalars['String'] /** * A few words telling the customer how long it will normally take to ship this product, such as 'Usually ships in 24 hours'. * @deprecated Use description inside availabilityV2 instead. */ availabilityDescription: Scalars['String'] /** The availability state of the product. */ availabilityV2: ProductAvailability /** List of categories associated with the product. */ categories: CategoryConnection /** Brand associated with the product. */ brand?: Maybe<Brand> /** Variants associated with the product. */ variants: VariantConnection /** Custom fields of the product. */ customFields: CustomFieldConnection /** A list of the images for a product. */ images: ImageConnection /** Default image for a product. */ defaultImage?: Maybe<Image> /** Related products for this product. */ relatedProducts: RelatedProductsConnection /** Inventory information of the product. */ inventory: ProductInventory /** Metafield data related to a product. */ metafields: MetafieldConnection /** Universal product code. */ upc?: Maybe<Scalars['String']> /** Manufacturer part number. */ mpn?: Maybe<Scalars['String']> /** Global trade item number. */ gtin?: Maybe<Scalars['String']> /** * Product creation date * @deprecated Alpha version. Do not use in production. */ createdAt: DateTimeExtended /** Reviews associated with the product. */ reviews: ReviewConnection /** Product SEO details. */ seo: SeoDetails } /** Product */ export type ProductPlainTextDescriptionArgs = { characterLimit?: Maybe<Scalars['Int']> } /** Product */ export type ProductPricesArgs = { includeTax?: Maybe<Scalars['Boolean']> currencyCode?: Maybe<CurrencyCode> } /** Product */ export type ProductPriceRangesArgs = { includeTax?: Maybe<Scalars['Boolean']> } /** Product */ export type ProductOptionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductProductOptionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductCategoriesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductVariantsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> entityIds?: Maybe<Array<Scalars['Int']>> optionValueIds?: Maybe<Array<OptionValueId>> } /** Product */ export type ProductCustomFieldsArgs = { names?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductImagesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductRelatedProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductMetafieldsArgs = { namespace: Scalars['String'] keys?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Product */ export type ProductReviewsArgs = { sort?: Maybe<ProductReviewsSortInput> filters?: Maybe<ProductReviewsFiltersInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type ProductAttributeSearchFilterInput = { attribute: Scalars['String'] values: Array<Scalars['String']> } /** Product availability */ export type ProductAvailability = { /** The availability state of the product. */ status: ProductAvailabilityStatus /** A few words telling the customer how long it will normally take to ship this product, such as 'Usually ships in 24 hours'. */ description: Scalars['String'] } /** Product availability status */ export enum ProductAvailabilityStatus { Available = 'Available', Preorder = 'Preorder', Unavailable = 'Unavailable', } /** Available Product */ export type ProductAvailable = ProductAvailability & { __typename?: 'ProductAvailable' /** The availability state of the product. */ status: ProductAvailabilityStatus /** A few words telling the customer how long it will normally take to ship this product, such as 'Usually ships in 24 hours'. */ description: Scalars['String'] } /** A connection to a list of items. */ export type ProductConnection = { __typename?: 'ProductConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<ProductEdge>>> } /** An edge in a connection. */ export type ProductEdge = { __typename?: 'ProductEdge' /** The item at the end of the edge. */ node: Product /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Product Inventory Information */ export type ProductInventory = { __typename?: 'ProductInventory' /** Indicates whether this product is in stock. */ isInStock: Scalars['Boolean'] /** Indicates whether this product's inventory is being tracked on variant level. If true, you may wish to check the variants node to understand the true inventory of each individual variant, rather than relying on this product-level aggregate to understand how many items may be added to cart. */ hasVariantInventory: Scalars['Boolean'] /** Aggregated product inventory information. This data may not be available if not set or if the store's Inventory Settings have disabled displaying stock levels on the storefront. */ aggregated?: Maybe<AggregatedInventory> } /** Product Option */ export type ProductOption = { __typename?: 'ProductOption' /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Option values. */ values: OptionValueConnection } /** Product Option */ export type ProductOptionValuesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type ProductOptionConnection = { __typename?: 'ProductOptionConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<ProductOptionEdge>>> } /** An edge in a connection. */ export type ProductOptionEdge = { __typename?: 'ProductOptionEdge' /** The item at the end of the edge. */ node: CatalogProductOption /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Product Option Value */ export type ProductOptionValue = { __typename?: 'ProductOptionValue' /** Unique ID for the option value. */ entityId: Scalars['Int'] /** Label for the option value. */ label: Scalars['String'] } /** A connection to a list of items. */ export type ProductOptionValueConnection = { __typename?: 'ProductOptionValueConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<ProductOptionValueEdge>>> } /** An edge in a connection. */ export type ProductOptionValueEdge = { __typename?: 'ProductOptionValueEdge' /** The item at the end of the edge. */ node: CatalogProductOptionValue /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** A Product PickList Value - a product to be mapped to the base product if selected. */ export type ProductPickListOptionValue = CatalogProductOptionValue & { __typename?: 'ProductPickListOptionValue' /** The ID of the product associated with this option value. */ productId: Scalars['Int'] /** Unique ID for the option value. */ entityId: Scalars['Int'] /** Label for the option value. */ label: Scalars['String'] /** Indicates whether this value is the chosen default selected value. */ isDefault: Scalars['Boolean'] } /** PreOrder Product */ export type ProductPreOrder = ProductAvailability & { __typename?: 'ProductPreOrder' /** The message to be shown in the store when a product is put into the pre-order availability state, e.g. "Expected release date is %%DATE%%" */ message?: Maybe<Scalars['String']> /** Product release date */ willBeReleasedAt?: Maybe<DateTimeExtended> /** The availability state of the product. */ status: ProductAvailabilityStatus /** A few words telling the customer how long it will normally take to ship this product, such as 'Usually ships in 24 hours'. */ description: Scalars['String'] } export type ProductReviewsFiltersInput = { rating?: Maybe<ProductReviewsRatingFilterInput> } export type ProductReviewsRatingFilterInput = { minRating?: Maybe<Scalars['Int']> maxRating?: Maybe<Scalars['Int']> } export enum ProductReviewsSortInput { Newest = 'NEWEST', Oldest = 'OLDEST', HighestRating = 'HIGHEST_RATING', LowestRating = 'LOWEST_RATING', } /** Unavailable Product */ export type ProductUnavailable = ProductAvailability & { __typename?: 'ProductUnavailable' /** The message to be shown in the store when "Call for pricing" is enabled for this product, e.g. "Contact us at 555-5555" */ message?: Maybe<Scalars['String']> /** The availability state of the product. */ status: ProductAvailabilityStatus /** A few words telling the customer how long it will normally take to ship this product, such as 'Usually ships in 24 hours'. */ description: Scalars['String'] } /** Public Wishlist */ export type PublicWishlist = { __typename?: 'PublicWishlist' /** The wishlist id. */ entityId: Scalars['Int'] /** The wishlist name. */ name: Scalars['String'] /** The wishlist token. */ token: Scalars['String'] items: WishlistItemConnection } /** Public Wishlist */ export type PublicWishlistItemsArgs = { hideOutOfStock?: Maybe<Scalars['Boolean']> first?: Maybe<Scalars['Int']> } export type Query = { __typename?: 'Query' site: Site /** The currently logged in customer. */ customer?: Maybe<Customer> /** Fetches an object given its ID */ node?: Maybe<Node> /** @deprecated Alpha version. Do not use in production. */ inventory: Inventory } export type QueryNodeArgs = { id: Scalars['ID'] } export type RatingSearchFilterInput = { minRating?: Maybe<Scalars['Float']> maxRating?: Maybe<Scalars['Float']> } export type Region = { __typename?: 'Region' /** The name of a region. */ name: Scalars['String'] /** The rendered HTML content targeted at the region. */ html: Scalars['String'] } /** A connection to a list of items. */ export type RelatedProductsConnection = { __typename?: 'RelatedProductsConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<RelatedProductsEdge>>> } /** An edge in a connection. */ export type RelatedProductsEdge = { __typename?: 'RelatedProductsEdge' /** The item at the end of the edge. */ node: Product /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** The rendered regions by specific page. */ export type RenderedRegionsByPageType = { __typename?: 'RenderedRegionsByPageType' regions: Array<Region> } /** Review */ export type Review = { __typename?: 'Review' /** Unique ID for the product review. */ entityId: Scalars['Long'] /** Product review author. */ author: Author /** Product review title. */ title: Scalars['String'] /** Product review text. */ text: Scalars['String'] /** Product review rating. */ rating: Scalars['Int'] /** Product review creation date. */ createdAt: DateTimeExtended } /** A connection to a list of items. */ export type ReviewConnection = { __typename?: 'ReviewConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<ReviewEdge>>> } /** An edge in a connection. */ export type ReviewEdge = { __typename?: 'ReviewEdge' /** The item at the end of the edge. */ node: Review /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Review Rating Summary */ export type Reviews = { __typename?: 'Reviews' /** * Average rating of the product. * @deprecated Alpha version. Do not use in production. */ averageRating: Scalars['Float'] /** Total number of reviews on product. */ numberOfReviews: Scalars['Int'] /** Summation of rating scores from each review. */ summationOfRatings: Scalars['Int'] } /** route */ export type Route = { __typename?: 'Route' /** node */ node?: Maybe<Node> } /** Store search settings. */ export type Search = { __typename?: 'Search' /** Product filtering enabled. */ productFilteringEnabled: Scalars['Boolean'] } export type SearchProducts = { __typename?: 'SearchProducts' /** Details of the products. */ products: ProductConnection } export type SearchProductsProductsArgs = { after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> } export type SearchProductsFiltersInput = { searchTerm?: Maybe<Scalars['String']> price?: Maybe<PriceSearchFilterInput> rating?: Maybe<RatingSearchFilterInput> categoryEntityId?: Maybe<Scalars['Int']> categoryEntityIds?: Maybe<Array<Scalars['Int']>> brandEntityIds?: Maybe<Array<Scalars['Int']>> productAttributes?: Maybe<Array<ProductAttributeSearchFilterInput>> isFreeShipping?: Maybe<Scalars['Boolean']> isFeatured?: Maybe<Scalars['Boolean']> isInStock?: Maybe<Scalars['Boolean']> } export enum SearchProductsSortInput { Featured = 'FEATURED', Newest = 'NEWEST', BestSelling = 'BEST_SELLING', BestReviewed = 'BEST_REVIEWED', AToZ = 'A_TO_Z', ZToA = 'Z_TO_A', LowestPrice = 'LOWEST_PRICE', HighestPrice = 'HIGHEST_PRICE', } export type SearchQueries = { __typename?: 'SearchQueries' /** Details of the products and facets matching given search criteria. */ searchProducts: SearchProducts } export type SearchQueriesSearchProductsArgs = { filters: SearchProductsFiltersInput sort?: Maybe<SearchProductsSortInput> } /** Seo Details */ export type SeoDetails = { __typename?: 'SeoDetails' /** Page title. */ pageTitle: Scalars['String'] /** Meta description. */ metaDescription: Scalars['String'] /** Meta keywords. */ metaKeywords: Scalars['String'] } /** Store settings information from the control panel. */ export type Settings = { __typename?: 'Settings' /** The name of the store. */ storeName: Scalars['String'] /** The hash of the store. */ storeHash: Scalars['String'] /** The current store status. */ status: StorefrontStatusType /** Logo information for the store. */ logo: LogoField /** Contact information for the store. */ contact?: Maybe<ContactField> /** Store urls. */ url: UrlField /** Store display format information. */ display: DisplayField /** Channel ID. */ channelId: Scalars['Long'] tax?: Maybe<TaxDisplaySettings> /** Store search settings. */ search: Search } /** A site */ export type Site = { __typename?: 'Site' /** * The Search queries. * @deprecated Alpha version. Do not use in production. */ search: SearchQueries categoryTree: Array<CategoryTreeItem> /** Retrieve a category object by the id. */ category?: Maybe<Category> /** Details of the brand. */ brands: BrandConnection /** Details of the products. */ products: ProductConnection /** Details of the newest products. */ newestProducts: ProductConnection /** Details of the best selling products. */ bestSellingProducts: ProductConnection /** Details of the featured products. */ featuredProducts: ProductConnection /** A single product object with variant pricing overlay capabilities. */ product?: Maybe<Product> /** Route for a node */ route: Route /** Store settings. */ settings?: Maybe<Settings> content: Content /** Currency details. */ currency?: Maybe<Currency> /** Store Currencies. */ currencies: CurrencyConnection publicWishlist?: Maybe<PublicWishlist> } /** A site */ export type SiteCategoryTreeArgs = { rootEntityId?: Maybe<Scalars['Int']> } /** A site */ export type SiteCategoryArgs = { entityId: Scalars['Int'] } /** A site */ export type SiteBrandsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> productEntityIds?: Maybe<Array<Scalars['Int']>> } /** A site */ export type SiteProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> ids?: Maybe<Array<Scalars['ID']>> entityIds?: Maybe<Array<Scalars['Int']>> hideOutOfStock?: Maybe<Scalars['Boolean']> } /** A site */ export type SiteNewestProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> hideOutOfStock?: Maybe<Scalars['Boolean']> } /** A site */ export type SiteBestSellingProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> hideOutOfStock?: Maybe<Scalars['Boolean']> } /** A site */ export type SiteFeaturedProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> hideOutOfStock?: Maybe<Scalars['Boolean']> } /** A site */ export type SiteProductArgs = { id?: Maybe<Scalars['ID']> entityId?: Maybe<Scalars['Int']> variantEntityId?: Maybe<Scalars['Int']> optionValueIds?: Maybe<Array<OptionValueId>> sku?: Maybe<Scalars['String']> } /** A site */ export type SiteRouteArgs = { path: Scalars['String'] } /** A site */ export type SiteCurrencyArgs = { currencyCode: CurrencyCode } /** A site */ export type SiteCurrenciesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A site */ export type SitePublicWishlistArgs = { token: Scalars['String'] } /** Storefront Mode */ export enum StorefrontStatusType { Launched = 'LAUNCHED', Maintenance = 'MAINTENANCE', PreLaunch = 'PRE_LAUNCH', Hibernation = 'HIBERNATION', } /** A swatch option value - swatch values can be associated with a list of hexidecimal colors or an image. */ export type SwatchOptionValue = CatalogProductOptionValue & { __typename?: 'SwatchOptionValue' /** List of up to 3 hex encoded colors to associate with a swatch value. */ hexColors: Array<Scalars['String']> /** Absolute path of a swatch texture image. */ imageUrl?: Maybe<Scalars['String']> /** Unique ID for the option value. */ entityId: Scalars['Int'] /** Label for the option value. */ label: Scalars['String'] /** Indicates whether this value is the chosen default selected value. */ isDefault: Scalars['Boolean'] } /** A swatch option value - swatch values can be associated with a list of hexidecimal colors or an image. */ export type SwatchOptionValueImageUrlArgs = { width: Scalars['Int'] height?: Maybe<Scalars['Int']> } export type TaxDisplaySettings = { __typename?: 'TaxDisplaySettings' /** Tax display setting for Product Details Page. */ pdp: TaxPriceDisplay /** Tax display setting for Product List Page. */ plp: TaxPriceDisplay } /** Tax setting can be set included or excluded (Tax setting can also be set to both on PDP/PLP). */ export enum TaxPriceDisplay { Inc = 'INC', Ex = 'EX', Both = 'BOTH', } /** A single line text input field. */ export type TextFieldOption = CatalogProductOption & { __typename?: 'TextFieldOption' /** Default value of the text field option. */ defaultValue?: Maybe<Scalars['String']> /** The minimum number of characters. */ minLength?: Maybe<Scalars['Int']> /** The maximum number of characters. */ maxLength?: Maybe<Scalars['Int']> /** Unique ID for the option. */ entityId: Scalars['Int'] /** Display name for the option. */ displayName: Scalars['String'] /** One of the option values is required to be selected for the checkout. */ isRequired: Scalars['Boolean'] /** Indicates whether it is a variant option or modifier. */ isVariantOption: Scalars['Boolean'] } /** Url field */ export type UrlField = { __typename?: 'UrlField' /** Store url. */ vanityUrl: Scalars['String'] /** CDN url to fetch assets. */ cdnUrl: Scalars['String'] } /** Variant */ export type Variant = Node & { __typename?: 'Variant' /** The ID of an object */ id: Scalars['ID'] /** Id of the variant. */ entityId: Scalars['Int'] /** Sku of the variant. */ sku: Scalars['String'] /** The variant's weight. If a weight was not explicitly specified on the variant, this will be the product's weight. */ weight?: Maybe<Measurement> /** The variant's height. If a height was not explicitly specified on the variant, this will be the product's height. */ height?: Maybe<Measurement> /** The variant's width. If a width was not explicitly specified on the variant, this will be the product's width. */ width?: Maybe<Measurement> /** The variant's depth. If a depth was not explicitly specified on the variant, this will be the product's depth. */ depth?: Maybe<Measurement> /** The options which define a variant. */ options: OptionConnection /** Product options that compose this variant. */ productOptions: ProductOptionConnection /** Default image for a variant. */ defaultImage?: Maybe<Image> /** Variant prices */ prices?: Maybe<Prices> /** Variant inventory */ inventory?: Maybe<VariantInventory> /** Metafield data related to a variant. */ metafields: MetafieldConnection /** Universal product code. */ upc?: Maybe<Scalars['String']> /** Manufacturer part number. */ mpn?: Maybe<Scalars['String']> /** Global trade item number. */ gtin?: Maybe<Scalars['String']> } /** Variant */ export type VariantOptionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Variant */ export type VariantProductOptionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Variant */ export type VariantPricesArgs = { includeTax?: Maybe<Scalars['Boolean']> currencyCode?: Maybe<CurrencyCode> } /** Variant */ export type VariantMetafieldsArgs = { namespace: Scalars['String'] keys?: Maybe<Array<Scalars['String']>> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type VariantConnection = { __typename?: 'VariantConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<VariantEdge>>> } /** An edge in a connection. */ export type VariantEdge = { __typename?: 'VariantEdge' /** The item at the end of the edge. */ node: Variant /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Variant Inventory */ export type VariantInventory = { __typename?: 'VariantInventory' /** Aggregated product variant inventory information. This data may not be available if not set or if the store's Inventory Settings have disabled displaying stock levels on the storefront. */ aggregated?: Maybe<Aggregated> /** Indicates whether this product is in stock. */ isInStock: Scalars['Boolean'] /** Inventory by locations. */ byLocation?: Maybe<LocationConnection> } /** Variant Inventory */ export type VariantInventoryByLocationArgs = { locationEntityIds?: Maybe<Array<Scalars['Int']>> locationEntityCodes?: Maybe<Array<Scalars['String']>> locationEntityTypeIds?: Maybe<Array<Scalars['String']>> locationEntityServiceTypeIds?: Maybe<Array<Scalars['String']>> distanceFilter?: Maybe<DistanceFilter> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type Wishlist = { __typename?: 'Wishlist' /** The wishlist id. */ entityId: Scalars['Int'] /** The wishlist name. */ name: Scalars['String'] /** Is the wishlist public? */ isPublic: Scalars['Boolean'] /** The wishlist token. */ token: Scalars['String'] items: WishlistItemConnection } export type WishlistItemsArgs = { hideOutOfStock?: Maybe<Scalars['Boolean']> first?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type WishlistConnection = { __typename?: 'WishlistConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<WishlistEdge>>> } /** An edge in a connection. */ export type WishlistEdge = { __typename?: 'WishlistEdge' /** The item at the end of the edge. */ node: Wishlist /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Wishlist filters input object */ export type WishlistFiltersInput = { entityIds?: Maybe<Array<Scalars['Int']>> } /** WishlistItem */ export type WishlistItem = { __typename?: 'WishlistItem' /** Wishlist item id. */ entityId: Scalars['Int'] product: Product productEntityId: Scalars['Int'] variantEntityId?: Maybe<Scalars['Int']> } /** A connection to a list of items. */ export type WishlistItemConnection = { __typename?: 'WishlistItemConnection' /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges?: Maybe<Array<Maybe<WishlistItemEdge>>> } /** An edge in a connection. */ export type WishlistItemEdge = { __typename?: 'WishlistItemEdge' /** The item at the end of the edge. */ node: WishlistItem /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Country Code */ export enum CountryCode { Aw = 'AW', Af = 'AF', Ao = 'AO', Ai = 'AI', Ax = 'AX', Al = 'AL', Ad = 'AD', Ae = 'AE', Ar = 'AR', Am = 'AM', As = 'AS', Aq = 'AQ', Tf = 'TF', Ag = 'AG', Au = 'AU', At = 'AT', Az = 'AZ', Bi = 'BI', Be = 'BE', Bj = 'BJ', Bq = 'BQ', Bf = 'BF', Bd = 'BD', Bg = 'BG', Bh = 'BH', Bs = 'BS', Ba = 'BA', Bl = 'BL', By = 'BY', Bz = 'BZ', Bm = 'BM', Bo = 'BO', Br = 'BR', Bb = 'BB', Bn = 'BN', Bt = 'BT', Bv = 'BV', Bw = 'BW', Cf = 'CF', Ca = 'CA', Cc = 'CC', Ch = 'CH', Cl = 'CL', Cn = 'CN', Ci = 'CI', Cm = 'CM', Cd = 'CD', Cg = 'CG', Ck = 'CK', Co = 'CO', Km = 'KM', Cv = 'CV', Cr = 'CR', Cu = 'CU', Cw = 'CW', Cx = 'CX', Ky = 'KY', Cy = 'CY', Cz = 'CZ', De = 'DE', Dj = 'DJ', Dm = 'DM', Dk = 'DK', Do = 'DO', Dz = 'DZ', Ec = 'EC', Eg = 'EG', Er = 'ER', Eh = 'EH', Es = 'ES', Ee = 'EE', Et = 'ET', Fi = 'FI', Fj = 'FJ', Fk = 'FK', Fr = 'FR', Fo = 'FO', Fm = 'FM', Ga = 'GA', Gb = 'GB', Ge = 'GE', Gg = 'GG', Gh = 'GH', Gi = 'GI', Gn = 'GN', Gp = 'GP', Gm = 'GM', Gw = 'GW', Gq = 'GQ', Gr = 'GR', Gd = 'GD', Gl = 'GL', Gt = 'GT', Gf = 'GF', Gu = 'GU', Gy = 'GY', Hk = 'HK', Hm = 'HM', Hn = 'HN', Hr = 'HR', Ht = 'HT', Hu = 'HU', Id = 'ID', Im = 'IM', In = 'IN', Io = 'IO', Ie = 'IE', Ir = 'IR', Iq = 'IQ', Is = 'IS', Il = 'IL', It = 'IT', Jm = 'JM', Je = 'JE', Jo = 'JO', Jp = 'JP', Kz = 'KZ', Ke = 'KE', Kg = 'KG', Kh = 'KH', Ki = 'KI', Kn = 'KN', Kr = 'KR', Kw = 'KW', La = 'LA', Lb = 'LB', Lr = 'LR', Ly = 'LY', Lc = 'LC', Li = 'LI', Lk = 'LK', Ls = 'LS', Lt = 'LT', Lu = 'LU', Lv = 'LV', Mo = 'MO', Mf = 'MF', Ma = 'MA', Mc = 'MC', Md = 'MD', Mg = 'MG', Mv = 'MV', Mx = 'MX', Mh = 'MH', Mk = 'MK', Ml = 'ML', Mt = 'MT', Mm = 'MM', Me = 'ME', Mn = 'MN', Mp = 'MP', Mz = 'MZ', Mr = 'MR', Ms = 'MS', Mq = 'MQ', Mu = 'MU', Mw = 'MW', My = 'MY', Yt = 'YT', Na = 'NA', Nc = 'NC', Ne = 'NE', Nf = 'NF', Ng = 'NG', Ni = 'NI', Nu = 'NU', Nl = 'NL', No = 'NO', Np = 'NP', Nr = 'NR', Nz = 'NZ', Om = 'OM', Pk = 'PK', Pa = 'PA', Pn = 'PN', Pe = 'PE', Ph = 'PH', Pw = 'PW', Pg = 'PG', Pl = 'PL', Pr = 'PR', Kp = 'KP', Pt = 'PT', Py = 'PY', Ps = 'PS', Pf = 'PF', Qa = 'QA', Re = 'RE', Ro = 'RO', Ru = 'RU', Rw = 'RW', Sa = 'SA', Sd = 'SD', Sn = 'SN', Sg = 'SG', Gs = 'GS', Sh = 'SH', Sj = 'SJ', Sb = 'SB', Sl = 'SL', Sv = 'SV', Sm = 'SM', So = 'SO', Pm = 'PM', Rs = 'RS', Ss = 'SS', St = 'ST', Sr = 'SR', Sk = 'SK', Si = 'SI', Se = 'SE', Sz = 'SZ', Sx = 'SX', Sc = 'SC', Sy = 'SY', Tc = 'TC', Td = 'TD', Tg = 'TG', Th = 'TH', Tj = 'TJ', Tk = 'TK', Tm = 'TM', Tl = 'TL', To = 'TO', Tt = 'TT', Tn = 'TN', Tr = 'TR', Tv = 'TV', Tw = 'TW', Tz = 'TZ', Ug = 'UG', Ua = 'UA', Um = 'UM', Uy = 'UY', Us = 'US', Uz = 'UZ', Va = 'VA', Vc = 'VC', Ve = 'VE', Vg = 'VG', Vi = 'VI', Vn = 'VN', Vu = 'VU', Wf = 'WF', Ws = 'WS', Ye = 'YE', Za = 'ZA', Zm = 'ZM', Zw = 'ZW', } /** Currency Code */ export enum CurrencyCode { Adp = 'ADP', Aed = 'AED', Afa = 'AFA', Afn = 'AFN', Alk = 'ALK', All = 'ALL', Amd = 'AMD', Ang = 'ANG', Aoa = 'AOA', Aok = 'AOK', Aon = 'AON', Aor = 'AOR', Ara = 'ARA', Arl = 'ARL', Arm = 'ARM', Arp = 'ARP', Ars = 'ARS', Ats = 'ATS', Aud = 'AUD', Awg = 'AWG', Azm = 'AZM', Azn = 'AZN', Bad = 'BAD', Bam = 'BAM', Ban = 'BAN', Bbd = 'BBD', Bdt = 'BDT', Bec = 'BEC', Bef = 'BEF', Bel = 'BEL', Bgl = 'BGL', Bgm = 'BGM', Bgn = 'BGN', Bgo = 'BGO', Bhd = 'BHD', Bif = 'BIF', Bmd = 'BMD', Bnd = 'BND', Bob = 'BOB', Bol = 'BOL', Bop = 'BOP', Bov = 'BOV', Brb = 'BRB', Brc = 'BRC', Bre = 'BRE', Brl = 'BRL', Brn = 'BRN', Brr = 'BRR', Brz = 'BRZ', Bsd = 'BSD', Btn = 'BTN', Buk = 'BUK', Bwp = 'BWP', Byb = 'BYB', Byn = 'BYN', Byr = 'BYR', Bzd = 'BZD', Cad = 'CAD', Cdf = 'CDF', Che = 'CHE', Chf = 'CHF', Chw = 'CHW', Cle = 'CLE', Clf = 'CLF', Clp = 'CLP', Cnx = 'CNX', Cny = 'CNY', Cop = 'COP', Cou = 'COU', Crc = 'CRC', Csd = 'CSD', Csk = 'CSK', Cuc = 'CUC', Cup = 'CUP', Cve = 'CVE', Cyp = 'CYP', Czk = 'CZK', Ddm = 'DDM', Dem = 'DEM', Djf = 'DJF', Dkk = 'DKK', Dop = 'DOP', Dzd = 'DZD', Ecs = 'ECS', Ecv = 'ECV', Eek = 'EEK', Egp = 'EGP', Ern = 'ERN', Esa = 'ESA', Esb = 'ESB', Esp = 'ESP', Etb = 'ETB', Eur = 'EUR', Fim = 'FIM', Fjd = 'FJD', Fkp = 'FKP', Frf = 'FRF', Gbp = 'GBP', Gek = 'GEK', Gel = 'GEL', Ghc = 'GHC', Ghs = 'GHS', Gip = 'GIP', Gmd = 'GMD', Gnf = 'GNF', Gns = 'GNS', Gqe = 'GQE', Grd = 'GRD', Gtq = 'GTQ', Gwe = 'GWE', Gwp = 'GWP', Gyd = 'GYD', Hkd = 'HKD', Hnl = 'HNL', Hrd = 'HRD', Hrk = 'HRK', Htg = 'HTG', Huf = 'HUF', Idr = 'IDR', Iep = 'IEP', Ilp = 'ILP', Ilr = 'ILR', Ils = 'ILS', Inr = 'INR', Iqd = 'IQD', Isj = 'ISJ', Irr = 'IRR', Isk = 'ISK', Itl = 'ITL', Jmd = 'JMD', Jod = 'JOD', Jpy = 'JPY', Kes = 'KES', Kgs = 'KGS', Khr = 'KHR', Kmf = 'KMF', Kpw = 'KPW', Krh = 'KRH', Kro = 'KRO', Krw = 'KRW', Kwd = 'KWD', Kyd = 'KYD', Kzt = 'KZT', Lak = 'LAK', Lbp = 'LBP', Lkr = 'LKR', Lrd = 'LRD', Lsl = 'LSL', Ltl = 'LTL', Ltt = 'LTT', Luc = 'LUC', Luf = 'LUF', Lul = 'LUL', Lvl = 'LVL', Lvr = 'LVR', Lyd = 'LYD', Mad = 'MAD', Maf = 'MAF', Mcf = 'MCF', Mdc = 'MDC', Mdl = 'MDL', Mga = 'MGA', Mgf = 'MGF', Mkd = 'MKD', Mkn = 'MKN', Mlf = 'MLF', Mmk = 'MMK', Mnt = 'MNT', Mop = 'MOP', Mro = 'MRO', Mtl = 'MTL', Mtp = 'MTP', Mur = 'MUR', Mvp = 'MVP', Mvr = 'MVR', Mwk = 'MWK', Mxn = 'MXN', Mxp = 'MXP', Mxv = 'MXV', Myr = 'MYR', Mze = 'MZE', Mzm = 'MZM', Mzn = 'MZN', Nad = 'NAD', Ngn = 'NGN', Nic = 'NIC', Nio = 'NIO', Nlg = 'NLG', Nok = 'NOK', Npr = 'NPR', Nzd = 'NZD', Omr = 'OMR', Pab = 'PAB', Pei = 'PEI', Pen = 'PEN', Pes = 'PES', Pgk = 'PGK', Php = 'PHP', Pkr = 'PKR', Pln = 'PLN', Plz = 'PLZ', Pte = 'PTE', Pyg = 'PYG', Qar = 'QAR', Rhd = 'RHD', Rol = 'ROL', Ron = 'RON', Rsd = 'RSD', Rub = 'RUB', Rur = 'RUR', Rwf = 'RWF', Sar = 'SAR', Sbd = 'SBD', Scr = 'SCR', Sdd = 'SDD', Sdg = 'SDG', Sdp = 'SDP', Sek = 'SEK', Sgd = 'SGD', Shp = 'SHP', Sit = 'SIT', Skk = 'SKK', Sll = 'SLL', Sos = 'SOS', Srd = 'SRD', Srg = 'SRG', Ssp = 'SSP', Std = 'STD', Sur = 'SUR', Svc = 'SVC', Syp = 'SYP', Szl = 'SZL', Thb = 'THB', Tjr = 'TJR', Tjs = 'TJS', Tmm = 'TMM', Tmt = 'TMT', Tnd = 'TND', Top = 'TOP', Tpe = 'TPE', Trl = 'TRL', Try = 'TRY', Ttd = 'TTD', Twd = 'TWD', Tzs = 'TZS', Uah = 'UAH', Uak = 'UAK', Ugs = 'UGS', Ugx = 'UGX', Usd = 'USD', Usn = 'USN', Uss = 'USS', Uyi = 'UYI', Uyp = 'UYP', Uyu = 'UYU', Uzs = 'UZS', Veb = 'VEB', Vef = 'VEF', Vnd = 'VND', Vnn = 'VNN', Vuv = 'VUV', Wst = 'WST', Xaf = 'XAF', Xcd = 'XCD', Xeu = 'XEU', Xfo = 'XFO', Xfu = 'XFU', Xof = 'XOF', Xpf = 'XPF', Xre = 'XRE', Ydd = 'YDD', Yer = 'YER', Yud = 'YUD', Yum = 'YUM', Yun = 'YUN', Yur = 'YUR', Zal = 'ZAL', Zar = 'ZAR', Zmk = 'ZMK', Zmw = 'ZMW', Zrn = 'ZRN', Zrz = 'ZRZ', Zwd = 'ZWD', Zwl = 'ZWL', Zwr = 'ZWR', } export type GetLoggedInCustomerQueryVariables = Exact<{ [key: string]: never }> export type GetLoggedInCustomerQuery = { __typename?: 'Query' } & { customer?: Maybe< { __typename?: 'Customer' } & Pick< Customer, | 'entityId' | 'firstName' | 'lastName' | 'email' | 'company' | 'customerGroupId' | 'notes' | 'phone' | 'addressCount' | 'attributeCount' > & { storeCredit: Array< { __typename?: 'Money' } & Pick<Money, 'value' | 'currencyCode'> > } > } export type CategoryTreeItemFragment = { __typename?: 'CategoryTreeItem' } & Pick< CategoryTreeItem, 'entityId' | 'name' | 'path' | 'description' | 'productCount' > & { image?: Maybe< { __typename?: 'Image' } & Pick< Image, 'urlOriginal' | 'altText' | 'isDefault' > > } export type ProductPricesFragment = { __typename?: 'Prices' } & { price: { __typename?: 'Money' } & Pick<Money, 'value' | 'currencyCode'> salePrice?: Maybe< { __typename?: 'Money' } & Pick<Money, 'value' | 'currencyCode'> > retailPrice?: Maybe< { __typename?: 'Money' } & Pick<Money, 'value' | 'currencyCode'> > basePrice?: Maybe< { __typename?: 'Money' } & Pick<Money, 'value' | 'currencyCode'> > } export type SwatchOptionFragment = { __typename?: 'SwatchOptionValue' } & Pick< SwatchOptionValue, 'isDefault' | 'hexColors' > export type ProductPickListOptionFragment = { __typename?: 'ProductPickListOptionValue' } & Pick<ProductPickListOptionValue, 'productId'> export type MultipleChoiceOptionFragment = { __typename?: 'MultipleChoiceOption' } & { values: { __typename?: 'ProductOptionValueConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'ProductOptionValueEdge' } & { node: | ({ __typename?: 'MultipleChoiceOptionValue' } & Pick< MultipleChoiceOptionValue, 'entityId' | 'label' | 'isDefault' >) | ({ __typename?: 'ProductPickListOptionValue' } & Pick< ProductPickListOptionValue, 'entityId' | 'label' | 'isDefault' > & ProductPickListOptionFragment) | ({ __typename?: 'SwatchOptionValue' } & Pick< SwatchOptionValue, 'entityId' | 'label' | 'isDefault' > & SwatchOptionFragment) } > > > } } export type CheckboxOptionFragment = { __typename?: 'CheckboxOption' } & Pick< CheckboxOption, 'checkedByDefault' > export type ProductInfoFragment = { __typename?: 'Product' } & Pick< Product, 'entityId' | 'name' | 'path' | 'description' > & { brand?: Maybe<{ __typename?: 'Brand' } & Pick<Brand, 'entityId' | 'name'>> prices?: Maybe<{ __typename?: 'Prices' } & ProductPricesFragment> images: { __typename?: 'ImageConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'ImageEdge' } & { node: { __typename?: 'Image' } & Pick< Image, 'urlOriginal' | 'altText' | 'isDefault' > } > > > } reviewSummary: { __typename?: 'Reviews' } & Pick< Reviews, 'numberOfReviews' | 'summationOfRatings' > variants: { __typename?: 'VariantConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'VariantEdge' } & { node: { __typename?: 'Variant' } & Pick<Variant, 'entityId'> & { defaultImage?: Maybe< { __typename?: 'Image' } & Pick< Image, 'urlOriginal' | 'altText' | 'isDefault' > > } } > > > } productOptions: { __typename?: 'ProductOptionConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'ProductOptionEdge' } & { node: | ({ __typename: 'CheckboxOption' } & Pick< CheckboxOption, 'entityId' | 'displayName' > & CheckboxOptionFragment) | ({ __typename: 'DateFieldOption' } & Pick< DateFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'FileUploadFieldOption' } & Pick< FileUploadFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'MultiLineTextFieldOption' } & Pick< MultiLineTextFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'MultipleChoiceOption' } & Pick< MultipleChoiceOption, 'entityId' | 'displayName' > & MultipleChoiceOptionFragment) | ({ __typename: 'NumberFieldOption' } & Pick< NumberFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'TextFieldOption' } & Pick< TextFieldOption, 'entityId' | 'displayName' >) } > > > } localeMeta: { __typename?: 'MetafieldConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'MetafieldEdge' } & { node: { __typename?: 'Metafields' } & Pick< Metafields, 'key' | 'value' > } > > > } } export type ProductConnnectionFragment = { __typename?: 'ProductConnection' } & { pageInfo: { __typename?: 'PageInfo' } & Pick< PageInfo, 'startCursor' | 'endCursor' > edges?: Maybe< Array< Maybe< { __typename?: 'ProductEdge' } & Pick<ProductEdge, 'cursor'> & { node: { __typename?: 'Product' } & ProductInfoFragment } > > > } export type GetAllProductPathsQueryVariables = Exact<{ first?: Maybe<Scalars['Int']> }> export type GetAllProductPathsQuery = { __typename?: 'Query' } & { site: { __typename?: 'Site' } & { products: { __typename?: 'ProductConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'ProductEdge' } & { node: { __typename?: 'Product' } & Pick<Product, 'path'> } > > > } } } export type GetAllProductsQueryVariables = Exact<{ hasLocale?: Maybe<Scalars['Boolean']> locale?: Maybe<Scalars['String']> entityIds?: Maybe<Array<Scalars['Int']>> first?: Maybe<Scalars['Int']> products?: Maybe<Scalars['Boolean']> featuredProducts?: Maybe<Scalars['Boolean']> bestSellingProducts?: Maybe<Scalars['Boolean']> newestProducts?: Maybe<Scalars['Boolean']> }> export type GetAllProductsQuery = { __typename?: 'Query' } & { site: { __typename?: 'Site' } & { products: { __typename?: 'ProductConnection' } & ProductConnnectionFragment featuredProducts: { __typename?: 'ProductConnection' } & ProductConnnectionFragment bestSellingProducts: { __typename?: 'ProductConnection' } & ProductConnnectionFragment newestProducts: { __typename?: 'ProductConnection' } & ProductConnnectionFragment } } export type GetCustomerIdQueryVariables = Exact<{ [key: string]: never }> export type GetCustomerIdQuery = { __typename?: 'Query' } & { customer?: Maybe<{ __typename?: 'Customer' } & Pick<Customer, 'entityId'>> } export type GetProductQueryVariables = Exact<{ hasLocale?: Maybe<Scalars['Boolean']> locale?: Maybe<Scalars['String']> path: Scalars['String'] }> export type GetProductQuery = { __typename?: 'Query' } & { site: { __typename?: 'Site' } & { route: { __typename?: 'Route' } & { node?: Maybe< | { __typename: 'Brand' } | { __typename: 'Category' } | ({ __typename: 'Product' } & { variants: { __typename?: 'VariantConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'VariantEdge' } & { node: { __typename?: 'Variant' } & Pick< Variant, 'entityId' > & { defaultImage?: Maybe< { __typename?: 'Image' } & Pick< Image, 'urlOriginal' | 'altText' | 'isDefault' > > prices?: Maybe< { __typename?: 'Prices' } & ProductPricesFragment > inventory?: Maybe< { __typename?: 'VariantInventory' } & Pick< VariantInventory, 'isInStock' > & { aggregated?: Maybe< { __typename?: 'Aggregated' } & Pick< Aggregated, 'availableToSell' | 'warningLevel' > > } > productOptions: { __typename?: 'ProductOptionConnection' } & { edges?: Maybe< Array< Maybe< { __typename?: 'ProductOptionEdge' } & { node: | ({ __typename: 'CheckboxOption' } & Pick< CheckboxOption, 'entityId' | 'displayName' >) | ({ __typename: 'DateFieldOption' } & Pick< DateFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'FileUploadFieldOption' } & Pick< FileUploadFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'MultiLineTextFieldOption' } & Pick< MultiLineTextFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'MultipleChoiceOption' } & Pick< MultipleChoiceOption, 'entityId' | 'displayName' > & MultipleChoiceOptionFragment) | ({ __typename: 'NumberFieldOption' } & Pick< NumberFieldOption, 'entityId' | 'displayName' >) | ({ __typename: 'TextFieldOption' } & Pick< TextFieldOption, 'entityId' | 'displayName' >) } > > > } } } > > > } } & ProductInfoFragment) | { __typename: 'Variant' } > } } } export type GetSiteInfoQueryVariables = Exact<{ [key: string]: never }> export type GetSiteInfoQuery = { __typename?: 'Query' } & { site: { __typename?: 'Site' } & { categoryTree: Array< { __typename?: 'CategoryTreeItem' } & { children: Array< { __typename?: 'CategoryTreeItem' } & { children: Array< { __typename?: 'CategoryTreeItem' } & CategoryTreeItemFragment > } & CategoryTreeItemFragment > } & CategoryTreeItemFragment > brands: { __typename?: 'BrandConnection' } & { pageInfo: { __typename?: 'PageInfo' } & Pick< PageInfo, 'startCursor' | 'endCursor' > edges?: Maybe< Array< Maybe< { __typename?: 'BrandEdge' } & Pick<BrandEdge, 'cursor'> & { node: { __typename?: 'Brand' } & Pick< Brand, | 'entityId' | 'name' | 'pageTitle' | 'metaDesc' | 'metaKeywords' | 'searchKeywords' | 'path' > & { defaultImage?: Maybe< { __typename?: 'Image' } & Pick< Image, 'urlOriginal' | 'altText' > > } } > > > } } } export type LoginMutationVariables = Exact<{ email: Scalars['String'] password: Scalars['String'] }> export type LoginMutation = { __typename?: 'Mutation' } & { login: { __typename?: 'LoginResult' } & Pick<LoginResult, 'result'> }
the_stack
import * as vscode from 'vscode'; import fs = require('fs'); import path = require('path'); import Consts from './Consts'; import OrchestrationStepsRenumber from './OrchestrationStepsRenumber'; export default class PolicBuild { static Build() { var rootPath: string; // Check if a folder is opened if ((!vscode.workspace.workspaceFolders) || (vscode.workspace.workspaceFolders.length == 0)) { vscode.window.showWarningMessage("To build a policy you need to open the policy folder in VS code"); return; } rootPath = vscode.workspace.workspaceFolders[0].uri.fsPath; var filePath = path.join(rootPath, "appsettings.json"); // Check if appsettings.json is existed under for root folder vscode.workspace.findFiles(new vscode.RelativePattern(vscode.workspace.rootPath as string, 'appsettings.json')) .then((uris) => { if (!uris || uris.length == 0) { vscode.window.showQuickPick(["Yes", "No"], { placeHolder: 'The appsettings.json file is missing, do you want to create?' }) .then(result => { if (!result || result === "No") return; // Create app settings file with default values fs.writeFile(filePath, Consts.DefaultDeploymentSettings, 'utf8', (err) => { if (err) throw err; vscode.workspace.openTextDocument(filePath).then(doc => { vscode.window.showTextDocument(doc); }); }); }); } else { var appSettings = JSON.parse(fs.readFileSync(filePath, 'utf8')); // Read all policy files from the root directory var environmentFolder; if (appSettings.EnvironmentsFolder == null) { environmentFolder = "Environments"; } else { environmentFolder = appSettings.EnvironmentsFolder; } vscode.workspace.findFiles(new vscode.RelativePattern(vscode.workspace.rootPath as string, '**/*.{xml}'), `**/${environmentFolder}/**`) .then((uris) => { let policyFiles: PolicyFile[] = []; uris.forEach((uri) => { if (uri.fsPath.indexOf("?") <= 0) { var data = fs.readFileSync(uri.fsPath, 'utf8'); policyFiles.push(new PolicyFile(uri.fsPath, data.toString())); } }); return policyFiles; }).then((policyFiles) => { // Automatically renumber orchestration steps if they are out of order let config = vscode.workspace.getConfiguration('aadb2c'); if (config.autoRenumber) { OrchestrationStepsRenumber.RenumberPolicies(policyFiles); } // Get the app settings vscode.workspace.openTextDocument(filePath).then(doc => { var appSettings = JSON.parse(doc.getText()); var environmentsRootPath = path.join(rootPath, environmentFolder); // Ensure environments folder exists if (!fs.existsSync(environmentsRootPath)) { fs.mkdirSync(environmentsRootPath); } // Iterate through environments appSettings.Environments.forEach(function (entry) { if (entry.PolicySettings == null) { vscode.window.showErrorMessage("Can't generate '" + entry.Name + "' environment policies. Error: Accepted PolicySettings element is missing. You may use old version of the appSettings.json file. For more information, see [App Settings](https://github.com/yoelhor/aad-b2c-vs-code-extension/blob/master/README.md#app-settings)"); } else { var environmentRootPath = path.join(environmentsRootPath, entry.Name); // Ensure environment folder exists if (!fs.existsSync(environmentRootPath)) { fs.mkdirSync(environmentRootPath); } // Iterate through the list of settings policyFiles.forEach(function (file) { var policContent = file.Data; // Replace the tenant name policContent = policContent.replace(new RegExp("\{Settings:Tenant\}", "gi"), entry.Tenant); // Replace the file name policContent = policContent.replace(new RegExp("\{Settings:Filename\}", "gi"), file.FileName.replace(/\.[^/.]+$/, "")); // Replace the file name and remove the policy prefix policContent = policContent.replace(new RegExp("\{Settings:PolicyFilename\}", "gi"), file.FileName.replace(/\.[^/.]+$/, "").replace(new RegExp("B2C_1A_", "g"), ""), ); // Replace the environment name policContent = policContent.replace(new RegExp("\{Settings:Environment\}", "gi"), entry.Name ); // Replace the rest of the policy settings Object.keys(entry.PolicySettings).forEach(key => { policContent = policContent.replace(new RegExp("\{Settings:" + key + "\}", "gi"), entry.PolicySettings[key]); }); // Check to see if the policy's subdirectory exists. if (file.SubFolder) { var policyFolderPath = path.join(environmentRootPath, file.SubFolder); if (!fs.existsSync(policyFolderPath)) { fs.mkdirSync(policyFolderPath, { recursive: true }); } } var filePath: string; // Save the policy if (file.SubFolder) { filePath = path.join(policyFolderPath, file.FileName); } else { filePath = path.join(environmentRootPath, file.FileName); } fs.writeFile(filePath, policContent, 'utf8', (err) => { if (err) throw err; }); }); vscode.window.showInformationMessage("Your policies successfully exported and stored under the Environment folder."); } }); }); }); } }); }; static GetAllSettings(): string[] { var items: string[] = []; var rootPath: string; // Check if a folder is opened if ((!vscode.workspace.workspaceFolders) || (vscode.workspace.workspaceFolders.length == 0)) { return items; } // Get the app settings file path rootPath = vscode.workspace.workspaceFolders[0].uri.fsPath; var filePath = path.join(rootPath, "appsettings.json"); // Check if file exists if (fs.existsSync(filePath)) { var fileContent = fs.readFileSync(filePath, "utf8"); var appSettings = JSON.parse(fileContent); // Add static settings items.push('{Settings:Tenant}'); items.push('{Settings:Filename}'); items.push('{Settings:PolicyFilename}'); items.push('{Settings:Environment}'); // Add the items from each environment appSettings.Environments.forEach(function (entry) { // Replace the rest of the policy settings Object.keys(entry.PolicySettings).forEach(key => { if (items.indexOf('{Settings:' + key + '}') == (-1)) { items.push('{Settings:' + key + '}'); } }); }); } return items; } } export class PolicyFile { public FileName: string; public Data: string; public SubFolder: string; constructor(fileName: string, data: string) { this.Data = data; this.FileName = path.basename(fileName); this.SubFolder = this.GetSubFolder(fileName); } GetSubFolder(filePath: string): string { var relativePath = vscode.workspace.asRelativePath(filePath, false); var subFolder = relativePath.substring(0, relativePath.lastIndexOf('/')); if (!subFolder) { return null; } return subFolder; } }
the_stack
import {List as ImmutableList, Map as ImmutableMap, OrderedMap as ImmutableOMap} from "immutable"; import {ElementType, ReactElement, Factory} from "react"; //////////////// // common ///////////////// type AnyObject = object; type Empty = null | undefined; type IdPath = Array<string> | ImmutableList<string>; type Optional<T> = { [P in keyof T]?: T[P]; } type TypedMap<T> = { [key: string]: T; } // You can not use a union for types on a key, but can define overloaded accessors of different types. // Key can be a string OR number type TypedKeyMap<K extends string|number, T> = { [key: string]: T; [key: number]: T; } // for export/import type MongoValue = any; type ElasticSearchQueryType = string; type JsonLogicResult = { logic?: JsonLogicTree, data?: Object, errors?: Array<string> } type JsonLogicTree = Object; type JsonLogicValue = any; type JsonLogicField = { "var": string }; //////////////// // query value ///////////////// type RuleValue = boolean | number | string | Date | Array<string> | any; type ValueSource = "value" | "field" | "func" | "const"; type RuleGroupMode = "struct" | "some" | "array"; type ItemType = "group" | "rule_group" | "rule"; type ItemProperties = RuleProperties | RuleGroupExtProperties | RuleGroupProperties | GroupProperties; type TypedValueSourceMap<T> = { [key in ValueSource]: T; } interface RuleProperties { field: string | Empty, operator: string | Empty, value: Array<RuleValue>, valueSrc?: Array<ValueSource>, valueType?: Array<string>, valueError?: Array<string>, operatorOptions?: AnyObject } interface RuleGroupExtProperties extends RuleProperties { mode: RuleGroupMode, } interface RuleGroupProperties { field: string | Empty, mode?: RuleGroupMode, } interface GroupProperties { conjunction: string, not?: boolean, } type JsonAnyRule = JsonRule|JsonRuleGroup|JsonRuleGroupExt; type JsonItem = JsonGroup|JsonAnyRule; type JsonGroup = { type: "group", id?: string, // tip: if got array, it will be converted to immutable ordered map in `_addChildren1` children1?: {[id: string]: JsonItem} | [JsonItem], properties?: GroupProperties } type JsonRuleGroup = { type: "rule_group", id?: string, children1?: {[id: string]: JsonRule} | [JsonRule], properties?: RuleGroupProperties } type JsonRuleGroupExt = { type: "rule_group", id?: string, children1?: {[id: string]: JsonRule} | [JsonRule], properties?: RuleGroupExtProperties } type JsonRule = { type: "rule", properties: RuleProperties, } export type JsonTree = JsonGroup; export type ImmutableTree = ImmutableOMap<string, any>; //////////////// // Query, Builder, Utils, Config ///////////////// export interface Utils { // export jsonLogicFormat(tree: ImmutableTree, config: Config): JsonLogicResult; queryBuilderFormat(tree: ImmutableTree, config: Config): Object | undefined; queryString(tree: ImmutableTree, config: Config, isForDisplay?: boolean): string | undefined; sqlFormat(tree: ImmutableTree, config: Config): string | undefined; mongodbFormat(tree: ImmutableTree, config: Config): Object | undefined; elasticSearchFormat(tree: ImmutableTree, config: Config): Object | undefined; // load, save getTree(tree: ImmutableTree, light?: boolean): JsonTree; loadTree(jsonTree: JsonTree): ImmutableTree; checkTree(tree: ImmutableTree, config: Config): ImmutableTree; isValidTree(tree: ImmutableTree): boolean; // import loadFromJsonLogic(logicTree: JsonLogicTree | undefined, config: Config): ImmutableTree; isJsonLogic(value: any): boolean; // other uuid(): string; simulateAsyncFetch(all: AsyncFetchListValues, pageSize?: number, delay?: number): AsyncFetchListValuesFn; // config utils ConfigUtils: { getFieldConfig(config: Config, field: string): Field | null; getFuncConfig(config: Config, func: string): Func | null; getFuncArgConfig(config: Config, func: string, arg: string): FuncArg | null; getOperatorConfig(config: Config, operator: string, field?: string): Operator | null; getFieldWidgetConfig(config: Config, field: string, operator: string, widget?: string, valueStr?: ValueSource): Widget | null; } } export interface BuilderProps { tree: ImmutableTree, config: Config, actions: Actions, dispatch: Dispatch, } export interface QueryProps { conjunctions: Conjunctions; operators: Operators; widgets: Widgets; types: Types; settings: Settings; fields: Fields; funcs?: Funcs; value: ImmutableTree; onChange(immutableTree: ImmutableTree, config: Config, actionMeta?: ActionMeta): void; renderBuilder(props: BuilderProps): ReactElement; } export type Builder = ElementType<BuilderProps>; export type Query = ElementType<QueryProps>; export interface Config { conjunctions: Conjunctions, operators: Operators, widgets: Widgets, types: Types, settings: Settings, fields: Fields, funcs?: Funcs, } ///////////////// // Actions ///////////////// type Placement = "after" | "before" | "append" | "prepend"; type ActionType = string | "ADD_RULE" | "REMOVE_RULE" | "ADD_GROUP" | "REMOVE_GROUP" | "SET_NOT" | "SET_CONJUNCTION" | "SET_FIELD" | "SET_OPERATOR" | "SET_VALUE" | "SET_VALUE_SRC" | "SET_OPERATOR_OPTION" | "MOVE_ITEM"; interface BaseAction { type: ActionType, id?: string, // for ADD_RULE, ADD_GROUP - id of new item path?: IdPath, // for all except MOVE_ITEM (for ADD_RULE/ADD_GROUP it's parent path) conjunction?: string, not?: boolean, field?: string, operator?: string, delta?: number, // for SET_VALUE value?: RuleValue, valueType?: string, srcKey?: ValueSource, name?: string, // for SET_OPERATOR_OPTION fromPath?: IdPath, // for MOVE_ITEM toPath?: IdPath, // for MOVE_ITEM placement?: Placement, // for MOVE_ITEM properties?: TypedMap<any>, // for ADD_RULE, ADD_GROUP } export interface InputAction extends BaseAction { config: Config, } export interface ActionMeta extends BaseAction { affectedField?: string, // gets field name from `path` (or `field` for first SET_FIELD) } export type Dispatch = (action: InputAction) => void; export interface Actions { // tip: children will be converted to immutable ordered map in `_addChildren1` addRule(path: IdPath, properties?: ItemProperties, type?: ItemType, children?: Array<JsonAnyRule>): undefined; removeRule(path: IdPath): undefined; addGroup(path: IdPath, properties?: ItemProperties, children?: Array<JsonItem>): undefined; removeGroup(path: IdPath): undefined; setNot(path: IdPath, not: boolean): undefined; setConjunction(path: IdPath, conjunction: string): undefined; setField(path: IdPath, field: string): undefined; setOperator(path: IdPath, operator: string): undefined; setValue(path: IdPath, delta: number, value: RuleValue, valueType: string): undefined; setValueSrc(path: IdPath, delta: number, valueSrc: ValueSource): undefined; setOperatorOption(path: IdPath, name: string, value: RuleValue): undefined; moveItem(fromPath: IdPath, toPath: IdPath, placement: Placement): undefined; setTree(tree: ImmutableTree): undefined; } ///////////////// // Widgets, WidgetProps ///////////////// type FormatValue = (val: RuleValue, fieldDef: Field, wgtDef: Widget, isForDisplay: boolean, op: string, opDef: Operator, rightFieldDef?: Field) => string; type SqlFormatValue = (val: RuleValue, fieldDef: Field, wgtDef: Widget, op: string, opDef: Operator, rightFieldDef?: Field) => string; type MongoFormatValue = (val: RuleValue, fieldDef: Field, wgtDef: Widget, op: string, opDef: Operator) => MongoValue; type ValidateValue = (val: RuleValue, fieldSettings: FieldSettings) => boolean | string | null; type ElasticSearchFormatValue = (queryType: ElasticSearchQueryType, val: RuleValue, op: string, field: string, config: Config) => AnyObject | null; interface BaseWidgetProps { value: RuleValue, setValue(val: RuleValue, asyncListValues?: Array<any>): void, placeholder: string, field: string, parentField?: string, operator: string, fieldDefinition: Field, config: Config, delta?: number, customProps?: AnyObject, readonly?: boolean, id?: string, // id of rule groupId?: string, // id of parent group } interface RangeWidgetProps extends BaseWidgetProps { placeholders: Array<string>, textSeparators: Array<string>, } export type WidgetProps = (BaseWidgetProps | RangeWidgetProps) & FieldSettings; export type TextWidgetProps = BaseWidgetProps & TextFieldSettings; export type DateTimeWidgetProps = BaseWidgetProps & DateTimeFieldSettings; export type BooleanWidgetProps = BaseWidgetProps & BooleanFieldSettings; export type NumberWidgetProps = BaseWidgetProps & NumberFieldSettings; export type SelectWidgetProps = BaseWidgetProps & SelectFieldSettings; export type TreeSelectWidgetProps = BaseWidgetProps & TreeSelectFieldSettings; export type RangeSliderWidgetProps = RangeWidgetProps & NumberFieldSettings; export interface BaseWidget { customProps?: AnyObject, type: string, jsType?: string, factory: Factory<WidgetProps>, valueSrc?: ValueSource, valuePlaceholder?: string, valueLabel?: string, fullWidth?: boolean, formatValue: FormatValue, sqlFormatValue: SqlFormatValue, mongoFormatValue?: MongoFormatValue, elasticSearchFormatValue?: ElasticSearchFormatValue, hideOperator?: boolean, //obsolete: validateValue?: ValidateValue, } export interface RangeableWidget extends BaseWidget { singleWidget?: string, valueLabels?: Array<string | {label: string, placeholder: string}>, } export interface FieldWidget { customProps?: AnyObject, valueSrc: "field", valuePlaceholder?: string, valueLabel?: string, formatValue: FormatValue, // with rightFieldDef sqlFormatValue: SqlFormatValue, // with rightFieldDef //obsolete: validateValue?: ValidateValue, } export type TextWidget = BaseWidget & TextFieldSettings; export type DateTimeWidget = RangeableWidget & DateTimeFieldSettings; export type BooleanWidget = BaseWidget & BooleanFieldSettings; export type NumberWidget = RangeableWidget & NumberFieldSettings; export type SelectWidget = BaseWidget & SelectFieldSettings; export type TreeSelectWidget = BaseWidget & TreeSelectFieldSettings; export type Widget = FieldWidget | TextWidget | DateTimeWidget | BooleanWidget | NumberWidget | SelectWidget | TreeSelectWidget | RangeableWidget | BaseWidget; export type Widgets = TypedMap<Widget>; ///////////////// // Conjunctions ///////////////// type FormatConj = (children: ImmutableList<string>, conj: string, not: boolean, isForDisplay?: boolean) => string; type SqlFormatConj = (children: ImmutableList<string>, conj: string, not: boolean) => string; export interface Conjunction { label: string, formatConj: FormatConj, sqlFormatConj: SqlFormatConj, mongoConj: string, reversedConj?: string, } export type Conjunctions = TypedMap<Conjunction>; export interface ConjunctionOption { id: string, key: string, label: string, checked: boolean, } export interface ConjsProps { id: string, readonly?: boolean, disabled?: boolean, selectedConjunction?: string, setConjunction(conj: string): void, conjunctionOptions?: TypedMap<ConjunctionOption>, config?: Config, not: boolean, setNot(not: boolean): void, showNot?: boolean, notLabel?: string, } ///////////////// // Rule, Group ///////////////// export interface ButtonProps { type: "addRule" | "addGroup" | "delRule" | "delGroup" | "addRuleGroup" | "delRuleGroup", onClick(): void, label: string, config?: Config, } export interface ButtonGroupProps { children: ReactElement, config?: Config, } export interface ProviderProps { children: ReactElement, config?: Config, } export type ValueSourceItem = { label: string, } type ValueSourcesItems = TypedValueSourceMap<ValueSourceItem>; export interface ValueSourcesProps { config?: Config, valueSources: ValueSourcesItems, valueSrc?: ValueSource, setValueSrc(valueSrc: string): void, readonly?: boolean, title: string, } export interface ConfirmModalProps { onOk(): void, okText: string, cancelText?: string, title: string, } export interface RuleErrorProps { error: string, } ///////////////// // Operators ///////////////// type FormatOperator = (field: string, op: string, vals: string | Array<string>, valueSrc?: ValueSource, valueType?: string, opDef?: Operator, operatorOptions?: AnyObject, isForDisplay?: boolean) => string; type MongoFormatOperator = (field: string, op: string, vals: MongoValue | Array<MongoValue>, useExpr?: boolean, valueSrc?: ValueSource, valueType?: string, opDef?: Operator, operatorOptions?: AnyObject) => Object; type SqlFormatOperator = (field: string, op: string, vals: string | Array<string>, valueSrc?: ValueSource, valueType?: string, opDef?: Operator, operatorOptions?: AnyObject) => string; type JsonLogicFormatOperator = (field: JsonLogicField, op: string, vals: JsonLogicValue | Array<JsonLogicValue>, opDef?: Operator, operatorOptions?: AnyObject) => JsonLogicTree; type ElasticSearchFormatQueryType = (valueType: string) => ElasticSearchQueryType; interface ProximityConfig { optionLabel: string, optionTextBefore: string, optionPlaceholder: string, minProximity: number, maxProximity: number, defaults: { proximity: number, }, customProps?: AnyObject, } export interface ProximityProps extends ProximityConfig { options: ImmutableMap<string, any>, setOption: (key: string, value: any) => void, config: Config, } export interface ProximityOptions extends ProximityConfig { factory: Factory<ProximityProps>, } interface BaseOperator { label: string, reversedOp: string, isNotOp?: boolean, cardinality?: number, formatOp?: FormatOperator, labelForFormat?: string, mongoFormatOp?: MongoFormatOperator, sqlOp?: string, sqlFormatOp?: SqlFormatOperator, jsonLogic?: string | JsonLogicFormatOperator, _jsonLogicIsRevArgs?: boolean, elasticSearchQueryType?: ElasticSearchQueryType | ElasticSearchFormatQueryType, valueSources?: Array<ValueSource>, } interface UnaryOperator extends BaseOperator { //cardinality: 0, } interface BinaryOperator extends BaseOperator { //cardinality: 1, } interface Operator2 extends BaseOperator { //cardinality: 2 textSeparators: Array<string>, valueLabels: Array<string | {label: string, placeholder: string}>, isSpecialRange?: boolean, } interface OperatorProximity extends Operator2 { options: ProximityOptions, } export type Operator = UnaryOperator | BinaryOperator | Operator2 | OperatorProximity; export type Operators = TypedMap<Operator>; ///////////////// // Types ///////////////// interface WidgetConfigForType { widgetProps?: Optional<Widget>, opProps?: Optional<Operator>, operators?: Array<string>, } interface Type { valueSources?: Array<ValueSource>, defaultOperator?: string, widgets: TypedMap<WidgetConfigForType>, } export type Types = TypedMap<Type>; ///////////////// // Fields ///////////////// type FieldType = string | "!struct" | "!group"; interface ListItem { value: any, title?: string, } interface TreeItem extends ListItem { children?: Array<TreeItem>, parent?: any, disabled?: boolean, selectable?: boolean, disableCheckbox?: boolean, checkable?: boolean, } type TreeData = Array<TreeItem>; type ListValues = TypedMap<string> | TypedKeyMap<string | number, string> | Array<ListItem> | Array<string | number>; type AsyncFetchListValues = ListValues; interface AsyncFetchListValuesResult { values: AsyncFetchListValues, hasMore?: boolean, } type AsyncFetchListValuesFn = (search: string | null, offset: number) => Promise<AsyncFetchListValuesResult>; export interface BasicFieldSettings { validateValue?: ValidateValue, } export interface TextFieldSettings extends BasicFieldSettings { maxLength?: number, maxRows?: number, } export interface NumberFieldSettings extends BasicFieldSettings { min?: number, max?: number, step?: number, marks?: {[mark: number]: ReactElement | string} } export interface DateTimeFieldSettings extends BasicFieldSettings { timeFormat?: string, dateFormat?: string, valueFormat?: string, use12Hours?: boolean, useKeyboard?: boolean, } export interface SelectFieldSettings extends BasicFieldSettings { listValues?: ListValues, allowCustomValues?: boolean, showSearch?: boolean, showCheckboxes?: boolean, asyncFetch?: AsyncFetchListValuesFn, useLoadMore?: boolean, useAsyncSearch?: boolean, forceAsyncSearch?: boolean, } export interface TreeSelectFieldSettings extends BasicFieldSettings { listValues?: TreeData, treeExpandAll?: boolean, treeSelectOnlyLeafs?: boolean, } export interface BooleanFieldSettings extends BasicFieldSettings { labelYes?: ReactElement | string, labelNo?: ReactElement | string, } export type FieldSettings = NumberFieldSettings | DateTimeFieldSettings | SelectFieldSettings | TreeSelectFieldSettings | BooleanFieldSettings | TextFieldSettings | BasicFieldSettings; interface BaseField { type: FieldType, label?: string, tooltip?: string, } interface ValueField extends BaseField { type: string, preferWidgets?: Array<string>, valueSources?: Array<ValueSource>, funcs?: Array<string>, tableName?: string, // legacy: PR #18, PR #20 fieldName?: string, jsonLogicVar?: string, fieldSettings?: FieldSettings, defaultValue?: RuleValue, widgets?: TypedMap<WidgetConfigForType>, mainWidgetProps?: Optional<Widget>, hideForSelect?: boolean, hideForCompare?: boolean, //obsolete - moved to FieldSettings listValues?: ListValues, allowCustomValues?: boolean, } interface SimpleField extends ValueField { label2?: string, operators?: Array<string>, defaultOperator?: string, excludeOperators?: Array<string>, } interface FieldStruct extends BaseField { type: "!struct", subfields: Fields, } interface FieldGroup extends BaseField { type: "!group", subfields: Fields, mode: RuleGroupMode, } interface FieldGroupExt extends BaseField { type: "!group", subfields: Fields, mode: "array", operators?: Array<string>, defaultOperator?: string, initialEmptyWhere?: boolean, showNot?: boolean, conjunctions?: Array<string>, } export type Field = SimpleField; type FieldOrGroup = FieldStruct | FieldGroup | FieldGroupExt | Field; export type Fields = TypedMap<FieldOrGroup>; ///////////////// // FieldProps ///////////////// export type FieldItem = { items?: FieldItems, key: string, path?: string, // field path with separator label: string, fullLabel?: string, altLabel?: string, tooltip?: string, disabled?: boolean, } type FieldItems = TypedMap<FieldItem>; export interface FieldProps { items: FieldItems, setField(fieldPath: string): void, selectedKey: string | Empty, selectedKeys?: Array<string> | Empty, selectedPath?: Array<string> | Empty, selectedLabel?: string | Empty, selectedAltLabel?: string | Empty, selectedFullLabel?: string | Empty, config?: Config, customProps?: AnyObject, placeholder?: string, selectedOpts?: {tooltip?: string}, readonly?: boolean, id?: string, // id of rule groupId?: string, // id of parent group } ///////////////// // Settings ///////////////// type ValueSourcesInfo = {[vs in ValueSource]?: {label: string, widget?: string}} type AntdPosition = "topLeft" | "topCenter" | "topRight" | "bottomLeft" | "bottomCenter" | "bottomRight"; type AntdSize = "small" | "large" | "medium"; type ChangeFieldStrategy = "default" | "keep" | "first" | "none"; type FormatReverse = (q: string, op: string, reversedOp: string, operatorDefinition: Operator, revOperatorDefinition: Operator, isForDisplay: boolean) => string; type SqlFormatReverse = (q: string, op: string, reversedOp: string, operatorDefinition: Operator, revOperatorDefinition: Operator) => string; type FormatField = (field: string, parts: Array<string>, label2: string, fieldDefinition: Field, config: Config, isForDisplay: boolean) => string; type CanCompareFieldWithField = (leftField: string, leftFieldConfig: Field, rightField: string, rightFieldConfig: Field, op: string) => boolean; type FormatAggr = (whereStr: string, aggrField: string, operator: string, value: string | Array<string>, valueSrc: ValueSource, valueType: string, opDef: Operator, operatorOptions: AnyObject, isForDisplay: boolean, aggrFieldDef: Field) => string; export interface LocaleSettings { locale?: { moment?: string, antd?: Object, material?: Object, }, theme?: { material?: Object, }, valueLabel?: string, valuePlaceholder?: string, fieldLabel?: string, operatorLabel?: string, fieldPlaceholder?: string, funcPlaceholder?: string, funcLabel?: string, operatorPlaceholder?: string, deleteLabel?: string, addGroupLabel?: string, addRuleLabel?: string, addSubRuleLabel?: string, delGroupLabel?: string, notLabel?: string, valueSourcesPopupTitle?: string, removeRuleConfirmOptions?: { title?: string, okText?: string, okType?: string, cancelText?: string, }, removeGroupConfirmOptions?: { title?: string, okText?: string, okType?: string, cancelText?: string, }, } export interface RenderSettings { renderField?: Factory<FieldProps>, renderOperator?: Factory<FieldProps>, renderFunc?: Factory<FieldProps>, renderConjs?: Factory<ConjsProps>, renderButton?: Factory<ButtonProps>, renderButtonGroup?: Factory<ButtonGroupProps>, renderProvider?: Factory<ProviderProps>, renderValueSources?: Factory<ValueSourcesProps>, renderConfirm?: ConfirmFunc, useConfirm?: () => Function, renderSize?: AntdSize, dropdownPlacement?: AntdPosition, groupActionsPosition?: AntdPosition, showLabels?: boolean, maxLabelsLength?: number, customFieldSelectProps?: AnyObject, renderBeforeWidget?: Factory<FieldProps>, renderAfterWidget?: Factory<FieldProps>, renderBeforeActions?: Factory<FieldProps>, renderAfterActions?: Factory<FieldProps>, renderRuleError?: Factory<RuleErrorProps>, defaultSliderWidth?: string, defaultSelectWidth?: string, defaultSearchWidth?: string, defaultMaxRows?: number, } export interface BehaviourSettings { valueSourcesInfo?: ValueSourcesInfo, canCompareFieldWithField?: CanCompareFieldWithField, canReorder?: boolean, canRegroup?: boolean, showNot?: boolean, maxNesting?: number, setOpOnChangeField: Array<ChangeFieldStrategy>, clearValueOnChangeField?: boolean, clearValueOnChangeOp?: boolean, canLeaveEmptyGroup?: boolean, shouldCreateEmptyGroup?: boolean, immutableGroupsMode?: boolean, immutableFieldsMode?: boolean, immutableOpsMode?: boolean, immutableValuesMode?: boolean, maxNumberOfRules?: Number, showErrorMessage?: boolean, canShortMongoQuery?: boolean, convertableWidgets?: TypedMap<Array<string>>, } export interface OtherSettings { fieldSeparator?: string, fieldSeparatorDisplay?: string, formatReverse?: FormatReverse, sqlFormatReverse?: SqlFormatReverse, formatField?: FormatField, formarAggr?: FormatAggr, } export type Settings = LocaleSettings & RenderSettings & BehaviourSettings & OtherSettings; ///////////////// // Funcs ///////////////// type SqlFormatFunc = (formattedArgs: TypedMap<string>) => string; type FormatFunc = (formattedArgs: TypedMap<string>, isForDisplay: boolean) => string; type MongoFormatFunc = (formattedArgs: TypedMap<MongoValue>) => MongoValue; type JsonLogicFormatFunc = (formattedArgs: TypedMap<JsonLogicValue>) => JsonLogicTree; type JsonLogicImportFunc = (val: JsonLogicValue) => Array<RuleValue>; interface FuncGroup { type?: "!struct", label?: string, subfields: TypedMap<Func>, } export interface Func { returnType: string, args: TypedMap<FuncArg>, label?: string, sqlFunc?: string, mongoFunc?: string, mongoArgsAsObject?: boolean, jsonLogic?: string | JsonLogicFormatFunc, // Deprecated! // Calling methods on objects was remvoed in JsonLogic 2.x // https://github.com/jwadhams/json-logic-js/issues/86 jsonLogicIsMethod?: boolean, jsonLogicImport?: JsonLogicImportFunc, formatFunc?: FormatFunc, sqlFormatFunc?: SqlFormatFunc, mongoFormatFunc?: MongoFormatFunc, renderBrackets?: Array<ReactElement | string>, renderSeps?: Array<ReactElement | string>, } export interface FuncArg extends ValueField { isOptional?: boolean, showPrefix?: boolean, } export type Funcs = TypedMap<Func | FuncGroup>; ///////////////// // BasicConfig ///////////////// export interface BasicConfig extends Config { conjunctions: { AND: Conjunction, OR: Conjunction, }, operators: { equal: BinaryOperator, not_equal: BinaryOperator, less: BinaryOperator, less_or_equal: BinaryOperator, greater: BinaryOperator, greater_or_equal: BinaryOperator, like: BinaryOperator, not_like: BinaryOperator, starts_with: BinaryOperator, ends_with: BinaryOperator, between: Operator2, not_between: Operator2, is_empty: UnaryOperator, is_not_empty: UnaryOperator, select_equals: BinaryOperator, select_not_equals: BinaryOperator, select_any_in: BinaryOperator, select_not_any_in: BinaryOperator, multiselect_equals: BinaryOperator, multiselect_not_equals: BinaryOperator, proximity: OperatorProximity, }, widgets: { text: TextWidget, textarea: TextWidget, number: NumberWidget, slider: NumberWidget, rangeslider: NumberWidget, select: SelectWidget, multiselect: SelectWidget, treeselect: TreeSelectWidget, treemultiselect: TreeSelectWidget, date: DateTimeWidget, time: DateTimeWidget, datetime: DateTimeWidget, boolean: BooleanWidget, field: FieldWidget, func: FieldWidget, }, types: { text: Type, number: Type, date: Type, time: Type, datetime: Type, select: Type, multiselect: Type, treeselect: Type, treemultiselect: Type, boolean: Type, }, settings: Settings, } ///////////////// // ReadyWidgets ///////////////// type ConfirmFunc = (opts: ConfirmModalProps) => void; interface VanillaWidgets { // vanilla core widgets VanillaFieldSelect: ElementType<FieldProps>, VanillaConjs: ElementType<ConjsProps>, VanillaButton: ElementType<ButtonProps>, VanillaButtonGroup: ElementType<ButtonGroupProps>, VanillaProvider: ElementType<ProviderProps>, VanillaValueSources: ElementType<ValueSourcesProps>, vanillaConfirm: ConfirmFunc, // vanilla core widgets VanillaBooleanWidget: ElementType<BooleanWidgetProps>, VanillaTextWidget: ElementType<TextWidgetProps>, VanillaTextAreaWidget: ElementType<TextWidgetProps>, VanillaDateWidget: ElementType<DateTimeWidgetProps>, VanillaTimeWidget: ElementType<DateTimeWidgetProps>, VanillaDateTimeWidget: ElementType<DateTimeWidgetProps>, VanillaMultiSelectWidget: ElementType<SelectWidgetProps>, VanillaSelectWidget: ElementType<SelectWidgetProps>, VanillaNumberWidget: ElementType<NumberWidgetProps>, VanillaSliderWidget: ElementType<NumberWidgetProps>, } export interface AntdWidgets { // antd core widgets FieldSelect: ElementType<FieldProps>, FieldDropdown: ElementType<FieldProps>, FieldCascader: ElementType<FieldProps>, FieldTreeSelect: ElementType<FieldProps>, Button: ElementType<ButtonProps>, ButtonGroup: ElementType<ButtonGroupProps>, Conjs: ElementType<ConjsProps>, Provider: ElementType<ProviderProps>, ValueSources: ElementType<ValueSourcesProps>, confirm: ConfirmFunc, // antd value widgets TextWidget: ElementType<TextWidgetProps>, TextAreaWidget: ElementType<TextWidgetProps>, NumberWidget: ElementType<NumberWidgetProps>, SliderWidget: ElementType<NumberWidgetProps>, RangeWidget: ElementType<RangeSliderWidgetProps>, SelectWidget: ElementType<SelectWidgetProps>, MultiSelectWidget: ElementType<SelectWidgetProps>, TreeSelectWidget: ElementType<TreeSelectWidgetProps>, DateWidget: ElementType<DateTimeWidgetProps>, TimeWidget: ElementType<DateTimeWidgetProps>, DateTimeWidget: ElementType<DateTimeWidgetProps>, BooleanWidget: ElementType<BooleanWidgetProps>, } interface ReadyWidgets extends VanillaWidgets { ValueFieldWidget: ElementType<WidgetProps>, FuncWidget: ElementType<WidgetProps>, } export interface MaterialWidgets { // material core widgets MaterialFieldSelect: ElementType<FieldProps>, MaterialConjs: ElementType<ConjsProps>, MaterialButton: ElementType<ButtonProps>, MaterialButtonGroup: ElementType<ButtonGroupProps>, MaterialProvider: ElementType<ProviderProps>, MaterialValueSources: ElementType<ValueSourcesProps>, MaterialConfirm: ConfirmFunc, MaterialUseConfirm: () => Function, // material core widgets MaterialBooleanWidget: ElementType<BooleanWidgetProps>, MaterialTextWidget: ElementType<TextWidgetProps>, MaterialTextAreaWidget: ElementType<TextWidgetProps>, MaterialDateWidget: ElementType<DateTimeWidgetProps>, MaterialTimeWidget: ElementType<DateTimeWidgetProps>, MaterialDateTimeWidget: ElementType<DateTimeWidgetProps>, MaterialMultiSelectWidget: ElementType<SelectWidgetProps>, MaterialSelectWidget: ElementType<SelectWidgetProps>, MaterialNumberWidget: ElementType<NumberWidgetProps>, MaterialSliderWidget: ElementType<NumberWidgetProps>, MaterialRangeWidget: ElementType<RangeSliderWidgetProps>, MaterialAutocompleteWidget: ElementType<SelectWidgetProps>, } ///////////////// export const Utils: Utils; export const Query: Query; export const Builder: Builder; export const BasicConfig: BasicConfig; export const BasicFuncs: Funcs; export const Widgets: ReadyWidgets;
the_stack
import '@graphql-codegen/testing'; import { buildSchema } from 'graphql'; import { plugin } from '../src/index'; import { validateJava } from '../../common/tests/validate-java'; import { mergeOutputs } from '@graphql-codegen/plugin-helpers'; const OUTPUT_FILE = 'com/java/generated/resolvers.java'; describe('Java', () => { const schema = buildSchema(/* GraphQL */ ` scalar DateTime type Query { me: User! user(id: ID!): User! searchUser(searchFields: SearchUser!): [User!]! updateUser(input: UpdateUserMetadataInput!): [User!]! } input InputWithArray { f: [String] g: [SearchUser] } input SearchUser { username: String email: String name: String dateOfBirth: DateTime sort: ResultSort metadata: MetadataSearch } input MetadataSearch { something: Int } input UpdateUserInput { id: ID! username: String metadata: UpdateUserMetadataInput } input UpdateUserMetadataInput { something: Int } input CustomInput { id: ID! } enum ResultSort { ASC DESC } interface Node { id: ID! } type User implements Node { id: ID! username: String! email: String! name: String dateOfBirth: DateTime friends(skip: Int, limit: Int): [User!]! } type Chat implements Node { id: ID! users: [User!]! title: String } enum UserRole { ADMIN USER EDITOR } union SearchResult = Chat | User `); it('Should produce valid Java code', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); validateJava(mergeOutputs([result])); }); describe('Config', () => { it('Should use the correct package name by default', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toContain(`package com.java.generated;`); }); it('Should use the package name provided from the config', async () => { const result = await plugin(schema, [], { package: 'com.my.package' }, { outputFile: OUTPUT_FILE }); expect(result).toContain(`package com.my.package;`); }); }); describe('Enums', () => { it('Should add imports that are relevant to enums', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toContain(`import java.util.HashMap;`); expect(result).toContain(`import java.util.Map;`); }); it('Should generate basic enums correctly', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(` public enum UserRole { ADMIN, USER, EDITOR }`); }); it('Should allow to override enum values with custom values', async () => { const result = await plugin( schema, [], { enumValues: { UserRole: { ADMIN: 'AdminRoleValue', }, }, }, { outputFile: OUTPUT_FILE } ); expect(result).toContain(`AdminRoleValue,`); expect(result).toContain(`USER,`); }); }); describe('Input Types / Arguments useEmptyCtor default false', () => { it('Should generate arguments correctly when using Array', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class InputWithArrayInput { private Iterable<String> f; private Iterable<SearchUserInput> g; public InputWithArrayInput(Map<String, Object> args) { if (args != null) { this.f = (Iterable<String>) args.get("f"); if (args.get("g") != null) { this.g = (Iterable<SearchUserInput>) args.get("g"); } } } public Iterable<String> getF() { return this.f; } public Iterable<SearchUserInput> getG() { return this.g; } public void setF(Iterable<String> f) { this.f = f; } public void setG(Iterable<SearchUserInput> g) { this.g = g; } }`); }); it('Should generate input class per each type with field arguments', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class UserFriendsArgs { private Integer skip; private Integer limit; public UserFriendsArgs(Map<String, Object> args) { if (args != null) { this.skip = (Integer) args.get("skip"); this.limit = (Integer) args.get("limit"); } } public Integer getSkip() { return this.skip; } public Integer getLimit() { return this.limit; } public void setSkip(Integer skip) { this.skip = skip; } public void setLimit(Integer limit) { this.limit = limit; } }`); }); it('Should omit extra Input suffix from input class name if schema name already includes the "Input" suffix', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class CustomInput { private Object id; public CustomInput(Map<String, Object> args) { if (args != null) { this.id = (Object) args.get("id"); } } public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } }`); }); it('Should generate input class per each query with arguments', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class QueryUserArgs { private Object id; public QueryUserArgs(Map<String, Object> args) { if (args != null) { this.id = (Object) args.get("id"); } } public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } }`); expect(result).toBeSimilarStringTo(`public static class QuerySearchUserArgs { private SearchUserInput searchFields; public QuerySearchUserArgs(Map<String, Object> args) { if (args != null) { this.searchFields = new SearchUserInput((Map<String, Object>) args.get("searchFields")); } } public SearchUserInput getSearchFields() { return this.searchFields; } public void setSearchFields(SearchUserInput searchFields) { this.searchFields = searchFields; } }`); }); it('Should generate check type for enum', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`if (args.get("sort") instanceof ResultSort) { this.sort = (ResultSort) args.get("sort"); } else { this.sort = ResultSort.valueOf((String) args.get("sort")); }`); }); it('Should generate input class per each input, also with nested input types', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class MetadataSearchInput { private Integer something; public MetadataSearchInput(Map<String, Object> args) { if (args != null) { this.something = (Integer) args.get("something"); } } public Integer getSomething() { return this.something; } public void setSomething(Integer something) { this.something = something; } }`); expect(result).toBeSimilarStringTo(`public static class SearchUserInput { private String username; private String email; private String name; private Object dateOfBirth; private ResultSort sort; private MetadataSearchInput metadata; public SearchUserInput(Map<String, Object> args) { if (args != null) { this.username = (String) args.get("username"); this.email = (String) args.get("email"); this.name = (String) args.get("name"); this.dateOfBirth = (Object) args.get("dateOfBirth"); if (args.get("sort") instanceof ResultSort) { this.sort = (ResultSort) args.get("sort"); } else { this.sort = ResultSort.valueOf((String) args.get("sort")); } this.metadata = new MetadataSearchInput((Map<String, Object>) args.get("metadata")); } } public String getUsername() { return this.username; } public String getEmail() { return this.email; } public String getName() { return this.name; } public Object getDateOfBirth() { return this.dateOfBirth; } public ResultSort getSort() { return this.sort; } public MetadataSearchInput getMetadata() { return this.metadata; } public void setUsername(String username) { this.username = username; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public void setDateOfBirth(Object dateOfBirth) { this.dateOfBirth = dateOfBirth; } public void setSort(ResultSort sort) { this.sort = sort; } public void setMetadata(MetadataSearchInput metadata) { this.metadata = metadata; } }`); }); it('Should generate nested inputs with out duplicated `Input` suffix', async () => { const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class UpdateUserMetadataInput { private Integer something; public UpdateUserMetadataInput(Map<String, Object> args) { if (args != null) { this.something = (Integer) args.get("something"); } } public Integer getSomething() { return this.something; } public void setSomething(Integer something) { this.something = something; } }`); expect(result).toBeSimilarStringTo(`public static class UpdateUserInput { private Object id; private String username; private UpdateUserMetadataInput metadata; public UpdateUserInput(Map<String, Object> args) { if (args != null) { this.id = (Object) args.get("id"); this.username = (String) args.get("username"); this.metadata = new UpdateUserMetadataInput((Map<String, Object>) args.get("metadata")); } } public Object getId() { return this.id; } public String getUsername() { return this.username; } public UpdateUserMetadataInput getMetadata() { return this.metadata; } public void setId(Object id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setMetadata(UpdateUserMetadataInput metadata) { this.metadata = metadata; } }`); }); }); describe('Input Types / Arguments useEmptyCtor true', () => { it('Should generate arguments correctly when using Array', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class InputWithArrayInput { private Iterable<String> f; private Iterable<SearchUserInput> g; public InputWithArrayInput() {} public Iterable<String> getF() { return this.f; } public Iterable<SearchUserInput> getG() { return this.g; } public void setF(Iterable<String> f) { this.f = f; } public void setG(Iterable<SearchUserInput> g) { this.g = g; } }`); }); it('Should generate input class per each type with field arguments', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class UserFriendsArgs { private Integer skip; private Integer limit; public UserFriendsArgs() {} public Integer getSkip() { return this.skip; } public Integer getLimit() { return this.limit; } public void setSkip(Integer skip) { this.skip = skip; } public void setLimit(Integer limit) { this.limit = limit; } }`); }); it('Should omit extra Input suffix from input class name if schema name already includes the "Input" suffix', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class CustomInput { private Object id; public CustomInput() {} public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } }`); }); it('Should generate input class per each query with arguments', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class QueryUserArgs { private Object id; public QueryUserArgs() {} public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } }`); expect(result).toBeSimilarStringTo(`public static class QuerySearchUserArgs { private SearchUserInput searchFields; public QuerySearchUserArgs() {} public SearchUserInput getSearchFields() { return this.searchFields; } public void setSearchFields(SearchUserInput searchFields) { this.searchFields = searchFields; } }`); }); // it('Should generate check type for enum', async () => { // const result = await plugin(schema, [], {}, { outputFile: OUTPUT_FILE }); // expect(result).toBeSimilarStringTo(`if (args.get("sort") instanceof ResultSort) { // this.sort = (ResultSort) args.get("sort"); // } else { // this.sort = ResultSort.valueOf((String) args.get("sort")); // }`); // }); it('Should generate input class per each input, also with nested input types', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class MetadataSearchInput { private Integer something; public MetadataSearchInput() {} public Integer getSomething() { return this.something; } public void setSomething(Integer something) { this.something = something; } }`); expect(result).toBeSimilarStringTo(`public static class SearchUserInput { private String username; private String email; private String name; private Object dateOfBirth; private ResultSort sort; private MetadataSearchInput metadata; public SearchUserInput() {} public String getUsername() { return this.username; } public String getEmail() { return this.email; } public String getName() { return this.name; } public Object getDateOfBirth() { return this.dateOfBirth; } public ResultSort getSort() { return this.sort; } public MetadataSearchInput getMetadata() { return this.metadata; } public void setUsername(String username) { this.username = username; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public void setDateOfBirth(Object dateOfBirth) { this.dateOfBirth = dateOfBirth; } public void setSort(ResultSort sort) { this.sort = sort; } public void setMetadata(MetadataSearchInput metadata) { this.metadata = metadata; } }`); }); it('Should generate nested inputs with out duplicated `Input` suffix', async () => { const result = await plugin(schema, [], { useEmptyCtor: true }, { outputFile: OUTPUT_FILE }); expect(result).toBeSimilarStringTo(`public static class UpdateUserMetadataInput { private Integer something; public UpdateUserMetadataInput() {} public Integer getSomething() { return this.something; } public void setSomething(Integer something) { this.something = something; } }`); expect(result).toBeSimilarStringTo(`public static class UpdateUserInput { private Object id; private String username; private UpdateUserMetadataInput metadata; public UpdateUserInput() {} public Object getId() { return this.id; } public String getUsername() { return this.username; } public UpdateUserMetadataInput getMetadata() { return this.metadata; } public void setId(Object id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setMetadata(UpdateUserMetadataInput metadata) { this.metadata = metadata; } }`); }); }); });
the_stack
import { expect } from "chai"; import * as faker from "faker"; import sinon from "sinon"; import * as moq from "typemoq"; import { Id64 } from "@itwin/core-bentley"; import { IpcApp } from "@itwin/core-frontend"; import { RulesetVariable, VariableValueTypes } from "@itwin/presentation-common"; import { createRandomId } from "@itwin/presentation-common/lib/cjs/test"; import { IpcRequestsHandler } from "../presentation-frontend/IpcRequestsHandler"; import { RulesetVariablesManagerImpl } from "../presentation-frontend/RulesetVariablesManager"; describe("RulesetVariablesManager", () => { let vars: RulesetVariablesManagerImpl; let variableId: string; beforeEach(() => { variableId = faker.random.word(); vars = new RulesetVariablesManagerImpl("test-ruleset-id"); }); describe("one-backend-one-frontend mode", () => { it("calls ipc handler to set variable value on backend", async () => { sinon.stub(IpcApp, "isValid").get(() => true); const ipcHandlerMock = moq.Mock.ofType<IpcRequestsHandler>(); const rulesetId = "test-ruleset-id"; vars = new RulesetVariablesManagerImpl(rulesetId, ipcHandlerMock.object); const testVariable: RulesetVariable = { id: "test-var-id", type: VariableValueTypes.String, value: "test-value", }; ipcHandlerMock.setup(async (x) => x.setRulesetVariable(moq.It.isObjectWith({ rulesetId, variable: testVariable }))).verifiable(moq.Times.once()); await vars.setString(testVariable.id, testVariable.value); ipcHandlerMock.verifyAll(); }); it("calls ipc handler to unset variable value on backend", async () => { sinon.stub(IpcApp, "isValid").get(() => true); const ipcHandlerMock = moq.Mock.ofType<IpcRequestsHandler>(); const rulesetId = "test-ruleset-id"; vars = new RulesetVariablesManagerImpl(rulesetId, ipcHandlerMock.object); await vars.setString("test-id", "test-value"); ipcHandlerMock.setup(async (x) => x.unsetRulesetVariable(moq.It.isObjectWith({ rulesetId, variableId: "test-id" }))).verifiable(moq.Times.once()); await vars.unset("test-id"); ipcHandlerMock.verifyAll(); }); }); describe("getAllVariables", () => { it("return empty array if there's no variables", async () => { expect(vars.getAllVariables()).to.deep.eq([]); }); it("returns variables", async () => { const variables = [{ id: variableId, type: VariableValueTypes.String, value: faker.random.word() }]; await vars.setString(variables[0].id, variables[0].value); const allVariables = vars.getAllVariables(); expect(allVariables).to.deep.eq(variables); }); }); describe("unset", () => { it("unsets existing value", async () => { await vars.setString(variableId, "a"); expect(vars.getAllVariables()).to.deep.eq([{ id: variableId, type: VariableValueTypes.String, value: "a", }]); await vars.unset(variableId); expect(vars.getAllVariables()).to.deep.eq([]); }); it("doesn't raise onVariableChanged event when value is not set", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.unset(variableId); expect(spy).to.not.be.called; }); }); describe("string", () => { it("returns empty string if there's no value", async () => { expect(await vars.getString(variableId)).to.eq(""); }); it("sets and returns value", async () => { const value = faker.random.word(); await vars.setString(variableId, value); expect(await vars.getString(variableId)).to.eq(value); }); it("raises onVariableChanged event when variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setString(variableId, "a"); expect(spy).to.be.calledWithExactly(variableId, undefined, "a"); spy.resetHistory(); await vars.setString(variableId, "b"); expect(spy).to.be.calledWith(variableId, "a", "b"); spy.resetHistory(); await vars.setString(variableId, "b"); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, "b", undefined); }); }); describe("bool", () => { it("returns `false` if there's no value", async () => { expect(await vars.getBool(variableId)).to.be.false; }); it("sets and returns value", async () => { const value = faker.random.boolean(); await vars.setBool(variableId, value); expect(await vars.getBool(variableId)).to.eq(value); }); it("raises onVariableChanged event when variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setBool(variableId, false); expect(spy).to.be.calledWith(variableId, undefined, false); spy.resetHistory(); await vars.setBool(variableId, true); expect(spy).to.be.calledWith(variableId, false, true); spy.resetHistory(); await vars.setBool(variableId, true); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, true, undefined); }); it("handles type conversion", async () => { await vars.setBool(variableId, false); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInt(variableId)).to.deep.eq(0); expect(await vars.getInts(variableId)).to.deep.eq([]); expect(await vars.getId64(variableId)).to.deep.eq(Id64.invalid); expect(await vars.getId64s(variableId)).to.deep.eq([]); await vars.setBool(variableId, true); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInt(variableId)).to.deep.eq(1); expect(await vars.getInts(variableId)).to.deep.eq([]); expect(await vars.getId64(variableId)).to.deep.eq(Id64.fromLocalAndBriefcaseIds(1, 0)); expect(await vars.getId64s(variableId)).to.deep.eq([]); }); }); describe("int", () => { it("returns `0` if there's no value", async () => { expect(await vars.getInt(variableId)).to.eq(0); }); it("sets and returns value", async () => { const value = faker.random.number(); await vars.setInt(variableId, value); expect(await vars.getInt(variableId)).to.eq(value); }); it("raises onVariableChanged event when variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setInt(variableId, 123); expect(spy).to.be.calledWith(variableId, undefined, 123); spy.resetHistory(); await vars.setInt(variableId, 456); expect(spy).to.be.calledWith(variableId, 123, 456); spy.resetHistory(); await vars.setInt(variableId, 456); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, 456, undefined); }); it("handles type conversion", async () => { const value = faker.random.number(); await vars.setInt(variableId, value); expect(await vars.getBool(variableId)).to.deep.eq(true); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInts(variableId)).to.deep.eq([]); expect(await vars.getId64(variableId)).to.deep.eq(Id64.fromLocalAndBriefcaseIds(value, 0)); expect(await vars.getId64s(variableId)).to.deep.eq([]); }); }); describe("int[]", () => { it("returns empty list if there's no value", async () => { expect(await vars.getInts(variableId)).to.deep.eq([]); }); it("sets and returns value", async () => { const value = [faker.random.number(), faker.random.number()]; await vars.setInts(variableId, value); expect(await vars.getInts(variableId)).to.deep.eq(value); }); it("raises onVariableChanged event when immutable variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setInts(variableId, [1, 2]); expect(spy).to.be.calledWith(variableId, undefined, [1, 2]); spy.resetHistory(); await vars.setInts(variableId, [1, 2, 3]); expect(spy).to.be.calledWith(variableId, [1, 2], [1, 2, 3]); spy.resetHistory(); await vars.setInts(variableId, [4, 5, 6]); expect(spy).to.be.calledWith(variableId, [1, 2, 3], [4, 5, 6]); spy.resetHistory(); await vars.setInts(variableId, [4, 5, 6]); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, [4, 5, 6], undefined); }); it("raises onVariableChanged event when mutable variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); const value = [1, 2]; await vars.setInts(variableId, value); expect(spy).to.be.calledWith(variableId, undefined, value); spy.resetHistory(); value.push(3); await vars.setInts(variableId, value); expect(spy).to.be.calledWith(variableId, [1, 2], value); spy.resetHistory(); value.splice(2, 1, 4); await vars.setInts(variableId, value); expect(spy).to.be.calledWith(variableId, [1, 2, 3], value); spy.resetHistory(); await vars.setInts(variableId, value); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, value, undefined); }); it("handles type conversion", async () => { const value = [faker.random.number(), faker.random.number()]; await vars.setInts(variableId, value); expect(await vars.getBool(variableId)).to.deep.eq(false); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInt(variableId)).to.deep.eq(0); expect(await vars.getId64(variableId)).to.deep.eq(Id64.invalid); expect(await vars.getId64s(variableId)).to.deep.eq(value.map((v) => Id64.fromLocalAndBriefcaseIds(v, 0))); }); }); describe("Id64", () => { it("returns invalid Id64 if there's no value", async () => { expect(await vars.getId64(variableId)).to.deep.eq(Id64.invalid); }); it("sets and returns value", async () => { const value = createRandomId(); await vars.setId64(variableId, value); expect(await vars.getId64(variableId)).to.eq(value); }); it("raises onVariableChanged event when variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setId64(variableId, "0x123"); expect(spy).to.be.calledWith(variableId, undefined, "0x123"); spy.resetHistory(); await vars.setId64(variableId, "0x456"); expect(spy).to.be.calledWith(variableId, "0x123", "0x456"); spy.resetHistory(); await vars.setId64(variableId, "0x456"); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, "0x456", undefined); }); it("handles type conversion", async () => { const value = createRandomId(); await vars.setId64(variableId, value); expect(await vars.getBool(variableId)).to.deep.eq(Id64.isValid(value)); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInt(variableId)).to.deep.eq(Id64.getUpperUint32(value)); expect(await vars.getInts(variableId)).to.deep.eq([]); expect(await vars.getId64s(variableId)).to.deep.eq([]); }); }); describe("Id64[]", () => { it("returns empty list if there's no value", async () => { expect(await vars.getId64s(variableId)).to.deep.eq([]); }); it("sets and returns value", async () => { const value = [createRandomId(), createRandomId()]; await vars.setId64s(variableId, value); expect(await vars.getId64s(variableId)).to.deep.eq(value); }); it("raises onVariableChanged event when immutable variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); await vars.setId64s(variableId, ["0x123", "0x789"]); expect(spy).to.be.calledWith(variableId, undefined, ["0x123", "0x789"]); spy.resetHistory(); await vars.setId64s(variableId, ["0x456"]); expect(spy).to.be.calledWith(variableId, ["0x123", "0x789"], ["0x456"]); spy.resetHistory(); await vars.setId64s(variableId, ["0x789"]); expect(spy).to.be.calledWith(variableId, ["0x456"], ["0x789"]); spy.resetHistory(); await vars.setId64s(variableId, ["0x789"]); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, ["0x789"], undefined); }); it("raises onVariableChanged event when mutable variable changes", async () => { const spy = sinon.spy(); vars.onVariableChanged.addListener(spy); const value = ["0x123", "0x789"]; await vars.setId64s(variableId, value); expect(spy).to.be.calledWith(variableId, undefined, value); spy.resetHistory(); value.splice(0, 2, "0x456"); await vars.setId64s(variableId, value); expect(spy).to.be.calledWith(variableId, ["0x123", "0x789"], value); spy.resetHistory(); value.splice(0, 1, "0x789"); await vars.setId64s(variableId, value); expect(spy).to.be.calledWith(variableId, ["0x456"], value); spy.resetHistory(); await vars.setId64s(variableId, value); expect(spy).to.not.be.called; spy.resetHistory(); await vars.unset(variableId); expect(spy).to.be.calledWith(variableId, value, undefined); }); it("handles type conversion", async () => { const value = [createRandomId(), createRandomId()]; await vars.setId64s(variableId, value); expect(await vars.getBool(variableId)).to.deep.eq(false); expect(await vars.getString(variableId)).to.deep.eq(""); expect(await vars.getInt(variableId)).to.deep.eq(0); expect(await vars.getInts(variableId)).to.deep.eq(value.map((v) => Id64.getUpperUint32(v))); expect(await vars.getId64(variableId)).to.deep.eq(Id64.invalid); }); }); it("sets value to different type", async () => { await vars.setInt(variableId, 123); expect(vars.getAllVariables()).to.deep.eq([{ id: variableId, type: VariableValueTypes.Int, value: 123, }]); await vars.setString(variableId, "456"); expect(vars.getAllVariables()).to.deep.eq([{ id: variableId, type: VariableValueTypes.String, value: "456", }]); }); });
the_stack
import * as path from 'path'; import * as os from 'os'; import * as fs from 'fs'; import * as vscode from 'vscode'; import * as types from 'vscode-languageserver-types'; import { workspace as Workspace, ExtensionContext, env as Env, commands as Commands, TextDocument, WorkspaceFolder, Uri, window, TextEditor, } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, DocumentSelector, } from 'vscode-languageclient/node'; import * as express from 'express'; import { Server } from 'http'; let defaultClient: LanguageClient; let clients: Map<string, LanguageClient> = new Map(); function registerCustomCommands(context: ExtensionContext) { context.subscriptions.push(Commands.registerCommand('lua.config', (data) => { let config = Workspace.getConfiguration(undefined, Uri.parse(data.uri)); if (data.action == 'add') { let value: any[] = config.get(data.key); value.push(data.value); config.update(data.key, value, data.global); return; } if (data.action == 'set') { config.update(data.key, data.value, data.global); return; } })) } let _sortedWorkspaceFolders: string[] | undefined; function sortedWorkspaceFolders(): string[] { if (_sortedWorkspaceFolders === void 0) { _sortedWorkspaceFolders = Workspace.workspaceFolders ? Workspace.workspaceFolders.map(folder => { let result = folder.uri.toString(); if (result.charAt(result.length - 1) !== '/') { result = result + '/'; } return result; }).sort( (a, b) => { return a.length - b.length; } ) : []; } return _sortedWorkspaceFolders; } Workspace.onDidChangeWorkspaceFolders(() => _sortedWorkspaceFolders = undefined); function getOuterMostWorkspaceFolder(folder: WorkspaceFolder): WorkspaceFolder { let sorted = sortedWorkspaceFolders(); for (let element of sorted) { let uri = folder.uri.toString(); if (uri.charAt(uri.length - 1) !== '/') { uri = uri + '/'; } if (uri.startsWith(element)) { return Workspace.getWorkspaceFolder(Uri.parse(element))!; } } return folder; } function start(context: ExtensionContext, documentSelector: DocumentSelector, folder: WorkspaceFolder) { // Options to control the language client let clientOptions: LanguageClientOptions = { // Register the server for plain text documents documentSelector: documentSelector, workspaceFolder: folder, progressOnInitialization: true, markdown: { isTrusted: true, }, }; let config = Workspace.getConfiguration(undefined, folder); let develop: boolean = config.get("robloxLsp.develop.enable"); let debuggerPort: number = config.get("robloxLsp.develop.debuggerPort"); let debuggerWait: boolean = config.get("robloxLsp.develop.debuggerWait"); let commandParam: string = config.get("robloxLsp.misc.parameters"); let command: string; let platform: string = os.platform(); switch (platform) { case "win32": command = context.asAbsolutePath( path.join( 'server', 'bin', 'Windows', 'lua-language-server.exe' ) ); break; case "linux": command = context.asAbsolutePath( path.join( 'server', 'bin', 'Linux', 'lua-language-server' ) ); fs.chmodSync(command, '777'); break; case "darwin": command = context.asAbsolutePath( path.join( 'server', 'bin', 'macOS', 'lua-language-server' ) ); fs.chmodSync(command, '777'); break; } let serverOptions: ServerOptions = { command: command, args: [ '-E', context.asAbsolutePath(path.join( 'server', 'main.lua', )), `--develop=${develop}`, `--dbgport=${debuggerPort}`, `--dbgwait=${debuggerWait}`, commandParam, ] }; let client = new LanguageClient( 'Lua', 'Lua', serverOptions, clientOptions ); // client.registerProposedFeatures(); client.start(); client.onReady().then(() => { onCommand(client); onDecorations(client); statusBar(client); startPluginServer(client); }); return client; } let server: Server | undefined; function startPluginServer(client: LanguageClient) { try { let lastUpdate = ""; let app = express(); app.use('/update', express.json({ limit: '3mb', })); app.post('/update', async (req, res) => { if (!req.body) { res.status(400); res.json({ success: false, reason: 'Missing JSON', }); return; } if (!req.body.DataModel) { res.status(400); res.json({ success: false, reason: 'Missing body.DataModel', }); return; } try { client.sendNotification('$/updateDataModel', { "datamodel": req.body.DataModel, "version": req.body.Version }); lastUpdate = req.body.DataModel; } catch (err) { vscode.window.showErrorMessage(err); } res.status(200); res.json({success: true}); }); app.get("/last", (req, res) => { res.send(lastUpdate); }); let port = vscode.workspace.getConfiguration().get("robloxLsp.misc.serverPort"); if (port > 0) { server = app.listen(port, () => { // vscode.window.showInformationMessage(`Started Roblox LSP Plugin Server on port ${port}`); }); } } catch (err) { vscode.window.showErrorMessage(`Failed to launch Roblox LSP plugin server: ${err}`); } } let barCount = 0; function statusBar(client: LanguageClient) { let bar = window.createStatusBarItem(); bar.text = 'Roblox LSP'; barCount ++; bar.command = 'Lua.statusBar:' + barCount; Commands.registerCommand(bar.command, () => { client.sendNotification('$/status/click'); }) client.onNotification('$/status/show', (params) => { bar.show(); }) client.onNotification('$/status/hide', (params) => { bar.hide(); }) client.onNotification('$/status/report', (params) => { bar.text = params.text; bar.tooltip = params.tooltip; }) } function onCommand(client: LanguageClient) { client.onNotification('$/command', (params) => { Commands.executeCommand(params.command, params.data); }); } function isDocumentInClient(textDocuments: TextDocument, client: LanguageClient): boolean { let selectors = client.clientOptions.documentSelector; if (!DocumentSelector.is(selectors)) {{ return false; }} if (vscode.languages.match(selectors, textDocuments)) { return true; } return false; } function onDecorations(client: LanguageClient) { let textType = window.createTextEditorDecorationType({}) function notifyVisibleRanges(textEditor: TextEditor) { if (!isDocumentInClient(textEditor.document, client)) { return; } let uri: types.DocumentUri = client.code2ProtocolConverter.asUri(textEditor.document.uri); let ranges: types.Range[] = []; for (let index = 0; index < textEditor.visibleRanges.length; index++) { const range = textEditor.visibleRanges[index]; ranges[index] = client.code2ProtocolConverter.asRange(new vscode.Range( Math.max(range.start.line - 3, 0), range.start.character, Math.min(range.end.line + 3, textEditor.document.lineCount - 1), range.end.character )); } for (let index = ranges.length; index > 1; index--) { const current = ranges[index]; const before = ranges[index - 1]; if (current.start.line > before.end.line) { continue; } if (current.start.line == before.end.line && current.start.character > before.end.character) { continue; } ranges.pop(); before.end = current.end; } client.sendNotification('$/didChangeVisibleRanges', { uri: uri, ranges: ranges, }) } for (let index = 0; index < window.visibleTextEditors.length; index++) { notifyVisibleRanges(window.visibleTextEditors[index]); } window.onDidChangeVisibleTextEditors((params: TextEditor[]) => { for (let index = 0; index < params.length; index++) { notifyVisibleRanges(params[index]); } }) window.onDidChangeTextEditorVisibleRanges((params: vscode.TextEditorVisibleRangesChangeEvent) => { notifyVisibleRanges(params.textEditor); }) client.onNotification('$/hint', (params) => { let uri: types.URI = params.uri; for (let index = 0; index < window.visibleTextEditors.length; index++) { const editor = window.visibleTextEditors[index]; if (editor.document.uri.toString() == uri && isDocumentInClient(editor.document, client)) { let textEditor = editor; let edits: types.TextEdit[] = params.edits let options: vscode.DecorationOptions[] = []; for (let index = 0; index < edits.length; index++) { const edit = edits[index]; options[index] = { hoverMessage: edit.newText, range: client.protocol2CodeConverter.asRange(edit.range), renderOptions: { light: { after: { contentText: edit.newText, color: '#888888', backgroundColor: '#EEEEEE;border-radius: 4px; padding: 0px 2px;', fontWeight: '400; font-size: 12px; line-height: 1;', } }, dark: { after: { contentText: edit.newText, color: '#888888', backgroundColor: '#333333;border-radius: 4px; padding: 0px 2px;', fontWeight: '400; font-size: 12px; line-height: 1;', } } } } } textEditor.setDecorations(textType, options); } } }) let textType2 = window.createTextEditorDecorationType({opacity: "0.6",}) client.onNotification('$/luaComment', (params) => { let uri: types.URI = params.uri; for (let index = 0; index < window.visibleTextEditors.length; index++) { const editor = window.visibleTextEditors[index]; if (editor.document.uri.toString() == uri && isDocumentInClient(editor.document, client)) { let ranges: vscode.Range[] = params.ranges let options: vscode.DecorationOptions[] = []; for (let index = 0; index < ranges.length; index++) { options[index] = {range: ranges[index]} } editor.setDecorations(textType2, options); } } }) } export function activate(context: ExtensionContext) { registerCustomCommands(context); function didOpenTextDocument(document: TextDocument) { // We are only interested in language mode text if (document.languageId !== 'lua' || (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled')) { return; } let uri = document.uri; let folder = Workspace.getWorkspaceFolder(uri); // Untitled files go to a default client. if (folder == null && Workspace.workspaceFolders == null && !defaultClient) { defaultClient = start(context, [ { scheme: 'file', language: 'lua' } ], null); return; } // Files outside a folder can't be handled. This might depend on the language. // Single file languages like JSON might handle files outside the workspace folders. if (!folder) { return; } // If we have nested workspace folders we only start a server on the outer most workspace folder. folder = getOuterMostWorkspaceFolder(folder); if (!clients.has(folder.uri.toString())) { let pattern: string = folder.uri.fsPath.replace(/(\[|\])/g, '[$1]') + '/**/*'; let client = start(context, [ { scheme: 'file', language: 'lua', pattern: pattern } ], folder); clients.set(folder.uri.toString(), client); } } function didCloseTextDocument(document: TextDocument): void { let uri = document.uri; if (clients.has(uri.toString())) { let client = clients.get(uri.toString()); if (client) { clients.delete(uri.toString()); client.stop(); } } } Workspace.onDidOpenTextDocument(didOpenTextDocument); //Workspace.onDidCloseTextDocument(didCloseTextDocument); Workspace.textDocuments.forEach(didOpenTextDocument); Workspace.onDidChangeWorkspaceFolders((event) => { for (let folder of event.removed) { let client = clients.get(folder.uri.toString()); if (client) { clients.delete(folder.uri.toString()); client.stop(); } } }); } export function deactivate(): Thenable<void> | undefined { if (server != undefined) { server.close(); server = undefined; } let promises: Thenable<void>[] = []; if (defaultClient) { promises.push(defaultClient.stop()); } for (let client of clients.values()) { promises.push(client.stop()); } return Promise.all(promises).then(() => undefined); }
the_stack
import React, { RefObject } from 'react'; import { withSitecoreContext, trackingApi, TrackingRequestOptions, } from '@sitecore-jss/sitecore-jss-nextjs'; import { dataFetcher } from 'lib/data-fetcher'; import config from 'temp/config'; import StyleguideSpecimen from './Styleguide-Specimen'; import { ComponentWithContextProps } from 'lib/component-props'; import { StyleguideSpecimenFields } from 'lib/component-props/styleguide'; /* eslint-disable no-alert,no-undef */ type StyleguideTrackingProps = ComponentWithContextProps & StyleguideSpecimenFields; /** * Demonstrates analytics tracking patterns (xDB) */ class StyleguideTracking extends React.Component<StyleguideTrackingProps> { private event: RefObject<HTMLInputElement>; private goal: RefObject<HTMLInputElement>; private outcomeName: RefObject<HTMLInputElement>; private outcomeValue: RefObject<HTMLInputElement>; private campaign: RefObject<HTMLInputElement>; private pageId: RefObject<HTMLInputElement>; private pageUrl: RefObject<HTMLInputElement>; private trackingApiOptions: TrackingRequestOptions; constructor(props: StyleguideTrackingProps) { super(props); this.event = React.createRef(); this.goal = React.createRef(); this.outcomeName = React.createRef(); this.outcomeValue = React.createRef(); this.campaign = React.createRef(); this.pageId = React.createRef(); this.pageUrl = React.createRef(); this.trackingApiOptions = { host: config.sitecoreApiHost, querystringParams: { sc_apikey: config.sitecoreApiKey, }, fetcher: dataFetcher, }; } submitEvent() { if (!this.event.current) return; trackingApi .trackEvent([{ eventId: this.event.current.value }], this.trackingApiOptions) .then(() => alert('Page event pushed')) .catch((error) => alert(error)); } submitGoal() { if (!this.goal.current) return; trackingApi .trackEvent([{ goalId: this.goal.current.value }], this.trackingApiOptions) .then(() => alert('Goal pushed')) .catch((error) => alert(error)); } submitOutcome() { if ( !this.pageUrl.current || !this.pageId.current || !this.outcomeName.current || !this.outcomeValue.current ) { return; } trackingApi .trackEvent( [ { url: this.pageUrl.current.value, pageId: this.pageId.current.value, outcomeId: this.outcomeName.current.value, currencyCode: 'USD', monetaryValue: this.outcomeValue.current.value, }, ], this.trackingApiOptions ) .then(() => alert('Outcome pushed')) .catch((error) => alert(error)); } triggerCampaign() { if (!this.campaign.current) return; trackingApi .trackEvent([{ campaignId: this.campaign.current.value }], this.trackingApiOptions) .then(() => alert('Campaign set')) .catch((error) => alert(error)); } submitPageView() { if (!this.pageId.current || !this.pageUrl.current) return; trackingApi .trackEvent( [ { pageId: this.pageId.current.value, url: this.pageUrl.current.value, }, ], this.trackingApiOptions ) .then(() => alert('Page view pushed')) .catch((error) => alert(error)); } abandonSession() { const abandonOptions = { action: 'flush', ...this.trackingApiOptions, }; trackingApi .trackEvent([], abandonOptions) .then(() => alert('Interaction has been terminated and its data pushed to xConnect.')) .catch((error) => alert(error)); } submitBatching() { trackingApi .trackEvent( [ { eventId: 'Download' }, { goalId: 'Instant Demo' }, { outcomeId: 'Opportunity' }, { pageId: '{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}', url: '/arbitrary/url/you/own', }, // this goal will be added to the new page/route ID set above, not the current route { goalId: 'Register' }, ], this.trackingApiOptions ) .then(() => alert('Batch of events pushed')) .catch((error) => alert(error)); } render() { const disconnectedMode = this.props.sitecoreContext.itemId === 'available-in-connected-mode'; return ( <StyleguideSpecimen {...this.props} e2eId="styleguide-tracking"> {disconnectedMode && ( <p>The tracking API is only available in connected, integrated, or headless modes.</p> )} {!disconnectedMode && ( <div> <p className="alert alert-warning"> Note: The JSS tracker API is disabled by default. Consult the{' '} <a href="https://jss.sitecore.com/docs/fundamentals/services/tracking"> tracking documentation </a>{' '} to enable it. </p> <div className="row"> <fieldset className="form-group col-sm"> <legend>Event</legend> <p> Events are defined in <code>/sitecore/system/Settings/Analytics/Page Events</code> </p> <label htmlFor="event">Event GUID or Name</label> <input type="text" id="event" className="form-control" ref={this.event} /> <button type="button" className="btn btn-primary mt-3" onClick={this.submitEvent.bind(this)} > Submit </button> </fieldset> <fieldset className="form-group col-sm"> <legend>Goal</legend> <p> Goals are defined in <code>/sitecore/system/Marketing Control Panel/Goals</code> </p> <label htmlFor="goal">Goal GUID or Name</label> <input type="text" className="form-control" id="goal" ref={this.goal} placeholder="i.e. Register" /> <button type="button" className="btn btn-primary mt-3" onClick={this.submitGoal.bind(this)} > Submit </button> </fieldset> </div> <div className="row"> <fieldset className="form-group col-sm"> <legend>Outcome</legend> <p> Outcomes are defined in{' '} <code>/sitecore/system/Marketing Control Panel/Outcomes</code> </p> <label htmlFor="outcomeName">Outcome GUID or Name</label> <input type="text" className="form-control" id="outcomeName" ref={this.outcomeName} placeholder="i.e. Marketing Lead" /> <br /> <label htmlFor="outcomeValue">Monetary Value (optional)</label> <input type="number" className="form-control" id="outcomeValue" ref={this.outcomeValue} placeholder="i.e. 1337.00" /> <button type="button" className="btn btn-primary mt-3" onClick={this.submitOutcome.bind(this)} > Submit </button> </fieldset> <fieldset className="form-group col-sm"> <legend>Campaign</legend> <p> Campaigns are defined in{' '} <code>/sitecore/system/Marketing Control Panel/Campaigns</code> </p> <label htmlFor="campaign">Campaign GUID or Name</label> <input type="text" className="form-control" id="campaign" ref={this.campaign} /> <button type="button" className="btn btn-primary mt-3" onClick={this.triggerCampaign.bind(this)} > Submit </button> </fieldset> </div> <div className="row"> <fieldset className="form-group col-sm"> <legend>Page View</legend> <p> Track arbitrary page views for custom routing or offline use. Note that Layout Service tracks page views by default unless <code>tracking=false</code> is passed in its query string. </p> <label htmlFor="pageId">Page Item GUID</label> <input type="text" className="form-control" id="pageId" ref={this.pageId} placeholder="i.e. {11111111-1111-1111-1111-111111111111}" /> <br /> <label htmlFor="pageUrl">Page URL</label> <input type="text" className="form-control" id="pageUrl" ref={this.pageUrl} placeholder="i.e. /foo/bar" /> <button type="button" className="btn btn-primary mt-3" onClick={this.submitPageView.bind(this)} > Submit </button> </fieldset> <fieldset className="form-group col-sm"> <legend>Batching</legend> <p> The tracking API supports pushing a whole batch of events in a single request. This can be useful for queuing strategies or offline PWA usage. </p> <button type="button" className="btn btn-primary" onClick={this.submitBatching.bind(this)} > Submit Batch of Events </button> </fieldset> </div> <div className="row"> <fieldset className="form-group col-sm"> <legend>Interaction Control</legend> <p> Tracking data is not pushed into the xConnect service until your session ends on the Sitecore server. Click this button to instantly end your session and flush the data - great for debugging and testing. </p> <p className="alert alert-warning"> Note: By default <em>anonymous</em> contacts will not be shown in Experience Profile. If your interactions are not showing up in Experience Profile, you may need to{' '} <a href="https://doc.sitecore.net/developers/xp/xconnect/xconnect-search-indexer/enable-anonymous-contact-indexing.html"> enable anonymous contact indexing. </a> </p> <button type="button" className="btn btn-primary" onClick={this.abandonSession.bind(this)} > End Interaction </button> </fieldset> </div> </div> )} </StyleguideSpecimen> ); } } export default withSitecoreContext()(StyleguideTracking);
the_stack
import {assert} from './assert.js'; import {Intent} from './intent.js'; import * as Comlink from './lib/comlink.js'; import * as loadTimeData from './models/load_time_data.js'; import * as localStorage from './models/local_storage.js'; import {ChromeHelper} from './mojo/chrome_helper.js'; import * as state from './state.js'; import { Facing, Mode, PerfEvent, PerfInformation, Resolution, } from './type.js'; import {GAHelperInterface} from './untrusted_helper_interfaces.js'; import * as util from './util.js'; import {WaitableEvent} from './waitable_event.js'; /** * The tracker ID of the GA metrics. */ const GA_ID = 'UA-134822711-1'; let baseDimen: Map<number, string|number>|null = null; const ready = new WaitableEvent(); const gaHelper = util.createUntrustedJSModule<GAHelperInterface>( '/js/untrusted_ga_helper.js'); /** * Send the event to GA backend. * @param event The event to send. * @param dimen Optional object contains dimension information. */ async function sendEvent( event: UniversalAnalytics.FieldsObject, dimen?: Map<number, unknown>) { const assignDimension = (e, d) => { for (const [key, value] of d.entries()) { e[`dimension${key}`] = value; } }; assert(baseDimen !== null); assignDimension(event, baseDimen); if (dimen !== undefined) { assignDimension(event, dimen); } await ready.wait(); // This value reflects the logging consent option in OS settings. const canSendMetrics = await ChromeHelper.getInstance().isMetricsAndCrashReportingEnabled(); if (canSendMetrics) { (await gaHelper).sendGAEvent(event); } } /** * Set if the metrics is enabled. Note that the metrics will only be sent if it * is enabled AND the logging consent option is enabled in OS settings. * @param enabled True if the metrics is enabled. */ export async function setMetricsEnabled(enabled: boolean): Promise<void> { await ready.wait(); await (await gaHelper).setMetricsEnabled(GA_ID, enabled); } const SCHEMA_VERSION = 2; /** * Initializes metrics with parameters. */ export async function initMetrics(): Promise<void> { const board = loadTimeData.getBoard(); const boardName = /^(x86-)?(\w*)/.exec(board)[0]; const match = navigator.appVersion.match(/CrOS\s+\S+\s+([\d.]+)/); const osVer = match ? match[1] : ''; baseDimen = new Map<number, string|number>([ [1, boardName], [2, osVer], [31, SCHEMA_VERSION], ]); const GA_LOCAL_STORAGE_KEY = 'google-analytics.analytics.user-id'; const clientId = localStorage.getString(GA_LOCAL_STORAGE_KEY); const setClientId = (id) => { localStorage.set(GA_LOCAL_STORAGE_KEY, id); }; await (await gaHelper).initGA(GA_ID, clientId, Comlink.proxy(setClientId)); ready.signal(); } /** * Types of different ways to launch CCA. */ export enum LaunchType { DEFAULT = 'default', ASSISTANT = 'assistant', } /** * Parameters for logging launch event. |launchType| stands for how CCA is * launched. */ export interface LaunchEventParam { launchType: LaunchType; } /** * Sends launch type event. */ export function sendLaunchEvent({launchType}: LaunchEventParam): void { sendEvent( { eventCategory: 'launch', eventAction: 'start', eventLabel: '', }, new Map([ [32, launchType], ])); } /** * Types of intent result dimension. */ export enum IntentResultType { NOT_INTENT = '', CANCELED = 'canceled', CONFIRMED = 'confirmed', } /** * Types of document scanning result dimension. */ export enum DocResultType { NOT_DOCUMENT = '', CANCELED = 'canceled', SAVE_AS_PHOTO = 'save-as-photo', SAVE_AS_PDF = 'save-as-pdf', SHARE = 'share', } /** * Types of user interaction with fix document page. */ export enum DocFixType { NONE = 0, NO_FIX = 1, FIX_ROTATION = 2, FIX_POSITION = 3, FIX_BOTH = 4, } /** * Types of gif recording result dimension. */ export enum GifResultType { NOT_GIF_RESULT = 0, RETAKE = 1, SHARE = 2, SAVE = 3, } /** * Types of recording in video mode. */ export enum RecordType { NOT_RECORDING = 0, NORMAL_VIDEO = 1, GIF = 2, } /** * Types of different ways to trigger shutter button. */ export enum ShutterType { UNKNOWN = 'unknown', MOUSE = 'mouse', KEYBOARD = 'keyboard', TOUCH = 'touch', VOLUME_KEY = 'volume-key', ASSISTANT = 'assistant', } /** * Parameters of capture metrics event. */ export interface CaptureEventParam { /** Camera facing of the capture. */ facing: Facing; /** Length of duration for captured motion result in milliseconds. */ duration?: number; /** Capture resolution. */ resolution: Resolution; intentResult?: IntentResultType; shutterType: ShutterType; /** Whether the event is for video snapshot. */ isVideoSnapshot?: boolean; /** Whether the video have ever paused and resumed in the recording. */ everPaused?: boolean; docResult?: DocResultType; docFixType?: DocFixType; gifResult?: GifResultType; recordType?: RecordType; } /** * Sends capture type event. */ export function sendCaptureEvent({ facing, duration = 0, resolution, intentResult = IntentResultType.NOT_INTENT, shutterType, isVideoSnapshot = false, everPaused = false, docResult = DocResultType.NOT_DOCUMENT, docFixType, recordType = RecordType.NOT_RECORDING, gifResult = GifResultType.NOT_GIF_RESULT, }: CaptureEventParam): void { const condState = (states: state.StateUnion[], cond?: state.StateUnion, strict?: boolean): string => { // Return the first existing state among the given states only if // there is no gate condition or the condition is met. const prerequisite = !cond || state.get(cond); if (strict && !prerequisite) { return ''; } return prerequisite && states.find((s) => state.get(s)) || 'n/a'; }; const State = state.State; sendEvent( { eventCategory: 'capture', eventAction: condState(Object.values(Mode)), eventLabel: facing, eventValue: duration, }, new Map<number, unknown>([ // Skips 3rd dimension for obsolete 'sound' state. [4, condState([State.MIRROR])], [ 5, condState( [State.GRID_3x3, State.GRID_4x4, State.GRID_GOLDEN], State.GRID), ], [6, condState([State.TIMER_3SEC, State.TIMER_10SEC], State.TIMER)], [7, condState([State.MIC], Mode.VIDEO, true)], [8, condState([State.MAX_WND])], [9, condState([State.TALL])], [10, resolution.toString()], [11, condState([State.FPS_30, State.FPS_60], Mode.VIDEO, true)], [12, intentResult], [21, shutterType], [22, isVideoSnapshot], [23, everPaused], [27, docResult], [28, recordType], [29, gifResult], [30, duration], // This is included in baseDimen. // [31, SCHEMA_VERSION] [32, docFixType ?? ''], ])); } /** * Parameters for logging perf event. */ interface PerfEventParam { /** Target event type. */ event: PerfEvent; /** Duration of the event in ms. */ duration: number; /** Optional information for the event. */ perfInfo?: PerfInformation; } /** * Sends perf type event. */ export function sendPerfEvent({event, duration, perfInfo = {}}: PerfEventParam): void { const resolution = perfInfo['resolution'] || ''; const facing = perfInfo['facing'] || ''; sendEvent( { eventCategory: 'perf', eventAction: event, eventLabel: facing, // Round the duration here since GA expects that the value is an // integer. Reference: // https://support.google.com/analytics/answer/1033068 eventValue: Math.round(duration), }, new Map([ [10, `${resolution}`], ])); } /** * See Intent class in intent.js for the descriptions of each field. */ export interface IntentEventParam { intent: Intent; result: IntentResultType; } /** * Sends intent type event. */ export function sendIntentEvent({intent, result}: IntentEventParam): void { const {mode, shouldHandleResult, shouldDownScale, isSecure} = intent; const getBoolValue = (b) => b ? '1' : '0'; sendEvent( { eventCategory: 'intent', eventAction: mode, eventLabel: result, }, new Map([ [12, result], [13, getBoolValue(shouldHandleResult)], [14, getBoolValue(shouldDownScale)], [15, getBoolValue(isSecure)], ])); } export interface ErrorEventParam { type: string; level: string; errorName: string; fileName: string; funcName: string; lineNo: string; colNo: string; } /** * Sends error type event. */ export function sendErrorEvent( {type, level, errorName, fileName, funcName, lineNo, colNo}: ErrorEventParam): void { sendEvent( { eventCategory: 'error', eventAction: type, eventLabel: level, }, new Map([ [16, errorName], [17, fileName], [18, funcName], [19, lineNo], [20, colNo], ])); } /** * Sends the barcode enabled event. */ export function sendBarcodeEnabledEvent(): void { sendEvent({ eventCategory: 'barcode', eventAction: 'enable', }); } /** * Types of the decoded barcode content. */ export enum BarcodeContentType { TEXT = 'text', URL = 'url', } interface BarcodeDetectedEventParam { contentType: BarcodeContentType; } /** * Sends the barcode detected event. */ export function sendBarcodeDetectedEvent( {contentType}: BarcodeDetectedEventParam): void { sendEvent({ eventCategory: 'barcode', eventAction: 'detect', eventLabel: contentType, }); } /** * Sends the open ptz panel event. */ export function sendOpenPTZPanelEvent( capabilities: {pan: boolean, tilt: boolean, zoom: boolean}): void { sendEvent( { eventCategory: 'ptz', eventAction: 'open-panel', }, new Map([ [24, capabilities.pan], [25, capabilities.tilt], [26, capabilities.zoom], ])); }
the_stack
import { action, toJS } from 'mobx'; import { observer, useLocalStore } from 'mobx-react-lite'; import React, { useEffect, useState } from 'react'; import { Alert, Button, FormField, Header, Input, Modal, Select, SpaceBetween, StatusIndicator, Table } from '@awsui/components-react'; import { useI18n } from '@/components/i18n-context'; import { valueAsArray } from '@/utils'; import { AcceleratorConfigurationNode } from '../configuration'; import { WizardField } from './fields'; import { LabelWithDescription } from './label-with-description'; import { useInput } from '@/utils/hooks'; import { OptionDefinition } from '../../../../node_modules/@awsui/components-react/internal/components/option/interfaces'; const cidrPoolsNode = AcceleratorConfigurationNode.nested('global-options').nested('cidr-pools'); const dummyCidrPoolNode = cidrPoolsNode.nested(0); interface SimpleCidrPoolUnitValue { cidr: string; pool: string; description: string; region: string; origPoolName: string; } export interface CidrPoolTableProps { state: any; } export const CidrPoolTable: React.VFC<CidrPoolTableProps> = observer(({ state }) => { const { tr } = useI18n(); const [modalVisible, setModalVisible] = useState(false); const [modalType, setModalType] = useState<'add' | 'edit'>('add'); const [modalInitialValue, setModalInitialValue] = useState<any>({}); const [selectedItem, setSelectedItem] = useState<any>(); const [dependencyAlertVisible, setDependencyAlertVisible] = useState(false); const [editNameAlert, setEditNameAlert] = useState(false); const [addNameAlert, setAddNameAlert] = useState(false); const [cannotAddCIDR, setCannotAddCIDR] = useState(false); // Fetch translations to be used as table headers const { title: nameTitle } = tr(dummyCidrPoolNode.nested('pool')); const { title: cidrTitle } = tr(dummyCidrPoolNode.nested('cidr')); const { title: regionTitle } = tr(dummyCidrPoolNode.nested('region')); const cidrPoolsNodeState = cidrPoolsNode.get(state) ?? {} const cidrPoolList: SimpleCidrPoolUnitValue[] = Object.entries(cidrPoolsNodeState).map( ([key, cidrConfig]: [string, any]) => { return { cidr: cidrConfig?.cidr, pool: cidrConfig?.pool, description: cidrConfig?.description, region: cidrConfig?.region, origPoolName: cidrConfig?.pool }; }, ); const pools = valueAsArray(cidrPoolsNode.get(state)); const handleAdd = action(() => { setModalType('add'); setModalInitialValue({}); setModalVisible(true); }); const handleEdit = action(() => { setModalType('edit'); setModalInitialValue(selectedItem ? toJS(selectedItem) : {}); setModalVisible(true); }); const nameExists = (pool: string | undefined) => { for (let each in pools) { if (pools[each]['pool'] == pool) { return true; } } return false; } const validateForm = (cidr: string, pool: string, description: string, region: String) => { if (cidr == "" || pool == "" || description == "" || region == "") { return false } else { return true } } const handleSubmitAdd = action((value: SimpleCidrPoolUnitValue) => { const {cidr, pool, description, region, origPoolName} = value; if (nameExists(pool)) { setAddNameAlert(true); } else if (validateForm(cidr, pool, description, region)) { cidrPoolsNodeState.push( { cidr: cidr, pool: pool, region: region, description: description, origPoolName: pool, } ) } else { setCannotAddCIDR(true); } /*if (nameExists(value['pool'])) { } else { cidrPoolsNode.set(state, [...pools, value]); }*/ }); const handleSubmitEdit = action((value: SimpleCidrPoolUnitValue) => { const {cidr, pool, description, region, origPoolName} = value; if(pool !== origPoolName) { if (nameExists(pool)) { setEditNameAlert(true); return; } else { cidrRecurs(selectedItem.pool, value.pool, state) } } let index = 0; for (let each in cidrPoolList) { if (cidrPoolList[each].pool == selectedItem.pool) { index = parseInt(each) } } cidrPoolsNodeState[index] = { cidr: cidr, pool: pool, region: region, description: description, } }); const cidrRecurs = action((oldValue: string, newValue: string, node: any) => { Object.entries(node).forEach(([key, value]) => { if (typeof(value) != 'object') { if (Array.isArray(value)) { for (const each of value) { if (typeof(each == 'object')) cidrRecurs(oldValue, newValue, each) } } else { if (key == 'pool' && node[key] == oldValue) { node[key] = newValue } return } } cidrRecurs(oldValue, newValue, value) }) }); const handleSubmit = action((value: any) => { if (modalType === 'add') { handleSubmitAdd(value); } else { handleSubmitEdit(value); } setSelectedItem(undefined); setModalVisible(false); }); const handleRemove = action(() => { if (checkDependency(selectedItem?.pool, state)) { setDependencyAlertVisible(true); } else { const newPools = pools.filter(pool => selectedItem?.pool !== pool.pool); cidrPoolsNode.set(state, newPools); } setSelectedItem(undefined); }); const checkDependency = (cidrName: string, node: any) => { var dependencyExists = false; Object.entries(node).forEach(([key, value]) => { if (key == 'global-options') { return; } if (typeof(value) != 'object') { if (Array.isArray(value)) { for (const each of value) { if (typeof(each == 'object')) dependencyExists = dependencyExists || checkDependency(cidrName, each) } } else { if (key == 'pool' && node[key] == cidrName) { dependencyExists = true; return true } return dependencyExists } } dependencyExists = dependencyExists || checkDependency(cidrName, value) }) return dependencyExists }; return ( <> <AddCidrPoolModal type={modalType} visible={modalVisible} initialValue={modalInitialValue} onDismiss={() => setModalVisible(false)} onSubmit={handleSubmit} state={state} /> <Table items={cidrPoolList} trackBy="pool" selectionType="single" selectedItems={selectedItem ? [selectedItem] : []} onSelectionChange={e => setSelectedItem(e.detail.selectedItems?.[0])} columnDefinitions={[ { header: nameTitle, cell: ({ pool, description }) => <LabelWithDescription label={pool} description={description} />, }, { header: cidrTitle, cell: ({ cidr }) => cidr, }, { header: regionTitle, cell: ({ region }) => region, }, ]} header={ <> <Header variant="h2" counter={`(${pools.length})`} description={tr('wizard.headers.cidr_pools_desc')} actions={ <SpaceBetween size="xs" direction="horizontal"> <Button disabled={selectedItem == null} onClick={handleRemove}> {tr('buttons.remove')} </Button> <Button disabled={selectedItem == null} onClick={handleEdit}> {tr('buttons.edit')} </Button> <Button iconName="add-plus" variant="primary" onClick={handleAdd}> {tr('buttons.add')} </Button> </SpaceBetween> } > {tr('wizard.headers.cidr_pools')} </Header> { cannotAddCIDR === true && <Alert onDismiss={() => setCannotAddCIDR(false)} visible={cannotAddCIDR} dismissible type="error" dismissAriaLabel="Close alert" header="Can't add new CIDR Pool" > Fields cannot be left empty when adding a new CIDR Pool. </Alert> } { dependencyAlertVisible === true && <Alert onDismiss={() => setDependencyAlertVisible(false)} visible={dependencyAlertVisible} dismissible type="error" dismissAriaLabel="Close alert" header="Cannot remove this CIDR pool due to dependency" > There are other sections of your configuration that depend on this CIDR pool. Remove those dependencies first and try again. </Alert> } { editNameAlert === true && <Alert onDismiss={() => setEditNameAlert(false)} visible={editNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unsuccessful name change for CIDR pool" > You cannot rename a CIDR pool to an already existing CIDR pool. . </Alert> } { addNameAlert === true && <Alert onDismiss={() => setAddNameAlert(false)} visible={addNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unable to add CIDR pool" > You cannot add a CIDR pool with the same name of an already existing CIDR pool. </Alert> } </> } footer={<StatusIndicator type="info">{tr('wizard.labels.cidr_pools_use_graphical_editor')}</StatusIndicator>} /> </> ); }); interface AddCidrPoolModalProps { type: 'add' | 'edit'; visible: boolean; initialValue: any; onDismiss: () => void; onSubmit: (value: any) => void; state: any; } /** * This component renders the add modal to add a new CIDR pool. */ const AddCidrPoolModal = observer(function AddCidrPoolModal({ type, visible, initialValue, onDismiss, onSubmit, state }: AddCidrPoolModalProps) { const { tr } = useI18n(); //const staging = useLocalStore(() => ({})); const cidrPoolNameInputProps = useInput(); const cidrPoolSizeInputProps = useInput(); const cidrPoolDescInputProps = useInput(); // prettier-ignore const headerText = type === 'add' ? tr('wizard.headers.add_cidr_pool') : tr('wizard.headers.edit_cidr_pool'); // prettier-ignore const buttonText = type === 'add' ? tr('buttons.add') : tr('buttons.save_changes'); const { title: nameTitle, description: nameDesc } = tr(dummyCidrPoolNode.nested('pool')); const { title: cidrTitle, description: cidrDesc } = tr(dummyCidrPoolNode.nested('cidr')); const { title: regionTitle, description: regionDesc } = tr(dummyCidrPoolNode.nested('region')); const { title: descTitle, description: descDesc } = tr(dummyCidrPoolNode.nested('description')); const [selectedOption, setSelectedOption] = useState<OptionDefinition>({ label: "", value: "" }); const regionsNode = AcceleratorConfigurationNode.nested('global-options').nested('supported-regions'); const regionsNodeState = regionsNode.get(state) ?? {} var options: { label: string; value: string; }[] = [] const populateSelect = () => { for (const each in regionsNodeState) { options.push({label: regionsNodeState[each], value: regionsNodeState[each]}) } } const handleSubmit = () => { onSubmit({ cidr: cidrPoolSizeInputProps.value ?? '', pool: cidrPoolNameInputProps.value ?? '', description: cidrPoolDescInputProps.value ?? '', region: String(selectedOption.value) ?? '', origPoolName: initialValue.pool }); }; /*useEffect(() => dummyCidrPoolNode.set(staging, initialValue), [visible]);*/ useEffect(() => { cidrPoolNameInputProps.setValue(initialValue.pool ?? ''); cidrPoolSizeInputProps.setValue(initialValue.cidr ?? ''); cidrPoolDescInputProps.setValue(initialValue.description ?? ''); setSelectedOption({ label: initialValue.region ?? '', value: initialValue.region ?? ''}); }, [visible]); return ( <Modal visible={visible} header={<Header variant="h3">{headerText}</Header>} footer={ <Button variant="primary" className="float-button" onClick={handleSubmit}> {buttonText} </Button> } onDismiss={onDismiss} > <form onSubmit={event => { event.stopPropagation(); event.preventDefault(); handleSubmit(); }} > {populateSelect()} <SpaceBetween size="m"> <FormField label={nameTitle} description={nameDesc} stretch> <Input {...cidrPoolNameInputProps}/> </FormField> <FormField label={cidrTitle} description={cidrDesc} stretch> <Input {...cidrPoolSizeInputProps} /> </FormField> <FormField label={regionTitle} description={regionDesc} stretch> <Select selectedOption={selectedOption} onChange={({ detail }) => setSelectedOption(detail.selectedOption) } options={options} selectedAriaLabel="Selected" /> </FormField> <FormField label={descTitle} description={descDesc} stretch> <Input {...cidrPoolDescInputProps} /> </FormField> </SpaceBetween> </form> {/* Use staging state to create the new pool in <WizardField state={staging} node={dummyCidrPoolNode.nested('pool')} /> <WizardField state={staging} node={dummyCidrPoolNode.nested('cidr')} /> <WizardField state={staging} node={dummyCidrPoolNode.nested('region')} /> <WizardField state={staging} node={dummyCidrPoolNode.nested('description')} />*/} </Modal> ); });
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { environment } from './../../../../../environments/environment'; import { AssetGroupObservableService } from '../../../../core/services/asset-group-observable.service'; import { ActivatedRoute, Router } from '@angular/router'; import { DataCacheService } from '../../../../core/services/data-cache.service'; import { Subscription } from 'rxjs/Subscription'; import { IssueListingService } from '../../../services/issue-listing.service'; import { IssueFilterService } from '../../../services/issue-filter.service'; import * as _ from 'lodash'; 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 { DownloadService } from '../../../../shared/services/download.service'; import { RefactorFieldsService } from './../../../../shared/services/refactor-fields.service'; import { WorkflowService } from '../../../../core/services/workflow.service'; import { RouterUtilityService } from '../../../../shared/services/router-utility.service'; @Component({ selector: 'app-vulnerabilities', templateUrl: './vulnerabilities.component.html', styleUrls: ['./vulnerabilities.component.css'], providers: [ IssueListingService, IssueFilterService, LoggerService, ErrorHandlingService ] }) export class VulnerabilitiesComponent implements OnInit, OnDestroy { pageTitle = 'Vulnerabilities'; issueListingdata: any; selectedAssetGroup: string; breadcrumbArray: any = ['Compliance']; breadcrumbLinks: any = ['compliance-dashboard']; breadcrumbPresent: any; outerArr: any = []; dataLoaded = false; errorMessage: any; showingArr: any = ['severity', 'owner', 'executionId']; allColumns: any = []; totalRows = 0; currentBucket: any = []; bucketNumber = 0; firstPaginator = 1; lastPaginator: number; currentPointer = 0; seekdata = false; showLoader = true; paginatorSize = 25; searchTxt = ''; popRows: any = ['Vulnerability list', 'Vulnerability list with asset details']; dataTableData: any = []; tableDataLoaded = false; filters: any = []; searchCriteria: any; filterText: any = {}; errorValue = 0; showGenericMessage = false; urlID = ''; public labels: any; FullQueryParams: any; queryParamsWithoutFilter: any; urlToRedirect: any = ''; backButtonRequired; pageLevel = 0; private assetGroupSubscription: Subscription; private routeSubscription: Subscription; private complianceDropdownSubscription: Subscription; private issueListingSubscription: Subscription; private issueFilterSubscription: Subscription; private downloadSubscription: Subscription; constructor( private assetGroupObservableService: AssetGroupObservableService, private activatedRoute: ActivatedRoute, private dataStore: DataCacheService, private issueListingService: IssueListingService, private issueFilterService: IssueFilterService, private router: Router, private workflowService: WorkflowService, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private downloadService: DownloadService, private refactorFieldsService: RefactorFieldsService, private routerUtilityService: RouterUtilityService ) { this.assetGroupSubscription = this.assetGroupObservableService .getAssetGroup() .subscribe(assetGroupName => { this.selectedAssetGroup = assetGroupName; this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently( this.pageLevel ); this.routerParam(); this.deleteFilters(); this.getFilterArray(); this.updateComponent(); }); } ngOnInit() { this.breadcrumbPresent = 'All Vulnerabilities'; } /* * This function gets the urlparameter and queryObj *based on that urlparameter 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) { /** * FullQueryParams hold the entire queryobj(filter obj + the other obj) * queryParamsWithoutFilter holds only the part without the filter, * queryParamsWithoutFilter is used so that while deleting the filter we can append the remaining part * which is not part of filterobj(check in deleteFilters function) */ this.FullQueryParams = currentQueryParams; this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams)); delete this.queryParamsWithoutFilter['filter']; /** * 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(currentQueryParams); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } updatePaginator(event) { if (event !== this.paginatorSize) { this.paginatorSize = event; this.updateComponent(); } } deleteFilters(event?) { try { if (!event) { this.filters = []; } else { if (event.clearAll) { this.filters = []; } else { this.filters.splice(event.index, 1); } this.filterText = this.utils.arrayToObject( this.filters, 'filterkey', 'value' ); // <-- TO update the queryparam which is passed in the filter of the api this.filterText = this.utils.makeFilterObj(this.filterText); /** * To change the url * with the deleted filter value along with the other existing paramter(ex-->tv:true) */ const updatedFilters = Object.assign( this.filterText, this.queryParamsWithoutFilter ); this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: updatedFilters }); /** * Finally after changing URL Link * api is again called with the updated filter */ this.filterText = this.utils.processFilterObj(this.filterText); this.updateComponent(); } } catch (error) { this.logger.log('error', error); } } /* * this functin passes query params to filter component to show filter */ getFilterArray() { try { const localFilters = []; // <<-- this filter is used to store data for filter const filterObjKeys = Object.keys(this.filterText); const dataArray = []; for (let i = 0; i < filterObjKeys.length; i++) { let obj = {}; obj = { name: filterObjKeys[i] }; dataArray.push(obj); } const filterValues = dataArray; const refactoredService = this.refactorFieldsService; // add By trinanjan const formattedFilters = dataArray.map(function(data) { data.name = refactoredService.getDisplayNameForAKey(data.name.toLowerCase()) || data.name; return data; }); for (let i = 0; i < formattedFilters.length; i++) { const eachObj = { key: formattedFilters[i].name, // <-- displayKey-- Resource Type value: this.filterText[filterObjKeys[i]], // <<-- value to be shown in the filter UI-- S2 filterkey: filterObjKeys[i].trim(), // <<-- filter key that to be passed -- "resourceType " compareKey : filterObjKeys[i].toLowerCase().trim()// <<-- key to compare whether a key is already present -- "resourcetype" }; localFilters.push(eachObj); } this.filters = localFilters; } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.searchTxt = ''; this.currentBucket = []; this.bucketNumber = 0; this.firstPaginator = 1; this.showLoader = true; this.currentPointer = 0; this.dataLoaded = false; this.dataTableData = []; this.tableDataLoaded = false; this.seekdata = false; this.errorValue = 0; this.showGenericMessage = false; this.getData(); } getData() { try { if (this.issueListingSubscription) { this.issueListingSubscription.unsubscribe(); } let queryParams; queryParams = { ag: this.selectedAssetGroup, filter: this.filterText, from: this.bucketNumber * this.paginatorSize, searchtext: this.searchTxt, size: this.paginatorSize }; this.errorValue = 0; const allVulnerabilityUrl = environment.allVulnerability.url; const allVulnerabilityMethod = environment.allVulnerability.method; this.issueListingSubscription = this.issueListingService .getData(queryParams, allVulnerabilityUrl, allVulnerabilityMethod) .subscribe( response => { this.showGenericMessage = false; try { this.errorValue = 1; this.searchCriteria = undefined; this.tableDataLoaded = true; this.dataTableData = response[0].response; const data = response[0]; this.showLoader = false; this.dataLoaded = true; if (response[0].response.length === 0) { this.errorValue = -1; this.outerArr = []; this.allColumns = []; this.totalRows = 0; } if (data.response.length > 0) { this.issueListingdata = data.response; this.seekdata = false; this.totalRows = data.total; this.firstPaginator = this.bucketNumber * this.paginatorSize + 1; this.lastPaginator = this.bucketNumber * this.paginatorSize + this.paginatorSize; this.currentPointer = this.bucketNumber; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } const updatedResponse = this.utils.massageTableData(this.issueListingdata); this.currentBucket[this.bucketNumber] = updatedResponse; this.processData(updatedResponse); } } catch (e) { this.errorValue = 0; this.errorValue = -1; this.outerArr = []; this.dataLoaded = true; this.seekdata = true; this.errorMessage = this.errorHandling.handleJavascriptError(e); } }, error => { this.showGenericMessage = true; this.errorValue = -1; this.outerArr = []; this.dataLoaded = true; this.seekdata = true; this.errorMessage = 'apiResponseError'; } ); } catch (error) { this.showLoader = false; this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } processData(data) { try { let innerArr = {}; const totalVariablesObj = {}; let cellObj = {}; this.outerArr = []; const getData = data; let getCols; if (getData.length) { getCols = Object.keys(getData[0]); } else { this.seekdata = true; } for (let row = 0; row < getData.length; row++) { innerArr = {}; for (let col = 0; col < getCols.length; col++) { if (getCols[col].toLowerCase() === 'title' || getCols[col].toLowerCase() === 'qid') { cellObj = { link: 'View Vulnerability Details', properties: { color: '', 'text-shadow': '0.1px 0' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: getData[row][getCols[col]], valText: getData[row][getCols[col]] }; } else if (getCols[col].toLowerCase() === 'severity') { if (getData[row][getCols[col]] === 'low') { cellObj = { link: '', properties: { color: '', 'text-transform': 'capitalize' }, colName: getCols[col], hasPreImg: true, imgLink: '', text: getData[row][getCols[col]], valText: 1, statusProp: { 'background-color': '#ffe00d' } }; } else if (getData[row][getCols[col]] === 'medium') { cellObj = { link: '', properties: { color: '', 'text-transform': 'capitalize' }, colName: getCols[col], hasPreImg: true, imgLink: '', valText: 2, text: getData[row][getCols[col]], statusProp: { 'background-color': '#ffb00d' } }; } else if (getData[row][getCols[col]] === 'high') { cellObj = { link: '', properties: { color: '', 'text-transform': 'capitalize' }, colName: getCols[col], hasPreImg: true, valText: 3, imgLink: '', text: getData[row][getCols[col]], statusProp: { 'background-color': '#ed0295' } }; } else { cellObj = { link: '', properties: { color: '', 'text-transform': 'capitalize' }, colName: getCols[col], hasPreImg: true, imgLink: '', valText: 4, text: getData[row][getCols[col]], statusProp: { 'background-color': '#e60127' } }; } } else if ( getCols[col].toLowerCase() === 'assets affected' || getCols[col].toLowerCase() === 'assetsaffected') { cellObj = { link: 'View Asset List', properties: { color: '', 'text-decoration': 'underline #383C4D' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: getData[row][getCols[col]], valText: getData[row][getCols[col]] }; } else if ( getCols[col].toLowerCase() === 'createdon' || getCols[col].toLowerCase() === 'created on' || getCols[col].toLowerCase() === 'modifiedon' || getCols[col].toLowerCase() === 'modified on' ) { cellObj = { link: '', properties: { color: '' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: this.utils.calculateDate(getData[row][getCols[col]]), valText: new Date(getData[row][getCols[col]]).getTime() }; } else { cellObj = { link: '', properties: { color: '' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: getData[row][getCols[col]], valText: getData[row][getCols[col]] }; } innerArr[getCols[col]] = cellObj; totalVariablesObj[getCols[col]] = ''; } this.outerArr.push(innerArr); } if (this.outerArr.length > getData.length) { const halfLength = this.outerArr.length / 2; this.outerArr = this.outerArr.splice(halfLength); } this.allColumns = Object.keys(totalVariablesObj); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } goToDetails(row) { console.log(row); try { const apiTarget = { TypeAsset: 'vulnerable' }; this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root); if (row.col.toLowerCase() === 'assets affected' || row.col.toLowerCase() === 'assetsaffected') { const applicationFilterValue = this.filterText['tags.Application.keyword']; const environmentFilterValue = this.filterText['tags.Environment.keyword']; const eachParams = { qid: row.row.qid.valText, application: applicationFilterValue, environment: environmentFilterValue}; let newParams = this.utils.makeFilterObj(eachParams); newParams = Object.assign(newParams, apiTarget); newParams['mandatory'] = 'qid'; this.router.navigate(['../../../assets', 'asset-list'], { relativeTo: this.activatedRoute, queryParams: newParams, queryParamsHandling: 'merge' }); } else if (row.col.toLowerCase() === 'qid' || row.col.toLowerCase() === 'title') { this.router.navigate(['../../vulnerabilities/vulnerability-details', row.row.qid.valText ], { relativeTo: this.activatedRoute, queryParams: this.queryParamsWithoutFilter, queryParamsHandling: 'merge' }); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } searchCalled(search) { this.searchTxt = search; } prevPg() { try { this.currentPointer--; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = this.currentPointer * this.paginatorSize + 1; this.lastPaginator = this.currentPointer * this.paginatorSize + this.paginatorSize; } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } nextPg() { try { if (this.currentPointer < this.bucketNumber) { this.currentPointer++; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = this.currentPointer * this.paginatorSize + 1; this.lastPaginator = this.currentPointer * this.paginatorSize + this.paginatorSize; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } } else { this.bucketNumber++; this.getData(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } callNewSearch() { this.bucketNumber = 0; this.currentBucket = []; this.getData(); } vulnerabilitiesCSV(serviceName) { const fileType = 'csv'; let downloadCsvName; let downloadSize = 0; try { let queryParams; queryParams = { fileFormat: 'csv', fileType: fileType }; if (serviceName === 'Vulnerability list') { queryParams.serviceId = 6; downloadCsvName = 'All Vulnerabilities'; downloadSize = this.totalRows; } else if (serviceName === 'Vulnerability list with asset details') { queryParams.serviceId = 19; downloadCsvName = 'All Vulnerabilities with Details'; } const downloadRequest = { ag: this.selectedAssetGroup, filter: this.filterText, from: 0, searchtext: this.searchTxt, size: downloadSize }; const downloadUrl = environment.download.url; const downloadMethod = environment.download.method; this.downloadService .requestForDownload( queryParams, downloadUrl, downloadMethod, downloadRequest, downloadCsvName, this.totalRows ); } catch (error) { this.logger.log('error', error); } } updateUrlWithNewFilters(filterArr) { this.filters = filterArr; this.getUpdatedUrl(); this.updateComponent(); } getUpdatedUrl() { this.filterText = this.utils.arrayToObject( this.filters, 'filterkey', 'value' ); // <-- TO update the queryparam which is passed in the filter of the api this.filterText = this.utils.makeFilterObj(this.filterText); /** * To change the url * with the deleted filter value along with the other existing paramter(ex-->tv:true) */ const updatedFilters = Object.assign( this.filterText, this.queryParamsWithoutFilter ); this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: updatedFilters }); /** * Finally after changing URL Link * api is again called with the updated filter */ this.filterText = this.utils.processFilterObj(this.filterText); } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } ngOnDestroy() { try { // pushes the current url to datastore this.dataStore.set('urlToRedirect', this.urlToRedirect); if (this.assetGroupSubscription) { this.assetGroupSubscription.unsubscribe(); } if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.complianceDropdownSubscription) { this.complianceDropdownSubscription.unsubscribe(); } if (this.issueListingSubscription) { this.issueListingSubscription.unsubscribe(); } if (this.issueFilterSubscription) { this.issueFilterSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
import type { Expression, Literal, RegExpLiteral } from "estree" import type { Rule, AST, SourceCode } from "eslint" import { getStaticValue } from "." import { dereferenceOwnedVariable, astRangeToLocation, getPropertyName, getStringValueRange, isRegexpLiteral, isStringLiteral, } from "./utils" /** * The range of a node/construct within a regexp pattern. */ export interface PatternRange { readonly start: number readonly end: number } /** * A range in source code that can be edited. */ export class PatternReplaceRange { public range: AST.Range public type: "RegExp" | "SingleQuotedString" | "DoubleQuotedString" public constructor(range: AST.Range, type: PatternReplaceRange["type"]) { if (!range || range[0] < 0 || range[0] > range[1]) { throw new Error(`Invalid range: ${JSON.stringify(range)}`) } this.range = range this.type = type } public static fromLiteral( node: Literal, sourceCode: SourceCode, nodeRange: PatternRange, range: PatternRange, ): PatternReplaceRange | null { if (!node.range) { return null } const start = range.start - nodeRange.start const end = range.end - nodeRange.start if (isRegexpLiteral(node)) { const nodeStart = node.range[0] + "/".length return new PatternReplaceRange( [nodeStart + start, nodeStart + end], "RegExp", ) } if (isStringLiteral(node)) { const astRange = getStringValueRange(sourceCode, node, start, end) if (astRange) { const quote = sourceCode.text[node.range[0]] return new PatternReplaceRange( astRange, quote === "'" ? "SingleQuotedString" : "DoubleQuotedString", ) } } return null } public getAstLocation(sourceCode: SourceCode): AST.SourceLocation { return astRangeToLocation(sourceCode, this.range) } public escape(text: string): string { if ( this.type === "DoubleQuotedString" || this.type === "SingleQuotedString" ) { const base = text .replace(/\\/gu, "\\\\") .replace(/\n/gu, "\\n") .replace(/\r/gu, "\\r") .replace(/\t/gu, "\\t") if (this.type === "DoubleQuotedString") { return base.replace(/"/gu, '\\"') } return base.replace(/'/gu, "\\'") } return text.replace(/\n/gu, "\\n").replace(/\r/gu, "\\r") } public replace(fixer: Rule.RuleFixer, text: string): Rule.Fix { return fixer.replaceTextRange(this.range, this.escape(text)) } public remove(fixer: Rule.RuleFixer): Rule.Fix { return fixer.removeRange(this.range) } public insertAfter(fixer: Rule.RuleFixer, text: string): Rule.Fix { return fixer.insertTextAfterRange(this.range, this.escape(text)) } public insertBefore(fixer: Rule.RuleFixer, text: string): Rule.Fix { return fixer.insertTextBeforeRange(this.range, this.escape(text)) } } class PatternSegment implements PatternRange { private readonly sourceCode: SourceCode public readonly node: Expression public readonly value: string public readonly start: number public readonly end: number public constructor( sourceCode: SourceCode, node: Expression, value: string, start: number, ) { this.sourceCode = sourceCode this.node = node this.value = value this.start = start this.end = start + value.length } public contains(range: PatternRange): boolean { return this.start <= range.start && range.end <= this.end } public getOwnedRegExpLiteral(): RegExpLiteral | null { if (isRegexpLiteral(this.node)) { return this.node } // e.g. /foo/.source if ( this.node.type === "MemberExpression" && this.node.object.type !== "Super" && isRegexpLiteral(this.node.object) && getPropertyName(this.node) === "source" ) { return this.node.object } return null } public getReplaceRange(range: PatternRange): PatternReplaceRange | null { if (!this.contains(range)) { return null } const regexp = this.getOwnedRegExpLiteral() if (regexp) { return PatternReplaceRange.fromLiteral( regexp, this.sourceCode, this, range, ) } if (this.node.type === "Literal") { // This will cover string literals return PatternReplaceRange.fromLiteral( this.node, this.sourceCode, this, range, ) } return null } public getAstRange(range: PatternRange): AST.Range { const replaceRange = this.getReplaceRange(range) if (replaceRange) { return replaceRange.range } return this.node.range! } } export interface RegExpValue { readonly source: string readonly flags: string /** * If the RegExp object is an owned RegExp literal, then this value will be * non-null. * * If the RegExp object is shared or not created a literal, this will be * `null`. */ readonly ownedNode: RegExpLiteral | null } export class PatternSource { private readonly sourceCode: SourceCode public readonly node: Expression public readonly value: string private readonly segments: readonly PatternSegment[] /** * If the pattern of a regexp is defined by a RegExp object, this value * will be non-null. This is the case for simple RegExp literals * (e.g. `/foo/`) and RegExp constructors (e.g. `RegExp(/foo/, "i")`). * * If the pattern source is defined by a string value * (e.g. `RegExp("foo")`), then this will be `null`. */ public readonly regexpValue: RegExpValue | null public isStringValue(): this is PatternSource & { readonly regexpValue: null } { return this.regexpValue === null } private constructor( sourceCode: SourceCode, node: Expression, value: string, segments: readonly PatternSegment[], regexpValue: RegExpValue | null, ) { this.sourceCode = sourceCode this.node = node this.value = value this.segments = segments this.regexpValue = regexpValue } public static fromExpression( context: Rule.RuleContext, expression: Expression, ): PatternSource | null { // eslint-disable-next-line no-param-reassign -- x expression = dereferenceOwnedVariable(context, expression) if (isRegexpLiteral(expression)) { return PatternSource.fromRegExpLiteral(context, expression) } const sourceCode = context.getSourceCode() const flat = flattenPlus(context, expression) const items: PatternSegment[] = [] let value = "" for (const e of flat) { const staticValue = getStaticValue(context, e) if (!staticValue) { return null } if (flat.length === 1 && staticValue.value instanceof RegExp) { // This means we have a non-owned reference to something that // evaluates to an RegExp object return PatternSource.fromRegExpObject( context, e, staticValue.value.source, staticValue.value.flags, ) } if (typeof staticValue.value !== "string") { return null } items.push( new PatternSegment( sourceCode, e, staticValue.value, value.length, ), ) value += staticValue.value } return new PatternSource(sourceCode, expression, value, items, null) } private static fromRegExpObject( context: Rule.RuleContext, expression: Expression, source: string, flags: string, ): PatternSource { const sourceCode = context.getSourceCode() return new PatternSource( sourceCode, expression, source, [new PatternSegment(sourceCode, expression, source, 0)], { source, flags, ownedNode: null, }, ) } public static fromRegExpLiteral( context: Rule.RuleContext, expression: RegExpLiteral, ): PatternSource { const sourceCode = context.getSourceCode() return new PatternSource( sourceCode, expression, expression.regex.pattern, [ new PatternSegment( sourceCode, expression, expression.regex.pattern, 0, ), ], { source: expression.regex.pattern, flags: expression.regex.flags, ownedNode: expression, }, ) } private getSegment(range: PatternRange): PatternSegment | null { const segments = this.getSegments(range) if (segments.length === 1) { return segments[0] } return null } private getSegments(range: PatternRange): PatternSegment[] { return this.segments.filter( (item) => item.start < range.end && range.start < item.end, ) } public getReplaceRange(range: PatternRange): PatternReplaceRange | null { const segment = this.getSegment(range) if (segment) { return segment.getReplaceRange(range) } return null } /** * Returns an approximate AST range for the given pattern range. * * DO NOT use this in fixes to edit source code. Use * {@link PatternSource.getReplaceRange} instead. */ public getAstRange(range: PatternRange): AST.Range { const overlapping = this.getSegments(range) if (overlapping.length === 1) { return overlapping[0].getAstRange(range) } // the input range comes from multiple sources // union all their ranges let min = Infinity let max = -Infinity for (const item of overlapping) { min = Math.min(min, item.node.range![0]) max = Math.max(max, item.node.range![1]) } if (min > max) { return this.node.range! } return [min, max] } /** * Returns an approximate AST source location for the given pattern range. * * DO NOT use this in fixes to edit source code. Use * {@link PatternSource.getReplaceRange} instead. */ public getAstLocation(range: PatternRange): AST.SourceLocation { return astRangeToLocation(this.sourceCode, this.getAstRange(range)) } /** * Returns all RegExp literals nodes that are owned by this pattern. * * This means that the returned RegExp literals are only used to create * this pattern and for nothing else. */ public getOwnedRegExpLiterals(): readonly RegExpLiteral[] { const literals: RegExpLiteral[] = [] for (const segment of this.segments) { const regexp = segment.getOwnedRegExpLiteral() if (regexp) { literals.push(regexp) } } return literals } } /** * Flattens binary + expressions into an array. * * This will automatically dereference owned constants. */ function flattenPlus(context: Rule.RuleContext, e: Expression): Expression[] { if (e.type === "BinaryExpression" && e.operator === "+") { return [ ...flattenPlus(context, e.left), ...flattenPlus(context, e.right), ] } const deRef = dereferenceOwnedVariable(context, e) if (deRef !== e) { return flattenPlus(context, deRef) } return [e] }
the_stack
import { app, BrowserWindow, nativeTheme, systemPreferences, dialog } from "electron"; import ServerLog from "electron-log"; import * as process from "process"; import { EventEmitter } from "events"; import * as macosVersion from "macos-version"; // Configuration/Filesytem Imports import { Queue } from "@server/databases/server/entity/Queue"; import { FileSystem } from "@server/fileSystem"; import { DEFAULT_POLL_FREQUENCY_MS } from "@server/constants"; // Database Imports import { ServerRepository, ServerConfigChange } from "@server/databases/server"; import { MessageRepository } from "@server/databases/imessage"; import { ContactRepository } from "@server/databases/contacts"; import { IncomingMessageListener, OutgoingMessageListener, GroupChangeListener } from "@server/databases/imessage/listeners"; import { Message, getMessageResponse } from "@server/databases/imessage/entity/Message"; import { ChangeListener } from "@server/databases/imessage/listeners/changeListener"; // Service Imports import { HttpService, FCMService, AlertService, CaffeinateService, NgrokService, LocalTunnelService, NetworkService, QueueService, IPCService, UpdateService } from "@server/services"; import { EventCache } from "@server/eventCache"; import { runTerminalScript, openSystemPreferences } from "@server/fileSystem/scripts"; import { ActionHandler } from "./helpers/actions"; import { insertChatParticipants, sanitizeStr } from "./helpers/utils"; import { Proxy } from "./services/proxy"; import { BlueBubblesHelperService } from "./services/helperProcess"; const findProcess = require("find-process"); const osVersion = macosVersion(); // Set the log format const logFormat = "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}"; ServerLog.transports.console.format = logFormat; ServerLog.transports.file.format = logFormat; /** * Create a singleton for the server so that it can be referenced everywhere. * Plus, we only want one instance of it running at all times. */ let server: BlueBubblesServer = null; export const Server = (win: BrowserWindow = null) => { // If we already have a server, update the window (if not null) and return // the same instance if (server) { if (win) server.window = win; return server; } server = new BlueBubblesServer(win); return server; }; /** * Main entry point for the back-end server * This will handle all services and helpers that get spun * up when running the application. */ class BlueBubblesServer extends EventEmitter { window: BrowserWindow; repo: ServerRepository; iMessageRepo: MessageRepository; contactsRepo: ContactRepository; httpService: HttpService; privateApiHelper: BlueBubblesHelperService; fcm: FCMService; alerter: AlertService; networkChecker: NetworkService; caffeinate: CaffeinateService; updater: UpdateService; queue: QueueService; proxyServices: Proxy[]; actionHandler: ActionHandler; chatListeners: ChangeListener[]; eventCache: EventCache; hasDiskAccess: boolean; hasAccessibilityAccess: boolean; hasSetup: boolean; hasStarted: boolean; notificationCount: number; isRestarting: boolean; isStopping: boolean; /** * Constructor to just initialize everything to null pretty much * * @param window The browser window associated with the Electron app */ constructor(window: BrowserWindow) { super(); this.window = window; // Databases this.repo = null; this.iMessageRepo = null; this.contactsRepo = null; // Other helpers this.eventCache = null; this.chatListeners = []; this.actionHandler = null; // Services this.httpService = null; this.privateApiHelper = null; this.fcm = null; this.caffeinate = null; this.networkChecker = null; this.queue = null; this.proxyServices = []; this.updater = null; this.hasDiskAccess = true; this.hasAccessibilityAccess = false; this.hasSetup = false; this.hasStarted = false; this.notificationCount = 0; this.isRestarting = false; this.isStopping = false; } emitToUI(event: string, data: any) { try { if (this.window) this.window.webContents.send(event, data); } catch { /* Ignore errors here */ } } /** * Handler for sending logs. This allows us to also route * the logs to the main Electron window * * @param message The message to print * @param type The log type */ log(message: any, type?: "log" | "error" | "warn" | "debug") { switch (type) { case "error": ServerLog.error(message); AlertService.create("error", message); this.notificationCount += 1; break; case "debug": ServerLog.debug(message); break; case "warn": ServerLog.warn(message); AlertService.create("warn", message); this.notificationCount += 1; break; case "log": default: ServerLog.log(message); } if (["error", "warn"].includes(type)) { app.setBadgeCount(this.notificationCount); } this.emitToUI("new-log", { message, type: type ?? "log" }); } /** * Officially starts the server. First, runs the setup, * then starts all of the services required for the server */ async start(): Promise<void> { if (!this.hasStarted) { this.getTheme(); await this.setupServer(); // Do some pre-flight checks await this.preChecks(); if (this.isRestarting) return; this.log("Starting Configuration IPC Listeners.."); IPCService.startConfigIpcListeners(); } try { this.log("Launching Services.."); await this.setupServices(); } catch (ex: any) { this.log("There was a problem launching the Server listeners.", "error"); } await this.startServices(); await this.postChecks(); // Let everyone know the setup is complete this.emit("setup-complete"); // After setup is complete, start the update checker try { this.log("Initializing Update Service.."); this.updater = new UpdateService(this.window); const check = Server().repo.getConfig("check_for_updates") as boolean; if (check) { this.updater.start(); this.updater.checkForUpdate(); } } catch (ex: any) { this.log("There was a problem initializing the update service.", "error"); } } /** * Performs the initial setup for the server. * Mainly, instantiation of a bunch of classes/handlers */ private async setupServer(): Promise<void> { this.log("Performing initial setup..."); this.log("Initializing server database..."); this.repo = new ServerRepository(); this.repo.on("config-update", (args: ServerConfigChange) => this.handleConfigUpdate(args)); await this.repo.initialize(); // Load notification count try { this.log("Initializing alert service..."); const alerts = (await AlertService.find()).filter(item => !item.isRead); this.notificationCount = alerts.length; } catch (ex: any) { this.log("Failed to get initial notification count. Skipping.", "warn"); } // Setup lightweight message cache this.log("Initializing event cache..."); this.eventCache = new EventCache(); try { this.log("Initializing filesystem..."); FileSystem.setup(); } catch (ex: any) { this.log(`Failed to setup Filesystem! ${ex.message}`, "error"); } this.log("Initializing caffeinate service..."); await this.setupCaffeinate(); try { this.log("Initializing queue service..."); this.queue = new QueueService(); } catch (ex: any) { this.log(`Failed to setup queue service! ${ex.message}`, "error"); } try { this.log("Initializing connection to Google FCM..."); this.fcm = new FCMService(); } catch (ex: any) { this.log(`Failed to setup Google FCM service! ${ex.message}`, "error"); } try { this.log("Initializing network service..."); this.networkChecker = new NetworkService(); this.networkChecker.on("status-change", connected => { if (connected) { this.log("Re-connected to network!"); this.restartProxyServices(); } else { this.log("Disconnected from network!"); } }); this.networkChecker.start(); } catch (ex: any) { this.log(`Failed to setup network service! ${ex.message}`, "error"); } } async restartProxyServices() { for (const i of this.proxyServices) { await i.restart(); } } async stopProxyServices() { for (const i of this.proxyServices) { await i.disconnect(); } } private async preChecks(): Promise<void> { this.log("Running pre-start checks..."); // Set the dock icon according to the config this.setDockIcon(); try { // Restart via terminal if configured const restartViaTerminal = Server().repo.getConfig("start_via_terminal") as boolean; const parentProc = await findProcess("pid", process.ppid); const parentName = parentProc && parentProc.length > 0 ? parentProc[0].name : null; // Restart if enabled and the parent process is the app being launched if (restartViaTerminal && (!parentProc[0].name || parentName === "launchd")) { this.isRestarting = true; Server().log("Restarting via terminal after post-check (configured)"); await this.restartViaTerminal(); } } catch (ex: any) { Server().log(`Failed to restart via terminal!\n${ex}`); } // Log some server metadata this.log(`Server Metadata -> macOS Version: v${osVersion}`, "debug"); this.log(`Server Metadata -> Local Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`, "debug"); // Check if on Big Sur. If we are, then create a log/alert saying that const isBigSur = macosVersion.isGreaterThanOrEqualTo("11.0"); if (isBigSur) { this.log("Warning: macOS Big Sur does NOT support creating chats due to API limitations!", "warn"); } this.log("Finished pre-start checks..."); } private async postChecks(): Promise<void> { this.log("Running post-start checks..."); // Make sure a password is set const password = this.repo.getConfig("password") as string; const tutorialFinished = this.repo.getConfig("tutorial_is_done") as boolean; if (tutorialFinished && (!password || password.length === 0)) { dialog.showMessageBox(this.window, { type: "warning", buttons: ["OK"], title: "BlueBubbles Warning", message: "No Password Set!", detail: `No password is currently set. BlueBubbles will not function correctly without one. ` + `Please go to the configuration page, fill in a password, and save the configuration.` }); } this.setDockIcon(); this.log("Finished post-start checks..."); } private setDockIcon() { if (!this.repo || !this.repo.db) return; const hideDockIcon = this.repo.getConfig("hide_dock_icon") as boolean; if (hideDockIcon) { app.dock.hide(); app.show(); } else { app.dock.show(); } } /** * Sets up the caffeinate service */ private async setupCaffeinate(): Promise<void> { try { this.caffeinate = new CaffeinateService(); if (this.repo.getConfig("auto_caffeinate")) { this.caffeinate.start(); } } catch (ex: any) { this.log(`Failed to setup caffeinate service! ${ex.message}`, "error"); } } /** * Handles a configuration change * * @param prevConfig The previous configuration * @param nextConfig The current configuration */ private async handleConfigUpdate({ prevConfig, nextConfig }: ServerConfigChange) { // If the socket port changed, disconnect and reconnect let proxiesRestarted = false; if (prevConfig.socket_port !== nextConfig.socket_port) { await this.restartProxyServices(); if (this.httpService) await this.httpService.restart(); proxiesRestarted = true; } // If the ngrok URL is different, emit the change to the listeners if (prevConfig.server_address !== nextConfig.server_address) { if (this.httpService) await this.emitMessage("new-server", nextConfig.server_address, "high"); if (this.fcm) await this.fcm.setServerUrl(nextConfig.server_address as string); } // If the ngrok API key is different, restart the ngrok process if (prevConfig.ngrok_key !== nextConfig.ngrok_key && !proxiesRestarted) { await this.restartProxyServices(); } // If the dock style changes if (prevConfig.hide_dock_icon !== nextConfig.hide_dock_icon) { this.setDockIcon(); } this.emitToUI("config-update", nextConfig); } /** * Emits a notification to to your connected devices over FCM and socket * * @param type The type of notification * @param data Associated data with the notification (as a string) */ async emitMessage(type: string, data: any, priority: "normal" | "high" = "normal") { this.httpService.socketServer.emit(type, data); // Send notification to devices if (FCMService.getApp()) { const devices = await this.repo.devices().find(); if (!devices || devices.length === 0) return; const notifData = JSON.stringify(data); await this.fcm.sendNotification( devices.map(device => device.identifier), { type, data: notifData }, priority ); } } private getTheme() { nativeTheme.on("updated", () => { this.setTheme(nativeTheme.shouldUseDarkColors); }); } private setTheme(shouldUseDarkColors: boolean) { if (shouldUseDarkColors === true) { this.emitToUI("theme-update", "dark"); } else { this.emitToUI("theme-update", "light"); } } /** * Starts the chat listener service. This service will listen for new * iMessages from your chat database. Anytime there is a new message, * we will emit a message to the socket, as well as the FCM server */ private startChatListener() { if (!this.iMessageRepo?.db) { AlertService.create( "info", "Restart the app once 'Full Disk Access' and 'Accessibility' permissions are enabled" ); return; } // Create a listener to listen for new/updated messages const incomingMsgListener = new IncomingMessageListener( this.iMessageRepo, this.eventCache, DEFAULT_POLL_FREQUENCY_MS ); const outgoingMsgListener = new OutgoingMessageListener( this.iMessageRepo, this.eventCache, DEFAULT_POLL_FREQUENCY_MS * 2 ); // No real rhyme or reason to multiply this by 2. It's just not as much a priority const groupEventListener = new GroupChangeListener(this.iMessageRepo, DEFAULT_POLL_FREQUENCY_MS * 2); // Add to listeners this.chatListeners = [outgoingMsgListener, incomingMsgListener, groupEventListener]; /** * Message listener for when we find matches for a given sent message */ outgoingMsgListener.on("message-match", async (item: { tempGuid: string; message: Message }) => { const text = item.message.cacheHasAttachments ? `Attachment: ${sanitizeStr(item.message.text) || "<No Text>"}` : item.message.text; this.log(`Message match found for text, [${text}]`); const newMessage = await insertChatParticipants(item.message); const resp = await getMessageResponse(newMessage); resp.tempGuid = item.tempGuid; // We are emitting this as a new message, the only difference being the included tempGuid await this.emitMessage("new-message", resp); }); /** * Message listener for my messages only. We need this because messages from ourselves * need to be fully sent before forwarding to any clients. If we emit a notification * before the message is sent, it will cause a duplicate. */ outgoingMsgListener.on("new-entry", async (item: Message) => { const text = item.cacheHasAttachments ? `Attachment: ${sanitizeStr(item.text) || "<No Text>"}` : item.text; this.log(`New message from [You]: [${(text ?? "<No Text>").substring(0, 50)}]`); const newMessage = await insertChatParticipants(item); // Emit it to the socket and FCM devices await this.emitMessage("new-message", await getMessageResponse(newMessage)); }); /** * Message listener checking for updated messages. This means either the message's * delivered date or read date have changed since the last time we checked the database. */ outgoingMsgListener.on("updated-entry", async (item: Message) => { // ATTENTION: If "from" is null, it means you sent the message from a group chat // Check the isFromMe key prior to checking the "from" key const from = item.isFromMe ? "You" : item.handle?.id; const time = item.dateDelivered || item.dateRead; const updateType = item.dateRead ? "Text Read" : "Text Delivered"; const text = item.cacheHasAttachments ? `Attachment: ${sanitizeStr(item.text) || "<No Text>"}` : item.text; this.log( `Updated message from [${from}]: [${(text ?? "<No Text>").substring( 0, 50 )}] - [${updateType} -> ${time.toLocaleString()}]` ); const newMessage = await insertChatParticipants(item); // Emit it to the socket and FCM devices await this.emitMessage("updated-message", await getMessageResponse(newMessage)); }); /** * Message listener for outgoing messages that timedout */ outgoingMsgListener.on("message-timeout", async (item: Queue) => { const text = (item.text ?? "").startsWith(item.tempGuid) ? "image" : `text, [${item.text ?? "<No Text>"}]`; this.log(`Message send timeout for ${text}`, "warn"); await this.emitMessage("message-timeout", item); }); /** * Message listener for messages that have errored out */ outgoingMsgListener.on("message-send-error", async (item: Message) => { const text = item.cacheHasAttachments ? `Attachment: ${(item.text ?? " ").slice(1, item.text.length) || "<No Text>"}` : item.text; this.log(`Failed to send message: [${(text ?? "<No Text>").substring(0, 50)}]`); // Emit it to the socket and FCM devices /** * ERROR CODES: * 4: Message Timeout */ await this.emitMessage("message-send-error", await getMessageResponse(item)); }); /** * Message listener for new messages not from yourself. See 'myMsgListener' comment * for why we separate them out into two separate listeners. */ incomingMsgListener.on("new-entry", async (item: Message) => { const text = item.cacheHasAttachments ? `Attachment: ${(item.text ?? " ").slice(1, item.text.length) || "<No Text>"}` : item.text; this.log(`New message from [${item.handle?.id}]: [${(text ?? "<No Text>").substring(0, 50)}]`); const newMessage = await insertChatParticipants(item); // Emit it to the socket and FCM devices await this.emitMessage("new-message", await getMessageResponse(newMessage), "high"); }); groupEventListener.on("name-change", async (item: Message) => { this.log(`Group name for [${item.cacheRoomnames}] changed to [${item.groupTitle}]`); await this.emitMessage("group-name-change", await getMessageResponse(item)); }); groupEventListener.on("participant-removed", async (item: Message) => { const from = item.isFromMe || item.handleId === 0 ? "You" : item.handle?.id; this.log(`[${from}] removed [${item.otherHandle}] from [${item.cacheRoomnames}]`); await this.emitMessage("participant-removed", await getMessageResponse(item)); }); groupEventListener.on("participant-added", async (item: Message) => { const from = item.isFromMe || item.handleId === 0 ? "You" : item.handle?.id; this.log(`[${from}] added [${item.otherHandle}] to [${item.cacheRoomnames}]`); await this.emitMessage("participant-added", await getMessageResponse(item)); }); groupEventListener.on("participant-left", async (item: Message) => { const from = item.isFromMe || item.handleId === 0 ? "You" : item.handle?.id; this.log(`[${from}] left [${item.cacheRoomnames}]`); await this.emitMessage("participant-left", await getMessageResponse(item)); }); outgoingMsgListener.on("error", (error: Error) => this.log(error.message, "error")); incomingMsgListener.on("error", (error: Error) => this.log(error.message, "error")); groupEventListener.on("error", (error: Error) => this.log(error.message, "error")); } /** * Helper method for running setup on the message services */ async setupServices() { if (this.hasSetup) return; try { this.log("Connecting to iMessage database..."); this.iMessageRepo = new MessageRepository(); await this.iMessageRepo.initialize(); } catch (ex: any) { this.log(ex, "error"); const dialogOpts = { type: "error", buttons: ["Restart", "Open System Preferences", "Ignore"], title: "BlueBubbles Error", message: "Full-Disk Access Permission Required!", detail: `In order to function correctly, BlueBubbles requires full-disk access. ` + `Please enable Full-Disk Access in System Preferences > Security & Privacy.` }; dialog.showMessageBox(this.window, dialogOpts).then(returnValue => { if (returnValue.response === 0) { this.relaunch(); } else if (returnValue.response === 1) { FileSystem.executeAppleScript(openSystemPreferences()); app.quit(); } }); } try { this.log("Connecting to Contacts database..."); this.contactsRepo = new ContactRepository(); await this.contactsRepo.initialize(); } catch (ex: any) { this.log(`Failed to connect to Contacts database! Please enable Full Disk Access!`, "error"); } try { this.log("Initializing up sockets..."); this.httpService = new HttpService(); } catch (ex: any) { this.log(`Failed to setup socket service! ${ex.message}`, "error"); } const privateApiEnabled = this.repo.getConfig("enable_private_api") as boolean; if (privateApiEnabled) { try { this.log("Initializing helper service..."); this.privateApiHelper = new BlueBubblesHelperService(); } catch (ex: any) { this.log(`Failed to setup helper service! ${ex.message}`, "error"); } } this.log("Checking Permissions..."); // Log if we dont have accessibility access if (systemPreferences.isTrustedAccessibilityClient(false) === true) { this.hasAccessibilityAccess = true; this.log("Accessibility permissions are enabled"); } else { this.log("Accessibility permissions are required for certain actions!", "error"); } // Log if we dont have accessibility access if (this.iMessageRepo?.db) { this.hasDiskAccess = true; this.log("Full-disk access permissions are enabled"); } else { this.log("Full-disk access permissions are required!", "error"); } this.hasSetup = true; } /** * Helper method for starting the message services * */ async startServices() { // Start the IPC listener first for the UI if (this.hasDiskAccess && !this.hasStarted) IPCService.startIpcListener(); try { this.log("Connecting to proxies..."); this.proxyServices = [new NgrokService(), new LocalTunnelService()]; await this.restartProxyServices(); } catch (ex: any) { this.log(`Failed to connect to Ngrok! ${ex.message}`, "error"); } try { this.log("Starting FCM service..."); await this.fcm.start(); } catch (ex: any) { this.log(`Failed to start FCM service! ${ex.message}`, "error"); } this.log("Starting socket service..."); this.httpService.restart(); const privateApiEnabled = this.repo.getConfig("enable_private_api") as boolean; if (privateApiEnabled) { if (this.privateApiHelper === null) { this.privateApiHelper = new BlueBubblesHelperService(); } this.log("Starting helper listener..."); this.privateApiHelper.start(); } if (this.hasDiskAccess && this.chatListeners.length === 0) { this.log("Starting chat listener..."); this.startChatListener(); } this.hasStarted = true; } private removeChatListeners() { // Remove all listeners this.log("Removing chat listeners..."); for (const i of this.chatListeners) i.stop(); this.chatListeners = []; } /** * Restarts the server */ async hotRestart() { this.log("Restarting the server..."); // Remove all listeners this.removeChatListeners(); // Disconnect & reconnect to the iMessage DB if (this.iMessageRepo.db.isConnected) { this.log("Reconnecting to iMessage database..."); await this.iMessageRepo.db.close(); await this.iMessageRepo.db.connect(); } // Start the server up again await this.start(); } async relaunch() { this.isRestarting = true; // Close everything gracefully await this.stopServices(); // Relaunch the process app.relaunch({ args: process.argv.slice(1).concat(["--relaunch"]) }); app.exit(0); } async stopServices() { this.isStopping = true; Server().log("Stopping all services..."); try { this.removeChatListeners(); this.removeAllListeners(); } catch (ex: any) { Server().log(`There was an issue stopping listeners!\n${ex}`); } try { await this.stopProxyServices(); } catch (ex: any) { Server().log(`There was an issue stopping Ngrok!\n${ex}`); } try { if (this?.httpService?.socketServer) this.httpService.socketServer.close(); } catch (ex: any) { Server().log(`There was an issue stopping the socket!\n${ex}`); } try { if (this.networkChecker) this.networkChecker.stop(); } catch (ex: any) { Server().log(`There was an issue stopping the network checker service!\n${ex}`); } try { FCMService.stop(); } catch (ex: any) { Server().log(`There was an issue stopping the FCM service!\n${ex}`); } try { await this.privateApiHelper?.stop(); } catch (ex: any) { Server().log(`There was an issue stopping the Private API listener!\n${ex}`); } try { if (this.caffeinate) this.caffeinate.stop(); } catch (ex: any) { Server().log(`There was an issue stopping the caffeinate service!\n${ex}`); } try { await this.contactsRepo?.db?.close(); } catch (ex: any) { Server().log(`There was an issue stopping the contacts database connection!\n${ex}`); } try { await this.iMessageRepo?.db?.close(); } catch (ex: any) { Server().log(`There was an issue stopping the iMessage database connection!\n${ex}`); } try { if (this.repo?.db?.isConnected) { await this.repo?.db?.close(); } } catch (ex: any) { Server().log(`There was an issue stopping the server database connection!\n${ex}`); } } async restartViaTerminal() { this.isRestarting = true; // Close everything gracefully await this.stopServices(); // Kick off the restart script FileSystem.executeAppleScript(runTerminalScript(process.execPath)); // Exit the current instance app.exit(0); } }
the_stack
import BN from 'bn.js' import Web3 from 'web3' import { BlockTransactionString, FeeHistoryResult } from 'web3-eth' import { EventData, PastEventOptions } from 'web3-eth-contract' import { PrefixedHexString, toBuffer } from 'ethereumjs-util' import { TxOptions } from '@ethereumjs/tx' import { toBN, toHex } from 'web3-utils' import { BlockNumber, Transaction, TransactionReceipt } from 'web3-core' import abi from 'web3-eth-abi' import { RelayRequest } from './EIP712/RelayRequest' import paymasterAbi from './interfaces/IPaymaster.json' import relayHubAbi from './interfaces/IRelayHub.json' import forwarderAbi from './interfaces/IForwarder.json' import stakeManagerAbi from './interfaces/IStakeManager.json' import penalizerAbi from './interfaces/IPenalizer.json' import gsnRecipientAbi from './interfaces/IERC2771Recipient.json' import relayRegistrarAbi from './interfaces/IRelayRegistrar.json' import iErc20TokenAbi from './interfaces/IERC20Token.json' import { VersionsManager } from './VersionsManager' import { replaceErrors } from './ErrorReplacerJSON' import { LoggerInterface } from './LoggerInterface' import { PaymasterGasAndDataLimits, address2topic, calculateCalldataBytesZeroNonzero, decodeRevertReason, errorAsBoolean, event2topic, formatTokenAmount, packRelayUrlForRegistrar, splitRelayUrlForRegistrar, toNumber } from './Utils' import { IERC20TokenInstance, IERC2771RecipientInstance, IForwarderInstance, IPaymasterInstance, IPenalizerInstance, IRelayHubInstance, IRelayRegistrarInstance, IStakeManagerInstance } from '@opengsn/contracts/types/truffle-contracts' import { Address, EventName, IntString, ObjectMap, SemVerString, Web3ProviderBaseInterface } from './types/Aliases' import { GsnTransactionDetails } from './types/GsnTransactionDetails' import { Contract, TruffleContract } from './LightTruffleContract' import { gsnRequiredVersion, gsnRuntimeVersion } from './Version' import Common from '@ethereumjs/common' import { GSNContractsDeployment } from './GSNContractsDeployment' import { ActiveManagerEvents, HubUnauthorized, RelayRegisteredEventInfo, RelayServerRegistered, RelayWorkersAdded, StakeInfo, StakePenalized, StakeUnlocked } from './types/GSNContractsDataTypes' import { sleep } from './Utils.js' import { Environment } from './Environments' import { RelayHubConfiguration } from './types/RelayHubConfiguration' import { RelayTransactionRequest } from './types/RelayTransactionRequest' import { BigNumber } from 'bignumber.js' import { TransactionType } from './types/TransactionType' import { constants } from './Constants' import TransactionDetails = Truffle.TransactionDetails export interface ConstructorParams { provider: Web3ProviderBaseInterface logger: LoggerInterface versionManager?: VersionsManager deployment?: GSNContractsDeployment maxPageSize: number environment: Environment } export interface RelayCallABI { signature: PrefixedHexString relayRequest: RelayRequest approvalData: PrefixedHexString maxAcceptanceBudget: PrefixedHexString } export function asRelayCallAbi (r: RelayTransactionRequest): RelayCallABI { return { relayRequest: r.relayRequest, signature: r.metadata.signature, approvalData: r.metadata.approvalData, maxAcceptanceBudget: r.metadata.maxAcceptanceBudget } } interface ManagerStakeStatus { isStaked: boolean errorMessage: string | null } export interface ERC20TokenMetadata { tokenName: string tokenSymbol: string tokenDecimals: BN } export interface ViewCallVerificationResult { paymasterAccepted: boolean returnValue: string reverted: boolean } export class ContractInteractor { private readonly IPaymasterContract: Contract<IPaymasterInstance> private readonly IRelayHubContract: Contract<IRelayHubInstance> private readonly IForwarderContract: Contract<IForwarderInstance> private readonly IStakeManager: Contract<IStakeManagerInstance> private readonly IPenalizer: Contract<IPenalizerInstance> private readonly IERC2771Recipient: Contract<IERC2771RecipientInstance> private readonly IRelayRegistrar: Contract<IRelayRegistrarInstance> private readonly IERC20Token: Contract<IERC20TokenInstance> private paymasterInstance!: IPaymasterInstance relayHubInstance!: IRelayHubInstance relayHubConfiguration!: RelayHubConfiguration private forwarderInstance!: IForwarderInstance private stakeManagerInstance!: IStakeManagerInstance penalizerInstance!: IPenalizerInstance private erc2771RecipientInstance?: IERC2771RecipientInstance relayRegistrar!: IRelayRegistrarInstance erc20Token!: IERC20TokenInstance private readonly relayCallMethod: any readonly web3: Web3 private readonly provider: Web3ProviderBaseInterface private deployment: GSNContractsDeployment private readonly versionManager: VersionsManager private readonly logger: LoggerInterface private readonly maxPageSize: number private lastBlockNumber: number private rawTxOptions?: TxOptions chainId!: number private networkId?: number private networkType?: string private paymasterVersion?: SemVerString readonly environment: Environment transactionType: TransactionType = TransactionType.LEGACY constructor ( { maxPageSize, provider, versionManager, logger, environment, deployment = {} }: ConstructorParams) { this.maxPageSize = maxPageSize this.logger = logger this.versionManager = versionManager ?? new VersionsManager(gsnRuntimeVersion, gsnRequiredVersion) this.web3 = new Web3(provider as any) this.deployment = deployment this.provider = provider this.lastBlockNumber = 0 this.environment = environment this.IPaymasterContract = TruffleContract({ contractName: 'IPaymaster', abi: paymasterAbi }) this.IRelayHubContract = TruffleContract({ contractName: 'IRelayHub', abi: relayHubAbi }) this.IForwarderContract = TruffleContract({ contractName: 'IForwarder', abi: forwarderAbi }) this.IStakeManager = TruffleContract({ contractName: 'IStakeManager', abi: stakeManagerAbi }) this.IPenalizer = TruffleContract({ contractName: 'IPenalizer', abi: penalizerAbi }) this.IERC2771Recipient = TruffleContract({ contractName: 'IERC2771Recipient', abi: gsnRecipientAbi }) this.IRelayRegistrar = TruffleContract({ contractName: 'IRelayRegistrar', abi: relayRegistrarAbi }) this.IERC20Token = TruffleContract({ contractName: 'IERC20Token', abi: iErc20TokenAbi }) this.IStakeManager.setProvider(this.provider, undefined) this.IRelayHubContract.setProvider(this.provider, undefined) this.IPaymasterContract.setProvider(this.provider, undefined) this.IForwarderContract.setProvider(this.provider, undefined) this.IPenalizer.setProvider(this.provider, undefined) this.IERC2771Recipient.setProvider(this.provider, undefined) this.IRelayRegistrar.setProvider(this.provider, undefined) this.IERC20Token.setProvider(this.provider, undefined) this.relayCallMethod = this.IRelayHubContract.createContract('').methods.relayCall } async init (): Promise<ContractInteractor> { const initStartTimestamp = Date.now() this.logger.debug('interactor init start') if (this.rawTxOptions != null) { throw new Error('init was already called') } const block = await this.web3.eth.getBlock('latest').catch((e: Error) => { throw new Error(`getBlock('latest') failed: ${e.message}\nCheck your internet/ethereum node connection`) }) if (block.baseFeePerGas != null) { this.transactionType = TransactionType.TYPE_TWO } await this._resolveDeployment() await this._initializeContracts() await this._validateCompatibility() await this._initializeNetworkParams() if (this.relayHubInstance != null) { this.relayHubConfiguration = await this.relayHubInstance.getConfiguration() } this.logger.debug(`client init finished in ${Date.now() - initStartTimestamp} ms`) return this } async _initializeNetworkParams (): Promise<void> { this.chainId = await this.web3.eth.getChainId() this.networkId = await this.web3.eth.net.getId() this.networkType = await this.web3.eth.net.getNetworkType() // networkType === 'private' means we're on ganache, and ethereumjs-tx.Transaction doesn't support that chain type this.rawTxOptions = getRawTxOptions(this.chainId, this.networkId, this.networkType) } async _resolveDeployment (): Promise<void> { if (this.deployment.paymasterAddress != null && this.deployment.relayHubAddress != null) { this.logger.warn('Already resolved!') return } if (this.deployment.paymasterAddress != null) { await this._resolveDeploymentFromPaymaster(this.deployment.paymasterAddress) } else if (this.deployment.relayHubAddress != null) { if (!await this.isContractDeployed(this.deployment.relayHubAddress)) { throw new Error(`RelayHub: no contract at address ${this.deployment.relayHubAddress}`) } // TODO: this branch shouldn't exist as it's only used by the Server and can lead to broken Client configuration await this._resolveDeploymentFromRelayHub(this.deployment.relayHubAddress) } else { this.logger.info(`Contract interactor cannot resolve a full deployment from the following input: ${JSON.stringify(this.deployment)}`) } } async _resolveDeploymentFromPaymaster (paymasterAddress: Address): Promise<void> { this.paymasterInstance = await this._createPaymaster(paymasterAddress) const [ relayHubAddress, forwarderAddress, paymasterVersion ] = await Promise.all([ this.paymasterInstance.getRelayHub().catch((e: Error) => { throw new Error(`Not a paymaster contract: ${e.message}`) }), this.paymasterInstance.getTrustedForwarder().catch( (e: Error) => { throw new Error(`paymaster has no trustedForwarder(): ${e.message}`) }), this.paymasterInstance.versionPaymaster().catch((e: Error) => { throw new Error(`Not a paymaster contract: ${e.message}`) }).then( (version: string) => { this._validateVersion(version, 'Paymaster') return version }) ]) this.deployment.relayHubAddress = relayHubAddress this.deployment.forwarderAddress = forwarderAddress this.paymasterVersion = paymasterVersion await this._resolveDeploymentFromRelayHub(relayHubAddress) } async _resolveDeploymentFromRelayHub (relayHubAddress: Address): Promise<void> { this.relayHubInstance = await this._createRelayHub(relayHubAddress) const [stakeManagerAddress, penalizerAddress, relayRegistrarAddress] = await Promise.all([ this._hubStakeManagerAddress(), this._hubPenalizerAddress(), this._hubRelayRegistrarAddress() ]) this.deployment.relayHubAddress = relayHubAddress this.deployment.stakeManagerAddress = stakeManagerAddress this.deployment.penalizerAddress = penalizerAddress this.deployment.relayRegistrarAddress = relayRegistrarAddress } async _validateCompatibility (): Promise<void> { if (this.deployment == null || this.relayHubInstance == null) { return } const hub = this.relayHubInstance const version = await hub.versionHub() this._validateVersion(version, 'RelayHub') } _validateVersion (version: string, contractName: string): void { const versionSatisfied = this.versionManager.isRequiredVersionSatisfied(version) if (!versionSatisfied) { throw new Error( `Provided ${contractName} version(${version}) does not satisfy the requirement(${this.versionManager.requiredVersionRange})`) } } async _initializeContracts (): Promise<void> { // TODO: do we need all this "differential" deployment ? // any sense NOT to initialize some components, or NOT to read them all from the PM and then RH ? if (this.relayHubInstance == null && this.deployment.relayHubAddress != null) { this.relayHubInstance = await this._createRelayHub(this.deployment.relayHubAddress) } if (this.relayRegistrar == null && this.deployment.relayRegistrarAddress != null) { this.relayRegistrar = await this._createRelayRegistrar(this.deployment.relayRegistrarAddress) } if (this.paymasterInstance == null && this.deployment.paymasterAddress != null) { this.paymasterInstance = await this._createPaymaster(this.deployment.paymasterAddress) } if (this.deployment.forwarderAddress != null) { this.forwarderInstance = await this._createForwarder(this.deployment.forwarderAddress) } if (this.deployment.stakeManagerAddress != null) { this.stakeManagerInstance = await this._createStakeManager(this.deployment.stakeManagerAddress) } if (this.deployment.penalizerAddress != null) { this.penalizerInstance = await this._createPenalizer(this.deployment.penalizerAddress) } if (this.deployment.managerStakeTokenAddress != null) { this.erc20Token = await this._createERC20(this.deployment.managerStakeTokenAddress) } } // must use these options when creating Transaction object getRawTxOptions (): TxOptions { if (this.rawTxOptions == null) { throw new Error('_init not called') } return this.rawTxOptions } async _createRecipient (address: Address): Promise<IERC2771RecipientInstance> { if (this.erc2771RecipientInstance != null && this.erc2771RecipientInstance.address.toLowerCase() === address.toLowerCase()) { return this.erc2771RecipientInstance } this.erc2771RecipientInstance = await this.IERC2771Recipient.at(address) return this.erc2771RecipientInstance } async _createPaymaster (address: Address): Promise<IPaymasterInstance> { return await this.IPaymasterContract.at(address) } async _createRelayHub (address: Address): Promise<IRelayHubInstance> { return await this.IRelayHubContract.at(address) } async _createForwarder (address: Address): Promise<IForwarderInstance> { return await this.IForwarderContract.at(address) } async _createStakeManager (address: Address): Promise<IStakeManagerInstance> { return await this.IStakeManager.at(address) } async _createPenalizer (address: Address): Promise<IPenalizerInstance> { return await this.IPenalizer.at(address) } async _createRelayRegistrar (address: Address): Promise<IRelayRegistrarInstance> { return await this.IRelayRegistrar.at(address) } async _createERC20 (address: Address): Promise<IERC20TokenInstance> { return await this.IERC20Token.at(address) } /** * Queries the balance of the token and displays it in a human-readable format, taking 'decimals' into account. * Note: does not round up the fraction and truncates it. */ async getTokenBalanceFormatted (address: Address): Promise<string> { const balance = await this.erc20Token.balanceOf(address) return await this.formatTokenAmount(balance) } async formatTokenAmount (balance: BN): Promise<string> { const { tokenSymbol, tokenDecimals } = await this.getErc20TokenMetadata() return formatTokenAmount(balance, tokenDecimals, tokenSymbol) } async getErc20TokenMetadata (): Promise<ERC20TokenMetadata> { let tokenName: string try { tokenName = await this.erc20Token.name() } catch (_) { tokenName = `ERC-20 token ${this.erc20Token.address}` } let tokenSymbol: string try { tokenSymbol = await this.erc20Token.symbol() } catch (_) { tokenSymbol = `ERC-20 token ${this.erc20Token.address}` } let tokenDecimals: BN try { tokenDecimals = await this.erc20Token.decimals() } catch (_) { tokenDecimals = toBN(0) } return { tokenName, tokenSymbol, tokenDecimals } } async isTrustedForwarder (recipientAddress: Address, forwarder: Address): Promise<boolean> { const recipient = await this._createRecipient(recipientAddress) return await recipient.isTrustedForwarder(forwarder) } async getSenderNonce (sender: Address, forwarderAddress: Address): Promise<IntString> { const forwarder = await this._createForwarder(forwarderAddress) const nonce = await forwarder.getNonce(sender) return nonce.toString() } async _getBlockGasLimit (): Promise<number> { const latestBlock = await this.web3.eth.getBlock('latest') return latestBlock.gasLimit } _fixGasFees (relayRequest: RelayRequest): { gasPrice?: string, maxFeePerGas?: string, maxPriorityFeePerGas?: string } { if (this.transactionType === TransactionType.LEGACY) { return { gasPrice: toHex(relayRequest.relayData.maxFeePerGas) } } else { return { maxFeePerGas: toHex(relayRequest.relayData.maxFeePerGas), maxPriorityFeePerGas: toHex(relayRequest.relayData.maxPriorityFeePerGas) } } } /** * make a view call to relayCall(), just like the way it will be called by the relayer. * returns: * - paymasterAccepted - true if accepted * - reverted - true if relayCall was reverted. * - returnValue - if either reverted or paymaster NOT accepted, then this is the reason string. */ async validateRelayCall ( relayCallABIData: RelayCallABI, viewCallGasLimit: BN, isDryRun: boolean): Promise<ViewCallVerificationResult> { if (viewCallGasLimit == null || relayCallABIData.relayRequest.relayData.maxFeePerGas == null || relayCallABIData.relayRequest.relayData.maxPriorityFeePerGas == null) { throw new Error('validateRelayCall: invalid input') } const relayHub = this.relayHubInstance const from = isDryRun ? constants.DRY_RUN_ADDRESS : relayCallABIData.relayRequest.relayData.relayWorker try { const encodedRelayCall = this.encodeABI(relayCallABIData) const res: string = await new Promise((resolve, reject) => { const gasFees = this._fixGasFees(relayCallABIData.relayRequest) const rpcPayload = { jsonrpc: '2.0', id: 1, method: 'eth_call', params: [ { from, to: relayHub.address, gas: toHex(viewCallGasLimit), data: encodedRelayCall, ...gasFees }, 'latest' ] } this.logger.debug(`Sending in view mode: \n${JSON.stringify(rpcPayload)}\n encoded data: \n${JSON.stringify(relayCallABIData)}`) // @ts-ignore this.web3.currentProvider.send(rpcPayload, (err: any, res: { result: string, error: any }) => { if (res.error != null) { err = res.error } const revertMsg = this._decodeRevertFromResponse(err, res) if (revertMsg != null) { reject(new Error(revertMsg)) } else if (errorAsBoolean(err)) { reject(err) } else { resolve(res.result) } }) }) this.logger.debug('relayCall res=' + res) // @ts-ignore const decoded = abi.decodeParameters(['bool', 'bytes'], res) const paymasterAccepted: boolean = decoded[0] let returnValue: string if (paymasterAccepted) { returnValue = decoded[1] } else { returnValue = this._decodeRevertFromResponse({}, { result: decoded[1] }) ?? decoded[1] } return { returnValue: returnValue, paymasterAccepted: paymasterAccepted, reverted: false } } catch (e) { const message = e instanceof Error ? e.message : JSON.stringify(e, replaceErrors) return { paymasterAccepted: false, reverted: true, returnValue: `view call to 'relayCall' reverted in client: ${message}` } } } async getMaxViewableGasLimit (relayRequest: RelayRequest, maxViewableGasLimit: IntString): Promise<BN> { const maxViewableGasLimitBN = toBN(maxViewableGasLimit) const gasPrice = toBN(relayRequest.relayData.maxFeePerGas) if (gasPrice.eqn(0)) { return maxViewableGasLimitBN } const workerBalanceString = await this.getBalance(relayRequest.relayData.relayWorker) if (workerBalanceString == null) { this.logger.error('getMaxViewableGasLimit: failed to get relay worker balance') return maxViewableGasLimitBN } const workerBalance = toBN(workerBalanceString) const workerGasLimit = workerBalance.div(gasPrice) return BN.min(maxViewableGasLimitBN, workerGasLimit) } /** * decode revert from rpc response. * called from the callback of the provider "eth_call" call. * check if response is revert, and extract revert reason from it. * support kovan, geth, ganache error formats.. * @param err - provider err value * @param res - provider res value */ // decode revert from rpc response. // _decodeRevertFromResponse (err?: { message?: string, data?: any }, res?: { error?: any, result?: string }): string | null { let matchGanache = err?.data?.message?.toString().match(/: revert(?:ed)? (.*)/) if (matchGanache == null) { matchGanache = res?.error?.message?.toString().match(/: revert(?:ed)? (.*)/) } if (matchGanache != null) { // also cleaning up Hardhat Node's verbose revert errors return matchGanache[1].replace('with reason string ', '').replace(/^'|'$/g, '') } const errorData = err?.data ?? res?.error?.data const m = errorData?.toString().match(/(0x08c379a0\S*)/) if (m != null) { return decodeRevertReason(m[1]) } const result = res?.result ?? '' if (result.startsWith('0x08c379a0')) { return decodeRevertReason(result) } return null } encodeABI ( _: RelayCallABI ): PrefixedHexString { return this.relayCallMethod(_.maxAcceptanceBudget, _.relayRequest, _.signature, _.approvalData).encodeABI() } async getPastEventsForHub (extraTopics: Array<string[] | string | undefined>, options: PastEventOptions, names: EventName[] = ActiveManagerEvents): Promise<EventData[]> { return await this._getPastEventsPaginated(this.relayHubInstance.contract, names, extraTopics, options) } async getPastEventsForRegistrar (extraTopics: Array<string[] | string | undefined>, options: PastEventOptions, names: EventName[] = [RelayServerRegistered]): Promise<EventData[]> { return await this._getPastEventsPaginated(this.relayRegistrar.contract, names, extraTopics, options) } async getPastEventsForStakeManager (names: EventName[], extraTopics: Array<string[] | string | undefined>, options: PastEventOptions): Promise<EventData[]> { const stakeManager = await this.stakeManagerInstance return await this._getPastEventsPaginated(stakeManager.contract, names, extraTopics, options) } async getPastEventsForPenalizer (names: EventName[], extraTopics: Array<string[] | string | undefined>, options: PastEventOptions): Promise<EventData[]> { return await this._getPastEventsPaginated(this.penalizerInstance.contract, names, extraTopics, options) } getLogsPagesForRange (fromBlock: BlockNumber = 1, toBlock?: BlockNumber): number { // save 'getBlockNumber' roundtrip for a known max value if (this.maxPageSize === Number.MAX_SAFE_INTEGER) { return 1 } // noinspection SuspiciousTypeOfGuard - known false positive if (typeof fromBlock !== 'number' || typeof toBlock !== 'number') { throw new Error( `ContractInteractor:getLogsPagesForRange: [${fromBlock.toString()}..${toBlock?.toString()}]: only numbers supported when using pagination`) } const rangeSize = toBlock - fromBlock + 1 const pagesForRange = Math.max(Math.ceil(rangeSize / this.maxPageSize), 1) if (pagesForRange > 1) { this.logger.info(`Splitting request for ${rangeSize} blocks into ${pagesForRange} smaller paginated requests!`) } return pagesForRange } splitRange (fromBlock: BlockNumber, toBlock: BlockNumber, parts: number): Array<{ fromBlock: BlockNumber, toBlock: BlockNumber }> { if (parts === 1) { return [{ fromBlock, toBlock }] } // noinspection SuspiciousTypeOfGuard - known false positive if (typeof fromBlock !== 'number' || typeof toBlock !== 'number') { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new Error(`ContractInteractor:splitRange: only number supported for block range when using pagination, ${fromBlock} ${toBlock} ${parts}`) } const rangeSize = toBlock - fromBlock + 1 const splitSize = Math.ceil(rangeSize / parts) const ret: Array<{ fromBlock: number, toBlock: number }> = [] for (let b = fromBlock; b <= toBlock; b += splitSize) { ret.push({ fromBlock: b, toBlock: Math.min(toBlock, b + splitSize - 1) }) } return ret } /** * Splits requested range into pages to avoid fetching too many blocks at once. * In case 'getLogs' returned with a common error message of "more than X events" dynamically decrease page size. */ async _getPastEventsPaginated (contract: any, names: EventName[], extraTopics: Array<string[] | string | undefined>, options: PastEventOptions): Promise<EventData[]> { const delay = this.getNetworkType() === 'private' ? 0 : 300 if (options.toBlock == null) { // this is to avoid '!' for TypeScript options.toBlock = 'latest' } if (options.fromBlock == null) { options.fromBlock = 1 } // save 'getBlockNumber' roundtrip for a known max value (must match check in getLogsPagesForRange) if (this.maxPageSize !== Number.MAX_SAFE_INTEGER && options.toBlock === 'latest') { options.toBlock = await this.getBlockNumber() if (options.fromBlock > options.toBlock) { options.toBlock = options.fromBlock } } if (options.fromBlock > options.toBlock) { const message = `fromBlock(${options.fromBlock.toString()}) > toBlock(${options.toBlock.toString()})` this.logger.error(message) throw new Error(message) } let pagesCurrent: number = await this.getLogsPagesForRange(options.fromBlock, options.toBlock) const relayEventParts: EventData[][] = [] while (true) { const rangeParts = await this.splitRange(options.fromBlock, options.toBlock, pagesCurrent) try { // eslint-disable-next-line for (const { fromBlock, toBlock } of rangeParts) { // this.logger.debug('Getting events from block ' + fromBlock.toString() + ' to ' + toBlock.toString()) let attempts = 0 while (true) { try { const pastEvents = await this._getPastEvents(contract, names, extraTopics, Object.assign({}, options, { fromBlock, toBlock })) relayEventParts.push(pastEvents) break } catch (e: any) { /* eslint-disable */ this.logger.error(`error in getPastEvents. fromBlock: ${fromBlock.toString()} toBlock: ${toBlock.toString()} attempts: ${attempts.toString()} names: ${names.toString()} extraTopics: ${extraTopics.toString()} options: ${JSON.stringify(options)} \n${e.toString()}`) /* eslint-enable */ attempts++ if (attempts >= 100) { this.logger.error('Too many attempts. throwing ') throw e } await sleep(delay) } } } break } catch (e: any) { // dynamically adjust query size fo some RPC providers if (e.toString().match(/query returned more than/) != null) { this.logger.warn( 'Received "query returned more than X events" error from server, will try to split the request into smaller chunks') if (pagesCurrent > 16) { throw new Error(`Too many events after splitting by ${pagesCurrent}`) } pagesCurrent *= 4 } else { throw e } } } return relayEventParts.flat() } async _getPastEvents (contract: any, names: EventName[], extraTopics: Array<string[] | string | undefined>, options: PastEventOptions): Promise<EventData[]> { const topics: Array<string[] | string| undefined> = [] const eventTopic = event2topic(contract, names) topics.push(eventTopic) // TODO: AFAIK this means only the first parameter of the event is supported if (extraTopics.length > 0) { topics.push(...extraTopics) } return contract.getPastEvents('allEvents', Object.assign({}, options, { topics })) } async getBalance (address: Address, defaultBlock: BlockNumber = 'latest'): Promise<string> { return await this.web3.eth.getBalance(address, defaultBlock) } async getBlockNumberRightNow (): Promise<number> { return await this.web3.eth.getBlockNumber() } async getBlockNumber (): Promise<number> { let blockNumber = -1 let attempts = 0 const delay = this.getNetworkType() === 'private' ? 0 : 1000 while (blockNumber < this.lastBlockNumber && attempts <= 10) { try { blockNumber = await this.web3.eth.getBlockNumber() } catch (e) { this.logger.error(`getBlockNumber: ${(e as Error).message}`) } if (blockNumber >= this.lastBlockNumber) { break } await sleep(delay) attempts++ } if (blockNumber < this.lastBlockNumber) { throw new Error(`couldn't retrieve latest blockNumber from node. last block: ${this.lastBlockNumber}, got block: ${blockNumber}`) } this.lastBlockNumber = blockNumber return blockNumber } async sendSignedTransaction (rawTx: string): Promise<TransactionReceipt> { // noinspection ES6RedundantAwait - PromiEvent makes lint less happy about this line return await this.web3.eth.sendSignedTransaction(rawTx) } async estimateGas (transactionDetails: TransactionConfig): Promise<number> { return await this.web3.eth.estimateGas(transactionDetails) } async estimateGasWithoutCalldata (gsnTransactionDetails: GsnTransactionDetails): Promise<number> { const originalGasEstimation = await this.estimateGas(gsnTransactionDetails) const calldataGasCost = this.calculateCalldataCost(gsnTransactionDetails.data) const adjustedEstimation = originalGasEstimation - calldataGasCost this.logger.debug( `estimateGasWithoutCalldata: original estimation: ${originalGasEstimation}; calldata cost: ${calldataGasCost}; adjusted estimation: ${adjustedEstimation}`) if (adjustedEstimation < 0) { throw new Error('estimateGasWithoutCalldata: calldataGasCost exceeded originalGasEstimation\n' + 'your Environment configuration and Ethereum node you are connected to are not compatible') } return adjustedEstimation } /** * @returns result - maximum possible gas consumption by this relayed call * (calculated on chain by RelayHub.verifyGasAndDataLimits) */ calculateTransactionMaxPossibleGas ( _: { msgData: PrefixedHexString gasAndDataLimits: PaymasterGasAndDataLimits relayCallGasLimit: string }): number { const msgDataLength = toBuffer(_.msgData).length const msgDataGasCostInsideTransaction = toBN(this.environment.dataOnChainHandlingGasCostPerByte) .muln(msgDataLength) .toNumber() const calldataCost = this.calculateCalldataCost(_.msgData) const result = toNumber(this.relayHubConfiguration.gasOverhead) + msgDataGasCostInsideTransaction + calldataCost + parseInt(_.relayCallGasLimit) + toNumber(_.gasAndDataLimits.preRelayedCallGasLimit) + toNumber(_.gasAndDataLimits.postRelayedCallGasLimit) this.logger.debug(` input:\n${JSON.stringify(_)} msgDataLength: ${msgDataLength} calldataCost: ${calldataCost} msgDataGasCostInsideTransaction: ${msgDataGasCostInsideTransaction} environment: ${JSON.stringify(this.environment)} relayHubConfiguration: ${JSON.stringify(this.relayHubConfiguration)} calculateTransactionMaxPossibleGas: result: ${result} `) return result } /** * @param relayRequestOriginal request input of the 'relayCall' method with some fields not yet initialized * @param variableFieldSizes configurable sizes of 'relayCall' parameters with variable size types * @return {PrefixedHexString} top boundary estimation of how much gas sending this data will consume */ estimateCalldataCostForRequest ( relayRequestOriginal: RelayRequest, variableFieldSizes: { maxApprovalDataLength: number, maxPaymasterDataLength: number } ): PrefixedHexString { // protecting the original object from temporary modifications done here const relayRequest: RelayRequest = Object.assign( {}, relayRequestOriginal, { relayData: Object.assign({}, relayRequestOriginal.relayData) }) relayRequest.relayData.transactionCalldataGasUsed = '0xffffffffff' relayRequest.relayData.paymasterData = '0x' + 'ff'.repeat(variableFieldSizes.maxPaymasterDataLength) const maxAcceptanceBudget = '0xffffffffff' const signature = '0x' + 'ff'.repeat(65) const approvalData = '0x' + 'ff'.repeat(variableFieldSizes.maxApprovalDataLength) const encodedData = this.encodeABI({ relayRequest, signature, approvalData, maxAcceptanceBudget }) return `0x${this.calculateCalldataCost(encodedData).toString(16)}` } calculateCalldataCost (msgData: PrefixedHexString): number { const { calldataZeroBytes, calldataNonzeroBytes } = calculateCalldataBytesZeroNonzero(msgData) return calldataZeroBytes * this.environment.gtxdatazero + calldataNonzeroBytes * this.environment.gtxdatanonzero } // TODO: cache response for some time to optimize. It doesn't make sense to optimize these requests in calling code. async getGasPrice (): Promise<IntString> { const gasPriceFromNode = await this.web3.eth.getGasPrice() if (gasPriceFromNode == null) { throw new Error('getGasPrice: node returned null value') } // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!this.environment.getGasPriceFactor) { this.logger.warn('Environment not set') return gasPriceFromNode } const gasPriceActual = toBN(gasPriceFromNode) .muln(this.environment.getGasPriceFactor) return gasPriceActual.toString() } async getFeeHistory (blockCount: number | BigNumber | BN | string, lastBlock: number | BigNumber | BN | string, rewardPercentiles: number[]): Promise<FeeHistoryResult> { return await this.web3.eth.getFeeHistory(blockCount, lastBlock, rewardPercentiles) } async getMaxPriorityFee (): Promise<string> { const gasFees = await this.getGasFees() return gasFees.priorityFeePerGas } async getGasFees (): Promise<{ baseFeePerGas: string, priorityFeePerGas: string }> { if (this.transactionType === TransactionType.LEGACY) { const gasPrice = await this.getGasPrice() return { baseFeePerGas: gasPrice, priorityFeePerGas: gasPrice } } const networkHistoryFees = await this.getFeeHistory('0x1', 'latest', [0.5]) const baseFeePerGas = networkHistoryFees.baseFeePerGas[0] const priorityFeePerGas = networkHistoryFees.reward[0][0] return { baseFeePerGas, priorityFeePerGas } } async getTransactionCount (address: string, defaultBlock?: BlockNumber): Promise<number> { // @ts-ignore (web3 does not define 'defaultBlock' as optional) return await this.web3.eth.getTransactionCount(address, defaultBlock) } async getTransaction (transactionHash: string): Promise<Transaction> { return await this.web3.eth.getTransaction(transactionHash) } async getBlock (blockHashOrBlockNumber: BlockNumber): Promise<BlockTransactionString> { return await this.web3.eth.getBlock(blockHashOrBlockNumber) } validateAddress (address: string, exceptionTitle = 'invalid address:'): void { if (!this.web3.utils.isAddress(address)) { throw new Error(exceptionTitle + ' ' + address) } } async getCode (address: string): Promise<string> { return await this.web3.eth.getCode(address) } getNetworkId (): number { if (this.networkId == null) { throw new Error('_init not called') } return this.networkId } getNetworkType (): string { if (this.networkType == null) { throw new Error('_init not called') } return this.networkType } async isContractDeployed (address: Address): Promise<boolean> { const code = await this.web3.eth.getCode(address) return code !== '0x' } async workerToManager (worker: Address): Promise<string> { return await this.relayHubInstance.getWorkerManager(worker) } /** * Gets balance of an address on the current RelayHub. * @param address - can be a Paymaster or a Relay Manger */ async hubBalanceOf (address: Address): Promise<BN> { return await this.relayHubInstance.balanceOf(address) } /** * Gets stake of an address on the current StakeManager. * @param managerAddress */ async getStakeInfo (managerAddress: Address): Promise<StakeInfo> { const getStakeInfoResult = await this.stakeManagerInstance.getStakeInfo(managerAddress) // @ts-ignore - TypeChain generates incorrect type declarations for tuples return getStakeInfoResult[0] } async isRelayManagerStakedOnHub (relayManager: Address): Promise<ManagerStakeStatus> { const res: ManagerStakeStatus = await new Promise((resolve) => { const rpcPayload = { jsonrpc: '2.0', id: 1, method: 'eth_call', params: [ { to: this.relayHubInstance.address, data: this.relayHubInstance.contract.methods.verifyRelayManagerStaked(relayManager).encodeABI() }, 'latest' ] } // @ts-ignore this.web3.currentProvider.send(rpcPayload, (err: any, res: { result: string, error: any }) => { if (res.error != null) { err = res.error } const errorMessage = this._decodeRevertFromResponse(err, res) resolve({ isStaked: res.result === '0x', errorMessage }) }) }) return res } async initDeployment (deployment: GSNContractsDeployment): Promise<void> { this.deployment = deployment await this._initializeContracts() } getDeployment (): GSNContractsDeployment { if (this.deployment == null) { throw new Error('Contracts deployment is not initialized for Contract Interactor!') } return this.deployment } async withdrawHubBalanceEstimateGas (amount: BN, destination: Address, managerAddress: Address, gasPrice: IntString): Promise<{ gasCost: BN gasLimit: number method: any }> { const hub = this.relayHubInstance const method = hub.contract.methods.withdraw(destination, amount.toString()) const withdrawTxGasLimit = await method.estimateGas( { from: managerAddress }) const gasCost = toBN(withdrawTxGasLimit).mul(toBN(gasPrice)) return { gasLimit: parseInt(withdrawTxGasLimit), gasCost, method } } // TODO: a way to make a relay hub transaction with a specified nonce without exposing the 'method' abstraction async getRegisterRelayMethod (relayHub: Address, baseRelayFee: IntString, pctRelayFee: number, url: string): Promise<any> { const registrar = this.relayRegistrar return registrar?.contract.methods.registerRelayServer(relayHub, baseRelayFee, pctRelayFee, splitRelayUrlForRegistrar(url)) } async getAddRelayWorkersMethod (workers: Address[]): Promise<any> { const hub = this.relayHubInstance return hub.contract.methods.addRelayWorkers(workers) } async getSetRelayManagerMethod (owner: Address): Promise<any> { const sm = this.stakeManagerInstance return sm.contract.methods.setRelayManagerOwner(owner) } /** * Web3.js as of 1.2.6 (see web3-core-method::_confirmTransaction) does not allow * broadcasting of a transaction without waiting for it to be mined. * This method sends the RPC call directly * @param signedTransaction - the raw signed transaction to broadcast */ async broadcastTransaction (signedTransaction: PrefixedHexString): Promise<PrefixedHexString> { return await new Promise((resolve, reject) => { if (this.provider == null) { throw new Error('provider is not set') } this.provider.send({ jsonrpc: '2.0', method: 'eth_sendRawTransaction', params: [ signedTransaction ], id: Date.now() }, (e: Error | null, r: any) => { if (errorAsBoolean(e)) { reject(e) } else if (errorAsBoolean(r.error)) { reject(r.error) } else { resolve(r.result) } }) }) } async hubDepositFor (paymaster: Address, transactionDetails: TransactionDetails): Promise<any> { return await this.relayHubInstance.depositFor(paymaster, transactionDetails) } async resolveDeploymentVersions (): Promise<ObjectMap<PrefixedHexString>> { const versionsMap: ObjectMap<PrefixedHexString> = {} if (this.deployment.relayHubAddress != null) { versionsMap[this.deployment.relayHubAddress] = await this.relayHubInstance.versionHub() } if (this.deployment.penalizerAddress != null) { versionsMap[this.deployment.penalizerAddress] = await this.penalizerInstance.versionPenalizer() } if (this.deployment.stakeManagerAddress != null) { versionsMap[this.deployment.stakeManagerAddress] = await this.stakeManagerInstance.versionSM() } return versionsMap } async queryDeploymentBalances (): Promise<ObjectMap<IntString>> { const balances: ObjectMap<IntString> = {} if (this.deployment.relayHubAddress != null) { balances[this.deployment.relayHubAddress] = await this.getBalance(this.deployment.relayHubAddress) } if (this.deployment.penalizerAddress != null) { balances[this.deployment.penalizerAddress] = await this.getBalance(this.deployment.penalizerAddress) } if (this.deployment.stakeManagerAddress != null) { balances[this.deployment.stakeManagerAddress] = await this.getBalance(this.deployment.stakeManagerAddress) } return balances } private async _hubStakeManagerAddress (): Promise<Address> { return await this.relayHubInstance.getStakeManager() } stakeManagerAddress (): Address { return this.stakeManagerInstance.address } private async _hubPenalizerAddress (): Promise<Address> { return await this.relayHubInstance.getPenalizer() } private async _hubRelayRegistrarAddress (): Promise<Address> { return await this.relayHubInstance.getRelayRegistrar() } penalizerAddress (): Address { return this.penalizerInstance.address } /** * discover registered relays * @param relayRegistrationMaximumAge - the oldest registrations to be counted */ async getRegisteredRelays (relayRegistrationMaximumAge: number): Promise<RelayRegisteredEventInfo[]> { return await this.getRegisteredRelaysFromRegistrar(relayRegistrationMaximumAge) } async getRegisteredRelaysFromEvents (subsetManagers?: string[], fromBlock?: number): Promise<RelayRegisteredEventInfo[]> { // each topic in getPastEvent is either a string or array-of-strings, to search for any. const extraTopics = subsetManagers == null ? [] : [subsetManagers?.map(address2topic)] as any const registerEvents = await this.getPastEventsForRegistrar(extraTopics, { fromBlock }, [RelayServerRegistered]) const unregisterEvents = await this.getPastEventsForStakeManager([HubUnauthorized, StakePenalized, StakeUnlocked], [extraTopics], { fromBlock }) // we don't check event order: removed relayer can't be re-registered, so we simply ignore any "register" of a relayer that was ever removed/unauthorized/penalized const removed = new Set(unregisterEvents.map(event => event.returnValues.relayManager)) const relaySet: { [relayManager: string]: RelayRegisteredEventInfo } = {} registerEvents .filter(event => !removed.has(event.returnValues.relayManager)) .map(event => { const { relayManager, pctRelayFee, baseRelayFee, url } = event.returnValues const ret: RelayRegisteredEventInfo = { relayManager, pctRelayFee, baseRelayFee, relayUrl: url } return ret }) .forEach(info => { relaySet[info.relayManager] = info }) return Object.values(relaySet) } /** * get registered relayers from registrar * (output format matches event info) */ async getRegisteredRelaysFromRegistrar (relayRegistrationMaximumAge: number): Promise<RelayRegisteredEventInfo[]> { if (this.relayRegistrar == null) { throw new Error('Relay Registrar is not initialized') } const relayHub = this.relayHubInstance.address if (relayHub == null) { throw new Error('RelayHub is not initialized!') } let oldestBlockTimestamp = 0 if (relayRegistrationMaximumAge !== 0) { const block = await this.getBlock('latest') oldestBlockTimestamp = Math.max(0, toNumber(block.timestamp) - relayRegistrationMaximumAge) } const relayInfos = await this.relayRegistrar.readRelayInfos(relayHub, 0, oldestBlockTimestamp, 100) return relayInfos.map(info => { return { relayManager: info.relayManager, pctRelayFee: info.pctRelayFee.toString(), baseRelayFee: info.baseRelayFee.toString(), relayUrl: packRelayUrlForRegistrar(info.urlParts) } }) } async getCreationBlockFromRelayHub (): Promise<BN> { return await this.relayHubInstance.getCreationBlock() } async getRegisteredWorkers (managerAddress: Address): Promise<Address[]> { const topics = address2topic(managerAddress) const workersAddedEvents = await this.getPastEventsForHub([topics], { fromBlock: 1 }, [RelayWorkersAdded]) return workersAddedEvents.map(it => it.returnValues.newRelayWorkers).flat() } } /** * Ganache does not seem to enforce EIP-155 signature. Buidler does, though. * This is how {@link Transaction} constructor allows support for custom and private network. * @param chainId * @param networkId * @param chain * @return {{common: Common}} */ export function getRawTxOptions (chainId: number, networkId: number, chain?: string): TxOptions { if (chain == null || chain === 'main' || chain === 'private') { chain = 'mainnet' } return { common: Common.forCustomChain( chain, { chainId, networkId }, 'london') } }
the_stack
import * as assert from "assert"; import * as ts from "typescript"; import { ArrayType, ConditionalType, DeclarationReflection, IndexedAccessType, InferredType, IntersectionType, IntrinsicType, NamedTupleMember, PredicateType, QueryType, ReferenceType, ReflectionKind, ReflectionType, LiteralType, TupleType, Type, TypeOperatorType, UnionType, UnknownType, MappedType, SignatureReflection, ReflectionFlag, OptionalType, RestType, TemplateLiteralType, } from "../models"; import { zip } from "../utils/array"; import type { Context } from "./context"; import { ConverterEvents } from "./converter-events"; import { convertIndexSignature } from "./factories/index-signature"; import { convertParameterNodes, convertTypeParameterNodes, createSignature, } from "./factories/signature"; import { convertSymbol } from "./symbols"; import { removeUndefined } from "./utils/reflections"; export interface TypeConverter< TNode extends ts.TypeNode = ts.TypeNode, TType extends ts.Type = ts.Type > { kind: TNode["kind"][]; // getTypeAtLocation is expensive, so don't pass the type here. convert(context: Context, node: TNode): Type; // We use typeToTypeNode to figure out what method to call in the first place, // so we have a non-type-checkable node here, necessary for some converters. convertType(context: Context, type: TType, node: TNode): Type; } const converters = new Map<ts.SyntaxKind, TypeConverter>(); export function loadConverters() { if (converters.size) return; for (const actor of [ arrayConverter, conditionalConverter, constructorConverter, exprWithTypeArgsConverter, functionTypeConverter, importType, indexedAccessConverter, inferredConverter, intersectionConverter, jsDocVariadicTypeConverter, keywordConverter, optionalConverter, parensConverter, predicateConverter, queryConverter, typeLiteralConverter, referenceConverter, restConverter, namedTupleMemberConverter, mappedConverter, literalTypeConverter, templateLiteralConverter, thisConverter, tupleConverter, typeOperatorConverter, unionConverter, // Only used if skipLibCheck: true jsDocNullableTypeConverter, jsDocNonNullableTypeConverter, ]) { for (const key of actor.kind) { if (key === undefined) { // Might happen if running on an older TS version. continue; } assert(!converters.has(key)); converters.set(key, actor); } } } // This ought not be necessary, but we need some way to discover recursively // typed symbols which do not have type nodes. See the `recursive` symbol in the variables test. const seenTypeSymbols = new Set<ts.Symbol>(); export function convertType( context: Context, typeOrNode: ts.Type | ts.TypeNode | undefined ): Type { if (!typeOrNode) { return new IntrinsicType("any"); } loadConverters(); if ("kind" in typeOrNode) { const converter = converters.get(typeOrNode.kind); if (converter) { return converter.convert(context, typeOrNode); } return requestBugReport(context, typeOrNode); } // IgnoreErrors is important, without it, we can't assert that we will get a node. const node = context.checker.typeToTypeNode( typeOrNode, void 0, ts.NodeBuilderFlags.IgnoreErrors ); assert(node); // According to the TS source of typeToString, this is a bug if it does not hold. const symbol = typeOrNode.getSymbol(); if (symbol) { if ( node.kind !== ts.SyntaxKind.TypeReference && node.kind !== ts.SyntaxKind.ArrayType && seenTypeSymbols.has(symbol) ) { const typeString = context.checker.typeToString(typeOrNode); context.logger.verbose( `Refusing to recurse when converting type: ${typeString}` ); return new UnknownType(typeString); } seenTypeSymbols.add(symbol); } const converter = converters.get(node.kind); if (converter) { const result = converter.convertType(context, typeOrNode, node); if (symbol) seenTypeSymbols.delete(symbol); return result; } return requestBugReport(context, typeOrNode); } const arrayConverter: TypeConverter<ts.ArrayTypeNode, ts.TypeReference> = { kind: [ts.SyntaxKind.ArrayType], convert(context, node) { return new ArrayType(convertType(context, node.elementType)); }, convertType(context, type) { const params = context.checker.getTypeArguments(type); // This is *almost* always true... except for when this type is in the constraint of a type parameter see GH#1408 // assert(params.length === 1); assert(params.length > 0); return new ArrayType(convertType(context, params[0])); }, }; const conditionalConverter: TypeConverter< ts.ConditionalTypeNode, ts.ConditionalType > = { kind: [ts.SyntaxKind.ConditionalType], convert(context, node) { return new ConditionalType( convertType(context, node.checkType), convertType(context, node.extendsType), convertType(context, node.trueType), convertType(context, node.falseType) ); }, convertType(context, type) { return new ConditionalType( convertType(context, type.checkType), convertType(context, type.extendsType), convertType(context, type.resolvedTrueType), convertType(context, type.resolvedFalseType) ); }, }; const constructorConverter: TypeConverter<ts.ConstructorTypeNode, ts.Type> = { kind: [ts.SyntaxKind.ConstructorType], convert(context, node) { const symbol = context.getSymbolAtLocation(node) ?? node.symbol; const type = context.getTypeAtLocation(node); if (!symbol || !type) { return new IntrinsicType("Function"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.Constructor, context.scope ); const rc = context.withScope(reflection); rc.setConvertingTypeNode(); context.registerReflection(reflection, symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node); const signature = new SignatureReflection( "__type", ReflectionKind.ConstructorSignature, reflection ); // This is unfortunate... but seems the obvious place to put this with the current // architecture. Ideally, this would be a property on a "ConstructorType"... but that // needs to wait until TypeDoc 0.22 when making other breaking changes. if ( node.modifiers?.some( (m) => m.kind === ts.SyntaxKind.AbstractKeyword ) ) { signature.setFlag(ReflectionFlag.Abstract); } context.registerReflection(signature, void 0); const signatureCtx = rc.withScope(signature); reflection.signatures = [signature]; signature.type = convertType(signatureCtx, node.type); signature.parameters = convertParameterNodes( signatureCtx, signature, node.parameters ); signature.typeParameters = convertTypeParameterNodes( signatureCtx, node.typeParameters ); return new ReflectionType(reflection); }, convertType(context, type) { if (!type.symbol) { return new IntrinsicType("Function"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.Constructor, context.scope ); context.registerReflection(reflection, type.symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection); createSignature( context.withScope(reflection), ReflectionKind.ConstructorSignature, type.getConstructSignatures()[0] ); return new ReflectionType(reflection); }, }; const exprWithTypeArgsConverter: TypeConverter< ts.ExpressionWithTypeArguments, ts.Type > = { kind: [ts.SyntaxKind.ExpressionWithTypeArguments], convert(context, node) { const targetSymbol = context.getSymbolAtLocation(node.expression); // Mixins... we might not have a symbol here. if (!targetSymbol) { return convertType( context, context.checker.getTypeAtLocation(node) ); } const parameters = node.typeArguments?.map((type) => convertType(context, type)) ?? []; const ref = new ReferenceType( targetSymbol.name, context.resolveAliasedSymbol(targetSymbol), context.project ); ref.typeArguments = parameters; return ref; }, convertType: requestBugReport, }; const functionTypeConverter: TypeConverter<ts.FunctionTypeNode, ts.Type> = { kind: [ts.SyntaxKind.FunctionType], convert(context, node) { const symbol = context.getSymbolAtLocation(node) ?? node.symbol; const type = context.getTypeAtLocation(node); if (!symbol || !type) { return new IntrinsicType("Function"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.TypeLiteral, context.scope ); const rc = context.withScope(reflection); context.registerReflection(reflection, symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node); const signature = new SignatureReflection( "__type", ReflectionKind.CallSignature, reflection ); context.registerReflection(signature, void 0); const signatureCtx = rc.withScope(signature); reflection.signatures = [signature]; signature.type = convertType(signatureCtx, node.type); signature.parameters = convertParameterNodes( signatureCtx, signature, node.parameters ); signature.typeParameters = convertTypeParameterNodes( signatureCtx, node.typeParameters ); return new ReflectionType(reflection); }, convertType(context, type) { if (!type.symbol) { return new IntrinsicType("Function"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.TypeLiteral, context.scope ); context.registerReflection(reflection, type.symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection); createSignature( context.withScope(reflection), ReflectionKind.CallSignature, type.getCallSignatures()[0] ); return new ReflectionType(reflection); }, }; const importType: TypeConverter<ts.ImportTypeNode> = { kind: [ts.SyntaxKind.ImportType], convert(context, node) { const name = node.qualifier?.getText() ?? "__module"; const symbol = context.checker.getSymbolAtLocation(node); assert(symbol, "Missing symbol when converting import type node"); return new ReferenceType( name, context.resolveAliasedSymbol(symbol), context.project ); }, convertType(context, type) { const symbol = type.getSymbol(); assert(symbol, "Missing symbol when converting import type"); // Should be a compiler error return new ReferenceType( "__module", context.resolveAliasedSymbol(symbol), context.project ); }, }; const indexedAccessConverter: TypeConverter< ts.IndexedAccessTypeNode, ts.IndexedAccessType > = { kind: [ts.SyntaxKind.IndexedAccessType], convert(context, node) { return new IndexedAccessType( convertType(context, node.objectType), convertType(context, node.indexType) ); }, convertType(context, type) { return new IndexedAccessType( convertType(context, type.objectType), convertType(context, type.indexType) ); }, }; const inferredConverter: TypeConverter<ts.InferTypeNode> = { kind: [ts.SyntaxKind.InferType], convert(_context, node) { return new InferredType(node.typeParameter.getText()); }, convertType(_context, type) { return new InferredType(type.symbol.name); }, }; const intersectionConverter: TypeConverter< ts.IntersectionTypeNode, ts.IntersectionType > = { kind: [ts.SyntaxKind.IntersectionType], convert(context, node) { return new IntersectionType( node.types.map((type) => convertType(context, type)) ); }, convertType(context, type) { return new IntersectionType( type.types.map((type) => convertType(context, type)) ); }, }; const jsDocVariadicTypeConverter: TypeConverter<ts.JSDocVariadicType> = { kind: [ts.SyntaxKind.JSDocVariadicType], convert(context, node) { return new ArrayType(convertType(context, node.type)); }, // Should just be an ArrayType convertType: requestBugReport, }; const keywordNames = { [ts.SyntaxKind.AnyKeyword]: "any", [ts.SyntaxKind.BigIntKeyword]: "bigint", [ts.SyntaxKind.BooleanKeyword]: "boolean", [ts.SyntaxKind.NeverKeyword]: "never", [ts.SyntaxKind.NumberKeyword]: "number", [ts.SyntaxKind.ObjectKeyword]: "object", [ts.SyntaxKind.StringKeyword]: "string", [ts.SyntaxKind.SymbolKeyword]: "symbol", [ts.SyntaxKind.UndefinedKeyword]: "undefined", [ts.SyntaxKind.UnknownKeyword]: "unknown", [ts.SyntaxKind.VoidKeyword]: "void", [ts.SyntaxKind.IntrinsicKeyword]: "intrinsic", }; const keywordConverter: TypeConverter<ts.KeywordTypeNode> = { kind: [ ts.SyntaxKind.AnyKeyword, ts.SyntaxKind.BigIntKeyword, ts.SyntaxKind.BooleanKeyword, ts.SyntaxKind.NeverKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.ObjectKeyword, ts.SyntaxKind.StringKeyword, ts.SyntaxKind.SymbolKeyword, ts.SyntaxKind.UndefinedKeyword, ts.SyntaxKind.UnknownKeyword, ts.SyntaxKind.VoidKeyword, ], convert(_context, node) { return new IntrinsicType(keywordNames[node.kind]); }, convertType(_context, _type, node) { return new IntrinsicType(keywordNames[node.kind]); }, }; const optionalConverter: TypeConverter<ts.OptionalTypeNode> = { kind: [ts.SyntaxKind.OptionalType], convert(context, node) { return new OptionalType( removeUndefined(convertType(context, node.type)) ); }, // Handled by the tuple converter convertType: requestBugReport, }; const parensConverter: TypeConverter<ts.ParenthesizedTypeNode> = { kind: [ts.SyntaxKind.ParenthesizedType], convert(context, node) { return convertType(context, node.type); }, // TS strips these out too... shouldn't run into this. convertType: requestBugReport, }; const predicateConverter: TypeConverter<ts.TypePredicateNode, ts.Type> = { kind: [ts.SyntaxKind.TypePredicate], convert(context, node) { const name = ts.isThisTypeNode(node.parameterName) ? "this" : node.parameterName.getText(); const asserts = !!node.assertsModifier; const targetType = node.type ? convertType(context, node.type) : void 0; return new PredicateType(name, asserts, targetType); }, // Never inferred by TS 4.0, could potentially change in a future TS version. convertType: requestBugReport, }; // This is a horrible thing... we're going to want to split this into converters // for different types at some point. const typeLiteralConverter: TypeConverter<ts.TypeLiteralNode> = { kind: [ts.SyntaxKind.TypeLiteral], convert(context, node) { const symbol = context.getSymbolAtLocation(node) ?? node.symbol; const type = context.getTypeAtLocation(node); if (!symbol || !type) { return new IntrinsicType("Object"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.TypeLiteral, context.scope ); const rc = context.withScope(reflection); rc.setConvertingTypeNode(); context.registerReflection(reflection, symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node); for (const prop of context.checker.getPropertiesOfType(type)) { convertSymbol(rc, prop); } for (const signature of type.getCallSignatures()) { createSignature(rc, ReflectionKind.CallSignature, signature); } convertIndexSignature(rc, symbol); return new ReflectionType(reflection); }, convertType(context, type) { if (!type.symbol) { return new IntrinsicType("Object"); } const reflection = new DeclarationReflection( "__type", ReflectionKind.TypeLiteral, context.scope ); context.registerReflection(reflection, type.symbol); context.trigger(ConverterEvents.CREATE_DECLARATION, reflection); for (const prop of context.checker.getPropertiesOfType(type)) { convertSymbol(context.withScope(reflection), prop); } for (const signature of type.getCallSignatures()) { createSignature( context.withScope(reflection), ReflectionKind.CallSignature, signature ); } convertIndexSignature(context.withScope(reflection), type.symbol); return new ReflectionType(reflection); }, }; const queryConverter: TypeConverter<ts.TypeQueryNode> = { kind: [ts.SyntaxKind.TypeQuery], convert(context, node) { const querySymbol = context.getSymbolAtLocation(node.exprName); if (!querySymbol) { // This can happen if someone uses `typeof` on some property // on a variable typed as `any` with a name that doesn't exist. return new QueryType( ReferenceType.createBrokenReference( node.exprName.getText(), context.project ) ); } return new QueryType( new ReferenceType( node.exprName.getText(), context.resolveAliasedSymbol(querySymbol), context.project ) ); }, convertType(context, type) { const symbol = type.getSymbol(); assert( symbol, `Query type failed to get a symbol for: ${context.checker.typeToString( type )}. This is a bug.` ); return new QueryType( new ReferenceType( symbol.name, context.resolveAliasedSymbol(symbol), context.project ) ); }, }; const referenceConverter: TypeConverter< ts.TypeReferenceNode, ts.TypeReference > = { kind: [ts.SyntaxKind.TypeReference], convert(context, node) { const isArray = context.checker.typeToTypeNode( context.checker.getTypeAtLocation(node.typeName), void 0, ts.NodeBuilderFlags.IgnoreErrors )?.kind === ts.SyntaxKind.ArrayType; if (isArray) { return new ArrayType(convertType(context, node.typeArguments?.[0])); } const symbol = context.expectSymbolAtLocation(node.typeName); const name = node.typeName.getText(); const type = new ReferenceType( name, context.resolveAliasedSymbol(symbol), context.project ); type.typeArguments = node.typeArguments?.map((type) => convertType(context, type) ); return type; }, convertType(context, type) { const symbol = type.aliasSymbol ?? type.getSymbol(); if (!symbol) { // This happens when we get a reference to a type parameter // created within a mapped type, `K` in: `{ [K in T]: string }` return ReferenceType.createBrokenReference( context.checker.typeToString(type), context.project ); } const ref = new ReferenceType( symbol.name, context.resolveAliasedSymbol(symbol), context.project ); ref.typeArguments = ( type.aliasSymbol ? type.aliasTypeArguments : type.typeArguments )?.map((ref) => convertType(context, ref)); return ref; }, }; const restConverter: TypeConverter<ts.RestTypeNode> = { kind: [ts.SyntaxKind.RestType], convert(context, node) { return new RestType(convertType(context, node.type)); }, // This is handled in the tuple converter convertType: requestBugReport, }; const namedTupleMemberConverter: TypeConverter<ts.NamedTupleMember> = { kind: [ts.SyntaxKind.NamedTupleMember], convert(context, node) { const innerType = convertType(context, node.type); return new NamedTupleMember( node.name.getText(), !!node.questionToken, innerType ); }, // This ought to be impossible. convertType: requestBugReport, }; // { -readonly [K in string]-?: number} // ^ readonlyToken // ^ typeParameter // ^^^^^^ typeParameter.constraint // ^ questionToken // ^^^^^^ type const mappedConverter: TypeConverter< ts.MappedTypeNode, ts.Type & { // Beware! Internal TS API here. templateType: ts.Type; typeParameter: ts.TypeParameter; constraintType: ts.Type; nameType?: ts.Type; } > = { kind: [ts.SyntaxKind.MappedType], convert(context, node) { const optionalModifier = kindToModifier(node.questionToken?.kind); const templateType = convertType(context, node.type); return new MappedType( node.typeParameter.name.text, convertType(context, node.typeParameter.constraint), optionalModifier === "+" ? removeUndefined(templateType) : templateType, kindToModifier(node.readonlyToken?.kind), optionalModifier, node.nameType ? convertType(context, node.nameType) : void 0 ); }, convertType(context, type, node) { // This can happen if a generic function does not have a return type annotated. const optionalModifier = kindToModifier(node.questionToken?.kind); const templateType = convertType(context, type.templateType); return new MappedType( type.typeParameter.symbol?.name, convertType(context, type.typeParameter.getConstraint()), optionalModifier === "+" ? removeUndefined(templateType) : templateType, kindToModifier(node.readonlyToken?.kind), optionalModifier, type.nameType ? convertType(context, type.nameType) : void 0 ); }, }; const literalTypeConverter: TypeConverter<ts.LiteralTypeNode, ts.LiteralType> = { kind: [ts.SyntaxKind.LiteralType], convert(context, node) { switch (node.literal.kind) { case ts.SyntaxKind.TrueKeyword: case ts.SyntaxKind.FalseKeyword: return new LiteralType( node.literal.kind === ts.SyntaxKind.TrueKeyword ); case ts.SyntaxKind.StringLiteral: return new LiteralType(node.literal.text); case ts.SyntaxKind.NumericLiteral: return new LiteralType(Number(node.literal.text)); case ts.SyntaxKind.NullKeyword: return new LiteralType(null); case ts.SyntaxKind.PrefixUnaryExpression: { const operand = (node.literal as ts.PrefixUnaryExpression) .operand; switch (operand.kind) { case ts.SyntaxKind.NumericLiteral: return new LiteralType( Number(node.literal.getText()) ); case ts.SyntaxKind.BigIntLiteral: return new LiteralType( BigInt(node.literal.getText().replace("n", "")) ); default: return requestBugReport(context, node.literal); } } case ts.SyntaxKind.BigIntLiteral: return new LiteralType( BigInt(node.literal.getText().replace("n", "")) ); case ts.SyntaxKind.NoSubstitutionTemplateLiteral: return new LiteralType(node.literal.text); } return requestBugReport(context, node.literal); }, convertType(_context, type, node) { switch (node.literal.kind) { case ts.SyntaxKind.StringLiteral: return new LiteralType(node.literal.text); case ts.SyntaxKind.NumericLiteral: return new LiteralType(+node.literal.text); case ts.SyntaxKind.TrueKeyword: case ts.SyntaxKind.FalseKeyword: return new LiteralType( node.literal.kind === ts.SyntaxKind.TrueKeyword ); case ts.SyntaxKind.NullKeyword: return new LiteralType(null); } if (typeof type.value === "object") { return new LiteralType( BigInt( `${type.value.negative ? "-" : ""}${ type.value.base10Value }` ) ); } return new LiteralType(type.value); }, }; const templateLiteralConverter: TypeConverter< ts.TemplateLiteralTypeNode, ts.TemplateLiteralType > = { kind: [ts.SyntaxKind.TemplateLiteralType], convert(context, node) { return new TemplateLiteralType( node.head.text, node.templateSpans.map((span) => { return [convertType(context, span.type), span.literal.text]; }) ); }, convertType(context, type) { assert(type.texts.length === type.types.length + 1); const parts: [Type, string][] = []; for (const [a, b] of zip(type.types, type.texts.slice(1))) { parts.push([convertType(context, a), b]); } return new TemplateLiteralType(type.texts[0], parts); }, }; const thisConverter: TypeConverter<ts.ThisTypeNode> = { kind: [ts.SyntaxKind.ThisType], convert() { return new IntrinsicType("this"); }, convertType() { return new IntrinsicType("this"); }, }; const tupleConverter: TypeConverter<ts.TupleTypeNode, ts.TupleTypeReference> = { kind: [ts.SyntaxKind.TupleType], convert(context, node) { const elements = node.elements.map((node) => convertType(context, node) ); return new TupleType(elements); }, convertType(context, type, node) { const types = type.typeArguments?.slice(0, node.elements.length); let elements = types?.map((type) => convertType(context, type)); if (type.target.labeledElementDeclarations) { const namedDeclarations = type.target.labeledElementDeclarations; elements = elements?.map( (el, i) => new NamedTupleMember( namedDeclarations[i].name.getText(), !!namedDeclarations[i].questionToken, removeUndefined(el) ) ); } elements = elements?.map((el, i) => { if (type.target.elementFlags[i] & ts.ElementFlags.Variable) { // In the node case, we don't need to add the wrapping Array type... but we do here. if (el instanceof NamedTupleMember) { return new RestType( new NamedTupleMember( el.name, el.isOptional, new ArrayType(el.element) ) ); } return new RestType(new ArrayType(el)); } if ( type.target.elementFlags[i] & ts.ElementFlags.Optional && !(el instanceof NamedTupleMember) ) { return new OptionalType(removeUndefined(el)); } return el; }); return new TupleType(elements ?? []); }, }; const supportedOperatorNames = { [ts.SyntaxKind.KeyOfKeyword]: "keyof", [ts.SyntaxKind.UniqueKeyword]: "unique", [ts.SyntaxKind.ReadonlyKeyword]: "readonly", } as const; const typeOperatorConverter: TypeConverter<ts.TypeOperatorNode> = { kind: [ts.SyntaxKind.TypeOperator], convert(context, node) { return new TypeOperatorType( convertType(context, node.type), supportedOperatorNames[node.operator] ); }, convertType(context, type, node) { // readonly is only valid on array and tuple literal types. if (node.operator === ts.SyntaxKind.ReadonlyKeyword) { const resolved = resolveReference(type); assert(isObjectType(resolved)); const args = context.checker .getTypeArguments(type as ts.TypeReference) .map((type) => convertType(context, type)); const inner = resolved.objectFlags & ts.ObjectFlags.Tuple ? new TupleType(args) : new ArrayType(args[0]); return new TypeOperatorType(inner, "readonly"); } // keyof will only show up with generic functions, otherwise it gets eagerly // resolved to a union of strings. if (node.operator === ts.SyntaxKind.KeyOfKeyword) { // TS 4.2 added this to enable better tracking of type aliases. if (type.isUnion() && type.origin) { return convertType(context, type.origin); } // There's probably an interface for this somewhere... I couldn't find it. const targetType = (type as ts.Type & { type: ts.Type }).type; return new TypeOperatorType( convertType(context, targetType), "keyof" ); } // TS drops `unique` in `unique symbol` everywhere. If someone used it, we ought // to have a type node. This shouldn't ever happen. return requestBugReport(context, type); }, }; const unionConverter: TypeConverter<ts.UnionTypeNode, ts.UnionType> = { kind: [ts.SyntaxKind.UnionType], convert(context, node) { return new UnionType( node.types.map((type) => convertType(context, type)) ); }, convertType(context, type) { // TS 4.2 added this to enable better tracking of type aliases. if (type.origin) { return convertType(context, type.origin); } return new UnionType( type.types.map((type) => convertType(context, type)) ); }, }; const jsDocNullableTypeConverter: TypeConverter<ts.JSDocNullableType> = { kind: [ts.SyntaxKind.JSDocNullableType], convert(context, node) { return new UnionType([ convertType(context, node.type), new LiteralType(null), ]); }, // Should be a UnionType convertType: requestBugReport, }; const jsDocNonNullableTypeConverter: TypeConverter<ts.JSDocNonNullableType> = { kind: [ts.SyntaxKind.JSDocNonNullableType], convert(context, node) { return convertType(context, node.type); }, // Should be a UnionType convertType: requestBugReport, }; function requestBugReport(context: Context, nodeOrType: ts.Node | ts.Type) { if ("kind" in nodeOrType) { const kindName = ts.SyntaxKind[nodeOrType.kind]; const { line, character } = ts.getLineAndCharacterOfPosition( nodeOrType.getSourceFile(), nodeOrType.pos ); context.logger.warn( `Failed to convert type node with kind: ${kindName} and text ${nodeOrType.getText()}. Please report a bug.\n\t` + `${nodeOrType.getSourceFile().fileName}:${ line + 1 }:${character}` ); return new UnknownType(nodeOrType.getText()); } else { const typeString = context.checker.typeToString(nodeOrType); context.logger.warn( `Failed to convert type: ${typeString} when converting ${context.scope.getFullName()}. Please report a bug.` ); return new UnknownType(typeString); } } function isObjectType(type: ts.Type): type is ts.ObjectType { return typeof (type as any).objectFlags === "number"; } function resolveReference(type: ts.Type) { if (isObjectType(type) && type.objectFlags & ts.ObjectFlags.Reference) { return (type as ts.TypeReference).target; } return type; } function kindToModifier( kind: | ts.SyntaxKind.PlusToken | ts.SyntaxKind.MinusToken | ts.SyntaxKind.ReadonlyKeyword | ts.SyntaxKind.QuestionToken | undefined ): "+" | "-" | undefined { switch (kind) { case ts.SyntaxKind.ReadonlyKeyword: case ts.SyntaxKind.QuestionToken: case ts.SyntaxKind.PlusToken: return "+"; case ts.SyntaxKind.MinusToken: return "-"; default: return undefined; } }
the_stack
import { EventEmitter, Input, OnInit, Output, Directive } from '@angular/core'; import { AbstractControl, ControlValueAccessor, Validator } from '@angular/forms'; import { convertDateToISODate, convertDateToISOExtended, convertIsoToDate, convertToBoolean, formatYear, getShortBrowserLanguage, isTypeof, setYearFrom0To100, validateDateRange } from '../../../utils/util'; import { dateFailed, requiredFailed } from './../validators'; import { InputBoolean } from '../../../decorators'; import { PoMask } from '../po-input/po-mask'; import { PoDatepickerIsoFormat } from './enums/po-datepicker-iso-format.enum'; import { PoLanguageService } from '../../../services/po-language/po-language.service'; import { poLocaleDefault } from '../../../services/po-language/po-language.constant'; const poDatepickerFormatDefault: string = 'dd/mm/yyyy'; /** * @description * * O `po-datepicker` é um componente específico para manipulação de datas permitindo a digitação e / ou seleção. * * O formato de exibição da data, ou seja, o formato que é apresentado ao usuário é o dd/mm/yyyy, * mas podem ser definidos outros padrões (veja mais na propriedade `p-format`). * * O idioma padrão do calendário será exibido de acordo com o navegador, caso tenha necessidade de alterar * use a propriedade `p-locale`. * * O datepicker aceita três formatos de data: o E8601DZw (yyyy-mm-ddThh:mm:ss+|-hh:mm), o E8601DAw (yyyy-mm-dd) e o * Date padrão do Javascript. * * > Por padrão, o formato de saída do *model* se ajustará conforme o formato de entrada. Se por acaso precisar controlar o valor de saída, * a propriedade `p-iso-format` provê esse controle independentemente do formato de entrada. Veja abaixo os formatos disponíveis: * * - Formato de entrada e saída (E8601DZw) - `'2017-11-28T00:00:00-02:00'`; * * - Formato de entrada e saída (E8601DAw) - `'2017-11-28'`; * * - Formato de entrada (Date) - `new Date(2017, 10, 28)` e saída (E8601DAw) - `'2017-11-28'`; * * **Importante:** * * - Para utilizar datas com ano inferior a 100, verificar o comportamento do [`new Date`](https://www.w3schools.com/js/js_dates.asp) * e utilizar o método [`setFullYear`](https://www.w3schools.com/jsref/jsref_setfullyear.asp). * - Caso a data esteja inválida, o `model` receberá **'Data inválida'**. * - Caso o `input` esteja passando um `[(ngModel)]`, mas não tenha um `name`, então irá ocorrer um erro * do próprio Angular (`[ngModelOptions]="{standalone: true}"`). * * Exemplo: * * ``` * <po-datepicker * [(ngModel)]="pessoa.nome" * [ngModelOptions]="{standalone: true}" * </po-datepicker> * ``` * * > Não esqueça de importar o `FormsModule` em seu módulo, tal como para utilizar o `input default`. */ @Directive() export abstract class PoDatepickerBaseComponent implements ControlValueAccessor, OnInit, Validator { /** * @optional * * @description * * Aplica foco no elemento ao ser iniciado. * * > Caso mais de um elemento seja configurado com essa propriedade, apenas o último elemento declarado com ela terá o foco. * * @default `false` */ @Input('p-auto-focus') @InputBoolean() autoFocus: boolean = false; /* Nome do componente datepicker. */ @Input('name') name: string; /** * @optional * * @description * * Define se a indicação de campo opcional será exibida. * * > Não será exibida a indicação se: * - O campo conter `p-required`; * - Não possuir `p-help` e/ou `p-label`. * * @default `false` */ @Input('p-optional') optional: boolean; /** * Mensagem apresentada quando a data for inválida ou fora do período. * * > Esta mensagem não é apresentada quando o campo estiver vazio, mesmo que ele seja obrigatório. */ @Input('p-error-pattern') errorPattern?: string = ''; /** * @optional * * @description * * Evento disparado ao sair do campo. */ @Output('p-blur') onblur: EventEmitter<any> = new EventEmitter<any>(); /** * @optional * * @description * * Evento disparado ao alterar valor do campo. */ @Output('p-change') onchange: EventEmitter<any> = new EventEmitter<any>(); protected firstStart = true; protected hour: string = 'T00:00:01-00:00'; protected isExtendedISO: boolean = false; protected objMask: any; protected onChangeModel: any = null; protected validatorChange: any; protected onTouchedModel: any = null; private _format?: string = poDatepickerFormatDefault; private _isoFormat: PoDatepickerIsoFormat; private _maxDate: Date; private _minDate: Date; private _noAutocomplete?: boolean = false; private _placeholder?: string = ''; private shortLanguage: string; private previousValue: any; private _date: Date; /** * @optional * * @description * * Define a propriedade nativa `autocomplete` do campo como `off`. * * @default `false` */ @Input('p-no-autocomplete') set noAutocomplete(value: boolean) { this._noAutocomplete = convertToBoolean(value); } get noAutocomplete() { return this._noAutocomplete; } /** * @optional * * @description * * Mensagem que aparecerá enquanto o campo não estiver preenchido. */ @Input('p-placeholder') set placeholder(placeholder: string) { this._placeholder = isTypeof(placeholder, 'string') ? placeholder : ''; } get placeholder() { return this._placeholder; } /** Desabilita o campo. */ // eslint-disable-next-line @typescript-eslint/member-ordering disabled?: boolean = false; @Input('p-disabled') set setDisabled(disabled: string) { this.disabled = disabled === '' ? true : convertToBoolean(disabled); this.validateModel(convertDateToISOExtended(this.date, this.hour)); } /** Torna o elemento somente leitura. */ // eslint-disable-next-line @typescript-eslint/member-ordering readonly?: boolean = false; @Input('p-readonly') set setReadonly(readonly: string) { this.readonly = readonly === '' ? true : convertToBoolean(readonly); } /** Faz com que o campo seja obrigatório. */ // eslint-disable-next-line @typescript-eslint/member-ordering required?: boolean = false; @Input('p-required') set setRequired(required: string) { this.required = required === '' ? true : convertToBoolean(required); this.validateModel(convertDateToISOExtended(this.date, this.hour)); } /** Habilita ação para limpar o campo. */ // eslint-disable-next-line @typescript-eslint/member-ordering clean?: boolean = false; @Input('p-clean') set setClean(clean: string) { this.clean = clean === '' ? true : convertToBoolean(clean); } /** * @optional * * @description * * Define uma data mínima para o `po-datepicker`. */ @Input('p-min-date') set minDate(value: string | Date) { if (value instanceof Date) { const year = value.getFullYear(); const date = new Date(year, value.getMonth(), value.getDate(), 0, 0, 0); setYearFrom0To100(date, year); this._minDate = date; } else { this._minDate = convertIsoToDate(value, true, false); } this.validateModel(convertDateToISOExtended(this.date, this.hour)); } get minDate() { return this._minDate; } /** * @optional * * @description * * Define uma data máxima para o `po-datepicker`. */ @Input('p-max-date') set maxDate(value: string | Date) { if (value instanceof Date) { const year = value.getFullYear(); const date = new Date(year, value.getMonth(), value.getDate(), 23, 59, 59); setYearFrom0To100(date, year); this._maxDate = date; } else { this._maxDate = convertIsoToDate(value, false, true); } this.validateModel(convertDateToISOExtended(this.date, this.hour)); } get maxDate() { return this._maxDate; } /** * @optional * * @description * * Formato de exibição da data. * * Valores válidos: * - `dd/mm/yyyy` * - `mm/dd/yyyy` * - `yyyy/mm/dd` * * @default `dd/mm/yyyy` */ @Input('p-format') set format(value: string) { if (value) { value = value.toLowerCase(); if (value.match(/dd/) && value.match(/mm/) && value.match(/yyyy/)) { this._format = value; this.objMask = this.buildMask(); this.refreshValue(this.date); return; } } this._format = poDatepickerFormatDefault; this.objMask = this.buildMask(); } get format() { return this._format; } /** * @optional * * @description * * Padrão de formatação para saída do *model*, independentemente do formato de entrada. * * > Veja os valores válidos no *enum* `PoDatepickerIsoFormat`. */ @Input('p-iso-format') set isoFormat(value: PoDatepickerIsoFormat) { if (Object.values(PoDatepickerIsoFormat).includes(value)) { this._isoFormat = value; this.isExtendedISO = value === PoDatepickerIsoFormat.Extended; } } get isoFormat() { return this._isoFormat; } /** * @optional * * @description * * Idioma do Datepicker. * * > O locale padrão sera recuperado com base no [`PoI18nService`](/documentation/po-i18n) ou *browser*. */ // eslint-disable-next-line @typescript-eslint/member-ordering _locale?: string; @Input('p-locale') set locale(value: string) { if (value) { this._locale = value.length >= 2 ? value : poLocaleDefault; } else { this._locale = this.shortLanguage; } } get locale() { return this._locale || this.shortLanguage; } constructor(private languageService: PoLanguageService) { this.shortLanguage = this.languageService.getShortLanguage(); } set date(value: any) { this._date = typeof value === 'string' ? convertIsoToDate(value, false, false) : value; } get date() { return this._date; } ngOnInit() { // Classe de máscara this.objMask = this.buildMask(); } // Converte um objeto string em Date getDateFromString(dateString: string) { const day = parseInt(dateString.substring(this.format.indexOf('d'), this.format.indexOf('d') + 2), 10); const month = parseInt(dateString.substring(this.format.indexOf('m'), this.format.indexOf('m') + 2), 10) - 1; const year = parseInt(dateString.substring(this.format.indexOf('y'), this.format.indexOf('y') + 4), 10); const date = new Date(year, month, day); setYearFrom0To100(date, year); return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day ? date : null; } // Formata a data. formatToDate(value: Date) { let dateFormatted = this.format; dateFormatted = dateFormatted.replace('dd', ('0' + value.getDate()).slice(-2)); dateFormatted = dateFormatted.replace('mm', ('0' + (value.getMonth() + 1)).slice(-2)); dateFormatted = dateFormatted.replace('yyyy', formatYear(value.getFullYear())); return dateFormatted; } // Método responsável por controlar o modelo. controlModel(date: Date) { this.date = date; if (date && this.isExtendedISO) { this.callOnChange(convertDateToISOExtended(this.date, this.hour)); } else if (date && !this.isExtendedISO) { this.callOnChange(convertDateToISODate(this.date)); } else { date === undefined ? this.callOnChange('') : this.callOnChange('Data inválida'); } } // Executa a função onChange callOnChange(value: any, retry: boolean = true) { if (this.onChangeModel && value !== this.previousValue) { this.onChangeModel(value); this.previousValue = value; } else if (retry) { setTimeout(() => this.callOnChange(value, false)); } } // Função implementada do ControlValueAccessor // Usada para interceptar os estados de habilitado via forms api setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } // Função implementada do ControlValueAccessor // Usada para interceptar as mudanças e não atualizar automaticamente o Model registerOnChange(func: any): void { this.onChangeModel = func; } // Função implementada do ControlValueAccessor // Usada para interceptar as mudanças e não atualizar automaticamente o Model registerOnTouched(func: any): void { this.onTouchedModel = func; } registerOnValidatorChange(fn: () => void) { this.validatorChange = fn; } validate(c: AbstractControl): { [key: string]: any } { // Verifica se já possui algum error pattern padrão. this.errorPattern = this.errorPattern !== 'Data inválida' && this.errorPattern !== 'Data fora do período' ? this.errorPattern : ''; if (dateFailed(c.value)) { this.errorPattern = this.errorPattern || 'Data inválida'; return { date: { valid: false } }; } if (requiredFailed(this.required, this.disabled, c.value)) { return { required: { valid: false } }; } if (this.date && !validateDateRange(this.date, this._minDate, this._maxDate)) { this.errorPattern = this.errorPattern || 'Data fora do período'; return { date: { valid: false } }; } return null; } protected validateModel(model: any) { if (this.validatorChange) { this.validatorChange(model); } } // Retorna um objeto do tipo PoMask com a mascara configurada. protected buildMask() { let mask = this.format.toUpperCase(); mask = mask.replace(/DD/g, '99'); mask = mask.replace(/MM/g, '99'); mask = mask.replace(/YYYY/g, '9999'); return new PoMask(mask, true); } abstract writeValue(value: any): void; abstract refreshValue(value: Date): void; }
the_stack
import { dialog, MessageBoxReturnValue, app, Event } from 'electron'; import { CommonInterfaces } from './interfaces/interface.common'; import { IApplication, EExitCodes } from './interfaces/interface.app'; import * as FS from './tools/fs'; import Logger from './tools/env.logger'; import LogsService from './tools/env.logger.service'; // Services import ServiceElectron from './services/service.electron'; import ServiceNotifications from './services/service.notifications'; import ServicePackage from './services/service.package'; import ServiceEnv from './services/service.env'; import ServiceHotkeys from './services/service.hotkeys'; import ServicePaths, { getHomeFolder } from './services/service.paths'; import ServiceUserPaths from './services/service.paths.user'; import ServiceNetwork from './services/service.network'; import ServicePlugins from './services/service.plugins'; import ServiceStreams from './services/service.streams'; import ServiceSettings from './services/service.settings'; import ServiceConfigDefault from './services/service.settings.default'; import ServiceStorage from './services/service.storage'; import ServiceWindowState from './services/service.window.state'; import ServiceElectronState from './services/service.electron.state'; import ServiceProduction from './services/service.production'; import ServiceFileInfo from './services/files/service.file.info'; import ServiceMergeFiles from './services/features/service.merge.files'; import ServiceConcatFiles from './services/features/service.concat.files'; import ServiceTimestamp from './services/features/service.timestamp'; import ServiceFileReader from './services/files/service.file.reader'; import ServiceFileSearch from './services/files/service.file.search'; import ServiceFileOpener from './services/files/service.file.opener'; import ServiceFilePicker from './services/files/service.file.picker'; import ServiceFileRecent from './services/files/service.file.recent'; import ServiceFileWriter from './services/files/service.file.writer'; import ServiceStreamSources from './services/service.stream.sources'; import ServiceFilters from './services/service.filters'; import ServiceAppState from './services/service.app.state'; import ServiceUpdate from './services/service.update'; import ServiceDLTFiles from './services/parsers/service.dlt.files'; import ServicePatchesBefore from './services/service.patches.before'; import ServiceDLTDeamonConnector from './services/connectors/service.dlt.deamon'; import ServiceOutputExport from './services/output/service.output.export'; import ServiceRenderState from './services/service.render.state'; import ServiceLogs from './services/service.logs'; import ServiceLogsExtractor from './services/service.logs.extractor'; import ServiceReleaseNotes from './services/service.release.notes'; import ServiceCLI from './services/service.cli'; import ServiceTimestampFormatRecent from './services/features/service.timestamp.recent'; import ServiceImporter from './services/service.importer'; import { IService } from './interfaces/interface.service'; type THook = () => Promise<void>; interface IHook { name: string; fn: THook; } enum EAppState { initing = 'initing', working = 'working', destroying = 'destroying', } export class CloseProcessRunning extends Error { constructor() { super(); } } const InitializeStages = [ // Apply patches ("before") [ ServicePatchesBefore ], // Stage #1. Detect OS env [ ServiceEnv ], // Stage #2 [ ServiceProduction ], // Stage #3 [ ServicePaths ], // Stage #4 [ ServicePackage ], // Stage #5 [ ServiceSettings, ServiceWindowState, ServiceStorage ], [ ServiceConfigDefault ], // Stage #6. Init custom user paths and electron. Prepare browser window [ ServiceUserPaths, ServiceNetwork, ServiceElectron ], // Stage #7. Render logs service [ ServiceLogs ], // Stage #8. Init services and helpers [ ServiceElectronState, ServiceNotifications, ServiceRenderState ], // Stage #9. Stream service [ ServiceStreamSources, ServiceStreams ], // Stage #10. Common functionality [ ServiceFileInfo, ServiceMergeFiles, ServiceConcatFiles, ServiceFileSearch, ServiceFilters, ServiceFileReader, ServiceFileOpener, ServiceAppState, ServiceDLTFiles, ServiceHotkeys, ServiceFilePicker, ServiceDLTDeamonConnector, ServiceOutputExport, ServiceLogsExtractor, ServiceFileRecent, ServiceTimestamp, ServiceFileWriter, ServiceTimestampFormatRecent, ServiceImporter, ], // Stage #10. Init plugins and current release data [ ServicePlugins, ServiceReleaseNotes, ServiceCLI ], // (last service should startup service and should be single always) [ ServiceUpdate ], ]; // tslint:disable-next-line: max-classes-per-file class Application implements IApplication { private _logger: Logger = new Logger('Application'); private _state: EAppState = EAppState.initing; private _code: EExitCodes = EExitCodes.normal; /** * Initialization of application * Will start application in case of success of initialization * @returns void */ public init(): Promise<Application> { return new Promise((resolve, reject) => { this._initGlobalNamespace(); this._bindProcessEvents(); this._init(0, (error?: Error) => { if (error instanceof Error) { const dialogOpts = { type: 'info', buttons: ['Drop settings and close', 'Close'], title: 'Error', message: `Sorry, it looks like we have a problems with starting. You can try to drop settings and start it again.`, detail: `Error: ${error.message}`, }; dialog.showMessageBox(dialogOpts).then((response: MessageBoxReturnValue) => { this._logger.debug(`Selected option: ${response}`); switch (response.response) { case 0: FS.rmdir(getHomeFolder()).then(() => { app.quit(); }).catch((errorRmdir: Error) => { this._logger.error(`Fail to drop settings due error: ${errorRmdir.message}`); app.quit(); }); break; case 1: app.quit(); break; } }); return reject(error); } // All done const hooks: IHook[] = []; InitializeStages.forEach((services: IService[]) => { services.forEach((service: IService) => { if (typeof service.afterAppInit === 'function') { hooks.push({ name: service.getName(), fn: service.afterAppInit}); } }); }); Promise.all(hooks.map((info: IHook) => { return info.fn.bind(this); })).then(() => { resolve(this); }).catch((err: Error) => { this._logger.error(`Services failed to be initialized on afterAppInit due to error: ${err.message}`); }); resolve(this); }); }); } public destroy(code: EExitCodes = EExitCodes.normal): Promise<void> { return new Promise((resolve, reject) => { if (code !== EExitCodes.normal) { this._code = code; } if (this._state === EAppState.destroying) { // Destroy method was already called. return reject(new CloseProcessRunning()); } this._state = EAppState.destroying; // Lock IPC ServiceElectron.lock(); // Close window ServiceElectron.closeWindow().then(() => { this._logger.debug(`Browser window is closed`); }).catch((closeWinErr: Error) => { this._logger.warn(`Fail to close browser window before close due error: ${closeWinErr.message}`); }).finally(() => { // Close all active sessions ServiceStreams.closeAll().then(() => { this._logger.debug(`All streams are closed`); }).catch((closeErr: Error) => { this._logger.warn(`Fail to close all session before close due error: ${closeErr.message}`); }).finally(() => { // Shutdown all plugins ServicePlugins.accomplish().then(() => { this._logger.debug(`All plugins actions are accomplish`); }).catch((shutdownErr: Error) => { this._logger.warn(`Fail to accomplish plugins actions due error: ${shutdownErr.message}`); }).finally(() => { // Shutdown application this._destroy(InitializeStages.length - 1, (destroyErr?: Error) => { if (destroyErr instanceof Error) { // tslint:disable-next-line: no-console console.log(`Fail destroy due error: ${destroyErr.message}`); } this._quit().catch((quitErr: Error) => { // tslint:disable-next-line: no-console console.log(`Fail quit due error: ${quitErr.message}`); }).finally(() => { resolve(); }); }); }); }); }); }); } public getLogger(): Logger { return this._logger; } private _init(stage: number = 0, callback: (error?: Error) => any): void { if (InitializeStages.length <= stage) { this._logger.debug(`Application is initialized`); this._state = EAppState.working; if (typeof callback === 'function') { callback(); } return; } this._logger.debug(`Application initialization: stage #${stage + 1}: starting...`); const services: any[] = InitializeStages[stage]; const tasks: Array<Promise<any>> = services.map((ref: any) => { this._logger.debug(`Init: ${ref.getName()}`); return ref.init(this).catch((err: Error) => { this._logger.error(`${ref.getName()}: ${err.message}`); return Promise.reject(err); }); }); if (tasks.length === 0) { return this._init(stage + 1, callback); } Promise.all(tasks).then(() => { this._logger.debug(`Application initialization: stage #${stage + 1}: OK`); this._init(stage + 1, callback); }).catch((error: Error) => { this._logger.debug(`Fail to initialize application dure error: ${error.message}`); callback(error); }); } private _destroy(stage: number = 0, callback: (error?: Error) => any): void { if (stage < 0) { this._logger.debug(`Application is destroyed`); if (typeof callback === 'function') { callback(); } return; } this._logger.debug(`Application destroy: stage #${stage + 1}: starting...`); const services: any[] = InitializeStages[stage]; const tasks: Array<Promise<any>> = services.map((ref: any) => { this._logger.debug(`Destroy: ${ref.getName()}: started...`); return ref.destroy().then(() => { this._logger.debug(`Destroy: ${ref.getName()}: DONE`); }).catch((err: Error) => { this._logger.error(`Destroy: ${ref.getName()}: FAILED due: ${err.message}`); }); }); if (tasks.length === 0) { return this._destroy(stage - 1, callback); } Promise.all(tasks).then(() => { this._logger.debug(`Application destroyed: stage #${stage + 1}: OK`); this._destroy(stage - 1, callback); }).catch((error: Error) => { this._logger.debug(`Fail to destroy application dure error: ${error.message}`); callback(error); }); } private _bindProcessEvents() { process.once('exit', this._onClose.bind(this)); process.once('SIGINT', this._onClose.bind(this)); process.once('SIGTERM', this._onClose.bind(this)); app.once('will-quit', (event: Event) => { event.preventDefault(); this._onClose(); }); process.on('uncaughtException', this._onUncaughtException.bind(this)); process.on('unhandledRejection', this._onUnhandledRejection.bind(this)); } private _onUnhandledRejection(reason: Error | any, promise: Promise<any>) { if (reason instanceof Error) { this._logger.error(`[BAD] UnhandledRejection: ${reason.message}`); } else { this._logger.error(`[BAD] UnhandledRejection happened. No reason as error was provided.`); } } private _onUncaughtException(error: Error) { this._logger.error(`[BAD] UncaughtException: ${error.message}`); } private _onClose() { this._logger.debug(`Application would be closed.`); process.stdin.resume(); // Destroy services this.destroy().catch((error: Error | CloseProcessRunning) => { if (error instanceof CloseProcessRunning) { return; } this._logger.warn(`Fail correctly close app due error: ${error.message}`); }); } private _quit(): Promise<void> { return new Promise((resolve, reject) => { this._logger.debug(`Application are ready to be closed with code "${this._code}".`); this._logger.debug(`LogsService will be shutdown.`); LogsService.shutdown().then(() => { resolve(); process.exit(this._code); }).catch((error: Error) => { // tslint:disable-next-line: no-console console.log(`Fail shutdown logservice due error: ${error.message}`); reject(error); app.exit(this._code); }); }); } private _initGlobalNamespace() { const gLogger: Logger = new Logger('Global'); const cGlobal: CommonInterfaces.NodeGlobal.IChipmunkNodeGlobal = { logger: { warn: gLogger.warn.bind(gLogger), debug: gLogger.debug.bind(gLogger), env: gLogger.env.bind(gLogger), error: gLogger.error.bind(gLogger), info: gLogger.info.bind(gLogger), verbose: gLogger.verbose.bind(gLogger), wtf: gLogger.wtf.bind(gLogger), }, }; (global as any).chipmunk = cGlobal; } } (new Application()).init().then((application: Application) => { application.getLogger().debug(`Application is ready.`); ServiceSettings.subscribe().then(() => { ServiceElectronState.setStateAsReady(); ServicePlugins.revision(); }).catch((settingsErr: Error) => { application.getLogger().error(`Fail to subscribe settings service due error: ${settingsErr.message}`); }); }).catch((error: Error) => { // tslint:disable-next-line:no-console console.log(error); });
the_stack
import { _global } from "../globals/global"; export const keys = Object.keys; export const isArray = Array.isArray; if (typeof Promise !== 'undefined' && !_global.Promise){ // In jsdom, this it can be the case that Promise is not put on the global object. // If so, we need to patch the global object for the rest of the code to work as expected. // Other dexie code expects Promise to be on the global object (like normal browser environments) _global.Promise = Promise; } export { _global } export function extend<T extends object,X extends object>(obj: T, extension: X): T & X { if (typeof extension !== 'object') return obj as T & X; keys(extension).forEach(function (key) { obj[key] = extension[key]; }); return obj as T & X; } export const getProto = Object.getPrototypeOf; export const _hasOwn = {}.hasOwnProperty; export function hasOwn(obj, prop) { return _hasOwn.call(obj, prop); } export function props (proto, extension) { if (typeof extension === 'function') extension = extension(getProto(proto)); (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(key => { setProp(proto, key, extension[key]); }); } export const defineProperty = Object.defineProperty; export function setProp(obj, prop, functionOrGetSet, options?) { defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} : {value: functionOrGetSet, configurable: true, writable: true}, options)); } export function derive(Child) { return { from: function (Parent) { Child.prototype = Object.create(Parent.prototype); setProp(Child.prototype, "constructor", Child); return { extend: props.bind(null, Child.prototype) }; } }; } export const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; export function getPropertyDescriptor(obj, prop) { const pd = getOwnPropertyDescriptor(obj, prop); let proto; return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop); } const _slice = [].slice; export function slice(args, start?, end?) { return _slice.call(args, start, end); } export function override(origFunc, overridedFactory) { return overridedFactory(origFunc); } export function assert (b) { if (!b) throw new Error("Assertion Failed"); } export function asap(fn) { // @ts-ignore if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0); } export function getUniqueArray(a) { return a.filter((value, index, self) => self.indexOf(value) === index); } /** Generate an object (hash map) based on given array. * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to * instert on the resulting object for each item in the array. If this function returns a falsy value, the * current item wont affect the resulting object. */ export function arrayToObject<T,R> (array: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} { return array.reduce((result, item, i) => { var nameAndValue = extractor(item, i); if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; return result; }, {}); } export function trycatcher(fn, reject) { return function () { try { fn.apply(this, arguments); } catch (e) { reject(e); } }; } export function tryCatch(fn: (...args: any[])=>void, onerror, args?) : void { try { fn.apply(null, args); } catch (ex) { onerror && onerror(ex); } } export function getByKeyPath(obj, keyPath) { // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. if (!keyPath) return obj; if (typeof keyPath !== 'string') { var rv = []; for (var i = 0, l = keyPath.length; i < l; ++i) { var val = getByKeyPath(obj, keyPath[i]); rv.push(val); } return rv; } var period = keyPath.indexOf('.'); if (period !== -1) { var innerObj = obj[keyPath.substr(0, period)]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); } return undefined; } export function setByKeyPath(obj, keyPath, value) { if (!obj || keyPath === undefined) return; if ('isFrozen' in Object && Object.isFrozen(obj)) return; if (typeof keyPath !== 'string' && 'length' in keyPath) { assert(typeof value !== 'string' && 'length' in value); for (var i = 0, l = keyPath.length; i < l; ++i) { setByKeyPath(obj, keyPath[i], value[i]); } } else { var period = keyPath.indexOf('.'); if (period !== -1) { var currentKeyPath = keyPath.substr(0, period); var remainingKeyPath = keyPath.substr(period + 1); if (remainingKeyPath === "") if (value === undefined) { if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1); else delete obj[currentKeyPath]; } else obj[currentKeyPath] = value; else { var innerObj = obj[currentKeyPath]; if (!innerObj || !hasOwn(obj, currentKeyPath)) innerObj = (obj[currentKeyPath] = {}); setByKeyPath(innerObj, remainingKeyPath, value); } } else { if (value === undefined) { if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1); else delete obj[keyPath]; } else obj[keyPath] = value; } } } export function delByKeyPath(obj, keyPath) { if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined); else if ('length' in keyPath) [].map.call(keyPath, function(kp) { setByKeyPath(obj, kp, undefined); }); } export function shallowClone(obj) { var rv = {}; for (var m in obj) { if (hasOwn(obj, m)) rv[m] = obj[m]; } return rv; } const concat = [].concat; export function flatten<T> (a: (T | T[])[]) : T[] { return concat.apply([], a); } //https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm const intrinsicTypeNames = "Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" .split(',').concat( flatten([8,16,32,64].map(num=>["Int","Uint","Float"].map(t=>t+num+"Array"))) ).filter(t=>_global[t]); const intrinsicTypes = intrinsicTypeNames.map(t=>_global[t]); export const intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]); let circularRefs: null | WeakMap<any,any> = null; export function deepClone<T>(any: T): T { circularRefs = typeof WeakMap !== 'undefined' && new WeakMap(); const rv = innerDeepClone(any); circularRefs = null; return rv; } function innerDeepClone<T>(any: T): T { if (!any || typeof any !== 'object') return any; let rv = circularRefs && circularRefs.get(any); // Resolve circular references if (rv) return rv; if (isArray(any)) { rv = []; circularRefs && circularRefs.set(any, rv); for (var i = 0, l = any.length; i < l; ++i) { rv.push(innerDeepClone(any[i])); } } else if (intrinsicTypes.indexOf(any.constructor) >= 0) { rv = any; } else { const proto = getProto(any); rv = proto === Object.prototype ? {} : Object.create(proto); circularRefs && circularRefs.set(any, rv); for (var prop in any) { if (hasOwn(any, prop)) { rv[prop] = innerDeepClone(any[prop]); } } } return rv; } const {toString} = {}; export function toStringTag(o: Object) { return toString.call(o).slice(8, -1); } // If first argument is iterable or array-like, return it as an array export const iteratorSymbol = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; export const getIteratorOf = typeof iteratorSymbol === "symbol" ? function(x) { var i; return x != null && (i = x[iteratorSymbol]) && i.apply(x); } : function () { return null; }; export const asyncIteratorSymbol = typeof Symbol !== 'undefined' ? Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator") : '@asyncIterator'; export const NO_CHAR_ARRAY = {}; // Takes one or several arguments and returns an array based on the following criteras: // * If several arguments provided, return arguments converted to an array in a way that // still allows javascript engine to optimize the code. // * If single argument is an array, return a clone of it. // * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special // case to the two bullets below. // * If single argument is an iterable, convert it to an array and return the resulting array. // * If single argument is array-like (has length of type number), convert it to an array. export function getArrayOf (arrayLike) { var i, a, x, it; if (arguments.length === 1) { if (isArray(arrayLike)) return arrayLike.slice(); if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; if ((it = getIteratorOf(arrayLike))) { a = []; while ((x = it.next()), !x.done) a.push(x.value); return a; } if (arrayLike == null) return [arrayLike]; i = arrayLike.length; if (typeof i === 'number') { a = new Array(i); while (i--) a[i] = arrayLike[i]; return a; } return [arrayLike]; } i = arguments.length; a = new Array(i); while (i--) a[i] = arguments[i]; return a; } export const isAsyncFunction = typeof Symbol !== 'undefined' ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction' : ()=>false;
the_stack
declare type UnionOmit<T, K extends keyof any> = T extends T ? Pick<T, Exclude<keyof T, K>> : never; declare module Mongo { // prettier-ignore type BsonType = 1 | "double" | 2 | "string" | 3 | "object" | 4 | "array" | 5 | "binData" | 6 | "undefined" | 7 | "objectId" | 8 | "bool" | 9 | "date" | 10 | "null" | 11 | "regex" | 12 | "dbPointer" | 13 | "javascript" | 14 | "symbol" | 15 | "javascriptWithScope" | 16 | "int" | 17 | "timestamp" | 18 | "long" | 19 | "decimal" | -1 | "minKey" | 127 | "maxKey" | "number"; type FieldExpression<T> = { $eq?: T | undefined; $gt?: T | undefined; $gte?: T | undefined; $lt?: T | undefined; $lte?: T | undefined; $in?: T[] | undefined; $nin?: T[] | undefined; $ne?: T | undefined; $exists?: boolean | undefined; $type?: BsonType[] | BsonType | undefined; $not?: FieldExpression<T> | undefined; $expr?: FieldExpression<T> | undefined; $jsonSchema?: any; $mod?: number[] | undefined; $regex?: RegExp | string | undefined; $options?: string | undefined; $text?: | { $search: string; $language?: string | undefined; $caseSensitive?: boolean | undefined; $diacriticSensitive?: boolean | undefined; } | undefined; $where?: string | Function | undefined; $geoIntersects?: any; $geoWithin?: any; $near?: any; $nearSphere?: any; $all?: T[] | undefined; $elemMatch?: T extends {} ? Query<T> : FieldExpression<T> | undefined; $size?: number | undefined; $bitsAllClear?: any; $bitsAllSet?: any; $bitsAnyClear?: any; $bitsAnySet?: any; $comment?: string | undefined; }; type Flatten<T> = T extends any[] ? T[0] : T; type Query<T> = { [P in keyof T]?: Flatten<T[P]> | RegExp | FieldExpression<Flatten<T[P]>> } & { $or?: Query<T>[] | undefined; $and?: Query<T>[] | undefined; $nor?: Query<T>[] | undefined; } & Dictionary<any>; type QueryWithModifiers<T> = { $query: Query<T>; $comment?: string | undefined; $explain?: any; $hint?: any; $maxScan?: any; $max?: any; $maxTimeMS?: any; $min?: any; $orderby?: any; $returnKey?: any; $showDiskLoc?: any; $natural?: any; }; type Selector<T> = Query<T> | QueryWithModifiers<T>; type Dictionary<T> = { [key: string]: T }; type PartialMapTo<T, M> = Partial<Record<keyof T, M>>; type OnlyArrays<T> = T extends any[] ? T : never; type OnlyElementsOfArrays<T> = T extends any[] ? Partial<T[0]> : never; type ElementsOf<T> = { [P in keyof T]?: OnlyElementsOfArrays<T[P]>; }; type PushModifier<T> = { [P in keyof T]?: | OnlyElementsOfArrays<T[P]> | { $each?: T[P] | undefined; $position?: number | undefined; $slice?: number | undefined; $sort?: 1 | -1 | Dictionary<number> | undefined; }; }; type ArraysOrEach<T> = { [P in keyof T]?: OnlyElementsOfArrays<T[P]> | { $each: T[P] }; }; type CurrentDateModifier = { $type: 'timestamp' | 'date' } | true; type Modifier<T> = | T | { $currentDate?: | (Partial<Record<keyof T, CurrentDateModifier>> & Dictionary<CurrentDateModifier>) | undefined; $inc?: (PartialMapTo<T, number> & Dictionary<number>) | undefined; $min?: (PartialMapTo<T, Date | number> & Dictionary<Date | number>) | undefined; $max?: (PartialMapTo<T, Date | number> & Dictionary<Date | number>) | undefined; $mul?: (PartialMapTo<T, number> & Dictionary<number>) | undefined; $rename?: (PartialMapTo<T, string> & Dictionary<string>) | undefined; $set?: (Partial<T> & Dictionary<any>) | undefined; $setOnInsert?: (Partial<T> & Dictionary<any>) | undefined; $unset?: (PartialMapTo<T, string | boolean | 1 | 0> & Dictionary<any>) | undefined; $addToSet?: (ArraysOrEach<T> & Dictionary<any>) | undefined; $push?: (PushModifier<T> & Dictionary<any>) | undefined; $pull?: (ElementsOf<T> & Dictionary<any>) | undefined; $pullAll?: (Partial<T> & Dictionary<any>) | undefined; $pop?: (PartialMapTo<T, 1 | -1> & Dictionary<1 | -1>) | undefined; }; type OptionalId<TSchema> = UnionOmit<TSchema, '_id'> & { _id?: any }; interface SortSpecifier {} interface FieldSpecifier { [id: string]: Number; } type Transform<T> = ((doc: T) => any) | null | undefined; type Options<T> = { /** Sort order (default: natural order) */ sort?: SortSpecifier | undefined; /** Number of results to skip at the beginning */ skip?: number | undefined; /** Maximum number of results to return */ limit?: number | undefined; /** Dictionary of fields to return or exclude. */ fields?: FieldSpecifier | undefined; /** (Client only) Default `true`; pass `false` to disable reactivity */ reactive?: boolean | undefined; /** Overrides `transform` on the [`Collection`](#collections) for this cursor. Pass `null` to disable transformation. */ transform?: Transform<T> | undefined; }; type DispatchTransform<Transform, T, U> = Transform extends (...args: any) => any ? ReturnType<Transform> : Transform extends null ? T : U; var Collection: CollectionStatic; interface CollectionStatic { /** * Constructor for a Collection * @param name The name of the collection. If null, creates an unmanaged (unsynchronized) local collection. */ new <T, U = T>( name: string | null, options?: { /** * The server connection that will manage this collection. Uses the default connection if not specified. Pass the return value of calling `DDP.connect` to specify a different * server. Pass `null` to specify no connection. Unmanaged (`name` is null) collections cannot specify a connection. */ connection?: Object | null | undefined; /** The method of generating the `_id` fields of new documents in this collection. Possible values: * - **`'STRING'`**: random strings * - **`'MONGO'`**: random [`Mongo.ObjectID`](#mongo_object_id) values * * The default id generation technique is `'STRING'`. */ idGeneration?: string | undefined; /** * An optional transformation function. Documents will be passed through this function before being returned from `fetch` or `findOne`, and before being passed to callbacks of * `observe`, `map`, `forEach`, `allow`, and `deny`. Transforms are *not* applied for the callbacks of `observeChanges` or to cursors returned from publish functions. */ transform?: (doc: T) => U; /** Set to `false` to skip setting up the mutation methods that enable insert/update/remove from client code. Default `true`. */ defineMutationMethods?: boolean | undefined; }, ): Collection<T, U>; } interface Collection<T, U = T> { allow<Fn extends Transform<T> = undefined>(options: { insert?: ((userId: string, doc: DispatchTransform<Fn, T, U>) => boolean) | undefined; update?: | ((userId: string, doc: DispatchTransform<Fn, T, U>, fieldNames: string[], modifier: any) => boolean) | undefined; remove?: ((userId: string, doc: DispatchTransform<Fn, T, U>) => boolean) | undefined; fetch?: string[] | undefined; transform?: Fn | undefined; }): boolean; createIndex(index: { [key: string]: number | string } | string, options?: any): void; deny<Fn extends Transform<T> = undefined>(options: { insert?: ((userId: string, doc: DispatchTransform<Fn, T, U>) => boolean) | undefined; update?: | ((userId: string, doc: DispatchTransform<Fn, T, U>, fieldNames: string[], modifier: any) => boolean) | undefined; remove?: ((userId: string, doc: DispatchTransform<Fn, T, U>) => boolean) | undefined; fetch?: string[] | undefined; transform?: Fn | undefined; }): boolean; /** * Find the documents in a collection that match the selector. * @param selector A query describing the documents to find */ find(selector?: Selector<T> | ObjectID | string): Cursor<T, U>; /** * Find the documents in a collection that match the selector. * @param selector A query describing the documents to find */ find<O extends Options<T>>( selector?: Selector<T> | ObjectID | string, options?: O, ): Cursor<T, DispatchTransform<O['transform'], T, U>>; /** * Finds the first document that matches the selector, as ordered by sort and skip options. Returns `undefined` if no matching document is found. * @param selector A query describing the documents to find */ findOne(selector?: Selector<T> | ObjectID | string): U | undefined; /** * Finds the first document that matches the selector, as ordered by sort and skip options. Returns `undefined` if no matching document is found. * @param selector A query describing the documents to find */ findOne<O extends Omit<Options<T>, 'limit'>>( selector?: Selector<T> | ObjectID | string, options?: O, ): DispatchTransform<O['transform'], T, U> | undefined; /** * Insert a document in the collection. Returns its unique _id. * @param doc The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you. * @param callback If present, called with an error object as the first argument and, if no error, the _id as the second. */ insert(doc: OptionalId<T>, callback?: Function): string; /** * Returns the [`Collection`](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html) object corresponding to this collection from the * [npm `mongodb` driver module](https://www.npmjs.com/package/mongodb) which is wrapped by `Mongo.Collection`. */ rawCollection(): any; /** * Returns the [`Db`](http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html) object corresponding to this collection's database connection from the * [npm `mongodb` driver module](https://www.npmjs.com/package/mongodb) which is wrapped by `Mongo.Collection`. */ rawDatabase(): any; /** * Remove documents from the collection * @param selector Specifies which documents to remove * @param callback If present, called with an error object as its argument. */ remove(selector: Selector<T> | ObjectID | string, callback?: Function): number; /** * Modify one or more documents in the collection. Returns the number of matched documents. * @param selector Specifies which documents to modify * @param modifier Specifies how to modify the documents * @param callback If present, called with an error object as the first argument and, if no error, the number of affected documents as the second. */ update( selector: Selector<T> | ObjectID | string, modifier: Modifier<T>, options?: { /** True to modify all matching documents; false to only modify one of the matching documents (the default). */ multi?: boolean | undefined; /** True to insert a document if no matching documents are found. */ upsert?: boolean | undefined; /** * Used in combination with MongoDB [filtered positional operator](https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/) to specify which elements to * modify in an array field. */ arrayFilters?: { [identifier: string]: any }[] | undefined; }, callback?: Function, ): number; /** * Modify one or more documents in the collection, or insert one if no matching documents were found. Returns an object with keys `numberAffected` (the number of documents modified) and * `insertedId` (the unique _id of the document that was inserted, if any). * @param selector Specifies which documents to modify * @param modifier Specifies how to modify the documents * @param callback If present, called with an error object as the first argument and, if no error, the number of affected documents as the second. */ upsert( selector: Selector<T> | ObjectID | string, modifier: Modifier<T>, options?: { /** True to modify all matching documents; false to only modify one of the matching documents (the default). */ multi?: boolean | undefined; }, callback?: Function, ): { numberAffected?: number | undefined; insertedId?: string | undefined; }; /** @deprecated */ _ensureIndex(keys: { [key: string]: number | string } | string, options?: { [key: string]: any }): void; _dropIndex(keys: { [key: string]: number | string } | string): void; } var Cursor: CursorStatic; interface CursorStatic { /** * To create a cursor, use find. To access the documents in a cursor, use forEach, map, or fetch. */ new <T, U = T>(): Cursor<T, U>; } interface ObserveCallbacks<T> { added?(document: T): void; addedAt?(document: T, atIndex: number, before: T | null): void; changed?(newDocument: T, oldDocument: T): void; changedAt?(newDocument: T, oldDocument: T, indexAt: number): void; removed?(oldDocument: T): void; removedAt?(oldDocument: T, atIndex: number): void; movedTo?(document: T, fromIndex: number, toIndex: number, before: T | null): void; } interface ObserveChangesCallbacks<T> { added?(id: string, fields: Partial<T>): void; addedBefore?(id: string, fields: Partial<T>, before: T | null): void; changed?(id: string, fields: Partial<T>): void; movedBefore?(id: string, before: T | null): void; removed?(id: string): void; } interface Cursor<T, U = T> { /** * Returns the number of documents that match a query. * @param applySkipLimit If set to `false`, the value returned will reflect the total number of matching documents, ignoring any value supplied for limit. (Default: true) */ count(applySkipLimit?: boolean): number; /** * Return all matching documents as an Array. */ fetch(): Array<U>; /** * Call `callback` once for each matching document, sequentially and * synchronously. * @param callback Function to call. It will be called with three arguments: the document, a 0-based index, and <em>cursor</em> itself. * @param thisArg An object which will be the value of `this` inside `callback`. */ forEach(callback: (doc: U, index: number, cursor: Cursor<T, U>) => void, thisArg?: any): void; /** * Map callback over all matching documents. Returns an Array. * @param callback Function to call. It will be called with three arguments: the document, a 0-based index, and <em>cursor</em> itself. * @param thisArg An object which will be the value of `this` inside `callback`. */ map<M>(callback: (doc: U, index: number, cursor: Cursor<T, U>) => M, thisArg?: any): Array<M>; /** * Watch a query. Receive callbacks as the result set changes. * @param callbacks Functions to call to deliver the result set as it changes */ observe(callbacks: ObserveCallbacks<U>): Meteor.LiveQueryHandle; /** * Watch a query. Receive callbacks as the result set changes. Only the differences between the old and new documents are passed to the callbacks. * @param callbacks Functions to call to deliver the result set as it changes */ observeChanges( callbacks: ObserveChangesCallbacks<T>, options?: { nonMutatingCallbacks?: boolean | undefined }, ): Meteor.LiveQueryHandle; } var ObjectID: ObjectIDStatic; interface ObjectIDStatic { /** * Create a Mongo-style `ObjectID`. If you don't specify a `hexString`, the `ObjectID` will generated randomly (not using MongoDB's ID construction rules). * @param hexString The 24-character hexadecimal contents of the ObjectID to create */ new (hexString?: string): ObjectID; } interface ObjectID { toHexString(): string; equals(otherID: ObjectID): boolean; } function setConnectionOptions(options: any): void; } declare module Mongo { interface AllowDenyOptions { insert?: ((userId: string, doc: any) => boolean) | undefined; update?: ((userId: string, doc: any, fieldNames: string[], modifier: any) => boolean) | undefined; remove?: ((userId: string, doc: any) => boolean) | undefined; fetch?: string[] | undefined; transform?: Function | null | undefined; } } declare interface MongoConnection { db: any; client: any; } declare function defaultRemoteCollectionDriver(): { mongo: MongoConnection; }; declare var NpmModules: any;
the_stack
import * as _ from 'lodash'; // https://github.com/moxiecode/plupload/wiki/Options export namespace Pluploader { // https://github.com/moxiecode/plupload/wiki/Uploader export class Uploader { // Properties id?: string; state?; features?; runtime?; files?; settings?; total?; // Method init?: Function; setOption?: Function; getOption?: Function; refresh?: Function; start?: Function; stop?: Function; disableBrowse?: Function; getFile?: Function; addFile?: Function; removeFile?: Function; splice?: Function; trigger?: Function; hasEventListener?: Function; bind?: Function; unbind?: Function; unbindAll?: Function; destroy?: Function; // Events Init?: Function; PostInit?: Function; OptionChanged?: Function; Refresh?: Function; StateChanged?: Function; Browse?: Function; FileFiltered?: Function; QueueChanged?: Function; FilesAdded?: Function; FilesRemoved?: Function; BeforeUpload?: Function; UploadFile?: Function; UploadProgress?: Function; BeforeChunkUpload?: Function; ChunkUploaded?: Function; FileUploaded?: Function; UploadComplete?: Function; Error?: Function; Destroy?: Function; } export namespace Builder { export class UploaderOptionsBuilder { private _browseButton: string; private _url: string; private _filters: FileFilters; private _headers: object; private _multipart: boolean; private _multipartParams: object; private _maxRetries: number; private _chunkSize: number | string; private _resize: ImageResize; private _dropElement: string; private _multiSelection: boolean; private _requiredFeatures: string | object; private _uniqueNames: boolean; private _runtimes: string; private _fileDataName: string; private _container: string; private _flashSwfUrl: string; private _httpMethod: 'POST' | 'PUT'; private _silverlightXapUrl: string; private _sendChunkNumber: boolean; private _sendFileName: boolean; private _init; // TODO Init(value): UploaderOptionsBuilder { this._init = value; return this; } get init() { return this._init; } //////////////////////////////// //// Required //////////////////////////////// /** * Almost any DOM element can be turned into a file dialog trigger, but usually it is either a button, actual file input or an image. * Value for the option can be either a DOM element itself or its id * 파일 업로더 박스를 사용할 DOM 요소 또는 DOM 요소의 ID * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ BrowseButton(value: string): UploaderOptionsBuilder { this._browseButton = value; return this; } get browseButton() { return this._browseButton; } /** * Url of the server-side upload handler that will accept the files, do some security checks and finally move them to a destination folder. * Might be relative or absolute * 파일을 업로드할 URL 주소 * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Url(value: string): UploaderOptionsBuilder { this._url = value; return this; } get url() { return this._url; } //////////////////////////////// //// Optional //////////////////////////////// /** * Plupload comes with several built-in filters that provide a way to restrict a selection (or perhaps an upload) of files that do not meet specific requirements * 업로드가능한 파일에 대해 필터를 설정 * @param {FileFilters} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Filters(value: FileFilters): UploaderOptionsBuilder { this._filters = value; return this; } get filters(): FileFilters { return this._filters; } /** * A way to pass custom HTTP headers with each upload request. * The option is simple set of key/value pairs of header names and their values. * - Not supported by html4 runtime. * - Requires special operational mode in case of flash and silverlight runtimes. * 파일 업로드시 HTTP 헤더에 설정할 key-value * @param {object} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Headers(value: object): UploaderOptionsBuilder { this._headers = value; return this; } get headers(): object { return this._headers; } /** * Whether to send the file as multipart/form-data (default) or binary stream. * The latter case is not supported by html4 and is a bit troublesome in flash runtime. * It also requires a special care on server-side * Multipart 형식의 메시지로 파일 및 추가 매개 변수 전송 여부 (기본값: TRUE) * @param {boolean} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Multipart(value: boolean): UploaderOptionsBuilder { this._multipart = value; return this; } get multipart(): boolean { return this._multipart; } /** * Additional multipart fields to be passed along with each upload request. * Each field can be represented by simple key/value pair or some nested arrays and/or objects * Multipart 파일 업로드와 함께 보낼 key/value Objects. * @param {object} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ MultipartParams(value: object): UploaderOptionsBuilder { this._multipartParams = value; return this; } get multipartParams(): object { return this._multipartParams; } /** * If max_retries is greater than 0, upload will be retried that many times every time there is plupload.HTTP_ERROR detected. * Be it complete file or a single chunk. * 오류 이벤트를 수행하기 전에 chunk 또는 파일을 업로드를 재시도할 횟수 (기본값: 0) * @param {number} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ MaxRetries(value: number): UploaderOptionsBuilder { this._maxRetries = value; return this; } get maxRetries(): number { return this._maxRetries; } /** * Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. (default: disabled) * 파일을 잘라 넣을 청크 크기(바이트). b, kb, mb, gb, tb 접미사가 있는 쇼커트도 지원된다 (기본값: 사용안함) * e.g. 204800 or "204800b" or "200kb" * @param {number | string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ ChunkSize(value: number | string): UploaderOptionsBuilder { this._chunkSize = value; return this; } get chunkSize() { return this._chunkSize; } /** * Plupload can downsize the images on client-side, mainly to save the bandwidth. * Perfect solution for thumbs, avatars and such. Currently not recommended for images sensible to quality drop * Plupload는 주로 대역폭을 절약하기 위해 클라이언트측에서 이미지 크기를 줄일 수 있다. 엄지손가락, 아바타 등을 위한 완벽한 솔루션. 현재 화질 하락에 대한 센스 있는 이미지에는 권장되지 않는다 * e.g new ImageResizeBuilder().width(10) * @param {ImageResize} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Resize(value: ImageResize): UploaderOptionsBuilder { this._resize = value; return this; } get resize(): ImageResize { return this._resize; } /** * The DOM element to be used as the dropzone for the files, or folders (Chrome 21+). * Can be an id of the DOM element or the DOM element itself, or an array of DOM elements (in the case of multiple dropzones). * Currently supported only by html5 runtime (and this will probably never change). * Drag drop 시 업로더 활성화 영역으로 사용할 DOM 요소 또는 DOM 요소의 ID * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ DropElement(value: string): UploaderOptionsBuilder { this._dropElement = value; return this; } get dropElement() { return this._dropElement; } /** * This option allows you to select multiple files from the browse dialog. * It is enabled by default, but not possible in some environments and runtimes. * 파일 업로더 상자에서 한 번에 여러 파일을 선택할 수 있는 기능 사용 (기본값: TRUE) * @param {boolean} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ MultiSelection(value: boolean): UploaderOptionsBuilder { this._multiSelection = value; return this; } get multiSelection(): boolean { return this._multiSelection; } /** * required_features is an option of mixed type - it can be a comma-separated string of features to take into account. * Or - an object of key/value pairs, where the key represents the required feature and the value must be fulfilled by the runtime in question. * Or it can be simply set to true and then the configuration itself will be translated into a corresponding set of features that the selected runtime must have to fulfill the expectations. * @param {string | object} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ RequiredFeatures(value: string | object): UploaderOptionsBuilder { this._requiredFeatures = value; return this; } get requiredFeatures(): string | object { return this._requiredFeatures; } /** * When set to true, will generate an unique file name for the uploaded file and send it as an additional argument - name. * This argument can then be used by the server-side upload handler to save the file under that name. * 이 옵션이 TRUE라면 업로드된 파일에 대한 고유한 파일 이름이 생성 (기본값: FALSE) * @param {boolean} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ UniqueNames(value: boolean): UploaderOptionsBuilder { this._uniqueNames = value; return this; } get uniqueNames(): boolean { return this._uniqueNames; } /** * Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails (default: html5,flash,silverlight,html4) * You only need to provide this option if you want to change the order in which runtimes will be tried, or want to exclude some of them at all. * Uploader 가능한 클라이언트 목록 (기본값: html5,flash,silverlight,html4) * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Runtimes(value: string): UploaderOptionsBuilder { this._runtimes = value; return this; } get runtimes(): string { return this._runtimes; } /** * Value of file_data_name will be used as the name for the file field in multipart request. * If for some reason you need it to be named differently, you can pass a different value for file_data_name. * Multipart 형식 메시지의 파일 필드 이름 (기본값: file) * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ FileDataName(value: string): UploaderOptionsBuilder { this._fileDataName = value; return this; } get fileDataName(): string { return this._fileDataName; } /** * Defaults to a parent node of browse_button * DOM element that will be used as a container for the Plupload html structures. * By default an immediate parent of the browse_button element is used. * 업로더 구조에 사용될 DOM 요소 또는 DOM 요소 자체의 ID. Browse_button 요소의 상위 * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ Container(value: string): UploaderOptionsBuilder { this._container = value; return this; } get container() { return this._container; } /** * The url of the Flash component, required by the flash runtime. * It will fail, if the component is not found or cannot be loaded within a sane amount of time and Plupload will try the next runtime in the list. * You do not need to set this option manually if you are using default file structure. * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ FlashSwfUrl(value: string): UploaderOptionsBuilder { this._flashSwfUrl = value; return this; } get flashSwfUrl(): string { return this._flashSwfUrl; } /** * The url of the Silverlight component, required by the silverlight runtime. * It will fail, if the component is not found or cannot be loaded within a sane amount of time and Plupload will try the next runtime in the list. * You do not need to set this option manually if you are using default file structure. * @param {string} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ SilverlightXapUrl(value: string): UploaderOptionsBuilder { this._silverlightXapUrl = value; return this; } get silverlightXapUrl(): string { return this._silverlightXapUrl; } /** * HTTP method to use during upload (only PUT or POST allowed) (default: POST) * 업로드하는 동안 사용할 API의 HTTP Method(PUT 또는 POST만 허용) (기본값: POST) * @param {"POST" | "PUT"} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ HttpMethod(value: 'POST' | 'PUT'): UploaderOptionsBuilder { this._httpMethod = value; return this; } get httpMethod(): string { return this._httpMethod; } /** * Whether to send chunks and chunk numbers, or total and offset bytes (default: TRUE) * 청크 및 청크 번호 또는 총 및 오프셋 바이트를 보낼지 여부 * @param {boolean} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * * @constructor */ SendChunkNumber(value: boolean): UploaderOptionsBuilder { this._sendChunkNumber = value; return this; } get sendChunkNumber(): boolean { return this._sendChunkNumber; } /** * Whether to send file name as additional argument - 'name' (required for chunked uploads and some other cases where file name cannot be sent via normal ways) (default: TRUE) * 추가 인수로 파일 이름을 보낼지 여부 - '이름' (청크 업로드 및 일반적인 방법으로 파일 이름을 보낼 수 없는 일부 경우 필요) (기본값: TRUE) * @param {boolean} value * @return {Pluploader.Builder.UploaderOptionsBuilder} * @constructor */ SendFileName(value: boolean): UploaderOptionsBuilder { this._sendFileName = value; return this; } get sendFileName(): boolean { return this._sendFileName; } /** * builder * @return {Pluploader.Builder.UploaderOptions} */ build(): UploaderOptions { return new UploaderOptions(this); } } export class UploaderOptions { // // required // @ts-ignore private browse_button: string; // @ts-ignore private url: string; // optional // @ts-ignore private filters: FileFilters; // @ts-ignore private headers; // @ts-ignore private multipart: boolean; // @ts-ignore private multipart_params; // @ts-ignore private max_retries: number; // @ts-ignore private chunk_size: number | string; // @ts-ignore private resize: ImageResize; // @ts-ignore private drop_element: string; // @ts-ignore private multi_selection: boolean; // @ts-ignore private required_features: string | object; // @ts-ignore private unique_names: boolean; // @ts-ignore private runtimes: string; // @ts-ignore private file_data_name: string; // @ts-ignore private container: string; // @ts-ignore private flash_swf_url: string; // @ts-ignore private silverlight_xap_url: string; // @ts-ignore private http_method: string; // @ts-ignore private send_chunk_number: boolean; // @ts-ignore private send_file_name: boolean; // @ts-ignore private init; constructor(builder: UploaderOptionsBuilder) { if (!_.isNil(builder.browseButton)) { this.browse_button = builder.browseButton; } if (!_.isNil(builder.chunkSize)) { this.chunk_size = builder.chunkSize; } if (!_.isNil(builder.container)) { this.container = builder.container; } if (!_.isNil(builder.dropElement)) { this.drop_element = builder.dropElement; } if (!_.isNil(builder.fileDataName)) { this.file_data_name = builder.fileDataName; } if (!_.isNil(builder.filters)) { this.filters = builder.filters; } if (!_.isNil(builder.flashSwfUrl)) { this.flash_swf_url = builder.flashSwfUrl; } if (!_.isNil(builder.headers)) { this.headers = builder.headers; } if (!_.isNil(builder.httpMethod)) { this.http_method = builder.httpMethod; } if (!_.isNil(builder.maxRetries)) { this.max_retries = builder.maxRetries; } if (!_.isNil(builder.multipart)) { this.multipart = builder.multipart; } if (!_.isNil(builder.multipartParams)) { this.multipart_params = builder.multipartParams; } if (!_.isNil(builder.multiSelection)) { this.multi_selection = builder.multiSelection; } if (!_.isNil(builder.requiredFeatures)) { this.required_features = builder.requiredFeatures; } if (!_.isNil(builder.resize)) { this.resize = builder.resize; } if (!_.isNil(builder.runtimes)) { this.runtimes = builder.runtimes; } if (!_.isNil(builder.silverlightXapUrl)) { this.silverlight_xap_url = builder.silverlightXapUrl; } if (!_.isNil(builder.sendChunkNumber)) { this.send_chunk_number = builder.sendChunkNumber; } if (!_.isNil(builder.sendFileName)) { this.send_file_name = builder.sendFileName; } if (!_.isNil(builder.url)) { this.url = builder.url; } if (!_.isNil(builder.uniqueNames)) { this.unique_names = builder.uniqueNames; } if (!_.isNil(builder.init)) { this.init = builder.init; } } } export class UploaderEventBuilder { // @ts-ignore private _init: Function; private _postInit: Function; // @ts-ignore private _optionChanged: Function; // @ts-ignore private _refresh: Function; // @ts-ignore private _stateChanged: Function; // @ts-ignore private _browse: Function; // @ts-ignore private _fileFiltered: Function; // @ts-ignore private _queueChanged: Function; private _filesAdded: Function; // @ts-ignore private _filesRemoved: Function; private _beforeUpload: Function; private _uploadFile: Function; private _uploadProgress: Function; private _beforeChunkUpload: Function; private _chunkUploaded: Function; private _fileUploaded: Function; private _uploadComplete: Function; // @ts-ignore private _error: Function; // @ts-ignore private _destroy: Function; PostInit(callback: Function) { this._postInit = callback; return this; } get postInit() { return this._postInit; } FilesAdded(callback: Function) { this._filesAdded = callback; return this; } get filesAdded() { return this._filesAdded; } UploadProgress(callback: Function) { this._uploadProgress = callback; return this; } get uploadProgress() { return this._uploadProgress; } BeforeUpload(callback: Function) { this._beforeUpload = callback; return this; } get beforeUpload() { return this._beforeUpload; } UploadFile(callback: Function) { this._uploadFile = callback; return this; } get uploadFile() { return this._uploadFile; } FileUploaded(callback: Function) { this._fileUploaded = callback; return this; } get fileUploaded() { return this._fileUploaded; } BeforeChunkUpload(callback: Function) { this._beforeChunkUpload = callback; return this; } get beforeChunkUpload() { return this._beforeChunkUpload; } ChunkUploaded(callback: Function) { this._chunkUploaded = callback; return this; } get chunkUploaded() { return this._chunkUploaded; } UploadComplete(callback: Function) { this._uploadComplete = callback; return this; } get uploadComplete() { return this._uploadComplete; } Error(callback: Function) { this._postInit = callback; return this; } get error() { return this._postInit; } /** * build * @return {Pluploader.Builder.UploaderEvent} */ build(): UploaderEvent { return new UploaderEvent(this); } } export class UploaderEvent { // @ts-ignore private Init: Function; // @ts-ignore private PostInit: Function; // @ts-ignore private OptionChanged: Function; // @ts-ignore private Refresh: Function; // @ts-ignore private StateChanged: Function; // @ts-ignore private Browse: Function; // @ts-ignore private FileFiltered: Function; // @ts-ignore private QueueChanged: Function; // @ts-ignore private FilesAdded: Function; // @ts-ignore private FilesRemoved: Function; // @ts-ignore private BeforeUpload: Function; // @ts-ignore private UploadFile: Function; // @ts-ignore private UploadProgress: Function; // @ts-ignore private BeforeChunkUpload: Function; // @ts-ignore private ChunkUploaded: Function; // @ts-ignore private FileUploaded: Function; // @ts-ignore private UploadComplete: Function; // @ts-ignore private Error: Function; // @ts-ignore private Destroy: Function; constructor(builder: UploaderEventBuilder) { if (!_.isNil(builder.postInit)) { this.PostInit = builder.postInit; } if (!_.isNil(builder.filesAdded)) { this.FilesAdded = builder.filesAdded; } if (!_.isNil(builder.uploadProgress)) { this.UploadProgress = builder.uploadProgress; } if (!_.isNil(builder.beforeUpload)) { this.BeforeUpload = builder.beforeUpload; } if (!_.isNil(builder.uploadFile)) { this.UploadFile = builder.uploadFile; } if (!_.isNil(builder.fileUploaded)) { this.FileUploaded = builder.fileUploaded; } if (!_.isNil(builder.beforeChunkUpload)) { this.BeforeChunkUpload = builder.beforeChunkUpload; } if (!_.isNil(builder.chunkUploaded)) { this.ChunkUploaded = builder.chunkUploaded; } if (!_.isNil(builder.uploadComplete)) { this.UploadComplete = builder.uploadComplete; } if (!_.isNil(builder.error)) { this.Error = builder.error; } } } // https://github.com/moxiecode/plupload/wiki/Options#filters export class FileFiltersBuilder { private _mimeTypes; private _maxFileSize: number | string; private _preventDuplicates: boolean; private _preventEmpty: boolean; /** * By default any file type can be picked from file selection dialog (which is obviously a rarely desired case), * so by supplying a mime_types filter one can constrain it to only specific file types * 기본적으로 파일 선택 대화 상자에서 파일 형식을 선택할 수 있으므로 mime_types필터를 제공함으로써 특정 파일 형식에만 제한 * e.g. [ * { title : "Image files", extensions : "jpg,gif,png" }, * { title : "Zip files", extensions : "zip" } * ] * @param value * @return {Pluploader.Builder.FileFiltersBuilder} * @constructor */ MimeTypes(value): FileFiltersBuilder { this._mimeTypes = value; return this; } get mimeTypes() { return this._mimeTypes; } /** * By default, file of any size is allowed to the queue. But it is possible to constrain it from the top with the max_file_size filter. It accepts numeric or formatted string values * 기본적으로 모든 크기의 파일은 대기열에 허용됨. 그러나 max_file_size 필터로 상단에서 제약할 수 있다 * e.g.: 204800 or "204800b" or "200kb" * error : FILE_SIZE_ERROR * @param {number | string} value * @return {Pluploader.Builder.FileFiltersBuilder} * @constructor */ MaxFileSize(value: number | string): FileFiltersBuilder { this._maxFileSize = value; return this; } get maxFileSize(): number | string { return this._maxFileSize; } /** * If set to true the Plupload will not allow duplicates. Duplicates are detected by matching file's name and size * TRUE로 설정하면 중복을 허용하지 않음 (파일 이름과 크기가 일치하여 중복이 감지) * @param {boolean} value * @return {Pluploader.Builder.FileFiltersBuilder} * @constructor */ PreventDuplicates(value: boolean): FileFiltersBuilder { this._preventDuplicates = value; return this; } get preventDuplicates(): boolean { return this._preventDuplicates; } /** * Empty files are known to cause problems in some older browsers (like IE10), or third party shims (like Silverlight), * so a while ago we decided to filter them out by default. * But as it turned out many users wanted to allow them anyway, so we transformed the constraint into the filter, that can be turned on or off * 빈 파일 허용 여부 설정 * @param {boolean} value * @return {Pluploader.Builder.FileFiltersBuilder} * @constructor */ PreventEmpty(value: boolean): FileFiltersBuilder { this._preventEmpty = value; return this; } get preventEmpty(): boolean { return this._preventEmpty; } /** * builder * @return {Pluploader.Builder.FileFilters} */ builder(): FileFilters { return new FileFilters(this); } } export class FileFilters { // @ts-ignore private max_file_size: number | string = 0; // @ts-ignore private mime_types = []; // @ts-ignore private prevent_duplicates: boolean = false; // @ts-ignore private prevent_empty: boolean = true; constructor(builder: FileFiltersBuilder) { if (!_.isNil(builder.maxFileSize)) { this.max_file_size = builder.maxFileSize; } if (!_.isNil(builder.mimeTypes)) { this.mime_types = builder.mimeTypes; } if (!_.isNil(builder.PreventDuplicates)) { this.prevent_duplicates = builder.preventDuplicates; } if (!_.isNil(builder.preventEmpty)) { this.prevent_empty = builder.preventEmpty; } } } // https://github.com/moxiecode/plupload/wiki/Options#client-side-resize export class ImageResizeBuilder { private _width: number; private _height: number; private _crop: boolean; private _quality: number; private _preserveHeaders: boolean; /** * The new width for the downsized image. If not specified will default to the actual width of the image. * 축소된 이미지의 새 너비. 지정하지 않으면 이미지의 실제 너비로 기본값 * @param {number} value * @return {Pluploader.Builder.ImageResizeBuilder} * @constructor */ Width(value: number): ImageResizeBuilder { this._width = value; return this; } get width(): number { return this._width; } /** * The new height for the downsized image. If not specified will default to the actual height of the image. * 축소된 이미지의 새 높이. 지정되지 않으면 이미지의 실제 높이로 기기본값 * @param {number} value * @return {Pluploader.Builder.ImageResizeBuilder} * @constructor */ Height(value: number): ImageResizeBuilder { this._height = value; return this; } get height(): number { return this._height; } /** * Whether to crop the image to exact dimensions, specified by width and height, or - not * 너비와 높이로 지정된 정확한 치수로 영상을 자르는지 여부 * @param {boolean} value * @return {Pluploader.Builder.ImageResizeBuilder} * @constructor */ Crop(value: boolean): ImageResizeBuilder { this._crop = value; return this; } get crop(): boolean { return this._crop; } /** * This option is only applicable to JPEGs, since PNGs are lossless and are not subjected to quality cuts. * The higher is quality the better the image looks, but the bigger its size is. * It must said that quality can only be dropped and never improved. So this option must be used carefully * Compression quality for jpegs (1-100) * @param {number} value * @return {Pluploader.Builder.ImageResizeBuilder} * @constructor */ Quality(value: number): ImageResizeBuilder { if (value < 1) { this._quality = 1; } else if (value > 100) { this._quality = 100; } else { this._quality = value; } return this; } get quality(): number { return this._quality; } /** * Another option that is only applicable to JPEGs. * Controls whether the meta headers, containing Exif, GPS or IPTC data, etc, should be retained after the downsize completes. * By default meta headers are preserved, but you can set this to false if you do not require them and save some more bytes * JPEG만 적용되는 옵션, 메타 헤더를 유지하는지 여부 * @param {boolean} value * @return {Pluploader.Builder.ImageResizeBuilder} * @constructor */ PreserveHeaders(value: boolean): ImageResizeBuilder { this._preserveHeaders = value; return this; } get preserveHeaders(): boolean { return this._preserveHeaders; } /** * builder * @return {Pluploader.Builder.ImageResize} */ builder(): ImageResize { return new ImageResize(this); } } export class ImageResize { width: number; height: number; crop: boolean; quality: number; preserve_headers: boolean; constructor(builder: ImageResizeBuilder) { if (!_.isNil(builder.width)) { this.width = builder.width; } if (!_.isNil(builder.height)) { this.height = builder.height; } if (!_.isNil(builder.crop)) { this.crop = builder.crop; } if (!_.isNil(builder.quality)) { this.quality = builder.quality; } if (!_.isNil(builder.preserveHeaders)) { this.preserve_headers = builder.preserveHeaders; } } } } // https://github.com/moxiecode/plupload/wiki/File export class File { // Properties id?: string; name?: string; type?; size?: number; origSize?: number; loaded?; percent?: number; status?: FileStatus; lastModifiedDate?; // Method getNative?: Function; getSource?: Function; destroy?: Function; // UI isUploading?: boolean; isCanceled?: boolean; isFailed?: boolean; isComplete?: boolean; errorMessage?: string; response?: string; responseHeaders?: string; } export enum FileStatus { QUEUED = 1, UPLOADING = 2, FAILED = 4, DONE = 5, } export enum ErrorCode { GENERIC_ERROR = -100, HTTP_ERROR = -200, IO_ERROR = -300, SECURITY_ERROR = -400, INIT_ERROR = -500, FILE_SIZE_ERROR = -600, FILE_EXTENSION_ERROR = -601, FILE_DUPLICATE_ERROR = -602, IMAGE_FORMAT_ERROR = -700, MEMORY_ERROR = -701, IMAGE_DIMENSIONS_ERROR = -702 } }
the_stack
'use strict'; import { ExtensionUtil } from '../util/ExtensionUtil'; import * as path from 'path'; import * as fs from 'fs-extra'; import * as vscode from 'vscode'; import * as semver from 'semver'; import { CommandUtil } from '../util/CommandUtil'; import { GlobalState, ExtensionData } from '../util/GlobalState'; import { RequiredDependencies, OptionalDependencies, Dependencies, defaultDependencies, DependencyProperties } from './Dependencies'; import OS = require('os'); export class DependencyManager { public static instance(): DependencyManager { return this._instance; } private static _instance: DependencyManager = new DependencyManager(); private constructor() { } public isValidDependency(dependency: any): boolean { const name: string = dependency.name; const needsToBeInstalledWithSemver: Array<string> = [ defaultDependencies.optional.node.name, defaultDependencies.optional.java.name, defaultDependencies.optional.npm.name, defaultDependencies.required.docker.name, defaultDependencies.optional.go.name, defaultDependencies.optional.openssl.name ]; const needsToBeInstalled: Array<string> = [ defaultDependencies.optional.goExtension.name, defaultDependencies.optional.javaLanguageExtension.name, defaultDependencies.optional.javaDebuggerExtension.name, defaultDependencies.optional.javaTestRunnerExtension.name, defaultDependencies.optional.nodeTestRunnerExtension.name, defaultDependencies.optional.ibmCloudAccountExtension.name, ]; const needsToBeComplete: Array<string> = [ defaultDependencies.required.dockerForWindows.name, defaultDependencies.required.systemRequirements.name ]; if (needsToBeInstalledWithSemver.includes(name)) { if (dependency.version) { return semver.satisfies(dependency.version, dependency.requiredVersion); } else { return false; } } else if (needsToBeInstalled.includes(name)) { if (dependency.version) { return true; } else { return false; } } else if (needsToBeComplete.includes(name)) { if (!dependency.complete) { dependency.complete = false; } return dependency.complete; } return false; } public areAllValidDependencies(properties: Array<string>, dependencies: any): boolean { const isWindows: boolean = (process.platform === 'win32'); for (const property of properties) { if (dependencies.hasOwnProperty(property)) { if (!isWindows && dependencies[property].windowsOnly) { continue; } const isValid: boolean = this.isValidDependency(dependencies[property]); if (!isValid) { return false; } } } return true; } public async hasPreReqsInstalled(dependencies?: any, optionalInstalled: boolean = false): Promise<boolean> { if (!dependencies) { dependencies = await this.getPreReqVersions(); } const localFabricEnabled: boolean = ExtensionUtil.getExtensionLocalFabricSetting(); if (localFabricEnabled) { const localFabricProperties: Array<string> = ['docker', 'systemRequirements']; if (!this.areAllValidDependencies(localFabricProperties, dependencies)) { return false; } } if (process.platform === 'win32') { // Windows if (localFabricEnabled) { const windowsProperties: Array<string> = ['dockerForWindows']; if (!this.areAllValidDependencies(windowsProperties, dependencies)) { return false; } } } // Optional installs if (optionalInstalled) { const optionalInstallProperties: Array<string> = Object.getOwnPropertyNames(defaultDependencies.optional); if (!this.areAllValidDependencies(optionalInstallProperties, dependencies)) { return false; } } return true; } public async getPreReqVersions(): Promise<Dependencies> { // Only want to attempt to get extension context when activated. // We store whether the user has confirmed that they have met the System Requirements, so need to access the global state const extensionData: ExtensionData = GlobalState.get(); // The order that we add dependencies to this object matters, as the webview will create the panels in the same order. // So we want to handle the optional dependencies last const getMultipleVersions: Array<Promise<any>> = [ this.getRequiredDependencies(extensionData.dockerForWindows), this.getOptionalDependencies(), ]; const [requiredDependencies, optionalDependencies] = await Promise.all(getMultipleVersions); const dependencies: Dependencies = { ...requiredDependencies, ...optionalDependencies, }; return dependencies; } public async clearExtensionCache(): Promise<void> { const extensionPath: string = ExtensionUtil.getExtensionPath(); const extensionsPath: string = path.resolve(extensionPath, '..'); const currentDate: Date = new Date(); await fs.utimes(extensionsPath, currentDate, currentDate); } public getPackageJsonPath(): string { return path.resolve(ExtensionUtil.getExtensionPath(), 'package.json'); } public async getRawPackageJson(): Promise<any> { // Use getRawPackageJson to read and write back to package.json // This prevents obtaining any of VSCode's expanded variables. const fileContents: string = await fs.readFile(this.getPackageJsonPath(), 'utf8'); return JSON.parse(fileContents); } public async writePackageJson(packageJson: any): Promise<void> { const packageJsonString: string = JSON.stringify(packageJson, null, 4); return fs.writeFile(this.getPackageJsonPath(), packageJsonString, 'utf8'); } private isCommandFound(output: string): boolean { if (output.toLowerCase().includes('not found') || output.toLowerCase().includes('not recognized') || output.toLowerCase().includes('no such file or directory') || output.toLowerCase().includes('unable to get active developer directory')) { return false; } else { return true; } } private async getRequiredDependencies(dockerForWindows: boolean): Promise<RequiredDependencies> { // The order of the dependencies matters const localFabricEnabled: boolean = ExtensionUtil.getExtensionLocalFabricSetting(); const isWindows: boolean = process.platform === 'win32'; const dependencies: RequiredDependencies = {}; if (localFabricEnabled) { const getDockerVersions: Array<Promise<string>> = [this.getDockerVersion()]; const [dockerVersion] = await Promise.all(getDockerVersions); const systemRequirementsVersion: number = OS.totalmem() / 1073741824; dependencies.docker = { ...defaultDependencies.required.docker, version: dockerVersion, }; dependencies.systemRequirements = { ...defaultDependencies.required.systemRequirements, version: systemRequirementsVersion, complete: systemRequirementsVersion >= 4, }; if (isWindows) { dependencies.dockerForWindows = { ...defaultDependencies.required.dockerForWindows, complete: !!dockerForWindows, }; } return dependencies; } return {}; } private async getOptionalDependencies(): Promise<OptionalDependencies> { // The order of the dependencies matters // System dependencies const getOptionalVersions: Array<Promise<string>> = [ this.getNodeVersion(), this.getNPMVersion(), this.getGoVersion(), this.getJavaVersion(), ]; const [nodeVersion, npmVersion, goVersion, javaVersion] = await Promise.all(getOptionalVersions); // VSCode extension dependencies const goExtensionVersion: string = this.getExtensionVersion(DependencyProperties.GO_LANGUAGE_EXTENSION); const javaLanguageExtensionVersion: string = this.getExtensionVersion(DependencyProperties.JAVA_LANGUAGE_EXTENSION); const javaDebuggerExtensionVersion: string = this.getExtensionVersion(DependencyProperties.JAVA_DEBUG_EXTENSION); const javaTestRunnerExtensionVersion: string = this.getExtensionVersion(DependencyProperties.JAVA_TEST_RUNNER_EXTENSION); const nodeTestRunnerExtensionVersion: string = this.getExtensionVersion(DependencyProperties.NODEJS_TEST_RUNNER_EXTENSION); const ibmCloudAccountExtensionVersion: string = this.getExtensionVersion(DependencyProperties.IBM_CLOUD_ACCOUNT_EXTENSION); const isWindows: boolean = process.platform === 'win32'; const optionalDependencies: OptionalDependencies = { ...defaultDependencies.optional }; // todo update if (isWindows) { optionalDependencies.openssl.version = await this.getOpensslVersion(); } else { for (const [property, value] of Object.entries(optionalDependencies)) { if (value.windowsOnly) { delete optionalDependencies[property]; } } } // Update versions optionalDependencies.node.version = nodeVersion; optionalDependencies.npm.version = npmVersion; optionalDependencies.go.version = goVersion; optionalDependencies.goExtension.version = goExtensionVersion; optionalDependencies.java.version = javaVersion; optionalDependencies.javaLanguageExtension.version = javaLanguageExtensionVersion; optionalDependencies.javaDebuggerExtension.version = javaDebuggerExtensionVersion; optionalDependencies.javaTestRunnerExtension.version = javaTestRunnerExtensionVersion; optionalDependencies.nodeTestRunnerExtension.version = nodeTestRunnerExtensionVersion; optionalDependencies.ibmCloudAccountExtension.version = ibmCloudAccountExtensionVersion; return optionalDependencies; } private async getDockerVersion(): Promise<string> { try { const dockerResult: string = await CommandUtil.sendCommand('docker -v'); // Format: Docker version X.Y.Z-ce, build e68fc7a if (this.isCommandFound(dockerResult)) { const dockerMatchedVersion: string = dockerResult.match(/version (.*),/)[1]; // Format: X.Y.Z-ce "version 18.06.1-ce," const dockerCleaned: string = semver.clean(dockerMatchedVersion, { loose: true }); const dockerVersionCoerced: semver.SemVer = semver.coerce(dockerCleaned); // Format: X.Y.Z const dockerVersion: string = semver.valid(dockerVersionCoerced); // Returns version return dockerVersion; } } catch (error) { // Ignore return; } } private async getOpensslVersion(): Promise<string> { try { const libPath: string = path.win32.join('C:\\OpenSSL-Win64', 'lib', 'libeay32.lib'); const libExists: boolean = await fs.pathExists(libPath); // This path only exists for OpenSSL 1.0.2 - x509 REQUIRES this exact path. if (libExists) { return '1.0.2'; } } catch (error) { // Ignore } } private async getNodeVersion(): Promise<string> { try { const nodeResult: string = await CommandUtil.sendCommand('node -v'); // Format: vX.Y.Z if (this.isCommandFound(nodeResult)) { const nodeVersion: string = nodeResult.substr(1); const nodeValid: string = semver.valid(nodeVersion); // Returns version return nodeValid; } } catch (error) { // Ignore } } private async getNPMVersion(): Promise<string> { try { const npmResult: string = await CommandUtil.sendCommand('npm -v'); // Format: X.Y.Z if (this.isCommandFound(npmResult)) { const npmVersion: string = semver.valid(npmResult); // Returns version return npmVersion; } } catch (error) { // Ignore } } private async getGoVersion(): Promise<string> { try { const goResult: string = await CommandUtil.sendCommand('go version'); // Format: go version go1.12.5 darwin/amd64 if (this.isCommandFound(goResult)) { const goMatchedVersion: string = goResult.match(/go version go(.*) /)[1]; // Format: X.Y.Z or X.Y const goVersionCoerced: semver.SemVer = semver.coerce(goMatchedVersion); // Format: X.Y.Z const goVersion: string = semver.valid(goVersionCoerced); // Returns version return goVersion; } } catch (error) { // Ignore the error } } private async getJavaVersion(): Promise<string> { try { let getVersion: boolean = true; if (process.platform === 'darwin') { const javaPath: string = '/Library/Java/JavaVirtualMachines'; // This is the standard Mac install location. const javaDirExists: boolean = await fs.pathExists(javaPath); getVersion = javaDirExists; } if (getVersion) { // For some reason, the response is going to stderr, so we have to redirect it to stdout. const javaResult: string = await CommandUtil.sendCommand('java -version 2>&1'); // Format: openjdk|java version "1.8.0_212" if (this.isCommandFound(javaResult)) { const javaMatchedVersion: string = javaResult.match(/(openjdk|java) version "(.*)"/)[2]; // Format: X.Y.Z_A const javaVersionCoerced: semver.SemVer = semver.coerce(javaMatchedVersion); // Format: X.Y.Z const javaVersion: string = semver.valid(javaVersionCoerced); // Returns version return javaVersion; } } } catch (error) { // Ignore the error } } private getExtensionVersion(extension: string): string { try { const nextensionResult: vscode.Extension<any> = vscode.extensions.getExtension(extension); if (nextensionResult) { return nextensionResult.packageJSON.version; } } catch (error) { // Ignore the error } } }
the_stack
import { StyleProp, ViewStyle } from 'react-native'; import { Placement } from './Types'; import { Rect, Size, Point, getArrowSize, getBorderRadius } from './Utility'; import { POPOVER_MARGIN } from './Constants'; type ComputeGeometryBaseProps = { requestedContentSize: Size; displayArea: Rect; debug: (line: string, obj?: unknown) => void; } type ComputeGeometryProps = ComputeGeometryBaseProps & { placement?: Placement; previousPlacement?: Placement; fromRect: Rect | null; arrowStyle: StyleProp<ViewStyle>; popoverStyle: StyleProp<ViewStyle>; arrowShift?: number; } type ComputeGeometryDirectionProps = ComputeGeometryBaseProps & { fromRect: Rect; arrowStyle: StyleProp<ViewStyle>; borderRadius: number; debug: (line: string, obj?: unknown) => void; } type ComputeGeometryAutoProps = ComputeGeometryDirectionProps & { previousPlacement?: Placement; }; export class Geometry { popoverOrigin: Point; anchorPoint: Point; placement: Placement; forcedContentSize: Size | null; viewLargerThanDisplayArea: { width: boolean, height: boolean } constructor( { popoverOrigin, anchorPoint, placement, forcedContentSize, viewLargerThanDisplayArea }: { popoverOrigin: Point; anchorPoint: Point; placement: Placement; forcedContentSize: Size | null; viewLargerThanDisplayArea: { width: boolean, height: boolean } } ) { this.popoverOrigin = popoverOrigin; this.anchorPoint = anchorPoint; this.placement = placement; this.forcedContentSize = forcedContentSize; this.viewLargerThanDisplayArea = viewLargerThanDisplayArea; } static equals(a: Geometry, b: Geometry): boolean { return Point.equals(a.popoverOrigin, b.popoverOrigin) && Point.equals(a.anchorPoint, b.anchorPoint) && a.placement === b.placement && a.forcedContentSize?.width === b.forcedContentSize?.width && a.forcedContentSize?.height === b.forcedContentSize?.height && a.viewLargerThanDisplayArea?.width === b.viewLargerThanDisplayArea?.width && a.viewLargerThanDisplayArea?.height === b.viewLargerThanDisplayArea?.height; } } export function computeGeometry(options: ComputeGeometryProps): Geometry { const { requestedContentSize, placement, displayArea, debug, popoverStyle, arrowShift } = options; let newGeom = null; // Make copy so doesn't modify original const fromRect = options.fromRect ? Rect.clone(options.fromRect) : null; if (fromRect && options.fromRect instanceof Rect) { // Check to see if fromRect is outside of displayArea, and adjust if it is if (fromRect.x > displayArea.x + displayArea.width) fromRect.x = displayArea.x + displayArea.width; if (fromRect.y > displayArea.y + displayArea.height) fromRect.y = displayArea.y + displayArea.height; if (fromRect.x + fromRect.width < 0) fromRect.x = -1 * fromRect.width; if (fromRect.y + fromRect.height < 0) fromRect.y = -1 * fromRect.height; const borderRadius = getBorderRadius(popoverStyle); switch (placement) { case Placement.TOP: newGeom = computeTopGeometry({ ...options, fromRect, borderRadius }); break; case Placement.BOTTOM: newGeom = computeBottomGeometry({ ...options, fromRect, borderRadius }); break; case Placement.LEFT: newGeom = computeLeftGeometry({ ...options, fromRect, borderRadius }); break; case Placement.RIGHT: newGeom = computeRightGeometry({ ...options, fromRect, borderRadius }); break; case Placement.CENTER: newGeom = null; break; default: newGeom = computeAutoGeometry({ ...options, fromRect, borderRadius }); } debug('computeGeometry - initial chosen geometry', newGeom); /* * If the popover will be restricted and the view that the popover isshowing * from is sufficiently large, try to show the popover inside the view */ if ( newGeom && (newGeom.viewLargerThanDisplayArea.width || newGeom.viewLargerThanDisplayArea.height) ) { const fromRectHeightVisible = fromRect.y < displayArea.y ? fromRect.height - (displayArea.y - fromRect.y) : displayArea.y + displayArea.height - fromRect.y; if ( fromRect.width > requestedContentSize.width && fromRectHeightVisible > requestedContentSize.height ) { const preferredX = Math.max( fromRect.x + 10, fromRect.x + ((fromRect.width - requestedContentSize.width) / 2) ); const preferredY = Math.max( fromRect.y + 10, fromRect.y + ((fromRect.height - requestedContentSize.height) / 2) ); let constrainedX = Math.max(preferredX, displayArea.x); if (constrainedX + requestedContentSize.width > displayArea.x + displayArea.width) constrainedX = displayArea.x + displayArea.width - requestedContentSize.width; let constrainedY = Math.max(preferredY, displayArea.y); if (constrainedY + requestedContentSize.height > displayArea.y + displayArea.height) constrainedY = displayArea.y + displayArea.height - requestedContentSize.height; const forcedContentSize = { width: Math.min(fromRect.width - 20, displayArea.width), height: Math.min(fromRect.height - 20, displayArea.height) }; debug('computeGeometry - showing inside anchor'); newGeom = new Geometry({ popoverOrigin: new Point(constrainedX, constrainedY), anchorPoint: new Point(fromRect.x + (fromRect.width / 2), fromRect.y + (fromRect.height / 2)), placement: Placement.CENTER, forcedContentSize, viewLargerThanDisplayArea: { width: requestedContentSize.width > forcedContentSize.width, height: requestedContentSize.height > forcedContentSize.height } }); } else if ( /* * If we can't fit inside or outside the fromRect, show the popover centered on the screen, * but only do this if they haven't asked for a specifc placement type * and if it will actually help show more content */ placement === Placement.AUTO && ( ( newGeom.viewLargerThanDisplayArea.width && [Placement.RIGHT, Placement.LEFT].includes(newGeom.placement) ) || ( newGeom.viewLargerThanDisplayArea.height && [Placement.TOP, Placement.BOTTOM].includes(newGeom.placement) ) ) ) { newGeom = null; } } } if (!newGeom) { const minY = displayArea.y; const minX = displayArea.x; const preferedY = ((displayArea.height - requestedContentSize.height) / 2) + displayArea.y; const preferedX = ((displayArea.width - requestedContentSize.width) / 2) + displayArea.x; debug('computeGeometry - showing centered on screen'); newGeom = new Geometry({ popoverOrigin: new Point(Math.max(minX, preferedX), Math.max(minY, preferedY)), anchorPoint: new Point( (displayArea.width / 2) + displayArea.x, (displayArea.height / 2) + displayArea.y ), placement: Placement.CENTER, forcedContentSize: { width: displayArea.width, height: displayArea.height }, viewLargerThanDisplayArea: { width: preferedX < minX - 1, height: preferedY < minY - 1 } }); } if (arrowShift && fromRect) { if (newGeom.placement === Placement.BOTTOM || newGeom.placement === Placement.TOP) newGeom.anchorPoint.x += arrowShift * 0.5 * fromRect.width; else newGeom.anchorPoint.y += arrowShift * 0.5 * fromRect.height; } debug('computeGeometry - final chosen geometry', newGeom); return newGeom; } function computeTopGeometry({ displayArea, fromRect, requestedContentSize, arrowStyle, borderRadius }: ComputeGeometryDirectionProps): Geometry { // Apply a margin on non-arrow sides displayArea = new Rect( displayArea.x + POPOVER_MARGIN, displayArea.y + POPOVER_MARGIN, displayArea.width - (POPOVER_MARGIN * 2), displayArea.height ); const arrowSize = getArrowSize(Placement.TOP, arrowStyle); const minY = displayArea.y; const preferredY = fromRect.y - requestedContentSize.height - arrowSize.height; const forcedContentSize = { height: (fromRect.y - arrowSize.height - displayArea.y), width: displayArea.width }; const viewLargerThanDisplayArea = { height: preferredY <= minY - 1, width: requestedContentSize.width >= displayArea.width + 1 }; const viewWidth = viewLargerThanDisplayArea.width ? forcedContentSize.width : requestedContentSize.width; const maxX = displayArea.x + displayArea.width - viewWidth; const minX = displayArea.x; const preferredX = fromRect.x + ((fromRect.width - viewWidth) / 2); const popoverOrigin = new Point( Math.min(maxX, Math.max(minX, preferredX)), Math.max(minY, preferredY) ); const anchorPoint = new Point(fromRect.x + (fromRect.width / 2), fromRect.y); // Make sure the arrow isn't cut off anchorPoint.x = Math.max(anchorPoint.x, (arrowSize.width / 2) + borderRadius); anchorPoint.x = Math.min( anchorPoint.x, displayArea.x + displayArea.width - (arrowSize.width / 2) - borderRadius ); return new Geometry({ popoverOrigin, anchorPoint, placement: Placement.TOP, forcedContentSize, viewLargerThanDisplayArea }); } function computeBottomGeometry({ displayArea, fromRect, requestedContentSize, arrowStyle, borderRadius }: ComputeGeometryDirectionProps): Geometry { // Apply a margin on non-arrow sides displayArea = new Rect( displayArea.x + POPOVER_MARGIN, displayArea.y, displayArea.width - (POPOVER_MARGIN * 2), displayArea.height - POPOVER_MARGIN ); const arrowSize = getArrowSize(Placement.BOTTOM, arrowStyle); const preferedY = fromRect.y + fromRect.height + arrowSize.height; const forcedContentSize = { height: displayArea.y + displayArea.height - preferedY, width: displayArea.width }; const viewLargerThanDisplayArea = { height: preferedY + requestedContentSize.height >= displayArea.y + displayArea.height + 1, width: requestedContentSize.width >= displayArea.width + 1 }; const viewWidth = viewLargerThanDisplayArea.width ? forcedContentSize.width : requestedContentSize.width; const maxX = displayArea.x + displayArea.width - viewWidth; const minX = displayArea.x; const preferedX = fromRect.x + ((fromRect.width - viewWidth) / 2); const popoverOrigin = new Point( Math.min(maxX, Math.max(minX, preferedX)), preferedY ); const anchorPoint = new Point(fromRect.x + (fromRect.width / 2), fromRect.y + fromRect.height); // Make sure the arrow isn't cut off anchorPoint.x = Math.max(anchorPoint.x, (arrowSize.width / 2) + borderRadius); anchorPoint.x = Math.min( anchorPoint.x, displayArea.x + displayArea.width - (arrowSize.width / 2) - borderRadius ); return new Geometry({ popoverOrigin, anchorPoint, placement: Placement.BOTTOM, forcedContentSize, viewLargerThanDisplayArea }); } function computeLeftGeometry({ displayArea, fromRect, requestedContentSize, borderRadius, arrowStyle }: ComputeGeometryDirectionProps): Geometry { // Apply a margin on non-arrow sides displayArea = new Rect( displayArea.x + POPOVER_MARGIN, displayArea.y + POPOVER_MARGIN, displayArea.width, displayArea.height - (POPOVER_MARGIN * 2) ); const arrowSize = getArrowSize(Placement.LEFT, arrowStyle); const forcedContentSize = { height: displayArea.height, width: fromRect.x - displayArea.x - arrowSize.width }; const viewLargerThanDisplayArea = { height: requestedContentSize.height >= displayArea.height + 1, width: requestedContentSize.width >= fromRect.x - displayArea.x - arrowSize.width + 1 }; const viewWidth = viewLargerThanDisplayArea.width ? forcedContentSize.width : requestedContentSize.width; const viewHeight = viewLargerThanDisplayArea.height ? forcedContentSize.height : requestedContentSize.height; const preferedX = fromRect.x - viewWidth - arrowSize.width; const preferedY = fromRect.y + ((fromRect.height - viewHeight) / 2); const minY = displayArea.y; const maxY = (displayArea.height - viewHeight) + displayArea.y; const popoverOrigin = new Point( preferedX, Math.min(Math.max(minY, preferedY), maxY) ); const anchorPoint = new Point(fromRect.x, fromRect.y + (fromRect.height / 2)); // Make sure the arrow isn't cut off anchorPoint.y = Math.max(anchorPoint.y, (arrowSize.height / 2) + borderRadius); anchorPoint.y = Math.min( anchorPoint.y, displayArea.y + displayArea.height - (arrowSize.height / 2) - borderRadius ); return new Geometry({ popoverOrigin, anchorPoint, placement: Placement.LEFT, forcedContentSize, viewLargerThanDisplayArea }); } function computeRightGeometry({ displayArea, fromRect, requestedContentSize, arrowStyle, borderRadius }: ComputeGeometryDirectionProps): Geometry { // Apply a margin on non-arrow sides displayArea = new Rect( displayArea.x, displayArea.y + POPOVER_MARGIN, displayArea.width - POPOVER_MARGIN, displayArea.height - (POPOVER_MARGIN * 2) ); const arrowSize = getArrowSize(Placement.RIGHT, arrowStyle); const horizontalSpace = displayArea.x + displayArea.width - (fromRect.x + fromRect.width) - arrowSize.width; const forcedContentSize = { height: displayArea.height, width: horizontalSpace }; const viewLargerThanDisplayArea = { height: requestedContentSize.height >= displayArea.height + 1, width: requestedContentSize.width >= horizontalSpace + 1 }; const viewHeight = viewLargerThanDisplayArea.height ? forcedContentSize.height : requestedContentSize.height; const preferedX = fromRect.x + fromRect.width + arrowSize.width; const preferedY = fromRect.y + ((fromRect.height - viewHeight) / 2); const minY = displayArea.y + POPOVER_MARGIN; const maxY = (displayArea.height - viewHeight) + displayArea.y - POPOVER_MARGIN; const popoverOrigin = new Point( preferedX, Math.min(Math.max(minY, preferedY), maxY) ); const anchorPoint = new Point(fromRect.x + fromRect.width, fromRect.y + (fromRect.height / 2.0)); // Make sure the arrow isn't cut off anchorPoint.y = Math.max(anchorPoint.y, (arrowSize.height / 2) + borderRadius); anchorPoint.y = Math.min( anchorPoint.y, displayArea.y + displayArea.height - (arrowSize.height / 2) - borderRadius ); return new Geometry({ popoverOrigin, anchorPoint, placement: Placement.RIGHT, forcedContentSize, viewLargerThanDisplayArea }); } function computeAutoGeometry(options: ComputeGeometryAutoProps): Geometry | null { const { displayArea, requestedContentSize, fromRect, previousPlacement, debug, arrowStyle } = options; // Keep same placement if possible (left/right) if (previousPlacement === Placement.LEFT || previousPlacement === Placement.RIGHT) { const geom = previousPlacement === Placement.LEFT ? computeLeftGeometry(options) : computeRightGeometry(options); debug('computeAutoGeometry - Left/right tryping to keep same, geometry', geom); if (!geom.viewLargerThanDisplayArea.width) return geom; } // Keep same placement if possible (top/bottom) if (previousPlacement === Placement.TOP || previousPlacement === Placement.BOTTOM) { const geom = previousPlacement === Placement.TOP ? computeTopGeometry(options) : computeBottomGeometry(options); debug('computeAutoGeometry - Top/bottom tryping to keep same, geometry', geom); if (!geom.viewLargerThanDisplayArea.height) return geom; } /* * Otherwise, find the place that can fit it best (try left/right but * default to top/bottom as that will typically have more space) */ const arrowSize = getArrowSize(Placement.LEFT, arrowStyle); // generating list of all possible sides with validity debug('computeAutoGeometry - displayArea', displayArea); debug('computeAutoGeometry - fromRect', fromRect); const spaceList: SpaceList = { [Placement.LEFT]: { sizeAvailable: fromRect.x - displayArea.x - arrowSize.width, sizeRequested: requestedContentSize.width }, [Placement.RIGHT]: { sizeAvailable: displayArea.x + displayArea.width - (fromRect.x + fromRect.width) - arrowSize.width, sizeRequested: requestedContentSize.width }, [Placement.TOP]: { sizeAvailable: fromRect.y - displayArea.y - arrowSize.width, sizeRequested: requestedContentSize.height }, [Placement.BOTTOM]: { sizeAvailable: displayArea.y + displayArea.height - (fromRect.y + fromRect.height) - arrowSize.width, sizeRequested: requestedContentSize.height } }; debug('computeAutoGeometry - List of availabe space', spaceList); const bestPlacementPosition = findBestPlacement(spaceList); debug('computeAutoGeometry - Found best postition for placement', bestPlacementPosition); switch (bestPlacementPosition) { case Placement.LEFT: return computeLeftGeometry(options); case Placement.RIGHT: return computeRightGeometry(options); case Placement.BOTTOM: return computeBottomGeometry(options); case Placement.TOP: return computeTopGeometry(options); // Return nothing so popover will be placed in middle of screen default: return null; } } type SpaceList = Record< Placement.LEFT | Placement.RIGHT | Placement.TOP | Placement.BOTTOM, PlacementOption > type PlacementOption = { sizeRequested: number; sizeAvailable: number; } function findBestPlacement(spaceList: SpaceList): Placement | null { return Object.keys(spaceList).reduce( (bestPlacement, placement) => ( // If it can fit, and is the first one or fits better than the last one, use this placement spaceList[placement].sizeRequested <= spaceList[placement].sizeAvailable && ( !bestPlacement || spaceList[placement].sizeAvailable > spaceList[bestPlacement].sizeAvailable ) ? placement as Placement : bestPlacement ), null as Placement | null ); }
the_stack
import * as React from 'react'; import { Button, Tooltip } from '@patternfly/react-core'; import { MinusCircleIcon, PlusCircleIcon } from '@patternfly/react-icons'; import * as _ from 'lodash'; import { useTranslation } from 'react-i18next'; import { NodeAffinity as NodeAffinityType, MatchExpression, PodAffinity as PodAffinityType, PodAffinityTerm, Selector, } from '@console/internal/module/k8s'; import { MatchExpressions } from './match-expressions'; enum AffinityRuleType { Preferred = 'Preferred', Required = 'Required', } const ALLOWED_MATCH_EXPRESSION_OPERATORS: MatchExpression['operator'][] = [ 'In', 'NotIn', 'Exists', 'DoesNotExist', ]; const DEFAULT_MATCH_EXPRESSION: MatchExpression = { key: '', operator: 'Exists', }; export const DEFAULT_NODE_AFFINITY: NodeAffinityType = { requiredDuringSchedulingIgnoredDuringExecution: { nodeSelectorTerms: [{ matchExpressions: [_.cloneDeep(DEFAULT_MATCH_EXPRESSION)] }], }, preferredDuringSchedulingIgnoredDuringExecution: [ { weight: 1, preference: { matchExpressions: [_.cloneDeep(DEFAULT_MATCH_EXPRESSION)] }, }, ], }; export const DEFAULT_POD_AFFINITY: PodAffinityType = { requiredDuringSchedulingIgnoredDuringExecution: [ { topologyKey: 'failure-domain.beta.kubernetes.io/zone', labelSelector: { matchExpressions: [_.cloneDeep(DEFAULT_MATCH_EXPRESSION)] }, }, ], preferredDuringSchedulingIgnoredDuringExecution: [ { weight: 1, podAffinityTerm: { topologyKey: 'failure-domain.beta.kubernetes.io/zone', labelSelector: { matchExpressions: [_.cloneDeep(DEFAULT_MATCH_EXPRESSION)] }, }, }, ], }; const NodeAffinityRule: React.FC<NodeAffinityRuleProps> = ({ key, type, showRemoveButton = false, onClickRemove, onChange = () => {}, rule, }) => { const { t } = useTranslation(); const { weight, selector } = rule; const onChangeMatchExpressions = (matchExpressions: MatchExpression[]): void => onChange({ ...rule, selector: { ...selector, matchExpressions, }, }); const onChangeWeight = (e: React.ChangeEvent<HTMLInputElement>): void => { const parsedValue = _.parseInt(e?.target?.value); onChange({ ...rule, weight: _.isFinite(parsedValue) ? parsedValue : undefined, }); }; return ( <div className="co-affinity-term"> {showRemoveButton && ( <Button type="button" className="co-affinity-term__remove" onClick={onClickRemove} variant="link" > <MinusCircleIcon className="co-icon-space-r" /> {t('olm~Remove {{item}}', { item: type })} </Button> )} {type === AffinityRuleType.Preferred && ( <div className="co-affinity-term__weight-input"> <label className="control-label co-required" htmlFor={`preference-${key}`}> {t('olm~Weight')} </label> <input className="pf-c-form-control" type="number" value={weight} onChange={onChangeWeight} required /> </div> )} <MatchExpressions matchExpressions={selector?.matchExpressions} onChange={onChangeMatchExpressions} allowedOperators={ALLOWED_MATCH_EXPRESSION_OPERATORS} uid={key} /> </div> ); }; export const NodeAffinity: React.FC<NodeAffinityProps> = ({ affinity, onChange, uid = '' }) => { const { t } = useTranslation(); const requiredRules = affinity?.requiredDuringSchedulingIgnoredDuringExecution?.nodeSelectorTerms || []; const preferredRules = affinity?.preferredDuringSchedulingIgnoredDuringExecution || []; const addRequiredRule = () => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: { nodeSelectorTerms: [...requiredRules, { matchExpressions: [] }], }, }); const removeRequiredRule = (atIndex: number) => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: { nodeSelectorTerms: requiredRules.filter((_v, index) => index !== atIndex), }, }); const updateRequiredRules = ({ selector }: NodeAffinityRule, atIndex: number) => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: { nodeSelectorTerms: requiredRules.map((current, index) => index === atIndex ? selector : current, ), }, }); const addPreferredRule = () => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: [ ...preferredRules, { weight: 1, preference: { matchExpressions: [] } }, ], }); const removePreferredRule = (atIndex: number) => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: preferredRules.filter( (_v, index) => index !== atIndex, ), }); const updatePreferredRules = ( { selector: preference, weight }: NodeAffinityRule, atIndex: number, ) => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: preferredRules.map((current, index) => index === atIndex ? { preference, weight } : current, ), }); return ( <dl> <Tooltip content={t('olm~Required rules must be met before a pod can be scheduled on a node.')} > <dt>{t('olm~Required during scheduling, ignored during execution')}</dt> </Tooltip> <dd> {requiredRules.map((selector, requiredIndex) => ( <NodeAffinityRule // Have to use array index in the key bc any other unique id whould have to use editable fields. // eslint-disable-next-line react/no-array-index-key key={`${uid}-node-affinity-required-${requiredIndex}`} onChange={(rule) => updateRequiredRules(rule, requiredIndex)} onClickRemove={() => removeRequiredRule(requiredIndex)} rule={{ selector }} showRemoveButton type={AffinityRuleType.Required} /> ))} <div className="row"> <Button type="button" onClick={addRequiredRule} variant="link"> <PlusCircleIcon className="co-icon-space-r" /> {t('olm~Add required')} </Button> </div> </dd> <Tooltip content={t( 'olm~Preferred rules specify that, if the rule is met, the scheduler tries to enforce the rules, but does not guarantee enforcement.', )} > <dt>{t('olm~Preferred during scheduling, ignored during execution')}</dt> </Tooltip> <dd> {preferredRules.map(({ preference: selector, weight }, preferredIndex) => ( <NodeAffinityRule // Have to use array index in the key bc any other unique id whould have to use editable fields. // eslint-disable-next-line react/no-array-index-key key={`${uid}-node-affinity-preferred-${preferredIndex}`} onChange={(rule) => updatePreferredRules(rule, preferredIndex)} onClickRemove={() => removePreferredRule(preferredIndex)} rule={{ selector, weight }} showRemoveButton type={AffinityRuleType.Preferred} /> ))} <div className="row"> <Button type="button" onClick={addPreferredRule} variant="link"> <PlusCircleIcon className="co-icon-space-r" /> {t('olm~Add preferred')} </Button> </div> </dd> </dl> ); }; const PodAffinityRule: React.FC<PodAffinityRuleProps> = ({ key, onChange = () => {}, onClickRemove = () => {}, showRemoveButton = false, rule, type, }) => { const { t } = useTranslation(); const { podAffinityTerm, weight } = rule; const selector = podAffinityTerm?.labelSelector || {}; const topologyKey = podAffinityTerm?.topologyKey; const onChangeWeight = (e: React.ChangeEvent<HTMLInputElement>): void => { const parsed = _.parseInt(e?.target?.value); onChange({ ...rule, weight: _.isFinite(parsed) ? parsed : undefined, }); }; const onChangeTopologyKey = (e: React.ChangeEvent<HTMLInputElement>): void => onChange({ ...rule, podAffinityTerm: { ...podAffinityTerm, topologyKey: e?.target?.value, }, }); const onChangeMatchExpressions = (matchExpressions: MatchExpression[]): void => onChange({ ...rule, podAffinityTerm: { ...podAffinityTerm, labelSelector: { ...selector, matchExpressions, }, }, }); return podAffinityTerm ? ( <div className="co-affinity-term"> {showRemoveButton && ( <Button type="button" className="co-affinity-term__remove" onClick={onClickRemove} variant="link" > <MinusCircleIcon className="co-icon-space-r" /> {t('olm~Remove {{item}}', { item: type })} </Button> )} <div className="co-affinity-term__topology"> {type === AffinityRuleType.Preferred && ( <div className="co-affinity-term__weight-input"> <label className="control-label co-required" htmlFor={`preference-${key}`}> {t('olm~Weight')} </label> <input className="pf-c-form-control" type="number" value={weight} onChange={onChangeWeight} required /> </div> )} <div className="co-affinity-term__topology-input"> <label className="control-label co-required" htmlFor={`topology-${key}`}> {t('olm~Topology key')} </label> <input id={`topology-${key}`} className="pf-c-form-control" type="text" value={topologyKey} onChange={onChangeTopologyKey} required /> </div> </div> <MatchExpressions matchExpressions={selector?.matchExpressions} onChange={onChangeMatchExpressions} allowedOperators={ALLOWED_MATCH_EXPRESSION_OPERATORS} uid={key} /> </div> ) : null; }; export const PodAffinity: React.FC<PodAffinityProps> = ({ affinity, onChange, uid = '' }) => { const { requiredDuringSchedulingIgnoredDuringExecution: requiredRules = [], preferredDuringSchedulingIgnoredDuringExecution: preferredRules = [], } = affinity || {}; const { t } = useTranslation(); const addRequiredRule = () => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: [ ...requiredRules, { topologyKey: '', labelSelector: { matchExpressions: [] } }, ], }); const removeRequiredRule = (atIndex: number) => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: requiredRules.filter( (_v, index) => atIndex !== index, ), }); const updateRequiredRules = ({ podAffinityTerm: next }: PodAffinityRule, atIndex: number) => onChange?.({ ...affinity, requiredDuringSchedulingIgnoredDuringExecution: requiredRules.map((current, index) => index === atIndex ? next : current, ), }); const addPreferredRule = () => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: [ ...preferredRules, { weight: 1, podAffinityTerm: { topologyKey: '', labelSelector: { matchExpressions: [] } }, }, ], }); const removePreferredRule = (atIndex: number) => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: preferredRules.filter( (_v, index) => atIndex !== index, ), }); const updatePreferredRules = (next: PodAffinityRule, atIndex: number) => onChange?.({ ...affinity, preferredDuringSchedulingIgnoredDuringExecution: preferredRules.map((current, index) => index === atIndex ? next : current, ), }); return ( <dl> <Tooltip content={t('olm~Required rules must be met before a pod can be scheduled on a node.')} > <dt>{t('olm~Required during scheduling, ignored during execution')}</dt> </Tooltip> <dd> {_.map(requiredRules, (podAffinityTerm, ruleIndex) => ( // Have to use array index in the key bc any other unique id whould have to use editable fields. // eslint-disable-next-line react/no-array-index-key <PodAffinityRule key={`${uid}-pod-affinity-required-${ruleIndex}`} rule={{ podAffinityTerm }} onChange={(rule) => updateRequiredRules(rule, ruleIndex)} onClickRemove={() => removeRequiredRule(ruleIndex)} showRemoveButton type={AffinityRuleType.Required} /> ))} <div className="row"> <Button type="button" onClick={addRequiredRule} variant="link"> <PlusCircleIcon className="co-icon-space-r" /> {t('olm~Add required')} </Button> </div> </dd> <Tooltip content={t( 'olm~Preferred rules specify that, if the rule is met, the scheduler tries to enforce the rules, but does not guarantee enforcement.', )} > <dt>{t('olm~Preferred during scheduling, ignored during execution')}</dt> </Tooltip> <dd> {preferredRules.map((preferredRule, ruleIndex) => { // Have to use array index in the key bc any other unique id whould have to use editable fields. return ( <PodAffinityRule // eslint-disable-next-line react/no-array-index-key key={`${uid}-pod-affinity-preferred-${ruleIndex}`} onChange={(rule) => updatePreferredRules(rule, ruleIndex)} onClickRemove={() => removePreferredRule(ruleIndex)} showRemoveButton rule={preferredRule} type={AffinityRuleType.Preferred} /> ); })} <div className="row"> <Button type="button" onClick={addPreferredRule} variant="link"> <PlusCircleIcon className="co-icon-space-r" /> {t('olm~Add preferred')} </Button> </div> </dd> </dl> ); }; type NodeAffinityRule = { selector: Selector; weight?: number; }; export type NodeAffinityRuleProps = { key: string; onChange?: (rule: NodeAffinityRule) => void; onClickRemove?: () => void; rule: NodeAffinityRule; showRemoveButton?: boolean; type: AffinityRuleType; }; export type NodeAffinityProps = { uid?: string; affinity: NodeAffinityType; onChange: (affinity: NodeAffinityType) => void; }; type PodAffinityRule = { podAffinityTerm: PodAffinityTerm; weight?: number; }; export type PodAffinityRuleProps = { key: string; rule: PodAffinityRule; onChange?: (rule: PodAffinityRule) => void; onClickRemove?: () => void; showRemoveButton?: boolean; type: AffinityRuleType; }; export type PodAffinityProps = { uid?: string; affinity: PodAffinityType; onChange: (affinity: PodAffinityType) => void; }; NodeAffinity.displayName = 'NodeAffinity'; PodAffinity.displayName = 'PodAffinity';
the_stack
import {times} from 'lodash' import { Aperture, BatteryLevel, ConfigForDevicePropTable, DriveMode, DriveModeTable, ExposureMode, ExposureModeTable, ISO, WhiteBalance, WhiteBalanceTable, } from '../configs' import {DeviceInfo} from '../DeviceInfo' import { DatatypeCode, DevicePropCode, EventCode, ObjectFormatCode, OpCode, PTPAccessCapabilityCode, PTPFilesystemTypeCode, PTPStorageTypeCode, ResCode, } from '../PTPDatacode' import {PTPDataView} from '../PTPDataView' import {PTPDevice, PTPEvent} from '../PTPDevice' import { ConfigDesc, createReadonlyConfigDesc, OperationResult, TakePhotoOption, Tethr, } from '../Tethr' import {TethrObject, TethrObjectInfo} from '../TethrObject' import {isntNil, toHexString} from '../util' type DevicePropScheme<T, D extends DatatypeCode> = { devicePropCode: number datatypeCode: D decode: (data: DataViewTypeForDatatypeCode<D>) => T | null encode: (value: T) => DataViewTypeForDatatypeCode<D> | null } type DataViewTypeForDatatypeCode<D extends DatatypeCode> = D extends DatatypeCode.String ? string : D extends DatatypeCode.Uint64 ? bigint : D extends DatatypeCode.Int64 ? bigint : D extends DatatypeCode.Uint128 ? bigint : D extends DatatypeCode.Int128 ? bigint : number export class TethrPTPUSB extends Tethr { protected _opened = false public constructor(protected device: PTPDevice) { super() } public get opened(): boolean { return this._opened } public async open(): Promise<void> { if (!this.device.opened) { await this.device.open() } await this.device.sendCommand({ label: 'Open Session', opcode: OpCode.OpenSession, parameters: [0x1], expectedResCodes: [ResCode.OK, ResCode.SessionAlreadyOpen], }) this.device.onEventCode( EventCode.DevicePropChanged, this.onDevicePropChanged ) this.device.on('disconnect', () => this.emit('disconnect')) window.addEventListener('beforeunload', async () => { await this.close() }) this._opened = true } public async close(): Promise<void> { this._opened = false await this.device.sendCommand({ label: 'Close Session', opcode: OpCode.CloseSession, }) await this.device.close() } // Configs public setAperture(value: Aperture) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.FNumber, datatypeCode: DatatypeCode.Uint16, encode(value) { if (value === 'auto') return null return Math.round(value * 100) }, value, }) } public getApertureDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.FNumber, datatypeCode: DatatypeCode.Uint16, decode(data) { return (data / 100) as Aperture }, }) } public getBatteryLevelDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.BatteryLevel, datatypeCode: DatatypeCode.Uint8, decode: data => data as BatteryLevel, }) } public async getCanTakePhotoDesc() { const {operationsSupported} = await this.getDeviceInfo() const value = operationsSupported.includes(OpCode.InitiateCapture) return createReadonlyConfigDesc(value) } public setCaptureDelay(value: number) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.CaptureDelay, datatypeCode: DatatypeCode.Uint32, encode: data => data, value, }) } public getCaptureDelayDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.CaptureDelay, datatypeCode: DatatypeCode.Uint32, decode: data => data, }) } public setDriveMode(value: DriveMode) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.StillCaptureMode, datatypeCode: DatatypeCode.Uint16, encode(value) { return DriveModeTable.getKey(value) ?? 0x0 }, value, }) } public getDriveModeDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.StillCaptureMode, datatypeCode: DatatypeCode.Uint16, decode: data => { return DriveModeTable.get(data) ?? 'normal' }, }) } public setExposureComp(value: string) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.ExposureBiasCompensation, datatypeCode: DatatypeCode.Int16, encode(str) { if (str === '0') return 0 const match = str.match(/^([+-]?)([0-9]+)?\s?(1\/2|1\/3|2\/3)?$/) if (!match) return null const [, signStr, integerStr, fractionStr] = match const sign = signStr === '-' ? -1 : +1 const integer = parseInt(integerStr) let fracMills = 0 switch (fractionStr) { case '1/3': fracMills = 300 break case '1/2': fracMills = 500 break case '2/3': fracMills = 700 break } return sign * (integer * 1000 + fracMills) }, value, }) } public getExposureCompDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.ExposureBiasCompensation, datatypeCode: DatatypeCode.Int16, decode(mills) { if (mills === 0) return '0' const millsAbs = Math.abs(mills) const sign = mills > 0 ? '+' : '-' const integer = Math.floor(millsAbs / 1000) const fracMills = millsAbs % 1000 let fraction = '' switch (fracMills) { case 300: fraction = '1/3' break case 500: fraction = '1/2' break case 700: fraction = '2/3' break } if (integer === 0) return `${sign}${fraction}` if (fraction === '') return `${sign}${integer}` return `${sign}${integer} ${fraction}` }, }) } public async setExposureMode(value: ExposureMode) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.ExposureProgramMode, datatypeCode: DatatypeCode.Uint16, encode: value => { return ( ExposureModeTable.getKey(value) ?? parseInt(value.replace('vendor ', ''), 16) ) }, value, }) } public async getExposureModeDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.ExposureProgramMode, datatypeCode: DatatypeCode.Uint16, decode(data) { return ( ExposureModeTable.get(data) ?? (`vendor ${toHexString(data, 4)}` as ExposureMode) ) }, }) } public setImageSizeValue(value: string) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.ImageSize, datatypeCode: DatatypeCode.String, encode: data => data, value, }) } public getImageSizeDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.ImageSize, datatypeCode: DatatypeCode.String, decode: data => data, }) } public setIso(value: ISO) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.ExposureIndex, datatypeCode: DatatypeCode.Uint16, encode(iso) { if (iso === 'auto') return 0xffff return iso }, value, }) } public getIsoDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.ExposureIndex, datatypeCode: DatatypeCode.Uint16, decode: data => { if (data === 0xffff) return 'auto' return data }, }) } public async getManufacturerDesc() { return { writable: false, value: (await this.getDeviceInfo()).manufacturer, } } public async getModelDesc() { return { writable: false, value: (await this.getDeviceInfo()).model, } } public setWhiteBalance(value: WhiteBalance) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.WhiteBalance, datatypeCode: DatatypeCode.Uint16, encode(value) { return ( WhiteBalanceTable.getKey(value) ?? parseInt(value.replace(/^vendor /, ''), 16) ) }, value, }) } public getWhiteBalanceDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.WhiteBalance, datatypeCode: DatatypeCode.Uint16, decode: data => { return ( WhiteBalanceTable.get(data) ?? (`vendor ${toHexString(data, 4)}` as WhiteBalance) ) }, }) } public setTimelapseNumber(value: number) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.TimelapseNumber, datatypeCode: DatatypeCode.Uint32, encode: data => data, value, }) } public getTimelapseNumberDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.TimelapseNumber, datatypeCode: DatatypeCode.Uint32, decode: data => data, }) } public setTimelapseInterval(value: number) { return this.setDevicePropValue({ devicePropCode: DevicePropCode.TimelapseInterval, datatypeCode: DatatypeCode.Uint32, encode: data => data, value, }) } public getTimelapseIntervalDesc() { return this.getDevicePropDesc({ devicePropCode: DevicePropCode.TimelapseInterval, datatypeCode: DatatypeCode.Uint32, decode: data => data, }) } // Actions public async takePhoto({download = true}: TakePhotoOption = {}): Promise< OperationResult<TethrObject[]> > { const {operationsSupported} = await this.getDeviceInfo() if (!operationsSupported.includes(OpCode.InitiateCapture)) { return {status: 'unsupported'} } await this.device.sendCommand({ label: 'InitiateCapture', opcode: OpCode.InitiateCapture, parameters: [0x0], }) const objectAddedEvent = await this.device.waitEvent(EventCode.ObjectAdded) if (!download) return {status: 'ok', value: []} const objectID = objectAddedEvent.parameters[0] const objectInfo = await this.getObjectInfo(objectID) const objectBuffer = await this.getObject(objectID) const tethrObject: TethrObject = { ...objectInfo, blob: new Blob([objectBuffer], {type: 'image/jpeg'}), } return {status: 'ok', value: [tethrObject]} } // Utility functions protected async setDevicePropValue<T, D extends DatatypeCode>({ devicePropCode, datatypeCode, encode, value, }: Omit<DevicePropScheme<T, D>, 'decode'> & {value: T}): Promise< OperationResult<void> > { const devicePropData = encode(value) if (devicePropData === null) { return { status: 'invalid parameter', } } const dataView = new PTPDataView() switch (datatypeCode) { case DatatypeCode.Uint8: dataView.writeUint8(devicePropData as number) break case DatatypeCode.Int8: dataView.writeInt8(devicePropData as number) break case DatatypeCode.Uint16: dataView.writeUint16(devicePropData as number) break case DatatypeCode.Int16: dataView.writeInt16(devicePropData as number) break case DatatypeCode.Uint32: dataView.writeUint32(devicePropData as number) break case DatatypeCode.Int32: dataView.writeInt32(devicePropData as number) break case DatatypeCode.Uint64: dataView.writeBigUint64(devicePropData as bigint) break case DatatypeCode.String: dataView.writeBigUint64(devicePropData as bigint) break default: { const label = DatatypeCode[datatypeCode] ?? toHexString(16) throw new Error( `DevicePropDesc of datatype ${label} is not yet supported` ) } } const {resCode} = await this.device.sendData({ label: 'SetDevicePropValue', opcode: OpCode.SetDevicePropValue, parameters: [devicePropCode], data: dataView.toBuffer(), expectedResCodes: [ResCode.OK, ResCode.DeviceBusy], }) return { status: resCode === ResCode.OK ? 'ok' : 'busy', } } protected async getDevicePropDesc<T, D extends DatatypeCode>({ devicePropCode, datatypeCode, decode, }: Omit<DevicePropScheme<T, D>, 'encode'>): Promise<ConfigDesc<T>> { // Check if the deviceProps is supported if (!(await this.isDevicePropSupported(devicePropCode))) { return { writable: false, value: null, } } const {data} = await this.device.receiveData({ label: 'GetDevicePropDesc', opcode: OpCode.GetDevicePropDesc, parameters: [devicePropCode], }) const dataView = new PTPDataView(data.slice(2)) /*const dataType =*/ dataView.readUint16() const writable = dataView.readUint8() === 0x01 // Get/Set let readValue: () => DataViewTypeForDatatypeCode<D> switch (datatypeCode) { case DatatypeCode.Uint8: readValue = dataView.readUint8 as any break case DatatypeCode.Uint16: readValue = dataView.readUint16 as any break case DatatypeCode.Int16: readValue = dataView.readInt16 as any break case DatatypeCode.Uint32: readValue = dataView.readUint32 as any break case DatatypeCode.Uint64: readValue = dataView.readUint64 as any break case DatatypeCode.String: readValue = dataView.readUTF16StringNT as any break default: { const label = DatatypeCode[datatypeCode] ?? toHexString(16) throw new Error(`PropDesc of datatype ${label} is not yet supported`) } } readValue() // Skip factoryDefault const value = decode(readValue()) // Read options const formFlag = dataView.readUint8() let option: ConfigDesc<T>['option'] switch (formFlag) { case 0x00: // None option = undefined break case 0x01: { // Range const min = decode(readValue()) const max = decode(readValue()) const step = decode(readValue()) if ( typeof min !== 'number' || typeof max !== 'number' || typeof step !== 'number' ) { throw new Error(`Cannot enumerate supported values of device config`) } option = { type: 'range', min, max, step, } break } case 0x02: { // Enumeration const length = dataView.readUint16() option = { type: 'enum', values: times(length, readValue).map(decode).filter(isntNil), } break } default: throw new Error(`Invalid form flag ${formFlag}`) } return { writable, value, option, } } private async isDevicePropSupported(code: number): Promise<boolean> { const {devicePropsSupported} = await this.getDeviceInfo() return devicePropsSupported.includes(code) } protected async getDeviceInfo(): Promise<DeviceInfo> { return await TethrPTPUSB.getDeviceInfo(this.device) } protected async getObjectHandles(storageId = 0xffffffff): Promise<number[]> { const {data} = await this.device.receiveData({ label: 'GetObjectHandles', opcode: OpCode.GetObjectHandles, parameters: [storageId, 0xffffffff, 0x0], }) return new PTPDataView(data).readUint32Array() } protected async getObjectInfo(id: number): Promise<TethrObjectInfo> { const {data} = await this.device.receiveData({ label: 'GetObjectInfo', opcode: OpCode.GetObjectInfo, parameters: [id], }) const dataView = new PTPDataView(data) return { id, storageID: dataView.readUint32(), format: this.getObjectFormatNameByCode(dataView.readUint16()), // protectionStatus: dataView.readUint16(), byteLength: dataView.skip(2).readUint32(), thumb: { format: this.getObjectFormatNameByCode(dataView.readUint16()), compressedSize: dataView.readUint32(), width: dataView.readUint32(), height: dataView.readUint32(), }, image: { width: dataView.readUint32(), height: dataView.readUint32(), bitDepth: dataView.readUint32(), }, // parent: dataView.readUint32(), // associationType: dataView.readUint16(), // associationDesc: dataView.readUint32(), sequenceNumber: dataView.skip(4 + 2 + 4).readUint32(), filename: dataView.readFixedUTF16String(), captureDate: dataView.readDate(), modificationDate: dataView.readDate(), // keywords: dataView.readFixedUTF16String(), } } protected async getObject(objectID: number): Promise<ArrayBuffer> { const {byteLength} = await this.getObjectInfo(objectID) const {data} = await this.device.receiveData({ label: 'GetObject', opcode: OpCode.GetObject, parameters: [objectID], maxByteLength: byteLength + 1000, }) return data } protected async getStorageInfo(): Promise<void> { const {data} = await this.device.receiveData({ label: 'Get Storage IDs', opcode: OpCode.GetStorageIDs, }) const dataView = new PTPDataView(data) const storageIDs = dataView.readUint32Array() console.log('Storage IDs =', storageIDs) for (const id of storageIDs) { const {data} = await this.device.receiveData({ label: 'GetStorageInfo', parameters: [id], opcode: OpCode.GetStorageInfo, }) const storageInfo = new PTPDataView(data) const info = { storageId: id, storageType: PTPStorageTypeCode[storageInfo.readUint16()], filesystemType: PTPFilesystemTypeCode[storageInfo.readUint16()], accessCapability: PTPAccessCapabilityCode[storageInfo.readUint16()], maxCapability: storageInfo.readUint64(), freeSpaceInBytes: storageInfo.readUint64(), freeSpaceInImages: storageInfo.readUint32(), } console.log(`Storage info for ${id}=`, info) } } protected onDevicePropChanged = async (event: PTPEvent) => { const devicePropCode = event.parameters[0] const name = this.getConfigNameByCode(devicePropCode) if (!name) return const desc = await this.getDesc(name) this.emit(`${name}Changed`, desc) } protected getConfigNameByCode(code: number) { return ConfigForDevicePropTable.get(code) ?? null } protected getObjectFormatNameByCode(code: number) { return ObjectFormatCode[code].toLowerCase() } public static async getDeviceInfo(device: PTPDevice): Promise<DeviceInfo> { const {data} = await device.receiveData({ label: 'GetDeviceInfo', opcode: OpCode.GetDeviceInfo, }) const dataView = new PTPDataView(data) return { standardVersion: dataView.readUint16(), vendorExtensionID: dataView.readUint32(), vendorExtensionVersion: dataView.readUint16(), vendorExtensionDesc: dataView.readFixedUTF16String(), functionalMode: dataView.readUint16(), operationsSupported: dataView.readUint16Array(), eventsSupported: dataView.readUint16Array(), devicePropsSupported: dataView.readUint16Array(), captureFormats: dataView.readUint16Array(), imageFormats: dataView.readUint16Array(), manufacturer: dataView.readFixedUTF16String(), model: dataView.readFixedUTF16String(), deviceVersion: dataView.readFixedUTF16String(), serialNumber: dataView.readFixedUTF16String(), } } }
the_stack
namespace annie { /** * 显示对象的容器类,可以将其他显示对象放入其中,是annie引擎的核心容器类. * Sprite 类是基本显示列表构造块:一个可显示图形并且也可包含子项的显示列表节点。 * Sprite 对象与影片剪辑类似,但没有时间轴。Sprite 是不需要时间轴的对象的相应基类。 * 例如,Sprite 将是通常不使用时间轴的用户界面 (UI) 组件的逻辑基类 * @class annie.Sprite * @extends annie.DisplayObject * @public * @since 1.0.0 */ export class Sprite extends DisplayObject { /** * 构造函数 * @method Sprite * @public * @since 1.0.0 */ public constructor() { super(); let s = this; s._instanceType = "annie.Sprite"; } public destroy(): void { let s: any = this; //让子级也destroy for (let i = 0; i < s.children.length; i++) { s.children[i].destroy(); } if (s.parent instanceof annie.Sprite) Sprite._removeFormParent(s.parent, s); s.children = null; s._hitArea = null; super.destroy(); } /** * 容器类所有动画的播放速度,默认是1.如果有嵌套的话,速度相乘; * @property mcSpeed * @public * @type {number} * @since 3.1.5 * @default 1 * */ public mcSpeed: number = 1; protected _cMcSpeed: number = 1; /** * 是否可以让children接收鼠标事件 * 鼠标事件将不会往下冒泡 * @property mouseChildren * @type {boolean} * @default true * @public * @since 1.0.0 */ public mouseChildren: boolean = true; /** * 显示对象的child列表 * @property children * @type {Array} * @public * @since 1.0.0 * @default [] * @readonly */ public children: DisplayObject[] = []; /** * 添加一个显示对象到Sprite * @method addChild * @param {annie.DisplayObject} child * @public * @since 1.0.0 * @return {void} */ public addChild(child: DisplayObject): void { this.addChildAt(child, this.children.length); } /** * 从Sprite中移除一个child * @method removeChild * @public * @since 1.0.0 * @param {annie.DisplayObject} child * @return {void} */ public removeChild(child: DisplayObject): void { let s = this; let len = s.children.length; for (let i = 0; i < len; i++) { if (s.children[i] == child) { s.removeChildAt(i); break; } } } //全局遍历查找 private static _getElementsByName(rex: RegExp, root: annie.Sprite, isOnlyOne: boolean, isRecursive: boolean, resultList: Array<annie.DisplayObject>): void { let len = root.children.length; if (len > 0) { let name: string; let child: any; for (let i = 0; i < len; i++) { child = root.children[i]; name = child.name; if (name && name != "") { if (rex.test(name)) { resultList[resultList.length] = child; if (isOnlyOne) { return; } } } if (isRecursive) { if (child instanceof annie.Sprite) { Sprite._getElementsByName(rex, child, isOnlyOne, isRecursive, resultList); } } } } } /** * 通过给displayObject设置的名字来获取一个child,可以使用正则匹配查找 * @method getChildByName * @param {string} name 对象的具体名字或是一个正则表达式 * @param {boolean} isOnlyOne 默认为true,如果为true,只返回最先找到的对象,如果为false则会找到所有匹配的对象数组 * @param {boolean} isRecursive false,如果为true,则会递归查找下去,而不只是查找当前对象中的child,child里的child也会找,依此类推 * @return {string|Array} 返回一个对象,或者一个对象数组,没有找到则返回空 * @public * @since 1.0.0 */ public getChildByName(name: string | RegExp, isOnlyOne: boolean = true, isRecursive: boolean = false): any { if (!name) return null; let s = this; let rex: any; if (typeof(name) == "string") { rex = new RegExp("^" + name + "$"); } else { rex = name; } let elements: Array<annie.DisplayObject> = []; Sprite._getElementsByName(rex, s, isOnlyOne, isRecursive, elements); let len = elements.length; if (len == 0) { return null; } else if (len == 1) { return elements[0]; } else { return elements; } } /** * 添加一个child到Sprite中并指定添加到哪个层级 * @method addChildAt * @param {annie.DisplayObject} child * @param {number} index 从0开始 * @public * @since 1.0.0 * @return {void} */ public addChildAt(child: DisplayObject, index: number): void { if (!(child instanceof annie.DisplayObject)) return; let s = this; let len: number; let cp = child.parent; if (cp instanceof annie.Sprite) { Sprite._removeFormParent(cp, child); } len = s.children.length; if (index >= len) { s.children[len] = child; } else if (index == 0) { s.children.unshift(child); } else { s.children.splice(index, 0, child); } if (cp != s) { child._cp = true; child.parent = s; if (s._isOnStage && !child._isOnStage) { child.stage = s.stage; child._onAddEvent(); } } } private static _removeFormParent(cp: Sprite, child: DisplayObject): void { let cpc = cp.children; let len = cpc.length; for (let i = 0; i < len; i++) { if (cpc[i] == child) { cpc.splice(i, 1); break; } } } /** * 获取Sprite中指定层级一个child * @method getChildAt * @param {number} index 从0开始 * @public * @since 1.0.0 * @return {annie.DisplayObject} */ public getChildAt(index: number): annie.DisplayObject { if ((this.children.length - 1) >= index) { return this.children[index]; } else { return null; } } /** * 获取Sprite中一个child所在的层级索引,找到则返回索引数,未找到则返回-1 * @method getChildIndex * @param {annie.DisplayObject} child 子对象 * @public * @since 1.0.2 * @return {number} */ public getChildIndex(child: DisplayObject): number { let s = this; let len = s.children.length; for (let i: number = 0; i < len; i++) { if (s.children[i] == child) { return i; } } return -1; } /** * 交换两个显示对象的层级 * @method swapChild * @param child1 显示对象,或者显示对象的索引 * @param child2 显示对象,或者显示对象的索引 * @since 2.0.0 * @return {boolean} */ public swapChild(child1: any, child2: any): boolean { let s = this; let id1 = -1; let id2 = -1; let childCount = s.children.length; if (typeof(child1) == "number") { id1 = child1; } else { id1 = s.getChildIndex(child1); } if (typeof(child2) == "number") { id2 = child2; } else { id2 = s.getChildIndex(child2); } if (id1 == id2 || id1 < 0 || id1 >= childCount || id2 < 0 || id2 >= childCount) { return false; } else { let temp: any = s.children[id1]; s.children[id1] = s.children[id2]; s.children[id2] = temp; return true; } } /** * 移除指定层级上的孩子 * @method removeChildAt * @param {number} index 从0开始 * @public * @since 1.0.0 * @return {void} */ public removeChildAt(index: number): void { let s = this; let child: DisplayObject; let len = s.children.length - 1; if (len < 0) return; if (index == len) { child = s.children.pop(); } else if (index == 0) { child = s.children.shift(); } else { child = s.children.splice(index, 1)[0]; } if (s._isOnStage && child._isOnStage) { child._onRemoveEvent(false); child.stage = null; } child.parent = null; } /** * 移除Sprite上的所有child * @method removeAllChildren * @public * @since 1.0.0 * @return {void} */ public removeAllChildren(): void { let s = this; let len = s.children.length; for (let i = len - 1; i >= 0; i--) { s.removeChildAt(0); } } public hitTestPoint(hitPoint: Point, isGlobalPoint: boolean = false): DisplayObject { let s:any = this; if (!s._visible || !s.mouseEnable) return null; if(s._hitArea){ return super.hitTestPoint(hitPoint,isGlobalPoint); } let p: Point = hitPoint; if (!isGlobalPoint) { p = s.localToGlobal(hitPoint, new Point()); } let len = s.children.length; let hitDisplayObject: DisplayObject; let child: any; let maskObjList: any = {}; //这里特别注意是从上往下遍历 for (let i = len - 1; i >= 0; i--) { child = s.children[i]; if (child._isUseToMask > 0) continue; if (child.mask != void 0) { if (maskObjList[child.mask._instanceId] == void 0) { //看看点是否在遮罩内 if (child.mask.hitTestPoint(p, true)) { //如果都不在遮罩里面,那还检测什么直接检测下一个 maskObjList[child.mask._instanceId] = true; } else { maskObjList[child.mask._instanceId] = false; } } if (maskObjList[child.mask._instanceId] == false) { continue; } } hitDisplayObject = child.hitTestPoint(p, true); if (hitDisplayObject) { return hitDisplayObject; } } return null; } public getBounds(): Rectangle { let s = this; let rect: Rectangle = s._bounds; rect.x = 0; rect.y = 0; rect.width = 0; rect.height = 0; let children: any = s.children, len: number = children.length; if (len > 0) { for (let i = 0; i < len; i++) { if (children[i].visible && children[i]._isUseToMask == 0) children[i].getDrawRect(); Rectangle.createFromRects(rect, DisplayObject._transformRect); } } return rect; } protected _updateMatrix(): void { let s = this; if (s._visible) { super._updateMatrix(); let children: any = s.children; let len: number = children.length; for (let i = 0; i < len; i++) { children[i]._updateMatrix(); } s.a2x_ua = false; s.a2x_um = false; } } public _render(renderObj: IRender): void { let s: any = this; let len: number = s.children.length; if (s._visible && s._cAlpha > 0 && len > 0) { let children: any = s.children; let ro: any = renderObj; let maskObj: any; let child: any; for (let i = 0; i < len; i++) { child = children[i]; if (child._isUseToMask > 0) { continue; } if (maskObj instanceof annie.DisplayObject) { if (child.mask instanceof annie.DisplayObject && child.mask.parent == child.parent) { if (child.mask != maskObj) { ro.endMask(); maskObj = child.mask; ro.beginMask(maskObj); } } else { ro.endMask(); maskObj = null; } } else { if (child.mask instanceof annie.DisplayObject && child.mask.parent == child.parent) { maskObj = child.mask; ro.beginMask(maskObj); } } child._render(ro); } if (maskObj instanceof annie.DisplayObject) { ro.endMask(); } } } public _onRemoveEvent(isReSetMc: boolean): void { let s = this; let child: any = null; //这里用concat 隔离出一个新的children是非常重要的一步 let children = s.children.concat(); let len = children.length; for (let i = len - 1; i >= 0; i--) { child = children[i]; if (child instanceof annie.DisplayObject && child._isOnStage) { child._onRemoveEvent(isReSetMc); child.stage = null; } } super._onRemoveEvent(isReSetMc); } public _onAddEvent(): void { let s = this; let child: any = null; //这里用concat 隔离出一个新的children是非常重要的一步 let children = s.children.concat(); let len = children.length; for (let i = len - 1; i >= 0; i--) { child = children[i]; if (child instanceof annie.DisplayObject && !child._isOnStage) { child.stage = s.stage; child._onAddEvent(); } } super._onAddEvent(); } public _onUpdateFrame(mcSpeed: number = 1, isOffCanvas: boolean = false): void { let s = this; s._cMcSpeed = s.mcSpeed * mcSpeed; super._onUpdateFrame(s._cMcSpeed, isOffCanvas); let child: any = null; let children = s.children.concat(); let len = children.length; for (let i = len - 1; i >= 0; i--) { child = children[i]; if (child) { child._onUpdateFrame(s._cMcSpeed, isOffCanvas); } } } } }
the_stack
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Output, EventEmitter, HostBinding, Input, OnDestroy, AfterContentInit, ContentChild } from '@angular/core'; import { SohoWizardTickComponent } from './soho-wizard-tick.component'; import { SohoWizardHeaderComponent } from './soho-wizard-header.component'; import { SohoWizardPagesComponent } from './soho-wizard-pages.component'; import { SohoWizardPageComponent } from './soho-wizard-page.component'; /** * Angular Wrapper for the Soho Wizard Component. * * This component searches for a div with the attribute * 'soho-wizard' in the DOM, initialising those found with * the SoHo Wizard control. * * TODO: * ===== * * - handling of ticks / tick model (based on underlying widget) * - model driven * - support Builder Panel style (with title?) * - support for "modal style" buttons. * - extract state machine */ @Component({ selector: 'div[soho-wizard]', // eslint-disable-line template: `<ng-content></ng-content>`, styles: [ `:host { display: flex; flex: 1; flex-direction: column; }` ], changeDetection: ChangeDetectionStrategy.OnPush }) export class SohoWizardComponent implements AfterViewInit, AfterContentInit, OnDestroy { /** * Reference to the underlying container for the pages. * * * */ @ContentChild(SohoWizardPagesComponent, { static: true }) pagesContainer?: SohoWizardPagesComponent; /** * Reference to the header, container for the ticks. * * * */ @ContentChild(SohoWizardHeaderComponent, { static: true }) header?: SohoWizardHeaderComponent; // ------------------------------------------- // Inputs // ------------------------------------------- /** * Ticks for the settings - this does not really work yet (i think). */ @Input() set ticks(ticks: SohoWizardTick[]) { this._options.ticks = ticks; if (this.wizard) { this.wizard.settings.ticks = this._options.ticks; this.wizard.updated(); } } get ticks() { return this._options.ticks as any; } /** Id of the current tick. */ @Input() set currentTickId(tickId: string) { this.pagesContainer?.pages.forEach(p => p.hidden = (p.tickId !== tickId)); const step = this.header?.steps?.find(s => s.tickId === tickId); if (this.wizard && step?.jQueryElement) { this.wizard.activate(null, step.jQueryElement); } } get currentTickId(): string { const step = this.currentStep(); const tickId = step?.tickId; return tickId || ''; } /** * Provides a `beforeActivate` vetoable handler, which * allows the caller to prevent activation of a link. * * @todo needs linking with any buttons! */ @Input() private beforeActivate?: (tick?: SohoWizardTick) => boolean; /** * This event is fired when a tick is activated. */ @Output() public activated = new EventEmitter<SohoWizardEvent>(); /** * This event is fired after a tick is activated. */ @Output() public afteractivated = new EventEmitter<SohoWizardEvent>(); // ------------------------------------------- // Hostbinding // ------------------------------------------- @HostBinding('class.wizard') isWizardClass = true; // ------------------------------------------- // Private Member Data // ------------------------------------------- /** Reference to the jQuery control. */ private jQueryElement?: JQuery; /** Reference to the SoHo wizard control api. */ private wizard?: SohoWizardStatic | undefined; /** An internal options object that gets updated by using the component's Inputs(). */ private _options: SohoWizardOptions = {}; /** * Ordered list of steps. * * * * */ private _steps?: SohoWizardTickComponent[]; /** * Has the wizard finished. */ private finished = false; /** * Constructor. * * @param elementRef - the element matching this component. */ constructor(private elementRef: ElementRef) { } // ------------------------------------------- // Public API // ------------------------------------------- /** * Returns the currently selected page. */ public get currentPage(): SohoWizardPageComponent | undefined { if (this.pagesContainer && this.pagesContainer?.pages) { return this.pagesContainer?.pages.find(p => p.tickId === this.currentTickId); } return undefined; } /** * Moves to the first state if possible. */ public first() { if (this.wizard && !this.finished && this.stepCount() > 0) { const step = this.stepAt(0); if (step && step.jQueryElement) { this.wizard.activate(null, step.jQueryElement); } } } /** * Attempts to move to the next step, if allowed. * * */ public next() { // This is a bit grim ... but we need to rely on ticks for the state. let currentIndex = this.currentIndex(); // @todo handle disabled states. if (!this.finished && ++currentIndex < this.stepCount()) { const step = this.stepAt(currentIndex); if (step && step.jQueryElement) { this.wizard?.activate(null, step.jQueryElement); } } } /** * Attempts to move to the previous step, if allowed. * * */ public previous() { let currentIndex = this.currentIndex(); if (!this.finished && --currentIndex >= 0) { const step = this.stepAt(currentIndex); if (step && step.jQueryElement) { this.wizard?.activate(null, step.jQueryElement); } } } /** * Attempts to move to the last step, if allowed. * * */ public last() { const step = this.stepAt(this.stepCount() - 1); if (step && step.jQueryElement) { this.wizard?.activate(null, step.jQueryElement); } } /** * Attempts to move to the last step, and finish the wizard. * * */ public finish() { // Mark the wizard as finished. this.finished = true; // Disabled all ticks. this.header?.steps?.forEach(p => p.disabled = this.finished); // Move to the last tick. this.last(); } /** * Is there another step after the current step? * * @return true if there is another step; otherwise false. * */ public hasNext(): boolean { return !this.finished && this.currentIndex() < this.stepCount() - 1; } /** * Is there previous step. */ public hasPrevious(): boolean { return !this.finished && this.currentIndex() > 0; } /** * Returns true if the process has finished, * otherwise false. */ public hasFinished(): boolean { return this.finished; } /** * Resets the state machine, moving to the first page * and clearing finished flag. */ public reset(): void { this.finished = false; this.first(); } // ------------------------------------------ // Lifecycle Events // ------------------------------------------ ngAfterViewInit() { // Wrap the "unordered list" element in a jQuery selector. this.jQueryElement = jQuery(this.elementRef.nativeElement); // Initialise the Soho control. this.jQueryElement.wizard(this._options); // Once the control is initialised, extract the control // plug-in from the element. The element name is // defined by the plug-in, but in this case it is 'wizard'. this.wizard = this.jQueryElement.data('wizard'); // Initialize any event handlers. this.jQueryElement .on('beforeactivate', (_e: JQuery.TriggeredEvent, tick: SohoWizardTick) => this.onBeforeActivate(tick)) .on('activated', (_e: JQuery.TriggeredEvent, tick: JQuery) => this.onActivated(tick)) .on('afteractivated', (_e: JQuery.TriggeredEvent, tick: JQuery) => this.afteractivated.next({ tick })); // Reset the cached steps if the list of steps changes. if (this.header) { this.header.steps?.changes.subscribe(() => { this._steps = []; }); } } ngAfterContentInit() { // Added delay otherwise the component is not complete // causing the active page to not be displayed. setTimeout(() => { if (this.header) { const step = this.header.steps?.find(s => s.isCurrentTick()); this.pagesContainer?.pages.forEach(p => p.hidden = (!step || step.tickId !== p.tickId)); } }); } /** * Handle component destruction by clearing down the SoHo * wizard component. * * */ ngOnDestroy() { if (this.wizard) { this.wizard.destroy(); this.wizard = undefined; } } private onActivated(tick: JQuery): void { // When activated - make sure the rest of the component is // updated ... if (tick) { // ... find the id of the tick activated ... const tickId = tick.attr('tickId'); // ... if we have one (to avoid errors) ... if (tickId) { // hide all the inactive pages and show the active page. this.pagesContainer?.pages.forEach( (p) => { if (tickId === p.tickId) { // fire an event on the page. p.fireActivated({ tick }); // ... show it. p.hidden = false; } else { // hide it. p.hidden = true; } }); // ... publish. this.activated.next({ tick }); } } } private onBeforeActivate(tick: SohoWizardTick): boolean { // Check for vetoing. return this.beforeActivate != null ? this.beforeActivate.call(tick) : true; } private stepCount(): number { return this.header?.steps?.length || 0; } private steps(): SohoWizardTickComponent[] | undefined { if (!this._steps && this.header) { this._steps = this.header?.steps?.toArray(); } return this._steps; } private stepAt(index: number): SohoWizardTickComponent | undefined { const steps = this.steps(); return steps ? steps[index] : undefined; } private currentIndex(): number { const steps = this.steps(); const currentStep = this.currentStep(); return steps && currentStep ? steps.indexOf(currentStep) : -1; } private currentStep(): SohoWizardTickComponent | undefined { const steps = this.steps(); return steps ? steps.find(s => s.isCurrentTick()) : undefined; } }
the_stack
import { SoftmaxRegressionSparse } from "../../supervised/classifier/neural_network/learner/SoftmaxRegressionSparse"; import { NgramSubwordFeaturizer } from "../../language_understanding/featurizer/NgramSubwordFeaturizer"; import { AbstractBaseModelFeaturizerEvaluator } from "../abstract_base_evaluator/AbstractBaseModelFeaturizerEvaluator"; import { BinaryConfusionMatrix } from "../../../mathematics/confusion_matrix/BinaryConfusionMatrix"; import { ListArrayUtility } from "../../../utility/ListArrayUtility"; import { IDictionaryStringIdGenericArrays } from "../../../data_structure/IDictionaryStringIdGenericArrays"; import { IDictionaryStringIdGenericValue } from "../../../data_structure/IDictionaryStringIdGenericValue"; import { DictionaryMapUtility } from "../../../data_structure/DictionaryMapUtility"; import { Utility } from "../../../utility/Utility"; const NumberOfLabelsPerBatchToReport: number = 8; const EnableDebuggingInstrumentation: boolean = false; export class ThresholdReporter extends AbstractBaseModelFeaturizerEvaluator { protected instancePredictedScoreArrays: number[][] = []; protected instanceGroudTruthLabelIds: number[] = []; protected instanceFeatureTexts: string[] = []; protected instanceIdentifiers: string[] = []; protected instanceWeights: number[] = []; protected targetLabelBatchesToReport: string[][] = []; protected numberOfLabelsPerBatch: number = NumberOfLabelsPerBatchToReport; protected explicitTotal: number = -1; protected explicitTotalPositives: number = -1; protected explicitTotalNegatives: number = -1; protected fMeasureBeta: number = 1; protected effectivenessMeasureAlpha: number = 0.5; protected rejectRate: number = -1; protected alpha: number = 1; protected beta: number = 1; protected A: number = 1; protected B: number = 1; protected explicitMaxPositives: number = -1; constructor( modelFilename: string, featurizerFilename: string, modelNullable: SoftmaxRegressionSparse|null, featurizerNullable: NgramSubwordFeaturizer|null, labels: string[], labelMap: Map<string, number>, targetLabelBatchesToReport: string[][] = [], numberOfLabelsPerBatch: number = NumberOfLabelsPerBatchToReport, explicitTotal: number = -1, explicitTotalPositives: number = -1, explicitTotalNegatives: number = -1, fMeasureBeta: number = 1, effectivenessMeasureAlpha: number = 0.5, rejectRate: number = -1, alpha: number = 1, beta: number = 1, A: number = 1, B: number = 1, explicitMaxPositives: number = -1) { super(modelFilename, featurizerFilename, modelNullable, featurizerNullable, labels, labelMap); this.targetLabelBatchesToReport = targetLabelBatchesToReport; this.numberOfLabelsPerBatch = numberOfLabelsPerBatch; this.explicitTotal = explicitTotal; this.explicitTotalPositives = explicitTotalPositives; this.explicitTotalNegatives = explicitTotalNegatives; this.fMeasureBeta = fMeasureBeta; this.effectivenessMeasureAlpha = effectivenessMeasureAlpha; this.rejectRate = rejectRate; this.alpha = alpha; this.beta = beta; this.A = A; this.B = B; this.explicitMaxPositives = explicitMaxPositives; } public generateEvaluationDataArraysReport(): IDictionaryStringIdGenericArrays<string> { const outputEvaluationReportDataArrays: IDictionaryStringIdGenericArrays<string> = {}; { const outputEvaluationReportDataArrayConfusionMatrixThresholdMetrics: string[][] = this.reportToDataArrays(); outputEvaluationReportDataArrays.ConfusionMatrixThresholdMetrics = outputEvaluationReportDataArrayConfusionMatrixThresholdMetrics; } return outputEvaluationReportDataArrays; } public generateEvaluationDataArraysReportToFiles( outputReportFilenamePrefix: string, outputDataArraryHeaders: string[] = [], columnDelimiter: string = "\t", recordDelimiter: string = "\n", encoding: string = "utf8", outputEvaluationReportDataArrays: IDictionaryStringIdGenericArrays<string> = {}): { "outputEvaluationReportDataArrays": IDictionaryStringIdGenericArrays<string>, "outputFilenames": string[], } { if (DictionaryMapUtility.isEmptyStringIdGenericArraysDictionary(outputEvaluationReportDataArrays)) { outputEvaluationReportDataArrays = this.generateEvaluationDataArraysReport(); } { let outputFilename: string = `${outputReportFilenamePrefix}_ConfusionMatrixThresholdMetrics.txt`; outputFilename = Utility.storeDataArraysToTsvFile( outputFilename, outputEvaluationReportDataArrays.ConfusionMatrixThresholdMetrics, outputDataArraryHeaders, columnDelimiter, recordDelimiter, encoding); const outputFilenames: string[] = [outputFilename]; return { outputEvaluationReportDataArrays, outputFilenames }; } } public generateEvaluationJsonReport(): IDictionaryStringIdGenericValue<any> { return {}; // ---- NOTE: nothing to report here. } public generateEvaluationJsonReportToFiles( outputReportFilenamePrefix: string, encoding: string = "utf8", outputEvaluationReportJson: IDictionaryStringIdGenericValue<any> = {}): { "outputEvaluationReportJson": IDictionaryStringIdGenericValue<any>, "outputFilenames": string[], } { const outputFilenames: string[] = []; // ---- NOTE: nothing to report here. return { outputEvaluationReportJson, outputFilenames, }; } public generateEvaluationDirectReport(): IDictionaryStringIdGenericValue<string> { return {}; // ---- NOTE: nothing to report here. } public generateEvaluationDirectReportToFiles( outputReportFilenamePrefix: string, encoding: string, outputEvaluationReportDirect: IDictionaryStringIdGenericValue<string> = {}): IDictionaryStringIdGenericValue<string> { // ---- NOTE: nothing to report here. return outputEvaluationReportDirect; } public getNumberInstances(): number { return this.instancePredictedScoreArrays.length; } public addInstance( instancePredictedScoreArray: number[], instanceGroudTruthLabelId: number, instanceFeatureText: string, instanceIdentifier: string, instanceWeight: number): void { this.instancePredictedScoreArrays.push(instancePredictedScoreArray); this.instanceGroudTruthLabelIds.push(instanceGroudTruthLabelId); this.instanceFeatureTexts.push(instanceFeatureText); this.instanceIdentifiers.push(instanceIdentifier); this.instanceWeights.push(instanceWeight); } public reportToDataArrays(): string[][] { const reportResults: Array<Array<{ "targetLabel": string, "scoreThresholds": number[], "binaryConfusionMatrices": BinaryConfusionMatrix[], "metricNames": string[], "metricNameMap": IDictionaryStringIdGenericValue<number>, "metricValues": number[][], }>> = this.report( this.targetLabelBatchesToReport, this.numberOfLabelsPerBatch, this.explicitTotal, this.explicitTotalPositives, this.explicitTotalNegatives, this.fMeasureBeta, this.effectivenessMeasureAlpha, this.rejectRate, this.alpha, this.beta, this.A, this.B, this.explicitMaxPositives); let cell11MetricIndexForDebugInstrumentation: number = -1; let ratioCell11MetricIndexForDebugInstrumentation: number = -1; let cell11MetricIndexInOutputArrayForDebugInstrumentation: number = -1; let ratioCell11MetricIndexInOutputArrayForDebugInstrumentation: number = -1; const outputEvaluationReportDataArrayHeader: string[] = []; const outputEvaluationReportDataArrays: string[][] = []; for (const reportResultsPerBatch of reportResults) { for (const reportResultPerLabel of reportResultsPerBatch) { const tarrgetLabel: string = reportResultPerLabel.targetLabel; const scoreThresholds: number[] = reportResultPerLabel.scoreThresholds; const metricNames: string[] = reportResultPerLabel.metricNames; const metricNameMap: IDictionaryStringIdGenericValue<number> = reportResultPerLabel.metricNameMap; const metricValues: number[][] = reportResultPerLabel.metricValues; if (EnableDebuggingInstrumentation) { // ---- NOTE-DEBUG-INSTRUMENTATION ---- // const binaryConfusionMatrices: BinaryConfusionMatrix[] = // reportResultPerLabel.binaryConfusionMatrices; cell11MetricIndexForDebugInstrumentation = metricNameMap.Cell11; ratioCell11MetricIndexForDebugInstrumentation = metricNameMap.RatioCell11; cell11MetricIndexInOutputArrayForDebugInstrumentation = cell11MetricIndexForDebugInstrumentation + 2; ratioCell11MetricIndexInOutputArrayForDebugInstrumentation = ratioCell11MetricIndexForDebugInstrumentation + 2; } if (Utility.isEmptyStringArray(outputEvaluationReportDataArrayHeader)) { outputEvaluationReportDataArrayHeader.push("TargetLabel"); outputEvaluationReportDataArrayHeader.push("ScoreThreshold"); for (const metricName of metricNames) { outputEvaluationReportDataArrayHeader.push(metricName); } outputEvaluationReportDataArrays.push(outputEvaluationReportDataArrayHeader); } const numberInstances: number = scoreThresholds.length; for (let indexInstance: number = 0; indexInstance < numberInstances; indexInstance++) { const outputEvaluationReportDataArray: string[] = []; const scoreThreshold: number = scoreThresholds[indexInstance]; const metricValueArray: number[] = metricValues[indexInstance]; outputEvaluationReportDataArray.push(tarrgetLabel); outputEvaluationReportDataArray.push(scoreThreshold.toString()); for (const metricValue of metricValueArray) { outputEvaluationReportDataArray.push(metricValue.toString()); } outputEvaluationReportDataArrays.push(outputEvaluationReportDataArray); if (EnableDebuggingInstrumentation) { // ---- NOTE-DEBUG-INSTRUMENTATION ---- const cell1MetricValue: number = metricValueArray[cell11MetricIndexForDebugInstrumentation]; const ratioCell1MetricValue: number = metricValueArray[ratioCell11MetricIndexForDebugInstrumentation]; const cell1MetricValueInString: string = outputEvaluationReportDataArray[cell11MetricIndexInOutputArrayForDebugInstrumentation]; const ratioCell1MetricValueInString: string = outputEvaluationReportDataArray[ratioCell11MetricIndexInOutputArrayForDebugInstrumentation]; if (cell1MetricValue > 0) { Utility.debuggingLog( `cell1MetricValue=${cell1MetricValue}`); Utility.debuggingLog( `cell1MetricValueInString=${cell1MetricValueInString}`); Utility.debuggingLog( `ratioCell1MetricValue=${ratioCell1MetricValue}`); Utility.debuggingLog( `ratioCell1MetricValueInString=${ratioCell1MetricValueInString}`); } } } } } return outputEvaluationReportDataArrays; } public report( targetLabelBatchesToReport: string[][] = [], numberOfLabelsPerBatch: number = NumberOfLabelsPerBatchToReport, explicitTotal: number = -1, explicitTotalPositives: number = -1, explicitTotalNegatives: number = -1, fMeasureBeta: number = 1, effectivenessMeasureAlpha: number = 0.5, rejectRate: number = -1, alpha: number = 1, beta: number = 1, A: number = 1, B: number = 1, explicitMaxPositives: number = -1): Array<Array<{ "targetLabel": string, "scoreThresholds": number[], "binaryConfusionMatrices": BinaryConfusionMatrix[], "metricNames": string[], "metricNameMap": IDictionaryStringIdGenericValue<number>, "metricValues": number[][], }>> { this.validate(); const labels: string[] = this.getLabels(); const numberLabels: number = labels.length; if (Utility.isEmptyStringArrays(targetLabelBatchesToReport)) { targetLabelBatchesToReport = []; if (numberOfLabelsPerBatch <= 0) { numberOfLabelsPerBatch = NumberOfLabelsPerBatchToReport; } let numberLabelBatches: number = Math.floor(numberLabels / numberOfLabelsPerBatch); if ((numberLabelBatches * numberOfLabelsPerBatch) < numberLabels) { numberLabelBatches++; } for (let batch = 0; batch < numberLabelBatches; batch++) { const labelIndexBegin = batch * numberOfLabelsPerBatch; let labelIndexEnd = labelIndexBegin + numberOfLabelsPerBatch; if (labelIndexEnd > numberLabels) { labelIndexEnd = numberLabels; } if (labelIndexEnd > labelIndexBegin) { const targetLabelsPerBatch: string[] = []; for (let labelIndex = labelIndexBegin; labelIndex < labelIndexEnd; labelIndex++) { targetLabelsPerBatch.push(labels[labelIndex]); } targetLabelBatchesToReport.push(targetLabelsPerBatch); } } } const labelMap: Map<string, number> = this.getLabelMap(); let metricNames: string[] = []; let metricNameMap: IDictionaryStringIdGenericValue<number> = {}; const numberInstances: number = this.instanceGroudTruthLabelIds.length; const reportResults: Array<Array<{ "targetLabel": string, "scoreThresholds": number[], "binaryConfusionMatrices": BinaryConfusionMatrix[], "metricNames": string[], "metricNameMap": IDictionaryStringIdGenericValue<number>, "metricValues": number[][], }>> = []; for (const targetLabelsPerBatchToReport of targetLabelBatchesToReport) { const reportResultsPerBatch: Array<{ "targetLabel": string, "scoreThresholds": number[], "binaryConfusionMatrices": BinaryConfusionMatrix[], "metricNames": string[], "metricNameMap": IDictionaryStringIdGenericValue<number>, "metricValues": number[][], }> = []; for (const targetLabel of targetLabelsPerBatchToReport) { const targetLabelIndex: number = labelMap.get(targetLabel) as number; if (targetLabelIndex === undefined) { Utility.debuggingThrow( `targetLabel|${targetLabel}| is not defined.`); } let targetLabelIndexScores: number[] = this.instancePredictedScoreArrays.map( (scoreArray) => scoreArray[targetLabelIndex]); const targetLabelPositives: number = this.instanceGroudTruthLabelIds.reduce( (total, instanceGroudTruthLabelId) => (instanceGroudTruthLabelId === targetLabelIndex ? total + 1 : total), 0); let orderSequence: number[] = ListArrayUtility.sortGenerateOrderSequence( targetLabelIndexScores); { orderSequence = orderSequence.reverse(); targetLabelIndexScores = targetLabelIndexScores.reverse(); } const binaryConfusionMatrixBase: BinaryConfusionMatrix = new BinaryConfusionMatrix( numberInstances, 0, targetLabelPositives, 0); if (Utility.isEmptyStringArray(metricNames)) { metricNames = binaryConfusionMatrixBase.getMetricNames(); } if (DictionaryMapUtility.isEmptyStringIdGenericValueDictionary(metricNameMap)) { metricNameMap = binaryConfusionMatrixBase.getMetricNameMap(); } const binaryConfusionMatrices: BinaryConfusionMatrix[] = orderSequence.map( (instanceIndex) => binaryConfusionMatrixBase.moveFromPredictedNegativeToPositive( this.instanceGroudTruthLabelIds[instanceIndex] === targetLabelIndex)); const metricValues: number[][] = binaryConfusionMatrices.map((binaryConfusionMatrix) => binaryConfusionMatrix.getMetricValues( explicitTotal, explicitTotalPositives, explicitTotalNegatives, fMeasureBeta, effectivenessMeasureAlpha, rejectRate, alpha, beta, A, B, explicitMaxPositives)); if (EnableDebuggingInstrumentation) { // ---- NOTE-DEBUG-INSTRUMENTATION ---- const totalMetricIndex: number = metricNameMap.Total; const cell11MetricIndex: number = metricNameMap.Cell11; const ratioCell11MetricIndex: number = metricNameMap.RatioCell11; const totalMatricValues: number[] = metricValues.map((x: number[]) => x[totalMetricIndex]); const cell11MatricValues: number[] = metricValues.map((x: number[]) => x[cell11MetricIndex]); const ratioCell11MatricValues: number[] = metricValues.map((x: number[]) => x[ratioCell11MetricIndex]); Utility.debuggingLog( `cell11MatricValues=${cell11MatricValues}`); Utility.debuggingLog( `ratioCell11MatricValues=${ratioCell11MatricValues}`); Utility.debuggingLog( `totalMatricValues=${totalMatricValues}`); } const reportResultPerLabel: { "targetLabel": string, "scoreThresholds": number[], "binaryConfusionMatrices": BinaryConfusionMatrix[], "metricNames": string[], "metricNameMap": IDictionaryStringIdGenericValue<number>, "metricValues": number[][], } = { targetLabel, scoreThresholds: targetLabelIndexScores, binaryConfusionMatrices, metricNames, metricNameMap, metricValues, }; reportResultsPerBatch.push(reportResultPerLabel); } reportResults.push(reportResultsPerBatch); } return reportResults; } public validate(): void { if (Utility.isEmptyArray(this.instancePredictedScoreArrays)) { Utility.debuggingThrow("'this.instancePredictedScoreArrays' array is empty"); } if (Utility.isEmptyNumberArray(this.instanceGroudTruthLabelIds)) { Utility.debuggingThrow("'this.instanceGroudTruthLabelIds' array is empty"); } if (Utility.isEmptyStringArray(this.instanceFeatureTexts)) { Utility.debuggingThrow("'this.instanceFeatureTexts' array is empty"); } if (Utility.isEmptyStringArray(this.instanceIdentifiers)) { Utility.debuggingThrow("'this.instanceIdentifiers' array is empty"); } if (Utility.isEmptyNumberArray(this.instanceWeights)) { Utility.debuggingThrow("'this.instanceWeights' array is empty"); } const numberInstances: number = this.getNumberInstances(); if (this.instanceGroudTruthLabelIds.length !== numberInstances) { Utility.debuggingThrow( `this.instanceGroudTruthLabelIds.length|${this.instanceGroudTruthLabelIds.length}|!==numberInstances|${numberInstances}|`); } if (this.instanceFeatureTexts.length !== numberInstances) { Utility.debuggingThrow( `this.instanceFeatureTexts.length|${this.instanceFeatureTexts.length}|!==numberInstances|${numberInstances}|`); } if (this.instanceIdentifiers.length !== numberInstances) { Utility.debuggingThrow( `this.instanceIdentifiers.length|${this.instanceIdentifiers.length}|!==numberInstances|${numberInstances}|`); } if (this.instanceWeights.length !== numberInstances) { Utility.debuggingThrow( `this.instanceWeights.length|${this.instanceWeights.length}|!==numberInstances|${numberInstances}|`); } } public loadScoreFileAndPopulate( scoreFilename: string, labelColumnIndex: number = 0, textColumnIndex: number = 1, weightColumnIndex: number = -1, scoreColumnBeginIndex: number = 2, identifierColumnIndex: number = -1, predictedLabelColumnIndex: number = -1, revisedTextColumnIndex: number = -1, lineIndexToStart: number = 0): void { const scoreDataStructure: { "labels": string[], "texts": string[], "weights": number[], "identifiers": string[], "scoreArrays": number[][], "predictedLabels": string[], "revisedTexts": string[] } = Utility.loadLabelTextScoreFile( scoreFilename, labelColumnIndex, textColumnIndex, weightColumnIndex, scoreColumnBeginIndex, this.getNumberLabels(), identifierColumnIndex, predictedLabelColumnIndex, revisedTextColumnIndex, lineIndexToStart); const labelMap: Map<string, number> = this.getLabelMap(); const numberInstances: number = scoreDataStructure.labels.length; for (let i = 0; i < numberInstances; i++) { const label: string = scoreDataStructure.labels[i]; const text: string = scoreDataStructure.texts[i]; const identifier: string = scoreDataStructure.identifiers[i]; const scoreArray: number[] = scoreDataStructure.scoreArrays[i]; const labelId: number = labelMap.get(label) as number; const weight: number = scoreDataStructure.weights[i]; this.addInstance(scoreArray, labelId, text, identifier, weight); } } }
the_stack
import fse from 'fs-extra' import electron from 'electron' import * as Cfg from '../../config' import * as Dialogs from '../../dialogs' import * as Defs from '../definitions' import * as Val from '../validation' import { registerLabware } from '..' import { uiInitialized } from '@opentrons/app/src/redux/shell/actions' import * as CustomLabware from '@opentrons/app/src/redux/custom-labware' import * as CustomLabwareFixtures from '@opentrons/app/src/redux/custom-labware/__fixtures__' import type { Config } from '@opentrons/app/src/redux/config/types' import type { Dispatch } from '../../types' jest.mock('fs-extra') jest.mock('electron') jest.mock('../../config') jest.mock('../../dialogs') jest.mock('../definitions') jest.mock('../validation') const ensureDir = fse.ensureDir as jest.MockedFunction<typeof fse.ensureDir> const getFullConfig = Cfg.getFullConfig as jest.MockedFunction< typeof Cfg.getFullConfig > const handleConfigChange = Cfg.handleConfigChange as jest.MockedFunction< typeof Cfg.handleConfigChange > const showOpenDirectoryDialog = Dialogs.showOpenDirectoryDialog as jest.MockedFunction< typeof Dialogs.showOpenDirectoryDialog > const showOpenFileDialog = Dialogs.showOpenFileDialog as jest.MockedFunction< typeof Dialogs.showOpenFileDialog > const readLabwareDirectory = Defs.readLabwareDirectory as jest.MockedFunction< typeof Defs.readLabwareDirectory > const parseLabwareFiles = Defs.parseLabwareFiles as jest.MockedFunction< typeof Defs.parseLabwareFiles > const addLabwareFile = Defs.addLabwareFile as jest.MockedFunction< typeof Defs.addLabwareFile > const removeLabwareFile = Defs.removeLabwareFile as jest.MockedFunction< typeof Defs.removeLabwareFile > const validateLabwareFiles = Val.validateLabwareFiles as jest.MockedFunction< typeof Val.validateLabwareFiles > const validateNewLabwareFile = Val.validateNewLabwareFile as jest.MockedFunction< typeof Val.validateNewLabwareFile > // wait a few ticks to let the mock Promises clear const flush = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 0)) describe('labware module dispatches', () => { const labwareDir = '/path/to/somewhere' const mockMainWindow = ({ browserWindow: true, } as unknown) as electron.BrowserWindow let dispatch: jest.MockedFunction<Dispatch> let handleAction: Dispatch beforeEach(() => { getFullConfig.mockReturnValue({ labware: { directory: labwareDir }, } as Config) ensureDir.mockResolvedValue(undefined as never) addLabwareFile.mockResolvedValue() removeLabwareFile.mockResolvedValue() readLabwareDirectory.mockResolvedValue([]) parseLabwareFiles.mockResolvedValue([]) validateLabwareFiles.mockReturnValue([]) showOpenDirectoryDialog.mockResolvedValue([]) showOpenFileDialog.mockResolvedValue([]) dispatch = jest.fn() handleAction = registerLabware(dispatch, mockMainWindow) }) afterEach(() => { jest.resetAllMocks() }) it('ensures labware directory exists on FETCH_CUSTOM_LABWARE', () => { handleAction(CustomLabware.fetchCustomLabware()) expect(ensureDir).toHaveBeenCalledWith(labwareDir) }) it('reads labware directory on FETCH_CUSTOM_LABWARE', () => { handleAction(CustomLabware.fetchCustomLabware()) return flush().then(() => expect(readLabwareDirectory).toHaveBeenCalledWith(labwareDir) ) }) it('reads labware directory on shell:UI_INITIALIZED', () => { handleAction(uiInitialized()) return flush().then(() => expect(readLabwareDirectory).toHaveBeenCalledWith(labwareDir) ) }) it('reads and parses definition files', () => { const mockDirectoryListing = ['a.json', 'b.json', 'c.json', 'd.json'] const mockParsedFiles = [ { filename: 'a.json', modified: 0, data: {} }, { filename: 'b.json', modified: 1, data: {} }, { filename: 'c.json', modified: 2, data: {} }, { filename: 'd.json', modified: 3, data: {} }, ] readLabwareDirectory.mockResolvedValueOnce(mockDirectoryListing) parseLabwareFiles.mockResolvedValueOnce(mockParsedFiles) handleAction(CustomLabware.fetchCustomLabware()) return flush().then(() => { expect(parseLabwareFiles).toHaveBeenCalledWith(mockDirectoryListing) expect(validateLabwareFiles).toHaveBeenCalledWith(mockParsedFiles) }) }) it('dispatches CUSTOM_LABWARE_LIST with labware files', () => { const mockValidatedFiles = [ CustomLabwareFixtures.mockInvalidLabware, CustomLabwareFixtures.mockDuplicateLabware, CustomLabwareFixtures.mockValidLabware, ] validateLabwareFiles.mockReturnValueOnce(mockValidatedFiles) handleAction(CustomLabware.fetchCustomLabware()) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith( CustomLabware.customLabwareList(mockValidatedFiles) ) }) }) it('dispatches CUSTOM_LABWARE_LIST_FAILURE if read fails', () => { readLabwareDirectory.mockRejectedValue(new Error('AH')) handleAction(CustomLabware.fetchCustomLabware()) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith( CustomLabware.customLabwareListFailure('AH') ) }) }) it('opens file picker on CHANGE_CUSTOM_LABWARE_DIRECTORY', () => { handleAction(CustomLabware.changeCustomLabwareDirectory()) return flush().then(() => { expect(showOpenDirectoryDialog).toHaveBeenCalledWith(mockMainWindow, { defaultPath: labwareDir, }) expect(dispatch).not.toHaveBeenCalled() }) }) it('dispatches config:UPDATE on labware dir selection', () => { showOpenDirectoryDialog.mockResolvedValue(['/path/to/labware']) handleAction(CustomLabware.changeCustomLabwareDirectory()) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith({ type: 'config:UPDATE_VALUE', payload: { path: 'labware.directory', value: '/path/to/labware' }, meta: { shell: true }, }) }) }) it('reads labware directory on config change', () => { expect(handleConfigChange).toHaveBeenCalledWith( 'labware.directory', expect.any(Function) ) const changeHandler = handleConfigChange.mock.calls[0][1] changeHandler('old', 'new') return flush().then(() => { expect(readLabwareDirectory).toHaveBeenCalledWith(labwareDir) expect(dispatch).toHaveBeenCalledWith( CustomLabware.customLabwareList([], 'changeDirectory') ) }) }) it('dispatches labware directory list error on config change', () => { const changeHandler = handleConfigChange.mock.calls[0][1] readLabwareDirectory.mockRejectedValue(new Error('AH')) changeHandler('old', 'new') return flush().then(() => { expect(readLabwareDirectory).toHaveBeenCalledWith(labwareDir) expect(dispatch).toHaveBeenCalledWith( CustomLabware.customLabwareListFailure('AH', 'changeDirectory') ) }) }) it('opens file picker on ADD_CUSTOM_LABWARE', () => { handleAction(CustomLabware.addCustomLabware()) return flush().then(() => { expect(showOpenFileDialog).toHaveBeenCalledWith(mockMainWindow, { defaultPath: '__mock-app-path__', filters: [{ name: 'JSON Labware Definitions', extensions: ['json'] }], }) expect(dispatch).not.toHaveBeenCalled() }) }) it('reads labware directory and new file and compares', () => { const mockValidatedFiles = [CustomLabwareFixtures.mockInvalidLabware] const mockNewUncheckedFile = { filename: '/path/to/labware.json', modified: 0, data: {}, } showOpenFileDialog.mockResolvedValue(['/path/to/labware.json']) // validation of existing definitions validateLabwareFiles.mockReturnValueOnce(mockValidatedFiles) // existing files mock return parseLabwareFiles.mockResolvedValue([]) // new file mock return parseLabwareFiles.mockResolvedValue([mockNewUncheckedFile]) // new file (not needed for this test except to prevent a type error) validateNewLabwareFile.mockReturnValueOnce(mockValidatedFiles[0]) handleAction(CustomLabware.addCustomLabware()) return flush().then(() => { expect(validateNewLabwareFile).toHaveBeenCalledWith( mockValidatedFiles, mockNewUncheckedFile ) }) }) it('dispatches ADD_CUSTOM_LABWARE_FAILURE if checked file is invalid', () => { const mockInvalidFile = CustomLabwareFixtures.mockInvalidLabware const expectedAction = CustomLabware.addCustomLabwareFailure( mockInvalidFile ) showOpenFileDialog.mockResolvedValue(['c.json']) validateNewLabwareFile.mockReturnValueOnce(mockInvalidFile) handleAction(CustomLabware.addCustomLabware()) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith(expectedAction) }) }) it('adds file and triggers a re-scan if valid', () => { const mockValidFile = CustomLabwareFixtures.mockValidLabware const expectedAction = CustomLabware.customLabwareList( [mockValidFile], 'addLabware' ) showOpenFileDialog.mockResolvedValue([mockValidFile.filename]) validateNewLabwareFile.mockReturnValueOnce(mockValidFile) // initial read validateLabwareFiles.mockReturnValueOnce([]) // read after add validateLabwareFiles.mockReturnValueOnce([mockValidFile]) handleAction(CustomLabware.addCustomLabware()) return flush().then(() => { expect(addLabwareFile).toHaveBeenCalledWith( mockValidFile.filename, labwareDir ) expect(dispatch).toHaveBeenCalledWith(expectedAction) }) }) it('dispatches ADD_CUSTOM_LABWARE_FAILURE if something rejects', () => { const mockValidFile = CustomLabwareFixtures.mockValidLabware const expectedAction = CustomLabware.addCustomLabwareFailure(null, 'AH') showOpenFileDialog.mockResolvedValue(['a.json']) validateNewLabwareFile.mockReturnValueOnce(mockValidFile) validateLabwareFiles.mockReturnValueOnce([]) addLabwareFile.mockRejectedValue(new Error('AH')) handleAction(CustomLabware.addCustomLabware()) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith(expectedAction) }) }) it('skips file picker on ADD_CUSTOM_LABWARE with overwrite', () => { const duplicate = CustomLabwareFixtures.mockDuplicateLabware const mockExisting = [ { ...duplicate, filename: '/duplicate1.json' }, { ...duplicate, filename: '/duplicate2.json' }, ] const mockAfterDeletes = [CustomLabwareFixtures.mockValidLabware] const expectedAction = CustomLabware.customLabwareList( mockAfterDeletes, 'overwriteLabware' ) // validation of existing definitions validateLabwareFiles.mockReturnValueOnce(mockExisting) // validation after deletes validateLabwareFiles.mockReturnValueOnce(mockAfterDeletes) handleAction(CustomLabware.addCustomLabware(duplicate)) return flush().then(() => { expect(removeLabwareFile).toHaveBeenCalledWith('/duplicate1.json') expect(removeLabwareFile).toHaveBeenCalledWith('/duplicate2.json') expect(addLabwareFile).toHaveBeenCalledWith( duplicate.filename, labwareDir ) expect(dispatch).toHaveBeenCalledWith(expectedAction) }) }) it('sends ADD_CUSTOM_LABWARE_FAILURE if a something rejects', () => { const duplicate = CustomLabwareFixtures.mockDuplicateLabware const mockExisting = [ { ...duplicate, filename: '/duplicate1.json' }, { ...duplicate, filename: '/duplicate2.json' }, ] const expectedAction = CustomLabware.addCustomLabwareFailure(null, 'AH') validateLabwareFiles.mockReturnValueOnce(mockExisting) removeLabwareFile.mockRejectedValue(new Error('AH')) handleAction(CustomLabware.addCustomLabware(duplicate)) return flush().then(() => { expect(dispatch).toHaveBeenCalledWith(expectedAction) }) }) it('opens custom labware directory on OPEN_CUSTOM_LABWARE_DIRECTORY', () => { handleAction(CustomLabware.openCustomLabwareDirectory()) return flush().then(() => { expect(electron.shell.openPath).toHaveBeenCalledWith(labwareDir) }) }) })
the_stack
import { expect } from "chai"; import CodePushDeploymentListListCommand from "../../../../src/commands/codepush/deployment/list"; import { models } from "../../../../src/util/apis"; import { CommandArgs, CommandFailedResult } from "../../../../src/util/commandline"; import * as Sinon from "sinon"; import * as Nock from "nock"; import { formatDate } from "../../../../src/commands/codepush/deployment/lib/date-helper"; import { getFakeParamsForRequest, FakeParamsForRequests } from "../utils"; import { out } from "../../../../src/util/interaction/index"; import * as chalk from "chalk"; // Have to use `require` because of this: https://github.com/chalk/strip-ansi/issues/11 const stripAnsi = require("strip-ansi"); describe("codepush deployment list tests", () => { const fakeBlobUrl = "fakeURL"; const fakeIsDisabled = false; const fakeIsMandatory = false; const fakeLabel = "fakeLabel"; const fakePackageHash = "fakeHash"; const fakeReleasedBy = "fakeAuthor"; const fakeReleaseMethod = "Upload"; const fakeRollout = 100; const fakeSize = 100; const fakeTargetBinaryRange = "fakeTarget"; const fakeUploadTime = 1538747519563; const fakeDescription = "fakeDescription"; const fakeReleasesTotalActive = 3; const successfulStatus = 200; const unsuccessfulStatus = 404; const fakeHost = "http://localhost:1700"; const fakeParamsForRequest: FakeParamsForRequests = getFakeParamsForRequest(); const defaultCommandArgsForListCommand: CommandArgs = getCommandArgsForListCommand(fakeParamsForRequest); const fakeMetadataRelease: models.CodePushRelease = { blobUrl: fakeBlobUrl, isDisabled: fakeIsDisabled, isMandatory: fakeIsMandatory, label: fakeLabel, packageHash: fakePackageHash, releasedBy: fakeReleasedBy, releaseMethod: fakeReleaseMethod, rollout: fakeRollout, size: fakeSize, targetBinaryRange: fakeTargetBinaryRange, uploadTime: fakeUploadTime, }; const fakeReleaseForRequest = { target_binary_range: fakeTargetBinaryRange, blob_url: fakeBlobUrl, description: fakeDescription, is_disabled: fakeIsDisabled, is_mandatory: fakeIsMandatory, label: fakeLabel, package_hash: fakePackageHash, released_by: fakeReleasedBy, release_method: fakeReleaseMethod, rollout: fakeRollout, size: fakeSize, upload_time: fakeUploadTime, diff_package_map: {}, }; const noUpdatesString = "No updates released"; const noMetricsString = "No installs recorded"; const fakeDeployment: models.Deployment = { name: "fakeDeploymentName", key: "fakeDeploymentKey", }; const fakeDeploymentWithRelease: models.Deployment = Object.assign({ latest_release: fakeReleaseForRequest }, fakeDeployment); const expectedGeneratedMetadataString = "Label: " + fakeLabel + "\nApp Version: " + fakeTargetBinaryRange + "\nMandatory: No" + "\nRelease Time: " + formatDate(fakeUploadTime) + "\nReleased By: " + fakeReleasedBy; const expectedOutputHelperText = "Note: To display deployment keys add -k|--displayKeys option"; const expectedErrorMessage = `The app ${fakeParamsForRequest.userName}/${fakeParamsForRequest.appName} does not exist.`; describe("deployment list unit tests", () => { it("generateMetadataString", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetadataString: (release: models.CodePushRelease) => string = command["generateMetadataString"]; // Act const result = generateMetadataString(fakeMetadataRelease); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedGeneratedMetadataString); }); it("generateColoredTableTitles", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateColoredTableTitles: (tableTitles: string[]) => string[] = command["generateColoredTableTitles"]; const fakeDeploymentsName = ["fakeDeployment", "fakeDeployment2"]; const expected = [chalk.cyan("fakeDeployment"), chalk.cyan("fakeDeployment2")]; // Act const result = generateColoredTableTitles(fakeDeploymentsName); // Assert expect(result).to.be.an("array"); expect(result).to.be.eql(expected); }); describe("generateMetricsString", () => { it("should return correct metrics for any% active releases", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetricsString: (releaseMetrics: models.CodePushReleaseMetric, releasesTotalActive: number) => string = command["generateMetricsString"]; const fakeReleaseMetrics = { active: 1, downloaded: 1, failed: 0, installed: 1, label: fakeLabel, }; const fakeActiveString: string = "33% (1 of 3)"; const fakeInstalled: string = "1"; const expectedMetrics = getExpectedMetricsString(fakeActiveString, fakeInstalled); // Act const result = generateMetricsString(fakeReleaseMetrics, fakeReleasesTotalActive); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedMetrics); }); it("should return correct metrics for 0% active releases", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetricsString: (releaseMetrics: models.CodePushReleaseMetric, releasesTotalActive: number) => string = command["generateMetricsString"]; const fakeReleaseMetrics = { active: 0, downloaded: 1, failed: 0, installed: 1, label: fakeLabel, }; const fakeActiveString: string = "0% (0 of 3)"; const fakeInstalled: string = "1"; const expectedMetrics = getExpectedMetricsString(fakeActiveString, fakeInstalled); // Act const result = generateMetricsString(fakeReleaseMetrics, fakeReleasesTotalActive); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedMetrics); }); it("should return correct metrics for 100% active releases", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetricsString: (releaseMetrics: models.CodePushReleaseMetric, releasesTotalActive: number) => string = command["generateMetricsString"]; const fakeReleaseMetrics = { active: 3, downloaded: 3, failed: 0, installed: 3, label: fakeLabel, }; const fakeActiveString: string = "100% (3 of 3)"; const fakeInstalled: string = "3"; const expectedMetrics = getExpectedMetricsString(fakeActiveString, fakeInstalled); // Act const result = generateMetricsString(fakeReleaseMetrics, fakeReleasesTotalActive); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedMetrics); }); }); it("should return correct metrics with pending releases", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetricsString: (releaseMetrics: models.CodePushReleaseMetric, releasesTotalActive: number) => string = command["generateMetricsString"]; const fakeReleaseMetrics = { active: 3, downloaded: 5, failed: 0, installed: 3, label: fakeLabel, }; const fakeActiveString = "100% (3 of 3)"; const fakeInstalled = "3"; const fakePending = " (2 pending)"; const expectedMetrics = getExpectedMetricsString(fakeActiveString, fakeInstalled, fakePending); // Act const result = generateMetricsString(fakeReleaseMetrics, fakeReleasesTotalActive); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedMetrics); }); it("should return correct string for empty metrics", () => { // Arrange const command = new CodePushDeploymentListListCommand(defaultCommandArgsForListCommand); const generateMetricsString: (releaseMetrics: models.CodePushReleaseMetric, releasesTotalActive: number) => string = command["generateMetricsString"]; const expectedMetrics = noMetricsString; // Act const result = generateMetricsString(undefined, fakeReleasesTotalActive); // Assert expect(result).to.be.an("string"); expect(removeColorFromText(result)).to.be.eql(expectedMetrics); }); }); describe("deployment list tests", () => { let sandbox: Sinon.SinonSandbox; let nockScope: Nock.Scope; beforeEach(() => { sandbox = Sinon.createSandbox(); nockScope = Nock(fakeHost); }); afterEach(() => { sandbox.restore(); Nock.cleanAll(); }); it("should output table without releases and metrics", async () => { // Arrange setupNockGetDeploymentsResponse(nockScope, fakeParamsForRequest, [fakeDeployment]); const expectedOutputTable = [[fakeDeployment.name, noUpdatesString, noMetricsString]]; const spyOutTable = sandbox.stub(out, "table"); const spyOutText = sandbox.stub(out, "text"); // Act const command = new CodePushDeploymentListListCommand(getCommandArgsForListCommand(fakeParamsForRequest)); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; expect(spyOutTable.calledOnce).to.be.true; expect(spyOutText.calledOnce).to.be.true; const resultTable = spyOutTable.lastCall.args[1]; expect(resultTable).to.be.an("array"); expect(removeColorFromTableRows(resultTable)).to.be.eql(expectedOutputTable); const resultText = spyOutText.getCall(0).args[0]; expect(resultText).to.be.an("string"); expect(resultText).to.be.eql(expectedOutputHelperText); nockScope.done(); }); it("should output table with correct data for releases without metrics", async () => { // Arrange setupNockGetDeploymentsResponse(nockScope, fakeParamsForRequest, [fakeDeploymentWithRelease]); setupNockGetDeploymentMetricsResponse(nockScope, fakeParamsForRequest, {}, fakeDeployment); const expectedOutputTable = [[fakeDeployment.name, expectedGeneratedMetadataString, noMetricsString]]; const spyOutTable = sandbox.stub(out, "table"); const spyOutText = sandbox.stub(out, "text"); // Act const command = new CodePushDeploymentListListCommand(getCommandArgsForListCommand(fakeParamsForRequest)); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; expect(spyOutTable.calledOnce).to.be.true; expect(spyOutText.calledOnce).to.be.true; const resultTable = spyOutTable.lastCall.args[1]; expect(resultTable).to.be.an("array"); expect(removeColorFromTableRows(resultTable)).to.be.eql(expectedOutputTable); const resultText = spyOutText.getCall(0).args[0]; expect(resultText).to.be.an("string"); expect(resultText).to.be.eql(expectedOutputHelperText); nockScope.done(); }); it("should output table with correct data for releases with metrics", async () => { // Arrange const fakeReleaseMetrics = { active: 3, downloaded: 5, failed: 0, installed: 3, label: fakeLabel, }; setupNockGetDeploymentsResponse(nockScope, fakeParamsForRequest, [fakeDeploymentWithRelease, fakeDeploymentWithRelease]); setupNockGetDeploymentMetricsResponse( nockScope, fakeParamsForRequest, [fakeReleaseMetrics], fakeDeployment, successfulStatus, 2 ); const fakeActiveString = "100% (3 of 3)"; const fakeInstalled = "3"; const fakePending = " (2 pending)"; const expectedLine = [ fakeDeployment.name, expectedGeneratedMetadataString, getExpectedMetricsString(fakeActiveString, fakeInstalled, fakePending), ]; const expectedOutputTable = [expectedLine, expectedLine]; const spyOutTable = sandbox.stub(out, "table"); const spyOutText = sandbox.stub(out, "text"); // Act const command = new CodePushDeploymentListListCommand(getCommandArgsForListCommand(fakeParamsForRequest)); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; expect(spyOutTable.calledOnce).to.be.true; expect(spyOutText.calledOnce).to.be.true; const resultTable = spyOutTable.lastCall.args[1]; expect(removeColorFromTableRows(resultTable)).to.be.eql(expectedOutputTable); const resultText = spyOutText.getCall(0).args[0]; expect(resultText).to.be.an("string"); expect(resultText).to.be.eql(expectedOutputHelperText); nockScope.done(); }); it("should output table with deployment keys", async () => { // Arrange setupNockGetDeploymentsResponse(nockScope, fakeParamsForRequest, [fakeDeployment]); const expectedOutputTable = [fakeDeployment.name, fakeDeployment.key]; const spyOutTable = sandbox.stub(out, "table"); // Act const command = new CodePushDeploymentListListCommand(getCommandArgsForListCommand(fakeParamsForRequest, ["-k"])); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; expect(spyOutTable.calledOnce).to.be.true; const resultTable = spyOutTable.lastCall.args[1]; expect(resultTable[0]).to.be.an("array"); expect(resultTable[0]).to.be.eql(expectedOutputTable); nockScope.done(); }); it("should output error when app does not exist", async () => { // Arrange setupNockGetDeploymentsResponse(nockScope, fakeParamsForRequest, {}, unsuccessfulStatus); // Act const command = new CodePushDeploymentListListCommand(getCommandArgsForListCommand(fakeParamsForRequest)); const result = await command.execute(); // Assert expect(result.succeeded).to.be.false; expect((result as CommandFailedResult).errorMessage).contain(expectedErrorMessage); nockScope.done(); }); }); function getExpectedMetricsString(fakeActiveString: string, fakeInstalled: string, pendingString?: string): string { let metricsString = "Active: " + fakeActiveString + "\nInstalled: " + fakeInstalled; if (pendingString) { metricsString += pendingString; } return metricsString; } function setupNockGetDeploymentsResponse( nockScope: Nock.Scope, fakeParamsForRequest: FakeParamsForRequests, returnDeployments: models.Deployment[] | {}, statusCode: number = 200 ): void { nockScope .get(`/${fakeParamsForRequest.appVersion}/apps/${fakeParamsForRequest.userName}/${fakeParamsForRequest.appName}/deployments`) .reply((uri: any, requestBody: any) => { return [statusCode, returnDeployments]; }); } function setupNockGetDeploymentMetricsResponse( nockScope: Nock.Scope, fakeParamsForRequest: FakeParamsForRequests, returnMetrics: models.CodePushReleaseMetric[] | {}, fakeDeployment: models.Deployment, statusCode: number = 200, times: number = 1 ): void { nockScope .get( `/${fakeParamsForRequest.appVersion}/apps/${fakeParamsForRequest.userName}/${fakeParamsForRequest.appName}/deployments/${fakeDeployment.name}/metrics` ) .times(times) .reply((uri: any, requestBody: any): any => { return [statusCode, returnMetrics]; }); } function removeColorFromText(text: string): string { return stripAnsi(text); } function removeColorFromTableRows(tableRows: string[][]) { return tableRows.map((row) => row.map((element) => stripAnsi(element))); } function getCommandArgsForListCommand(fakeConsts: FakeParamsForRequests, additionalArgs: string[] = []): CommandArgs { const args: string[] = [ "-a", `${fakeConsts.userName}/${fakeConsts.appName}`, "--token", fakeConsts.token, "--env", "local", ].concat(additionalArgs); return { args, command: ["codepush", "deployment", "list"], commandPath: fakeConsts.path, }; } });
the_stack
import { ObjectType, ElemID, BuiltinTypes, InstanceElement, PrimitiveType, PrimitiveTypes, TypeElement, Variable, } from '@salto-io/adapter-api' import { collections } from '@salto-io/lowerdash' import { mergeElements, DuplicateAnnotationError, mergeSingleElement } from '../src/merger' import { ConflictingFieldTypesError, DuplicateAnnotationFieldDefinitionError, DuplicateAnnotationTypeError } from '../src/merger/internal/object_types' import { DuplicateInstanceKeyError } from '../src/merger/internal/instances' import { MultiplePrimitiveTypesError } from '../src/merger/internal/primitives' import { DuplicateVariableNameError } from '../src/merger/internal/variables' const { awu } = collections.asynciterable describe('merger', () => { const baseElemID = new ElemID('salto', 'base') const base = new ObjectType({ elemID: baseElemID, fields: { field1: { refType: BuiltinTypes.STRING, annotations: { label: 'base' }, }, field2: { refType: BuiltinTypes.STRING, annotations: { label: 'base' }, }, }, annotations: { _default: { field1: 'base1', field2: 'base2', }, }, }) const unrelated = new ObjectType({ elemID: new ElemID('salto', 'unrelated'), fields: { field1: { refType: BuiltinTypes.STRING, annotations: { label: 'base' }, }, }, }) const fieldAnnotationConflict = new ObjectType({ elemID: baseElemID, fields: { field1: { refType: BuiltinTypes.STRING, annotations: { label: 'update1' }, }, }, }) const fieldTypeConflict = new ObjectType({ elemID: baseElemID, fields: { field2: { refType: BuiltinTypes.NUMBER }, }, }) const fieldUpdate = new ObjectType({ elemID: baseElemID, fields: { field1: { refType: BuiltinTypes.STRING, annotations: { a: 'update' }, }, }, }) const fieldUpdate2 = new ObjectType({ elemID: baseElemID, fields: { field1: { refType: BuiltinTypes.STRING, annotations: { b: 'update' }, }, }, }) const newField = new ObjectType({ elemID: baseElemID, fields: { field3: { refType: BuiltinTypes.STRING }, }, }) const updateAnno = new ObjectType({ elemID: baseElemID, annotationRefsOrTypes: { anno1: BuiltinTypes.STRING, }, }) const multipleUpdateAnno = new ObjectType({ elemID: baseElemID, annotationRefsOrTypes: { anno1: BuiltinTypes.STRING, }, }) const updateAnnoValues = new ObjectType({ elemID: baseElemID, annotations: { anno1: 'updated', }, }) const multipleUpdateAnnoValues = new ObjectType({ elemID: baseElemID, annotations: { anno1: 'updated', }, }) const mergedObject = new ObjectType({ elemID: baseElemID, fields: { field1: { refType: BuiltinTypes.STRING, annotations: { label: 'base', a: 'update', b: 'update' }, }, field2: { refType: BuiltinTypes.STRING, annotations: { label: 'base' }, }, field3: { refType: BuiltinTypes.STRING, }, }, annotations: { anno1: 'updated', _default: { field1: 'base1', field2: 'base2', }, }, annotationRefsOrTypes: { anno1: BuiltinTypes.STRING, }, }) const typeRef = (typeToRef: TypeElement): ObjectType => new ObjectType({ elemID: typeToRef.elemID }) describe('updates', () => { it('does not modify an element list with no updates', async () => { const elements = [base, unrelated] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) expect(await awu(merged.values()).toArray()).toHaveLength(2) }) it('merges multiple field blocks', async () => { const elements = [ base, unrelated, fieldUpdate, fieldUpdate2, newField, updateAnno, updateAnnoValues, ] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) expect(await awu(merged.values()).toArray()).toHaveLength(2) expect((await awu(merged.values()).toArray())[0]).toEqual(mergedObject) }) it('returns the same result regardless of the elements order', async () => { const elements = [ fieldUpdate, updateAnno, newField, base, unrelated, fieldUpdate2, updateAnnoValues, ] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) expect(await awu(merged.values()).toArray()).toHaveLength(2) expect((await awu(merged.values()).toArray())[0]).toEqual(mergedObject) }) it('returns an error when the same field annotation is defined multiple times', async () => { const elements = [ base, fieldAnnotationConflict, ] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateAnnotationFieldDefinitionError) }) it('returns an error when multiple updates exists for same annotation', async () => { const elements = [ base, updateAnno, multipleUpdateAnno, ] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateAnnotationTypeError) }) it('returns an error when multiple updates exists for same annotation value', async () => { const elements = [ base, updateAnnoValues, multipleUpdateAnnoValues, ] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateAnnotationError) }) it('returns an error when field definitions have conflicting types', async () => { const elements = [ base, fieldTypeConflict, ] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(ConflictingFieldTypesError) expect(errors[0].message).toContain(BuiltinTypes.STRING.elemID.getFullName()) expect(errors[0].message).toContain(BuiltinTypes.NUMBER.elemID.getFullName()) expect(String(errors[0])).toEqual(errors[0].message) }) }) describe('merging instances', () => { const strType = new PrimitiveType({ elemID: new ElemID('salto', 'string'), primitive: PrimitiveTypes.STRING, annotations: { _default: 'type' }, }) const nestedElemID = new ElemID('salto', 'nested') const nested = new ObjectType({ elemID: nestedElemID, fields: { field1: { refType: strType, annotations: { _default: 'field1' }, }, field2: { refType: strType, }, base: { refType: base, }, }, }) const ins1 = new InstanceElement( 'ins', nested, { field1: 'ins1', field2: 'ins1' }, undefined, { anno: 1 }, ) const ins2 = new InstanceElement( 'ins', nested, { base: { field1: 'ins2', field2: 'ins2' } }, undefined, { anno2: 1 }, ) const shouldUseFieldDef = new InstanceElement('ins', nested, { field2: 'ins1', }) it('should merge instances', async () => { const elements = [ins1, ins2] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) expect(await awu(merged.values()).toArray()).toHaveLength(1) const ins = (await awu(merged.values()).toArray())[0] as InstanceElement expect(ins.value).toEqual({ field1: 'ins1', field2: 'ins1', base: { field1: 'ins2', field2: 'ins2', }, }) expect(ins.annotations).toEqual({ anno: 1, anno2: 1 }) }) it('should fail on multiple values for same key', async () => { const elements = [ins1, shouldUseFieldDef] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateInstanceKeyError) }) it('should fail on multiple values for same annotation', async () => { const conflicting = ins2.clone() conflicting.annotations = ins1.annotations const errors = await awu(( await mergeElements(awu([ins1, conflicting]))).errors.values()).flat() .toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateAnnotationError) }) }) describe('merging primitives', () => { const strType = new PrimitiveType({ elemID: new ElemID('salto', 'string'), primitive: PrimitiveTypes.STRING, annotationRefsOrTypes: { somethingElse: BuiltinTypes.STRING, }, annotations: { somethingElse: 'type' }, }) const duplicateType = new PrimitiveType({ elemID: new ElemID('salto', 'string'), primitive: PrimitiveTypes.NUMBER, annotations: { _default: 'type' }, }) it('should fail when more then one primitive is defined with same elemID and different primitives', async () => { const elements = [strType, duplicateType] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(MultiplePrimitiveTypesError) }) it('should fail when annotation types and annoations are defined in multiple fragments', async () => { const elements = [strType, strType] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(2) expect(errors[0]).toBeInstanceOf(DuplicateAnnotationTypeError) expect(errors[1]).toBeInstanceOf(DuplicateAnnotationTypeError) }) }) describe('merging variables', () => { it('should fail when more then one variable is defined with same elemID', async () => { const var1 = new Variable(new ElemID(ElemID.VARIABLES_NAMESPACE, 'varName'), 5) const var2 = new Variable(new ElemID(ElemID.VARIABLES_NAMESPACE, 'varName'), 5) const elements = [var1, var2] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0]).toBeInstanceOf(DuplicateVariableNameError) }) it('should succeed when no more then one variable is defined with same elemID', async () => { const var1 = new Variable(new ElemID(ElemID.VARIABLES_NAMESPACE, 'varName'), 5) const var2 = new Variable(new ElemID(ElemID.VARIABLES_NAMESPACE, 'varName2'), 8) const elements = [var1, var2] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) expect(await awu(merged.values()).toArray()).toHaveLength(2) const merged1 = (await awu(merged.values()).toArray())[0] as Variable const merged2 = (await awu(merged.values()).toArray())[1] as Variable expect(merged1.value).toEqual(5) expect(merged2.value).toEqual(8) expect(merged1.elemID.getFullName()).toEqual('var.varName') expect(merged2.elemID.getFullName()).toEqual('var.varName2') }) }) describe('merging settings', () => { const settingElemID = new ElemID('salto', 'settingObj') const setting1 = new ObjectType({ isSettings: true, elemID: settingElemID, fields: { setting1: { refType: BuiltinTypes.STRING, }, }, }) const setting2 = new ObjectType({ isSettings: true, elemID: settingElemID, fields: { setting2: { refType: BuiltinTypes.STRING, }, }, }) const mergedSetting = new ObjectType({ isSettings: true, elemID: settingElemID, fields: { setting1: { refType: BuiltinTypes.STRING, }, setting2: { refType: BuiltinTypes.STRING, }, }, }) const badSettingType = new ObjectType({ isSettings: false, elemID: settingElemID, }) it('should merge settings types', async () => { const elements = [setting1, setting2] const { merged, errors } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().isEmpty()).toBeTruthy() expect(await awu(merged.values()).toArray()).toHaveLength(1) expect((await awu(merged.values()).toArray())[0]).toEqual(mergedSetting) }) it('should raise an error for isSettingType mismatch', async () => { const elements = [setting1, badSettingType] const errors = await awu( (await mergeElements(awu(elements)) ).errors.values() ).flat().toArray() expect(errors).toHaveLength(1) expect(errors[0].message).toEqual('Error merging salto.settingObj: conflicting is settings definitions') }) }) describe('merge with context', () => { const objectTypeElemID = new ElemID('salesforce', 'test') const objTypeAnnotation = { test: 'my test' } const objectType = new ObjectType({ elemID: objectTypeElemID, annotations: objTypeAnnotation }) const instanceElementToMerge = new InstanceElement('inst', typeRef(objectType)) const instanceElementContext = new InstanceElement('instInContext', typeRef(objectType)) it('should replace type refs with full types in the elements that are being merged', async () => { const elements = [instanceElementToMerge] const { errors, merged } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) const mergedElement = (await awu(merged.values()) .filter(e => e.elemID.isEqual(instanceElementToMerge.elemID)).toArray()) expect(mergedElement).toBeDefined() // expect((mergedElement as InstanceElement).type).toBe(objectType) }) it('should not replace type refs with full types in the context elements', async () => { const elements = [instanceElementToMerge] const { errors, merged } = await mergeElements(awu(elements)) expect(await awu(errors.values()).flat().toArray()).toHaveLength(0) const mergedElement = await awu(merged.values()) .find(e => e.elemID.isEqual(instanceElementContext.elemID)) expect(mergedElement).toBeUndefined() expect(instanceElementContext.refType).not.toBe(objectType.elemID) }) }) describe('merge single element', () => { const type = new ObjectType({ elemID: new ElemID('adapter', 'type') }) it('should throw an error if there is a merge error', async () => { const instance1 = new InstanceElement('instance', type, { value: 1 }) const instance2 = new InstanceElement('instance', type, { value: 2 }) await expect(mergeSingleElement([instance1, instance2])).rejects.toThrow('Received merge errors') }) it('should throw an error if received more than one merged elements', async () => { const instance1 = new InstanceElement('instance', type, { value: 1 }) const instance2 = new InstanceElement('instance2', type, { value: 2 }) await expect(mergeSingleElement([instance1, instance2])).rejects.toThrow('Received invalid number of merged elements when expected one') }) it('should return the merged element when valid', async () => { const instance1 = new InstanceElement('instance', type, { value1: 1 }) const instance2 = new InstanceElement('instance', type, { value2: 2 }) const merged = await mergeSingleElement([instance1, instance2]) expect(merged.value).toEqual({ value1: 1, value2: 2 }) }) }) })
the_stack
import {LifeCycle} from '@tko/lifecycle' import { safeStringify, isThenable } from '@tko/utils' import { applyBindings, contextFor } from '@tko/bind' import { isObservable, unwrap, observable } from '@tko/observable' import { isComputed } from '@tko/computed' import { NativeProvider, NATIVE_BINDINGS } from '@tko/provider.native' import { queueCleanNode } from './jsxClean' export const ORIGINAL_JSX_SYM = Symbol('Knockout - Original JSX') const NAMESPACES = { svg: 'http://www.w3.org/2000/svg', html: 'http://www.w3.org/1999/xhtml', xml: 'http://www.w3.org/XML/1998/namespace', xlink: 'http://www.w3.org/1999/xlink', xmlns: 'http://www.w3.org/2000/xmlns/' } function isIterable (v) { return v && typeof v[Symbol.iterator] === 'function' } /** * JSX object from a pre-processor. * @typedef {Object} JSX * @property {string} elementName becomes the `tagName` * @property {Array.<JSX>} children * @property {object} attributes */ /** * Observe a variety of possible cases from JSX, modifying the * `parentNode` at `insertBefore` with the result. */ export class JsxObserver extends LifeCycle { /** * @param {any} jsxOrObservable take a long list of permutations */ constructor (jsxOrObservable, parentNode, insertBefore = null, xmlns, noInitialBinding) { super() const parentNodeIsComment = parentNode.nodeType === 8 const parentNodeTarget = this.getParentTarget(parentNode) if (isObservable(jsxOrObservable)) { jsxOrObservable.extend({ trackArrayChanges: true }) this.subscribe(jsxOrObservable, this.observableArrayChange, 'arrayChange') if (!insertBefore) { const insertAt = parentNodeIsComment ? parentNode.nextSibling : null insertBefore = this.createComment('O') parentNodeTarget.insertBefore(insertBefore, insertAt) } else { this.adoptedInsertBefore = true } } if (parentNodeIsComment && !insertBefore) { // Typcially: insertBefore becomes <!-- /ko --> insertBefore = parentNode.nextSibling // Mark this so we don't remove the next node - since we didn't create it. this.adoptedInsertBefore = true } this.anchorTo(insertBefore || parentNode) Object.assign(this, { insertBefore, noInitialBinding, parentNode, parentNodeTarget, xmlns, nodeArrayOrObservableAtIndex: [], subscriptionsForNode: new Map(), }) const jsx = unwrap(jsxOrObservable) const computed = isComputed(jsxOrObservable) if (computed || (jsx !== null && jsx !== undefined)) { this.observableArrayChange(this.createInitialAdditions(jsx)) } this.noInitialBinding = false } /** * @param {HMTLElement|Comment|HTMLTemplateElement} parentNode */ getParentTarget (parentNode) { if ('content' in parentNode) { return parentNode.content } if (parentNode.nodeType === 8) { return parentNode.parentNode } return parentNode } remove () { this.dispose() } dispose () { super.dispose() const ib = this.insertBefore const insertBeforeIsChild = ib && this.parentNodeTarget === ib.parentNode if (insertBeforeIsChild && !this.adoptedInsertBefore) { this.parentNodeTarget.removeChild(ib) } this.removeAllPriorNodes() Object.assign(this, { parentNode: null, parentNodeTarget: null, insertBefore: null, nodeArrayOrObservableAtIndex: [] }) for (const subscriptions of this.subscriptionsForNode.values()) { subscriptions.forEach(s => s.dispose()) } this.subscriptionsForNode.clear() } createInitialAdditions (possibleIterable) { const status = 'added' if (typeof possibleIteratable === 'object' && posibleIterable !== null && Symbol.iterator in possibleIterable) { possibleIterable = [...possibleIterable] } return Array.isArray(possibleIterable) ? possibleIterable.map((value, index) => ({ index, status, value })) : [{ status, index: 0, value: possibleIterable }] } /** * Note: array change notification indexes are: * - to the original array indexes for deletes * - to the new array indexes for adds * - sorted by index in ascending order */ observableArrayChange (changes) { let adds = [] let dels = [] for (const index in changes) { const change = changes[index] if (change.status === 'added') { adds.push([change.index, change.value]) } else { dels.unshift([change.index, change.value]) } } dels.forEach(change => this.delChange(...change)) adds.forEach(change => this.addChange(...change)) } /** * Add a change at the given index. * * @param {int} index * @param {string|object|Array|Observable.string|Observable.Array|Obseravble.object} jsx */ addChange (index, jsx) { this.nodeArrayOrObservableAtIndex.splice(index, 0, this.injectNode(jsx, this.lastNodeFor(index))) } injectNode (jsx, nextNode) { let nodeArrayOrObservable if (isObservable(jsx)) { const {parentNode, xmlns} = this const observer = new JsxObserver(jsx, parentNode, nextNode, xmlns, this.noInitialBinding) nodeArrayOrObservable = [observer] } else if (typeof jsx !== 'string' && isIterable(jsx)) { nodeArrayOrObservable = [] for (const child of jsx) { nodeArrayOrObservable.unshift( this.injectNode(child, nextNode)) } } else { const $context = contextFor(this.parentNode) const isInsideTemplate = 'content' in this.parentNode const shouldApplyBindings = $context && !isInsideTemplate && !this.noInitialBinding if (Array.isArray(jsx)) { nodeArrayOrObservable = jsx.map(j => this.anyToNode(j)) } else { nodeArrayOrObservable = [this.anyToNode(jsx)] } for (const node of nodeArrayOrObservable) { this.parentNodeTarget.insertBefore(node, nextNode) if (shouldApplyBindings && this.canApplyBindings(node)) { applyBindings($context, node) } } } return nodeArrayOrObservable } /** * True when Node is a type suitable for applyBindings i.e. a HTMLElement * or a Comment. * @param {Node} node */ canApplyBindings (node) { return node.nodeType === 1 || node.nodeType === 8 } delChange (index) { this.removeNodeArrayOrObservable( this.nodeArrayOrObservableAtIndex[index]) this.nodeArrayOrObservableAtIndex.splice(index, 1) } getSubscriptionsForNode (node) { if (!this.subscriptionsForNode.has(node)) { const subscriptions = [] this.subscriptionsForNode.set(node, subscriptions) return subscriptions } return this.subscriptionsForNode.get(node) } isJsx (jsx) { return typeof jsx.elementName === 'string' && 'children' in jsx && 'attributes' in jsx } /** * @param {any} value acceptable to turn into a Node * * The one thing `any` cannot be here is an Array or Observable; both those * cases are handled with new JsxObservers. */ anyToNode (any) { if (isThenable(any)) { return this.futureJsxNode(any) } switch (typeof any) { case 'object': if (any instanceof Error) { return this.createComment(any.toString()) } if (any === null) { return this.createComment(String(any)) } if (any instanceof Node) { return this.cloneJSXorMoveNode(any) } if (Symbol.iterator in any) { return any } break case 'function': return this.anyToNode(any()) case 'undefined': case 'symbol': return this.createComment(String(any)) case 'string': return this.createTextNode(any) case 'boolean': case 'number': case 'bigint': default: return this.createTextNode(String(any)) } return this.isJsx(any) ? this.jsxToNode(any) : this.createComment(safeStringify(any)) } createComment (string) { const node = document.createComment(string) node[NATIVE_BINDINGS] = true return node } createTextNode (string) { const node = document.createTextNode(string) node[NATIVE_BINDINGS] = true return node } /** * Clone a node; if that node was originally from JSX, we clone from there * so we preserve binding handlers. * * @param {HTMLElement} node */ cloneJSXorMoveNode (node) { return ORIGINAL_JSX_SYM in node ? this.jsxToNode(node[ORIGINAL_JSX_SYM]) : node } /** * @param {JSX} jsx to convert to a node. */ jsxToNode (jsx) { const xmlns = jsx.attributes.xmlns || NAMESPACES[jsx.elementName] || this.xmlns const node = document.createElementNS(xmlns || NAMESPACES.html, jsx.elementName) /** Slots need to be able to replicate with the attributes, which * are not preserved when cloning from template nodes. */ node[ORIGINAL_JSX_SYM] = jsx if (isObservable(jsx.attributes)) { const subscriptions = this.getSubscriptionsForNode(node) subscriptions.push( jsx.attributes.subscribe(attrs => { this.updateAttributes(node, unwrap(attrs)) })) } this.updateAttributes(node, unwrap(jsx.attributes)) this.addDisposable(new JsxObserver(jsx.children, node, null, xmlns, this.noInitialBinding)) return node } futureJsxNode (promise) { const obs = observable() promise.then(obs).catch(e => obs(e instanceof Error ? e : Error(e))) const jo = new JsxObserver(obs, this.parentNode, null, this.xmlns, this.noInitialBinding) this.addDisposable(jo) return jo.insertBefore } updateAttributes (node, attributes) { const subscriptions = this.getSubscriptionsForNode(node) const toRemove = new Set([...node.attributes].map(n => n.name)) for (const [name, value] of Object.entries(attributes || {})) { toRemove.delete(name) if (isObservable(value)) { subscriptions.push( value.subscribe(attr => this.setNodeAttribute(node, name, value))) } this.setNodeAttribute(node, name, value) } for (const name of toRemove) { this.setNodeAttribute(node, name, undefined) } } /** * See https://stackoverflow.com/a/52572048 * @param {string} attr element attribute * @return {string} namespace argument for setAtttributeNS */ getNamespaceOfAttribute (attr) { const [prefix, ...unqualifiedName] = attr.split(':') if (prefix === 'xmlns' || (unqualifiedName.length && NAMESPACES[prefix])) { return NAMESPACES[prefix] } return null } /** * * @param {HTMLElement} node * @param {string} name * @param {any} valueOrObservable */ setNodeAttribute (node, name, valueOrObservable) { const value = unwrap(valueOrObservable) NativeProvider.addValueToNode(node, name, valueOrObservable) if (value === undefined) { node.removeAttributeNS(null, name) } else if (isThenable(valueOrObservable)) { Promise.resolve(valueOrObservable) .then(v => this.setNodeAttribute(node, name, v)) } else { const ns = this.getNamespaceOfAttribute(name) node.setAttributeNS(ns, name, String(value)) } } /** * @param {int} index * @return {Comment} that immediately precedes this. */ lastNodeFor (index) { const nodesAtIndex = this.nodeArrayOrObservableAtIndex[index] || [] const [lastNodeOfPrior] = nodesAtIndex.slice(-1) const insertBefore = lastNodeOfPrior instanceof JsxObserver ? lastNodeOfPrior.insertBefore : lastNodeOfPrior || this.insertBefore if (insertBefore) { return insertBefore.parentNode ? insertBefore : null } return null } removeAllPriorNodes () { const {nodeArrayOrObservableAtIndex} = this while (nodeArrayOrObservableAtIndex.length) { this.removeNodeArrayOrObservable(nodeArrayOrObservableAtIndex.pop()) } } removeNodeArrayOrObservable (nodeArrayOrObservable) { for (const nodeOrObservable of nodeArrayOrObservable) { if (nodeOrObservable instanceof JsxObserver) { nodeOrObservable.dispose() continue } const node = nodeOrObservable delete node[ORIGINAL_JSX_SYM] this.detachAndDispose(node) const subscriptions = this.subscriptionsForNode.get(node) if (subscriptions) { subscriptions.forEach(s => s.dispose()) this.subscriptionsForNode.delete(node) } } } /** * Detach the given node, and dispose of its children. * * The cleaning can trigger a lot of garbage collection, so we defer that. */ detachAndDispose (node) { if (isIterable(node)) { for (const child of node) { this.detachAndDispose(child) } } else { node.remove() } queueCleanNode(node) } } export default JsxObserver
the_stack
import * as React from 'react'; import styles from '../Crm.module.scss'; import DialogUtility from '../../../utilities/DialogUtility'; import { ICrmComponentProps } from '../ICrmComponentProps'; import { IOrganization } from '../../../data/IOrganization'; import { IOrganizationSet } from '../../../dataProviders/IOrganizationSet'; import ItemFieldIterator from '../../../sharePointComponents/ItemFieldIterator'; import ItemMultilineTextFieldEditor from '../../../sharePointComponents/ItemMultilineTextFieldEditor'; import ItemMultiLookupFieldEditor from '../../../sharePointComponents/ItemMultiLookupFieldEditor'; import ItemTextFieldEditor from '../../../sharePointComponents/ItemTextFieldEditor'; import ItemUrlFieldEditor from '../../../sharePointComponents/ItemUrlFieldEditor'; import ItemContext from '../../../sharePointComponents/ItemContext'; import ItemPeopleFieldEditor from '../../../sharePointComponents/ItemPeopleFieldEditor'; import { PivotItem, Pivot } from 'office-ui-fabric-react/lib/Pivot'; export interface IOrganizationEditProps extends ICrmComponentProps { organization: IOrganization; ensureNew : boolean; isDialog? : boolean; } export interface IOrganizationEditState { organization: IOrganization; newItemWasCreated : boolean; } export default class OrganizationEdit extends React.Component<IOrganizationEditProps, IOrganizationEditState> { private _itemContext : ItemContext = null; public constructor(props?: IOrganizationEditProps, context?: any) { super(props, context); this.onSave = this.onSave.bind(this); this.onCancel = this.onCancel.bind(this); this._itemContext = new ItemContext(); this._itemContext.dataProvider = this.props.manager.data; } public componentWillMount() { var newProps = this.props; if (newProps != null && newProps.organization != null) { this.state = { organization: newProps.organization, newItemWasCreated: false }; } else if (newProps.ensureNew) { newProps.manager.data.createOrganizationItem("", "").then((data: IOrganizationSet) => { this._itemContext.itemId = data.organizations[0].Id; this._itemContext.itemObject = data.organizations[0]; this.setState( { organization: data.organizations[0], newItemWasCreated: true }); } ); } if (newProps.isDialog) { DialogUtility.setActions(this.onCancel, this.onSave); } this._updateProps(this.props); } public componentWillReceiveProps(nextProps : IOrganizationEditProps) { this._updateProps(nextProps); } private _updateProps(newProps : IOrganizationEditProps) { if (newProps != null && newProps.manager != null) { this._itemContext.list = newProps.manager.data.selectedOrganizationList; this._itemContext.itemObject = newProps.organization; } } public onSave() : void { var me = this; var wasUpdated : boolean = me.state.newItemWasCreated; if (wasUpdated || this._itemContext.hasChanged) { if (me.state.newItemWasCreated) { //Debug.message("Saving new organization" + JSON.stringify(this.state.organization)); this.props.manager.data.addOrganizationItem(this.state.organization).then((data: IOrganizationSet) => { //Debug.message("Result from saving organization (note new ID)" + JSON.stringify(data.organizations[0])); this._itemContext.itemId = data.organizations[0].Id; this._itemContext.itemObject = data.organizations[0]; this.setState( { organization: data.organizations[0], newItemWasCreated: false }); }); } else { me.props.manager.data.updateOrganizationItem(this.state.organization).then((data: IOrganizationSet) => { }); } this._itemContext.hasChanged = false; me.props.manager.data.notifyOrganizationChanged(this.state.organization); } } public onCancel() : void { } public render(): JSX.Element { return ( <div className={styles.organizationEdit}> <div className={styles.mainFieldArea}> <ItemTextFieldEditor field={ this._itemContext.getField("Title") } itemContext={ this._itemContext } /> </div> <Pivot ref="pivot"> <PivotItem key="summary" headerText="Summary"> <div className={styles.fieldTab}> <div>Description:</div> <ItemMultilineTextFieldEditor stripHtml={true} field={this._itemContext.getField("Description") } itemContext={ this._itemContext } /> <div>Notes:</div> <ItemMultilineTextFieldEditor stripHtml={true} field={this._itemContext.getField("Notes") } itemContext={ this._itemContext } /> <div className={styles.fieldListArea}> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Tags: </div> <div className={styles.fieldInput}> <ItemMultiLookupFieldEditor field={this._itemContext.getField("Tags") } itemContext={ this._itemContext } /> </div> <div className={styles.fieldLabel}> Priority: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("Organizational_x0020_Priority") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Owner: </div> <div className={styles.fieldInput}> <ItemPeopleFieldEditor field={this._itemContext.getField("Owner") } itemContext={ this._itemContext } /> </div> </div> </div> </div> </PivotItem> <PivotItem key="org" headerText='Address' > <div className="{styles.fieldTab}"> <div className={styles.fieldListArea}> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Address: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("PrimaryAddress") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> City: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("PrimaryCity") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Zip/Postal Code: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("PrimaryZipPostalCode") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> State/Province: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("PrimaryStateProvince") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Country: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("PrimaryCountry") } itemContext={ this._itemContext } /> </div> </div> </div> </div> </PivotItem> <PivotItem key="res" headerText='Resources' > <div className="{styles.fieldTab}"> <div className={styles.fieldListArea}> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Home Page: </div> <div className={styles.fieldInput}> <ItemTextFieldEditor field={this._itemContext.getField("HomePage") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> About: </div> <div className={styles.fieldInput}> <ItemUrlFieldEditor field={this._itemContext.getField("About") } itemContext={ this._itemContext } /> </div> </div> <div className={styles.fieldArea}> <div className={styles.fieldLabel}> Logo: </div> <div className={styles.fieldInput}> <ItemUrlFieldEditor field={this._itemContext.getField("Logo") } itemContext={ this._itemContext } /> </div> </div> </div> </div> </PivotItem> <PivotItem key="orgrecent" headerText='Miscellaneous' > <div className={styles.fieldTab}> <div className={styles.iteratorArea}> <ItemFieldIterator excludedFields={ ["Title", "Updates", "Notes", "Description", "Tags", "Organizational_x0020_Priority", "Owner", "Homepage", "Logo", "About", "PrimaryAddress", "PrimaryCity", "PrimaryStateProvince", "PrimaryZipPostalCode", "PrimaryCountry"] } itemContext={ this._itemContext } /> </div> </div> </PivotItem> </Pivot> </div> ); } }
the_stack
import { execSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import chalk from 'chalk'; import { ethers } from 'ethers'; import { flatten, unflatten } from 'flat'; import { createContext, createParams, createResult, CreationStatus, EnvVariable, EnvVariables, HardhatOptions, } from '../types'; const port = 8545; // eslint-disable-next-line @typescript-eslint/ban-types const prettyStringify = (obj: object): string => JSON.stringify(obj, null, 2); const injectFlattenedJsonToFile = ( file: string, // eslint-disable-next-line @typescript-eslint/ban-types options: object, // eslint-disable-next-line @typescript-eslint/ban-types maybeUnflattened?: object ) => { !fs.existsSync(file) && fs.writeFileSync(file, JSON.stringify({})); fs.writeFileSync( file, prettyStringify({ ...unflatten({ ...(flatten( JSON.parse(fs.readFileSync(file, 'utf-8')) // eslint-disable-next-line @typescript-eslint/ban-types ) as object), ...options, }), ...(typeof maybeUnflattened === 'object' ? maybeUnflattened : {}), }) ); }; const createBaseProject = ({ name }: createParams) => execSync(`npx create-react-native-app ${name} -t with-typescript`, { stdio: 'inherit', }); //const ejectExpoProject = (ctx: createContext) => { // const { // bundleIdentifier, packageName, uriScheme, // } = ctx; // const { projectDir } = ctx; // // injectFlattenedJsonToFile(path.resolve(projectDir, 'app.json'), { // 'expo.ios.bundleIdentifier': bundleIdentifier, // 'expo.android.package': packageName, // 'expo.scheme': uriScheme, // 'expo.icon': 'assets/image/app-icon.png', // 'expo.splash.image': 'assets/image/app-icon.png', // 'expo.splash.resizeMode': 'contain', // 'expo.splash.backgroundColor': '#222222', // }); // // execSync(`expo eject --non-interactive`, { // stdio: 'inherit', // cwd: `${projectDir}`, // }); // // const gradle = path.resolve(projectDir, 'android', 'gradle.properties'); // fs.writeFileSync( // gradle, // ` //${fs.readFileSync(gradle, 'utf-8')} // //# 4GB Heap Size //org.gradle.jvmargs=-Xmx4608m // `.trim(), // ); //}; const setAppIcon = (ctx: createContext) => { const { projectDir } = ctx; const assetsDir = path.resolve(projectDir, 'assets'); !fs.existsSync(assetsDir) && fs.mkdirSync(assetsDir); ['image', 'video', 'json', 'raw'].map((type: string) => { const dir = path.resolve(assetsDir, type); const gitkeep = path.resolve(dir, '.gitkeep'); !fs.existsSync(dir) && fs.mkdirSync(dir); fs.writeFileSync(gitkeep, ''); }); const appIcon = path.resolve(assetsDir, 'image', 'app-icon.png'); fs.copyFileSync(require.resolve('../assets/app-icon.png'), appIcon); const assetDeclarations = path.resolve(assetsDir, 'index.d.ts'); fs.writeFileSync( assetDeclarations, ` import { ImageSourcePropType } from 'react-native'; declare module '*.png' { export default ImageSourcePropType; } declare module '*.jpg' { export default ImageSourcePropType; } declare module '*.jpeg' { export default ImageSourcePropType; } declare module '*.gif' { export default ImageSourcePropType; } declare module '*.mp4' { export default unknown; } `.trim(), ); }; const createFileThunk = (root: string) => (f: readonly string[]): string => { return path.resolve(root, ...f); }; const hardhatOptions = async ( projectFile: (f: readonly string[]) => string, scriptFile: (f: readonly string[]) => string ): Promise<HardhatOptions> => { const hardhatAccounts = await Promise.all( [...Array(10)].map(async () => { const { privateKey } = await ethers.Wallet.createRandom(); return { privateKey, balance: '1000000000000000000000' }; // 1000 ETH }) ); return { hardhat: scriptFile(['hardhat.ts']), hardhatConfig: projectFile(['hardhat.config.js']), hardhatAccounts, } as HardhatOptions; }; const createBaseContext = async ( params: createParams ): Promise<createContext> => { const { name } = params; const projectDir = path.resolve(name); const scriptsDir = path.resolve(projectDir, 'scripts'); const testsDir = path.resolve(projectDir, '__tests__'); const projectFile = createFileThunk(projectDir); const scriptFile = createFileThunk(scriptsDir); const srcDir = path.resolve(projectDir, 'frontend'); return Object.freeze({ ...params, yarn: fs.existsSync(projectFile(['yarn.lock'])), hardhat: await hardhatOptions(projectFile, scriptFile), projectDir, scriptsDir, testsDir, srcDir, }); }; // TODO: Find a nice version. const shimProcessVersion = 'v9.40'; const injectShims = (ctx: createContext) => { const { projectDir } = ctx; fs.writeFileSync( path.resolve(projectDir, 'index.js'), ` /* eslint-disable eslint-comments/no-unlimited-disable */ /* eslint-disable */ // This file has been auto-generated by Ξ create-react-native-dapp Ξ. // Feel free to modify it, but please take care to maintain the exact // procedure listed between /* dapp-begin */ and /* dapp-end */, as // this will help persist a known template for future migrations. /* dapp-begin */ const { Platform, LogBox } = require('react-native'); if (Platform.OS !== 'web') { require('react-native-get-random-values'); LogBox.ignoreLogs( [ "Warning: The provided value 'ms-stream' is not a valid 'responseType'.", "Warning: The provided value 'moz-chunked-arraybuffer' is not a valid 'responseType'.", ], ); } if (typeof Buffer === 'undefined') { global.Buffer = require('buffer').Buffer; } global.btoa = global.btoa || require('base-64').encode; global.atob = global.atob || require('base-64').decode; process.version = '${shimProcessVersion}'; const { registerRootComponent, scheme } = require('expo'); const { default: App } = require('./frontend/App'); const { default: AsyncStorage } = require('@react-native-async-storage/async-storage'); const { withWalletConnect } = require('@walletconnect/react-native-dapp'); // registerRootComponent calls AppRegistry.registerComponent('main', () => App); // It also ensures that whether you load the app in the Expo client or in a native build, // the environment is set up appropriately registerRootComponent(withWalletConnect(App, { redirectUrl: Platform.OS === 'web' ? window.location.origin : \`\${scheme}://\`, storageOptions: { asyncStorage: AsyncStorage, }, })); /* dapp-end */ `.trim() ); }; const createScripts = (ctx: createContext) => { const { scriptsDir } = ctx; !fs.existsSync(scriptsDir) && fs.mkdirSync(scriptsDir); const postinstall = path.resolve(scriptsDir, 'postinstall.ts'); const android = path.resolve(scriptsDir, 'android.ts'); const ios = path.resolve(scriptsDir, 'ios.ts'); const web = path.resolve(scriptsDir, 'web.ts'); fs.writeFileSync( postinstall, ` import 'dotenv/config'; import * as child_process from 'child_process'; // Uncommment to rename the application binaries on postinstall. //const {APP_DISPLAY_NAME} = process.env; //child_process.execSync( // \`npx react-native-rename \${APP_DISPLAY_NAME}\`, // {stdio: 'inherit'} //); // Uncommment to regenerate the application icon on postinstall. //child_process.execSync( // 'npx app-icon generate -i assets/image/app-icon.png --platforms=android,ios', // {stdio: 'inherit'} //); child_process.execSync('npx patch-package', { stdio: 'inherit' }); // Uncomment to reinstall pods on postinstall. // import {macos} from 'platform-detect'; // if (macos) { // child_process.execSync('npx pod-install', { stdio: 'inherit' }); // } `.trim() ); fs.writeFileSync( android, ` import 'dotenv/config'; import * as child_process from 'child_process'; import * as appRootPath from 'app-root-path'; import * as chokidar from 'chokidar'; const opts: child_process.ExecSyncOptions = { cwd: \`\${appRootPath}\`, stdio: 'inherit' }; chokidar.watch('contracts').on('all', () => { child_process.execSync('npx hardhat compile', opts); }); child_process.execSync('npx kill-port ${port}', opts); child_process.execSync('adb reverse tcp:${port} tcp:${port}', opts); child_process.execSync('npx hardhat node --hostname 0.0.0.0 & expo run:android &', opts); `.trim(), ); fs.writeFileSync( ios, ` import 'dotenv/config'; import * as child_process from 'child_process'; import * as appRootPath from 'app-root-path'; import * as chokidar from 'chokidar'; const opts: child_process.ExecSyncOptions = { cwd: \`\${appRootPath}\`, stdio: 'inherit' }; chokidar.watch('contracts').on('all', () => { child_process.execSync('npx hardhat compile', opts); }); child_process.execSync('npx kill-port ${port}', opts); child_process.execSync('npx hardhat node --hostname 0.0.0.0 & expo run:ios &', opts); `.trim(), ); fs.writeFileSync( web, ` import 'dotenv/config'; import * as child_process from 'child_process'; import * as appRootPath from 'app-root-path'; import * as chokidar from 'chokidar'; const opts: child_process.ExecSyncOptions = { cwd: \`\${appRootPath}\`, stdio: 'inherit' }; chokidar.watch('contracts').on('all', () => { child_process.execSync('npx hardhat compile', opts); }); child_process.execSync('npx kill-port 8545', opts); child_process.execSync('expo web & npx hardhat node --hostname 0.0.0.0 &', opts); `.trim(), ); }; const getAllEnvVariables = (ctx: createContext): EnvVariables => { const { hardhat: { hardhatAccounts } } = ctx; return [ ['APP_DISPLAY_NAME', 'string', `${ctx.name}`], ['HARDHAT_PORT', 'string', `${port}`], ['HARDHAT_PRIVATE_KEY', 'string', hardhatAccounts[0].privateKey], ]; }; const shouldPrepareTypeRoots = (ctx: createContext) => { const stringsToRender = getAllEnvVariables(ctx).map( ([name, type]: EnvVariable) => ` export const ${name}: ${type};` ); return fs.writeFileSync( path.resolve(ctx.projectDir, 'index.d.ts'), ` declare module '@env' { ${stringsToRender.join('\n')} } `.trim() ); }; const shouldPrepareSpelling = (ctx: createContext) => fs.writeFileSync( path.resolve(ctx.projectDir, '.cspell.json'), prettyStringify({ words: ["bytecode", "dapp"], }), ); const shouldPrepareTsc = (ctx: createContext) => { fs.writeFileSync( path.resolve(ctx.projectDir, 'tsconfig.json'), prettyStringify({ compilerOptions: { allowSyntheticDefaultImports: true, jsx: 'react-native', lib: ['dom', 'esnext'], moduleResolution: 'node', noEmit: true, skipLibCheck: true, resolveJsonModule: true, typeRoots: ['index.d.ts'], types: ['node', 'jest'], }, include: ['**/*.ts', '**/*.tsx'], exclude: [ 'node_modules', 'babel.config.js', 'metro.config.js', 'jest.config.js', '**/*.test.tsx', '**/*.test.ts', '**/*.spec.tsx', '**/*.spec.ts', ], }) ); }; const preparePackage = (ctx: createContext) => injectFlattenedJsonToFile( path.resolve(ctx.projectDir, 'package.json'), { homepage: 'https://cawfree.github.io/create-react-native-dapp', license: 'MIT', contributors: [ { name: '@cawfree', url: "https://github.com/cawfree" }, ], keywords: [ 'react', 'react-native', 'blockchain', 'dapp', 'ethereum', 'web3', 'starter', 'react-native-web', ], // scripts 'scripts.audit': `${ctx.yarn ? '' : 'npm_config_yes=true '}npx yarn-audit-fix`, 'scripts.postinstall': 'node_modules/.bin/ts-node scripts/postinstall', 'scripts.test': 'npx hardhat test && jest', 'scripts.android': 'node_modules/.bin/ts-node scripts/android', 'scripts.ios': 'node_modules/.bin/ts-node scripts/ios', 'scripts.web': 'node_modules/.bin/ts-node scripts/web', 'scripts.web:deploy': 'expo build:web && gh-pages -d web-build', // dependencies 'dependencies.@react-native-async-storage/async-storage': '1.13.4', 'dependencies.@walletconnect/react-native-dapp': '1.6.1', 'dependencies.react-native-svg': '9.6.4', 'dependencies.base-64': '1.0.0', 'dependencies.buffer': '6.0.3', 'dependencies.node-libs-browser': '2.2.1', 'dependencies.path-browserify': '0.0.0', 'dependencies.react-native-crypto': '2.2.0', 'dependencies.react-native-dotenv': '2.4.3', 'dependencies.react-native-localhost': '1.0.0', 'dependencies.react-native-get-random-values': '1.5.0', 'dependencies.react-native-stream': '0.1.9', 'dependencies.web3': '1.3.1', 'devDependencies.@babel/core': '7.15.5', 'devDependencies.@babel/plugin-proposal-private-property-in-object': '7.15.4', 'devDependencies.@babel/preset-env': '7.15.6', 'devDependencies.@babel/preset-typescript': '7.15.0', 'devDependencies.app-root-path': '3.0.0', 'devDependencies.babel-jest': '27.2.3', 'devDependencies.chokidar': '3.5.1', 'devDependencies.commitizen': '4.2.3', 'devDependencies.cz-conventional-changelog': '^3.2.0', 'devDependencies.dotenv': '8.2.0', 'devDependencies.enzyme': '3.11.0', 'devDependencies.enzyme-adapter-react-16': '1.15.6', 'devDependencies.husky': '4.3.8', 'devDependencies.prettier': '2.2.1', 'devDependencies.platform-detect': '3.0.1', 'devDependencies.@typescript-eslint/eslint-plugin': '^4.0.1', 'devDependencies.@typescript-eslint/parser': '^4.0.1', 'devDependencies.@openzeppelin/contracts': '^4.3.0', 'devDependencies.eslint': '^7.8.0', 'devDependencies.eslint-config-prettier': '^6.11.0', 'devDependencies.eslint-plugin-eslint-comments': '^3.2.0', 'devDependencies.eslint-plugin-functional': '^3.0.2', 'devDependencies.eslint-plugin-import': '^2.22.0', 'devDependencies.eslint-plugin-react': '7.22.0', 'devDependencies.eslint-plugin-react-native': '3.10.0', 'devDependencies.lint-staged': '10.5.3', 'devDependencies.@types/node': '14.14.22', "devDependencies.@types/jest": '^26.0.20', 'devDependencies.hardhat': '2.0.6', 'devDependencies.@nomiclabs/hardhat-ethers': '^2.0.1', 'devDependencies.@nomiclabs/hardhat-waffle': '^2.0.1', 'devDependencies.chai': '^4.2.0', 'devDependencies.ethereum-waffle': '^3.2.1', 'devDependencies.gh-pages': '^3.2.3', 'devDependencies.jest': '26.6.3', 'devDependencies.react-test-renderer': '17.0.1', 'devDependencies.ts-node': '9.1.1', // react-native 'react-native.stream': 'react-native-stream', 'react-native.crypto': 'react-native-crypto', 'react-native.path': 'path-browserify', 'react-native.process': 'node-libs-browser/mock/process', // jest 'jest.preset': 'react-native', 'jest.testMatch': ["**/__tests__/frontend/**/*.[jt]s?(x)"], 'jest.transformIgnorePatterns': ['node_modules/(?!@ngrx|(?!deck.gl)|ng-dynamic)'] }, { config: { commitizen: { path: './node_modules/cz-conventional-changelog' } }, husky: { hooks: { 'prepare-commit-msg': 'exec < /dev/tty && git cz --hook', 'pre-commit': 'lint-staged && tsc', 'pre-push': 'test' } }, 'lint-staged': { '*.{ts,tsx,js,jsx}': "eslint --fix --ext '.ts,.tsx,.js,.jsx' -c .eslintrc.json", }, } ); const shouldPrepareMetro = (ctx: createContext) => fs.writeFileSync( path.resolve(ctx.projectDir, 'metro.config.js'), ` const extraNodeModules = require('node-libs-browser'); module.exports = { resolver: { extraNodeModules, }, transformer: { assetPlugins: ['expo-asset/tools/hashAssetFiles'], }, }; `.trim() ); const shouldPrepareBabel = (ctx: createContext) => fs.writeFileSync( path.resolve(ctx.projectDir, 'babel.config.js'), ` module.exports = function(api) { api.cache(true); return { presets: [ 'babel-preset-expo', ['@babel/preset-env', {targets: {node: 'current'}}], '@babel/preset-typescript', ], plugins: [ ['@babel/plugin-proposal-private-property-in-object', {loose: true}], ['module:react-native-dotenv'], ], }; }; `.trim() ); const shouldPrepareEslint = (ctx: createContext) => fs.writeFileSync( path.resolve(ctx.projectDir, '.eslintrc.json'), prettyStringify({ root: true, parser: '@typescript-eslint/parser', env: { es6: true }, ignorePatterns: [ 'node_modules', 'build', 'coverage', 'babel.config.js', 'metro.config.js', 'hardhat.config.js', '__tests__/contracts', ], plugins: ['import', 'eslint-comments', 'functional', 'react', 'react-native'], extends: [ 'eslint:recommended', 'plugin:eslint-comments/recommended', 'plugin:@typescript-eslint/recommended', 'plugin:import/typescript', 'plugin:functional/lite', 'prettier', 'prettier/@typescript-eslint', ], globals: { // TODO: Enable support in RN for BigInteger. //BigInt: true, console: true, __DEV__: true, }, rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', 'eslint-comments/disable-enable-pair': [ 'error', { allowWholeFile: true }, ], 'eslint-comments/no-unused-disable': 'error', 'import/order': [ 'error', { 'newlines-between': 'always', alphabetize: { order: 'asc' } }, ], 'sort-imports': [ 'error', { ignoreDeclarationSort: true, ignoreCase: true }, ], 'sort-keys': [ 'error', 'asc', { 'caseSensitive': true, 'natural': false, 'minKeys': 2, }, ], 'react-native/no-unused-styles': 2, 'react-native/split-platform-components': 2, 'react-native/no-inline-styles': 2, 'react-native/no-color-literals': 2, 'react-native/no-raw-text': 2, 'react-native/no-single-element-style-arrays': 2, }, parserOptions: { ecmaFeatures: { jsx: true, }, }, }) ); const shouldWriteEnv = (ctx: createContext) => { const lines = getAllEnvVariables(ctx).map( // eslint-disable-next-line @typescript-eslint/no-unused-vars ([name, _type, value]) => `${name}=${value}` ); const env = path.resolve(ctx.projectDir, '.env'); const example = path.resolve(ctx.projectDir, '.env.example'); fs.writeFileSync(env, `${lines.join('\n')}\n`); fs.copyFileSync(env, example); }; const shouldInstall = (ctx: createContext) => execSync( `${ctx.yarn ? 'yarn' : 'npm i'}`, { stdio: 'inherit', cwd: `${ctx.projectDir}`, } ); const getExampleContract = () => ` // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "hardhat/console.sol"; contract Hello { string defaultSuffix; constructor() { defaultSuffix = '!'; } function sayHello(string memory name) public view returns(string memory) { console.log("Saying hello to %s!", msg.sender); return string(abi.encodePacked("Welcome to ", name, defaultSuffix)); } } `.trim(); const shouldPrepareExample = (ctx: createContext) => { const { projectDir, testsDir, srcDir, hardhat: { hardhatConfig, hardhatAccounts, }, } = ctx; const contracts = path.resolve(projectDir, 'contracts'); const patches = path.resolve(projectDir, 'patches'); !fs.existsSync(contracts) && fs.mkdirSync(contracts); !fs.existsSync(patches) && fs.mkdirSync(patches); !fs.existsSync(testsDir) && fs.mkdirSync(testsDir); const contractsTestDir = path.resolve(testsDir, 'contracts'); const frontendTestDir = path.resolve(testsDir, 'frontend'); fs.mkdirSync(contractsTestDir); fs.mkdirSync(frontendTestDir); fs.writeFileSync(path.resolve(contractsTestDir, '.gitkeep'), ''); fs.writeFileSync(path.resolve(frontendTestDir, '.gitkeep'), ''); const contractTest = path.resolve(contractsTestDir, 'Hello.test.js'); const frontendTest = path.resolve(frontendTestDir, 'App.test.tsx'); fs.writeFileSync( contractTest, ` const { expect } = require('chai'); describe("Hello", function() { it("Should return the default greeting", async function() { const Hello = await ethers.getContractFactory("Hello"); const hello = await Hello.deploy(); await hello.deployed(); expect(await hello.sayHello("React Native")).to.equal("Welcome to React Native!"); expect(await hello.sayHello("Web3")).to.equal("Welcome to Web3!"); }); }); ` ); fs.writeFileSync( frontendTest, ` import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import React from 'react'; import App from '../../frontend/App'; Enzyme.configure({ adapter: new Adapter() }); test('renders correctly', () => { const wrapper = Enzyme.shallow(<App />); expect(wrapper.find({ testID: 'tid-message'}).contains('Loading...')).toBe(true); }); `.trim(), ); const contract = path.resolve(contracts, 'Hello.sol'); fs.writeFileSync(contract, getExampleContract()); fs.writeFileSync( hardhatConfig, ` /** * @type import('hardhat/config').HardhatUserConfig */ require("@nomiclabs/hardhat-waffle"); require("dotenv/config"); const { HARDHAT_PORT } = process.env; module.exports = { solidity: "0.7.3", networks: { localhost: { url: \`http://127.0.0.1:\${HARDHAT_PORT}\` }, hardhat: { accounts: ${JSON.stringify(hardhatAccounts)} }, }, paths: { sources: './contracts', tests: './__tests__/contracts', cache: './cache', artifacts: './artifacts', }, }; `.trim() ); !fs.existsSync(srcDir) && fs.mkdirSync(srcDir); fs.writeFileSync( path.resolve(srcDir, 'App.tsx'), ` import { HARDHAT_PORT, HARDHAT_PRIVATE_KEY } from '@env'; import { useWalletConnect } from '@walletconnect/react-native-dapp'; import React from 'react'; import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import localhost from 'react-native-localhost'; import Web3 from 'web3'; import Hello from '../artifacts/contracts/Hello.sol/Hello.json'; const styles = StyleSheet.create({ center: { alignItems: 'center', justifyContent: 'center' }, // eslint-disable-next-line react-native/no-color-literals white: { backgroundColor: 'white' }, }); const shouldDeployContract = async (web3, abi, data, from: string) => { const deployment = new web3.eth.Contract(abi).deploy({ data }); const gas = await deployment.estimateGas(); const { options: { address: contractAddress }, } = await deployment.send({ from, gas }); return new web3.eth.Contract(abi, contractAddress); }; export default function App(): JSX.Element { const connector = useWalletConnect(); const [message, setMessage] = React.useState<string>('Loading...'); const web3 = React.useMemo( () => new Web3(new Web3.providers.HttpProvider(\`http://\${localhost}:\${HARDHAT_PORT}\`)), [HARDHAT_PORT] ); React.useEffect(() => { void (async () => { const { address } = await web3.eth.accounts.privateKeyToAccount(HARDHAT_PRIVATE_KEY); const contract = await shouldDeployContract( web3, Hello.abi, Hello.bytecode, address ); setMessage(await contract.methods.sayHello('React Native').call()); })(); }, [web3, shouldDeployContract, setMessage, HARDHAT_PRIVATE_KEY]); const connectWallet = React.useCallback(() => { return connector.connect(); }, [connector]); const signTransaction = React.useCallback(async () => { try { await connector.signTransaction({ data: '0x', from: '0xbc28Ea04101F03aA7a94C1379bc3AB32E65e62d3', gas: '0x9c40', gasPrice: '0x02540be400', nonce: '0x0114', to: '0x89D24A7b4cCB1b6fAA2625Fe562bDd9A23260359', value: '0x00', }); } catch (e) { console.error(e); } }, [connector]); const killSession = React.useCallback(() => { return connector.killSession(); }, [connector]); return ( <View style={[StyleSheet.absoluteFill, styles.center, styles.white]}> <Text testID="tid-message">{message}</Text> {!connector.connected && ( <TouchableOpacity onPress={connectWallet}> <Text>Connect a Wallet</Text> </TouchableOpacity> )} {!!connector.connected && ( <> <TouchableOpacity onPress={signTransaction}> <Text>Sign a Transaction</Text> </TouchableOpacity> <TouchableOpacity onPress={killSession}> <Text>Kill Session</Text> </TouchableOpacity> </> )} </View> ); } `.trim() ); const orig = path.resolve(projectDir, 'App.tsx'); fs.existsSync(orig) && fs.unlinkSync(orig); execSync(`npx hardhat compile`, { cwd: `${projectDir}`, stdio: 'inherit' }); }; const getHardhatGitIgnore = (): string | null => { return ` # Hardhat artifacts/ cache/ `.trim(); }; const shouldPrepareGitignore = (ctx: createContext) => { const { projectDir } = ctx; const lines = [getHardhatGitIgnore()].filter((e) => !!e) as readonly string[]; const gitignore = path.resolve(projectDir, '.gitignore'); fs.writeFileSync( gitignore, ` ${fs.readFileSync(gitignore, 'utf-8')} # Environment Variables (Store safe defaults in .env.example!) .env # Jest .snap # Package Managers ${ctx.yarn ? 'package-lock.json' : 'yarn.lock'} ${lines.join('\n\n')} `.trim() ); }; const getScriptCommandString = (ctx: createContext, str: string) => chalk.white.bold`${ctx.yarn ? 'yarn' : 'npm run-script'} ${str}`; export const getSuccessMessage = (ctx: createContext): string => { return ` ${chalk.green`✔`} Successfully integrated Web3 into React Native! To compile and run your project in development, execute one of the following commands: - ${getScriptCommandString(ctx, `ios`)} - ${getScriptCommandString(ctx, `android`)} - ${getScriptCommandString(ctx, `web`)} `.trim(); }; export const create = async (params: createParams): Promise<createResult> => { createBaseProject(params); const ctx = await createBaseContext(params); if (!fs.existsSync(ctx.projectDir)) { return Object.freeze({ ...ctx, status: CreationStatus.FAILURE, message: `Failed to resolve project directory.`, }); } setAppIcon(ctx); //ejectExpoProject(ctx); injectShims(ctx); createScripts(ctx); preparePackage(ctx); shouldPrepareMetro(ctx); shouldPrepareBabel(ctx); shouldPrepareEslint(ctx); shouldPrepareTypeRoots(ctx); shouldPrepareSpelling(ctx); shouldPrepareTsc(ctx); shouldPrepareGitignore(ctx); shouldWriteEnv(ctx); shouldInstall(ctx); shouldPrepareExample(ctx); return Object.freeze({ ...ctx, status: CreationStatus.SUCCESS, message: getSuccessMessage(ctx), }); };
the_stack
import { useRef, useContext, useEffect, useMemo, useState } from 'react'; import type { FormInstance } from 'antd'; import { Button, Collapse, Form, Popconfirm } from 'antd'; import classNames from 'classnames'; import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'; import { DATA_SOURCE_ENUM, formItemLayout } from '@/constant'; import stream from '@/api'; import { isHaveSchema, isHaveTableColumn, isHaveTableList, isCacheExceptLRU } from '@/utils/is'; import molecule from '@dtinsight/molecule'; import type { IDataColumnsProps, IDataSourceUsedInSyncProps, IFlinkSideProps } from '@/interface'; import DimensionForm from './form'; import type { IRightBarComponentProps } from '@/services/rightBarService'; import { FormContext } from '@/services/rightBarService'; const { Panel } = Collapse; const DEFAULT_INPUT_VALUE: Partial<IFlinkSideProps> = { type: DATA_SOURCE_ENUM.MYSQL, columns: [], sourceId: undefined, table: undefined, tableName: undefined, primaryKey: undefined, hbasePrimaryKey: undefined, hbasePrimaryKeyType: undefined, errorLimit: undefined, esType: undefined, index: undefined, parallelism: 1, cache: 'LRU', cacheSize: 10000, cacheTTLMs: 60000, asyncPoolSize: 5, }; /** * 表单收集的字段 */ export const NAME_FIELD = 'panelColumn'; interface IFormFieldProps { [NAME_FIELD]: Partial<IFlinkSideProps>[]; } export default function FlinkDimensionPanel({ current }: IRightBarComponentProps) { const { form } = useContext(FormContext) as { form?: FormInstance<IFormFieldProps> }; const [panelActiveKey, setPanelKey] = useState<string[]>([]); // 数据源下拉列表,用 key 值缓存结果 const [dataSourceOptions, setDataSourceOptions] = useState< Record<string, IDataSourceUsedInSyncProps[]> >({}); /** * 表下拉列表,以 soureceId-schema 拼接作 key 值,后以 searchKey 作为 key 值,最后是搜索结果 * { * [`${sourceId}-${schema}`]: {[`${searchKey}`]: string[]}} * } */ const [tableOptions, setTableOptions] = useState<Record<string, Record<string, string[]>>>({}); // 表字段列下拉列表 const [columnsOptions, setColOptions] = useState<Record<string, IDataColumnsProps[]>>({}); // 用于表示添加或删除的标志位 const isAddOrRemove = useRef(false); const getTableColumns = (sourceId: number, tableName: string, schema = '') => { if (!sourceId || !tableName) { return; } const uniqKey = `${sourceId}-${tableName}-${schema}`; if (!columnsOptions[uniqKey]) { stream .getStreamTableColumn({ sourceId, tableName, schema, flinkVersion: current?.tab?.data?.componentVersion, }) .then((v) => { if (v.code === 1) { setColOptions((options) => { const next = options; next[uniqKey] = v.data; return { ...next }; }); } }); } }; /** * 获取Schema列表 * @deprecated 暂时没有数据源会有请求 schema 列表 */ const getSchemaData = async () => {}; const getTypeOriginData = (type: DATA_SOURCE_ENUM) => { if (!dataSourceOptions[type]) { stream.getTypeOriginData({ type }).then((v) => { if (v.code === 1) { setDataSourceOptions((options) => { const next = options; next[type] = v.data; return { ...next }; }); } }); } }; // 获取表 const getTableType = async ( type: DATA_SOURCE_ENUM, sourceId: number, schema?: string, searchKey?: string, ) => { const uniqKey = `${sourceId}-${schema}`; // postgresql kingbasees8 schema必填处理 const disableReq = (type === DATA_SOURCE_ENUM.POSTGRESQL || type === DATA_SOURCE_ENUM.KINGBASE8) && !schema; if (disableReq) { return; } stream .listTablesBySchema({ sourceId, schema: schema || '', isSys: false, searchKey, }) .then((res) => { if (res.code === 1) { setTableOptions((options) => { const next = options; if (next[uniqKey]) { next[uniqKey][searchKey || ''] = res.data; } else { next[uniqKey] = { [searchKey || '']: res.data }; } return { ...next }; }); } }); }; const handleSyncFormToTab = () => { const side = form?.getFieldsValue()[NAME_FIELD]; // 将表单的值保存至 tab 中 molecule.editor.updateTab({ id: current!.tab!.id, data: { ...current!.tab!.data, side, }, }); }; const handleFormValuesChange = (changedValues: IFormFieldProps, values: IFormFieldProps) => { if (isAddOrRemove.current) { isAddOrRemove.current = false; handleSyncFormToTab(); return; } // 当前正在修改的数据索引 const changeIndex = changedValues[NAME_FIELD].findIndex((col) => col); const checkedKeys = Object.keys(changedValues[NAME_FIELD][changeIndex]); if (checkedKeys.includes('type')) { const value = changedValues[NAME_FIELD][changeIndex].type; getTypeOriginData(value!); // reset all fields const nextValue = { ...values }; nextValue[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: value, cache: isCacheExceptLRU(value) ? 'ALL' : 'LRU', }; form?.setFieldsValue(nextValue); } if (checkedKeys.includes('sourceId')) { const value = changedValues[NAME_FIELD][changeIndex].sourceId; const nextValue = { ...values }; // reset fields nextValue[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: nextValue[NAME_FIELD][changeIndex].type, sourceId: value, cache: isCacheExceptLRU(nextValue[NAME_FIELD][changeIndex].type) ? 'ALL' : 'LRU', }; form?.setFieldsValue(nextValue); const panel = nextValue[NAME_FIELD][changeIndex]; if (isHaveTableList(panel.type)) { getTableType(panel.type!, panel.sourceId!, panel.schema); if (isHaveSchema(panel.type)) { getSchemaData(); } } } if (checkedKeys.includes('schema')) { const value = changedValues[NAME_FIELD][changeIndex].schema; const nextValue = { ...values }; // reset fields nextValue[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: nextValue[NAME_FIELD][changeIndex].type, sourceId: nextValue[NAME_FIELD][changeIndex].sourceId, customParams: nextValue[NAME_FIELD][changeIndex].customParams, schema: value, cache: isCacheExceptLRU(nextValue[NAME_FIELD][changeIndex].type) ? 'ALL' : 'LRU', }; form?.setFieldsValue(nextValue); const panel = nextValue[NAME_FIELD][changeIndex]; if (isHaveTableList(panel.type)) { getTableType(panel.type!, panel.sourceId!, panel.schema); } } if (checkedKeys.includes('table')) { const value = changedValues[NAME_FIELD][changeIndex].table; const nextValue = { ...values }; // reset fields nextValue[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: nextValue[NAME_FIELD][changeIndex].type, sourceId: nextValue[NAME_FIELD][changeIndex].sourceId, customParams: nextValue[NAME_FIELD][changeIndex].customParams, schema: nextValue[NAME_FIELD][changeIndex].schema, table: value, cache: isCacheExceptLRU(nextValue[NAME_FIELD][changeIndex].type) ? 'ALL' : 'LRU', }; form?.setFieldsValue(nextValue); const panel = nextValue[NAME_FIELD][changeIndex]; if (isHaveTableColumn(panel.type)) { getTableColumns(panel.sourceId!, panel.table!, panel.schema); } } handleSyncFormToTab(); }; const handlePanelChanged = (type: 'add' | 'delete', index?: string) => { return new Promise<void>((resolve) => { switch (type) { case 'add': { isAddOrRemove.current = true; getTypeOriginData(DEFAULT_INPUT_VALUE.type!); resolve(); break; } case 'delete': { isAddOrRemove.current = true; setPanelKey((keys) => { const idx = keys.indexOf(index!); if (idx !== -1) { keys.splice(idx, 1); } return keys.concat(); }); resolve(); break; } default: break; } }); }; useEffect(() => { current?.tab?.data?.side?.forEach((item: IFlinkSideProps) => { if (item.type) { getTypeOriginData(item.type); } if (item.type && item.sourceId) { getTableType(item.type, item.sourceId, item.schema); } if (item.sourceId && item.table) { getTableColumns(item.sourceId, item.table, item.schema); } }); }, [current]); const initialValues = useMemo<IFormFieldProps>(() => { return { [NAME_FIELD]: (current?.tab?.data?.side as IFlinkSideProps[]) || [], }; }, []); return ( <molecule.component.Scrollable> <div className="panel-content"> <Form<IFormFieldProps> {...formItemLayout} form={form} onValuesChange={handleFormValuesChange} initialValues={initialValues} > <Form.List name={NAME_FIELD}> {(fields, { add, remove }) => ( <> <Collapse activeKey={panelActiveKey} bordered={false} onChange={(key) => setPanelKey(key as string[])} destroyInactivePanel > {fields.map((field, index) => { const col = form?.getFieldValue(NAME_FIELD)[index] || {}; return ( <Panel header={ <div className="input-panel-title"> <span>{` 维表 ${index + 1} ${ col.table ? `(${col.table})` : '' }`}</span> </div> } key={field.key.toString()} extra={ <Popconfirm placement="topLeft" title="你确定要删除此维表吗?" onConfirm={() => handlePanelChanged( 'delete', field.key.toString(), ).then(() => { remove(field.name); }) } {...{ onClick: (e: any) => { e.stopPropagation(); }, }} > <DeleteOutlined className={classNames('title-icon')} /> </Popconfirm> } style={{ position: 'relative' }} className="input-panel" > <DimensionForm index={index} sourceOptions={dataSourceOptions[col.type!]} tableOptions={ tableOptions[ `${col.sourceId}-${col.schema}` ] } columnsOptions={ columnsOptions[ `${col.sourceId}-${col.table}-${ col.schema || '' }` ] } onTableSearch={getTableType} /> </Panel> ); })} </Collapse> <Button size="large" block onClick={() => handlePanelChanged('add').then(() => add({ ...DEFAULT_INPUT_VALUE }), ) } icon={<PlusOutlined />} > <span>添加维表</span> </Button> </> )} </Form.List> </Form> </div> </molecule.component.Scrollable> ); }
the_stack
declare const map: AMap.Map; declare const div: HTMLElement; declare const lnglat: AMap.LngLat; declare const lnglatTuple: [number, number]; declare const bounds: AMap.Bounds; declare const polygon: AMap.Polygon; declare const lang: AMap.Lang; // $ExpectType PlaceSearch const placeSearch = new AMap.PlaceSearch(); // $ExpectType PlaceSearch new AMap.PlaceSearch({}); // $ExpectType PlaceSearch new AMap.PlaceSearch({ city: '深圳', citylimit: true, children: 1, type: '餐饮服务', lang: 'zh_cn', pageSize: 10, pageIndex: 10, extensions: 'all', map, panel: div, showCover: true, renderStyle: 'newpc', autoFitView: true }); // $ExpectType void placeSearch.search('keyword', (status, result) => { const temp: 'error' | 'complete' | 'no_data' = status; // $ExpectType string | SearchResult result; if (typeof result !== 'string') { // $ExpectType string result.info; // $ExpectType PoiList result.poiList; // $ExpectType string[] | undefined result.keywordList; // $ExpectType CityInfo[] | undefined result.cityList; const poiList = result.poiList; // $ExpectType number poiList.pageIndex; // $ExpectType number poiList.pageSize; // $ExpectType number poiList.count; const poi = poiList.pois[0]; // $ExpectType string poi.address; // $ExpectType number poi.distance; // $ExpectType string poi.id; // $ExpectType LngLat | null poi.location; // $ExpectType string poi.name; // $ExpectType string poi.shopinfo; // $ExpectType string poi.tel; // $ExpectType string poi.type; if ('website' in poi) { // $ExpectType string poi.adcode; // $ExpectType string poi.adname; // $ExpectType string poi.citycode; // $ExpectType string poi.cityname; // $ExpectType boolean poi.discount; // $ExpectType string poi.email; // $ExpectType LngLat | null poi.entr_location; // $ExpectType LngLat | null poi.exit_location; // $ExpectType boolean poi.groupbuy; if (poi.indoor_map) { const indoorData = poi.indoor_data; // $ExpectType string indoorData.cpid; // $ExpectType string indoorData.floor; // $ExpectType string indoorData.truefloor; } poi.pcode; // $ExpectType PoiPhoto[] poi.photos; // $ExpectType string poi.pname; // $ExpectType string poi.postcode; // $ExpectType string poi.website; const photo = poi.photos[0]; // $ExpectType string photo.title; // $ExpectType string photo.url; // $ExpectType Groupbuy[] | undefined poi.groupbuys; if (poi.groupbuys) { const groupbuy = poi.groupbuys[0]; // $ExpectType string groupbuy.title; // $ExpectType string groupbuy.type_code; // $ExpectType string groupbuy.type; // $ExpectType string groupbuy.detail; // $ExpectType string groupbuy.stime; // $ExpectType string groupbuy.etime; // $ExpectType number groupbuy.count; // $ExpectType number groupbuy.sold_num; // $ExpectType number groupbuy.original_price; // $ExpectType number groupbuy.groupbuy_price; // $ExpectType number groupbuy.discount; // $ExpectType string groupbuy.ticket_address; // $ExpectType string groupbuy.ticket_tel; // $ExpectType PoiPhoto[] groupbuy.photos; // $ExpectType string groupbuy.url; // $ExpectType string groupbuy.provider; } // $ExpectType Discount[] | undefined poi.discounts; if (poi.discounts) { const discount = poi.discounts[0]; // $ExpectType string discount.title; // $ExpectType string discount.detail; // $ExpectType string discount.start_time; // $ExpectType string discount.end_time; // $ExpectType number discount.sold_num; // $ExpectType PoiPhoto[] discount.photos; // $ExpectType string discount.url; // $ExpectType string discount.provider; } if (poi.deep_type === 'CINEMA') { // $ExpectType Cinema const cinema = poi.cinema; // $ExpectType string cinema.intro; // $ExpectType string cinema.rating; // $ExpectType string cinema.deep_src; // $ExpectType string cinema.parking; // $ExpectType string cinema.opentime_GDF; // $ExpectType string cinema.opentime; // $ExpectType PoiPhoto[] cinema.photos; } if (poi.deep_type === 'DINING') { // $ExpectType Dining const dining = poi.dining; // $ExpectType string dining.cuisines; // $ExpectType string dining.tag; // $ExpectType string dining.intro; // $ExpectType string dining.rating; // $ExpectType string dining.cp_rating; // $ExpectType string dining.deep_src; // $ExpectType string dining.taste_rating; // $ExpectType string dining.environment_rating; // $ExpectType string dining.service_rating; // $ExpectType string dining.cost; // $ExpectType string dining.recommend; // $ExpectType string dining.atmosphere; // $ExpectType string dining.ordering_wap_url; // $ExpectType string dining.ordering_web_url; // $ExpectType string dining.ordering_app_url; // $ExpectType string dining.opentime_GDF; // $ExpectType string dining.opentime; // $ExpectType string dining.addition; // $ExpectType PoiPhoto[] dining.photos; } if (poi.deep_type === 'SCENIC') { // $ExpectType Scenic const scenic = poi.scenic; // $ExpectType string scenic.intro; // $ExpectType string scenic.rating; // $ExpectType string scenic.deep_src; // $ExpectType string scenic.level; // $ExpectType string scenic.price; // $ExpectType string scenic.season; // $ExpectType string scenic.recommend; // $ExpectType string scenic.theme; // $ExpectType string scenic.ordering_wap_url; // $ExpectType string scenic.ordering_web_url; // $ExpectType string scenic.opentime_GDF; // $ExpectType string scenic.opentime; // $ExpectType PoiPhoto[] scenic.photos; } if (poi.deep_type === 'HOTEL') { // $ExpectType Hotel const hotel = poi.hotel; // $ExpectType string hotel.rating; // $ExpectType string hotel.star; // $ExpectType string hotel.intro; // $ExpectType string hotel.lowest_price; // $ExpectType string hotel.faci_rating; // $ExpectType string hotel.health_rating; // $ExpectType string hotel.environment_rating; // $ExpectType string hotel.service_rating; // $ExpectType string hotel.traffic; // $ExpectType string hotel.addition; // $ExpectType string hotel.deep_src; // $ExpectType PoiPhoto[] hotel.photos; } } if (result.cityList) { const city = result.cityList[0]; // $ExpectType string city.adcode; // $ExpectType string city.citycode; // $ExpectType number city.count; // $ExpectType string city.name; } } else { // $ExpectType string result; } }); // $ExpectType void placeSearch.searchNearBy('keyword', lnglat, 10, (status, result) => { const temp: 'error' | 'complete' | 'no_data' = status; // $ExpectType string | SearchResult result; }); // $ExpectType void placeSearch.searchNearBy('keyword', lnglatTuple, 10, () => { }); // $ExpectType void placeSearch.searchInBounds('keyword', bounds, (status, result) => { const temp: 'error' | 'complete' | 'no_data' = status; // $ExpectType string | SearchResult result; }); // $ExpectType void placeSearch.searchInBounds('keyword', polygon, () => { }); // $ExpectType void placeSearch.getDetails('id', (status, result) => { const temp: 'error' | 'complete' | 'no_data' = status; // $ExpectType string | SearchResult result; }); // $ExpectType void placeSearch.setType('type'); // $ExpectType void placeSearch.setType(); // $ExpectType void placeSearch.setCityLimit(true); // $ExpectType void placeSearch.setCityLimit(); // $ExpectType void placeSearch.setPageIndex(1); // $ExpectType void placeSearch.setPageIndex(); // $ExpectType void placeSearch.setPageSize(1); // $ExpectType void placeSearch.setPageSize(); // $ExpectType void placeSearch.setCity('city'); // $ExpectType void placeSearch.setCity(); // $ExpectType void placeSearch.setLang(lang); // $ExpectType void placeSearch.setLang(); // $ExpectType "zh_cn" | "en" | "zh_en" | undefined || Lang | undefined placeSearch.getLang(); // $ExpectType void placeSearch.clear(); // $ExpectType void placeSearch.poiOnAMAP({ id: 'id', }); // $ExpectType void placeSearch.poiOnAMAP({ location: lnglat, id: 'id', name: 'name' }); // $ExpectType void placeSearch.detailOnAMAP({ id: 'id', }); // $ExpectType void placeSearch.detailOnAMAP({ location: lnglat, id: 'id', name: 'name' }); // $ExpectType void placeSearch.open(); // $ExpectType void placeSearch.close(); placeSearch.on('complete', (event: AMap.PlaceSearch.EventMap['complete']) => { // $ExpectType "complete" event.type; // $ExpectType string event.info; // $ExpectType PoiList event.poiList; // $ExpectType string[] | undefined event.keywordList; // $ExpectType CityInfo[] | undefined event.cityList; }); placeSearch.on('listElementClick', (event: AMap.PlaceSearch.EventMap['listElementClick']) => { // $ExpectType MouseEvent event.event; // $ExpectType string event.id; // $ExpectType number event.index; // $ExpectType Marker<any> event.marker; // $ExpectType HTMLLIElement event.listElement; }); placeSearch.on('markerClick', (event: AMap.PlaceSearch.EventMap['markerClick']) => { const markerEvent = event.event; // $ExpectType Marker<any> markerEvent.target; // $ExpectType string event.id; // $ExpectType number event.index; // $ExpectType Marker<any> event.marker; // $ExpectType HTMLLIElement event.listElement; });
the_stack
import { PdfColorSpace } from './../enum'; import { PdfColor } from './../pdf-color'; import { PdfBrush } from './pdf-brush'; import { PointF, Rectangle } from './../../drawing/pdf-drawing'; import { PdfDictionary} from '../../primitives/pdf-dictionary'; import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties'; import { PdfBoolean } from '../../primitives/pdf-boolean'; import { PdfArray } from './../../primitives/pdf-array'; import { PdfNumber } from './../../primitives/pdf-number'; import { PdfColorBlend } from './pdf-color-blend'; import { PdfBlend } from './pdf-blend'; import { PdfGradientBrush } from './pdf-gradient-brush'; import { PdfExtend , PdfLinearGradientMode, ShadingType} from './enum'; /** * `PdfLinearGradientBrush` Implements linear gradient brush by using PDF axial shading pattern. * @private */ export class PdfLinearGradientBrush extends PdfGradientBrush { //Fields /** * Local variable to store the point start. * @private */ private mPointStart: PointF; /** * Local variable to store the point end. */ private mPointEnd: PointF; /** * Local variable to store the colours. */ private mColours: PdfColor[]; /** * Local variable to store the colour Blend. */ private mColourBlend: PdfColorBlend; /** * Local variable to store the blend. * @private */ private mBlend: PdfBlend; /** * Local variable to store the boundaries. * @private */ private mBoundaries: Rectangle; /** * Local variable to store the dictionary properties. * @private */ private mDictionaryProperties : DictionaryProperties = new DictionaryProperties(); //Constructor /** * Initializes a new instance of the `PdfLinearGradientBrush` class. * @public */ public constructor(point1: PointF, point2: PointF, color1: PdfColor, color2: PdfColor) /** * Initializes a new instance of the `PdfLinearGradientBrush` class. * @public */ public constructor(rect: Rectangle, color1: PdfColor, color2: PdfColor, mode: PdfLinearGradientMode) /** * Initializes a new instance of the `PdfLinearGradientBrush` class. * @public */ public constructor(rect: Rectangle, color1: PdfColor, color2: PdfColor, angle: number) /** * Initializes a new instance of the `PdfLinearGradientBrush` class. * @public */ /* tslint:disable-next-line:max-line-length */ public constructor(arg1: Rectangle|PdfColor|PointF, arg2: PointF|PdfColor, arg3 ?: PdfColor, arg4 ?: PdfColor|PdfLinearGradientMode|number) { super(new PdfDictionary()); if (arg1 instanceof PointF && arg2 instanceof PointF && arg3 instanceof PdfColor && arg4 instanceof PdfColor) { this.initialize(arg3, arg4); this.mPointStart = arg1; this.mPointEnd = arg2; this.setPoints(this.mPointStart, this.mPointEnd); } else if (arg1 instanceof Rectangle) { this.initialize(arg2 as PdfColor, arg3); /* tslint:disable-next-line:max-line-length */ if ((arg4 === PdfLinearGradientMode.BackwardDiagonal || arg4 === PdfLinearGradientMode.ForwardDiagonal || arg4 === PdfLinearGradientMode.Horizontal || arg4 === PdfLinearGradientMode.Vertical)) { this.mBoundaries = arg1 as Rectangle; switch (arg4) { case PdfLinearGradientMode.BackwardDiagonal: this.mPointStart = new PointF(arg1.right, arg1.top); this.mPointEnd = new PointF(arg1.left, arg1.bottom); break; case PdfLinearGradientMode.ForwardDiagonal: this.mPointStart = new PointF(arg1.left, arg1.top); this.mPointEnd = new PointF(arg1.right, arg1.bottom); break; case PdfLinearGradientMode.Horizontal: this.mPointStart = new PointF(arg1.left, arg1.top); this.mPointEnd = new PointF(arg1.right, arg1.top); break; case PdfLinearGradientMode.Vertical: this.mPointStart = new PointF(arg1.left, arg1.top); this.mPointEnd = new PointF(arg1.left, arg1.bottom); break; default: throw new Error('ArgumentException -- Unsupported linear gradient mode: ' + arg4 + ' mode'); } this.setPoints(this.mPointStart, this.mPointEnd); } else if (typeof arg4 === 'number' && typeof arg4 !== 'undefined') { this.mBoundaries = arg1; arg4 = arg4 % 360; if ((arg4 === 0)) { this.mPointStart = new PointF(arg1.left, arg1.top); this.mPointEnd = new PointF(arg1.right, arg1.top); } else if ((arg4 === 90)) { this.mPointStart = new PointF(arg1.left, arg1.top); this.mPointEnd = new PointF(arg1.left, arg1.bottom); } else if ((arg4 === 180)) { this.mPointEnd = new PointF(arg1.left, arg1.top); this.mPointStart = new PointF(arg1.right, arg1.top); } else if ((arg4 === 270)) { this.mPointEnd = new PointF(arg1.left, arg1.top); this.mPointStart = new PointF(arg1.left, arg1.bottom); } else { let d2r: number = (Math.PI / 180); let radAngle: number = (arg4 * d2r); let k: number = Math.tan(radAngle); let x: number = (this.mBoundaries.left + ((this.mBoundaries.right - this.mBoundaries.left) / 2)); let y: number = (this.mBoundaries.top + ((this.mBoundaries.bottom - this.mBoundaries.top) / 2)); let centre: PointF = new PointF(x, y); x = (this.mBoundaries.width / (2 * (<number>(Math.cos(radAngle))))); y = (<number>((k * x))); x = (x + centre.x); y = (y + centre.y); let p1: PointF = new PointF(x, y); let cp1: PointF = this.subPoints(p1, centre); // P1 - P0 let p: PointF = this.choosePoint(arg4); let coef: number = (this.mulPoints(this.subPoints(p, centre), cp1) / this.mulPoints(cp1, cp1)); this.mPointEnd = this.addPoints(centre, this.mulPoint(cp1, coef)); // Parametric line equation. this.mPointStart = this.addPoints(centre, this.mulPoint(cp1, (coef * -1))); } this.setPoints(this.mPointEnd, this.mPointStart); } } } /** * Initializes a new instance of the `PdfLinearGradientBrush` class. * @param color1 The starting color of the gradient. * @param color2 The end color of the gradient. */ private initialize(color1: PdfColor, color2: PdfColor) : void { this.mColours = [ color1, color2]; this.mColourBlend = new PdfColorBlend(2); this.mColourBlend.positions = [ 0, 1]; this.mColourBlend.colors = this.mColours; this.initShading(); } //Properties /** * Gets or sets a PdfBlend that specifies positions * and factors that define a custom falloff for the gradient. * @public */ public get blend(): PdfBlend { return this.mBlend; } public set blend(value: PdfBlend) { if ((value == null)) { throw new Error('ArgumentNullException : Blend'); } if ((this.mColours == null)) { throw new Error('NotSupportedException : There is no starting and ending colours specified.'); } this.mBlend = value; // TODO: generate correct colour blend. this.mColourBlend = this.mBlend.generateColorBlend(this.mColours, this.colorSpace); this.resetFunction(); } /** * Gets or sets a ColorBlend that defines a multicolor linear gradient. * @public */ public get interpolationColors(): PdfColorBlend { return this.mColourBlend; } public set interpolationColors(value: PdfColorBlend) { if ((value == null)) { throw new Error('ArgumentNullException : InterpolationColors'); } this.mBlend = null; this.mColours = null; this.mColourBlend = value; this.resetFunction(); } /** * Gets or sets the starting and ending colors of the gradient. * @public */ public get linearColors(): PdfColor[] { return this.mColours; } public set linearColors(value: PdfColor[]) { if ((value == null)) { throw new Error('ArgumentNullException : LinearColors'); } if ((value.length < 2)) { throw new Error('ArgumentException : The array is too small - LinearColors'); } if ((this.mColours == null && typeof this.mColours === 'undefined')) { this.mColours = [value[0], value[1]]; } else { this.mColours[0] = value[0]; this.mColours[1] = value[1]; } if ((this.mBlend == null && typeof this.mBlend === 'undefined')) { // Set correct colour blend. this.mColourBlend = new PdfColorBlend(2); this.mColourBlend.colors = this.mColours; this.mColourBlend.positions = [0, 1]; } else { this.mColourBlend = this.mBlend.generateColorBlend(this.mColours, this.colorSpace); } this.resetFunction(); } /** * Gets a rectangular region that defines the boundaries of the gradient. * @public */ public get rectangle(): Rectangle { return this.mBoundaries; } /** * Gets or sets the value indicating whether the gradient should extend starting and ending points. * @public */ public get extend(): PdfExtend { let result: PdfExtend = PdfExtend.None; let extend: PdfArray = (<PdfArray>(this.shading.items.getValue(this.mDictionaryProperties.extend))); if ((extend != null)) { let extStart: PdfBoolean = (<PdfBoolean>(extend.items(0))); let extEnd: PdfBoolean = (<PdfBoolean>(extend.items(1))); if (extStart.value) { result = (result | PdfExtend.Start); } if (extEnd.value) { result = (result | PdfExtend.End); } } return result; } public set extend(value: PdfExtend) { let extend: PdfArray = (<PdfArray>(this.shading.items.getValue(this.mDictionaryProperties.extend))); let extStart: PdfBoolean; let extEnd: PdfBoolean; if ((extend == null)) { extStart = new PdfBoolean(false); extEnd = new PdfBoolean(false); extend = new PdfArray(); extend.add(extStart); extend.add(extEnd); this.shading.items.setValue(this.mDictionaryProperties.extend, extend); } else { extStart = (<PdfBoolean>(extend.items(0))); extEnd = (<PdfBoolean>(extend.items(1))); } // extStart.value = ((value && PdfExtend.Start) > 0); // extEnd.value = ((value && PdfExtend.End) > 0); } //Implementation /** * Adds two points to each other. * @param point1 The point1. * @param point2 The point2. */ private addPoints(point1: PointF, point2: PointF): PointF { let x: number = (point1.x + point2.x); let y: number = (point1.y + point2.y); let result: PointF = new PointF(x, y); return result; } /** * Subs the second point from the first one. * @param point1 The point1. * @param point2 The point2. */ private subPoints(point1: PointF, point2: PointF): PointF { let x: number = (point1.x - point2.x); let y: number = (point1.y - point2.y); let result: PointF = new PointF(x, y); return result; } /** * Makes scalar multiplication of two points. * @param point1 The point1. * @param point2 The point2. */ private mulPoints(point1: PointF, point2: PointF): number { let result: number = ((point1.x * point2.x) + (point1.y * point2.y)); return result; } /** * Multiplies the point by the value specified. * @param point The point1. * @param value The value. */ private mulPoint(point: PointF, value: number): PointF { point.x = (point.x * value); point.y = (point.y * value); return point; } /** * Choose the point according to the angle. * @param angle The angle. */ private choosePoint(angle: number): PointF { let point: PointF = new PointF(0, 0); // Choose the correct point. if ((angle < 90) && (angle > 0)) { point = new PointF(this.mBoundaries.right, this.mBoundaries.bottom); } else if ((angle < 180) && (angle > 90)) { point = new PointF(this.mBoundaries.left, this.mBoundaries.bottom); } else if ((angle < 270) && (angle > 180)) { point = new PointF(this.mBoundaries.left, this.mBoundaries.top); } else if (angle > 270) { point = new PointF(this.mBoundaries.right, this.mBoundaries.top); } else { throw new Error('PdfException - Internal error.'); } return point; } /** * Sets the start and end points. * @param point1 The point1. * @param point2 The point2. */ private setPoints(point1: PointF, point2: PointF) : void { let points: PdfArray = new PdfArray(); points.add(new PdfNumber(point1.x)); points.add(new PdfNumber(this.updateY(point1.y))); points.add(new PdfNumber(point2.x)); points.add(new PdfNumber(this.updateY(point2.y))); this.shading.items.setValue(this.mDictionaryProperties.coords, points); } /** * Updates y co-ordinate. * @param y Y co-ordinate.. */ private updateY(y: number): number { if (y !== 0) { return -y; } else { return y; } } //Overrides /** * Initializes the shading dictionary. * @private */ private initShading(): void { this.colorSpace = PdfColorSpace.Rgb; this.function = this.mColourBlend.getFunction(this.colorSpace); this.shading.items.setValue(this.mDictionaryProperties.shadingType, new PdfNumber((<number>(ShadingType.Axial)))); } //Overrides /** * Creates a new copy of a brush. * @public */ public clone(): PdfBrush { let brush: PdfLinearGradientBrush = this; brush.resetPatternDictionary(new PdfDictionary(this.patternDictionary)); brush.shading = new PdfDictionary(); brush.initShading(); brush.setPoints(brush.mPointStart, brush.mPointEnd); if (brush !== null && brush instanceof PdfLinearGradientBrush) { if ((this.matrix != null && typeof this.matrix !== 'undefined')) { brush.matrix = this.matrix.clone(); } } if ((this.mColours != null && typeof this.mColours !== 'undefined')) { brush.mColours = (<PdfColor[]>(this.mColours)); } if ((this.blend != null && typeof this.blend !== 'undefined')) { brush.blend = this.blend.clonePdfBlend(); } else if ((this.interpolationColors != null && typeof this.interpolationColors !== 'undefined')) { brush.interpolationColors = this.interpolationColors.cloneColorBlend(); } brush.extend = this.extend; this.cloneBackgroundValue(brush); this.cloneAntiAliasingValue(brush); return brush; } /** * Resets the function. * @public */ public resetFunction() : void { this.function = this.mColourBlend.getFunction(this.colorSpace); } }
the_stack
import { UnwrapPromiseTuple } from "../utils/PromiseProvider" import { DatabaseType, QueryRunner } from "./QueryRunner" export abstract class AbstractPoolQueryRunner implements QueryRunner { abstract readonly database: DatabaseType private currentQueryRunner?: QueryRunner private transactionLevel = 0 execute<RESULT>(fn: (connection: unknown, transaction?: unknown) => Promise<RESULT>): Promise<RESULT> { return this.getQueryRunner().then(queryRunner => queryRunner.execute(fn)).finally(() => this.releaseIfNeeded()) } executeSelectOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeSelectOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeSelectManyRows(query: string, params: any[] = []): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeSelectManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeSelectOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeSelectOneColumnOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeSelectOneColumnManyRows(query: string, params: any[] =[]): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeSelectOneColumnManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeInsert(query: string, params: any[] = []): Promise<number> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsert(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningLastInsertedId(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningLastInsertedId(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningMultipleLastInsertedId(query: string, params: any[] = []): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningMultipleLastInsertedId(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningOneColumnOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeInsertReturningOneColumnManyRows(query: string, params: any[] =[]): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeInsertReturningOneColumnManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeUpdate(query: string, params: any[] = []): Promise<number> { return this.getQueryRunner().then(queryRunner => queryRunner.executeUpdate(query, params)).finally(() => this.releaseIfNeeded()) } executeUpdateReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeUpdateReturningOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeUpdateReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeUpdateReturningManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeUpdateReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeUpdateReturningOneColumnOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeUpdateReturningOneColumnManyRows(query: string, params: any[] =[]): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeUpdateReturningOneColumnManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeDelete(query: string, params: any[] = []): Promise<number> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDelete(query, params)).finally(() => this.releaseIfNeeded()) } executeDeleteReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDeleteReturningOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeDeleteReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDeleteReturningManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeDeleteReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDeleteReturningOneColumnOneRow(query, params)).finally(() => this.releaseIfNeeded()) } executeDeleteReturningOneColumnManyRows(query: string, params: any[] =[]): Promise<any[]> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDeleteReturningOneColumnManyRows(query, params)).finally(() => this.releaseIfNeeded()) } executeProcedure(query: string, params: any[] = []): Promise<void> { return this.getQueryRunner().then(queryRunner => queryRunner.executeProcedure(query, params)).finally(() => this.releaseIfNeeded()) } executeFunction(query: string, params: any[] = []): Promise<any> { return this.getQueryRunner().then(queryRunner => queryRunner.executeFunction(query, params)).finally(() => this.releaseIfNeeded()) } executeBeginTransaction(): Promise<void> { if (this.transactionLevel <= 0) { this.transactionLevel = 1 return this.createResolvedPromise(undefined) } else { return this.getQueryRunner().then(queryRunner => queryRunner.executeBeginTransaction()).then(() => { this.transactionLevel++ }) } } executeCommit(): Promise<void> { if (this.transactionLevel <= 0) { throw new Error('You are not in a transaction') } if (this.currentQueryRunner) { return this.currentQueryRunner.executeCommit().then(() => { // Transaction count and release only modified when commit successful, in case of error there is still an open transaction this.transactionLevel-- if (this.transactionLevel < 0) { this.transactionLevel = 0 } this.releaseIfNeeded() }) } this.transactionLevel-- if (this.transactionLevel < 0) { this.transactionLevel = 0 } return this.createResolvedPromise(undefined) } executeRollback(): Promise<void> { if (this.transactionLevel <= 0) { throw new Error('You are not in a transaction') } if (this.currentQueryRunner) { return this.currentQueryRunner.executeRollback().finally(() => { this.transactionLevel-- if (this.transactionLevel < 0) { this.transactionLevel = 0 } this.releaseIfNeeded() }) } this.transactionLevel-- if (this.transactionLevel < 0) { this.transactionLevel = 0 } return this.createResolvedPromise(undefined) } isTransactionActive(): boolean { return this.transactionLevel > 0 } executeDatabaseSchemaModification(query: string, params: any[] = []): Promise<void> { return this.getQueryRunner().then(queryRunner => queryRunner.executeDatabaseSchemaModification(query, params)).finally(() => this.releaseIfNeeded()) } abstract executeInTransaction<P extends Promise<any>[]>(fn: () => [...P], outermostQueryRunner: QueryRunner): Promise<UnwrapPromiseTuple<P>> abstract executeInTransaction<T>(fn: () => Promise<T>, outermostQueryRunner: QueryRunner): Promise<T> abstract executeInTransaction(fn: () => Promise<any>[] | Promise<any>, outermostQueryRunner: QueryRunner): Promise<any> abstract executeCombined<R1, R2>(fn1: () => Promise<R1>, fn2: () => Promise<R2>): Promise<[R1, R2]> abstract useDatabase(database: DatabaseType): void abstract getNativeRunner(): unknown abstract addParam(params: any[], value: any): string addOutParam(_params: any[], _name: string): string { throw new Error('Unsupported output parameters') } abstract createResolvedPromise<RESULT>(result: RESULT): Promise<RESULT> private getQueryRunner(): Promise<QueryRunner> { if (!this.currentQueryRunner) { return this.createQueryRunner().then(queryRunner => { this.currentQueryRunner = queryRunner if (this.transactionLevel > 0) { return this.currentQueryRunner.executeBeginTransaction().then(() => { return queryRunner }) } return queryRunner }) } return this.createResolvedPromise(this.currentQueryRunner) } private releaseIfNeeded() { if (this.transactionLevel <= 0 && this.currentQueryRunner) { this.releaseQueryRunner(this.currentQueryRunner) this.currentQueryRunner = undefined } } protected abstract createQueryRunner(): Promise<QueryRunner> protected abstract releaseQueryRunner(queryRunner: QueryRunner): void isMocked(): boolean { return false } }
the_stack
import { context, trace, Span, SpanKind, SpanStatusCode, diag } from '@opentelemetry/api'; import { InstrumentationBase, InstrumentationNodeModuleFile, InstrumentationNodeModuleDefinition, isWrapped, safeExecuteInTheMiddle, } from '@opentelemetry/instrumentation'; import { SemanticAttributes, MessagingOperationValues, MessagingDestinationKindValues, } from '@opentelemetry/semantic-conventions'; import type { HttpInstrumentationConfig } from '@opentelemetry/instrumentation-http'; import { SocketIoInstrumentationConfig, Io, SocketIoInstrumentationAttributes, defaultSocketIoPath } from './types'; import { VERSION } from './version'; import isPromise from 'is-promise'; const reservedEvents = ['connect', 'connect_error', 'disconnect', 'disconnecting', 'newListener', 'removeListener']; export class SocketIoInstrumentation extends InstrumentationBase<Io> { protected override _config!: SocketIoInstrumentationConfig; constructor(config: SocketIoInstrumentationConfig = {}) { super('opentelemetry-instrumentation-socket.io', VERSION, normalizeConfig(config)); if (config.filterHttpTransport) { const httpInstrumentationConfig = config.filterHttpTransport.httpInstrumentation.getConfig() as HttpInstrumentationConfig; if (!Array.isArray(httpInstrumentationConfig.ignoreIncomingPaths)) { httpInstrumentationConfig.ignoreIncomingPaths = []; } httpInstrumentationConfig.ignoreIncomingPaths.push( config.filterHttpTransport.socketPath ?? defaultSocketIoPath ); config.filterHttpTransport.httpInstrumentation.setConfig(httpInstrumentationConfig); } } protected init() { const socketInstrumentation = new InstrumentationNodeModuleFile<any>( 'socket.io/dist/socket.js', ['>=3'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Socket`); if (isWrapped(moduleExports?.Socket?.prototype?.on)) { this._unwrap(moduleExports.Socket.prototype, 'on'); } this._wrap(moduleExports.Socket.prototype, 'on', this._patchOn(moduleVersion)); if (isWrapped(moduleExports?.Socket?.prototype?.emit)) { this._unwrap(moduleExports.Socket.prototype, 'emit'); } this._wrap(moduleExports.Socket.prototype, 'emit', this._patchEmit(moduleVersion)); return moduleExports; }, (moduleExports) => { if (isWrapped(moduleExports?.Socket?.prototype?.on)) { this._unwrap(moduleExports.Socket.prototype, 'on'); } if (isWrapped(moduleExports?.Socket?.prototype?.emit)) { this._unwrap(moduleExports.Socket.prototype, 'emit'); } return moduleExports; } ); const broadcastOperatorInstrumentation = new InstrumentationNodeModuleFile<any>( 'socket.io/dist/broadcast-operator.js', ['>=4'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug( `socket.io instrumentation: applying patch to socket.io@${moduleVersion} StrictEventEmitter` ); if (isWrapped(moduleExports?.BroadcastOperator?.prototype?.emit)) { this._unwrap(moduleExports.BroadcastOperator.prototype, 'emit'); } this._wrap(moduleExports.BroadcastOperator.prototype, 'emit', this._patchEmit(moduleVersion)); return moduleExports; }, (moduleExports) => { if (isWrapped(moduleExports?.BroadcastOperator?.prototype?.emit)) { this._unwrap(moduleExports.BroadcastOperator.prototype, 'emit'); } return moduleExports; } ); const namespaceInstrumentation = new InstrumentationNodeModuleFile<any>( 'socket.io/dist/namespace.js', ['<4'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Namespace`); if (isWrapped(moduleExports?.Namespace?.prototype?.emit)) { this._unwrap(moduleExports.Namespace.prototype, 'emit'); } this._wrap(moduleExports.Namespace.prototype, 'emit', this._patchEmit(moduleVersion)); return moduleExports; }, (moduleExports) => { if (isWrapped(moduleExports?.Namespace?.prototype?.emit)) { this._unwrap(moduleExports.Namespace.prototype, 'emit'); } } ); const socketInstrumentationLegacy = new InstrumentationNodeModuleFile<any>( 'socket.io/lib/socket.js', ['2'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Socket`); if (isWrapped(moduleExports.prototype?.on)) { this._unwrap(moduleExports.prototype, 'on'); } this._wrap(moduleExports.prototype, 'on', this._patchOn(moduleVersion)); if (isWrapped(moduleExports.prototype?.emit)) { this._unwrap(moduleExports.prototype, 'emit'); } this._wrap(moduleExports.prototype, 'emit', this._patchEmit(moduleVersion)); return moduleExports; }, (moduleExports) => { if (isWrapped(moduleExports.prototype?.on)) { this._unwrap(moduleExports.prototype, 'on'); } if (isWrapped(moduleExports.prototype?.emit)) { this._unwrap(moduleExports.prototype, 'emit'); } return moduleExports; } ); const namespaceInstrumentationLegacy = new InstrumentationNodeModuleFile<any>( 'socket.io/lib/namespace.js', ['2'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Namespace`); if (isWrapped(moduleExports?.prototype?.emit)) { this._unwrap(moduleExports.prototype, 'emit'); } this._wrap(moduleExports.prototype, 'emit', this._patchEmit(moduleVersion)); return moduleExports; }, (moduleExports) => { if (isWrapped(moduleExports?.prototype?.emit)) { this._unwrap(moduleExports.prototype, 'emit'); } } ); return [ new InstrumentationNodeModuleDefinition<Io>( 'socket.io', ['>=3'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Server`); if (isWrapped(moduleExports?.Server?.prototype?.on)) { this._unwrap(moduleExports.Server.prototype, 'on'); } this._wrap(moduleExports.Server.prototype, 'on', this._patchOn(moduleVersion)); return moduleExports; }, (moduleExports, moduleVersion) => { if (isWrapped(moduleExports?.Server?.prototype?.on)) { this._unwrap(moduleExports.Server.prototype, 'on'); } return moduleExports; }, [broadcastOperatorInstrumentation, namespaceInstrumentation, socketInstrumentation] ), new InstrumentationNodeModuleDefinition<any>( 'socket.io', ['2'], (moduleExports, moduleVersion) => { if (moduleExports === undefined || moduleExports === null) { return moduleExports; } diag.debug(`socket.io instrumentation: applying patch to socket.io@${moduleVersion} Server`); if (isWrapped(moduleExports?.prototype?.on)) { this._unwrap(moduleExports.prototype, 'on'); } this._wrap(moduleExports.prototype, 'on', this._patchOn(moduleVersion)); return moduleExports; }, (moduleExports, moduleVersion) => { if (isWrapped(moduleExports?.prototype?.on)) { this._unwrap(moduleExports.prototype, 'on'); } return moduleExports; }, [namespaceInstrumentationLegacy, socketInstrumentationLegacy] ), ]; } override setConfig(config: SocketIoInstrumentationConfig = {}) { return super.setConfig(normalizeConfig(config)); } private _patchOn(moduleVersion: string) { const self = this; return (original: Function) => { return function (ev: any, originalListener: Function) { if (!self._config.traceReserved && reservedEvents.includes(ev)) { return original.apply(this, arguments); } if (self._config.onIgnoreEventList.includes(ev)) { return original.apply(this, arguments); } const wrappedListener = function (...args: any[]) { const eventName = ev; const defaultNamespace = '/'; const namespace = this.name || this.adapter?.nsp?.name; const destination = namespace === defaultNamespace ? eventName : `${namespace} ${eventName}`; const span: Span = self.tracer.startSpan(`${destination} ${MessagingOperationValues.RECEIVE}`, { kind: SpanKind.CONSUMER, attributes: { [SemanticAttributes.MESSAGING_SYSTEM]: 'socket.io', [SemanticAttributes.MESSAGING_DESTINATION]: namespace, [SemanticAttributes.MESSAGING_OPERATION]: MessagingOperationValues.RECEIVE, [SocketIoInstrumentationAttributes.SOCKET_IO_EVENT_NAME]: eventName, }, }); if (self._config.onHook) { safeExecuteInTheMiddle( () => self._config.onHook(span, { moduleVersion, payload: args }), (e) => { if (e) diag.error(`socket.io instrumentation: onHook error`, e); }, true ); } return context.with(trace.setSpan(context.active(), span), () => self.endSpan(() => originalListener.apply(this, arguments), span) ); }; return original.apply(this, [ev, wrappedListener]); }; }; } private endSpan(traced: () => any | Promise<any>, span: Span) { try { const result = traced(); if (isPromise(result)) { return Promise.resolve(result) .catch((err) => { if (err) { if (typeof err === 'string') { span.setStatus({ code: SpanStatusCode.ERROR, message: err }); } else { span.recordException(err); span.setStatus({ code: SpanStatusCode.ERROR, message: err?.message }); } } throw err; }) .finally(() => span.end()); } else { span.end(); return result; } } catch (error: any) { span.recordException(error); span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message }); span.end(); throw error; } } private _patchEmit(moduleVersion: string) { const self = this; return (original: Function) => { return function (ev: any, ...args: any[]) { if (!self._config.traceReserved && reservedEvents.includes(ev)) { return original.apply(this, arguments); } if (self._config.emitIgnoreEventList.includes(ev)) { return original.apply(this, arguments); } const messagingSystem = 'socket.io'; const eventName = ev; const attributes: any = { [SemanticAttributes.MESSAGING_SYSTEM]: messagingSystem, [SemanticAttributes.MESSAGING_DESTINATION_KIND]: MessagingDestinationKindValues.TOPIC, [SocketIoInstrumentationAttributes.SOCKET_IO_EVENT_NAME]: eventName, }; let rooms = this.rooms || this._rooms || this.sockets?._rooms || this.sockets?.rooms || []; // Some of the attributes above are of Set type. Convert it. if (!Array.isArray(rooms)) { rooms = Array.from<string>(rooms); } // only for v2: this.id is only set for v2. That's to mimic later versions which have this.id in the rooms Set. if (rooms.length === 0 && this.id) { rooms.push(this.id); } if (rooms.length) { attributes[SocketIoInstrumentationAttributes.SOCKET_IO_ROOMS] = rooms; } const namespace = this.name || this.adapter?.nsp?.name || this.sockets?.name; if (namespace) { attributes[SocketIoInstrumentationAttributes.SOCKET_IO_NAMESPACE] = namespace; attributes[SemanticAttributes.MESSAGING_DESTINATION] = namespace; } const spanRooms = rooms.length ? `[${rooms.join()}]` : ''; const span = self.tracer.startSpan(`${namespace}${spanRooms} send`, { kind: SpanKind.PRODUCER, attributes, }); if (self._config.emitHook) { safeExecuteInTheMiddle( () => self._config.emitHook(span, { moduleVersion, payload: args }), (e) => { if (e) diag.error(`socket.io instrumentation: emitHook error`, e); }, true ); } try { return context.with(trace.setSpan(context.active(), span), () => original.apply(this, arguments)); } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } }; }; } } const normalizeConfig = (config?: SocketIoInstrumentationConfig) => { config = Object.assign({}, config); if (!Array.isArray(config.emitIgnoreEventList)) { config.emitIgnoreEventList = []; } if (!Array.isArray(config.onIgnoreEventList)) { config.onIgnoreEventList = []; } return config; };
the_stack
import { SoftmaxRegressionSparse } from "./SoftmaxRegressionSparse"; import { NgramSubwordFeaturizer } from "../../../../language_understanding/featurizer/NgramSubwordFeaturizer"; import { IMathematicsHelper } from "../../../../../mathematics/mathematics_helper/IMathematicsHelper"; import { MathematicsHelper } from "../../../../../mathematics/mathematics_helper/MathematicsHelper"; import { Utility } from "../../../../../utility/Utility"; export class LearnerUtility { public static readonly MathematicsHelperObject: IMathematicsHelper = MathematicsHelper.GetMathematicsHelperObject(); public static exampleFunctionPredictAndEvaluateTestDataset( featurizer: NgramSubwordFeaturizer, model: SoftmaxRegressionSparse, testDatasetFilename: string, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, lineIndexToStart: number) { // ------------------------------------------------------------------- const labels: string[] = featurizer.getLabels(); // ------------------------------------------------------------------- const intentsUtterancesWeightsDev: { "intents": string[], "texts": string[], "weights": number[] } = LearnerUtility.exampleFunctionLoadTestDataset( testDatasetFilename, labelColumnIndex, textColumnIndex, weightColumnIndex, lineIndexToStart); const intents: string[] = intentsUtterancesWeightsDev.intents; const texts: string[] = intentsUtterancesWeightsDev.texts; // const weights: string[] = // intentsUtterancesWeightsDev.weights; const numberIntentUtterancesDev: number = intents.length; let countPredictionsCorrect = 0; for (let i: number = 0; i < numberIntentUtterancesDev; i++) { const intent: string = intents[i]; const text: string = texts[i]; const textFeatureIndexArray: string[] = new Array<string>(1); textFeatureIndexArray[0] = text; const textFeatures: number[][] = featurizer.createFeatureSparseIndexArrays( textFeatureIndexArray); const predictions: number[][] = model.predict(textFeatures); const predictionsDataArray: number[][] = predictions; const predictionLabelIndexMax: { "indexMax": number, "max": number } = LearnerUtility.MathematicsHelperObject.getIndexOnFirstMaxEntry(predictionsDataArray[0]); const predictionLabelIndex: number = predictionLabelIndexMax.indexMax; const predictionLabel: string = labels[predictionLabelIndex]; // Utility.debuggingLog( // "" + i + "th entry: " // + "labelled-intent=" + intent // + ", predicted-label=" + predictionLabel // + ", predicted-label-index=" + predictionLabelIndex // + ", predictionLabelIndexMax=" + predictionLabelIndexMax // + ", predictions=" + predictions); if (predictionLabel === intent) { countPredictionsCorrect++; } } const accuracy: number = countPredictionsCorrect / numberIntentUtterancesDev; Utility.debuggingLog( "countPredictionsCorrect=" + countPredictionsCorrect + ", numberIntentUtterancesDev=" + numberIntentUtterancesDev + ", accuracy=" + accuracy); // ------------------------------------------------------------------- } public static exampleFunctionPredictAndEvaluateTestDatasetHashing( featurizer: NgramSubwordFeaturizer, model: SoftmaxRegressionSparse, testDatasetFilename: string, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, lineIndexToStart: number) { // ------------------------------------------------------------------- const labels: string[] = featurizer.getLabels(); // ------------------------------------------------------------------- const intentsUtterancesWeightsDev: { "intents": string[], "texts": string[], "weights": number[] } = LearnerUtility.exampleFunctionLoadTestDataset( testDatasetFilename, labelColumnIndex, textColumnIndex, weightColumnIndex, lineIndexToStart); const intents: string[] = intentsUtterancesWeightsDev.intents; const texts: string[] = intentsUtterancesWeightsDev.texts; const weights: number[] = intentsUtterancesWeightsDev.weights; const numberIntentUtterancesDev: number = intents.length; let countPredictionsCorrect = 0; for (let i: number = 0; i < numberIntentUtterancesDev; i++) { const intent: string = intents[i]; const text: string = texts[i]; const textFeatureIndexArray: string[] = new Array<string>(1); textFeatureIndexArray[0] = text; const textFeatures: number[][] = featurizer.createFeatureHashingSparseIndexArrays( textFeatureIndexArray); const predictions: number[][] = model.predict(textFeatures); const predictionsDataArray: number[][] = predictions; const predictionLabelIndexMax: { "indexMax": number, "max": number } = LearnerUtility.MathematicsHelperObject.getIndexOnFirstMaxEntry(predictionsDataArray[0]); const predictionLabelIndex: number = predictionLabelIndexMax.indexMax; const predictionLabel: string = labels[predictionLabelIndex]; // Utility.debuggingLog( // "" + i + "th entry: " // + "labelled-intent=" + intent // + ", predicted-label=" + predictionLabel // + ", predicted-label-index=" + predictionLabelIndex // + ", predictionLabelIndexMax=" + predictionLabelIndexMax // + ", predictions=" + predictions); if (predictionLabel === intent) { countPredictionsCorrect++; } } const accuracy: number = countPredictionsCorrect / numberIntentUtterancesDev; Utility.debuggingLog( "countPredictionsCorrect=" + countPredictionsCorrect + ", numberIntentUtterancesDev=" + numberIntentUtterancesDev + ", accuracy=" + accuracy); // ------------------------------------------------------------------- } public static exampleFunctionLoadFeaturizeTrainDataset( numberHashingFeaturesSetting: number = 0, filename: string, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, lineIndexToStart: number, subwordNgramBegin: number = 3, subwordNgramEnd: number = 4, toLowercase: boolean = true, toRemovePunctuations: boolean = false, toRemoveEmptyElements: boolean = true, splitDelimiter: string = " ") { if (!Utility.exists(filename)) { Utility.debuggingThrow( `The input dataset file ${filename} does not exist! process.cwd()=${process.cwd()}`); } const intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } = Utility.loadLabelUtteranceColumnarFile( filename, // ---- filename: string, labelColumnIndex, // ---- labelColumnIndex: number = 0, textColumnIndex, // ---- textColumnIndex: number = 1, weightColumnIndex, // ---- weightColumnIndex: number = -1, lineIndexToStart, // ---- lineIndexToStart: number = 0, "\t", // ---- columnDelimiter: string = "\t", "\n", // ---- rowDelimiter: string = "\n", "utf8", // ---- encoding: string = "utf8", -1, // ---- lineIndexToEnd: number = -1 ); const featurizer: NgramSubwordFeaturizer = new NgramSubwordFeaturizer( subwordNgramBegin, subwordNgramEnd, toLowercase, toRemovePunctuations, toRemoveEmptyElements, splitDelimiter, numberHashingFeaturesSetting); featurizer.resetLabelFeatureMaps(intentsUtterancesWeights); return featurizer; } public static exampleFunctionLoadTestDataset( filename: string, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, lineIndexToStart: number): { "intents": string[], "texts": string[], "weights": number[] } { if (!Utility.exists(filename)) { Utility.debuggingThrow( `The input dataset file ${filename} does not exist! process.cwd()=${process.cwd()}`); } const intentsUtterancesWeights: { "intents": string[], "texts": string[], "weights": number[] } = Utility.loadLabelTextColumnarFile( filename, // ---- filename: string, labelColumnIndex, // ---- labelColumnIndex: number = 0, textColumnIndex, // ---- textColumnIndex: number = 1, weightColumnIndex, // ---- weightColumnIndex: number = -1, lineIndexToStart, // ---- lineIndexToStart: number = 0, "\t", // ---- columnDelimiter: string = "\t", "\n", // ---- rowDelimiter: string = "\n", "utf8", // ---- encoding: string = "utf8", -1, // ---- lineIndexToEnd: number = -1 ); return intentsUtterancesWeights; } }
the_stack
import * as angular from 'angular'; /** * @controller * @name MessageBannerController * @private * @description * Used to more easily inject the Angular $log and $window services into the directive. */ export class MessageBannerController { public static $inject: string[] = ['$scope', '$log', '$window']; constructor(public $scope: IMessageBannerScope, public $log: angular.ILogService, public $window: angular.IWindowService) { } } /** * @ngdoc interface * @name IMessageBannerScope * @module officeuifabric.components.messagebanner * * @description * This is the scope used by the `<uif-message-banner />` directive. * * * @property {string} actionLabel - Label for the action button. * @property {boolean} isVisible - Hide or show message banner * */ export interface IMessageBannerScope extends angular.IScope { uifActionLabel: string; uifIsVisible: boolean; isExpanded: boolean; onResize: () => void; } /** * @ngdoc interface * @name IMessageBannerAttributes * @module officeuifabric.components.messagebanner * * @description * This is the attribute interface used by the directive. * * @property {Function} uifAction - Expression to be called on the button click event * @property {string} uifActionLabel - Label for the action button. * @property {boolean} uifIsVisible - Hide or show the message banner * @property {Function} uifOnClose - Expression to be called on message banner close event * */ export interface IMessageBannerAttributes extends angular.IAttributes { uifAction: () => void; uifActionLabel: string; uifIsVisible: boolean; uifOnClose: () => void; } /** * @ngdoc directive * @name uifMessageBanner * @module officeuifabric.components.messagebanner * * @restrict E * * @description * `<uif-message-banner>` is an message banner directive. * * @see {link http://dev.office.com/fabric/components/messagebanner} * * @usage * <uif-message-banner uif-action="" uif-action-label="" uif-is-open="" uif-on-close="OnCloseCallback"> * <uif-content> * <uif-icon uif-type="alert"></uif-icon><b>Important message goes here</b> * </uif-content> * </uif-message-banner> */ export class MessageBannerDirective implements angular.IDirective { public controller: typeof MessageBannerController = MessageBannerController; public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public require: string = 'uifMessageBanner'; public isExpanded: boolean = false; public template: string = ` <div class="ms-MessageBanner" ng-show="uifIsVisible"> <div class="ms-MessageBanner-content"> <div class="ms-MessageBanner-text"> <div class="ms-MessageBanner-clipper"></div> </div> <uif-button type="button" uif-type="command" class="ms-MessageBanner-expand"> <uif-icon uif-type="chevronsDown" ng-show="!isExpanded"></uif-icon> <uif-icon uif-type="chevronsUp" ng-show="isExpanded"></uif-icon> </uif-button> <div class="ms-MessageBanner-action"> <uif-button type="button" uif-type="primary" class="ms-fontColor-neutralLight" ng-click="uifAction()">{{ uifActionLabel }}</uif-button> </div> </div> <uif-button type="button" uif-type="command" class="ms-MessageBanner-close" ng-click="uifOnClose()" style="height:52px"> <uif-icon uif-type="x"></uif-icon> </uif-button> </div>`; public scope: any = { uifAction: '&', uifActionLabel: '@', uifIsVisible: '=?', uifOnClose: '&?' }; // ui fabric js variables private _clipper: angular.IAugmentedJQuery; private _bufferSize: number; private _textContainerMaxWidth: number = 700; private _clientWidth: number; private _textWidth: string; private _initTextWidth: number; private _chevronButton: angular.IAugmentedJQuery; private _messageBanner: angular.IAugmentedJQuery; private _actionButton: angular.IAugmentedJQuery; private _closeButton: angular.IAugmentedJQuery; private _bufferElementsWidth: number = 88; private _bufferElementsWidthSmall: number = 35; private SMALL_BREAK_POINT: number = 480; // ui fabric js variables end public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService, $timeout: angular.ITimeoutService) => new MessageBannerDirective($log, $timeout); directive.$inject = ['$log', '$timeout']; return directive; } constructor(private $log: angular.ILogService, private $timeout: angular.ITimeoutService) { } public link: angular.IDirectiveLinkFn = ( $scope: IMessageBannerScope, $elem: angular.IAugmentedJQuery, $attrs: IMessageBannerAttributes, $controller: MessageBannerController, $transclude: angular.ITranscludeFunction): void => { $scope.uifActionLabel = $attrs.uifActionLabel; $scope.isExpanded = false; $scope.onResize = (innerWidth?: number) => { if (innerWidth === undefined) { innerWidth = window.innerWidth; } this._clientWidth = this._messageBanner[0].offsetWidth; if (innerWidth >= this.SMALL_BREAK_POINT) { this._resizeRegular(); } else { this._resizeSmall(); } }; this._initLocals($elem); this.transcludeChilds($scope, $elem, $transclude); this._initTextWidth = (this._clipper.children().eq(0))[0].offsetWidth; // office ui fabric functions bindings angular.element($controller.$window).bind('resize', () => { $scope.onResize(); $scope.$digest(); }); angular.element(this._chevronButton).bind('click', () => { this._toggleExpansion($scope); }); angular.element(this._closeButton).bind('click', () => { this._hideBanner($scope); }); $scope.onResize(); } private transcludeChilds( $scope: IMessageBannerScope, $element: angular.IAugmentedJQuery, $transclude: angular.ITranscludeFunction): void { $transclude((clone: angular.IAugmentedJQuery) => { let hasContent: boolean = this.hasItemContent(clone); // if (!hasContent && !$scope.message) { if (!hasContent) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.messagebanner - ' + 'you need to provide a text for the message banner.\n' + 'For <uif-message-banner> you need to specify' + '<uif-content> as a child directive'); } this.insertItemContent(clone, $scope, $element); }); } private insertItemContent(clone: angular.IAugmentedJQuery, $scope: IMessageBannerScope, $element: angular.IAugmentedJQuery): void { let contentElement: JQuery = angular.element($element[0].querySelector('.ms-MessageBanner-clipper')); if (this.hasItemContent(clone)) { /* element provided */ for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { contentElement.append(element); break; } } } } private hasItemContent(clone: angular.IAugmentedJQuery): boolean { for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { return true; } } return false; } // ui fabric private functions /** * helper for init of local variables */ private _initLocals($elem: angular.IAugmentedJQuery): void { this._messageBanner = angular.element($elem[0].querySelector('.ms-MessageBanner')); this._clipper = angular.element($elem[0].querySelector('.ms-MessageBanner-clipper')); this._chevronButton = angular.element($elem[0].querySelectorAll('.ms-MessageBanner-expand')); this._actionButton = angular.element($elem[0].querySelector('.ms-MessageBanner-action')); this._bufferSize = this._actionButton[0].offsetWidth + this._bufferElementsWidth; this._closeButton = angular.element($elem[0].querySelector('.ms-MessageBanner-close')); } /** * resize above 480 pixel breakpoint */ private _resizeRegular(): void { if ((this._clientWidth - this._bufferSize) > this._initTextWidth && this._initTextWidth < this._textContainerMaxWidth) { this._textWidth = 'auto'; this._chevronButton[0].className = 'ms-MessageBanner-expand'; } else { this._textWidth = Math.min((this._clientWidth - this._bufferSize), this._textContainerMaxWidth) + 'px'; if (!this._chevronButton.hasClass('is-visible')) { this._chevronButton[0].className += ' is-visible'; } } this._clipper[0].style.width = this._textWidth; this._chevronButton[0].style.height = '52px'; } /** * resize below 480 pixel breakpoint */ private _resizeSmall(): void { if (this._clientWidth - (this._bufferElementsWidthSmall + this._closeButton[0].offsetWidth) > this._initTextWidth) { this._textWidth = 'auto'; } else { this._textWidth = (this._clientWidth - (this._bufferElementsWidthSmall + this._closeButton[0].offsetWidth)) + 'px'; } this._clipper[0].style.width = this._textWidth; this._chevronButton[0].style.height = '85px'; } private _toggleExpansion($scope: IMessageBannerScope): void { $scope.isExpanded = !$scope.isExpanded; $scope.$digest(); this._messageBanner.toggleClass('is-expanded'); } /** * hides banner when close button is clicked */ private _hideBanner($scope: IMessageBannerScope): void { if ($scope.uifIsVisible) { this._messageBanner.addClass('hide'); this.$timeout( (): void => { $scope.uifIsVisible = false; $scope.$apply(); this._messageBanner.removeClass('hide'); }, 500); } } } /** * @ngdoc module * @name officeuifabric.components.messagebanner * * @description * MessageBanner * */ export let module: angular.IModule = angular.module('officeuifabric.components.messagebanner', ['officeuifabric.components']) .directive('uifMessageBanner', MessageBannerDirective.factory());
the_stack
import loader = AMDLoader; QUnit.module('ConfigurationOptionsUtil'); /** * Assert that two configuration options are equal and disregard `onError` */ function assertConfigurationIs(actual: loader.IConfigurationOptions, expected: loader.IConfigurationOptions): void { actual.onError = null; actual.nodeCachedData = null; expected.onError = null; expected.nodeCachedData = null; QUnit.deepEqual(actual, expected, 'Configuration options are equal'); } QUnit.test('Default configuration', () => { var result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions(); assertConfigurationIs(result, { baseUrl: '', catchError: false, ignoreDuplicateModules: [], isBuild: false, paths: {}, config: {}, urlArgs: '', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); }); function createSimpleKnownConfigurationOptions(): loader.IConfigurationOptions { return loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ baseUrl: 'myBaseUrl', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); } QUnit.test('Simple known configuration options', () => { var result = createSimpleKnownConfigurationOptions(); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); }); QUnit.test('Overwriting known configuration options', () => { // Overwrite baseUrl 1 var result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ baseUrl: '' }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: '', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Overwrite baseUrl 2 result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ baseUrl: '/' }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: '/', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Overwrite catchError result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ catchError: false }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: false, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Contribute additional ignoreDuplicateModules result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ ignoreDuplicateModules: ['b'] }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: true, ignoreDuplicateModules: ['a', 'b'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Change defined paths result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ paths: { 'a': 'c' } }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'c' }, config: { 'd': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Contribute additional module configs result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ config: { 'e': {} } }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': {}, 'e': {} }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Change defined module configs result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions({ config: { 'd': { 'a': 'a' } } }, createSimpleKnownConfigurationOptions()); assertConfigurationIs(result, { baseUrl: 'myBaseUrl/', catchError: true, ignoreDuplicateModules: ['a'], isBuild: false, paths: { 'a': 'b' }, config: { 'd': { 'a': 'a' } }, urlArgs: 'myUrlArgs', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); }); QUnit.test('Overwriting unknown configuration options', () => { var result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions(); assertConfigurationIs(result, { baseUrl: '', catchError: false, ignoreDuplicateModules: [], isBuild: false, paths: {}, config: {}, urlArgs: '', cspNonce: '', preferScriptTags: false, recordStats: false, nodeModules: [] }); // Adding unknown key result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions(<any>{ unknownKey1: 'value1' }, result); assertConfigurationIs(result, <any>{ baseUrl: '', catchError: false, ignoreDuplicateModules: [], isBuild: false, paths: {}, config: {}, urlArgs: '', cspNonce: '', preferScriptTags: false, recordStats: false, unknownKey1: 'value1', nodeModules: [] }); // Adding another unknown key result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions(<any>{ unknownKey2: 'value2' }, result); assertConfigurationIs(result, <any>{ baseUrl: '', catchError: false, ignoreDuplicateModules: [], isBuild: false, paths: {}, config: {}, urlArgs: '', cspNonce: '', preferScriptTags: false, recordStats: false, unknownKey1: 'value1', unknownKey2: 'value2', nodeModules: [] }); // Overwriting unknown key result = loader.ConfigurationOptionsUtil.mergeConfigurationOptions(<any>{ unknownKey2: 'new-value2' }, result); assertConfigurationIs(result, <any>{ baseUrl: '', catchError: false, ignoreDuplicateModules: [], isBuild: false, paths: {}, config: {}, urlArgs: '', cspNonce: '', preferScriptTags: false, recordStats: false, unknownKey1: 'value1', unknownKey2: 'new-value2', nodeModules: [] }); }); QUnit.module('Configuration'); QUnit.test('moduleIdToPath', () => { var config = new loader.Configuration(new loader.Environment(), { baseUrl: 'prefix', urlArgs: 'suffix', paths: { 'a': 'newa', 'knockout': 'http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js', 'editor': '/src/editor' } }); // baseUrl is applied QUnit.equal(config.moduleIdToPaths('b/c/d'), 'prefix/b/c/d.js?suffix'); // paths rules are applied QUnit.equal(config.moduleIdToPaths('a'), 'prefix/newa.js?suffix'); QUnit.equal(config.moduleIdToPaths('a/b/c/d'), 'prefix/newa/b/c/d.js?suffix'); // paths rules check if value is an absolute path QUnit.equal(config.moduleIdToPaths('knockout'), 'http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js?suffix'); // modules ending in .js skip baseUrl + paths rules QUnit.equal(config.moduleIdToPaths('b/c/d.js'), 'b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('a/b/c/d.js'), 'a/b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('a.js'), 'a.js?suffix'); // modules redirected to / still get .js appended QUnit.equal(config.moduleIdToPaths('editor/x'), '/src/editor/x.js?suffix'); // modules starting with / skip baseUrl + paths rules QUnit.equal(config.moduleIdToPaths('/b/c/d'), '/b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('/a/b/c/d'), '/a/b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('/a'), '/a.js?suffix'); // modules starting with http:// or https:// skip baseUrl + paths rules QUnit.equal(config.moduleIdToPaths('file:///c:/a/b/c'), 'file:///c:/a/b/c.js?suffix'); QUnit.equal(config.moduleIdToPaths('http://b/c/d'), 'http://b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('http://a/b/c/d'), 'http://a/b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('http://a'), 'http://a.js?suffix'); QUnit.equal(config.moduleIdToPaths('https://b/c/d'), 'https://b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('https://a/b/c/d'), 'https://a/b/c/d.js?suffix'); QUnit.equal(config.moduleIdToPaths('https://a'), 'https://a.js?suffix'); }); QUnit.test('requireToUrl', () => { var config = new loader.Configuration(new loader.Environment(), { baseUrl: 'prefix', urlArgs: 'suffix', paths: { 'a': 'newa' } }); // baseUrl is applied QUnit.equal(config.requireToUrl('b/c/d'), 'prefix/b/c/d?suffix'); QUnit.equal(config.requireToUrl('../a/b/c/d'), 'prefix/../a/b/c/d?suffix'); // paths rules are applied QUnit.equal(config.requireToUrl('a'), 'prefix/newa?suffix'); QUnit.equal(config.requireToUrl('a/b/c/d'), 'prefix/newa/b/c/d?suffix'); // urls ending in .js get no special treatment QUnit.equal(config.requireToUrl('b/c/d.js'), 'prefix/b/c/d.js?suffix'); QUnit.equal(config.requireToUrl('a/b/c/d.js'), 'prefix/newa/b/c/d.js?suffix'); QUnit.equal(config.requireToUrl('a.js'), 'prefix/newa.js?suffix'); // requireToUrl does not append .js QUnit.equal(config.requireToUrl('b/c/d.png'), 'prefix/b/c/d.png?suffix'); QUnit.equal(config.requireToUrl('a/b/c/d.png'), 'prefix/newa/b/c/d.png?suffix'); QUnit.equal(config.requireToUrl('a.png'), 'prefix/newa.png?suffix'); // urls starting with / skip baseUrl + paths rules QUnit.equal(config.requireToUrl('/b/c/d'), '/b/c/d?suffix'); QUnit.equal(config.requireToUrl('/a/b/c/d'), '/a/b/c/d?suffix'); QUnit.equal(config.requireToUrl('/a'), '/a?suffix'); // urls starting with http:// or https:// skip baseUrl + paths rules QUnit.equal(config.requireToUrl('http://b/c/d'), 'http://b/c/d?suffix'); QUnit.equal(config.requireToUrl('http://a/b/c/d'), 'http://a/b/c/d?suffix'); QUnit.equal(config.requireToUrl('http://a'), 'http://a?suffix'); QUnit.equal(config.requireToUrl('https://b/c/d'), 'https://b/c/d?suffix'); QUnit.equal(config.requireToUrl('https://a/b/c/d'), 'https://a/b/c/d?suffix'); QUnit.equal(config.requireToUrl('https://a'), 'https://a?suffix'); }); QUnit.test('ignoreDuplicateModules', () => { var config = new loader.Configuration(new loader.Environment(), { ignoreDuplicateModules: ['a1', 'a2', 'a/b/c'] }); QUnit.equal(config.isDuplicateMessageIgnoredFor('a1'), true); QUnit.equal(config.isDuplicateMessageIgnoredFor('a2'), true); QUnit.equal(config.isDuplicateMessageIgnoredFor('a/b/c'), true); QUnit.equal(config.isDuplicateMessageIgnoredFor('a'), false); }); QUnit.module('ModuleIdResolver'); QUnit.test('resolveModule', () => { var resolver = new loader.ModuleIdResolver('a/b/c/d'); // normal modules QUnit.equal(resolver.resolveModule('e/f/g'), 'e/f/g'); QUnit.equal(resolver.resolveModule('e/f/../f/g'), 'e/f/../f/g'); // normal modules ending in .js QUnit.equal(resolver.resolveModule('e/f/g.js'), 'e/f/g.js'); // relative modules QUnit.equal(resolver.resolveModule('./e/f/g'), 'a/b/c/e/f/g'); QUnit.equal(resolver.resolveModule('../e/f/g'), 'a/b/e/f/g'); QUnit.equal(resolver.resolveModule('../../e/f/g'), 'a/e/f/g'); QUnit.equal(resolver.resolveModule('../../../e/f/g'), 'e/f/g'); QUnit.equal(resolver.resolveModule('../../../../e/f/g'), '../e/f/g'); QUnit.equal(resolver.resolveModule('../b/../c/d'), 'a/b/c/d'); // relative modules ending in .js QUnit.equal(resolver.resolveModule('./e/f/g.js'), 'a/b/c/e/f/g.js'); QUnit.equal(resolver.resolveModule('../e/f/g.js'), 'a/b/e/f/g.js'); QUnit.equal(resolver.resolveModule('../../e/f/g.js'), 'a/e/f/g.js'); QUnit.equal(resolver.resolveModule('../../../e/f/g.js'), 'e/f/g.js'); QUnit.equal(resolver.resolveModule('../../../../e/f/g.js'), '../e/f/g.js'); // modules starting with / QUnit.equal(resolver.resolveModule('/b/c/d'), '/b/c/d'); QUnit.equal(resolver.resolveModule('/a'), '/a'); QUnit.equal(resolver.resolveModule('/a/b/c/d.js'), '/a/b/c/d.js'); QUnit.equal(resolver.resolveModule('/../a/b/c'), '/../a/b/c'); // modules starting with http:// or https:// QUnit.equal(resolver.resolveModule('http://b/c/d'), 'http://b/c/d'); QUnit.equal(resolver.resolveModule('http://a'), 'http://a'); QUnit.equal(resolver.resolveModule('http://a/b/c/d.js'), 'http://a/b/c/d.js'); QUnit.equal(resolver.resolveModule('https://b/c/d'), 'https://b/c/d'); QUnit.equal(resolver.resolveModule('https://a'), 'https://a'); QUnit.equal(resolver.resolveModule('https://a/b/c/d.js'), 'https://a/b/c/d.js'); // modules starting with file:// QUnit.equal(resolver.resolveModule('file://b/c/d'), 'file://b/c/d'); QUnit.equal(resolver.resolveModule('file://a'), 'file://a'); QUnit.equal(resolver.resolveModule('file://a/b/c/d.js'), 'file://a/b/c/d.js'); QUnit.equal(loader.ModuleIdResolver._normalizeModuleId('./a'), 'a'); QUnit.equal(loader.ModuleIdResolver._normalizeModuleId('./././a'), 'a'); QUnit.equal(loader.ModuleIdResolver._normalizeModuleId('a/b/c/d/../../../../../e/f/g/h'), '../e/f/g/h'); QUnit.equal(loader.ModuleIdResolver._normalizeModuleId('file:///c:/a/b/c/d/e.f.g/h/./j'), 'file:///c:/a/b/c/d/e.f.g/h/j'); QUnit.equal(loader.ModuleIdResolver._normalizeModuleId('../../ab/../a'), '../../a'); }); QUnit.module('ModuleManager'); QUnit.test('Loading 3 simple modules', () => { QUnit.expect(3); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'a1.js') { mm.enqueueDefineAnonymousModule([], 'a1'); loadCallback(); } else if (scriptPath === 'a2.js') { mm.defineModule('a2', [], 'a2', null, null); loadCallback(); } else { QUnit.ok(false); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a', ['a1', 'a2'], (a1: string, a2: string) => { QUnit.equal(a1, 'a1'); QUnit.equal(a2, 'a2'); return 'a'; }, null, null); QUnit.equal(mm.synchronousRequire('a'), 'a'); }); QUnit.test('Loading a plugin dependency', () => { QUnit.expect(5); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'plugin.js') { mm.enqueueDefineAnonymousModule([], { normalize: (pluginParam: string, normalize: (moduleId: string) => string) => { return normalize(pluginParam); }, load: (pluginParam: string, parentRequire: loader.IRelativeRequire, loadCallback: loader.IPluginLoadCallback, options: loader.IConfigurationOptions) => { parentRequire([pluginParam], (v: any) => loadCallback(v)); } }); loadCallback(); } else if (scriptPath === 'a/b/d.js') { mm.enqueueDefineAnonymousModule([], 'r'); loadCallback(); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a/b/c', ['../../plugin!./d', 'require'], (r: any, req: any) => { QUnit.equal(r, 'r'); QUnit.equal(req.toUrl('./d.txt'), 'a/b/d.txt'); return 'a/b/c'; }, null, null); QUnit.equal(mm.synchronousRequire('a/b/c'), 'a/b/c'); mm.defineModule('a2', ['./plugin!a/b/d'], (r: any) => { QUnit.equal(r, 'r'); return 'a2'; }, null, null); QUnit.equal(mm.synchronousRequire('a2'), 'a2'); }); QUnit.test('Loading a dependency cycle', () => { QUnit.expect(6); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'b.js') { mm.enqueueDefineAnonymousModule(['c'], (c: any) => { // This is how the cycle is broken. One of the modules receives undefined as the argument value QUnit.equal(c, 'c'); return 'b'; }); loadCallback(); } else if (scriptPath === 'c.js') { mm.enqueueDefineAnonymousModule(['a'], (a: any) => { // This is how the cycle is broken. One of the modules receives undefined as the argument value QUnit.deepEqual(a, {}); // QUnit.ok(typeof a === 'undefined'); return 'c'; }); loadCallback(); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a', ['b'], (b: any) => { QUnit.equal(b, 'b'); return 'a'; }, null, null); QUnit.equal(mm.synchronousRequire('a'), 'a'); QUnit.equal(mm.synchronousRequire('b'), 'b'); QUnit.equal(mm.synchronousRequire('c'), 'c'); }); QUnit.test('Using a local error handler immediate script loading failure', () => { QUnit.expect(1); // a -> b and b fails to load var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'b.js') { errorCallback('b.js not found'); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a', ['b'], (b: any) => { QUnit.equal(b, 'b'); return 'a'; }, (err) => { QUnit.equal(err.message, 'b.js not found'); }, null); }); QUnit.test('Using a local error handler secondary script loading failure', () => { QUnit.expect(1); // a -> b -> c and c fails to load var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'b.js') { mm.enqueueDefineAnonymousModule(['c'], (c: any) => { QUnit.equal(c, 'c'); return 'b'; }); loadCallback(); } else if (scriptPath === 'c.js') { errorCallback('c.js not found'); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a', ['b'], (b: any) => { QUnit.ok(false); }, (err) => { QUnit.equal(err.message, 'c.js not found'); }, null); }); QUnit.test('RelativeRequire error handler', () => { QUnit.expect(1); const dne = 'Does not exist'; var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { errorCallback(new Error(dne)); }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('a/b/d', ['require'], (relativeRequire) => { relativeRequire(['doesnotexist'], undefined, (err: Error) => { QUnit.deepEqual(err.message, dne); }); return 'a/b/d'; }, null, null); }); QUnit.module('FallBack Tests'); QUnit.test('No path config', () => { QUnit.expect(1); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'a.js') { errorCallback('a.js not found'); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('first', ['a'], () => { QUnit.ok(false, 'a should not be found'); }, (err) => { QUnit.ok(true, 'a should not be found'); }, null); }); QUnit.test('With path config', () => { QUnit.expect(1); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'alocation.js') { errorCallback('alocation.js not found'); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.configure({ paths: { a: 'alocation.js' } }, false); mm.defineModule('first', ['a'], () => { QUnit.ok(false, 'a should not be found'); }, (err) => { QUnit.ok(true, 'a should not be found'); }, null); }); QUnit.test('With one fallback', () => { QUnit.expect(1); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'alocation.js') { errorCallback('alocation.js not found'); } else if (scriptPath === 'afallback.js') { mm.enqueueDefineAnonymousModule([], () => { return 'a'; }); loadCallback(); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.configure({ paths: { a: ['alocation.js', 'afallback.js'] } }, false); mm.defineModule('first', ['a'], () => { QUnit.ok(true, 'a was found'); }, (err) => { QUnit.ok(false, 'a was not found'); }, null); }); QUnit.test('With two fallbacks', () => { QUnit.expect(1); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { if (scriptPath === 'alocation.js') { errorCallback('alocation.js not found'); } else if (scriptPath === 'afallback.js') { errorCallback('afallback.js not found'); } else if (scriptPath === 'anotherfallback.js') { mm.enqueueDefineAnonymousModule([], () => { return 'a'; }); loadCallback(); } else { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); } }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.configure({ paths: { a: ['alocation.js', 'afallback.js', 'anotherfallback.js'] } }, false); mm.defineModule('first', ['a'], () => { QUnit.ok(true, 'a was found'); }, (err) => { QUnit.ok(false, 'a was not found'); }, null); }); QUnit.module('Bugs'); QUnit.test('Bug #11710: [loader] Loader can enter a stale-mate when the last dependency to resolve is a (missing) plugin dependency', () => { QUnit.expect(2); // A script loader that captures the load request for 'plugin.js' var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); // Define the resolved plugin value mm.defineModule('plugin!pluginParam', [], () => { return { value: 5 }; }, (err) => { QUnit.ok(false); }, null); // Ask for the plugin mm.defineModule('a', ['plugin!pluginParam'], (b: any) => { QUnit.equal(b.value, 5); return { value: b.value * 2 }; }, (err) => { QUnit.ok(false); }, null); // Depend on a module that asks for the plugin mm.defineModule('b', ['a'], (a: any) => { QUnit.equal(a.value, 10); }, (err) => { QUnit.ok(false); }, null); }); QUnit.test('Bug #12024: [loader] Should not append .js to URLs containing query string', () => { var config = new loader.Configuration(new loader.Environment(), { baseUrl: 'prefix', paths: { 'searchBoxJss': 'http://services.social.microsoft.com/search/Widgets/SearchBox.jss?boxid=HeaderSearchTextBox&btnid=HeaderSearchButton&brand=Msdn&loc=en-us&Refinement=198,234&focusOnInit=false&iroot=vscom&emptyWatermark=true&searchButtonTooltip=Search here' } }); // No .js is appended QUnit.equal(config.moduleIdToPaths('searchBoxJss'), 'http://services.social.microsoft.com/search/Widgets/SearchBox.jss?boxid=HeaderSearchTextBox&btnid=HeaderSearchButton&brand=Msdn&loc=en-us&Refinement=198,234&focusOnInit=false&iroot=vscom&emptyWatermark=true&searchButtonTooltip=Search here'); }); QUnit.test('Bug #12020: [loader] relative (synchronous) require does not normalize plugin argument that follows "!"', () => { QUnit.expect(3); var scriptLoader: loader.IScriptLoader = { load: (moduleManager: AMDLoader.IModuleManager, scriptPath: string, loadCallback: () => void, errorCallback: (err: any) => void) => { QUnit.ok(false, 'Unexpected scriptPath: ' + scriptPath); }, }; var mm = new loader.ModuleManager(new loader.Environment(), scriptLoader, null, null); mm.defineModule('plugin!a/b/c', [], () => { QUnit.ok(true); return 'plugin!a/b/c'; }, null, null); mm.defineModule('a/b/d', ['require'], (relativeRequire) => { QUnit.ok(true); QUnit.equal(relativeRequire('plugin!./c'), 'plugin!a/b/c'); return 'a/b/d'; }, null, null); }); QUnit.test('Utilities.fileUriToFilePath', () => { var test = (isWindows: boolean, input: string, expected: string) => { QUnit.equal(loader.Utilities.fileUriToFilePath(isWindows, input), expected, 'Result for ' + input); }; test(true, 'file:///c:/alex.txt', 'c:/alex.txt'); test(true, 'file://monacotools/isi.txt', '//monacotools/isi.txt'); test(true, 'file://monacotools1/certificates/SSL/', '//monacotools1/certificates/SSL/'); test(false, 'file:///c:/alex.txt', '/c:/alex.txt'); test(false, 'file://monacotools/isi.txt', 'monacotools/isi.txt'); test(false, 'file://monacotools1/certificates/SSL/', 'monacotools1/certificates/SSL/'); }); QUnit.test('Utilities.containsQueryString', () => { var test = (input: string, expected: boolean) => { QUnit.equal(loader.Utilities.containsQueryString(input), expected, 'Result for ' + input); }; test('http://www.microsoft.com/something?q=123&r=345#bangbang', true); test('http://www.microsoft.com/something#bangbang', false); test('http://www.microsoft.com/something#bangbang?asd=3', false); test('http://www.microsoft.com/something#?asd=3', false); });
the_stack
import * as errors from 'balena-errors'; import type { ResourceAlternateKey } from '../../typings/pinejs-client-core'; import type { Organization, OrganizationMembership, OrganizationMembershipRoles, OrganizationMembershipTag, PineOptions, PineSubmitBody, InjectedDependenciesParam, } from '..'; import { mergePineOptions } from '../util'; const RESOURCE = 'organization_membership'; type ResourceKey = | number | ResourceAlternateKey< Pick<OrganizationMembership, 'user' | 'is_member_of__organization'> >; export interface OrganizationMembershipCreationOptions { organization: string | number; username: string; roleName?: OrganizationMembershipRoles; } const getOrganizationMembershipModel = function ( deps: InjectedDependenciesParam, getOrganization: ( handleOrId: string | number, options?: PineOptions<Organization>, ) => Promise<Organization>, ) { const { pine } = deps; const { addCallbackSupportToModule } = require('../util/callbacks') as typeof import('../util/callbacks'); const { buildDependentResource } = require('../util/dependent-resource') as typeof import('../util/dependent-resource'); const tagsModel = buildDependentResource<OrganizationMembershipTag>( { pine }, { resourceName: 'organization_membership_tag', resourceKeyField: 'tag_key', parentResourceName: 'organization_membership', async getResourceId(membershipId: string | number): Promise<number> { // @ts-expect-error const membership = await exports.get(membershipId); return membership.id; }, }, ); const getRoleId = async (roleName: string) => { const role = await pine.get({ resource: 'organization_membership_role', id: { name: roleName, }, options: { $select: 'id', }, }); // Throw if the user provided a roleName, but we didn't find that role if (!role) { throw new errors.BalenaOrganizationMembershipRoleNotFound(roleName); } return role.id; }; const exports = { /** * @summary Get a single organization membership * @name get * @public * @function * @memberof balena.models.organization.membership * * @description * This method returns a single organization membership. * * @param {number|Object} membershipId - the id or an object with the unique `user` & `is_member_of__organization` numeric pair of the membership * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - organization membership * @returns {Promise} * * @example * balena.models.organization.membership.get(5).then(function(memberships) { * console.log(memberships); * }); * * @example * balena.models.organization.membership.get(5, function(error, memberships) { * console.log(memberships); * }); */ async get( membershipId: ResourceKey, options: PineOptions<OrganizationMembership> = {}, ): Promise<OrganizationMembership> { if ( typeof membershipId !== 'number' && typeof membershipId !== 'object' ) { throw new errors.BalenaInvalidParameterError( 'membershipId', membershipId, ); } const result = await pine.get({ resource: RESOURCE, id: membershipId, options, }); if (result == null) { throw new errors.BalenaError( `Organization Membership not found: ${membershipId}`, ); } return result; }, /** * @summary Get all organization memberships * @name getAll * @public * @function * @memberof balena.models.organization.membership * * @description * This method returns all organization memberships. * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - organization memberships * @returns {Promise} * * @example * balena.models.organization.membership.getAll().then(function(memberships) { * console.log(memberships); * }); * * @example * balena.models.organization.membership.getAll(function(error, memberships) { * console.log(memberships); * }); */ getAll( options: PineOptions<OrganizationMembership> = {}, ): Promise<OrganizationMembership[]> { return pine.get({ resource: RESOURCE, options, }); }, /** * @summary Get all memberships by organization * @name getAllByOrganization * @public * @function * @memberof balena.models.organization.membership * * @description * This method returns all organization memberships for a specific organization. * * @param {String|Number} handleOrId - organization handle (string) or id (number). * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - organization memberships * @returns {Promise} * * @example * balena.models.organization.membership.getAllByOrganization('MyOrg').then(function(memberships) { * console.log(memberships); * }); * * @example * balena.models.organization.membership.getAllByOrganization(123).then(function(memberships) { * console.log(memberships); * }); * * @example * balena.models.organization.membership.getAllByOrganization(123, function(error, memberships) { * console.log(memberships); * }); */ async getAllByOrganization( handleOrId: number | string, options: PineOptions<OrganizationMembership> = {}, ): Promise<OrganizationMembership[]> { const { id } = await getOrganization(handleOrId, { $select: 'id', }); return await exports.getAll( mergePineOptions( { $filter: { is_member_of__organization: id } }, options, ), ); }, /** * @summary Creates a new membership for an organization * @name create * @public * @function * @memberof balena.models.organization.membership * * @description This method adds a user to an organization by their usename. * * @param {Object} options - membership creation parameters * @param {String|Number} options.organization - organization handle (string), or id (number) * @param {String} options.username - the username of the balena user that will become a member * @param {String} [options.roleName="member"] - the role name to be granted to the membership * * @fulfil {Object} - organization membership * @returns {Promise} * * @example * balena.models.organization.membership.create({ organization: "myorg", username: "user123", roleName: "member" }).then(function(membership) { * console.log(membership); * }); * * @example * balena.models.organization.membership.create({ organization: 53, username: "user123" }, function(error, membership) { * console.log(membership); * }); */ async create({ organization, username, roleName, }: OrganizationMembershipCreationOptions): Promise<OrganizationMembership> { const [{ id }, roleId] = await Promise.all([ getOrganization(organization, { $select: 'id' }), roleName ? getRoleId(roleName) : undefined, ]); type OrganizationMembershipBase = Omit<OrganizationMembership, 'user'>; type OrganizationMembershipPostBody = OrganizationMembershipBase & { username: string; }; const body: PineSubmitBody<OrganizationMembershipPostBody> = { username, is_member_of__organization: id, }; if (roleName) { body.organization_membership_role = roleId; } return (await pine.post<OrganizationMembershipBase>({ resource: RESOURCE, body, })) as OrganizationMembership; }, /** * @summary Changes the role of an organization member * @name changeRole * @public * @function * @memberof balena.models.organization.membership * * @description This method changes the role of an organization member. * * @param {Number|Object} idOrUniqueKey - the id or an object with the unique `user` & `is_member_of__organization` numeric pair of the membership that will be changed * @param {String} roleName - the role name to be granted to the membership * * @returns {Promise} * * @example * balena.models.organization.membership.changeRole(123, "member").then(function() { * console.log('OK'); * }); * * @example * balena.models.organization.membership.changeRole({ * user: 123, * is_member_of__organization: 125, * }, "member").then(function() { * console.log('OK'); * }); * * @example * balena.models.organization.membership.changeRole(123, "administrator", function(error) { * console.log('OK'); * }); */ async changeRole( idOrUniqueKey: ResourceKey, roleName: string, ): Promise<void> { const roleId = await getRoleId(roleName); await pine.patch<OrganizationMembership>({ resource: 'organization_membership', id: idOrUniqueKey, body: { organization_membership_role: roleId, }, }); }, /** * @summary Remove a membership * @name remove * @public * @function * @memberof balena.models.organization.membership * * @param {Number} id - organization membership id * @returns {Promise} * * @example * balena.models.organization.membership.remove(123); * * @example * balena.models.organization.membership.remove({ * user: 123, * is_member_of__application: 125, * }); * * @example * balena.models.organization.membership.remove(123,function(error) { * if (error) throw error; * ... * }); */ async remove(idOrUniqueKey: ResourceKey): Promise<void> { await pine.delete({ resource: RESOURCE, id: idOrUniqueKey }); }, /** * @namespace balena.models.organization.memberships.tags * @memberof balena.models.organization.memberships */ tags: addCallbackSupportToModule({ /** * @summary Get all organization membership tags for an organization * @name getAllByOrganization * @public * @function * @memberof balena.models.organization.memberships.tags * * @param {String|Number} handleOrId - organization handle (string) or id (number). * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - organization membership tags * @returns {Promise} * * @example * balena.models.organization.memberships.tags.getAllByOrganization('MyOrg').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.organization.memberships.tags.getAllByOrganization(999999).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.organization.memberships.tags.getAllByOrganization('MyOrg', function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ async getAllByOrganization( handleOrId: string | number, options?: PineOptions<OrganizationMembershipTag>, ): Promise<OrganizationMembershipTag[]> { if (options == null) { options = {}; } const { id } = await getOrganization(handleOrId, { $select: 'id', }); return await tagsModel.getAll( mergePineOptions( { $filter: { organization_membership: { $any: { $alias: 'om', $expr: { om: { is_member_of__organization: id } }, }, }, }, }, options, ), ); }, /** * @summary Get all organization membership tags for all memberships of an organization * @name getAllByOrganizationMembership * @public * @function * @memberof balena.models.organization.memberships.tags * * @param {Number} membershipId - organization membership id (number). * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - organization membership tags * @returns {Promise} * * @example * balena.models.organization.memberships.tags.getAllByOrganizationMembership(5).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.organization.memberships.tags.getAllByOrganizationMembership(5, function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAllByOrganizationMembership: tagsModel.getAllByParent, /** * @summary Get all organization membership tags * @name getAll * @public * @function * @memberof balena.models.organization.memberships.tags * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - organization membership tags * @returns {Promise} * * @example * balena.models.organization.memberships.tags.getAll().then(function(tags) { * console.log(tags); * }); * * @example * balena.models.organization.memberships.tags.getAll(function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAll: tagsModel.getAll, /** * @summary Set an organization membership tag * @name set * @public * @function * @memberof balena.models.organization.memberships.tags * * @param {Number} handleOrId - organization handle (string) or id (number). * @param {String} tagKey - tag key * @param {String|undefined} value - tag value * * @returns {Promise} * * @example * balena.models.organization.memberships.tags.set(5, 'EDITOR', 'vim'); * * @example * balena.models.organization.memberships.tags.set(5, 'EDITOR', 'vim', function(error) { * if (error) throw error; * }); */ set: tagsModel.set, /** * @summary Remove an organization membership tag * @name remove * @public * @function * @memberof balena.models.organization.memberships.tags * * @param {Number} handleOrId - organization handle (string) or id (number). * @param {String} tagKey - tag key * @returns {Promise} * * @example * balena.models.organization.memberships.tags.remove(5, 'EDITOR'); * * @example * balena.models.organization.memberships.tags.remove(5, 'EDITOR', function(error) { * if (error) throw error; * }); */ remove: tagsModel.remove, }), }; return exports; }; export default getOrganizationMembershipModel;
the_stack
import fse from "fs-extra"; import { dirname, join, relative } from "path"; import { assert, ASTContext, ASTNodeFactory, ASTReader, CompilationOutput, CompileFailedError, compileJson, compileJsonData, CompileResult, compileSol, compileSourceString, ContractDefinition, ContractKind, FunctionDefinition, FunctionKind, FunctionStateMutability, FunctionVisibility, getABIEncoderVersion, isSane, SourceUnit, SrcRangeMap, Statement, StatementWithChildren, VariableDeclaration } from "solc-typed-ast"; import { rewriteImports } from "../ast_to_source_printer"; import { AnnotationExtractionContext, AnnotationFilterOptions, AnnotationMap, AnnotationMetaData, AnnotationTarget, buildAnnotationMap, gatherContractAnnotations, gatherFunctionAnnotations, MacroError, PropertyMetaData, SyntaxError, UnsupportedByTargetError, UserFunctionDefinitionMetaData } from "../instrumenter/annotations"; import { getCallGraph } from "../instrumenter/callgraph"; import { CHA, getCHA } from "../instrumenter/cha"; import { AbsDatastructurePath, interposeMap } from "../instrumenter/custom_maps"; import { findDeprecatedAnnotations, Warning } from "../instrumenter/deprecated_warnings"; import { generateUtilsContract, instrumentContract, instrumentFunction, instrumentStatement, UnsupportedConstruct } from "../instrumenter/instrument"; import { InstrumentationContext } from "../instrumenter/instrumentation_context"; import { findStateVarUpdates } from "../instrumenter/state_vars"; import { instrumentStateVars } from "../instrumenter/state_var_instrumenter"; import { ScribbleFactory } from "../instrumenter/utils"; import { MacroDefinition, readMacroDefinitions } from "../macros"; import { flattenUnits } from "../rewriter/flatten"; import { merge } from "../rewriter/merge"; import { AnnotationType, NodeLocation } from "../spec-lang/ast"; import { scUnits, SemError, SemMap, STypeError, tcUnits, TypeEnv } from "../spec-lang/tc"; import { buildOutputJSON, dedup, flatten, generateInstrumentationMetadata, getOr, isChangingState, isExternallyVisible, Location, MacroFile, ppLoc, Range, searchRecursive, SolFile, SourceFile, SourceMap } from "../util"; import { YamlSchemaError } from "../util/yaml"; import cli from "./scribble_cli.json"; const commandLineArgs = require("command-line-args"); const commandLineUsage = require("command-line-usage"); function error(msg: string): never { console.error(msg); process.exit(1); } /// TODO: Eventually make this support returning multiple lines function getSrcLine(l: Range | Location): string { const startLoc = "start" in l ? l.start : l; const lineStart = startLoc.offset - startLoc.column; let lineEnd = startLoc.file.contents.indexOf("\n", lineStart); lineEnd = lineEnd == -1 ? startLoc.file.contents.length : lineEnd; return startLoc.file.contents.slice(lineStart, lineEnd); } /// TODO: Eventually make this support underlining a range spanning multiple liens function ppSrcLine(l: Range | Location): string[] { const startLoc = "start" in l ? l.start : l; const marker = " ".repeat(startLoc.column) + ("end" in l ? "^".repeat(l.end.offset - l.start.offset) : "^"); return [ppLoc(startLoc) + ":", getSrcLine(startLoc), marker]; } function prettyError(type: string, message: string, location: NodeLocation | Location): never { let primaryLoc: Location; if ("offset" in location) { primaryLoc = location; } else if ("start" in location) { primaryLoc = location.start; } else { primaryLoc = location[0].start; } const descriptionLines = [`${ppLoc(primaryLoc)} ${type}: ${message}`]; if (location instanceof Array) { descriptionLines.push("In macro:"); descriptionLines.push(...ppSrcLine(location[0])); descriptionLines.push("Instantiated from:"); descriptionLines.push(...ppSrcLine(location[1])); } else { descriptionLines.push(...ppSrcLine(location)); } error(descriptionLines.join("\n")); } function ppWarning(warn: Warning): string[] { const start = "start" in warn.location ? warn.location.start : warn.location; return [`${ppLoc(start)} Warning: ${warn.msg}`, getSrcLine(warn.location)]; } function compile( fileName: string, type: "source" | "json", compilerVersion: string, remapping: string[], compilerSettings: any ): CompileResult { const astOnlyOutput = [ CompilationOutput.AST, CompilationOutput.ABI, CompilationOutput.DEVDOC, CompilationOutput.USERDOC ]; if (fileName === "--") { const content = fse.readFileSync(0, { encoding: "utf-8" }); fileName = "stdin"; return type === "json" ? compileJsonData( fileName, JSON.parse(content), compilerVersion, remapping, astOnlyOutput, compilerSettings ) : compileSourceString( fileName, content, compilerVersion, remapping, astOnlyOutput, compilerSettings ); } if (!fileName || !fse.existsSync(fileName)) { throw new Error("Path not found"); } const stats = fse.statSync(fileName); if (!stats.isFile()) { throw new Error("Target is not a file"); } return type === "json" ? compileJson(fileName, compilerVersion, remapping, astOnlyOutput, compilerSettings) : compileSol(fileName, compilerVersion, remapping, astOnlyOutput, compilerSettings); } /** * Not all contracts in the CHA need to have contract-wide invariants instrumentation. * * If we consider the CHA to consist of disjoint DAGs, then a contract needs contract-invariant * instrumentation IFF at least one contract in it's DAG has contract invariant annotations. * * @param cha - contract inheritance hierarchy * @param annotMap - map with extracted contract annotations */ function computeContractsNeedingInstr( cha: CHA<ContractDefinition>, annotMap: AnnotationMap ): Set<ContractDefinition> { // Find the contracts needing instrumentaion by doing bfs starting from the annotated contracts const wave = [...annotMap.entries()] .filter( ([n, annots]) => n instanceof ContractDefinition && annots.filter( (annot) => annot instanceof PropertyMetaData && annot.type === AnnotationType.Invariant ).length > 0 ) .map(([contract]) => contract); const visited = new Set<ContractDefinition>(); while (wave.length > 0) { const cur = wave.pop() as ContractDefinition; if (visited.has(cur)) continue; visited.add(cur); for (const parent of cha.parents.get(cur) as ContractDefinition[]) { if (!visited.has(parent)) wave.push(parent); } for (const child of cha.children.get(cur) as Set<ContractDefinition>) { if (!visited.has(child)) wave.push(child); } } return visited; } function detectMacroDefinitions( path: string, defs: Map<string, MacroDefinition>, sources: SourceMap ): void { const fileNames = searchRecursive(path, (fileName) => fileName.endsWith(".scribble.yaml")); for (const fileName of fileNames) { const data = fse.readFileSync(fileName, { encoding: "utf-8" }); const macroFile = new MacroFile(fileName, data); sources.set(fileName, macroFile); readMacroDefinitions(macroFile, defs); } } function instrumentFiles( ctx: InstrumentationContext, annotMap: AnnotationMap, contractsNeedingInstr: Set<ContractDefinition> ) { const units = ctx.units; const worklist: Array<[AnnotationTarget, AnnotationMetaData[]]> = []; const stateVarsWithAnnot: VariableDeclaration[] = []; if (ctx.varInterposingQueue.length > 0) { interposeMap(ctx, ctx.varInterposingQueue, units); } for (const unit of units) { const contents = ctx.files.get(unit.sourceEntryKey); assert(contents !== undefined, `Missing source for ${unit.absolutePath}`); for (const contract of unit.vContracts) { const contractAnnot = getOr(annotMap, contract, []); const needsStateInvariantInstr = contractsNeedingInstr.has(contract); const userFuns = contractAnnot.filter( (annot) => annot instanceof UserFunctionDefinitionMetaData ); // Nothing to instrument on interfaces if (contract.kind === ContractKind.Interface) { continue; } if (needsStateInvariantInstr || userFuns.length > 0) { worklist.push([contract, contractAnnot]); assert( ![ContractKind.Library, ContractKind.Interface].includes(contract.kind), `Shouldn't be instrumenting ${contract.kind} ${contract.name} with contract invs` ); } for (const stateVar of contract.vStateVariables) { const stateVarAnnots = getOr(annotMap, stateVar, []); if (stateVarAnnots.length > 0) { stateVarsWithAnnot.push(stateVar); } } const allProperties = gatherContractAnnotations(contract, annotMap); const allowedFuncProp = allProperties.filter( (annot) => annot instanceof PropertyMetaData && [ AnnotationType.IfSucceeds, AnnotationType.Try, AnnotationType.Require ].includes(annot.parsedAnnot.type) ); for (const fun of contract.vFunctions) { // Skip functions without a body if (fun.vBody === undefined) { continue; } let annotations = gatherFunctionAnnotations(fun, annotMap); if ( (fun.visibility == FunctionVisibility.External || fun.visibility == FunctionVisibility.Public) && fun.stateMutability !== FunctionStateMutability.Pure && fun.stateMutability !== FunctionStateMutability.View ) { annotations = annotations.concat(allowedFuncProp); } /** * We interpose on functions if either of these is true * a) They have annotations * b) They are external or public AND they modify state (not constant/pure/view) AND they are not the constructor AND they are not fallback/receive * * Note: Constructors are instrumented in instrumentContract, not by instrumentFunction. fallback() and receive() don't check state invariants. */ if ( annotations.length > 0 || (needsStateInvariantInstr && isExternallyVisible(fun) && isChangingState(fun) && contract.kind === ContractKind.Contract && fun.kind === FunctionKind.Function) ) { worklist.push([fun, annotations]); } } } } // Finally add in all of the assertions to the worklist for (const [target, annots] of annotMap.entries()) { if ( (target instanceof Statement || target instanceof StatementWithChildren) && annots.length > 0 ) { worklist.push([target, annots]); } } for (const [target, annotations] of worklist) { if (target instanceof ContractDefinition) { instrumentContract(ctx, annotations, target, contractsNeedingInstr.has(target)); } else if (target instanceof FunctionDefinition) { const contract = target.vScope; assert( contract instanceof ContractDefinition, `Function instrumentation allowed only on contract funs` ); instrumentFunction(ctx, annotations, target, contractsNeedingInstr.has(contract)); } else { assert( target instanceof Statement || target instanceof StatementWithChildren, `State vars handled below` ); instrumentStatement(ctx, annotations, target); } } if (stateVarsWithAnnot.length > 0) { const stateVarUpdates = findStateVarUpdates(ctx.units, ctx); instrumentStateVars(ctx, annotMap, stateVarUpdates); } ctx.finalize(); } const params = cli as any; let options = params[1].optionList; for (const option of options) { option.type = (global as any)[option.type]; } try { options = commandLineArgs(params[1].optionList); } catch (e: any) { console.error(e.message); process.exit(1); } function oneOf(input: any, options: string[], msg: string): any { if (!options.includes(input)) { error(msg); } return input; } function writeOut(contents: string, fileName: string) { if (fileName === "--") { console.log(contents); } else { fse.writeFileSync(fileName, contents); } } function makeUtilsUnit( utilsOutputDir: string, factory: ASTNodeFactory, version: string, ctx: InstrumentationContext ): SourceUnit { let utilsPath = "__scribble_ReentrancyUtils.sol"; let utilsAbsPath = "__scribble_ReentrancyUtils.sol"; if (utilsOutputDir !== "--") { utilsPath = join(utilsOutputDir, "__scribble_ReentrancyUtils.sol"); utilsAbsPath = join(fse.realpathSync(utilsOutputDir), "__scribble_ReentrancyUtils.sol"); } return generateUtilsContract(factory, utilsPath, utilsAbsPath, version, ctx); } function copy(from: string, to: string, options: any): void { if (!options.quiet) { console.error(`Copying ${from} to ${to}`); } fse.copyFileSync(from, to); } function move(from: string, to: string, options: any): void { if (!options.quiet) { console.error(`Moving ${from} to ${to}`); } fse.moveSync(from, to, { overwrite: true }); } function remove(filePath: string, options: any): void { if (!options.quiet) { console.error(`Removing ${filePath}`); } fse.removeSync(filePath); } /** * Given a map of the versions used for the various targets try and select a single version. * @param versionUsedMap */ function pickVersion(versionUsedMap: Map<string, string>): string { const versions = [...new Set([...versionUsedMap.values()])]; if (versions.length !== 1) { error( `Multiple compiler versions detected: ${versions}. Please specify an exact version to use with '--compiler-version'.` ); } return versions[0]; } const pkg = fse.readJSONSync(join(__dirname, "../../package.json"), { encoding: "utf-8" }); if ("version" in options) { console.log(pkg.version); } else if ("help" in options || !("solFiles" in options)) { const usage = commandLineUsage(params); console.log(usage); } else { const targets: string[] = options.solFiles; const addAssert = "no-assert" in options ? false : true; const inputMode: "source" | "json" = oneOf( options["input-mode"], ["source", "json"], `Error: --input-mode must be either source or json` ); const pathRemapping: string[] = options["path-remapping"] ? options["path-remapping"].split(";") : []; const compilerVersion: string = options["compiler-version"] !== undefined ? options["compiler-version"] : "auto"; let compilerSettings: any; try { compilerSettings = options["compiler-settings"] !== undefined ? JSON.parse(options["compiler-settings"]) : undefined; } catch (e) { error( `--compiler-settings expects a valid JSON string, not ${options["compiler-settings"]}` ); } const filterOptions: AnnotationFilterOptions = {}; if (options["filter-type"]) { filterOptions.type = options["filter-type"]; } if (options["filter-message"]) { filterOptions.message = options["filter-message"]; } const targetDir = targets[0] !== "--" ? relative(process.cwd(), dirname(fse.realpathSync(targets[0]))) : targets[0]; const utilsOutputDir = options["utils-output-path"] === undefined ? targetDir : options["utils-output-path"]; const assertionMode: "log" | "mstore" = oneOf( options["user-assert-mode"], ["log", "mstore"], `Error: --user-assert-mode must be either log or mstore, not ${options["user-assert-mode"]}` ); const debugEvents: boolean = options["debug-events"] !== undefined ? options["debug-events"] : false; const outputMode: "flat" | "files" | "json" = oneOf( options["output-mode"], ["flat", "files", "json"], `Error: --output-mode must be either 'flat', 'files' or 'json` ); const compilerVersionUsedMap: Map<string, string> = new Map(); const groupsMap: Map<string, SourceUnit[]> = new Map(); const ctxtsMap: Map<string, ASTContext> = new Map(); const filesMap: Map<string, Map<string, string>> = new Map(); const originalFiles: Set<string> = new Set(); const instrumentationFiles: Set<string> = new Set(); /** * Try to compile each target. */ for (const target of targets) { try { let targetResult: CompileResult; try { targetResult = compile( target, inputMode, compilerVersion, pathRemapping, compilerSettings ); } catch (e: any) { if (e instanceof CompileFailedError) { console.error(`Compile errors encountered for ${target}:`); for (const failure of e.failures) { console.error( failure.compilerVersion ? `SolcJS ${failure.compilerVersion}:` : `Unknown compiler` ); for (const error of failure.errors) { console.error(error); } } } else { console.error(e.message); } process.exit(1); } if (options["disarm"]) { for (const [targetName] of targetResult.files) { const originalFileName = targetName + ".original"; const instrFileName = targetName + ".instrumented"; if (fse.existsSync(originalFileName)) { originalFiles.add(originalFileName); } if (fse.existsSync(instrFileName)) { instrumentationFiles.add(instrFileName); } } if (utilsOutputDir !== "--") { const helperFileName = join(utilsOutputDir, "__scribble_ReentrancyUtils.sol"); if (fse.existsSync(helperFileName)) { instrumentationFiles.add(helperFileName); } } continue; } const compilerVersionUsed: string = targetResult.compilerVersion !== undefined ? targetResult.compilerVersion : compilerVersion; if (compilerVersionUsed === "auto") { error( `When passing in JSON you must specify an explicit compiler version with --compiler-version` ); } const ctx = new ASTContext(); const reader = new ASTReader(ctx); if (targetResult.files.size === 0) { error( `Missing source files in input. Did you pass in JSON without a sources entry?` ); } const originalUnits = reader.read(targetResult.data, undefined, targetResult.files); /** * This is inefficient, but we re-create the utils source unit for every target. This is due to * the inability to merge the id-spaces of the nodes of different compilation results. */ compilerVersionUsedMap.set(target, compilerVersionUsed); groupsMap.set(target, originalUnits); ctxtsMap.set(target, ctx); filesMap.set(target, targetResult.files); } catch (e) { console.error(e); process.exit(1); } } const instrumentationMarker = "/// This file is auto-generated by Scribble and shouldn't be edited directly.\n" + "/// Use --disarm prior to make any changes.\n"; if (options["disarm"]) { // In disarm mode we don't need to instrument - just replace the instrumented files with the `.original` files for (const originalFileName of originalFiles) { move(originalFileName, originalFileName.replace(".sol.original", ".sol"), options); } if (!options["keep-instrumented"]) { for (const instrFileName of instrumentationFiles) { remove(instrFileName, options); } } } else { // Without --disarm we need to instrument and output something. const contentsMap: SourceMap = new Map(); // First load any macros if `--macro-path` was specified const macros = new Map<string, MacroDefinition>(); if (options["macro-path"]) { try { detectMacroDefinitions(options["macro-path"], macros, contentsMap); } catch (e) { if (e instanceof YamlSchemaError) { prettyError(e.constructor.name, e.message, e.range); } throw e; } } /** * Merge the CHAs and file maps computed for each target */ const groups: SourceUnit[][] = targets.map( (target) => groupsMap.get(target) as SourceUnit[] ); const [mergedUnits, mergedCtx] = merge(groups); // Check that merging produced sane ASTs for (const mergedUnit of mergedUnits) { assert( isSane(mergedUnit, mergedCtx), `Merged unit ${mergedUnit.absolutePath} is insane` ); } for (const target of targets) { const units = groupsMap.get(target) as SourceUnit[]; const files = filesMap.get(target) as Map<string, string>; for (const unit of units) { if (!contentsMap.has(unit.absolutePath)) { if (files.has(unit.sourceEntryKey)) { contentsMap.set( unit.absolutePath, new SolFile(unit.absolutePath, files.get(unit.sourceEntryKey) as string) ); } } } } const cha = getCHA(mergedUnits); const compilerVersionUsed = pickVersion(compilerVersionUsedMap); const abiEncoderVersion = getABIEncoderVersion(mergedUnits, compilerVersionUsed); const callgraph = getCallGraph(mergedUnits, abiEncoderVersion); const annotExtractionCtx: AnnotationExtractionContext = { filterOptions, compilerVersion: compilerVersionUsed, macros }; let annotMap: AnnotationMap; try { annotMap = buildAnnotationMap(mergedUnits, contentsMap, annotExtractionCtx); } catch (e) { if ( e instanceof SyntaxError || e instanceof UnsupportedByTargetError || e instanceof MacroError ) { prettyError(e.constructor.name, e.message, e.range.start); } throw e; } const typeEnv = new TypeEnv(compilerVersionUsed, abiEncoderVersion); const semMap: SemMap = new Map(); let interposingQueue: Array<[VariableDeclaration, AbsDatastructurePath]>; try { // Type check tcUnits(mergedUnits, annotMap, typeEnv); // Semantic check interposingQueue = scUnits(mergedUnits, annotMap, typeEnv, semMap); } catch (err: any) { if (err instanceof STypeError || err instanceof SemError) { prettyError("TypeError", err.message, err.loc()); } else { error(`Internal error in type-checking: ${err.message}`); } } // If we are not outputting to stdout directly, print a summary of the // found annotations and warnings for things that were ignored but look like annotations if (!((outputMode === "flat" || outputMode === "json") && options.output === "--")) { const filesWithAnnots = new Set<SourceFile>(); let nAnnots = 0; for (const annots of annotMap.values()) { for (const annot of annots) { filesWithAnnots.add(annot.originalSourceFile); nAnnots++; } } if (nAnnots === 0) { console.log(`Found ${nAnnots} annotations.`); } else { console.log( `Found ${nAnnots} annotations in ${filesWithAnnots.size} different files.` ); } for (const warning of findDeprecatedAnnotations( mergedUnits, contentsMap, compilerVersionUsed )) { console.error(ppWarning(warning).join("\n")); } } /** * Walk over the computed CHA and compute: * 1. The set of contracts that have contract invariants (as the map contractInvs) * 2. The set of contracts that NEED contract instrumentation (because they, a parent of theirs, or a child of theirs has contract invariants) */ const contractsNeedingInstr = computeContractsNeedingInstr(cha, annotMap); const factory = new ScribbleFactory(mergedCtx); // Next we re-write the imports to fix broken alias references (Some // Solidity versions have broken references imports). mergedUnits.forEach((sourceUnit) => { if (contentsMap.has(sourceUnit.absolutePath)) { rewriteImports(sourceUnit, contentsMap, factory); } }); /** * Next try to instrument the merged SourceUnits. */ const instrCtx = new InstrumentationContext( factory, mergedUnits, assertionMode, options["cov-assertions"], addAssert, callgraph, cha, filterOptions, dedup(flatten(annotMap.values())), new Map(), contentsMap, compilerVersionUsed, debugEvents, new Map(), outputMode, typeEnv, semMap, interposingQueue ); const utilsUnit = makeUtilsUnit(utilsOutputDir, factory, compilerVersionUsed, instrCtx); try { // Check that none of the map state vars to be overwritten is aliased for (const [sVar] of interposingQueue) { instrCtx.crashIfAliased(sVar); } instrumentFiles(instrCtx, annotMap, contractsNeedingInstr); } catch (e) { if (e instanceof UnsupportedConstruct) { prettyError(e.name, e.message, e.range); } throw e; } const allUnits: SourceUnit[] = [...instrCtx.units, utilsUnit]; let modifiedFiles: SourceUnit[]; const newSrcMap: SrcRangeMap = new Map(); if (outputMode === "flat" || outputMode === "json") { // 1. Flatten all the source files in a single SourceUnit const version = pickVersion(compilerVersionUsedMap); const flatUnit = flattenUnits(allUnits, factory, options.output, version); modifiedFiles = [flatUnit]; // 2. Print the flattened unit const flatContents = instrCtx .printUnits(modifiedFiles, newSrcMap, instrumentationMarker) .get(flatUnit) as string; // 3. If the output mode is just 'flat' we just write out the contents now. if (outputMode === "flat") { writeOut(flatContents, options.output); } else { // 4. If the output mode is 'json' we have more work - need to re-compile the flattened code. let flatCompiled: CompileResult; try { flatCompiled = compileSourceString( `flattened.sol`, flatContents, version, pathRemapping, [CompilationOutput.ALL], compilerSettings ); } catch (e: any) { if (e instanceof CompileFailedError) { console.error(`Compile errors encountered for flattend instrumetned file:`); for (const failure of e.failures) { console.error( failure.compilerVersion ? `SolcJS ${failure.compilerVersion}:` : `Unknown compiler` ); for (const error of failure.errors) { console.error(error); } } } else { console.error(e.message); } process.exit(1); } // 5. Build the output and write it out const resultJSON = JSON.stringify( buildOutputJSON( instrCtx, flatCompiled, instrCtx.units, modifiedFiles, newSrcMap, pkg.version, options.output, options["arm"] !== undefined ), undefined, 2 ); writeOut(resultJSON, options.output); } } else { modifiedFiles = [...instrCtx.changedUnits, utilsUnit]; // 1. In 'files' mode first write out the files const newContents = instrCtx.printUnits( modifiedFiles, newSrcMap, instrumentationMarker ); // 2. For all changed files write out a `.instrumented` version of the file. for (const unit of instrCtx.changedUnits) { const instrumentedFileName = unit.absolutePath + ".instrumented"; if (!options.quiet) { console.error(`${unit.absolutePath} -> ${instrumentedFileName}`); } fse.writeFileSync(instrumentedFileName, newContents.get(unit) as string); } // 3. Write out the utils contract fse.writeFileSync(utilsUnit.absolutePath, newContents.get(utilsUnit) as string); // 4. Finally if --arm is passed put the instrumented files in-place if (options["arm"]) { for (const unit of instrCtx.changedUnits) { const instrumentedFileName = unit.absolutePath + ".instrumented"; const originalFileName = unit.absolutePath + ".original"; copy(unit.absolutePath, originalFileName, options); copy(instrumentedFileName, unit.absolutePath, options); } } } if (options["instrumentation-metadata-file"] !== undefined) { const metadata: any = generateInstrumentationMetadata( instrCtx, newSrcMap, instrCtx.units, modifiedFiles, options["arm"] !== undefined, pkg.version, options["output"] ); writeOut( JSON.stringify(metadata, undefined, 2), options["instrumentation-metadata-file"] ); } } }
the_stack
import { SchedulerLike, VirtualAction, VirtualTimeScheduler } from 'rxjs'; import { Observable, ObservableNotification, Subscription } from 'rxjs'; import { ReturnTypeWithArgs } from '../interfaces/ReturnTypeWithArgs'; import { parseObservableMarble } from '../marbles/parseObservableMarble'; import { SubscriptionMarbleToken } from '../marbles/SubscriptionMarbleToken'; import { TestMessage } from '../message/TestMessage'; import { TestMessageValue } from '../message/TestMessage'; import { AsyncAction, ColdObservable, HotObservable } from '../utils/coreInternalImport'; import { calculateSubscriptionFrame } from './calculateSubscriptionFrame'; /** * State to be bind into each function we'll create for testscheduler. */ interface SandboxState { coldObservables: Array<ColdObservable<any>>; hotObservables: Array<HotObservable<any>>; flushed: boolean; flushing: boolean; maxFrame: Readonly<number>; frameTimeFactor: number; scheduler: VirtualTimeScheduler; autoFlush: boolean; } /** * Naive utility fn to determine if given object is promise. */ const isPromise = <T = void>(obj: any): obj is Promise<T> => !!obj && Promise.resolve(obj) == obj; /** * Creates `createColdObservable` function. */ const getCreateColdObservable = (state: SandboxState) => { const { frameTimeFactor, maxFrame, scheduler } = state; function createColdObservable<T = string>( marble: string, value?: { [key: string]: T } | null, error?: any ): ColdObservable<T>; function createColdObservable<T = string>(message: Array<TestMessage<T>>): ColdObservable<T>; function createColdObservable<T = string>(...args: Array<any>): ColdObservable<T> { const [marbleValue, value, error] = args; if (typeof marbleValue === 'string' && marbleValue.indexOf(SubscriptionMarbleToken.SUBSCRIBE) !== -1) { throw new Error(`Cold observable cannot have subscription offset ${SubscriptionMarbleToken.SUBSCRIBE}`); } const messages = Array.isArray(marbleValue) ? marbleValue : (parseObservableMarble(marbleValue, value, error, false, frameTimeFactor, maxFrame) as any); const observable = new ColdObservable<T>(messages, scheduler); state.coldObservables.push(observable); return observable; } return createColdObservable; }; /** * Creates `createHotObservable` function. */ const getCreateHotObservable = (state: SandboxState) => { const { frameTimeFactor, maxFrame, scheduler } = state; function createHotObservable<T = string>( marble: string, value?: { [key: string]: T } | null, error?: any ): HotObservable<T>; function createHotObservable<T = string>(message: Array<TestMessage<T>>): HotObservable<T>; function createHotObservable<T = string>(...args: Array<any>): HotObservable<T> { const [marbleValue, value, error] = args; const messages = Array.isArray(marbleValue) ? marbleValue : (parseObservableMarble(marbleValue, value, error, false, frameTimeFactor, maxFrame) as any); const subject = new HotObservable<T>(messages, scheduler); state.hotObservables.push(subject); return subject; } return createHotObservable; }; /** * Create `flush` functions for given scheduler. If `flushWithAsyncTick` specified, * will create flush function to schedule individual actions into native tick. * * As we don't inherit virtualtimescheduler anymore, only these functions should be * used to properly flush out actions. Calling `scheduler.flush()` will not do any work. */ function getSchedulerFlushFunctions( state: SandboxState, flushWithAsyncTick: true ): { flushUntil: (toFrame?: number) => Promise<void>; advanceTo: (toFrame?: number) => Promise<void>; }; function getSchedulerFlushFunctions( state: SandboxState, flushWithAsyncTick: false ): { flushUntil: (toFrame?: number) => void; advanceTo: (toFrame?: number) => void; }; function getSchedulerFlushFunctions(state: SandboxState, flushWithAsyncTick: boolean): any { const { maxFrame, autoFlush } = state; const flushUntil = (toFrame: number = maxFrame): Promise<void> | void => { if (state.flushing) { if (flushWithAsyncTick) { return Promise.resolve(); } } if (state.flushed) { throw new Error(`Cannot schedule to get marbles, scheduler's already flushed`); } while (state.hotObservables.length > 0) { state.hotObservables.shift()!.setup(); } state.flushing = true; /** * Custom loop actions to schedule flusing actions synchronously or asynchronously based on flag. * * For synchronous loop, it'll use plain `while` loop. In case of flushing with tick, each action * will be scheduled into promise instead. */ function loopActions( loopState: SandboxState, condition: (loopState: SandboxState) => boolean, fn: (loopState: SandboxState) => Error | undefined ): Promise<Error | undefined> | Error | undefined { if (!flushWithAsyncTick) { let fnResult; while (condition(loopState)) { fnResult = fn(loopState); if (!!fnResult) { break; } } return fnResult; } else { function loopWithTick(tickState: SandboxState, error?: Error): Promise<Error | undefined> { if (condition(tickState) && !error) { const p = new Promise<Error | undefined>((res) => res(fn(tickState))); return p.then((result: Error | undefined) => loopWithTick(tickState, result)); } else { return Promise.resolve(error); } } return loopWithTick(state); } } // flush actions via custom loop fn, as same as // https://github.com/kwonoj/rx-sandbox/blob/c2922e5c5e2503739c64af626f2861b1e1f38159/src/scheduler/TestScheduler.ts#L166-L173 const loopResult = loopActions( state, (flushState) => { const action = flushState.scheduler.actions[0]; return !!action && action.delay <= toFrame; }, (flushState) => { const action = flushState.scheduler.actions.shift()!; flushState.scheduler.frame = action.delay; return action.execute(action.state, action.delay); } ); const tearDown = (error?: Error) => { state.flushing = false; if (toFrame >= maxFrame) { state.flushed = true; } if (error) { const { actions } = state.scheduler; let action: AsyncAction<any> | null | undefined = null; while ((action = actions.shift())) { action.unsubscribe(); } throw error; } }; if (isPromise<Error | undefined>(loopResult)) { return loopResult.then((result) => tearDown(result)); } else { tearDown(loopResult); } }; const advanceTo = (toFrame: number) => { if (autoFlush) { const error = new Error('Cannot advance frame manually with autoflushing scheduler'); if (flushWithAsyncTick) { return Promise.reject(error); } throw error; } if (toFrame < 0 || toFrame < state.scheduler.frame) { const error = new Error(`Cannot advance frame, given frame is either negative or smaller than current frame`); if (flushWithAsyncTick) { return Promise.reject(error); } throw error; } const flushResult = flushUntil(toFrame); const tearDown = () => { state.scheduler.frame = toFrame; }; return isPromise(flushResult) ? flushResult.then(() => tearDown()) : tearDown(); }; return { flushUntil, advanceTo }; } type getMessages = <T = string>( observable: Observable<T>, unsubscriptionMarbles?: string | null ) => Array<TestMessage<T | Array<TestMessage<T>>>>; type getMessagesWithTick = <T = string>( observable: Observable<T>, unsubscriptionMarbles?: string | null ) => Promise<Array<TestMessage<T | Array<TestMessage<T>>>>>; /** * create getMessages function. Depends on flush, this'll either work asynchronously or synchronously. */ function createGetMessages(state: SandboxState, flush: () => Promise<any>): getMessagesWithTick; function createGetMessages(state: SandboxState, flush: () => void): getMessages; function createGetMessages(state: SandboxState, flush: Function): Function { const { frameTimeFactor, autoFlush } = state; const materializeInnerObservable = <T>(observable: Observable<any>, outerFrame: number): Array<TestMessage<T>> => { const innerObservableMetadata: Array<TestMessage<T>> = []; const pushMetaData = (notification: ObservableNotification<T>) => innerObservableMetadata.push(new TestMessageValue<T>(state.scheduler.frame - outerFrame, notification)); observable.subscribe({ next: (value) => pushMetaData({ kind: 'N', value }), error: (error) => pushMetaData({ kind: 'E', error }), complete: () => pushMetaData({ kind: 'C' }), }); return innerObservableMetadata; }; const getMessages = <T = string>(observable: Observable<T>, unsubscriptionMarbles: string | null = null) => { const { subscribedFrame, unsubscribedFrame } = calculateSubscriptionFrame( observable, unsubscriptionMarbles, frameTimeFactor ); const observableMetadata: Array<TestMessage<T | Array<TestMessage<T>>>> = []; const pushMetadata = (notification: ObservableNotification<T | Array<TestMessage<T>>>) => observableMetadata.push(new TestMessageValue<T | Array<TestMessage<T>>>(state.scheduler.frame, notification)); let subscription: Subscription | null = null; state.scheduler.schedule(() => { subscription = observable.subscribe({ next: (value: T) => pushMetadata({ kind: 'N', value: value instanceof Observable ? materializeInnerObservable<T>(value, state.scheduler.frame) : value, }), error: (error: any) => pushMetadata({ kind: 'E', error }), complete: () => pushMetadata({ kind: 'C' }), }); }, subscribedFrame); if (unsubscribedFrame !== Number.POSITIVE_INFINITY) { state.scheduler.schedule(() => subscription?.unsubscribe(), unsubscribedFrame); } const flushResult = autoFlush ? flush() : null; if (!isPromise(flushResult)) { return observableMetadata; } return flushResult.then(() => observableMetadata); }; return getMessages; } const initializeSandboxState = (autoFlush: boolean, frameTimeFactor: number, maxFrameValue: number): SandboxState => { const maxFrame = maxFrameValue * frameTimeFactor; return { coldObservables: [], hotObservables: [], flushed: false, flushing: false, maxFrame, frameTimeFactor, scheduler: new VirtualTimeScheduler(VirtualAction, Number.POSITIVE_INFINITY), autoFlush, }; }; interface BaseSchedulerInstance { /** * Test scheduler created for sandbox instance */ scheduler: SchedulerLike; /** * Creates a hot observable using marble diagram DSL, or TestMessage. */ hot: ReturnType<typeof getCreateHotObservable>; /** * Creates a cold obsrevable using marbld diagram DSL, or TestMessage. */ cold: ReturnType<typeof getCreateColdObservable>; /** * Maxmium frame number scheduler will flush into. */ maxFrame: number; } interface SchedulerInstance extends BaseSchedulerInstance { /** * Flush out currently scheduled observables, only until reaches frame specfied. */ advanceTo: ReturnType<typeof getSchedulerFlushFunctions>['advanceTo']; /** * Flush out currently scheduled observables, fill values returned by `getMarbles`. */ flush: () => void; /** * Get array of observable value's metadata TestMessage<T> from observable * created via `hot` or `cold`. Returned array will be filled once scheduler flushes * scheduled actions, either via explicit `flush` or implicit `autoFlush`. */ getMessages: ReturnType<typeof createGetMessages>; } interface AsyncSchedulerInstance extends BaseSchedulerInstance { /** * Flush out currently scheduled observables, only until reaches frame specfied. */ advanceTo: ReturnTypeWithArgs<typeof getSchedulerFlushFunctions, [SandboxState, true]>['advanceTo']; /** * Flush out currently scheduled observables, fill values returned by `getMarbles`. */ flush: () => Promise<void>; /** * Get array of observable value's metadata TestMessage<T> from observable * created via `hot` or `cold`. Returned array will be filled once scheduler flushes * scheduled actions, either via explicit `flush` or implicit `autoFlush`. */ getMessages: ReturnTypeWithArgs<typeof createGetMessages, [SandboxState, () => Promise<void>]>; } /** * Creates a new instance of virtualScheduler, along with utility functions for sandbox assertions. */ function createTestScheduler( autoFlush: boolean, frameTimeFactor: number, maxFrameValue: number, flushWithAsyncTick: true ): AsyncSchedulerInstance; function createTestScheduler( autoFlush: boolean, frameTimeFactor: number, maxFrameValue: number, flushWithAsyncTick: false ): SchedulerInstance; function createTestScheduler( autoFlush: boolean, frameTimeFactor: number, maxFrameValue: number, flushWithAsyncTick: boolean ): any { const sandboxState = initializeSandboxState(autoFlush, frameTimeFactor, maxFrameValue); const { flushUntil, advanceTo } = getSchedulerFlushFunctions(sandboxState, flushWithAsyncTick as any); const flush = () => flushUntil(); return { scheduler: sandboxState.scheduler, advanceTo, getMessages: createGetMessages(sandboxState, flush), cold: getCreateColdObservable(sandboxState), hot: getCreateHotObservable(sandboxState), flush, maxFrame: sandboxState.maxFrame, }; } export { createTestScheduler, SchedulerInstance, AsyncSchedulerInstance };
the_stack
import { ExpNum } from 'src/backend/symExpressions'; import { fetchAddr, isSize } from '../backend/backUtils'; import { Context, ContextSet } from '../backend/context'; import { CodeSource, ShValue, SVBool, SVInt, SVType } from '../backend/sharpValues'; import { LCImpl } from '.'; import { LCBase } from './libcall'; // use with assert // e.g.) assert LibCall.guard.require_lt(3, 5, "3 < 5") export namespace GuardLCImpl { // LibCall.guard.require_lt(a, b, message): add require(a < b, message) to this context. return true export function require_lt( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_lt': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [addrA, addrB, messageAddr] = params; const a = fetchAddr(addrA, heap); const b = fetchAddr(addrB, heap); const msg = fetchAddr(messageAddr, heap); if ( !(a?.type === SVType.Int || a?.type === SVType.Float) || !(b?.type === SVType.Int || b?.type === SVType.Float) ) { return ctx .warnWithMsg(`from 'LibCall.guard.require_lt': operand is not a numeric`, source) .toSetWith(SVBool.create(true, source)); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_lt: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx.require(ctx.genLt(a.value, b.value, source), msg.value, source).return(SVBool.create(true, source)); } export function require_lte( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_lte': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [addrA, addrB, messageAddr] = params; const a = fetchAddr(addrA, heap); const b = fetchAddr(addrB, heap); const msg = fetchAddr(messageAddr, heap); if ( !(a?.type === SVType.Int || a?.type === SVType.Float) || !(b?.type === SVType.Int || b?.type === SVType.Float) ) { return ctx .warnWithMsg(`from 'LibCall.guard.require_lte': operand is not a numeric`, source) .toSetWith(SVBool.create(true, source)); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_lte: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx.require(ctx.genLte(a.value, b.value, source), msg.value, source).return(SVBool.create(true, source)); } export function require_eq( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_eq': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [addrA, addrB, messageAddr] = params; const a = fetchAddr(addrA, heap); const b = fetchAddr(addrB, heap); const msg = fetchAddr(messageAddr, heap); if ( !(a?.type === SVType.Int || a?.type === SVType.Float || a?.type === SVType.String) || !(b?.type === SVType.Int || b?.type === SVType.Float || b?.type === SVType.String) ) { return ctx .warnWithMsg(`from 'LibCall.guard.require_eq': operand is not a numeric or string`, source) .toSetWith(SVBool.create(true, source)); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_eq: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx.require(ctx.genEq(a.value, b.value, source), msg.value, source).return(SVBool.create(true, source)); } export function require_neq( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_neq': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [addrA, addrB, messageAddr] = params; const a = fetchAddr(addrA, heap); const b = fetchAddr(addrB, heap); const msg = fetchAddr(messageAddr, heap); if ( !(a?.type === SVType.Int || a?.type === SVType.Float || a?.type === SVType.String) || !(b?.type === SVType.Int || b?.type === SVType.Float || b?.type === SVType.String) ) { return ctx .warnWithMsg(`from 'LibCall.guard.require_neq': operand is not a numeric or string`, source) .toSetWith(SVBool.create(true, source)); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_neq: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx.require(ctx.genNeq(a.value, b.value, source), msg.value, source).return(SVBool.create(true, source)); } export function require_broadcastable( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_broadcastable': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [leftAddr, rightAddr, messageAddr] = params; const left = fetchAddr(leftAddr, heap); const right = fetchAddr(rightAddr, heap); const msg = fetchAddr(messageAddr, heap); if (!isSize(left)) { return ctx .warnWithMsg(`from 'LibCall.guard.require_broadcastable': left is not a Size type`, source) .toSet(); } if (!isSize(right)) { return ctx .warnWithMsg(`from 'LibCall.guard.require_broadcastable': right is not a Size type`, source) .toSet(); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_broadcastable: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx .require(ctx.genBroadcastable(left.shape, right.shape, source), msg.value, source) .return(SVBool.create(true, source)); } export function require_shape_eq( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.guard.require_shape_eq': got insufficient number of argument: ${params.length}`, source ) .toSetWith(SVBool.create(true, source)); } const heap = ctx.heap; const [leftAddr, rightAddr, messageAddr] = params; const left = fetchAddr(leftAddr, heap); const right = fetchAddr(rightAddr, heap); const msg = fetchAddr(messageAddr, heap); if (!isSize(left)) { return ctx.warnWithMsg(`from 'LibCall.guard.require_shape_eq': left is not a Size type`, source).toSet(); } if (!isSize(right)) { return ctx.warnWithMsg(`from 'LibCall.guard.require_shape_eq': right is not a Size type`, source).toSet(); } if (!(msg?.type === SVType.String && typeof msg.value === 'string')) { return ctx .warnWithMsg(`from 'LibCall.guard.require_shape_eq: message is not a constant string`, source) .toSetWith(SVBool.create(true, source)); } return ctx .require(ctx.genEq(left.shape, right.shape, source), msg.value, source) .return(SVBool.create(true, source)); } // return new symbolic variable that is equal with given value. // if given value is constant, return that constant export function new_symbol_int( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx .warnWithMsg( `from 'LibCall.guard.new_symbol_int': got insufficient number of argument: ${params.length}`, source ) .toSet(); } const heap = ctx.heap; const [nameAddr, valueAddr] = params; const name = fetchAddr(nameAddr, heap); const value = fetchAddr(valueAddr, heap); if (name?.type !== SVType.String || typeof name.value !== 'string') { return ctx .warnWithMsg(`from 'LibCall.guard.new_symbol_int': name is not a constant string`, source) .toSet(); } if (value?.type !== SVType.Int) { return ctx.warnWithMsg(`from 'LibCall.guard.new_symbol_int': value is not an integer type`, source).toSet(); } const valueRng = ctx.getCachedRange(value.value); if (valueRng?.isConst()) { return ctx.toSetWith(SVInt.create(valueRng.start, value.source)); } const newCtx = ctx.genIntEq(name.value, value.value, source); const exp = SVInt.create(newCtx.retVal, source); return newCtx.toSetWith(exp); } export const libCallImpls: { [key: string]: LCImpl } = { require_lt, require_lte, require_eq, require_neq, require_broadcastable, require_shape_eq, new_symbol_int, }; } export const libCallMap: Map<string, LCImpl> = new Map([...Object.entries(GuardLCImpl.libCallImpls)]);
the_stack
import {Component, ElementRef, OnInit, AfterViewInit, ViewChild, Output, EventEmitter } from '@angular/core'; import {StemPlayer} from "../../classes/stem-player"; import {VisualTracks} from "../visual-tracks/visual-tracks"; import {GUI} from 'dat.gui'; import {Stem} from "../../classes/stem" import {Track} from "../../interfaces/track"; import {EventsService} from "../../services/events.service"; import {Intent} from "../../interfaces/intent"; import {StemService} from "../../services/stem.service"; import {SuggestionService} from "../../services/suggestion.service"; import {Angulartics2} from "angulartics2"; import indefiniteArticle from "indefinite-article" import {FallbackService} from "../../services/fallback.service"; declare var window; // Constants const SFXInterval = 5000; @Component({ selector: 'app-multitrack-editor', templateUrl: './multitrack-editor.component.html', styleUrls: ['./multitrack-editor.component.scss'] }) export class MultitrackEditorComponent implements OnInit, AfterViewInit { @ViewChild('visualTracksCanvas') canvasRef: ElementRef; public SHARED_TRACK_NO_AUTOPLAY: string = 'Press anywhere on the screen and make sure your sound is on to hear your friend’s mix.'; public SHARED_TRACK: string = 'Make sure your sound is on to hear your friend’s mix.'; public DEFAULT: string = 'Tap anywhere on the screen to do a quick sound check.'; public NUM_TRACKS: number = 4; public MAX_VOLUME: number = 10; public MIN_VOLUME: number = -25; public FEEDBACK_TIME: number = 1700; public multitracks; public visualTracks; public addedStems = []; public addedSFX = []; public tracks: Array<Track>; public volume: number = 0; public fifthTrackShowing: boolean; public button; public voiceButtonVisible: boolean = false; public isTouch: boolean; public showMobilePlay = false; public numberOfSuccessfulRequests: number = 0; public numberOfUnSuccessfulRequests: number = 0; public sfxTimeouts: Array<any> = []; public hideCanvas = false; public canAutoplay: boolean; public mobileIntroText: string = 'Tap anywhere to begin.'; public isJamming: boolean; public audioCxtActivated: boolean; public isOnJamPage: boolean; public seenIntro: boolean; public isSharedSong: boolean; public startCopy: string = 'Start Jamming'; public showIntroText:boolean = true; public fallback; constructor( public eventsService: EventsService, public stemService: StemService, public suggestionsService: SuggestionService, public angulartics2: Angulartics2, public fallbackService: FallbackService ) { this.isTouch = 'ontouchstart' in document.documentElement; let AudioContext = window.AudioContext || window.webkitAudioContext; let audioContextTest = new AudioContext(); this.canAutoplay = (audioContextTest && audioContextTest.state === 'running'); } ngOnInit() { // Check browser support from service this.fallbackService.checkBrowserSupport(true).then(res => { this.fallback = ((res) ? res : null); }); this.eventsService.on('intent', (data: Intent) => { var matchingAddedStem: Stem; var excludedIds: string = ''; if (data.action) { if (typeof data.parameters.instrument === 'string') { matchingAddedStem = this.addedStems.find((stem: Stem) => { return stem.instrument === data.parameters.instrument.toLowerCase(); }); } // Search for match by instrument if the first one didn't work if (!matchingAddedStem) { if (typeof data.parameters.instrument === 'string') { matchingAddedStem = this.addedStems.find((stem: Stem) => { return stem.type === data.parameters.instrument.toLowerCase(); }); } } if (data.parameters.sfx) { data.action = 'sfx' } let history = {action: data.action, instrument: '', genre: '', sfx: ''}; if (data.parameters.instrument) { history.instrument = data.parameters.instrument; } if (data.parameters.genre) { history.genre = data.parameters.genre; } if (data.parameters.sfx) { history.sfx = data.parameters.sfx; } this.suggestionsService.addHistory(history); if (data.action !== 'input.unknown') { this.numberOfSuccessfulRequests++; this.angulartics2.eventTrack.next({ action: 'Intent', properties: { category: 'Successful_Action', label: this.numberOfSuccessfulRequests }}); } else { this.numberOfUnSuccessfulRequests++; this.angulartics2.eventTrack.next({ action: 'Intent', properties: { category: 'Unsuccessful_Action', label: this.numberOfSuccessfulRequests }}); } switch (data.action) { case 'sfx': this.stemService.getSfx(data.parameters.sfx).then((result) => { if (result && result[0].file) { if (!this.multitracks) { this.multitracks = new StemPlayer(); } this.fireAnalyticsIntentTag('SFX_Success', data, result); this.multitracks.playOneOff(result[0].file.mp3).then((duration) => { this.showFxViz(duration); }); this.addedSFX.push({ sfxId: result[0].sfxId, loop: false, tag: result[0].tag, }); setTimeout(() => { this.eventsService.broadcast('savedSFX', this.addedSFX); }, 300); this.eventsService.broadcast('actionHappened'); } }).catch(() => { this.eventsService.broadcast('updateCommandText', {text: 'Couldn’t find one.', time: 1700}); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('SFX_Fail', data); }); break; case 'pause': this.eventsService.broadcast('updateCommandText', {text: 'You’re Paused', time: this.FEEDBACK_TIME}); this.multitracks.pause(); this.eventsService.broadcast('actionHappened'); break; case 'resume': this.eventsService.broadcast('updateCommandText', {text: 'Resuming', time: this.FEEDBACK_TIME}); this.multitracks.resume(); this.eventsService.broadcast('actionHappened'); break; case 'speedUp': this.eventsService.broadcast('updateCommandText', {text: 'Ok, making it faster.', time: this.FEEDBACK_TIME}); this.stemService.increaseTempo(); this.reloadStems(); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Speed_Up', data); break; case 'slowDown': this.eventsService.broadcast('updateCommandText', {text: 'Ok, making it slower.', time: this.FEEDBACK_TIME}); this.stemService.decreaseTempo(); this.reloadStems(); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Slow_Down', data); break; case 'superFast': this.eventsService.broadcast('updateCommandText', {text: 'Ok, making it as fast as I can.', time: this.FEEDBACK_TIME}); this.stemService.tempo = this.stemService.MAX_TEMPO; this.reloadStems(); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Super_Fast', data); break; case 'superSlow': this.eventsService.broadcast('updateCommandText', {text: 'Ok, making it as slow as I can.', time: this.FEEDBACK_TIME}); this.stemService.tempo = this.stemService.MIN_TEMPO; this.reloadStems(); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Super_Slow', data); break; case 'normalSpeed': this.eventsService.broadcast('updateCommandText', {text: 'Ok, making it back to normal speed.', time: this.FEEDBACK_TIME}); this.stemService.tempo = this.stemService.NORMAL_TEMPO; this.reloadStems(); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Normal_Speed', data); break; case 'volumeUp': if (matchingAddedStem) { matchingAddedStem.increaseVolume(); this.eventsService.broadcast('updateCommandText', { text: 'The ' + matchingAddedStem.track.name + '’s volume is at ' + matchingAddedStem.getDisplayVolume(), time: this.FEEDBACK_TIME}); this.fireAnalyticsIntentTag('Volume_Up_Track', data, matchingAddedStem); } else { this.increaseVolume(); this.eventsService.broadcast('updateCommandText', { text: 'The song’s volume is at ' + this.getDisplayVolume(), time: this.FEEDBACK_TIME}); this.fireAnalyticsIntentTag('Volume_Up_Song', data); } this.eventsService.broadcast('actionHappened'); break; case 'volumeDown': if (matchingAddedStem) { matchingAddedStem.decreaseVolume(); this.eventsService.broadcast('updateCommandText', { text: 'The ' + matchingAddedStem.track.name + '’s volume is at ' + matchingAddedStem.getDisplayVolume(), time: this.FEEDBACK_TIME}); this.fireAnalyticsIntentTag('Volume_Down_Instrument', data, matchingAddedStem); } else { this.decreaseVolume(); this.eventsService.broadcast('updateCommandText', { text: 'The song’s volume is at ' + this.getDisplayVolume(), time: this.FEEDBACK_TIME}); this.fireAnalyticsIntentTag('Volume_Down_Song', data); } this.eventsService.broadcast('actionHappened'); break; case 'replaceInstrument': // replaceInstrument = 'give me a different guitar' if (matchingAddedStem && matchingAddedStem.id) { excludedIds = matchingAddedStem.id; } //continue… case 'addInstrument': let trackingPreface = (!excludedIds) ? 'Add_' : 'Replace_'; this.stemService.getStem(data.parameters.instrument, data.parameters.genre, null, excludedIds).then((stem: Stem) => { this.add(stem, true, matchingAddedStem); this.fireAnalyticsIntentTag(trackingPreface + 'Instrument_Success', data, stem, true); }, (failData) => { this.fireAnalyticsIntentTag(trackingPreface + 'Instrument_Fail', data, null, true); if (failData && failData.suggestions && failData.suggestions.length > 0) { let firstSuggestion = failData.suggestions[0]; let article = indefiniteArticle(firstSuggestion); let suggestions = `Don’t know that one. Try saying “Add ${article} ${failData.suggestions[0]}”.`; this.eventsService.broadcast('updateCommandText', {text: suggestions, time: 2000}); this.eventsService.broadcast('actionHappened'); } else { this.eventsService.broadcast('updateCommandText', {text: 'Don’t know that one. Try something else.', time: 1700}); this.eventsService.broadcast('actionHappened'); } }); break; case 'clear': this.clear(); this.eventsService.broadcast('updateCommandText', {text: 'You got it. Let’s jam again soon.', time: this.FEEDBACK_TIME}); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Clear', data); break; case 'changeGenre': // not supporting this anymore, maybe it tries to change genre for previous tracK break; case 'removeInstrument': if (matchingAddedStem) { this.remove(matchingAddedStem); this.eventsService.broadcast('updateCommandText', {text: `Ok, removed the ${matchingAddedStem.getDisplayName()}.`, time: this.FEEDBACK_TIME}); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Remove_Instrument', data, matchingAddedStem); } else { this.eventsService.broadcast('updateCommandText', {text: `Can’t remove ${data.parameters.instrument} if it’s not in play.`, time: this.FEEDBACK_TIME}); this.eventsService.broadcast('actionHappened'); this.fireAnalyticsIntentTag('Remove_Instrument_Fail', data); } break; case 'allInstruments': this.clear(); this.stemService.getSong(data.parameters.genres).then((stems) => { let stemsGenres = ''; let stemsIds = ''; Object.keys(stems).forEach( key => { this.add(stems[key], false); stemsGenres += stems[key].tag +','; stemsIds += stems[key].id +','; }); let genreList = ''; let length = data.parameters.genres.length; data.parameters.genres.forEach((genre, i) => { genreList += genre; if (i + 1 !== length) { genreList +=', '; } else { genreList +=' '; } }); this.eventsService.broadcast('updateCommandText', {text: 'Here’s a ' + genreList + 'song.', time: this.FEEDBACK_TIME}); this.fireAnalyticsIntentTag('Make_Song', data, null, false, genreList + ';' + stemsGenres + ';' + stemsIds); }).catch(() => { this.fireAnalyticsIntentTag('Make_Song_Fail', data); this.eventsService.broadcast('updateCommandText', {text: 'Don’t know that one. Try something else.', time: this.FEEDBACK_TIME}); }); break; case 'singleInstrument': this.eventsService.broadcast('updateCommandText', {text: 'Playing a single instrument', time: this.FEEDBACK_TIME}); this.addedStems.forEach((stem) => { if ( !matchingAddedStem || (matchingAddedStem && matchingAddedStem.instrument !== stem.instrument) ) { setTimeout(() => { this.remove(stem); }, 100); } }); this.fireAnalyticsIntentTag('Single_Instrument', data, matchingAddedStem); this.eventsService.broadcast('actionHappened'); break; case 'input.unknown': default: this.eventsService.broadcast('updateCommandText', {text: 'I didn’t understand. Try again.', time: 2300}); this.eventsService.broadcast('actionHappened'); this.angulartics2.eventTrack.next({ action: 'Intent', properties: { category: 'Unknown' }}); break; } } }); this.eventsService.on('speechStart', () => { if (this.multitracks) { this.multitracks.setVolume(this.MIN_VOLUME); } }); this.eventsService.on('speechEnd', () => { if (this.multitracks) { this.multitracks.setVolume(this.volume); this.eventsService.broadcast('volumeChange', false); // Unmute on add } }); this.eventsService.on('clearTracks', () => { this.clear(); this.mute(); this.addedSFX.forEach((timeout) => { clearTimeout(timeout); }) }); this.eventsService.on('volumeChange', (mute) => { mute ? this.mute() : this.unmute(); }); this.eventsService.on('songPause', (state) => { if (this.multitracks) { ((!state) ? this.multitracks.pause() : this.multitracks.resume()); ((!state) ? this.visualTracks.stopAnimation() : this.visualTracks.startAnimation()); } }); this.eventsService.on('hideVoiceButton', (state) => { this.voiceButtonVisible = false; }); this.eventsService.on('showVoiceButton', (state) => { if (!this.isTouch) { this.voiceButtonVisible = true; } }); // Hide canvas when tooltip shows // iOS bug that doesn't allow copy/paste when canvas is up this.eventsService.on('hideCanvas', (state) => { if (state) { this.canvasRef.nativeElement.remove(); } }); let mobileTouchInitHandler = () => { if (!this.seenIntro && this.isOnJamPage) { this.touchAudio(); this.unmute(); this.addDrums(); this.seenIntro = true; } //document.removeEventListener('touchstart', mobileTouchInitHandler); }; document.addEventListener('touchstart', mobileTouchInitHandler); this.eventsService.on('offJamPage', () => { this.isOnJamPage = false; this.seenIntro = false; this.isSharedSong = false; this.showIntroText = true; document.dispatchEvent(new CustomEvent('hideButton')); }); this.eventsService.on('onJamPage', () => { if (this.isSharedSong) { this.mobileIntroText = (this.canAutoplay) ? this.SHARED_TRACK : this.SHARED_TRACK_NO_AUTOPLAY; this.isOnJamPage = true; this.seenIntro = true; this.showIntroText = true; this.startCopy = 'Add to Your Friend’s Mix'; } else { this.mobileIntroText = this.DEFAULT; this.isOnJamPage = true; this.seenIntro = false; this.showIntroText = true; this.startCopy = 'Start Jamming'; } }); document.addEventListener('onMicEnableError', () => { alert('To use MixLab, you’ll need to grant microphone access. You may need to also refresh the page.'); }); } // First add must be called on a user action (like a click) add(stem: Stem, showResponse: boolean = false, previousStem: Stem = null) { if (!this.multitracks) { this.multitracks = new StemPlayer(); } if (showResponse) { let title = stem.getDisplayName(); this.eventsService.broadcast('updateCommandText', { text: 'Adding ' + title, time: this.FEEDBACK_TIME}); } this.multitracks.loadTrack(stem).then((data) => { let removing = false; let slot = stem.track.slot; let i = this.addedStems.length; while(i--) { if (this.addedStems[i].track.slot === stem.track.slot) { this.remove(this.addedStems[i]); removing = true; } } let timeoutLen = (removing) ? 500 : 0; setTimeout(() => { this.addedStems.push(stem); let style = 'flat'; if (slot === 5) { style = 'gradient'; if (!this.fifthTrackShowing) { this.visualTracks.showFiveTracks(); this.fifthTrackShowing = true; } } if (previousStem) { style = 'gradient'; setTimeout(() => { this.visualTracks.tracks[slot].set({ fillType: 'flat' }); }, 3500); } this.visualTracks.tracks[slot].set({ type: stem.type, analyser: data.analyser, name: stem.getDisplayName(), fillType: style }); this.suggestionsService.addInstrument(stem.type); this.eventsService.broadcast('actionHappened'); }, timeoutLen); // Broadcast stems to share service this.eventsService.broadcast('savedStems', this.addedStems); }); } // Clear all active stems clear() { let i = this.addedStems.length; while(i--) { this.remove(this.addedStems[i]); } this.stemService.tempo = null; } // Get loaded stem data from /jam state guard ngAfterViewInit() { this.visualTracks = new VisualTracks({ canvas: this.canvasRef.nativeElement, numberTracks: this.NUM_TRACKS }, this.eventsService); this.eventsService.on('loadedStems', (data) => { if (data) { this.isSharedSong = true; setTimeout(() => { let stemArray = []; let sfxArray = []; console.log('Loaded Saved Jam: ' + window.location.pathname.replace('/jam/', '')); // Get loaded track data then add them each to mulitrack if (data.tracks) { data.tracks.forEach((track) => { let newStem = { bpm: track.bpm, id: track.id, volume: track.volume, }; stemArray.push(newStem); }); this.stemService.getSavedStems(stemArray).then((stems: any[]) => { stems.forEach((data) => { this.add(data, false); }); }); } // Play sounds effects if (data.sfx) { data.sfx.forEach((track, index) => { this.playSFX(index, track, data.sfx.length); }); } }, 900); // Show mobile play overlay if (!this.canAutoplay) { this.showMobilePlay = true; } } }); } // Retrieve SFX data and play based on saved SFX phrase playSFX(index, track, total) { this.stemService.getSfx(track.tag).then((result: any[]) => { if (!this.multitracks) { this.multitracks = new StemPlayer(); } this.sfxTimeouts.push(setTimeout(() => { this.multitracks.playOneOff(result[0].file.mp3); this.showFxViz(); }, SFXInterval * (index + 1))); }); } remove(stem: Stem) { let trackName = (stem.track.name === 'wind' || stem.track.name === 'strings') ? '' : stem.track.name; this.multitracks.remove(stem); this.visualTracks.tracks[stem.track.slot].reset(); this.visualTracks.tracks[stem.track.slot].updateName(trackName); this.suggestionsService.removeInstrument(stem.type); let i = this.addedStems.length; while(i--) { if (this.addedStems[i].slug === stem.slug) { this.addedStems.splice(i, 1); } } if (stem.track.slot === 5) { this.visualTracks.hideFiveTracks(); this.fifthTrackShowing = false; } } increaseVolume() { this.volume += 5; this.volume = (this.volume < this.MAX_VOLUME) ? this.volume : this.MAX_VOLUME; if (this.multitracks) { this.multitracks.setVolume(this.volume); } } decreaseVolume() { this.volume -= 5; this.volume = (this.volume > this.MIN_VOLUME) ? this.volume : this.MIN_VOLUME; if (this.multitracks) { this.multitracks.setVolume(this.volume); } } getDisplayVolume() { let map = (x, in_min, in_max, out_min, out_max) => { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }; let volume = map(this.volume, this.MIN_VOLUME, this.MAX_VOLUME, 0, 100); //round to nearest 5th: return Math.ceil(volume / 5) * 5; } reloadStems(keepStem: boolean = true) { this.addedStems.forEach((stem: Stem) => { let previousVolume = stem.volume; let stemId = (keepStem) ? stem.id : null; let genre = (keepStem) ? stem.genre : null; let reload = ((type, genre, id, volume) => { this.stemService.getStem(type, genre, id).then((stem: Stem) => { this.add(stem); stem.volume = volume; }); })(stem.type, genre, stemId, previousVolume); }); } mute() { if (this.multitracks) { this.multitracks.setVolume(-100); } } unmute() { if (this.multitracks) { this.multitracks.setVolume(this.volume); } } arrayToSentence(arr) { let last = arr.pop(); return arr.join(', ') + ' or ' + last; } touchAudio() { if (!this.multitracks) { this.multitracks = new StemPlayer(); this.audioCxtActivated = true; } } // Play loaded song on mobile playLoaded() { this.eventsService.broadcast('playBtnClick'); this.showMobilePlay = false; if (this.multitracks) { this.multitracks.resume(); } } showFxViz(time: number = 3) { let stem = this.addedStems[Math.floor(Math.random()*this.addedStems.length)]; if (stem) { let slot = stem.track.slot; let adjustedTime = (time > 6) ? 6 : time; adjustedTime = (time < 2) ? 2 : time; this.visualTracks.tracks[slot].releaseBubble(0.1 + 0.8 * Math.random(), adjustedTime); } } fireAnalyticsIntentTag(category, intent: Intent = null, data = null, returnGenreTags = false, extra: string = null) { let tag: string = ''; //requested instrument data: if (intent && intent.parameters && (intent.parameters.genre || intent.parameters.instrument)) { let intentGenre = (typeof intent.parameters.genre === 'undefined') ? '': intent.parameters.genre; tag += `${intent.parameters.instrument};`; if (returnGenreTags) { tag += `${intentGenre};`; } } //returned instrument data: if (data && data.id && data.instrument) { let stemTag = (typeof data.tag === 'undefined') ? '': data.tag; tag += `${data.instrument};`; if (returnGenreTags) { tag += stemTag + ';' } tag += data.id + ';'; } //request sfx if (intent && intent.parameters && intent.parameters.sfx) { tag += `${intent.parameters.sfx};`; } //returned sfx: if (data && data[0] && data[0].sfxId) { let sfxTag = (typeof data[0].tag === 'undefined') ? '': data[0].tag; tag += `${sfxTag};${data[0].sfxId};`; } if (extra) { tag += extra + ';'; } this.angulartics2.eventTrack.next({ action: 'Intent', properties: { category: category, label: tag }}); } startMobile() { this.voiceButtonVisible = true; this.eventsService.broadcast('jamStart'); } addDrums() { this.mobileIntroText = 'Adjust your volume. You should be able to hear drums.'; this.stemService.getStem('drums', null) .then((stem: Stem) => { this.add(stem, false); }); } }
the_stack
import { android as AndroidApp } from "tns-core-modules/application"; import { screen } from "tns-core-modules/platform"; import { View } from "tns-core-modules/ui/core/view"; import { AnimationCurve } from "tns-core-modules/ui/enums"; import { Page } from "tns-core-modules/ui/page"; import { TabView } from "tns-core-modules/ui/tab-view"; import { ad } from "tns-core-modules/utils/utils"; import { ToolbarBase } from "./keyboard-toolbar.common"; import { topmost } from "tns-core-modules/ui/frame"; export class Toolbar extends ToolbarBase { private startPositionY: number; private lastHeight: number; private navbarHeight: number; private navbarHeightWhenKeyboardOpen: number; private isNavbarVisible: boolean; private lastKeyboardHeight: number; private onGlobalLayoutListener: android.view.ViewTreeObserver.OnGlobalLayoutListener; private thePage: any; private static supportVirtualKeyboardCheck; // private onScrollChangedListener: android.view.ViewTreeObserver.OnScrollChangedListener; constructor() { super(); this.verticalAlignment = "top"; // weird but true } protected _loaded(): void { setTimeout(() => this.applyInitialPosition(), 300); setTimeout(() => { const prepFocusEvents = (forView) => { forView.on("focus", () => { this.hasFocus = true; if (that.lastKeyboardHeight) { this.showToolbar(<View>this.content.parent); } }); forView.on("blur", () => { this.hasFocus = false; this.hideToolbar(<View>this.content.parent); }); }; let pg; if (topmost()) { pg = topmost().currentPage; } else { pg = this.content.parent; while (pg && !(pg instanceof Page)) { pg = pg.parent; } } this.thePage = pg; const forView = <View>this.thePage.getViewById(this.forId); if (forView) { prepFocusEvents(forView); return; } // let's see if we're inside a tabview, because of https://github.com/EddyVerbruggen/nativescript-keyboard-toolbar/issues/7 let p = this.thePage.parent; while (p && !(p instanceof TabView)) { p = p.parent; } if (p instanceof TabView) { p.on(TabView.selectedIndexChangedEvent, () => { let forView2 = p.getViewById(this.forId); if (forView2) { prepFocusEvents(forView2); p.off(TabView.selectedIndexChangedEvent); } }); } else { console.log(`\n⌨ ⌨ ⌨ Please make sure forId="<view id>" resolves to a visible view, or the toolbar won't render correctly! Example: <Toolbar forId="${this.forId || "myId"}" height="44">\n\n`); } }, 500); const that = this; this.onGlobalLayoutListener = new android.view.ViewTreeObserver.OnGlobalLayoutListener({ onGlobalLayout(): void { // this can happen during livesync - no problemo if (!that.content.android) { return; } const rect = new android.graphics.Rect(); that.content.android.getWindowVisibleDisplayFrame(rect); const newKeyboardHeight = (Toolbar.getUsableScreenSizeY() - rect.bottom) / screen.mainScreen.scale; if (newKeyboardHeight <= 0 && that.lastKeyboardHeight === undefined) { return; } if (newKeyboardHeight === that.lastKeyboardHeight) { return; } // TODO see if orientation needs to be accounted for: https://github.com/siebeprojects/samples-keyboardheight/blob/c6f8aded59447748266515afeb9c54cf8e666610/app/src/main/java/com/siebeprojects/samples/keyboardheight/KeyboardHeightProvider.java#L163 that.lastKeyboardHeight = newKeyboardHeight; if (that.hasFocus) { if (newKeyboardHeight <= 0) { that.hideToolbar(that.content.parent); } else { that.showToolbar(that.content.parent); } } } }); that.content.android.getViewTreeObserver().addOnGlobalLayoutListener(that.onGlobalLayoutListener); // that.content.android.getViewTreeObserver().addOnScrollChangedListener(that.onScrollChangedListener); } protected _unloaded(): void { this.content.android.getViewTreeObserver().removeOnGlobalLayoutListener(this.onGlobalLayoutListener); // this.content.android.getViewTreeObserver().removeOnScrollChangedListener(this.onScrollChangedListener); this.onGlobalLayoutListener = undefined; // this.onScrollChangedListener = undefined; } private showToolbar(parent): void { let navbarHeight = this.isNavbarVisible ? 0 : this.navbarHeight; // some devices (Samsung S8) with a hidden virtual navbar show the navbar when the keyboard is open, so subtract its height if (!this.isNavbarVisible) { const isNavbarVisibleWhenKeyboardOpen = this.thePage.getMeasuredHeight() < Toolbar.getUsableScreenSizeY() && (Toolbar.isVirtualNavbarHidden_butShowsWhenKeyboardIsOpen() || Toolbar.hasPermanentMenuKey()); if (isNavbarVisibleWhenKeyboardOpen) { // caching for (very minor) performance reasons if (!this.navbarHeightWhenKeyboardOpen) { this.navbarHeightWhenKeyboardOpen = Toolbar.getNavbarHeightWhenKeyboardOpen(); } navbarHeight = this.navbarHeightWhenKeyboardOpen; } } const animateToY = this.startPositionY - this.lastKeyboardHeight - (this.showWhenKeyboardHidden === true ? 0 : (this.lastHeight / screen.mainScreen.scale)) - navbarHeight; parent.animate({ translate: {x: 0, y: animateToY}, curve: AnimationCurve.cubicBezier(.32, .49, .56, 1), duration: 370 }).then(() => { }); } private hideToolbar(parent): void { const animateToY = this.showWhenKeyboardHidden === true && this.showAtBottomWhenKeyboardHidden !== true ? 0 : (this.startPositionY + this.navbarHeight); // console.log("hideToolbar, animateToY: " + animateToY); parent.animate({ translate: {x: 0, y: animateToY}, curve: AnimationCurve.cubicBezier(.32, .49, .56, 1), // perhaps make this one a little different as it's the same as the 'show' animation duration: 370 }).then(() => { }); } private applyInitialPosition(): void { if (this.startPositionY !== undefined) { return; } const parent = <View>this.content.parent; // at this point, topmost().currentPage is null, so do it like this: this.thePage = parent; while (!this.thePage && !this.thePage.frame) { this.thePage = this.thePage.parent; } const loc = parent.getLocationOnScreen(); if (!loc) { return; } const y = loc.y; const newHeight = parent.getMeasuredHeight(); // this is the bottom navbar - which may be hidden by the user.. so figure out its actual height this.navbarHeight = Toolbar.getNavbarHeight(); this.isNavbarVisible = !!this.navbarHeight; this.startPositionY = screen.mainScreen.heightDIPs - y - ((this.showWhenKeyboardHidden === true ? newHeight : 0) / screen.mainScreen.scale) - (this.isNavbarVisible ? this.navbarHeight : 0); if (this.lastHeight === undefined) { // this moves the keyboardview to the bottom (just move it offscreen/toggle visibility(?) if the user doesn't want to show it without the keyboard being up) if (this.showWhenKeyboardHidden === true) { if (this.showAtBottomWhenKeyboardHidden === true) { parent.translateY = this.startPositionY; } } else { parent.translateY = this.startPositionY + this.navbarHeight; } } else if (this.lastHeight !== newHeight) { parent.translateY = this.startPositionY + this.navbarHeight; } this.lastHeight = newHeight; } private static getNavbarHeight() { // detect correct height from: https://shiv19.com/how-to-get-android-navbar-height-nativescript-vanilla/ const context = (<android.content.Context>ad.getApplicationContext()); let navBarHeight = 0; let windowManager = context.getSystemService(android.content.Context.WINDOW_SERVICE); let d = windowManager.getDefaultDisplay(); let realDisplayMetrics = new android.util.DisplayMetrics(); d.getRealMetrics(realDisplayMetrics); let realHeight = realDisplayMetrics.heightPixels; let realWidth = realDisplayMetrics.widthPixels; let displayMetrics = new android.util.DisplayMetrics(); d.getMetrics(displayMetrics); let displayHeight = displayMetrics.heightPixels; let displayWidth = displayMetrics.widthPixels; if ((realHeight - displayHeight) > 0) { // Portrait navBarHeight = realHeight - displayHeight; } else if ((realWidth - displayWidth) > 0) { // Landscape navBarHeight = realWidth - displayWidth; } // Convert to device independent pixels and return return navBarHeight / context.getResources().getDisplayMetrics().density; } private static getNavbarHeightWhenKeyboardOpen() { const resources = (<android.content.Context>ad.getApplicationContext()).getResources(); const resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { return resources.getDimensionPixelSize(resourceId) / screen.mainScreen.scale; } return 0; } private static hasPermanentMenuKey() { return android.view.ViewConfiguration.get(<android.content.Context>ad.getApplicationContext()).hasPermanentMenuKey(); } private static isVirtualNavbarHidden_butShowsWhenKeyboardIsOpen(): boolean { if (Toolbar.supportVirtualKeyboardCheck !== undefined) { return Toolbar.supportVirtualKeyboardCheck; } const SAMSUNG_NAVIGATION_EVENT = "navigationbar_hide_bar_enabled"; try { // eventId is 1 in case the virtual navbar is hidden (but it shows when the keyboard opens) Toolbar.supportVirtualKeyboardCheck = android.provider.Settings.Global.getInt(AndroidApp.foregroundActivity.getContentResolver(), SAMSUNG_NAVIGATION_EVENT) === 1; } catch (e) { // non-Samsung devices throw a 'SettingNotFoundException' console.log(">> e: " + e); Toolbar.supportVirtualKeyboardCheck = false; } return Toolbar.supportVirtualKeyboardCheck; } private static getUsableScreenSizeY(): number { const screenSize = new android.graphics.Point(); AndroidApp.foregroundActivity.getWindowManager().getDefaultDisplay().getSize(screenSize); return screenSize.y; } }
the_stack
import get from 'lodash/get'; import groupBy from 'lodash/groupBy'; import { EdgeStyle, IUserEdge } from '@cylynx/graphin'; import { GraphData, EdgeStyleOptions, Edge, EdgeColor, ColorFixed, ColorLegend, EdgeWidth, ArrowOptions, } from '../../redux/graph/types'; import { DEFAULT_EDGE_STYLE, EDGE_DEFAULT_COLOR, edgeFontColor, } from '../../constants/graph-shapes'; import { normalizeColor } from './color-utils'; import { EdgePattern, mapEdgePattern } from '../shape-utils'; /** * Style an edge dataset based on a given method * * @param {GraphData} data * @param {EdgeStyleOptions} edgeStyleOptions * @return {*} {Edge[]} */ export const styleEdges = ( data: GraphData, edgeStyleOptions: EdgeStyleOptions, ): void => { // Separated out as it cannot be done in the loop if (edgeStyleOptions.width && edgeStyleOptions.width.id !== 'fixed') { styleEdgeWidthByProp(data, edgeStyleOptions.width); } // For perf reasons, batch style operations which require a single loop through nodes data.edges.forEach((edge: IUserEdge) => { const edgeStyle: Partial<EdgeStyle> = edge.style ?? {}; // If no property is found, set edge width to default if ( edgeStyleOptions.width.id === 'property' && !edgeStyleOptions.width.variable ) { styleLineWidth(edgeStyle, DEFAULT_EDGE_STYLE.lineWidth); } if (edgeStyleOptions.width && edgeStyleOptions.width.id === 'fixed') { styleLineWidth(edgeStyle, edgeStyleOptions.width.value); } if (edgeStyleOptions.pattern) { styleEdgePattern(edgeStyle, edgeStyleOptions.pattern); } if (edgeStyleOptions.color) { styleEdgeColor(edge, edgeStyle, edgeStyleOptions.color); } if (edgeStyleOptions.label) { styleEdgeLabel(edge, edgeStyle, edgeStyleOptions.label); } if (edgeStyleOptions.fontSize) { styleEdgeFontSize(edgeStyle, edgeStyleOptions.fontSize); } if (edgeStyleOptions.arrow) { styleEdgeArrow(edgeStyle, edgeStyleOptions.arrow); } Object.assign(edge, { style: edgeStyle }); }); // Assign edge type - line, loop or quadratic deriveEdgeType(data); }; /** * Utility function to map a edge property between a given range * * @param {Edge[]} edges * @param {string} propertyName * @param {[number, number]} visualRange */ export const mapEdgeWidth = ( edges: IUserEdge[], propertyName: string, visualRange: [number, number], ): void => { let minp = 9999999999; let maxp = -9999999999; edges.forEach((edge: IUserEdge) => { const edgeStyle: Partial<EdgeStyle> = edge.style ?? {}; const keyshapeStyle: Partial<EdgeStyle['keyshape']> = edgeStyle.keyshape ?? {}; let edgeLineWidth = Number(get(edge, propertyName)) ** (1 / 3); minp = edgeLineWidth < minp ? edgeLineWidth : minp; maxp = edgeLineWidth > maxp ? edgeLineWidth : maxp; edgeLineWidth = Number.isNaN(edgeLineWidth) ? DEFAULT_EDGE_STYLE.lineWidth : edgeLineWidth; Object.assign(edgeStyle, { keyshape: Object.assign(keyshapeStyle, { lineWidth: edgeLineWidth, stroke: keyshapeStyle.stroke ?? DEFAULT_EDGE_STYLE.keyshape.stroke, }), }); Object.assign(edge, { style: edgeStyle }); }); const rangepLength = maxp - minp; const rangevLength = visualRange[1] - visualRange[0]; edges.forEach((edge: IUserEdge) => { let edgeLineWidth = ((Number(get(edge, propertyName)) ** (1 / 3) - minp) / rangepLength) * rangevLength + visualRange[0]; edgeLineWidth = Number.isNaN(edgeLineWidth) ? DEFAULT_EDGE_STYLE.lineWidth : edgeLineWidth; Object.assign(edge.style.keyshape, { lineWidth: edgeLineWidth }); }); }; /** * Style Line Width based on Edge Filter Options * * @param {Partial<EdgeStyle>} edgeStyle * @param {number} lineWidth * @return {void} */ export const styleLineWidth = ( edgeStyle: Partial<EdgeStyle>, lineWidth: number, ): void => { const keyShapeStyle: Partial<EdgeStyle['keyshape']> = edgeStyle.keyshape ?? { stroke: DEFAULT_EDGE_STYLE.keyshape.stroke, }; Object.assign(keyShapeStyle, { lineWidth, }); Object.assign(edgeStyle, { keyshape: keyShapeStyle }); }; /** * Style Edge width based on given value in Edge Filter Options * * @param {GraphData} data * @param {EdgeWidth} option * @return {void} */ export const styleEdgeWidthByProp = ( data: GraphData, option: EdgeWidth, ): void => { if (option.id === 'property' && option.variable) { mapEdgeWidth(data.edges, option.variable, option.range); } }; /** * Style Edge Label based on given value in Edge Filter Options * @param {IUserEdge} edge * @param {Partial<EdgeStyle>} edgeStyle * @param {(string | string[])} label * @return {void} */ export const styleEdgeLabel = ( edge: IUserEdge, edgeStyle: Partial<EdgeStyle>, label: string | string[], ): void => { const labelStyle: Partial<EdgeStyle['label']> = edgeStyle.label ?? { fill: edgeFontColor.normal, fontSize: DEFAULT_EDGE_STYLE.label.fontSize, // @ts-ignore textAlign: DEFAULT_EDGE_STYLE.label.textAlign, offset: DEFAULT_EDGE_STYLE.label.offset, }; // display comma separated string if array and display only non-empty elements let customLabel = Array.isArray(label) ? label .map((field) => get(edge, field)) .filter((x) => x) .join(',') : get(edge, label) ?? ''; customLabel = customLabel.toString(); Object.assign(labelStyle, { value: customLabel, }); Object.assign(edgeStyle, { label: labelStyle }); }; export const styleEdgePattern = ( edgeStyle: Partial<EdgeStyle>, pattern: EdgePattern, ): void => { const edgeKeyshape: Partial<EdgeStyle['keyshape']> = edgeStyle.keyshape ?? {}; if (pattern === 'none') { delete edgeKeyshape.lineDash; return; } edgeKeyshape.lineDash = mapEdgePattern(pattern); Object.assign(edgeStyle, { keyshape: edgeKeyshape }); }; /** * Style Edge Font Size with given value by Edge Style Filter * * @param edgeStyle * @param fontSize * @return {void} */ export const styleEdgeFontSize = ( edgeStyle: Partial<EdgeStyle>, fontSize: number, ): void => { const edgeLabelStyle: Partial<EdgeStyle['label']> = edgeStyle.label ?? {}; edgeLabelStyle.fontSize = fontSize; Object.assign(edgeStyle, { label: edgeLabelStyle }); }; /** * Style Edge's arrow with given value by Edge Style Filter * @param edgeStyle * @param arrow * @return {void} */ export const styleEdgeArrow = ( edgeStyle: Partial<EdgeStyle>, arrow: ArrowOptions, ): void => { const edgeKeyShape: Partial<EdgeStyle['keyshape']> = edgeStyle.keyshape ?? {}; const isArrowDisplay: boolean = arrow === 'display'; if (isArrowDisplay === false) { edgeKeyShape.endArrow = { d: -1 / 2, path: `M 0,0 L 0,0 L 0,0 Z`, }; return; } Object.assign(edgeStyle, { keyshape: edgeKeyShape }); }; type MinMax = { min: number; max: number; }; /** * Check edge.data.value is array to determine if it is grouped * * @param {Edge} edge * @param {string} edgeWidth accesor function that maps to edge width */ export const isGroupEdges = (edge: Edge, edgeWidth: string): boolean => Array.isArray(get(edge, edgeWidth)); /** * Get minimum and maximum value of attribute that maps to edge width * * @param {GraphData} data * @param {string} edgeWidth accesor string that maps to edge width * @return {MinMax} */ export const getMinMaxValue = (data: GraphData, edgeWidth: string): MinMax => { const arrValue = []; for (const edge of data.edges) { if (isGroupEdges(edge, edgeWidth)) { // isGroupEdges ensures that it is of type number[]. Sum all values in array arrValue.push( (get(edge, edgeWidth) as number[]).reduce((a, b) => a + b, 0), ); } else { arrValue.push(get(edge, edgeWidth)); } } return { min: Math.min(...(arrValue as number[])), max: Math.max(...(arrValue as number[])), }; }; /** * Derive edge type (line, loop or quadratic) based on a given GraphData. * Assign type = loop if edges have the same source and target. * Assign type = line if the edge is the only edge connecting the two nodes. * Assign type = quadratic if the edge is one of many connecting the two nodes. * Quadratic edges are assigned an offset and bundled based on their source and target. * * @param {GraphData} data * @return {void} */ const deriveEdgeType = (data: GraphData): void => { const noLoopEdges: Edge[] = data.edges.filter( (edge: Edge) => edge.source !== edge.target, ); const groups = groupBy(noLoopEdges, (edge) => { return `${edge.source}-${edge.target}`; }); for (const edge of noLoopEdges) { const group = groups[`${edge.source}-${edge.target}`]; const revGroup = groups[`${edge.target}-${edge.source}`] || []; const isBidirection = revGroup.length > 0; if (group.length === 1 && !isBidirection) { Object.assign(edge.style.keyshape, { type: 'line' }); } // If single direction, alternate the edges offset e.g. 20, -20, 40, -40 else if (group.length > 1 && !isBidirection) { const index = group.findIndex((e) => e.id === edge.id); const EVEN_OFFSET = group.length % 2 === 0 ? 1 : 0; const OFFSET = Math.round((index + EVEN_OFFSET) / 2) * 20; const CURVE_OFFSET = index % 2 === 0 ? OFFSET : -OFFSET; Object.assign(edge.style.keyshape, { type: 'poly', poly: { distance: CURVE_OFFSET, }, }); } // If bidirectional, each direction will have it's own distinct group else { const index = group.findIndex((e) => e.id === edge.id); const OFFSET = (index + 1) * 20; Object.assign(edge.style.keyshape, { type: 'poly', poly: { distance: -OFFSET, }, }); } } }; /** * Style Edge Color based on values given by: * 1. Fixed edge color * 2. Legend Selection * * @param {Edge} edge * @param {Partial<EdgeStyle>} edgeStyle * @param {EdgeColor} option * @return {void} */ export const styleEdgeColor = ( edge: Edge, edgeStyle: Partial<EdgeStyle>, option: EdgeColor, ): void => { const { id } = option; const edgeKeyShape: Partial<EdgeStyle['keyshape']> = edgeStyle.keyshape ?? {}; const edgeArrowShape: Partial<EdgeStyle['keyshape']['endArrow']> = edgeStyle .keyshape.endArrow ?? { ...DEFAULT_EDGE_STYLE.keyshape.endArrow }; if (id === 'fixed') { const { value } = option as ColorFixed; const fixedEdgeColor = normalizeColor(value); Object.assign(edgeStyle, { keyshape: Object.assign(edgeKeyShape, { stroke: fixedEdgeColor.normal, endArrow: Object.assign(edgeArrowShape, { fill: fixedEdgeColor.normal, }), }), }); return; } const { variable, mapping } = option as ColorLegend; const variableProperty: string | unknown = get(edge, variable); const defaultEdgeColor = normalizeColor(EDGE_DEFAULT_COLOR); // Exclude null or undefined if (!(variableProperty == null)) { const edgeColor = normalizeColor(mapping[variableProperty as string]); Object.assign(edgeStyle, { keyshape: Object.assign(edgeKeyShape, { stroke: edgeColor.normal, endArrow: Object.assign(edgeArrowShape, { fill: edgeColor.normal, }), }), }); return; } Object.assign(edgeStyle, { keyshape: Object.assign(edgeKeyShape, { stroke: defaultEdgeColor.dark, endArrow: Object.assign(edgeArrowShape, { fill: defaultEdgeColor.normal, }), }), }); };
the_stack
import test from 'japa' import { join } from 'path' import dedent from 'dedent-js' import { EdgeError } from 'edge-error' import { Filesystem } from '@poppinss/dev-utils' import { Loader } from '../src/Loader' import { Compiler } from '../src/Compiler' import { Template } from '../src/Template' import { Processor } from '../src/Processor' import { ifTag } from '../src/Tags/If' import { slotTag } from '../src/Tags/Slot' import { injectTag } from '../src/Tags/Inject' import { includeTag } from '../src/Tags/Include' import { componentTag } from '../src/Tags/Component' import './assert-extend' const fs = new Filesystem(join(__dirname, 'views')) const tags = { component: componentTag, slot: slotTag, inject: injectTag, if: ifTag, include: includeTag, } const loader = new Loader() loader.mount('default', fs.basePath) const processor = new Processor() const compiler = new Compiler(loader, tags, processor, { cache: false }) test.group('Component | compile | errors', (group) => { group.afterEach(async () => { await fs.cleanup() }) test('report component arguments error', async (assert) => { assert.plan(4) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component([1, 2]) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, '"[1, 2]" is not a valid argument type for the @component tag') assert.equal(error.line, 3) assert.equal(error.col, 11) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report slot argument name error', async (assert) => { assert.plan(4) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('foo') @slot(getSlotName()) @endslot @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, '"getSlotName()" is not a valid argument type for the @slot tag') assert.equal(error.line, 4) assert.equal(error.col, 8) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report slot arguments error', async (assert) => { assert.plan(4) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('foo') @slot('main', 'foo', 'bar') @endslot @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'maximum of 2 arguments are allowed for @slot tag') assert.equal(error.line, 4) assert.equal(error.col, 8) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report slot scope argument error', async (assert) => { assert.plan(4) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('foo') @slot('main', [1, 2]) @endslot @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, '"[1, 2]" is not valid prop identifier for @slot tag') assert.equal(error.line, 4) assert.equal(error.col, 16) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) }) test.group('Component | render | errors', (group) => { group.afterEach(async () => { await fs.cleanup() }) test('report component name runtime error', async (assert) => { assert.plan(4) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component(getComponentName()) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getComponentName is not a function') assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report component state argument error', async (assert) => { assert.plan(4) await fs.add('button.edge', '') await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('button', { color: getColor() }) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getColor is not a function') assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report component state argument error when spread over multiple lines', async (assert) => { assert.plan(4) await fs.add('button.edge', '') await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('button', { color: getColor(), }) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getColor is not a function') /** * Expected to be on line 4. But okay for now */ assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report component state argument error with assignment expression', async (assert) => { assert.plan(4) await fs.add('button.edge', '') await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('button', color = getColor()) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getColor is not a function') assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report component state argument error with assignment expression in multiple lines', async (assert) => { assert.plan(4) await fs.add('button.edge', '') await fs.add( 'eval.edge', dedent` <p> Some content </p> @component( 'button', color = getColor() ) @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getColor is not a function') /** * Expected to be on line 5. But okay for now */ assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report scoped slot error', async (assert) => { assert.plan(4) await fs.add('button.edge', '{{ $slots.text() }}') await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('button') @slot('text', button) {{ button.isPrimary() ? 'Hello primary' : 'Hello' }} @endslot @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.match(error.message, /^(?=.*\bCannot read\b)(?=.*\bisPrimary\b).*$/) assert.equal(error.line, 5) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) test('report component file errors', async (assert) => { assert.plan(4) await fs.add( 'button.edge', dedent` <button style="color: {{ getColor() }}" > </button> ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @!component('button') ` ) const template = new Template(compiler, {}, {}, processor) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'getColor is not a function') assert.equal(error.line, 2) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'button.edge')) } }) test('point error back to the caller when props validation fails', async (assert) => { assert.plan(4) await fs.add( 'button.edge', `{{ $props.validate('text', () => { raise('text prop is required', $caller) }) }}` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @!component('button') ` ) const template = new Template( compiler, { raise: (message: string, options: any) => { throw new EdgeError(message, 'E_RUNTIME_EXCEPTION', options) }, }, {}, processor ) try { template.render('eval.edge', {}) } catch (error) { assert.equal(error.message, 'text prop is required') assert.equal(error.line, 3) assert.equal(error.col, 0) assert.equal(error.filename, join(fs.basePath, 'eval.edge')) } }) }) test.group('Component | context API', (group) => { group.afterEach(async () => { await fs.cleanup() }) test('inject data from the component to the parent', async (assert) => { await fs.add( 'modal.edge', dedent` @if(needsHandler) @inject({ closeHandler: 'closePopup' }) @endif {{{ $slots.main() }}} ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modal', needsHandler = true) <p>{{ $context.closeHandler }}</p> @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <p>closePopup</p> ` ) }) test('do not leak context out of the component scope', async (assert) => { await fs.add( 'modal.edge', dedent` @if(needsHandler) @inject({ closeHandler: 'closePopup' }) @endif {{{ $slots.main() }}} ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modal', needsHandler = true) <p>{{ $context.closeHandler }}</p> @endcomponent <p>{{ $context.closeHandler }}</p> ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <p>closePopup</p> <p>undefined</p> ` ) }) test('do not leak context across sibling components', async (assert) => { await fs.add( 'modal.edge', dedent` @if(needsHandler) @inject({ closeHandler: 'closePopup' }) @endif {{{ $slots.main() }}} ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modal', needsHandler = true) <p>{{ $context.closeHandler }}</p> @endcomponent @component('modal', needsHandler = false) <p>{{ $context.closeHandler }}</p> @endcomponent ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <p>closePopup</p> <p>undefined</p> ` ) }) test('do not leak context across sibling components within a nested component', async (assert) => { await fs.add( 'modal.edge', dedent` @if(needsHandler) @inject({ closeHandler: 'closePopup' }) @endif {{{ $slots.main() }}} ` ) await fs.add( 'wrapper.edge', dedent` @inject({}) {{{ $slots.main() }}} ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('wrapper') @component('modal', needsHandler = true) <p>{{ $context.closeHandler }}</p> @endcomponent @component('modal', needsHandler = false) <p>{{ $context.closeHandler }}</p> @endcomponent @end ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <p>closePopup</p> <p>undefined</p> ` ) }) test('share context with nested components', async (assert) => { await fs.add( 'modal.edge', dedent` @inject({}) {{{ $slots.main() }}} ` ) await fs.add( 'modalsRoot.edge', dedent` @inject({ closeHandler: 'closePopup' }) {{{ $slots.main() }}} ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modalsRoot') @component('modal') <p>{{ $context.closeHandler }}</p> @endcomponent @component('modal') <p>{{ $context.closeHandler }}</p> @endcomponent @end ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <p>closePopup</p> <p>closePopup</p> ` ) }) test('share context with partials', async (assert) => { await fs.add( 'modal.edge', dedent` @inject({}) {{{ $slots.main() }}} ` ) await fs.add( 'modalsRoot.edge', dedent` @inject({ closeHandler: 'closePopup' }) {{{ $slots.main() }}} ` ) await fs.add('button.edge', dedent`<button>{{ $context.closeHandler }}</button>`) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modalsRoot') @component('modal') @include('button') @endcomponent @component('modal') @include('button') @endcomponent @end ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <button>closePopup</button> <button>closePopup</button> ` ) }) test('share context with components', async (assert) => { await fs.add( 'modal.edge', dedent` @inject({}) {{{ $slots.main() }}} ` ) await fs.add( 'modalsRoot.edge', dedent` @inject({ closeHandler: 'closePopup' }) {{{ $slots.main() }}} ` ) await fs.add('button.edge', dedent`<button>{{ $context.closeHandler }}</button>`) await fs.add( 'eval.edge', dedent` <p> Some content </p> @component('modalsRoot') @component('modal') @!component('button') @endcomponent @component('modal') @!component('button') @endcomponent @end ` ) const template = new Template(compiler, {}, {}, processor) const output = template.render<string>('eval.edge', {}).trim() assert.stringEqual( output, dedent` <p> Some content </p> <button>closePopup</button> <button>closePopup</button> ` ) }) test('raise error when trying to use inject outside of the component scope', async (assert) => { assert.plan(3) await fs.add( 'button.edge', dedent` I will render a button And then try to inject some values @inject({ foo: 'bar' }) ` ) await fs.add( 'eval.edge', dedent` <p> Some content </p> @include('button') ` ) const template = new Template(compiler, {}, {}, processor) try { template.render<string>('eval.edge', {}) } catch (error) { assert.equal(error.message, 'Cannot use "@inject" outside of a component scope') assert.equal(error.filename, join(fs.basePath, 'button.edge')) assert.equal(error.line, 5) } }) })
the_stack
import StateMachine from '../../src/app/app' import visualize from '../../src/plugins/visualize' const dotcfg = visualize.dotcfg, // converts FSM to DOT CONFIG dotify = visualize.dotify; // converts DOT CONFIG to DOT OUTPUT //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- test('visualize state machine', () => { const fsm = new StateMachine({ init: 'solid', transitions: [ { name: 'melt', from: 'solid', to: 'liquid' }, { name: 'freeze', from: 'liquid', to: 'solid' }, { name: 'vaporize', from: 'liquid', to: 'gas' }, { name: 'condense', from: 'gas', to: 'liquid' } ] }) expect(visualize(fsm)).toBe(`digraph "fsm" { "solid"; "liquid"; "gas"; "solid" -> "liquid" [ label=" melt " ]; "liquid" -> "solid" [ label=" freeze " ]; "liquid" -> "gas" [ label=" vaporize " ]; "gas" -> "liquid" [ label=" condense " ]; }`); }); //------------------------------------------------------------------------------------------------- test('visualize state machine factory', () => { const FSM = StateMachine.factory({ init: 'solid', transitions: [ { name: 'melt', from: 'solid', to: 'liquid' }, { name: 'freeze', from: 'liquid', to: 'solid' }, { name: 'vaporize', from: 'liquid', to: 'gas' }, { name: 'condense', from: 'gas', to: 'liquid' } ] }) expect(visualize(new FSM())).toBe(`digraph "fsm" { "solid"; "liquid"; "gas"; "solid" -> "liquid" [ label=" melt " ]; "liquid" -> "solid" [ label=" freeze " ]; "liquid" -> "gas" [ label=" vaporize " ]; "gas" -> "liquid" [ label=" condense " ]; }`); }); //------------------------------------------------------------------------------------------------- test('visualize with custom .dot markup', () => { const fsm = new StateMachine({ init: 'solid', transitions: [ { name: 'melt', from: 'solid', to: 'liquid', dot: { color: 'red', headport: 'nw', tailport: 'ne' } }, { name: 'freeze', from: 'liquid', to: 'solid', dot: { color: 'grey', headport: 'se', tailport: 'sw' } }, { name: 'vaporize', from: 'liquid', to: 'gas', dot: { color: 'yellow', headport: 'nw', tailport: 'ne' } }, { name: 'condense', from: 'gas', to: 'liquid', dot: { color: 'brown', headport: 'se', tailport: 'sw' } } ] }) expect(visualize(fsm, { name: 'matter', orientation: 'horizontal' })).toBe(`digraph "matter" { rankdir=LR; "solid"; "liquid"; "gas"; "solid" -> "liquid" [ color="red" ; headport="nw" ; label=" melt " ; tailport="ne" ]; "liquid" -> "solid" [ color="grey" ; headport="se" ; label=" freeze " ; tailport="sw" ]; "liquid" -> "gas" [ color="yellow" ; headport="nw" ; label=" vaporize " ; tailport="ne" ]; "gas" -> "liquid" [ color="brown" ; headport="se" ; label=" condense " ; tailport="sw" ]; }`); }); //================================================================================================= // TEST FSM => DOTCFG //================================================================================================= test('dotcfg simple state machine', () => { const fsm = new StateMachine({ init: 'solid', transitions: [ { name: 'melt', from: 'solid', to: 'liquid' }, { name: 'freeze', from: 'liquid', to: 'solid' }, { name: 'vaporize', from: 'liquid', to: 'gas' }, { name: 'condense', from: 'gas', to: 'liquid' } ] }) expect(dotcfg(fsm)).toEqual({ states: [ 'solid', 'liquid', 'gas' ], transitions: [ { from: 'solid', to: 'liquid', label: ' melt ' }, { from: 'liquid', to: 'solid', label: ' freeze ' }, { from: 'liquid', to: 'gas', label: ' vaporize ' }, { from: 'gas', to: 'liquid', label: ' condense ' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for state machine - optionally include :init transition', () => { const fsm = new StateMachine({ init: { name: 'boot', from: 'booting', to: 'ready', dot: { color: 'red' } } }); expect(dotcfg(fsm, { init: false })).toEqual({ states: [ 'ready' ] }); expect(dotcfg(fsm, { init: true })).toEqual({ states: [ 'booting', 'ready' ], transitions: [ { from: 'booting', to: 'ready', label: ' boot ', color: 'red' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for fsm with multiple transitions with same :name', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'step', from: 'B', to: 'C' }, { name: 'step', from: 'C', to: 'D' } ] }) expect(dotcfg(fsm)).toEqual({ states: [ 'A', 'B', 'C', 'D' ], transitions: [ { from: 'A', to: 'B', label: ' step ' }, { from: 'B', to: 'C', label: ' step ' }, { from: 'C', to: 'D', label: ' step ' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for fsm transition with multiple :from', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'step', from: 'B', to: 'C' }, { name: 'step', from: 'C', to: 'D' }, { name: 'reset', from: [ 'A', 'B' ], to: 'A' } ] }); expect(dotcfg(fsm)).toEqual({ states: [ 'A', 'B', 'C', 'D' ], transitions: [ { from: 'A', to: 'B', label: ' step ' }, { from: 'B', to: 'C', label: ' step ' }, { from: 'C', to: 'D', label: ' step ' }, { from: 'A', to: 'A', label: ' reset ' }, { from: 'B', to: 'A', label: ' reset ' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for fsm with wildcard/missing :from', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'step', from: 'B', to: 'C' }, { name: 'step', from: 'C', to: 'D' }, { name: 'reset', from: '*', to: 'A' }, { name: 'finish', /* missing */ to: 'X' } ] }); expect(dotcfg(fsm)).toEqual({ states: [ 'A', 'B', 'C', 'D', 'X' ], transitions: [ { from: 'A', to: 'B', label: ' step ' }, { from: 'B', to: 'C', label: ' step ' }, { from: 'C', to: 'D', label: ' step ' }, { from: 'none', to: 'A', label: ' reset ' }, { from: 'A', to: 'A', label: ' reset ' }, { from: 'B', to: 'A', label: ' reset ' }, { from: 'C', to: 'A', label: ' reset ' }, { from: 'D', to: 'A', label: ' reset ' }, { from: 'X', to: 'A', label: ' reset ' }, { from: 'none', to: 'X', label: ' finish ' }, { from: 'A', to: 'X', label: ' finish ' }, { from: 'B', to: 'X', label: ' finish ' }, { from: 'C', to: 'X', label: ' finish ' }, { from: 'D', to: 'X', label: ' finish ' }, { from: 'X', to: 'X', label: ' finish ' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for fsm with wildcard/missing :to', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B' }, { name: 'step', from: 'B', to: 'C' }, { name: 'step', from: 'C', to: 'D' }, { name: 'stay', from: 'A', to: 'A' }, { name: 'stay', from: 'B', to: '*' }, { name: 'stay', from: 'C' /* missing */ }, { name: 'noop', from: '*', to: '*' } ] }); expect(dotcfg(fsm)).toEqual({ states: [ 'A', 'B', 'C', 'D' ], transitions: [ { from: 'A', to: 'B', label: ' step ' }, { from: 'B', to: 'C', label: ' step ' }, { from: 'C', to: 'D', label: ' step ' }, { from: 'A', to: 'A', label: ' stay ' }, { from: 'B', to: 'B', label: ' stay ' }, { from: 'C', to: 'C', label: ' stay ' }, { from: 'none', to: 'none', label: ' noop ' }, { from: 'A', to: 'A', label: ' noop ' }, { from: 'B', to: 'B', label: ' noop ' }, { from: 'C', to: 'C', label: ' noop ' }, { from: 'D', to: 'D', label: ' noop ' } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for fsm - conditional transition is not displayed', () => { const fsm = new StateMachine({ init: 'A', transitions: [ // @ts-ignore { name: 'step', from: '*', to: function(n) { return this.skip(n) } }, ], methods: { skip: function(amount) { // @ts-ignore const code = this.state.charCodeAt(0); return String.fromCharCode(code + (amount || 1)); } } }); expect(dotcfg(fsm)).toEqual({ states: [ 'A' ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg with custom transition .dot edge markup', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step', from: 'A', to: 'B', dot: { color: "red", headport: 'nw', tailport: 'ne', label: 'A2B' } }, { name: 'step', from: 'B', to: 'C', dot: { color: "green", headport: 'sw', tailport: 'se', label: 'B2C' } } ] }) expect(dotcfg(fsm)).toEqual({ states: [ 'A', 'B', 'C' ], transitions: [ { from: 'A', to: 'B', label: 'A2B', color: "red", headport: "nw", tailport: "ne" }, { from: 'B', to: 'C', label: 'B2C', color: "green", headport: "sw", tailport: "se" } ] }); }); //------------------------------------------------------------------------------------------------- test('dotcfg with custom name', () => { const fsm = new StateMachine(); expect(dotcfg(fsm, { name: 'bob' })).toEqual({ name: 'bob', }); }); //------------------------------------------------------------------------------------------------- test('dotcfg with custom orientation', () => { const fsm = new StateMachine(); expect(dotcfg(fsm, { orientation: 'horizontal' })).toEqual({ rankdir: 'LR', }); expect(dotcfg(fsm, { orientation: 'vertical' })).toEqual({ rankdir: 'TB', }); }); //------------------------------------------------------------------------------------------------- test('dotcfg for empty state machine', () => { const fsm = new StateMachine(); expect(dotcfg(fsm)).toEqual({}); }); //================================================================================================= // TEST DOTCFG => DOT OUTPUT //================================================================================================= test('dotify empty', () => { const expected = `digraph "fsm" { }` expect(dotify()).toBe(expected) expect(dotify({})).toBe(expected) }); //------------------------------------------------------------------------------------------------- test('dotify name', () => { expect(dotify({ name: 'bob' })).toBe(`digraph "bob" { }`); }); //------------------------------------------------------------------------------------------------- test('dotify rankdir', () => { expect(dotify({ rankdir: 'LR' })).toBe(`digraph "fsm" { rankdir=LR; }`); }); //------------------------------------------------------------------------------------------------- test('dotify states', () => { const states = [ 'A', 'B' ]; expect(dotify({ states: states })).toBe(`digraph "fsm" { "A"; "B"; }`); }); //------------------------------------------------------------------------------------------------- test('dotify transitions', () => { const transitions = [ { from: 'A', to: 'B' }, { from: 'B', to: 'C' }, ]; expect(dotify({ transitions: transitions })).toBe(`digraph "fsm" { "A" -> "B"; "B" -> "C"; }`) }) //------------------------------------------------------------------------------------------------- test('dotify transitions with labels', () => { const transitions = [ { from: 'A', to: 'B', label: 'first' }, { from: 'B', to: 'C', label: 'second' } ]; expect(dotify({ transitions: transitions })).toBe(`digraph "fsm" { "A" -> "B" [ label="first" ]; "B" -> "C" [ label="second" ]; }`); }); //------------------------------------------------------------------------------------------------- test('dotify transitions with custom .dot edge markup', () => { const transitions = [ { from: 'A', to: 'B', label: 'first', color: 'red', headport: 'nw', tailport: 'ne' }, { from: 'B', to: 'A', label: 'second', color: 'green', headport: 'se', tailport: 'sw' } ] expect(dotify({ transitions: transitions })).toBe(`digraph "fsm" { "A" -> "B" [ color="red" ; headport="nw" ; label="first" ; tailport="ne" ]; "B" -> "A" [ color="green" ; headport="se" ; label="second" ; tailport="sw" ]; }`); }) //------------------------------------------------------------------------------------------------- test('dotify kitchen sink', () => { const name = "my fsm", rankdir = "LR", states = [ 'none', 'solid', 'liquid', 'gas' ], transitions = [ { from: 'none', to: 'solid', color: 'red', label: 'init' }, { from: 'solid', to: 'liquid', color: 'red', label: 'melt' }, { from: 'liquid', to: 'solid', color: 'green', label: 'freeze' }, { from: 'liquid', to: 'gas', color: 'red', label: 'vaporize' }, { from: 'gas', to: 'liquid', color: 'green', label: 'condense' } ]; expect(dotify({ name: name, rankdir: rankdir, states: states, transitions: transitions })).toBe(`digraph "my fsm" { rankdir=LR; "none"; "solid"; "liquid"; "gas"; "none" -> "solid" [ color="red" ; label="init" ]; "solid" -> "liquid" [ color="red" ; label="melt" ]; "liquid" -> "solid" [ color="green" ; label="freeze" ]; "liquid" -> "gas" [ color="red" ; label="vaporize" ]; "gas" -> "liquid" [ color="green" ; label="condense" ]; }`); }); //=================================================================================================
the_stack
import { ABIDefault, ABIDefaultType, ABIParameter, ABIReturn, AddressString, addressToScriptHash, assertAttributeTypeJSON, assertCallFlags as clientAssertCallFlags, assertOracleResponseCode as assertOracleResponseCodeIn, Attribute, AttributeTypeModel, BufferString, CallFlags, common, ContractABI, ContractABIClient, ContractEventDescriptor, ContractEventDescriptorClient, ContractGroup, ContractManifest, ContractManifestClient, ContractMethodDescriptor, ContractMethodDescriptorClient, ContractParameterDefinition, ContractPermission, ContractPermissionDescriptor, ForwardValue, Hash256String, InvokeSendUnsafeReceiveTransactionOptions, IterOptions, MethodToken, NefFile, OracleResponseCode, Param, PrivateKeyString, privateKeyToPublicKey, PublicKeyString, ScriptBuilderParam, scriptHashToAddress, SmartContractDefinition, SmartContractNetworkDefinition, SmartContractNetworksDefinition, SourceMaps, toAttributeType, TransactionOptions, Transfer, UInt160Hex, UpdateAccountNameOptions, UserAccountID, wifToPrivateKey, Wildcard, WildcardContainer, } from '@neo-one/client-common'; import { JSONObject, JSONValue, OmitStrict, utils } from '@neo-one/utils'; import BigNumber from 'bignumber.js'; import { BN } from 'bn.js'; import _ from 'lodash'; import { InvalidArgumentError } from './errors'; export const assertString = (name: string, param?: unknown): string => { if (param == undefined || typeof param !== 'string') { throw new InvalidArgumentError('string', name, param); } return param; }; export const assertBoolean = (name: string, value?: unknown): boolean => { if (value == undefined || typeof value !== 'boolean') { throw new InvalidArgumentError('boolean', name, value); } return value; }; export const assertNullableBoolean = (name: string, value?: unknown): boolean | undefined => { if (value == undefined) { return undefined; } return assertBoolean(name, value); }; export const assertNonNegativeNumber = (name: string, value?: unknown): number => { if (value == undefined || typeof value !== 'number' || value < 0) { throw new InvalidArgumentError('number', name, value); } return value; }; export const assertNumber = (name: string, value?: unknown): number => { if (value == undefined || typeof value !== 'number') { throw new InvalidArgumentError('number', name, value); } return value; }; export const assertNullableNumber = (name: string, value?: unknown): number | undefined => { if (value == undefined) { return undefined; } if (typeof value !== 'number') { throw new InvalidArgumentError('number', name, value); } return value; }; export const assertAddress = (name: string, addressIn?: unknown): AddressString => { const address = assertString(name, addressIn); try { addressToScriptHash(address); return address; } catch { try { return scriptHashToAddress(address); } catch { throw new InvalidArgumentError('Address', name, address); } } }; export const tryGetUInt160Hex = (name: string, addressOrUInt160In: unknown): UInt160Hex => { const addressOrUInt160 = assertString(name, addressOrUInt160In); try { scriptHashToAddress(addressOrUInt160); return addressOrUInt160; } catch { try { return addressToScriptHash(addressOrUInt160); } catch { throw new InvalidArgumentError('AddressOrUInt160', name, addressOrUInt160); } } }; export const assertHash256 = (name: string, hash?: unknown): Hash256String => { const value = assertString(name, hash); try { return common.uInt256ToString(common.stringToUInt256(value)); } catch { throw new InvalidArgumentError('Hash256', name, value); } }; export const assertBuffer = (name: string, buffer?: unknown): BufferString => { const value = assertString(name, buffer); if (Buffer.from(value, 'hex').toString('hex') !== value.toLowerCase()) { throw new InvalidArgumentError('Buffer', name, value); } return value; }; const assertNullablePublicKey = (name: string, publicKey?: unknown): PublicKeyString | undefined => { if (publicKey == undefined) { return undefined; } return assertPublicKey(name, publicKey); }; export const assertPublicKey = (name: string, publicKey?: unknown): PublicKeyString => { const value = assertBuffer(name, publicKey); try { return common.ecPointToString(common.stringToECPoint(value)); } catch { throw new InvalidArgumentError('PublicKey', name, value); } }; const assertNullableUInt160Hex = (name: string, value?: unknown): UInt160Hex | undefined => { if (value == undefined) { return undefined; } return assertUInt160Hex(name, value); }; const assertUInt160Hex = (name: string, value?: unknown): UInt160Hex => { const valueIn = assertString(name, value); try { return common.uInt160ToString(common.stringToUInt160(valueIn)); } catch { throw new InvalidArgumentError('UInt160Hex', name, value); } }; export const assertBigNumber = (name: string, value?: unknown): BigNumber => { if (value == undefined || !BigNumber.isBigNumber(value)) { throw new InvalidArgumentError('BigNumber', name, value); } return value; }; export const assertNullableBigNumber = (name: string, value?: unknown): BigNumber | undefined => { if (value == undefined) { return undefined; } return assertBigNumber(name, value); }; export const assertBN = (name: string, value?: unknown): BN => { if (value == undefined || !BN.isBN(value)) { throw new InvalidArgumentError('BN', name, value); } return value; }; export const assertArray = (name: string, value?: unknown): readonly unknown[] => { if (!Array.isArray(value)) { throw new InvalidArgumentError('Array', name, value); } return value; }; export const assertNullableArray = (name: string, value?: unknown): readonly unknown[] => { if (value == undefined) { return []; } return assertArray(name, value); }; export const assertMap = (name: string, value?: unknown): ReadonlyMap<unknown, unknown> => { if (!(value instanceof Map)) { throw new InvalidArgumentError('Map', name, value); } return value; }; export const assertObject = (name: string, value?: unknown): { readonly [key: string]: unknown } => { if (!isObject(value)) { throw new InvalidArgumentError('Object', name, value); } return value as { readonly [key: string]: unknown }; }; export const assertNullableMap = (name: string, value?: unknown): ReadonlyMap<unknown, unknown> => { if (value == undefined) { return new Map(); } return assertMap(name, value); }; export const isObject = (value?: unknown): value is object => value != undefined && typeof value === 'object'; export const assertProperty = <T, Name extends string, P>( value: T, objectName: string, name: Name, assertType: (name: string, v?: unknown) => P, ): P => { // tslint:disable-next-line no-any const valueAny: any = value; return assertType(`${objectName}.${name}`, valueAny[name]); }; export const assertUserAccountID = (name: string, value?: unknown): UserAccountID => { if (!isObject(value)) { throw new InvalidArgumentError('UserAccountID', name, value); } return { network: assertProperty(value, 'UserAccountID', 'network', assertString), address: assertProperty(value, 'UserAccountID', 'address', assertAddress), }; }; export const assertNullableUserAccountID = (name: string, value?: unknown): UserAccountID | undefined => { if (value == undefined) { return undefined; } return assertUserAccountID(name, value); }; export const assertUpdateAccountNameOptions = (name: string, value?: unknown): UpdateAccountNameOptions => { if (!isObject(value)) { throw new InvalidArgumentError('UpdateAccountNameOptions', name, value); } return { id: assertProperty(value, 'UpdateAccountNameOptions', 'id', assertUserAccountID), name: assertProperty(value, 'UpdateAccountNameOptions', 'name', assertString), }; }; const CONTRACT_PARAMETER_TYPES = new Set([ 'Any', 'Signature', 'Boolean', 'Address', 'Hash160', 'Hash256', 'Buffer', 'PublicKey', 'String', 'Array', 'Map', 'Object', 'Void', 'Integer', 'ForwardValue', ]); const assertContractParameterType = (name: string, valueIn?: unknown): ContractParameterDefinition['type'] => { const value = assertString(name, valueIn); if (!CONTRACT_PARAMETER_TYPES.has(value)) { throw new InvalidArgumentError('ContractParameterType', name, value); } return value as ContractParameterDefinition['type']; }; const ABI_TYPES = new Set([ 'Any', 'Signature', 'Boolean', 'Hash160', 'Address', 'Hash256', 'Buffer', 'PublicKey', 'String', 'Array', 'Map', 'Object', 'Void', 'Integer', 'ForwardValue', ]); const assertABIType = (name: string, valueIn?: unknown): ABIReturn['type'] => { const value = assertString(name, valueIn); if (!ABI_TYPES.has(value)) { throw new InvalidArgumentError('ABIType', name, value); } return value as ABIReturn['type']; }; const assertContractParameterDefinition = (name: string, value?: unknown): ContractParameterDefinition => { if (!isObject(value)) { throw new InvalidArgumentError('ContractParameterDefinition', name, value); } return { type: assertProperty(value, 'ContractParameterDefinition', 'type', assertContractParameterType), name: assertProperty(value, 'ContractParameterDefinition', 'name', assertString), }; }; const assertABIDefaultType = (name: string, valueIn?: unknown): ABIDefaultType => { const value = assertString(name, valueIn); switch (value) { case 'sender': return 'sender'; default: throw new InvalidArgumentError('ABIDefaultType', name, value); } }; const assertNullableABIDefault = (name: string, value?: unknown): ABIDefault | undefined => { if (value == undefined) { return undefined; } if (!isObject(value)) { throw new InvalidArgumentError('ABIDefault', name, value); } const type = assertProperty(value, 'ABIDefault', 'type', assertABIDefaultType); switch (type) { case 'sender': return { type: 'sender' }; default: throw new InvalidArgumentError('ABIDefaultType', name, value); } }; const assertABIParameter = (propName: string, value?: unknown): ABIParameter => { if (!isObject(value)) { throw new InvalidArgumentError('ABIParameter', propName, value); } const type = assertProperty(value, 'ABIParameter', 'type', assertABIType); const name = assertProperty(value, 'ABIParameter', 'name', assertString); const optional = assertProperty(value, 'ABIParameter', 'optional', assertNullableBoolean); const rest = assertProperty(value, 'ABIParameter', 'rest', assertNullableBoolean); const defaultValue = assertProperty(value, 'ABIParameter', 'default', assertNullableABIDefault); const forwardedValue = assertProperty(value, 'ABIParameter', 'forwardedValue', assertNullableBoolean); switch (type) { case 'Any': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Signature': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Boolean': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Hash160': case 'Address': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Hash256': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Buffer': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'PublicKey': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'String': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Array': return { type, name, optional, default: defaultValue, value: assertProperty(value, 'ABIParameter', 'value', assertABIReturn), forwardedValue, rest, }; case 'Map': return { type, name, optional, default: defaultValue, key: assertProperty(value, 'ABIParameter', 'key', assertABIReturn), value: assertProperty(value, 'ABIParameter', 'value', assertABIReturn), forwardedValue, rest, }; case 'Object': return { type, name, optional, default: defaultValue, properties: assertProperty(value, 'ABIParameter', 'properties', assertABIProperties), forwardedValue, rest, }; case 'Void': return { type, name, optional, default: defaultValue, forwardedValue, rest }; case 'Integer': return { type, name, optional, default: defaultValue, decimals: assertProperty(value, 'ABIParameter', 'decimals', assertNumber), forwardedValue, }; case 'ForwardValue': return { type, name, optional, default: defaultValue, forwardedValue, rest }; default: /* istanbul ignore next */ utils.assertNever(type); /* istanbul ignore next */ throw new Error('For TS'); } }; const assertABIProperties = (name: string, value?: unknown): { readonly [key: string]: ABIReturn } => { if (!isObject(value)) { throw new InvalidArgumentError('ABIReturn', name, value); } return _.fromPairs(Object.entries(value).map(([k, v]) => [assertString(name, k), assertABIReturn(name, v)])); }; const assertABIReturn = (name: string, value?: unknown): ABIReturn => { if (!isObject(value)) { throw new InvalidArgumentError('ABIReturn', name, value); } const type = assertProperty(value, 'ABIReturn', 'type', assertABIType); const optional = assertProperty(value, 'ABIReturn', 'optional', assertNullableBoolean); const forwardedValue = assertProperty(value, 'ABIReturn', 'forwardedValue', assertNullableBoolean); switch (type) { case 'Any': return { type, optional, forwardedValue }; case 'Signature': return { type, optional, forwardedValue }; case 'Boolean': return { type, optional, forwardedValue }; case 'Hash160': case 'Address': return { type, optional, forwardedValue }; case 'Hash256': return { type, optional, forwardedValue }; case 'Buffer': return { type, optional, forwardedValue }; case 'PublicKey': return { type, optional, forwardedValue }; case 'String': return { type, optional, forwardedValue }; case 'Array': return { type, value: assertProperty(value, 'ABIReturn', 'value', assertABIReturn), optional, forwardedValue }; case 'Map': return { type, key: assertProperty(value, 'ABIReturn', 'key', assertABIReturn), value: assertProperty(value, 'ABIReturn', 'value', assertABIReturn), optional, forwardedValue, }; case 'Object': return { type, properties: assertProperty(value, 'ABIReturn', 'properties', assertABIProperties), optional, forwardedValue, }; case 'Void': return { type, optional, forwardedValue }; case 'Integer': return { type, decimals: assertProperty(value, 'ABIReturn', 'decimals', assertNumber), optional, forwardedValue }; case 'ForwardValue': return { type, optional, forwardedValue }; default: /* istanbul ignore next */ utils.assertNever(type); /* istanbul ignore next */ throw new Error('For TS'); } }; const assertContractMethodDescriptorClient = (name: string, value?: unknown): ContractMethodDescriptorClient => { if (!isObject(value)) { throw new InvalidArgumentError('ContractMethodDescriptorClient', name, value); } return { name: assertProperty(value, 'ContractMethodDescriptorClient', 'name', assertString), parameters: assertProperty(value, 'ContractMethodDescriptorClient', 'parameters', assertNullableArray).map( (parameter) => assertABIParameter('ContractMethodDescriptorClient.parameters', parameter), ), returnType: assertProperty(value, 'ContractMethodDescriptorClient', 'returnType', assertABIReturn), constant: assertProperty(value, 'ContractMethodDescriptorClient', 'constant', assertNullableBoolean), safe: assertProperty(value, 'ContractMethodDescriptorClient', 'safe', assertBoolean), offset: assertProperty(value, 'ContractMethodDescriptorClient', 'offset', assertNumber), }; }; const assertContractMethodDescriptor = (name: string, value?: unknown): ContractMethodDescriptor => { if (!isObject(value)) { throw new InvalidArgumentError('ContractMethodDescriptor', name, value); } return { name: assertProperty(value, 'ContractMethodDescriptor', 'name', assertString), parameters: assertProperty(value, 'ContractMethodDescriptor', 'parameters', assertNullableArray).map((parameter) => assertContractParameterDefinition('ContractMethodDescriptor.parameters', parameter), ), returnType: assertProperty(value, 'ContractMethodDescriptor', 'returnType', assertContractParameterType), offset: assertProperty(value, 'ContractMethodDescriptor', 'offset', assertNumber), safe: assertProperty(value, 'ContractMethodDescriptor', 'safe', assertBoolean), }; }; const assertContractEventDescriptorClient = (name: string, value?: unknown): ContractEventDescriptorClient => { if (!isObject(value)) { throw new InvalidArgumentError('ContractEventDescriptorClient', name, value); } return { name: assertProperty(value, 'ContractEventDescriptorClient', 'name', assertString), parameters: assertProperty(value, 'ContractEventDescriptorClient', 'parameters', assertNullableArray).map( (parameter) => assertABIParameter('ContractEventDescriptorClient.parameters', parameter), ), }; }; const assertContractEventDescriptor = (name: string, value?: unknown): ContractEventDescriptor => { if (!isObject(value)) { throw new InvalidArgumentError('ContractEventDescriptor', name, value); } return { name: assertProperty(value, 'ContractEventDescriptor', 'name', assertString), parameters: assertProperty(value, 'ContractEventDescriptor', 'parameters', assertNullableArray).map((parameter) => assertContractParameterDefinition('ContractEventDescriptor.parameters', parameter), ), }; }; export const assertContractABIClient = (name: string, value?: unknown): ContractABIClient => { if (!isObject(value)) { throw new InvalidArgumentError('ContractABI', name, value); } return { methods: assertProperty(value, 'ContractABI', 'methods', assertArray).map((method) => assertContractMethodDescriptorClient('ContractABI.methods', method), ), events: assertProperty(value, 'ABI', 'events', assertArray).map((func) => assertContractEventDescriptorClient('ABI.events', func), ), }; }; export const assertContractABI = (name: string, value?: unknown): ContractABI => { if (!isObject(value)) { throw new InvalidArgumentError('ContractABI', name, value); } return { methods: assertProperty(value, 'ContractABI', 'methods', assertArray).map((method) => assertContractMethodDescriptor('ContractABI.methods', method), ), events: assertProperty(value, 'ABI', 'events', assertArray).map((func) => assertContractEventDescriptor('ABI.events', func), ), }; }; export const assertWildcardContainer = (name: string, value: unknown): WildcardContainer<unknown> => { if (value === undefined || value === '*') { return '*'; } if (!Array.isArray(value) && value !== '*') { throw new InvalidArgumentError('WildcardContainer', name, value); } return value; }; export const assertWildcardContainerProperty = <T, Name extends string, P>( value: T, objectName: string, name: Name, assertType: (name: string, v?: unknown) => P, ): readonly P[] | Wildcard => { const wildcardOrArray = assertProperty(value, objectName, name, assertWildcardContainer); if (wildcardOrArray === '*') { return '*'; } return assertProperty(value, objectName, name, assertArray).map((val) => assertType(`${objectName}.${name}`, val)); }; export const isJSON = (value?: unknown): value is JSONObject => { if (value === undefined) { return false; } if (!isObject(value)) { return false; } try { Object.keys(value).forEach((key) => assertString('JSONObject', key)); Object.values(value).forEach((val) => assertJSONValue('JSONObject', val)); } catch { return false; } return true; }; export const isJSONValue = (value?: unknown): value is JSONValue => { if (value === undefined) { return false; } if (typeof value === 'object') { return isJSON(value); } if (Array.isArray(value)) { return value.every(isJSONValue); } return true; }; export const assertJSONValue = (name: string, value?: unknown): JSONValue => { if (!isJSONValue(value)) { throw new InvalidArgumentError('JSONObject', name, value); } return value; }; export const assertNullableJSON = (name: string, value?: unknown): JSONObject => { if (value === undefined) { return {}; } if (!isJSON(value)) { throw new InvalidArgumentError('JSONObject', name, value); } return value; }; export const assertCallFlags = (name: string, value?: unknown): CallFlags => { const numberIn = assertNumber(name, value); let result; try { result = clientAssertCallFlags(numberIn); } catch { throw new InvalidArgumentError('CallFlags', name, value); } return result; }; export const assertMethodToken = (name: string, value?: unknown): MethodToken => { if (!isObject(value)) { throw new InvalidArgumentError('MethodToken', name, value); } return { hash: assertProperty(value, 'MethodToken', 'hash', assertUInt160Hex), method: assertProperty(value, 'MethodToken', 'method', assertString), paramCount: assertProperty(value, 'MethodToken', 'paramCount', assertNonNegativeNumber), hasReturnValue: assertProperty(value, 'MethodToken', 'hasReturnValue', assertBoolean), callFlags: assertProperty(value, 'MethodToken', 'callFlags', assertCallFlags), }; }; export const assertNefFile = (name: string, value?: unknown): Omit<NefFile, 'checksum' | 'magic'> => { if (!isObject(value)) { throw new InvalidArgumentError('NefFile', name, value); } return { compiler: assertProperty(value, 'NefFile', 'compiler', assertString), script: assertProperty(value, 'NefFile', 'script', assertString), tokens: assertProperty(value, 'NefFile', 'tokens', assertArray).map((token) => assertMethodToken('NefFile.tokens', token), ), }; }; export const assertContractManifestClient = (name: string, value?: unknown): ContractManifestClient => { if (!isObject(value)) { throw new InvalidArgumentError('ContractManifest', name, value); } return { name: assertProperty(value, 'ContractManifest', 'name', assertString), groups: assertProperty(value, 'ContractManifest', 'groups', assertArray).map((group) => assertContractGroup('ContractManifest.groups', group), ), supportedStandards: assertProperty(value, 'ContractManifest', 'supportedStandards', assertArray).map((std) => assertString('ContractManifest.supportedStandards', std), ), abi: assertProperty(value, 'ContractManifest', 'abi', assertContractABIClient), permissions: assertProperty(value, 'ContractManifest', 'permissions', assertArray).map((permission) => assertContractPermission('ContractManifest.permissions', permission), ), trusts: assertWildcardContainerProperty(value, 'ContractManifest', 'trusts', assertContractPermissionDescriptor), extra: assertProperty(value, 'ContractManifest', 'extra', assertNullableJSON), }; }; export const assertContractManifest = (name: string, value?: unknown): ContractManifest => { if (!isObject(value)) { throw new InvalidArgumentError('ContractManifest', name, value); } return { name: assertProperty(value, 'ContractManifest', 'name', assertString), groups: assertProperty(value, 'ContractManifest', 'groups', assertArray).map((group) => assertContractGroup('ContractManifest.groups', group), ), supportedStandards: assertProperty(value, 'ContractManifest', 'supportedStandards', assertArray).map((std) => assertString('ContractManifest.supportedStandards', std), ), abi: assertProperty(value, 'ContractManifest', 'abi', assertContractABI), permissions: assertProperty(value, 'ContractManifest', 'permissions', assertArray).map((permission) => assertContractPermission('ContractManifest.permissions', permission), ), trusts: assertWildcardContainerProperty(value, 'ContractManifest', 'trusts', assertContractPermissionDescriptor), extra: assertProperty(value, 'ContractManifest', 'extra', assertNullableJSON), }; }; const assertContractPermission = (name: string, value?: unknown): ContractPermission => { if (!isObject(value)) { throw new InvalidArgumentError('ContractPermission', name, value); } return { contract: assertProperty(value, 'ContractPermission', 'contract', assertContractPermissionDescriptor), methods: assertWildcardContainerProperty(value, 'ContractPermission', 'methods', assertString), }; }; const assertContractPermissionDescriptor = (name: string, value?: unknown): ContractPermissionDescriptor => { if (!isObject(value)) { throw new InvalidArgumentError('ContractPermissionDescriptor', name, value); } const hash = assertProperty(value, 'ContractPermissionDescriptor', 'hash', assertNullableUInt160Hex); const group = assertProperty(value, 'ContractPermissionDescriptor', 'group', assertNullablePublicKey); if (hash === undefined && group === undefined) { throw new InvalidArgumentError('ContractPermissionDescriptor', name, value); } return { hash, group, }; }; const assertContractGroup = (name: string, value?: unknown): ContractGroup => { if (!isObject(value)) { throw new InvalidArgumentError('ContractGroup', name, value); } return { publicKey: assertProperty(value, 'ContractGroup', 'publicKey', assertPublicKey), signature: assertProperty(value, 'ContractGroup', 'signature', assertBuffer), }; }; const assertSmartContractNetworkDefinition = (name: string, value?: unknown): SmartContractNetworkDefinition => { if (!isObject(value)) { throw new InvalidArgumentError('SmartContractNetworkDefinition', name, value); } return { address: assertProperty(value, 'SmartContractNetworkDefinition', 'address', assertAddress), }; }; const assertSmartContractNetworksDefinition = (name: string, value?: unknown): SmartContractNetworksDefinition => { if (!isObject(value)) { throw new InvalidArgumentError('SmartContractNetworksDefinition', name, value); } return _.mapValues(value, (val) => assertSmartContractNetworkDefinition('SmartContractNetworksDefinition', val), ) as SmartContractNetworksDefinition; }; export const assertSourceMaps = (_name: string, value?: unknown): SourceMaps | undefined => { if (value == undefined) { return undefined; } return value as SourceMaps; }; export const assertSmartContractDefinition = (name: string, value?: unknown): SmartContractDefinition => { if (!isObject(value)) { throw new InvalidArgumentError('SmartContractDefinition', name, value); } return { networks: assertProperty(value, 'SmartContractDefinition', 'networks', assertSmartContractNetworksDefinition), manifest: assertProperty(value, 'SmartContractDefinition', 'manifest', assertContractManifestClient), sourceMaps: assertProperty(value, 'SmartContractDefinition', 'sourceMaps', assertSourceMaps), }; }; export const assertScriptBuilderParam = (name: string, value?: unknown): ScriptBuilderParam => { if (value == undefined) { throw new InvalidArgumentError('ScriptBuilderParam', name, value); } // tslint:disable-next-line no-any return value as any; }; export const assertNullableScriptBuilderParam = (name: string, value?: unknown): ScriptBuilderParam | undefined => { if (value == undefined) { return undefined; } return assertScriptBuilderParam(name, value); }; export const assertParam = (name: string, value?: unknown): Param => { if (value == undefined) { throw new InvalidArgumentError('Param', name, value); } // tslint:disable-next-line no-any return value as any; }; export const assertNullableParam = (name: string, value?: unknown): Param | undefined => { if (value == undefined) { return undefined; } return assertParam(name, value); }; export const assertForwardValue = (name: string, value?: unknown): ForwardValue => { if (!isObject(value)) { throw new InvalidArgumentError('ForwardValue', name, value); } return { name: assertProperty(value, 'ForwardValue', 'name', assertString), converted: assertProperty(value, 'ForwardValue', 'converted', assertNullableScriptBuilderParam), param: assertProperty(value, 'ForwardValue', 'param', assertNullableParam), // tslint:disable-next-line no-any } as any; }; export const assertTransfer = (name: string, value?: unknown): Transfer => { if (!isObject(value)) { throw new InvalidArgumentError('Transfer', name, value); } return { amount: assertProperty(value, 'Transfer', 'amount', assertBigNumber), asset: assertProperty(value, 'Transfer', 'asset', tryGetUInt160Hex), to: assertProperty(value, 'Transfer', 'to', assertAddress), }; }; export const assertPrivateKey = (name: string, valueIn?: unknown): PrivateKeyString => { const value = assertString(name, valueIn); try { privateKeyToPublicKey(value); return value; } catch { try { return wifToPrivateKey(value); } catch { throw new InvalidArgumentError('PrivateKey', name, value); } } }; export const assertTransfers = (name: string, valueIn?: unknown): readonly Transfer[] => { const value = assertArray(name, valueIn); return value.map((val) => assertTransfer(name, val)); }; const assertAttributeTypeArg = (name: string, valueIn?: unknown): AttributeTypeModel => { const value = assertString(name, valueIn); try { return toAttributeType(assertAttributeTypeJSON(value)); } catch { throw new InvalidArgumentError('AttributeType', name, value); } }; const assertOracleResponseCode = (name: string, valueIn?: unknown): OracleResponseCode => { const value = assertNumber(name, valueIn); try { return assertOracleResponseCodeIn(value); } catch { throw new InvalidArgumentError('AttributeType', name, value); } }; export const assertAttribute = (name: string, attribute?: unknown): Attribute => { if (!isObject(attribute)) { throw new InvalidArgumentError('Attribute', name, attribute); } const type = assertProperty(attribute, 'Attribute', 'type', assertAttributeTypeArg); if (type === AttributeTypeModel.HighPriority) { return { type, }; } return { type, id: assertProperty(attribute, 'Attribute', 'id', assertBigNumber), code: assertProperty(attribute, 'Attribute', 'code', assertOracleResponseCode), result: assertProperty(attribute, 'Attribute', 'result', assertBuffer), }; }; export const assertTransactionOptions = (name: string, options?: unknown): TransactionOptions => { if (options == undefined) { return {}; } if (!isObject(options)) { throw new InvalidArgumentError('TransactionOptions', name, options); } return { from: assertProperty(options, 'TransactionOptions', 'from', assertNullableUserAccountID), attributes: assertProperty(options, 'TransactionOptions', 'attributes', assertNullableArray).map((value) => assertAttribute('TransactionOption.attributes', value), ), maxNetworkFee: assertProperty(options, 'TransactionOptions', 'maxNetworkFee', assertNullableBigNumber), maxSystemFee: assertProperty(options, 'TransactionOptions', 'maxSystemFee', assertNullableBigNumber), validBlockCount: assertProperty(options, 'TransactionOptions', 'validBlockCount', assertNullableNumber), // TODO: need sendTo and sendFrom here? Yes if they are included in TransactionOptions }; }; export const assertInvokeSendUnsafeReceiveTransactionOptions = ( name: string, options?: unknown, ): InvokeSendUnsafeReceiveTransactionOptions => { if (options == undefined) { return {}; } if (!isObject(options)) { throw new InvalidArgumentError('InvokeSendUnsafeReceiveTransactionOptions', name, options); } return { from: assertProperty(options, 'InvokeSendUnsafeReceiveTransactionOptions', 'from', assertNullableUserAccountID), attributes: assertProperty( options, 'InvokeSendUnsafeReceiveTransactionOptions', 'attributes', assertNullableArray, ).map((value) => assertAttribute('TransactionOption.attributes', value)), maxNetworkFee: assertProperty( options, 'InvokeSendUnsafeReceiveTransactionOptions', 'maxNetworkFee', assertNullableBigNumber, ), maxSystemFee: assertProperty( options, 'InvokeSendUnsafeReceiveTransactionOptions', 'maxSystemFee', assertNullableBigNumber, ), sendTo: assertProperty(options, 'InvokeSendUnsafeReceiveTransactionOptions', 'sendTo', assertNullableSendTo), sendFrom: assertProperty(options, 'InvokeSendUnsafeReceiveTransactionOptions', 'sendFrom', assertNullableSendFrom), }; }; const assertNullableSendTo = (name: string, value?: unknown): ReadonlyArray<OmitStrict<Transfer, 'to'>> | undefined => { if (value == undefined) { return undefined; } return assertNullableArray(name, value).map((transfer) => ({ amount: assertProperty(transfer, 'transfer', 'amount', assertBigNumber), asset: assertProperty(transfer, 'transfer', 'asset', assertUInt160Hex), })); }; const assertNullableSendFrom = (name: string, value?: unknown): readonly Transfer[] | undefined => { if (value == undefined) { return undefined; } return assertTransfers(name, value); }; export const assertNullableIterOptions = (name: string, options?: unknown): IterOptions | undefined => { if (options == undefined) { return undefined; } if (!isObject(options)) { throw new InvalidArgumentError('IterOptions', name, options); } const indexStart = assertProperty(options, 'IterOptions', 'indexStart', assertNullableNumber); const indexStop = assertProperty(options, 'IterOptions', 'indexStop', assertNullableNumber); if (indexStart != undefined && indexStop != undefined && indexStart >= indexStop) { throw new InvalidArgumentError('IterOptions', name, options); } return { indexStart, indexStop, }; };
the_stack
import React from "react"; import {Router} from "react-router"; import {render, fireEvent, wait, cleanup} from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import "@testing-library/jest-dom/extend-expect"; import {createMemoryHistory} from "history"; const history = createMemoryHistory(); import axiosMock from "axios"; import data from "../../assets/mock-data/curation/flows.data"; import Flows from "./flows"; import {SecurityTooltips} from "../../config/tooltips.config"; import {getViewSettings} from "../../util/user-context"; jest.mock("axios"); describe("Flows component", () => { let flowsProps = { flows: data.flows.data, steps: data.steps.data, deleteFlow: () => null, createFlow: () => null, updateFlow: () => null, deleteStep: () => null, runStep: () => null, running: [], uploadError: "", newStepToFlowOptions: () => null, addStepToFlow: () => null, flowsDefaultActiveKey: [], showStepRunResponse: () => null, runEnded: {}, onReorderFlow: () => null, }; const flowName = data.flows.data[0].name; const flowStepName = data.flows.data[0].steps[1].stepName; const addStepName = data.steps.data["ingestionSteps"][0].name; beforeEach(() => { axiosMock.get["mockImplementationOnce"](jest.fn(() => Promise.resolve({}))); }); afterEach(() => { jest.clearAllMocks(); cleanup(); }); it("Verifies input format names and type circles", () => { const allKindsOfIngestInAFlow = [{name: "allInputFormats", steps: [{ "stepDefinitionType": "ingestion", "sourceFormat": "csv" }, { "stepDefinitionType": "ingestion", "sourceFormat": "binary" }, { "stepDefinitionType": "ingestion", "sourceFormat": "text" }, { "stepDefinitionType": "ingestion", "sourceFormat": "json" }, { "stepDefinitionType": "ingestion", "sourceFormat": "xml"} ] }]; const {getByText, getByLabelText} = render( <Router history={history}> <Flows {...data.flowProps} flows={allKindsOfIngestInAFlow} /> </Router>); userEvent.click(getByLabelText("icon: right")); ["CSV", "BIN", "TXT", "JSON", "XML"].forEach(format => { expect(getByText(format)).toBeInTheDocument(); expect(getByText(format)).toHaveStyle("height: 35px; width: 35px; line-height: 35px; text-align: center;"); }); }); it("user with flow read, write, and operator privileges can view, edit, and run", async () => { const {getByText, getByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={true} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("icon: right"); expect(getByText(flowName)).toBeInTheDocument(); expect(getByLabelText("create-flow")).toBeInTheDocument(); expect(getByLabelText("deleteFlow-"+flowName)).toBeInTheDocument(); // check if delete tooltip appears fireEvent.mouseOver(getByLabelText("deleteFlow-"+flowName)); await wait(() => expect(getByText("Delete Flow")).toBeInTheDocument()); // Open flow fireEvent.click(flowButton); expect(getByText(flowStepName)).toBeInTheDocument(); expect(getByLabelText("runStep-"+flowStepName)).toBeInTheDocument(); expect(getByLabelText("deleteStep-"+flowStepName)).toBeInTheDocument(); // Open Add Step let addStep = getByText("Add Step"); fireEvent.click(addStep); expect(getByText(addStepName)).toBeInTheDocument(); }); it("user without flow write privileges cannot edit", async () => { const {getByText, getByLabelText, queryByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={false} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("icon: right"); expect(getByText(flowName)).toBeInTheDocument(); expect(getByLabelText("create-flow-disabled")).toBeInTheDocument(); expect(getByLabelText("deleteFlowDisabled-"+flowName)).toBeInTheDocument(); // test delete, create flow, add step buttons display correct tooltip when disabled fireEvent.mouseOver(getByLabelText("deleteFlowDisabled-"+flowName)); await wait(() => expect(getByText("Delete Flow: " + SecurityTooltips.missingPermission)).toBeInTheDocument()); fireEvent.mouseOver(getByLabelText("addStepDisabled-0")); await wait(() => expect(getByText(SecurityTooltips.missingPermission)).toBeInTheDocument()); fireEvent.mouseOver(getByLabelText("create-flow-disabled")); await wait(() => expect(getByText(SecurityTooltips.missingPermission)).toBeInTheDocument()); // Open flow fireEvent.click(flowButton); expect(getByText(flowStepName)).toBeInTheDocument(); expect(getByLabelText("runStep-"+flowStepName)).toBeInTheDocument(); // Has operator priv's, can still run expect(getByLabelText("deleteStepDisabled-"+flowStepName)).toBeInTheDocument(); // Open Add Step let addStep = getByText("Add Step"); fireEvent.click(addStep); expect(queryByLabelText(addStepName)).not.toBeInTheDocument(); }); it("user without flow write or operator privileges cannot edit or run", () => { const {getByText, getByLabelText, queryByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={false} hasOperatorRole={false} /></Router> ); let flowButton = getByLabelText("icon: right"); expect(getByText(flowName)).toBeInTheDocument(); expect(getByLabelText("create-flow-disabled")).toBeInTheDocument(); expect(getByLabelText("deleteFlowDisabled-"+flowName)).toBeInTheDocument(); // Open flow fireEvent.click(flowButton); expect(getByText(flowStepName)).toBeInTheDocument(); expect(getByLabelText("runStepDisabled-"+flowStepName)).toBeInTheDocument(); expect(getByLabelText("deleteStepDisabled-"+flowStepName)).toBeInTheDocument(); // Open Add Step let addStep = getByText("Add Step"); fireEvent.click(addStep); expect(queryByLabelText(addStepName)).not.toBeInTheDocument(); }); it("user without flow read, write, or operator privileges cannot view, edit, or run", () => { const {queryByText, queryByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={false} canWriteFlow={false} hasOperatorRole={false} /></Router> ); // Nothing shown, including Create button expect(queryByLabelText("(\"icon: right")).not.toBeInTheDocument(); expect(queryByText(flowName)).not.toBeInTheDocument(); }); it("create flow button can be focused and pressed by keyboard", async () => { const {getByText, getByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={true} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("create-flow"); expect(flowButton).toBeInTheDocument(); flowButton.focus(); expect(flowButton).toHaveFocus(); // button should be focusable // verified by tabbing away and tabbing back userEvent.tab(); expect(flowButton).not.toHaveFocus(); userEvent.tab({shift: true}); expect(flowButton).toHaveFocus(); // pressing enter on button should bring up New Flow dialogue box fireEvent.keyDown(flowButton, {key: "Enter", code: "Enter"}); expect(getByText("New Flow")).toBeInTheDocument(); }); it("links for steps lead to correct path", async () => { const {getByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={true} hasOperatorRole={true} /></Router> ); let i : number; userEvent.click(getByLabelText("icon: right")); for (i = 1; i < data.flows.data[0].steps.length + 1; ++i) { const pathname = `http://localhost/tiles/${data.flows.data[0].steps[i-1]["stepDefinitionType"] === "ingestion" ? "load": "curate"}`; expect(getByLabelText(`${flowName}-${i}-cardlink`).firstChild.href).toBe(pathname); } }); it("user with write privileges can reorder a flow", () => { const {getByText, getByLabelText, queryByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={true} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("icon: right"); fireEvent.click(flowButton); expect(getByText(flowStepName)).toBeInTheDocument(); // Middle step(s) have both left and right arrows expect(getByLabelText("rightArrow-"+flowStepName)).toBeInTheDocument(); expect(getByLabelText("leftArrow-"+flowStepName)).toBeInTheDocument(); // First step only has right arrow, and no left arrow const firstFlowStep = data.flows.data[0].steps[0].stepName; expect(getByLabelText("rightArrow-"+firstFlowStep)).toBeInTheDocument(); expect(queryByLabelText("leftArrow-"+firstFlowStep)).not.toBeInTheDocument(); // Last step only has left arrow, and no right arrow const lastFlowStep = data.flows.data[0].steps[data.flows.data[0].steps.length-1].stepName; expect(getByLabelText("leftArrow-"+lastFlowStep)).toBeInTheDocument(); expect(queryByLabelText("rightArrow-"+lastFlowStep)).not.toBeInTheDocument(); }); it("user without write privileges can't reorder a flow", () => { const {getByText, getByLabelText, queryByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={false} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("icon: right"); fireEvent.click(flowButton); expect(getByText(flowStepName)).toBeInTheDocument(); expect(queryByLabelText("rightArrow-"+flowStepName)).not.toBeInTheDocument(); expect(queryByLabelText("leftArrow-"+flowStepName)).not.toBeInTheDocument(); }); it("reorder flow buttons can be focused and pressed by keyboard", async () => { const {getByLabelText} = render( <Router history={history}><Flows {...flowsProps} canReadFlow={true} canWriteFlow={true} hasOperatorRole={true} /></Router> ); let flowButton = getByLabelText("icon: right"); fireEvent.click(flowButton); const rightArrowButton = getByLabelText("rightArrow-"+flowStepName); expect(rightArrowButton).toBeInTheDocument(); rightArrowButton.focus(); expect(rightArrowButton).toHaveFocus(); userEvent.tab(); expect(rightArrowButton).not.toHaveFocus(); userEvent.tab({shift: true}); expect(rightArrowButton).toHaveFocus(); const leftArrowButton = getByLabelText("leftArrow-"+flowStepName); expect(leftArrowButton).toBeInTheDocument(); leftArrowButton.focus(); expect(leftArrowButton).toHaveFocus(); userEvent.tab(); expect(leftArrowButton).not.toHaveFocus(); userEvent.tab({shift: true}); expect(leftArrowButton).toHaveFocus(); // Verifying a user can press enter to reorder steps in a flow rightArrowButton.onkeydown = jest.fn(); fireEvent.keyDown(rightArrowButton, {key: "Enter", code: "Enter"}); expect(rightArrowButton.onkeydown).toHaveBeenCalledTimes(1); leftArrowButton.onkeydown = jest.fn(); fireEvent.keyDown(leftArrowButton, {key: "Enter", code: "Enter"}); expect(leftArrowButton.onkeydown).toHaveBeenCalledTimes(1); }); }); describe("getViewSettings", () => { beforeEach(() => { window.sessionStorage.clear(); jest.restoreAllMocks(); }); const sessionStorageMock = (() => { let store = {}; return { getItem(key) { return store[key] || null; }, setItem(key, value) { store[key] = value.toString(); }, removeItem(key) { delete store[key]; }, clear() { store = {}; } }; })(); Object.defineProperty(window, "sessionStorage", { value: sessionStorageMock }); it("should get stored flows from session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({run: {openFlows: ["0", "1", "2"]}})); const actualValue = getViewSettings(); expect(actualValue).toEqual({run: {openFlows: ["0", "1", "2"]}}); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); it("should get stored flows from session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({run: {openFlows: ["0"]}})); const actualValue = getViewSettings(); expect(actualValue).toEqual({run: {openFlows: ["0"]}}); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); it("should get empty object if no info in session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); const actualValue = getViewSettings(); expect(actualValue).toEqual({}); expect(window.sessionStorage.getItem).toBeCalledWith("dataHubViewSettings"); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); });
the_stack
import Migrations from '../../lib/collections/migrations/collection'; import { Vulcan } from '../../lib/vulcan-lib'; import * as _ from 'underscore'; import { getSchema } from '../../lib/utils/getSchema'; // When running migrations with split batches, the fraction of time spent // running those batches (as opposed to sleeping). Used to limit database // load, since maxing out database capacity with a migration script could bring // the site down otherwise. See `runThenSleep`. const DEFAULT_LOAD_FACTOR = 0.5; export const availableMigrations: Record<string,any> = {}; export const migrationRunners: Record<string,any> = {}; // Put migration functions in a dictionary Vulcan.migrations to make it // accessible in meteor shell, working around awkward inability to import // things non-relatively there. Vulcan.migrations = migrationRunners; export function registerMigration({ name, dateWritten, idempotent, action }) { if (!name) throw new Error("Missing argument: name"); if (!dateWritten) throw new Error(`Migration ${name} is missing required field: dateWritten`); if (!action) throw new Error(`Migration ${name} is missing required field: action`); // The 'idempotent' parameter is mostly about forcing you to explicitly think // about migrations' idempotency and make them idempotent, and only // secondarily to enable the possibility of non-idempotent migrations later. // If you try to define a migration without marking it idempotent, throw an // error. if (!idempotent) { throw new Error(`Migration ${name} is not marked as idempotent; it can't use registerMigration unless it's marked as (and is) idempotent.`); } if (name in availableMigrations) { throw new Error(`Duplicate migration or name collision: ${name}`); } availableMigrations[name] = { name, dateWritten, idempotent, action }; migrationRunners[name] = async () => await runMigration(name); } export async function runMigration(name: string) { if (!(name in availableMigrations)) throw new Error(`Unrecognized migration: ${name}`); // eslint-disable-next-line no-unused-vars const { dateWritten, idempotent, action } = availableMigrations[name]; // eslint-disable-next-line no-console console.log(`Beginning migration: ${name}`); const migrationLogId = await Migrations.rawInsert({ name: name, started: new Date(), }); try { await action(); await Migrations.rawUpdateOne({_id: migrationLogId}, {$set: { finished: true, succeeded: true, }}); // eslint-disable-next-line no-console console.log(`Finished migration: ${name}`); } catch(e) { // eslint-disable-next-line no-console console.error(`FAILED migration: ${name}.`); // eslint-disable-next-line no-console console.error(e); await Migrations.rawUpdateOne({_id: migrationLogId}, {$set: { finished: true, succeeded: false, }}); } } function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } // Run a function, timing how long it took, then sleep for an amount of time // such that if you apply this to each of a series of batches, the fraction of // time spent not sleeping is equal to `loadFactor`. Used when doing a batch // migration or similarly slow operation, which can be broken into smaller // steps, to keep the database load low enough for the site to keep running. export async function runThenSleep(loadFactor: number, func: ()=>Promise<void>) { if (loadFactor <=0 || loadFactor > 1) throw new Error(`Invalid loadFactor ${loadFactor}: must be in (0,1].`); const startTime = new Date(); try { await func(); } finally { const endTime = new Date(); const timeSpentMs = endTime.valueOf()-startTime.valueOf(); // loadFactor = timeSpentMs / (timeSpentMs + sleepTimeMs) // [Algebra happens] // sleepTimeMs = timeSpentMs * (1/loadFactor - 1) const sleepTimeMs = timeSpentMs * ((1/loadFactor) - 1); await sleep(sleepTimeMs); } } // Given a collection which has a field that has a default value (specified // with ...schemaDefaultValue), fill in the default value for any rows where it // is missing. export async function fillDefaultValues<T extends DbObject>({ collection, fieldName, batchSize, loadFactor=DEFAULT_LOAD_FACTOR }: { collection: CollectionBase<T>, fieldName: string, batchSize?: number, loadFactor?: number }) { if (!collection) throw new Error("Missing required argument: collection"); if (!fieldName) throw new Error("Missing required argument: fieldName"); const schema = getSchema(collection); if (!schema) throw new Error(`Collection ${collection.collectionName} does not have a schema`); const defaultValue = schema[fieldName].defaultValue; if (defaultValue === undefined) throw new Error(`Field ${fieldName} does not have a default value`); if (!schema[fieldName].canAutofillDefault) throw new Error(`Field ${fieldName} is not marked autofillable`); // eslint-disable-next-line no-console console.log(`Filling in default values of ${collection.collectionName}.${fieldName}`); let nMatched = 0; await forEachBucketRangeInCollection({ collection, bucketSize: batchSize||10000, filter: { [fieldName]: null }, fn: async (bucketSelector) => { await runThenSleep(loadFactor, async () => { const mutation = { $set: { [fieldName]: defaultValue } }; const writeResult = await collection.rawUpdateMany(bucketSelector, mutation, {multi: true}); nMatched += writeResult || 0; // eslint-disable-next-line no-console console.log(`Finished bucket. Write result: ${JSON.stringify(writeResult)}`); }); } }); // eslint-disable-next-line no-console console.log(`Done. ${nMatched} rows matched`); } // Given a query which finds documents in need of a migration, and a function // which takes a batch of documents and migrates them, repeatedly search for // unmigrated documents and call the migrate function, until there are no // unmigrated documents left. // // `migrate` should be a function which takes an array of documents (from a // `collection.find`), and performs database operations to update them. After // the update is performed, the documents should no longer match // unmigratedDocumentQuery. (If they do, and the same document gets returned // in any two consecutive queries, this will abort and throw an exception. // However, this is not guaranteed to ever happen, because the // unmigratedDocumentQuery is run without a sort criterion applied). // // No special effort is made to do locking or protect you from race conditions // if things other than this migration script are happening on the same // database. This function makes sense for filling in new denormalized fields, // where figuring out the new field's value requires an additional query. export async function migrateDocuments<T extends DbObject>({ description, collection, batchSize, unmigratedDocumentQuery, migrate, loadFactor=DEFAULT_LOAD_FACTOR }: { description?: string, collection: CollectionBase<T>, batchSize?: number, unmigratedDocumentQuery?: any, migrate: (documents: Array<T>) => Promise<void>, loadFactor?: number, }) { // Validate arguments if (!collection) throw new Error("Missing required argument: collection"); // if (!unmigratedDocumentQuery) throw new Error("Missing required argument: unmigratedDocumentQuery"); if (!migrate) throw new Error("Missing required argument: migrate"); if (!batchSize || !(batchSize>0)) throw new Error("Invalid batch size"); if (!description) description = "Migration on "+collection.collectionName; // eslint-disable-next-line no-console console.log(`Beginning migration step: ${description}`); if (!unmigratedDocumentQuery) { // eslint-disable-next-line no-console console.log(`No unmigrated-document query found, migrating all documents in ${collection.collectionName}`) await forEachDocumentBatchInCollection({collection, batchSize, callback: migrate, loadFactor}) // eslint-disable-next-line no-console console.log(`Finished migration step ${description} for all documents`) return } let previousDocumentIds = {}; let documentsAffected = 0; let done = false; // eslint-disable-next-line no-constant-condition while(!done) { await runThenSleep(loadFactor, async () => { let documents = await collection.find(unmigratedDocumentQuery, {limit: batchSize}).fetch(); if (!documents.length) { done = true; return; } // Check if any of the documents returned were supposed to have been // migrated by the previous batch's update operation. let docsNotMigrated = _.filter(documents, doc => previousDocumentIds[doc._id]); if (docsNotMigrated.length > 0) { let errorMessage = `Documents not updated in migrateDocuments: ${_.map(docsNotMigrated, doc=>doc._id)}`; // eslint-disable-next-line no-console console.error(errorMessage); throw new Error(errorMessage); } previousDocumentIds = {}; _.each(documents, doc => previousDocumentIds[doc._id] = true); // Migrate documents in the batch try { await migrate(documents); documentsAffected += documents.length; // eslint-disable-next-line no-console console.log("Documents updated: ", documentsAffected) } catch(e) { // eslint-disable-next-line no-console console.error("Error running migration"); // eslint-disable-next-line no-console console.error(JSON.stringify(e)); throw(e); } }); } // eslint-disable-next-line no-console console.log(`Finished migration step: ${description}. ${documentsAffected} documents affected.`); } export async function dropUnusedField(collection, fieldName) { const loadFactor = 0.5; let nMatched = 0; await forEachBucketRangeInCollection({ collection, filter: { [fieldName]: {$exists: true} }, fn: async (bucketSelector) => { await runThenSleep(loadFactor, async () => { const mutation = { $unset: { [fieldName]: 1 } }; const writeResult = await collection.rawUpdateMany( bucketSelector, mutation, {multi: true} ); nMatched += writeResult; }); } }); // eslint-disable-next-line no-console console.log(`Dropped unused field ${collection.collectionName}.${fieldName} (${nMatched} rows)`); } // Given a collection and a batch size, run a callback for each row in the // collection, grouped into batches of up to the given size. Rows created or // deleted while this is running might or might not get included (neither is // guaranteed). // // This works by querying a range of IDs, with a limit, and using the largest // ID from each batch to find the start of the interval for the next batch. // This expects that `max` is a sensible operation on IDs, treated the same // way in Javascript as in Mongo; which translates into the assumption that IDs // are homogenously string typed. Ie, this function will break if some rows // have _id of type ObjectID instead of string. export async function forEachDocumentBatchInCollection({collection, batchSize=1000, filter=null, callback, loadFactor=1.0}: { collection: any, batchSize?: number, filter?: MongoSelector<DbObject> | null, callback: Function, loadFactor?: number }) { // As described in the docstring, we need to be able to query on the _id. // Without this check, someone trying to use _id in the filter would overwrite // this function's query and find themselves with an infinite loop. if (filter && '_id' in filter) { throw new Error('forEachDocumentBatchInCollection does not support filtering by _id') } let rows = await collection.find({ ...filter }, { sort: {_id: 1}, limit: batchSize } ).fetch(); while(rows.length > 0) { await runThenSleep(loadFactor, async () => { await callback(rows); const lastID = rows[rows.length - 1]._id rows = await collection.find( { _id: {$gt: lastID}, ...filter }, { sort: {_id: 1}, limit: batchSize } ).fetch(); }); } } export async function forEachDocumentInCollection({collection, batchSize=1000, filter=null, callback, loadFactor=1.0}: { collection: any, batchSize?: number, filter?: MongoSelector<DbObject> | null, callback: Function, loadFactor?: number }) { await forEachDocumentBatchInCollection({collection,batchSize,filter,loadFactor, callback: async (docs: any[]) => { for (let doc of docs) { await callback(doc); } } }); } // Given a collection, an optional filter, and a target batch size, partition // the collection into buckets of approximately that size, and call a function // with a series of selectors that narrow the collection to each of those // buckets. // // collection: The collection to iterate over. // filter: (Optional) A mongo query which constrains the subset of documents // iterated over. // bucketSize: Approximate number of results in each bucket. This will not // be exact, both because buckets will be approximately balanced (so eg if // you ask for 2k-row buckets of a 3k-row collection, you actually get // 1.5k-row average buckets), and because bucket boundaries are generated // by a statistical approximation using sampling. // fn: (bucketSelector=>null) Callback function run for each bucket. Takes a // selector, which includes both an _id range (either one- or two-sided) // and also the selector from `filter`. export async function forEachBucketRangeInCollection({collection, filter, bucketSize=1000, fn}) { // Get filtered collection size and use it to calculate a number of buckets const count = await collection.find(filter).count(); // If no documents match the filter, return with zero batches if (count === 0) return; // Calculate target number of buckets const bucketCount = Math.max(1, Math.floor(count / bucketSize)); // Calculate target sample size const sampleSize = 20 * bucketCount // Calculate bucket boundaries using Mongo aggregate const maybeFilter = (filter ? [{ $match: filter }] : []); const bucketBoundaries = await collection.aggregate([ ...maybeFilter, { $sample: { size: sampleSize } }, { $sort: {_id: 1} }, { $bucketAuto: { groupBy: '$_id', buckets: bucketCount}}, { $project: {value: '$_id.max', _id: 0}} ]).toArray(); // Starting at the lowest bucket boundary, iterate over buckets await fn({ _id: {$lt: bucketBoundaries[0].value}, ...filter }); for (let i=0; i<bucketBoundaries.length-1; i++) { await fn({ _id: { $gte: bucketBoundaries[i].value, $lt: bucketBoundaries[i+1].value, }, ...filter }) } await fn({ _id: {$gte: bucketBoundaries[bucketBoundaries.length-1].value}, ...filter }); } Vulcan.dropUnusedField = dropUnusedField
the_stack
import type { ElementType, FunctionComponent } from 'react'; import React, { Component, Fragment, Suspense, forwardRef } from 'react'; import { RicosEngine, shouldRenderChild, localeStrategy, getBiCallback as getCallback, } from 'ricos-common'; import type { DraftContent } from 'ricos-content'; import type { RichContentEditorProps } from 'wix-rich-content-editor'; import { RichContentEditor } from 'wix-rich-content-editor'; import { createDataConverter, filterDraftEditorSettings } from './utils/editorUtils'; import ReactDOM from 'react-dom'; import type { EditorState, ContentState } from 'draft-js'; import RicosModal from './modals/RicosModal'; import editorCss from '../statics/styles/styles.scss'; import type { RicosEditorProps, EditorDataInstance } from '.'; import type { RicosEditorRef } from './RicosEditorRef'; import { hasActiveUploads } from './utils/hasActiveUploads'; import { convertToRaw, convertFromRaw, createWithContent, } from 'wix-rich-content-editor/libs/editorStateConversion'; import { isEqual, compact } from 'lodash'; import { EditorEventsContext, EditorEvents, } from 'wix-rich-content-editor-common/libs/EditorEventsContext'; import { ToolbarType, Version, RicosTranslate, getLangDir, GlobalContext, } from 'wix-rich-content-common'; import { getEmptyDraftContent, getEditorContentSummary } from 'wix-rich-content-editor-common'; import englishResources from 'wix-rich-content-common/dist/statics/locale/messages_en.json'; import type { TextFormattingToolbarType } from './toolbars/TextFormattingToolbar'; import { getBiFunctions } from './toolbars/utils/biUtils'; import { renderSideBlockComponent } from './utils/renderBlockComponent'; import type { TiptapEditorPlugin } from 'ricos-tiptap-types'; import { createEditorStyleClasses } from './utils/createEditorStyleClasses'; import { DraftEditorStateTranslator } from './content-conversion/draft-editor-state-translator'; import { TiptapEditorStateTranslator } from './content-conversion/tiptap-editor-state-translator'; import { DraftEditablesRepository } from './content-modification/services/draft-editables-repository'; import { TiptapEditablesRepository } from './content-modification/services/tiptap-editables-repository'; import { EditorCommandRunner } from './content-modification/command-runner'; import { TiptapMockToolbar } from './tiptapMockToolbar/TiptapMockToolbar'; import { convertToolbarContext } from './toolbars/convertToolbarContext'; import { coreCommands } from './content-modification/commands/core-commands'; import UploadObserver from './utils/UploadObserver'; import { Node_Type } from 'ricos-schema'; // eslint-disable-next-line export const PUBLISH_DEPRECATION_WARNING_v9 = `Please provide the postId via RicosEditor biSettings prop and use editorEvents.publish() APIs for publishing. The getContent(postId, isPublishing) API is deprecated and will be removed in ricos v9.0.0`; const LinkToolbar = React.lazy(() => import('./toolbars/LinkToolbar')); interface State { StaticToolbar?: ElementType; localeData: { locale?: string; localeResource?: Record<string, string> }; remountKey: boolean; editorState?: EditorState; activeEditor: RichContentEditor | null; // eslint-disable-next-line @typescript-eslint/no-explicit-any tiptapEditorModule: Record<string, any> | null; tiptapToolbar: unknown; error?: string; contentId?: string; TextFormattingToolbar?: TextFormattingToolbarType | null; } // controller between tiptap extensions to ricos editor // extracts data from Ricos Extensions // gives context (Ricos editor context) // awares of tiptap // sort , filter export class RicosEditor extends Component<RicosEditorProps, State> implements RicosEditorRef { editor!: RichContentEditor; useTiptap = false; useNewFormattingToolbar = false; useToolbarsV3 = false; detachCommands = false; dataInstance!: EditorDataInstance; draftEditorStateTranslator!: DraftEditorStateTranslator; tiptapEditorStateTranslator!: TiptapEditorStateTranslator; editorCommandRunner!: EditorCommandRunner; isBusy = false; initialContentChanged = false; getBiCallback: typeof getCallback; currentEditorRef!: ElementType; textFormattingToolbarRef!: Record<'updateToolbar', () => void>; linkToolbarRef!: Record<'updateToolbar', () => void>; UploadObserver?: UploadObserver; static getDerivedStateFromError(error: string) { return { error }; } componentDidCatch(error, errorInfo) { console.error({ error, errorInfo }); } constructor(props: RicosEditorProps) { super(props); this.detachCommands = !!props.experiments?.detachCommandsFromEditor?.enabled; if (this.detachCommands) { this.draftEditorStateTranslator = new DraftEditorStateTranslator(); this.tiptapEditorStateTranslator = new TiptapEditorStateTranslator(); } this.dataInstance = createDataConverter( [this.props.onChange, this.draftEditorStateTranslator?.onChange], this.props.content ); this.getBiCallback = getCallback.bind(this); this.state = { localeData: { locale: props.locale }, remountKey: false, activeEditor: null, tiptapEditorModule: null, tiptapToolbar: null, TextFormattingToolbar: null, }; this.useTiptap = !!props.experiments?.tiptapEditor?.enabled; this.useNewFormattingToolbar = !!props.experiments?.newFormattingToolbar?.enabled; this.useToolbarsV3 = !!props.experiments?.toolbarsV3?.enabled; props.experiments?.useUploadContext?.enabled && (this.UploadObserver = new UploadObserver()); } static defaultProps = { onError: err => { throw err; }, locale: 'en', }; updateLocale = async () => { const { children } = this.props; const locale = children?.props.locale || this.props.locale; await localeStrategy(locale) .then(localeData => this.setState({ localeData, remountKey: !this.state.remountKey })) .catch(error => this.setState({ error })); }; componentDidMount() { this.updateLocale(); this.loadEditor(); this.loadToolbar(); this.initCommandRunner(); const { isMobile, toolbarSettings, _rcProps = {} } = this.props; const { useStaticTextToolbar } = toolbarSettings || {}; const contentId = this.getContentId(); this.setState({ contentId }); this.getBiCallback('onOpenEditorSuccess')?.( Version.currentVersion, isMobile ? ToolbarType.MOBILE : useStaticTextToolbar ? ToolbarType.STATIC : ToolbarType.INLINE, contentId ); this.props.editorEvents?.subscribe(EditorEvents.RICOS_PUBLISH, this.onPublish); if (_rcProps.onLoad) { const { theme, locale, plugins, linkPanelSettings, linkSettings, experiments, cssOverride } = this.props; const { onLoad, helpers } = _rcProps; onLoad( convertToolbarContext({ contentId, isMobile, theme, locale, helpers, plugins, linkPanelSettings, linkSettings, experiments, toolbarSettings, cssOverride, getEditorCommands: this.getEditorCommands, }) ); } } loadEditor() { if (this.useTiptap) { import( /* webpackChunkName: "wix-tiptap-editor" */ 'wix-tiptap-editor' ).then(tiptapEditorModule => { this.setState({ tiptapEditorModule }); }); } } loadToolbar() { if (this.useNewFormattingToolbar) { import( /* webpackChunkName: "./toolbars/TextFormattingToolbar" */ './toolbars/TextFormattingToolbar' ).then(textFormattingToolbarModule => { this.setState({ TextFormattingToolbar: textFormattingToolbarModule?.default }); }); } } initCommandRunner = async () => { if (this.detachCommands) { const repo = await (this.useTiptap ? this.initTiptapRepository() : this.initDraftRepository()); this.editorCommandRunner = new EditorCommandRunner(repo); [...coreCommands, ...(this.props?.commands || [])].map(command => this.editorCommandRunner.register(command) ); } }; initDraftRepository = () => { return import( /* webpackChunkName: "ricos-content/libs/converters" */ 'ricos-content/libs/converters' ).then(convertersModule => { const { toDraft, fromDraft } = convertersModule; return new DraftEditablesRepository(this.draftEditorStateTranslator, toDraft, fromDraft); }); }; initTiptapRepository() { return import( /* webpackChunkName:"ricos-converters" */ 'ricos-converters' ).then(convertersModule => { const { toTiptap, fromTiptap } = convertersModule; return new TiptapEditablesRepository(this.tiptapEditorStateTranslator, toTiptap, fromTiptap); }); } onUpdate = ({ content }: { content: DraftContent }) => { const editorState = createWithContent(convertFromRaw(content)); this.onChange()(editorState); }; componentWillUnmount() { this.props.editorEvents?.unsubscribe(EditorEvents.RICOS_PUBLISH, this.onPublish); } // TODO: remove deprecated postId once getContent(postId) is removed (9.0.0) sendPublishBi = async (postId?: string) => { const onPublish = this.props._rcProps?.helpers?.onPublish; if (!onPublish) { return; } const contentState = this.dataInstance.getContentState(); const { pluginsCount, pluginsDetails } = getEditorContentSummary(contentState) || {}; onPublish(postId, pluginsCount, pluginsDetails, Version.currentVersion, this.getContentId()); }; onPublish = async () => { // TODO: remove this param after getContent(postId) is deprecated this.sendPublishBi(undefined as unknown as string); console.debug('editor publish callback'); // eslint-disable-line return { type: 'EDITOR_PUBLISH', data: await this.getContent(), }; }; publish = async () => { const publishResponse = await this.onPublish(); return publishResponse.data; }; componentWillReceiveProps(newProps: RicosEditorProps) { if (newProps.locale !== this.props.locale) { this.updateLocale(); } if ( newProps.injectedContent && !isEqual(this.props.injectedContent, newProps.injectedContent) ) { console.debug('new content provided as editorState'); // eslint-disable-line const editorState = createWithContent(convertFromRaw(newProps.injectedContent)); this.setState({ editorState }, () => { this.dataInstance = createDataConverter( [ this.props.onChange, this.detachCommands ? this.draftEditorStateTranslator.onChange : undefined, ], this.props.injectedContent ); this.dataInstance.refresh(editorState); }); } } onInitialContentChanged = () => { const contentId = this.getContentId(); this.getBiCallback('onContentEdited')?.({ version: Version.currentVersion, contentId }); this.initialContentChanged = true; }; onChange = (childOnChange?: RichContentEditorProps['onChange']) => (editorState: EditorState) => { try { this.dataInstance.refresh(editorState); if (!this.initialContentChanged && this.getContentTraits().isContentChanged) { this.onInitialContentChanged(); } childOnChange?.(editorState); this.onBusyChange(editorState.getCurrentContent()); this.useNewFormattingToolbar && this.updateToolbars(); } catch (err) { this.setState({ error: err }); } }; getToolbarProps = (type: ToolbarType) => this.editor?.getToolbarProps(type); focus = () => this.editor.focus(); blur = () => this.editor.blur(); getToolbars = () => this.editor.getToolbars(); getContentTraits = () => this.dataInstance.getContentTraits(); getContent = async ( postId?: string, forPublish?: boolean, shouldRemoveErrorBlocks = true ): Promise<DraftContent> => { if (postId && forPublish) { console.warn(PUBLISH_DEPRECATION_WARNING_v9); // eslint-disable-line this.sendPublishBi(postId); //async } return this.dataInstance.getContentState({ shouldRemoveErrorBlocks }); }; getContentPromise = async ({ publishId, flush, }: { flush?: boolean; publishId?: string } = {}) => { const { getContentStatePromise, waitForUpdate } = this.dataInstance; if (flush) { waitForUpdate(); this.blur(); } const res = await getContentStatePromise(); if (publishId) { console.warn(PUBLISH_DEPRECATION_WARNING_v9); // eslint-disable-line this.sendPublishBi(publishId); } return res; }; onBusyChange = (contentState: ContentState) => { const { onBusyChange, onChange, experiments } = this.props; const isBusy = experiments?.useUploadContext?.enabled ? !!this.UploadObserver?.hasActiveUploads() : hasActiveUploads(contentState); if (this.isBusy !== isBusy) { this.isBusy = isBusy; onBusyChange?.(isBusy); onChange?.(convertToRaw(contentState)); } }; setActiveEditor = ref => { const { activeEditor } = this.state; if (ref && ref !== activeEditor) { const { MobileToolbar, TextToolbar } = ref.getToolbars(); this.setState({ StaticToolbar: MobileToolbar || TextToolbar, activeEditor: ref }); } }; setEditorRef = ref => { this.editor = ref; this.setActiveEditor(ref); if (this.detachCommands && ref && !this.useTiptap) { this.draftEditorStateTranslator.setEditorState = ref.setEditorState; } }; getEditorCommands = () => this.editor?.getEditorCommands(); getCommands = () => (this.detachCommands ? this.editorCommandRunner.getCommands() : {}); getT = () => this.editor.getT(); getContentId = () => this.dataInstance.getContentState().ID; renderToolbarPortal(Toolbar) { return ( <StaticToolbarPortal StaticToolbar={Toolbar} textToolbarContainer={this.props.toolbarSettings?.textToolbarContainer} /> ); } renderRicosEngine(child, childProps) { const { toolbarSettings, draftEditorSettings = {}, localeContent, ...props } = this.props; const { isMobile, experiments = {}, cssOverride } = props; const supportedDraftEditorSettings = filterDraftEditorSettings(draftEditorSettings); const contentProp = this.getContentProp(); return ( <RicosEngine RicosModal={RicosModal} isViewer={false} key={'editor'} toolbarSettings={toolbarSettings} getContentId={this.getContentId} editorCommands={this.getEditorCommands()} {...contentProp.content} {...props} {...this.state.localeData} UploadObserver={this.UploadObserver} experiments={experiments} > {React.cloneElement(child, { editorKey: 'editor', setEditorToolbars: this.setActiveEditor, editorStyleClasses: createEditorStyleClasses({ isMobile, experiments, cssOverride, editorCss, }), ...childProps, ...contentProp.editorState, ...supportedDraftEditorSettings, ...this.state.localeData, localeContent, })} </RicosEngine> ); } setTextFormattingToolbarRef = ref => (this.textFormattingToolbarRef = ref); setLinkToolbarRef = ref => (this.linkToolbarRef = ref); updateToolbars = () => { this.textFormattingToolbarRef?.updateToolbar(); this.linkToolbarRef?.updateToolbar(); }; renderNewToolbars() { const { TextFormattingToolbar, activeEditor, contentId } = this.state; const { isMobile = false, theme, locale, _rcProps: { helpers } = {}, plugins, linkPanelSettings, linkSettings, toolbarSettings, cssOverride, experiments = {}, } = this.props; const getEditorContainer = this.editor?.getContainer; const { useStaticTextToolbar } = toolbarSettings || {}; const activeEditorIsTableCell = !this.useTiptap && activeEditor?.isInnerRCERenderedInTable(); const textToolbarType = isMobile ? ToolbarType.MOBILE : useStaticTextToolbar ? ToolbarType.STATIC : ToolbarType.INLINE; const biFunctions = helpers && getBiFunctions(helpers, contentId); const toolbarsProps = { textToolbarType, isMobile, theme, toolbarSettings, locale, plugins, linkPanelSettings, linkSettings, ...biFunctions, cssOverride, getEditorContainer, }; const baseStyles = { flex: 'none', webkitTapHighlightColor: 'transparent' }; const baseMobileStyles = { ...baseStyles, position: 'sticky', top: 0, zIndex: 9 }; const linkPluginInstalled = !!plugins?.find(plugin => plugin.type === 'LINK'); return ( !activeEditorIsTableCell && activeEditor && ( <GlobalContext.Provider value={{ experiments, isMobile }}> <div data-hook={'ricos-editor-toolbars'} style={isMobile ? baseMobileStyles : baseStyles} dir={getLangDir(locale)} > {TextFormattingToolbar && ( <TextFormattingToolbar ref={this.setTextFormattingToolbarRef} activeEditor={activeEditor} {...toolbarsProps} /> )} {linkPluginInstalled && ( <Suspense fallback={''}> <LinkToolbar ref={this.setLinkToolbarRef} activeEditor={activeEditor} {...toolbarsProps} /> </Suspense> )} </div> </GlobalContext.Provider> ) ); } renderToolbars() { if (this.useToolbarsV3) { return null; } const { StaticToolbar } = this.state; return this.useNewFormattingToolbar ? this.renderNewToolbars() : this.renderToolbarPortal(StaticToolbar); } renderSideBlocksComponents = () => { const { sideBlockComponent, locale } = this.props; if (!sideBlockComponent) { return null; } const dir = getLangDir(locale); const nodes = this.getEditorCommands()?.getAllBlocksKeys(); return ( <div dir={dir} style={{ position: 'absolute' }}> {nodes?.map(id => renderSideBlockComponent(id, dir, sideBlockComponent))} </div> ); }; renderDraftEditor() { const { remountKey } = this.state; const child = this.props.children && shouldRenderChild('RichContentEditor', this.props.children) ? ( this.props.children ) : ( <RichContentEditor /> ); return ( <Fragment key={`${remountKey}`}> {this.renderToolbars()} {this.renderSideBlocksComponents()} {this.renderRicosEngine(child, { onChange: this.onChange(child.props.onChange), ref: this.setEditorRef, })} </Fragment> ); } updateNewFormattingToolbar = () => this.useNewFormattingToolbar && this.updateToolbars(); renderTiptapEditor() { const { tiptapEditorModule } = this.state; if (!tiptapEditorModule) { return null; } const { RicosTiptapEditor, RichContentAdapter, draftToTiptap, TIPTAP_TYPE_TO_RICOS_TYPE } = tiptapEditorModule; const { content, injectedContent, plugins, onAtomicBlockFocus, experiments } = this.props; const { tiptapToolbar } = this.state; // TODO: Enforce Content ID's existance (or generate it) // when tiptap will eventually be released (ask @Barackos, @talevy17) const initialContent = draftToTiptap(content ?? injectedContent ?? getEmptyDraftContent()); const { localeData } = this.state; const { locale, localeResource } = localeData; const extensions = compact(plugins?.flatMap((plugin: TiptapEditorPlugin) => plugin.tiptapExtensions)) || []; return ( <Fragment> {this.renderToolbars()} {tiptapToolbar && this.renderToolbarPortal(tiptapToolbar)} {experiments?.TiptapMockToolbar?.enabled && ( <TiptapMockToolbar editor={this.state.activeEditor} /> )} { <RicosTranslate locale={locale} localeResource={localeResource || englishResources}> {t => { const tiptapEditor = ( <RicosTiptapEditor ricosProps={this.props} placeholder={this.props.placeholder} extensions={extensions} content={initialContent} t={t} onLoad={editor => { const richContentAdapter = new RichContentAdapter(editor, t, plugins); this.setEditorRef(richContentAdapter); if (this.detachCommands) { this.tiptapEditorStateTranslator.onChange(editor); } const TextToolbar = richContentAdapter.getToolbars().TextToolbar; this.setState({ tiptapToolbar: TextToolbar }); }} onUpdate={this.onUpdate} onBlur={this.updateNewFormattingToolbar} onSelectionUpdate={({ selectedNodes, content }) => { //TODO: add 'textContainer' to group field of this extension config const textContainers = [ Node_Type.PARAGRAPH, Node_Type.CODE_BLOCK, Node_Type.HEADING, ]; const parentNodes = selectedNodes.length === 1 ? selectedNodes : selectedNodes.filter(node => textContainers.includes(node.type.name)); if (parentNodes.length === 1 && parentNodes[0].isBlock) { const firstNode = parentNodes[0]; const blockKey = firstNode.attrs.id; const type = TIPTAP_TYPE_TO_RICOS_TYPE[firstNode.type.name] || 'text'; const data = firstNode.attrs; onAtomicBlockFocus?.({ blockKey, type, data }); } else { onAtomicBlockFocus?.({ blockKey: undefined, type: undefined, data: undefined, }); } this.updateNewFormattingToolbar(); this.onUpdate({ content }); }} /> ); return this.renderRicosEngine(tiptapEditor, {}); }} </RicosTranslate> } </Fragment> ); } getContentProp() { const { editorState } = this.state; const { content } = this.props; return editorState ? { editorState: { editorState }, content: {} } : { editorState: {}, content: { content } }; } render() { try { if (this.state.error) { this.props.onError?.(this.state.error); return null; } return this.useTiptap ? this.renderTiptapEditor() : this.renderDraftEditor(); } catch (e) { this.props.onError?.(e); return null; } } } export default forwardRef<RicosEditor, RicosEditorProps>((props, ref) => ( <EditorEventsContext.Consumer> {contextValue => <RicosEditor editorEvents={contextValue} {...props} ref={ref} />} </EditorEventsContext.Consumer> )); const StaticToolbarPortal: FunctionComponent<{ StaticToolbar?: ElementType; textToolbarContainer?: HTMLElement; }> = ({ StaticToolbar, textToolbarContainer }) => { if (!StaticToolbar) return null; if (textToolbarContainer) { return ReactDOM.createPortal(<StaticToolbar />, textToolbarContainer); } return <StaticToolbar />; };
the_stack
describe.concurrent("Stream", () => { describe.concurrent("zipAllSortedByKeyWith", () => { // TODO(Mike/Max): implement after Gen it.skip("zips and sorts by keys", async () => { // val genSortedByKey = for { // map <- Gen.mapOf(Gen.int(1, 100), Gen.int(1, 100)) // chunk = Chunk.fromIterable(map).sorted // chunks <- splitChunks(Chunk(chunk)) // } yield chunks // check(genSortedByKey, genSortedByKey) { (as, bs) => // val left = ZStream.fromChunks(as: _*) // val right = ZStream.fromChunks(bs: _*) // val actual = left.zipAllSortedByKeyWith(right)(identity, identity)(_ + _) // val expected = Chunk.fromIterable { // as.flatten.toMap.foldLeft(bs.flatten.toMap) { case (map, (k, v)) => // map.get(k).fold(map + (k -> v))(v1 => map + (k -> (v + v1))) // } // }.sorted // assertM(actual.runCollect)(equalTo(expected)) // } }) }) describe.concurrent("zip", () => { it("doesn't pull too much when one of the streams is done", async () => { const left = Stream.fromChunks(Chunk(1, 2), Chunk(3, 4), Chunk(5)) + Stream.fail("nothing to see here") const right = Stream.fromChunks(Chunk("a", "b"), Chunk("c")) const program = left.zip(right).runCollect() const result = await program.unsafeRunPromise() assert.isTrue(result == Chunk(Tuple(1, "a"), Tuple(2, "b"), Tuple(3, "c"))) }) it("equivalence with Chunk.zip", async () => { const left = Chunk(Chunk(1, 2), Chunk(3, 4), Chunk(5)) const right = Chunk(Chunk(6, 7), Chunk(8, 9), Chunk(10)) const program = Effect.struct({ chunkResult: Effect.succeed(left.flatten().zip(right.flatten())), streamResult: Stream.fromChunks(...left) .zip(Stream.fromChunks(...right)) .runCollect() }) const { chunkResult, streamResult } = await program.unsafeRunPromise() assert.isTrue(streamResult == chunkResult) }) }) describe.concurrent("zipWith", () => { it("prioritizes failure", async () => { const program = Stream.never .zipWith(Stream.fail("ouch"), () => Option.none) .runCollect() .either() const result = await program.unsafeRunPromise() assert.isTrue(result == Either.left("ouch")) }) it("dies if one of the streams throws an exception", async () => { const error = Error("ouch") const program = Stream(1) .flatMap(() => Stream.succeed(() => { throw error }) ) .zipWith(Stream(1), (a, b) => a + b) .runCollect() const result = await program.unsafeRunPromiseExit() assert.isTrue(result.untraced() == Exit.die(error)) }) }) describe.concurrent("zipAll", () => { it("prioritizes failure", async () => { const program = Stream.never .zipAll(Stream.fail("ouch"), Option.none, Option.none) .runCollect() .either() const result = await program.unsafeRunPromise() assert.isTrue(result == Either.left("ouch")) }) }) describe.concurrent("zipAllWith", () => { it("simple example", async () => { const left = Chunk(Chunk(1, 2), Chunk(3, 4), Chunk(5)) const right = Chunk(Chunk(6, 7), Chunk(8, 9), Chunk(10)) const program = Stream.fromChunks(...left) .map(Option.some) .zipAll(Stream.fromChunks(...right).map(Option.some), Option.none, Option.none) .runCollect() const result = await program.unsafeRunPromise() const expected = left.flatten().zipAllWith( right.flatten(), (a, b) => Tuple(Option.some(a), Option.some(b)), (a) => Tuple(Option.some(a), Option.none), (b) => Tuple(Option.none, Option.some(b)) ) assert.isTrue(result == expected) }) }) describe.concurrent("zipWithIndex", () => { it("equivalence with Chunk.zipWithIndex", async () => { const stream = Stream.range(0, 5) const program = Effect.struct({ streamResult: stream.zipWithIndex().runCollect(), chunkResult: stream.runCollect().map((chunk) => chunk.zipWithIndex()) }) const { chunkResult, streamResult } = await program.unsafeRunPromise() assert.isTrue(streamResult == chunkResult) }) }) describe.concurrent("zipWithLatest", () => { it("succeed", async () => { const program = Effect.Do() .bind("left", () => Queue.unbounded<Chunk<number>>()) .bind("right", () => Queue.unbounded<Chunk<number>>()) .bind("out", () => Queue.bounded<Take<never, Tuple<[number, number]>>>(1)) .tap(({ left, out, right }) => Stream.fromChunkQueue(left) .zipWithLatest(Stream.fromChunkQueue(right), (a, b) => Tuple(a, b)) .runIntoQueue(out) .fork() ) .tap(({ left }) => left.offer(Chunk.single(0))) .tap(({ right }) => right.offerAll(Chunk(Chunk.single(0), Chunk.single(1)))) .bind("chunk1", ({ out }) => out.take .flatMap((take) => take.done()) .replicateEffect(2) .map((chunk) => chunk.flatten())) .tap(({ left }) => left.offerAll(Chunk(Chunk.single(1), Chunk.single(2)))) .bind("chunk2", ({ out }) => out.take .flatMap((take) => take.done()) .replicateEffect(2) .map((chunk) => chunk.flatten())) const { chunk1, chunk2 } = await program.unsafeRunPromise() assert.isTrue(chunk1 == Chunk(Tuple(0, 0), Tuple(0, 1))) assert.isTrue(chunk2 == Chunk(Tuple(1, 1), Tuple(2, 1))) }) it("handle empty pulls properly - 1", async () => { const stream0 = Stream.fromChunks( Chunk.empty<number>(), Chunk.empty<number>(), Chunk.single(2) ) const stream1 = Stream.fromChunks(Chunk.single(1), Chunk.single(1)) const program = Effect.Do() .bind("deferred", () => Deferred.make<never, number>()) .bind("latch", () => Deferred.make<never, void>()) .bind("fiber", ({ deferred, latch }) => (stream0 + Stream.fromEffect(deferred.await()) + Stream(2)) .zipWithLatest( Stream(1, 1).ensuring(latch.succeed(undefined)) + stream1, (_, n) => n ) .take(3) .runCollect() .fork()) .tap(({ latch }) => latch.await()) .tap(({ deferred }) => deferred.succeed(2)) .flatMap(({ fiber }) => fiber.join()) const result = await program.unsafeRunPromise() assert.isTrue(result == Chunk(1, 1, 1)) }) it("handle empty pulls properly - 2", async () => { const program = Stream.unfold( 0, (n) => Option.some(Tuple(n < 3 ? Chunk.empty<number>() : Chunk.single(2), n + 1)) ) .unchunks() .forever() .zipWithLatest(Stream(1).forever(), (_, n) => n) .take(3) .runCollect() const result = await program.unsafeRunPromise() assert.isTrue(result == Chunk(1, 1, 1)) }) // TODO(Mike/Max): implement after Gen it.skip("preserves partial ordering of stream elements", async () => { // val genSortedStream = for { // chunk <- Gen.chunkOf(Gen.int(1, 100)).map(_.sorted) // chunks <- splitChunks(Chunk(chunk)) // } yield ZStream.fromChunks(chunks: _*) // check(genSortedStream, genSortedStream) { (left, right) => // for { // out <- left.zipWithLatest(right)(_ + _).runCollect // } yield assert(out)(isSorted) // } }) }) describe.concurrent("zipWithNext", () => { it("should zip with next element for a single chunk", async () => { const program = Stream(1, 2, 3).zipWithNext().runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(1, Option.some(2)), Tuple(2, Option.some(3)), Tuple(3, Option.none) ) ) }) it("should work with multiple chunks", async () => { const program = Stream.fromChunks( Chunk.single(1), Chunk.single(2), Chunk.single(3) ) .zipWithNext() .runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(1, Option.some(2)), Tuple(2, Option.some(3)), Tuple(3, Option.none) ) ) }) it("should play well with empty streams", async () => { const program = Stream.empty.zipWithNext().runCollect() const result = await program.unsafeRunPromise() assert.isTrue(result.isEmpty()) }) it("should output same values as zipping with tail plus last element", async () => { const chunks = Chunk(Chunk(1, 2), Chunk(3, 4), Chunk(5, 6, 7), Chunk(8)) const stream = Stream.fromChunks(...chunks) const program = Effect.struct({ result0: stream.zipWithNext().runCollect(), result1: stream.zipAll(stream.drop(1).map(Option.some), 0, Option.none).runCollect() }) const { result0, result1 } = await program.unsafeRunPromise() assert.isTrue(result0 == result1) }) }) describe.concurrent("zipWithPrevious", () => { it("should zip with previous element for a single chunk", async () => { const program = Stream(1, 2, 3).zipWithPrevious().runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(Option.none, 1), Tuple(Option.some(1), 2), Tuple(Option.some(2), 3) ) ) }) it("should work with multiple chunks", async () => { const program = Stream.fromChunks( Chunk.single(1), Chunk.single(2), Chunk.single(3) ) .zipWithPrevious() .runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(Option.none, 1), Tuple(Option.some(1), 2), Tuple(Option.some(2), 3) ) ) }) it("should play well with empty streams", async () => { const program = Stream.empty.zipWithPrevious().runCollect() const result = await program.unsafeRunPromise() assert.isTrue(result.isEmpty()) }) it("should output same values as first element plus zipping with init", async () => { const chunks = Chunk(Chunk(1, 2), Chunk(3, 4), Chunk(5, 6, 7), Chunk(8)) const stream = Stream.fromChunks(...chunks) const program = Effect.struct({ result0: stream.zipWithPrevious().runCollect(), result1: (Stream(Option.none) + stream.map(Option.some)).zip(stream).runCollect() }) const { result0, result1 } = await program.unsafeRunPromise() assert.isTrue(result0 == result1) }) }) describe.concurrent("zipWithPreviousAndNext", () => { it("succeed", async () => { const program = Stream(1, 2, 3).zipWithPreviousAndNext().runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(Option.none, 1, Option.some(2)), Tuple(Option.some(1), 2, Option.some(3)), Tuple(Option.some(2), 3, Option.none) ) ) }) it("should output same values as zipping with both previous and next element", async () => { const chunks = Chunk(Chunk(1, 2), Chunk(3, 4), Chunk(5, 6, 7), Chunk(8)) const stream = Stream.fromChunks(...chunks) const program = Effect.struct({ result0: stream.zipWithPreviousAndNext().runCollect(), result1: (Stream(Option.none) + stream.map(Option.some)) .zipFlatten(stream) .zipFlatten(stream.drop(1).map(Option.some) + Stream(Option.none)) .runCollect() }) const { result0, result1 } = await program.unsafeRunPromise() assert.isTrue(result0 == result1) }) }) describe.concurrent("tuple", () => { it("should zip the results of an arbitrary number of streams into a Tuple", async () => { const program = Stream.tuple( Stream(1, 2, 3), Stream("a", "b", "c"), Stream(true, false, true) ).runCollect() const result = await program.unsafeRunPromise() assert.isTrue( result == Chunk( Tuple(1, "a", true), Tuple(2, "b", false), Tuple(3, "c", true) ) ) }) it("should terminate on exit of the shortest stream", async () => { const program = Stream.tuple( Stream(1, 2, 3), Stream("a", "b", "c"), Stream(true, false) ).runCollect() const result = await program.unsafeRunPromise() assert.isTrue(result == Chunk(Tuple(1, "a", true), Tuple(2, "b", false))) }) }) })
the_stack
import { Component, OnInit, Input, NgZone, ViewChild, ElementRef, OnChanges } from '@angular/core'; import * as d3 from 'd3-selection'; import * as d3Shape from 'd3-shape'; import * as d3Scale from 'd3-scale'; import * as d3Array from 'd3-array'; import * as d3Axis from 'd3-axis'; import * as d3TimeFormat from 'd3-time-format'; @Component({ selector: 'app-multiline-chart', templateUrl: './multiline-chart.component.html', styleUrls: ['./multiline-chart.component.css'], providers: [] }) export class MultilineChartComponent implements OnInit, OnChanges { @Input() graphWidth: any; @Input() graphHeight: any; @Input() xAxisValues: any; @Input() smoothEdge: any; @Input() yAxisLabel: any; @Input() axisUnit: any; @Input() dataResponse: any; @Input() verticalLines: any; @Input() idUnique: any; @Input() colorSet: any; @Input() hover: any; @Input() multipleData: any; @Input() targetType: any; @Input() yCoordinates: any; @Input() colorSetLegends: any; @Input() translateChange: any; @Input() fullArea: any; @ViewChild('widgetContainer') widgetContainer: ElementRef; private margin = {top: 15, right: 20, bottom: 30, left: 60}; public lineColors = ['#26ba9d', '#645ec5', '#289cf7']; public textMax = ['MAX', 'MIN']; // Lowest and Highest Line in the graph private lowerLine: any; private lowerLineIndex: any = 0; private higherLine: any; private higherLineIndex: any = 1; // Smaller and longer line (to help plot the area between the bottom and top lines) private smallerLine: any; private longerLine: any; private width: number; private timeLineWidth: number; private height: number; private x: any; private y: any; private svg: any; private line: d3Shape.Line<[number, number]>; private area: any; private areaFull: any; private combinedData: any = []; private data: any; private focus: any; bisectDate: any; focusContent: any; i: any; legendHover: any = []; searchAnObjectFromArray: any; tickValues: any; curveBasis: any; tickUnit: any; showdata = false; wholeData: any = {}; legendsvalue: any = []; interval: any; private graphData: any = []; public error = false; private dataLoaded = false; constructor(private ngZone: NgZone) { window.onresize = (e) => { // ngZone.run will help to run change detection this.ngZone.run(() => { this.graphWidth = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('width'), 10); }); }; } ngOnChanges() { this.updateComponent(); } updateComponent() { this.dataLoaded = true; if (this.graphWidth) { // Issue using this.margin.top, this.margin.left, this.margin.bottom and this.margin.right, values getting appended, that's why using the exacr values instead of variables.. this.width = this.graphWidth - 60 - 40; this.timeLineWidth = this.width * 0.75; this.height = this.graphHeight - 15 - 30 - 70; } this.getIssues(); } getIssues() { if (this.dataResponse) { this.wholeData = {'val': this.dataResponse}; this.interval = this.dataResponse[0].values.length; for ( let i = 0 ; i < this.dataResponse.length; i++) { this.legendsvalue.push(this.dataResponse[0].values[0].legends[i]); } this.dataLoaded = true; this.error = false; this.graphData = this.dataResponse; const idValue = this.idUnique; const uniqueId = document.getElementById(idValue); // To remove the graph content if its present before re-plotting if (d3.select(uniqueId).select('g') !== undefined) { d3.select(uniqueId).select('g').remove(); d3.select(uniqueId).append('g'); } // Plot the graph and do all associated processes try { this.initSvg(); this.initComponents(); if (this.graphData[0].values.length >= 2) { this.computeLowerAndHigherLines(); this.formatDataForArea(); } this.drawAxisAndGrid(); this.drawLine(); if (this.graphData[0].values.length >= 2 && ((this.hover === true) || (this.hover === 'true'))) { this.drawHover(); } } catch (e) { this.handleError(e); } } } handleError(error) { // To remove the graph content in case of error to make space for error message if (d3.selectAll('#' + this.idUnique).selectAll('g') !== undefined) { d3.selectAll('#' + this.idUnique).selectAll('g').remove(); d3.select('#' + this.idUnique).append('g'); } this.dataLoaded = false; // this.errorMessage = 'apiResponseError'; this.error = true; } ngOnInit() { this.updateComponent(); } private initSvg() { const idValue = this.idUnique; const uniqueId = document.getElementById(idValue); let yCoordinate; if ((this.axisUnit === 'false')) { yCoordinate = -(this.graphHeight / 7); d3.select(uniqueId).select('svg').attr('width', this.graphWidth); } else { yCoordinate = -(this.graphHeight / this.yCoordinates); d3.select(uniqueId).select('svg').attr('width', this.graphWidth - 40); } d3.select(uniqueId).select('svg').attr('height', this.graphHeight - 59); this.svg = d3.select(uniqueId) .select('svg') .append('g') .attr('transform', 'translate(' + 60 + ',' + yCoordinate + ')'); } private initComponents() { this.data = this.graphData.map((v) => v.values.map((z) => z.date ))[0]; this.x = d3Scale.scaleTime().range([0, this.width]); this.y = d3Scale.scaleLinear().range([this.height, 0]); const maxValue = d3Array.max(this.graphData, function(c) { return d3Array.max(c[`values`], function(d) { return d[`value`]; }); }); this.x.domain(d3Array.extent(this.data, (d: Date) => d )); if (this.translateChange === true) { if (maxValue > 10) { this.y.domain([ 0, 100 ]); } else { this.y.domain([ 0, d3Array.max(this.graphData, function(c) { return d3Array.max(c[`values`], function(d) { return d[`value`] * 1.3; }); }) ]); } } else { this.y.domain([ 0, d3Array.max(this.graphData, function(c) { return d3Array.max(c[`values`], function(d) { return d[`value`] * 1.3; }); }) ]); } this.svg.append('defs').append('clipPath') .attr('id', 'clip') .append('rect') .attr('width', 0) .attr('height', this.height); this.focus = this.svg.append('g') .attr('class', 'focus') .attr('transform', 'translate(0,' + ( 2 * this.margin.top + 40) + ')'); } private computeLowerAndHigherLines() { // Computing the Lowest / Highest line and their indices respectively this.lowerLine = this.graphData[0]; for ( let i = 0; i < this.graphData.length; i++) { if (this.graphData[i][`values`].length < this.lowerLineIndex) { this.lowerLineIndex = i; } else { if (this.graphData[i][`values`].length > this.higherLineIndex) { this.higherLineIndex = i; } } } this.lowerLine = this.graphData[this.lowerLineIndex]; this.higherLine = this.graphData[this.higherLineIndex]; if ((this.lowerLine !== undefined) && (this.higherLine !== undefined)) { if (this.lowerLine[`values`].length > this.higherLine[`values`].length) { this.smallerLine = this.higherLine; this.longerLine = this.lowerLine; } else { this.smallerLine = this.lowerLine; this.longerLine = this.higherLine; } } } private formatDataForArea() { // Merging the data of top and bottom lines to supply to plot shaded area // between top and bottom graph lines this.combinedData = []; if (this.smallerLine !== undefined) { for ( let i = 0; i < this.smallerLine[`values`].length; i++) { const lowerX = new Date(this.smallerLine[`values`][i].date); let lowerY = 0; let higherX = 0; let higherY = 0; // Forming mm/dd/yyyy of both higher and lower line data points as we cannot directly compare both, // as time may change in the data point for any given day const smallerLineDate = new Date(this.smallerLine[`values`][i].date); const smallerLineFormattedDate = smallerLineDate.getUTCMonth() + '/' + smallerLineDate.getUTCDate() + '/' + smallerLineDate.getUTCFullYear(); for ( let j = 0; j < this.longerLine[`values`].length; j++) { const longerLineDate = new Date(this.longerLine[`values`][j].date); const longerLineFormattedDate = longerLineDate.getUTCMonth() + '/' + longerLineDate.getUTCDate() + '/' + longerLineDate.getUTCFullYear(); if (longerLineFormattedDate === smallerLineFormattedDate) { higherX = this.longerLine[`values`][j].date; this.longerLine[`values`][j].value === 0 ? higherY = 1 : higherY = this.longerLine[`values`][j].value; this.smallerLine[`values`][i].value === 0 ? lowerY = 1 : lowerY = this.smallerLine[`values`][i].value; const obj = { 'x0': higherX, 'x1': lowerX, 'y0': higherY, 'y1': lowerY }; this.combinedData.push(obj); break; } } } } } private drawAxisAndGrid() { if ((this.xAxisValues === true) || (this.xAxisValues === 'true')) { this.tickValues = '%b %e'; } else if ((this.xAxisValues === false) || (this.xAxisValues === 'false')) { this.tickValues = ''; } if (this.translateChange === true) { this.tickValues = '%m/%e'; } let ticksNumber; if (this.interval < 4) { ticksNumber = 2; } else if ((this.interval >= 4 ) && (this.interval < 8)) { ticksNumber = 4; } else { ticksNumber = 6; } // Main Graph x-axis this.focus.append('g') .attr('class', 'axis axis--x') .attr('transform', 'translate(0,' + this.height + ')') .call(d3Axis.axisBottom(this.x) .ticks(ticksNumber) .tickSizeInner(10) .tickSizeOuter(0) .tickFormat(d3TimeFormat.timeFormat(this.tickValues)) ); if ((this.verticalLines === true) || (this.verticalLines === 'true')) { // Vertical Grid Lines this.svg.append('g') .attr('class', 'grid vertical') .attr('transform', 'translate(0,' + (2 * this.margin.top + this.height + 40) + ')') .call(d3Axis.axisBottom(this.x) .ticks(7) .tickSize(-this.height) .tickFormat(d => '') ); } // Horizontal Grid Lines this.svg.append('g') .attr('class', 'grid horizontal multiline') .attr('transform', 'translate(0,' + (2 * this.margin.top + 40) + ')') .call(d3Axis.axisLeft(this.y) .ticks(3) .tickSize(-this.width) .tickFormat(d => '') ); // Main Graph y-axis and associated Label if (this.axisUnit === '%') { this.focus.append('g') .attr('class', 'axis axis--y') .attr('stroke-width', '0') .attr('transform', 'translate(0,' + 0 + ')') .attr('stroke', '#fff') .call(d3Axis.axisLeft(this.y).ticks(3).tickFormat(d => d + '%')); this.svg.append('text') .attr('class', 'axis-title') .attr('transform', 'rotate(-90)') .attr('y', -47) .attr('x', -100) .attr('dy', '.71em') .attr('stroke-width', '0') .attr('fill', '#2c2e3d') .attr('stroke', '#2c2e3d') .style('text-anchor', 'end') .text(this.yAxisLabel); } else if (this.axisUnit === 'false') { this.focus.append('g') .attr('class', 'axis axis--y') .attr('stroke-width', '0') .attr('stroke', '#fff') .call(d3Axis.axisLeft(this.y).ticks(3).tickFormat(d => this.abbreviateNumber(d, 'top'))); if (this.translateChange === true) { this.svg.append('text') .attr('class', 'axis-title') .attr('transform', 'rotate(-90)') .attr('y', -50) .attr('x', -100) .attr('dy', '.71em') .attr('stroke-width', '0') .attr('fill', '#2c2e3d') .attr('stroke', '#2c2e3d') .style('text-anchor', 'end') .text(this.yAxisLabel); } else { this.svg.append('text') .attr('class', 'axis-title') .attr('transform', 'rotate(-90)') .attr('y', -50) .attr('x', -160) .attr('dy', '.71em') .attr('stroke-width', '0') .attr('fill', '#2c2e3d') .attr('stroke', '#2c2e3d') .style('text-anchor', 'end') .text(this.yAxisLabel); } } else { this.focus.append('g') .attr('class', 'axis axis--y') .attr('stroke-width', '0') .attr('transform', 'translate(0,' + 0 + ')') .attr('stroke', '#fff') .call(d3Axis.axisLeft(this.y).ticks(3).tickFormat(d => this.abbreviateNumber(d, 'bottom'))); this.svg.append('text') .attr('class', 'axis-title') .attr('transform', 'rotate(-90)') .attr('y', -57) .attr('x', -90) .attr('dy', '.71em') .attr('stroke-width', '0') .attr('fill', '#2c2e3d') .attr('stroke', '#2c2e3d') .style('text-anchor', 'end') .text(this.yAxisLabel); } } abbreviateNumber(number, value) { if (value === 'top') { if (number < '99') { return number; } else { number = parseInt(number, 10); number = number > 1000000 ? (number / 1000000) + 'M' : (number > 1000 ? (number / 1000) + 'K' : number); return number; } } else { if ( number < '100' ) { number = number + this.axisUnit; return number; } else { number = parseInt(number, 10); number = number > 1000000 ? (number / 1000000) + this.axisUnit : (number >= 1000 ? (number / 1000) + this.axisUnit : (number >= 100 ? (number / 1000) + this.axisUnit : number)); return number; } } } private drawLine() { if ((this.smoothEdge === true) || (this.smoothEdge === 'true')) { this.line = d3Shape.line() .x( (d: any) => this.x(d.date) ) .y( (d: any) => this.y(d.value) ) .curve(d3Shape.curveMonotoneX); } else if ((this.smoothEdge === false) || (this.smoothEdge === 'false')) { this.line = d3Shape.line() .x( (d: any) => this.x(d.date) ) .y( (d: any) => this.y(d.value) ); } // Line Graphs for ( let i = 0; i < this.graphData.length; i++) { this.focus.append('path') .datum(this.graphData[i].values) .attr('clip-path', 'url(#clip)') .transition() .duration(2000) .attr('class', 'line line' + `${i + 1}`) .attr('fill', 'none') .attr('stroke-width', '1.5px') .attr('stroke', this.colorSet[i]) .attr('d', this.line); } this.area = d3Shape.area() .x0((d: any) => this.x(d.x0)) .x1((d: any) => this.x(d.x1)) .y0( (d: any) => this.y(d.y1)) .y1( (d: any) => this.y(d.y0)) .curve(d3Shape.curveMonotoneX); this.areaFull = d3Shape.area() .x((d: any) => this.x(d.x0)) .y0(this.height) .y1((d: any) => this.y(d.y1)) .curve(d3Shape.curveLinear); if ((this.multipleData === true) || (this.multipleData === 'true')) { // Draw area between the top and bottom lines this.focus.append('path') .datum(this.combinedData) .attr('class', 'area') .attr('fill', '#ccc') .attr('stroke-width', '0.5') .attr('stroke', '#2c2e3d') .attr('d', this.area); } if ((this.fullArea === true) || (this.fullArea === 'true')) { // Draw area between the top line and x-axis this.focus.append('path') .datum(this.combinedData) .attr('class', 'area') .attr('fill', '#ccc') .attr('stroke-width', '0.5') .attr('stroke', '#2c2e3d') .attr('d', this.areaFull); } d3.selectAll('.ticks'); this.svg.select('#clip rect') .transition() .duration(2000) .attr('width', this.width); } private drawHover() { this.legendHover = this.dataResponse.map(function(eachLine){ return eachLine.value; }); this.searchAnObjectFromArray = function( key, value, array ) { const obj = array.filter( function( objs ) { return objs[ key ] === value; } )[ 0 ]; return obj; }; this.margin.left = this.margin.left + 20; this.focus = this.svg.append('g') .attr('class', 'focus') .style('display', 'none') .attr('transform', 'translate(0,' + ( 2 * this.margin.top + 40) + ')'); this.focus.append('line') .attr('class', 'x') .style('stroke', '#bbb') .style('stroke-width', '2px') .style('opacity', 1) .attr('y1', 0) .attr('y2', this.height); this.focus.append('text') .attr('class', 'dateData') .attr('x', 9) .attr('dy', '.35em'); this.focus.append('text') .attr('class', 'yearData') .attr('x', 9) .attr('dy', '1.5em'); for ( let i = 0; i < this.dataResponse.length; i++ ) { if (this.colorSetLegends === 'true') { this.focus.append('rect') .attr('class', 'rectData' + i) .attr('fill', this.colorSet[this.dataResponse.length - 1 - i]) .attr('height', '1.5rem') .attr('width', '3.8rem') .style('stroke', '#fff') .attr('rx', 4) .attr('ry', 4) .attr('x', -93) .attr('y', -7); } else { this.focus.append('rect') .attr('class', 'rectData' + i) .attr('fill', this.colorSet[this.dataResponse.length - 1 - i]) .attr('height', '1.5rem') .attr('width', '2.7rem') .style('stroke', '#fff') .attr('rx', 4) .attr('ry', 4) .attr('x', -93) .attr('y', -7); } this.focus.append('text') .attr('class', 'valueData' + i) .attr('x', 9) .attr('dy', '.35em'); this.focus.append('text') .attr('class', 'rectText' + i ) .style('stroke', '#fff') .style('font-size', '10px') .attr('x', 9) .attr('dy', '.35em'); this.focus.append('circle') .attr('class', 'c' + i ) .style('stroke', this.colorSet[this.dataResponse.length - 1 - i ]) .style('stroke-width', '2px') .attr('r', 4.5); } this.svg.append('rect') .attr('transform', 'translate(' + 0 + ',' + (60) + ')') .attr('class', 'overlay') .attr('width', this.width) .attr('height', this.height) .on('mouseover', () => this.focus.style('display', null)) .on('mouseout', () => this.focus.style('display', 'none')) .on('mousemove', mousemove); const self = this; function mousemove() { const mousePosition = d3.mouse(this)[0]; const formatDate = d3TimeFormat.timeFormat('%b %d'); const formatYear = d3TimeFormat.timeFormat('%Y'); const label = self.x.invert(d3.mouse(this)[0]); const dobj = {}; dobj[`label`] = label; const getIssuesForHoverDate = self.combinedData.filter(function (issue) { const issueDate = issue.x0.getDate() + '-' + issue.x0.getMonth() + '-' + issue.x0.getFullYear(); const labelDate = dobj[`label`].getDate() + '-' + dobj[`label`].getMonth() + '-' + dobj[`label`].getFullYear(); return (issueDate === labelDate); }); self.legendHover.map(function (legend) { const searchedObj = self.searchAnObjectFromArray('key', legend, getIssuesForHoverDate); for (let j = 0; j < self.dataResponse.length; j++) { if (searchedObj) { dobj['value' + j] = searchedObj[`y` + j]; } else { dobj['value' + j] = 'NO DATA'; } } }); self.focus.select('.x') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('y2', self.height); for (let k = 0; k < self.dataResponse.length; k++) { if (dobj[`value` + k] === 'NO DATA') { self.focus.select('.c' + k) .attr('r', 0); } else { self.focus.select('.c' + k) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + self.y(dobj[`value` + k]) + ')') .attr('r', 4.5) .attr('y2', self.height); } } let rightSide; if ((this.axisUnit === 'false')) { if (self.graphWidth < 770) { rightSide = 610; } else if (self.graphWidth >= 770) { rightSide = 1030; } } else { if (self.graphWidth < 498) { rightSide = 175; } else if (self.graphWidth >= 498) { rightSide = 279; } } if (mousePosition < 55) { self.dataResponse.forEach((eachline) => { self.focus.select('.dateData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatDate(dobj[`label`])).toUpperCase()) .attr('dx', '.35em') .attr('dy', '.35em'); }); self.dataResponse.forEach((eachline) => { self.focus.select('.yearData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatYear(dobj[`label`])).toUpperCase()) .attr('dx', '.35em') .attr('dy', '1.5em'); }); for (let z = 0; z < self.dataResponse.length; z++) { self.dataResponse.forEach((eachline) => { self.focus.select('.valueData' + z) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(dobj['value' + z]) .attr('dx', '5.5em') .attr('dy', .35 + (z * 3) + 'em'); }); if (self.colorSetLegends === 'true') { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + z) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[self.dataResponse.length - 1 - z]) .attr('dx', '6.7em') .attr('dy', 2.2 + (z * 3.5) + 'em'); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + z) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[z]) .attr('dx', '6.7em') .attr('dy', 2 + (z * 3.5) + 'em'); }); } self.dataResponse.forEach((eachline) => { self.focus.select('.rectData' + z) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('x', '70') .attr('y', 10 + (z * 32)); }); } } else if (mousePosition > rightSide) { self.dataResponse.forEach((eachline) => { self.focus.select('.dateData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatDate(dobj[`label`])).toUpperCase()) .attr('dx', '-12em') .attr('dy', '.5em'); }); self.dataResponse.forEach((eachline) => { self.focus.select('.yearData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatYear(dobj[`label`])).toUpperCase()) .attr('dx', '-12em') .attr('dy', '1.8em'); }); for (let i = 0; i < self.dataResponse.length; i++) { if (dobj[`value` + i] === 'NO DATA') { self.dataResponse.forEach((eachline) => { self.focus.select('.valueData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(dobj['value' + i]) .attr('dx', '-5.5em') .attr('dy', .35 + (i * 2.7) + 'em'); }); if (self.colorSetLegends === 'true') { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[self.dataResponse.length - 1 - i]) .attr('dx', '-9.7em') .attr('dy', 0.5 + (i * 3.5) + 'em'); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[i]) .attr('dx', '-9.7em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } self.dataResponse.forEach((eachline) => { self.focus.select('.rectData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('x', '-93') .attr('y', -7 + (i * 34)); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.valueData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(dobj['value' + i]) .attr('dx', '-6.8em') .attr('dy', 2 + (i * 2.7) + 'em'); }); if (self.colorSetLegends === 'true') { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[self.dataResponse.length - 1 - i]) .attr('dx', '-7.6em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[i]) .attr('dx', '-7.6em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } self.dataResponse.forEach((eachline) => { self.focus.select('.rectData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('x', '-73') .attr('y', -7 + (i * 34)); }); } } } else { self.dataResponse.forEach((eachline) => { self.focus.select('.dateData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatDate(dobj[`label`])).toUpperCase()) .attr('dx', '.35em') .attr('dy', '.35em'); }); self.dataResponse.forEach((eachline) => { self.focus.select('.yearData') .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text((formatYear(dobj[`label`])).toUpperCase()) .attr('dx', '.35em') .attr('dy', '1.5em'); }); for (let i = 0; i < self.dataResponse.length; i++) { if (dobj[`value` + i] === 'NO DATA') { self.dataResponse.forEach((eachline) => { self.focus.select('.valueData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(dobj['value' + i]) .attr('dx', '-5.5em') .attr('dy', .35 + (i * 2.7) + 'em'); }); if (self.colorSetLegends === 'true') { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[self.dataResponse.length - 1 - i]) .attr('dx', '-9.7em') .attr('dy', 0.5 + (i * 3.5) + 'em'); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[i]) .attr('dx', '-9.7em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } self.dataResponse.forEach((eachline) => { self.focus.select('.rectData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('x', '-93') .attr('y', -7 + (i * 34)); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.valueData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(dobj['value' + i]) .attr('dx', '-6.8em') .attr('dy', 2 + (i * 2.7) + 'em'); }); if (self.colorSetLegends === 'true') { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[self.dataResponse.length - 1 - i]) .attr('dx', '-7.6em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } else { self.dataResponse.forEach((eachline) => { self.focus.select('.rectText' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .text(self.legendsvalue[i]) .attr('dx', '-7.6em') .attr('dy', 0.6 + (i * 3.5) + 'em'); }); } self.dataResponse.forEach((eachline) => { self.focus.select('.rectData' + i) .attr('transform', 'translate(' + self.x(dobj[`label`]) + ',' + 0 + ')') .attr('x', '-73') .attr('y', -7 + (i * 34)); }); } } } } } }
the_stack
import * as process from 'process'; import * as os from 'os'; import * as path from 'path'; import * as util from 'util'; import * as fs from 'fs-extra'; import { fs as fscore } from '@salesforce/core'; import * as mime from 'mime'; import * as AdmZip from 'adm-zip'; import * as BBPromise from 'bluebird'; import { SfdxError } from '@salesforce/core'; import srcDevUtil = require('../../core/srcDevUtil'); import { XmlMetadataDocument } from '../xmlMetadataDocument'; import { MetadataType } from '../metadataType'; import * as PathUtil from '../sourcePathUtil'; import { checkForXmlParseError } from '../sourceUtil'; const mimeTypeExtensions = require('mime/types.json'); const fallBackMimeTypeExtensions = require('../mimeTypes'); /** * Encapsulates logic for handling of static resources. * * Static resources differ in the following ways from default mdapi expectations: * 1. The file name has a normal extension reflecting the mime type (zip, jar, jpeg) rather than "resource" * 2. A zip or jar archive can be exploded into a directory, and will be by default on pull. Only if an * archive file with the resource full name exists in the resources directory will it remain zipped. * * Note that when an archive is expanded on pull no attempt is made to avoid redundant updates of unmodified files * (as would happen in some other metadata decompositions). */ export class StaticResource { private metadataPath: string; private metadataType; private usingGAWorkspace: boolean; private resourcesDir: string; private fullName: string; private mimeType: string; private fileExtensions: string[]; private multiVersionHackUntilWorkspaceVersionsAreSupported: boolean; constructor( metadataPath: string, metadataType: MetadataType, workspaceVersion, retrievedMetadataFilePath?: string, unsupportedMimeTypes?: string[] ) { this.metadataPath = metadataPath; this.metadataType = metadataType; this.usingGAWorkspace = !util.isNullOrUndefined(workspaceVersion); // TODO - once we know what the version looks like this.resourcesDir = path.dirname(metadataPath); this.fullName = this.metadataType.getFullNameFromFilePath(metadataPath); const effectiveMetadataFilePath = util.isNullOrUndefined(retrievedMetadataFilePath) ? metadataPath : retrievedMetadataFilePath; this.mimeType = StaticResource.getMimeType(effectiveMetadataFilePath); this.fileExtensions = this.getMimeTypeExtension(unsupportedMimeTypes); this.multiVersionHackUntilWorkspaceVersionsAreSupported = true; // sigh } getResource(): BBPromise<string> { if (this.multiVersionHackUntilWorkspaceVersionsAreSupported) { if (this.isExplodedArchive()) { return StaticResource.zipDir(this.getExplodedFolderPath()); } else if (srcDevUtil.pathExistsSync(this.getLegacyFilePath())) { return BBPromise.resolve(this.getLegacyFilePath()); } else if (srcDevUtil.pathExistsSync(this.getSingleFilePathPreferExisting())) { return BBPromise.resolve(this.getSingleFilePathPreferExisting()); } else { return BBPromise.resolve(PathUtil.getContentPathWithNonStdExtFromMetadataPath(this.metadataPath)); } } else { if (this.usingGAWorkspace) { if (this.isExplodedArchive()) { return StaticResource.zipDir(this.getExplodedFolderPath()); } else { return BBPromise.resolve(this.getSingleFilePathPreferExisting()); } } else { return BBPromise.resolve(this.getLegacyFilePath()); } } } async saveResource( sourcePath: string, createDuplicates?: boolean, forceoverwrite = false ): Promise<[string[], string[], string[]]> { const updatedPaths = []; const duplicatePaths = []; const deletedPaths = []; if (this.multiVersionHackUntilWorkspaceVersionsAreSupported) { if (this.isExplodedArchive()) { return this.expandArchive(sourcePath, createDuplicates, forceoverwrite); } else if (srcDevUtil.pathExistsSync(this.getLegacyFilePath())) { return await this.handleLegacyPath(sourcePath, createDuplicates); } else { return await this.handleResource(sourcePath, createDuplicates, forceoverwrite); } } else { if (this.usingGAWorkspace) { if (this.isExplodedArchive()) { return this.expandArchive(sourcePath, createDuplicates, forceoverwrite); } else { await fs.copyFile(sourcePath, this.getSingleFilePathPreferExisting()); updatedPaths.push(this.getSingleFilePathPreferExisting()); } } else { return await this.handleResource(sourcePath, createDuplicates, forceoverwrite); } } return [updatedPaths, duplicatePaths, deletedPaths]; } isExplodedArchive(): boolean { if (this.multiVersionHackUntilWorkspaceVersionsAreSupported) { const singleFileArchiveExists = srcDevUtil.pathExistsSync(this.getSingleFilePath()) || srcDevUtil.pathExistsSync(this.getLegacyFilePath()); return this.isArchiveMimeType() && !singleFileArchiveExists; } else { const singleFileArchiveExists = srcDevUtil.pathExistsSync(this.getSingleFilePath()); return this.isArchiveMimeType() && !singleFileArchiveExists; } } getContentPaths(): string[] { let contentPaths: string[] = []; if (this.multiVersionHackUntilWorkspaceVersionsAreSupported) { if (this.isExplodedArchive()) { if (srcDevUtil.pathExistsSync(this.getExplodedFolderPath())) { contentPaths = contentPaths.concat(this.getFiles(this.getExplodedFolderPath())); } } else if (srcDevUtil.pathExistsSync(this.getLegacyFilePath())) { contentPaths.push(this.getLegacyFilePath()); } else { const contentPath = this.getSingleFilePathPreferExisting(); if (srcDevUtil.pathExistsSync(contentPath)) { contentPaths.push(contentPath); } } } else { if (this.usingGAWorkspace) { if (this.isExplodedArchive()) { if (srcDevUtil.pathExistsSync(this.getExplodedFolderPath())) { contentPaths = contentPaths.concat(this.getFiles(this.getExplodedFolderPath())); } } else { const contentPath = this.getSingleFilePathPreferExisting(); if (srcDevUtil.pathExistsSync(contentPath)) { contentPaths.push(contentPath); } } } else if (srcDevUtil.pathExistsSync(this.getLegacyFilePath())) { contentPaths.push(this.getLegacyFilePath()); } } return contentPaths; } static zipDir(dir: string): BBPromise<string> { const zipFile = path.join(os.tmpdir() || '.', `sdx_srzip_${process.hrtime()[0]}${process.hrtime()[1]}.zip`); return srcDevUtil.zipDir(dir, zipFile, { level: 9 }); } /** * Get the mime type from the npm mime library file. * If the mime type is not supported there, use our backup manually added mime types file * If the mime type is not supported there, throw an error * * @param unsupportedMimeTypes - an array of unsupported mime types for the purpose of logging * @returns {string[]} the mime type extension(s) */ private getMimeTypeExtension(unsupportedMimeTypes?: string[]): string[] { let ext = mimeTypeExtensions[this.mimeType]; if (!ext || ext.length === 0) { ext = fallBackMimeTypeExtensions[this.mimeType]; } if (ext) { return ext; } if (unsupportedMimeTypes) { unsupportedMimeTypes.push(this.mimeType); } return [this.metadataType.getExt()]; } private getFiles(file): string[] { let found: string[] = []; found.push(file); const stat = fs.statSync(file); if (stat.isDirectory()) { const nestedFiles = fs.readdirSync(file); nestedFiles.forEach((nestedFile) => { const nestedPath = path.join(file, nestedFile); const nestedStat = fs.statSync(nestedPath); if (nestedStat.isDirectory()) { found = found.concat(this.getFiles(nestedPath)); } else { found.push(nestedPath); } }); } return found; } private static getMimeType(metadataPath: string): string { if (srcDevUtil.pathExistsSync(metadataPath)) { const doc = new XmlMetadataDocument('StaticResource'); try { doc.setRepresentation(fs.readFileSync(metadataPath, 'utf8')); } catch (e) { throw checkForXmlParseError(metadataPath, e); } const nodeTypeElement = 1; let child = doc.data.documentElement.firstChild; while (child !== null) { if (child.nodeType === nodeTypeElement && child.nodeName === 'contentType') { return child.firstChild.nodeValue; } child = child.nextSibling; } } return mime.lookup(''); // this defaults to bin -- is this correct? } private getLegacyFilePath(): string { return path.join(this.resourcesDir, `${this.fullName}.${this.metadataType.getExt()}`); } private getSingleFilePath(ext?: string): string { let extension = ext; if (!ext) { const mimeLib = mime.extension(this.mimeType); extension = mimeLib ? mimeLib : this.getMimeTypeExtension(); } return path.join(this.resourcesDir, `${this.fullName}.${extension}`); } private getSingleFilePathPreferExisting(): string { // eslint-disable-next-line @typescript-eslint/no-shadow const ext = this.fileExtensions.find((ext) => srcDevUtil.pathExistsSync(this.getSingleFilePath(ext))); return this.getSingleFilePath(ext); } private getExplodedFolderPath(): string { return path.join(this.resourcesDir, this.fullName); } private isArchiveMimeType(): boolean { const fallBackExtension = fallBackMimeTypeExtensions[this.mimeType]; let isZip = false; if (fallBackExtension) { isZip = fallBackExtension[0] === 'zip'; } return this.mimeType === mime.lookup('zip') || this.mimeType === mime.lookup('jar') || isZip; } private async expandArchive( sourcePath: string, createDuplicates: boolean, forceoverwrite = false ): Promise<[string[], string[], string[]]> { const updatedPaths = []; const duplicatePaths = []; // expand the archive into a temp directory const tempDir = path.join(os.tmpdir(), `sfdx_staticresource_${this.fullName}_${Date.now()}`); srcDevUtil.ensureDirectoryExistsSync(tempDir); try { new AdmZip(sourcePath).extractAllTo(tempDir); } catch (error) { throw SfdxError.create('salesforce-alm', 'mdapi_convert', 'AdmZipError', [sourcePath, this.mimeType, error]) .message; } // compare exploded directories if needed const isUpdatingExistingStaticResource = srcDevUtil.pathExistsSync(this.getExplodedFolderPath()); if (isUpdatingExistingStaticResource && createDuplicates) { await this.compareExplodedDirs(tempDir, duplicatePaths, updatedPaths, forceoverwrite); } const existingPaths = new Set<string>(); if (isUpdatingExistingStaticResource) { // eslint-disable-next-line @typescript-eslint/require-await await fscore.actOn(this.getExplodedFolderPath(), async (file) => { existingPaths.add(file); }); } // now copy all the files in the temp dir into the workspace srcDevUtil.deleteDirIfExistsSync(this.getExplodedFolderPath()); fs.copySync(tempDir, this.getExplodedFolderPath()); // override new file with existing // if this is a new static resource then simply report all files as changed if (!isUpdatingExistingStaticResource || forceoverwrite) { // eslint-disable-next-line @typescript-eslint/require-await await fscore.actOn(tempDir, async (file) => { updatedPaths.push(file.replace(tempDir, this.getExplodedFolderPath())); }); } else { // if this is an existing static resource then we want to figure which files are new // and add those to updatedPaths // eslint-disable-next-line @typescript-eslint/require-await await fscore.actOn(tempDir, async (file) => { const filePath = file.replace(tempDir, this.getExplodedFolderPath()); if (!existingPaths.has(filePath)) { updatedPaths.push(filePath); } existingPaths.delete(filePath); }); } // We determine the deleted paths by removing files from existingPaths as they're found in the tempDir // whatever remains we assume needs to be deleted const deletedPaths = existingPaths.size ? [...existingPaths] : []; return [updatedPaths, duplicatePaths, deletedPaths]; } // if an exploded directory structure exists in the workspace then loop through each new file and see if a file // with same name exists in the workspace. If that file exists then compare the hashes. If hashes are different // then create a duplicate file. private async compareExplodedDirs( tempDir: string, duplicatePaths: string[], updatedPaths: string[], forceoverwrite = false ) { await fscore.actOn(tempDir, async (file) => { if (!fs.statSync(file).isDirectory()) { const relativePath = file.substring(file.indexOf(tempDir) + tempDir.length); const workspaceFile = path.join(this.getExplodedFolderPath(), relativePath); if (srcDevUtil.pathExistsSync(workspaceFile)) { const equalCheck = await fscore.areFilesEqual(workspaceFile, file); if (!equalCheck) { // file with same name exists and contents are different await fs.copyFile(file, file + '.dup'); // copy newFile to .dup duplicatePaths.push(workspaceFile + '.dup'); // keep track of dups await fs.copyFile(workspaceFile, file); } else if (forceoverwrite) { // if file exists and contents are the same then don't report it as updated unless we're force overwriting updatedPaths.push(workspaceFile); // override new file with existing } } else { updatedPaths.push(workspaceFile); // this is a net new file } } }); } private async handleResource( sourcePath: string, createDuplicates: boolean, forceoverwrite = false ): Promise<[string[], string[], string[]]> { const updatedPaths = []; const duplicatePaths = []; const deletedPaths = []; const destFile = this.getSingleFilePathPreferExisting(); if (forceoverwrite || !(await fscore.fileExists(destFile))) { await fs.copyFile(sourcePath, destFile); updatedPaths.push(this.getSingleFilePathPreferExisting()); } else { const compareFiles = await fscore.areFilesEqual(sourcePath, destFile); if (!compareFiles && createDuplicates) { await fs.copyFile(sourcePath, `${this.getSingleFilePathPreferExisting()}.dup`); duplicatePaths.push(`${destFile}.dup`); } else if (!compareFiles && !createDuplicates) { // replace existing file with remote await fs.copyFile(sourcePath, destFile); duplicatePaths.push(this.getSingleFilePathPreferExisting()); } } return [updatedPaths, duplicatePaths, deletedPaths]; } private async handleLegacyPath( sourcePath: string, createDuplicates: boolean ): Promise<[string[], string[], string[]]> { const updatedPaths = []; const duplicatePaths = []; const deletedPaths = []; const legacyFilePath = this.getLegacyFilePath(); if (createDuplicates) { if (!(await fscore.areFilesEqual(sourcePath, legacyFilePath))) { await fs.copyFile(sourcePath, legacyFilePath + '.dup'); duplicatePaths.push(legacyFilePath + '.dup'); } // if contents are equal and we are doing a mdapi:convert (createDuplicates=true) then ignore this file } else { await fs.copyFile(sourcePath, legacyFilePath); updatedPaths.push(legacyFilePath); } return [updatedPaths, duplicatePaths, deletedPaths]; } }
the_stack
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { BehaviorSubject, combineLatest as observableCombineLatest, Observable, of as observableOf, Subscription } from 'rxjs'; import { catchError, map, switchMap, take, tap } from 'rxjs/operators'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model'; import { RemoteData } from '../../core/data/remote-data'; import { RequestService } from '../../core/data/request.service'; import { EPersonDataService } from '../../core/eperson/eperson-data.service'; import { GroupDataService } from '../../core/eperson/group-data.service'; import { EPerson } from '../../core/eperson/models/eperson.model'; import { GroupDtoModel } from '../../core/eperson/models/group-dto.model'; import { Group } from '../../core/eperson/models/group.model'; import { RouteService } from '../../core/services/route.service'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { getAllSucceededRemoteData, getFirstCompletedRemoteData, getFirstSucceededRemoteData, getRemoteDataPayload } from '../../core/shared/operators'; import { PageInfo } from '../../core/shared/page-info.model'; import { hasValue } from '../../shared/empty.util'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { NoContent } from '../../core/shared/NoContent.model'; import { PaginationService } from '../../core/pagination/pagination.service'; import { followLink } from '../../shared/utils/follow-link-config.model'; @Component({ selector: 'ds-groups-registry', templateUrl: './groups-registry.component.html', }) /** * A component used for managing all existing groups within the repository. * The admin can create, edit or delete groups here. */ export class GroupsRegistryComponent implements OnInit, OnDestroy { messagePrefix = 'admin.access-control.groups.'; /** * Pagination config used to display the list of groups */ config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { id: 'gl', pageSize: 5, currentPage: 1 }); /** * A BehaviorSubject with the list of GroupDtoModel objects made from the Groups in the repository or * as the result of the search */ groupsDto$: BehaviorSubject<PaginatedList<GroupDtoModel>> = new BehaviorSubject<PaginatedList<GroupDtoModel>>({} as any); deletedGroupsIds: string[] = []; /** * An observable for the pageInfo, needed to pass to the pagination component */ pageInfoState$: BehaviorSubject<PageInfo> = new BehaviorSubject<PageInfo>(undefined); // The search form searchForm; /** * A boolean representing if a search is pending */ loading$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); // Current search in groups registry currentSearchQuery: string; /** * The subscription for the search method */ searchSub: Subscription; paginationSub: Subscription; /** * List of subscriptions */ subs: Subscription[] = []; constructor(public groupService: GroupDataService, private ePersonDataService: EPersonDataService, private dSpaceObjectDataService: DSpaceObjectDataService, private translateService: TranslateService, private notificationsService: NotificationsService, private formBuilder: FormBuilder, protected routeService: RouteService, private router: Router, private authorizationService: AuthorizationDataService, private paginationService: PaginationService, public requestService: RequestService) { this.currentSearchQuery = ''; this.searchForm = this.formBuilder.group(({ query: this.currentSearchQuery, })); } ngOnInit() { this.search({ query: this.currentSearchQuery }); } /** * Search in the groups (searches by group name and by uuid exact match) * @param data Contains query param */ search(data: any) { if (hasValue(this.searchSub)) { this.searchSub.unsubscribe(); this.subs = this.subs.filter((sub: Subscription) => sub !== this.searchSub); } this.searchSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( tap(() => this.loading$.next(true)), switchMap((paginationOptions) => { const query: string = data.query; if (query != null && this.currentSearchQuery !== query) { this.currentSearchQuery = query; this.paginationService.updateRouteWithUrl(this.config.id, [], {page: 1}); } return this.groupService.searchGroups(this.currentSearchQuery.trim(), { currentPage: paginationOptions.currentPage, elementsPerPage: paginationOptions.pageSize, }, true, true, followLink('object')); }), getAllSucceededRemoteData(), getRemoteDataPayload(), switchMap((groups: PaginatedList<Group>) => { if (groups.page.length === 0) { return observableOf(buildPaginatedList(groups.pageInfo, [])); } return this.authorizationService.isAuthorized(FeatureID.AdministratorOf).pipe( switchMap((isSiteAdmin: boolean) => { return observableCombineLatest(groups.page.map((group: Group) => { if (hasValue(group) && !this.deletedGroupsIds.includes(group.id)) { return observableCombineLatest([ this.authorizationService.isAuthorized(FeatureID.CanDelete, group.self), this.canManageGroup$(isSiteAdmin, group), this.hasLinkedDSO(group), this.getSubgroups(group), this.getMembers(group) ]).pipe( map(([canDelete, canManageGroup, hasLinkedDSO, subgroups, members]: [boolean, boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => { const groupDtoModel: GroupDtoModel = new GroupDtoModel(); groupDtoModel.ableToDelete = canDelete && !hasLinkedDSO; groupDtoModel.ableToEdit = canManageGroup; groupDtoModel.group = group; groupDtoModel.subgroups = subgroups.payload; groupDtoModel.epersons = members.payload; return groupDtoModel; } ) ); } })).pipe(map((dtos: GroupDtoModel[]) => { return buildPaginatedList(groups.pageInfo, dtos); })); }) ); }) ).subscribe((value: PaginatedList<GroupDtoModel>) => { this.groupsDto$.next(value); this.pageInfoState$.next(value.pageInfo); this.loading$.next(false); }); this.subs.push(this.searchSub); } canManageGroup$(isSiteAdmin: boolean, group: Group): Observable<boolean> { if (isSiteAdmin) { return observableOf(true); } else { return this.authorizationService.isAuthorized(FeatureID.CanManageGroup, group.self); } } /** * Delete Group */ deleteGroup(group: GroupDtoModel) { if (hasValue(group.group.id)) { this.groupService.delete(group.group.id).pipe(getFirstCompletedRemoteData()) .subscribe((rd: RemoteData<NoContent>) => { if (rd.hasSucceeded) { this.deletedGroupsIds = [...this.deletedGroupsIds, group.group.id]; this.notificationsService.success(this.translateService.get(this.messagePrefix + 'notification.deleted.success', { name: group.group.name })); this.reset(); } else { this.notificationsService.error( this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: group.group.name }), this.translateService.get(this.messagePrefix + 'notification.deleted.failure.content', { cause: rd.errorMessage })); } }); } } /** * This method will set everything to stale, which will cause the lists on this page to update. */ reset() { this.groupService.getBrowseEndpoint().pipe( take(1) ).subscribe((href: string) => { this.requestService.setStaleByHrefSubstring(href); }); } /** * Get the members (epersons embedded value of a group) * @param group */ getMembers(group: Group): Observable<RemoteData<PaginatedList<EPerson>>> { return this.ePersonDataService.findAllByHref(group._links.epersons.href).pipe(getFirstSucceededRemoteData()); } /** * Get the subgroups (groups embedded value of a group) * @param group */ getSubgroups(group: Group): Observable<RemoteData<PaginatedList<Group>>> { return this.groupService.findAllByHref(group._links.subgroups.href).pipe(getFirstSucceededRemoteData()); } /** * Check if group has a linked object (community or collection linked to a workflow group) * @param group */ hasLinkedDSO(group: Group): Observable<boolean> { return this.dSpaceObjectDataService.findByHref(group._links.object.href).pipe( getFirstSucceededRemoteData(), map((rd: RemoteData<DSpaceObject>) => hasValue(rd) && hasValue(rd.payload)), catchError(() => observableOf(false)), ); } /** * Reset all input-fields to be empty and search all search */ clearFormAndResetResult() { this.searchForm.patchValue({ query: '', }); this.search({ query: '' }); } /** * Unsub all subscriptions */ ngOnDestroy(): void { this.cleanupSubscribes(); this.paginationService.clearPagination(this.config.id); } cleanupSubscribes() { if (hasValue(this.paginationSub)) { this.paginationSub.unsubscribe(); } this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); this.paginationService.clearPagination(this.config.id); } }
the_stack
import { ILegendItem, IChartInstance } from './type-interface' import MonitorBaseSeries from './base-chart-option' import deepMerge from 'deepmerge' import { lineOrBarOptions } from './echart-options-config' import { getValueFormat, ValueFormatter } from '../valueFormats' export default class MonitorLineSeries extends MonitorBaseSeries implements IChartInstance { public defaultOption: any public constructor(props: any) { super(props) this.defaultOption = deepMerge(deepMerge(lineOrBarOptions, { color: this.colors, yAxis: { axisLabel: { formatter: this.handleYxisLabelFormatter } } }, { arrayMerge: this.overwriteMerge }), this.chartOption, { arrayMerge: this.overwriteMerge }) } // 设置折线图 public getOptions(data: any, otherOptions: any = {}) { const { series } = data || {} const hasSeries = series && series.length > 0 const formatterFunc = hasSeries && series[0].data && series[0].data.length ? this.handleSetFormatterFunc(series[0].data) : null const { series: newSeries, legendData } = this.getSeriesData(series) const [firstSery] = newSeries || [] const { canScale, minThreshold, maxThreshold } = this.handleSetThreholds(series) const options = { yAxis: { scale: canScale, axisLabel: { formatter: newSeries.every((item: any) => item.unit && item.unit === firstSery.unit) ? (v: any) => { const obj = getValueFormat(firstSery.unit)(v, firstSery.precision) return obj.text + (obj.suffix || '') } : this.handleYxisLabelFormatter }, max: (v: {min: number, max: number}) => Math.max(v.max, maxThreshold), min: (v: {min: number, max: number}) => Math.min(v.min, minThreshold), splitNumber: 4, minInterval: 1 }, xAxis: { axisLabel: { formatter: hasSeries && formatterFunc ? formatterFunc : '{value}' } }, legend: { show: false }, series: hasSeries ? newSeries : [] } return { options: deepMerge(deepMerge( this.defaultOption, otherOptions, { arrayMerge: this.overwriteMerge } ), options, { arrayMerge: this.overwriteMerge }), legendData } } private getSeriesData(seriess: any = []) { const legendData: ILegendItem[] = [] const seriesData: any = deepMerge([], seriess) const series = seriesData.map((item: any, index: number) => { let showSymbol = !!item?.markPoints?.every((set: any) => set?.length === 2) const hasLegend = !!item.name const legendItem: ILegendItem = { name: String(item.name), max: 0, min: '', avg: 0, total: 0, color: item.color || this.colors[index % this.colors.length], show: true } const unitFormatter = getValueFormat(item.unit || '') const precision = this.handleGetMinPrecision( item.data.filter((set: any) => typeof set[1] === 'number').map(set => set[1]) , unitFormatter, item.unit ) item.data.forEach((seriesItem: any, seriesIndex: number) => { if (seriesItem?.length && seriesItem[1]) { const pre = item.data[seriesIndex - 1] const next = item.data[seriesIndex + 1] if (typeof seriesItem[1] === 'number') { const curValue = +seriesItem[1] legendItem.max = Math.max(legendItem.max, curValue) legendItem.min = legendItem.min === '' ? curValue : Math.min(+legendItem.min, curValue) legendItem.total = (legendItem.total + curValue) } if (item?.markPoints?.some((set: any) => set[1] === seriesItem[0])) { item.data[seriesIndex] = { symbolSize: 12, value: [seriesItem[0], seriesItem[1]], itemStyle: { borderWidth: 6, enabled: true, shadowBlur: 0, opacity: 1 }, label: { show: false } } } else { const hasNoBrother = (!pre && !next) || (pre && next && pre.length && next.length && pre[1] === null && next[1] === null) if (hasNoBrother) { showSymbol = true } item.data[seriesIndex] = { symbolSize: hasNoBrother ? 4 : 1, value: [seriesItem[0], seriesItem[1]], itemStyle: { borderWidth: hasNoBrother ? 4 : 1, enabled: true, shadowBlur: 0, opacity: 1 } } } } else if (seriesItem.symbolSize) { showSymbol = true } }) legendItem.avg = +(legendItem.total / item.data.length).toFixed(2) legendItem.total = +(legendItem.total).toFixed(2) const seriesItem = { ...item, type: this.chartType, showSymbol, symbol: 'circle', z: 4, smooth: 0.2, unitFormatter, precision, lineStyle: { width: this.lineWidth || 1 } } if (item?.markTimeRange?.length) { seriesItem.markArea = this.handleSetThresholdBand(item.markTimeRange) } if (item?.thresholds?.length) { seriesItem.markLine = this.handleSetThresholdLine(item.thresholds) seriesItem.markArea = deepMerge(seriesItem.markArea, this.handleSetThresholdArea(item.thresholds)) } if (hasLegend) { Object.keys(legendItem).forEach((key) => { if (['min', 'max', 'avg', 'total'].includes(key)) { const set = unitFormatter(legendItem[key], item.unit !== 'none' && precision < 1 ? 2 : precision) legendItem[key] = set.text + (set.suffix || '') } }) legendData.push(legendItem) } return seriesItem }) return { legendData, series } } // 设置阈值线 private handleSetThresholdLine(thresholdLine: []) { return { symbol: [], label: { show: true, position: 'insideStartTop' }, lineStyle: { color: '#FD9C9C', type: 'dashed', distance: 3, width: 1 }, data: thresholdLine.map((item: any) => ({ ...item, label: { show: true, formatter(v: any) { return v.name || '' } } })) } } // 设置阈值面板 private handleSetThresholdBand(plotBands: {to: number, from: number}[]) { return { silent: true, show: true, itemStyle: { color: '#FFF5EC', borderWidth: 1, borderColor: '#FFE9D5', shadowColor: '#FFF5EC', shadowBlur: 0 }, data: plotBands.map(item => ( [{ xAxis: item.from, y: 'max' }, { xAxis: item.to || 'max', y: '0%' }] )), opacity: 0.1 } } private handleGetMinPrecision(data: number[], formattter: ValueFormatter, unit: string) { if (!data || data.length === 0) { return 0 } data.sort() const len = data.length if (data[0] === data[len - 1]) { if (unit === 'none') return 0 const setList = String(data[0]).split('.') return (!setList || setList.length < 2) ? 2 : setList[1].length } let precision = 0 let sampling = [] const middle = Math.ceil(len / 2) sampling.push(data[0]) sampling.push(data[Math.ceil((middle) / 2)]) sampling.push(data[middle]) sampling.push(data[middle + Math.floor((len - middle) / 2)]) sampling.push(data[len - 1]) sampling = Array.from(new Set(sampling.filter(n => n !== undefined))) while (precision < 5) { // eslint-disable-next-line no-loop-func const samp = sampling.reduce((pre, cur) => { pre[formattter(cur, precision).text] = 1 return pre }, {}) if (Object.keys(samp).length >= sampling.length) { return precision } precision += 1 } return precision } handleSetThreholds(series: any) { let thresholdList = series.filter((set: any) => set?.thresholds?.length).map((set: any) => set.thresholds) thresholdList = thresholdList.reduce((pre: any, cur: any, index: number) => { pre.push(...cur.map((set: any) => set.yAxis)) if (index === thresholdList.length - 1) { return Array.from(new Set(pre)) } return pre }, []) return { canScale: thresholdList.every((set: number) => set > 0), minThreshold: Math.min(...thresholdList), maxThreshold: Math.max(...thresholdList) } } private handleSetThresholdArea(thresholdLine: any[]) { const data = this.handleSetThresholdAreaData(thresholdLine) return { label: { show: false }, data } } private handleSetThresholdAreaData(thresholdLine: any[]) { const threshold = thresholdLine.filter(item => item.method && !['eq', 'neq'].includes(item.method)) const openInterval = ['gte', 'gt'] // 开区间 const closedInterval = ['lte', 'lt'] // 闭区间 const data = [] // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let index = 0; index < threshold.length; index++) { const current = threshold[index] const nextThreshold = threshold[index + 1] // 判断是否为一个闭合区间 let yAxis = undefined if (openInterval.includes(current.method) && nextThreshold && nextThreshold.condition === 'and' && closedInterval.includes(nextThreshold.method) && (nextThreshold.yAxis >= current.yAxis)) { yAxis = nextThreshold.yAxis index += 1 } else if (closedInterval.includes(current.method) && nextThreshold && nextThreshold.condition === 'and' && openInterval.includes(nextThreshold.method) && (nextThreshold.yAxis <= current.yAxis)) { yAxis = nextThreshold.yAxis index += 1 } else if (openInterval.includes(current.method)) { yAxis = 'max' } else if (closedInterval.includes(current.method)) { yAxis = current.yAxis < 0 ? current.yAxis : 0 } yAxis !== undefined && data.push([ { ...current }, { yAxis, y: yAxis === 'max' ? '0%' : '' } ]) } return data } }
the_stack
import { expect } from "chai" import map from "lodash/map" import { IToken, ITokenGrammarPath, TokenType } from "@chevrotain/types" import { NextAfterTokenWalker, nextPossibleTokensAfter, NextTerminalAfterAtLeastOneSepWalker, NextTerminalAfterAtLeastOneWalker, NextTerminalAfterManySepWalker, NextTerminalAfterManyWalker, PartialPathAndSuffixes, possiblePathsFrom } from "../../../src/parse/grammar/interpreter" import { createRegularToken, setEquality } from "../../utils/matchers" import { createToken } from "../../../src/scan/tokens_public" import { Lexer } from "../../../src/scan/lexer_public" import { augmentTokenTypes, tokenStructuredMatcher } from "../../../src/scan/tokens" import { EmbeddedActionsParser } from "../../../src/parse/parser/traits/parser_traits" import { Alternation, Alternative, Repetition, RepetitionWithSeparator, Rule, Terminal, Option, RepetitionMandatory, NonTerminal, RepetitionMandatoryWithSeparator } from "../../../src/parse/grammar/gast/gast_public" import { createDeferredTokenBuilder } from "../../utils/builders" // ugly utilities to deffer execution of productive code until the relevant tests have started // it is done in this "ugly" manner as an "quick/easy" win as part of refactoring the whole tests to achieve this. const getLSquareTok = createDeferredTokenBuilder({ name: "LSquareTok", pattern: /NA/ }) const getRSquareTok = createDeferredTokenBuilder({ name: "RSquareTok", pattern: /NA/ }) const getActionTok = createDeferredTokenBuilder({ name: "ActionTok", pattern: /NA/ }) const getIdentTok = createDeferredTokenBuilder({ name: "IdentTok", pattern: /NA/ }) const getDotTok = createDeferredTokenBuilder({ name: "DotTok", pattern: /NA/ }) const getColonTok = createDeferredTokenBuilder({ name: "ColonTok", pattern: /NA/ }) let fqnCache: Rule function buildQualifiedName(): Rule { if (fqnCache === undefined) { fqnCache = new Rule({ name: "qualifiedName", definition: [ new Terminal({ terminalType: getIdentTok() }), new Repetition({ definition: [ new Terminal({ terminalType: getDotTok() }), new Terminal({ terminalType: getIdentTok(), idx: 2 }) ] }) ] }) } return fqnCache } let paramSpecCache: Rule function getParamSpec(): Rule { if (paramSpecCache === undefined) { paramSpecCache = new Rule({ name: "paramSpec", definition: [ new Terminal({ terminalType: getIdentTok() }), new Terminal({ terminalType: getColonTok() }), new NonTerminal({ nonTerminalName: "qualifiedName", referencedRule: buildQualifiedName() }), new Option({ definition: [ new Terminal({ terminalType: getLSquareTok() }), new Terminal({ terminalType: getRSquareTok() }) ] }) ] }) } return paramSpecCache } describe("The Grammar Interpeter namespace", () => { let actionDec: Rule let SemicolonTok: TokenType let CommaTok: TokenType let LParenTok: TokenType let RParenTok: TokenType before(() => { LParenTok = createToken({ name: "LParenTok", pattern: /NA/ }) RParenTok = createToken({ name: "RParenTok", pattern: /NA/ }) SemicolonTok = createToken({ name: "SemicolonTok", pattern: /NA/ }) CommaTok = createToken({ name: "CommaTok", pattern: /NA/ }) actionDec = new Rule({ name: "actionDec", definition: [ new Terminal({ terminalType: getActionTok() }), new Terminal({ terminalType: getIdentTok() }), new Terminal({ terminalType: LParenTok }), new Option({ definition: [ new NonTerminal({ nonTerminalName: "paramSpec", referencedRule: getParamSpec() }), new Repetition({ definition: [ new Terminal({ terminalType: CommaTok }), new NonTerminal({ nonTerminalName: "paramSpec", referencedRule: getParamSpec(), idx: 2 }) ] }) ] }), new Terminal({ terminalType: RParenTok }), new Option({ definition: [ new Terminal({ terminalType: getColonTok() }), new NonTerminal({ nonTerminalName: "qualifiedName", referencedRule: buildQualifiedName() }) ], idx: 2 }), new Terminal({ terminalType: SemicolonTok }) ] }) }) describe("The NextAfterTokenWalker", () => { it("can compute the next possible token types From ActionDec in scope of ActionDec #1", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: getActionTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #2", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: getIdentTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(LParenTok) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: LParenTok, lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [getIdentTok(), RParenTok]) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #4", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: CommaTok, lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #5", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: RParenTok, lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [SemicolonTok, getColonTok()]) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #6", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: getColonTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) }) it("can compute the next possible token types From ActionDec in scope of ActionDec #7", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec"], occurrenceStack: [1], lastTok: SemicolonTok, lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(0) }) it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #1", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 1], lastTok: getIdentTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getColonTok()) }) it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #2", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 1], lastTok: getColonTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) }) it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 1], lastTok: getLSquareTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getRSquareTok()) }) it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #4", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 1], lastTok: getRSquareTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [CommaTok, RParenTok]) }) it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #1", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 2], lastTok: getIdentTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getColonTok()) }) it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #2", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 2], lastTok: getColonTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) }) it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 2], lastTok: getLSquareTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getRSquareTok()) }) it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #4", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec"], occurrenceStack: [1, 2], lastTok: getRSquareTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [CommaTok, RParenTok]) }) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #1", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec", "qualifiedName"], occurrenceStack: [1, 1, 1], lastTok: getIdentTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(4) setEquality(possibleNextTokTypes, [ getDotTok(), getLSquareTok(), CommaTok, RParenTok ]) } ) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #2", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec", "qualifiedName"], occurrenceStack: [1, 1, 1], lastTok: getDotTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) } ) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["actionDec", "paramSpec", "qualifiedName"], occurrenceStack: [1, 1, 1], lastTok: getIdentTok(), lastTokOccurrence: 2 } const possibleNextTokTypes = new NextAfterTokenWalker( actionDec, caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(4) setEquality(possibleNextTokTypes, [ getDotTok(), getLSquareTok(), CommaTok, RParenTok ]) } ) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["paramSpec", "qualifiedName"], occurrenceStack: [1, 1], lastTok: getIdentTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( getParamSpec(), caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [getDotTok(), getLSquareTok()]) } ) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["paramSpec", "qualifiedName"], occurrenceStack: [1, 1], lastTok: getDotTok(), lastTokOccurrence: 1 } const possibleNextTokTypes = new NextAfterTokenWalker( getParamSpec(), caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(1) expect(possibleNextTokTypes[0]).to.equal(getIdentTok()) } ) it( "can compute the next possible token types From a fqn inside an actionParamSpec" + " inside an paramSpec INSIDE ActionDec #3", () => { const caPath: ITokenGrammarPath = { ruleStack: ["paramSpec", "qualifiedName"], occurrenceStack: [1, 1], lastTok: getIdentTok(), lastTokOccurrence: 2 } const possibleNextTokTypes = new NextAfterTokenWalker( getParamSpec(), caPath ).startWalking() expect(possibleNextTokTypes.length).to.equal(2) setEquality(possibleNextTokTypes, [getDotTok(), getLSquareTok()]) } ) it("will fail if we try to compute the next token starting from a rule that does not match the path", () => { const caPath: ITokenGrammarPath = { ruleStack: ["I_WILL_FAIL_THE_WALKER", "qualifiedName"], occurrenceStack: [1, 1], lastTok: getIdentTok(), lastTokOccurrence: 2 } const walker = new NextAfterTokenWalker(getParamSpec(), caPath) expect(() => walker.startWalking()).to.throw( "The path does not start with the walker's top Rule!" ) }) }) describe("The NextTerminalAfterManyWalker", () => { it("can compute the next possible token types after the MANY in QualifiedName", () => { const rule = new Rule({ name: "TwoRepetitionRule", definition: [ new Repetition({ definition: [ new Terminal({ terminalType: getIdentTok(), idx: 1 }) ], idx: 2 }), new Terminal({ terminalType: getIdentTok(), idx: 2 }), new Repetition({ definition: [ new Terminal({ terminalType: getDotTok() }), new Terminal({ terminalType: getIdentTok(), idx: 3 }) ] }) ] }) const result = new NextTerminalAfterManyWalker(rule, 1).startWalking() //noinspection BadExpressionStatementJS expect(result.occurrence).to.be.undefined //noinspection BadExpressionStatementJS expect(result.token).to.be.undefined }) it("can compute the next possible token types after the MANY in paramSpec inside ActionDec", () => { const result = new NextTerminalAfterManyWalker( actionDec, 1 ).startWalking() expect(result.occurrence).to.equal(1) expect(result.token).to.equal(RParenTok) }) }) describe("The NextTerminalAfterManySepWalker", () => { it("can compute the next possible token types after the MANY_SEP in QualifiedName", () => { const callArguments = new Rule({ name: "callArguments", definition: [ new RepetitionWithSeparator({ definition: [new Terminal({ terminalType: getIdentTok(), idx: 1 })], separator: CommaTok }), new RepetitionWithSeparator({ definition: [new Terminal({ terminalType: getIdentTok(), idx: 2 })], separator: CommaTok, idx: 2 }) ] }) const result = new NextTerminalAfterManySepWalker( callArguments, 1 ).startWalking() //noinspection BadExpressionStatementJS expect(result.occurrence).to.be.undefined //noinspection BadExpressionStatementJS expect(result.token).to.be.undefined }) it("can compute the next possible token types after the MANY in paramSpec inside ActionDec", () => { const ActionTok = createToken({ name: "ActionTok", pattern: /NA/ }) const actionDecSep = new Rule({ name: "actionDecSep", definition: [ new Terminal({ terminalType: ActionTok }), new Terminal({ terminalType: getIdentTok() }), new Terminal({ terminalType: LParenTok }), new RepetitionWithSeparator({ definition: [ new NonTerminal({ nonTerminalName: "paramSpec", referencedRule: getParamSpec(), idx: 2 }) ], separator: CommaTok }), new Terminal({ terminalType: RParenTok }), new Option({ definition: [ new Terminal({ terminalType: getColonTok() }), new NonTerminal({ nonTerminalName: "qualifiedName", referencedRule: buildQualifiedName() }) ], idx: 2 }), new Terminal({ terminalType: SemicolonTok }) ] }) const result = new NextTerminalAfterManySepWalker( actionDecSep, 1 ).startWalking() expect(result.occurrence).to.equal(1) expect(result.token).to.equal(RParenTok) }) }) describe("The NextTerminalAfterAtLeastOneWalker", () => { it("can compute the next possible token types after an AT_LEAST_ONE production", () => { const EntityTok = createToken({ name: "EntityTok", pattern: /NA/ }) const atLeastOneRule = new Rule({ name: "atLeastOneRule", definition: [ new RepetitionMandatory({ definition: [ new RepetitionMandatory({ definition: [ new RepetitionMandatory({ definition: [new Terminal({ terminalType: EntityTok })], idx: 3 }), new Terminal({ terminalType: CommaTok }) ], idx: 2 }), new Terminal({ terminalType: getDotTok(), idx: 1 }) ] }), new Terminal({ terminalType: getDotTok(), idx: 2 }) ] }) const result = new NextTerminalAfterAtLeastOneWalker( atLeastOneRule, 1 ).startWalking() expect(result.occurrence).to.equal(2) expect(result.token).to.equal(getDotTok()) const result2 = new NextTerminalAfterAtLeastOneWalker( atLeastOneRule, 2 ).startWalking() expect(result2.occurrence).to.equal(1) expect(result2.token).to.equal(getDotTok()) const result3 = new NextTerminalAfterAtLeastOneWalker( atLeastOneRule, 3 ).startWalking() expect(result3.occurrence).to.equal(1) expect(result3.token).to.equal(CommaTok) }) it("can compute the next possible token types after an AT_LEAST_ONE production - EMPTY", () => { const atLeastOneRule = new Rule({ name: "atLeastOneRule", definition: [ new RepetitionMandatory({ definition: [ new Terminal({ terminalType: getDotTok(), idx: 1 }) ] }) ] }) const result = new NextTerminalAfterAtLeastOneWalker( atLeastOneRule, 1 ).startWalking() expect(result.occurrence).to.be.undefined expect(result.token).to.be.undefined }) }) describe("The NextTerminalAfterAtLeastOneSepWalker", () => { it("can compute the next possible token types after an AT_LEAST_ONE_SEP production", () => { const EntityTok = createToken({ name: "EntityTok", pattern: /NA/ }) const atLeastOneSepRule = new Rule({ name: "atLeastOneSepRule", definition: [ new RepetitionMandatoryWithSeparator({ definition: [ new RepetitionMandatoryWithSeparator({ definition: [ new RepetitionMandatoryWithSeparator({ definition: [new Terminal({ terminalType: EntityTok })], separator: SemicolonTok, idx: 3 }), new Terminal({ terminalType: CommaTok }) ], separator: SemicolonTok, idx: 2 }), new Terminal({ terminalType: getDotTok(), idx: 1 }) ], separator: SemicolonTok }), new Terminal({ terminalType: getDotTok(), idx: 2 }) ] }) const result = new NextTerminalAfterAtLeastOneSepWalker( atLeastOneSepRule, 1 ).startWalking() expect(result.occurrence).to.equal(2) expect(result.token).to.equal(getDotTok()) const result2 = new NextTerminalAfterAtLeastOneSepWalker( atLeastOneSepRule, 2 ).startWalking() expect(result2.occurrence).to.equal(1) expect(result2.token).to.equal(getDotTok()) const result3 = new NextTerminalAfterAtLeastOneSepWalker( atLeastOneSepRule, 3 ).startWalking() expect(result3.occurrence).to.equal(1) expect(result3.token).to.equal(CommaTok) }) it("can compute the next possible token types after an AT_LEAST_ONE_SEP production EMPTY", () => { const qualifiedNameSep = new Rule({ name: "qualifiedNameSep", definition: [ new RepetitionMandatoryWithSeparator({ definition: [new Terminal({ terminalType: getIdentTok(), idx: 1 })], separator: getDotTok() }) ] }) const result = new NextTerminalAfterAtLeastOneSepWalker( qualifiedNameSep, 1 ).startWalking() //noinspection BadExpressionStatementJS expect(result.occurrence).to.be.undefined //noinspection BadExpressionStatementJS expect(result.token).to.be.undefined }) }) describe("The chevrotain grammar interpreter capabilities", () => { function extractPartialPaths(newResultFormat: PartialPathAndSuffixes[]) { return map(newResultFormat, (currItem) => currItem.partialPath) } class Alpha { static PATTERN = /NA/ } class Beta { static PATTERN = /NA/ } class Gamma { static PATTERN = /NA/ } class Comma { static PATTERN = /NA/ } before(() => { augmentTokenTypes([Alpha, Beta, Gamma, Comma]) }) context("can calculate the next possible paths in a", () => { it("Sequence", () => { const seq = [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Gamma }) ] expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([ [Alpha] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([ [Alpha, Beta] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([ [Alpha, Beta, Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([ [Alpha, Beta, Gamma] ]) }) it("Optional", () => { const seq = [ new Terminal({ terminalType: Alpha }), new Option({ definition: [new Terminal({ terminalType: Beta })] }), new Terminal({ terminalType: Gamma }) ] expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([ [Alpha] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([ [Alpha, Beta], [Alpha, Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([ [Alpha, Beta, Gamma], [Alpha, Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([ [Alpha, Beta, Gamma], [Alpha, Gamma] ]) }) it("Alternation", () => { const alts = [ new Alternation({ definition: [ new Alternative({ definition: [new Terminal({ terminalType: Alpha })] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Beta }) ] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Gamma }) ] }) ] }) ] expect(extractPartialPaths(possiblePathsFrom(alts, 1))).to.deep.equal([ [Alpha], [Beta], [Beta] ]) expect(extractPartialPaths(possiblePathsFrom(alts, 2))).to.deep.equal([ [Alpha], [Beta, Beta], [Beta, Alpha] ]) expect(extractPartialPaths(possiblePathsFrom(alts, 3))).to.deep.equal([ [Alpha], [Beta, Beta], [Beta, Alpha, Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(alts, 4))).to.deep.equal([ [Alpha], [Beta, Beta], [Beta, Alpha, Gamma] ]) }) it("Repetition", () => { const rep = [ new Repetition({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Alpha }) ] }), new Terminal({ terminalType: Gamma }) ] expect(extractPartialPaths(possiblePathsFrom(rep, 1))).to.deep.equal([ [Alpha], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 2))).to.deep.equal([ [Alpha, Alpha], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 3))).to.deep.equal([ [Alpha, Alpha, Alpha], [Alpha, Alpha, Gamma], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 4))).to.deep.equal([ [Alpha, Alpha, Alpha, Alpha], [Alpha, Alpha, Gamma], [Gamma] ]) }) it("Mandatory Repetition", () => { const repMand = [ new RepetitionMandatory({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Alpha }) ] }), new Terminal({ terminalType: Gamma }) ] expect( extractPartialPaths(possiblePathsFrom(repMand, 1)) ).to.deep.equal([[Alpha]]) expect( extractPartialPaths(possiblePathsFrom(repMand, 2)) ).to.deep.equal([[Alpha, Alpha]]) expect( extractPartialPaths(possiblePathsFrom(repMand, 3)) ).to.deep.equal([ [Alpha, Alpha, Alpha], [Alpha, Alpha, Gamma] ]) expect( extractPartialPaths(possiblePathsFrom(repMand, 4)) ).to.deep.equal([ [Alpha, Alpha, Alpha, Alpha], [Alpha, Alpha, Gamma] ]) }) it("Repetition with Separator", () => { // same as Mandatory Repetition because currently possiblePaths only cares about // the first repetition. const rep = [ new RepetitionWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Alpha }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] expect(extractPartialPaths(possiblePathsFrom(rep, 1))).to.deep.equal([ [Alpha], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 2))).to.deep.equal([ [Alpha, Alpha], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 3))).to.deep.equal([ [Alpha, Alpha, Comma], [Alpha, Alpha, Gamma], [Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(rep, 4))).to.deep.equal([ [Alpha, Alpha, Comma, Alpha], [Alpha, Alpha, Gamma], [Gamma] ]) }) it("Mandatory Repetition with Separator", () => { // same as Mandatory Repetition because currently possiblePaths only cares about // the first repetition. const repMandSep = [ new RepetitionMandatoryWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Alpha }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] expect( extractPartialPaths(possiblePathsFrom(repMandSep, 1)) ).to.deep.equal([[Alpha]]) expect( extractPartialPaths(possiblePathsFrom(repMandSep, 2)) ).to.deep.equal([[Alpha, Alpha]]) expect( extractPartialPaths(possiblePathsFrom(repMandSep, 3)) ).to.deep.equal([ [Alpha, Alpha, Comma], [Alpha, Alpha, Gamma] ]) expect( extractPartialPaths(possiblePathsFrom(repMandSep, 4)) ).to.deep.equal([ [Alpha, Alpha, Comma, Alpha], [Alpha, Alpha, Gamma] ]) }) it("NonTerminal", () => { const someSubRule = new Rule({ name: "blah", definition: [new Terminal({ terminalType: Beta })] }) const seq = [ new Terminal({ terminalType: Alpha }), new NonTerminal({ nonTerminalName: "blah", referencedRule: someSubRule }), new Terminal({ terminalType: Gamma }) ] expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([ [Alpha] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([ [Alpha, Beta] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([ [Alpha, Beta, Gamma] ]) expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([ [Alpha, Beta, Gamma] ]) }) }) context("can calculate the next possible single tokens for: ", () => { function INPUT(tokTypes: TokenType[]): IToken[] { return map(tokTypes, (currTokType) => createRegularToken(currTokType)) } function pluckTokenTypes(arr: any[]): TokenType[] { return map(arr, (currItem) => currItem.nextTokenType) } it("Sequence positive", () => { const seq = [ new Alternative({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Gamma }) ] }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( seq, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( seq, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Gamma] ) }) it("Sequence negative", () => { const seq = [ new Alternative({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Gamma }) ] }) ] // negative expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5) ).to.be.empty }) it("Optional positive", () => { const seq = [ new Terminal({ terminalType: Alpha }), new Option({ definition: [new Terminal({ terminalType: Beta })] }), new Terminal({ terminalType: Gamma }) ] // setEquality(pluckTokenTypes(nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5)), [Alpha]) setEquality( pluckTokenTypes( nextPossibleTokensAfter( seq, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta, Gamma] ) // setEquality(pluckTokenTypes(nextPossibleTokensAfter(seq, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5)), [Gamma]) }) it("Optional Negative", () => { const seq = [ new Terminal({ terminalType: Alpha }), new Option({ definition: [new Terminal({ terminalType: Beta })] }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5) ).to.be.empty expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Alpha]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("Alternation positive", () => { const alts = [ new Alternation({ definition: [ new Alternative({ definition: [new Terminal({ terminalType: Alpha })] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Beta }) ] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Gamma }) ] }), new Alternative({ definition: [new Terminal({ terminalType: Gamma })] }) ] }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter(alts, INPUT([]), tokenStructuredMatcher, 5) ), [Alpha, Beta, Beta, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( alts, INPUT([Beta]), tokenStructuredMatcher, 5 ) ), [Beta, Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( alts, INPUT([Beta, Alpha]), tokenStructuredMatcher, 5 ) ), [Gamma] ) }) it("Alternation Negative", () => { const alts = [ new Alternation({ definition: [ new Alternative({ definition: [new Terminal({ terminalType: Alpha })] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Beta }) ] }), new Alternative({ definition: [ new Terminal({ terminalType: Beta }), new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Gamma }) ] }) ] }) ] expect( nextPossibleTokensAfter( alts, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( alts, INPUT([Gamma, Alpha]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( alts, INPUT([Beta, Beta]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( alts, INPUT([Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("Repetition - positive", () => { const rep = [ new Repetition({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ] }), new Terminal({ terminalType: Gamma }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter(rep, INPUT([]), tokenStructuredMatcher, 5) ), [Alpha, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( rep, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( rep, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Alpha, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( rep, INPUT([Alpha, Beta, Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( rep, INPUT([Alpha, Beta, Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Alpha, Gamma] ) }) it("Repetition - negative", () => { const rep = [ new Repetition({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ] }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter(rep, INPUT([Beta]), tokenStructuredMatcher, 5) ).to.be.empty expect( nextPossibleTokensAfter( rep, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( rep, INPUT([Alpha, Beta, Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( rep, INPUT([Alpha, Beta, Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("Mandatory Repetition - positive", () => { const repMand = [ new RepetitionMandatory({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ] }), new Terminal({ terminalType: Gamma }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter( repMand, INPUT([]), tokenStructuredMatcher, 5 ) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repMand, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Alpha, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Alpha, Gamma] ) }) it("Mandatory Repetition - negative", () => { const repMand = [ new RepetitionMandatory({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ] }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter( repMand, INPUT([Beta]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("Repetition with Separator - positive", () => { const repSep = [ new RepetitionWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([]), tokenStructuredMatcher, 5 ) ), [Alpha, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Comma, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta, Comma]), tokenStructuredMatcher, 5 ) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta, Comma, Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Comma, Gamma] ) }) it("Repetition with Separator - negative", () => { const repMand = [ new RepetitionWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter( repMand, INPUT([Comma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Comma, Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Comma, Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("Repetition with Separator Mandatory - positive", () => { const repSep = [ new RepetitionMandatoryWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([]), tokenStructuredMatcher, 5 ) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Comma, Gamma] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta, Comma]), tokenStructuredMatcher, 5 ) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( repSep, INPUT([Alpha, Beta, Comma, Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Comma, Gamma] ) }) it("Repetition with Separator Mandatory - negative", () => { const repMand = [ new RepetitionMandatoryWithSeparator({ definition: [ new Terminal({ terminalType: Alpha }), new Terminal({ terminalType: Beta }) ], separator: Comma }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter( repMand, INPUT([Comma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Comma, Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( repMand, INPUT([Alpha, Beta, Comma, Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) it("NonTerminal - positive", () => { const someSubRule = new Rule({ name: "blah", definition: [new Terminal({ terminalType: Beta })] }) const seq = [ new Terminal({ terminalType: Alpha }), new NonTerminal({ nonTerminalName: "blah", referencedRule: someSubRule }), new Terminal({ terminalType: Gamma }) ] setEquality( pluckTokenTypes( nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5) ), [Alpha] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( seq, INPUT([Alpha]), tokenStructuredMatcher, 5 ) ), [Beta] ) setEquality( pluckTokenTypes( nextPossibleTokensAfter( seq, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5 ) ), [Gamma] ) }) it("NonTerminal - negative", () => { const someSubRule = new Rule({ name: "blah", definition: [new Terminal({ terminalType: Beta })] }) const seq = [ new Terminal({ terminalType: Alpha }), new NonTerminal({ nonTerminalName: "blah", referencedRule: someSubRule }), new Terminal({ terminalType: Gamma }) ] expect( nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5) ).to.be.empty expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty expect( nextPossibleTokensAfter( seq, INPUT([Alpha, Beta, Gamma]), tokenStructuredMatcher, 5 ) ).to.be.empty }) }) }) describe("issue 391 - WITH_SEP variants do not take SEP into account in lookahead", () => { it("Reproduce issue", () => { const LParen = createToken({ name: "LParen", pattern: /\(/ }) const RParen = createToken({ name: "RParen", pattern: /\)/ }) const Comma = createToken({ name: "Comma", pattern: /,/ }) const FatArrow = createToken({ name: "FatArrow", pattern: /=>/ }) const Identifier = createToken({ name: "Identifier", pattern: /[a-zA-Z]+/ }) const WhiteSpace = createToken({ name: "WhiteSpace", pattern: /\s+/, group: Lexer.SKIPPED, line_breaks: true }) const allTokens = [ WhiteSpace, LParen, RParen, Comma, FatArrow, Identifier ] const issue391Lexer = new Lexer(allTokens) class Issue391Parser extends EmbeddedActionsParser { constructor(input: IToken[] = []) { super(allTokens, { maxLookahead: 4 }) this.performSelfAnalysis() this.input = input } topRule = this.RULE("topRule", () => { return this.OR9([ { // Lambda Function ALT: () => { this.CONSUME1(LParen) this.MANY_SEP({ SEP: Comma, DEF: () => { this.CONSUME1(Identifier) } }) this.CONSUME1(RParen) this.CONSUME1(FatArrow) } }, { // Parenthesis Expression ALT: () => { this.CONSUME2(LParen) this.CONSUME2(Identifier) this.CONSUME2(RParen) } } ]) }) } expect(() => new Issue391Parser([])).to.not.throw( "Ambiguous alternatives: <1 ,2>" ) const myParser = new Issue391Parser([]) function testInput(input: string) { const tokens = issue391Lexer.tokenize(input).tokens myParser.input = tokens myParser.topRule() expect(myParser.errors).to.be.empty } testInput("(x, y) => ") testInput("() =>") testInput("(x) =>") testInput("(x)") }) }) })
the_stack
import expect from "expect"; import { ASTNode, BoolType, eq, IntType } from "solc-typed-ast"; import { Logger } from "../../src/logger"; import { AnnotationType, SAnnotation, SBinaryOperation, SBooleanLiteral, SConditional, SForAll, SFunctionCall, SId, SIfAssigned, SIfUpdated, SIndexAccess, SLet, SMemberAccess, SNode, SNumber, SProperty, SResult, SStringLiteral, SUnaryOperation, SUserFunctionDefinition } from "../../src/spec-lang/ast"; import { parseAnnotation, parseExpression as parseExpr } from "../../src/spec-lang/expr_parser"; import { DummySourceFile } from "../../src/util/sources"; describe("Expression Parser Unit Tests", () => { const goodSamples: Array<[string, SNode]> = [ // Literals ["abcd", new SId("abcd")], ["1234", new SNumber(BigInt(1234), 10)], ["10 wei", new SNumber(BigInt(10), 10)], ["10 gwei", new SNumber(BigInt(1e10), 10)], ["1 ether", new SNumber(BigInt(1e18), 10)], ["100 seconds", new SNumber(BigInt(100), 10)], ["100 \n\n\n minutes", new SNumber(BigInt(6000), 10)], ["100 hours", new SNumber(BigInt(360000), 10)], ["100 days", new SNumber(BigInt(8640000), 10)], ["100 weeks", new SNumber(BigInt(60480000), 10)], ["true", new SBooleanLiteral(true)], ["false", new SBooleanLiteral(false)], // ops ["-1", new SUnaryOperation("-", new SNumber(BigInt(1), 10))], ["--a", new SUnaryOperation("-", new SUnaryOperation("-", new SId("a")))], ["!-a", new SUnaryOperation("!", new SUnaryOperation("-", new SId("a")))], // Binary ops // Power [ "43**0x9", new SBinaryOperation(new SNumber(BigInt(43), 10), "**", new SNumber(BigInt(9), 16)) ], [ "2**2**3", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(2), 10), "**", new SNumber(BigInt(2), 10)), "**", new SNumber(BigInt(3), 10) ) ], // Multiplicative [ "43*0x9", new SBinaryOperation(new SNumber(BigInt(43), 10), "*", new SNumber(BigInt(9), 16)) ], [ "43*0x9*a", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(43), 10), "*", new SNumber(BigInt(9), 16)), "*", new SId("a") ) ], [ "43*0x9/a", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(43), 10), "*", new SNumber(BigInt(9), 16)), "/", new SId("a") ) ], [ "43%0x9/a", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(43), 10), "%", new SNumber(BigInt(9), 16)), "/", new SId("a") ) ], // Here left-to-right order matters for correctness. With the correct order this evals to 3, and with the wrong one to 1 [ "13%7/2", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(13), 10), "%", new SNumber(BigInt(7), 10)), "/", new SNumber(BigInt(2), 10) ) ], // Additive [ "43+0x9", new SBinaryOperation(new SNumber(BigInt(43), 10), "+", new SNumber(BigInt(9), 16)) ], [ "43-5", new SBinaryOperation(new SNumber(BigInt(43), 10), "-", new SNumber(BigInt(5), 10)) ], [ "43-5*6", new SBinaryOperation( new SNumber(BigInt(43), 10), "-", new SBinaryOperation(new SNumber(BigInt(5), 10), "*", new SNumber(BigInt(6), 10)) ) ], //assert(43-5*-6==73); [ "43-5*-6", new SBinaryOperation( new SNumber(BigInt(43), 10), "-", new SBinaryOperation( new SNumber(BigInt(5), 10), "*", new SUnaryOperation("-", new SNumber(BigInt(6), 10)) ) ) ], //assert(43-5+6==44); [ "43-5+6", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(43), 10), "-", new SNumber(BigInt(5), 10)), "+", new SNumber(BigInt(6), 10) ) ], // Bitwise //assert(256 >> 4 == 16); [ "256>>4", new SBinaryOperation(new SNumber(BigInt(256), 10), ">>", new SNumber(BigInt(4), 10)) ], //assert(256 >> 4 >> 1 == 8); [ "256>>4>>1", new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(256), 10), ">>", new SNumber(BigInt(4), 10) ), ">>", new SNumber(BigInt(1), 10) ) ], // assert(256 << 4 << 1 == 2 ** 13); [ "256<<4<<1", new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(256), 10), "<<", new SNumber(BigInt(4), 10) ), "<<", new SNumber(BigInt(1), 10) ) ], // assert(3+4 << 1 == 14); // weird right? [ "3+4<<1", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "+", new SNumber(BigInt(4), 10)), "<<", new SNumber(BigInt(1), 10) ) ], // assert(3+2*2 << 1 == 14); [ "3+2*2<<1", new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(3), 10), "+", new SBinaryOperation( new SNumber(BigInt(2), 10), "*", new SNumber(BigInt(2), 10) ) ), "<<", new SNumber(BigInt(1), 10) ) ], // assert(3*3 << 1 == 18); [ "3*3<<1", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "*", new SNumber(BigInt(3), 10)), "<<", new SNumber(BigInt(1), 10) ) ], // relational operators ["4>0", new SBinaryOperation(new SNumber(BigInt(4), 10), ">", new SNumber(BigInt(0), 10))], [ "4+4<=8", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(4), 10), "+", new SNumber(BigInt(4), 10)), "<=", new SNumber(BigInt(8), 10) ) ], [ "-1*5>=-6", new SBinaryOperation( new SBinaryOperation( new SUnaryOperation("-", new SNumber(BigInt(1), 10)), "*", new SNumber(BigInt(5), 10) ), ">=", new SUnaryOperation("-", new SNumber(BigInt(6), 10)) ) ], [ "3<<2>=6", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "<<", new SNumber(BigInt(2), 10)), ">=", new SNumber(BigInt(6), 10) ) ], // Equality operators [ "4 == 4", new SBinaryOperation(new SNumber(BigInt(4), 10), "==", new SNumber(BigInt(4), 10)) ], [ "3+1 == 2+2", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "+", new SNumber(BigInt(1), 10)), "==", new SBinaryOperation(new SNumber(BigInt(2), 10), "+", new SNumber(BigInt(2), 10)) ) ], [ "3>1 == 2>=2", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), ">", new SNumber(BigInt(1), 10)), "==", new SBinaryOperation(new SNumber(BigInt(2), 10), ">=", new SNumber(BigInt(2), 10)) ) ], [ "true == false == false", new SBinaryOperation( new SBinaryOperation(new SBooleanLiteral(true), "==", new SBooleanLiteral(false)), "==", new SBooleanLiteral(false) ) ], // Bitwise binary operators [ "3 & 4", new SBinaryOperation(new SNumber(BigInt(3), 10), "&", new SNumber(BigInt(4), 10)) ], [ "3 | 4", new SBinaryOperation(new SNumber(BigInt(3), 10), "|", new SNumber(BigInt(4), 10)) ], [ "3 ^ 4", new SBinaryOperation(new SNumber(BigInt(3), 10), "^", new SNumber(BigInt(4), 10)) ], [ "3 + 4 ^ 4", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "+", new SNumber(BigInt(4), 10)), "^", new SNumber(BigInt(4), 10) ) ], [ "3 ^ 4 & 4", new SBinaryOperation( new SNumber(BigInt(3), 10), "^", new SBinaryOperation(new SNumber(BigInt(4), 10), "&", new SNumber(BigInt(4), 10)) ) ], [ "3 | 4 ^ 4", new SBinaryOperation( new SNumber(BigInt(3), 10), "|", new SBinaryOperation(new SNumber(BigInt(4), 10), "^", new SNumber(BigInt(4), 10)) ) ], [ "true || false", new SBinaryOperation(new SBooleanLiteral(true), "||", new SBooleanLiteral(false)) ], [ "true && true", new SBinaryOperation(new SBooleanLiteral(true), "&&", new SBooleanLiteral(true)) ], [ "3<4 && 3^4 > 3", new SBinaryOperation( new SBinaryOperation(new SNumber(BigInt(3), 10), "<", new SNumber(BigInt(4), 10)), "&&", new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(3), 10), "^", new SNumber(BigInt(4), 10) ), ">", new SNumber(BigInt(3), 10) ) ) ], [ "false ==> true", new SBinaryOperation(new SBooleanLiteral(false), "==>", new SBooleanLiteral(true)) ], [ "3+4>1 ==> true", new SBinaryOperation( new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(3), 10), "+", new SNumber(BigInt(4), 10) ), ">", new SNumber(BigInt(1), 10) ), "==>", new SBooleanLiteral(true) ) ], // We define implication to be right-associative. [ "3+4>1 ==> true ==> 1==1", new SBinaryOperation( new SBinaryOperation( new SBinaryOperation( new SNumber(BigInt(3), 10), "+", new SNumber(BigInt(4), 10) ), ">", new SNumber(BigInt(1), 10) ), "==>", new SBinaryOperation( new SBooleanLiteral(true), "==>", new SBinaryOperation( new SNumber(BigInt(1), 10), "==", new SNumber(BigInt(1), 10) ) ) ) ], // Member Expressions ["a.b", new SMemberAccess(new SId("a"), "b")], ["a.b.c", new SMemberAccess(new SMemberAccess(new SId("a"), "b"), "c")], [ "1<a.b.c", new SBinaryOperation( new SNumber(BigInt(1), 10), "<", new SMemberAccess(new SMemberAccess(new SId("a"), "b"), "c") ) ], // Index Expressions ["a[b]", new SIndexAccess(new SId("a"), new SId("b"))], [ "a[b+c]", new SIndexAccess(new SId("a"), new SBinaryOperation(new SId("b"), "+", new SId("c"))) ], [ "a[b+c][d]", new SIndexAccess( new SIndexAccess( new SId("a"), new SBinaryOperation(new SId("b"), "+", new SId("c")) ), new SId("d") ) ], [ "a[d][b+c]", new SIndexAccess( new SIndexAccess(new SId("a"), new SId("d")), new SBinaryOperation(new SId("b"), "+", new SId("c")) ) ], ["a.foo[b]", new SIndexAccess(new SMemberAccess(new SId("a"), "foo"), new SId("b"))], [ "a[d].foo[b+c]", new SIndexAccess( new SMemberAccess(new SIndexAccess(new SId("a"), new SId("d")), "foo"), new SBinaryOperation(new SId("b"), "+", new SId("c")) ) ], // Function calls ["a()", new SFunctionCall(new SId("a"), [])], ["a(1)", new SFunctionCall(new SId("a"), [new SNumber(BigInt(1), 10)])], [ "a(1, 0x2+c)", new SFunctionCall(new SId("a"), [ new SNumber(BigInt(1), 10), new SBinaryOperation(new SNumber(BigInt(2), 16), "+", new SId("c")) ]) ], [ "a(1, 0x2+c, x.f)", new SFunctionCall(new SId("a"), [ new SNumber(BigInt(1), 10), new SBinaryOperation(new SNumber(BigInt(2), 16), "+", new SId("c")), new SMemberAccess(new SId("x"), "f") ]) ], [ "a.f(1)", new SFunctionCall(new SMemberAccess(new SId("a"), "f"), [new SNumber(BigInt(1), 10)]) ], [ "a.f[b](1)", new SFunctionCall( new SIndexAccess(new SMemberAccess(new SId("a"), "f"), new SId("b")), [new SNumber(BigInt(1), 10)] ) ], [ "a().f[b](1)", new SFunctionCall( new SIndexAccess( new SMemberAccess(new SFunctionCall(new SId("a"), []), "f"), new SId("b") ), [new SNumber(BigInt(1), 10)] ) ], // Old expression (looks like a function call but is treated as a unary operation) ["old(a)", new SUnaryOperation("old", new SId("a"))], ["old(a).f", new SMemberAccess(new SUnaryOperation("old", new SId("a")), "f")], ["old(a)[f]", new SIndexAccess(new SUnaryOperation("old", new SId("a")), new SId("f"))], [ "old(a+b)", new SUnaryOperation("old", new SBinaryOperation(new SId("a"), "+", new SId("b"))) ], ["old(a)()", new SFunctionCall(new SUnaryOperation("old", new SId("a")), [])], // Conditional ["a?b:c", new SConditional(new SId("a"), new SId("b"), new SId("c"))], [ "a?b+1:c-d", new SConditional( new SId("a"), new SBinaryOperation(new SId("b"), "+", new SNumber(BigInt(1), 10)), new SBinaryOperation(new SId("c"), "-", new SId("d")) ) ], [ "false || true ? false : true", new SConditional( new SBinaryOperation(new SBooleanLiteral(false), "||", new SBooleanLiteral(true)), new SBooleanLiteral(false), new SBooleanLiteral(true) ) ], [ "false || true ? 1 : 2", new SConditional( new SBinaryOperation(new SBooleanLiteral(false), "||", new SBooleanLiteral(true)), new SNumber(BigInt(1), 10), new SNumber(BigInt(2), 10) ) ], [ // ternaries have a higher priority than || (this evaluates to true) "true ? true : false || false", new SConditional( new SBooleanLiteral(true), new SBooleanLiteral(true), new SBinaryOperation(new SBooleanLiteral(false), "||", new SBooleanLiteral(false)) ) ], [ // ternaries associate to the right (this evaluates to true) "true ? true : false ? false : true", new SConditional( new SBooleanLiteral(true), new SBooleanLiteral(true), new SConditional( new SBooleanLiteral(false), new SBooleanLiteral(false), new SBooleanLiteral(true) ) ) ], // Let expressions ["let a := 1 in a", new SLet([new SId("a")], new SNumber(BigInt(1), 10), new SId("a"))], [ "let a := b+c in a", new SLet( [new SId("a")], new SBinaryOperation(new SId("b"), "+", new SId("c")), new SId("a") ) ], [ "let a := b+c in a*a", new SLet( [new SId("a")], new SBinaryOperation(new SId("b"), "+", new SId("c")), new SBinaryOperation(new SId("a"), "*", new SId("a")) ) ], [ "let a := let b := 1 in b+b in a*a", new SLet( [new SId("a")], new SLet( [new SId("b")], new SNumber(BigInt(1), 10), new SBinaryOperation(new SId("b"), "+", new SId("b")) ), new SBinaryOperation(new SId("a"), "*", new SId("a")) ) ], [ "let a := let b := 1 in b+b in let c := a*a in c+1", new SLet( [new SId("a")], new SLet( [new SId("b")], new SNumber(BigInt(1), 10), new SBinaryOperation(new SId("b"), "+", new SId("b")) ), new SLet( [new SId("c")], new SBinaryOperation(new SId("a"), "*", new SId("a")), new SBinaryOperation(new SId("c"), "+", new SNumber(BigInt(1), 10)) ) ) ], [ "let a, b := foo() in a+b", new SLet( [new SId("a"), new SId("b")], new SFunctionCall(new SId("foo"), []), new SBinaryOperation(new SId("a"), "+", new SId("b")) ) ], [ "forall (uint x in a) a[x]>10", new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), undefined, undefined, new SId("a") ) ], [ "forall (uint x in 1...10) a[x]>10", new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), new SNumber(BigInt(1), 10), new SNumber(BigInt(10), 10) ) ], ["$result", new SResult()], [ "true && forall (uint x in 1...10) a[x]>10", new SBinaryOperation( new SBooleanLiteral(true), "&&", new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), new SNumber(BigInt(1), 10), new SNumber(BigInt(10), 10) ) ) ], [ "true && forall (uint x in 1...10) true || forall (uint x in 1...10) false", new SBinaryOperation( new SBooleanLiteral(true), "&&", new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SBooleanLiteral(true), "||", new SForAll( new IntType(256, false), new SId("x"), new SBooleanLiteral(false), new SNumber(BigInt(1), 10), new SNumber(BigInt(10), 10) ) ), new SNumber(BigInt(1), 10), new SNumber(BigInt(10), 10) ) ) ] ]; const badSamples: string[] = [ "0asdf", "100 satoshi", "0x10ab gwei", "0x123av", "123a", "a.1", "old", "old.foo", "old+1", "old[1]", "old(1,2)", "forall (uint x in let) f(sheep)", "forall (uint x in [0, 100)] a[x] > 10", "forall (x in 0...100) x > 0" ]; for (const [sample, expectedAST] of goodSamples) { describe(`Sample ${sample}`, () => { it("Parses correctly", () => { const parsed = parseExpr( sample, undefined as unknown as ASTNode, "0.6.0", new DummySourceFile(), 0 ); expect(eq(parsed, expectedAST)).toEqual(true); }); }); } for (const sample of badSamples) { describe(`Sample ${sample}`, () => { it("Fails as expected", () => { expect(() => { parseExpr( sample, undefined as unknown as ASTNode, "0.6.0", new DummySourceFile(), 0 ); }).toThrow(); }); }); } }); describe("Annotation Parser Unit Tests", () => { const goodSamples: Array<[string, SAnnotation]> = [ ["#if_succeeds true;", new SProperty(AnnotationType.IfSucceeds, new SBooleanLiteral(true))], [ "/// #if_succeeds true;", new SProperty(AnnotationType.IfSucceeds, new SBooleanLiteral(true)) ], [ "/// @custom:scribble #if_succeeds false;", new SProperty(AnnotationType.IfSucceeds, new SBooleanLiteral(false)) ], [ '/// #if_succeeds {:msg "hi"} true;', new SProperty(AnnotationType.IfSucceeds, new SBooleanLiteral(true), { msg: new SStringLiteral("hi") }) ], [ `* #if_succeeds {:msg "hi" } 1 - 2 ;`, new SProperty( AnnotationType.IfSucceeds, new SBinaryOperation(new SNumber(BigInt(1), 10), "-", new SNumber(BigInt(2), 10)), { msg: new SStringLiteral("hi") } ) ], [ `* #if_updated {:msg "hi" } 1 - 2 ;`, new SIfUpdated( new SBinaryOperation(new SNumber(BigInt(1), 10), "-", new SNumber(BigInt(2), 10)), [], { msg: new SStringLiteral("hi") } ) ], [ `* #if_assigned[a] {:msg "bye" } true; ;`, new SIfAssigned(new SBooleanLiteral(true), [new SId("a")], { msg: new SStringLiteral("bye") }) ], [ `* #if_assigned.foo {:msg "bye" } true; ;`, new SIfAssigned(new SBooleanLiteral(true), ["foo"], { msg: new SStringLiteral("bye") }) ], [ `* #if_assigned._bar0.boo[a][b].foo[c] {:msg "felicia" } false; ;`, new SIfAssigned( new SBooleanLiteral(false), ["_bar0", "boo", new SId("a"), new SId("b"), "foo", new SId("c")], { msg: new SStringLiteral("felicia") } ) ], [ `* #invariant {:msg "hi" } 1 - 2 ;`, new SProperty( AnnotationType.Invariant, new SBinaryOperation(new SNumber(BigInt(1), 10), "-", new SNumber(BigInt(2), 10)), { msg: new SStringLiteral("hi") } ) ], [ "#define foo() bool = true;", new SUserFunctionDefinition( new SId("foo"), [], new BoolType(), new SBooleanLiteral(true) ) ], [ "/// #define foo() bool = true;", new SUserFunctionDefinition( new SId("foo"), [], new BoolType(), new SBooleanLiteral(true) ) ], [ "* #define foo() bool = true;", new SUserFunctionDefinition( new SId("foo"), [], new BoolType(), new SBooleanLiteral(true) ) ], [ '#define {:msg "tralala" } foo() bool = true;', new SUserFunctionDefinition( new SId("foo"), [], new BoolType(), new SBooleanLiteral(true), { msg: new SStringLiteral("tralala") } ) ], [ `#define {:msg "tralala" } foo( ) bool = true ;`, new SUserFunctionDefinition( new SId("foo"), [], new BoolType(), new SBooleanLiteral(true), { msg: new SStringLiteral("tralala") } ) ], [ "#define boo(uint a) uint = a;", new SUserFunctionDefinition( new SId("boo"), [[new SId("a"), new IntType(256, false)]], new IntType(256, false), new SId("a") ) ], [ "#define moo(uint a, uint b) uint = a+b;", new SUserFunctionDefinition( new SId("moo"), [ [new SId("a"), new IntType(256, false)], [new SId("b"), new IntType(256, false)] ], new IntType(256, false), new SBinaryOperation(new SId("a"), "+", new SId("b")) ) ], [ "/// #if_succeeds forall (uint x in 1...10) a[x]>10;", new SProperty( AnnotationType.IfSucceeds, new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), new SNumber(BigInt(1), 10), new SNumber(BigInt(10), 10) ) ) ], [ "/// #if_succeeds forall (uint x in a) a[x]>10;", new SProperty( AnnotationType.IfSucceeds, new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), undefined, undefined, new SId("a") ) ) ], ["/// #assert true;", new SProperty(AnnotationType.Assert, new SBooleanLiteral(true))], ["/// #assert {} true;", new SProperty(AnnotationType.Assert, new SBooleanLiteral(true))], [ "/// #assert forall (uint x in a) a[x] > 10;", new SProperty( AnnotationType.Assert, new SForAll( new IntType(256, false), new SId("x"), new SBinaryOperation( new SIndexAccess(new SId("a"), new SId("x")), ">", new SNumber(BigInt(10), 10) ), undefined, undefined, new SId("a") ) ) ] ]; const badSamples: string[] = [ `* if_assigned true;`, `* #if_assigned[1+2] {:msg "felicia" } false; ;`, `* #if_assigned [a] {:msg "felicia" } false; ;`, `* #if_assigned0ab {:msg "felicia" } false; ;`, `* #if_assigned,ab {:msg "felicia" } false; ;`, `* #if_updated[a] {:msg "bye" } true; ;`, `* #if_updated.foo {:msg "bye" } true; ;`, `/// #if_succeeds {bad: "true"} true;`, `/// #if_succeeds {msg: 1} true;`, `/// dshgd_$ $€%^@&8()su@custom:scribble #if_succeeds false;`, `///blah blah @custom:scrible #if_succeeds false; dhsgf gfds jdhsg s`, `/// @custom:scribble #if_succeeds a +;`, `/// @custom:scribble if_succeeds true;`, `/// @custom:scribble blah` ]; for (const [sample, expected] of goodSamples) { describe(`Sample ${sample}`, () => { it("Parses correctly", () => { const parsed = parseAnnotation( sample, undefined as unknown as ASTNode, "0.6.0", new DummySourceFile(), 0 ); Logger.debug(`[${sample}]: Got: ${parsed.pp()} expected: ${expected.pp()}`); expect(eq(parsed, expected)).toEqual(true); }); }); } for (const sample of badSamples) { describe(`Sample ${sample}`, () => { it("Fails as expected", () => { expect(() => { parseAnnotation( sample, undefined as unknown as ASTNode, "0.6.0", new DummySourceFile(), 0 ); }).toThrow(); }); }); } });
the_stack
import { action, observable, runInAction } from "mobx"; import defaultValue from "terriajs-cesium/Source/Core/defaultValue"; import DeveloperError from "terriajs-cesium/Source/Core/DeveloperError"; import CorsProxy from "../Core/CorsProxy"; import isDefined from "../Core/isDefined"; import loadJson from "../Core/loadJson"; /* Encapsulates one entry in regionMapping.json Responsibilities: - communicate with MVT server - provide region IDs for a given region type - determine whether a given column name matches - identify region and disambiguation columns - provide a lookup function for a given column of data */ type ReplacementVar = | "dataReplacements" | "serverReplacements" | "disambigDataReplacements" | "disambigServerReplacements"; export interface RegionProvierOptions { /** * Feature attribute whose value will correspond to each region's code. */ regionProp: string; /** * Feature attribute whose value can be used as a user-facing name for the region. If this property is undefined, the regions * do not have names. */ nameProp: string; /** * A text description of this region type, which may feature in the user interface. */ description: string; /** * Name of the MVT layer where these regions are found. */ layerName: string; /** * URL of the MVT server */ server: string; /** * List of subdomains for requests to be sent to (only defined for MVT providers) */ serverSubdomains: string[] | undefined; /** * Minimum zoom which the server serves tiles at */ serverMinZoom: number; /** * Maximum zoom which the maximum native zoom tiles can be rendered at */ serverMaxZoom: number; /** * Maximum zoom which the server serves tiles at */ serverMaxNativeZoom: number; /** * Bounding box of vector geometry [w,s,e,n] (only defined for MVT providers) */ bbox: number[] | undefined; /** * List of aliases which will be matched against if found as column headings. */ aliases: string[]; /** * Array of [regex, replacement] arrays which will be applied to each ID element on the server side before matching * is attempted. For example, [ [ ' \(.\)$' ], '' ] will convert 'Baw Baw (S)' to 'Baw Baw' */ serverReplacements: [string, string][]; /** * Array of [regex, replacement] arrays which will be applied to each user-provided ID element before matching * is attempted. For example, [ [ ' \(.\)$' ], '' ] will convert 'Baw Baw (S)' to 'Baw Baw' */ dataReplacements: [string, string][]; /** The property within the same WFS region that can be used for disambiguation. */ disambigProp: string | undefined; /** * Returns the name of a field which uniquely identifies each region. This field is not necessarily used for matching, or * of interest to the user, but is needed for reverse lookups. This field must count from zero, and features must be * returned in sorted order. */ uniqueIdProp: string; /** * Whether this region type uses text codes, rather than numeric. It matters because numeric codes are treated differently by the * CSV handling models. */ textCodes: boolean; /** * The URL of a pre-generated JSON file containing just a long list of IDs for a given * layer attribute, in the order of ascending feature IDs (fids). If defined, it will * be used in preference to requesting those attributes from the WFS server. */ regionIdsFile: string; /** * JSON file for disambiguation attribute, as per regionIdsFile. */ regionDisambigIdsFile: string; } interface Region { fid?: number; regionProp?: string | number | undefined; regionPropWithServerReplacement?: string | number | undefined; disambigProp?: string | number | undefined; disambigPropWithServerReplacement?: string | number | undefined; } interface RegionIndex { [key: string]: number | number[]; } export default class RegionProvider { readonly corsProxy: CorsProxy; readonly regionType: string; readonly regionProp: string; readonly nameProp: string; readonly description: string; readonly layerName: string; readonly server: string; readonly serverSubdomains: string[] | undefined; readonly serverMinZoom: number; readonly serverMaxZoom: number; readonly serverMaxNativeZoom: number; readonly bbox: number[] | undefined; readonly aliases: string[]; readonly serverReplacements: [string, string, RegExp][]; readonly dataReplacements: [string, string, RegExp][]; readonly disambigProp: string | undefined; readonly uniqueIdProp: string; readonly textCodes: boolean; readonly regionIdsFile: string; readonly regionDisambigIdsFile: string; private disambigDataReplacements: [string, string, RegExp][] | undefined; private disambigServerReplacements: [string, string, RegExp][] | undefined; private disambigAliases: string[] | undefined; private _appliedReplacements = { serverReplacements: {} as any, disambigServerReplacements: {} as any, dataReplacements: {} as any, disambigDataReplacements: {} as any }; /** * Array of attributes of each region, once retrieved from the server. */ private _regions: Region[] = []; get regions() { return this._regions; } /** * Look-up table of attributes, for speed. */ private _idIndex: RegionIndex = {}; /** Cache the loadRegionID promises so they are not regenerated each time until this._regions is defined. */ private _loadRegionIDsPromises: Promise<any>[] | undefined = undefined; /** Flag to indicate if loadRegionID has finished */ @observable private _loaded = false; get loaded() { return this._loaded; } constructor( regionType: string, properties: RegionProvierOptions, corsProxy: CorsProxy ) { this.regionType = regionType; this.corsProxy = corsProxy; this.regionProp = properties.regionProp; this.nameProp = properties.nameProp; this.description = properties.description; this.layerName = properties.layerName; this.server = properties.server; this.serverSubdomains = properties.serverSubdomains; this.serverMinZoom = defaultValue(properties.serverMinZoom, 0); this.serverMaxZoom = defaultValue(properties.serverMaxZoom, Infinity); this.serverMaxNativeZoom = defaultValue( properties.serverMaxNativeZoom, this.serverMaxZoom ); this.bbox = properties.bbox; this.aliases = defaultValue(properties.aliases, [this.regionType]); this.serverReplacements = properties.serverReplacements instanceof Array ? properties.serverReplacements.map(function(r) { return [ r[0], r[1].toLowerCase(), new RegExp(r[0].toLowerCase(), "gi") ]; }) : []; this.dataReplacements = properties.dataReplacements instanceof Array ? properties.dataReplacements.map(function(r) { return [ r[0], r[1].toLowerCase(), new RegExp(r[0].toLowerCase(), "gi") ]; }) : []; this.disambigProp = properties.disambigProp; this.uniqueIdProp = defaultValue(properties.uniqueIdProp, "FID"); this.textCodes = defaultValue(properties.textCodes, false); // yes, it's singular... this.regionIdsFile = properties.regionIdsFile; this.regionDisambigIdsFile = properties.regionDisambigIdsFile; } setDisambigProperties(dp: RegionProvider | undefined) { this.disambigDataReplacements = dp?.dataReplacements; this.disambigServerReplacements = dp?.serverReplacements; this.disambigAliases = dp?.aliases; } /** * Given an entry from the region mapping config, load the IDs that correspond to it, and possibly the disambiguation properties. */ @action async loadRegionIDs() { try { if (this._regions.length > 0) { return; // already loaded, so return insta-promise. } if (this.server === undefined) { // technically this may not be a problem yet, but it will be when we want to actually fetch tiles. throw new DeveloperError( "No server for region mapping defined: " + this.regionType ); } // Check for a pre-calculated promise (which may not have resolved yet), and returned that if it exists. if (!isDefined(this._loadRegionIDsPromises)) { const fetchAndProcess = async ( idListFile: string, disambig: boolean ) => { if (!isDefined(idListFile)) { return; } this.processRegionIds((await loadJson(idListFile)).values, disambig); }; this._loadRegionIDsPromises = [ fetchAndProcess(this.regionIdsFile, false), fetchAndProcess(this.regionDisambigIdsFile, true) ]; } await Promise.all(this._loadRegionIDsPromises); } catch (e) { console.log(`Failed to load region IDS for ${this.regionType}`); } finally { runInAction(() => (this._loaded = true)); } } /** * Returns the region variable of the given name, matching against the aliases provided. * * @param {string[]} varNames Array of variable names. * @returns {string} The name of the first column that matches any of the given aliases. */ findRegionVariable(varNames: string[]) { return findVariableForAliases(varNames, [this.regionType, ...this.aliases]); } /** * If a disambiguation column is known for this provider, return a column matching its description. * * @param {string[]} varNames Array of variable names. * @returns {string} The name of the first column that matches any of the given disambiguation aliases. */ findDisambigVariable(varNames: string[]) { if (!isDefined(this.disambigAliases) || this.disambigAliases.length === 0) { return undefined; } return findVariableForAliases(varNames, this.disambigAliases); } /** * Given a list of region IDs in feature ID order, apply server replacements if needed, and build the this._regions array. * If no propertyName is supplied, also builds this._idIndex (a lookup by attribute for performance). * @param {Array} values An array of string or numeric region IDs, eg. [10050, 10110, 10150, ...] or ['2060', '2061', '2062', ...] * @param {boolean} disambig True if processing region IDs for disambiguation */ processRegionIds(values: number[] | string[], disambig: boolean) { // There is also generally a `layer` and `property` property in this file, which we ignore for now. values.forEach((value: string | number | undefined, index: number) => { if (!isDefined(this._regions[index])) { this._regions[index] = {}; } let valueAfterReplacement = value; if (typeof valueAfterReplacement === "string") { // we apply server-side replacements while loading. If it ever turns out we need // to store the un-regexed version, we should add a line here. valueAfterReplacement = this.applyReplacements( valueAfterReplacement.toLowerCase(), disambig ? "disambigServerReplacements" : "serverReplacements" ); } // If disambig IDS - only set this._regions properties - not this._index properties if (disambig) { this._regions[index].disambigProp = value; this._regions[ index ].disambigPropWithServerReplacement = valueAfterReplacement; } else { this._regions[index].regionProp = value; this._regions[ index ].regionPropWithServerReplacement = valueAfterReplacement; // store a lookup by attribute, for performance. // This is only used for region prop (not disambig prop) if (isDefined(value) && isDefined(valueAfterReplacement)) { // If value is different after replacement, then also add original value for _index if (value !== valueAfterReplacement) { this._idIndex[value] = index; } if (!isDefined(this._idIndex[valueAfterReplacement])) { this._idIndex[valueAfterReplacement] = index; } else { // if we have already seen this value before, store an array of values, not one value. if (Array.isArray(this._idIndex[valueAfterReplacement])) { (this._idIndex[valueAfterReplacement] as number[]).push(index); } else { this._idIndex[valueAfterReplacement] = [ this._idIndex[valueAfterReplacement] as number, index ]; } } // Here we make a big assumption that every region has a unique identifier (probably called FID), that it counts from zero, // and that regions are provided in sorted order from FID 0. We do this to avoid having to explicitly request // the FID column, which would double the amount of traffic per region dataset. // It is needed to simplify reverse lookups from complex matches (regexes and disambigs) this._regions[index].fid = index; } } }); } /** * Apply an array of regular expression replacements to a string. Also caches the applied replacements in regionProvider._appliedReplacements. * @param {String} s The string. * @param {String} replacementsProp Name of a property containing [ [ regex, replacement], ... ], where replacement is a string which can contain '$1' etc. */ applyReplacements( s: string | number, replacementsProp: ReplacementVar ): string { let r: string; if (typeof s === "number") { r = String(s); } else { r = s.toLowerCase().trim(); } let replacements = this[replacementsProp]; if (replacements === undefined || replacements.length === 0) { return r; } if (this._appliedReplacements[replacementsProp][r] !== undefined) { return this._appliedReplacements[replacementsProp][r]; } replacements.forEach(function(rep: any) { r = r.replace(rep[2], rep[1]); }); this._appliedReplacements[replacementsProp][s] = r; return r; } /** * Given a region code, try to find a region that matches it, using replacements, disambiguation, indexes and other wizardry. * @param {string | number} code Code to search for. Falsy codes return -1. * @param {string | number | undefined} disambigCode Code to use if disambiguation is necessary * @returns {Number} Zero-based index in list of regions if successful, or -1. */ findRegionIndex( code: string | number, disambigCode: string | number | undefined ): number { if (!isDefined(code) || code === "") { // Note a code of 0 is ok return -1; } const codeAfterReplacement = this.applyReplacements( code, "dataReplacements" ); let id = this._idIndex[code]; let idAfterReplacement = this._idIndex[codeAfterReplacement]; if (!isDefined(id) && !isDefined(idAfterReplacement)) { return -1; } if (typeof id === "number") { // found an unambiguous match (without replacement) return id; } else if (typeof idAfterReplacement === "number") { // found an unambiguous match (with replacement) return idAfterReplacement; } else { const ids = id ?? idAfterReplacement; // found an ambiguous match if (!isDefined(disambigCode)) { // we have an ambiguous value, but nothing with which to disambiguate. We pick the first, warn. console.warn( "Ambiguous value found in region mapping: " + codeAfterReplacement ?? code ); return ids[0]; } if (this.disambigProp) { const processedDisambigCode = this.applyReplacements( disambigCode, "disambigDataReplacements" ); // Check out each of the matching IDs to see if the disambiguation field matches the one we have. for (let i = 0; i < ids.length; i++) { if ( this._regions[ids[i]].disambigProp === processedDisambigCode || this._regions[ids[i]].disambigPropWithServerReplacement === processedDisambigCode ) { return ids[i]; } } } } return -1; } } function findVariableForAliases(varNames: string[], aliases: string[]) { for (let j = 0; j < aliases.length; j++) { const re = new RegExp("^" + aliases[j] + "$", "i"); for (let i = 0; i < varNames.length; i++) { if (re.test(varNames[i])) { return varNames[i]; } } } return undefined; }
the_stack
interface KeyMap { [key: number]: string; } interface CtrlKeyMap { [key: string]: string; } interface ActionEvent { type: string; } interface HotkeyCallbacks { [key: string]: HotkeyCallbackCfg[]; } interface HotkeyDirectMap { [key: string]: HotkeyCallback; } export type HotkeyCallback = (e: KeyboardEvent, combo?: string) => any | false; interface HotkeyCallbackCfg { callback: HotkeyCallback; modifiers: string[]; action: string; seq?: string; level?: number; combo?: string; } interface KeyInfo { key: string; modifiers: string[]; action: string; } interface SequenceLevels { [key: string]: number; } const MAP: KeyMap = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta', }; const KEYCODE_MAP: KeyMap = { 106: '*', 107: '+', 109: '-', 110: '.', 111: '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: "'", }; const SHIFT_MAP: CtrlKeyMap = { '~': '`', '!': '1', '@': '2', '#': '3', $: '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', _: '-', '+': '=', ':': ';', '"': "'", '<': ',', '>': '.', '?': '/', '|': '\\', }; const SPECIAL_ALIASES: CtrlKeyMap = { option: 'alt', command: 'meta', return: 'enter', escape: 'esc', plus: '+', mod: /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl', }; let REVERSE_MAP: CtrlKeyMap; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (let i = 1; i < 20; ++i) { MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (let i = 0; i <= 9; ++i) { MAP[i + 96] = String(i); } /** * takes the event and returns the key character */ function characterFromEvent(e: KeyboardEvent): string { const keyCode = e.keyCode || e.which; // for keypress events we should return the character as is if (e.type === 'keypress') { let character = String.fromCharCode(keyCode); // if the shift key is not pressed then it is safe to assume // that we want the character to be lowercase. this means if // you accidentally have caps lock on then your key bindings // will continue to work // // the only side effect that might not be desired is if you // bind something like 'A' cause you want to trigger an // event when capital A is pressed caps lock will no longer // trigger the event. shift+a will though. if (!e.shiftKey) { character = character.toLowerCase(); } return character; } // for non keypress events the special maps are needed if (MAP[keyCode]) { return MAP[keyCode]; } if (KEYCODE_MAP[keyCode]) { return KEYCODE_MAP[keyCode]; } // if it is not in the special map // with keydown and keyup events the character seems to always // come in as an uppercase character whether you are pressing shift // or not. we should make sure it is always lowercase for comparisons return String.fromCharCode(keyCode).toLowerCase(); } interface KeypressEvent extends KeyboardEvent { type: 'keypress'; } function isPressEvent(e: KeyboardEvent | ActionEvent): e is KeypressEvent { return e.type === 'keypress'; } export function isFormEvent(e: KeyboardEvent) { const t = e.target as HTMLFormElement; if (!t) { return false; } if (t.form || /^(INPUT|SELECT|TEXTAREA)$/.test(t.tagName)) { return true; } if (/write/.test(window.getComputedStyle(t).getPropertyValue('-webkit-user-modify'))) { return true; } return false; } /** * checks if two arrays are equal */ function modifiersMatch(modifiers1: string[], modifiers2: string[]): boolean { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * takes a key event and figures out what the modifiers are */ function eventModifiers(e: KeyboardEvent): string[] { const modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * determines if the keycode specified is a modifier key or not */ function isModifier(key: string): boolean { return key === 'shift' || key === 'ctrl' || key === 'alt' || key === 'meta'; } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function getReverseMap(): CtrlKeyMap { if (!REVERSE_MAP) { REVERSE_MAP = {}; for (const key in MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (Number(key) > 95 && Number(key) < 112) { continue; } if (MAP.hasOwnProperty(key)) { REVERSE_MAP[MAP[key]] = key; } } } return REVERSE_MAP; } /** * picks the best action based on the key combination */ function pickBestAction(key: string, modifiers: string[], action?: string): string { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action === 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * Converts from a string key combination to an array * * @param {string} combination like "command+shift+l" * @return {Array} */ function keysFromString(combination: string): string[] { if (combination === '+') { return ['+']; } combination = combination.replace(/\+{2}/g, '+plus'); return combination.split('+'); } /** * Gets info for a specific key combination * * @param combination key combination ("command+s" or "a" or "*") */ function getKeyInfo(combination: string, action?: string): KeyInfo { let keys: string[] = []; let key = ''; let i: number; const modifiers: string[] = []; // take the keys from this pattern and figure out what the actual // pattern is all about keys = keysFromString(combination); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (SPECIAL_ALIASES[key]) { key = SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action !== 'keypress' && SHIFT_MAP[key]) { key = SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = pickBestAction(key, modifiers, action); return { key, modifiers, action, }; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event */ function fireCallback(callback: HotkeyCallback, e: KeyboardEvent, combo?: string, sequence?: string): void { if (callback(e, combo) === false) { e.preventDefault(); e.stopPropagation(); } } export default class Hotkey { private callBacks: HotkeyCallbacks = {}; private directMap: HotkeyDirectMap = {}; private sequenceLevels: SequenceLevels = {}; private resetTimer: number = 0; private ignoreNextKeyup: boolean | string = false; private ignoreNextKeypress: boolean = false; private nextExpectedAction: boolean | string = false; mount(window: Window) { const document = window.document; const handleKeyEvent = this.handleKeyEvent.bind(this); document.addEventListener('keypress', handleKeyEvent, false); document.addEventListener('keydown', handleKeyEvent, false); document.addEventListener('keyup', handleKeyEvent, false); return () => { document.removeEventListener('keypress', handleKeyEvent, false); document.removeEventListener('keydown', handleKeyEvent, false); document.removeEventListener('keyup', handleKeyEvent, false); }; } bind(combos: string[] | string, callback: HotkeyCallback, action?: string): Hotkey { this.bindMultiple(Array.isArray(combos) ? combos : [combos], callback, action); return this; } /** * resets all sequence counters except for the ones passed in */ private resetSequences(doNotReset?: SequenceLevels): void { // doNotReset = doNotReset || {}; let activeSequences = false; let key = ''; for (key in this.sequenceLevels) { if (doNotReset && doNotReset[key]) { activeSequences = true; } else { this.sequenceLevels[key] = 0; } } if (!activeSequences) { this.nextExpectedAction = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action */ private getMatches( character: string, modifiers: string[], e: KeyboardEvent | ActionEvent, sequenceName?: string, combination?: string, level?: number, ): HotkeyCallbackCfg[] { let i: number; let callback: HotkeyCallbackCfg; const matches: HotkeyCallbackCfg[] = []; const action: string = e.type; // if there are no events related to this keycode if (!this.callBacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action === 'keyup' && isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < this.callBacks[character].length; ++i) { callback = this.callBacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && this.sequenceLevels[callback.seq] !== callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action !== callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((isPressEvent(e) && !e.metaKey && !e.ctrlKey) || modifiersMatch(modifiers, callback.modifiers)) { const deleteCombo = !sequenceName && callback.combo === combination; const deleteSequence = sequenceName && callback.seq === sequenceName && callback.level === level; if (deleteCombo || deleteSequence) { this.callBacks[character].splice(i, 1); } matches.push(callback); } } return matches; } private handleKey(character: string, modifiers: string[], e: KeyboardEvent): void { const callbacks: HotkeyCallbackCfg[] = this.getMatches(character, modifiers, e); let i: number; const doNotReset: SequenceLevels = {}; let maxLevel = 0; let processedSequenceCallback = false; // Calculate the maxLevel for sequences so we can only execute the longest callback sequence for (i = 0; i < callbacks.length; ++i) { if (callbacks[i].seq) { maxLevel = Math.max(maxLevel, callbacks[i].level || 0); } } // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { // only fire callbacks for the maxLevel to prevent // subsequences from also firing // // for example 'a option b' should not cause 'option b' to fire // even though 'option b' is part of the other sequence // // any sequences that do not match here will be discarded // below by the resetSequences call if (callbacks[i].level !== maxLevel) { continue; } processedSequenceCallback = true; // keep a list of which sequences were matches for later doNotReset[callbacks[i].seq || ''] = 1; fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processedSequenceCallback) { fireCallback(callbacks[i].callback, e, callbacks[i].combo); } } const ignoreThisKeypress = e.type === 'keypress' && this.ignoreNextKeypress; if (e.type === this.nextExpectedAction && !isModifier(character) && !ignoreThisKeypress) { this.resetSequences(doNotReset); } this.ignoreNextKeypress = processedSequenceCallback && e.type === 'keydown'; } private handleKeyEvent(e: KeyboardEvent): void { const character = characterFromEvent(e); // no character found then stop if (!character) { return; } // need to use === for the character check because the character can be 0 if (e.type === 'keyup' && this.ignoreNextKeyup === character) { this.ignoreNextKeyup = false; return; } this.handleKey(character, eventModifiers(e), e); } private resetSequenceTimer(): void { if (this.resetTimer) { clearTimeout(this.resetTimer); } this.resetTimer = window.setTimeout(this.resetSequences, 1000); } private bindSequence(combo: string, keys: string[], callback: HotkeyCallback, action?: string): void { // const self: any = this; this.sequenceLevels[combo] = 0; const increaseSequence = (nextAction: string) => { return () => { this.nextExpectedAction = nextAction; ++this.sequenceLevels[combo]; this.resetSequenceTimer(); }; }; const callbackAndReset = (e: KeyboardEvent): void => { fireCallback(callback, e, combo); if (action !== 'keyup') { this.ignoreNextKeyup = characterFromEvent(e); } setTimeout(this.resetSequences, 10); }; for (let i = 0; i < keys.length; ++i) { const isFinal = i + 1 === keys.length; const wrappedCallback = isFinal ? callbackAndReset : increaseSequence(action || getKeyInfo(keys[i + 1]).action); this.bindSingle(keys[i], wrappedCallback, action, combo, i); } } private bindSingle( combination: string, callback: HotkeyCallback, action?: string, sequenceName?: string, level?: number, ): void { // store a direct mapped reference for use with HotKey.trigger this.directMap[`${combination}:${action}`] = callback; // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); const sequence: string[] = combination.split(' '); let info: KeyInfo; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { this.bindSequence(combination, sequence, callback, action); return; } info = getKeyInfo(combination, action); // make sure to initialize array if this is the first time // a callback is added for this key this.callBacks[info.key] = this.callBacks[info.key] || []; // remove an existing match if there is one this.getMatches(info.key, info.modifiers, { type: info.action }, sequenceName, combination, level); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first this.callBacks[info.key][sequenceName ? 'unshift' : 'push']({ callback, modifiers: info.modifiers, action: info.action, seq: sequenceName, level, combo: combination, }); } private bindMultiple(combinations: string[], callback: HotkeyCallback, action?: string) { for (const item of combinations) { this.bindSingle(item, callback, action); } } }
the_stack
import { Collection, Db, DBRef as MongodbDBRef, Long as MongodbLong, MaxKey as MongodbMaxKey, MinKey as MongodbMinKey, MongoClientOptions, ObjectId as MongodbObjectId, Timestamp as MongodbTimestamp } from 'mongodb'; import { Action, ActionTypes, CreatedAction, Database, DBRef, Long, MaxKey, MinKey, Model, ModelClass, ObjectId, Plugin, PluginNext, PluginStore, Query, ReducerModifier, ReducerState, RefreshedAction, RemovedAction, State, Timestamp, UpdatedAction } from 'mongorito'; const URL = `192.168.99.100:27017`; // "jest" dependency declare function describe(description: string, callback: () => void): void; declare function it(description: string, callback: (() => void) | (() => Promise<void>)): void; declare function expect(obj: any): any; function expectToBeAModelClass(obj: ModelClass) { expect(obj).toBeInstanceOf(Function); expect(obj).toHaveProperty('constructor'); expect(obj).toHaveProperty('database'); // static field set by "Database.register()" call } function expectToBeAPluginStore(obj: PluginStore) { expect(obj.dispatch).toBeInstanceOf(Function); expect(obj.getState).toBeInstanceOf(Function); const storeState: State = obj.getState(); expectToBeAState(storeState); expectToBeAModelClass(obj.modelClass); expect(obj.model).toBeInstanceOf(Model); } function expectToBeAState(obj: State) { expect(obj).toHaveProperty('unset'); expect(Array.isArray(obj.unset)).toBe(true); expect(obj).toHaveProperty('fields'); expect(obj.fields).toBeInstanceOf(Object); } function expectToBeAQuery(obj: Query) { expectToBeAModelClass(obj.Model); expect(Array.isArray(obj.query)).toBe(true); } function expectToBeAAction(obj: Action) { expect(obj).toBeInstanceOf(Object); expect(typeof obj.type).toBe("string"); } function expectToBeACreatedAction(obj: CreatedAction | UpdatedAction) { expect(obj).toBeInstanceOf(Object); expect(obj.type).toEqual(ActionTypes.CREATED); expect((obj as any).id).toBeInstanceOf(ObjectId); } function expectToBeAUpdatedAction(obj: CreatedAction | UpdatedAction) { expect(obj).toBeInstanceOf(Object); expect(obj.type).toEqual(ActionTypes.UPDATED); expect((obj as any).fields).toBeInstanceOf(Object); } function expectToBeARefreshedAction(obj: RefreshedAction) { expect(obj).toBeInstanceOf(Object); expect(obj.type).toEqual(ActionTypes.REFRESHED); expect(obj.fields).toBeInstanceOf(Object); } function expectToBeARemovedAction(obj: RemovedAction) { expect(obj).toBeInstanceOf(Object); expect(obj.type).toEqual(ActionTypes.REMOVED); } function expectToBeACollection(obj: Collection) { // expect(obj).toBeInstanceOf(Object); expect(typeof obj.collectionName).toBe("string"); expect(typeof obj.namespace).toBe("string"); // expect(obj).toHaveProperty("writeConcern"); // expect(obj).toHaveProperty("readConcern"); // expect(obj).toHaveProperty("hint"); } describe('mongorito', () => { const plugin1: Plugin = (modelClass: ModelClass) => (store: PluginStore) => (next: PluginNext) => (action: Action) => { // next(action); }; const plugin2: Plugin = (modelClass: ModelClass) => (store: PluginStore) => (next: PluginNext) => (action: Action) => { // next(action); }; const plugin3: Plugin = (modelClass: ModelClass) => (store: PluginStore) => (next: PluginNext) => (action: Action) => { // next(action); }; it('Plugin', async () => { const plugin: Plugin = (modelClass: ModelClass) => { expectToBeAModelClass(modelClass); return (store: PluginStore) => { expectToBeAPluginStore(store); return (next: PluginNext) => { expect(next).toBeInstanceOf(Function); return (action: Action) => { expectToBeAAction(action); // next(action); }; }; }; }; const database = new Database(URL); await database.connect(); class PluggedModel extends Model { } database.register(PluggedModel); PluggedModel.use(plugin); const obj: Model = new PluggedModel({attr: 42}); await obj.save(); }); it('Database', async () => { // ----- constructor ----- new Database(URL); const options: MongoClientOptions = {}; const database = new Database(URL, options); new Database(URL); new Database(['other', URL]); new Database(['other', URL], options); // ----- connect ----- const connectResultPromise: Promise<Db> = database.connect(); expect(connectResultPromise).toBeInstanceOf(Promise); const connectResult: Db = await connectResultPromise; expect(connectResult).toBeInstanceOf(Db); // ----- connection ----- const connectionResultPromise: Promise<Db> = database.connection(); expect(connectionResultPromise).toBeInstanceOf(Promise); const connectionResult: Db = await connectionResultPromise; expect(connectionResult).toBeInstanceOf(Db); // ----- disconnect ----- const disconnectResultPromise: Promise<void> = database.disconnect(); expect(disconnectResultPromise).toBeInstanceOf(Promise); // expect(await disconnectResultPromise).toBeUndefined(); await disconnectResultPromise; // $ExpectType void // ----- register ----- class RegisteredModel extends Model { constructor(fields?: object) { super(fields); } } class RegisteredModelA extends Model { constructor(fields?: object) { super(fields); } } class RegisteredModelB extends Model { constructor(fields?: object) { super(fields); } } // expect(database.register(RegisteredModel)).toBeUndefined(); database.register(RegisteredModel); // $ExpectType void // expect(database.register([RegisteredModelA, RegisteredModelB])).toBeUndefined(); database.register([RegisteredModelA, RegisteredModelB]); // $ExpectType void // ----- use ----- // expect(database.use(plugin1)).toBeUndefined(); database.use(plugin1); // $ExpectType void // expect(database.use([plugin2, plugin3])).toBeUndefined(); database.use([plugin2, plugin3]); // $ExpectType void }); describe('Model', () => { it('base static', async () => { const database = new Database(URL); await database.connect(); class Sample extends Model { constructor(fields?: object) { super(fields); } } database.register(Sample); const fieldOrSpec = 'any'; // ----- getConnection ----- const getConnectionResultPromise: Promise<Db> = Sample.getConnection(); expect(getConnectionResultPromise).toBeInstanceOf(Promise); const getConnectionResult: Db = await getConnectionResultPromise; expect(getConnectionResult).toBeInstanceOf(Db); // ----- getCollection ----- const getCollectionResultPromise: Promise<Collection<any>> = Sample.getCollection(); expect(getCollectionResultPromise).toBeInstanceOf(Promise); const getCollectionResult: Collection<any> = await getCollectionResultPromise; expectToBeACollection(getCollectionResult); // ----- use ----- // expect(Sample.use(plugin1)).toBeUndefined(); // expect(Sample.use([plugin2, plugin3])).toBeUndefined(); // ----- modifyReducer ----- const reducer: ReducerModifier = (reducerState: ReducerState) => { expect(reducerState.unset).toBeInstanceOf(Function); expect(reducerState.fields).toBeInstanceOf(Function); return reducerState; }; // expect(Sample.modifyReducer(reducer)).toBeUndefined(); Sample.modifyReducer(reducer); // $ExpectType void // ----- query ----- await new Sample({attr: 'first'}).save(); await new Sample({attr: 'second'}).save(); const method = 'find'; const query: Array<[string, any]> = [ ['where', {attr: {$exists: true}}], ['limit', 5] ]; const queryResultPromise: Promise<object[]> = Sample.query(method, query); expect(queryResultPromise).toBeInstanceOf(Promise); const queryResult: object[] = await queryResultPromise; expect(Array.isArray(queryResult)).toBe(true); expect(queryResult.length).toBeGreaterThan(0); queryResult.forEach(x => expect(x).toBeInstanceOf(Object)); // ----- listIndexes ----- const listIndexesResultPromise: Promise<any[]> = Sample.listIndexes(); expect(listIndexesResultPromise).toBeInstanceOf(Promise); const listIndexesResult: any[] = await listIndexesResultPromise; expect(Array.isArray(listIndexesResult)).toBe(true); listIndexesResult.forEach(x => expect(x).not.toBeUndefined()); // ----- createIndex ----- const createIndexResultPromise: Promise<string> = Sample.createIndex(fieldOrSpec); expect(createIndexResultPromise).toBeInstanceOf(Promise); const createIndexResult: string = await createIndexResultPromise; expect(typeof createIndexResult).toBe('string'); // ----- dropIndex ----- const dropIndexResultPromise: Promise<object> = Sample.dropIndex(createIndexResult); expect(dropIndexResultPromise).toBeInstanceOf(Promise); const dropIndexResult: object = await dropIndexResultPromise; expect(dropIndexResult).not.toBeUndefined(); // ----- embeds ----- class EmbeddedModel extends Model { } const key = 'any'; const model: ModelClass = EmbeddedModel; // expect(Sample.embeds(key, model)).toBeUndefined(); Sample.embeds(key, model); // $ExpectType void }); it('base', async () => { const database = new Database(URL); await database.connect(); class Sample extends Model { constructor(fields?: object) { super(fields); } } database.register(Sample); // ----- constructor ----- const fields: object = {views: 5, comments: 2}; const model = new Sample(fields); new Sample(); // ----- collection ----- const collectionResult: string = model.collection(); expect(typeof collectionResult).toBe('string'); // ----- getConnection ----- const getConnectionResultPromise: Promise<Db> = model.getConnection(); expect(getConnectionResultPromise).toBeInstanceOf(Promise); const getConnectionResult: Db = await getConnectionResultPromise; expect(getConnectionResult).toBeInstanceOf(Db); // ----- getCollection ----- const getCollectionResultPromise: Promise<Collection<any>> = model.getCollection(); expect(getCollectionResultPromise).toBeInstanceOf(Promise); const getCollectionResult: Collection<any> = await getCollectionResultPromise; expectToBeACollection(getCollectionResult); // ----- set ----- const key = 'attr'; const key2 = 'attr2'; const key3 = 'attr3'; // expect(model.set(key, 'val')).toBeUndefined(); model.set(key, 'val'); // $ExpectType void // expect(model.set({key2: 'val1', key3: 'val2'})).toBeUndefined(); model.set({key2: 'val1', key3: 'val2'}); // $ExpectType void // ----- get ----- const getResult1: any = model.get(key); expect(getResult1).not.toBeUndefined(); const getResult2: any = model.get(); expect(getResult2).not.toBeUndefined(); // ----- unset ----- // expect(model.unset(key)).toBeUndefined(); model.unset(key); // $ExpectType void const keys: string[] = [key2, key3]; // expect(model.unset(keys)).toBeUndefined(); model.unset(keys); // $ExpectType void // ----- toJSON ----- const toJSONResult: object = model.toJSON(); expect(toJSONResult).toBeInstanceOf(Object); // ----- isSaved ----- const isSavedResult: boolean = model.isSaved(); expect(typeof isSavedResult).toBe('boolean'); // ----- save ----- const save1ResultPromise: Promise<CreatedAction | UpdatedAction> = model.save(); expect(save1ResultPromise).toBeInstanceOf(Promise); const save1Result: CreatedAction | UpdatedAction = await save1ResultPromise; expectToBeACreatedAction(save1Result); const save2ResultPromise: Promise<CreatedAction | UpdatedAction> = model.save(); expect(save2ResultPromise).toBeInstanceOf(Promise); const save2Result: CreatedAction | UpdatedAction = await save2ResultPromise; expectToBeAUpdatedAction(save2Result); // ----- increment ----- const incrementResultPromise1: Promise<any> = model.increment('views'); expect(incrementResultPromise1).toBeInstanceOf(Promise); const incrementResult1: any = await incrementResultPromise1; expectToBeARefreshedAction(incrementResult1); const incrementResultPromise2: Promise<any> = model.increment('views', 2); expect(incrementResultPromise2).toBeInstanceOf(Promise); const incrementResult2: any = await incrementResultPromise2; expectToBeARefreshedAction(incrementResult2); const incrementResultPromise3: Promise<any> = model.increment({views: 10, comments: 3}); expect(incrementResultPromise3).toBeInstanceOf(Promise); const incrementResult3: any = await incrementResultPromise3; expectToBeARefreshedAction(incrementResult3); // ----- refresh ----- const refreshResultPromise: Promise<RefreshedAction> = model.refresh(); expect(refreshResultPromise).toBeInstanceOf(Promise); const refreshResult: RefreshedAction = await refreshResultPromise; expectToBeARefreshedAction(refreshResult); // ----- remove ----- const removeResultPromise: Promise<RemovedAction> = model.remove(); expect(removeResultPromise).toBeInstanceOf(Promise); const removeResult: RemovedAction = await removeResultPromise; expectToBeARemovedAction(removeResult); }); it('Query', async () => { const database = new Database(URL); await database.connect(); class Sample extends Model { constructor(fields?: object) { super(fields); } } database.register(Sample); const cas = new Sample(); await cas.save(); const ID = cas.get('_id'); const query: object = {_id: ID}; // ----- find ----- const findResultPromise1: Promise<Sample[]> = Sample.find(); expect(findResultPromise1).toBeInstanceOf(Promise); const findResult1: Sample[] = await findResultPromise1; expect(Array.isArray(findResult1)).toBe(true); expect(findResult1[0]).toBeInstanceOf(Sample); const findResultPromise2: Promise<Sample[]> = Sample.find(query); expect(findResultPromise2).toBeInstanceOf(Promise); const findResult2: Sample[] = await findResultPromise2; expect(Array.isArray(findResult2)).toBe(true); expect(findResult2[0]).toBeInstanceOf(Sample); // ----- findOne ----- const findOneResultPromise1: Promise<Sample | null> = Sample.findOne(); expect(findOneResultPromise1).toBeInstanceOf(Promise); const findOneResult1: Sample | null = await findOneResultPromise1; expect(findOneResult1).toBeInstanceOf(Sample); const findOneResultPromise2: Promise<Sample | null> = Sample.findOne(query); expect(findOneResultPromise2).toBeInstanceOf(Promise); const findOneResult2: Sample | null = await findOneResultPromise2; expect(findOneResult2).toBeInstanceOf(Sample); // ----- findById ----- const findByIdResultPromise: Promise<Sample | null> = Sample.findById(ID); expect(findByIdResultPromise).toBeInstanceOf(Promise); const findByIdResult: Sample | null = await findByIdResultPromise; expect(findByIdResult).toBeInstanceOf(Sample); await Sample.findById(ID.toString()); // ----- count ----- const countResultPromise: Promise<number> = Sample.count(); expect(countResultPromise).toBeInstanceOf(Promise); const countResult: number = await countResultPromise; expect(typeof countResult).toBe('number'); await Sample.count(query); // ----- sort ----- const sortResult1: Query = Sample.sort('field-test'); expectToBeAQuery(sortResult1); const sortResult2: Query = Sample.sort({field: 1, test: -1}); expectToBeAQuery(sortResult2); // ----- include ----- const includeResult1: Query = Sample.include('field-test'); expectToBeAQuery(includeResult1); const includeResult2: Query = Sample.include({field: 1, test: -1}); expectToBeAQuery(includeResult2); // ----- exclude ----- const excludeResult1: Query = Sample.exclude('field-test'); expectToBeAQuery(excludeResult1); const excludeResult2: Query = Sample.exclude({field: 1, test: -1}); expectToBeAQuery(excludeResult2); // ----- remove ----- const removeResultPromise: Promise<object> = Sample.remove(); expect(removeResultPromise).toBeInstanceOf(Promise); const removeResult: object = await removeResultPromise; expect(removeResult).toBeInstanceOf(Object); await Sample.remove(query); }); }); it('Timestamp', async () => { const obj: Timestamp = new Timestamp(1, 9); expect(obj).toBeInstanceOf(Timestamp); expect(obj).toBeInstanceOf(MongodbTimestamp); }); it('ObjectId', async () => { const obj: ObjectId = new ObjectId(); expect(obj).toBeInstanceOf(ObjectId); expect(obj).toBeInstanceOf(MongodbObjectId); }); it('MinKey', async () => { const obj: MinKey = new MinKey(); expect(obj).toBeInstanceOf(MinKey); expect(obj).toBeInstanceOf(MongodbMinKey); }); it('MaxKey', async () => { const obj: MaxKey = new MaxKey(); expect(obj).toBeInstanceOf(MaxKey); expect(obj).toBeInstanceOf(MongodbMaxKey); }); it('DBRef', async () => { const obj: DBRef = new DBRef('namespace', new ObjectId()); expect(obj).toBeInstanceOf(DBRef); expect(obj).toBeInstanceOf(MongodbDBRef); }); it('Long', async () => { const obj: Long = new Long(1, 9); expect(obj).toBeInstanceOf(Long); expect(obj).toBeInstanceOf(MongodbLong); }); });
the_stack
import { jsx, css } from "@emotion/core"; import * as React from "react"; import { Text } from "./Text"; import VisuallyHidden from "@reach/visually-hidden"; import PropTypes from "prop-types"; import { alpha } from "./Theme/colors"; import { useUid } from "./Hooks/use-uid"; import { Theme } from "./Theme"; import { useTheme } from "./Theme/Providers"; import { getHeight, focusShadow } from "./Button"; import { IconAlertCircle, IconChevronDown } from "./Icons"; import { safeBind } from "./Hooks/compose-bind"; const getInputSizes = (theme: Theme) => ({ sm: css({ fontSize: theme.fontSizes[0], padding: "0.25rem 0.5rem" }), md: css({ fontSize: theme.fontSizes[1], padding: "0.5rem 0.75rem" }), lg: css({ fontSize: theme.fontSizes[2], padding: "0.65rem 1rem" }) }); export type InputSize = "sm" | "md" | "lg"; export interface InputGroupProps extends React.HTMLAttributes<HTMLDivElement> { id?: string; /** A label is required for accessibility purposes. Use `hideLabel` to hide it. */ label: string; /** Visually hide the label. It remains accessible to screen readers. */ hideLabel?: boolean; error?: string | React.ReactNode; /** Optional help text */ helpText?: string; /** A single input element */ children?: React.ReactNode; } interface InputGroupContextType { uid?: string; error?: string | React.ReactNode; } const InputGroupContext = React.createContext<InputGroupContextType>({ uid: undefined, error: undefined }); export const InputGroup: React.FunctionComponent<InputGroupProps> = ({ id, label, children, error, helpText, hideLabel, ...other }) => { const uid = useUid(id); const theme = useTheme(); const isDark = theme.colors.mode === "dark"; const danger = isDark ? theme.colors.intent.danger.light : theme.colors.intent.danger.base; return ( <div className="InputGroup" css={{ marginTop: theme.spaces.md, ":first-child": { marginTop: 0 } }} {...other} > <Label hide={hideLabel} htmlFor={uid}> {label} </Label> <InputGroupContext.Provider value={{ uid, error }} > {children} </InputGroupContext.Provider> {error && typeof error === "string" ? ( <div className="InputGroup__error" css={{ alignItems: "center", marginTop: theme.spaces.sm, display: "flex" }} > <IconAlertCircle size="sm" color={danger} /> <Text css={{ display: "block", marginLeft: theme.spaces.xs, fontSize: theme.fontSizes[0], color: danger }} > {error} </Text> </div> ) : ( error )} {helpText && ( <Text className="InputGroup__help" css={{ display: "block", marginTop: theme.spaces.xs, color: theme.colors.text.muted, fontSize: theme.fontSizes[0] }} variant="body" > {helpText} </Text> )} </div> ); }; InputGroup.propTypes = { label: PropTypes.string.isRequired, hideLabel: PropTypes.bool, helpText: PropTypes.string, error: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), id: PropTypes.string, children: PropTypes.node }; function shadowBorder(color: string, opacity: number) { return `0 0 0 2px transparent inset, 0 0 0 1px ${alpha( color, opacity )} inset`; } function getBaseStyles(theme: Theme) { const dark = theme.colors.mode === "dark"; const baseStyles = css({ display: "block", width: "100%", lineHeight: theme.lineHeights.body, color: theme.colors.text.default, backgroundColor: "transparent", backgroundImage: "none", backgroundClip: "padding-box", WebkitFontSmoothing: "antialiased", WebkitTapHighlightColor: "transparent", WebkitAppearance: "none", boxSizing: "border-box", touchAction: "manipulation", fontFamily: theme.fonts.base, border: "none", boxShadow: dark ? shadowBorder(theme.colors.palette.gray.lightest, 0.14) : shadowBorder(theme.colors.palette.gray.dark, 0.2), borderRadius: theme.radii.sm, transition: "background 0.25s cubic-bezier(0.35,0,0.25,1), border-color 0.15s cubic-bezier(0.35,0,0.25,1), box-shadow 0.15s cubic-bezier(0.35,0,0.25,1)", "::placeholder": { color: alpha(theme.colors.text.default, 0.45) }, ":focus": { boxShadow: dark ? focusShadow( alpha(theme.colors.palette.blue.light, 0.5), alpha(theme.colors.palette.gray.dark, 0.4), alpha(theme.colors.palette.gray.light, 0.2) ) : focusShadow( alpha(theme.colors.palette.blue.dark, 0.1), alpha(theme.colors.palette.gray.dark, 0.2), alpha(theme.colors.palette.gray.dark, 0.05) ), outline: "none" }, ":disabled": { opacity: dark ? 0.4 : 0.8, background: theme.colors.background.tint1, cursor: "not-allowed", boxShadow: dark ? shadowBorder(theme.colors.palette.gray.lightest, 0.15) : shadowBorder(theme.colors.palette.gray.dark, 0.12) }, ":active": { background: theme.colors.background.tint1 } }); return baseStyles; } function useActiveStyle() { const [active, setActive] = React.useState(false); return { bind: { onTouchStart: () => setActive(true), onTouchEnd: () => setActive(false) }, active }; } function useSharedStyle() { const theme = useTheme(); const errorStyles = { boxShadow: shadowBorder(theme.colors.intent.danger.base, 0.45) }; const baseStyles = React.useMemo(() => getBaseStyles(theme), [theme]); const inputSizes = React.useMemo(() => getInputSizes(theme), [theme]); const activeBackground = css({ background: theme.colors.background.tint1 }); return { baseStyles, inputSizes, activeBackground, errorStyles }; } export interface InputBaseProps extends React.InputHTMLAttributes<HTMLInputElement> { /** The size of the input element */ inputSize?: InputSize; } /** * Our basic Input element. Use this when building customized * forms. Otherwise, stick with InputGroup */ export const InputBase: React.RefForwardingComponent< React.Ref<HTMLInputElement>, InputBaseProps > = React.forwardRef( ( { autoComplete, autoFocus, inputSize = "md", ...other }: InputBaseProps, ref: React.Ref<HTMLInputElement> ) => { const { uid, error } = React.useContext(InputGroupContext); const { bind, active } = useActiveStyle(); const { baseStyles, inputSizes, activeBackground, errorStyles } = useSharedStyle(); const height = getHeight(inputSize); return ( <input id={uid} className="Input" autoComplete={autoComplete} autoFocus={autoFocus} {...bind} css={[ baseStyles, inputSizes[inputSize], active && activeBackground, error && errorStyles, { height } ]} {...safeBind({ ref }, other)} /> ); } ); InputBase.propTypes = { inputSize: PropTypes.oneOf(["sm", "md", "lg"] as InputSize[]), autoComplete: PropTypes.bool, autoFocus: PropTypes.bool }; export const Input = InputBase; export interface TextAreaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { /** The size of the textarea element */ inputSize?: InputSize; } /** * Textarea version of InputBase */ export const TextArea: React.FunctionComponent<TextAreaProps> = ({ inputSize = "md", ...other }) => { const { bind, active } = useActiveStyle(); const { baseStyles, inputSizes, activeBackground, errorStyles } = useSharedStyle(); const { uid, error } = React.useContext(InputGroupContext); return ( <textarea className="TextArea" id={uid} {...bind} css={[ baseStyles, inputSizes[inputSize], { overflow: "auto", resize: "vertical" }, active && activeBackground, error && errorStyles ]} {...other} /> ); }; TextArea.propTypes = { inputSize: PropTypes.oneOf(["sm", "md", "lg"] as InputSize[]) }; export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> { hide?: boolean; htmlFor: string; } /** * A styled Label to go along with input elements */ export const Label: React.FunctionComponent<LabelProps> = ({ children, hide, ...other }) => { const theme = useTheme(); const child = ( <label className="Label" css={{ display: "inline-block", marginBottom: hide ? 0 : theme.spaces.sm }} {...other} > <Text className="Label__text" variant={"subtitle"}> {children} </Text> </label> ); return hide ? <VisuallyHidden>{child}</VisuallyHidden> : child; }; Label.propTypes = { hide: PropTypes.bool, children: PropTypes.node }; export interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> { /** The size of the select box */ inputSize?: InputSize; } /** * A styled select menu */ export const Select: React.FunctionComponent<SelectProps> = ({ multiple, inputSize = "md", ...other }) => { const theme = useTheme(); const inputSizes = getInputSizes(theme); const { uid, error } = React.useContext(InputGroupContext); const selectSize = { sm: inputSizes.sm, md: inputSizes.md, lg: inputSizes.lg }; const dark = theme.colors.mode === "dark"; const height = getHeight(inputSize); return ( <div className="Select" css={{ position: "relative" }} > <select className="Select__input" id={uid} css={[ selectSize[inputSize], { WebkitAppearance: "none", display: "block", width: "100%", lineHeight: theme.lineHeights.body, height, color: theme.colors.text.default, background: "transparent", fontFamily: theme.fonts.base, boxShadow: `0 0 0 2px transparent inset, 0 0 0 1px ${ dark ? alpha(theme.colors.palette.gray.lightest, 0.14) : alpha(theme.colors.palette.gray.dark, 0.2) } inset`, border: "none", backgroundClip: "padding-box", borderRadius: theme.radii.sm, margin: 0, ":disabled": { ":disabled": { opacity: dark ? 0.4 : 0.8, background: theme.colors.background.tint1, cursor: "not-allowed", boxShadow: `0 0 0 2px transparent inset, 0 0 0 1px ${ dark ? alpha(theme.colors.palette.gray.lightest, 0.15) : alpha(theme.colors.palette.gray.dark, 0.12) } inset` } }, ":focus": { borderColor: theme.colors.palette.blue.base, boxShadow: dark ? focusShadow( alpha(theme.colors.palette.blue.light, 0.5), alpha(theme.colors.palette.gray.dark, 0.4), alpha(theme.colors.palette.gray.light, 0.2) ) : focusShadow( alpha(theme.colors.palette.blue.dark, 0.1), alpha(theme.colors.palette.gray.dark, 0.2), alpha(theme.colors.palette.gray.dark, 0.05) ), outline: 0 } }, error && { boxShadow: shadowBorder(theme.colors.intent.danger.base, 0.45) } ]} multiple={multiple} {...other} /> {!multiple && ( <IconChevronDown className="Select__icon" color={theme.colors.text.muted} css={{ position: "absolute", top: "50%", right: "0.75rem", transform: "translateY(-50%)", pointerEvents: "none" }} /> )} </div> ); }; Select.propTypes = { inputSize: PropTypes.oneOf(["sm", "md", "lg"]), multiple: PropTypes.bool }; export interface CheckProps extends React.InputHTMLAttributes<HTMLInputElement> { /** A label for the checkmark. */ label: string; } export const Check: React.FunctionComponent<CheckProps> = ({ label, id, disabled, ...other }) => { const uid = useUid(id); const theme = useTheme(); return ( <div className="Check" css={{ display: "flex", alignItems: "center" }} {...other} > <input disabled={disabled} className="Check__input" type="checkbox" id={uid} {...other} /> <label className="Check__label" css={{ opacity: disabled ? 0.6 : undefined, marginLeft: theme.spaces.xs }} htmlFor={uid} > <Text>{label}</Text> </label> </div> ); }; Check.propTypes = { label: PropTypes.string.isRequired, id: PropTypes.string, disabled: PropTypes.bool };
the_stack
import { Component, OnInit, NgModule, ViewChild } from "@angular/core"; import { TranslateService } from "@ngx-translate/core"; import { IdpService } from "../idp-service.service"; import { IdprestapiService } from "../idprestapi.service"; import { Router } from "@angular/router"; import { IdpdataService } from "../idpdata.service"; import { CookieService } from "ngx-cookie"; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service'; import { NgTableComponent, NgTableFilteringDirective, NgTablePagingDirective, NgTableSortingDirective } from "ng2-table/ng2-table"; import {DatePipe} from "@angular/common"; @Component({ selector: "app-show-config", templateUrl: "./show-config.component.html", styleUrls: ["./show-config.component.css"] }) export class ShowConfigurationsComponent implements OnInit { @ViewChild ("modalforAlertconfig") button; @ViewChild ("modalforDelete") modalforDelete; @ViewChild ("modalforDeleteAlert") msgAlertDel; reqData: any; schedule: any; data: any; isBuild: any = false; isDeploy: any = false; public rows: Array<any> = []; public columns: Array<any> = [ { title: "Application", name: "applicationName" }, { title: "Pipeline", name: "pipelineName", sort: 'asc' }, { title: "Creation Date", name: "creationDate", style: 'text-align: center'}, { title: "Trigger", name: "trigger", sort: false }, { title: "Schedule", name: "schedule", sort: false }, { title: "Copy", name: "copy", sort: false }, { title: "Edit", name: "edit", sort: false }, { title: "Delete", name: "delete", sort: false }, ]; public page = 1; public itemsPerPage = 10; public maxSize = 5; public numPages = 1; public length = 0; public config: any = { paging: true, sorting: { columns: this.columns }, filtering: { filterString: "" }, className: ["table-striped"] }; modalforDeleteRef: BsModalRef; modalForSuccessRef: BsModalRef; public constructor( private idpdataService: IdpdataService, private IdpService: IdpService, private IdprestapiService: IdprestapiService, private router: Router, private _cookieService: CookieService, private modalService: BsModalService, private datePipe:DatePipe ) { this.idpdataService.schedulePage = false; this.idpdataService.data = JSON.parse(JSON.stringify(this.idpdataService.template)); this.idpdataService.operation = ""; this.idpdataService.appName = ""; this.idpdataService.isRmsApp =false; // workflow remove this.idpdataService.workflowData = []; this.idpdataService.workflowDataTemp = []; this.callforRest(); } callforRest() { this.IdprestapiService.getData() .then(response => { try { if (response) { this.idpdataService.devServerURL = response.json().idpresturl; this.idpdataService.subscriptionServerURL = response.json().idpsubscriptionurl; this.idpdataService.buildUT = response.json().sapCharmBuildUT; //"In Development,To Be Tested"; this.idpdataService.buildCA = response.json().sapCharmBuildCA; //"To Be Tested,Successfully Tested"; this.idpdataService.buildCAUT = response.json().sapCharmBuildCAUT; //"In Development,To Be Tested,Successfully Tested"; this.idpdataService.IDPDashboardURL = response.json().idpdashboardurl; this.idpdataService.IDPLink = response.json().IDPLink; this.idpdataService.geUrl = response.json().geUrl; this.idpdataService.geFlag = response.json().geFlag; this.idpdataService.serverUrl = response.json().tfsServerUrl; this.idpdataService.uName = response.json().uName; this.idpdataService.pass = response.json().pass; if (this._cookieService.get("access_token")) { this.getPipelineData(); this.IdpService.getDetails(); } } } catch (e) { alert("failed to get properties details"); console.log(e); } }); } public ngOnInit(): void { } public changePage(page: any, data: Array<any> = this.data): Array<any> { const start = (page.page - 1) * page.itemsPerPage; const end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length; return data.slice(start, end); } public changeSort(data: any, config: any): any { if (!config.sorting) { return data; } const columns = this.config.sorting.columns || []; let columnName: string = void 0; let sort: string = void 0; for (let i = 0; i < columns.length; i++) { if (columns[i].sort !== "" && columns[i].sort !== false) { columnName = columns[i].name; sort = columns[i].sort; } } if (!columnName) { return data; } // simple sorting return data.sort((previous: any, current: any) => { if (previous[columnName] > current[columnName]) { return sort === "desc" ? -1 : 1; } else if (previous[columnName] < current[columnName]) { return sort === "asc" ? -1 : 1; } return 0; }); } public changeFilter(data: any, config: any): any { let filteredData: Array<any> = data; this.columns.forEach((column: any) => { if (column.filtering) { filteredData = filteredData.filter((item: any) => { return item[column.name].match(column.filtering.filterString); }); } }); if (!config.filtering) { return filteredData; } if (config.filtering.columnName) { return filteredData.filter((item: any) => item[config.filtering.columnName].toLowerCase().match(this.config.filtering.filterString.toLowerCase())); } const tempArray: Array<any> = []; filteredData.forEach((item: any) => { let flag = false; this.columns.forEach((column: any) => { if (item[column.name] !== undefined) { if (item[column.name].toString().toLowerCase().match(this.config.filtering.filterString.toLowerCase())) { flag = true; } } }); if (flag) { tempArray.push(item); } }); filteredData = tempArray; return filteredData; } public onChangeTable(config: any, page: any = { page: this.page, itemsPerPage: this.itemsPerPage }): any { if (config.filtering) { Object.assign(this.config.filtering, config.filtering); } if (config.sorting) { Object.assign(this.config.sorting, config.sorting); } const filteredData = this.changeFilter(this.data, this.config); const sortedData = this.changeSort(filteredData, this.config); this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData; this.length = sortedData.length; } public onCellClick(data: any): any { this.idpdataService.operation = ""; const indexStart = data.row.pipelineName.indexOf(">") + 1; const indexEnd = data.row.pipelineName.indexOf("</"); const pName = data.row.pipelineName.substring(indexStart, indexEnd); let reqData = { "applicationName": data.row.applicationName, "pipelineName": pName, "userName": this.idpdataService.idpUserName }; if (data.column === "pipelineName") { this.idpdataService.pipelineName = reqData.pipelineName; this.idpdataService.appName = reqData.applicationName; this.stageView(); } if (data.column === "trigger") { let trigger = true; for (let i = 0 ; i < this.idpdataService.pipelineData.length; i++) { if (data.row.pipelineName === this.idpdataService.pipelineData[i].pipelineName) { trigger = this.idpdataService.pipelineData[i].triggerFlag; break; } } this.idpdataService.pipelineName = reqData.pipelineName; this.idpdataService.appName = reqData.applicationName; if (data.column === "trigger" && trigger) { this.trigger(reqData); } } if (data.column === "schedule") { this.idpdataService.schedulePage = true; this.idpdataService.pipelineName = reqData.pipelineName; this.idpdataService.appName = reqData.applicationName; this.trigger(reqData); } if (data.column === "copy" || data.column === "edit") { let copy = true; let edit = true; for (let i = 0 ; i < this.idpdataService.pipelineData.length; i++) { if (data.row.pipelineName === this.idpdataService.pipelineData[i].pipelineName) { copy = this.idpdataService.pipelineData[i].copyFlag; edit = this.idpdataService.pipelineData[i].editFlag; break; } } if (data.column === "copy" && copy) { this.copyEdit(data.column,reqData); } else if (data.column === "edit" && edit) { this.copyEdit(data.column,reqData); } } if (data.column === "delete") { let delete1 = true ; for (let i = 0 ; i < this.idpdataService.pipelineData.length; i++) { if (data.row.pipelineName === this.idpdataService.pipelineData[i].pipelineName) { delete1 = this.idpdataService.pipelineData[i].deleteFlag; break; } } if (data.column === "delete" && delete1) { this.deleteAlert(reqData); } } if(data.column === "approve"){ let approve=true ; for(var i = 0 ;i <this.idpdataService.pipelineData.length;i++){ if(data.row.pipelineName===this.idpdataService.pipelineData[i].pipelineName){ approve=this.idpdataService.pipelineData[i].approveFlag; console.log(approve); break; } } this.idpdataService.appName=data.row.applicationName; this.idpdataService.pipelineName=pName; if(data.column==="approve" && approve){ this.router.navigate(['/previousConfig/approve']); } } } stageView() { this.router.navigate(["/previousConfig/stageviewHistory"]); } trigger(reqData) { this.checkApplicationType(reqData); this.trigger1(reqData); } trigger1(reqData) { this.IdprestapiService.triggerJob(reqData) .then(response => { try { if (response) { const result = response.json().resource; if (result !== "{}" && result !== null) { this.idpdataService.triggerJobData = JSON.parse(result); const temp = JSON.parse(result); const checkInBuild = this.idpdataService.triggerJobData.hasOwnProperty("build") && this.idpdataService.triggerJobData.build.approveBuild !== undefined && this.idpdataService.triggerJobData.build.approveBuild !== null && this.idpdataService.triggerJobData.build.approveBuild.length !== 0; const checkInDeploy = this.idpdataService.triggerJobData.hasOwnProperty("deploy") && this.idpdataService.triggerJobData.deploy.workEnvApprovalList !== undefined && this.idpdataService.triggerJobData.deploy.workEnvApprovalList !== null && Object.keys(this.idpdataService.triggerJobData.deploy.workEnvApprovalList).length !== 0 && this.idpdataService.triggerJobData.deploy.workEnvApprovalList.constructor === Object; if (checkInBuild || checkInDeploy) { this.idpdataService.checkPausedBuilds = true; if (checkInBuild) { this.isBuild = true; } if (checkInDeploy) { this.isDeploy = true; } } else { this.idpdataService.checkPausedBuilds = false; } if (this.idpdataService.triggerJobData.hasOwnProperty("systemNames") || this.idpdataService.triggerJobData.hasOwnProperty("userStory")) { this.idpdataService.isSAPApplication = true; if (this.idpdataService.triggerJobData.systemNames) { if (this.idpdataService.triggerJobData.systemNames.length !== 0) { this.idpdataService.checkpollALM = false; } else { alert("Failed to get SAP System Names"); } } else { this.idpdataService.checkpollALM = true; } } if (this.idpdataService.triggerJobData.applicationName) { const applicationName = this.idpdataService.triggerJobData.applicationName; if (this.idpdataService.isSAPApplication) { this.IdprestapiService.getLandscapesForSap(applicationName).then(response => { if (response) { if (response.json().resource !== "{}" && response.json().resource !== null) { const temp = response.json().resource; this.idpdataService.SAPEnvList = JSON.parse(temp).landscapes; } else { alert("Failed to get landscapes Names"); } } else { alert("Failed to get landscapes Names"); } }); } } if (this.idpdataService.triggerJobData.releaseNumber !== null && this.idpdataService.triggerJobData.releaseNumber.length !== 0) { if (this.idpdataService.triggerJobData.technology !== undefined && this.idpdataService.triggerJobData.technology === "workflow" && this.idpdataService.triggerJobData.pipelines !== undefined && this.idpdataService.triggerJobData.pipelines.length > 0) { this.idpdataService.workflowTrigger = true; this.router.navigate(["/previousConfig/workflowInfo"],{queryParams:{applicationName:reqData.applicationName,pipelineName:reqData.pipelineName}}); } else if (this.idpdataService.checkPausedBuilds === true) { if (this.idpdataService.triggerJobData.roles.indexOf("RELEASE_MANAGER") !== -1 && (this.isBuild === true || this.isDeploy === true)) { const forBuild = this.isBuild && this.idpdataService.approveBuildFlag; const forDeploy = this.isDeploy && this.idpdataService.approveDeployFlag; if (forBuild && forDeploy) { this.router.navigate(["/previousConfig/approveBuild"]); } if (forBuild) { if ((this.idpdataService.approveDeployFlag !== true)) { alert("You do no thave permission to approve build for Deploy Stage"); } this.router.navigate(["/previousConfig/approveBuild"]); } if (forDeploy) { if ((this.idpdataService.approveBuildFlag !== true)) { alert("You do no thave permission to approve build for Build Stage"); } this.router.navigate(["/previousConfig/approveBuild"]); } } else { alert("A build is waiting approval. Kindly contact your release manager."); } } else { const x = confirm("Please ensure slave is launched"); if (x) { if (this.idpdataService.schedulePage === true) { this.router.navigate(["/previousConfig/schedule"],{queryParams:{applicationName:reqData.applicationName,pipelineName:reqData.pipelineName}}); } else { this.router.navigate(["/previousConfig/trigger"],{queryParams:{applicationName:reqData.applicationName,pipelineName:reqData.pipelineName}}); } } } } else if (this.idpdataService.triggerJobData.roles.indexOf("RELEASE_MANAGER") !== -1) { alert("No active releases for this pipeline. Please add releases."); this.router.navigate(["/releaseConfig/release"]); } else { alert("No active releases for this pipeline. Please contact the release manager."); } } else { alert("Failed to get the Trigger Job Details"); } } } catch (e) { alert("Failed to get trigger details"); console.log(e); } }); } copyEdit(operation,reqData) { this.idpdataService.operation = operation; localStorage.setItem("appName", reqData.applicationName); localStorage.setItem("pipeName", reqData.pipelineName); const data = reqData.applicationName; this.checkApplicationType(reqData); this.router.navigate(["createConfig/basicInfo"]); } checkApplicationType(reqData) { const data = reqData.applicationName; this.IdprestapiService.checkForApplicationType(data).then(response => { try { if (response) { if (response.json().errorMessage === null && response.json().resource !== "") { if (response.json().resource === "true") { this.idpdataService.isSAPApplication = true; } else { this.idpdataService.isSAPApplication = false; } } else { alert("Failed to verify application Type"); } } } catch (e) { alert("Failed during verifying the application type"); } this.idpdataService.loading = false; }); } TriggerAlert() { this.button.nativeElement.click(); } deleteAlert(data) { this.modalforDeleteRef = this.modalService.show(this.modalforDelete); this.modalforDeleteRef.content = data; } delete(modalRef) { modalRef.hide(); this.IdprestapiService.deletePipeline(modalRef.content) .then(response => { try { if (response) { this.msgAlert(modalRef.content); this.getPipelineData(); } } catch (e) { alert("failed to delete the pipeline "); console.log(e); } }); } msgAlert(data) { this.modalForSuccessRef = this.modalService.show(this.msgAlertDel); this.modalForSuccessRef.content = data; } getPipelineData() { console.log(this.idpdataService.devServerURL); this.IdprestapiService.checkAvailableJobs() .then(response => { try { if (response) { const data = response.json().resource; if (data !== "No pipelines to trigger") { this.idpdataService.pipelineData = []; const maindata = JSON.parse(data).pipelineDetails; if (maindata && maindata.length !== 0) { for (let i = 0; i < maindata.length; i++) { maindata[i].creationDate = maindata[i].creationDate; this.idpdataService.pipelineData.push(maindata[i]); const tempPipeName = maindata[i].pipelineName; const permissions = maindata[i].permissions; const triggerPipeline = (permissions.indexOf("BUILD") === -1 && permissions.indexOf("DEPLOY") === -1 && permissions.indexOf("TEST") === -1) ? false : true; const copyPipeline = (permissions.indexOf("COPY_PIPELINE") === -1) ? false : true ; const editPipeline = (permissions.indexOf("EDIT_PIPELINE") === -1) ? false : true ; const deletePipeline = (permissions.indexOf("DELETE_PIPELINE") === -1) ? false : true ; const approveRelease = (this.idpdataService.role.indexOf("ENVIRONMENT_OWNER") === -1 || maindata[i].buildTool === "SapNonCharm" || maindata[i].buildTool === "workflow") ? false : true ; this.idpdataService.pipelineData[i].pipelineName = "<a style=\"cursor:pointer\">" + tempPipeName + "</a>"; this.idpdataService.pipelineData[i].trigger = '<div class="text-center field-tip">'+ maindata[i].creationDate +'</div>'; this.idpdataService.pipelineData[i].trigger = '<div class="text-center field-tip"><input TYPE="image" src="assets/images/build_now.png" id="TBN" name="TBN" /></div>'; this.idpdataService.pipelineData[i].copyFlag = copyPipeline; this.idpdataService.pipelineData[i].editFlag = editPipeline; this.idpdataService.pipelineData[i].deleteFlag = deletePipeline; this.idpdataService.pipelineData[i].approveFlag = approveRelease; this.idpdataService.pipelineData[i].triggerFlag = triggerPipeline; if (copyPipeline) { this.idpdataService.pipelineData[i].copy = `<div class="text-center"> <button class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/copy.svg" alt="copyPipelineBtn"/> </button> </div>`; } else { this.idpdataService.pipelineData[i].copy = `<div class="field-tip" style="cursor:not-allowed"> <button [disabled]="true" class="btn bg-transparent"> <i class="fa fa-icon fa-2x fa-copy text-secondary"></i> </button> <span class="tip-content hover-tip-content-copy text-center" style="z-index: 1;cursor:not-allowed;width:90px;zoom:83%;"> "Copy pipeline is not available </span> </div>`; } if (editPipeline) { this.idpdataService.pipelineData[i].edit = `<div class=\"text-center \"> <button class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/edit.svg" alt="editPipelineBtn"/> </button> </div>`; } else { this.idpdataService.pipelineData[i].edit = `<div class="field-tip" style="cursor:not-allowed"> <button [disabled]="true" class="btn bg-transparent"> <i class="fa fa-icon fa-2x fa-edit text-secondary"></i> </button> <span class="tip-content text-center" style="z-index: 1;cursor:not-allowed;width:70px;zoom:80%;"> Edit pipeline is not available </span> </div>`; } if (deletePipeline) { this.idpdataService.pipelineData[i].delete = `<div class="text-center"> <button class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/delete.svg" alt="deletePipelineBtn"/> </button> </div>`; } else { this.idpdataService.pipelineData[i].delete = `<div class=" field-tip" style="cursor:not-allowed"> <button [disabled]="true" class="btn bg-transparent"> <i class="fa fa-icon fa-2x fa-trash text-secondary"></i> </button> <span class="tip-content text-center" style="z-index: 1;cursor:not-allowed;width:78px;zoom:83%;"> Delete pipeline is not available </span> </div>`; } if (approveRelease) { this.idpdataService.pipelineData[i].approve = `<div class="text-center"> <button class="btn bg-transparent"> <i class="fa fa-icon fa-2x fa-check-circle text-primary"></i> </button> </div>`; } else { this.idpdataService.pipelineData[i].approve = `<div class="field-tip text-center" style="cursor:not-allowed"> <button [disabled]="true" class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/success_messages.svg" alt="successBtn"/> </button> <span class="tip-content text-center" style="z-index: 1;cursor:not-allowed;width:82%;zoom:86%;"> Approve artifacts is not available </span> </div>`; } if (triggerPipeline) { this.idpdataService.pipelineData[i].trigger = `<div class="text-center field-tip"> <button class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/trigger.svg" alt="trigger"/> </button> </div>`; } else { this.idpdataService.pipelineData[i].trigger = `<div class="field-tip" style="cursor:not-allowed" > <button [disabled]="true" class="btn bg-transparent"> <i class="fa fa-icon fa-2x fa-play-circle text-secondary"></i> </button> <span class="tip-content text-center" style="z-index: 1;cursor:not-allowed;width:70px;zoom:80%"> Trigger is not allowed for this user.</span> </div>`; } this.idpdataService.pipelineData[i].schedule = `<div class=\"text-center \"> <button class="btn bg-transparent"> <img class="idp-icon" src="assets/img/icon/schedule.svg" alt="schedulePipelineBtn"/> </button> </div>`; } this.data = this.idpdataService.pipelineData; this.length = this.data.length; this.onChangeTable(this.config); } } else { alert("No pipelines available"); } } } catch (e) { alert("failed to get the pipeline Details"); console.log(e); } }); } noAccessCheck() { if (this.idpdataService.noAccess) { return true; } else { return false; } } accessCheck() { if (!this.idpdataService.noAccess) { return true; } else { return false; } } }
the_stack
import { Injectable } from '@angular/core'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCommentsArea } from '@features/comments/services/comments'; import { CoreCourseSummary, CoreCourseModuleSummary } from '@features/course/services/course'; import { CorePushNotifications } from '@features/pushnotifications/services/pushnotifications'; import { CoreUserSummary } from '@features/user/services/user'; import { CoreSites } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; const ROOT_CACHE_KEY = 'mmaCompetency:'; /** * Service to handle caompetency learning plans. */ @Injectable( { providedIn: 'root' }) export class AddonCompetencyProvider { // Learning plan status. static readonly STATUS_DRAFT = 0; static readonly STATUS_ACTIVE = 1; static readonly STATUS_COMPLETE = 2; static readonly STATUS_WAITING_FOR_REVIEW = 3; static readonly STATUS_IN_REVIEW = 4; // Competency status. static readonly REVIEW_STATUS_IDLE = 0; static readonly REVIEW_STATUS_WAITING_FOR_REVIEW = 1; static readonly REVIEW_STATUS_IN_REVIEW = 2; /** * Check if all competencies features are disabled. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether all competency features are disabled. */ async allCompetenciesDisabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return site.isFeatureDisabled('CoreMainMenuDelegate_AddonCompetency') && site.isFeatureDisabled('CoreCourseOptionsDelegate_AddonCompetency') && site.isFeatureDisabled('CoreUserDelegate_AddonCompetency'); } /** * Returns whether current user can see another user competencies in a course. * * @param courseId Course ID. * @param userId User ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether the user can view the competencies. */ async canViewUserCompetenciesInCourse(courseId: number, userId?: number, siteId?: string): Promise<boolean> { if (!CoreSites.isLoggedIn()) { return false; } try { const response = await this.getCourseCompetenciesPage(courseId, siteId); if (!response.competencies.length) { // No competencies. return false; } if (!userId || userId == CoreSites.getCurrentSiteUserId()) { // Current user. return true; } // Check if current user can view any competency of the user. await this.getCompetencyInCourse(courseId, response.competencies[0].competency.id, userId, siteId); return true; } catch { return false; } } /** * Get cache key for user learning plans data WS calls. * * @param userId User ID. * @return Cache key. */ protected getLearningPlansCacheKey(userId: number): string { return ROOT_CACHE_KEY + 'userplans:' + userId; } /** * Get cache key for learning plan data WS calls. * * @param planId Plan ID. * @return Cache key. */ protected getLearningPlanCacheKey(planId: number): string { return ROOT_CACHE_KEY + 'learningplan:' + planId; } /** * Get cache key for competency in plan data WS calls. * * @param planId Plan ID. * @param competencyId Competency ID. * @return Cache key. */ protected getCompetencyInPlanCacheKey(planId: number, competencyId: number): string { return ROOT_CACHE_KEY + 'plancompetency:' + planId + ':' + competencyId; } /** * Get cache key for competency in course data WS calls. * * @param courseId Course ID. * @param competencyId Competency ID. * @param userId User ID. * @return Cache key. */ protected getCompetencyInCourseCacheKey(courseId: number, competencyId: number, userId: number): string { return ROOT_CACHE_KEY + 'coursecompetency:' + userId + ':' + courseId + ':' + competencyId; } /** * Get cache key for competency summary data WS calls. * * @param competencyId Competency ID. * @param userId User ID. * @return Cache key. */ protected getCompetencySummaryCacheKey(competencyId: number, userId: number): string { return ROOT_CACHE_KEY + 'competencysummary:' + userId + ':' + competencyId; } /** * Get cache key for course competencies data WS calls. * * @param courseId Course ID. * @return Cache key. */ protected getCourseCompetenciesCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'coursecompetencies:' + courseId; } /** * Returns whether competencies are enabled. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return competencies if enabled for the given course, false otherwise. */ async isPluginForCourseEnabled(courseId: number, siteId?: string): Promise<boolean> { if (!CoreSites.isLoggedIn()) { return false; } return CoreUtils.promiseWorks(this.getCourseCompetencies(courseId, undefined, siteId)); } /** * Get plans for a certain user. * * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise to be resolved when the plans are retrieved. */ async getLearningPlans(userId?: number, siteId?: string): Promise<AddonCompetencyPlan[]> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonCompetencyDataForPlansPageWSParams = { userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getLearningPlansCacheKey(userId), updateFrequency: CoreSite.FREQUENCY_RARELY, }; const response = await site.read<AddonCompetencyDataForPlansPageWSResponse>('tool_lp_data_for_plans_page', params, preSets); return response.plans; } /** * Get a certain plan. * * @param planId ID of the plan. * @param siteId Site ID. If not defined, current site. * @return Promise to be resolved when the plan is retrieved. */ async getLearningPlan(planId: number, siteId?: string): Promise<AddonCompetencyDataForPlanPageWSResponse> { const site = await CoreSites.getSite(siteId); const params: AddonCompetencyDataForPlanPageWSParams = { planid: planId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getLearningPlanCacheKey(planId), updateFrequency: CoreSite.FREQUENCY_RARELY, }; return site.read('tool_lp_data_for_plan_page', params, preSets); } /** * Get a certain competency in a plan. * * @param planId ID of the plan. * @param competencyId ID of the competency. * @param siteId Site ID. If not defined, current site. * @return Promise to be resolved when the competency is retrieved. */ async getCompetencyInPlan( planId: number, competencyId: number, siteId?: string, ): Promise<AddonCompetencyDataForUserCompetencySummaryInPlanWSResponse> { const site = await CoreSites.getSite(siteId); const params: AddonCompetencyDataForUserCompetencySummaryInPlanWSParams = { planid: planId, competencyid: competencyId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCompetencyInPlanCacheKey(planId, competencyId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; return site.read( 'tool_lp_data_for_user_competency_summary_in_plan', params, preSets, ); } /** * Get a certain competency in a course. * * @param courseId ID of the course. * @param competencyId ID of the competency. * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise to be resolved when the competency is retrieved. */ async getCompetencyInCourse( courseId: number, competencyId: number, userId?: number, siteId?: string, ignoreCache = false, ): Promise<AddonCompetencyDataForUserCompetencySummaryInCourseWSResponse> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonCompetencyDataForUserCompetencySummaryInCourseWSParams = { courseid: courseId, competencyid: competencyId, userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCompetencyInCourseCacheKey(courseId, competencyId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } return site.read('tool_lp_data_for_user_competency_summary_in_course', params, preSets); } /** * Get a certain competency summary. * * @param competencyId ID of the competency. * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise to be resolved when the competency summary is retrieved. */ async getCompetencySummary( competencyId: number, userId?: number, siteId?: string, ignoreCache = false, ): Promise<AddonCompetencyDataForUserCompetencySummaryWSResponse> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonCompetencyDataForUserCompetencySummaryWSParams = { competencyid: competencyId, userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCompetencySummaryCacheKey(competencyId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } return site.read('tool_lp_data_for_user_competency_summary', params, preSets); } /** * Get all competencies in a course for a certain user. * * @param courseId ID of the course. * @param userId ID of the user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise to be resolved when the course competencies are retrieved. */ async getCourseCompetencies( courseId: number, userId?: number, siteId?: string, ignoreCache = false, ): Promise<AddonCompetencyDataForCourseCompetenciesPageWSResponse> { const courseCompetencies = await this.getCourseCompetenciesPage(courseId, siteId, ignoreCache); if (!userId || userId == CoreSites.getCurrentSiteUserId()) { return courseCompetencies; } const userCompetenciesSumaries: AddonCompetencyDataForUserCompetencySummaryInCourseWSResponse[] = await Promise.all(courseCompetencies.competencies.map((competency) => this.getCompetencyInCourse(courseId, competency.competency.id, userId, siteId))); userCompetenciesSumaries.forEach((userCompetenciesSumary, index) => { courseCompetencies.competencies[index].usercompetencycourse = userCompetenciesSumary.usercompetencysummary.usercompetencycourse; }); return courseCompetencies; } /** * Get all competencies in a course. * * @param courseId ID of the course. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise to be resolved when the course competencies are retrieved. */ async getCourseCompetenciesPage( courseId: number, siteId?: string, ignoreCache = false, ): Promise<AddonCompetencyDataForCourseCompetenciesPageWSResponse> { const site = await CoreSites.getSite(siteId); const params: AddonCompetencyDataForCourseCompetenciesPageWSParams = { courseid: courseId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCourseCompetenciesCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } return site.read<AddonCompetencyDataForCourseCompetenciesPageWSResponse>( 'tool_lp_data_for_course_competencies_page', params, preSets, ); } /** * Invalidates User Learning Plans data. * * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateLearningPlans(userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getLearningPlansCacheKey(userId)); } /** * Invalidates Learning Plan data. * * @param planId ID of the plan. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateLearningPlan(planId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getLearningPlanCacheKey(planId)); } /** * Invalidates Competency in Plan data. * * @param planId ID of the plan. * @param competencyId ID of the competency. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCompetencyInPlan(planId: number, competencyId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCompetencyInPlanCacheKey(planId, competencyId)); } /** * Invalidates Competency in Course data. * * @param courseId ID of the course. * @param competencyId ID of the competency. * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCompetencyInCourse(courseId: number, competencyId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getCompetencyInCourseCacheKey(courseId, competencyId, userId)); } /** * Invalidates Competency Summary data. * * @param competencyId ID of the competency. * @param userId ID of the user. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCompetencySummary(competencyId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getCompetencySummaryCacheKey(competencyId, userId)); } /** * Invalidates Course Competencies data. * * @param courseId ID of the course. * @param userId ID of the user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCourseCompetencies(courseId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCourseCompetenciesCacheKey(courseId)); if (!userId || userId == CoreSites.getCurrentSiteUserId()) { return; } const competencies = await this.getCourseCompetencies(courseId, 0, siteId); const promises = competencies.competencies.map((competency) => this.invalidateCompetencyInCourse(courseId, competency.competency.id, userId, siteId)); await Promise.all(promises); } /** * Report the competency as being viewed in plan. * * @param planId ID of the plan. * @param competencyId ID of the competency. * @param planStatus Current plan Status to decide what action should be logged. * @param name Name of the competency. * @param userId User ID. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logCompetencyInPlanView( planId: number, competencyId: number, planStatus: number, name?: string, userId?: number, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonCompetencyUserCompetencyPlanViewedWSParams = { planid: planId, competencyid: competencyId, userid: userId, }; const preSets: CoreSiteWSPreSets = { typeExpected: 'boolean', }; const wsName = planStatus == AddonCompetencyProvider.STATUS_COMPLETE ? 'core_competency_user_competency_plan_viewed' : 'core_competency_user_competency_viewed_in_plan'; CorePushNotifications.logViewEvent(competencyId, name, 'competency', wsName, { planid: planId, planstatus: planStatus, userid: userId, }, siteId); await site.write(wsName, params, preSets); } /** * Report the competency as being viewed in course. * * @param courseId ID of the course. * @param competencyId ID of the competency. * @param name Name of the competency. * @param userId User ID. If not defined, current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logCompetencyInCourseView( courseId: number, competencyId: number, name?: string, userId?: number, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonCompetencyUserCompetencyViewedInCourseWSParams = { courseid: courseId, competencyid: competencyId, userid: userId, }; const preSets: CoreSiteWSPreSets = { typeExpected: 'boolean', }; const wsName = 'core_competency_user_competency_viewed_in_course'; CorePushNotifications.logViewEvent(competencyId, name, 'competency', 'wsName', { courseid: courseId, userid: userId, }, siteId); await site.write(wsName, params, preSets); } /** * Report the competency as being viewed. * * @param competencyId ID of the competency. * @param name Name of the competency. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logCompetencyView(competencyId: number, name?: string, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonCompetencyCompetencyViewedWSParams = { id: competencyId, }; const preSets: CoreSiteWSPreSets = { typeExpected: 'boolean', }; const wsName = 'core_competency_competency_viewed'; CorePushNotifications.logViewEvent(competencyId, name, 'competency', wsName, {}, siteId); await site.write(wsName, params, preSets); } } export const AddonCompetency = makeSingleton(AddonCompetencyProvider); /** * Data returned by competency's plan_exporter. */ export type AddonCompetencyPlan = { name: string; // Name. description: string; // Description. descriptionformat?: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). userid: number; // Userid. templateid: number; // Templateid. origtemplateid: number; // Origtemplateid. status: number; // Status. duedate: number; // Duedate. reviewerid: number; // Reviewerid. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. statusname: string; // Statusname. isbasedontemplate: boolean; // Isbasedontemplate. canmanage: boolean; // Canmanage. canrequestreview: boolean; // Canrequestreview. canreview: boolean; // Canreview. canbeedited: boolean; // Canbeedited. isactive: boolean; // Isactive. isdraft: boolean; // Isdraft. iscompleted: boolean; // Iscompleted. isinreview: boolean; // Isinreview. iswaitingforreview: boolean; // Iswaitingforreview. isreopenallowed: boolean; // Isreopenallowed. iscompleteallowed: boolean; // Iscompleteallowed. isunlinkallowed: boolean; // Isunlinkallowed. isrequestreviewallowed: boolean; // Isrequestreviewallowed. iscancelreviewrequestallowed: boolean; // Iscancelreviewrequestallowed. isstartreviewallowed: boolean; // Isstartreviewallowed. isstopreviewallowed: boolean; // Isstopreviewallowed. isapproveallowed: boolean; // Isapproveallowed. isunapproveallowed: boolean; // Isunapproveallowed. duedateformatted: string; // Duedateformatted. commentarea: CoreCommentsArea; reviewer?: CoreUserSummary; template?: AddonCompetencyTemplate; url: string; // Url. }; /** * Data returned by competency's template_exporter. */ export type AddonCompetencyTemplate = { shortname: string; // Shortname. description: string; // Description. descriptionformat?: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). duedate: number; // Duedate. visible: boolean; // Visible. contextid: number; // Contextid. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. duedateformatted: string; // Duedateformatted. cohortscount: number; // Cohortscount. planscount: number; // Planscount. canmanage: boolean; // Canmanage. canread: boolean; // Canread. contextname: string; // Contextname. contextnamenoprefix: string; // Contextnamenoprefix. }; /** * Data returned by competency's competency_exporter. */ export type AddonCompetencyCompetency = { shortname: string; // Shortname. idnumber: string; // Idnumber. description: string; // Description. descriptionformat: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). sortorder: number; // Sortorder. parentid: number; // Parentid. path: string; // Path. ruleoutcome: number; // Ruleoutcome. ruletype: string; // Ruletype. ruleconfig: string; // Ruleconfig. scaleid: number; // Scaleid. scaleconfiguration: string; // Scaleconfiguration. competencyframeworkid: number; // Competencyframeworkid. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. }; /** * Data returned by competency's competency_path_exporter. */ export type AddonCompetencyPath = { ancestors: AddonCompetencyPathNode[]; // Ancestors. framework: AddonCompetencyPathNode; pluginbaseurl: string; // Pluginbaseurl. pagecontextid: number; // Pagecontextid. showlinks: boolean; // @since 3.7. Showlinks. }; /** * Data returned by competency's path_node_exporter. */ export type AddonCompetencyPathNode = { id: number; // Id. name: string; // Name. first: boolean; // First. last: boolean; // Last. position: number; // Position. }; /** * Data returned by competency's user_competency_exporter. */ export type AddonCompetencyUserCompetency = { userid: number; // Userid. competencyid: number; // Competencyid. status: number; // Status. reviewerid: number; // Reviewerid. proficiency: boolean; // Proficiency. grade: number; // Grade. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. canrequestreview: boolean; // Canrequestreview. canreview: boolean; // Canreview. gradename: string; // Gradename. isrequestreviewallowed: boolean; // Isrequestreviewallowed. iscancelreviewrequestallowed: boolean; // Iscancelreviewrequestallowed. isstartreviewallowed: boolean; // Isstartreviewallowed. isstopreviewallowed: boolean; // Isstopreviewallowed. isstatusidle: boolean; // Isstatusidle. isstatusinreview: boolean; // Isstatusinreview. isstatuswaitingforreview: boolean; // Isstatuswaitingforreview. proficiencyname: string; // Proficiencyname. reviewer?: CoreUserSummary; statusname: string; // Statusname. url: string; // Url. }; /** * Data returned by competency's user_competency_plan_exporter. */ export type AddonCompetencyUserCompetencyPlan = { userid: number; // Userid. competencyid: number; // Competencyid. proficiency: boolean; // Proficiency. grade: number; // Grade. planid: number; // Planid. sortorder: number; // Sortorder. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. gradename: string; // Gradename. proficiencyname: string; // Proficiencyname. }; /** * Params of tool_lp_data_for_user_competency_summary_in_plan WS. */ type AddonCompetencyDataForUserCompetencySummaryInPlanWSParams = { competencyid: number; // Data base record id for the competency. planid: number; // Data base record id for the plan. }; /** * Data returned by competency's user_competency_summary_in_plan_exporter. */ export type AddonCompetencyDataForUserCompetencySummaryInPlanWSResponse = { usercompetencysummary: AddonCompetencyDataForUserCompetencySummaryWSResponse; plan: AddonCompetencyPlan; }; /** * Params of tool_lp_data_for_user_competency_summary WS. */ type AddonCompetencyDataForUserCompetencySummaryWSParams = { userid: number; // Data base record id for the user. competencyid: number; // Data base record id for the competency. }; /** * Data returned by competency's user_competency_summary_exporter. */ export type AddonCompetencyDataForUserCompetencySummaryWSResponse = { showrelatedcompetencies: boolean; // Showrelatedcompetencies. cangrade: boolean; // Cangrade. competency: AddonCompetencySummary; user: CoreUserSummary; usercompetency?: AddonCompetencyUserCompetency; usercompetencyplan?: AddonCompetencyUserCompetencyPlan; usercompetencycourse?: AddonCompetencyUserCompetencyCourse; evidence: AddonCompetencyEvidence[]; // Evidence. commentarea?: CoreCommentsArea; }; /** * Data returned by competency's competency_summary_exporter. */ export type AddonCompetencySummary = { linkedcourses: CoreCourseSummary; // Linkedcourses. relatedcompetencies: AddonCompetencyCompetency[]; // Relatedcompetencies. competency: AddonCompetencyCompetency; framework: AddonCompetencyFramework; hascourses: boolean; // Hascourses. hasrelatedcompetencies: boolean; // Hasrelatedcompetencies. scaleid: number; // Scaleid. scaleconfiguration: string; // Scaleconfiguration. taxonomyterm: string; // Taxonomyterm. comppath: AddonCompetencyPath; pluginbaseurl: string; // @since 3.7. Pluginbaseurl. }; /** * Data returned by competency's competency_framework_exporter. */ export type AddonCompetencyFramework = { shortname: string; // Shortname. idnumber: string; // Idnumber. description: string; // Description. descriptionformat: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). visible: boolean; // Visible. scaleid: number; // Scaleid. scaleconfiguration: string; // Scaleconfiguration. contextid: number; // Contextid. taxonomies: string; // Taxonomies. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. canmanage: boolean; // Canmanage. competenciescount: number; // Competenciescount. contextname: string; // Contextname. contextnamenoprefix: string; // Contextnamenoprefix. }; /** * Data returned by competency's user_competency_course_exporter. */ export type AddonCompetencyUserCompetencyCourse = { userid: number; // Userid. courseid: number; // Courseid. competencyid: number; // Competencyid. proficiency: boolean; // Proficiency. grade: number; // Grade. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. gradename: string; // Gradename. proficiencyname: string; // Proficiencyname. }; /** * Data returned by competency's evidence_exporter. */ export type AddonCompetencyEvidence = { usercompetencyid: number; // Usercompetencyid. contextid: number; // Contextid. action: number; // Action. actionuserid: number; // Actionuserid. descidentifier: string; // Descidentifier. desccomponent: string; // Desccomponent. desca: string; // Desca. url: string; // Url. grade: number; // Grade. note: string; // Note. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. actionuser?: CoreUserSummary; description: string; // Description. gradename: string; // Gradename. userdate: string; // Userdate. candelete: boolean; // Candelete. }; /** * Params of tool_lp_data_for_user_competency_summary_in_course WS. */ type AddonCompetencyDataForUserCompetencySummaryInCourseWSParams = { userid: number; // Data base record id for the user. competencyid: number; // Data base record id for the competency. courseid: number; // Data base record id for the course. }; /** * Data returned by competency's user_competency_summary_in_course_exporter. */ export type AddonCompetencyDataForUserCompetencySummaryInCourseWSResponse = { usercompetencysummary: AddonCompetencyDataForUserCompetencySummaryWSResponse; course: CoreCourseSummary; coursemodules: CoreCourseModuleSummary[]; // Coursemodules. plans: AddonCompetencyPlan[]; // @since 3.7. Plans. pluginbaseurl: string; // @since 3.7. Pluginbaseurl. }; /** * Data returned by competency's course_competency_settings_exporter. */ export type AddonCompetencyCourseCompetencySettings = { courseid: number; // Courseid. pushratingstouserplans: boolean; // Pushratingstouserplans. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. }; /** * Data returned by competency's course_competency_statistics_exporter. */ export type AddonCompetencyCourseCompetencyStatistics = { competencycount: number; // Competencycount. proficientcompetencycount: number; // Proficientcompetencycount. proficientcompetencypercentage: number; // Proficientcompetencypercentage. proficientcompetencypercentageformatted: string; // Proficientcompetencypercentageformatted. leastproficient: AddonCompetencyCompetency[]; // Leastproficient. leastproficientcount: number; // Leastproficientcount. canbegradedincourse: boolean; // Canbegradedincourse. canmanagecoursecompetencies: boolean; // Canmanagecoursecompetencies. }; /** * Data returned by competency's course_competency_exporter. */ export type AddonCompetencyCourseCompetency = { courseid: number; // Courseid. competencyid: number; // Competencyid. sortorder: number; // Sortorder. ruleoutcome: number; // Ruleoutcome. id: number; // Id. timecreated: number; // Timecreated. timemodified: number; // Timemodified. usermodified: number; // Usermodified. }; /** * Params of tool_lp_data_for_plans_page WS. */ type AddonCompetencyDataForPlansPageWSParams = { userid: number; // The user id. }; /** * Data returned by tool_lp_data_for_plans_page WS. */ export type AddonCompetencyDataForPlansPageWSResponse = { userid: number; // The learning plan user id. plans: AddonCompetencyPlan[]; pluginbaseurl: string; // Url to the tool_lp plugin folder on this Moodle site. navigation: string[]; canreaduserevidence: boolean; // Can the current user view the user's evidence. canmanageuserplans: boolean; // Can the current user manage the user's plans. }; /** * Params of tool_lp_data_for_plan_page WS. */ type AddonCompetencyDataForPlanPageWSParams = { planid: number; // The plan id. }; /** * Data returned by tool_lp_data_for_plan_page WS. */ export type AddonCompetencyDataForPlanPageWSResponse = { plan: AddonCompetencyPlan; contextid: number; // Context ID. pluginbaseurl: string; // Plugin base URL. competencies: AddonCompetencyDataForPlanPageCompetency[]; competencycount: number; // Count of competencies. proficientcompetencycount: number; // Count of proficientcompetencies. proficientcompetencypercentage: number; // Percentage of competencies proficient. proficientcompetencypercentageformatted: string; // Displayable percentage. }; /** * Competency data returned by tool_lp_data_for_plan_page. */ export type AddonCompetencyDataForPlanPageCompetency = { competency: AddonCompetencyCompetency; comppath: AddonCompetencyPath; usercompetency?: AddonCompetencyUserCompetency; usercompetencyplan?: AddonCompetencyUserCompetencyPlan; }; /** * Params of tool_lp_data_for_course_competencies_page WS. */ type AddonCompetencyDataForCourseCompetenciesPageWSParams = { courseid: number; // The course id. moduleid?: number; // The module id. }; /** * Data returned by tool_lp_data_for_course_competencies_page WS. */ export type AddonCompetencyDataForCourseCompetenciesPageWSResponse = { courseid: number; // The current course id. pagecontextid: number; // The current page context ID. gradableuserid?: number; // Current user id, if the user is a gradable user. canmanagecompetencyframeworks: boolean; // User can manage competency frameworks. canmanagecoursecompetencies: boolean; // User can manage linked course competencies. canconfigurecoursecompetencies: boolean; // User can configure course competency settings. cangradecompetencies: boolean; // User can grade competencies. settings: AddonCompetencyCourseCompetencySettings; statistics: AddonCompetencyCourseCompetencyStatistics; competencies: AddonCompetencyDataForCourseCompetenciesPageCompetency[]; manageurl: string; // Url to the manage competencies page. pluginbaseurl: string; // @since 3.6. Url to the course competencies page. }; /** * Competency data returned by tool_lp_data_for_course_competencies_page. */ export type AddonCompetencyDataForCourseCompetenciesPageCompetency = { competency: AddonCompetencyCompetency; coursecompetency: AddonCompetencyCourseCompetency; coursemodules: CoreCourseModuleSummary[]; usercompetencycourse?: AddonCompetencyUserCompetencyCourse; ruleoutcomeoptions: { value: number; // The option value. text: string; // The name of the option. selected: boolean; // If this is the currently selected option. }[]; comppath: AddonCompetencyPath; plans: AddonCompetencyPlan[]; // @since 3.7. }; /** * Params of core_competency_user_competency_plan_viewed and core_competency_user_competency_viewed_in_plan WS. */ type AddonCompetencyUserCompetencyPlanViewedWSParams = { competencyid: number; // The competency id. userid: number; // The user id. planid: number; // The plan id. }; /** * Params of core_competency_user_competency_viewed_in_course WS. */ type AddonCompetencyUserCompetencyViewedInCourseWSParams = { competencyid: number; // The competency id. userid: number; // The user id. courseid: number; // The course id. }; /** * Params of core_competency_competency_viewed WS. */ type AddonCompetencyCompetencyViewedWSParams = { id: number; // The competency id. };
the_stack
import { GoAction } from "../action/GoAction"; import * as Utils from "../Utils"; import { Position } from "../VimStyle"; import { AbstractMotion } from "./AbstractMotion"; /** * b B e E * cb cB ce cE * this class will be replaced */ export class WordMotion extends AbstractMotion { public Direction: Direction; // public IsCW: boolean; public IsSkipBlankLine: boolean; public IsStopLineEnd: boolean; public IsWordEnd: boolean; public Command: string; public IsWORD: boolean; public IsForRange: boolean; constructor(direction: Direction) { super(); this.Direction = direction; // this.IsCW = false; this.IsSkipBlankLine = false; this.IsStopLineEnd = false; this.IsWordEnd = false; this.IsWORD = false; this.IsForRange = false; }; public CalculateEnd(editor: IEditor, vim: IVimStyle, start: IPosition): IPosition { let count = this.Count; let previousCharClass: CharGroup = null; let charClass: CharGroup = null; let nextCharClass: CharGroup = null; let previousPosition: Position = null; let position: Position = null; let nextPosition: Position = editor.GetCurrentPosition().Copy(); // this count use for skip to stop current position let beforeCountLoop: number; let line = editor.ReadLine(nextPosition.Line); let lineLength = line.length; let documentLength = editor.GetLastLineNum() + 1; if (this.Direction === Direction.Right) { if (nextPosition.Char === 0) { charClass = CharGroup.Spaces; nextCharClass = CharGroup.Spaces; nextPosition.Char = -1; if (this.Command !== "dw" && line.length > 0) { let charCode = line.charCodeAt(nextPosition.Char); charClass = Utils.GetCharClass(charCode); if (charClass !== CharGroup.Spaces) { count += 1; } } beforeCountLoop = -1; } else if (nextPosition.Char === 1) { nextCharClass = CharGroup.Spaces; beforeCountLoop = -2; } else { nextPosition.Char--; beforeCountLoop = -3; } } else { if (lineLength - 2 === nextPosition.Char) { charClass = CharGroup.Spaces; nextCharClass = CharGroup.Spaces; beforeCountLoop = -1; } else if (lineLength - 1 === nextPosition.Char) { nextCharClass = CharGroup.Spaces; beforeCountLoop = -2; } else { nextPosition.Char++; beforeCountLoop = -3; } } if (this.IsForRange && nextCharClass !== CharGroup.Spaces) { count--; } let isReachLast = false; let charCode: number; let lineEnd: boolean; let skipCountDown: boolean; while (count > -1) { skipCountDown = false; lineEnd = false; previousPosition = position; previousCharClass = charClass; position = nextPosition; charClass = nextCharClass; nextPosition = new Position(position.Line, position.Char); // get next charactor if (this.Direction === Direction.Left) { nextPosition.Char--; if (nextPosition.Char === -1) { nextCharClass = CharGroup.Spaces; } else if (nextPosition.Char < -1) { // First of line nextPosition.Line--; if (nextPosition.Line < 0) { // Fist of document isReachLast = true; break; } else { // before line line = editor.ReadLine(nextPosition.Line); lineLength = line.length; nextPosition.Char = lineLength - 1; nextCharClass = CharGroup.Spaces; } } else { // char code let nextCharCode = line.charCodeAt(nextPosition.Char); nextCharClass = Utils.GetCharClass(nextCharCode); } } else { nextPosition.Char++; if (lineLength <= nextPosition.Char) { // End of line lineEnd = true; nextPosition.Line++; if (nextPosition.Line === documentLength) { // End of document isReachLast = true; break; } else { // next line line = editor.ReadLine(nextPosition.Line); lineLength = line.length; nextPosition.Char = -1; nextCharClass = CharGroup.Spaces; } } else { // char code let nextCharCode = line.charCodeAt(nextPosition.Char); nextCharClass = Utils.GetCharClass(nextCharCode); } } beforeCountLoop++; if (beforeCountLoop < 0) { continue; } else if (beforeCountLoop === 0 && this.IsWordEnd && this.Command !== "cw") { if (charClass !== CharGroup.Spaces && nextCharClass !== CharGroup.Spaces) { if (this.IsWORD || charClass === nextCharClass) { // e start at a charactor at not end of word count--; skipCountDown = true; } } } // handle let newWord = false; if (!skipCountDown) { if (charClass !== CharGroup.Spaces) { if (this.IsWORD) { if (previousCharClass === CharGroup.Spaces) { newWord = true; count--; } } else { if (previousCharClass !== charClass) { newWord = true; count--; } } } else if (!newWord && !this.IsSkipBlankLine) { if (this.Direction === Direction.Right) { if (previousPosition !== null && previousPosition.Char === -1) { count--; } } else { if (position.Char === -1 && previousPosition.Char === -1) { count--; } } } } if (count === 0) { if (this.IsWordEnd) { if (this.IsWORD) { // E B cW if (nextCharClass === CharGroup.Spaces) { break; } if (lineEnd) { break; } } else { // e b cw if (charClass !== nextCharClass) { break; } } } else if (this.IsForRange) { if (this.Direction === Direction.Right) { // dw yw if (position.Char === -1) { break; } } } else { // W gE dW yW // e ge dw yw break; } } } if (isReachLast) { // reach last position if (this.Direction === Direction.Left) { // top position return new Position(0, 0); } else { // last position if (this.IsForRange) { position.Char += 1; } return position; } } if (this.IsForRange && position.Char === -1) { // Stop end of line line = editor.ReadLine(position.Line - 1); return new Position(position.Line - 1, line.length); } if (this.Command === "cw") { if (line.length - 1 > position.Char) { position.Char++; } } return position; } } // Nb export function GotoWordBackword(num: number): IAction { let a = new GoAction(); let m: WordMotion; m = new WordMotion(Direction.Left); m.IsWordEnd = true; m.IsWORD = false; m.IsSkipBlankLine = false; m.Count = num > 0 ? num : 1; a.Motion = m; return a; } // cNb export function AddWordBackwardMotion(num: number, action: IAction) { let m: WordMotion; m = new WordMotion(Direction.Left); m.IsWordEnd = true; m.IsWORD = false; m.IsSkipBlankLine = false; // m.IsForRange = true; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } // NB export function GotoBlankSeparatedBackwordWord(num: number): IAction { let a = new GoAction(); let m: WordMotion; m = new WordMotion(Direction.Left); m.IsWordEnd = true; m.IsWORD = true; m.IsSkipBlankLine = false; m.Count = num > 0 ? num : 1; a.Motion = m; return a; } // cNB export function AddBlankSeparatedBackwordMotion(num: number, action: IAction) { let m: WordMotion; m = new WordMotion(Direction.Left); m.IsWordEnd = true; m.IsWORD = true; m.IsSkipBlankLine = false; // m.IsForRange = true; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; }
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import {AccessControlService} from '../../../services/AccessControlService'; import {EntityAccessControlService} from '../../shared/entity-access-control/EntityAccessControlService'; const moduleName = require('../module-name'); export class CategoryDefinitionController { /** * Manages the Category Definition section of the Category Details page. * * @constructor * @param $scope the application model * @param $mdDialog the Angular Material dialog service * @param $mdToast the Angular Material toast service * @param {AccessControlService} AccessControlService the access control service * @param CategoriesService the category service * @param StateService the URL service * @param FeedSecurityGroups the feed security groups service * @param FeedService the feed service */ /** * The Angular form for validation * @type {{}} */ categoryForm:any = {}; /** * Indicates if the category definition may be edited. * @type {boolean} */ allowEdit:boolean = false; /** * Indicates the user has the permission to delete * @type {boolean} */ allowDelete:boolean = false; /** * Category data used in "edit" mode. * @type {CategoryModel} */ editModel:any; /** * Indicates if the view is in "edit" mode. * @type {boolean} {@code true} if in "edit" mode or {@code false} if in "normal" mode */ isEditable:any; /** * Category data used in "normal" mode. * @type {CategoryModel} */ model:any; categorySecurityGroups:any; securityGroupChips:any; securityGroupsEnabled:boolean = false; systemNameEditable:boolean = false; /** * Prevent users from creating categories with these names * @type {string[]} */ reservedCategoryNames:any = ['thinkbig'] static readonly $inject = ["$scope", "$mdDialog", "$mdToast", "$q", "$timeout", "$window", "AccessControlService", "EntityAccessControlService", "CategoriesService", "StateService", "FeedSecurityGroups", "FeedService"]; constructor(private $scope:IScope, private $mdDialog:angular.material.IDialogService, private $mdToast:angular.material.IToastService, private $q:angular.IQService, private $timeout:angular.ITimeoutService , private $window:angular.IWindowService, private accessControlService:AccessControlService, private entityAccessControlService:EntityAccessControlService , private CategoriesService:any, private StateService:any, private FeedSecurityGroups:any, private FeedService:any) { this.editModel = angular.copy(CategoriesService.model); this.isEditable = !angular.isString(CategoriesService.model.id); this.model = CategoriesService.model; this.categorySecurityGroups = FeedSecurityGroups; this.securityGroupChips = {}; this.securityGroupChips.selectedItem = null; this.securityGroupChips.searchText = null; FeedSecurityGroups.isEnabled().then( (isValid:any) => { this.securityGroupsEnabled = isValid; } ); this.checkAccessPermissions(); // Fetch the existing categories CategoriesService.reload().then((response:any) =>{ if (this.editModel) { this.validateDisplayName(); this.validateSystemName(); } }); // Watch for changes to name $scope.$watch( () =>{ return this.editModel.name }, () =>{ this.validateDisplayName() } ); // Watch for changes to system name $scope.$watch( () =>{ return this.editModel.systemName }, () =>{ this.validateSystemName() } ); } /** * System Name states: * !new 0, !editable 0, !feeds 0 - not auto generated, can change * !new 0, !editable 0, feeds 1 - not auto generated, cannot change * !new 0, editable 1, !feeds 0 - not auto generated, editable * !new 0, editable 1, feeds 1 - invalid state (cannot be editable with feeds) * new 1, !editable 0, !feeds 0 - auto generated, can change * new 1, !editable 0, feeds 1 - invalid state (new cannot be with feeds) * new 1, editable 1, !feeds 0 - not auto generated, editable * new 1, editable 1, feeds 1 - invalid state (cannot be editable with feeds) */ getSystemNameDescription() { // console.log("this.isNewCategory() = " + this.isNewCategory()); // console.log("this.isSystemNameEditable() = " + this.isSystemNameEditable()); // console.log("this.hasFeeds() = " + this.hasFeeds()); if (!this.isNewCategory() && !this.isSystemNameEditable() && this.hasNoFeeds()) { return "Can be customized"; } if (!this.isNewCategory() && !this.isSystemNameEditable() && this.hasFeeds()) { return "Cannot be customized because category has feeds"; } if (!this.isNewCategory() && this.isSystemNameEditable() && this.hasNoFeeds()) { return "System name is now editable"; } if (!this.isNewCategory() && this.isSystemNameEditable() && this.hasFeeds()) { return ""; //invalid state, cannot be both editable and have feeds! } if (this.isNewCategory() && !this.isSystemNameEditable() && this.hasNoFeeds()) { return "Auto generated from category name, can be customized"; } if (this.isNewCategory() && !this.isSystemNameEditable() && this.hasFeeds()) { return ""; //invalid state, cannot be new and already have feeds } if (this.isNewCategory() && this.isSystemNameEditable() && this.hasNoFeeds()) { return "System name is now editable"; } if (this.isNewCategory() && this.isSystemNameEditable() && this.hasFeeds()) { return ""; //invalid state, cannot be new with feeds } return ""; }; isNewCategory() { return this.editModel.id == undefined; }; isSystemNameEditable() { return this.systemNameEditable; }; hasFeeds() { return !this.hasNoFeeds(); }; hasNoFeeds() { return (!angular.isArray(this.model.relatedFeedSummaries) || this.model.relatedFeedSummaries.length === 0); }; allowEditSystemName() { this.systemNameEditable = true; this.$timeout(()=> { var systemNameInput = this.$window.document.getElementById("systemName"); if(systemNameInput) { systemNameInput.focus(); } }); }; splitSecurityGroups() { if (this.model.securityGroups) { return _.map(this.model.securityGroups, (securityGroup:any) =>{ return securityGroup.name }).join(","); } }; /** * Indicates if the category can be deleted. * @return {boolean} {@code true} if the category can be deleted, or {@code false} otherwise */ canDelete() { return this.allowDelete && (angular.isString(this.model.id) && this.hasNoFeeds()); }; /** * Returns to the category list page if creating a new category. */ onCancel() { this.systemNameEditable = false; if (!angular.isString(this.model.id)) { this.StateService.FeedManager().Category().navigateToCategories(); } }; /** * Deletes this category. */ onDelete() { var name = this.editModel.name; this.CategoriesService.delete(this.editModel).then( () => { this.systemNameEditable = false; this.CategoriesService.reload(); this.$mdToast.show( this.$mdToast.simple() .textContent('Successfully deleted the category ' + name) .hideDelay(3000) ); //redirect this.StateService.FeedManager().Category().navigateToCategories(); }, (err:any) => { this.$mdDialog.show( this.$mdDialog.alert() .clickOutsideToClose(true) .title('Unable to delete the category') .textContent('Unable to delete the category ' + name + ". " + err.data.message) .ariaLabel('Unable to delete the category') .ok('Got it!') ); }); }; /** * Switches to "edit" mode. */ onEdit() { this.editModel = angular.copy(this.model); }; /** * Check for duplicate display and system names. */ validateDisplayAndSystemName() { var displayNameExists = false; var systemNameExists = false; var newDisplayName = this.editModel.name; this.FeedService.getSystemName(newDisplayName) .then( (response:any) =>{ var systemName = response.data; if (this.isNewCategory() && !this.isSystemNameEditable()) { this.editModel.systemName = systemName; } displayNameExists = _.some(this.CategoriesService.categories, (category:any) =>{ return (this.editModel.id == null || (this.editModel.id != null && category.id != this.editModel.id)) && category.name === newDisplayName; }); systemNameExists = _.some(this.CategoriesService.categories, (category:any) =>{ return (this.editModel.id == null || (this.editModel.id != null && category.id != this.editModel.id)) && category.systemName === this.editModel.systemName; }); var reservedCategoryDisplayName = newDisplayName && _.indexOf(this.reservedCategoryNames, newDisplayName.toLowerCase()) >= 0; var reservedCategorySystemName = this.editModel.systemName && _.indexOf(this.reservedCategoryNames, this.editModel.systemName.toLowerCase()) >= 0; if (this.categoryForm) { if (this.categoryForm['categoryName']) { this.categoryForm['categoryName'].$setValidity('duplicateDisplayName', !displayNameExists); this.categoryForm['categoryName'].$setValidity('reservedCategoryName', !reservedCategoryDisplayName); } if (this.categoryForm['systemName']) { this.categoryForm['systemName'].$setValidity('duplicateSystemName', !systemNameExists); this.categoryForm['systemName'].$setValidity('reservedCategoryName', !reservedCategorySystemName); } } }); }; /** * Check for duplicate display and system names. */ validateDisplayName() { var nameExists = false; var newName = this.editModel.name; this.FeedService.getSystemName(newName) .then((response:any) =>{ var systemName = response.data; if (this.isNewCategory() && !this.isSystemNameEditable()) { this.editModel.systemName = systemName; } nameExists = _.some(this.CategoriesService.categories, (category:any) =>{ return (this.editModel.id == null || (this.editModel.id != null && category.id != this.editModel.id)) && category.name === newName; }); var reservedCategoryDisplayName = newName && _.indexOf(this.reservedCategoryNames, newName.toLowerCase()) >= 0; if (this.categoryForm) { if (this.categoryForm['categoryName']) { this.categoryForm['categoryName'].$setValidity('duplicateDisplayName', !nameExists); this.categoryForm['categoryName'].$setValidity('reservedCategoryName', !reservedCategoryDisplayName); } } }); }; /** * Check for duplicate display and system names. */ validateSystemName() { var nameExists = false; var newName = this.editModel.systemName; this.FeedService.getSystemName(newName) .then((response:any) =>{ var systemName = response.data; nameExists = _.some(this.CategoriesService.categories, (category:any) =>{ return (this.editModel.id == null || (this.editModel.id != null && category.id != this.editModel.id)) && category.systemName === systemName; }); var reservedCategorySystemName = this.editModel.systemName && _.indexOf(this.reservedCategoryNames, this.editModel.systemName.toLowerCase()) >= 0; var invalidName = newName !== systemName; if (this.categoryForm) { if (this.categoryForm['systemName']) { this.categoryForm['systemName'].$setValidity('invalidName', !invalidName); this.categoryForm['systemName'].$setValidity('duplicateSystemName', !nameExists); this.categoryForm['systemName'].$setValidity('reservedCategoryName', !reservedCategorySystemName); } } }); }; /** * Saves the category definition. */ onSave() { var model = angular.copy(this.CategoriesService.model); model.name = this.editModel.name; model.systemName = this.editModel.systemName; model.description = this.editModel.description; model.icon = this.editModel.icon; model.iconColor = this.editModel.iconColor; model.userProperties = (this.model.id === null) ? this.editModel.userProperties : null; model.securityGroups = this.editModel.securityGroups; model.allowIndexing = this.editModel.allowIndexing; this.CategoriesService.save(model).then((response:any) =>{ this.systemNameEditable = false; this.CategoriesService.update(response.data); this.model = this.CategoriesService.model = response.data; this.$mdToast.show( this.$mdToast.simple() .textContent('Saved the Category') .hideDelay(3000) ); this.checkAccessPermissions(); }, (err:any) =>{ this.$mdDialog.show( this.$mdDialog.alert() .clickOutsideToClose(true) .title("Save Failed") .textContent("The category '" + model.name + "' could not be saved. " + err.data.message) .ariaLabel("Failed to save category") .ok("Got it!") ); }); }; /** * Shows the icon picker dialog. */ showIconPicker() { var self = this; this.$mdDialog.show({ controller: 'IconPickerDialog', templateUrl: '../../../common/icon-picker-dialog/icon-picker-dialog.html', parent: angular.element(document.body), clickOutsideToClose: false, fullscreen: true, locals: { iconModel: this.editModel } }) .then((msg:any) =>{ if (msg) { this.editModel.icon = msg.icon; this.editModel.iconColor = msg.color; } }); }; getIconColorStyle(iconColor:any) { return {'fill': iconColor}; }; checkAccessPermissions() { //Apply the entity access permissions this.$q.when(this.accessControlService.hasPermission(AccessControlService.CATEGORIES_EDIT, this.model, AccessControlService.ENTITY_ACCESS.CATEGORY.EDIT_CATEGORY_DETAILS)).then((access:any) =>{ this.allowEdit = access; }); this.$q.when(this.accessControlService.hasPermission(AccessControlService.CATEGORIES_EDIT, this.model, AccessControlService.ENTITY_ACCESS.CATEGORY.DELETE_CATEGORY)).then((access:any) =>{ this.allowDelete = access; }); } } angular.module(moduleName).component("thinkbigCategoryDefinition",{ controller: CategoryDefinitionController, controllerAs: "vm", templateUrl: "./category-definition.html" });
the_stack
import { getTmpDir } from './test/getTmpDir' import { EnvironmentMigrator } from './EnvironmentMigrator' import * as fs from 'fs-extra' import * as path from 'path' import { TestOutput } from './Output/interface' /** * Tests overview test('.graphcool with json, non-existent backup file', () => { test('.graphcool with json, existing backup file', () => { test('.graphcool with yaml, non-existent backup file', () => { test('.graphcool with yaml, existing backup file', () => { test('.graphcool folder, non-existent backup file, non-existent .graphcoolrc', () => { test('.graphcool folder, non-existent backup file, existing .graphcoolrc', () => { test('.graphcool folder, non-existent backup file, existing .graphcoolrc', () => { test('.graphcoolrc folder, non-existent backup file', () => { test('.graphcoolrc folder, existing backup folder (or file)', () => { test('.graphcoolrc file with valid yaml, non-existent backup file', () => { test('.graphcoolrc file with valid yaml, existing backup folder (or file)', () => { test('.graphcoolrc file with invalid yaml, non-existent backup file', () => { test('.graphcoolrc file with invalid yaml, existing backup folder (or file)', () => { */ describe('EnvironmentMigrator', () => { test('.graphcool with json, non-existent backup file', () => { const home = getTmpDir() fs.outputFileSync(path.join(home, '.graphcool'), '{"example": "Json"}') const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool with json, existing backup file', () => { const home = getTmpDir() fs.writeFileSync(path.join(home, '.graphcool'), '{"example": "Json"}') fs.writeFileSync(path.join(home, '.graphcool.backup'), '') const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool with yaml, non-existent backup file', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcool'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool with yaml, existing backup file', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcool'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) fs.outputFileSync( path.join(home, '.graphcool.backup'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool folder, non-existent backup file, non-existent .graphcoolrc', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcool/config.yml'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool folder, non-existent backup file, existing .graphcoolrc', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcool/config.yml'), `clusters: local2: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) fs.outputFileSync( path.join(home, '.graphcoolrc'), `graphcool-framework: clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token' graphcool-1.0: clusters: local: host: 'http://localhost:60002' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcool folder, existing backup folder (or file), execute 2 times', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcool/config.yml'), `clusters: local2: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) fs.outputFileSync( path.join(home, '.graphcool.backup'), `graphcool-framework: clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token' graphcool-1.0: clusters: local: host: 'http://localhost:60002' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() // migrate 2 times migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc folder, non-existent backup file', () => { const home = getTmpDir() fs.mkdirpSync(path.join(home, '.graphcoolrc')) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() // migrate 2 times migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc folder, existing backup folder (or file)', () => { const home = getTmpDir() fs.mkdirpSync(path.join(home, '.graphcoolrc')) fs.mkdirpSync(path.join(home, '.graphcoolrc.backup')) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc file with valid yaml, non-existent backup file', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcoolrc'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc file with valid yaml, existing backup folder (or file)', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcoolrc'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) fs.outputFileSync( path.join(home, '.graphcoolrc.backup'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc file with invalid yaml, non-existent backup file', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcoolrc'), `clusters local: host: http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) test('.graphcoolrc file with invalid yaml, existing backup folder (or file)', () => { const home = getTmpDir() fs.outputFileSync( path.join(home, '.graphcoolrc'), `clusters: local: host 'http://localhost:60000' remote: host: https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) fs.outputFileSync( path.join(home, '.graphcoolrc.backup'), `clusters: local: host: 'http://localhost:60000' remote: host: 'https://remote.graph.cool' clusterSecret: 'here-is-a-token'`, ) const out = new TestOutput() const migrator = new EnvironmentMigrator(home, out) migrator.migrate() expect(out.output).toMatchSnapshot() expect(fs.readdirSync(home)).toMatchSnapshot() expect( fs.readFileSync(path.join(home, '.graphcoolrc'), 'utf-8'), ).toMatchSnapshot() fs.removeSync(home) }) })
the_stack