hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "\n", "export class MarkdownString implements IMarkdownString {\n", "\n", "\tstatic isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean {\n", "\t\tif (MarkdownString.isMarkdownString(oneOrMany)) {\n", "\t\t\treturn Boolean(oneOrMany.value);\n", "\t\t} else if (Array.isArray(oneOrMany)) {\n", "\t\t\treturn oneOrMany.every(MarkdownString.isEmpty);\n", "\t\t} else {\n", "\t\t\treturn false;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn !oneOrMany.value;\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "panelActionTooltip": "{0} ({1})", "closePanel": "Paneli Kapat", "togglePanel": "Paneli Aç/Kapat", "focusPanel": "Panele Odakla", "toggleMaximizedPanel": "Panelin Ekranı Kaplamasını Aç/Kapat", "maximizePanel": "Panel Boyutunu Olabildiğince Genişlet", "minimizePanel": "Panel Boyutunu Geri Al", "view": "Görüntüle" }
i18n/trk/src/vs/workbench/browser/parts/panel/panelActions.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017424850375391543, 0.00017321181076113135, 0.00017217511776834726, 0.00017321181076113135, 0.0000010366929927840829 ]
{ "id": 0, "code_window": [ "\n", "export class MarkdownString implements IMarkdownString {\n", "\n", "\tstatic isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean {\n", "\t\tif (MarkdownString.isMarkdownString(oneOrMany)) {\n", "\t\t\treturn Boolean(oneOrMany.value);\n", "\t\t} else if (Array.isArray(oneOrMany)) {\n", "\t\t\treturn oneOrMany.every(MarkdownString.isEmpty);\n", "\t\t} else {\n", "\t\t\treturn false;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn !oneOrMany.value;\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "noFolderDebugConfig": "高度なデバッグ構成を行うには、最初にフォルダーを開いてください。" }
i18n/jpn/src/vs/workbench/parts/debug/electron-browser/debugCommands.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017381257202941924, 0.00017381257202941924, 0.00017381257202941924, 0.00017381257202941924, 0 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tappendCodeblock(langId: string, code: string): this {\n", "\t\tthis.value += '```';\n", "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import URI from 'vs/base/common/uri'; import { onUnexpectedError } from 'vs/base/common/errors'; import * as dom from 'vs/base/browser/dom'; import { TPromise } from 'vs/base/common/winjs.base'; import { renderMarkdown } from 'vs/base/browser/htmlContentRenderer'; import { IOpenerService, NullOpenerService } from 'vs/platform/opener/common/opener'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IRange, Range } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import { HoverProviderRegistry, Hover, IColor, IColorFormatter } from 'vs/editor/common/modes'; import { tokenizeToString } from 'vs/editor/common/modes/textToHtmlTokenizer'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { getHover } from '../common/hover'; import { HoverOperation, IHoverComputer } from './hoverOperation'; import { ContentHoverWidget } from './hoverWidgets'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModelWithDecorations'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { ColorPickerWidget } from 'vs/editor/contrib/colorPicker/browser/colorPickerWidget'; import { ColorDetector } from 'vs/editor/contrib/colorPicker/browser/colorDetector'; import { Color, RGBA } from 'vs/base/common/color'; import { IDisposable, empty as EmptyDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle'; const $ = dom.$; class ColorHover { constructor( public readonly range: IRange, public readonly color: IColor, public readonly formatters: IColorFormatter[] ) { } } type HoverPart = Hover | ColorHover; class ModesContentComputer implements IHoverComputer<HoverPart[]> { private _editor: ICodeEditor; private _result: HoverPart[]; private _range: Range; constructor(editor: ICodeEditor) { this._editor = editor; this._range = null; } setRange(range: Range): void { this._range = range; this._result = []; } clearResult(): void { this._result = []; } computeAsync(): TPromise<HoverPart[]> { const model = this._editor.getModel(); if (!HoverProviderRegistry.has(model)) { return TPromise.as(null); } return getHover(model, new Position( this._range.startLineNumber, this._range.startColumn )); } computeSync(): HoverPart[] { const lineNumber = this._range.startLineNumber; if (lineNumber > this._editor.getModel().getLineCount()) { // Illegal line number => no results return []; } const colorDetector = ColorDetector.get(this._editor); const maxColumn = this._editor.getModel().getLineMaxColumn(lineNumber); const lineDecorations = this._editor.getLineDecorations(lineNumber); let didFindColor = false; const result = lineDecorations.map(d => { const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1; const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn; if (startColumn > this._range.startColumn || this._range.endColumn > endColumn) { return null; } const range = new Range(this._range.startLineNumber, startColumn, this._range.startLineNumber, endColumn); const colorRange = colorDetector.getColorRange(d.range.getStartPosition()); if (!didFindColor && colorRange) { didFindColor = true; const { color, formatters } = colorRange; return new ColorHover(d.range, color, formatters); } else { if (MarkdownString.isEmpty(d.options.hoverMessage)) { return null; } let contents: IMarkdownString[]; if (d.options.hoverMessage) { if (Array.isArray(d.options.hoverMessage)) { contents = [...d.options.hoverMessage]; } else { contents = [d.options.hoverMessage]; } } return { contents, range }; } }); return result.filter(d => !!d); } onResult(result: HoverPart[], isFromSynchronousComputation: boolean): void { // Always put synchronous messages before asynchronous ones if (isFromSynchronousComputation) { this._result = result.concat(this._result.sort((a, b) => { if (a instanceof ColorHover) { // sort picker messages at to the top return -1; } else if (b instanceof ColorHover) { return 1; } return 0; })); } else { this._result = this._result.concat(result); } } getResult(): HoverPart[] { return this._result.slice(0); } getResultWithLoadingMessage(): HoverPart[] { return this._result.slice(0).concat([this._getLoadingMessage()]); } private _getLoadingMessage(): HoverPart { return { range: this._range, contents: [new MarkdownString().appendText(nls.localize('modesContentHover.loading', "Loading..."))] }; } } export class ModesContentHoverWidget extends ContentHoverWidget { static ID = 'editor.contrib.modesContentHoverWidget'; private _messages: HoverPart[]; private _lastRange: Range; private _computer: ModesContentComputer; private _hoverOperation: HoverOperation<HoverPart[]>; private _highlightDecorations: string[]; private _isChangingDecorations: boolean; private _openerService: IOpenerService; private _modeService: IModeService; private _shouldFocus: boolean; private _colorPicker: ColorPickerWidget; private renderDisposable: IDisposable = EmptyDisposable; private toDispose: IDisposable[]; constructor(editor: ICodeEditor, openerService: IOpenerService, modeService: IModeService) { super(ModesContentHoverWidget.ID, editor); this._computer = new ModesContentComputer(this._editor); this._highlightDecorations = []; this._isChangingDecorations = false; this._openerService = openerService || NullOpenerService; this._modeService = modeService; this._hoverOperation = new HoverOperation( this._computer, result => this._withResult(result, true), null, result => this._withResult(result, false) ); this.toDispose = []; this.toDispose.push(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.FOCUS, () => { if (this._colorPicker) { dom.addClass(this.getDomNode(), 'colorpicker-hover'); } })); this.toDispose.push(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.BLUR, () => { dom.removeClass(this.getDomNode(), 'colorpicker-hover'); })); } dispose(): void { this.renderDisposable.dispose(); this.renderDisposable = EmptyDisposable; this._hoverOperation.cancel(); this.toDispose = dispose(this.toDispose); super.dispose(); } onModelDecorationsChanged(): void { if (this._isChangingDecorations) { return; } if (this.isVisible) { // The decorations have changed and the hover is visible, // we need to recompute the displayed text this._hoverOperation.cancel(); this._computer.clearResult(); if (!this._colorPicker) { // TODO@Michel ensure that displayed text for other decorations is computed even if color picker is in place this._hoverOperation.start(); } } } startShowingAt(range: Range, focus: boolean): void { if (this._lastRange && this._lastRange.equalsRange(range)) { // We have to show the widget at the exact same range as before, so no work is needed return; } this._hoverOperation.cancel(); if (this.isVisible) { // The range might have changed, but the hover is visible // Instead of hiding it completely, filter out messages that are still in the new range and // kick off a new computation if (this._showAtPosition.lineNumber !== range.startLineNumber) { this.hide(); } else { var filteredMessages: HoverPart[] = []; for (var i = 0, len = this._messages.length; i < len; i++) { var msg = this._messages[i]; var rng = msg.range; if (rng.startColumn <= range.startColumn && rng.endColumn >= range.endColumn) { filteredMessages.push(msg); } } if (filteredMessages.length > 0) { this._renderMessages(range, filteredMessages); } else { this.hide(); } } } this._lastRange = range; this._computer.setRange(range); this._shouldFocus = focus; this._hoverOperation.start(); } hide(): void { this._lastRange = null; this._hoverOperation.cancel(); super.hide(); this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, []); this._isChangingDecorations = false; this.renderDisposable.dispose(); this.renderDisposable = EmptyDisposable; this._colorPicker = null; } isColorPickerVisible(): boolean { if (this._colorPicker) { return true; } return false; } private _withResult(result: HoverPart[], complete: boolean): void { this._messages = result; if (this._lastRange && this._messages.length > 0) { this._renderMessages(this._lastRange, this._messages); } else if (complete) { this.hide(); } } private _renderMessages(renderRange: Range, messages: HoverPart[]): void { this.renderDisposable.dispose(); this._colorPicker = null; // update column from which to show var renderColumn = Number.MAX_VALUE, highlightRange = messages[0].range, fragment = document.createDocumentFragment(); messages.forEach((msg) => { if (!msg.range) { return; } renderColumn = Math.min(renderColumn, msg.range.startColumn); highlightRange = Range.plusRange(highlightRange, msg.range); if (!(msg instanceof ColorHover)) { msg.contents .filter(contents => !!contents) .forEach(contents => { const renderedContents = renderMarkdown(contents, { actionCallback: (content) => { this._openerService.open(URI.parse(content)).then(void 0, onUnexpectedError); }, codeBlockRenderer: (languageAlias, value): string | TPromise<string> => { // In markdown, // it is possible that we stumble upon language aliases (e.g.js instead of javascript) // it is possible no alias is given in which case we fall back to the current editor lang const modeId = languageAlias ? this._modeService.getModeIdForLanguageName(languageAlias) : this._editor.getModel().getLanguageIdentifier().language; return this._modeService.getOrCreateMode(modeId).then(_ => { return tokenizeToString(value, modeId); }); } }); fragment.appendChild($('div.hover-row', null, renderedContents)); }); } else { const { red, green, blue, alpha } = msg.color; const rgba = new RGBA(red * 255, green * 255, blue * 255, alpha); const color = new Color(rgba); const formatters = [...msg.formatters]; const text = this._editor.getModel().getValueInRange(msg.range); let formatterIndex = 0; for (let i = 0; i < formatters.length; i++) { if (text === formatters[i].format(color)) { formatterIndex = i; break; } } const model = new ColorPickerModel(color, formatters, formatterIndex); const widget = new ColorPickerWidget(fragment, model, this._editor.getConfiguration().pixelRatio); const editorModel = this._editor.getModel(); let range = new Range(msg.range.startLineNumber, msg.range.startColumn, msg.range.endLineNumber, msg.range.endColumn); const updateEditorModel = () => { const text = model.formatter.format(model.color); editorModel.pushEditOperations([], [{ identifier: null, range, text, forceMoveMarkers: false }], () => []); range = range.setEndPosition(range.endLineNumber, range.startColumn + text.length); }; const colorListener = model.onDidChangeColor(updateEditorModel); const formatterListener = model.onDidChangeFormatter(updateEditorModel); this._colorPicker = widget; this.renderDisposable = combinedDisposable([colorListener, formatterListener, widget]); } }); // show this.showAt(new Position(renderRange.startLineNumber, renderColumn), this._shouldFocus); this.updateContents(fragment); if (this._colorPicker) { this._colorPicker.layout(); } this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, [{ range: highlightRange, options: ModesContentHoverWidget._DECORATION_OPTIONS }]); this._isChangingDecorations = false; } private static _DECORATION_OPTIONS = ModelDecorationOptions.register({ className: 'hoverHighlight' }); }
src/vs/editor/contrib/hover/browser/modesContentHover.ts
1
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.0016187709989026189, 0.00021003372967243195, 0.00016507112013641745, 0.00017166766338050365, 0.00022587782586924732 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tappendCodeblock(langId: string, code: string): this {\n", "\t\tthis.value += '```';\n", "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/scmViewlet'; import { localize } from 'vs/nls'; import { TPromise } from 'vs/base/common/winjs.base'; import { chain } from 'vs/base/common/event'; import { onUnexpectedError } from 'vs/base/common/errors'; import * as platform from 'vs/base/common/platform'; import { domEvent } from 'vs/base/browser/event'; import { IDisposable, dispose, empty as EmptyDisposable, combinedDisposable } from 'vs/base/common/lifecycle'; import { Builder, Dimension } from 'vs/base/browser/builder'; import { Viewlet } from 'vs/workbench/browser/viewlet'; import { append, $, toggleClass } from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IDelegate, IRenderer, IListContextMenuEvent } from 'vs/base/browser/ui/list/list'; import { VIEWLET_ID } from 'vs/workbench/parts/scm/common/scm'; import { FileLabel } from 'vs/workbench/browser/labels'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { ISCMService, ISCMProvider, ISCMResourceGroup, ISCMResource } from 'vs/workbench/services/scm/common/scm'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService } from 'vs/platform/message/common/message'; import { IListService } from 'vs/platform/list/browser/listService'; import { IMenuService, MenuItemAction } from 'vs/platform/actions/common/actions'; import { IAction, IActionItem, ActionRunner } from 'vs/base/common/actions'; import { MenuItemActionItem } from 'vs/platform/actions/browser/menuItemActionItem'; import { SCMMenus } from './scmMenus'; import { ActionBar, IActionItemProvider } from 'vs/base/browser/ui/actionbar/actionbar'; import { IThemeService, LIGHT } from 'vs/platform/theme/common/themeService'; import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { IModelService } from 'vs/editor/common/services/modelService'; import { comparePaths } from 'vs/base/common/comparers'; import { isSCMResource } from './scmUtil'; import { attachInputBoxStyler, attachListStyler, attachBadgeStyler } from 'vs/platform/theme/common/styler'; import Severity from 'vs/base/common/severity'; // TODO@Joao // Need to subclass MenuItemActionItem in order to respect // the action context coming from any action bar, without breaking // existing users class SCMMenuItemActionItem extends MenuItemActionItem { onClick(event: MouseEvent): void { event.preventDefault(); event.stopPropagation(); this.actionRunner.run(this._commandAction, this._context) .done(undefined, err => this._messageService.show(Severity.Error, err)); } } function identityProvider(r: ISCMResourceGroup | ISCMResource): string { if (isSCMResource(r)) { const group = r.resourceGroup; const provider = group.provider; return `${provider.id}/${group.id}/${r.sourceUri.toString()}`; } else { const provider = r.provider; return `${provider.id}/${r.id}`; } } interface SearchInputEvent extends Event { target: HTMLInputElement; immediate?: boolean; } interface ResourceGroupTemplate { name: HTMLElement; count: CountBadge; actionBar: ActionBar; dispose: () => void; } class ResourceGroupRenderer implements IRenderer<ISCMResourceGroup, ResourceGroupTemplate> { static TEMPLATE_ID = 'resource group'; get templateId(): string { return ResourceGroupRenderer.TEMPLATE_ID; } constructor( private scmMenus: SCMMenus, private actionItemProvider: IActionItemProvider, private themeService: IThemeService ) { } renderTemplate(container: HTMLElement): ResourceGroupTemplate { const element = append(container, $('.resource-group')); const name = append(element, $('.name')); const actionsContainer = append(element, $('.actions')); const actionBar = new ActionBar(actionsContainer, { actionItemProvider: this.actionItemProvider }); const countContainer = append(element, $('.count')); const count = new CountBadge(countContainer); const styler = attachBadgeStyler(count, this.themeService); return { name, count, actionBar, dispose: () => { actionBar.dispose(); styler.dispose(); } }; } renderElement(group: ISCMResourceGroup, index: number, template: ResourceGroupTemplate): void { template.name.textContent = group.label; template.count.setCount(group.resources.length); template.actionBar.clear(); template.actionBar.context = group; template.actionBar.push(this.scmMenus.getResourceGroupActions(group)); } disposeTemplate(template: ResourceGroupTemplate): void { template.dispose(); } } interface ResourceTemplate { element: HTMLElement; name: HTMLElement; fileLabel: FileLabel; decorationIcon: HTMLElement; actionBar: ActionBar; } class MultipleSelectionActionRunner extends ActionRunner { constructor(private getSelectedResources: () => ISCMResource[]) { super(); } runAction(action: IAction, context: ISCMResource): TPromise<any> { if (action instanceof MenuItemAction) { const selection = this.getSelectedResources(); const filteredSelection = selection.filter(s => s !== context); if (selection.length === filteredSelection.length || selection.length === 1) { return action.run(context); } return action.run(context, ...filteredSelection); } return super.runAction(action, context); } } class ResourceRenderer implements IRenderer<ISCMResource, ResourceTemplate> { static TEMPLATE_ID = 'resource'; get templateId(): string { return ResourceRenderer.TEMPLATE_ID; } constructor( private scmMenus: SCMMenus, private actionItemProvider: IActionItemProvider, private getSelectedResources: () => ISCMResource[], @IThemeService private themeService: IThemeService, @IInstantiationService private instantiationService: IInstantiationService ) { } renderTemplate(container: HTMLElement): ResourceTemplate { const element = append(container, $('.resource')); const name = append(element, $('.name')); const fileLabel = this.instantiationService.createInstance(FileLabel, name, void 0); const actionsContainer = append(element, $('.actions')); const actionBar = new ActionBar(actionsContainer, { actionItemProvider: this.actionItemProvider, actionRunner: new MultipleSelectionActionRunner(this.getSelectedResources) }); const decorationIcon = append(element, $('.decoration-icon')); return { element, name, fileLabel, decorationIcon, actionBar }; } renderElement(resource: ISCMResource, index: number, template: ResourceTemplate): void { template.fileLabel.setFile(resource.sourceUri); template.actionBar.clear(); template.actionBar.context = resource; template.actionBar.push(this.scmMenus.getResourceActions(resource)); toggleClass(template.name, 'strike-through', resource.decorations.strikeThrough); toggleClass(template.element, 'faded', resource.decorations.faded); const theme = this.themeService.getTheme(); const icon = theme.type === LIGHT ? resource.decorations.icon : resource.decorations.iconDark; if (icon) { template.decorationIcon.style.backgroundImage = `url('${icon}')`; template.decorationIcon.title = resource.decorations.tooltip; } else { template.decorationIcon.style.backgroundImage = ''; } } disposeTemplate(template: ResourceTemplate): void { // noop } } class Delegate implements IDelegate<ISCMResourceGroup | ISCMResource> { getHeight() { return 22; } getTemplateId(element: ISCMResourceGroup | ISCMResource) { return isSCMResource(element) ? ResourceRenderer.TEMPLATE_ID : ResourceGroupRenderer.TEMPLATE_ID; } } function resourceSorter(a: ISCMResource, b: ISCMResource): number { return comparePaths(a.sourceUri.fsPath, b.sourceUri.fsPath); } export class SCMViewlet extends Viewlet { private activeProvider: ISCMProvider | undefined; private cachedDimension: Dimension; private inputBoxContainer: HTMLElement; private inputBox: InputBox; private listContainer: HTMLElement; private list: List<ISCMResourceGroup | ISCMResource>; private menus: SCMMenus; private providerChangeDisposable: IDisposable = EmptyDisposable; private disposables: IDisposable[] = []; constructor( @ITelemetryService telemetryService: ITelemetryService, @ISCMService private scmService: ISCMService, @IInstantiationService private instantiationService: IInstantiationService, @IContextViewService private contextViewService: IContextViewService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IMessageService private messageService: IMessageService, @IListService private listService: IListService, @IContextMenuService private contextMenuService: IContextMenuService, @IThemeService protected themeService: IThemeService, @IMenuService private menuService: IMenuService, @IModelService private modelService: IModelService, @ICommandService private commandService: ICommandService, @IEditorGroupService private groupService: IEditorGroupService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService ) { super(VIEWLET_ID, telemetryService, themeService); this.menus = this.instantiationService.createInstance(SCMMenus); this.menus.onDidChangeTitle(this.updateTitleArea, this, this.disposables); this.disposables.push(this.menus); } private setActiveProvider(activeProvider: ISCMProvider | undefined): void { this.providerChangeDisposable.dispose(); this.activeProvider = activeProvider; if (activeProvider) { const disposables = [activeProvider.onDidChange(this.update, this)]; if (activeProvider.onDidChangeCommitTemplate) { disposables.push(activeProvider.onDidChangeCommitTemplate(this.updateInputBox, this)); } this.providerChangeDisposable = combinedDisposable(disposables); } else { this.providerChangeDisposable = EmptyDisposable; } this.updateInputBox(); this.updateTitleArea(); this.update(); } create(parent: Builder): TPromise<void> { super.create(parent); parent.addClass('scm-viewlet'); const root = parent.getHTMLElement(); this.inputBoxContainer = append(root, $('.scm-editor')); this.inputBox = new InputBox(this.inputBoxContainer, this.contextViewService, { placeholder: localize('commitMessage', "Message (press {0} to commit)", platform.isMacintosh ? 'Cmd+Enter' : 'Ctrl+Enter'), flexibleHeight: true }); this.disposables.push(attachInputBoxStyler(this.inputBox, this.themeService)); this.disposables.push(this.inputBox); this.inputBox.value = this.scmService.input.value; this.inputBox.onDidChange(value => this.scmService.input.value = value, null, this.disposables); this.scmService.input.onDidChange(value => this.inputBox.value = value, null, this.disposables); this.disposables.push(this.inputBox.onDidHeightChange(() => this.layout())); chain(domEvent(this.inputBox.inputElement, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.equals(KeyMod.CtrlCmd | KeyCode.Enter) || e.equals(KeyMod.CtrlCmd | KeyCode.KEY_S)) .on(this.onDidAcceptInput, this, this.disposables); this.listContainer = append(root, $('.scm-status.show-file-icons')); const delegate = new Delegate(); const actionItemProvider = action => this.getActionItem(action); const renderers = [ new ResourceGroupRenderer(this.menus, actionItemProvider, this.themeService), this.instantiationService.createInstance(ResourceRenderer, this.menus, actionItemProvider, () => this.getSelectedResources()), ]; this.list = new List(this.listContainer, delegate, renderers, { identityProvider, keyboardSupport: false }); this.disposables.push(attachListStyler(this.list, this.themeService)); this.disposables.push(this.listService.register(this.list)); chain(this.list.onOpen) .map(e => e.elements[0]) .filter(e => !!e && isSCMResource(e)) .on(this.open, this, this.disposables); chain(this.list.onPin) .map(e => e.elements[0]) .filter(e => !!e && isSCMResource(e)) .on(this.pin, this, this.disposables); this.list.onContextMenu(this.onListContextMenu, this, this.disposables); this.disposables.push(this.list); this.setActiveProvider(this.scmService.activeProvider); this.scmService.onDidChangeProvider(this.setActiveProvider, this, this.disposables); this.themeService.onThemeChange(this.update, this, this.disposables); return TPromise.as(null); } private onDidAcceptInput(): void { if (!this.activeProvider) { return; } if (!this.activeProvider.acceptInputCommand) { return; } const id = this.activeProvider.acceptInputCommand.id; const args = this.activeProvider.acceptInputCommand.arguments; this.commandService.executeCommand(id, ...args) .done(undefined, onUnexpectedError); } private update(): void { const provider = this.scmService.activeProvider; if (!provider) { this.list.splice(0, this.list.length); return; } const elements = provider.resources .reduce<(ISCMResourceGroup | ISCMResource)[]>((r, g) => [...r, g, ...g.resources.sort(resourceSorter)], []); this.list.splice(0, this.list.length, elements); } private updateInputBox(): void { if (!this.activeProvider) { return; } if (typeof this.activeProvider.commitTemplate === 'undefined') { return; } this.inputBox.value = this.activeProvider.commitTemplate; } layout(dimension: Dimension = this.cachedDimension): void { if (!dimension) { return; } this.cachedDimension = dimension; this.inputBox.layout(); const editorHeight = this.inputBox.height; const listHeight = dimension.height - (editorHeight + 12 /* margin */); this.listContainer.style.height = `${listHeight}px`; this.list.layout(listHeight); toggleClass(this.inputBoxContainer, 'scroll', editorHeight >= 134); } getOptimalWidth(): number { return 400; } focus(): void { super.focus(); this.inputBox.focus(); } private open(e: ISCMResource): void { if (!e.command) { return; } this.commandService.executeCommand(e.command.id, ...e.command.arguments) .done(undefined, onUnexpectedError); } private pin(): void { const activeEditor = this.editorService.getActiveEditor(); const activeEditorInput = this.editorService.getActiveEditorInput(); this.groupService.pinEditor(activeEditor.position, activeEditorInput); } getTitle(): string { const title = localize('source control', "Source Control"); const providerLabel = this.scmService.activeProvider && this.scmService.activeProvider.label; if (providerLabel) { return localize('viewletTitle', "{0}: {1}", title, providerLabel); } else { return title; } } getActions(): IAction[] { return this.menus.getTitleActions(); } getSecondaryActions(): IAction[] { return this.menus.getTitleSecondaryActions(); } getActionItem(action: IAction): IActionItem { if (!(action instanceof MenuItemAction)) { return undefined; } return new SCMMenuItemActionItem(action, this.keybindingService, this.messageService); } private onListContextMenu(e: IListContextMenuEvent<ISCMResourceGroup | ISCMResource>): void { const element = e.element; let actions: IAction[]; if (isSCMResource(element)) { actions = this.menus.getResourceContextActions(element); } else { actions = this.menus.getResourceGroupContextActions(element); } this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => TPromise.as(actions), getActionsContext: () => element, actionRunner: new MultipleSelectionActionRunner(() => this.getSelectedResources()) }); } private getSelectedResources(): ISCMResource[] { return this.list.getSelectedElements() .filter(r => isSCMResource(r)) as ISCMResource[]; } dispose(): void { this.disposables = dispose(this.disposables); super.dispose(); } }
src/vs/workbench/parts/scm/electron-browser/scmViewlet.ts
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.0002396258496446535, 0.000173280990566127, 0.0001644320582272485, 0.00017140962881967425, 0.000011499136235215701 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tappendCodeblock(langId: string, code: string): this {\n", "\t\tthis.value += '```';\n", "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "binaryFileEditor": "Visualizzatore file binari" }
i18n/ita/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017724029021337628, 0.00017724029021337628, 0.00017724029021337628, 0.00017724029021337628, 0 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tappendCodeblock(langId: string, code: string): this {\n", "\t\tthis.value += '```';\n", "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "notFound": "L'estensione non è stata trovata", "noCompatible": "Non è stata trovata una versione di {0} compatibile con questa versione di Visual Studio Code." }
i18n/ita/src/vs/platform/extensionManagement/node/extensionGalleryService.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017470918828621507, 0.00017470918828621507, 0.00017470918828621507, 0.00017470918828621507, 0 ]
{ "id": 2, "code_window": [ "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n", "\t\tthis.value += '```\\n';\n", "\t\treturn this;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```\\n';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { equals } from 'vs/base/common/arrays'; import { marked } from 'vs/base/common/marked/marked'; export interface IMarkdownString { value: string; trusted?: true; } export class MarkdownString implements IMarkdownString { static isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean { if (MarkdownString.isMarkdownString(oneOrMany)) { return Boolean(oneOrMany.value); } else if (Array.isArray(oneOrMany)) { return oneOrMany.every(MarkdownString.isEmpty); } else { return false; } } static isMarkdownString(thing: any): thing is IMarkdownString { if (thing instanceof MarkdownString) { return true; } else if (typeof thing === 'object') { return typeof (<IMarkdownString>thing).value === 'string' && (typeof (<IMarkdownString>thing).trusted === 'boolean' || (<IMarkdownString>thing).trusted === void 0); } return false; } value: string; trusted?: true; constructor(value: string = '') { this.value = value; } appendText(value: string): this { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash this.value += value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); return this; } appendCodeblock(langId: string, code: string): this { this.value += '```'; this.value += langId; this.value += '\n'; this.value += code; this.value += '```\n'; return this; } } export function markedStringsEquals(a: IMarkdownString | IMarkdownString[], b: IMarkdownString | IMarkdownString[]): boolean { if (!a && !b) { return true; } else if (!a || !b) { return false; } else if (Array.isArray(a) && Array.isArray(b)) { return equals(a, b, markdownStringEqual); } else if (MarkdownString.isMarkdownString(a) && MarkdownString.isMarkdownString(b)) { return markdownStringEqual(a, b); } else { return false; } } function markdownStringEqual(a: IMarkdownString, b: IMarkdownString): boolean { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.value === b.value && a.trusted === b.trusted; } } export function removeMarkdownEscapes(text: string): string { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); } export function containsCommandLink(value: string): boolean { let uses = false; const renderer = new marked.Renderer(); renderer.link = (href, title, text): string => { if (href.match(/^command:/i)) { uses = true; } return 'link'; }; marked(value, { renderer }); return uses; }
src/vs/base/common/htmlContent.ts
1
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.9960046410560608, 0.09073920547962189, 0.00016444695938844234, 0.00017257056606467813, 0.2862700819969177 ]
{ "id": 2, "code_window": [ "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n", "\t\tthis.value += '```\\n';\n", "\t\treturn this;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```\\n';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IRange } from 'vs/editor/common/core/range'; /** * @internal */ export const TextModelEventType = { ModelDispose: 'modelDispose', ModelTokensChanged: 'modelTokensChanged', ModelLanguageChanged: 'modelLanguageChanged', ModelOptionsChanged: 'modelOptionsChanged', ModelContentChanged: 'contentChanged', ModelRawContentChanged2: 'rawContentChanged2', ModelDecorationsChanged: 'decorationsChanged', }; /** * An event describing that the current mode associated with a model has changed. */ export interface IModelLanguageChangedEvent { /** * Previous language */ readonly oldLanguage: string; /** * New language */ readonly newLanguage: string; } export interface IModelContentChange { /** * The range that got replaced. */ readonly range: IRange; /** * The length of the range that got replaced. */ readonly rangeLength: number; /** * The new text for the range. */ readonly text: string; } /** * An event describing a change in the text of a model. */ export interface IModelContentChangedEvent { readonly changes: IModelContentChange[]; /** * The (new) end-of-line character. */ readonly eol: string; /** * The new version id the model has transitioned to. */ readonly versionId: number; /** * Flag that indicates that this event was generated while undoing. */ readonly isUndoing: boolean; /** * Flag that indicates that this event was generated while redoing. */ readonly isRedoing: boolean; /** * Flag that indicates that all decorations were lost with this edit. * The model has been reset to a new value. */ readonly isFlush: boolean; } /** * An event describing that model decorations have changed. */ export interface IModelDecorationsChangedEvent { /** * Lists of ids for added decorations. */ readonly addedDecorations: string[]; /** * Lists of ids for changed decorations. */ readonly changedDecorations: string[]; /** * List of ids for removed decorations. */ readonly removedDecorations: string[]; } /** * An event describing that some ranges of lines have been tokenized (their tokens have changed). */ export interface IModelTokensChangedEvent { readonly ranges: { /** * The start of the range (inclusive) */ readonly fromLineNumber: number; /** * The end of the range (inclusive) */ readonly toLineNumber: number; }[]; } export interface IModelOptionsChangedEvent { readonly tabSize: boolean; readonly insertSpaces: boolean; readonly trimAutoWhitespace: boolean; } /** * @internal */ export const enum RawContentChangedType { Flush = 1, LineChanged = 2, LinesDeleted = 3, LinesInserted = 4, EOLChanged = 5 } /** * An event describing that a model has been reset to a new value. * @internal */ export class ModelRawFlush { public readonly changeType = RawContentChangedType.Flush; } /** * An event describing that a line has changed in a model. * @internal */ export class ModelRawLineChanged { public readonly changeType = RawContentChangedType.LineChanged; /** * The line that has changed. */ public readonly lineNumber: number; /** * The new value of the line. */ public readonly detail: string; constructor(lineNumber: number, detail: string) { this.lineNumber = lineNumber; this.detail = detail; } } /** * An event describing that line(s) have been deleted in a model. * @internal */ export class ModelRawLinesDeleted { public readonly changeType = RawContentChangedType.LinesDeleted; /** * At what line the deletion began (inclusive). */ public readonly fromLineNumber: number; /** * At what line the deletion stopped (inclusive). */ public readonly toLineNumber: number; constructor(fromLineNumber: number, toLineNumber: number) { this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } } /** * An event describing that line(s) have been inserted in a model. * @internal */ export class ModelRawLinesInserted { public readonly changeType = RawContentChangedType.LinesInserted; /** * Before what line did the insertion begin */ public readonly fromLineNumber: number; /** * `toLineNumber` - `fromLineNumber` + 1 denotes the number of lines that were inserted */ public readonly toLineNumber: number; /** * The text that was inserted */ public readonly detail: string; constructor(fromLineNumber: number, toLineNumber: number, detail: string) { this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; this.detail = detail; } } /** * An event describing that a model has had its EOL changed. * @internal */ export class ModelRawEOLChanged { public readonly changeType = RawContentChangedType.EOLChanged; } /** * @internal */ export type ModelRawChange = ModelRawFlush | ModelRawLineChanged | ModelRawLinesDeleted | ModelRawLinesInserted | ModelRawEOLChanged; /** * An event describing a change in the text of a model. * @internal */ export class ModelRawContentChangedEvent { public readonly changes: ModelRawChange[]; /** * The new version id the model has transitioned to. */ public readonly versionId: number; /** * Flag that indicates that this event was generated while undoing. */ public readonly isUndoing: boolean; /** * Flag that indicates that this event was generated while redoing. */ public readonly isRedoing: boolean; constructor(changes: ModelRawChange[], versionId: number, isUndoing: boolean, isRedoing: boolean) { this.changes = changes; this.versionId = versionId; this.isUndoing = isUndoing; this.isRedoing = isRedoing; } public containsEvent(type: RawContentChangedType): boolean { for (let i = 0, len = this.changes.length; i < len; i++) { const change = this.changes[i]; if (change.changeType === type) { return true; } } return false; } }
src/vs/editor/common/model/textModelEvents.ts
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00019963506201747805, 0.00017157265392597765, 0.000164747194503434, 0.00016981709632091224, 0.0000067322130234970246 ]
{ "id": 2, "code_window": [ "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n", "\t\tthis.value += '```\\n';\n", "\t\treturn this;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```\\n';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "removeFromActivityBar": "Quitar de la barra de actividades", "keepInActivityBar": "Guardar en la barra de la actividad", "titleKeybinding": "{0} ({1})", "additionalViews": "Vistas adicionales", "numberBadge": "{0} ({1})", "manageExtension": "Administrar extensión", "toggle": "Alternar vista fijada" }
i18n/esn/src/vs/workbench/browser/parts/activitybar/activitybarActions.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.0001764965709298849, 0.00017538134125061333, 0.00017426611157134175, 0.00017538134125061333, 0.0000011152296792715788 ]
{ "id": 2, "code_window": [ "\t\tthis.value += langId;\n", "\t\tthis.value += '\\n';\n", "\t\tthis.value += code;\n", "\t\tthis.value += '```\\n';\n", "\t\treturn this;\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.value += '\\n```\\n';\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "terminalLinkHandler.followLinkAlt": "Alt + clic pour suivre le lien", "terminalLinkHandler.followLinkCmd": "Commande + clic pour suivre le lien", "terminalLinkHandler.followLinkCtrl": "Ctrl + clic pour suivre le lien" }
i18n/fra/src/vs/workbench/parts/terminal/electron-browser/terminalLinkHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017599544662516564, 0.00017573771765455604, 0.00017548000323586166, 0.00017573771765455604, 2.5772169465199113e-7 ]
{ "id": 3, "code_window": [ "\t\t\thighlightRange = Range.plusRange(highlightRange, msg.range);\n", "\n", "\t\t\tif (!(msg instanceof ColorHover)) {\n", "\t\t\t\tmsg.contents\n", "\t\t\t\t\t.filter(contents => !!contents)\n", "\t\t\t\t\t.forEach(contents => {\n", "\t\t\t\t\t\tconst renderedContents = renderMarkdown(contents, {\n", "\t\t\t\t\t\t\tactionCallback: (content) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t.filter(contents => !MarkdownString.isEmpty(contents))\n" ], "file_path": "src/vs/editor/contrib/hover/browser/modesContentHover.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { equals } from 'vs/base/common/arrays'; import { marked } from 'vs/base/common/marked/marked'; export interface IMarkdownString { value: string; trusted?: true; } export class MarkdownString implements IMarkdownString { static isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean { if (MarkdownString.isMarkdownString(oneOrMany)) { return Boolean(oneOrMany.value); } else if (Array.isArray(oneOrMany)) { return oneOrMany.every(MarkdownString.isEmpty); } else { return false; } } static isMarkdownString(thing: any): thing is IMarkdownString { if (thing instanceof MarkdownString) { return true; } else if (typeof thing === 'object') { return typeof (<IMarkdownString>thing).value === 'string' && (typeof (<IMarkdownString>thing).trusted === 'boolean' || (<IMarkdownString>thing).trusted === void 0); } return false; } value: string; trusted?: true; constructor(value: string = '') { this.value = value; } appendText(value: string): this { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash this.value += value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); return this; } appendCodeblock(langId: string, code: string): this { this.value += '```'; this.value += langId; this.value += '\n'; this.value += code; this.value += '```\n'; return this; } } export function markedStringsEquals(a: IMarkdownString | IMarkdownString[], b: IMarkdownString | IMarkdownString[]): boolean { if (!a && !b) { return true; } else if (!a || !b) { return false; } else if (Array.isArray(a) && Array.isArray(b)) { return equals(a, b, markdownStringEqual); } else if (MarkdownString.isMarkdownString(a) && MarkdownString.isMarkdownString(b)) { return markdownStringEqual(a, b); } else { return false; } } function markdownStringEqual(a: IMarkdownString, b: IMarkdownString): boolean { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.value === b.value && a.trusted === b.trusted; } } export function removeMarkdownEscapes(text: string): string { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); } export function containsCommandLink(value: string): boolean { let uses = false; const renderer = new marked.Renderer(); renderer.link = (href, title, text): string => { if (href.match(/^command:/i)) { uses = true; } return 'link'; }; marked(value, { renderer }); return uses; }
src/vs/base/common/htmlContent.ts
1
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.001293521374464035, 0.0002951249771285802, 0.00016459738253615797, 0.0001737169804982841, 0.00032165381708182395 ]
{ "id": 3, "code_window": [ "\t\t\thighlightRange = Range.plusRange(highlightRange, msg.range);\n", "\n", "\t\t\tif (!(msg instanceof ColorHover)) {\n", "\t\t\t\tmsg.contents\n", "\t\t\t\t\t.filter(contents => !!contents)\n", "\t\t\t\t\t.forEach(contents => {\n", "\t\t\t\t\t\tconst renderedContents = renderMarkdown(contents, {\n", "\t\t\t\t\t\t\tactionCallback: (content) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t.filter(contents => !MarkdownString.isEmpty(contents))\n" ], "file_path": "src/vs/editor/contrib/hover/browser/modesContentHover.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { KeybindingEditorDecorationsRenderer } from 'vs/workbench/parts/preferences/browser/keybindingsEditorContribution'; suite('KeybindingsEditorContribution', () => { function assertUserSettingsFuzzyEquals(a: string, b: string, expected: boolean): void { const actual = KeybindingEditorDecorationsRenderer._userSettingsFuzzyEquals(a, b); const message = expected ? `${a} == ${b}` : `${a} != ${b}`; assert.equal(actual, expected, 'fuzzy: ' + message); } function assertEqual(a: string, b: string): void { assertUserSettingsFuzzyEquals(a, b, true); } function assertDifferent(a: string, b: string): void { assertUserSettingsFuzzyEquals(a, b, false); } test('_userSettingsFuzzyEquals', () => { assertEqual('a', 'a'); assertEqual('a', 'A'); assertEqual('ctrl+a', 'CTRL+A'); assertEqual('ctrl+a', ' CTRL+A '); assertEqual('ctrl+shift+a', 'shift+ctrl+a'); assertEqual('ctrl+shift+a ctrl+alt+b', 'shift+ctrl+a alt+ctrl+b'); assertDifferent('ctrl+[KeyA]', 'ctrl+a'); // issue #23335 assertEqual('cmd+shift+p', 'shift+cmd+p'); assertEqual('cmd+shift+p', 'shift-cmd-p'); }); });
src/vs/workbench/parts/preferences/test/browser/keybindingsEditorContribution.test.ts
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017654182738624513, 0.00017360158381052315, 0.00017055014905054122, 0.00017394355381838977, 0.000002167639877370675 ]
{ "id": 3, "code_window": [ "\t\t\thighlightRange = Range.plusRange(highlightRange, msg.range);\n", "\n", "\t\t\tif (!(msg instanceof ColorHover)) {\n", "\t\t\t\tmsg.contents\n", "\t\t\t\t\t.filter(contents => !!contents)\n", "\t\t\t\t\t.forEach(contents => {\n", "\t\t\t\t\t\tconst renderedContents = renderMarkdown(contents, {\n", "\t\t\t\t\t\t\tactionCallback: (content) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t.filter(contents => !MarkdownString.isEmpty(contents))\n" ], "file_path": "src/vs/editor/contrib/hover/browser/modesContentHover.ts", "type": "replace", "edit_start_line_idx": 312 }
[ { "c": ";", "t": "source.ini comment.line.semicolon.ini punctuation.definition.comment.ini", "r": { "dark_plus": "comment: #608B4E", "light_plus": "comment: #008000", "dark_vs": "comment: #608B4E", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " last modified 1 April 2001 by John Doe", "t": "source.ini comment.line.semicolon.ini", "r": { "dark_plus": "comment: #608B4E", "light_plus": "comment: #008000", "dark_vs": "comment: #608B4E", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "[", "t": "source.ini entity.name.section.group-title.ini punctuation.definition.entity.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "owner", "t": "source.ini entity.name.section.group-title.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "]", "t": "source.ini entity.name.section.group-title.ini punctuation.definition.entity.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "name", "t": "source.ini keyword.other.definition.ini", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "=", "t": "source.ini punctuation.separator.key-value.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "John Doe", "t": "source.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "organization", "t": "source.ini keyword.other.definition.ini", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "=", "t": "source.ini punctuation.separator.key-value.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Acme Widgets Inc.", "t": "source.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "[", "t": "source.ini entity.name.section.group-title.ini punctuation.definition.entity.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "database", "t": "source.ini entity.name.section.group-title.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "]", "t": "source.ini entity.name.section.group-title.ini punctuation.definition.entity.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ";", "t": "source.ini comment.line.semicolon.ini punctuation.definition.comment.ini", "r": { "dark_plus": "comment: #608B4E", "light_plus": "comment: #008000", "dark_vs": "comment: #608B4E", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " use IP address in case network name resolution is not working", "t": "source.ini comment.line.semicolon.ini", "r": { "dark_plus": "comment: #608B4E", "light_plus": "comment: #008000", "dark_vs": "comment: #608B4E", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "server", "t": "source.ini keyword.other.definition.ini", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "=", "t": "source.ini punctuation.separator.key-value.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "192.0.2.62", "t": "source.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "port", "t": "source.ini keyword.other.definition.ini", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "=", "t": "source.ini punctuation.separator.key-value.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "143", "t": "source.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "file", "t": "source.ini keyword.other.definition.ini", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": "=", "t": "source.ini punctuation.separator.key-value.ini", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.ini string.quoted.double.ini punctuation.definition.string.begin.ini", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "payroll.dat", "t": "source.ini string.quoted.double.ini", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.ini string.quoted.double.ini punctuation.definition.string.end.ini", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } } ]
extensions/ini/test/colorize-results/test_ini.json
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00017665213090367615, 0.00017392462177667767, 0.0001703653542790562, 0.00017427190323360264, 0.0000015312607501982711 ]
{ "id": 3, "code_window": [ "\t\t\thighlightRange = Range.plusRange(highlightRange, msg.range);\n", "\n", "\t\t\tif (!(msg instanceof ColorHover)) {\n", "\t\t\t\tmsg.contents\n", "\t\t\t\t\t.filter(contents => !!contents)\n", "\t\t\t\t\t.forEach(contents => {\n", "\t\t\t\t\t\tconst renderedContents = renderMarkdown(contents, {\n", "\t\t\t\t\t\t\tactionCallback: (content) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t.filter(contents => !MarkdownString.isEmpty(contents))\n" ], "file_path": "src/vs/editor/contrib/hover/browser/modesContentHover.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/extensionEditor'; import { localize } from 'vs/nls'; import { TPromise } from 'vs/base/common/winjs.base'; import { marked } from 'vs/base/common/marked/marked'; import { always } from 'vs/base/common/async'; import * as arrays from 'vs/base/common/arrays'; import { OS } from 'vs/base/common/platform'; import Event, { Emitter, once, fromEventEmitter, chain } from 'vs/base/common/event'; import Cache from 'vs/base/common/cache'; import { Action } from 'vs/base/common/actions'; import { isPromiseCanceledError } from 'vs/base/common/errors'; import Severity from 'vs/base/common/severity'; import { IDisposable, empty, dispose, toDisposable } from 'vs/base/common/lifecycle'; import { Builder } from 'vs/base/browser/builder'; import { domEvent } from 'vs/base/browser/event'; import { append, $, addClass, removeClass, finalHandler, join } from 'vs/base/browser/dom'; import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionGalleryService, IExtensionManifest, IKeyBinding, IView } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ResolvedKeybinding, KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { ExtensionsInput } from 'vs/workbench/parts/extensions/common/extensionsInput'; import { IExtensionsWorkbenchService, IExtensionsViewlet, VIEWLET_ID, IExtension, IExtensionDependencies } from 'vs/workbench/parts/extensions/common/extensions'; import { Renderer, DataSource, Controller } from 'vs/workbench/parts/extensions/browser/dependenciesViewer'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITemplateData } from 'vs/workbench/parts/extensions/browser/extensionsList'; import { RatingsWidget, InstallWidget } from 'vs/workbench/parts/extensions/browser/extensionsWidgets'; import { EditorOptions } from 'vs/workbench/common/editor'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { CombinedInstallAction, UpdateAction, EnableAction, DisableAction, BuiltinStatusLabelAction, ReloadAction } from 'vs/workbench/parts/extensions/browser/extensionsActions'; import WebView from 'vs/workbench/parts/html/browser/webview'; import { KeybindingIO } from 'vs/workbench/services/keybinding/common/keybindingIO'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { IMessageService } from 'vs/platform/message/common/message'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { Position } from 'vs/platform/editor/common/editor'; import { IListService } from 'vs/platform/list/browser/listService'; import { IPartService, Parts } from 'vs/workbench/services/part/common/partService'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { KeybindingLabel } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel'; import { attachListStyler } from 'vs/platform/theme/common/styler'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IContextKeyService, RawContextKey, ContextKeyExpr, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { Command } from 'vs/editor/common/editorCommonExtensions'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; /** A context key that is set when an extension editor webview has focus. */ export const KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_FOCUS = new RawContextKey<boolean>('extensionEditorWebviewFocus', undefined); /** A context key that is set when an extension editor webview not have focus. */ export const KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_NOT_FOCUSED: ContextKeyExpr = KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_FOCUS.toNegated(); function renderBody(body: string): string { return `<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https:; media-src https:; script-src 'none'; style-src file:; child-src 'none'; frame-src 'none';"> <link rel="stylesheet" type="text/css" href="${require.toUrl('./media/markdown.css')}"> </head> <body>${body}</body> </html>`; } function removeEmbeddedSVGs(documentContent: string): string { const newDocument = new DOMParser().parseFromString(documentContent, 'text/html'); // remove all inline svgs const allSVGs = newDocument.documentElement.querySelectorAll('svg'); for (let i = 0; i < allSVGs.length; i++) { allSVGs[i].parentNode.removeChild(allSVGs[i]); } return newDocument.documentElement.outerHTML; } class NavBar { private _onChange = new Emitter<string>(); get onChange(): Event<string> { return this._onChange.event; } private currentId: string = null; private actions: Action[]; private actionbar: ActionBar; constructor(container: HTMLElement) { const element = append(container, $('.navbar')); this.actions = []; this.actionbar = new ActionBar(element, { animated: false }); } push(id: string, label: string): void { const run = () => this._update(id); const action = new Action(id, label, null, true, run); this.actions.push(action); this.actionbar.push(action); if (this.actions.length === 1) { run(); } } clear(): void { this.actions = dispose(this.actions); this.actionbar.clear(); } update(): void { this._update(this.currentId); } _update(id: string = this.currentId): TPromise<void> { this.currentId = id; this._onChange.fire(id); this.actions.forEach(a => a.enabled = a.id !== id); return TPromise.as(null); } dispose(): void { this.actionbar = dispose(this.actionbar); } } const NavbarSection = { Readme: 'readme', Contributions: 'contributions', Changelog: 'changelog', Dependencies: 'dependencies' }; interface ILayoutParticipant { layout(): void; } export class ExtensionEditor extends BaseEditor { static ID: string = 'workbench.editor.extension'; private icon: HTMLImageElement; private name: HTMLElement; private identifier: HTMLElement; private license: HTMLElement; private publisher: HTMLElement; private installCount: HTMLElement; private rating: HTMLElement; private description: HTMLElement; private extensionActionBar: ActionBar; private navbar: NavBar; private content: HTMLElement; private _highlight: ITemplateData; private highlightDisposable: IDisposable; private extensionReadme: Cache<string>; private extensionChangelog: Cache<string>; private extensionManifest: Cache<IExtensionManifest>; private extensionDependencies: Cache<IExtensionDependencies>; private contextKey: IContextKey<boolean>; private layoutParticipants: ILayoutParticipant[] = []; private contentDisposables: IDisposable[] = []; private transientDisposables: IDisposable[] = []; private disposables: IDisposable[]; private activeWebview: WebView; constructor( @ITelemetryService telemetryService: ITelemetryService, @IExtensionGalleryService private galleryService: IExtensionGalleryService, @IConfigurationService private configurationService: IConfigurationService, @IInstantiationService private instantiationService: IInstantiationService, @IViewletService private viewletService: IViewletService, @IExtensionsWorkbenchService private extensionsWorkbenchService: IExtensionsWorkbenchService, @IThemeService protected themeService: IThemeService, @IKeybindingService private keybindingService: IKeybindingService, @IMessageService private messageService: IMessageService, @IOpenerService private openerService: IOpenerService, @IListService private listService: IListService, @IPartService private partService: IPartService, @IContextViewService private contextViewService: IContextViewService, @IContextKeyService private contextKeyService: IContextKeyService, ) { super(ExtensionEditor.ID, telemetryService, themeService); this._highlight = null; this.highlightDisposable = empty; this.disposables = []; this.extensionReadme = null; this.extensionChangelog = null; this.extensionManifest = null; this.extensionDependencies = null; this.contextKey = KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_FOCUS.bindTo(contextKeyService); } createEditor(parent: Builder): void { const container = parent.getHTMLElement(); const root = append(container, $('.extension-editor')); const header = append(root, $('.header')); this.icon = append(header, $<HTMLImageElement>('img.icon', { draggable: false })); const details = append(header, $('.details')); const title = append(details, $('.title')); this.name = append(title, $('span.name.clickable', { title: localize('name', "Extension name") })); this.identifier = append(title, $('span.identifier', { title: localize('extension id', "Extension identifier") })); const subtitle = append(details, $('.subtitle')); this.publisher = append(subtitle, $('span.publisher.clickable', { title: localize('publisher', "Publisher name") })); this.installCount = append(subtitle, $('span.install', { title: localize('install count', "Install count") })); this.rating = append(subtitle, $('span.rating.clickable', { title: localize('rating', "Rating") })); this.license = append(subtitle, $('span.license.clickable')); this.license.textContent = localize('license', 'License'); this.license.style.display = 'none'; this.description = append(details, $('.description')); const extensionActions = append(details, $('.actions')); this.extensionActionBar = new ActionBar(extensionActions, { animated: false, actionItemProvider: (action: Action) => { if (action.id === EnableAction.ID) { return (<EnableAction>action).actionItem; } if (action.id === DisableAction.ID) { return (<DisableAction>action).actionItem; } return null; } }); this.disposables.push(this.extensionActionBar); chain(fromEventEmitter<{ error?: any; }>(this.extensionActionBar, 'run')) .map(({ error }) => error) .filter(error => !!error) .on(this.onError, this, this.disposables); const body = append(root, $('.body')); this.navbar = new NavBar(body); this.content = append(body, $('.content')); } setInput(input: ExtensionsInput, options: EditorOptions): TPromise<void> { const extension = input.extension; this.transientDisposables = dispose(this.transientDisposables); this.telemetryService.publicLog('extensionGallery:openExtension', extension.telemetryData); this.extensionReadme = new Cache(() => extension.getReadme()); this.extensionChangelog = new Cache(() => extension.getChangelog()); this.extensionManifest = new Cache(() => extension.getManifest()); this.extensionDependencies = new Cache(() => this.extensionsWorkbenchService.loadDependencies(extension)); const onError = once(domEvent(this.icon, 'error')); onError(() => this.icon.src = extension.iconUrlFallback, null, this.transientDisposables); this.icon.src = extension.iconUrl; this.name.textContent = extension.displayName; this.identifier.textContent = extension.id; this.publisher.textContent = extension.publisherDisplayName; this.description.textContent = extension.description; if (extension.url) { this.name.onclick = finalHandler(() => window.open(extension.url)); this.rating.onclick = finalHandler(() => window.open(`${extension.url}#review-details`)); this.publisher.onclick = finalHandler(() => { this.viewletService.openViewlet(VIEWLET_ID, true) .then(viewlet => viewlet as IExtensionsViewlet) .done(viewlet => viewlet.search(`publisher:"${extension.publisherDisplayName}"`)); }); if (extension.licenseUrl) { this.license.onclick = finalHandler(() => window.open(extension.licenseUrl)); this.license.style.display = 'initial'; } else { this.license.onclick = null; this.license.style.display = 'none'; } } const install = this.instantiationService.createInstance(InstallWidget, this.installCount, { extension }); this.transientDisposables.push(install); const ratings = this.instantiationService.createInstance(RatingsWidget, this.rating, { extension }); this.transientDisposables.push(ratings); const builtinStatusAction = this.instantiationService.createInstance(BuiltinStatusLabelAction); const installAction = this.instantiationService.createInstance(CombinedInstallAction); const updateAction = this.instantiationService.createInstance(UpdateAction); const enableAction = this.instantiationService.createInstance(EnableAction); const disableAction = this.instantiationService.createInstance(DisableAction); const reloadAction = this.instantiationService.createInstance(ReloadAction); installAction.extension = extension; builtinStatusAction.extension = extension; updateAction.extension = extension; enableAction.extension = extension; disableAction.extension = extension; reloadAction.extension = extension; this.extensionActionBar.clear(); this.extensionActionBar.push([reloadAction, updateAction, enableAction, disableAction, installAction, builtinStatusAction], { icon: true, label: true }); this.transientDisposables.push(enableAction, updateAction, reloadAction, disableAction, installAction, builtinStatusAction); this.navbar.clear(); this.navbar.onChange(this.onNavbarChange.bind(this, extension), this, this.transientDisposables); this.navbar.push(NavbarSection.Readme, localize('details', "Details")); this.navbar.push(NavbarSection.Contributions, localize('contributions', "Contributions")); this.navbar.push(NavbarSection.Changelog, localize('changelog', "Changelog")); this.navbar.push(NavbarSection.Dependencies, localize('dependencies', "Dependencies")); this.content.innerHTML = ''; return super.setInput(input, options); } changePosition(position: Position): void { this.navbar.update(); super.changePosition(position); } showFind(): void { if (this.activeWebview) { this.activeWebview.showFind(); } } hideFind(): void { if (this.activeWebview) { this.activeWebview.hideFind(); } } private onNavbarChange(extension: IExtension, id: string): void { this.contentDisposables = dispose(this.contentDisposables); this.content.innerHTML = ''; this.activeWebview = null; switch (id) { case NavbarSection.Readme: return this.openReadme(); case NavbarSection.Contributions: return this.openContributions(); case NavbarSection.Changelog: return this.openChangelog(); case NavbarSection.Dependencies: return this.openDependencies(extension); } } private openMarkdown(content: TPromise<string>, noContentCopy: string) { return this.loadContents(() => content .then(marked.parse) .then(renderBody) .then(removeEmbeddedSVGs) .then<void>(body => { const allowedBadgeProviders = this.extensionsWorkbenchService.allowedBadgeProviders; const webViewOptions = allowedBadgeProviders.length > 0 ? { allowScripts: false, allowSvgs: false, svgWhiteList: allowedBadgeProviders } : undefined; this.activeWebview = new WebView(this.content, this.partService.getContainer(Parts.EDITOR_PART), this.contextViewService, this.contextKey, webViewOptions); const removeLayoutParticipant = arrays.insert(this.layoutParticipants, this.activeWebview); this.contentDisposables.push(toDisposable(removeLayoutParticipant)); this.activeWebview.style(this.themeService.getTheme()); this.activeWebview.contents = [body]; this.activeWebview.onDidClickLink(link => { // Whitelist supported schemes for links if (link && ['http', 'https', 'mailto'].indexOf(link.scheme) >= 0) { this.openerService.open(link); } }, null, this.contentDisposables); this.themeService.onThemeChange(theme => this.activeWebview.style(theme), null, this.contentDisposables); this.contentDisposables.push(this.activeWebview); }) .then(null, () => { const p = append(this.content, $('p.nocontent')); p.textContent = noContentCopy; })); } private openReadme() { return this.openMarkdown(this.extensionReadme.get(), localize('noReadme', "No README available.")); } private openChangelog() { return this.openMarkdown(this.extensionChangelog.get(), localize('noChangelog', "No Changelog available.")); } private openContributions() { return this.loadContents(() => this.extensionManifest.get() .then(manifest => { const content = $('div', { class: 'subcontent' }); const scrollableContent = new DomScrollableElement(content, {}); const layout = () => scrollableContent.scanDomNode(); const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout }); this.contentDisposables.push(toDisposable(removeLayoutParticipant)); const renders = [ this.renderSettings(content, manifest, layout), this.renderCommands(content, manifest, layout), this.renderLanguages(content, manifest, layout), this.renderThemes(content, manifest, layout), this.renderJSONValidation(content, manifest, layout), this.renderDebuggers(content, manifest, layout), this.renderViews(content, manifest, layout) ]; const isEmpty = !renders.reduce((v, r) => r || v, false); scrollableContent.scanDomNode(); if (isEmpty) { append(this.content, $('p.nocontent')).textContent = localize('noContributions', "No Contributions"); return; } else { append(this.content, scrollableContent.getDomNode()); this.contentDisposables.push(scrollableContent); } })); } private openDependencies(extension: IExtension) { if (extension.dependencies.length === 0) { append(this.content, $('p.nocontent')).textContent = localize('noDependencies', "No Dependencies"); return; } return this.loadContents(() => { return this.extensionDependencies.get().then(extensionDependencies => { const content = $('div', { class: 'subcontent' }); const scrollableContent = new DomScrollableElement(content, {}); append(this.content, scrollableContent.getDomNode()); this.contentDisposables.push(scrollableContent); const tree = this.renderDependencies(content, extensionDependencies); const layout = () => { scrollableContent.scanDomNode(); const scrollDimensions = scrollableContent.getScrollDimensions(); tree.layout(scrollDimensions.height); }; const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout }); this.contentDisposables.push(toDisposable(removeLayoutParticipant)); this.contentDisposables.push(tree); scrollableContent.scanDomNode(); }, error => { append(this.content, $('p.nocontent')).textContent = error; this.messageService.show(Severity.Error, error); }); }); } private renderDependencies(container: HTMLElement, extensionDependencies: IExtensionDependencies): Tree { const renderer = this.instantiationService.createInstance(Renderer); const controller = this.instantiationService.createInstance(Controller); const tree = new Tree(container, { dataSource: new DataSource(), renderer, controller }, { indentPixels: 40, twistiePixels: 20, keyboardSupport: false }); this.contentDisposables.push(attachListStyler(tree, this.themeService)); tree.setInput(extensionDependencies); this.contentDisposables.push(tree.addListener('selection', event => { if (event && event.payload && event.payload.origin === 'keyboard') { controller.openExtension(tree, false); } })); this.contentDisposables.push(this.listService.register(tree)); return tree; } private renderSettings(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const configuration = contributes && contributes.configuration; const properties = configuration && configuration.properties; const contrib = properties ? Object.keys(properties) : []; if (!contrib.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('settings', "Settings ({0})", contrib.length)), $('table', null, $('tr', null, $('th', null, localize('setting name', "Name")), $('th', null, localize('description', "Description")), $('th', null, localize('default', "Default")) ), ...contrib.map(key => $('tr', null, $('td', null, $('code', null, key)), $('td', null, properties[key].description), $('td', null, $('code', null, properties[key].default)) )) ) ); append(container, details); return true; } private renderDebuggers(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const contrib = contributes && contributes.debuggers || []; if (!contrib.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('debuggers', "Debuggers ({0})", contrib.length)), $('table', null, $('tr', null, $('th', null, localize('debugger name', "Name")), $('th', null, localize('debugger type', "Type")), ), ...contrib.map(d => $('tr', null, $('td', null, d.label), $('td', null, d.type))) ) ); append(container, details); return true; } private renderViews(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const contrib = contributes && contributes.views || {}; let views = <{ id: string, name: string, location: string }[]>Object.keys(contrib).reduce((result, location) => { let viewsForLocation: IView[] = contrib[location]; result.push(...viewsForLocation.map(view => ({ ...view, location }))); return result; }, []); if (!views.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('views', "Views ({0})", views.length)), $('table', null, $('tr', null, $('th', null, localize('view id', "ID")), $('th', null, localize('view name', "Name")), $('th', null, localize('view location', "Where"))), ...views.map(view => $('tr', null, $('td', null, view.id), $('td', null, view.name), $('td', null, view.location))) ) ); append(container, details); return true; } private renderThemes(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const contrib = contributes && contributes.themes || []; if (!contrib.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('themes', "Themes ({0})", contrib.length)), $('ul', null, ...contrib.map(theme => $('li', null, theme.label))) ); append(container, details); return true; } private renderJSONValidation(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const contrib = contributes && contributes.jsonValidation || []; if (!contrib.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('JSON Validation', "JSON Validation ({0})", contrib.length)), $('ul', null, ...contrib.map(v => $('li', null, v.fileMatch))) ); append(container, details); return true; } private renderCommands(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const rawCommands = contributes && contributes.commands || []; const commands = rawCommands.map(c => ({ id: c.command, title: c.title, keybindings: [], menus: [] })); const byId = arrays.index(commands, c => c.id); const menus = contributes && contributes.menus || {}; Object.keys(menus).forEach(context => { menus[context].forEach(menu => { let command = byId[menu.command]; if (!command) { command = { id: menu.command, title: '', keybindings: [], menus: [context] }; byId[command.id] = command; commands.push(command); } else { command.menus.push(context); } }); }); const rawKeybindings = contributes && contributes.keybindings || []; rawKeybindings.forEach(rawKeybinding => { const keybinding = this.resolveKeybinding(rawKeybinding); if (!keybinding) { return; } let command = byId[rawKeybinding.command]; if (!command) { command = { id: rawKeybinding.command, title: '', keybindings: [keybinding], menus: [] }; byId[command.id] = command; commands.push(command); } else { command.keybindings.push(keybinding); } }); if (!commands.length) { return false; } const renderKeybinding = (keybinding: ResolvedKeybinding): HTMLElement => { const element = $(''); new KeybindingLabel(element, OS).set(keybinding, null); return element; }; const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('commands', "Commands ({0})", commands.length)), $('table', null, $('tr', null, $('th', null, localize('command name', "Name")), $('th', null, localize('description', "Description")), $('th', null, localize('keyboard shortcuts', "Keyboard Shortcuts")), $('th', null, localize('menuContexts', "Menu Contexts")) ), ...commands.map(c => $('tr', null, $('td', null, $('code', null, c.id)), $('td', null, c.title), $('td', null, ...c.keybindings.map(keybinding => renderKeybinding(keybinding))), $('td', null, ...c.menus.map(context => $('code', null, context))) )) ) ); append(container, details); return true; } private renderLanguages(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean { const contributes = manifest.contributes; const rawLanguages = contributes && contributes.languages || []; const languages = rawLanguages.map(l => ({ id: l.id, name: (l.aliases || [])[0] || l.id, extensions: l.extensions || [], hasGrammar: false, hasSnippets: false })); const byId = arrays.index(languages, l => l.id); const grammars = contributes && contributes.grammars || []; grammars.forEach(grammar => { let language = byId[grammar.language]; if (!language) { language = { id: grammar.language, name: grammar.language, extensions: [], hasGrammar: true, hasSnippets: false }; byId[language.id] = language; languages.push(language); } else { language.hasGrammar = true; } }); const snippets = contributes && contributes.snippets || []; snippets.forEach(snippet => { let language = byId[snippet.language]; if (!language) { language = { id: snippet.language, name: snippet.language, extensions: [], hasGrammar: false, hasSnippets: true }; byId[language.id] = language; languages.push(language); } else { language.hasSnippets = true; } }); if (!languages.length) { return false; } const details = $('details', { open: true, ontoggle: onDetailsToggle }, $('summary', null, localize('languages', "Languages ({0})", languages.length)), $('table', null, $('tr', null, $('th', null, localize('language id', "ID")), $('th', null, localize('language name', "Name")), $('th', null, localize('file extensions', "File Extensions")), $('th', null, localize('grammar', "Grammar")), $('th', null, localize('snippets', "Snippets")) ), ...languages.map(l => $('tr', null, $('td', null, l.id), $('td', null, l.name), $('td', null, ...join(l.extensions.map(ext => $('code', null, ext)), ' ')), $('td', null, document.createTextNode(l.hasGrammar ? '✔︎' : '—')), $('td', null, document.createTextNode(l.hasSnippets ? '✔︎' : '—')) )) ) ); append(container, details); return true; } private resolveKeybinding(rawKeyBinding: IKeyBinding): ResolvedKeybinding { let key: string; switch (process.platform) { case 'win32': key = rawKeyBinding.win; break; case 'linux': key = rawKeyBinding.linux; break; case 'darwin': key = rawKeyBinding.mac; break; } const keyBinding = KeybindingIO.readKeybinding(key || rawKeyBinding.key, OS); if (!keyBinding) { return null; } return this.keybindingService.resolveKeybinding(keyBinding)[0]; } private loadContents(loadingTask: () => TPromise<any>): void { addClass(this.content, 'loading'); let promise = loadingTask(); promise = always(promise, () => removeClass(this.content, 'loading')); this.contentDisposables.push(toDisposable(() => promise.cancel())); } layout(): void { this.layoutParticipants.forEach(p => p.layout()); } private onError(err: any): void { if (isPromiseCanceledError(err)) { return; } this.messageService.show(Severity.Error, err); } dispose(): void { this._highlight = null; this.transientDisposables = dispose(this.transientDisposables); this.disposables = dispose(this.disposables); super.dispose(); } } class ShowExtensionEditorFindCommand extends Command { public runCommand(accessor: ServicesAccessor, args: any): void { const extensionEditor = this.getExtensionEditor(accessor); if (extensionEditor) { extensionEditor.showFind(); } } private getExtensionEditor(accessor: ServicesAccessor): ExtensionEditor { const activeEditor = accessor.get(IWorkbenchEditorService).getActiveEditor() as ExtensionEditor; if (activeEditor instanceof ExtensionEditor) { return activeEditor; } return null; } } const showCommand = new ShowExtensionEditorFindCommand({ id: 'editor.action.extensioneditor.showfind', precondition: KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_FOCUS, kbOpts: { primary: KeyMod.CtrlCmd | KeyCode.KEY_F } }); KeybindingsRegistry.registerCommandAndKeybindingRule(showCommand.toCommandAndKeybindingRule(KeybindingsRegistry.WEIGHT.editorContrib())); class HideExtensionEditorFindCommand extends Command { public runCommand(accessor: ServicesAccessor, args: any): void { const extensionEditor = this.getExtensionEditor(accessor); if (extensionEditor) { extensionEditor.hideFind(); } } private getExtensionEditor(accessor: ServicesAccessor): ExtensionEditor { const activeEditor = accessor.get(IWorkbenchEditorService).getActiveEditor() as ExtensionEditor; if (activeEditor instanceof ExtensionEditor) { return activeEditor; } return null; } } const hideCommand = new ShowExtensionEditorFindCommand({ id: 'editor.action.extensioneditor.hidefind', precondition: KEYBINDING_CONTEXT_EXTENSIONEDITOR_WEBVIEW_FOCUS, kbOpts: { primary: KeyMod.CtrlCmd | KeyCode.KEY_F } }); KeybindingsRegistry.registerCommandAndKeybindingRule(hideCommand.toCommandAndKeybindingRule(KeybindingsRegistry.WEIGHT.editorContrib()));
src/vs/workbench/parts/extensions/browser/extensionEditor.ts
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.0016296168323606253, 0.0002118757547577843, 0.00016313832020387053, 0.00017287525406572968, 0.00021601669141091406 ]
{ "id": 0, "code_window": [ "\n", " // Memoize plot context\n", " const plotCtx = useMemo(() => {\n", " return {\n", " plot: plotInstance.current,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " getPlot: () => plotInstance.current,\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.9987930059432983, 0.25059983134269714, 0.00016748577763792127, 0.00021178252063691616, 0.431139200925827 ]
{ "id": 0, "code_window": [ "\n", " // Memoize plot context\n", " const plotCtx = useMemo(() => {\n", " return {\n", " plot: plotInstance.current,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " getPlot: () => plotInstance.current,\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React, { FC } from 'react'; import { css, cx } from '@emotion/css'; import { DataFrame, DataLink, GrafanaThemeV2 } from '@grafana/data'; import { stylesFactory, useTheme2 } from '../../../themes'; import { HorizontalGroup, VerticalGroup } from '../../Layout/Layout'; import { IconButton } from '../../IconButton/IconButton'; export interface DataLinksListItemProps { index: number; link: DataLink; data: DataFrame[]; onChange: (index: number, link: DataLink) => void; onEdit: () => void; onRemove: () => void; isEditing?: boolean; } export const DataLinksListItem: FC<DataLinksListItemProps> = ({ link, onEdit, onRemove }) => { const theme = useTheme2(); const styles = getDataLinkListItemStyles(theme); const { title = '', url = '' } = link; const hasTitle = title.trim() !== ''; const hasUrl = url.trim() !== ''; return ( <div className={styles.wrapper}> <VerticalGroup spacing="xs"> <HorizontalGroup justify="space-between" align="flex-start" width="100%"> <div className={cx(styles.title, !hasTitle && styles.notConfigured)}> {hasTitle ? title : 'Data link title not provided'} </div> <HorizontalGroup> <IconButton name="pen" onClick={onEdit} /> <IconButton name="times" onClick={onRemove} /> </HorizontalGroup> </HorizontalGroup> <div className={cx(styles.url, !hasUrl && styles.notConfigured)} title={url}> {hasUrl ? url : 'Data link url not provided'} </div> </VerticalGroup> </div> ); }; const getDataLinkListItemStyles = stylesFactory((theme: GrafanaThemeV2) => { return { wrapper: css` margin-bottom: ${theme.spacing(2)}; width: 100%; &:last-child { margin-bottom: 0; } `, notConfigured: css` font-style: italic; `, title: css` color: ${theme.colors.text.primary}; font-size: ${theme.typography.size.sm}; font-weight: ${theme.typography.fontWeightMedium}; `, url: css` color: ${theme.colors.text.secondary}; font-size: ${theme.typography.size.sm}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 90%; `, }; });
packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017763450159691274, 0.00017226338968612254, 0.00016685550508555025, 0.00017280635074712336, 0.0000031733845844428288 ]
{ "id": 0, "code_window": [ "\n", " // Memoize plot context\n", " const plotCtx = useMemo(() => {\n", " return {\n", " plot: plotInstance.current,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " getPlot: () => plotInstance.current,\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React, { PureComponent } from 'react'; import { NavigationKey } from '../types'; export interface Props { onChange: (value: string) => void; onNavigate: (key: NavigationKey, clearOthers: boolean) => void; value: string | null; } export class VariableInput extends PureComponent<Props> { onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { if (NavigationKey[event.keyCode]) { const clearOthers = event.ctrlKey || event.metaKey || event.shiftKey; this.props.onNavigate(event.keyCode as NavigationKey, clearOthers); event.preventDefault(); } }; onChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.props.onChange(event.target.value); }; render() { return ( <input ref={(instance) => { if (instance) { instance.focus(); instance.setAttribute('style', `width:${Math.max(instance.width, 80)}px`); } }} type="text" className="gf-form-input" value={this.props.value ?? ''} onChange={this.onChange} onKeyDown={this.onKeyDown} /> ); } }
public/app/features/variables/pickers/shared/VariableInput.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.000182156843948178, 0.00017336853488814086, 0.0001676220417721197, 0.00017206794291269034, 0.000004914578312309459 ]
{ "id": 0, "code_window": [ "\n", " // Memoize plot context\n", " const plotCtx = useMemo(() => {\n", " return {\n", " plot: plotInstance.current,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " getPlot: () => plotInstance.current,\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 76 }
{ "__inputs": [], "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "7.3.0-pre" }, { "type": "panel", "id": "graph", "name": "Graph", "version": "" }, { "type": "datasource", "id": "stackdriver", "name": "Google Cloud Monitoring", "version": "1.0.0" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "gnetId": null, "graphTooltip": 0, "id": null, "links": [], "panels": [ { "datasource": null, "description": "", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "gridPos": { "h": 3, "w": 24, "x": 0, "y": 0 }, "id": 0, "options": { "mode": "markdown", "content": "This dashboard has 10 charts for the related [GCE VM metrics](https://cloud.google.com/monitoring/api/metrics_gcp#gcp-compute), including metrics for CPU, disk read/write, and network." }, "pluginVersion": "7.4.0-pre", "timeFrom": null, "timeShift": null, "title": "GCE VM Instance Monitoring", "type": "text" }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 0 }, "hiddenSeries": false, "id": 1, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - CPU Utilization", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "{{metric.label.instance_name}}", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_MEAN", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "GAUGE", "metricType": "compute.googleapis.com/instance/cpu/utilization", "projectName": "$project", "unit": "10^2.%", "valueType": "DOUBLE" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 0 }, "hiddenSeries": false, "id": 2, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - Uptime", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/uptime", "projectName": "$project", "unit": "s{uptime}", "valueType": "DOUBLE" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 }, "hiddenSeries": false, "id": 3, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Disk read operations", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/disk/read_ops_count", "projectName": "$project", "unit": "1", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 }, "hiddenSeries": false, "id": 4, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Disk write operations", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/disk/write_ops_count", "projectName": "$project", "unit": "1", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 16 }, "hiddenSeries": false, "id": 5, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Disk read bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/disk/read_bytes_count", "projectName": "$project", "unit": "By", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 16 }, "hiddenSeries": false, "id": 6, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Disk write bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/disk/write_bytes_count", "projectName": "$project", "unit": "By", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 24 }, "hiddenSeries": false, "id": 7, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - Received packets", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/network/received_packets_count", "projectName": "$project", "unit": "1", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 24 }, "hiddenSeries": false, "id": 8, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - Sent packets count", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/nat/sent_packets_count", "projectName": "$project", "unit": "{packet}", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 32 }, "hiddenSeries": false, "id": 9, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - Received bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/network/received_bytes_count", "projectName": "$project", "unit": "By", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 32 }, "hiddenSeries": false, "id": 10, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "GCE VM Instance - Sent bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "gce_instance"], "groupBys": [], "metricKind": "DELTA", "metricType": "compute.googleapis.com/instance/network/sent_bytes_count", "projectName": "$project", "unit": "By", "valueType": "INT64" } } ] } ], "schemaVersion": 26, "style": "dark", "tags": ["Compute", "Cloud Monitoring", "GCP"], "templating": { "list": [ { "current": {}, "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Datasource", "multi": false, "name": "datasource", "options": [], "query": "stackdriver", "queryValue": "", "refresh": 1, "regex": "", "skipUrlSync": false, "type": "datasource" }, { "allValue": null, "current": {}, "datasource": "$datasource", "definition": "Google Cloud Monitoring - Projects", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Project", "multi": false, "name": "project", "options": [], "query": { "labelKey": "", "loading": false, "projectName": "$project", "projects": [], "selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users", "selectedQueryType": "projects", "selectedSLOService": "", "selectedService": "actions.googleapis.com", "sloServices": [] }, "refresh": 1, "regex": "", "skipUrlSync": false, "sort": 0, "tagValuesQuery": "", "tags": [], "tagsQuery": "", "type": "query", "useTags": false }, { "allValue": null, "current": { "selected": false, "text": "grafana auto", "value": "grafana-auto" }, "datasource": "${datasource}", "definition": "", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Alignment Period", "multi": false, "name": "alignmentPeriod", "options": [ { "selected": true, "text": "grafana auto", "value": "grafana-auto" }, { "selected": false, "text": "stackdriver auto", "value": "stackdriver-auto" }, { "selected": false, "text": "cloud monitoring auto", "value": "cloud-monitoring-auto" }, { "selected": false, "text": "1m", "value": "+60s" }, { "selected": false, "text": "2m", "value": "+120s" }, { "selected": false, "text": "5m", "value": "+300s" }, { "selected": false, "text": "10m", "value": "+600s" }, { "selected": false, "text": "30m", "value": "+1800s" }, { "selected": false, "text": "1h", "value": "+3600s" }, { "selected": false, "text": "3h", "value": "+7200s" }, { "selected": false, "text": "6h", "value": "+21600s" }, { "selected": false, "text": "1d", "value": "+86400s" }, { "selected": false, "text": "3d", "value": "+259200s" }, { "selected": false, "text": "1w", "value": "+604800s" } ], "query": { "labelKey": "", "loading": false, "projectName": "$project", "projects": [ { "name": "project-1", "value": "project-1" }, { "name": "project-2", "value": "project-2" } ], "refId": "CloudMonitoringVariableQueryEditor-VariableQuery", "selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users", "selectedQueryType": "alignmentPeriods", "selectedSLOService": "", "selectedService": "actions.googleapis.com", "sloServices": [] }, "refresh": 0, "regex": "", "skipUrlSync": false, "sort": 0, "tagValuesQuery": "", "tags": [], "tagsQuery": "", "type": "query", "useTags": false } ] }, "time": { "from": "now-24h", "to": "now" }, "timepicker": {}, "timezone": "", "title": "GCE VM Instance Monitoring", "uid": "", "version": 5 }
public/app/plugins/datasource/cloud-monitoring/dashboards/gce-vm-instance-monitoring.json
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00018239321070723236, 0.00017339357873424888, 0.0001667085598455742, 0.000173630949575454, 0.000002288127916472149 ]
{ "id": 1, "code_window": [ " };\n", " }, [plotInstance.current, props.data]);\n", "\n", " return (\n", " <PlotContext.Provider value={plotCtx}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, []);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 78 }
import { DataFrame, Field, LinkModel, TimeZone, TIME_SERIES_TIME_FIELD_NAME, TIME_SERIES_VALUE_FIELD_NAME, } from '@grafana/data'; import { EventsCanvas, FIXED_UNIT, UPlotConfigBuilder, usePlotContext } from '@grafana/ui'; import React, { useCallback } from 'react'; import { ExemplarMarker } from './ExemplarMarker'; interface ExemplarsPluginProps { config: UPlotConfigBuilder; exemplars: DataFrame[]; timeZone: TimeZone; getFieldLinks: (field: Field, rowIndex: number) => Array<LinkModel<Field>>; } export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => { const plotCtx = usePlotContext(); const mapExemplarToXYCoords = useCallback( (dataFrame: DataFrame, index: number) => { const plotInstance = plotCtx.plot; const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME); const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME); if (!time || !value || !plotInstance) { return undefined; } // Filter x, y scales out const yScale = Object.keys(plotInstance.scales).find((scale) => !['x', 'y'].some((key) => key === scale)) ?? FIXED_UNIT; const yMin = plotInstance.scales[yScale].min; const yMax = plotInstance.scales[yScale].max; let y = value.values.get(index); // To not to show exemplars outside of the graph we set the y value to min if it is smaller and max if it is bigger than the size of the graph if (yMin != null && y < yMin) { y = yMin; } if (yMax != null && y > yMax) { y = yMax; } return { x: plotInstance.valToPos(time.values.get(index), 'x'), y: plotInstance.valToPos(y, yScale), }; }, [plotCtx] ); const renderMarker = useCallback( (dataFrame: DataFrame, index: number) => { return <ExemplarMarker timeZone={timeZone} getFieldLinks={getFieldLinks} dataFrame={dataFrame} index={index} />; }, [timeZone, getFieldLinks] ); return ( <EventsCanvas config={config} id="exemplars" events={exemplars} renderEventMarker={renderMarker} mapEventToXYCoords={mapExemplarToXYCoords} /> ); };
public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.003360461676493287, 0.0008030630415305495, 0.00016584209515713155, 0.00025764756719581783, 0.0010296005057170987 ]
{ "id": 1, "code_window": [ " };\n", " }, [plotInstance.current, props.data]);\n", "\n", " return (\n", " <PlotContext.Provider value={plotCtx}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, []);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 78 }
import React, { FC } from 'react'; import { useStyles } from '@grafana/ui'; import { GrafanaTheme } from '@grafana/data'; import { css } from '@emotion/css'; interface Props { labelKey: string; value: string; isRegex?: boolean; } export const AlertLabel: FC<Props> = ({ labelKey, value, isRegex = false }) => ( <div className={useStyles(getStyles)}> {labelKey}={isRegex && '~'} {value} </div> ); export const getStyles = (theme: GrafanaTheme) => css` padding: ${theme.spacing.xs} ${theme.spacing.sm}; border-radius: ${theme.border.radius.sm}; border: solid 1px ${theme.colors.border2}; font-size: ${theme.typography.size.sm}; background-color: ${theme.colors.bg2}; font-weight: ${theme.typography.weight.bold}; color: ${theme.colors.formLabel}; display: inline-block; line-height: 1.2; `;
public/app/features/alerting/unified/components/AlertLabel.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0003551464469637722, 0.00022996170446276665, 0.00016590538143645972, 0.00016883328498806804, 0.00008852704922901466 ]
{ "id": 1, "code_window": [ " };\n", " }, [plotInstance.current, props.data]);\n", "\n", " return (\n", " <PlotContext.Provider value={plotCtx}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, []);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 78 }
import { DashboardAcl, DashboardAclDTO } from 'app/types/acl'; export function processAclItems(items: DashboardAclDTO[]): DashboardAcl[] { return items.map(processAclItem).sort((a, b) => b.sortRank! - a.sortRank! || a.name!.localeCompare(b.name!)); } function processAclItem(dto: DashboardAclDTO): DashboardAcl { const item = dto as DashboardAcl; item.sortRank = 0; if (item.userId! > 0) { item.name = item.userLogin; item.sortRank = 10; } else if (item.teamId! > 0) { item.name = item.team; item.sortRank = 20; } else if (item.role) { item.icon = 'fa fa-fw fa-street-view'; item.name = item.role; item.sortRank = 30; if (item.role === 'Editor') { item.sortRank += 1; } } if (item.inherited) { item.sortRank += 100; } return item; }
public/app/core/utils/acl.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017212488455697894, 0.0001711749064270407, 0.0001701591827441007, 0.00017120776465162635, 9.057615670826635e-7 ]
{ "id": 1, "code_window": [ " };\n", " }, [plotInstance.current, props.data]);\n", "\n", " return (\n", " <PlotContext.Provider value={plotCtx}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " }, []);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/Plot.tsx", "type": "replace", "edit_start_line_idx": 78 }
// +build integration package tests import ( "encoding/json" "errors" "fmt" "math/rand" "testing" "time" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/services/ngalert/store" "github.com/grafana/grafana/pkg/registry" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const baseIntervalSeconds = 10 func mockTimeNow() { var timeSeed int64 store.TimeNow = func() time.Time { fakeNow := time.Unix(timeSeed, 0).UTC() timeSeed++ return fakeNow } } func resetTimeNow() { store.TimeNow = time.Now } func TestCreatingAlertDefinition(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var customIntervalSeconds int64 = 120 testCases := []struct { desc string inputIntervalSeconds *int64 inputTitle string expectedError error expectedInterval int64 expectedUpdated time.Time }{ { desc: "should create successfully an alert definition with default interval", inputIntervalSeconds: nil, inputTitle: "a name", expectedInterval: dbstore.DefaultIntervalSeconds, expectedUpdated: time.Unix(0, 0).UTC(), }, { desc: "should create successfully an alert definition with custom interval", inputIntervalSeconds: &customIntervalSeconds, inputTitle: "another name", expectedInterval: customIntervalSeconds, expectedUpdated: time.Unix(1, 0).UTC(), }, { desc: "should fail to create an alert definition with too big name", inputIntervalSeconds: &customIntervalSeconds, inputTitle: getLongString(store.AlertDefinitionMaxTitleLength + 1), expectedError: errors.New(""), }, { desc: "should fail to create an alert definition with empty title", inputIntervalSeconds: &customIntervalSeconds, inputTitle: "", expectedError: fmt.Errorf("title is empty"), }, } for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { q := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: tc.inputTitle, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } if tc.inputIntervalSeconds != nil { q.IntervalSeconds = tc.inputIntervalSeconds } err := dbstore.SaveAlertDefinition(&q) switch { case tc.expectedError != nil: require.Error(t, err) default: require.NoError(t, err) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, tc.expectedInterval, q.Result.IntervalSeconds) assert.Equal(t, int64(1), q.Result.Version) } }) } } func TestCreatingConflictionAlertDefinition(t *testing.T) { t.Run("Should fail to create alert definition with conflicting org_id, title", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: "title", Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } err := dbstore.SaveAlertDefinition(&q) require.NoError(t, err) err = dbstore.SaveAlertDefinition(&q) require.Error(t, err) assert.True(t, dbstore.SQLStore.Dialect.IsUniqueConstraintViolation(err)) }) } func TestUpdatingAlertDefinition(t *testing.T) { t.Run("zero rows affected when updating unknown alert", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.UpdateAlertDefinitionCommand{ UID: "unknown", OrgID: 1, Title: "something completely different", Condition: "A", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 2 > 1" }`), RefID: "A", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } err := dbstore.UpdateAlertDefinition(&q) require.NoError(t, err) }) t.Run("updating existing alert", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var initialInterval int64 = 120 alertDefinition := createTestAlertDefinition(t, dbstore, initialInterval) created := alertDefinition.Updated var customInterval int64 = 30 testCases := []struct { desc string inputOrgID int64 inputTitle string inputInterval *int64 expectedError error expectedIntervalSeconds int64 expectedUpdated time.Time expectedTitle string }{ { desc: "should not update previous interval if it's not provided", inputInterval: nil, inputOrgID: alertDefinition.OrgID, inputTitle: "something completely different", expectedIntervalSeconds: initialInterval, expectedUpdated: time.Unix(1, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should update interval if it's provided", inputInterval: &customInterval, inputOrgID: alertDefinition.OrgID, inputTitle: "something completely different", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(2, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should not update organisation if it's provided", inputInterval: &customInterval, inputOrgID: 0, inputTitle: "something completely different", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(3, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should not update alert definition if the title it's too big", inputInterval: &customInterval, inputOrgID: 0, inputTitle: getLongString(store.AlertDefinitionMaxTitleLength + 1), expectedError: errors.New(""), }, { desc: "should not update alert definition title if the title is empty", inputInterval: &customInterval, inputOrgID: 0, inputTitle: "", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(4, 0).UTC(), expectedTitle: "something completely different", }, } q := models.UpdateAlertDefinitionCommand{ UID: (*alertDefinition).UID, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, }, }, } lastUpdated := created previousAlertDefinition := alertDefinition for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { if tc.inputInterval != nil { q.IntervalSeconds = tc.inputInterval } if tc.inputOrgID != 0 { q.OrgID = tc.inputOrgID } q.Title = tc.inputTitle err := dbstore.UpdateAlertDefinition(&q) switch { case tc.expectedError != nil: require.Error(t, err) assert.Equal(t, previousAlertDefinition.Title, q.Result.Title) assert.Equal(t, previousAlertDefinition.Condition, q.Result.Condition) assert.Equal(t, len(previousAlertDefinition.Data), len(q.Result.Data)) assert.Equal(t, previousAlertDefinition.IntervalSeconds, q.Result.IntervalSeconds) assert.Equal(t, previousAlertDefinition.Updated, q.Result.Updated) assert.Equal(t, previousAlertDefinition.Version, q.Result.Version) assert.Equal(t, previousAlertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, previousAlertDefinition.UID, q.Result.UID) default: require.NoError(t, err) assert.Equal(t, previousAlertDefinition.ID, q.Result.ID) assert.Equal(t, previousAlertDefinition.UID, q.Result.UID) assert.True(t, q.Result.Updated.After(lastUpdated)) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, previousAlertDefinition.Version+1, q.Result.Version) assert.Equal(t, alertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, "something completely different", q.Result.Title) assert.Equal(t, "B", q.Result.Condition) assert.Equal(t, 1, len(q.Result.Data)) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, tc.expectedIntervalSeconds, q.Result.IntervalSeconds) assert.Equal(t, previousAlertDefinition.Version+1, q.Result.Version) assert.Equal(t, alertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, alertDefinition.UID, q.Result.UID) previousAlertDefinition = q.Result } }) } }) } func TestUpdatingConflictingAlertDefinition(t *testing.T) { t.Run("should fail to update alert definition with reserved title", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var initialInterval int64 = 120 alertDef1 := createTestAlertDefinition(t, dbstore, initialInterval) alertDef2 := createTestAlertDefinition(t, dbstore, initialInterval) q := models.UpdateAlertDefinitionCommand{ UID: (*alertDef2).UID, Title: alertDef1.Title, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, }, }, } err := dbstore.UpdateAlertDefinition(&q) require.Error(t, err) assert.True(t, dbstore.SQLStore.Dialect.IsUniqueConstraintViolation(err)) }) } func TestDeletingAlertDefinition(t *testing.T) { t.Run("zero rows affected when deleting unknown alert", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.DeleteAlertDefinitionByUIDCommand{ UID: "unknown", OrgID: 1, } err := dbstore.DeleteAlertDefinitionByUID(&q) require.NoError(t, err) }) t.Run("deleting successfully existing alert", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) alertDefinition := createTestAlertDefinition(t, dbstore, 60) q := models.DeleteAlertDefinitionByUIDCommand{ UID: (*alertDefinition).UID, OrgID: 1, } // save an instance for the definition saveCmd := &models.SaveAlertInstanceCommand{ DefinitionOrgID: alertDefinition.OrgID, DefinitionUID: alertDefinition.UID, State: models.InstanceStateFiring, Labels: models.InstanceLabels{"test": "testValue"}, } err := dbstore.SaveAlertInstance(saveCmd) require.NoError(t, err) listQuery := &models.ListAlertInstancesQuery{ DefinitionOrgID: alertDefinition.OrgID, DefinitionUID: alertDefinition.UID, } err = dbstore.ListAlertInstances(listQuery) require.NoError(t, err) require.Len(t, listQuery.Result, 1) err = dbstore.DeleteAlertDefinitionByUID(&q) require.NoError(t, err) // assert that alert instance is deleted err = dbstore.ListAlertInstances(listQuery) require.NoError(t, err) require.Len(t, listQuery.Result, 0) }) } func getLongString(n int) string { b := make([]rune, n) for i := range b { b[i] = 'a' } return string(b) } // createTestAlertDefinition creates a dummy alert definition to be used by the tests. func createTestAlertDefinition(t *testing.T, dbstore *store.DBstore, intervalSeconds int64) *models.AlertDefinition { cmd := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: fmt.Sprintf("an alert definition %d", rand.Intn(1000)), Condition: "A", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 2 > 1" }`), RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, RefID: "A", }, }, IntervalSeconds: &intervalSeconds, } err := dbstore.SaveAlertDefinition(&cmd) require.NoError(t, err) t.Logf("alert definition: %v with interval: %d created", cmd.Result.GetKey(), intervalSeconds) return cmd.Result }
pkg/services/ngalert/tests/database_test.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0001736037083901465, 0.00016914945445023477, 0.00016593890904914588, 0.00016932410653680563, 0.0000018454848031979054 ]
{ "id": 2, "code_window": [ "import React, { useContext } from 'react';\n", "import uPlot from 'uplot';\n", "\n", "interface PlotContextType {\n", " plot: uPlot | undefined;\n", "}\n", "\n", "/**\n", " * @alpha\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPlot: () => uPlot | undefined;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/context.ts", "type": "replace", "edit_start_line_idx": 4 }
import React, { useEffect, useLayoutEffect, useMemo, useRef } from 'react'; import uPlot, { AlignedData, Options } from 'uplot'; import { PlotContext } from './context'; import { DEFAULT_PLOT_CONFIG, pluginLog } from './utils'; import { PlotProps } from './types'; import usePrevious from 'react-use/lib/usePrevious'; /** * @internal * uPlot abstraction responsible for plot initialisation, setup and refresh * Receives a data frame that is x-axis aligned, as of https://github.com/leeoniya/uPlot/tree/master/docs#data-format * Exposes contexts for plugins registration and uPlot instance access */ export const UPlotChart: React.FC<PlotProps> = (props) => { const plotContainer = useRef<HTMLDivElement>(null); const plotInstance = useRef<uPlot>(); const prevProps = usePrevious(props); const config = useMemo(() => { return { ...DEFAULT_PLOT_CONFIG, width: props.width, height: props.height, ms: 1, ...props.config.getConfig(), } as uPlot.Options; }, [props.config]); useLayoutEffect(() => { if (!plotInstance.current || props.width === 0 || props.height === 0) { return; } pluginLog('uPlot core', false, 'updating size'); plotInstance.current.setSize({ width: props.width, height: props.height, }); }, [props.width, props.height]); // Effect responsible for uPlot updates/initialization logic. It's performed whenever component's props have changed useLayoutEffect(() => { // 0. Exit early if the component is not ready to initialize uPlot if (!plotContainer.current || props.width === 0 || props.height === 0) { return; } // 1. When config is ready and there is no uPlot instance, create new uPlot and return if (!plotInstance.current || !prevProps) { plotInstance.current = initializePlot(props.data, config, plotContainer.current); return; } // 2. Reinitialize uPlot if config changed if (props.config !== prevProps.config) { if (plotInstance.current) { pluginLog('uPlot core', false, 'destroying instance'); plotInstance.current.destroy(); } plotInstance.current = initializePlot(props.data, config, plotContainer.current); return; } // 3. Otherwise, assume only data has changed and update uPlot data if (props.data !== prevProps.data) { pluginLog('uPlot core', false, 'updating plot data(throttled log!)', props.data); plotInstance.current.setData(props.data); } }, [props, config]); // When component unmounts, clean the existing uPlot instance useEffect(() => () => plotInstance.current?.destroy(), []); // Memoize plot context const plotCtx = useMemo(() => { return { plot: plotInstance.current, }; }, [plotInstance.current, props.data]); return ( <PlotContext.Provider value={plotCtx}> <div style={{ position: 'relative' }}> <div ref={plotContainer} data-testid="uplot-main-div" /> {props.children} </div> </PlotContext.Provider> ); }; function initializePlot(data: AlignedData, config: Options, el: HTMLDivElement) { pluginLog('UPlotChart: init uPlot', false, 'initialized with', data, config); return new uPlot(config, data, el); }
packages/grafana-ui/src/components/uPlot/Plot.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0025710207410156727, 0.0008845791453495622, 0.0001979360677069053, 0.0006750717293471098, 0.0007516141631640494 ]
{ "id": 2, "code_window": [ "import React, { useContext } from 'react';\n", "import uPlot from 'uplot';\n", "\n", "interface PlotContextType {\n", " plot: uPlot | undefined;\n", "}\n", "\n", "/**\n", " * @alpha\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPlot: () => uPlot | undefined;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/context.ts", "type": "replace", "edit_start_line_idx": 4 }
+++ title = "Pause alert rule" description = "Pause an existing alert rule" keywords = ["grafana", "alerting", "guide", "rules", "view"] weight = 400 +++ # Pause an alert rule Pausing the evaluation of an alert rule can sometimes be useful. For example, during a maintenance window, pausing alert rules can avoid triggering a flood of alerts. 1. In the Grafana side bar, hover your cursor over the Alerting (bell) icon and then click **Alert Rules**. All configured alert rules are listed, along with their current state. 1. Find your alert in the list, and click the **Pause** icon on the right. The **Pause** icon turns into a **Play** icon. 1. Click the **Play** icon to resume evaluation of your alert.
docs/sources/alerting/pause-an-alert-rule.md
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.000173594118678011, 0.0001719821011647582, 0.00017037006909959018, 0.0001719821011647582, 0.000001612024789210409 ]
{ "id": 2, "code_window": [ "import React, { useContext } from 'react';\n", "import uPlot from 'uplot';\n", "\n", "interface PlotContextType {\n", " plot: uPlot | undefined;\n", "}\n", "\n", "/**\n", " * @alpha\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPlot: () => uPlot | undefined;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/context.ts", "type": "replace", "edit_start_line_idx": 4 }
import React, { PureComponent } from 'react'; import { css } from '@emotion/css'; import { ConfirmButton, ConfirmModal, Button } from '@grafana/ui'; import { AccessControlAction, UserSession } from 'app/types'; import { contextSrv } from 'app/core/core'; interface Props { sessions: UserSession[]; onSessionRevoke: (id: number) => void; onAllSessionsRevoke: () => void; } interface State { showLogoutModal: boolean; } export class UserSessions extends PureComponent<Props, State> { state: State = { showLogoutModal: false, }; showLogoutConfirmationModal = (show: boolean) => () => { this.setState({ showLogoutModal: show }); }; onSessionRevoke = (id: number) => { return () => { this.props.onSessionRevoke(id); }; }; onAllSessionsRevoke = () => { this.setState({ showLogoutModal: false }); this.props.onAllSessionsRevoke(); }; render() { const { sessions } = this.props; const { showLogoutModal } = this.state; const logoutFromAllDevicesClass = css` margin-top: 0.8rem; `; const canLogout = contextSrv.hasPermission(AccessControlAction.UsersLogout); return ( <> <h3 className="page-heading">Sessions</h3> <div className="gf-form-group"> <div className="gf-form"> <table className="filter-table form-inline"> <thead> <tr> <th>Last seen</th> <th>Logged on</th> <th>IP address</th> <th colSpan={2}>Browser and OS</th> </tr> </thead> <tbody> {sessions && sessions.map((session, index) => ( <tr key={`${session.id}-${index}`}> <td>{session.isActive ? 'Now' : session.seenAt}</td> <td>{session.createdAt}</td> <td>{session.clientIp}</td> <td>{`${session.browser} on ${session.os} ${session.osVersion}`}</td> <td> <div className="pull-right"> {canLogout && ( <ConfirmButton confirmText="Confirm logout" confirmVariant="destructive" onConfirm={this.onSessionRevoke(session.id)} > Force logout </ConfirmButton> )} </div> </td> </tr> ))} </tbody> </table> </div> <div className={logoutFromAllDevicesClass}> {canLogout && sessions.length > 0 && ( <Button variant="secondary" onClick={this.showLogoutConfirmationModal(true)}> Force logout from all devices </Button> )} <ConfirmModal isOpen={showLogoutModal} title="Force logout from all devices" body="Are you sure you want to force logout from all devices?" confirmText="Force logout" onConfirm={this.onAllSessionsRevoke} onDismiss={this.showLogoutConfirmationModal(false)} /> </div> </div> </> ); } }
public/app/features/admin/UserSessions.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0001732995588099584, 0.0001704397436697036, 0.00016717672406230122, 0.00017046788707375526, 0.0000015694323565185186 ]
{ "id": 2, "code_window": [ "import React, { useContext } from 'react';\n", "import uPlot from 'uplot';\n", "\n", "interface PlotContextType {\n", " plot: uPlot | undefined;\n", "}\n", "\n", "/**\n", " * @alpha\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPlot: () => uPlot | undefined;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/context.ts", "type": "replace", "edit_start_line_idx": 4 }
import { cloneDeep, find, isNumber, isObject, isString, first as _first, map as _map } from 'lodash'; import { DataFrame, DataLink, DataQuery, DataQueryRequest, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings, DateTime, dateTime, Field, getDefaultTimeRange, LogRowModel, MetricFindValue, PluginMeta, ScopedVars, TimeRange, toUtc, } from '@grafana/data'; import LanguageProvider from './language_provider'; import { ElasticResponse } from './elastic_response'; import { IndexPattern } from './index_pattern'; import { ElasticQueryBuilder } from './query_builder'; import { defaultBucketAgg, hasMetricOfType } from './query_def'; import { BackendSrvRequest, getBackendSrv, getDataSourceSrv } from '@grafana/runtime'; import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv'; import { DataLinkConfig, ElasticsearchOptions, ElasticsearchQuery } from './types'; import { RowContextOptions } from '@grafana/ui/src/components/Logs/LogRowContextProvider'; import { metricAggregationConfig } from './components/QueryEditor/MetricAggregationsEditor/utils'; import { isMetricAggregationWithField, isPipelineAggregationWithMultipleBucketPaths, Logs, } from './components/QueryEditor/MetricAggregationsEditor/aggregations'; import { bucketAggregationConfig } from './components/QueryEditor/BucketAggregationsEditor/utils'; import { BucketAggregation, isBucketAggregationWithField, } from './components/QueryEditor/BucketAggregationsEditor/aggregations'; import { generate, Observable, of, throwError } from 'rxjs'; import { catchError, first, map, mergeMap, skipWhile, throwIfEmpty } from 'rxjs/operators'; import { getScriptValue } from './utils'; // Those are metadata fields as defined in https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-fields.html#_identity_metadata_fields. // custom fields can start with underscores, therefore is not safe to exclude anything that starts with one. const ELASTIC_META_FIELDS = [ '_index', '_type', '_id', '_source', '_size', '_field_names', '_ignored', '_routing', '_meta', ]; export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, ElasticsearchOptions> { basicAuth?: string; withCredentials?: boolean; url: string; name: string; index: string; timeField: string; esVersion: number; interval: string; maxConcurrentShardRequests?: number; queryBuilder: ElasticQueryBuilder; indexPattern: IndexPattern; logMessageField?: string; logLevelField?: string; dataLinks: DataLinkConfig[]; languageProvider: LanguageProvider; constructor( instanceSettings: DataSourceInstanceSettings<ElasticsearchOptions>, private readonly templateSrv: TemplateSrv = getTemplateSrv() ) { super(instanceSettings); this.basicAuth = instanceSettings.basicAuth; this.withCredentials = instanceSettings.withCredentials; this.url = instanceSettings.url!; this.name = instanceSettings.name; this.index = instanceSettings.database ?? ''; const settingsData = instanceSettings.jsonData || ({} as ElasticsearchOptions); this.timeField = settingsData.timeField; this.esVersion = settingsData.esVersion; this.indexPattern = new IndexPattern(this.index, settingsData.interval); this.interval = settingsData.timeInterval; this.maxConcurrentShardRequests = settingsData.maxConcurrentShardRequests; this.queryBuilder = new ElasticQueryBuilder({ timeField: this.timeField, esVersion: this.esVersion, }); this.logMessageField = settingsData.logMessageField || ''; this.logLevelField = settingsData.logLevelField || ''; this.dataLinks = settingsData.dataLinks || []; if (this.logMessageField === '') { this.logMessageField = undefined; } if (this.logLevelField === '') { this.logLevelField = undefined; } this.languageProvider = new LanguageProvider(this); } private request( method: string, url: string, data?: undefined, headers?: BackendSrvRequest['headers'] ): Observable<any> { const options: BackendSrvRequest = { url: this.url + '/' + url, method, data, headers, }; if (this.basicAuth || this.withCredentials) { options.withCredentials = true; } if (this.basicAuth) { options.headers = { Authorization: this.basicAuth, }; } return getBackendSrv() .fetch<any>(options) .pipe( map((results) => { results.data.$$config = results.config; return results.data; }), catchError((err) => { if (err.data) { const message = err.data.error?.reason ?? err.data.message ?? 'Unknown error'; return throwError({ message: 'Elasticsearch error: ' + message, error: err.data.error, }); } return throwError(err); }) ); } async importQueries(queries: DataQuery[], originMeta: PluginMeta): Promise<ElasticsearchQuery[]> { return this.languageProvider.importQueries(queries, originMeta.id); } /** * Sends a GET request to the specified url on the newest matching and available index. * * When multiple indices span the provided time range, the request is sent starting from the newest index, * and then going backwards until an index is found. * * @param url the url to query the index on, for example `/_mapping`. */ private get(url: string, range = getDefaultTimeRange()): Observable<any> { let indexList = this.indexPattern.getIndexList(range.from, range.to); if (!Array.isArray(indexList)) { indexList = [this.indexPattern.getIndexForToday()]; } const indexUrlList = indexList.map((index) => index + url); return this.requestAllIndices(indexUrlList); } private requestAllIndices(indexList: string[]): Observable<any> { const maxTraversals = 7; // do not go beyond one week (for a daily pattern) const listLen = indexList.length; return generate( 0, (i) => i < Math.min(listLen, maxTraversals), (i) => i + 1 ).pipe( mergeMap((index) => { // catch all errors and emit an object with an err property to simplify checks later in the pipeline return this.request('GET', indexList[listLen - index - 1]).pipe(catchError((err) => of({ err }))); }), skipWhile((resp) => resp.err && resp.err.status === 404), // skip all requests that fail because missing Elastic index throwIfEmpty(() => 'Could not find an available index for this time range.'), // when i === Math.min(listLen, maxTraversals) generate will complete but without emitting any values which means we didn't find a valid index first(), // take the first value that isn't skipped map((resp) => { if (resp.err) { throw resp.err; // if there is some other error except 404 then we must throw it } return resp; }) ); } private post(url: string, data: any): Observable<any> { return this.request('POST', url, data, { 'Content-Type': 'application/x-ndjson' }); } annotationQuery(options: any): Promise<any> { const annotation = options.annotation; const timeField = annotation.timeField || '@timestamp'; const timeEndField = annotation.timeEndField || null; const queryString = annotation.query || '*'; const tagsField = annotation.tagsField || 'tags'; const textField = annotation.textField || null; const dateRanges = []; const rangeStart: any = {}; rangeStart[timeField] = { from: options.range.from.valueOf(), to: options.range.to.valueOf(), format: 'epoch_millis', }; dateRanges.push({ range: rangeStart }); if (timeEndField) { const rangeEnd: any = {}; rangeEnd[timeEndField] = { from: options.range.from.valueOf(), to: options.range.to.valueOf(), format: 'epoch_millis', }; dateRanges.push({ range: rangeEnd }); } const queryInterpolated = this.templateSrv.replace(queryString, {}, 'lucene'); const query = { bool: { filter: [ { bool: { should: dateRanges, minimum_should_match: 1, }, }, { query_string: { query: queryInterpolated, }, }, ], }, }; const data: any = { query, size: 10000, }; // fields field not supported on ES 5.x if (this.esVersion < 5) { data['fields'] = [timeField, '_source']; } const header: any = { search_type: 'query_then_fetch', ignore_unavailable: true, }; // old elastic annotations had index specified on them if (annotation.index) { header.index = annotation.index; } else { header.index = this.indexPattern.getIndexList(options.range.from, options.range.to); } const payload = JSON.stringify(header) + '\n' + JSON.stringify(data) + '\n'; return this.post('_msearch', payload) .pipe( map((res) => { const list = []; const hits = res.responses[0].hits.hits; const getFieldFromSource = (source: any, fieldName: any) => { if (!fieldName) { return; } const fieldNames = fieldName.split('.'); let fieldValue = source; for (let i = 0; i < fieldNames.length; i++) { fieldValue = fieldValue[fieldNames[i]]; if (!fieldValue) { console.log('could not find field in annotation: ', fieldName); return ''; } } return fieldValue; }; for (let i = 0; i < hits.length; i++) { const source = hits[i]._source; let time = getFieldFromSource(source, timeField); if (typeof hits[i].fields !== 'undefined') { const fields = hits[i].fields; if (isString(fields[timeField]) || isNumber(fields[timeField])) { time = fields[timeField]; } } const event: { annotation: any; time: number; timeEnd?: number; text: string; tags: string | string[]; } = { annotation: annotation, time: toUtc(time).valueOf(), text: getFieldFromSource(source, textField), tags: getFieldFromSource(source, tagsField), }; if (timeEndField) { const timeEnd = getFieldFromSource(source, timeEndField); if (timeEnd) { event.timeEnd = toUtc(timeEnd).valueOf(); } } // legacy support for title tield if (annotation.titleField) { const title = getFieldFromSource(source, annotation.titleField); if (title) { event.text = title + '\n' + event.text; } } if (typeof event.tags === 'string') { event.tags = event.tags.split(','); } list.push(event); } return list; }) ) .toPromise(); } private interpolateLuceneQuery(queryString: string, scopedVars: ScopedVars) { // Elasticsearch queryString should always be '*' if empty string return this.templateSrv.replace(queryString, scopedVars, 'lucene') || '*'; } interpolateVariablesInQueries(queries: ElasticsearchQuery[], scopedVars: ScopedVars): ElasticsearchQuery[] { // We need a separate interpolation format for lucene queries, therefore we first interpolate any // lucene query string and then everything else const interpolateBucketAgg = (bucketAgg: BucketAggregation): BucketAggregation => { if (bucketAgg.type === 'filters') { return { ...bucketAgg, settings: { ...bucketAgg.settings, filters: bucketAgg.settings?.filters?.map((filter) => ({ ...filter, query: this.interpolateLuceneQuery(filter.query || '', scopedVars), })), }, }; } return bucketAgg; }; const expandedQueries = queries.map( (query): ElasticsearchQuery => ({ ...query, datasource: this.name, query: this.interpolateLuceneQuery(query.query || '', scopedVars), bucketAggs: query.bucketAggs?.map(interpolateBucketAgg), }) ); const finalQueries: ElasticsearchQuery[] = JSON.parse( this.templateSrv.replace(JSON.stringify(expandedQueries), scopedVars) ); return finalQueries; } testDatasource() { // validate that the index exist and has date field return this.getFields('date') .pipe( mergeMap((dateFields) => { const timeField: any = find(dateFields, { text: this.timeField }); if (!timeField) { return of({ status: 'error', message: 'No date field named ' + this.timeField + ' found' }); } return of({ status: 'success', message: 'Index OK. Time field name OK.' }); }), catchError((err) => { console.error(err); if (err.message) { return of({ status: 'error', message: err.message }); } else { return of({ status: 'error', message: err.status }); } }) ) .toPromise(); } getQueryHeader(searchType: any, timeFrom?: DateTime, timeTo?: DateTime): string { const queryHeader: any = { search_type: searchType, ignore_unavailable: true, index: this.indexPattern.getIndexList(timeFrom, timeTo), }; if (this.esVersion >= 56 && this.esVersion < 70) { queryHeader['max_concurrent_shard_requests'] = this.maxConcurrentShardRequests; } return JSON.stringify(queryHeader); } getQueryDisplayText(query: ElasticsearchQuery) { // TODO: This might be refactored a bit. const metricAggs = query.metrics; const bucketAggs = query.bucketAggs; let text = ''; if (query.query) { text += 'Query: ' + query.query + ', '; } text += 'Metrics: '; text += metricAggs?.reduce((acc, metric) => { const metricConfig = metricAggregationConfig[metric.type]; let text = metricConfig.label + '('; if (isMetricAggregationWithField(metric)) { text += metric.field; } if (isPipelineAggregationWithMultipleBucketPaths(metric)) { text += getScriptValue(metric).replace(new RegExp('params.', 'g'), ''); } text += '), '; return `${acc} ${text}`; }, ''); text += bucketAggs?.reduce((acc, bucketAgg, index) => { const bucketConfig = bucketAggregationConfig[bucketAgg.type]; let text = ''; if (index === 0) { text += ' Group by: '; } text += bucketConfig.label + '('; if (isBucketAggregationWithField(bucketAgg)) { text += bucketAgg.field; } return `${acc} ${text}), `; }, ''); if (query.alias) { text += 'Alias: ' + query.alias; } return text; } /** * This method checks to ensure the user is running a 5.0+ cluster. This is * necessary bacause the query being used for the getLogRowContext relies on the * search_after feature. */ showContextToggle(): boolean { return this.esVersion > 5; } getLogRowContext = async (row: LogRowModel, options?: RowContextOptions): Promise<{ data: DataFrame[] }> => { const sortField = row.dataFrame.fields.find((f) => f.name === 'sort'); const searchAfter = sortField?.values.get(row.rowIndex) || [row.timeEpochMs]; const sort = options?.direction === 'FORWARD' ? 'asc' : 'desc'; const header = options?.direction === 'FORWARD' ? this.getQueryHeader('query_then_fetch', dateTime(row.timeEpochMs)) : this.getQueryHeader('query_then_fetch', undefined, dateTime(row.timeEpochMs)); const limit = options?.limit ?? 10; const esQuery = JSON.stringify({ size: limit, query: { bool: { filter: [ { range: { [this.timeField]: { [options?.direction === 'FORWARD' ? 'gte' : 'lte']: row.timeEpochMs, format: 'epoch_millis', }, }, }, ], }, }, sort: [{ [this.timeField]: sort }, { _doc: sort }], search_after: searchAfter, }); const payload = [header, esQuery].join('\n') + '\n'; const url = this.getMultiSearchUrl(); const response = await this.post(url, payload).toPromise(); const targets: ElasticsearchQuery[] = [{ refId: `${row.dataFrame.refId}`, metrics: [{ type: 'logs', id: '1' }] }]; const elasticResponse = new ElasticResponse(targets, transformHitsBasedOnDirection(response, sort)); const logResponse = elasticResponse.getLogs(this.logMessageField, this.logLevelField); const dataFrame = _first(logResponse.data); if (!dataFrame) { return { data: [] }; } /** * The LogRowContextProvider requires there is a field in the dataFrame.fields * named `ts` for timestamp and `line` for the actual log line to display. * Unfortunatly these fields are hardcoded and are required for the lines to * be properly displayed. This code just copies the fields based on this.timeField * and this.logMessageField and recreates the dataFrame so it works. */ const timestampField = dataFrame.fields.find((f: Field) => f.name === this.timeField); const lineField = dataFrame.fields.find((f: Field) => f.name === this.logMessageField); if (timestampField && lineField) { return { data: [ { ...dataFrame, fields: [...dataFrame.fields, { ...timestampField, name: 'ts' }, { ...lineField, name: 'line' }], }, ], }; } return logResponse; }; query(options: DataQueryRequest<ElasticsearchQuery>): Observable<DataQueryResponse> { let payload = ''; const targets = this.interpolateVariablesInQueries(cloneDeep(options.targets), options.scopedVars); const sentTargets: ElasticsearchQuery[] = []; let targetsContainsLogsQuery = targets.some((target) => hasMetricOfType(target, 'logs')); // add global adhoc filters to timeFilter const adhocFilters = this.templateSrv.getAdhocFilters(this.name); for (const target of targets) { if (target.hide) { continue; } let queryObj; if (hasMetricOfType(target, 'logs')) { // FIXME: All this logic here should be in the query builder. // When moving to the BE-only implementation we should remove this and let the BE // Handle this. // TODO: defaultBucketAgg creates a dete_histogram aggregation without a field, so it fallbacks to // the configured timeField. we should allow people to use a different time field here. target.bucketAggs = [defaultBucketAgg()]; const log = target.metrics?.find((m) => m.type === 'logs') as Logs; const limit = log.settings?.limit ? parseInt(log.settings?.limit, 10) : 500; target.metrics = []; // Setting this for metrics queries that are typed as logs queryObj = this.queryBuilder.getLogsQuery(target, limit, adhocFilters, target.query); } else { if (target.alias) { target.alias = this.templateSrv.replace(target.alias, options.scopedVars, 'lucene'); } queryObj = this.queryBuilder.build(target, adhocFilters, target.query); } const esQuery = JSON.stringify(queryObj); const searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch'; const header = this.getQueryHeader(searchType, options.range.from, options.range.to); payload += header + '\n'; payload += esQuery + '\n'; sentTargets.push(target); } if (sentTargets.length === 0) { return of({ data: [] }); } // We replace the range here for actual values. We need to replace it together with enclosing "" so that we replace // it as an integer not as string with digits. This is because elastic will convert the string only if the time // field is specified as type date (which probably should) but can also be specified as integer (millisecond epoch) // and then sending string will error out. payload = payload.replace(/"\$timeFrom"/g, options.range.from.valueOf().toString()); payload = payload.replace(/"\$timeTo"/g, options.range.to.valueOf().toString()); payload = this.templateSrv.replace(payload, options.scopedVars); const url = this.getMultiSearchUrl(); return this.post(url, payload).pipe( map((res) => { const er = new ElasticResponse(sentTargets, res); // TODO: This needs to be revisited, it seems wrong to process ALL the sent queries as logs if only one of them was a log query if (targetsContainsLogsQuery) { const response = er.getLogs(this.logMessageField, this.logLevelField); for (const dataFrame of response.data) { enhanceDataFrame(dataFrame, this.dataLinks); } return response; } return er.getTimeSeries(); }) ); } isMetadataField(fieldName: string) { return ELASTIC_META_FIELDS.includes(fieldName); } // TODO: instead of being a string, this could be a custom type representing all the elastic types // FIXME: This doesn't seem to return actual MetricFindValues, we should either change the return type // or fix the implementation. getFields(type?: string, range?: TimeRange): Observable<MetricFindValue[]> { const configuredEsVersion = this.esVersion; return this.get('/_mapping', range).pipe( map((result) => { const typeMap: any = { float: 'number', double: 'number', integer: 'number', long: 'number', date: 'date', date_nanos: 'date', string: 'string', text: 'string', scaled_float: 'number', nested: 'nested', histogram: 'number', }; const shouldAddField = (obj: any, key: string) => { if (this.isMetadataField(key)) { return false; } if (!type) { return true; } // equal query type filter, or via typemap translation return type === obj.type || type === typeMap[obj.type]; }; // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total const fieldNameParts: any = []; const fields: any = {}; function getFieldsRecursively(obj: any) { for (const key in obj) { const subObj = obj[key]; // Check mapping field for nested fields if (isObject(subObj.properties)) { fieldNameParts.push(key); getFieldsRecursively(subObj.properties); } if (isObject(subObj.fields)) { fieldNameParts.push(key); getFieldsRecursively(subObj.fields); } if (isString(subObj.type)) { const fieldName = fieldNameParts.concat(key).join('.'); // Hide meta-fields and check field type if (shouldAddField(subObj, key)) { fields[fieldName] = { text: fieldName, type: subObj.type, }; } } } fieldNameParts.pop(); } for (const indexName in result) { const index = result[indexName]; if (index && index.mappings) { const mappings = index.mappings; if (configuredEsVersion < 70) { for (const typeName in mappings) { const properties = mappings[typeName].properties; getFieldsRecursively(properties); } } else { const properties = mappings.properties; getFieldsRecursively(properties); } } } // transform to array return _map(fields, (value) => { return value; }); }) ); } getTerms(queryDef: any, range = getDefaultTimeRange()): Observable<MetricFindValue[]> { const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count'; const header = this.getQueryHeader(searchType, range.from, range.to); let esQuery = JSON.stringify(this.queryBuilder.getTermsQuery(queryDef)); esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf().toString()); esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf().toString()); esQuery = header + '\n' + esQuery + '\n'; const url = this.getMultiSearchUrl(); return this.post(url, esQuery).pipe( map((res) => { if (!res.responses[0].aggregations) { return []; } const buckets = res.responses[0].aggregations['1'].buckets; return _map(buckets, (bucket) => { return { text: bucket.key_as_string || bucket.key, value: bucket.key, }; }); }) ); } getMultiSearchUrl() { if (this.esVersion >= 70 && this.maxConcurrentShardRequests) { return `_msearch?max_concurrent_shard_requests=${this.maxConcurrentShardRequests}`; } return '_msearch'; } metricFindQuery(query: string, options?: any): Promise<MetricFindValue[]> { const range = options?.range; const parsedQuery = JSON.parse(query); if (query) { if (parsedQuery.find === 'fields') { parsedQuery.type = this.templateSrv.replace(parsedQuery.type, {}, 'lucene'); return this.getFields(parsedQuery.type, range).toPromise(); } if (parsedQuery.find === 'terms') { parsedQuery.field = this.templateSrv.replace(parsedQuery.field, {}, 'lucene'); parsedQuery.query = this.templateSrv.replace(parsedQuery.query || '*', {}, 'lucene'); return this.getTerms(parsedQuery, range).toPromise(); } } return Promise.resolve([]); } getTagKeys() { return this.getFields().toPromise(); } getTagValues(options: any) { return this.getTerms({ field: options.key, query: '*' }).toPromise(); } targetContainsTemplate(target: any) { if (this.templateSrv.variableExists(target.query) || this.templateSrv.variableExists(target.alias)) { return true; } for (const bucketAgg of target.bucketAggs) { if (this.templateSrv.variableExists(bucketAgg.field) || this.objectContainsTemplate(bucketAgg.settings)) { return true; } } for (const metric of target.metrics) { if ( this.templateSrv.variableExists(metric.field) || this.objectContainsTemplate(metric.settings) || this.objectContainsTemplate(metric.meta) ) { return true; } } return false; } private isPrimitive(obj: any) { if (obj === null || obj === undefined) { return true; } if (['string', 'number', 'boolean'].some((type) => type === typeof true)) { return true; } return false; } private objectContainsTemplate(obj: any) { if (!obj) { return false; } for (const key of Object.keys(obj)) { if (this.isPrimitive(obj[key])) { if (this.templateSrv.variableExists(obj[key])) { return true; } } else if (Array.isArray(obj[key])) { for (const item of obj[key]) { if (this.objectContainsTemplate(item)) { return true; } } } else { if (this.objectContainsTemplate(obj[key])) { return true; } } } return false; } } /** * Modifies dataframe and adds dataLinks from the config. * Exported for tests. */ export function enhanceDataFrame(dataFrame: DataFrame, dataLinks: DataLinkConfig[]) { const dataSourceSrv = getDataSourceSrv(); if (!dataLinks.length) { return; } for (const field of dataFrame.fields) { const dataLinkConfig = dataLinks.find((dataLink) => field.name && field.name.match(dataLink.field)); if (!dataLinkConfig) { continue; } let link: DataLink; if (dataLinkConfig.datasourceUid) { const dsSettings = dataSourceSrv.getInstanceSettings(dataLinkConfig.datasourceUid); link = { title: '', url: '', internal: { query: { query: dataLinkConfig.url }, datasourceUid: dataLinkConfig.datasourceUid, datasourceName: dsSettings?.name ?? 'Data source not found', }, }; } else { link = { title: '', url: dataLinkConfig.url, }; } field.config = field.config || {}; field.config.links = [...(field.config.links || []), link]; } } function transformHitsBasedOnDirection(response: any, direction: 'asc' | 'desc') { if (direction === 'desc') { return response; } const actualResponse = response.responses[0]; return { ...response, responses: [ { ...actualResponse, hits: { ...actualResponse.hits, hits: actualResponse.hits.hits.reverse(), }, }, ], }; }
public/app/plugins/datasource/elasticsearch/datasource.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00022346536570694298, 0.00017135331290774047, 0.00016524290549568832, 0.00017082365229725838, 0.000005875473107153084 ]
{ "id": 3, "code_window": [ " });\n", " }, [config, setRenderToken]);\n", "\n", " const eventMarkers = useMemo(() => {\n", " const markers: React.ReactNode[] = [];\n", " if (!plotCtx.plot || events.length === 0) {\n", " return markers;\n", " }\n", "\n", " for (let i = 0; i < events.length; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || events.length === 0) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 29 }
import { DataFrame, Field, LinkModel, TimeZone, TIME_SERIES_TIME_FIELD_NAME, TIME_SERIES_VALUE_FIELD_NAME, } from '@grafana/data'; import { EventsCanvas, FIXED_UNIT, UPlotConfigBuilder, usePlotContext } from '@grafana/ui'; import React, { useCallback } from 'react'; import { ExemplarMarker } from './ExemplarMarker'; interface ExemplarsPluginProps { config: UPlotConfigBuilder; exemplars: DataFrame[]; timeZone: TimeZone; getFieldLinks: (field: Field, rowIndex: number) => Array<LinkModel<Field>>; } export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => { const plotCtx = usePlotContext(); const mapExemplarToXYCoords = useCallback( (dataFrame: DataFrame, index: number) => { const plotInstance = plotCtx.plot; const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME); const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME); if (!time || !value || !plotInstance) { return undefined; } // Filter x, y scales out const yScale = Object.keys(plotInstance.scales).find((scale) => !['x', 'y'].some((key) => key === scale)) ?? FIXED_UNIT; const yMin = plotInstance.scales[yScale].min; const yMax = plotInstance.scales[yScale].max; let y = value.values.get(index); // To not to show exemplars outside of the graph we set the y value to min if it is smaller and max if it is bigger than the size of the graph if (yMin != null && y < yMin) { y = yMin; } if (yMax != null && y > yMax) { y = yMax; } return { x: plotInstance.valToPos(time.values.get(index), 'x'), y: plotInstance.valToPos(y, yScale), }; }, [plotCtx] ); const renderMarker = useCallback( (dataFrame: DataFrame, index: number) => { return <ExemplarMarker timeZone={timeZone} getFieldLinks={getFieldLinks} dataFrame={dataFrame} index={index} />; }, [timeZone, getFieldLinks] ); return ( <EventsCanvas config={config} id="exemplars" events={exemplars} renderEventMarker={renderMarker} mapEventToXYCoords={mapExemplarToXYCoords} /> ); };
public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.004749901592731476, 0.001669935998506844, 0.00016763099119998515, 0.00033225331571884453, 0.0019284940790385008 ]
{ "id": 3, "code_window": [ " });\n", " }, [config, setRenderToken]);\n", "\n", " const eventMarkers = useMemo(() => {\n", " const markers: React.ReactNode[] = [];\n", " if (!plotCtx.plot || events.length === 0) {\n", " return markers;\n", " }\n", "\n", " for (let i = 0; i < events.length; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || events.length === 0) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 29 }
import { Action } from '../../hooks/useStatelessReducer'; import { ElasticsearchQuery } from '../../types'; export const INIT = 'init'; const CHANGE_QUERY = 'change_query'; const CHANGE_ALIAS_PATTERN = 'change_alias_pattern'; export interface InitAction extends Action<typeof INIT> {} interface ChangeQueryAction extends Action<typeof CHANGE_QUERY> { payload: { query: string; }; } interface ChangeAliasPatternAction extends Action<typeof CHANGE_ALIAS_PATTERN> { payload: { aliasPattern: string; }; } /** * When the `initQuery` Action is dispatched, the query gets populated with default values where values are not present. * This means it won't override any existing value in place, but just ensure the query is in a "runnable" state. */ export const initQuery = (): InitAction => ({ type: INIT }); export const changeQuery = (query: string): ChangeQueryAction => ({ type: CHANGE_QUERY, payload: { query, }, }); export const changeAliasPattern = (aliasPattern: string): ChangeAliasPatternAction => ({ type: CHANGE_ALIAS_PATTERN, payload: { aliasPattern, }, }); export const queryReducer = (prevQuery: ElasticsearchQuery['query'], action: ChangeQueryAction | InitAction) => { switch (action.type) { case CHANGE_QUERY: return action.payload.query; case INIT: return prevQuery || ''; default: return prevQuery; } }; export const aliasPatternReducer = ( prevAliasPattern: ElasticsearchQuery['alias'], action: ChangeAliasPatternAction | InitAction ) => { switch (action.type) { case CHANGE_ALIAS_PATTERN: return action.payload.aliasPattern; case INIT: return prevAliasPattern || ''; default: return prevAliasPattern; } };
public/app/plugins/datasource/elasticsearch/components/QueryEditor/state.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017497157386969775, 0.0001727464987197891, 0.0001709211792331189, 0.00017333378491457552, 0.0000015791731584613444 ]
{ "id": 3, "code_window": [ " });\n", " }, [config, setRenderToken]);\n", "\n", " const eventMarkers = useMemo(() => {\n", " const markers: React.ReactNode[] = [];\n", " if (!plotCtx.plot || events.length === 0) {\n", " return markers;\n", " }\n", "\n", " for (let i = 0; i < events.length; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || events.length === 0) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 29 }
package models import ( "fmt" "time" "github.com/grafana/grafana/pkg/components/simplejson" ) type AlertStateType string type NoDataOption string type ExecutionErrorOption string const ( AlertStateNoData AlertStateType = "no_data" AlertStatePaused AlertStateType = "paused" AlertStateAlerting AlertStateType = "alerting" AlertStateOK AlertStateType = "ok" AlertStatePending AlertStateType = "pending" AlertStateUnknown AlertStateType = "unknown" ) const ( NoDataSetOK NoDataOption = "ok" NoDataSetNoData NoDataOption = "no_data" NoDataKeepState NoDataOption = "keep_state" NoDataSetAlerting NoDataOption = "alerting" ) const ( ExecutionErrorSetAlerting ExecutionErrorOption = "alerting" ExecutionErrorKeepState ExecutionErrorOption = "keep_state" ) var ( ErrCannotChangeStateOnPausedAlert = fmt.Errorf("cannot change state on pause alert") ErrRequiresNewState = fmt.Errorf("update alert state requires a new state") ) func (s AlertStateType) IsValid() bool { return s == AlertStateOK || s == AlertStateNoData || s == AlertStatePaused || s == AlertStatePending || s == AlertStateAlerting || s == AlertStateUnknown } func (s NoDataOption) IsValid() bool { return s == NoDataSetNoData || s == NoDataSetAlerting || s == NoDataKeepState || s == NoDataSetOK } func (s NoDataOption) ToAlertState() AlertStateType { return AlertStateType(s) } func (s ExecutionErrorOption) IsValid() bool { return s == ExecutionErrorSetAlerting || s == ExecutionErrorKeepState } func (s ExecutionErrorOption) ToAlertState() AlertStateType { return AlertStateType(s) } type Alert struct { Id int64 Version int64 OrgId int64 DashboardId int64 PanelId int64 Name string Message string Severity string // Unused State AlertStateType Handler int64 // Unused Silenced bool ExecutionError string Frequency int64 For time.Duration EvalData *simplejson.Json NewStateDate time.Time StateChanges int64 Created time.Time Updated time.Time Settings *simplejson.Json } func (a *Alert) ValidToSave() bool { return a.DashboardId != 0 && a.OrgId != 0 && a.PanelId != 0 } func (a *Alert) ContainsUpdates(other *Alert) bool { result := false result = result || a.Name != other.Name result = result || a.Message != other.Message if a.Settings != nil && other.Settings != nil { json1, err1 := a.Settings.Encode() json2, err2 := other.Settings.Encode() if err1 != nil || err2 != nil { return false } result = result || string(json1) != string(json2) } // don't compare .State! That would be insane. return result } func (a *Alert) GetTagsFromSettings() []*Tag { tags := []*Tag{} if a.Settings != nil { if data, ok := a.Settings.CheckGet("alertRuleTags"); ok { for tagNameString, tagValue := range data.MustMap() { // MustMap() already guarantees the return of a `map[string]interface{}`. // Therefore we only need to verify that tagValue is a String. tagValueString := simplejson.NewFromAny(tagValue).MustString() tags = append(tags, &Tag{Key: tagNameString, Value: tagValueString}) } } } return tags } type SaveAlertsCommand struct { DashboardId int64 UserId int64 OrgId int64 Alerts []*Alert } type PauseAlertCommand struct { OrgId int64 AlertIds []int64 ResultCount int64 Paused bool } type PauseAllAlertCommand struct { ResultCount int64 Paused bool } type SetAlertStateCommand struct { AlertId int64 OrgId int64 State AlertStateType Error string EvalData *simplejson.Json Result Alert } // Queries type GetAlertsQuery struct { OrgId int64 State []string DashboardIDs []int64 PanelId int64 Limit int64 Query string User *SignedInUser Result []*AlertListItemDTO } type GetAllAlertsQuery struct { Result []*Alert } type GetAlertByIdQuery struct { Id int64 Result *Alert } type GetAlertStatesForDashboardQuery struct { OrgId int64 DashboardId int64 Result []*AlertStateInfoDTO } type AlertListItemDTO struct { Id int64 `json:"id"` DashboardId int64 `json:"dashboardId"` DashboardUid string `json:"dashboardUid"` DashboardSlug string `json:"dashboardSlug"` PanelId int64 `json:"panelId"` Name string `json:"name"` State AlertStateType `json:"state"` NewStateDate time.Time `json:"newStateDate"` EvalDate time.Time `json:"evalDate"` EvalData *simplejson.Json `json:"evalData"` ExecutionError string `json:"executionError"` Url string `json:"url"` } type AlertStateInfoDTO struct { Id int64 `json:"id"` DashboardId int64 `json:"dashboardId"` PanelId int64 `json:"panelId"` State AlertStateType `json:"state"` NewStateDate time.Time `json:"newStateDate"` }
pkg/models/alert.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017418870993424207, 0.000170321756741032, 0.00016520402277819812, 0.00016983345267362893, 0.000002651179784152191 ]
{ "id": 3, "code_window": [ " });\n", " }, [config, setRenderToken]);\n", "\n", " const eventMarkers = useMemo(() => {\n", " const markers: React.ReactNode[] = [];\n", " if (!plotCtx.plot || events.length === 0) {\n", " return markers;\n", " }\n", "\n", " for (let i = 0; i < events.length; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || events.length === 0) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 29 }
package migrations import ( . "github.com/grafana/grafana/pkg/services/sqlstore/migrator" ) func addQuotaMigration(mg *Migrator) { var quotaV1 = Table{ Name: "quota", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "org_id", Type: DB_BigInt, Nullable: true}, {Name: "user_id", Type: DB_BigInt, Nullable: true}, {Name: "target", Type: DB_NVarchar, Length: 190, Nullable: false}, {Name: "limit", Type: DB_BigInt, Nullable: false}, {Name: "created", Type: DB_DateTime, Nullable: false}, {Name: "updated", Type: DB_DateTime, Nullable: false}, }, Indices: []*Index{ {Cols: []string{"org_id", "user_id", "target"}, Type: UniqueIndex}, }, } mg.AddMigration("create quota table v1", NewAddTableMigration(quotaV1)) //------- indexes ------------------ addTableIndicesMigrations(mg, "v1", quotaV1) mg.AddMigration("Update quota table charset", NewTableCharsetMigration("quota", []*Column{ {Name: "target", Type: DB_NVarchar, Length: 190, Nullable: false}, })) }
pkg/services/sqlstore/migrations/quota_mig.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017620112339500338, 0.00017261714674532413, 0.00017043310799635947, 0.0001719171996228397, 0.0000021581267901638057 ]
{ "id": 4, "code_window": [ " }\n", "\n", " return <>{markers}</>;\n", " }, [events, renderEventMarker, renderToken, plotCtx]);\n", "\n", " if (!plotCtx.plot) {\n", " return null;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!plotCtx.getPlot()) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 51 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0020669782534241676, 0.0005370949511416256, 0.00016610337479505688, 0.0001742205349728465, 0.0006601462955586612 ]
{ "id": 4, "code_window": [ " }\n", "\n", " return <>{markers}</>;\n", " }, [events, renderEventMarker, renderToken, plotCtx]);\n", "\n", " if (!plotCtx.plot) {\n", " return null;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!plotCtx.getPlot()) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 51 }
package plugins import ( "testing" "github.com/grafana/grafana-plugin-model/go/datasource" "github.com/grafana/grafana/pkg/infra/log" "github.com/stretchr/testify/require" ) func TestMapTables(t *testing.T) { dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil) var qr = &datasource.QueryResult{} qr.Tables = append(qr.Tables, &datasource.Table{ Columns: []*datasource.TableColumn{}, Rows: nil, }) have, err := dpw.mapTables(qr) require.NoError(t, err) require.Len(t, have, 1) } func TestMapTable(t *testing.T) { dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil) source := &datasource.Table{ Columns: []*datasource.TableColumn{{Name: "column1"}, {Name: "column2"}}, Rows: []*datasource.TableRow{{ Values: []*datasource.RowValue{ { Kind: datasource.RowValue_TYPE_BOOL, BoolValue: true, }, { Kind: datasource.RowValue_TYPE_INT64, Int64Value: 42, }, }, }}, } want := DataTable{ Columns: []DataTableColumn{{Text: "column1"}, {Text: "column2"}}, } have, err := dpw.mapTable(source) require.NoError(t, err) require.Equal(t, want.Columns, have.Columns) require.Len(t, have.Rows, 1) require.Len(t, have.Rows[0], 2) } func TestMappingRowValue(t *testing.T) { dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil) boolRowValue, err := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_BOOL, BoolValue: true}) require.NoError(t, err) haveBool, ok := boolRowValue.(bool) require.True(t, ok) require.True(t, haveBool) intRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_INT64, Int64Value: 42}) haveInt, ok := intRowValue.(int64) require.True(t, ok) require.Equal(t, int64(42), haveInt) stringRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_STRING, StringValue: "grafana"}) haveString, ok := stringRowValue.(string) require.True(t, ok) require.Equal(t, "grafana", haveString) doubleRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_DOUBLE, DoubleValue: 1.5}) haveDouble, ok := doubleRowValue.(float64) require.True(t, ok) require.Equal(t, 1.5, haveDouble) bytesRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_BYTES, BytesValue: []byte{66}}) haveBytes, ok := bytesRowValue.([]byte) require.True(t, ok) require.Equal(t, []byte{66}, haveBytes) haveNil, err := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_NULL}) require.NoError(t, err) require.Nil(t, haveNil) }
pkg/plugins/datasource_plugin_wrapper_test.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017828965792432427, 0.0001744405017234385, 0.00017196117551065981, 0.00017386612307745963, 0.0000018210591861134162 ]
{ "id": 4, "code_window": [ " }\n", "\n", " return <>{markers}</>;\n", " }, [events, renderEventMarker, renderToken, plotCtx]);\n", "\n", " if (!plotCtx.plot) {\n", " return null;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!plotCtx.getPlot()) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 51 }
declare var CloudWatchDatasource: any; export default CloudWatchDatasource;
public/app/plugins/datasource/cloudwatch/datasource.d.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017247845244128257, 0.00017247845244128257, 0.00017247845244128257, 0.00017247845244128257, 0 ]
{ "id": 4, "code_window": [ " }\n", "\n", " return <>{markers}</>;\n", " }, [events, renderEventMarker, renderToken, plotCtx]);\n", "\n", " if (!plotCtx.plot) {\n", " return null;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!plotCtx.getPlot()) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/EventsCanvas.tsx", "type": "replace", "edit_start_line_idx": 51 }
import { createColors } from './createColors'; describe('createColors', () => { it('Should enrich colors', () => { const palette = createColors({}); expect(palette.primary.name).toBe('primary'); }); it('Should allow overrides', () => { const palette = createColors({ primary: { main: '#FF0000', }, }); expect(palette.primary.main).toBe('#FF0000'); }); });
packages/grafana-data/src/themes/createColors.test.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017629473586566746, 0.00017382964142598212, 0.00017136454698629677, 0.00017382964142598212, 0.0000024650944396853447 ]
{ "id": 5, "code_window": [ " */\n", "export const XYCanvas: React.FC<XYCanvasProps> = ({ children }) => {\n", " const plotCtx = usePlotContext();\n", " const plotInstance = plotCtx.plot;\n", "\n", " if (!plotInstance) {\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx", "type": "replace", "edit_start_line_idx": 12 }
import React, { useContext } from 'react'; import uPlot from 'uplot'; interface PlotContextType { plot: uPlot | undefined; } /** * @alpha */ export const PlotContext = React.createContext<PlotContextType>({} as PlotContextType); // Exposes uPlot instance and bounding box of the entire canvas and plot area export const usePlotContext = (): PlotContextType => { return useContext<PlotContextType>(PlotContext); };
packages/grafana-ui/src/components/uPlot/context.ts
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.003564136102795601, 0.002483020070940256, 0.001401904271915555, 0.002483020070940256, 0.001081115915440023 ]
{ "id": 5, "code_window": [ " */\n", "export const XYCanvas: React.FC<XYCanvasProps> = ({ children }) => {\n", " const plotCtx = usePlotContext();\n", " const plotInstance = plotCtx.plot;\n", "\n", " if (!plotInstance) {\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx", "type": "replace", "edit_start_line_idx": 12 }
import './panel_directive'; import './query_ctrl'; import './panel_editor_tab'; import './query_editor_row'; import './panellinks/module';
public/app/features/panel/all.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017739448230713606, 0.00017739448230713606, 0.00017739448230713606, 0.00017739448230713606, 0 ]
{ "id": 5, "code_window": [ " */\n", "export const XYCanvas: React.FC<XYCanvasProps> = ({ children }) => {\n", " const plotCtx = usePlotContext();\n", " const plotInstance = plotCtx.plot;\n", "\n", " if (!plotInstance) {\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx", "type": "replace", "edit_start_line_idx": 12 }
import React, { useRef, useState, useLayoutEffect } from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { useClickAway } from 'react-use'; import { Portal } from '../Portal/Portal'; import { Menu } from '../Menu/Menu'; export interface ContextMenuProps { /** Starting horizontal position for the menu */ x: number; /** Starting vertical position for the menu */ y: number; /** Callback for closing the menu */ onClose?: () => void; /** RenderProp function that returns menu items to display */ renderMenuItems?: () => React.ReactNode; /** A function that returns header element */ renderHeader?: () => React.ReactNode; } export const ContextMenu: React.FC<ContextMenuProps> = React.memo( ({ x, y, onClose, renderMenuItems, renderHeader }) => { const menuRef = useRef<HTMLDivElement>(null); const [positionStyles, setPositionStyles] = useState({}); useLayoutEffect(() => { const menuElement = menuRef.current; if (menuElement) { const rect = menuElement.getBoundingClientRect(); const OFFSET = 5; const collisions = { right: window.innerWidth < x + rect.width, bottom: window.innerHeight < rect.bottom + rect.height + OFFSET, }; setPositionStyles({ position: 'fixed', left: collisions.right ? x - rect.width - OFFSET : x - OFFSET, top: collisions.bottom ? y - rect.height - OFFSET : y + OFFSET, }); } }, [x, y]); useClickAway(menuRef, () => { if (onClose) { onClose(); } }); const header = renderHeader && renderHeader(); const menuItems = renderMenuItems && renderMenuItems(); return ( <Portal> <Menu header={header} ref={menuRef} style={positionStyles} ariaLabel={selectors.components.Menu.MenuComponent('Context')} onClick={onClose} > {menuItems} </Menu> </Portal> ); } ); ContextMenu.displayName = 'ContextMenu';
packages/grafana-ui/src/components/ContextMenu/ContextMenu.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0002376549964537844, 0.0001859816547948867, 0.00016787508502602577, 0.00017638552526477724, 0.000022983782400842756 ]
{ "id": 5, "code_window": [ " */\n", "export const XYCanvas: React.FC<XYCanvasProps> = ({ children }) => {\n", " const plotCtx = usePlotContext();\n", " const plotInstance = plotCtx.plot;\n", "\n", " if (!plotInstance) {\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx", "type": "replace", "edit_start_line_idx": 12 }
import { getDashboardSrv } from '../../dashboard/services/DashboardSrv'; import { PanelData, LoadingState, DataSourceApi, CoreApp, urlUtil } from '@grafana/data'; import { reportMetaAnalytics, MetaAnalyticsEventName, DataRequestEventPayload } from '@grafana/runtime'; export function emitDataRequestEvent(datasource: DataSourceApi) { let done = false; return (data: PanelData) => { if (!data.request || done || data.request.app === CoreApp.Explore) { return; } const params = urlUtil.getUrlSearchParams(); if (params.editPanel != null) { return; } if (data.state !== LoadingState.Done && data.state !== LoadingState.Error) { return; } const eventData: DataRequestEventPayload = { eventName: MetaAnalyticsEventName.DataRequest, datasourceName: datasource.name, datasourceId: datasource.id, datasourceType: datasource.type, panelId: data.request.panelId, dashboardId: data.request.dashboardId, dataSize: 0, duration: data.request.endTime! - data.request.startTime, }; // enrich with dashboard info const dashboard = getDashboardSrv().getCurrent(); if (dashboard) { eventData.dashboardId = dashboard.id; eventData.dashboardName = dashboard.title; eventData.dashboardUid = dashboard.uid; eventData.folderName = dashboard.meta.folderTitle; } if (data.series && data.series.length > 0) { // estimate size eventData.dataSize = data.series.length; } if (data.error) { eventData.error = data.error.message; } reportMetaAnalytics(eventData); // this done check is to make sure we do not double emit events in case // there are multiple responses with done state done = true; }; }
public/app/features/query/state/queryAnalytics.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0001775510172592476, 0.00017581529391463846, 0.00017410585132893175, 0.0001757036370690912, 0.0000013802169860355207 ]
{ "id": 6, "code_window": [ " });\n", " }, [config]);\n", "\n", " if (!plotCtx.plot || focusedPointIdx === null) {\n", " return null;\n", " }\n", "\n", " // GraphNG expects aligned data, let's take field 0 as x field. FTW\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || focusedPointIdx === null) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 76 }
import { DataFrame, DataFrameView, dateTimeFormat, systemDateFormats, TimeZone } from '@grafana/data'; import { EventsCanvas, UPlotConfigBuilder, usePlotContext, useTheme } from '@grafana/ui'; import React, { useCallback, useEffect, useLayoutEffect, useRef } from 'react'; import { AnnotationMarker } from './AnnotationMarker'; interface AnnotationsPluginProps { config: UPlotConfigBuilder; annotations: DataFrame[]; timeZone: TimeZone; } interface AnnotationsDataFrameViewDTO { time: number; text: string; tags: string[]; } export const AnnotationsPlugin: React.FC<AnnotationsPluginProps> = ({ annotations, timeZone, config }) => { const theme = useTheme(); const plotCtx = usePlotContext(); const annotationsRef = useRef<Array<DataFrameView<AnnotationsDataFrameViewDTO>>>(); const timeFormatter = useCallback( (value: number) => { return dateTimeFormat(value, { format: systemDateFormats.fullDate, timeZone, }); }, [timeZone] ); // Update annotations views when new annotations came useEffect(() => { const views: Array<DataFrameView<AnnotationsDataFrameViewDTO>> = []; for (const frame of annotations) { views.push(new DataFrameView(frame)); } annotationsRef.current = views; }, [annotations]); useLayoutEffect(() => { config.addHook('draw', (u) => { // Render annotation lines on the canvas /** * We cannot rely on state value here, as it would require this effect to be dependent on the state value. */ if (!annotationsRef.current) { return null; } const ctx = u.ctx; if (!ctx) { return; } for (let i = 0; i < annotationsRef.current.length; i++) { const annotationsView = annotationsRef.current[i]; for (let j = 0; j < annotationsView.length; j++) { const annotation = annotationsView.get(j); if (!annotation.time) { continue; } const xpos = u.valToPos(annotation.time, 'x', true); ctx.beginPath(); ctx.lineWidth = 2; ctx.strokeStyle = theme.palette.red; ctx.setLineDash([5, 5]); ctx.moveTo(xpos, u.bbox.top); ctx.lineTo(xpos, u.bbox.top + u.bbox.height); ctx.stroke(); ctx.closePath(); } } return; }); }, [config, theme]); const mapAnnotationToXYCoords = useCallback( (frame: DataFrame, index: number) => { const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame); const annotation = view.get(index); const plotInstance = plotCtx.plot; if (!annotation.time || !plotInstance) { return undefined; } return { x: plotInstance.valToPos(annotation.time, 'x'), y: plotInstance.bbox.height / window.devicePixelRatio + 4, }; }, [plotCtx.plot] ); const renderMarker = useCallback( (frame: DataFrame, index: number) => { const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame); const annotation = view.get(index); return <AnnotationMarker time={timeFormatter(annotation.time)} text={annotation.text} tags={annotation.tags} />; }, [timeFormatter] ); return ( <EventsCanvas id="annotations" config={config} events={annotations} renderEventMarker={renderMarker} mapEventToXYCoords={mapAnnotationToXYCoords} /> ); };
public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.008187692612409592, 0.0011134480591863394, 0.00016671555931679904, 0.00017502190894447267, 0.002233212348073721 ]
{ "id": 6, "code_window": [ " });\n", " }, [config]);\n", "\n", " if (!plotCtx.plot || focusedPointIdx === null) {\n", " return null;\n", " }\n", "\n", " // GraphNG expects aligned data, let's take field 0 as x field. FTW\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || focusedPointIdx === null) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 76 }
import React, { useState, useCallback } from 'react'; import { action } from '@storybook/addon-actions'; import { Meta, Story } from '@storybook/react'; import { withCenteredStory } from '../../../../utils/storybook/withCenteredStory'; import { UseState } from '../../../../utils/storybook/UseState'; import { SelectableValue } from '@grafana/data'; import { Select, AsyncSelect as AsyncSelectComponent } from './Select'; export default { title: 'Forms/Legacy/Select', component: Select, decorators: [withCenteredStory], parameters: { knobs: { disable: true, }, controls: { exclude: [ 'className', 'menuPlacement', 'menuPosition', 'maxMenuHeight', 'minMenuHeight', 'maxVisibleValues', 'prefix', 'renderControl', 'value', 'tooltipContent', 'components', 'inputValue', 'id', 'inputId', 'defaultValue', 'loading', 'aria-label', ], }, }, argTypes: { width: { control: { type: 'range', min: 5, max: 30 } }, }, } as Meta; const initialValue: SelectableValue<string> = { label: 'A label', value: 'A value' }; const options = [ initialValue, { label: 'Another label', value: 'Another value 1' }, { label: 'Another label', value: 'Another value 2' }, { label: 'Another label', value: 'Another value 3' }, { label: 'Another label', value: 'Another value 4' }, { label: 'Another label', value: 'Another value 5' }, { label: 'Another label', value: 'Another value ' }, ]; export const Basic: Story = (args) => { return ( <UseState initialState={initialValue}> {(value, updateValue) => { return ( <Select {...args} onChange={(value: SelectableValue<string>) => { action('onChanged fired')(value); updateValue(value); }} /> ); }} </UseState> ); }; Basic.args = { placeholder: 'Choose...', options: options, width: 20, }; export const AsyncSelect: Story = (args) => { const [isLoading, setIsLoading] = useState<boolean>(args.loading); const [asyncValue, setAsyncValue] = useState<SelectableValue<any>>(); const loadAsyncOptions = useCallback((inputValue) => { return new Promise<Array<SelectableValue<string>>>((resolve) => { setTimeout(() => { setIsLoading(false); resolve(options.filter((option) => option.label && option.label.includes(inputValue))); }, 1000); }); }, []); return ( <AsyncSelectComponent {...args} value={asyncValue} isLoading={isLoading} loadOptions={loadAsyncOptions} onChange={(value) => { action('onChange')(value); setAsyncValue(value); }} /> ); }; AsyncSelect.args = { loading: true, defaultOptions: true, width: 20, };
packages/grafana-ui/src/components/Forms/Legacy/Select/Select.story.internal.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017834269965533167, 0.0001739554718369618, 0.0001705317699816078, 0.00017354547162540257, 0.0000019599215193011332 ]
{ "id": 6, "code_window": [ " });\n", " }, [config]);\n", "\n", " if (!plotCtx.plot || focusedPointIdx === null) {\n", " return null;\n", " }\n", "\n", " // GraphNG expects aligned data, let's take field 0 as x field. FTW\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || focusedPointIdx === null) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 76 }
import { StoreState } from 'app/types'; import { Store } from 'redux'; export let store: Store<StoreState>; export function setStore(newStore: Store<StoreState>) { store = newStore; } export function getState(): StoreState { if (!store || !store.getState) { return { templating: { variables: {}, }, } as StoreState; // used by tests } return store.getState(); } export function dispatch(action: any) { if (!store || !store.getState) { return; } return store.dispatch(action); }
public/app/store/store.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017597194528207183, 0.00017433486937079579, 0.00017126866441685706, 0.00017576399841345847, 0.000002169795834561228 ]
{ "id": 6, "code_window": [ " });\n", " }, [config]);\n", "\n", " if (!plotCtx.plot || focusedPointIdx === null) {\n", " return null;\n", " }\n", "\n", " // GraphNG expects aligned data, let's take field 0 as x field. FTW\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n", " if (!plotInstance || focusedPointIdx === null) {\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 76 }
<div class="edit-tab-content" ng-repeat="style in editor.panel.styles"> <div class="gf-form-group"> <h5 class="section-heading">Options</h5> <div class="gf-form-inline"> <div class="gf-form gf-form--grow"> <label class="gf-form-label width-8">Name pattern</label> <input type="text" placeholder="Name or regex" class="gf-form-input max-width-15" ng-model="style.pattern" bs-tooltip="'Specify regex using /my.*regex/ syntax'" bs-typeahead="editor.getColumnNames" ng-blur="editor.render()" data-min-length="0" data-items="100" ng-model-onblur data-placement="right" /> </div> </div> <div class="gf-form gf-form--grow" ng-if="style.type !== 'hidden'"> <label class="gf-form-label width-8">Column Header</label> <input type="text" class="gf-form-input max-width-15" ng-model="style.alias" ng-change="editor.render()" ng-model-onblur placeholder="Override header label" /> </div> <gf-form-switch class="gf-form" label-class="width-8" label="Render value as link" checked="style.link" on-change="editor.render()" ></gf-form-switch> </div> <div class="gf-form-group"> <h5 class="section-heading">Type</h5> <div class="gf-form gf-form--grow"> <label class="gf-form-label width-8">Type</label> <div class="gf-form-select-wrapper width-16"> <select class="gf-form-input" ng-model="style.type" ng-options="c.value as c.text for c in editor.columnTypes" ng-change="editor.render()" ></select> </div> </div> <div class="gf-form gf-form--grow" ng-if="style.type === 'date'"> <label class="gf-form-label width-8">Date Format</label> <gf-form-dropdown model="style.dateFormat" css-class="gf-form-input width-16" lookup-text="true" get-options="editor.dateFormats" on-change="editor.render()" allow-custom="true" > </gf-form-dropdown> </div> <div ng-if="style.type === 'string'"> <gf-form-switch class="gf-form" label-class="width-8" ng-if="style.type === 'string'" label="Sanitize HTML" checked="style.sanitize" on-change="editor.render()" ></gf-form-switch> </div> <div ng-if="style.type !== 'hidden'"> <div class="gf-form gf-form--grow"> <label class="gf-form-label width-8">Align</label> <gf-form-dropdown model="style.align" css-class="gf-form-input" lookup-text="true" get-options="editor.alignTypes" allow-custom="false" on-change="editor.render()" allow-custom="false" /> </div> </div> <div ng-if="style.type === 'string'"> <gf-form-switch class="gf-form" label-class="width-10" ng-if="style.type === 'string'" label="Preserve Formatting" checked="style.preserveFormat" on-change="editor.render()" ></gf-form-switch> </div> <div ng-if="style.type === 'number'"> <div class="gf-form"> <label class="gf-form-label width-8">Unit</label> <unit-picker onChange="editor.setUnitFormat(style)" value="style.unit" width="16"></unit-picker> </div> <div class="gf-form"> <label class="gf-form-label width-8">Decimals</label> <input type="number" class="gf-form-input width-4" data-placement="right" ng-model="style.decimals" ng-change="editor.render()" ng-model-onblur /> </div> </div> </div> <div class="gf-form-group" ng-if="style.type === 'string'"> <h5 class="section-heading">Value Mappings</h5> <div class="editor-row"> <div class="gf-form-group"> <div class="gf-form"> <span class="gf-form-label"> Type </span> <div class="gf-form-select-wrapper"> <select class="gf-form-input" ng-model="style.mappingType" ng-options="c.value as c.text for c in editor.mappingTypes" ng-change="editor.render()" ></select> </div> </div> <div class="gf-form-group" ng-if="style.mappingType==1"> <div class="gf-form" ng-repeat="map in style.valueMaps"> <span class="gf-form-label"> <icon name="'times'" ng-click="editor.removeValueMap(style, $index)"></icon> </span> <input type="text" class="gf-form-input max-width-6" ng-model="map.value" placeholder="Value" ng-blur="editor.render()" /> <label class="gf-form-label"> <icon name="'arrow-right'"></icon> </label> <input type="text" class="gf-form-input max-width-8" ng-model="map.text" placeholder="Text" ng-blur="editor.render()" /> </div> <div class="gf-form"> <label class="gf-form-label"> <a class="pointer" ng-click="editor.addValueMap(style)"><icon name="'plus'"></icon></a> </label> </div> </div> <div class="gf-form-group" ng-if="style.mappingType==2"> <div class="gf-form" ng-repeat="rangeMap in style.rangeMaps"> <span class="gf-form-label"> <icon name="'times'" ng-click="editor.removeRangeMap(style, $index)"></icon> </span> <span class="gf-form-label">From</span> <input type="text" ng-model="rangeMap.from" class="gf-form-input max-width-6" ng-blur="editor.render()" /> <span class="gf-form-label">To</span> <input type="text" ng-model="rangeMap.to" class="gf-form-input max-width-6" ng-blur="editor.render()" /> <span class="gf-form-label">Text</span> <input type="text" ng-model="rangeMap.text" class="gf-form-input max-width-8" ng-blur="editor.render()" /> </div> <div class="gf-form"> <label class="gf-form-label"> <a class="pointer" ng-click="editor.addRangeMap(style)"><icon name="'plus'"></icon></a> </label> </div> </div> </div> </div> </div> <div class="gf-form-group" ng-if="['number', 'string'].indexOf(style.type) !== -1"> <h5 class="section-heading">Thresholds</h5> <div class="gf-form"> <label class="gf-form-label width-8" >Thresholds <tip>Comma separated values</tip> </label> <input type="text" class="gf-form-input width-10" ng-model="style.thresholds" placeholder="50,80" ng-blur="editor.render()" array-join /> </div> <div class="gf-form"> <label class="gf-form-label width-8">Color Mode</label> <div class="gf-form-select-wrapper width-10"> <select class="gf-form-input" ng-model="style.colorMode" ng-options="c.value as c.text for c in editor.colorModes" ng-change="editor.render()" ></select> </div> </div> <div class="gf-form"> <label class="gf-form-label width-8">Colors</label> <span class="gf-form-label"> <color-picker color="style.colors[0]" onChange="editor.onColorChange(style, 0)"></color-picker> </span> <span class="gf-form-label"> <color-picker color="style.colors[1]" onChange="editor.onColorChange(style, 1)"></color-picker> </span> <span class="gf-form-label"> <color-picker color="style.colors[2]" onChange="editor.onColorChange(style, 2)"></color-picker> </span> <div class="gf-form-label"> <a class="pointer" ng-click="editor.invertColorOrder($index)">Invert</a> </div> </div> </div> <div class="section gf-form-group" ng-if="style.link"> <h5 class="section-heading">Link</h5> <div class="gf-form"> <label class="gf-form-label width-9"> Url <info-popover mode="right-normal"> <p>Specify an URL (relative or absolute)</p> <span> Use special variables to specify cell values: <br /> <em>${__cell}</em> refers to current cell value <br /> <em>${__cell_n}</em> refers to Nth column value in current row. Column indexes are started from 0. For instance, <em>${__cell_1}</em> refers to second column's value. <br /> <em>${__cell:raw}</em> disables all encoding. Useful if the value is a complete URL. By default values are URI encoded. </span> </info-popover> </label> <input type="text" class="gf-form-input width-29" ng-model="style.linkUrl" ng-blur="editor.render()" ng-model-onblur data-placement="right" /> </div> <div class="gf-form"> <label class="gf-form-label width-9"> Tooltip <info-popover mode="right-normal"> <p>Specify text for link tooltip.</p> <span> This title appears when user hovers pointer over the cell with link. Use the same variables as for URL. </span> </info-popover> </label> <input type="text" class="gf-form-input width-29" ng-model="style.linkTooltip" ng-blur="editor.render()" ng-model-onblur data-placement="right" /> </div> <gf-form-switch class="gf-form" label-class="width-9" label="Open in new tab" checked="style.linkTargetBlank" ></gf-form-switch> </div> <div class="clearfix"></div> <div class="gf-form-group"> <button class="btn btn-danger btn-small" ng-click="editor.removeColumnStyle(style)"> <icon name="'trash-alt'"></icon> Remove Rule </button> </div> <hr /> </div> <button class="btn btn-inverse" ng-click="editor.addColumnStyle()"> <icon name="'plus'"></icon>&nbsp;Add column style </button>
public/app/plugins/panel/table-old/column_options.html
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017518426466267556, 0.00017137767281383276, 0.00016574424807913601, 0.00017201562877744436, 0.000002671715719770873 ]
{ "id": 7, "code_window": [ "\n", " // when interacting with a point in single mode\n", " if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) {\n", " const field = otherProps.data.fields[focusedSeriesIdx];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 93 }
import React, { useContext } from 'react'; import uPlot from 'uplot'; interface PlotContextType { plot: uPlot | undefined; } /** * @alpha */ export const PlotContext = React.createContext<PlotContextType>({} as PlotContextType); // Exposes uPlot instance and bounding box of the entire canvas and plot area export const usePlotContext = (): PlotContextType => { return useContext<PlotContextType>(PlotContext); };
packages/grafana-ui/src/components/uPlot/context.ts
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00018182089843321592, 0.0001744297333061695, 0.0001670385681791231, 0.0001744297333061695, 0.000007391165127046406 ]
{ "id": 7, "code_window": [ "\n", " // when interacting with a point in single mode\n", " if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) {\n", " const field = otherProps.data.fields[focusedSeriesIdx];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 93 }
// +build integration package tests import ( "encoding/json" "errors" "fmt" "math/rand" "testing" "time" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/services/ngalert/store" "github.com/grafana/grafana/pkg/registry" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const baseIntervalSeconds = 10 func mockTimeNow() { var timeSeed int64 store.TimeNow = func() time.Time { fakeNow := time.Unix(timeSeed, 0).UTC() timeSeed++ return fakeNow } } func resetTimeNow() { store.TimeNow = time.Now } func TestCreatingAlertDefinition(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var customIntervalSeconds int64 = 120 testCases := []struct { desc string inputIntervalSeconds *int64 inputTitle string expectedError error expectedInterval int64 expectedUpdated time.Time }{ { desc: "should create successfully an alert definition with default interval", inputIntervalSeconds: nil, inputTitle: "a name", expectedInterval: dbstore.DefaultIntervalSeconds, expectedUpdated: time.Unix(0, 0).UTC(), }, { desc: "should create successfully an alert definition with custom interval", inputIntervalSeconds: &customIntervalSeconds, inputTitle: "another name", expectedInterval: customIntervalSeconds, expectedUpdated: time.Unix(1, 0).UTC(), }, { desc: "should fail to create an alert definition with too big name", inputIntervalSeconds: &customIntervalSeconds, inputTitle: getLongString(store.AlertDefinitionMaxTitleLength + 1), expectedError: errors.New(""), }, { desc: "should fail to create an alert definition with empty title", inputIntervalSeconds: &customIntervalSeconds, inputTitle: "", expectedError: fmt.Errorf("title is empty"), }, } for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { q := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: tc.inputTitle, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } if tc.inputIntervalSeconds != nil { q.IntervalSeconds = tc.inputIntervalSeconds } err := dbstore.SaveAlertDefinition(&q) switch { case tc.expectedError != nil: require.Error(t, err) default: require.NoError(t, err) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, tc.expectedInterval, q.Result.IntervalSeconds) assert.Equal(t, int64(1), q.Result.Version) } }) } } func TestCreatingConflictionAlertDefinition(t *testing.T) { t.Run("Should fail to create alert definition with conflicting org_id, title", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: "title", Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } err := dbstore.SaveAlertDefinition(&q) require.NoError(t, err) err = dbstore.SaveAlertDefinition(&q) require.Error(t, err) assert.True(t, dbstore.SQLStore.Dialect.IsUniqueConstraintViolation(err)) }) } func TestUpdatingAlertDefinition(t *testing.T) { t.Run("zero rows affected when updating unknown alert", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.UpdateAlertDefinitionCommand{ UID: "unknown", OrgID: 1, Title: "something completely different", Condition: "A", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 2 > 1" }`), RefID: "A", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(time.Duration(5) * time.Hour), To: models.Duration(time.Duration(3) * time.Hour), }, }, }, } err := dbstore.UpdateAlertDefinition(&q) require.NoError(t, err) }) t.Run("updating existing alert", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var initialInterval int64 = 120 alertDefinition := createTestAlertDefinition(t, dbstore, initialInterval) created := alertDefinition.Updated var customInterval int64 = 30 testCases := []struct { desc string inputOrgID int64 inputTitle string inputInterval *int64 expectedError error expectedIntervalSeconds int64 expectedUpdated time.Time expectedTitle string }{ { desc: "should not update previous interval if it's not provided", inputInterval: nil, inputOrgID: alertDefinition.OrgID, inputTitle: "something completely different", expectedIntervalSeconds: initialInterval, expectedUpdated: time.Unix(1, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should update interval if it's provided", inputInterval: &customInterval, inputOrgID: alertDefinition.OrgID, inputTitle: "something completely different", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(2, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should not update organisation if it's provided", inputInterval: &customInterval, inputOrgID: 0, inputTitle: "something completely different", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(3, 0).UTC(), expectedTitle: "something completely different", }, { desc: "should not update alert definition if the title it's too big", inputInterval: &customInterval, inputOrgID: 0, inputTitle: getLongString(store.AlertDefinitionMaxTitleLength + 1), expectedError: errors.New(""), }, { desc: "should not update alert definition title if the title is empty", inputInterval: &customInterval, inputOrgID: 0, inputTitle: "", expectedIntervalSeconds: customInterval, expectedUpdated: time.Unix(4, 0).UTC(), expectedTitle: "something completely different", }, } q := models.UpdateAlertDefinitionCommand{ UID: (*alertDefinition).UID, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, }, }, } lastUpdated := created previousAlertDefinition := alertDefinition for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { if tc.inputInterval != nil { q.IntervalSeconds = tc.inputInterval } if tc.inputOrgID != 0 { q.OrgID = tc.inputOrgID } q.Title = tc.inputTitle err := dbstore.UpdateAlertDefinition(&q) switch { case tc.expectedError != nil: require.Error(t, err) assert.Equal(t, previousAlertDefinition.Title, q.Result.Title) assert.Equal(t, previousAlertDefinition.Condition, q.Result.Condition) assert.Equal(t, len(previousAlertDefinition.Data), len(q.Result.Data)) assert.Equal(t, previousAlertDefinition.IntervalSeconds, q.Result.IntervalSeconds) assert.Equal(t, previousAlertDefinition.Updated, q.Result.Updated) assert.Equal(t, previousAlertDefinition.Version, q.Result.Version) assert.Equal(t, previousAlertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, previousAlertDefinition.UID, q.Result.UID) default: require.NoError(t, err) assert.Equal(t, previousAlertDefinition.ID, q.Result.ID) assert.Equal(t, previousAlertDefinition.UID, q.Result.UID) assert.True(t, q.Result.Updated.After(lastUpdated)) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, previousAlertDefinition.Version+1, q.Result.Version) assert.Equal(t, alertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, "something completely different", q.Result.Title) assert.Equal(t, "B", q.Result.Condition) assert.Equal(t, 1, len(q.Result.Data)) assert.Equal(t, tc.expectedUpdated, q.Result.Updated) assert.Equal(t, tc.expectedIntervalSeconds, q.Result.IntervalSeconds) assert.Equal(t, previousAlertDefinition.Version+1, q.Result.Version) assert.Equal(t, alertDefinition.OrgID, q.Result.OrgID) assert.Equal(t, alertDefinition.UID, q.Result.UID) previousAlertDefinition = q.Result } }) } }) } func TestUpdatingConflictingAlertDefinition(t *testing.T) { t.Run("should fail to update alert definition with reserved title", func(t *testing.T) { mockTimeNow() defer resetTimeNow() dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) var initialInterval int64 = 120 alertDef1 := createTestAlertDefinition(t, dbstore, initialInterval) alertDef2 := createTestAlertDefinition(t, dbstore, initialInterval) q := models.UpdateAlertDefinitionCommand{ UID: (*alertDef2).UID, Title: alertDef1.Title, Condition: "B", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 3 > 1" }`), RefID: "B", RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, }, }, } err := dbstore.UpdateAlertDefinition(&q) require.Error(t, err) assert.True(t, dbstore.SQLStore.Dialect.IsUniqueConstraintViolation(err)) }) } func TestDeletingAlertDefinition(t *testing.T) { t.Run("zero rows affected when deleting unknown alert", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) q := models.DeleteAlertDefinitionByUIDCommand{ UID: "unknown", OrgID: 1, } err := dbstore.DeleteAlertDefinitionByUID(&q) require.NoError(t, err) }) t.Run("deleting successfully existing alert", func(t *testing.T) { dbstore := setupTestEnv(t, baseIntervalSeconds) t.Cleanup(registry.ClearOverrides) alertDefinition := createTestAlertDefinition(t, dbstore, 60) q := models.DeleteAlertDefinitionByUIDCommand{ UID: (*alertDefinition).UID, OrgID: 1, } // save an instance for the definition saveCmd := &models.SaveAlertInstanceCommand{ DefinitionOrgID: alertDefinition.OrgID, DefinitionUID: alertDefinition.UID, State: models.InstanceStateFiring, Labels: models.InstanceLabels{"test": "testValue"}, } err := dbstore.SaveAlertInstance(saveCmd) require.NoError(t, err) listQuery := &models.ListAlertInstancesQuery{ DefinitionOrgID: alertDefinition.OrgID, DefinitionUID: alertDefinition.UID, } err = dbstore.ListAlertInstances(listQuery) require.NoError(t, err) require.Len(t, listQuery.Result, 1) err = dbstore.DeleteAlertDefinitionByUID(&q) require.NoError(t, err) // assert that alert instance is deleted err = dbstore.ListAlertInstances(listQuery) require.NoError(t, err) require.Len(t, listQuery.Result, 0) }) } func getLongString(n int) string { b := make([]rune, n) for i := range b { b[i] = 'a' } return string(b) } // createTestAlertDefinition creates a dummy alert definition to be used by the tests. func createTestAlertDefinition(t *testing.T, dbstore *store.DBstore, intervalSeconds int64) *models.AlertDefinition { cmd := models.SaveAlertDefinitionCommand{ OrgID: 1, Title: fmt.Sprintf("an alert definition %d", rand.Intn(1000)), Condition: "A", Data: []models.AlertQuery{ { Model: json.RawMessage(`{ "datasourceUid": "-100", "type":"math", "expression":"2 + 2 > 1" }`), RelativeTimeRange: models.RelativeTimeRange{ From: models.Duration(5 * time.Hour), To: models.Duration(3 * time.Hour), }, RefID: "A", }, }, IntervalSeconds: &intervalSeconds, } err := dbstore.SaveAlertDefinition(&cmd) require.NoError(t, err) t.Logf("alert definition: %v with interval: %d created", cmd.Result.GetKey(), intervalSeconds) return cmd.Result }
pkg/services/ngalert/tests/database_test.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017880277300719172, 0.0001758356229402125, 0.00016648313612677157, 0.00017650381778366864, 0.000002288408040840295 ]
{ "id": 7, "code_window": [ "\n", " // when interacting with a point in single mode\n", " if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) {\n", " const field = otherProps.data.fields[focusedSeriesIdx];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 93 }
@mixin hover { @if $enable-hover-media-query { // See Media Queries Level 4: http://drafts.csswg.org/mediaqueries/#hover // Currently shimmed by https://github.com/twbs/mq4-hover-shim @media (hover: hover) { &:hover { @content; } } } @else { &:hover { @content; } } } @mixin hover-focus { @if $enable-hover-media-query { &:focus { @content; } @include hover { @content; } } @else { &:focus, &:hover { @content; } } } @mixin plain-hover-focus { @if $enable-hover-media-query { &, &:focus { @content; } @include hover { @content; } } @else { &, &:focus, &:hover { @content; } } } @mixin hover-focus-active { @if $enable-hover-media-query { &:focus, &:active { @content; } @include hover { @content; } } @else { &:focus, &:active, &:hover { @content; } } }
public/sass/mixins/_hover.scss
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017897505313158035, 0.00017793291772250086, 0.00017615847173146904, 0.00017823443340603262, 8.846398031892022e-7 ]
{ "id": 7, "code_window": [ "\n", " // when interacting with a point in single mode\n", " if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) {\n", " const field = otherProps.data.fields[focusedSeriesIdx];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 93 }
import React from 'react'; import { withCenteredStory } from '../../utils/storybook/withCenteredStory'; import { FileUpload } from '@grafana/ui'; import mdx from './FileUpload.mdx'; import { useSize } from '../../utils/storybook/useSize'; import { ComponentSize } from '../../types/size'; export default { title: 'Forms/FileUpload', component: FileUpload, decorators: [withCenteredStory], parameters: { docs: { page: mdx, }, }, }; export const Single = () => { const size = useSize(); return ( <FileUpload size={size as ComponentSize} onFileUpload={({ currentTarget }) => console.log('file', currentTarget?.files && currentTarget.files[0])} /> ); };
packages/grafana-ui/src/components/FileUpload/FileUpload.story.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00021603118511848152, 0.00019207404693588614, 0.0001797484146663919, 0.00018044251191895455, 0.000016942631191341206 ]
{ "id": 8, "code_window": [ "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n", " const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]);\n", "\n", " tooltip = (\n", " <SeriesTable\n", " series={[\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const value = fieldFmt(plotInstance.data[focusedSeriesIdx!][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.9982061386108398, 0.32600128650665283, 0.00016627849254291505, 0.0021591975819319487, 0.44819390773773193 ]
{ "id": 8, "code_window": [ "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n", " const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]);\n", "\n", " tooltip = (\n", " <SeriesTable\n", " series={[\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const value = fieldFmt(plotInstance.data[focusedSeriesIdx!][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`LokiExploreQueryEditor should render component 1`] = ` <LokiQueryField ExtraFieldElement={ <LokiOptionFields lineLimitValue="0" onChange={[MockFunction]} onRunQuery={[MockFunction]} query={ Object { "expr": "", "maxLines": 0, "refId": "A", } } queryType="range" /> } absoluteRange={ Object { "from": 1577836800000, "to": 1577923200000, } } data={ Object { "request": Object { "app": "Grafana", "dashboardId": 1, "interval": "1s", "intervalMs": 1000, "panelId": 1, "range": Object { "from": "2020-01-01T00:00:00.000Z", "raw": Object { "from": "2020-01-01T00:00:00.000Z", "to": "2020-01-02T00:00:00.000Z", }, "to": "2020-01-02T00:00:00.000Z", }, "requestId": "1", "scopedVars": Object {}, "startTime": 0, "targets": Array [], "timezone": "GMT", }, "series": Array [], "state": "NotStarted", "timeRange": Object { "from": "2020-01-01T00:00:00.000Z", "raw": Object { "from": "2020-01-01T00:00:00.000Z", "to": "2020-01-02T00:00:00.000Z", }, "to": "2020-01-02T00:00:00.000Z", }, } } datasource={ Object { "getTimeRangeParams": [Function], "languageProvider": LokiLanguageProvider { "cleanText": [Function], "datasource": [Circular], "fetchSeries": [Function], "fetchSeriesLabels": [Function], "getBeginningCompletionItems": [Function], "getPipeCompletionItem": [Function], "getTermCompletionItems": [Function], "labelKeys": Array [], "labelsCache": LRUCache { Symbol(max): 10, Symbol(lengthCalculator): [Function], Symbol(allowStale): false, Symbol(maxAge): 0, Symbol(dispose): undefined, Symbol(noDisposeOnSet): false, Symbol(updateAgeOnGet): false, Symbol(cache): Map {}, Symbol(lruList): Yallist { "head": null, "length": 0, "tail": null, }, Symbol(length): 0, }, "logLabelFetchTs": 0, "lookupsDisabled": false, "request": [Function], "seriesCache": LRUCache { Symbol(max): 10, Symbol(lengthCalculator): [Function], Symbol(allowStale): false, Symbol(maxAge): 0, Symbol(dispose): undefined, Symbol(noDisposeOnSet): false, Symbol(updateAgeOnGet): false, Symbol(cache): Map {}, Symbol(lruList): Yallist { "head": null, "length": 0, "tail": null, }, Symbol(length): 0, }, "start": [Function], "started": false, }, "metadataRequest": [Function], } } history={Array []} onBlur={[Function]} onChange={[MockFunction]} onRunQuery={[MockFunction]} query={ Object { "expr": "", "maxLines": 0, "refId": "A", } } /> `;
public/app/plugins/datasource/loki/components/__snapshots__/LokiExploreQueryEditor.test.tsx.snap
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017922694678418338, 0.00017645340994931757, 0.00017329296679235995, 0.00017698039300739765, 0.0000017373430409861612 ]
{ "id": 8, "code_window": [ "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n", " const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]);\n", "\n", " tooltip = (\n", " <SeriesTable\n", " series={[\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const value = fieldFmt(plotInstance.data[focusedSeriesIdx!][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import angular from 'angular'; import coreModule from '../core_module'; export class JsonEditorCtrl { /** @ngInject */ constructor($scope: any) { $scope.json = angular.toJson($scope.model.object, true); $scope.canUpdate = $scope.model.updateHandler !== void 0 && $scope.model.canUpdate; $scope.canCopy = $scope.model.enableCopy; $scope.update = () => { const newObject = angular.fromJson($scope.json); $scope.model.updateHandler(newObject, $scope.model.object); }; $scope.getContentForClipboard = () => $scope.json; } } coreModule.controller('JsonEditorCtrl', JsonEditorCtrl);
public/app/core/controllers/json_editor_ctrl.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00018028962949756533, 0.00017881813982967287, 0.0001776179124135524, 0.00017854689212981611, 0.0000011074599797211704 ]
{ "id": 8, "code_window": [ "\n", " const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme });\n", " const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]);\n", "\n", " tooltip = (\n", " <SeriesTable\n", " series={[\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const value = fieldFmt(plotInstance.data[focusedSeriesIdx!][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package parse import ( "fmt" "testing" ) // Make the types prettyprint. var itemName = map[itemType]string{ itemError: "error", itemEOF: "EOF", itemNot: "!", itemAnd: "&&", itemOr: "||", itemGreater: ">", itemLess: "<", itemGreaterEq: ">=", itemLessEq: "<=", itemEq: "==", itemNotEq: "!=", itemPlus: "+", itemMinus: "-", itemMult: "*", itemDiv: "/", itemMod: "%", itemNumber: "number", itemComma: ",", itemLeftParen: "(", itemRightParen: ")", itemString: "string", itemFunc: "func", } func (i itemType) String() string { s := itemName[i] if s == "" { return fmt.Sprintf("item%d", int(i)) } return s } type lexTest struct { name string input string items []item } var ( tEOF = item{itemEOF, 0, ""} tLt = item{itemLess, 0, "<"} tGt = item{itemGreater, 0, ">"} tOr = item{itemOr, 0, "||"} tNot = item{itemNot, 0, "!"} tAnd = item{itemAnd, 0, "&&"} tLtEq = item{itemLessEq, 0, "<="} tGtEq = item{itemGreaterEq, 0, ">="} tNotEq = item{itemNotEq, 0, "!="} tEq = item{itemEq, 0, "=="} tPlus = item{itemPlus, 0, "+"} tMinus = item{itemMinus, 0, "-"} tMult = item{itemMult, 0, "*"} tDiv = item{itemDiv, 0, "/"} tMod = item{itemMod, 0, "%"} ) var lexTests = []lexTest{ {"empty", "", []item{tEOF}}, {"spaces", " \t\n", []item{tEOF}}, {"text", `"now is the time"`, []item{{itemString, 0, `"now is the time"`}, tEOF}}, {"operators", "! && || < > <= >= == != + - * / %", []item{ tNot, tAnd, tOr, tLt, tGt, tLtEq, tGtEq, tEq, tNotEq, tPlus, tMinus, tMult, tDiv, tMod, tEOF, }}, {"numbers", "1 02 0x14 7.2 1e3 1.2e-4", []item{ {itemNumber, 0, "1"}, {itemNumber, 0, "02"}, {itemNumber, 0, "0x14"}, {itemNumber, 0, "7.2"}, {itemNumber, 0, "1e3"}, {itemNumber, 0, "1.2e-4"}, tEOF, }}, {"curly brace var", "${My Var}", []item{ {itemVar, 0, "${My Var}"}, tEOF, }}, {"curly brace var plus 1", "${My Var} + 1", []item{ {itemVar, 0, "${My Var}"}, tPlus, {itemNumber, 0, "1"}, tEOF, }}, {"number plus var", "1 + $A", []item{ {itemNumber, 0, "1"}, tPlus, {itemVar, 0, "$A"}, tEOF, }}, // errors {"unclosed quote", "\"", []item{ {itemError, 0, "unterminated string"}, }}, {"single quote", "'single quote is invalid'", []item{ {itemError, 0, "invalid character: '"}, }}, {"invalid var", "$", []item{ {itemError, 0, "incomplete variable"}, }}, {"invalid curly var", "${adf sd", []item{ {itemError, 0, "unterminated variable missing closing }"}, }}, } // collect gathers the emitted items into a slice. func collect(t *lexTest) (items []item) { l := lex(t.input) for { item := l.nextItem() items = append(items, item) if item.typ == itemEOF || item.typ == itemError { break } } return } func equal(i1, i2 []item, checkPos bool) bool { if len(i1) != len(i2) { return false } for k := range i1 { if i1[k].typ != i2[k].typ { return false } if i1[k].val != i2[k].val { return false } if checkPos && i1[k].pos != i2[k].pos { return false } } return true } func TestLex(t *testing.T) { for i, test := range lexTests { items := collect(&lexTests[i]) if !equal(items, test.items, false) { t.Errorf("%s: got\n\t%+v\nexpected\n\t%v", test.name, items, test.items) } } }
pkg/expr/mathexp/parse/lex_test.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00018090868252329528, 0.0001772739051375538, 0.0001705548638710752, 0.00017701176693663, 0.000002780079739750363 ]
{ "id": 9, "code_window": [ "\n", " if (mode === TooltipDisplayMode.Multi) {\n", " let series: SeriesTableRowProps[] = [];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " for (let i = 0; i < plotSeries.length; i++) {\n", " const frame = otherProps.data;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 115 }
import React, { useContext } from 'react'; import uPlot from 'uplot'; interface PlotContextType { plot: uPlot | undefined; } /** * @alpha */ export const PlotContext = React.createContext<PlotContextType>({} as PlotContextType); // Exposes uPlot instance and bounding box of the entire canvas and plot area export const usePlotContext = (): PlotContextType => { return useContext<PlotContextType>(PlotContext); };
packages/grafana-ui/src/components/uPlot/context.ts
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00025075057055801153, 0.0002090593334287405, 0.0001673681108513847, 0.0002090593334287405, 0.000041691229853313416 ]
{ "id": 9, "code_window": [ "\n", " if (mode === TooltipDisplayMode.Multi) {\n", " let series: SeriesTableRowProps[] = [];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " for (let i = 0; i < plotSeries.length; i++) {\n", " const frame = otherProps.data;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 115 }
// Code based on Material UI // The MIT License (MIT) // Copyright (c) 2014 Call-Em-All // Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves // to learn the context in which each easing should be used. const easing = { // This is the most common easing curve. easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)', // Objects enter the screen at full velocity from off-screen and // slowly decelerate to a resting point. easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)', // Objects leave the screen at full velocity. They do not decelerate when off-screen. easeIn: 'cubic-bezier(0.4, 0, 1, 1)', // The sharp curve is used by objects that may return to the screen at any time. sharp: 'cubic-bezier(0.4, 0, 0.6, 1)', }; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations // to learn when use what timing const duration = { shortest: 150, shorter: 200, short: 250, // most basic recommended timing standard: 300, // this is to be used in complex animations complex: 375, // recommended when something is entering screen enteringScreen: 225, // recommended when something is leaving screen leavingScreen: 195, }; /** @alpha */ export interface CreateTransitionOptions { duration?: number | string; easing?: string; delay?: number | string; } /** @alpha */ export function create(props: string | string[] = ['all'], options: CreateTransitionOptions = {}) { const { duration: durationOption = duration.standard, easing: easingOption = easing.easeInOut, delay = 0 } = options; return (Array.isArray(props) ? props : [props]) .map( (animatedProp) => `${animatedProp} ${ typeof durationOption === 'string' ? durationOption : formatMs(durationOption) } ${easingOption} ${typeof delay === 'string' ? delay : formatMs(delay)}` ) .join(','); } export function getAutoHeightDuration(height: number) { if (!height) { return 0; } const constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10 return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10); } function formatMs(milliseconds: number) { return `${Math.round(milliseconds)}ms`; } /** @alpha */ export interface ThemeTransitions { create: typeof create; duration: typeof duration; easing: typeof easing; getAutoHeightDuration: typeof getAutoHeightDuration; } /** @internal */ export function createTransitions(): ThemeTransitions { return { create, duration, easing, getAutoHeightDuration, }; }
packages/grafana-data/src/themes/createTransitions.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017824461974669248, 0.00017473990737926215, 0.00017020849918480963, 0.00017564205336384475, 0.000002629444907142897 ]
{ "id": 9, "code_window": [ "\n", " if (mode === TooltipDisplayMode.Multi) {\n", " let series: SeriesTableRowProps[] = [];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " for (let i = 0; i < plotSeries.length; i++) {\n", " const frame = otherProps.data;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 115 }
import React from 'react'; import { DataTransformerID, SelectableValue, standardTransformers, TransformerRegistryItem, TransformerUIProps, } from '@grafana/data'; import { Select } from '@grafana/ui'; import { LabelsToFieldsOptions } from '@grafana/data/src/transformations/transformers/labelsToFields'; export const LabelsAsFieldsTransformerEditor: React.FC<TransformerUIProps<LabelsToFieldsOptions>> = ({ input, options, onChange, }) => { let labelNames: Array<SelectableValue<string>> = []; let uniqueLabels: Record<string, boolean> = {}; for (const frame of input) { for (const field of frame.fields) { if (!field.labels) { continue; } for (const labelName of Object.keys(field.labels)) { if (!uniqueLabels[labelName]) { labelNames.push({ value: labelName, label: labelName }); uniqueLabels[labelName] = true; } } } } const onValueLabelChange = (value: SelectableValue<string> | null) => { onChange({ valueLabel: value?.value }); }; return ( <div className="gf-form-inline"> <div className="gf-form"> <div className="gf-form-label width-8">Value field name</div> <Select isClearable={true} allowCustomValue={false} placeholder="(Optional) Select label" options={labelNames} className="min-width-18 gf-form-spacing" value={options?.valueLabel} onChange={onValueLabelChange} /> </div> </div> ); }; export const labelsToFieldsTransformerRegistryItem: TransformerRegistryItem<LabelsToFieldsOptions> = { id: DataTransformerID.labelsToFields, editor: LabelsAsFieldsTransformerEditor, transformation: standardTransformers.labelsToFieldsTransformer, name: 'Labels to fields', description: `Groups series by time and return labels or tags as fields. Useful for showing time series with labels in a table where each label key becomes a separate column`, };
public/app/core/components/TransformersUI/LabelsToFieldsTransformerEditor.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.003148820251226425, 0.0005965615855529904, 0.00016349930956494063, 0.00017468103033024818, 0.0010419622994959354 ]
{ "id": 9, "code_window": [ "\n", " if (mode === TooltipDisplayMode.Multi) {\n", " let series: SeriesTableRowProps[] = [];\n", " const plotSeries = plotCtx.plot.series;\n", "\n", " for (let i = 0; i < plotSeries.length; i++) {\n", " const frame = otherProps.data;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotSeries = plotInstance.series;\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 115 }
export { AnnotationSettingsEdit } from './AnnotationSettingsEdit'; export { AnnotationSettingsList } from './AnnotationSettingsList';
public/app/features/dashboard/components/AnnotationSettings/index.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017845514230430126, 0.00017845514230430126, 0.00017845514230430126, 0.00017845514230430126, 0 ]
{ "id": 10, "code_window": [ " field.config.custom?.hideFrom?.tooltip\n", " ) {\n", " continue;\n", " }\n", "\n", " const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]);\n", "\n", " series.push({\n", " // TODO: align with uPlot typings\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const value = field.display!(plotInstance.data[i][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 129 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.9979361295700073, 0.18964743614196777, 0.00016920006601139903, 0.001133742043748498, 0.3878958821296692 ]
{ "id": 10, "code_window": [ " field.config.custom?.hideFrom?.tooltip\n", " ) {\n", " continue;\n", " }\n", "\n", " const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]);\n", "\n", " series.push({\n", " // TODO: align with uPlot typings\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const value = field.display!(plotInstance.data[i][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 129 }
import uPlot, { Scale, Range } from 'uplot'; import { PlotConfigBuilder } from '../types'; import { ScaleDistribution, ScaleOrientation, ScaleDirection } from '../config'; export interface ScaleProps { scaleKey: string; isTime?: boolean; min?: number | null; max?: number | null; softMin?: number | null; softMax?: number | null; range?: Scale.Range; distribution?: ScaleDistribution; orientation: ScaleOrientation; direction: ScaleDirection; log?: number; } export class UPlotScaleBuilder extends PlotConfigBuilder<ScaleProps, Scale> { merge(props: ScaleProps) { this.props.min = optMinMax('min', this.props.min, props.min); this.props.max = optMinMax('max', this.props.max, props.max); } getConfig() { const { isTime, scaleKey, min: hardMin, max: hardMax, softMin, softMax, range, direction, orientation, } = this.props; const distribution = !isTime ? { distr: this.props.distribution === ScaleDistribution.Logarithmic ? 3 : this.props.distribution === ScaleDistribution.Ordinal ? 2 : 1, log: this.props.distribution === ScaleDistribution.Logarithmic ? this.props.log || 2 : undefined, } : {}; // uPlot's default ranging config for both min & max is {pad: 0.1, hard: null, soft: 0, mode: 3} let softMinMode: Range.SoftMode = softMin == null ? 3 : softMin === 0 ? 1 : 2; let softMaxMode: Range.SoftMode = softMax == null ? 3 : softMax === 0 ? 1 : 2; const rangeConfig: Range.Config = { min: { pad: 0.1, hard: hardMin ?? -Infinity, soft: softMin || 0, mode: softMinMode, }, max: { pad: 0.1, hard: hardMax ?? Infinity, soft: softMax || 0, mode: softMaxMode, }, }; let hardMinOnly = softMin == null && hardMin != null; let hardMaxOnly = softMax == null && hardMax != null; // uPlot range function const rangeFn = (u: uPlot, dataMin: number, dataMax: number, scaleKey: string) => { const scale = u.scales[scaleKey]; let minMax = [dataMin, dataMax]; if (scale.distr === 1 || scale.distr === 2) { // @ts-ignore here we may use hardMin / hardMax to make sure any extra padding is computed from a more accurate delta minMax = uPlot.rangeNum(hardMinOnly ? hardMin : dataMin, hardMaxOnly ? hardMax : dataMax, rangeConfig); } else if (scale.distr === 3) { minMax = uPlot.rangeLog(dataMin, dataMax, scale.log ?? 10, true); } // if all we got were hard limits, treat them as static min/max if (hardMinOnly) { minMax[0] = hardMin!; } if (hardMaxOnly) { minMax[1] = hardMax!; } return minMax; }; return { [scaleKey]: { time: isTime, auto: !isTime && !(hardMinOnly && hardMaxOnly), range: range ?? rangeFn, dir: direction, ori: orientation, ...distribution, }, }; } } export function optMinMax(minmax: 'min' | 'max', a?: number | null, b?: number | null): undefined | number | null { const hasA = !(a === undefined || a === null); const hasB = !(b === undefined || b === null); if (hasA) { if (!hasB) { return a; } if (minmax === 'min') { return a! < b! ? a : b; } return a! > b! ? a : b; } return b; }
packages/grafana-ui/src/components/uPlot/config/UPlotScaleBuilder.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00022320302377920598, 0.0001762095489539206, 0.0001645049633225426, 0.00017176124674733728, 0.000014825141988694668 ]
{ "id": 10, "code_window": [ " field.config.custom?.hideFrom?.tooltip\n", " ) {\n", " continue;\n", " }\n", "\n", " const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]);\n", "\n", " series.push({\n", " // TODO: align with uPlot typings\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const value = field.display!(plotInstance.data[i][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 129 }
package util import ( "testing" "github.com/stretchr/testify/assert" ) func TestSplitHostPortDefault_Valid(t *testing.T) { tests := []struct { input string defaultHost string defaultPort string host string port string }{ {input: "192.168.0.140:456", defaultHost: "", defaultPort: "", host: "192.168.0.140", port: "456"}, {input: "192.168.0.140", defaultHost: "", defaultPort: "123", host: "192.168.0.140", port: "123"}, {input: "[::1]:456", defaultHost: "", defaultPort: "", host: "::1", port: "456"}, {input: "[::1]", defaultHost: "", defaultPort: "123", host: "::1", port: "123"}, {input: ":456", defaultHost: "1.2.3.4", defaultPort: "", host: "1.2.3.4", port: "456"}, {input: "xyz.rds.amazonaws.com", defaultHost: "", defaultPort: "123", host: "xyz.rds.amazonaws.com", port: "123"}, {input: "xyz.rds.amazonaws.com:123", defaultHost: "", defaultPort: "", host: "xyz.rds.amazonaws.com", port: "123"}, {input: "", defaultHost: "localhost", defaultPort: "1433", host: "localhost", port: "1433"}, } for _, testcase := range tests { addr, err := SplitHostPortDefault(testcase.input, testcase.defaultHost, testcase.defaultPort) assert.NoError(t, err) assert.Equal(t, testcase.host, addr.Host) assert.Equal(t, testcase.port, addr.Port) } }
pkg/util/ip_address_test.go
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017678120639175177, 0.0001751776144374162, 0.00017277670849580318, 0.00017557627870701253, 0.0000015174374539128621 ]
{ "id": 10, "code_window": [ " field.config.custom?.hideFrom?.tooltip\n", " ) {\n", " continue;\n", " }\n", "\n", " const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]);\n", "\n", " series.push({\n", " // TODO: align with uPlot typings\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const value = field.display!(plotInstance.data[i][focusedPointIdx]);\n" ], "file_path": "packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx", "type": "replace", "edit_start_line_idx": 129 }
import { sleep, check, group } from 'k6'; import { createClient, createBasicAuthClient } from './modules/client.js'; import { createTestOrgIfNotExists, createTestdataDatasourceIfNotExists } from './modules/util.js'; export let options = { noCookiesReset: true, }; let endpoint = __ENV.URL || 'http://localhost:3000'; const slowQuery = __ENV.SLOW_QUERY && __ENV.SLOW_QUERY.length > 0 ? parseInt(__ENV.SLOW_QUERY, 10) : 5; const client = createClient(endpoint); export const setup = () => { const basicAuthClient = createBasicAuthClient(endpoint, 'admin', 'admin'); const orgId = createTestOrgIfNotExists(basicAuthClient); basicAuthClient.withOrgId(orgId); const datasourceId = createTestdataDatasourceIfNotExists(basicAuthClient); return { orgId, datasourceId, }; }; export default (data) => { client.withOrgId(data.orgId); group(`user auth token slow test (queries between 1 and ${slowQuery} seconds)`, () => { if (__ITER === 0) { group('user authenticates through ui with username and password', () => { let res = client.ui.login('admin', 'admin'); check(res, { 'response status is 200': (r) => r.status === 200, "response has cookie 'grafana_session' with 32 characters": (r) => r.cookies.grafana_session[0].value.length === 32, }); }); } if (__ITER !== 0) { group('batch tsdb requests', () => { const batchCount = 20; const requests = []; const payload = { from: '1547765247624', to: '1547768847624', queries: [ { refId: 'A', scenarioId: 'slow_query', stringInput: `${Math.floor(Math.random() * slowQuery) + 1}s`, intervalMs: 10000, maxDataPoints: 433, datasourceId: data.datasourceId, }, ], }; requests.push({ method: 'GET', url: '/api/annotations?dashboardId=2074&from=1548078832772&to=1548082432772' }); for (let n = 0; n < batchCount; n++) { requests.push({ method: 'POST', url: '/api/tsdb/query', body: payload }); } let responses = client.batch(requests); for (let n = 0; n < batchCount; n++) { check(responses[n], { 'response status is 200': (r) => r.status === 200, }); } }); } }); sleep(5); }; export const teardown = (data) => {};
devenv/docker/loadtest/auth_token_slow_test.js
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0001780492893885821, 0.0001732850942062214, 0.00016749519272707403, 0.0001732667733449489, 0.0000028991969429625897 ]
{ "id": 11, "code_window": [ " const mapAnnotationToXYCoords = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n", " const annotation = view.get(index);\n", " const plotInstance = plotCtx.plot;\n", " if (!annotation.time || !plotInstance) {\n", " return undefined;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 86 }
import { usePlotContext } from '../context'; import React from 'react'; import { css } from '@emotion/css'; interface XYCanvasProps {} /** * Renders absolutely positioned element on top of the uPlot's plotting area (axes are not included!). * Useful when you want to render some overlay with canvas-independent elements on top of the plot. */ export const XYCanvas: React.FC<XYCanvasProps> = ({ children }) => { const plotCtx = usePlotContext(); const plotInstance = plotCtx.plot; if (!plotInstance) { return null; } return ( <div className={css` position: absolute; overflow: visible; left: ${plotInstance.bbox.left / window.devicePixelRatio}px; top: ${plotInstance.bbox.top / window.devicePixelRatio}px; `} > {children} </div> ); };
packages/grafana-ui/src/components/uPlot/geometries/XYCanvas.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.9894243478775024, 0.2619842290878296, 0.00016391873941756785, 0.02917434275150299, 0.4206548035144806 ]
{ "id": 11, "code_window": [ " const mapAnnotationToXYCoords = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n", " const annotation = view.get(index);\n", " const plotInstance = plotCtx.plot;\n", " if (!annotation.time || !plotInstance) {\n", " return undefined;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 86 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve"> <style type="text/css"> .st0{fill:#52545c;} </style> <path class="st0" d="M63.2,32l-7-7V11.8c0-2.9-2.4-5.3-5.3-5.3l0,0c-2.9,0-5.3,2.4-5.3,5.3v2.6L34,2.8c-1.1-1.1-2.8-1.1-3.9,0 L0.8,32c-1.7,1.7-0.5,4.7,2,4.7h5l0,0v7.6v14.8c0,1.5,1.2,2.8,2.8,2.8h13.2V44.4h16.5V62h13.2c1.5,0,2.8-1.2,2.8-2.8V36.8l0,0l0,0h5 C63.7,36.8,64.9,33.8,63.2,32z"/> </svg>
public/img/icons_light_theme/icon_home.svg
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017535990627948195, 0.00017014509649015963, 0.00016493030125275254, 0.00017014509649015963, 0.0000052148025133647025 ]
{ "id": 11, "code_window": [ " const mapAnnotationToXYCoords = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n", " const annotation = view.get(index);\n", " const plotInstance = plotCtx.plot;\n", " if (!annotation.time || !plotInstance) {\n", " return undefined;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 86 }
+++ title = "Release notes for Grafana 7.5.0-beta2" [_build] list = false +++ <!-- Auto generated by update changelog github action --> # Release notes for Grafana 7.5.0-beta2 ### Features and enhancements * **CloudWatch**: Add support for EC2 IAM role. [#31804](https://github.com/grafana/grafana/pull/31804), [@sunker](https://github.com/sunker) * **CloudWatch**: Consume the grafana/aws-sdk. [#31807](https://github.com/grafana/grafana/pull/31807), [@sunker](https://github.com/sunker) * **CloudWatch**: Restrict auth provider and assume role usage according to Grafana configuration. [#31805](https://github.com/grafana/grafana/pull/31805), [@sunker](https://github.com/sunker) * **Cloudwatch**: ListMetrics API page limit. [#31788](https://github.com/grafana/grafana/pull/31788), [@sunker](https://github.com/sunker) * **Cloudwatch**: use shared library for aws auth. [#29550](https://github.com/grafana/grafana/pull/29550), [@ryantxu](https://github.com/ryantxu) * **DataLinks**: Bring back single click links for Stat, Gauge and BarGauge panel. [#31692](https://github.com/grafana/grafana/pull/31692), [@dprokop](https://github.com/dprokop) * **Docker**: Support pre-installed plugins from other sources in custom Dockerfiles. [#31234](https://github.com/grafana/grafana/pull/31234), [@sgnsys3](https://github.com/sgnsys3) * **Elasticseach**: Add support for histogram fields. [#29079](https://github.com/grafana/grafana/pull/29079), [@simianhacker](https://github.com/simianhacker) * **Exemplars**: Always query exemplars. [#31673](https://github.com/grafana/grafana/pull/31673), [@zoltanbedi](https://github.com/zoltanbedi) * **Explore**: Support full inspect drawer. [#32005](https://github.com/grafana/grafana/pull/32005), [@ivanahuckova](https://github.com/ivanahuckova) * **HttpServer**: Make read timeout configurable but disabled by default. [#31575](https://github.com/grafana/grafana/pull/31575), [@bergquist](https://github.com/bergquist) * **SQLStore**: Close session in withDbSession. [#31775](https://github.com/grafana/grafana/pull/31775), [@aknuds1](https://github.com/aknuds1) * **Templating**: Use dashboard timerange when variables are set to refresh 'On Dashboard Load'. [#31721](https://github.com/grafana/grafana/pull/31721), [@Elfo404](https://github.com/Elfo404) * **Tempo**: Convert to backend data source. [#31618](https://github.com/grafana/grafana/pull/31618), [@zoltanbedi](https://github.com/zoltanbedi) ### Bug fixes * **Admin**: Keeps expired api keys visible in table after delete. [#31636](https://github.com/grafana/grafana/pull/31636), [@hugohaggmark](https://github.com/hugohaggmark) * **Data proxy**: Fix encoded characters in URL path should be proxied as encoded. [#30597](https://github.com/grafana/grafana/pull/30597), [@marefr](https://github.com/marefr) * **Explore/Logs**: Fix escaping in ANSI logs. [#31731](https://github.com/grafana/grafana/pull/31731), [@ivanahuckova](https://github.com/ivanahuckova) * **GraphNG**: Fix tooltip series color for multi data frame scenario. [#32098](https://github.com/grafana/grafana/pull/32098), [@dprokop](https://github.com/dprokop) * **GraphNG**: Make sure data set and config are in sync when initializing and re-initializing uPlot. [#32106](https://github.com/grafana/grafana/pull/32106), [@dprokop](https://github.com/dprokop) * **Loki**: Fix autocomplete when re-editing Loki label values. [#31828](https://github.com/grafana/grafana/pull/31828), [@ivanahuckova](https://github.com/ivanahuckova) * **MixedDataSource**: Name is updated when data source variables change. [#32090](https://github.com/grafana/grafana/pull/32090), [@hugohaggmark](https://github.com/hugohaggmark) * **PanelInspect**: Interpolates variables in CSV file name. [#31936](https://github.com/grafana/grafana/pull/31936), [@hugohaggmark](https://github.com/hugohaggmark) * **ReduceTransform**: Include series with numeric string names. [#31763](https://github.com/grafana/grafana/pull/31763), [@hugohaggmark](https://github.com/hugohaggmark) * **Snapshots**: Fix usage of sign in link from the snapshot page. [#31986](https://github.com/grafana/grafana/pull/31986), [@marefr](https://github.com/marefr) * **TimePicker**: Fixes hidden time picker shown in kiosk TV mode. [#32062](https://github.com/grafana/grafana/pull/32062), [@torkelo](https://github.com/torkelo) * **ValueMappings**: Fixes value 0 not being mapped. [#31924](https://github.com/grafana/grafana/pull/31924), [@Willena](https://github.com/Willena) * **Variables**: Fixes filtering in picker with null items. [#31979](https://github.com/grafana/grafana/pull/31979), [@hugohaggmark](https://github.com/hugohaggmark) * **Variables**: Improves inspection performance and unknown filtering. [#31811](https://github.com/grafana/grafana/pull/31811), [@hugohaggmark](https://github.com/hugohaggmark) ### Plugin development fixes & changes * **Auth**: Allow soft token revocation. [#31601](https://github.com/grafana/grafana/pull/31601), [@joanlopez](https://github.com/joanlopez)
docs/sources/release-notes/release-notes-7-5-0-beta2.md
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0001781995961209759, 0.00017101802222896367, 0.0001658025721553713, 0.00016963591042440385, 0.000004585315309668658 ]
{ "id": 11, "code_window": [ " const mapAnnotationToXYCoords = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n", " const annotation = view.get(index);\n", " const plotInstance = plotCtx.plot;\n", " if (!annotation.time || !plotInstance) {\n", " return undefined;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 86 }
import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks'; import { Pagination } from './Pagination'; <Meta title="MDX|Pagination" component={Pagination} /> # Pagination Component used for rendering a page selector below paginated content. ### Usage ```tsx <div> <div> Page 1 content </div> <Pagination currentPage={1} numberOfPages={5} onNavigate={() => fetchPage(2)} /> </div> ``` <Props of={Pagination} />
packages/grafana-ui/src/components/Pagination/Pagination.mdx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017589512572158128, 0.00017538962129037827, 0.00017449060396756977, 0.00017578311963006854, 6.373402925419214e-7 ]
{ "id": 12, "code_window": [ " return {\n", " x: plotInstance.valToPos(annotation.time, 'x'),\n", " y: plotInstance.bbox.height / window.devicePixelRatio + 4,\n", " };\n", " },\n", " [plotCtx.plot]\n", " );\n", "\n", " const renderMarker = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " [plotCtx]\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.004408014006912708, 0.0005466605653055012, 0.00016233671340160072, 0.0001734371471684426, 0.001064499607309699 ]
{ "id": 12, "code_window": [ " return {\n", " x: plotInstance.valToPos(annotation.time, 'x'),\n", " y: plotInstance.bbox.height / window.devicePixelRatio + 4,\n", " };\n", " },\n", " [plotCtx.plot]\n", " );\n", "\n", " const renderMarker = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " [plotCtx]\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import React from 'react'; import { shallow } from 'enzyme'; import PageActionBar, { Props } from './PageActionBar'; const setup = (propOverrides?: object) => { const props: Props = { searchQuery: '', setSearchQuery: jest.fn(), target: '_blank', linkButton: { href: 'some/url', title: 'test' }, }; Object.assign(props, propOverrides); return shallow(<PageActionBar {...props} />); }; describe('Render', () => { it('should render component', () => { const wrapper = setup(); expect(wrapper).toMatchSnapshot(); }); });
public/app/core/components/PageActionBar/PageActionBar.test.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017785718955565244, 0.00017544685397297144, 0.00017391072469763458, 0.0001745726476656273, 0.0000017256543287658133 ]
{ "id": 12, "code_window": [ " return {\n", " x: plotInstance.valToPos(annotation.time, 'x'),\n", " y: plotInstance.bbox.height / window.devicePixelRatio + 4,\n", " };\n", " },\n", " [plotCtx.plot]\n", " );\n", "\n", " const renderMarker = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " [plotCtx]\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import React, { PureComponent } from 'react'; import { saveAs } from 'file-saver'; import { Button, Field, Modal, Switch } from '@grafana/ui'; import { DashboardModel, PanelModel } from 'app/features/dashboard/state'; import { DashboardExporter } from 'app/features/dashboard/components/DashExportModal'; import { appEvents } from 'app/core/core'; import { ShowModalReactEvent } from 'app/types/events'; import { ViewJsonModal } from './ViewJsonModal'; interface Props { dashboard: DashboardModel; panel?: PanelModel; onDismiss(): void; } interface State { shareExternally: boolean; } export class ShareExport extends PureComponent<Props, State> { private exporter: DashboardExporter; constructor(props: Props) { super(props); this.state = { shareExternally: false, }; this.exporter = new DashboardExporter(); } onShareExternallyChange = () => { this.setState({ shareExternally: !this.state.shareExternally, }); }; onSaveAsFile = () => { const { dashboard } = this.props; const { shareExternally } = this.state; if (shareExternally) { this.exporter.makeExportable(dashboard).then((dashboardJson: any) => { this.openSaveAsDialog(dashboardJson); }); } else { this.openSaveAsDialog(dashboard.getSaveModelClone()); } }; onViewJson = () => { const { dashboard } = this.props; const { shareExternally } = this.state; if (shareExternally) { this.exporter.makeExportable(dashboard).then((dashboardJson: any) => { this.openJsonModal(dashboardJson); }); } else { this.openJsonModal(dashboard.getSaveModelClone()); } }; openSaveAsDialog = (dash: any) => { const dashboardJsonPretty = JSON.stringify(dash, null, 2); const blob = new Blob([dashboardJsonPretty], { type: 'application/json;charset=utf-8', }); const time = new Date().getTime(); saveAs(blob, `${dash.title}-${time}.json`); }; openJsonModal = (clone: object) => { appEvents.publish( new ShowModalReactEvent({ props: { json: JSON.stringify(clone, null, 2), }, component: ViewJsonModal, }) ); this.props.onDismiss(); }; render() { const { onDismiss } = this.props; const { shareExternally } = this.state; return ( <> <p className="share-modal-info-text">Export this dashboard.</p> <Field label="Export for sharing externally"> <Switch value={shareExternally} onChange={this.onShareExternallyChange} /> </Field> <Modal.ButtonRow> <Button variant="secondary" onClick={onDismiss} fill="outline"> Cancel </Button> <Button variant="secondary" onClick={this.onViewJson}> View JSON </Button> <Button variant="primary" onClick={this.onSaveAsFile}> Save to file </Button> </Modal.ButtonRow> </> ); } }
public/app/features/dashboard/components/ShareModal/ShareExport.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017702748300507665, 0.0001726515038171783, 0.00016120850341394544, 0.00017374067101627588, 0.00000408890582548338 ]
{ "id": 12, "code_window": [ " return {\n", " x: plotInstance.valToPos(annotation.time, 'x'),\n", " y: plotInstance.bbox.height / window.devicePixelRatio + 4,\n", " };\n", " },\n", " [plotCtx.plot]\n", " );\n", "\n", " const renderMarker = useCallback(\n", " (frame: DataFrame, index: number) => {\n", " const view = new DataFrameView<AnnotationsDataFrameViewDTO>(frame);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " [plotCtx]\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/AnnotationsPlugin.tsx", "type": "replace", "edit_start_line_idx": 96 }
import { isNumber } from 'lodash'; import coreModule from 'app/core/core_module'; import { DashboardModel } from '../../state/DashboardModel'; import { getBackendSrv } from '@grafana/runtime'; export interface HistoryListOpts { limit: number; start: number; } export interface RevisionsModel { id: number; checked: boolean; dashboardId: number; parentVersion: number; version: number; created: Date; createdBy: string; message: string; } export interface DiffTarget { dashboardId: number; version: number; unsavedDashboard?: DashboardModel; // when doing diffs against unsaved dashboard version } export class HistorySrv { getHistoryList(dashboard: DashboardModel, options: HistoryListOpts) { const id = dashboard && dashboard.id ? dashboard.id : void 0; return id ? getBackendSrv().get(`api/dashboards/id/${id}/versions`, options) : Promise.resolve([]); } getDashboardVersion(id: number, version: number) { return getBackendSrv().get(`api/dashboards/id/${id}/versions/${version}`); } restoreDashboard(dashboard: DashboardModel, version: number) { const id = dashboard && dashboard.id ? dashboard.id : void 0; const url = `api/dashboards/id/${id}/restore`; return id && isNumber(version) ? getBackendSrv().post(url, { version }) : Promise.resolve({}); } } const historySrv = new HistorySrv(); export { historySrv }; coreModule.service('historySrv', HistorySrv);
public/app/features/dashboard/components/VersionHistory/HistorySrv.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017600970750208944, 0.00017383380327373743, 0.00017122963618021458, 0.00017429952276870608, 0.000001769953996699769 ]
{ "id": 13, "code_window": [ "export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => {\n", " const plotCtx = usePlotContext();\n", "\n", " const mapExemplarToXYCoords = useCallback(\n", " (dataFrame: DataFrame, index: number) => {\n", " const plotInstance = plotCtx.plot;\n", " const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME);\n", " const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);\n", "\n", " if (!time || !value || !plotInstance) {\n", " return undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx", "type": "replace", "edit_start_line_idx": 24 }
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '../../Portal/Portal'; import { usePlotContext } from '../context'; import { CartesianCoords2D, DataFrame, FieldType, formattedValueToString, getDisplayProcessor, getFieldDisplayName, TimeZone, } from '@grafana/data'; import { SeriesTable, SeriesTableRowProps, TooltipDisplayMode, VizTooltipContainer } from '../../VizTooltip'; import { UPlotConfigBuilder } from '../config/UPlotConfigBuilder'; import { pluginLog } from '../utils'; import { useTheme2 } from '../../../themes/ThemeContext'; interface TooltipPluginProps { mode?: TooltipDisplayMode; timeZone: TimeZone; data: DataFrame; config: UPlotConfigBuilder; } /** * @alpha */ export const TooltipPlugin: React.FC<TooltipPluginProps> = ({ mode = TooltipDisplayMode.Single, timeZone, config, ...otherProps }) => { const theme = useTheme2(); const plotCtx = usePlotContext(); const plotCanvas = useRef<HTMLDivElement>(); const plotCanvasBBox = useRef<any>({ left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; plotCanvas: CartesianCoords2D } | null>(null); // Debug logs useEffect(() => { pluginLog('TooltipPlugin', true, `Focused series: ${focusedSeriesIdx}, focused point: ${focusedPointIdx}`); }, [focusedPointIdx, focusedSeriesIdx]); // Add uPlot hooks to the config, or re-add when the config changed useLayoutEffect(() => { const onMouseCapture = (e: MouseEvent) => { setCoords({ plotCanvas: { x: e.clientX - plotCanvasBBox.current.left, y: e.clientY - plotCanvasBBox.current.top, }, viewport: { x: e.clientX, y: e.clientY, }, }); }; config.addHook('init', (u) => { const canvas = u.root.querySelector<HTMLDivElement>('.u-over'); plotCanvas.current = canvas || undefined; plotCanvas.current?.addEventListener('mousemove', onMouseCapture); plotCanvas.current?.addEventListener('mouseleave', () => {}); }); config.addHook('setCursor', (u) => { setFocusedPointIdx(u.cursor.idx === undefined ? null : u.cursor.idx); }); config.addHook('setSeries', (_, idx) => { setFocusedSeriesIdx(idx); }); }, [config]); if (!plotCtx.plot || focusedPointIdx === null) { return null; } // GraphNG expects aligned data, let's take field 0 as x field. FTW let xField = otherProps.data.fields[0]; if (!xField) { return null; } const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); let tooltip = null; const xVal = xFieldFmt(xField!.values.get(focusedPointIdx)).text; // when interacting with a point in single mode if (mode === TooltipDisplayMode.Single && focusedSeriesIdx !== null) { const field = otherProps.data.fields[focusedSeriesIdx]; const plotSeries = plotCtx.plot.series; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = fieldFmt(plotCtx.plot.data[focusedSeriesIdx!][focusedPointIdx]); tooltip = ( <SeriesTable series={[ { // TODO: align with uPlot typings color: (plotSeries[focusedSeriesIdx!].stroke as any)(), label: getFieldDisplayName(field, otherProps.data), value: value ? formattedValueToString(value) : null, }, ]} timestamp={xVal} /> ); } if (mode === TooltipDisplayMode.Multi) { let series: SeriesTableRowProps[] = []; const plotSeries = plotCtx.plot.series; for (let i = 0; i < plotSeries.length; i++) { const frame = otherProps.data; const field = frame.fields[i]; if ( field === xField || field.type === FieldType.time || field.type !== FieldType.number || field.config.custom?.hideFrom?.tooltip ) { continue; } const value = field.display!(plotCtx.plot.data[i][focusedPointIdx]); series.push({ // TODO: align with uPlot typings color: (plotSeries[i].stroke as any)!(), label: getFieldDisplayName(field, frame), value: value ? formattedValueToString(value) : null, isActive: focusedSeriesIdx === i, }); } tooltip = <SeriesTable series={series} timestamp={xVal} />; } if (!tooltip || !coords) { return null; } return ( <Portal> <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: 10, y: 10 }}> {tooltip} </VizTooltipContainer> </Portal> ); };
packages/grafana-ui/src/components/uPlot/plugins/TooltipPlugin.tsx
1
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.9581946730613708, 0.17931923270225525, 0.00016704176960047334, 0.00020417364430613816, 0.3709762394428253 ]
{ "id": 13, "code_window": [ "export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => {\n", " const plotCtx = usePlotContext();\n", "\n", " const mapExemplarToXYCoords = useCallback(\n", " (dataFrame: DataFrame, index: number) => {\n", " const plotInstance = plotCtx.plot;\n", " const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME);\n", " const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);\n", "\n", " if (!time || !value || !plotInstance) {\n", " return undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx", "type": "replace", "edit_start_line_idx": 24 }
import { AppEvents, applyFieldOverrides, dataFrameFromJSON, DataFrameJSON, DataQuery, DataSourceApi, } from '@grafana/data'; import { config, getBackendSrv, getDataSourceSrv, locationService } from '@grafana/runtime'; import { appEvents } from 'app/core/core'; import store from 'app/core/store'; import { ALERT_DEFINITION_UI_STATE_STORAGE_KEY, cleanUpState, loadAlertRules, loadedAlertRules, notificationChannelLoaded, setAlertDefinition, setAlertDefinitions, setInstanceData, setNotificationChannels, setUiState, updateAlertDefinitionOptions, } from './reducers'; import { AlertDefinition, AlertDefinitionState, AlertDefinitionUiState, AlertRuleDTO, NotifierDTO, QueryGroupDataSource, QueryGroupOptions, ThunkResult, } from 'app/types'; import { ExpressionDatasourceID } from '../../expressions/ExpressionDatasource'; import { isExpressionQuery } from 'app/features/expressions/guards'; export function getAlertRulesAsync(options: { state: string }): ThunkResult<void> { return async (dispatch) => { dispatch(loadAlertRules()); const rules: AlertRuleDTO[] = await getBackendSrv().get('/api/alerts', options); if (config.featureToggles.ngalert) { const ngAlertDefinitions = await getBackendSrv().get('/api/alert-definitions'); dispatch(setAlertDefinitions(ngAlertDefinitions.results)); } dispatch(loadedAlertRules(rules)); }; } export function togglePauseAlertRule(id: number, options: { paused: boolean }): ThunkResult<void> { return async (dispatch) => { await getBackendSrv().post(`/api/alerts/${id}/pause`, options); const stateFilter = locationService.getSearchObject().state || 'all'; dispatch(getAlertRulesAsync({ state: stateFilter.toString() })); }; } export function createNotificationChannel(data: any): ThunkResult<void> { return async (dispatch) => { try { await getBackendSrv().post(`/api/alert-notifications`, data); appEvents.emit(AppEvents.alertSuccess, ['Notification created']); locationService.push('/alerting/notifications'); } catch (error) { appEvents.emit(AppEvents.alertError, [error.data.error]); } }; } export function updateNotificationChannel(data: any): ThunkResult<void> { return async (dispatch) => { try { await getBackendSrv().put(`/api/alert-notifications/${data.id}`, data); appEvents.emit(AppEvents.alertSuccess, ['Notification updated']); } catch (error) { appEvents.emit(AppEvents.alertError, [error.data.error]); } }; } export function testNotificationChannel(data: any): ThunkResult<void> { return async (dispatch, getState) => { const channel = getState().notificationChannel.notificationChannel; await getBackendSrv().post('/api/alert-notifications/test', { id: channel.id, ...data }); }; } export function loadNotificationTypes(): ThunkResult<void> { return async (dispatch) => { const alertNotifiers: NotifierDTO[] = await getBackendSrv().get(`/api/alert-notifiers`); const notificationTypes = alertNotifiers.sort((o1, o2) => { if (o1.name > o2.name) { return 1; } return -1; }); dispatch(setNotificationChannels(notificationTypes)); }; } export function loadNotificationChannel(id: number): ThunkResult<void> { return async (dispatch) => { await dispatch(loadNotificationTypes()); const notificationChannel = await getBackendSrv().get(`/api/alert-notifications/${id}`); dispatch(notificationChannelLoaded(notificationChannel)); }; } export function getAlertDefinition(id: string): ThunkResult<void> { return async (dispatch) => { const alertDefinition = await getBackendSrv().get(`/api/alert-definitions/${id}`); dispatch(setAlertDefinition(alertDefinition)); }; } export function createAlertDefinition(): ThunkResult<void> { return async (dispatch, getStore) => { const alertDefinition = await buildAlertDefinition(getStore().alertDefinition); await getBackendSrv().post(`/api/alert-definitions`, alertDefinition); appEvents.emit(AppEvents.alertSuccess, ['Alert definition created']); locationService.push('/alerting/ng/list'); }; } export function updateAlertDefinition(): ThunkResult<void> { return async (dispatch, getStore) => { const alertDefinition = await buildAlertDefinition(getStore().alertDefinition); const updatedAlertDefinition = await getBackendSrv().put( `/api/alert-definitions/${alertDefinition.uid}`, alertDefinition ); appEvents.emit(AppEvents.alertSuccess, ['Alert definition updated']); dispatch(setAlertDefinition(updatedAlertDefinition)); }; } export function updateAlertDefinitionUiState(uiState: Partial<AlertDefinitionUiState>): ThunkResult<void> { return (dispatch, getStore) => { const nextState = { ...getStore().alertDefinition.uiState, ...uiState }; dispatch(setUiState(nextState)); try { store.setObject(ALERT_DEFINITION_UI_STATE_STORAGE_KEY, nextState); } catch (error) { console.error(error); } }; } export function updateAlertDefinitionOption(alertDefinition: Partial<AlertDefinition>): ThunkResult<void> { return (dispatch) => { dispatch(updateAlertDefinitionOptions(alertDefinition)); }; } export function evaluateAlertDefinition(): ThunkResult<void> { return async (dispatch, getStore) => { const { alertDefinition } = getStore().alertDefinition; const response: { instances: DataFrameJSON[] } = await getBackendSrv().get( `/api/alert-definitions/eval/${alertDefinition.uid}` ); const handledResponse = handleJSONResponse(response.instances); dispatch(setInstanceData(handledResponse)); appEvents.emit(AppEvents.alertSuccess, ['Alert definition tested successfully']); }; } export function evaluateNotSavedAlertDefinition(): ThunkResult<void> { return async (dispatch, getStore) => { const { alertDefinition } = getStore().alertDefinition; const defaultDataSource = await getDataSourceSrv().get(null); const response: { instances: DataFrameJSON[] } = await getBackendSrv().post('/api/alert-definitions/eval', { condition: alertDefinition.condition, data: buildDataQueryModel({} as QueryGroupOptions, defaultDataSource), }); const handledResponse = handleJSONResponse(response.instances); dispatch(setInstanceData(handledResponse)); appEvents.emit(AppEvents.alertSuccess, ['Alert definition tested successfully']); }; } export function cleanUpDefinitionState(): ThunkResult<void> { return (dispatch) => { dispatch(cleanUpState(undefined)); }; } async function buildAlertDefinition(state: AlertDefinitionState) { const queryOptions = {} as QueryGroupOptions; const currentAlertDefinition = state.alertDefinition; const defaultDataSource = await getDataSourceSrv().get(null); return { ...currentAlertDefinition, data: buildDataQueryModel(queryOptions, defaultDataSource), }; } function handleJSONResponse(frames: DataFrameJSON[]) { const dataFrames = frames.map((instance) => { return dataFrameFromJSON(instance); }); return applyFieldOverrides({ data: dataFrames, fieldConfig: { defaults: {}, overrides: [], }, replaceVariables: (value: any) => value, theme: config.theme2, }); } function buildDataQueryModel(queryOptions: QueryGroupOptions, defaultDataSource: DataSourceApi) { return queryOptions.queries.map((query: DataQuery) => { if (isExpressionQuery(query)) { const dataSource: QueryGroupDataSource = { name: ExpressionDatasourceID, uid: ExpressionDatasourceID, }; return { model: { ...query, type: query.type, datasource: dataSource.name, datasourceUid: dataSource.uid, }, refId: query.refId, }; } const dataSourceSetting = getDataSourceSrv().getInstanceSettings(query.datasource); const dataSource: QueryGroupDataSource = { name: dataSourceSetting?.name ?? defaultDataSource.name, uid: dataSourceSetting?.uid ?? defaultDataSource.uid, }; return { model: { ...query, type: query.queryType, datasource: dataSource.name, datasourceUid: dataSource.uid, }, refId: query.refId, relativeTimeRange: { from: 600, to: 0, }, }; }); }
public/app/features/alerting/state/actions.ts
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.0002037126978393644, 0.0001742423773976043, 0.0001641308335820213, 0.00017421877419110388, 0.00000669437758915592 ]
{ "id": 13, "code_window": [ "export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => {\n", " const plotCtx = usePlotContext();\n", "\n", " const mapExemplarToXYCoords = useCallback(\n", " (dataFrame: DataFrame, index: number) => {\n", " const plotInstance = plotCtx.plot;\n", " const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME);\n", " const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);\n", "\n", " if (!time || !value || !plotInstance) {\n", " return undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx", "type": "replace", "edit_start_line_idx": 24 }
#!/bin/bash set -eo pipefail source ./common.sh # # No longer required, but useful to keep just in case we want to deploy # changes in toolkit directly to the docker image # if [ -n "$INCLUDE_TOOLKIT" ]; then /bin/rm -rfv install/grafana-toolkit mkdir -pv install/grafana-toolkit cp -rv ../../bin install/grafana-toolkit cp -rv ../../src install/grafana-toolkit cp -v ../../package.json install/grafana-toolkit cp -v ../../tsconfig.json install/grafana-toolkit fi docker build -t ${DOCKER_IMAGE_NAME} . docker push $DOCKER_IMAGE_NAME docker tag ${DOCKER_IMAGE_NAME} ${DOCKER_IMAGE_BASE_NAME}:latest docker push ${DOCKER_IMAGE_BASE_NAME}:latest [ -n "$INCLUDE_TOOLKIT" ] && /bin/rm -rfv install/grafana-toolkit
packages/grafana-toolkit/docker/grafana-plugin-ci-e2e/build.sh
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017231571837328374, 0.00016990913718473166, 0.0001677261316217482, 0.00016968557611107826, 0.000001880348122540454 ]
{ "id": 13, "code_window": [ "export const ExemplarsPlugin: React.FC<ExemplarsPluginProps> = ({ exemplars, timeZone, getFieldLinks, config }) => {\n", " const plotCtx = usePlotContext();\n", "\n", " const mapExemplarToXYCoords = useCallback(\n", " (dataFrame: DataFrame, index: number) => {\n", " const plotInstance = plotCtx.plot;\n", " const time = dataFrame.fields.find((f) => f.name === TIME_SERIES_TIME_FIELD_NAME);\n", " const value = dataFrame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);\n", "\n", " if (!time || !value || !plotInstance) {\n", " return undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const plotInstance = plotCtx.getPlot();\n" ], "file_path": "public/app/plugins/panel/timeseries/plugins/ExemplarsPlugin.tsx", "type": "replace", "edit_start_line_idx": 24 }
import React from 'react'; import { DataSourceSettingsPage, Props } from './DataSourceSettingsPage'; import { getMockDataSource } from '../__mocks__/dataSourcesMocks'; import { getMockPlugin } from '../../plugins/__mocks__/pluginMocks'; import { dataSourceLoaded, setDataSourceName, setIsDefault } from '../state/reducers'; import { getRouteComponentProps } from 'app/core/navigation/__mocks__/routeProps'; import { cleanUpAction } from 'app/core/actions/cleanUp'; import { screen, render } from '@testing-library/react'; import { selectors } from '@grafana/e2e-selectors'; import { PluginState } from '@grafana/data'; const getMockNode = () => ({ text: 'text', subTitle: 'subtitle', icon: 'icon', }); const getProps = (): Props => ({ ...getRouteComponentProps(), navModel: { node: getMockNode(), main: getMockNode(), }, dataSource: getMockDataSource(), dataSourceMeta: getMockPlugin(), dataSourceId: 1, deleteDataSource: jest.fn(), loadDataSource: jest.fn(), setDataSourceName, updateDataSource: jest.fn(), initDataSourceSettings: jest.fn(), testDataSource: jest.fn(), setIsDefault, dataSourceLoaded, cleanUpAction, page: null, plugin: null, loadError: null, testingStatus: {}, }); describe('Render', () => { it('should not render loading when props are ready', () => { render(<DataSourceSettingsPage {...getProps()} />); expect(screen.queryByText('Loading ...')).not.toBeInTheDocument(); }); it('should render loading if datasource is not ready', () => { const mockProps = getProps(); mockProps.dataSource.id = 0; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByText('Loading ...')).toBeInTheDocument(); }); it('should render beta info text if plugin state is beta', () => { const mockProps = getProps(); mockProps.dataSourceMeta.state = PluginState.beta; render(<DataSourceSettingsPage {...mockProps} />); expect( screen.getByTitle('Beta Plugin: There could be bugs and minor breaking changes to this plugin') ).toBeInTheDocument(); }); it('should render alpha info text if plugin state is alpha', () => { const mockProps = getProps(); mockProps.dataSourceMeta.state = PluginState.alpha; render(<DataSourceSettingsPage {...mockProps} />); expect( screen.getByTitle('Alpha Plugin: This plugin is a work in progress and updates may include breaking changes') ).toBeInTheDocument(); }); it('should not render is ready only message is readOnly is false', () => { const mockProps = getProps(); mockProps.dataSource.readOnly = false; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.queryByLabelText(selectors.pages.DataSource.readOnly)).not.toBeInTheDocument(); }); it('should render is ready only message is readOnly is true', () => { const mockProps = getProps(); mockProps.dataSource.readOnly = true; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByLabelText(selectors.pages.DataSource.readOnly)).toBeInTheDocument(); }); it('should render error message with detailed message', () => { const mockProps = { ...getProps(), testingStatus: { message: 'message', status: 'error', details: { message: 'detailed message' }, }, }; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByText(mockProps.testingStatus.message)).toBeInTheDocument(); expect(screen.getByText(mockProps.testingStatus.details.message)).toBeInTheDocument(); }); it('should render error message with empty details', () => { const mockProps = { ...getProps(), testingStatus: { message: 'message', status: 'error', details: {}, }, }; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByText(mockProps.testingStatus.message)).toBeInTheDocument(); }); it('should render error message without details', () => { const mockProps = { ...getProps(), testingStatus: { message: 'message', status: 'error', }, }; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByText(mockProps.testingStatus.message)).toBeInTheDocument(); }); it('should render verbose error message with detailed verbose error message', () => { const mockProps = { ...getProps(), testingStatus: { message: 'message', status: 'error', details: { message: 'detailed message', verboseMessage: 'verbose message' }, }, }; render(<DataSourceSettingsPage {...mockProps} />); expect(screen.getByText(mockProps.testingStatus.details.verboseMessage)).toBeInTheDocument(); }); });
public/app/features/datasources/settings/DataSourceSettingsPage.test.tsx
0
https://github.com/grafana/grafana/commit/45c763a76bbf94c88be6ba13ffbe21381e266666
[ 0.00017567386385053396, 0.00017230154480785131, 0.0001650704798521474, 0.00017292900884058326, 0.000002874550546039245 ]
{ "id": 1, "code_window": [ " */\n", " openFile(fileName: string, openedByClient: boolean) {\n", " fileName = ts.normalizePath(fileName);\n", " let info = ts.lookUp(this.filenameToScriptInfo, fileName);\n", " if (!info) {\n", " let content: string;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " openFile(fileName: string, openedByClient: boolean, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1001 }
/// <reference path="..\compiler\commandLineParser.ts" /> /// <reference path="..\services\services.ts" /> /// <reference path="protocol.d.ts" /> /// <reference path="editorServices.ts" /> namespace ts.server { const spaceCache: string[] = []; interface StackTraceError extends Error { stack?: string; } export function generateSpaces(n: number): string { if (!spaceCache[n]) { let strBuilder = ""; for (let i = 0; i < n; i++) { strBuilder += " "; } spaceCache[n] = strBuilder; } return spaceCache[n]; } export function generateIndentString(n: number, editorOptions: EditorOptions): string { if (editorOptions.ConvertTabsToSpaces) { return generateSpaces(n); } else { let result = ""; for (let i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { result += "\t"; } for (let i = 0; i < n % editorOptions.TabSize; i++) { result += " "; } return result; } } interface FileStart { file: string; start: ILineInfo; } function compareNumber(a: number, b: number) { if (a < b) { return -1; } else if (a === b) { return 0; } else return 1; } function compareFileStart(a: FileStart, b: FileStart) { if (a.file < b.file) { return -1; } else if (a.file == b.file) { const n = compareNumber(a.start.line, b.start.line); if (n === 0) { return compareNumber(a.start.offset, b.start.offset); } else return n; } else { return 1; } } function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic) { return { start: project.compilerService.host.positionToLineOffset(fileName, diag.start), end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") }; } export interface PendingErrorCheck { fileName: string; project: Project; } function allEditsBeforePos(edits: ts.TextChange[], pos: number) { for (let i = 0, len = edits.length; i < len; i++) { if (ts.textSpanEnd(edits[i].span) >= pos) { return false; } } return true; } export namespace CommandNames { export const Brace = "brace"; export const Change = "change"; export const Close = "close"; export const Completions = "completions"; export const CompletionDetails = "completionEntryDetails"; export const Configure = "configure"; export const Definition = "definition"; export const Exit = "exit"; export const Format = "format"; export const Formatonkey = "formatonkey"; export const Geterr = "geterr"; export const GeterrForProject = "geterrForProject"; export const NavBar = "navbar"; export const Navto = "navto"; export const Occurrences = "occurrences"; export const DocumentHighlights = "documentHighlights"; export const Open = "open"; export const Quickinfo = "quickinfo"; export const References = "references"; export const Reload = "reload"; export const Rename = "rename"; export const Saveto = "saveto"; export const SignatureHelp = "signatureHelp"; export const TypeDefinition = "typeDefinition"; export const ProjectInfo = "projectInfo"; export const ReloadProjects = "reloadProjects"; export const Unknown = "unknown"; } namespace Errors { export const NoProject = new Error("No Project."); } export interface ServerHost extends ts.System { } export class Session { protected projectService: ProjectService; private pendingOperation = false; private fileHash: ts.Map<number> = {}; private nextFileId = 1; private errorTimer: any; /*NodeJS.Timer | number*/ private immediateId: any; private changeSeq = 0; constructor( private host: ServerHost, private byteLength: (buf: string, encoding?: string) => number, private hrtime: (start?: number[]) => number[], private logger: Logger ) { this.projectService = new ProjectService(host, logger, (eventName, project, fileName) => { this.handleEvent(eventName, project, fileName); }); } private handleEvent(eventName: string, project: Project, fileName: string) { if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); this.updateErrorCheck([{ fileName, project }], this.changeSeq, (n) => n === this.changeSeq, 100); } } public logError(err: Error, cmd: string) { const typedErr = <StackTraceError>err; let msg = "Exception on executing command " + cmd; if (typedErr.message) { msg += ":\n" + typedErr.message; if (typedErr.stack) { msg += "\n" + typedErr.stack; } } this.projectService.log(msg); } private sendLineToClient(line: string) { this.host.write(line + this.host.newLine); } public send(msg: protocol.Message) { const json = JSON.stringify(msg); if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + "\r\n\r\n" + json); } public event(info: any, eventName: string) { const ev: protocol.Event = { seq: 0, type: "event", event: eventName, body: info, }; this.send(ev); } private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) { const res: protocol.Response = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, success: !errorMsg, }; if (!errorMsg) { res.body = info; } else { res.message = errorMsg; } this.send(res); } public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) { this.response(body, commandName, requestSequence, errorMessage); } private semanticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSemanticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } } catch (err) { this.logError(err, "semantic check"); } } private syntacticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); } } catch (err) { this.logError(err, "syntactic check"); } } private errorCheck(file: string, project: Project) { this.syntacticCheck(file, project); this.semanticCheck(file, project); } private reloadProjects() { this.projectService.reloadProjects(); } private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) { setTimeout(() => { if (matchSeq(seq)) { this.projectService.updateProjectStructure(); } }, ms); } private updateErrorCheck(checkList: PendingErrorCheck[], seq: number, matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200, requireOpen = true) { if (followMs > ms) { followMs = ms; } if (this.errorTimer) { clearTimeout(this.errorTimer); } if (this.immediateId) { clearImmediate(this.immediateId); this.immediateId = undefined; } let index = 0; const checkOne = () => { if (matchSeq(seq)) { const checkSpec = checkList[index++]; if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) { this.syntacticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = setImmediate(() => { this.semanticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = undefined; if (checkList.length > index) { this.errorTimer = setTimeout(checkOne, followMs); } else { this.errorTimer = undefined; } }); } } }; if ((checkList.length > index) && (matchSeq(seq))) { this.errorTimer = setTimeout(checkOne, ms); } } private getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); if (!occurrences) { return undefined; } return occurrences.map(occurrence => { const { fileName, isWriteAccess, textSpan } = occurrence; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, file: fileName, isWriteAccess }; }); } private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); if (!documentHighlights) { return undefined; } return documentHighlights.map(convertToDocumentHighlightsItem); function convertToDocumentHighlightsItem(documentHighlights: ts.DocumentHighlights): ts.server.protocol.DocumentHighlightsItem { const { fileName, highlightSpans } = documentHighlights; return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan: ts.HighlightSpan): ts.server.protocol.HighlightSpan { const { textSpan, kind } = highlightSpan; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, kind }; } } } private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); const projectInfo: protocol.ProjectInfo = { configFileName: project.projectFilename }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); } return projectInfo; } private getRenameLocations(line: number, offset: number, fileName: string, findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const renameInfo = compilerService.languageService.getRenameInfo(file, position); if (!renameInfo) { return undefined; } if (!renameInfo.canRename) { return { info: renameInfo, locs: [] }; } const renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { return undefined; } const bakedRenameLocs = renameLocations.map(location => (<protocol.FileSpan>{ file: location.fileName, start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)), })).sort((a, b) => { if (a.file < b.file) { return -1; } else if (a.file > b.file) { return 1; } else { // reverse sort assuming no overlap if (a.start.line < b.start.line) { return 1; } else if (a.start.line > b.start.line) { return -1; } else { return b.start.offset - a.start.offset; } } }).reduce<protocol.SpanGroup[]>((accum: protocol.SpanGroup[], cur: protocol.FileSpan) => { let curFileAccum: protocol.SpanGroup; if (accum.length > 0) { curFileAccum = accum[accum.length - 1]; if (curFileAccum.file != cur.file) { curFileAccum = undefined; } } if (!curFileAccum) { curFileAccum = { file: cur.file, locs: [] }; accum.push(curFileAccum); } curFileAccum.locs.push({ start: cur.start, end: cur.end }); return accum; }, []); return { info: renameInfo, locs: bakedRenameLocs }; } private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody { // TODO: get all projects for this file; report refs for all projects deleting duplicates // can avoid duplicates by eliminating same ref file from subsequent projects const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { return undefined; } const nameInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { return undefined; } const displayString = ts.displayPartsToString(nameInfo.displayParts); const nameSpan = nameInfo.textSpan; const nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset; const nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); const bakedRefs: protocol.ReferencesResponseItem[] = references.map(ref => { const start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); const refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); const snap = compilerService.host.getScriptSnapshot(ref.fileName); const lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), isWriteAccess: ref.isWriteAccess }; }).sort(compareFileStart); return { refs: bakedRefs, symbolName: nameText, symbolStartOffset: nameColStart, symbolDisplayString: displayString }; } private openClientFile(fileName: string) { const file = ts.normalizePath(fileName); this.projectService.openClientFile(file); } private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!quickInfo) { return undefined; } const displayString = ts.displayPartsToString(quickInfo.displayParts); const docString = ts.displayPartsToString(quickInfo.documentation); return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, documentation: docString, }; } private getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); const endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); // TODO: avoid duplicate code (with formatonkey) const edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const formatOptions = this.projectService.getFormatCodeOptions(file); const edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); // Check whether we should auto-indent. This will be when // the position is on a line containing only whitespace. // This should leave the edits returned from // getFormattingEditsAfterKeytroke either empty or pertaining // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { const scriptInfo = compilerService.host.getScriptInfo(file); if (scriptInfo) { const lineInfo = scriptInfo.getLineInfo(line); if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { const lineText = lineInfo.leaf.text; if (lineText.search("\\S") < 0) { // TODO: get these options from host const editorOptions: ts.EditorOptions = { IndentSize: formatOptions.IndentSize, TabSize: formatOptions.TabSize, NewLineCharacter: "\n", ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, IndentStyle: ts.IndentStyle.Smart, }; const preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); let hasIndent = 0; let i: number, len: number; for (i = 0, len = lineText.length; i < len; i++) { if (lineText.charAt(i) == " ") { hasIndent++; } else if (lineText.charAt(i) == "\t") { hasIndent += editorOptions.TabSize; } else { break; } } // i points to the first non whitespace character if (preferredIndent !== hasIndent) { const firstNoWhiteSpacePosition = lineInfo.offset + i; edits.push({ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), newText: generateIndentString(preferredIndent, editorOptions) }); } } } } } if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] { if (!prefix) { prefix = ""; } const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const completions = compilerService.languageService.getCompletionsAtPosition(file, position); if (!completions) { return undefined; } return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { result.push(entry); } return result; }, []).sort((a, b) => a.name.localeCompare(b.name)); } private getCompletionEntryDetails(line: number, offset: number, entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); return entryNames.reduce((accum: protocol.CompletionEntryDetails[], entryName: string) => { const details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); } private getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const helpItems = compilerService.languageService.getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } const span = helpItems.applicableSpan; const result: protocol.SignatureHelpItems = { items: helpItems.items, applicableSpan: { start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, argumentCount: helpItems.argumentCount, }; return result; } private getDiagnostics(delay: number, fileNames: string[]) { const checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (project) { accum.push({ fileName, project }); } return accum; }, []); if (checkList.length > 0) { this.updateErrorCheck(checkList, this.changeSeq, (n) => n === this.changeSeq, delay); } } private change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (project) { const compilerService = project.compilerService; const start = compilerService.host.lineOffsetToPosition(file, line, offset); const end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); if (start >= 0) { compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, (n) => n === this.changeSeq); } } private reload(fileName: string, tempFileName: string, reqSeq = 0) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { this.changeSeq++; // make sure no changes happen before this one is finished project.compilerService.host.reloadScript(file, tmpfile, () => { this.output(undefined, CommandNames.Reload, reqSeq); }); } } private saveToTmp(fileName: string, tempFileName: string) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { project.compilerService.host.saveTo(file, tmpfile); } } private closeClientFile(fileName: string) { if (!fileName) { return; } const file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); } private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { if (!items) { return undefined; } const compilerService = project.compilerService; return items.map(item => ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(span => ({ start: compilerService.host.positionToLineOffset(fileName, span.start), end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) })), childItems: this.decorateNavigationBarItem(project, fileName, item.childItems) })); } private getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const items = compilerService.languageService.getNavigationBarItems(file); if (!items) { return undefined; } return this.decorateNavigationBarItem(project, fileName, items); } private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { return undefined; } return navItems.map((navItem) => { const start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); const end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); const bakedItem: protocol.NavtoItem = { name: navItem.name, kind: navItem.kind, file: navItem.fileName, start: start, end: end, }; if (navItem.kindModifiers && (navItem.kindModifiers != "")) { bakedItem.kindModifiers = navItem.kindModifiers; } if (navItem.matchKind !== "none") { bakedItem.matchKind = navItem.matchKind; } if (navItem.containerName && (navItem.containerName.length > 0)) { bakedItem.containerName = navItem.containerName; } if (navItem.containerKind && (navItem.containerKind.length > 0)) { bakedItem.containerKind = navItem.containerKind; } return bakedItem; }); } private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); if (!spans) { return undefined; } return spans.map(span => ({ start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) })); } getDiagnosticsForProject(delay: number, fileName: string) { const { configFileName, fileNames } = this.getProjectInfo(fileName, true); // No need to analyze lib.d.ts let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0); // Sort the file name list to make the recently touched files come first const highPriorityFiles: string[] = []; const mediumPriorityFiles: string[] = []; const lowPriorityFiles: string[] = []; const veryLowPriorityFiles: string[] = []; const normalizedFileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(normalizedFileName); for (const fileNameInProject of fileNamesInProject) { if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { const info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isOpen) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else lowPriorityFiles.push(fileNameInProject); } else mediumPriorityFiles.push(fileNameInProject); } } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { const checkList = fileNamesInProject.map<PendingErrorCheck>((fileName: string) => { const normalizedFileName = ts.normalizePath(fileName); return { fileName: normalizedFileName, project }; }); // Project level error analysis runs on background files too, therefore // doesn't require the file to be opened this.updateErrorCheck(checkList, this.changeSeq, (n) => n == this.changeSeq, delay, 200, /*requireOpen*/ false); } } getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); } exit() { } private handlers: Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = { [CommandNames.Exit]: () => { this.exit(); return { responseRequired: false}; }, [CommandNames.Definition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.TypeDefinition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.References]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.Rename]: (request: protocol.Request) => { const renameArgs = <protocol.RenameRequestArgs>request.arguments; return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true}; }, [CommandNames.Open]: (request: protocol.Request) => { const openArgs = <protocol.OpenRequestArgs>request.arguments; this.openClientFile(openArgs.file); return {responseRequired: false}; }, [CommandNames.Quickinfo]: (request: protocol.Request) => { const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true}; }, [CommandNames.Format]: (request: protocol.Request) => { const formatArgs = <protocol.FormatRequestArgs>request.arguments; return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true}; }, [CommandNames.Formatonkey]: (request: protocol.Request) => { const formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments; return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true}; }, [CommandNames.Completions]: (request: protocol.Request) => { const completionsArgs = <protocol.CompletionsRequestArgs>request.arguments; return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true}; }, [CommandNames.CompletionDetails]: (request: protocol.Request) => { const completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments; return {response: this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true}; }, [CommandNames.SignatureHelp]: (request: protocol.Request) => { const signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments; return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true}; }, [CommandNames.Geterr]: (request: protocol.Request) => { const geterrArgs = <protocol.GeterrRequestArgs>request.arguments; return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false}; }, [CommandNames.GeterrForProject]: (request: protocol.Request) => { const { file, delay } = <protocol.GeterrForProjectRequestArgs>request.arguments; return {response: this.getDiagnosticsForProject(delay, file), responseRequired: false}; }, [CommandNames.Change]: (request: protocol.Request) => { const changeArgs = <protocol.ChangeRequestArgs>request.arguments; this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); return {responseRequired: false}; }, [CommandNames.Configure]: (request: protocol.Request) => { const configureArgs = <protocol.ConfigureRequestArguments>request.arguments; this.projectService.setHostConfiguration(configureArgs); this.output(undefined, CommandNames.Configure, request.seq); return {responseRequired: false}; }, [CommandNames.Reload]: (request: protocol.Request) => { const reloadArgs = <protocol.ReloadRequestArgs>request.arguments; this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); return {responseRequired: false}; }, [CommandNames.Saveto]: (request: protocol.Request) => { const savetoArgs = <protocol.SavetoRequestArgs>request.arguments; this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return {responseRequired: false}; }, [CommandNames.Close]: (request: protocol.Request) => { const closeArgs = <protocol.FileRequestArgs>request.arguments; this.closeClientFile(closeArgs.file); return {responseRequired: false}; }, [CommandNames.Navto]: (request: protocol.Request) => { const navtoArgs = <protocol.NavtoRequestArgs>request.arguments; return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true}; }, [CommandNames.Brace]: (request: protocol.Request) => { const braceArguments = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true}; }, [CommandNames.NavBar]: (request: protocol.Request) => { const navBarArgs = <protocol.FileRequestArgs>request.arguments; return {response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true}; }, [CommandNames.Occurrences]: (request: protocol.Request) => { const { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getOccurrences(line, offset, fileName), responseRequired: true}; }, [CommandNames.DocumentHighlights]: (request: protocol.Request) => { const { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments; return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true}; }, [CommandNames.ProjectInfo]: (request: protocol.Request) => { const { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments; return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true}; }, [CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => { this.reloadProjects(); return {responseRequired: false}; } }; public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) { if (this.handlers[command]) { throw new Error(`Protocol handler already exists for command "${command}"`); } this.handlers[command] = handler; } public executeCommand(request: protocol.Request): {response?: any, responseRequired?: boolean} { const handler = this.handlers[request.command]; if (handler) { return handler(request); } else { this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return {responseRequired: false}; } } public onMessage(message: string) { let start: number[]; if (this.logger.isVerbose()) { this.logger.info("request: " + message); start = this.hrtime(); } let request: protocol.Request; try { request = <protocol.Request>JSON.parse(message); const {response, responseRequired} = this.executeCommand(request); if (this.logger.isVerbose()) { const elapsed = this.hrtime(start); const seconds = elapsed[0]; const nanoseconds = elapsed[1]; const elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; let leader = "Elapsed time (in milliseconds)"; if (!responseRequired) { leader = "Async elapsed time (in milliseconds)"; } this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); } else if (responseRequired) { this.output(undefined, request.command, request.seq, "No content available."); } } catch (err) { if (err instanceof OperationCanceledException) { // Handle cancellation exceptions } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message); } } } }
src/server/session.ts
1
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.9968859553337097, 0.21314287185668945, 0.00016429962124675512, 0.00017540372209623456, 0.383422315120697 ]
{ "id": 1, "code_window": [ " */\n", " openFile(fileName: string, openedByClient: boolean) {\n", " fileName = ts.normalizePath(fileName);\n", " let info = ts.lookUp(this.filenameToScriptInfo, fileName);\n", " if (!info) {\n", " let content: string;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " openFile(fileName: string, openedByClient: boolean, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1001 }
{ "scenario": "[Sourcemap]/[Sourceroot-Url]: outputdir_singleFile: specify outputDirectory", "projectRoot": "tests/cases/projects/outputdir_singleFile", "inputFiles": [ "test.ts" ], "outDir": "outdir/simple", "sourceMap": true, "declaration": true, "baselineCheck": true, "sourceRoot": "http://typescript.codeplex.com/" }
tests/cases/project/sourcerootUrlSingleFileSpecifyOutputDirectory.json
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00017497091903351247, 0.0001744928304105997, 0.00017401472723577172, 0.0001744928304105997, 4.780958988703787e-7 ]
{ "id": 1, "code_window": [ " */\n", " openFile(fileName: string, openedByClient: boolean) {\n", " fileName = ts.normalizePath(fileName);\n", " let info = ts.lookUp(this.filenameToScriptInfo, fileName);\n", " if (!info) {\n", " let content: string;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " openFile(fileName: string, openedByClient: boolean, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1001 }
=== tests/cases/compiler/collisionRestParameterClassConstructor.ts === // Constructors class c1 { >c1 : c1 constructor(_i: number, ...restParameters) { //_i is error >_i : number >restParameters : any[] var _i = 10; // no error >_i : number >10 : number } } class c1NoError { >c1NoError : c1NoError constructor(_i: number) { // no error >_i : number var _i = 10; // no error >_i : number >10 : number } } class c2 { >c2 : c2 constructor(...restParameters) { >restParameters : any[] var _i = 10; // no error >_i : number >10 : number } } class c2NoError { >c2NoError : c2NoError constructor() { var _i = 10; // no error >_i : number >10 : number } } class c3 { >c3 : c3 constructor(public _i: number, ...restParameters) { //_i is error >_i : number >restParameters : any[] var _i = 10; // no error >_i : number >10 : number } } class c3NoError { >c3NoError : c3NoError constructor(public _i: number) { // no error >_i : number var _i = 10; // no error >_i : number >10 : number } } declare class c4 { >c4 : c4 constructor(_i: number, ...restParameters); // No error - no code gen >_i : number >restParameters : any[] } declare class c4NoError { >c4NoError : c4NoError constructor(_i: number); // no error >_i : number } class c5 { >c5 : c5 constructor(_i: number, ...rest); // no codegen no error >_i : number >rest : any[] constructor(_i: string, ...rest); // no codegen no error >_i : string >rest : any[] constructor(_i: any, ...rest) { // error >_i : any >rest : any[] var _i: any; // no error >_i : any } } class c5NoError { >c5NoError : c5NoError constructor(_i: number); // no error >_i : number constructor(_i: string); // no error >_i : string constructor(_i: any) { // no error >_i : any var _i: any; // no error >_i : any } } declare class c6 { >c6 : c6 constructor(_i: number, ...rest); // no codegen no error >_i : number >rest : any[] constructor(_i: string, ...rest); // no codegen no error >_i : string >rest : any[] } declare class c6NoError { >c6NoError : c6NoError constructor(_i: number); // no error >_i : number constructor(_i: string); // no error >_i : string }
tests/baselines/reference/collisionRestParameterClassConstructor.types
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00024914080859161913, 0.00017765586380846798, 0.00016386029892601073, 0.00017229944933205843, 0.000020498433514148928 ]
{ "id": 1, "code_window": [ " */\n", " openFile(fileName: string, openedByClient: boolean) {\n", " fileName = ts.normalizePath(fileName);\n", " let info = ts.lookUp(this.filenameToScriptInfo, fileName);\n", " if (!info) {\n", " let content: string;\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " openFile(fileName: string, openedByClient: boolean, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1001 }
interface I<T> { v: A<T>; f1<T>(): T; f2?<T>(): T; <T>(): void; new <T>(): void; }
tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInInterfaceDeclaration1.ts
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00017454249609727412, 0.00017454249609727412, 0.00017454249609727412, 0.00017454249609727412, 0 ]
{ "id": 3, "code_window": [ " }\n", "\n", " /**\n", " * Open file whose contents is managed by the client\n", " * @param filename is absolute pathname\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " * @param fileContent is a known version of the file content that is more up to date \n" ], "file_path": "src/server/editorServices.ts", "type": "add", "edit_start_line_idx": 1054 }
/// <reference path="..\compiler\commandLineParser.ts" /> /// <reference path="..\services\services.ts" /> /// <reference path="protocol.d.ts" /> /// <reference path="editorServices.ts" /> namespace ts.server { const spaceCache: string[] = []; interface StackTraceError extends Error { stack?: string; } export function generateSpaces(n: number): string { if (!spaceCache[n]) { let strBuilder = ""; for (let i = 0; i < n; i++) { strBuilder += " "; } spaceCache[n] = strBuilder; } return spaceCache[n]; } export function generateIndentString(n: number, editorOptions: EditorOptions): string { if (editorOptions.ConvertTabsToSpaces) { return generateSpaces(n); } else { let result = ""; for (let i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { result += "\t"; } for (let i = 0; i < n % editorOptions.TabSize; i++) { result += " "; } return result; } } interface FileStart { file: string; start: ILineInfo; } function compareNumber(a: number, b: number) { if (a < b) { return -1; } else if (a === b) { return 0; } else return 1; } function compareFileStart(a: FileStart, b: FileStart) { if (a.file < b.file) { return -1; } else if (a.file == b.file) { const n = compareNumber(a.start.line, b.start.line); if (n === 0) { return compareNumber(a.start.offset, b.start.offset); } else return n; } else { return 1; } } function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic) { return { start: project.compilerService.host.positionToLineOffset(fileName, diag.start), end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") }; } export interface PendingErrorCheck { fileName: string; project: Project; } function allEditsBeforePos(edits: ts.TextChange[], pos: number) { for (let i = 0, len = edits.length; i < len; i++) { if (ts.textSpanEnd(edits[i].span) >= pos) { return false; } } return true; } export namespace CommandNames { export const Brace = "brace"; export const Change = "change"; export const Close = "close"; export const Completions = "completions"; export const CompletionDetails = "completionEntryDetails"; export const Configure = "configure"; export const Definition = "definition"; export const Exit = "exit"; export const Format = "format"; export const Formatonkey = "formatonkey"; export const Geterr = "geterr"; export const GeterrForProject = "geterrForProject"; export const NavBar = "navbar"; export const Navto = "navto"; export const Occurrences = "occurrences"; export const DocumentHighlights = "documentHighlights"; export const Open = "open"; export const Quickinfo = "quickinfo"; export const References = "references"; export const Reload = "reload"; export const Rename = "rename"; export const Saveto = "saveto"; export const SignatureHelp = "signatureHelp"; export const TypeDefinition = "typeDefinition"; export const ProjectInfo = "projectInfo"; export const ReloadProjects = "reloadProjects"; export const Unknown = "unknown"; } namespace Errors { export const NoProject = new Error("No Project."); } export interface ServerHost extends ts.System { } export class Session { protected projectService: ProjectService; private pendingOperation = false; private fileHash: ts.Map<number> = {}; private nextFileId = 1; private errorTimer: any; /*NodeJS.Timer | number*/ private immediateId: any; private changeSeq = 0; constructor( private host: ServerHost, private byteLength: (buf: string, encoding?: string) => number, private hrtime: (start?: number[]) => number[], private logger: Logger ) { this.projectService = new ProjectService(host, logger, (eventName, project, fileName) => { this.handleEvent(eventName, project, fileName); }); } private handleEvent(eventName: string, project: Project, fileName: string) { if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); this.updateErrorCheck([{ fileName, project }], this.changeSeq, (n) => n === this.changeSeq, 100); } } public logError(err: Error, cmd: string) { const typedErr = <StackTraceError>err; let msg = "Exception on executing command " + cmd; if (typedErr.message) { msg += ":\n" + typedErr.message; if (typedErr.stack) { msg += "\n" + typedErr.stack; } } this.projectService.log(msg); } private sendLineToClient(line: string) { this.host.write(line + this.host.newLine); } public send(msg: protocol.Message) { const json = JSON.stringify(msg); if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + "\r\n\r\n" + json); } public event(info: any, eventName: string) { const ev: protocol.Event = { seq: 0, type: "event", event: eventName, body: info, }; this.send(ev); } private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) { const res: protocol.Response = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, success: !errorMsg, }; if (!errorMsg) { res.body = info; } else { res.message = errorMsg; } this.send(res); } public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) { this.response(body, commandName, requestSequence, errorMessage); } private semanticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSemanticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } } catch (err) { this.logError(err, "semantic check"); } } private syntacticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); } } catch (err) { this.logError(err, "syntactic check"); } } private errorCheck(file: string, project: Project) { this.syntacticCheck(file, project); this.semanticCheck(file, project); } private reloadProjects() { this.projectService.reloadProjects(); } private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) { setTimeout(() => { if (matchSeq(seq)) { this.projectService.updateProjectStructure(); } }, ms); } private updateErrorCheck(checkList: PendingErrorCheck[], seq: number, matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200, requireOpen = true) { if (followMs > ms) { followMs = ms; } if (this.errorTimer) { clearTimeout(this.errorTimer); } if (this.immediateId) { clearImmediate(this.immediateId); this.immediateId = undefined; } let index = 0; const checkOne = () => { if (matchSeq(seq)) { const checkSpec = checkList[index++]; if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) { this.syntacticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = setImmediate(() => { this.semanticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = undefined; if (checkList.length > index) { this.errorTimer = setTimeout(checkOne, followMs); } else { this.errorTimer = undefined; } }); } } }; if ((checkList.length > index) && (matchSeq(seq))) { this.errorTimer = setTimeout(checkOne, ms); } } private getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); if (!occurrences) { return undefined; } return occurrences.map(occurrence => { const { fileName, isWriteAccess, textSpan } = occurrence; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, file: fileName, isWriteAccess }; }); } private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); if (!documentHighlights) { return undefined; } return documentHighlights.map(convertToDocumentHighlightsItem); function convertToDocumentHighlightsItem(documentHighlights: ts.DocumentHighlights): ts.server.protocol.DocumentHighlightsItem { const { fileName, highlightSpans } = documentHighlights; return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan: ts.HighlightSpan): ts.server.protocol.HighlightSpan { const { textSpan, kind } = highlightSpan; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, kind }; } } } private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); const projectInfo: protocol.ProjectInfo = { configFileName: project.projectFilename }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); } return projectInfo; } private getRenameLocations(line: number, offset: number, fileName: string, findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const renameInfo = compilerService.languageService.getRenameInfo(file, position); if (!renameInfo) { return undefined; } if (!renameInfo.canRename) { return { info: renameInfo, locs: [] }; } const renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { return undefined; } const bakedRenameLocs = renameLocations.map(location => (<protocol.FileSpan>{ file: location.fileName, start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)), })).sort((a, b) => { if (a.file < b.file) { return -1; } else if (a.file > b.file) { return 1; } else { // reverse sort assuming no overlap if (a.start.line < b.start.line) { return 1; } else if (a.start.line > b.start.line) { return -1; } else { return b.start.offset - a.start.offset; } } }).reduce<protocol.SpanGroup[]>((accum: protocol.SpanGroup[], cur: protocol.FileSpan) => { let curFileAccum: protocol.SpanGroup; if (accum.length > 0) { curFileAccum = accum[accum.length - 1]; if (curFileAccum.file != cur.file) { curFileAccum = undefined; } } if (!curFileAccum) { curFileAccum = { file: cur.file, locs: [] }; accum.push(curFileAccum); } curFileAccum.locs.push({ start: cur.start, end: cur.end }); return accum; }, []); return { info: renameInfo, locs: bakedRenameLocs }; } private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody { // TODO: get all projects for this file; report refs for all projects deleting duplicates // can avoid duplicates by eliminating same ref file from subsequent projects const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { return undefined; } const nameInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { return undefined; } const displayString = ts.displayPartsToString(nameInfo.displayParts); const nameSpan = nameInfo.textSpan; const nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset; const nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); const bakedRefs: protocol.ReferencesResponseItem[] = references.map(ref => { const start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); const refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); const snap = compilerService.host.getScriptSnapshot(ref.fileName); const lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), isWriteAccess: ref.isWriteAccess }; }).sort(compareFileStart); return { refs: bakedRefs, symbolName: nameText, symbolStartOffset: nameColStart, symbolDisplayString: displayString }; } private openClientFile(fileName: string) { const file = ts.normalizePath(fileName); this.projectService.openClientFile(file); } private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!quickInfo) { return undefined; } const displayString = ts.displayPartsToString(quickInfo.displayParts); const docString = ts.displayPartsToString(quickInfo.documentation); return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, documentation: docString, }; } private getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); const endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); // TODO: avoid duplicate code (with formatonkey) const edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const formatOptions = this.projectService.getFormatCodeOptions(file); const edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); // Check whether we should auto-indent. This will be when // the position is on a line containing only whitespace. // This should leave the edits returned from // getFormattingEditsAfterKeytroke either empty or pertaining // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { const scriptInfo = compilerService.host.getScriptInfo(file); if (scriptInfo) { const lineInfo = scriptInfo.getLineInfo(line); if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { const lineText = lineInfo.leaf.text; if (lineText.search("\\S") < 0) { // TODO: get these options from host const editorOptions: ts.EditorOptions = { IndentSize: formatOptions.IndentSize, TabSize: formatOptions.TabSize, NewLineCharacter: "\n", ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, IndentStyle: ts.IndentStyle.Smart, }; const preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); let hasIndent = 0; let i: number, len: number; for (i = 0, len = lineText.length; i < len; i++) { if (lineText.charAt(i) == " ") { hasIndent++; } else if (lineText.charAt(i) == "\t") { hasIndent += editorOptions.TabSize; } else { break; } } // i points to the first non whitespace character if (preferredIndent !== hasIndent) { const firstNoWhiteSpacePosition = lineInfo.offset + i; edits.push({ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), newText: generateIndentString(preferredIndent, editorOptions) }); } } } } } if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] { if (!prefix) { prefix = ""; } const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const completions = compilerService.languageService.getCompletionsAtPosition(file, position); if (!completions) { return undefined; } return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { result.push(entry); } return result; }, []).sort((a, b) => a.name.localeCompare(b.name)); } private getCompletionEntryDetails(line: number, offset: number, entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); return entryNames.reduce((accum: protocol.CompletionEntryDetails[], entryName: string) => { const details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); } private getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const helpItems = compilerService.languageService.getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } const span = helpItems.applicableSpan; const result: protocol.SignatureHelpItems = { items: helpItems.items, applicableSpan: { start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, argumentCount: helpItems.argumentCount, }; return result; } private getDiagnostics(delay: number, fileNames: string[]) { const checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (project) { accum.push({ fileName, project }); } return accum; }, []); if (checkList.length > 0) { this.updateErrorCheck(checkList, this.changeSeq, (n) => n === this.changeSeq, delay); } } private change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (project) { const compilerService = project.compilerService; const start = compilerService.host.lineOffsetToPosition(file, line, offset); const end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); if (start >= 0) { compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, (n) => n === this.changeSeq); } } private reload(fileName: string, tempFileName: string, reqSeq = 0) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { this.changeSeq++; // make sure no changes happen before this one is finished project.compilerService.host.reloadScript(file, tmpfile, () => { this.output(undefined, CommandNames.Reload, reqSeq); }); } } private saveToTmp(fileName: string, tempFileName: string) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { project.compilerService.host.saveTo(file, tmpfile); } } private closeClientFile(fileName: string) { if (!fileName) { return; } const file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); } private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { if (!items) { return undefined; } const compilerService = project.compilerService; return items.map(item => ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(span => ({ start: compilerService.host.positionToLineOffset(fileName, span.start), end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) })), childItems: this.decorateNavigationBarItem(project, fileName, item.childItems) })); } private getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const items = compilerService.languageService.getNavigationBarItems(file); if (!items) { return undefined; } return this.decorateNavigationBarItem(project, fileName, items); } private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { return undefined; } return navItems.map((navItem) => { const start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); const end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); const bakedItem: protocol.NavtoItem = { name: navItem.name, kind: navItem.kind, file: navItem.fileName, start: start, end: end, }; if (navItem.kindModifiers && (navItem.kindModifiers != "")) { bakedItem.kindModifiers = navItem.kindModifiers; } if (navItem.matchKind !== "none") { bakedItem.matchKind = navItem.matchKind; } if (navItem.containerName && (navItem.containerName.length > 0)) { bakedItem.containerName = navItem.containerName; } if (navItem.containerKind && (navItem.containerKind.length > 0)) { bakedItem.containerKind = navItem.containerKind; } return bakedItem; }); } private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); if (!spans) { return undefined; } return spans.map(span => ({ start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) })); } getDiagnosticsForProject(delay: number, fileName: string) { const { configFileName, fileNames } = this.getProjectInfo(fileName, true); // No need to analyze lib.d.ts let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0); // Sort the file name list to make the recently touched files come first const highPriorityFiles: string[] = []; const mediumPriorityFiles: string[] = []; const lowPriorityFiles: string[] = []; const veryLowPriorityFiles: string[] = []; const normalizedFileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(normalizedFileName); for (const fileNameInProject of fileNamesInProject) { if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { const info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isOpen) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else lowPriorityFiles.push(fileNameInProject); } else mediumPriorityFiles.push(fileNameInProject); } } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { const checkList = fileNamesInProject.map<PendingErrorCheck>((fileName: string) => { const normalizedFileName = ts.normalizePath(fileName); return { fileName: normalizedFileName, project }; }); // Project level error analysis runs on background files too, therefore // doesn't require the file to be opened this.updateErrorCheck(checkList, this.changeSeq, (n) => n == this.changeSeq, delay, 200, /*requireOpen*/ false); } } getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); } exit() { } private handlers: Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = { [CommandNames.Exit]: () => { this.exit(); return { responseRequired: false}; }, [CommandNames.Definition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.TypeDefinition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.References]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.Rename]: (request: protocol.Request) => { const renameArgs = <protocol.RenameRequestArgs>request.arguments; return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true}; }, [CommandNames.Open]: (request: protocol.Request) => { const openArgs = <protocol.OpenRequestArgs>request.arguments; this.openClientFile(openArgs.file); return {responseRequired: false}; }, [CommandNames.Quickinfo]: (request: protocol.Request) => { const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true}; }, [CommandNames.Format]: (request: protocol.Request) => { const formatArgs = <protocol.FormatRequestArgs>request.arguments; return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true}; }, [CommandNames.Formatonkey]: (request: protocol.Request) => { const formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments; return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true}; }, [CommandNames.Completions]: (request: protocol.Request) => { const completionsArgs = <protocol.CompletionsRequestArgs>request.arguments; return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true}; }, [CommandNames.CompletionDetails]: (request: protocol.Request) => { const completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments; return {response: this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true}; }, [CommandNames.SignatureHelp]: (request: protocol.Request) => { const signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments; return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true}; }, [CommandNames.Geterr]: (request: protocol.Request) => { const geterrArgs = <protocol.GeterrRequestArgs>request.arguments; return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false}; }, [CommandNames.GeterrForProject]: (request: protocol.Request) => { const { file, delay } = <protocol.GeterrForProjectRequestArgs>request.arguments; return {response: this.getDiagnosticsForProject(delay, file), responseRequired: false}; }, [CommandNames.Change]: (request: protocol.Request) => { const changeArgs = <protocol.ChangeRequestArgs>request.arguments; this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); return {responseRequired: false}; }, [CommandNames.Configure]: (request: protocol.Request) => { const configureArgs = <protocol.ConfigureRequestArguments>request.arguments; this.projectService.setHostConfiguration(configureArgs); this.output(undefined, CommandNames.Configure, request.seq); return {responseRequired: false}; }, [CommandNames.Reload]: (request: protocol.Request) => { const reloadArgs = <protocol.ReloadRequestArgs>request.arguments; this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); return {responseRequired: false}; }, [CommandNames.Saveto]: (request: protocol.Request) => { const savetoArgs = <protocol.SavetoRequestArgs>request.arguments; this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return {responseRequired: false}; }, [CommandNames.Close]: (request: protocol.Request) => { const closeArgs = <protocol.FileRequestArgs>request.arguments; this.closeClientFile(closeArgs.file); return {responseRequired: false}; }, [CommandNames.Navto]: (request: protocol.Request) => { const navtoArgs = <protocol.NavtoRequestArgs>request.arguments; return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true}; }, [CommandNames.Brace]: (request: protocol.Request) => { const braceArguments = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true}; }, [CommandNames.NavBar]: (request: protocol.Request) => { const navBarArgs = <protocol.FileRequestArgs>request.arguments; return {response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true}; }, [CommandNames.Occurrences]: (request: protocol.Request) => { const { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getOccurrences(line, offset, fileName), responseRequired: true}; }, [CommandNames.DocumentHighlights]: (request: protocol.Request) => { const { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments; return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true}; }, [CommandNames.ProjectInfo]: (request: protocol.Request) => { const { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments; return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true}; }, [CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => { this.reloadProjects(); return {responseRequired: false}; } }; public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) { if (this.handlers[command]) { throw new Error(`Protocol handler already exists for command "${command}"`); } this.handlers[command] = handler; } public executeCommand(request: protocol.Request): {response?: any, responseRequired?: boolean} { const handler = this.handlers[request.command]; if (handler) { return handler(request); } else { this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return {responseRequired: false}; } } public onMessage(message: string) { let start: number[]; if (this.logger.isVerbose()) { this.logger.info("request: " + message); start = this.hrtime(); } let request: protocol.Request; try { request = <protocol.Request>JSON.parse(message); const {response, responseRequired} = this.executeCommand(request); if (this.logger.isVerbose()) { const elapsed = this.hrtime(start); const seconds = elapsed[0]; const nanoseconds = elapsed[1]; const elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; let leader = "Elapsed time (in milliseconds)"; if (!responseRequired) { leader = "Async elapsed time (in milliseconds)"; } this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); } else if (responseRequired) { this.output(undefined, request.command, request.seq, "No content available."); } } catch (err) { if (err instanceof OperationCanceledException) { // Handle cancellation exceptions } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message); } } } }
src/server/session.ts
1
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00021812471095472574, 0.00017118071264121681, 0.00016384154150728136, 0.00016892458370421082, 0.000007170081516960636 ]
{ "id": 3, "code_window": [ " }\n", "\n", " /**\n", " * Open file whose contents is managed by the client\n", " * @param filename is absolute pathname\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " * @param fileContent is a known version of the file content that is more up to date \n" ], "file_path": "src/server/editorServices.ts", "type": "add", "edit_start_line_idx": 1054 }
=================================================================== JsFile: m1.js mapUrl: /tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder/ref/m1.js.map sourceRoot: sources: ../../../ref/m1.ts =================================================================== ------------------------------------------------------------------- emittedFile:ref/m1.js sourceFile:../../../ref/m1.ts ------------------------------------------------------------------- >>>var m1_a1 = 10; 1 > 2 >^^^^ 3 > ^^^^^ 4 > ^^^ 5 > ^^ 6 > ^ 7 > ^^^^^^^^^^^^-> 1 > 2 >var 3 > m1_a1 4 > = 5 > 10 6 > ; 1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) 2 >Emitted(1, 5) Source(1, 5) + SourceIndex(0) 3 >Emitted(1, 10) Source(1, 10) + SourceIndex(0) 4 >Emitted(1, 13) Source(1, 13) + SourceIndex(0) 5 >Emitted(1, 15) Source(1, 15) + SourceIndex(0) 6 >Emitted(1, 16) Source(1, 16) + SourceIndex(0) --- >>>var m1_c1 = (function () { 1-> 2 >^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > 1->Emitted(2, 1) Source(2, 1) + SourceIndex(0) --- >>> function m1_c1() { 1->^^^^ 2 > ^^-> 1-> 1->Emitted(3, 5) Source(2, 1) + SourceIndex(0) name (m1_c1) --- >>> } 1->^^^^ 2 > ^ 3 > ^^^^^^^^^^^^^-> 1->class m1_c1 { > public m1_c1_p1: number; > 2 > } 1->Emitted(4, 5) Source(4, 1) + SourceIndex(0) name (m1_c1.constructor) 2 >Emitted(4, 6) Source(4, 2) + SourceIndex(0) name (m1_c1.constructor) --- >>> return m1_c1; 1->^^^^ 2 > ^^^^^^^^^^^^ 1-> 2 > } 1->Emitted(5, 5) Source(4, 1) + SourceIndex(0) name (m1_c1) 2 >Emitted(5, 17) Source(4, 2) + SourceIndex(0) name (m1_c1) --- >>>})(); 1 > 2 >^ 3 > 4 > ^^^^ 5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > 2 >} 3 > 4 > class m1_c1 { > public m1_c1_p1: number; > } 1 >Emitted(6, 1) Source(4, 1) + SourceIndex(0) name (m1_c1) 2 >Emitted(6, 2) Source(4, 2) + SourceIndex(0) name (m1_c1) 3 >Emitted(6, 2) Source(2, 1) + SourceIndex(0) 4 >Emitted(6, 6) Source(4, 2) + SourceIndex(0) --- >>>var m1_instance1 = new m1_c1(); 1-> 2 >^^^^ 3 > ^^^^^^^^^^^^ 4 > ^^^ 5 > ^^^^ 6 > ^^^^^ 7 > ^^ 8 > ^ 1-> > > 2 >var 3 > m1_instance1 4 > = 5 > new 6 > m1_c1 7 > () 8 > ; 1->Emitted(7, 1) Source(6, 1) + SourceIndex(0) 2 >Emitted(7, 5) Source(6, 5) + SourceIndex(0) 3 >Emitted(7, 17) Source(6, 17) + SourceIndex(0) 4 >Emitted(7, 20) Source(6, 20) + SourceIndex(0) 5 >Emitted(7, 24) Source(6, 24) + SourceIndex(0) 6 >Emitted(7, 29) Source(6, 29) + SourceIndex(0) 7 >Emitted(7, 31) Source(6, 31) + SourceIndex(0) 8 >Emitted(7, 32) Source(6, 32) + SourceIndex(0) --- >>>function m1_f1() { 1 > 2 >^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 1 >Emitted(8, 1) Source(7, 1) + SourceIndex(0) --- >>> return m1_instance1; 1->^^^^ 2 > ^^^^^^ 3 > ^ 4 > ^^^^^^^^^^^^ 5 > ^ 1->function m1_f1() { > 2 > return 3 > 4 > m1_instance1 5 > ; 1->Emitted(9, 5) Source(8, 5) + SourceIndex(0) name (m1_f1) 2 >Emitted(9, 11) Source(8, 11) + SourceIndex(0) name (m1_f1) 3 >Emitted(9, 12) Source(8, 12) + SourceIndex(0) name (m1_f1) 4 >Emitted(9, 24) Source(8, 24) + SourceIndex(0) name (m1_f1) 5 >Emitted(9, 25) Source(8, 25) + SourceIndex(0) name (m1_f1) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(10, 1) Source(9, 1) + SourceIndex(0) name (m1_f1) 2 >Emitted(10, 2) Source(9, 2) + SourceIndex(0) name (m1_f1) --- >>>//# sourceMappingURL=/tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder/ref/m1.js.map=================================================================== JsFile: m2.js mapUrl: /tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder_ref/m2.js.map sourceRoot: sources: ../../../outputdir_multifolder_ref/m2.ts =================================================================== ------------------------------------------------------------------- emittedFile:diskFile1.js sourceFile:../../../outputdir_multifolder_ref/m2.ts ------------------------------------------------------------------- >>>var m2_a1 = 10; 1 > 2 >^^^^ 3 > ^^^^^ 4 > ^^^ 5 > ^^ 6 > ^ 7 > ^^^^^^^^^^^^-> 1 > 2 >var 3 > m2_a1 4 > = 5 > 10 6 > ; 1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) 2 >Emitted(1, 5) Source(1, 5) + SourceIndex(0) 3 >Emitted(1, 10) Source(1, 10) + SourceIndex(0) 4 >Emitted(1, 13) Source(1, 13) + SourceIndex(0) 5 >Emitted(1, 15) Source(1, 15) + SourceIndex(0) 6 >Emitted(1, 16) Source(1, 16) + SourceIndex(0) --- >>>var m2_c1 = (function () { 1-> 2 >^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > 1->Emitted(2, 1) Source(2, 1) + SourceIndex(0) --- >>> function m2_c1() { 1->^^^^ 2 > ^^-> 1-> 1->Emitted(3, 5) Source(2, 1) + SourceIndex(0) name (m2_c1) --- >>> } 1->^^^^ 2 > ^ 3 > ^^^^^^^^^^^^^-> 1->class m2_c1 { > public m2_c1_p1: number; > 2 > } 1->Emitted(4, 5) Source(4, 1) + SourceIndex(0) name (m2_c1.constructor) 2 >Emitted(4, 6) Source(4, 2) + SourceIndex(0) name (m2_c1.constructor) --- >>> return m2_c1; 1->^^^^ 2 > ^^^^^^^^^^^^ 1-> 2 > } 1->Emitted(5, 5) Source(4, 1) + SourceIndex(0) name (m2_c1) 2 >Emitted(5, 17) Source(4, 2) + SourceIndex(0) name (m2_c1) --- >>>})(); 1 > 2 >^ 3 > 4 > ^^^^ 5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > 2 >} 3 > 4 > class m2_c1 { > public m2_c1_p1: number; > } 1 >Emitted(6, 1) Source(4, 1) + SourceIndex(0) name (m2_c1) 2 >Emitted(6, 2) Source(4, 2) + SourceIndex(0) name (m2_c1) 3 >Emitted(6, 2) Source(2, 1) + SourceIndex(0) 4 >Emitted(6, 6) Source(4, 2) + SourceIndex(0) --- >>>var m2_instance1 = new m2_c1(); 1-> 2 >^^^^ 3 > ^^^^^^^^^^^^ 4 > ^^^ 5 > ^^^^ 6 > ^^^^^ 7 > ^^ 8 > ^ 1-> > > 2 >var 3 > m2_instance1 4 > = 5 > new 6 > m2_c1 7 > () 8 > ; 1->Emitted(7, 1) Source(6, 1) + SourceIndex(0) 2 >Emitted(7, 5) Source(6, 5) + SourceIndex(0) 3 >Emitted(7, 17) Source(6, 17) + SourceIndex(0) 4 >Emitted(7, 20) Source(6, 20) + SourceIndex(0) 5 >Emitted(7, 24) Source(6, 24) + SourceIndex(0) 6 >Emitted(7, 29) Source(6, 29) + SourceIndex(0) 7 >Emitted(7, 31) Source(6, 31) + SourceIndex(0) 8 >Emitted(7, 32) Source(6, 32) + SourceIndex(0) --- >>>function m2_f1() { 1 > 2 >^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 1 >Emitted(8, 1) Source(7, 1) + SourceIndex(0) --- >>> return m2_instance1; 1->^^^^ 2 > ^^^^^^ 3 > ^ 4 > ^^^^^^^^^^^^ 5 > ^ 1->function m2_f1() { > 2 > return 3 > 4 > m2_instance1 5 > ; 1->Emitted(9, 5) Source(8, 5) + SourceIndex(0) name (m2_f1) 2 >Emitted(9, 11) Source(8, 11) + SourceIndex(0) name (m2_f1) 3 >Emitted(9, 12) Source(8, 12) + SourceIndex(0) name (m2_f1) 4 >Emitted(9, 24) Source(8, 24) + SourceIndex(0) name (m2_f1) 5 >Emitted(9, 25) Source(8, 25) + SourceIndex(0) name (m2_f1) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(10, 1) Source(9, 1) + SourceIndex(0) name (m2_f1) 2 >Emitted(10, 2) Source(9, 2) + SourceIndex(0) name (m2_f1) --- >>>//# sourceMappingURL=/tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder_ref/m2.js.map=================================================================== JsFile: test.js mapUrl: /tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder/test.js.map sourceRoot: sources: ../../test.ts =================================================================== ------------------------------------------------------------------- emittedFile:test.js sourceFile:../../test.ts ------------------------------------------------------------------- >>>/// <reference path='ref/m1.ts'/> 1 > 2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > 2 >/// <reference path='ref/m1.ts'/> 1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) 2 >Emitted(1, 34) Source(1, 34) + SourceIndex(0) --- >>>/// <reference path='../outputdir_multifolder_ref/m2.ts'/> 1-> 2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1-> > 2 >/// <reference path='../outputdir_multifolder_ref/m2.ts'/> 1->Emitted(2, 1) Source(2, 1) + SourceIndex(0) 2 >Emitted(2, 59) Source(2, 59) + SourceIndex(0) --- >>>var a1 = 10; 1 > 2 >^^^^ 3 > ^^ 4 > ^^^ 5 > ^^ 6 > ^ 7 > ^^^^^^^^^^^^-> 1 > > 2 >var 3 > a1 4 > = 5 > 10 6 > ; 1 >Emitted(3, 1) Source(3, 1) + SourceIndex(0) 2 >Emitted(3, 5) Source(3, 5) + SourceIndex(0) 3 >Emitted(3, 7) Source(3, 7) + SourceIndex(0) 4 >Emitted(3, 10) Source(3, 10) + SourceIndex(0) 5 >Emitted(3, 12) Source(3, 12) + SourceIndex(0) 6 >Emitted(3, 13) Source(3, 13) + SourceIndex(0) --- >>>var c1 = (function () { 1-> 2 >^^^^^^^^^^^^^^^^^^^^-> 1-> > 1->Emitted(4, 1) Source(4, 1) + SourceIndex(0) --- >>> function c1() { 1->^^^^ 2 > ^^-> 1-> 1->Emitted(5, 5) Source(4, 1) + SourceIndex(0) name (c1) --- >>> } 1->^^^^ 2 > ^ 3 > ^^^^^^^^^^-> 1->class c1 { > public p1: number; > 2 > } 1->Emitted(6, 5) Source(6, 1) + SourceIndex(0) name (c1.constructor) 2 >Emitted(6, 6) Source(6, 2) + SourceIndex(0) name (c1.constructor) --- >>> return c1; 1->^^^^ 2 > ^^^^^^^^^ 1-> 2 > } 1->Emitted(7, 5) Source(6, 1) + SourceIndex(0) name (c1) 2 >Emitted(7, 14) Source(6, 2) + SourceIndex(0) name (c1) --- >>>})(); 1 > 2 >^ 3 > 4 > ^^^^ 5 > ^^^^^^^^^^^^^^^^^^^^^-> 1 > 2 >} 3 > 4 > class c1 { > public p1: number; > } 1 >Emitted(8, 1) Source(6, 1) + SourceIndex(0) name (c1) 2 >Emitted(8, 2) Source(6, 2) + SourceIndex(0) name (c1) 3 >Emitted(8, 2) Source(4, 1) + SourceIndex(0) 4 >Emitted(8, 6) Source(6, 2) + SourceIndex(0) --- >>>var instance1 = new c1(); 1-> 2 >^^^^ 3 > ^^^^^^^^^ 4 > ^^^ 5 > ^^^^ 6 > ^^ 7 > ^^ 8 > ^ 1-> > > 2 >var 3 > instance1 4 > = 5 > new 6 > c1 7 > () 8 > ; 1->Emitted(9, 1) Source(8, 1) + SourceIndex(0) 2 >Emitted(9, 5) Source(8, 5) + SourceIndex(0) 3 >Emitted(9, 14) Source(8, 14) + SourceIndex(0) 4 >Emitted(9, 17) Source(8, 17) + SourceIndex(0) 5 >Emitted(9, 21) Source(8, 21) + SourceIndex(0) 6 >Emitted(9, 23) Source(8, 23) + SourceIndex(0) 7 >Emitted(9, 25) Source(8, 25) + SourceIndex(0) 8 >Emitted(9, 26) Source(8, 26) + SourceIndex(0) --- >>>function f1() { 1 > 2 >^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 1 >Emitted(10, 1) Source(9, 1) + SourceIndex(0) --- >>> return instance1; 1->^^^^ 2 > ^^^^^^ 3 > ^ 4 > ^^^^^^^^^ 5 > ^ 1->function f1() { > 2 > return 3 > 4 > instance1 5 > ; 1->Emitted(11, 5) Source(10, 5) + SourceIndex(0) name (f1) 2 >Emitted(11, 11) Source(10, 11) + SourceIndex(0) name (f1) 3 >Emitted(11, 12) Source(10, 12) + SourceIndex(0) name (f1) 4 >Emitted(11, 21) Source(10, 21) + SourceIndex(0) name (f1) 5 >Emitted(11, 22) Source(10, 22) + SourceIndex(0) name (f1) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(12, 1) Source(11, 1) + SourceIndex(0) name (f1) 2 >Emitted(12, 2) Source(11, 2) + SourceIndex(0) name (f1) --- >>>//# sourceMappingURL=/tests/cases/projects/outputdir_multifolder/mapFiles/outputdir_multifolder/test.js.map
tests/baselines/reference/project/mapRootAbsolutePathMultifolderNoOutdir/amd/mapRootAbsolutePathMultifolderNoOutdir.sourcemap.txt
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00017320341430604458, 0.00016928184777498245, 0.0001639833062654361, 0.00016981021326500922, 0.0000024461774046358187 ]
{ "id": 3, "code_window": [ " }\n", "\n", " /**\n", " * Open file whose contents is managed by the client\n", " * @param filename is absolute pathname\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " * @param fileContent is a known version of the file content that is more up to date \n" ], "file_path": "src/server/editorServices.ts", "type": "add", "edit_start_line_idx": 1054 }
/// <reference path="fourslash.ts" /> /////*start*/class Point implements /*IPointRef*/IPoint { //// getDist() { //// ssss; //// } ////}/*end*/ // Edit to invalidate the intial typeCheck state goTo.eof(); edit.insertLine(""); // Attempt to resolve a symbol goTo.marker("IPointRef"); verify.quickInfoIs(""); // not found // trigger typecheck after the partial resolve, we should see errors verify.errorExistsAfterMarker("IPointRef"); goTo.eof(); edit.insertLine(""); // one more time with full typecheck verify.errorExistsAfterMarker("IPointRef");
tests/cases/fourslash/typeCheckAfterResolve.ts
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.0001722399756545201, 0.00016889280232135206, 0.0001671746576903388, 0.0001672637736191973, 0.0000023670886548643466 ]
{ "id": 3, "code_window": [ " }\n", "\n", " /**\n", " * Open file whose contents is managed by the client\n", " * @param filename is absolute pathname\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " * @param fileContent is a known version of the file content that is more up to date \n" ], "file_path": "src/server/editorServices.ts", "type": "add", "edit_start_line_idx": 1054 }
var s="hello"; s.substring(0); s.substring(3,4); s.subby(12); // error unresolved String.fromCharCode(12); module M { export class C { } var a=new C[]; a.length; a.push(new C()); (new C()).prototype; }
tests/cases/compiler/libMembers.ts
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00017068698070943356, 0.00016951434372458607, 0.00016834170673973858, 0.00016951434372458607, 0.000001172636984847486 ]
{ "id": 4, "code_window": [ " */\n", " openClientFile(fileName: string) {\n", " this.openOrUpdateConfiguredProjectForFile(fileName);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " openClientFile(fileName: string, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1055 }
/// <reference path="..\compiler\commandLineParser.ts" /> /// <reference path="..\services\services.ts" /> /// <reference path="protocol.d.ts" /> /// <reference path="editorServices.ts" /> namespace ts.server { const spaceCache: string[] = []; interface StackTraceError extends Error { stack?: string; } export function generateSpaces(n: number): string { if (!spaceCache[n]) { let strBuilder = ""; for (let i = 0; i < n; i++) { strBuilder += " "; } spaceCache[n] = strBuilder; } return spaceCache[n]; } export function generateIndentString(n: number, editorOptions: EditorOptions): string { if (editorOptions.ConvertTabsToSpaces) { return generateSpaces(n); } else { let result = ""; for (let i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { result += "\t"; } for (let i = 0; i < n % editorOptions.TabSize; i++) { result += " "; } return result; } } interface FileStart { file: string; start: ILineInfo; } function compareNumber(a: number, b: number) { if (a < b) { return -1; } else if (a === b) { return 0; } else return 1; } function compareFileStart(a: FileStart, b: FileStart) { if (a.file < b.file) { return -1; } else if (a.file == b.file) { const n = compareNumber(a.start.line, b.start.line); if (n === 0) { return compareNumber(a.start.offset, b.start.offset); } else return n; } else { return 1; } } function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic) { return { start: project.compilerService.host.positionToLineOffset(fileName, diag.start), end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") }; } export interface PendingErrorCheck { fileName: string; project: Project; } function allEditsBeforePos(edits: ts.TextChange[], pos: number) { for (let i = 0, len = edits.length; i < len; i++) { if (ts.textSpanEnd(edits[i].span) >= pos) { return false; } } return true; } export namespace CommandNames { export const Brace = "brace"; export const Change = "change"; export const Close = "close"; export const Completions = "completions"; export const CompletionDetails = "completionEntryDetails"; export const Configure = "configure"; export const Definition = "definition"; export const Exit = "exit"; export const Format = "format"; export const Formatonkey = "formatonkey"; export const Geterr = "geterr"; export const GeterrForProject = "geterrForProject"; export const NavBar = "navbar"; export const Navto = "navto"; export const Occurrences = "occurrences"; export const DocumentHighlights = "documentHighlights"; export const Open = "open"; export const Quickinfo = "quickinfo"; export const References = "references"; export const Reload = "reload"; export const Rename = "rename"; export const Saveto = "saveto"; export const SignatureHelp = "signatureHelp"; export const TypeDefinition = "typeDefinition"; export const ProjectInfo = "projectInfo"; export const ReloadProjects = "reloadProjects"; export const Unknown = "unknown"; } namespace Errors { export const NoProject = new Error("No Project."); } export interface ServerHost extends ts.System { } export class Session { protected projectService: ProjectService; private pendingOperation = false; private fileHash: ts.Map<number> = {}; private nextFileId = 1; private errorTimer: any; /*NodeJS.Timer | number*/ private immediateId: any; private changeSeq = 0; constructor( private host: ServerHost, private byteLength: (buf: string, encoding?: string) => number, private hrtime: (start?: number[]) => number[], private logger: Logger ) { this.projectService = new ProjectService(host, logger, (eventName, project, fileName) => { this.handleEvent(eventName, project, fileName); }); } private handleEvent(eventName: string, project: Project, fileName: string) { if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); this.updateErrorCheck([{ fileName, project }], this.changeSeq, (n) => n === this.changeSeq, 100); } } public logError(err: Error, cmd: string) { const typedErr = <StackTraceError>err; let msg = "Exception on executing command " + cmd; if (typedErr.message) { msg += ":\n" + typedErr.message; if (typedErr.stack) { msg += "\n" + typedErr.stack; } } this.projectService.log(msg); } private sendLineToClient(line: string) { this.host.write(line + this.host.newLine); } public send(msg: protocol.Message) { const json = JSON.stringify(msg); if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + "\r\n\r\n" + json); } public event(info: any, eventName: string) { const ev: protocol.Event = { seq: 0, type: "event", event: eventName, body: info, }; this.send(ev); } private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) { const res: protocol.Response = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, success: !errorMsg, }; if (!errorMsg) { res.body = info; } else { res.message = errorMsg; } this.send(res); } public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) { this.response(body, commandName, requestSequence, errorMessage); } private semanticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSemanticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } } catch (err) { this.logError(err, "semantic check"); } } private syntacticCheck(file: string, project: Project) { try { const diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { const bakedDiags = diags.map((diag) => formatDiag(file, project, diag)); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); } } catch (err) { this.logError(err, "syntactic check"); } } private errorCheck(file: string, project: Project) { this.syntacticCheck(file, project); this.semanticCheck(file, project); } private reloadProjects() { this.projectService.reloadProjects(); } private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) { setTimeout(() => { if (matchSeq(seq)) { this.projectService.updateProjectStructure(); } }, ms); } private updateErrorCheck(checkList: PendingErrorCheck[], seq: number, matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200, requireOpen = true) { if (followMs > ms) { followMs = ms; } if (this.errorTimer) { clearTimeout(this.errorTimer); } if (this.immediateId) { clearImmediate(this.immediateId); this.immediateId = undefined; } let index = 0; const checkOne = () => { if (matchSeq(seq)) { const checkSpec = checkList[index++]; if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) { this.syntacticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = setImmediate(() => { this.semanticCheck(checkSpec.fileName, checkSpec.project); this.immediateId = undefined; if (checkList.length > index) { this.errorTimer = setTimeout(checkOne, followMs); } else { this.errorTimer = undefined; } }); } } }; if ((checkList.length > index) && (matchSeq(seq))) { this.errorTimer = setTimeout(checkOne, ms); } } private getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } return definitions.map(def => ({ file: def.fileName, start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) })); } private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); if (!occurrences) { return undefined; } return occurrences.map(occurrence => { const { fileName, isWriteAccess, textSpan } = occurrence; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, file: fileName, isWriteAccess }; }); } private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (!project) { throw Errors.NoProject; } const { compilerService } = project; const position = compilerService.host.lineOffsetToPosition(fileName, line, offset); const documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); if (!documentHighlights) { return undefined; } return documentHighlights.map(convertToDocumentHighlightsItem); function convertToDocumentHighlightsItem(documentHighlights: ts.DocumentHighlights): ts.server.protocol.DocumentHighlightsItem { const { fileName, highlightSpans } = documentHighlights; return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan: ts.HighlightSpan): ts.server.protocol.HighlightSpan { const { textSpan, kind } = highlightSpan; const start = compilerService.host.positionToLineOffset(fileName, textSpan.start); const end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start, end, kind }; } } } private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); const projectInfo: protocol.ProjectInfo = { configFileName: project.projectFilename }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); } return projectInfo; } private getRenameLocations(line: number, offset: number, fileName: string, findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const renameInfo = compilerService.languageService.getRenameInfo(file, position); if (!renameInfo) { return undefined; } if (!renameInfo.canRename) { return { info: renameInfo, locs: [] }; } const renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { return undefined; } const bakedRenameLocs = renameLocations.map(location => (<protocol.FileSpan>{ file: location.fileName, start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)), })).sort((a, b) => { if (a.file < b.file) { return -1; } else if (a.file > b.file) { return 1; } else { // reverse sort assuming no overlap if (a.start.line < b.start.line) { return 1; } else if (a.start.line > b.start.line) { return -1; } else { return b.start.offset - a.start.offset; } } }).reduce<protocol.SpanGroup[]>((accum: protocol.SpanGroup[], cur: protocol.FileSpan) => { let curFileAccum: protocol.SpanGroup; if (accum.length > 0) { curFileAccum = accum[accum.length - 1]; if (curFileAccum.file != cur.file) { curFileAccum = undefined; } } if (!curFileAccum) { curFileAccum = { file: cur.file, locs: [] }; accum.push(curFileAccum); } curFileAccum.locs.push({ start: cur.start, end: cur.end }); return accum; }, []); return { info: renameInfo, locs: bakedRenameLocs }; } private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody { // TODO: get all projects for this file; report refs for all projects deleting duplicates // can avoid duplicates by eliminating same ref file from subsequent projects const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { return undefined; } const nameInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { return undefined; } const displayString = ts.displayPartsToString(nameInfo.displayParts); const nameSpan = nameInfo.textSpan; const nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset; const nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); const bakedRefs: protocol.ReferencesResponseItem[] = references.map(ref => { const start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); const refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); const snap = compilerService.host.getScriptSnapshot(ref.fileName); const lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), isWriteAccess: ref.isWriteAccess }; }).sort(compareFileStart); return { refs: bakedRefs, symbolName: nameText, symbolStartOffset: nameColStart, symbolDisplayString: displayString }; } private openClientFile(fileName: string) { const file = ts.normalizePath(fileName); this.projectService.openClientFile(file); } private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!quickInfo) { return undefined; } const displayString = ts.displayPartsToString(quickInfo.displayParts); const docString = ts.displayPartsToString(quickInfo.documentation); return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, documentation: docString, }; } private getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); const endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); // TODO: avoid duplicate code (with formatonkey) const edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const formatOptions = this.projectService.getFormatCodeOptions(file); const edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); // Check whether we should auto-indent. This will be when // the position is on a line containing only whitespace. // This should leave the edits returned from // getFormattingEditsAfterKeytroke either empty or pertaining // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { const scriptInfo = compilerService.host.getScriptInfo(file); if (scriptInfo) { const lineInfo = scriptInfo.getLineInfo(line); if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { const lineText = lineInfo.leaf.text; if (lineText.search("\\S") < 0) { // TODO: get these options from host const editorOptions: ts.EditorOptions = { IndentSize: formatOptions.IndentSize, TabSize: formatOptions.TabSize, NewLineCharacter: "\n", ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, IndentStyle: ts.IndentStyle.Smart, }; const preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); let hasIndent = 0; let i: number, len: number; for (i = 0, len = lineText.length; i < len; i++) { if (lineText.charAt(i) == " ") { hasIndent++; } else if (lineText.charAt(i) == "\t") { hasIndent += editorOptions.TabSize; } else { break; } } // i points to the first non whitespace character if (preferredIndent !== hasIndent) { const firstNoWhiteSpacePosition = lineInfo.offset + i; edits.push({ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), newText: generateIndentString(preferredIndent, editorOptions) }); } } } } } if (!edits) { return undefined; } return edits.map((edit) => { return { start: compilerService.host.positionToLineOffset(file, edit.span.start), end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); } private getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] { if (!prefix) { prefix = ""; } const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const completions = compilerService.languageService.getCompletionsAtPosition(file, position); if (!completions) { return undefined; } return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { result.push(entry); } return result; }, []).sort((a, b) => a.name.localeCompare(b.name)); } private getCompletionEntryDetails(line: number, offset: number, entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); return entryNames.reduce((accum: protocol.CompletionEntryDetails[], entryName: string) => { const details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); } private getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const helpItems = compilerService.languageService.getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } const span = helpItems.applicableSpan; const result: protocol.SignatureHelpItems = { items: helpItems.items, applicableSpan: { start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, argumentCount: helpItems.argumentCount, }; return result; } private getDiagnostics(delay: number, fileNames: string[]) { const checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); if (project) { accum.push({ fileName, project }); } return accum; }, []); if (checkList.length > 0) { this.updateErrorCheck(checkList, this.changeSeq, (n) => n === this.changeSeq, delay); } } private change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (project) { const compilerService = project.compilerService; const start = compilerService.host.lineOffsetToPosition(file, line, offset); const end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); if (start >= 0) { compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, (n) => n === this.changeSeq); } } private reload(fileName: string, tempFileName: string, reqSeq = 0) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { this.changeSeq++; // make sure no changes happen before this one is finished project.compilerService.host.reloadScript(file, tmpfile, () => { this.output(undefined, CommandNames.Reload, reqSeq); }); } } private saveToTmp(fileName: string, tempFileName: string) { const file = ts.normalizePath(fileName); const tmpfile = ts.normalizePath(tempFileName); const project = this.projectService.getProjectForFile(file); if (project) { project.compilerService.host.saveTo(file, tmpfile); } } private closeClientFile(fileName: string) { if (!fileName) { return; } const file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); } private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { if (!items) { return undefined; } const compilerService = project.compilerService; return items.map(item => ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(span => ({ start: compilerService.host.positionToLineOffset(fileName, span.start), end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) })), childItems: this.decorateNavigationBarItem(project, fileName, item.childItems) })); } private getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const items = compilerService.languageService.getNavigationBarItems(file); if (!items) { return undefined; } return this.decorateNavigationBarItem(project, fileName, items); } private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { return undefined; } return navItems.map((navItem) => { const start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); const end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); const bakedItem: protocol.NavtoItem = { name: navItem.name, kind: navItem.kind, file: navItem.fileName, start: start, end: end, }; if (navItem.kindModifiers && (navItem.kindModifiers != "")) { bakedItem.kindModifiers = navItem.kindModifiers; } if (navItem.matchKind !== "none") { bakedItem.matchKind = navItem.matchKind; } if (navItem.containerName && (navItem.containerName.length > 0)) { bakedItem.containerName = navItem.containerName; } if (navItem.containerKind && (navItem.containerKind.length > 0)) { bakedItem.containerKind = navItem.containerKind; } return bakedItem; }); } private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] { const file = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(file); if (!project) { throw Errors.NoProject; } const compilerService = project.compilerService; const position = compilerService.host.lineOffsetToPosition(file, line, offset); const spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); if (!spans) { return undefined; } return spans.map(span => ({ start: compilerService.host.positionToLineOffset(file, span.start), end: compilerService.host.positionToLineOffset(file, span.start + span.length) })); } getDiagnosticsForProject(delay: number, fileName: string) { const { configFileName, fileNames } = this.getProjectInfo(fileName, true); // No need to analyze lib.d.ts let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0); // Sort the file name list to make the recently touched files come first const highPriorityFiles: string[] = []; const mediumPriorityFiles: string[] = []; const lowPriorityFiles: string[] = []; const veryLowPriorityFiles: string[] = []; const normalizedFileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(normalizedFileName); for (const fileNameInProject of fileNamesInProject) { if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { const info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isOpen) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else lowPriorityFiles.push(fileNameInProject); } else mediumPriorityFiles.push(fileNameInProject); } } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { const checkList = fileNamesInProject.map<PendingErrorCheck>((fileName: string) => { const normalizedFileName = ts.normalizePath(fileName); return { fileName: normalizedFileName, project }; }); // Project level error analysis runs on background files too, therefore // doesn't require the file to be opened this.updateErrorCheck(checkList, this.changeSeq, (n) => n == this.changeSeq, delay, 200, /*requireOpen*/ false); } } getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); } exit() { } private handlers: Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = { [CommandNames.Exit]: () => { this.exit(); return { responseRequired: false}; }, [CommandNames.Definition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.TypeDefinition]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.References]: (request: protocol.Request) => { const defArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true}; }, [CommandNames.Rename]: (request: protocol.Request) => { const renameArgs = <protocol.RenameRequestArgs>request.arguments; return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true}; }, [CommandNames.Open]: (request: protocol.Request) => { const openArgs = <protocol.OpenRequestArgs>request.arguments; this.openClientFile(openArgs.file); return {responseRequired: false}; }, [CommandNames.Quickinfo]: (request: protocol.Request) => { const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true}; }, [CommandNames.Format]: (request: protocol.Request) => { const formatArgs = <protocol.FormatRequestArgs>request.arguments; return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true}; }, [CommandNames.Formatonkey]: (request: protocol.Request) => { const formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments; return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true}; }, [CommandNames.Completions]: (request: protocol.Request) => { const completionsArgs = <protocol.CompletionsRequestArgs>request.arguments; return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true}; }, [CommandNames.CompletionDetails]: (request: protocol.Request) => { const completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments; return {response: this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true}; }, [CommandNames.SignatureHelp]: (request: protocol.Request) => { const signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments; return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true}; }, [CommandNames.Geterr]: (request: protocol.Request) => { const geterrArgs = <protocol.GeterrRequestArgs>request.arguments; return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false}; }, [CommandNames.GeterrForProject]: (request: protocol.Request) => { const { file, delay } = <protocol.GeterrForProjectRequestArgs>request.arguments; return {response: this.getDiagnosticsForProject(delay, file), responseRequired: false}; }, [CommandNames.Change]: (request: protocol.Request) => { const changeArgs = <protocol.ChangeRequestArgs>request.arguments; this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); return {responseRequired: false}; }, [CommandNames.Configure]: (request: protocol.Request) => { const configureArgs = <protocol.ConfigureRequestArguments>request.arguments; this.projectService.setHostConfiguration(configureArgs); this.output(undefined, CommandNames.Configure, request.seq); return {responseRequired: false}; }, [CommandNames.Reload]: (request: protocol.Request) => { const reloadArgs = <protocol.ReloadRequestArgs>request.arguments; this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); return {responseRequired: false}; }, [CommandNames.Saveto]: (request: protocol.Request) => { const savetoArgs = <protocol.SavetoRequestArgs>request.arguments; this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return {responseRequired: false}; }, [CommandNames.Close]: (request: protocol.Request) => { const closeArgs = <protocol.FileRequestArgs>request.arguments; this.closeClientFile(closeArgs.file); return {responseRequired: false}; }, [CommandNames.Navto]: (request: protocol.Request) => { const navtoArgs = <protocol.NavtoRequestArgs>request.arguments; return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true}; }, [CommandNames.Brace]: (request: protocol.Request) => { const braceArguments = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true}; }, [CommandNames.NavBar]: (request: protocol.Request) => { const navBarArgs = <protocol.FileRequestArgs>request.arguments; return {response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true}; }, [CommandNames.Occurrences]: (request: protocol.Request) => { const { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments; return {response: this.getOccurrences(line, offset, fileName), responseRequired: true}; }, [CommandNames.DocumentHighlights]: (request: protocol.Request) => { const { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments; return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true}; }, [CommandNames.ProjectInfo]: (request: protocol.Request) => { const { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments; return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true}; }, [CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => { this.reloadProjects(); return {responseRequired: false}; } }; public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) { if (this.handlers[command]) { throw new Error(`Protocol handler already exists for command "${command}"`); } this.handlers[command] = handler; } public executeCommand(request: protocol.Request): {response?: any, responseRequired?: boolean} { const handler = this.handlers[request.command]; if (handler) { return handler(request); } else { this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return {responseRequired: false}; } } public onMessage(message: string) { let start: number[]; if (this.logger.isVerbose()) { this.logger.info("request: " + message); start = this.hrtime(); } let request: protocol.Request; try { request = <protocol.Request>JSON.parse(message); const {response, responseRequired} = this.executeCommand(request); if (this.logger.isVerbose()) { const elapsed = this.hrtime(start); const seconds = elapsed[0]; const nanoseconds = elapsed[1]; const elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; let leader = "Elapsed time (in milliseconds)"; if (!responseRequired) { leader = "Async elapsed time (in milliseconds)"; } this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); } else if (responseRequired) { this.output(undefined, request.command, request.seq, "No content available."); } } catch (err) { if (err instanceof OperationCanceledException) { // Handle cancellation exceptions } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message); } } } }
src/server/session.ts
1
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.9979705214500427, 0.034183286130428314, 0.00016302807489410043, 0.0001736489066388458, 0.17572224140167236 ]
{ "id": 4, "code_window": [ " */\n", " openClientFile(fileName: string) {\n", " this.openOrUpdateConfiguredProjectForFile(fileName);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " openClientFile(fileName: string, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1055 }
tests/cases/compiler/objectLiteralIndexerErrors.ts(13,5): error TS2322: Type '{ [x: string]: A; [x: number]: A; 0: A; x: B; }' is not assignable to type '{ [s: string]: A; [n: number]: B; }'. Index signatures are incompatible. Type 'A' is not assignable to type 'B'. ==== tests/cases/compiler/objectLiteralIndexerErrors.ts (1 errors) ==== interface A { x: number; } interface B extends A { y: string; } var a: A; var b: B; var c: any; var o1: { [s: string]: A;[n: number]: B; } = { x: b, 0: a }; // both indexers are A ~~ !!! error TS2322: Type '{ [x: string]: A; [x: number]: A; 0: A; x: B; }' is not assignable to type '{ [s: string]: A; [n: number]: B; }'. !!! error TS2322: Index signatures are incompatible. !!! error TS2322: Type 'A' is not assignable to type 'B'. o1 = { x: c, 0: a }; // string indexer is any, number indexer is A
tests/baselines/reference/objectLiteralIndexerErrors.errors.txt
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00016774420510046184, 0.00016724674787838012, 0.0001666373573243618, 0.00016735868121031672, 4.5874816123614437e-7 ]
{ "id": 4, "code_window": [ " */\n", " openClientFile(fileName: string) {\n", " this.openOrUpdateConfiguredProjectForFile(fileName);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " openClientFile(fileName: string, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1055 }
=== tests/cases/compiler/cyclicGenericTypeInstantiation.ts === function foo<T>() { >foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) >T : Symbol(T, Decl(cyclicGenericTypeInstantiation.ts, 0, 13)) var z = foo<typeof y>(); >z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 1, 7)) >foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) var y: { >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) y2: typeof z >y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiation.ts, 2, 12)) >z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 1, 7)) }; return y; >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) } function bar<T>() { >bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) >T : Symbol(T, Decl(cyclicGenericTypeInstantiation.ts, 9, 13)) var z = bar<typeof y>(); >z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 10, 7)) >bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) var y: { >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) y2: typeof z; >y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiation.ts, 11, 12)) >z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 10, 7)) } return y; >y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) } var a = foo<number>(); >a : Symbol(a, Decl(cyclicGenericTypeInstantiation.ts, 17, 3)) >foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) var b = bar<number>(); >b : Symbol(b, Decl(cyclicGenericTypeInstantiation.ts, 18, 3)) >bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) a = b; >a : Symbol(a, Decl(cyclicGenericTypeInstantiation.ts, 17, 3)) >b : Symbol(b, Decl(cyclicGenericTypeInstantiation.ts, 18, 3))
tests/baselines/reference/cyclicGenericTypeInstantiation.symbols
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.0001761018647812307, 0.00017432559980079532, 0.0001720533473417163, 0.00017459622176829726, 0.000001556278220959939 ]
{ "id": 4, "code_window": [ " */\n", " openClientFile(fileName: string) {\n", " this.openOrUpdateConfiguredProjectForFile(fileName);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " openClientFile(fileName: string, fileContent?: string) {\n" ], "file_path": "src/server/editorServices.ts", "type": "replace", "edit_start_line_idx": 1055 }
{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/test.ts"],"names":["m1_c1","m1_c1.constructor","m1_f1","m2_c1","m2_c1.constructor","m2_f1","c1","c1.constructor","f1"],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAAA;IAEAC,CAACA;IAADD,YAACA;AAADA,CAACA,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACIE,MAAMA,CAACA,YAAYA,CAACA;AACxBA,CAACA;;ICRU,aAAK,GAAG,EAAE,CAAC;IACtB;QAAAC;QAEAC,CAACA;QAADD,YAACA;IAADA,CAACA,AAFD,IAEC;IAFY,aAAK,QAEjB,CAAA;IAEU,oBAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACIE,MAAMA,CAACA,oBAAYA,CAACA;IACxBA,CAACA;IAFe,aAAK,QAEpB,CAAA;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAAC;IAEAC,CAACA;IAADD,SAACA;AAADA,CAACA,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACIE,MAAMA,CAACA,SAASA,CAACA;AACrBA,CAACA"}
tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00016514572780579329, 0.00016514572780579329, 0.00016514572780579329, 0.00016514572780579329, 0 ]
{ "id": 9, "code_window": [ " const renameArgs = <protocol.RenameRequestArgs>request.arguments;\n", " return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true};\n", " },\n", " [CommandNames.Open]: (request: protocol.Request) => {\n", " const openArgs = <protocol.OpenRequestArgs>request.arguments;\n", " this.openClientFile(openArgs.file);\n", " return {responseRequired: false};\n", " },\n", " [CommandNames.Quickinfo]: (request: protocol.Request) => {\n", " const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.openClientFile(openArgs.file, openArgs.fileContent);\n" ], "file_path": "src/server/session.ts", "type": "replace", "edit_start_line_idx": 970 }
/** * Declaration module describing the TypeScript Server protocol */ declare namespace ts.server.protocol { /** * A TypeScript Server message */ export interface Message { /** * Sequence number of the message */ seq: number; /** * One of "request", "response", or "event" */ type: string; } /** * Client-initiated request message */ export interface Request extends Message { /** * The command to execute */ command: string; /** * Object containing arguments for the command */ arguments?: any; } /** * Request to reload the project structure for all the opened files */ export interface ReloadProjectsRequest extends Message { } /** * Server-initiated event message */ export interface Event extends Message { /** * Name of event */ event: string; /** * Event-specific information */ body?: any; } /** * Response by server to client request message. */ export interface Response extends Message { /** * Sequence number of the request message. */ request_seq: number; /** * Outcome of the request. */ success: boolean; /** * The command requested. */ command: string; /** * Contains error message if success === false. */ message?: string; /** * Contains message body if success === true. */ body?: any; } /** * Arguments for FileRequest messages. */ export interface FileRequestArgs { /** * The file for the request (absolute pathname required). */ file: string; } /** * Arguments for ProjectInfoRequest request. */ export interface ProjectInfoRequestArgs extends FileRequestArgs { /** * Indicate if the file name list of the project is needed */ needFileNameList: boolean; } /** * A request to get the project information of the current file */ export interface ProjectInfoRequest extends Request { arguments: ProjectInfoRequestArgs; } /** * Response message body for "projectInfo" request */ export interface ProjectInfo { /** * For configured project, this is the normalized path of the 'tsconfig.json' file * For inferred project, this is undefined */ configFileName: string; /** * The list of normalized file name in the project, including 'lib.d.ts' */ fileNames?: string[]; } /** * Response message for "projectInfo" request */ export interface ProjectInfoResponse extends Response { body?: ProjectInfo; } /** * Request whose sole parameter is a file name. */ export interface FileRequest extends Request { arguments: FileRequestArgs; } /** * Instances of this interface specify a location in a source file: * (file, line, character offset), where line and character offset are 1-based. */ export interface FileLocationRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). */ line: number; /** * The character offset (on the line) for the request (1-based). */ offset: number; } /** * A request whose arguments specify a file location (file, line, col). */ export interface FileLocationRequest extends FileRequest { arguments: FileLocationRequestArgs; } /** * Arguments in document highlight request; include: filesToSearch, file, * line, offset. */ export interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { /** * List of files to search for document highlights. */ filesToSearch: string[]; } /** * Go to definition request; value of command field is * "definition". Return response giving the file locations that * define the symbol found in file at location line, col. */ export interface DefinitionRequest extends FileLocationRequest { } /** * Go to type request; value of command field is * "typeDefinition". Return response giving the file locations that * define the type for the symbol found in file at location line, col. */ export interface TypeDefinitionRequest extends FileLocationRequest { } /** * Location in source code expressed as (one-based) line and character offset. */ export interface Location { line: number; offset: number; } /** * Object found in response messages defining a span of text in source code. */ export interface TextSpan { /** * First character of the definition. */ start: Location; /** * One character past last character of the definition. */ end: Location; } /** * Object found in response messages defining a span of text in a specific source file. */ export interface FileSpan extends TextSpan { /** * File containing text span. */ file: string; } /** * Definition response message. Gives text range for definition. */ export interface DefinitionResponse extends Response { body?: FileSpan[]; } /** * Definition response message. Gives text range for definition. */ export interface TypeDefinitionResponse extends Response { body?: FileSpan[]; } /** * Get occurrences request; value of command field is * "occurrences". Return response giving spans that are relevant * in the file at a given line and column. */ export interface OccurrencesRequest extends FileLocationRequest { } export interface OccurrencesResponseItem extends FileSpan { /** * True if the occurrence is a write location, false otherwise. */ isWriteAccess: boolean; } export interface OccurrencesResponse extends Response { body?: OccurrencesResponseItem[]; } /** * Get document highlights request; value of command field is * "documentHighlights". Return response giving spans that are relevant * in the file at a given line and column. */ export interface DocumentHighlightsRequest extends FileLocationRequest { arguments: DocumentHighlightsRequestArgs; } export interface HighlightSpan extends TextSpan { kind: string; } export interface DocumentHighlightsItem { /** * File containing highlight spans. */ file: string; /** * Spans to highlight in file. */ highlightSpans: HighlightSpan[]; } export interface DocumentHighlightsResponse extends Response { body?: DocumentHighlightsItem[]; } /** * Find references request; value of command field is * "references". Return response giving the file locations that * reference the symbol found in file at location line, col. */ export interface ReferencesRequest extends FileLocationRequest { } export interface ReferencesResponseItem extends FileSpan { /** Text of line containing the reference. Including this * with the response avoids latency of editor loading files * to show text of reference line (the server already has * loaded the referencing files). */ lineText: string; /** * True if reference is a write location, false otherwise. */ isWriteAccess: boolean; } /** * The body of a "references" response message. */ export interface ReferencesResponseBody { /** * The file locations referencing the symbol. */ refs: ReferencesResponseItem[]; /** * The name of the symbol. */ symbolName: string; /** * The start character offset of the symbol (on the line provided by the references request). */ symbolStartOffset: number; /** * The full display name of the symbol. */ symbolDisplayString: string; } /** * Response to "references" request. */ export interface ReferencesResponse extends Response { body?: ReferencesResponseBody; } export interface RenameRequestArgs extends FileLocationRequestArgs { findInComments?: boolean; findInStrings?: boolean; } /** * Rename request; value of command field is "rename". Return * response giving the file locations that reference the symbol * found in file at location line, col. Also return full display * name of the symbol so that client can print it unambiguously. */ export interface RenameRequest extends FileLocationRequest { arguments: RenameRequestArgs; } /** * Information about the item to be renamed. */ export interface RenameInfo { /** * True if item can be renamed. */ canRename: boolean; /** * Error message if item can not be renamed. */ localizedErrorMessage?: string; /** * Display name of the item to be renamed. */ displayName: string; /** * Full display name of item to be renamed. */ fullDisplayName: string; /** * The items's kind (such as 'className' or 'parameterName' or plain 'text'). */ kind: string; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; } /** * A group of text spans, all in 'file'. */ export interface SpanGroup { /** The file to which the spans apply */ file: string; /** The text spans in this group */ locs: TextSpan[]; } export interface RenameResponseBody { /** * Information about the item to be renamed. */ info: RenameInfo; /** * An array of span groups (one per file) that refer to the item to be renamed. */ locs: SpanGroup[]; } /** * Rename response message. */ export interface RenameResponse extends Response { body?: RenameResponseBody; } /** * Editor options */ export interface EditorOptions { /** Number of spaces for each tab. Default value is 4. */ tabSize?: number; /** Number of spaces to indent during formatting. Default value is 4. */ indentSize?: number; /** The new line character to be used. Default value is the OS line delimiter. */ newLineCharacter?: string; /** Whether tabs should be converted to spaces. Default value is true. */ convertTabsToSpaces?: boolean; } /** * Format options */ export interface FormatOptions extends EditorOptions { /** Defines space handling after a comma delimiter. Default value is true. */ insertSpaceAfterCommaDelimiter?: boolean; /** Defines space handling after a semicolon in a for statemen. Default value is true */ insertSpaceAfterSemicolonInForStatements?: boolean; /** Defines space handling after a binary operator. Default value is true. */ insertSpaceBeforeAndAfterBinaryOperators?: boolean; /** Defines space handling after keywords in control flow statement. Default value is true. */ insertSpaceAfterKeywordsInControlFlowStatements?: boolean; /** Defines space handling after function keyword for anonymous functions. Default value is false. */ insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; /** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */ insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; /** Defines space handling after opening and before closing non empty brackets. Default value is false. */ insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; /** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */ placeOpenBraceOnNewLineForFunctions?: boolean; /** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */ placeOpenBraceOnNewLineForControlBlocks?: boolean; /** Index operator */ [key: string] : string | number | boolean; } /** * Information found in a configure request. */ export interface ConfigureRequestArguments { /** * Information about the host, for example 'Emacs 24.4' or * 'Sublime Text version 3075' */ hostInfo?: string; /** * If present, tab settings apply only to this file. */ file?: string; /** * The format options to use during formatting and other code editing features. */ formatOptions?: FormatOptions; } /** * Configure request; value of command field is "configure". Specifies * host information, such as host type, tab size, and indent size. */ export interface ConfigureRequest extends Request { arguments: ConfigureRequestArguments; } /** * Response to "configure" request. This is just an acknowledgement, so * no body field is required. */ export interface ConfigureResponse extends Response { } /** * Information found in an "open" request. */ export interface OpenRequestArgs extends FileRequestArgs { } /** * Open request; value of command field is "open". Notify the * server that the client has file open. The server will not * monitor the filesystem for changes in this file and will assume * that the client is updating the server (using the change and/or * reload messages) when the file changes. Server does not currently * send a response to an open request. */ export interface OpenRequest extends Request { arguments: OpenRequestArgs; } /** * Exit request; value of command field is "exit". Ask the server process * to exit. */ export interface ExitRequest extends Request { } /** * Close request; value of command field is "close". Notify the * server that the client has closed a previously open file. If * file is still referenced by open files, the server will resume * monitoring the filesystem for changes to file. Server does not * currently send a response to a close request. */ export interface CloseRequest extends FileRequest { } /** * Quickinfo request; value of command field is * "quickinfo". Return response giving a quick type and * documentation string for the symbol found in file at location * line, col. */ export interface QuickInfoRequest extends FileLocationRequest { } /** * Body of QuickInfoResponse. */ export interface QuickInfoResponseBody { /** * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). */ kind: string; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; /** * Starting file location of symbol. */ start: Location; /** * One past last character of symbol. */ end: Location; /** * Type and kind of symbol. */ displayString: string; /** * Documentation associated with symbol. */ documentation: string; } /** * Quickinfo response message. */ export interface QuickInfoResponse extends Response { body?: QuickInfoResponseBody; } /** * Arguments for format messages. */ export interface FormatRequestArgs extends FileLocationRequestArgs { /** * Last line of range for which to format text in file. */ endLine: number; /** * Character offset on last line of range for which to format text in file. */ endOffset: number; } /** * Format request; value of command field is "format". Return * response giving zero or more edit instructions. The edit * instructions will be sorted in file order. Applying the edit * instructions in reverse to file will result in correctly * reformatted text. */ export interface FormatRequest extends FileLocationRequest { arguments: FormatRequestArgs; } /** * Object found in response messages defining an editing * instruction for a span of text in source code. The effect of * this instruction is to replace the text starting at start and * ending one character before end with newText. For an insertion, * the text span is empty. For a deletion, newText is empty. */ export interface CodeEdit { /** * First character of the text span to edit. */ start: Location; /** * One character past last character of the text span to edit. */ end: Location; /** * Replace the span defined above with this string (may be * the empty string). */ newText: string; } /** * Format and format on key response message. */ export interface FormatResponse extends Response { body?: CodeEdit[]; } /** * Arguments for format on key messages. */ export interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { /** * Key pressed (';', '\n', or '}'). */ key: string; } /** * Format on key request; value of command field is * "formatonkey". Given file location and key typed (as string), * return response giving zero or more edit instructions. The * edit instructions will be sorted in file order. Applying the * edit instructions in reverse to file will result in correctly * reformatted text. */ export interface FormatOnKeyRequest extends FileLocationRequest { arguments: FormatOnKeyRequestArgs; } /** * Arguments for completions messages. */ export interface CompletionsRequestArgs extends FileLocationRequestArgs { /** * Optional prefix to apply to possible completions. */ prefix?: string; } /** * Completions request; value of command field is "completions". * Given a file location (file, line, col) and a prefix (which may * be the empty string), return the possible completions that * begin with prefix. */ export interface CompletionsRequest extends FileLocationRequest { arguments: CompletionsRequestArgs; } /** * Arguments for completion details request. */ export interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { /** * Names of one or more entries for which to obtain details. */ entryNames: string[]; } /** * Completion entry details request; value of command field is * "completionEntryDetails". Given a file location (file, line, * col) and an array of completion entry names return more * detailed information for each completion entry. */ export interface CompletionDetailsRequest extends FileLocationRequest { arguments: CompletionDetailsRequestArgs; } /** * Part of a symbol description. */ export interface SymbolDisplayPart { /** * Text of an item describing the symbol. */ text: string; /** * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). */ kind: string; } /** * An item found in a completion response. */ export interface CompletionEntry { /** * The symbol's name. */ name: string; /** * The symbol's kind (such as 'className' or 'parameterName'). */ kind: string; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; /** * A string that is used for comparing completion items so that they can be ordered. This * is often the same as the name but may be different in certain circumstances. */ sortText: string; } /** * Additional completion entry details, available on demand */ export interface CompletionEntryDetails { /** * The symbol's name. */ name: string; /** * The symbol's kind (such as 'className' or 'parameterName'). */ kind: string; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; /** * Display parts of the symbol (similar to quick info). */ displayParts: SymbolDisplayPart[]; /** * Documentation strings for the symbol. */ documentation: SymbolDisplayPart[]; } export interface CompletionsResponse extends Response { body?: CompletionEntry[]; } export interface CompletionDetailsResponse extends Response { body?: CompletionEntryDetails[]; } /** * Signature help information for a single parameter */ export interface SignatureHelpParameter { /** * The parameter's name */ name: string; /** * Documentation of the parameter. */ documentation: SymbolDisplayPart[]; /** * Display parts of the parameter. */ displayParts: SymbolDisplayPart[]; /** * Whether the parameter is optional or not. */ isOptional: boolean; } /** * Represents a single signature to show in signature help. */ export interface SignatureHelpItem { /** * Whether the signature accepts a variable number of arguments. */ isVariadic: boolean; /** * The prefix display parts. */ prefixDisplayParts: SymbolDisplayPart[]; /** * The suffix disaply parts. */ suffixDisplayParts: SymbolDisplayPart[]; /** * The separator display parts. */ separatorDisplayParts: SymbolDisplayPart[]; /** * The signature helps items for the parameters. */ parameters: SignatureHelpParameter[]; /** * The signature's documentation */ documentation: SymbolDisplayPart[]; } /** * Signature help items found in the response of a signature help request. */ export interface SignatureHelpItems { /** * The signature help items. */ items: SignatureHelpItem[]; /** * The span for which signature help should appear on a signature */ applicableSpan: TextSpan; /** * The item selected in the set of available help items. */ selectedItemIndex: number; /** * The argument selected in the set of parameters. */ argumentIndex: number; /** * The argument count */ argumentCount: number; } /** * Arguments of a signature help request. */ export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { } /** * Signature help request; value of command field is "signatureHelp". * Given a file location (file, line, col), return the signature * help. */ export interface SignatureHelpRequest extends FileLocationRequest { arguments: SignatureHelpRequestArgs; } /** * Repsonse object for a SignatureHelpRequest. */ export interface SignatureHelpResponse extends Response { body?: SignatureHelpItems; } /** * Arguments for GeterrForProject request. */ export interface GeterrForProjectRequestArgs { /** * the file requesting project error list */ file: string; /** * Delay in milliseconds to wait before starting to compute * errors for the files in the file list */ delay: number; } /** * GeterrForProjectRequest request; value of command field is * "geterrForProject". It works similarly with 'Geterr', only * it request for every file in this project. */ export interface GeterrForProjectRequest extends Request { arguments: GeterrForProjectRequestArgs; } /** * Arguments for geterr messages. */ export interface GeterrRequestArgs { /** * List of file names for which to compute compiler errors. * The files will be checked in list order. */ files: string[]; /** * Delay in milliseconds to wait before starting to compute * errors for the files in the file list */ delay: number; } /** * Geterr request; value of command field is "geterr". Wait for * delay milliseconds and then, if during the wait no change or * reload messages have arrived for the first file in the files * list, get the syntactic errors for the file, field requests, * and then get the semantic errors for the file. Repeat with a * smaller delay for each subsequent file on the files list. Best * practice for an editor is to send a file list containing each * file that is currently visible, in most-recently-used order. */ export interface GeterrRequest extends Request { arguments: GeterrRequestArgs; } /** * Item of diagnostic information found in a DiagnosticEvent message. */ export interface Diagnostic { /** * Starting file location at which text appies. */ start: Location; /** * The last file location at which the text applies. */ end: Location; /** * Text of diagnostic message. */ text: string; } export interface DiagnosticEventBody { /** * The file for which diagnostic information is reported. */ file: string; /** * An array of diagnostic information items. */ diagnostics: Diagnostic[]; } /** * Event message for "syntaxDiag" and "semanticDiag" event types. * These events provide syntactic and semantic errors for a file. */ export interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; } /** * Arguments for reload request. */ export interface ReloadRequestArgs extends FileRequestArgs { /** * Name of temporary file from which to reload file * contents. May be same as file. */ tmpfile: string; } /** * Reload request message; value of command field is "reload". * Reload contents of file with name given by the 'file' argument * from temporary file with name given by the 'tmpfile' argument. * The two names can be identical. */ export interface ReloadRequest extends FileRequest { arguments: ReloadRequestArgs; } /** * Response to "reload" request. This is just an acknowledgement, so * no body field is required. */ export interface ReloadResponse extends Response { } /** * Arguments for saveto request. */ export interface SavetoRequestArgs extends FileRequestArgs { /** * Name of temporary file into which to save server's view of * file contents. */ tmpfile: string; } /** * Saveto request message; value of command field is "saveto". * For debugging purposes, save to a temporaryfile (named by * argument 'tmpfile') the contents of file named by argument * 'file'. The server does not currently send a response to a * "saveto" request. */ export interface SavetoRequest extends FileRequest { arguments: SavetoRequestArgs; } /** * Arguments for navto request message. */ export interface NavtoRequestArgs extends FileRequestArgs { /** * Search term to navigate to from current location; term can * be '.*' or an identifier prefix. */ searchValue: string; /** * Optional limit on the number of items to return. */ maxResultCount?: number; } /** * Navto request message; value of command field is "navto". * Return list of objects giving file locations and symbols that * match the search term given in argument 'searchTerm'. The * context for the search is given by the named file. */ export interface NavtoRequest extends FileRequest { arguments: NavtoRequestArgs; } /** * An item found in a navto response. */ export interface NavtoItem { /** * The symbol's name. */ name: string; /** * The symbol's kind (such as 'className' or 'parameterName'). */ kind: string; /** * exact, substring, or prefix. */ matchKind?: string; /** * If this was a case sensitive or insensitive match. */ isCaseSensitive?: boolean; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers?: string; /** * The file in which the symbol is found. */ file: string; /** * The location within file at which the symbol is found. */ start: Location; /** * One past the last character of the symbol. */ end: Location; /** * Name of symbol's container symbol (if any); for example, * the class name if symbol is a class member. */ containerName?: string; /** * Kind of symbol's container symbol (if any). */ containerKind?: string; } /** * Navto response message. Body is an array of navto items. Each * item gives a symbol that matched the search term. */ export interface NavtoResponse extends Response { body?: NavtoItem[]; } /** * Arguments for change request message. */ export interface ChangeRequestArgs extends FormatRequestArgs { /** * Optional string to insert at location (file, line, offset). */ insertString?: string; } /** * Change request message; value of command field is "change". * Update the server's view of the file named by argument 'file'. * Server does not currently send a response to a change request. */ export interface ChangeRequest extends FileLocationRequest { arguments: ChangeRequestArgs; } /** * Response to "brace" request. */ export interface BraceResponse extends Response { body?: TextSpan[]; } /** * Brace matching request; value of command field is "brace". * Return response giving the file locations of matching braces * found in file at location line, offset. */ export interface BraceRequest extends FileLocationRequest { } /** * NavBar itesm request; value of command field is "navbar". * Return response giving the list of navigation bar entries * extracted from the requested file. */ export interface NavBarRequest extends FileRequest { } export interface NavigationBarItem { /** * The item's display text. */ text: string; /** * The symbol's kind (such as 'className' or 'parameterName'). */ kind: string; /** * Optional modifiers for the kind (such as 'public'). */ kindModifiers?: string; /** * The definition locations of the item. */ spans: TextSpan[]; /** * Optional children. */ childItems?: NavigationBarItem[]; } export interface NavBarResponse extends Response { body?: NavigationBarItem[]; } }
src/server/protocol.d.ts
1
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.0034195922780781984, 0.0003502310428302735, 0.00016298658738378435, 0.00017107103485614061, 0.0004881772038061172 ]
{ "id": 9, "code_window": [ " const renameArgs = <protocol.RenameRequestArgs>request.arguments;\n", " return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true};\n", " },\n", " [CommandNames.Open]: (request: protocol.Request) => {\n", " const openArgs = <protocol.OpenRequestArgs>request.arguments;\n", " this.openClientFile(openArgs.file);\n", " return {responseRequired: false};\n", " },\n", " [CommandNames.Quickinfo]: (request: protocol.Request) => {\n", " const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.openClientFile(openArgs.file, openArgs.fileContent);\n" ], "file_path": "src/server/session.ts", "type": "replace", "edit_start_line_idx": 970 }
declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; } declare var m1_instance1: m1_c1; declare function m1_f1(): m1_c1; declare var a1: number; declare class c1 { p1: number; } declare var instance1: c1; declare function f1(): c1;
tests/baselines/reference/project/mapRootRelativePathSimpleSpecifyOutputFile/node/bin/test.d.ts
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00017204874893650413, 0.00017098747775889933, 0.0001699261920293793, 0.00017098747775889933, 0.0000010612784535624087 ]
{ "id": 9, "code_window": [ " const renameArgs = <protocol.RenameRequestArgs>request.arguments;\n", " return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true};\n", " },\n", " [CommandNames.Open]: (request: protocol.Request) => {\n", " const openArgs = <protocol.OpenRequestArgs>request.arguments;\n", " this.openClientFile(openArgs.file);\n", " return {responseRequired: false};\n", " },\n", " [CommandNames.Quickinfo]: (request: protocol.Request) => {\n", " const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.openClientFile(openArgs.file, openArgs.fileContent);\n" ], "file_path": "src/server/session.ts", "type": "replace", "edit_start_line_idx": 970 }
{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":["m2_c1","m2_c1.constructor","m2_f1"],"mappings":"AAAW,aAAK,GAAG,EAAE,CAAC;AACtB;IAAAA;IAEAC,CAACA;IAADD,YAACA;AAADA,CAACA,AAFD,IAEC;AAFY,aAAK,QAEjB,CAAA;AAEU,oBAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACIE,MAAMA,CAACA,oBAAYA,CAACA;AACxBA,CAACA;AAFe,aAAK,QAEpB,CAAA"}
tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.00016753814998082817, 0.00016753814998082817, 0.00016753814998082817, 0.00016753814998082817, 0 ]
{ "id": 9, "code_window": [ " const renameArgs = <protocol.RenameRequestArgs>request.arguments;\n", " return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true};\n", " },\n", " [CommandNames.Open]: (request: protocol.Request) => {\n", " const openArgs = <protocol.OpenRequestArgs>request.arguments;\n", " this.openClientFile(openArgs.file);\n", " return {responseRequired: false};\n", " },\n", " [CommandNames.Quickinfo]: (request: protocol.Request) => {\n", " const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.openClientFile(openArgs.file, openArgs.fileContent);\n" ], "file_path": "src/server/session.ts", "type": "replace", "edit_start_line_idx": 970 }
//// [typeParametersInStaticMethods.ts] class foo<T> { static M(x: (x: T) => { x: { y: T } }) { } } //// [typeParametersInStaticMethods.js] var foo = (function () { function foo() { } foo.M = function (x) { }; return foo; })();
tests/baselines/reference/typeParametersInStaticMethods.js
0
https://github.com/microsoft/TypeScript/commit/f92d24188826e4e132f935a5c8571f0ebab53153
[ 0.0001746537018334493, 0.00017297343583777547, 0.0001712931552901864, 0.00017297343583777547, 0.0000016802732716314495 ]
{ "id": 0, "code_window": [ "\n", "The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc), SystemJS initialization, and dynamic import fallback. If you have a strict CSP policy requirement, you will need to [add the corresponding hashes to your `script-src` list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script):\n", "\n", "- `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=`\n", "- `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=`\n", "- `sha256-T9h4ixy0FtNsCwAyTfBtIY6uV5ZhMeNQIlL42GAKEME=`\n", "\n", "These values (without the `sha256-` prefix) can also be retrieved via\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "- `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=`\n", "- `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=`\n", "- `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=`\n" ], "file_path": "packages/plugin-legacy/README.md", "type": "replace", "edit_start_line_idx": 167 }
# @vitejs/plugin-legacy [![npm](https://img.shields.io/npm/v/@vitejs/plugin-legacy.svg)](https://npmjs.com/package/@vitejs/plugin-legacy) **Note: this plugin requires `vite@^2.0.0`**. Vite's default browser support baseline is [Native ESM](https://caniuse.com/es6-module). This plugin provides support for legacy browsers that do not support native ESM. By default, this plugin will: - Generate a corresponding legacy chunk for every chunk in the final bundle, transformed with [@babel/preset-env](https://babeljs.io/docs/en/babel-preset-env) and emitted as [SystemJS modules](https://github.com/systemjs/systemjs) (code splitting is still supported!). - Generate a polyfill chunk including SystemJS runtime, and any necessary polyfills determined by specified browser targets and **actual usage** in the bundle. - Inject `<script nomodule>` tags into generated HTML to conditionally load the polyfills and legacy bundle only in browsers without native ESM support. - Inject the `import.meta.env.LEGACY` env variable, which will only be `true` in the legacy production build, and `false` in all other cases. ## Usage ```js // vite.config.js import legacy from '@vitejs/plugin-legacy' export default { plugins: [ legacy({ targets: ['defaults', 'not IE 11'] }) ] } ``` When targeting IE11, you also need `regenerator-runtime`: ```js // vite.config.js import legacy from '@vitejs/plugin-legacy' export default { plugins: [ legacy({ targets: ['ie >= 11'], additionalLegacyPolyfills: ['regenerator-runtime/runtime'] }) ] } ``` ## Options ### `targets` - **Type:** `string | string[] | { [key: string]: string }` - **Default:** `'defaults'` If explicitly set, it's passed on to [`@babel/preset-env`](https://babeljs.io/docs/en/babel-preset-env#targets). The query is also [Browserslist compatible](https://github.com/browserslist/browserslist). The default value, `'defaults'`, is what is recommended by Browserslist. See [Browserslist Best Practices](https://github.com/browserslist/browserslist#best-practices) for more details. ### `polyfills` - **Type:** `boolean | string[]` - **Default:** `true` By default, a polyfills chunk is generated based on the target browser ranges and actual usage in the final bundle (detected via `@babel/preset-env`'s `useBuiltIns: 'usage'`). Set to a list of strings to explicitly control which polyfills to include. See [Polyfill Specifiers](#polyfill-specifiers) for details. Set to `false` to avoid generating polyfills and handle it yourself (will still generate legacy chunks with syntax transformations). ### `additionalLegacyPolyfills` - **Type:** `string[]` Add custom imports to the legacy polyfills chunk. Since the usage-based polyfill detection only covers ES language features, it may be necessary to manually specify additional DOM API polyfills using this option. Note: if additional polyfills are needed for both the modern and legacy chunks, they can simply be imported in the application source code. ### `ignoreBrowserslistConfig` - **Type:** `boolean` - **Default:** `false` `@babel/preset-env` automatically detects [`browserslist` config sources](https://github.com/browserslist/browserslist#browserslist-): - `browserslist` field in `package.json` - `.browserslistrc` file in cwd. Set to `false` to ignore these sources. ### `modernPolyfills` - **Type:** `boolean | string[]` - **Default:** `false` Defaults to `false`. Enabling this option will generate a separate polyfills chunk for the modern build (targeting browsers with [native ESM support](https://caniuse.com/es6-module)). Set to a list of strings to explicitly control which polyfills to include. See [Polyfill Specifiers](#polyfill-specifiers) for details. Note it is **not recommended** to use the `true` value (which uses auto-detection) because `core-js@3` is very aggressive in polyfill inclusions due to all the bleeding edge features it supports. Even when targeting native ESM support, it injects 15kb of polyfills! If you don't have hard reliance on bleeding edge runtime features, it is not that hard to avoid having to use polyfills in the modern build altogether. Alternatively, consider using an on-demand service like [Polyfill.io](https://polyfill.io/v3/) to only inject necessary polyfills based on actual browser user-agents (most modern browsers will need nothing!). ### `renderLegacyChunks` - **Type:** `boolean` - **Default:** `true` Set to `false` to disable legacy chunks. This is only useful if you are using `modernPolyfills`, which essentially allows you to use this plugin for injecting polyfills to the modern build only: ```js import legacy from '@vitejs/plugin-legacy' export default { plugins: [ legacy({ modernPolyfills: [ /* ... */ ], renderLegacyChunks: false }) ] } ``` ### `externalSystemJS` - **Type:** `boolean` - **Default:** `false` Defaults to `false`. Enabling this option will exclude `systemjs/dist/s.min.js` inside polyfills-legacy chunk. ## Dynamic Import The legacy plugin offers a way to use native `import()` in the modern build while falling back to the legacy build in browsers with native ESM but without dynamic import support (e.g. Legacy Edge). This feature works by injecting a runtime check and loading the legacy bundle with SystemJs runtime if needed. There are the following drawbacks: - Modern bundle is downloaded in all ESM browsers - Modern bundle throws `SyntaxError` in browsers without dynamic import ## Polyfill Specifiers Polyfill specifier strings for `polyfills` and `modernPolyfills` can be either of the following: - Any [`core-js` 3 sub import paths](https://unpkg.com/browse/[email protected]/) - e.g. `es/map` will import `core-js/es/map` - Any [individual `core-js` 3 modules](https://unpkg.com/browse/[email protected]/modules/) - e.g. `es.array.iterator` will import `core-js/modules/es.array.iterator.js` **Example** ```js import legacy from '@vitejs/plugin-legacy' export default { plugins: [ legacy({ polyfills: ['es.promise.finally', 'es/map', 'es/set'], modernPolyfills: ['es.promise.finally'] }) ] } ``` ## Content Security Policy The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc), SystemJS initialization, and dynamic import fallback. If you have a strict CSP policy requirement, you will need to [add the corresponding hashes to your `script-src` list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script): - `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=` - `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=` - `sha256-T9h4ixy0FtNsCwAyTfBtIY6uV5ZhMeNQIlL42GAKEME=` These values (without the `sha256-` prefix) can also be retrieved via ```js const { cspHashes } = require('@vitejs/plugin-legacy') ``` When using the `regenerator-runtime` polyfill, it will attempt to use the `globalThis` object to register itself. If `globalThis` is not available (it is [fairly new](https://caniuse.com/?search=globalThis) and not widely supported, including IE 11), it attempts to perform dynamic `Function(...)` call which violates the CSP. To avoid dynamic `eval` in the absence of `globalThis` consider adding `core-js/proposals/global-this` to `additionalLegacyPolyfills` to define it. ## References - [Vue CLI modern mode](https://cli.vuejs.org/guide/browser-compatibility.html#modern-mode) - [Using Native JavaScript Modules in Production Today](https://philipwalton.com/articles/using-native-javascript-modules-in-production-today/) - [rollup-native-modules-boilerplate](https://github.com/philipwalton/rollup-native-modules-boilerplate)
packages/plugin-legacy/README.md
1
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.9929621815681458, 0.05249673128128052, 0.0001595066860318184, 0.0001713274687062949, 0.22166994214057922 ]
{ "id": 0, "code_window": [ "\n", "The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc), SystemJS initialization, and dynamic import fallback. If you have a strict CSP policy requirement, you will need to [add the corresponding hashes to your `script-src` list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script):\n", "\n", "- `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=`\n", "- `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=`\n", "- `sha256-T9h4ixy0FtNsCwAyTfBtIY6uV5ZhMeNQIlL42GAKEME=`\n", "\n", "These values (without the `sha256-` prefix) can also be retrieved via\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "- `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=`\n", "- `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=`\n", "- `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=`\n" ], "file_path": "packages/plugin-legacy/README.md", "type": "replace", "edit_start_line_idx": 167 }
<template> <h2>Custom Element</h2> <button class="custom-element" type="button" @click="state.count++"> {{ label }}: {{ state.count }} </button> </template> <script setup> import { reactive, onBeforeMount } from 'vue' defineProps({ label: String }) const state = reactive({ count: 0 }) onBeforeMount(() => { state.count = 1 }) </script> <style scoped> .custom-element { color: green; } </style>
packages/playground/vue/CustomElement.ce.vue
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00017225574993062764, 0.00016833958216011524, 0.0001659257832216099, 0.0001668372133281082, 0.0000027940359359490685 ]
{ "id": 0, "code_window": [ "\n", "The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc), SystemJS initialization, and dynamic import fallback. If you have a strict CSP policy requirement, you will need to [add the corresponding hashes to your `script-src` list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script):\n", "\n", "- `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=`\n", "- `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=`\n", "- `sha256-T9h4ixy0FtNsCwAyTfBtIY6uV5ZhMeNQIlL42GAKEME=`\n", "\n", "These values (without the `sha256-` prefix) can also be retrieved via\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "- `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=`\n", "- `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=`\n", "- `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=`\n" ], "file_path": "packages/plugin-legacy/README.md", "type": "replace", "edit_start_line_idx": 167 }
{ "compilerOptions": { "module": "esnext", "lib": ["es2017", "dom", "dom.iterable"], "declaration": true, "emitDeclarationOnly": true, "outDir": "./types", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", "allowSyntheticDefaultImports": true, "experimentalDecorators": true, "forceConsistentCasingInFileNames": true, "useDefineForClassFields": false }, "include": ["src/**/*.ts"], "references": [{ "path": "./tsconfig.node.json" }] }
packages/create-vite/template-lit-ts/tsconfig.json
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.0001701763685559854, 0.00016730539209675044, 0.0001655646483413875, 0.0001661751593928784, 0.000002045329665634199 ]
{ "id": 0, "code_window": [ "\n", "The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc), SystemJS initialization, and dynamic import fallback. If you have a strict CSP policy requirement, you will need to [add the corresponding hashes to your `script-src` list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script):\n", "\n", "- `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=`\n", "- `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=`\n", "- `sha256-T9h4ixy0FtNsCwAyTfBtIY6uV5ZhMeNQIlL42GAKEME=`\n", "\n", "These values (without the `sha256-` prefix) can also be retrieved via\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "- `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=`\n", "- `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=`\n", "- `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=`\n" ], "file_path": "packages/plugin-legacy/README.md", "type": "replace", "edit_start_line_idx": 167 }
import { n } from '../nested/shared' console.log('foo' + n) export const msg = 'Foo view'
packages/playground/dynamic-import/views/foo.js
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00016945663082879037, 0.00016945663082879037, 0.00016945663082879037, 0.00016945663082879037, 0 ]
{ "id": 1, "code_window": [ "const legacyPolyfillId = 'vite-legacy-polyfill'\n", "const legacyEntryId = 'vite-legacy-entry'\n", "const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`\n", "const dynamicFallbackInlineCode = `!function(){try{new Function(\"m\",\"return import(m)\")}catch(o){console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();`\n", "\n", "const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`\n", "\n", "const legacyEnvVarMarker = `__VITE_IS_LEGACY__`\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "const detectDynamicImportVarName = '__vite_is_dynamic_import_support'\n", "const detectDynamicImportVarInitCode = `var ${detectDynamicImportVarName}=false;`\n", "const detectDynamicImportCode = `try{import(\"_\").catch(()=>1);}catch(e){}window.${detectDynamicImportVarName}=true;`\n", "const dynamicFallbackInlineCode = `!function(){if(window.${detectDynamicImportVarName})return;console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "replace", "edit_start_line_idx": 20 }
// @ts-check const path = require('path') const { createHash } = require('crypto') const { build } = require('vite') const MagicString = require('magic-string').default // lazy load babel since it's not used during dev let babel /** * @return {import('@babel/standalone')} */ const loadBabel = () => babel || (babel = require('@babel/standalone')) // https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc // DO NOT ALTER THIS CONTENT const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();` const legacyPolyfillId = 'vite-legacy-polyfill' const legacyEntryId = 'vite-legacy-entry' const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))` const dynamicFallbackInlineCode = `!function(){try{new Function("m","return import(m)")}catch(o){console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();` const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};` const legacyEnvVarMarker = `__VITE_IS_LEGACY__` /** * @param {import('.').Options} options * @returns {import('vite').Plugin[]} */ function viteLegacyPlugin(options = {}) { /** * @type {import('vite').ResolvedConfig} */ let config const targets = options.targets || 'defaults' const genLegacy = options.renderLegacyChunks !== false const genDynamicFallback = genLegacy const debugFlags = (process.env.DEBUG || '').split(',') const isDebug = debugFlags.includes('vite:*') || debugFlags.includes('vite:legacy') const facadeToLegacyChunkMap = new Map() const facadeToLegacyPolyfillMap = new Map() const facadeToModernPolyfillMap = new Map() const modernPolyfills = new Set() // System JS relies on the Promise interface. It needs to be polyfilled for IE 11. (array.iterator is mandatory for supporting Promise.all) const DEFAULT_LEGACY_POLYFILL = [ 'core-js/modules/es.promise', 'core-js/modules/es.array.iterator' ] const legacyPolyfills = new Set(DEFAULT_LEGACY_POLYFILL) if (Array.isArray(options.modernPolyfills)) { options.modernPolyfills.forEach((i) => { modernPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) }) } if (Array.isArray(options.polyfills)) { options.polyfills.forEach((i) => { if (i.startsWith(`regenerator`)) { legacyPolyfills.add(`regenerator-runtime/runtime.js`) } else { legacyPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) } }) } if (Array.isArray(options.additionalLegacyPolyfills)) { options.additionalLegacyPolyfills.forEach((i) => { legacyPolyfills.add(i) }) } /** * @type {import('vite').Plugin} */ const legacyConfigPlugin = { name: 'vite:legacy-config', apply: 'build', config(config) { if (!config.build) { config.build = {} } if (!config.build.cssTarget) { // Hint for esbuild that we are targeting legacy browsers when minifying CSS. // Full CSS compat table available at https://github.com/evanw/esbuild/blob/78e04680228cf989bdd7d471e02bbc2c8d345dc9/internal/compat/css_table.go // But note that only the `HexRGBA` feature affects the minify outcome. // HSL & rebeccapurple values will be minified away regardless the target. // So targeting `chrome61` suffices to fix the compatiblity issue. config.build.cssTarget = 'chrome61' } } } /** * @type {import('vite').Plugin} */ const legacyGenerateBundlePlugin = { name: 'vite:legacy-generate-polyfill-chunk', apply: 'build', async generateBundle(opts, bundle) { if (config.build.ssr) { return } if (!isLegacyBundle(bundle, opts)) { if (!modernPolyfills.size) { return } isDebug && console.log( `[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills ) await buildPolyfillChunk( 'polyfills-modern', modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, options.externalSystemJS ) return } if (!genLegacy) { return } // legacy bundle if (legacyPolyfills.size || genDynamicFallback) { if (!legacyPolyfills.has('es.promise')) { // check if the target needs Promise polyfill because SystemJS relies // on it detectPolyfills(`Promise.resolve()`, targets, legacyPolyfills) } isDebug && console.log( `[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills ) await buildPolyfillChunk( 'polyfills-legacy', legacyPolyfills, bundle, facadeToLegacyPolyfillMap, // force using terser for legacy polyfill minification, since esbuild // isn't legacy-safe config.build, options.externalSystemJS ) } } } /** * @type {import('vite').Plugin} */ const legacyPostPlugin = { name: 'vite:legacy-post-process', enforce: 'post', apply: 'build', configResolved(_config) { if (_config.build.lib) { throw new Error('@vitejs/plugin-legacy does not support library mode.') } config = _config if (!genLegacy || config.build.ssr) { return } /** * @param {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} fileNames * @param {string?} defaultFileName * @returns {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} */ const getLegacyOutputFileName = ( fileNames, defaultFileName = '[name]-legacy.[hash].js' ) => { if (!fileNames) { return path.posix.join(config.build.assetsDir, defaultFileName) } return (chunkInfo) => { let fileName = typeof fileNames === 'function' ? fileNames(chunkInfo) : fileNames if (fileName.includes('[name]')) { // [name]-[hash].[format] -> [name]-legacy-[hash].[format] fileName = fileName.replace('[name]', '[name]-legacy') } else { // entry.js -> entry-legacy.js fileName = fileName.replace(/(.+)\.(.+)/, '$1-legacy.$2') } return fileName } } /** * @param {import('rollup').OutputOptions} options * @returns {import('rollup').OutputOptions} */ const createLegacyOutput = (options = {}) => { return { ...options, format: 'system', entryFileNames: getLegacyOutputFileName(options.entryFileNames), chunkFileNames: getLegacyOutputFileName(options.chunkFileNames) } } const { rollupOptions } = config.build const { output } = rollupOptions if (Array.isArray(output)) { rollupOptions.output = [...output.map(createLegacyOutput), ...output] } else { rollupOptions.output = [createLegacyOutput(output), output || {}] } }, renderChunk(raw, chunk, opts) { if (config.build.ssr) { return } if (!isLegacyChunk(chunk, opts)) { if ( options.modernPolyfills && !Array.isArray(options.modernPolyfills) ) { // analyze and record modern polyfills detectPolyfills(raw, { esmodules: true }, modernPolyfills) } const ms = new MagicString(raw) if (genDynamicFallback && chunk.isEntry) { ms.prepend(forceDynamicImportUsage) } if (raw.includes(legacyEnvVarMarker)) { const re = new RegExp(legacyEnvVarMarker, 'g') let match while ((match = re.exec(raw))) { ms.overwrite( match.index, match.index + legacyEnvVarMarker.length, `false` ) } } if (config.build.sourcemap) { return { code: ms.toString(), map: ms.generateMap({ hires: true }) } } return ms.toString() } if (!genLegacy) { return } // @ts-ignore avoid esbuild transform on legacy chunks since it produces // legacy-unsafe code - e.g. rewriting object properties into shorthands opts.__vite_skip_esbuild__ = true // @ts-ignore force terser for legacy chunks. This only takes effect if // minification isn't disabled, because that leaves out the terser plugin // entirely. opts.__vite_force_terser__ = true // @ts-ignore // In the `generateBundle` hook, // we'll delete the assets from the legacy bundle to avoid emitting duplicate assets. // But that's still a waste of computing resource. // So we add this flag to avoid emitting the asset in the first place whenever possible. opts.__vite_skip_asset_emit__ = true // @ts-ignore avoid emitting assets for legacy bundle const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills) // transform the legacy chunk with @babel/preset-env const sourceMaps = !!config.build.sourcemap const { code, map } = loadBabel().transform(raw, { babelrc: false, configFile: false, compact: true, sourceMaps, inputSourceMap: sourceMaps && chunk.map, presets: [ // forcing our plugin to run before preset-env by wrapping it in a // preset so we can catch the injected import statements... [ () => ({ plugins: [ recordAndRemovePolyfillBabelPlugin(legacyPolyfills), replaceLegacyEnvBabelPlugin(), wrapIIFEBabelPlugin() ] }) ], [ 'env', { targets, modules: false, bugfixes: true, loose: false, useBuiltIns: needPolyfills ? 'usage' : false, corejs: needPolyfills ? { version: 3, proposals: false } : undefined, shippedProposals: true, ignoreBrowserslistConfig: options.ignoreBrowserslistConfig } ] ] }) return { code, map } }, transformIndexHtml(html, { chunk }) { if (config.build.ssr) return if (!chunk) return if (chunk.fileName.includes('-legacy')) { // The legacy bundle is built first, and its index.html isn't actually // emitted. Here we simply record its corresponding legacy chunk. facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName) return } /** * @type {import('vite').HtmlTagDescriptor[]} */ const tags = [] const htmlFilename = chunk.facadeModuleId.replace(/\?.*$/, '') // 1. inject modern polyfills const modernPolyfillFilename = facadeToModernPolyfillMap.get( chunk.facadeModuleId ) if (modernPolyfillFilename) { tags.push({ tag: 'script', attrs: { type: 'module', src: `${config.base}${modernPolyfillFilename}` } }) } else if (modernPolyfills.size) { throw new Error( `No corresponding modern polyfill chunk found for ${htmlFilename}` ) } if (!genLegacy) { return { html, tags } } // 2. inject Safari 10 nomodule fix tags.push({ tag: 'script', attrs: { nomodule: true }, children: safari10NoModuleFix, injectTo: 'body' }) // 3. inject legacy polyfills const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get( chunk.facadeModuleId ) if (legacyPolyfillFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, id: legacyPolyfillId, src: `${config.base}${legacyPolyfillFilename}` }, injectTo: 'body' }) } else if (legacyPolyfills.size) { throw new Error( `No corresponding legacy polyfill chunk found for ${htmlFilename}` ) } // 4. inject legacy entry const legacyEntryFilename = facadeToLegacyChunkMap.get( chunk.facadeModuleId ) if (legacyEntryFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, // we set the entry path on the element as an attribute so that the // script content will stay consistent - which allows using a constant // hash value for CSP. id: legacyEntryId, 'data-src': config.base + legacyEntryFilename }, children: systemJSInlineCode, injectTo: 'body' }) } else { throw new Error( `No corresponding legacy entry chunk found for ${htmlFilename}` ) } // 5. inject dynamic import fallback entry if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) { tags.push({ tag: 'script', attrs: { type: 'module' }, children: dynamicFallbackInlineCode, injectTo: 'head' }) } return { html, tags } }, generateBundle(opts, bundle) { if (config.build.ssr) { return } if (isLegacyBundle(bundle, opts)) { // avoid emitting duplicate assets for (const name in bundle) { if (bundle[name].type === 'asset') { delete bundle[name] } } } } } let envInjectionFailed = false /** * @type {import('vite').Plugin} */ const legacyEnvPlugin = { name: 'vite:legacy-env', config(config, env) { if (env) { return { define: { 'import.meta.env.LEGACY': env.command === 'serve' || config.build.ssr ? false : legacyEnvVarMarker } } } else { envInjectionFailed = true } }, configResolved(config) { if (envInjectionFailed) { config.logger.warn( `[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` + `to incompatible vite version (requires vite@^2.0.0-beta.69).` ) } } } return [ legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin, legacyEnvPlugin ] } /** * @param {string} code * @param {any} targets * @param {Set<string>} list */ function detectPolyfills(code, targets, list) { const { ast } = loadBabel().transform(code, { ast: true, babelrc: false, configFile: false, presets: [ [ 'env', { targets, modules: false, useBuiltIns: 'usage', corejs: { version: 3, proposals: false }, shippedProposals: true, ignoreBrowserslistConfig: true } ] ] }) for (const node of ast.program.body) { if (node.type === 'ImportDeclaration') { const source = node.source.value if ( source.startsWith('core-js/') || source.startsWith('regenerator-runtime/') ) { list.add(source) } } } } /** * @param {string} name * @param {Set<string>} imports * @param {import('rollup').OutputBundle} bundle * @param {Map<string, string>} facadeToChunkMap * @param {import('vite').BuildOptions} buildOptions */ async function buildPolyfillChunk( name, imports, bundle, facadeToChunkMap, buildOptions, externalSystemJS ) { let { minify, assetsDir } = buildOptions minify = minify ? 'terser' : false const res = await build({ // so that everything is resolved from here root: __dirname, configFile: false, logLevel: 'error', plugins: [polyfillsPlugin(imports, externalSystemJS)], build: { write: false, target: false, minify, assetsDir, rollupOptions: { input: { [name]: polyfillId }, output: { format: name.includes('legacy') ? 'iife' : 'es', manualChunks: undefined } } } }) const _polyfillChunk = Array.isArray(res) ? res[0] : res if (!('output' in _polyfillChunk)) return const polyfillChunk = _polyfillChunk.output[0] // associate the polyfill chunk to every entry chunk so that we can retrieve // the polyfill filename in index html transform for (const key in bundle) { const chunk = bundle[key] if (chunk.type === 'chunk' && chunk.facadeModuleId) { facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName) } } // add the chunk to the bundle bundle[polyfillChunk.name] = polyfillChunk } const polyfillId = '\0vite/legacy-polyfills' /** * @param {Set<string>} imports * @return {import('rollup').Plugin} */ function polyfillsPlugin(imports, externalSystemJS) { return { name: 'vite:legacy-polyfills', resolveId(id) { if (id === polyfillId) { return id } }, load(id) { if (id === polyfillId) { return ( [...imports].map((i) => `import "${i}";`).join('') + (externalSystemJS ? '' : `import "systemjs/dist/s.min.js";`) ) } } } } /** * @param {import('rollup').RenderedChunk} chunk * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyChunk(chunk, options) { return options.format === 'system' && chunk.fileName.includes('-legacy') } /** * @param {import('rollup').OutputBundle} bundle * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyBundle(bundle, options) { if (options.format === 'system') { const entryChunk = Object.values(bundle).find( (output) => output.type === 'chunk' && output.isEntry ) return !!entryChunk && entryChunk.fileName.includes('-legacy') } return false } /** * @param {Set<string>} polyfills */ function recordAndRemovePolyfillBabelPlugin(polyfills) { return ({ types: t }) => ({ name: 'vite-remove-polyfill-import', post({ path }) { path.get('body').forEach((p) => { if (t.isImportDeclaration(p)) { polyfills.add(p.node.source.value) p.remove() } }) } }) } function replaceLegacyEnvBabelPlugin() { return ({ types: t }) => ({ name: 'vite-replace-env-legacy', visitor: { Identifier(path) { if (path.node.name === legacyEnvVarMarker) { path.replaceWith(t.booleanLiteral(true)) } } } }) } function wrapIIFEBabelPlugin() { return ({ types: t, template }) => { const buildIIFE = template(';(function(){%%body%%})();') return { name: 'vite-wrap-iife', post({ path }) { if (!this.isWrapped) { this.isWrapped = true path.replaceWith(t.program(buildIIFE({ body: path.node.body }))) } } } } } module.exports = viteLegacyPlugin viteLegacyPlugin.default = viteLegacyPlugin viteLegacyPlugin.cspHashes = [ createHash('sha256').update(safari10NoModuleFix).digest('base64'), createHash('sha256').update(systemJSInlineCode).digest('base64'), createHash('sha256').update(dynamicFallbackInlineCode).digest('base64') ]
packages/plugin-legacy/index.js
1
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.9990776777267456, 0.15567319095134735, 0.00016304907330777496, 0.00020218745339661837, 0.35503044724464417 ]
{ "id": 1, "code_window": [ "const legacyPolyfillId = 'vite-legacy-polyfill'\n", "const legacyEntryId = 'vite-legacy-entry'\n", "const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`\n", "const dynamicFallbackInlineCode = `!function(){try{new Function(\"m\",\"return import(m)\")}catch(o){console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();`\n", "\n", "const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`\n", "\n", "const legacyEnvVarMarker = `__VITE_IS_LEGACY__`\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "const detectDynamicImportVarName = '__vite_is_dynamic_import_support'\n", "const detectDynamicImportVarInitCode = `var ${detectDynamicImportVarName}=false;`\n", "const detectDynamicImportCode = `try{import(\"_\").catch(()=>1);}catch(e){}window.${detectDynamicImportVarName}=true;`\n", "const dynamicFallbackInlineCode = `!function(){if(window.${detectDynamicImportVarName})return;console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "replace", "edit_start_line_idx": 20 }
const fs = require('fs') console.log('this should not run in the browser')
packages/playground/resolve/browser-field/not-browser.js
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.0001647599128773436, 0.0001647599128773436, 0.0001647599128773436, 0.0001647599128773436, 0 ]
{ "id": 1, "code_window": [ "const legacyPolyfillId = 'vite-legacy-polyfill'\n", "const legacyEntryId = 'vite-legacy-entry'\n", "const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`\n", "const dynamicFallbackInlineCode = `!function(){try{new Function(\"m\",\"return import(m)\")}catch(o){console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();`\n", "\n", "const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`\n", "\n", "const legacyEnvVarMarker = `__VITE_IS_LEGACY__`\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "const detectDynamicImportVarName = '__vite_is_dynamic_import_support'\n", "const detectDynamicImportVarInitCode = `var ${detectDynamicImportVarName}=false;`\n", "const detectDynamicImportCode = `try{import(\"_\").catch(()=>1);}catch(e){}window.${detectDynamicImportVarName}=true;`\n", "const dynamicFallbackInlineCode = `!function(){if(window.${detectDynamicImportVarName})return;console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "replace", "edit_start_line_idx": 20 }
{ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", "projectFolder": ".", "mainEntryPointFilePath": "./temp/index.d.ts", "dtsRollup": { "enabled": true, "untrimmedFilePath": "./dist/index.d.ts" }, "apiReport": { "enabled": false }, "docModel": { "enabled": false }, "tsdocMetadata": { "enabled": false }, "messages": { "compilerMessageReporting": { "default": { "logLevel": "warning" } }, "extractorMessageReporting": { "default": { "logLevel": "warning", "addToApiReportFile": true }, "ae-missing-release-tag": { "logLevel": "none" } }, "tsdocMessageReporting": { "default": { "logLevel": "warning" }, "tsdoc-undefined-tag": { "logLevel": "none" } } } }
packages/plugin-react/api-extractor.json
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00017519009998068213, 0.00017231848323717713, 0.0001642530842218548, 0.00017388032574672252, 0.0000037110216908331495 ]
{ "id": 1, "code_window": [ "const legacyPolyfillId = 'vite-legacy-polyfill'\n", "const legacyEntryId = 'vite-legacy-entry'\n", "const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`\n", "const dynamicFallbackInlineCode = `!function(){try{new Function(\"m\",\"return import(m)\")}catch(o){console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();`\n", "\n", "const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`\n", "\n", "const legacyEnvVarMarker = `__VITE_IS_LEGACY__`\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "const detectDynamicImportVarName = '__vite_is_dynamic_import_support'\n", "const detectDynamicImportVarInitCode = `var ${detectDynamicImportVarName}=false;`\n", "const detectDynamicImportCode = `try{import(\"_\").catch(()=>1);}catch(e){}window.${detectDynamicImportVarName}=true;`\n", "const dynamicFallbackInlineCode = `!function(){if(window.${detectDynamicImportVarName})return;console.warn(\"vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "replace", "edit_start_line_idx": 20 }
import axios from 'axios' axios.get('/ping').then((res) => { document.querySelector('.cjs-browser-field').textContent = res.data })
packages/playground/optimize-deps/glob/foo.js
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00016779443831183016, 0.00016779443831183016, 0.00016779443831183016, 0.00016779443831183016, 0 ]
{ "id": 2, "code_window": [ "\n", " // 5. inject dynamic import fallback entry\n", " if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: dynamicFallbackInlineCode,\n", " injectTo: 'head'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportVarInitCode,\n", " injectTo: 'head'\n", " })\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportCode,\n", " injectTo: 'head'\n", " })\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 432 }
// @ts-check const path = require('path') const { createHash } = require('crypto') const { build } = require('vite') const MagicString = require('magic-string').default // lazy load babel since it's not used during dev let babel /** * @return {import('@babel/standalone')} */ const loadBabel = () => babel || (babel = require('@babel/standalone')) // https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc // DO NOT ALTER THIS CONTENT const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();` const legacyPolyfillId = 'vite-legacy-polyfill' const legacyEntryId = 'vite-legacy-entry' const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))` const dynamicFallbackInlineCode = `!function(){try{new Function("m","return import(m)")}catch(o){console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();` const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};` const legacyEnvVarMarker = `__VITE_IS_LEGACY__` /** * @param {import('.').Options} options * @returns {import('vite').Plugin[]} */ function viteLegacyPlugin(options = {}) { /** * @type {import('vite').ResolvedConfig} */ let config const targets = options.targets || 'defaults' const genLegacy = options.renderLegacyChunks !== false const genDynamicFallback = genLegacy const debugFlags = (process.env.DEBUG || '').split(',') const isDebug = debugFlags.includes('vite:*') || debugFlags.includes('vite:legacy') const facadeToLegacyChunkMap = new Map() const facadeToLegacyPolyfillMap = new Map() const facadeToModernPolyfillMap = new Map() const modernPolyfills = new Set() // System JS relies on the Promise interface. It needs to be polyfilled for IE 11. (array.iterator is mandatory for supporting Promise.all) const DEFAULT_LEGACY_POLYFILL = [ 'core-js/modules/es.promise', 'core-js/modules/es.array.iterator' ] const legacyPolyfills = new Set(DEFAULT_LEGACY_POLYFILL) if (Array.isArray(options.modernPolyfills)) { options.modernPolyfills.forEach((i) => { modernPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) }) } if (Array.isArray(options.polyfills)) { options.polyfills.forEach((i) => { if (i.startsWith(`regenerator`)) { legacyPolyfills.add(`regenerator-runtime/runtime.js`) } else { legacyPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) } }) } if (Array.isArray(options.additionalLegacyPolyfills)) { options.additionalLegacyPolyfills.forEach((i) => { legacyPolyfills.add(i) }) } /** * @type {import('vite').Plugin} */ const legacyConfigPlugin = { name: 'vite:legacy-config', apply: 'build', config(config) { if (!config.build) { config.build = {} } if (!config.build.cssTarget) { // Hint for esbuild that we are targeting legacy browsers when minifying CSS. // Full CSS compat table available at https://github.com/evanw/esbuild/blob/78e04680228cf989bdd7d471e02bbc2c8d345dc9/internal/compat/css_table.go // But note that only the `HexRGBA` feature affects the minify outcome. // HSL & rebeccapurple values will be minified away regardless the target. // So targeting `chrome61` suffices to fix the compatiblity issue. config.build.cssTarget = 'chrome61' } } } /** * @type {import('vite').Plugin} */ const legacyGenerateBundlePlugin = { name: 'vite:legacy-generate-polyfill-chunk', apply: 'build', async generateBundle(opts, bundle) { if (config.build.ssr) { return } if (!isLegacyBundle(bundle, opts)) { if (!modernPolyfills.size) { return } isDebug && console.log( `[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills ) await buildPolyfillChunk( 'polyfills-modern', modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, options.externalSystemJS ) return } if (!genLegacy) { return } // legacy bundle if (legacyPolyfills.size || genDynamicFallback) { if (!legacyPolyfills.has('es.promise')) { // check if the target needs Promise polyfill because SystemJS relies // on it detectPolyfills(`Promise.resolve()`, targets, legacyPolyfills) } isDebug && console.log( `[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills ) await buildPolyfillChunk( 'polyfills-legacy', legacyPolyfills, bundle, facadeToLegacyPolyfillMap, // force using terser for legacy polyfill minification, since esbuild // isn't legacy-safe config.build, options.externalSystemJS ) } } } /** * @type {import('vite').Plugin} */ const legacyPostPlugin = { name: 'vite:legacy-post-process', enforce: 'post', apply: 'build', configResolved(_config) { if (_config.build.lib) { throw new Error('@vitejs/plugin-legacy does not support library mode.') } config = _config if (!genLegacy || config.build.ssr) { return } /** * @param {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} fileNames * @param {string?} defaultFileName * @returns {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} */ const getLegacyOutputFileName = ( fileNames, defaultFileName = '[name]-legacy.[hash].js' ) => { if (!fileNames) { return path.posix.join(config.build.assetsDir, defaultFileName) } return (chunkInfo) => { let fileName = typeof fileNames === 'function' ? fileNames(chunkInfo) : fileNames if (fileName.includes('[name]')) { // [name]-[hash].[format] -> [name]-legacy-[hash].[format] fileName = fileName.replace('[name]', '[name]-legacy') } else { // entry.js -> entry-legacy.js fileName = fileName.replace(/(.+)\.(.+)/, '$1-legacy.$2') } return fileName } } /** * @param {import('rollup').OutputOptions} options * @returns {import('rollup').OutputOptions} */ const createLegacyOutput = (options = {}) => { return { ...options, format: 'system', entryFileNames: getLegacyOutputFileName(options.entryFileNames), chunkFileNames: getLegacyOutputFileName(options.chunkFileNames) } } const { rollupOptions } = config.build const { output } = rollupOptions if (Array.isArray(output)) { rollupOptions.output = [...output.map(createLegacyOutput), ...output] } else { rollupOptions.output = [createLegacyOutput(output), output || {}] } }, renderChunk(raw, chunk, opts) { if (config.build.ssr) { return } if (!isLegacyChunk(chunk, opts)) { if ( options.modernPolyfills && !Array.isArray(options.modernPolyfills) ) { // analyze and record modern polyfills detectPolyfills(raw, { esmodules: true }, modernPolyfills) } const ms = new MagicString(raw) if (genDynamicFallback && chunk.isEntry) { ms.prepend(forceDynamicImportUsage) } if (raw.includes(legacyEnvVarMarker)) { const re = new RegExp(legacyEnvVarMarker, 'g') let match while ((match = re.exec(raw))) { ms.overwrite( match.index, match.index + legacyEnvVarMarker.length, `false` ) } } if (config.build.sourcemap) { return { code: ms.toString(), map: ms.generateMap({ hires: true }) } } return ms.toString() } if (!genLegacy) { return } // @ts-ignore avoid esbuild transform on legacy chunks since it produces // legacy-unsafe code - e.g. rewriting object properties into shorthands opts.__vite_skip_esbuild__ = true // @ts-ignore force terser for legacy chunks. This only takes effect if // minification isn't disabled, because that leaves out the terser plugin // entirely. opts.__vite_force_terser__ = true // @ts-ignore // In the `generateBundle` hook, // we'll delete the assets from the legacy bundle to avoid emitting duplicate assets. // But that's still a waste of computing resource. // So we add this flag to avoid emitting the asset in the first place whenever possible. opts.__vite_skip_asset_emit__ = true // @ts-ignore avoid emitting assets for legacy bundle const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills) // transform the legacy chunk with @babel/preset-env const sourceMaps = !!config.build.sourcemap const { code, map } = loadBabel().transform(raw, { babelrc: false, configFile: false, compact: true, sourceMaps, inputSourceMap: sourceMaps && chunk.map, presets: [ // forcing our plugin to run before preset-env by wrapping it in a // preset so we can catch the injected import statements... [ () => ({ plugins: [ recordAndRemovePolyfillBabelPlugin(legacyPolyfills), replaceLegacyEnvBabelPlugin(), wrapIIFEBabelPlugin() ] }) ], [ 'env', { targets, modules: false, bugfixes: true, loose: false, useBuiltIns: needPolyfills ? 'usage' : false, corejs: needPolyfills ? { version: 3, proposals: false } : undefined, shippedProposals: true, ignoreBrowserslistConfig: options.ignoreBrowserslistConfig } ] ] }) return { code, map } }, transformIndexHtml(html, { chunk }) { if (config.build.ssr) return if (!chunk) return if (chunk.fileName.includes('-legacy')) { // The legacy bundle is built first, and its index.html isn't actually // emitted. Here we simply record its corresponding legacy chunk. facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName) return } /** * @type {import('vite').HtmlTagDescriptor[]} */ const tags = [] const htmlFilename = chunk.facadeModuleId.replace(/\?.*$/, '') // 1. inject modern polyfills const modernPolyfillFilename = facadeToModernPolyfillMap.get( chunk.facadeModuleId ) if (modernPolyfillFilename) { tags.push({ tag: 'script', attrs: { type: 'module', src: `${config.base}${modernPolyfillFilename}` } }) } else if (modernPolyfills.size) { throw new Error( `No corresponding modern polyfill chunk found for ${htmlFilename}` ) } if (!genLegacy) { return { html, tags } } // 2. inject Safari 10 nomodule fix tags.push({ tag: 'script', attrs: { nomodule: true }, children: safari10NoModuleFix, injectTo: 'body' }) // 3. inject legacy polyfills const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get( chunk.facadeModuleId ) if (legacyPolyfillFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, id: legacyPolyfillId, src: `${config.base}${legacyPolyfillFilename}` }, injectTo: 'body' }) } else if (legacyPolyfills.size) { throw new Error( `No corresponding legacy polyfill chunk found for ${htmlFilename}` ) } // 4. inject legacy entry const legacyEntryFilename = facadeToLegacyChunkMap.get( chunk.facadeModuleId ) if (legacyEntryFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, // we set the entry path on the element as an attribute so that the // script content will stay consistent - which allows using a constant // hash value for CSP. id: legacyEntryId, 'data-src': config.base + legacyEntryFilename }, children: systemJSInlineCode, injectTo: 'body' }) } else { throw new Error( `No corresponding legacy entry chunk found for ${htmlFilename}` ) } // 5. inject dynamic import fallback entry if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) { tags.push({ tag: 'script', attrs: { type: 'module' }, children: dynamicFallbackInlineCode, injectTo: 'head' }) } return { html, tags } }, generateBundle(opts, bundle) { if (config.build.ssr) { return } if (isLegacyBundle(bundle, opts)) { // avoid emitting duplicate assets for (const name in bundle) { if (bundle[name].type === 'asset') { delete bundle[name] } } } } } let envInjectionFailed = false /** * @type {import('vite').Plugin} */ const legacyEnvPlugin = { name: 'vite:legacy-env', config(config, env) { if (env) { return { define: { 'import.meta.env.LEGACY': env.command === 'serve' || config.build.ssr ? false : legacyEnvVarMarker } } } else { envInjectionFailed = true } }, configResolved(config) { if (envInjectionFailed) { config.logger.warn( `[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` + `to incompatible vite version (requires vite@^2.0.0-beta.69).` ) } } } return [ legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin, legacyEnvPlugin ] } /** * @param {string} code * @param {any} targets * @param {Set<string>} list */ function detectPolyfills(code, targets, list) { const { ast } = loadBabel().transform(code, { ast: true, babelrc: false, configFile: false, presets: [ [ 'env', { targets, modules: false, useBuiltIns: 'usage', corejs: { version: 3, proposals: false }, shippedProposals: true, ignoreBrowserslistConfig: true } ] ] }) for (const node of ast.program.body) { if (node.type === 'ImportDeclaration') { const source = node.source.value if ( source.startsWith('core-js/') || source.startsWith('regenerator-runtime/') ) { list.add(source) } } } } /** * @param {string} name * @param {Set<string>} imports * @param {import('rollup').OutputBundle} bundle * @param {Map<string, string>} facadeToChunkMap * @param {import('vite').BuildOptions} buildOptions */ async function buildPolyfillChunk( name, imports, bundle, facadeToChunkMap, buildOptions, externalSystemJS ) { let { minify, assetsDir } = buildOptions minify = minify ? 'terser' : false const res = await build({ // so that everything is resolved from here root: __dirname, configFile: false, logLevel: 'error', plugins: [polyfillsPlugin(imports, externalSystemJS)], build: { write: false, target: false, minify, assetsDir, rollupOptions: { input: { [name]: polyfillId }, output: { format: name.includes('legacy') ? 'iife' : 'es', manualChunks: undefined } } } }) const _polyfillChunk = Array.isArray(res) ? res[0] : res if (!('output' in _polyfillChunk)) return const polyfillChunk = _polyfillChunk.output[0] // associate the polyfill chunk to every entry chunk so that we can retrieve // the polyfill filename in index html transform for (const key in bundle) { const chunk = bundle[key] if (chunk.type === 'chunk' && chunk.facadeModuleId) { facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName) } } // add the chunk to the bundle bundle[polyfillChunk.name] = polyfillChunk } const polyfillId = '\0vite/legacy-polyfills' /** * @param {Set<string>} imports * @return {import('rollup').Plugin} */ function polyfillsPlugin(imports, externalSystemJS) { return { name: 'vite:legacy-polyfills', resolveId(id) { if (id === polyfillId) { return id } }, load(id) { if (id === polyfillId) { return ( [...imports].map((i) => `import "${i}";`).join('') + (externalSystemJS ? '' : `import "systemjs/dist/s.min.js";`) ) } } } } /** * @param {import('rollup').RenderedChunk} chunk * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyChunk(chunk, options) { return options.format === 'system' && chunk.fileName.includes('-legacy') } /** * @param {import('rollup').OutputBundle} bundle * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyBundle(bundle, options) { if (options.format === 'system') { const entryChunk = Object.values(bundle).find( (output) => output.type === 'chunk' && output.isEntry ) return !!entryChunk && entryChunk.fileName.includes('-legacy') } return false } /** * @param {Set<string>} polyfills */ function recordAndRemovePolyfillBabelPlugin(polyfills) { return ({ types: t }) => ({ name: 'vite-remove-polyfill-import', post({ path }) { path.get('body').forEach((p) => { if (t.isImportDeclaration(p)) { polyfills.add(p.node.source.value) p.remove() } }) } }) } function replaceLegacyEnvBabelPlugin() { return ({ types: t }) => ({ name: 'vite-replace-env-legacy', visitor: { Identifier(path) { if (path.node.name === legacyEnvVarMarker) { path.replaceWith(t.booleanLiteral(true)) } } } }) } function wrapIIFEBabelPlugin() { return ({ types: t, template }) => { const buildIIFE = template(';(function(){%%body%%})();') return { name: 'vite-wrap-iife', post({ path }) { if (!this.isWrapped) { this.isWrapped = true path.replaceWith(t.program(buildIIFE({ body: path.node.body }))) } } } } } module.exports = viteLegacyPlugin viteLegacyPlugin.default = viteLegacyPlugin viteLegacyPlugin.cspHashes = [ createHash('sha256').update(safari10NoModuleFix).digest('base64'), createHash('sha256').update(systemJSInlineCode).digest('base64'), createHash('sha256').update(dynamicFallbackInlineCode).digest('base64') ]
packages/plugin-legacy/index.js
1
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.9967845678329468, 0.015500703826546669, 0.00016394813428632915, 0.00017192616360262036, 0.11816776543855667 ]
{ "id": 2, "code_window": [ "\n", " // 5. inject dynamic import fallback entry\n", " if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: dynamicFallbackInlineCode,\n", " injectTo: 'head'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportVarInitCode,\n", " injectTo: 'head'\n", " })\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportCode,\n", " injectTo: 'head'\n", " })\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 432 }
import { resolveLibFilename } from '../build' import { resolve } from 'path' describe('resolveLibFilename', () => { test('custom filename function', () => { const filename = resolveLibFilename( { fileName: (format) => `custom-filename-function.${format}.js`, entry: 'mylib.js' }, 'es', resolve(__dirname, 'packages/name') ) expect(filename).toBe('custom-filename-function.es.js') }) test('custom filename string', () => { const filename = resolveLibFilename( { fileName: 'custom-filename', entry: 'mylib.js' }, 'es', resolve(__dirname, 'packages/name') ) expect(filename).toBe('custom-filename.es.js') }) test('package name as filename', () => { const filename = resolveLibFilename( { entry: 'mylib.js' }, 'es', resolve(__dirname, 'packages/name') ) expect(filename).toBe('mylib.es.js') }) test('custom filename and no package name', () => { const filename = resolveLibFilename( { fileName: 'custom-filename', entry: 'mylib.js' }, 'es', resolve(__dirname, 'packages/noname') ) expect(filename).toBe('custom-filename.es.js') }) test('missing filename', () => { expect(() => { resolveLibFilename( { entry: 'mylib.js' }, 'es', resolve(__dirname, 'packages/noname') ) }).toThrow() }) })
packages/vite/src/node/__tests__/build.spec.ts
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00017590131028555334, 0.00017240431043319404, 0.00016936099564190954, 0.00017198314890265465, 0.0000018974471913679736 ]
{ "id": 2, "code_window": [ "\n", " // 5. inject dynamic import fallback entry\n", " if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: dynamicFallbackInlineCode,\n", " injectTo: 'head'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportVarInitCode,\n", " injectTo: 'head'\n", " })\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportCode,\n", " injectTo: 'head'\n", " })\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 432 }
import { createApp } from 'vue' import { Named, NamedSpec, default as Default } from './Comps' import { default as TsxDefault } from './Comp' import OtherExt from './OtherExt.tesx' import JsxScript from './Script.vue' import JsxSrcImport from './SrcImport.vue' import JsxSetupSyntax from './setup-syntax-jsx.vue' // eslint-disable-next-line import JsxWithQuery from './Query.jsx?query=true' function App() { return ( <> <Named /> <NamedSpec /> <Default /> <TsxDefault /> <OtherExt /> <JsxScript /> <JsxSrcImport /> <JsxSetupSyntax /> <JsxWithQuery /> </> ) } createApp(App).mount('#app')
packages/playground/vue-jsx/main.jsx
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.0003711944737005979, 0.00023618839622940868, 0.00016837590374052525, 0.00016899482579901814, 0.00009546404908178374 ]
{ "id": 2, "code_window": [ "\n", " // 5. inject dynamic import fallback entry\n", " if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: dynamicFallbackInlineCode,\n", " injectTo: 'head'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportVarInitCode,\n", " injectTo: 'head'\n", " })\n", " tags.push({\n", " tag: 'script',\n", " attrs: { type: 'module' },\n", " children: detectDynamicImportCode,\n", " injectTo: 'head'\n", " })\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 432 }
{ "compilerOptions": { "composite": true, "module": "esnext", "moduleResolution": "node" }, "include": ["vite.config.ts"] }
packages/create-vite/template-vue-ts/tsconfig.node.json
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00017016046331264079, 0.00017016046331264079, 0.00017016046331264079, 0.00017016046331264079, 0 ]
{ "id": 3, "code_window": [ "\n", "viteLegacyPlugin.cspHashes = [\n", " createHash('sha256').update(safari10NoModuleFix).digest('base64'),\n", " createHash('sha256').update(systemJSInlineCode).digest('base64'),\n", " createHash('sha256').update(dynamicFallbackInlineCode).digest('base64')\n", "]" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " createHash('sha256').update(detectDynamicImportVarInitCode).digest('base64'),\n", " createHash('sha256').update(detectDynamicImportCode).digest('base64'),\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 697 }
// @ts-check const path = require('path') const { createHash } = require('crypto') const { build } = require('vite') const MagicString = require('magic-string').default // lazy load babel since it's not used during dev let babel /** * @return {import('@babel/standalone')} */ const loadBabel = () => babel || (babel = require('@babel/standalone')) // https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc // DO NOT ALTER THIS CONTENT const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();` const legacyPolyfillId = 'vite-legacy-polyfill' const legacyEntryId = 'vite-legacy-entry' const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))` const dynamicFallbackInlineCode = `!function(){try{new Function("m","return import(m)")}catch(o){console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}}();` const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};` const legacyEnvVarMarker = `__VITE_IS_LEGACY__` /** * @param {import('.').Options} options * @returns {import('vite').Plugin[]} */ function viteLegacyPlugin(options = {}) { /** * @type {import('vite').ResolvedConfig} */ let config const targets = options.targets || 'defaults' const genLegacy = options.renderLegacyChunks !== false const genDynamicFallback = genLegacy const debugFlags = (process.env.DEBUG || '').split(',') const isDebug = debugFlags.includes('vite:*') || debugFlags.includes('vite:legacy') const facadeToLegacyChunkMap = new Map() const facadeToLegacyPolyfillMap = new Map() const facadeToModernPolyfillMap = new Map() const modernPolyfills = new Set() // System JS relies on the Promise interface. It needs to be polyfilled for IE 11. (array.iterator is mandatory for supporting Promise.all) const DEFAULT_LEGACY_POLYFILL = [ 'core-js/modules/es.promise', 'core-js/modules/es.array.iterator' ] const legacyPolyfills = new Set(DEFAULT_LEGACY_POLYFILL) if (Array.isArray(options.modernPolyfills)) { options.modernPolyfills.forEach((i) => { modernPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) }) } if (Array.isArray(options.polyfills)) { options.polyfills.forEach((i) => { if (i.startsWith(`regenerator`)) { legacyPolyfills.add(`regenerator-runtime/runtime.js`) } else { legacyPolyfills.add( i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` ) } }) } if (Array.isArray(options.additionalLegacyPolyfills)) { options.additionalLegacyPolyfills.forEach((i) => { legacyPolyfills.add(i) }) } /** * @type {import('vite').Plugin} */ const legacyConfigPlugin = { name: 'vite:legacy-config', apply: 'build', config(config) { if (!config.build) { config.build = {} } if (!config.build.cssTarget) { // Hint for esbuild that we are targeting legacy browsers when minifying CSS. // Full CSS compat table available at https://github.com/evanw/esbuild/blob/78e04680228cf989bdd7d471e02bbc2c8d345dc9/internal/compat/css_table.go // But note that only the `HexRGBA` feature affects the minify outcome. // HSL & rebeccapurple values will be minified away regardless the target. // So targeting `chrome61` suffices to fix the compatiblity issue. config.build.cssTarget = 'chrome61' } } } /** * @type {import('vite').Plugin} */ const legacyGenerateBundlePlugin = { name: 'vite:legacy-generate-polyfill-chunk', apply: 'build', async generateBundle(opts, bundle) { if (config.build.ssr) { return } if (!isLegacyBundle(bundle, opts)) { if (!modernPolyfills.size) { return } isDebug && console.log( `[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills ) await buildPolyfillChunk( 'polyfills-modern', modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, options.externalSystemJS ) return } if (!genLegacy) { return } // legacy bundle if (legacyPolyfills.size || genDynamicFallback) { if (!legacyPolyfills.has('es.promise')) { // check if the target needs Promise polyfill because SystemJS relies // on it detectPolyfills(`Promise.resolve()`, targets, legacyPolyfills) } isDebug && console.log( `[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills ) await buildPolyfillChunk( 'polyfills-legacy', legacyPolyfills, bundle, facadeToLegacyPolyfillMap, // force using terser for legacy polyfill minification, since esbuild // isn't legacy-safe config.build, options.externalSystemJS ) } } } /** * @type {import('vite').Plugin} */ const legacyPostPlugin = { name: 'vite:legacy-post-process', enforce: 'post', apply: 'build', configResolved(_config) { if (_config.build.lib) { throw new Error('@vitejs/plugin-legacy does not support library mode.') } config = _config if (!genLegacy || config.build.ssr) { return } /** * @param {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} fileNames * @param {string?} defaultFileName * @returns {string | ((chunkInfo: import('rollup').PreRenderedChunk) => string)} */ const getLegacyOutputFileName = ( fileNames, defaultFileName = '[name]-legacy.[hash].js' ) => { if (!fileNames) { return path.posix.join(config.build.assetsDir, defaultFileName) } return (chunkInfo) => { let fileName = typeof fileNames === 'function' ? fileNames(chunkInfo) : fileNames if (fileName.includes('[name]')) { // [name]-[hash].[format] -> [name]-legacy-[hash].[format] fileName = fileName.replace('[name]', '[name]-legacy') } else { // entry.js -> entry-legacy.js fileName = fileName.replace(/(.+)\.(.+)/, '$1-legacy.$2') } return fileName } } /** * @param {import('rollup').OutputOptions} options * @returns {import('rollup').OutputOptions} */ const createLegacyOutput = (options = {}) => { return { ...options, format: 'system', entryFileNames: getLegacyOutputFileName(options.entryFileNames), chunkFileNames: getLegacyOutputFileName(options.chunkFileNames) } } const { rollupOptions } = config.build const { output } = rollupOptions if (Array.isArray(output)) { rollupOptions.output = [...output.map(createLegacyOutput), ...output] } else { rollupOptions.output = [createLegacyOutput(output), output || {}] } }, renderChunk(raw, chunk, opts) { if (config.build.ssr) { return } if (!isLegacyChunk(chunk, opts)) { if ( options.modernPolyfills && !Array.isArray(options.modernPolyfills) ) { // analyze and record modern polyfills detectPolyfills(raw, { esmodules: true }, modernPolyfills) } const ms = new MagicString(raw) if (genDynamicFallback && chunk.isEntry) { ms.prepend(forceDynamicImportUsage) } if (raw.includes(legacyEnvVarMarker)) { const re = new RegExp(legacyEnvVarMarker, 'g') let match while ((match = re.exec(raw))) { ms.overwrite( match.index, match.index + legacyEnvVarMarker.length, `false` ) } } if (config.build.sourcemap) { return { code: ms.toString(), map: ms.generateMap({ hires: true }) } } return ms.toString() } if (!genLegacy) { return } // @ts-ignore avoid esbuild transform on legacy chunks since it produces // legacy-unsafe code - e.g. rewriting object properties into shorthands opts.__vite_skip_esbuild__ = true // @ts-ignore force terser for legacy chunks. This only takes effect if // minification isn't disabled, because that leaves out the terser plugin // entirely. opts.__vite_force_terser__ = true // @ts-ignore // In the `generateBundle` hook, // we'll delete the assets from the legacy bundle to avoid emitting duplicate assets. // But that's still a waste of computing resource. // So we add this flag to avoid emitting the asset in the first place whenever possible. opts.__vite_skip_asset_emit__ = true // @ts-ignore avoid emitting assets for legacy bundle const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills) // transform the legacy chunk with @babel/preset-env const sourceMaps = !!config.build.sourcemap const { code, map } = loadBabel().transform(raw, { babelrc: false, configFile: false, compact: true, sourceMaps, inputSourceMap: sourceMaps && chunk.map, presets: [ // forcing our plugin to run before preset-env by wrapping it in a // preset so we can catch the injected import statements... [ () => ({ plugins: [ recordAndRemovePolyfillBabelPlugin(legacyPolyfills), replaceLegacyEnvBabelPlugin(), wrapIIFEBabelPlugin() ] }) ], [ 'env', { targets, modules: false, bugfixes: true, loose: false, useBuiltIns: needPolyfills ? 'usage' : false, corejs: needPolyfills ? { version: 3, proposals: false } : undefined, shippedProposals: true, ignoreBrowserslistConfig: options.ignoreBrowserslistConfig } ] ] }) return { code, map } }, transformIndexHtml(html, { chunk }) { if (config.build.ssr) return if (!chunk) return if (chunk.fileName.includes('-legacy')) { // The legacy bundle is built first, and its index.html isn't actually // emitted. Here we simply record its corresponding legacy chunk. facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName) return } /** * @type {import('vite').HtmlTagDescriptor[]} */ const tags = [] const htmlFilename = chunk.facadeModuleId.replace(/\?.*$/, '') // 1. inject modern polyfills const modernPolyfillFilename = facadeToModernPolyfillMap.get( chunk.facadeModuleId ) if (modernPolyfillFilename) { tags.push({ tag: 'script', attrs: { type: 'module', src: `${config.base}${modernPolyfillFilename}` } }) } else if (modernPolyfills.size) { throw new Error( `No corresponding modern polyfill chunk found for ${htmlFilename}` ) } if (!genLegacy) { return { html, tags } } // 2. inject Safari 10 nomodule fix tags.push({ tag: 'script', attrs: { nomodule: true }, children: safari10NoModuleFix, injectTo: 'body' }) // 3. inject legacy polyfills const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get( chunk.facadeModuleId ) if (legacyPolyfillFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, id: legacyPolyfillId, src: `${config.base}${legacyPolyfillFilename}` }, injectTo: 'body' }) } else if (legacyPolyfills.size) { throw new Error( `No corresponding legacy polyfill chunk found for ${htmlFilename}` ) } // 4. inject legacy entry const legacyEntryFilename = facadeToLegacyChunkMap.get( chunk.facadeModuleId ) if (legacyEntryFilename) { tags.push({ tag: 'script', attrs: { nomodule: true, // we set the entry path on the element as an attribute so that the // script content will stay consistent - which allows using a constant // hash value for CSP. id: legacyEntryId, 'data-src': config.base + legacyEntryFilename }, children: systemJSInlineCode, injectTo: 'body' }) } else { throw new Error( `No corresponding legacy entry chunk found for ${htmlFilename}` ) } // 5. inject dynamic import fallback entry if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) { tags.push({ tag: 'script', attrs: { type: 'module' }, children: dynamicFallbackInlineCode, injectTo: 'head' }) } return { html, tags } }, generateBundle(opts, bundle) { if (config.build.ssr) { return } if (isLegacyBundle(bundle, opts)) { // avoid emitting duplicate assets for (const name in bundle) { if (bundle[name].type === 'asset') { delete bundle[name] } } } } } let envInjectionFailed = false /** * @type {import('vite').Plugin} */ const legacyEnvPlugin = { name: 'vite:legacy-env', config(config, env) { if (env) { return { define: { 'import.meta.env.LEGACY': env.command === 'serve' || config.build.ssr ? false : legacyEnvVarMarker } } } else { envInjectionFailed = true } }, configResolved(config) { if (envInjectionFailed) { config.logger.warn( `[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` + `to incompatible vite version (requires vite@^2.0.0-beta.69).` ) } } } return [ legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin, legacyEnvPlugin ] } /** * @param {string} code * @param {any} targets * @param {Set<string>} list */ function detectPolyfills(code, targets, list) { const { ast } = loadBabel().transform(code, { ast: true, babelrc: false, configFile: false, presets: [ [ 'env', { targets, modules: false, useBuiltIns: 'usage', corejs: { version: 3, proposals: false }, shippedProposals: true, ignoreBrowserslistConfig: true } ] ] }) for (const node of ast.program.body) { if (node.type === 'ImportDeclaration') { const source = node.source.value if ( source.startsWith('core-js/') || source.startsWith('regenerator-runtime/') ) { list.add(source) } } } } /** * @param {string} name * @param {Set<string>} imports * @param {import('rollup').OutputBundle} bundle * @param {Map<string, string>} facadeToChunkMap * @param {import('vite').BuildOptions} buildOptions */ async function buildPolyfillChunk( name, imports, bundle, facadeToChunkMap, buildOptions, externalSystemJS ) { let { minify, assetsDir } = buildOptions minify = minify ? 'terser' : false const res = await build({ // so that everything is resolved from here root: __dirname, configFile: false, logLevel: 'error', plugins: [polyfillsPlugin(imports, externalSystemJS)], build: { write: false, target: false, minify, assetsDir, rollupOptions: { input: { [name]: polyfillId }, output: { format: name.includes('legacy') ? 'iife' : 'es', manualChunks: undefined } } } }) const _polyfillChunk = Array.isArray(res) ? res[0] : res if (!('output' in _polyfillChunk)) return const polyfillChunk = _polyfillChunk.output[0] // associate the polyfill chunk to every entry chunk so that we can retrieve // the polyfill filename in index html transform for (const key in bundle) { const chunk = bundle[key] if (chunk.type === 'chunk' && chunk.facadeModuleId) { facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName) } } // add the chunk to the bundle bundle[polyfillChunk.name] = polyfillChunk } const polyfillId = '\0vite/legacy-polyfills' /** * @param {Set<string>} imports * @return {import('rollup').Plugin} */ function polyfillsPlugin(imports, externalSystemJS) { return { name: 'vite:legacy-polyfills', resolveId(id) { if (id === polyfillId) { return id } }, load(id) { if (id === polyfillId) { return ( [...imports].map((i) => `import "${i}";`).join('') + (externalSystemJS ? '' : `import "systemjs/dist/s.min.js";`) ) } } } } /** * @param {import('rollup').RenderedChunk} chunk * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyChunk(chunk, options) { return options.format === 'system' && chunk.fileName.includes('-legacy') } /** * @param {import('rollup').OutputBundle} bundle * @param {import('rollup').NormalizedOutputOptions} options */ function isLegacyBundle(bundle, options) { if (options.format === 'system') { const entryChunk = Object.values(bundle).find( (output) => output.type === 'chunk' && output.isEntry ) return !!entryChunk && entryChunk.fileName.includes('-legacy') } return false } /** * @param {Set<string>} polyfills */ function recordAndRemovePolyfillBabelPlugin(polyfills) { return ({ types: t }) => ({ name: 'vite-remove-polyfill-import', post({ path }) { path.get('body').forEach((p) => { if (t.isImportDeclaration(p)) { polyfills.add(p.node.source.value) p.remove() } }) } }) } function replaceLegacyEnvBabelPlugin() { return ({ types: t }) => ({ name: 'vite-replace-env-legacy', visitor: { Identifier(path) { if (path.node.name === legacyEnvVarMarker) { path.replaceWith(t.booleanLiteral(true)) } } } }) } function wrapIIFEBabelPlugin() { return ({ types: t, template }) => { const buildIIFE = template(';(function(){%%body%%})();') return { name: 'vite-wrap-iife', post({ path }) { if (!this.isWrapped) { this.isWrapped = true path.replaceWith(t.program(buildIIFE({ body: path.node.body }))) } } } } } module.exports = viteLegacyPlugin viteLegacyPlugin.default = viteLegacyPlugin viteLegacyPlugin.cspHashes = [ createHash('sha256').update(safari10NoModuleFix).digest('base64'), createHash('sha256').update(systemJSInlineCode).digest('base64'), createHash('sha256').update(dynamicFallbackInlineCode).digest('base64') ]
packages/plugin-legacy/index.js
1
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.9963456988334656, 0.015159031376242638, 0.0001658504770603031, 0.00017400139768142253, 0.11816134303808212 ]
{ "id": 3, "code_window": [ "\n", "viteLegacyPlugin.cspHashes = [\n", " createHash('sha256').update(safari10NoModuleFix).digest('base64'),\n", " createHash('sha256').update(systemJSInlineCode).digest('base64'),\n", " createHash('sha256').update(dynamicFallbackInlineCode).digest('base64')\n", "]" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " createHash('sha256').update(detectDynamicImportVarInitCode).digest('base64'),\n", " createHash('sha256').update(detectDynamicImportCode).digest('base64'),\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 697 }
// @ts-check import fs from 'fs' import path from 'path' import nodeResolve from '@rollup/plugin-node-resolve' import typescript from '@rollup/plugin-typescript' import commonjs from '@rollup/plugin-commonjs' import json from '@rollup/plugin-json' import alias from '@rollup/plugin-alias' import license from 'rollup-plugin-license' import MagicString from 'magic-string' import colors from 'picocolors' import fg from 'fast-glob' import { sync as resolve } from 'resolve' /** * @type { import('rollup').RollupOptions } */ const envConfig = { input: path.resolve(__dirname, 'src/client/env.ts'), plugins: [ typescript({ target: 'es2018', include: ['src/client/env.ts'], baseUrl: path.resolve(__dirname, 'src/env'), paths: { 'types/*': ['../../types/*'] } }) ], output: { file: path.resolve(__dirname, 'dist/client', 'env.mjs'), sourcemap: true } } /** * @type { import('rollup').RollupOptions } */ const clientConfig = { input: path.resolve(__dirname, 'src/client/client.ts'), external: ['./env', '@vite/env'], plugins: [ typescript({ target: 'es2018', include: ['src/client/**/*.ts'], baseUrl: path.resolve(__dirname, 'src/client'), paths: { 'types/*': ['../../types/*'] } }) ], output: { file: path.resolve(__dirname, 'dist/client', 'client.mjs'), sourcemap: true } } /** * @type { import('rollup').RollupOptions } */ const sharedNodeOptions = { treeshake: { moduleSideEffects: 'no-external', propertyReadSideEffects: false, tryCatchDeoptimization: false }, output: { dir: path.resolve(__dirname, 'dist'), entryFileNames: `node/[name].js`, chunkFileNames: 'node/chunks/dep-[hash].js', exports: 'named', format: 'cjs', externalLiveBindings: false, freeze: false }, onwarn(warning, warn) { // node-resolve complains a lot about this but seems to still work? if (warning.message.includes('Package subpath')) { return } // we use the eval('require') trick to deal with optional deps if (warning.message.includes('Use of eval')) { return } if (warning.message.includes('Circular dependency')) { return } warn(warning) } } /** * * @param {boolean} isProduction * @returns {import('rollup').RollupOptions} */ const createNodeConfig = (isProduction) => { /** * @type { import('rollup').RollupOptions } */ const nodeConfig = { ...sharedNodeOptions, input: { index: path.resolve(__dirname, 'src/node/index.ts'), cli: path.resolve(__dirname, 'src/node/cli.ts') }, output: { ...sharedNodeOptions.output, sourcemap: !isProduction }, external: [ 'fsevents', ...Object.keys(require('./package.json').dependencies), ...(isProduction ? [] : Object.keys(require('./package.json').devDependencies)) ], plugins: [ alias({ // packages with "module" field that doesn't play well with cjs bundles entries: { '@vue/compiler-dom': require.resolve( '@vue/compiler-dom/dist/compiler-dom.cjs.js' ) } }), nodeResolve({ preferBuiltins: true }), typescript({ tsconfig: 'src/node/tsconfig.json', module: 'esnext', target: 'es2019', include: ['src/**/*.ts', 'types/**'], exclude: ['src/**/__tests__/**'], esModuleInterop: true, // in production we use api-extractor for dts generation // in development we need to rely on the rollup ts plugin ...(isProduction ? { declaration: false, sourceMap: false } : { declaration: true, declarationDir: path.resolve(__dirname, 'dist/node') }) }), // Some deps have try...catch require of optional deps, but rollup will // generate code that force require them upfront for side effects. // Shim them with eval() so rollup can skip these calls. isProduction && shimDepsPlugin({ 'plugins/terser.ts': { src: `require.resolve('terser'`, replacement: `require.resolve('vite/dist/node/terser'` }, // chokidar -> fsevents 'fsevents-handler.js': { src: `require('fsevents')`, replacement: `eval('require')('fsevents')` }, // cac re-assigns module.exports even in its mjs dist 'cac/dist/index.mjs': { src: `if (typeof module !== "undefined") {`, replacement: `if (false) {` }, // postcss-import -> sugarss 'process-content.js': { src: 'require("sugarss")', replacement: `eval('require')('sugarss')` }, 'lilconfig/dist/index.js': { pattern: /: require,/g, replacement: `: eval('require'),` } }), commonjs({ extensions: ['.js'], // Optional peer deps of ws. Native deps that are mostly for performance. // Since ws is not that perf critical for us, just ignore these deps. ignore: ['bufferutil', 'utf-8-validate'] }), json(), isProduction && licensePlugin() ] } return nodeConfig } /** * Terser needs to be run inside a worker, so it cannot be part of the main * bundle. We produce a separate bundle for it and shims plugin/terser.ts to * use the production path during build. * * @type { import('rollup').RollupOptions } */ const terserConfig = { ...sharedNodeOptions, output: { ...sharedNodeOptions.output, exports: 'default', sourcemap: false }, input: { terser: require.resolve('terser') }, plugins: [nodeResolve(), commonjs()] } /** * @type { (deps: Record<string, { src?: string, replacement: string, pattern?: RegExp }>) => import('rollup').Plugin } */ function shimDepsPlugin(deps) { const transformed = {} return { name: 'shim-deps', transform(code, id) { for (const file in deps) { if (id.replace(/\\/g, '/').endsWith(file)) { const { src, replacement, pattern } = deps[file] const magicString = new MagicString(code) if (src) { const pos = code.indexOf(src) if (pos < 0) { this.error( `Could not find expected src "${src}" in file "${file}"` ) } transformed[file] = true magicString.overwrite(pos, pos + src.length, replacement) console.log(`shimmed: ${file}`) } if (pattern) { let match while ((match = pattern.exec(code))) { transformed[file] = true const start = match.index const end = start + match[0].length magicString.overwrite(start, end, replacement) } if (!transformed[file]) { this.error( `Could not find expected pattern "${pattern}" in file "${file}"` ) } console.log(`shimmed: ${file}`) } return { code: magicString.toString(), map: magicString.generateMap({ hires: true }) } } } }, buildEnd(err) { if (!err) { for (const file in deps) { if (!transformed[file]) { this.error( `Did not find "${file}" which is supposed to be shimmed, was the file renamed?` ) } } } } } } function licensePlugin() { return license({ thirdParty(dependencies) { // https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js // MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md const coreLicense = fs.readFileSync( path.resolve(__dirname, '../../LICENSE') ) function sortLicenses(licenses) { let withParenthesis = [] let noParenthesis = [] licenses.forEach((license) => { if (/^\(/.test(license)) { withParenthesis.push(license) } else { noParenthesis.push(license) } }) withParenthesis = withParenthesis.sort() noParenthesis = noParenthesis.sort() return [...noParenthesis, ...withParenthesis] } const licenses = new Set() const dependencyLicenseTexts = dependencies .sort(({ name: nameA }, { name: nameB }) => nameA > nameB ? 1 : nameB > nameA ? -1 : 0 ) .map( ({ name, license, licenseText, author, maintainers, contributors, repository }) => { let text = `## ${name}\n` if (license) { text += `License: ${license}\n` } const names = new Set() if (author && author.name) { names.add(author.name) } for (const person of maintainers.concat(contributors)) { if (person && person.name) { names.add(person.name) } } if (names.size > 0) { text += `By: ${Array.from(names).join(', ')}\n` } if (repository) { text += `Repository: ${repository.url || repository}\n` } if (!licenseText) { try { const pkgDir = path.dirname( resolve(path.join(name, 'package.json'), { preserveSymlinks: false }) ) const licenseFile = fg.sync(`${pkgDir}/LICENSE*`, { caseSensitiveMatch: false })[0] if (licenseFile) { licenseText = fs.readFileSync(licenseFile, 'utf-8') } } catch {} } if (licenseText) { text += '\n' + licenseText .trim() .replace(/(\r\n|\r)/gm, '\n') .split('\n') .map((line) => `> ${line}`) .join('\n') + '\n' } licenses.add(license) return text } ) .join('\n---------------------------------------\n\n') const licenseText = `# Vite core license\n` + `Vite is released under the MIT license:\n\n` + coreLicense + `\n# Licenses of bundled dependencies\n` + `The published Vite artifact additionally contains code with the following licenses:\n` + `${sortLicenses(licenses).join(', ')}\n\n` + `# Bundled dependencies:\n` + dependencyLicenseTexts const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8') if (existingLicenseText !== licenseText) { fs.writeFileSync('LICENSE.md', licenseText) console.warn( colors.yellow( '\nLICENSE.md updated. You should commit the updated file.\n' ) ) } } }) } export default (commandLineArgs) => { const isDev = commandLineArgs.watch const isProduction = !isDev return [ envConfig, clientConfig, createNodeConfig(isProduction), ...(isProduction ? [terserConfig] : []) ] }
packages/vite/rollup.config.js
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.0001770271483110264, 0.00017222708265762776, 0.00016713129298295826, 0.00017292775737587363, 0.00000275079673883738 ]