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": 2, "code_window": [ "\n", "from superset.constants import RouteMethod\n", "from superset.models.sql_lab import Query\n", "from superset.queries.filters import QueryFilter\n", "from superset.queries.schemas import openapi_spec_methods_override\n", "from superset.views.base_api import BaseSupersetModelRestApi\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "from superset.views.base_api import BaseSupersetModelRestApi, RelatedFieldFilter\n", "from superset.views.filters import FilterRelatedOwners\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 24 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable no-unused-expressions */ import React from 'react'; import { OverlayTrigger, Popover, Tab, Tabs, Radio } from 'react-bootstrap'; import sinon from 'sinon'; import { styledMount as mount } from 'spec/helpers/theming'; import Label from 'src/components/Label'; import DateFilterControl from 'src/explore/components/controls/DateFilterControl'; import ControlHeader from 'src/explore/components/ControlHeader'; // Mock moment.js to use a specific date jest.mock('moment', () => { const testDate = new Date('2020-09-07'); return () => jest.requireActual('moment')(testDate); }); const defaultProps = { animation: false, name: 'date', onChange: sinon.spy(), value: '90 days ago', label: 'date', }; describe('DateFilterControl', () => { let wrapper; beforeEach(() => { wrapper = mount(<DateFilterControl {...defaultProps} />); }); it('renders', () => { expect(wrapper.find(DateFilterControl)).toExist(); }); it('renders a ControlHeader', () => { const controlHeader = wrapper.find(ControlHeader); expect(controlHeader).toHaveLength(1); }); it('renders an OverlayTrigger', () => { expect(wrapper.find(OverlayTrigger)).toExist(); }); it('renders a popover', () => { const { overlay } = wrapper.find(OverlayTrigger).first().props(); const overlayWrapper = mount(overlay); expect(overlayWrapper.find(Popover)).toExist(); }); it('calls open/close methods on trigger click', () => { const open = jest.fn(); const close = jest.fn(); const props = { ...defaultProps, onOpenDateFilterControl: open, onCloseDateFilterControl: close, }; const testWrapper = mount(<DateFilterControl {...props} />); const label = testWrapper.find(Label).first(); label.simulate('click'); expect(open).toBeCalled(); expect(close).not.toBeCalled(); label.simulate('click'); expect(close).toBeCalled(); }); it('renders two tabs in popover', () => { const { overlay } = wrapper.find(OverlayTrigger).first().props(); const overlayWrapper = mount(overlay); const popover = overlayWrapper.find(Popover).first(); expect(popover.find(Tabs)).toExist(); expect(popover.find(Tab)).toHaveLength(2); }); it('renders default time options', () => { const { overlay } = wrapper.find(OverlayTrigger).first().props(); const overlayWrapper = mount(overlay); const defaultTab = overlayWrapper.find(Tab).first(); expect(defaultTab.find(Radio)).toExist(); expect(defaultTab.find(Radio)).toHaveLength(6); }); it('renders tooltips over timeframe options', () => { const { overlay } = wrapper.find(OverlayTrigger).first().props(); const overlayWrapper = mount(overlay); const defaultTab = overlayWrapper.find(Tab).first(); const radioTrigger = defaultTab.find(OverlayTrigger); expect(radioTrigger).toExist(); expect(radioTrigger).toHaveLength(6); }); it('renders the correct time range in tooltip', () => { const { overlay } = wrapper.find(OverlayTrigger).first().props(); const overlayWrapper = mount(overlay); const defaultTab = overlayWrapper.find(Tab).first(); const triggers = defaultTab.find(OverlayTrigger); const expectedLabels = { 'Last day': '2020-09-06 < col < 2020-09-07', 'Last week': '2020-08-31 < col < 2020-09-07', 'Last month': '2020-08-07 < col < 2020-09-07', 'Last quarter': '2020-06-07 < col < 2020-09-07', 'Last year': '2019-01-01 < col < 2020-01-01', 'No filter': '-∞ < col < ∞', }; triggers.forEach(trigger => { const { props } = trigger.props().overlay; const label = props.id.split('tooltip-')[1]; expect(trigger.props().overlay.props.children).toEqual( expectedLabels[label], ); }); }); });
superset-frontend/spec/javascripts/explore/components/DateFilterControl_spec.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017895321070682257, 0.00017548530013300478, 0.00016915233572945, 0.00017595835379324853, 0.000002812430921039777 ]
{ "id": 2, "code_window": [ "\n", "from superset.constants import RouteMethod\n", "from superset.models.sql_lab import Query\n", "from superset.queries.filters import QueryFilter\n", "from superset.queries.schemas import openapi_spec_methods_override\n", "from superset.views.base_api import BaseSupersetModelRestApi\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "from superset.views.base_api import BaseSupersetModelRestApi, RelatedFieldFilter\n", "from superset.views.filters import FilterRelatedOwners\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 24 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, FormControl, OverlayTrigger, Popover, } from 'react-bootstrap'; import Select from 'src/components/Select'; import { t } from '@superset-ui/core'; import { InfoTooltipWithTrigger } from '@superset-ui/chart-controls'; import BoundsControl from './BoundsControl'; import CheckboxControl from './CheckboxControl'; const propTypes = { label: PropTypes.string, tooltip: PropTypes.string, colType: PropTypes.string, width: PropTypes.string, height: PropTypes.string, timeLag: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), timeRatio: PropTypes.string, comparisonType: PropTypes.string, showYAxis: PropTypes.bool, yAxisBounds: PropTypes.array, bounds: PropTypes.array, d3format: PropTypes.string, dateFormat: PropTypes.string, onChange: PropTypes.func, }; const defaultProps = { label: t('Time Series Columns'), tooltip: '', colType: '', width: '', height: '', timeLag: '', timeRatio: '', comparisonType: '', showYAxis: false, yAxisBounds: [null, null], bounds: [null, null], d3format: '', dateFormat: '', onChange: () => {}, }; const comparisonTypeOptions = [ { value: 'value', label: 'Actual value' }, { value: 'diff', label: 'Difference' }, { value: 'perc', label: 'Percentage' }, { value: 'perc_change', label: 'Percentage Change' }, ]; const colTypeOptions = [ { value: 'time', label: 'Time Comparison' }, { value: 'contrib', label: 'Contribution' }, { value: 'spark', label: 'Sparkline' }, { value: 'avg', label: 'Period Average' }, ]; export default class TimeSeriesColumnControl extends React.Component { constructor(props) { super(props); const state = { label: this.props.label, tooltip: this.props.tooltip, colType: this.props.colType, width: this.props.width, height: this.props.height, timeLag: this.props.timeLag || 0, timeRatio: this.props.timeRatio, comparisonType: this.props.comparisonType, showYAxis: this.props.showYAxis, yAxisBounds: this.props.yAxisBounds, bounds: this.props.bounds, d3format: this.props.d3format, dateFormat: this.props.dateFormat, }; delete state.onChange; this.state = state; this.onChange = this.onChange.bind(this); } onChange() { this.props.onChange(this.state); } onSelectChange(attr, opt) { this.setState({ [attr]: opt.value }, this.onChange); } onTextInputChange(attr, event) { this.setState({ [attr]: event.target.value }, this.onChange); } onCheckboxChange(attr, value) { this.setState({ [attr]: value }, this.onChange); } onBoundsChange(bounds) { this.setState({ bounds }, this.onChange); } onYAxisBoundsChange(yAxisBounds) { this.setState({ yAxisBounds }, this.onChange); } setType() {} textSummary() { return `${this.state.label}`; } edit() {} formRow(label, tooltip, ttLabel, control) { return ( <Row style={{ marginTop: '5px' }}> <Col md={5}> {`${label} `} <InfoTooltipWithTrigger placement="top" tooltip={tooltip} label={ttLabel} /> </Col> <Col md={7}>{control}</Col> </Row> ); } renderPopover() { return ( <Popover id="ts-col-popo" title="Column Configuration"> <div style={{ width: 300 }}> {this.formRow( 'Label', 'The column header label', 'time-lag', <FormControl value={this.state.label} onChange={this.onTextInputChange.bind(this, 'label')} bsSize="small" placeholder="Label" />, )} {this.formRow( 'Tooltip', 'Column header tooltip', 'col-tooltip', <FormControl value={this.state.tooltip} onChange={this.onTextInputChange.bind(this, 'tooltip')} bsSize="small" placeholder="Tooltip" />, )} {this.formRow( 'Type', 'Type of comparison, value difference or percentage', 'col-type', <Select value={this.state.colType} clearable={false} onChange={this.onSelectChange.bind(this, 'colType')} options={colTypeOptions} />, )} <hr /> {this.state.colType === 'spark' && this.formRow( 'Width', 'Width of the sparkline', 'spark-width', <FormControl value={this.state.width} onChange={this.onTextInputChange.bind(this, 'width')} bsSize="small" placeholder="Width" />, )} {this.state.colType === 'spark' && this.formRow( 'Height', 'Height of the sparkline', 'spark-width', <FormControl value={this.state.height} onChange={this.onTextInputChange.bind(this, 'height')} bsSize="small" placeholder="height" />, )} {['time', 'avg'].indexOf(this.state.colType) >= 0 && this.formRow( 'Time Lag', 'Number of periods to compare against', 'time-lag', <FormControl value={this.state.timeLag} onChange={this.onTextInputChange.bind(this, 'timeLag')} bsSize="small" placeholder="Time Lag" />, )} {['spark'].indexOf(this.state.colType) >= 0 && this.formRow( 'Time Ratio', 'Number of periods to ratio against', 'time-ratio', <FormControl value={this.state.timeRatio} onChange={this.onTextInputChange.bind(this, 'timeRatio')} bsSize="small" placeholder="Time Ratio" />, )} {this.state.colType === 'time' && this.formRow( 'Type', 'Type of comparison, value difference or percentage', 'comp-type', <Select value={this.state.comparisonType} clearable={false} onChange={this.onSelectChange.bind(this, 'comparisonType')} options={comparisonTypeOptions} />, )} {this.state.colType === 'spark' && this.formRow( 'Show Y-axis', 'Show Y-axis on the sparkline. Will display the manually set min/max if set or min/max values in the data otherwise.', 'show-y-axis-bounds', <CheckboxControl value={this.state.showYAxis} onChange={this.onCheckboxChange.bind(this, 'showYAxis')} />, )} {this.state.colType === 'spark' && this.formRow( 'Y-axis bounds', 'Manually set min/max values for the y-axis.', 'y-axis-bounds', <BoundsControl value={this.state.yAxisBounds} onChange={this.onYAxisBoundsChange.bind(this)} />, )} {this.state.colType !== 'spark' && this.formRow( 'Color bounds', `Number bounds used for color encoding from red to blue. Reverse the numbers for blue to red. To get pure red or blue, you can enter either only min or max.`, 'bounds', <BoundsControl value={this.state.bounds} onChange={this.onBoundsChange.bind(this)} />, )} {this.formRow( 'Number format', 'Optional d3 number format string', 'd3-format', <FormControl value={this.state.d3format} onChange={this.onTextInputChange.bind(this, 'd3format')} bsSize="small" placeholder="Number format string" />, )} {this.state.colType === 'spark' && this.formRow( 'Date format', 'Optional d3 date format string', 'date-format', <FormControl value={this.state.dateFormat} onChange={this.onTextInputChange.bind(this, 'dateFormat')} bsSize="small" placeholder="Date format string" />, )} </div> </Popover> ); } render() { return ( <span> {this.textSummary()}{' '} <OverlayTrigger container={document.body} trigger="click" rootClose ref="trigger" placement="right" overlay={this.renderPopover()} > <InfoTooltipWithTrigger icon="edit" className="text-primary" onClick={this.edit.bind(this)} label="edit-ts-column" /> </OverlayTrigger> </span> ); } } TimeSeriesColumnControl.propTypes = propTypes; TimeSeriesColumnControl.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/TimeSeriesColumnControl.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017969819600693882, 0.00017399509670212865, 0.0001676078245509416, 0.00017430123989470303, 0.0000030199573757272447 ]
{ "id": 3, "code_window": [ "\n", " resource_name = \"query\"\n", " allow_browser_login = True\n", " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST}\n", "\n", " class_permission_name = \"QueryView\"\n", " list_columns = [\n", " \"user.username\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST, RouteMethod.RELATED}\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 34 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from flask_appbuilder.models.sqla.interface import SQLAInterface from superset.constants import RouteMethod from superset.models.sql_lab import Query from superset.queries.filters import QueryFilter from superset.queries.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi logger = logging.getLogger(__name__) class QueryRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(Query) resource_name = "query" allow_browser_login = True include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST} class_permission_name = "QueryView" list_columns = [ "user.username", "database.database_name", "status", "start_time", "end_time", ] show_columns = [ "client_id", "tmp_table_name", "tmp_schema_name", "status", "tab_name", "sql_editor_id", "database.id", "schema", "sql", "select_sql", "executed_sql", "limit", "select_as_cta", "select_as_cta_used", "progress", "rows", "error_message", "results_key", "start_time", "start_running_time", "end_time", "end_result_backend_time", "tracking_url", "changed_on", ] base_filters = [["id", QueryFilter, lambda: []]] base_order = ("changed_on", "desc") openapi_spec_tag = "Queries" openapi_spec_methods = openapi_spec_methods_override
superset/queries/api.py
1
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.9981870055198669, 0.12520825862884521, 0.00017212488455697894, 0.0002924744039773941, 0.32995522022247314 ]
{ "id": 3, "code_window": [ "\n", " resource_name = \"query\"\n", " allow_browser_login = True\n", " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST}\n", "\n", " class_permission_name = \"QueryView\"\n", " list_columns = [\n", " \"user.username\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST, RouteMethod.RELATED}\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 34 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export type ToastType = | 'INFO_TOAST' | 'SUCCESS_TOAST' | 'WARNING_TOAST' | 'DANGER_TOAST';
superset-frontend/src/messageToasts/types.ts
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.000175831577507779, 0.000175434208358638, 0.00017511310579720885, 0.00017535791266709566, 2.9823374347870413e-7 ]
{ "id": 3, "code_window": [ "\n", " resource_name = \"query\"\n", " allow_browser_login = True\n", " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST}\n", "\n", " class_permission_name = \"QueryView\"\n", " list_columns = [\n", " \"user.username\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST, RouteMethod.RELATED}\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 34 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { t } from '@superset-ui/core'; import 'react-checkbox-tree/lib/react-checkbox-tree.css'; import { CheckboxChecked, CheckboxUnchecked, CheckboxHalfChecked, } from '../../../components/CheckboxIcons'; const treeIcons = { check: <CheckboxChecked />, uncheck: <CheckboxUnchecked />, halfCheck: <CheckboxHalfChecked />, expandClose: <span className="rct-icon rct-icon-expand-close" />, expandOpen: <span className="rct-icon rct-icon-expand-open" />, expandAll: ( <span className="rct-icon rct-icon-expand-all">{t('Expand all')}</span> ), collapseAll: ( <span className="rct-icon rct-icon-collapse-all">{t('Collapse all')}</span> ), parentClose: <span className="rct-icon rct-icon-parent-close" />, parentOpen: <span className="rct-icon rct-icon-parent-open" />, leaf: <span className="rct-icon rct-icon-leaf" />, }; export default treeIcons;
superset-frontend/src/dashboard/components/filterscope/treeIcons.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017725279030855745, 0.00017551929340697825, 0.00017297384329140186, 0.0001760488230502233, 0.0000014424855407924042 ]
{ "id": 3, "code_window": [ "\n", " resource_name = \"query\"\n", " allow_browser_login = True\n", " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST}\n", "\n", " class_permission_name = \"QueryView\"\n", " list_columns = [\n", " \"user.username\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST, RouteMethod.RELATED}\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 34 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-env browser */ import React from 'react'; import PropTypes from 'prop-types'; import { DropdownButton, MenuItem } from 'react-bootstrap'; import { List } from 'react-virtualized'; import SearchInput, { createFilter } from 'react-search-input'; import { t } from '@superset-ui/core'; import AddSliceCard from './AddSliceCard'; import AddSliceDragPreview from './dnd/AddSliceDragPreview'; import DragDroppable from './dnd/DragDroppable'; import Loading from '../../components/Loading'; import { CHART_TYPE, NEW_COMPONENT_SOURCE_TYPE } from '../util/componentTypes'; import { NEW_CHART_ID, NEW_COMPONENTS_SOURCE_ID } from '../util/constants'; import { slicePropShape } from '../util/propShapes'; const propTypes = { fetchAllSlices: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, slices: PropTypes.objectOf(slicePropShape).isRequired, lastUpdated: PropTypes.number.isRequired, errorMessage: PropTypes.string, userId: PropTypes.string.isRequired, selectedSliceIds: PropTypes.arrayOf(PropTypes.number), editMode: PropTypes.bool, height: PropTypes.number, }; const defaultProps = { selectedSliceIds: [], editMode: false, errorMessage: '', height: window.innerHeight, }; const KEYS_TO_FILTERS = ['slice_name', 'viz_type', 'datasource_name']; const KEYS_TO_SORT = [ { key: 'slice_name', label: 'Name' }, { key: 'viz_type', label: 'Vis type' }, { key: 'datasource_name', label: 'Dataset' }, { key: 'changed_on', label: 'Recent' }, ]; const MARGIN_BOTTOM = 16; const SIDEPANE_HEADER_HEIGHT = 30; const SLICE_ADDER_CONTROL_HEIGHT = 64; const DEFAULT_CELL_HEIGHT = 112; class SliceAdder extends React.Component { static sortByComparator(attr) { const desc = attr === 'changed_on' ? -1 : 1; return (a, b) => { if (a[attr] < b[attr]) { return -1 * desc; } if (a[attr] > b[attr]) { return 1 * desc; } return 0; }; } constructor(props) { super(props); this.state = { filteredSlices: [], searchTerm: '', sortBy: KEYS_TO_SORT.findIndex(item => item.key === 'changed_on'), selectedSliceIdsSet: new Set(props.selectedSliceIds), }; this.rowRenderer = this.rowRenderer.bind(this); this.searchUpdated = this.searchUpdated.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleSelect = this.handleSelect.bind(this); } componentDidMount() { this.slicesRequest = this.props.fetchAllSlices(this.props.userId); } UNSAFE_componentWillReceiveProps(nextProps) { const nextState = {}; if (nextProps.lastUpdated !== this.props.lastUpdated) { nextState.filteredSlices = Object.values(nextProps.slices) .filter(createFilter(this.state.searchTerm, KEYS_TO_FILTERS)) .sort(SliceAdder.sortByComparator(KEYS_TO_SORT[this.state.sortBy].key)); } if (nextProps.selectedSliceIds !== this.props.selectedSliceIds) { nextState.selectedSliceIdsSet = new Set(nextProps.selectedSliceIds); } if (Object.keys(nextState).length) { this.setState(nextState); } } componentWillUnmount() { if (this.slicesRequest && this.slicesRequest.abort) { this.slicesRequest.abort(); } } getFilteredSortedSlices(searchTerm, sortBy) { return Object.values(this.props.slices) .filter(createFilter(searchTerm, KEYS_TO_FILTERS)) .sort(SliceAdder.sortByComparator(KEYS_TO_SORT[sortBy].key)); } handleKeyPress(ev) { if (ev.key === 'Enter') { ev.preventDefault(); this.searchUpdated(ev.target.value); } } searchUpdated(searchTerm) { this.setState(prevState => ({ searchTerm, filteredSlices: this.getFilteredSortedSlices( searchTerm, prevState.sortBy, ), })); } handleSelect(sortBy) { this.setState(prevState => ({ sortBy, filteredSlices: this.getFilteredSortedSlices( prevState.searchTerm, sortBy, ), })); } rowRenderer({ key, index, style }) { const { filteredSlices, selectedSliceIdsSet } = this.state; const cellData = filteredSlices[index]; const isSelected = selectedSliceIdsSet.has(cellData.slice_id); const type = CHART_TYPE; const id = NEW_CHART_ID; const meta = { chartId: cellData.slice_id, sliceName: cellData.slice_name, }; return ( <DragDroppable key={key} component={{ type, id, meta }} parentComponent={{ id: NEW_COMPONENTS_SOURCE_ID, type: NEW_COMPONENT_SOURCE_TYPE, }} index={index} depth={0} disableDragDrop={isSelected} editMode={this.props.editMode} // we must use a custom drag preview within the List because // it does not seem to work within a fixed-position container useEmptyDragPreview // List library expect style props here // actual style should be applied to nested AddSliceCard component style={{}} > {({ dragSourceRef }) => ( <AddSliceCard innerRef={dragSourceRef} style={style} sliceName={cellData.slice_name} lastModified={cellData.changed_on_humanized} visType={cellData.viz_type} datasourceUrl={cellData.datasource_url} datasourceName={cellData.datasource_name} isSelected={isSelected} /> )} </DragDroppable> ); } render() { const slicesListHeight = this.props.height - SIDEPANE_HEADER_HEIGHT - SLICE_ADDER_CONTROL_HEIGHT - MARGIN_BOTTOM; return ( <div className="slice-adder-container"> <div className="controls"> <SearchInput placeholder={t('Filter your charts')} className="search-input" onChange={this.searchUpdated} onKeyPress={this.handleKeyPress} /> <DropdownButton title={`Sort by ${KEYS_TO_SORT[this.state.sortBy].label}`} onSelect={this.handleSelect} id="slice-adder-sortby" > {KEYS_TO_SORT.map((item, index) => ( <MenuItem key={item.key} eventKey={index}> Sort by {item.label} </MenuItem> ))} </DropdownButton> </div> {this.props.isLoading && <Loading />} {!this.props.isLoading && this.state.filteredSlices.length > 0 && ( <List width={376} height={slicesListHeight} rowCount={this.state.filteredSlices.length} rowHeight={DEFAULT_CELL_HEIGHT} rowRenderer={this.rowRenderer} searchTerm={this.state.searchTerm} sortBy={this.state.sortBy} selectedSliceIds={this.props.selectedSliceIds} /> )} {this.props.errorMessage && ( <div className="error-message">{this.props.errorMessage}</div> )} {/* Drag preview is just a single fixed-position element */} <AddSliceDragPreview slices={this.state.filteredSlices} /> </div> ); } } SliceAdder.propTypes = propTypes; SliceAdder.defaultProps = defaultProps; export default SliceAdder;
superset-frontend/src/dashboard/components/SliceAdder.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00030943474848754704, 0.0001788146182661876, 0.00016453744319733232, 0.00017468363512307405, 0.000026355528461863287 ]
{ "id": 4, "code_window": [ "\n", " openapi_spec_tag = \"Queries\"\n", " openapi_spec_methods = openapi_spec_methods_override\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", " related_field_filters = {\n", " \"created_by\": RelatedFieldFilter(\"first_name\", FilterRelatedOwners),\n", " }\n", " allowed_rel_fields = {\"user\"}" ], "file_path": "superset/queries/api.py", "type": "add", "edit_start_line_idx": 75 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from flask_appbuilder.models.sqla.interface import SQLAInterface from superset.constants import RouteMethod from superset.models.sql_lab import Query from superset.queries.filters import QueryFilter from superset.queries.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi logger = logging.getLogger(__name__) class QueryRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(Query) resource_name = "query" allow_browser_login = True include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST} class_permission_name = "QueryView" list_columns = [ "user.username", "database.database_name", "status", "start_time", "end_time", ] show_columns = [ "client_id", "tmp_table_name", "tmp_schema_name", "status", "tab_name", "sql_editor_id", "database.id", "schema", "sql", "select_sql", "executed_sql", "limit", "select_as_cta", "select_as_cta_used", "progress", "rows", "error_message", "results_key", "start_time", "start_running_time", "end_time", "end_result_backend_time", "tracking_url", "changed_on", ] base_filters = [["id", QueryFilter, lambda: []]] base_order = ("changed_on", "desc") openapi_spec_tag = "Queries" openapi_spec_methods = openapi_spec_methods_override
superset/queries/api.py
1
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.9978506565093994, 0.23243901133537292, 0.0001665001327637583, 0.0001827145752031356, 0.4036160409450531 ]
{ "id": 4, "code_window": [ "\n", " openapi_spec_tag = \"Queries\"\n", " openapi_spec_methods = openapi_spec_methods_override\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", " related_field_filters = {\n", " \"created_by\": RelatedFieldFilter(\"first_name\", FilterRelatedOwners),\n", " }\n", " allowed_rel_fields = {\"user\"}" ], "file_path": "superset/queries/api.py", "type": "add", "edit_start_line_idx": 75 }
--- name: Security title: Security route: /docs/security --- ## Security Apache Software Foundation takes a rigorous standpoint in annihilating the security issues in its software projects. Apache Superset is highly sensitive and forthcoming to issues pertaining to its features and functionality. If you have apprehensions regarding Superset security or you discover vulnerability or potential threat, don’t hesitate to get in touch with the Apache Security Team by dropping a mail at [email protected]. In the mail, specify the project name Superset with the description of the issue or potential threat. You are also urged to recommend the way to reproduce and replicate the issue. The security team and the Superset community will get back to you after assessing and analysing the findings. PLEASE PAY ATTENTION to report the security issue on the security email before disclosing it on public domain. The ASF Security Team maintains a page with the description of how vulnerabilities and potential threats are handled, check their web page for more details.
docs/src/pages/docs/security-page.mdx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.000170834333403036, 0.00016927719116210938, 0.00016617070650681853, 0.00017082651902455837, 0.0000021966152417007834 ]
{ "id": 4, "code_window": [ "\n", " openapi_spec_tag = \"Queries\"\n", " openapi_spec_methods = openapi_spec_methods_override\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", " related_field_filters = {\n", " \"created_by\": RelatedFieldFilter(\"first_name\", FilterRelatedOwners),\n", " }\n", " allowed_rel_fields = {\"user\"}" ], "file_path": "superset/queries/api.py", "type": "add", "edit_start_line_idx": 75 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M10.5 16C10.5 16.5523 10.9477 17 11.5 17H12.5C13.0523 17 13.5 16.5523 13.5 16C13.5 15.4477 13.0523 15 12.5 15H11.5C10.9477 15 10.5 15.4477 10.5 16ZM6.5 7C5.94772 7 5.5 7.44772 5.5 8C5.5 8.55228 5.94772 9 6.5 9H17.5C18.0523 9 18.5 8.55228 18.5 8C18.5 7.44772 18.0523 7 17.5 7H6.5ZM8.5 12C8.5 12.5523 8.94772 13 9.5 13H14.5C15.0523 13 15.5 12.5523 15.5 12C15.5 11.4477 15.0523 11 14.5 11H9.5C8.94772 11 8.5 11.4477 8.5 12Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/filter.svg
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017698512237984687, 0.00017622904852032661, 0.0001758142898324877, 0.00017588773334864527, 5.354650625122304e-7 ]
{ "id": 4, "code_window": [ "\n", " openapi_spec_tag = \"Queries\"\n", " openapi_spec_methods = openapi_spec_methods_override\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", " related_field_filters = {\n", " \"created_by\": RelatedFieldFilter(\"first_name\", FilterRelatedOwners),\n", " }\n", " allowed_rel_fields = {\"user\"}" ], "file_path": "superset/queries/api.py", "type": "add", "edit_start_line_idx": 75 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """reconvert legacy filters into adhoc Revision ID: 78ee127d0d1d Revises: c2acd2cf3df2 Create Date: 2019-11-06 15:23:26.497876 """ # revision identifiers, used by Alembic. revision = "78ee127d0d1d" down_revision = "c2acd2cf3df2" import copy import json import logging import uuid from collections import defaultdict from alembic import op from sqlalchemy import Column, Integer, Text from sqlalchemy.ext.declarative import declarative_base from superset import db from superset.utils.core import ( convert_legacy_filters_into_adhoc, split_adhoc_filters_into_base_filters, ) Base = declarative_base() class Slice(Base): __tablename__ = "slices" id = Column(Integer, primary_key=True) params = Column(Text) def upgrade(): bind = op.get_bind() session = db.Session(bind=bind) for slc in session.query(Slice).all(): if slc.params: try: source = json.loads(slc.params) target = copy.deepcopy(source) convert_legacy_filters_into_adhoc(target) if source != target: slc.params = json.dumps(target, sort_keys=True) except Exception as ex: logging.warn(ex) session.commit() session.close() def downgrade(): pass
superset/migrations/versions/78ee127d0d1d_reconvert_legacy_filters_into_adhoc.py
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.0003122190828435123, 0.00019040284678339958, 0.0001691412035143003, 0.00017509417375549674, 0.00004613554119714536 ]
{ "id": 0, "code_window": [ " port?: number\n", " open?: boolean\n", " }\n", ") {\n", " await require('../dist').optimizeDeps(options)\n", "\n", " const server = require('../dist').createServer(options)\n", "\n", " let port = options.port || 3000\n", " server.on('error', (e: Error & { code?: string }) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/node/cli.ts", "type": "replace", "edit_start_line_idx": 115 }
import path from 'path' import fs from 'fs-extra' import chalk from 'chalk' import { createEsbuildPlugin } from './build/buildPluginEsbuild' import { ServerPlugin } from './server' import { Resolver } from './resolver' import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue' import { CompilerOptions } from '@vue/compiler-sfc' import Rollup, { InputOptions as RollupInputOptions, OutputOptions as RollupOutputOptions } from 'rollup' import { Transform } from './transform' export { Resolver, Transform } /** * Options shared between server and build. */ export interface SharedConfig { /** * Project root directory. Can be an absolute path, or a path relative from * the location of the config file itself. * @default process.cwd() */ root?: string /** * Import alias. Can only be exact mapping, does not support wildcard syntax. */ alias?: Record<string, string> /** * Custom file transforms. */ transforms?: Transform[] /** * Resolvers to map dev server public path requests to/from file system paths, * and optionally map module ids to public path requests. */ resolvers?: Resolver[] /** * Options to pass to @vue/compiler-dom */ vueCompilerOptions?: CompilerOptions /** * Configure what to use for jsx factory and fragment. * @default * { * factory: 'React.createElement', * fragment: 'React.Fragment' * } */ jsx?: | 'vue' | 'preact' | 'react' | { factory?: string fragment?: string } } export interface ServerConfig extends SharedConfig { /** * Whether to use a Service Worker to cache served code. This can greatly * improve full page reload performance, but requires a Service Worker * update + reload on each server restart. * * @default false */ serviceWorker?: boolean plugins?: ServerPlugin[] } export interface BuildConfig extends SharedConfig { /** * Base public path when served in production. * @default '/' */ base?: string /** * Directory relative from `root` where build output will be placed. If the * directory exists, it will be removed before the build. * @default 'dist' */ outDir?: string /** * Directory relative from `outDir` where the built js/css/image assets will * be placed. * @default 'assets' */ assetsDir?: string /** * Static asset files smaller than this number (in bytes) will be inlined as * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable. * @default 4096 */ assetsInlineLimit?: number /** * Whether to generate sourcemap * @default false */ sourcemap?: boolean /** * Set to `false` to dsiable minification, or specify the minifier to use. * Available options are 'terser' or 'esbuild'. * @default 'terser' */ minify?: boolean | 'terser' | 'esbuild' /** * Build for server-side rendering * @default false */ ssr?: boolean // The following are API only and not documented in the CLI. ----------------- /** * Will be passed to rollup.rollup() * https://rollupjs.org/guide/en/#big-list-of-options */ rollupInputOptions?: RollupInputOptions /** * Will be passed to bundle.generate() * https://rollupjs.org/guide/en/#big-list-of-options */ rollupOutputOptions?: RollupOutputOptions /** * Will be passed to rollup-plugin-vue * https://github.com/vuejs/rollup-plugin-vue/blob/next/src/index.ts */ rollupPluginVueOptions?: Partial<RollupPluginVueOptions> /** * Whether to log asset info to console * @default false */ silent?: boolean /** * Whether to write bundle to disk * @default true */ write?: boolean /** * Whether to emit index.html * @default true */ emitIndex?: boolean /** * Whether to emit assets other than JavaScript * @default true */ emitAssets?: boolean } export interface UserConfig extends BuildConfig, Pick<ServerConfig, 'serviceWorker'> { plugins?: Plugin[] configureServer?: ServerPlugin } export interface Plugin extends Pick< UserConfig, | 'alias' | 'transforms' | 'resolvers' | 'configureServer' | 'vueCompilerOptions' | 'rollupInputOptions' | 'rollupOutputOptions' > {} export type ResolvedConfig = UserConfig & { __path?: string } export async function resolveConfig( configPath: string | undefined ): Promise<ResolvedConfig | undefined> { const start = Date.now() let config: ResolvedConfig | undefined let resolvedPath: string | undefined let isTS = false if (configPath) { resolvedPath = path.resolve(process.cwd(), configPath) } else { const jsConfigPath = path.resolve(process.cwd(), 'vite.config.js') if (fs.existsSync(jsConfigPath)) { resolvedPath = jsConfigPath } else { const tsConfigPath = path.resolve(process.cwd(), 'vite.config.ts') if (fs.existsSync(tsConfigPath)) { isTS = true resolvedPath = tsConfigPath } } } if (!resolvedPath) { return } try { if (!isTS) { try { config = require(resolvedPath) } catch (e) { if ( !/Cannot use import statement|Unexpected token 'export'/.test( e.message ) ) { throw e } } } if (!config) { // 2. if we reach here, the file is ts or using es import syntax. // transpile es import syntax to require syntax using rollup. const rollup = require('rollup') as typeof Rollup const esbuilPlugin = await createEsbuildPlugin(false, {}) const bundle = await rollup.rollup({ external: (id: string) => (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json', input: resolvedPath, treeshake: false, plugins: [esbuilPlugin] }) const { output: [{ code }] } = await bundle.generate({ exports: 'named', format: 'cjs' }) config = await loadConfigFromBundledFile(resolvedPath, code) } // normalize config root to absolute if (config.root && !path.isAbsolute(config.root)) { config.root = path.resolve(path.dirname(resolvedPath), config.root) } // resolve plugins if (config.plugins) { for (const plugin of config.plugins) { config = resolvePlugin(config, plugin) } // delete plugins so it doesn't get passed to `createServer` as server // plugins. delete config.plugins } require('debug')('vite:config')( `config resolved in ${Date.now() - start}ms` ) config.__path = resolvedPath return config } catch (e) { console.error( chalk.red(`[vite] failed to load config from ${resolvedPath}:`) ) console.error(e) process.exit(1) } } interface NodeModuleWithCompile extends NodeModule { _compile(code: string, filename: string): any } async function loadConfigFromBundledFile( fileName: string, bundledCode: string ): Promise<UserConfig> { const extension = path.extname(fileName) const defaultLoader = require.extensions[extension]! require.extensions[extension] = (module: NodeModule, filename: string) => { if (filename === fileName) { ;(module as NodeModuleWithCompile)._compile(bundledCode, filename) } else { defaultLoader(module, filename) } } delete require.cache[fileName] const raw = require(fileName) const config = raw.__esModule ? raw.default : raw require.extensions[extension] = defaultLoader return config } function resolvePlugin(config: UserConfig, plugin: Plugin): UserConfig { return { ...config, alias: { ...plugin.alias, ...config.alias }, transforms: [...(config.transforms || []), ...(plugin.transforms || [])], resolvers: [...(config.resolvers || []), ...(plugin.resolvers || [])], configureServer: (ctx) => { if (config.configureServer) { config.configureServer(ctx) } if (plugin.configureServer) { plugin.configureServer(ctx) } }, vueCompilerOptions: { ...config.vueCompilerOptions, ...plugin.vueCompilerOptions }, rollupInputOptions: { ...config.rollupInputOptions, ...plugin.rollupInputOptions }, rollupOutputOptions: { ...config.rollupOutputOptions, ...plugin.rollupOutputOptions } } }
src/node/config.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0017512391787022352, 0.00022130750585347414, 0.00016408308874815702, 0.00017264709458686411, 0.00027057944680564106 ]
{ "id": 0, "code_window": [ " port?: number\n", " open?: boolean\n", " }\n", ") {\n", " await require('../dist').optimizeDeps(options)\n", "\n", " const server = require('../dist').createServer(options)\n", "\n", " let port = options.port || 3000\n", " server.on('error', (e: Error & { code?: string }) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/node/cli.ts", "type": "replace", "edit_start_line_idx": 115 }
<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="count++">count is: {{ count }}</button> <p>Edit <code>components/HelloWorld.vue</code> to test hot module replacement.</p> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, data() { return { count: 0 } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
create-vite-app/template-vue/components/HelloWorld.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017578111146576703, 0.0001743412867654115, 0.00017134020163211972, 0.00017512193880975246, 0.0000017555465774421464 ]
{ "id": 0, "code_window": [ " port?: number\n", " open?: boolean\n", " }\n", ") {\n", " await require('../dist').optimizeDeps(options)\n", "\n", " const server = require('../dist').createServer(options)\n", "\n", " let port = options.port || 3000\n", " server.on('error', (e: Error & { code?: string }) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/node/cli.ts", "type": "replace", "edit_start_line_idx": 115 }
export function foo() { return 1 }
playground/util/index.js
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017592949734535068, 0.00017592949734535068, 0.00017592949734535068, 0.00017592949734535068, 0 ]
{ "id": 0, "code_window": [ " port?: number\n", " open?: boolean\n", " }\n", ") {\n", " await require('../dist').optimizeDeps(options)\n", "\n", " const server = require('../dist').createServer(options)\n", "\n", " let port = options.port || 3000\n", " server.on('error', (e: Error & { code?: string }) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/node/cli.ts", "type": "replace", "edit_start_line_idx": 115 }
<template> <h2>PostCSS</h2> <div class="postcss-from-css"> CSS import with PostCSS: This should be red </div> <div class="postcss-from-sfc"> &lt;style&gt; with PostCSS: This should be green </div> </template> <script> import './testPostCss.css' export default {} </script> <style> body { & .postcss-from-sfc { color: green; } } </style>
playground/TestPostCss.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017998045950662345, 0.00017748116806615144, 0.00017505351570434868, 0.0001774095289874822, 0.0000020120542103541084 ]
{ "id": 1, "code_window": [ " OutputOptions as RollupOutputOptions\n", "} from 'rollup'\n", "import { Transform } from './transform'\n", "\n", "export { Resolver, Transform }\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DepOptimizationOptions } from './depOptimizer'\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 13 }
import fs from 'fs-extra' import path from 'path' import { createHash } from 'crypto' import { ResolvedConfig } from './config' import type Rollup from 'rollup' import { createResolver, supportedExts, resolveNodeModuleEntry } from './resolver' import { createBaseRollupPlugins } from './build' import { resolveFrom, lookupFile } from './utils' import { init, parse } from 'es-module-lexer' import chalk from 'chalk' import { Ora } from 'ora' const KNOWN_IGNORE_LIST = new Set(['tailwindcss']) export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache` export interface OptimizeOptions extends ResolvedConfig { force?: boolean } export async function optimizeDeps(config: OptimizeOptions, asCommand = false) { const log = asCommand ? console.log : require('debug')('vite:optimize') const root = config.root || process.cwd() // warn presence of web_modules if (fs.existsSync(path.join(root, 'web_modules'))) { console.warn( chalk.yellow( `[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` + `from web_modules is no longer supported.` ) ) } const cacheDir = path.join(root, OPTIMIZE_CACHE_DIR) const hashPath = path.join(cacheDir, 'hash') const depHash = getDepHash(root, config.__path) if (!config.force) { let prevhash try { prevhash = await fs.readFile(hashPath, 'utf-8') } catch (e) {} // hash is consistent, no need to re-bundle if (prevhash === depHash) { log('Hash is consistent. Skipping. Use --force to override.') return } } await fs.remove(cacheDir) await fs.ensureDir(cacheDir) const pkg = lookupFile(root, [`package.json`]) if (!pkg) { log(`package.json not found. Skipping.`) return } const deps = Object.keys(JSON.parse(pkg).dependencies || {}) if (!deps.length) { await fs.writeFile(hashPath, depHash) log(`No dependencies listed in package.json. Skipping.`) return } const resolver = createResolver(root, config.resolvers, config.alias) // Determine deps to optimize. The goal is to only pre-bundle deps that falls // under one of the following categories: // 1. Is CommonJS module // 2. Has imports to relative files (e.g. lodash-es, lit-html) // 3. Has imports to bare modules that are not in the project's own deps // (i.e. esm that imports its own dependencies, e.g. styled-components) await init const qualifiedDeps = deps.filter((id) => { if (KNOWN_IGNORE_LIST.has(id)) { return false } const entry = resolveNodeModuleEntry(root, id) if (!entry) { return false } if (!supportedExts.includes(path.extname(entry))) { return false } const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8') const [imports, exports] = parse(content) if (!exports.length) { // no exports, likely a commonjs module return true } for (const { s, e } of imports) { let i = content.slice(s, e).trim() i = resolver.alias(i) || i if (i.startsWith('.') || !deps.includes(i)) { return true } } }) if (!qualifiedDeps.length) { await fs.writeFile(hashPath, depHash) log(`No listed dependency requires optimization. Skipping.`) return } if (!asCommand) { // This is auto run on server start - let the user know that we are // pre-optimizing deps console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`)) } let spinner: Ora | undefined const msg = asCommand ? `Pre-bundling dependencies to speed up dev server page load...` : `Pre-bundling them to speed up dev server page load...\n` + ` (this will be run only when your dependencies have changed)` if (process.env.DEBUG || process.env.NODE_ENV === 'test') { console.log(msg) } else { spinner = require('ora')(msg + '\n').start() } try { // Non qualified deps are marked as externals, since they will be preserved // and resolved from their original node_modules locations. const preservedDeps = deps.filter((id) => !qualifiedDeps.includes(id)) const input = qualifiedDeps.reduce((entries, name) => { entries[name] = name return entries }, {} as Record<string, string>) const rollup = require('rollup') as typeof Rollup const bundle = await rollup.rollup({ input, external: preservedDeps, treeshake: { moduleSideEffects: 'no-external' }, onwarn(warning, warn) { if (warning.code !== 'CIRCULAR_DEPENDENCY') { warn(warning) } }, ...config.rollupInputOptions, plugins: await createBaseRollupPlugins(root, resolver, config) }) const { output } = await bundle.generate({ ...config.rollupOutputOptions, format: 'es', exports: 'named', chunkFileNames: 'common/[name]-[hash].js' }) spinner && spinner.stop() const optimized = [] for (const chunk of output) { if (chunk.type === 'chunk') { const fileName = chunk.fileName const filePath = path.join(cacheDir, fileName) await fs.ensureDir(path.dirname(filePath)) await fs.writeFile(filePath, chunk.code) if (!fileName.startsWith('common/')) { optimized.push(fileName.replace(/\.js$/, '')) } } } console.log( `Optimized modules:\n${optimized .map((id) => chalk.yellowBright(id)) .join(`, `)}` ) await fs.writeFile(hashPath, depHash) } catch (e) { spinner && spinner.stop() if (asCommand) { throw e } else { console.error(chalk.red(`[vite] Dep optimization failed with error:`)) console.error(e) } } } const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'] let cachedHash: string | undefined export function getDepHash( root: string, configPath: string | undefined ): string { if (cachedHash) { return cachedHash } let content = lookupFile(root, lockfileFormats) || '' const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}') content += JSON.stringify(pkg.dependencies) // also take config into account if (configPath) { content += fs.readFileSync(configPath, 'utf-8') } return createHash('sha1').update(content).digest('base64') }
src/node/depOptimizer.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.9834514856338501, 0.0450264997780323, 0.00016626295109745115, 0.00017435551853850484, 0.2047816812992096 ]
{ "id": 1, "code_window": [ " OutputOptions as RollupOutputOptions\n", "} from 'rollup'\n", "import { Transform } from './transform'\n", "\n", "export { Resolver, Transform }\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DepOptimizationOptions } from './depOptimizer'\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 13 }
.DS_Store node_modules dist dist-ssr TODOs.md *.log test/temp explorations
.gitignore
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017168429621960968, 0.00017168429621960968, 0.00017168429621960968, 0.00017168429621960968, 0 ]
{ "id": 1, "code_window": [ " OutputOptions as RollupOutputOptions\n", "} from 'rollup'\n", "import { Transform } from './transform'\n", "\n", "export { Resolver, Transform }\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DepOptimizationOptions } from './depOptimizer'\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 13 }
import path from 'path' import chalk from 'chalk' import { startService, Service, TransformOptions, Message } from 'esbuild' import { SharedConfig } from './config' const debug = require('debug')('vite:esbuild') export const tjsxRE = /\.(tsx?|jsx)$/ export const vueJsxPublicPath = '/vite/jsx' export const vueJsxFilePath = path.resolve(__dirname, 'vueJsxCompat.js') const JsxPresets: Record< string, Pick<TransformOptions, 'jsxFactory' | 'jsxFragment'> > = { vue: { jsxFactory: 'jsx', jsxFragment: 'Fragment' }, preact: { jsxFactory: 'h', jsxFragment: 'Fragment' }, react: {} // use esbuild default } export function reoslveJsxOptions(options: SharedConfig['jsx'] = 'vue') { if (typeof options === 'string') { if (!(options in JsxPresets)) { console.error(`[vite] unknown jsx preset: '${options}'.`) } return JsxPresets[options] || {} } else if (options) { return { jsxFactory: options.factory, jsxFragment: options.fragment } } } // lazy start the service let _service: Service | undefined const ensureService = async () => { if (!_service) { _service = await startService() } return _service } export const stopService = () => { _service && _service.stop() } const sourceMapRE = /\/\/# sourceMappingURL.*/ // transform used in server plugins with a more friendly API export const transform = async ( src: string, file: string, options: TransformOptions = {}, jsxOption?: SharedConfig['jsx'] ) => { const service = await ensureService() options = { ...options, loader: options.loader || (path.extname(file).slice(1) as any), sourcemap: true, sourcefile: file } try { const result = await service.transform(src, options) if (result.warnings.length) { console.error(`[vite] warnings while transforming ${file} with esbuild:`) result.warnings.forEach((m) => printMessage(m, src)) } let code = (result.js || '').replace(sourceMapRE, '') // if transpiling (j|t)sx file, inject the imports for the jsx helper and // Fragment. if (file.endsWith('x')) { if (!jsxOption || jsxOption === 'vue') { code += `\nimport { jsx } from '${vueJsxPublicPath}'` + `\nimport { Fragment } from 'vue'` } if (jsxOption === 'preact') { code += `\nimport { h, Fragment } from 'preact'` } } return { code, map: result.jsSourceMap } } catch (e) { console.error( chalk.red(`[vite] error while transforming ${file} with esbuild:`) ) e.errors.forEach((m: Message) => printMessage(m, src)) debug(`options used: `, options) return { code: '', map: undefined } } } function printMessage(m: Message, code: string) { console.error(chalk.yellow(m.text)) if (m.location) { const lines = code.split(/\r?\n/g) const line = Number(m.location.line) const column = Number(m.location.column) const offset = lines .slice(0, line - 1) .map((l) => l.length) .reduce((total, l) => total + l + 1, 0) + column console.error( require('@vue/compiler-core').generateCodeFrame(code, offset, offset + 1) ) } }
src/node/esbuildService.ts
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.004132266156375408, 0.00048376040649600327, 0.00016455972217954695, 0.00017492954793851823, 0.0010533606400713325 ]
{ "id": 1, "code_window": [ " OutputOptions as RollupOutputOptions\n", "} from 'rollup'\n", "import { Transform } from './transform'\n", "\n", "export { Resolver, Transform }\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DepOptimizationOptions } from './depOptimizer'\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 13 }
export declare const hot: { // single dep accept(dep: string, cb?: (newModule: any) => void): void // multiple deps accept(deps: string[], cb?: (newModules: any[]) => void): void // self-accepting accept(cb: (newModule: any) => void): void // dispose dispose(cb: () => void): void // custom events on(event: string, cb: (data: any) => void): void }
hmr.d.ts
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017241020395886153, 0.00017095831572078168, 0.0001695064129307866, 0.00017095831572078168, 0.0000014518954003506224 ]
{ "id": 2, "code_window": [ " * and optionally map module ids to public path requests.\n", " */\n", " resolvers?: Resolver[]\n", " /**\n", " * Options to pass to @vue/compiler-dom\n", " */\n", " vueCompilerOptions?: CompilerOptions\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Configure dep optimization behavior.\n", " */\n", " optimizeDeps?: DepOptimizationOptions\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 39 }
import http, { Server } from 'http' import Koa from 'koa' import chokidar from 'chokidar' import { createResolver, InternalResolver } from '../resolver' import { moduleRewritePlugin } from './serverPluginModuleRewrite' import { moduleResolvePlugin } from './serverPluginModuleResolve' import { vuePlugin } from './serverPluginVue' import { hmrPlugin, HMRWatcher } from './serverPluginHmr' import { serveStaticPlugin } from './serverPluginServeStatic' import { jsonPlugin } from './serverPluginJson' import { cssPlugin } from './serverPluginCss' import { assetPathPlugin } from './serverPluginAssets' import { esbuildPlugin } from './serverPluginEsbuild' import { ServerConfig } from '../config' import { createServerTransformPlugin } from '../transform' import { serviceWorkerPlugin } from './serverPluginServiceWorker' export { rewriteImports } from './serverPluginModuleRewrite' export type ServerPlugin = (ctx: ServerPluginContext) => void export interface ServerPluginContext { root: string app: Koa server: Server watcher: HMRWatcher resolver: InternalResolver config: ServerConfig & { __path?: string } } export function createServer(config: ServerConfig = {}): Server { const { root = process.cwd(), plugins = [], resolvers = [], alias = {}, transforms = [] } = config const app = new Koa() const server = http.createServer(app.callback()) const watcher = chokidar.watch(root, { ignored: [/node_modules/] }) as HMRWatcher const resolver = createResolver(root, resolvers, alias) const context = { root, app, server, watcher, resolver, config } const resolvedPlugins = [ ...plugins, serviceWorkerPlugin, hmrPlugin, moduleRewritePlugin, moduleResolvePlugin, vuePlugin, esbuildPlugin, jsonPlugin, cssPlugin, assetPathPlugin, ...(transforms.length ? [createServerTransformPlugin(transforms)] : []), serveStaticPlugin ] resolvedPlugins.forEach((m) => m(context)) return server }
src/node/server/index.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.01029883325099945, 0.0020532014314085245, 0.00017229188233613968, 0.000262529676547274, 0.003355766646564007 ]
{ "id": 2, "code_window": [ " * and optionally map module ids to public path requests.\n", " */\n", " resolvers?: Resolver[]\n", " /**\n", " * Options to pass to @vue/compiler-dom\n", " */\n", " vueCompilerOptions?: CompilerOptions\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Configure dep optimization behavior.\n", " */\n", " optimizeDeps?: DepOptimizationOptions\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 39 }
export * from './fsUtils' export * from './pathUtils' export * from './transformUtils' export * from './resolveVue' export * from './resolvePostCssConfig'
src/node/utils/index.ts
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00016810910892672837, 0.00016810910892672837, 0.00016810910892672837, 0.00016810910892672837, 0 ]
{ "id": 2, "code_window": [ " * and optionally map module ids to public path requests.\n", " */\n", " resolvers?: Resolver[]\n", " /**\n", " * Options to pass to @vue/compiler-dom\n", " */\n", " vueCompilerOptions?: CompilerOptions\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Configure dep optimization behavior.\n", " */\n", " optimizeDeps?: DepOptimizationOptions\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 39 }
<template> <h2>Hot Module Replacement</h2> <p> <span> HMR: click button and edit template part of <code>./TestHmr.vue</code>, count should not reset </span> <button class="hmr-increment" @click="count++"> &gt;&gt;&gt; {{ count }} &lt;&lt;&lt; </button> </p> <p> <span> HMR: edit the return value of <code>foo()</code> in <code>./testHmrPropagation.js</code>, should update without reloading page: </span> <span class="hmr-propagation">{{ foo() }}</span> </p> <p> HMR: manual API (see console) - edit <code>./testHmrManual.js</code> and it should log new exported value without reloading the page. </p> </template> <script> import { foo } from './testHmrPropagation' export default { setup() { return { count: 0, foo } } } </script>
playground/TestHmr.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00018368418386671692, 0.00017509411554783583, 0.00017044009291566908, 0.0001731261145323515, 0.0000051639026423799805 ]
{ "id": 2, "code_window": [ " * and optionally map module ids to public path requests.\n", " */\n", " resolvers?: Resolver[]\n", " /**\n", " * Options to pass to @vue/compiler-dom\n", " */\n", " vueCompilerOptions?: CompilerOptions\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Configure dep optimization behavior.\n", " */\n", " optimizeDeps?: DepOptimizationOptions\n" ], "file_path": "src/node/config.ts", "type": "add", "edit_start_line_idx": 39 }
<template src="./template.html"></template> <script src="./script.ts"></script> <style src="./style.css" scoped></style>
playground/src-import/TestBlockSrcImport.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00016930754645727575, 0.00016930754645727575, 0.00016930754645727575, 0.00016930754645727575, 0 ]
{ "id": 3, "code_window": [ "import { Ora } from 'ora'\n", "\n", "const KNOWN_IGNORE_LIST = new Set(['tailwindcss'])\n", "\n", "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export interface OptimizeOptions extends ResolvedConfig {\n", " force?: boolean\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "export interface DepOptimizationOptions {\n", " /**\n", " * Only optimize explicitly listed dependencies.\n", " */\n", " include?: string[]\n", " /**\n", " * Do not optimize these dependencies.\n", " */\n", " exclude?: string[]\n", " /**\n", " * Automatically run `vite optimize` on server start?\n", " * @default true\n", " */\n", " auto?: boolean\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 18 }
import path from 'path' import fs from 'fs-extra' import chalk from 'chalk' import { createEsbuildPlugin } from './build/buildPluginEsbuild' import { ServerPlugin } from './server' import { Resolver } from './resolver' import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue' import { CompilerOptions } from '@vue/compiler-sfc' import Rollup, { InputOptions as RollupInputOptions, OutputOptions as RollupOutputOptions } from 'rollup' import { Transform } from './transform' export { Resolver, Transform } /** * Options shared between server and build. */ export interface SharedConfig { /** * Project root directory. Can be an absolute path, or a path relative from * the location of the config file itself. * @default process.cwd() */ root?: string /** * Import alias. Can only be exact mapping, does not support wildcard syntax. */ alias?: Record<string, string> /** * Custom file transforms. */ transforms?: Transform[] /** * Resolvers to map dev server public path requests to/from file system paths, * and optionally map module ids to public path requests. */ resolvers?: Resolver[] /** * Options to pass to @vue/compiler-dom */ vueCompilerOptions?: CompilerOptions /** * Configure what to use for jsx factory and fragment. * @default * { * factory: 'React.createElement', * fragment: 'React.Fragment' * } */ jsx?: | 'vue' | 'preact' | 'react' | { factory?: string fragment?: string } } export interface ServerConfig extends SharedConfig { /** * Whether to use a Service Worker to cache served code. This can greatly * improve full page reload performance, but requires a Service Worker * update + reload on each server restart. * * @default false */ serviceWorker?: boolean plugins?: ServerPlugin[] } export interface BuildConfig extends SharedConfig { /** * Base public path when served in production. * @default '/' */ base?: string /** * Directory relative from `root` where build output will be placed. If the * directory exists, it will be removed before the build. * @default 'dist' */ outDir?: string /** * Directory relative from `outDir` where the built js/css/image assets will * be placed. * @default 'assets' */ assetsDir?: string /** * Static asset files smaller than this number (in bytes) will be inlined as * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable. * @default 4096 */ assetsInlineLimit?: number /** * Whether to generate sourcemap * @default false */ sourcemap?: boolean /** * Set to `false` to dsiable minification, or specify the minifier to use. * Available options are 'terser' or 'esbuild'. * @default 'terser' */ minify?: boolean | 'terser' | 'esbuild' /** * Build for server-side rendering * @default false */ ssr?: boolean // The following are API only and not documented in the CLI. ----------------- /** * Will be passed to rollup.rollup() * https://rollupjs.org/guide/en/#big-list-of-options */ rollupInputOptions?: RollupInputOptions /** * Will be passed to bundle.generate() * https://rollupjs.org/guide/en/#big-list-of-options */ rollupOutputOptions?: RollupOutputOptions /** * Will be passed to rollup-plugin-vue * https://github.com/vuejs/rollup-plugin-vue/blob/next/src/index.ts */ rollupPluginVueOptions?: Partial<RollupPluginVueOptions> /** * Whether to log asset info to console * @default false */ silent?: boolean /** * Whether to write bundle to disk * @default true */ write?: boolean /** * Whether to emit index.html * @default true */ emitIndex?: boolean /** * Whether to emit assets other than JavaScript * @default true */ emitAssets?: boolean } export interface UserConfig extends BuildConfig, Pick<ServerConfig, 'serviceWorker'> { plugins?: Plugin[] configureServer?: ServerPlugin } export interface Plugin extends Pick< UserConfig, | 'alias' | 'transforms' | 'resolvers' | 'configureServer' | 'vueCompilerOptions' | 'rollupInputOptions' | 'rollupOutputOptions' > {} export type ResolvedConfig = UserConfig & { __path?: string } export async function resolveConfig( configPath: string | undefined ): Promise<ResolvedConfig | undefined> { const start = Date.now() let config: ResolvedConfig | undefined let resolvedPath: string | undefined let isTS = false if (configPath) { resolvedPath = path.resolve(process.cwd(), configPath) } else { const jsConfigPath = path.resolve(process.cwd(), 'vite.config.js') if (fs.existsSync(jsConfigPath)) { resolvedPath = jsConfigPath } else { const tsConfigPath = path.resolve(process.cwd(), 'vite.config.ts') if (fs.existsSync(tsConfigPath)) { isTS = true resolvedPath = tsConfigPath } } } if (!resolvedPath) { return } try { if (!isTS) { try { config = require(resolvedPath) } catch (e) { if ( !/Cannot use import statement|Unexpected token 'export'/.test( e.message ) ) { throw e } } } if (!config) { // 2. if we reach here, the file is ts or using es import syntax. // transpile es import syntax to require syntax using rollup. const rollup = require('rollup') as typeof Rollup const esbuilPlugin = await createEsbuildPlugin(false, {}) const bundle = await rollup.rollup({ external: (id: string) => (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json', input: resolvedPath, treeshake: false, plugins: [esbuilPlugin] }) const { output: [{ code }] } = await bundle.generate({ exports: 'named', format: 'cjs' }) config = await loadConfigFromBundledFile(resolvedPath, code) } // normalize config root to absolute if (config.root && !path.isAbsolute(config.root)) { config.root = path.resolve(path.dirname(resolvedPath), config.root) } // resolve plugins if (config.plugins) { for (const plugin of config.plugins) { config = resolvePlugin(config, plugin) } // delete plugins so it doesn't get passed to `createServer` as server // plugins. delete config.plugins } require('debug')('vite:config')( `config resolved in ${Date.now() - start}ms` ) config.__path = resolvedPath return config } catch (e) { console.error( chalk.red(`[vite] failed to load config from ${resolvedPath}:`) ) console.error(e) process.exit(1) } } interface NodeModuleWithCompile extends NodeModule { _compile(code: string, filename: string): any } async function loadConfigFromBundledFile( fileName: string, bundledCode: string ): Promise<UserConfig> { const extension = path.extname(fileName) const defaultLoader = require.extensions[extension]! require.extensions[extension] = (module: NodeModule, filename: string) => { if (filename === fileName) { ;(module as NodeModuleWithCompile)._compile(bundledCode, filename) } else { defaultLoader(module, filename) } } delete require.cache[fileName] const raw = require(fileName) const config = raw.__esModule ? raw.default : raw require.extensions[extension] = defaultLoader return config } function resolvePlugin(config: UserConfig, plugin: Plugin): UserConfig { return { ...config, alias: { ...plugin.alias, ...config.alias }, transforms: [...(config.transforms || []), ...(plugin.transforms || [])], resolvers: [...(config.resolvers || []), ...(plugin.resolvers || [])], configureServer: (ctx) => { if (config.configureServer) { config.configureServer(ctx) } if (plugin.configureServer) { plugin.configureServer(ctx) } }, vueCompilerOptions: { ...config.vueCompilerOptions, ...plugin.vueCompilerOptions }, rollupInputOptions: { ...config.rollupInputOptions, ...plugin.rollupInputOptions }, rollupOutputOptions: { ...config.rollupOutputOptions, ...plugin.rollupOutputOptions } } }
src/node/config.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0018814230570569634, 0.00036863243440166116, 0.0001640565023990348, 0.00017328782996628433, 0.00043881338206119835 ]
{ "id": 3, "code_window": [ "import { Ora } from 'ora'\n", "\n", "const KNOWN_IGNORE_LIST = new Set(['tailwindcss'])\n", "\n", "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export interface OptimizeOptions extends ResolvedConfig {\n", " force?: boolean\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "export interface DepOptimizationOptions {\n", " /**\n", " * Only optimize explicitly listed dependencies.\n", " */\n", " include?: string[]\n", " /**\n", " * Do not optimize these dependencies.\n", " */\n", " exclude?: string[]\n", " /**\n", " * Automatically run `vite optimize` on server start?\n", " * @default true\n", " */\n", " auto?: boolean\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 18 }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace; }
create-vite-app/template-react/src/index.css
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001749465591274202, 0.00017480438691563904, 0.0001746622147038579, 0.00017480438691563904, 1.4217221178114414e-7 ]
{ "id": 3, "code_window": [ "import { Ora } from 'ora'\n", "\n", "const KNOWN_IGNORE_LIST = new Set(['tailwindcss'])\n", "\n", "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export interface OptimizeOptions extends ResolvedConfig {\n", " force?: boolean\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "export interface DepOptimizationOptions {\n", " /**\n", " * Only optimize explicitly listed dependencies.\n", " */\n", " include?: string[]\n", " /**\n", " * Do not optimize these dependencies.\n", " */\n", " exclude?: string[]\n", " /**\n", " * Automatically run `vite optimize` on server start?\n", " * @default true\n", " */\n", " auto?: boolean\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 18 }
export const jsPlugin = { transforms: [ { test(id) { return id.endsWith('testTransform.js') }, transform(code) { return code.replace(/__TEST_TRANSFORM__ = (\d)/, (matched, n) => { return `__TEST_TRANSFORM__ = ${Number(n) + 1}` }) } } ] }
playground/plugins/jsPlugin.js
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001773662370396778, 0.00017327928799204528, 0.00016919232439249754, 0.00017327928799204528, 0.00000408695632359013 ]
{ "id": 3, "code_window": [ "import { Ora } from 'ora'\n", "\n", "const KNOWN_IGNORE_LIST = new Set(['tailwindcss'])\n", "\n", "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export interface OptimizeOptions extends ResolvedConfig {\n", " force?: boolean\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "export interface DepOptimizationOptions {\n", " /**\n", " * Only optimize explicitly listed dependencies.\n", " */\n", " include?: string[]\n", " /**\n", " * Do not optimize these dependencies.\n", " */\n", " exclude?: string[]\n", " /**\n", " * Automatically run `vite optimize` on server start?\n", " * @default true\n", " */\n", " auto?: boolean\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 18 }
import { ServerPlugin } from '.' import path from 'path' import slash from 'slash' import LRUCache from 'lru-cache' import MagicString from 'magic-string' import { init as initLexer, parse as parseImports, ImportSpecifier } from 'es-module-lexer' import { InternalResolver, resolveBareModule } from '../resolver' import { debugHmr, importerMap, importeeMap, ensureMapEntry, rewriteFileWithHMR, hmrClientPublicPath, hmrClientId, hmrDirtyFilesMap } from './serverPluginHmr' import { readBody, cleanUrl, isExternalUrl, resolveRelativeRequest } from '../utils' import chalk from 'chalk' const debug = require('debug')('vite:rewrite') const rewriteCache = new LRUCache({ max: 1024 }) // Plugin for rewriting served js. // - Rewrites named module imports to `/@modules/:id` requests, e.g. // "vue" => "/@modules/vue" // - Rewrites HMR `hot.accept` calls to inject the file's own path. e.g. // `hot.accept('./dep.js', cb)` -> `hot.accept('/importer.js', './dep.js', cb)` // - Also tracks importer/importee relationship graph during the rewrite. // The graph is used by the HMR plugin to perform analysis on file change. export const moduleRewritePlugin: ServerPlugin = ({ root, app, watcher, resolver, config }) => { // inject __DEV__ and process.env.NODE_ENV flags // since some ESM builds expect these to be replaced by the bundler const devInjectionCode = `\n<script>\n` + `window.__DEV__ = true\n` + `window.__BASE__ = '/'\n` + `window.process = { env: { NODE_ENV: 'development' }}\n` + `</script>` + `\n<script type="module" src="${hmrClientPublicPath}"></script>\n` const scriptRE = /(<script\b[^>]*>)([\s\S]*?)<\/script>/gm const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/ async function rewriteIndex(html: string) { await initLexer let hasInjectedDevFlag = false const importer = '/index.html' return html!.replace(scriptRE, (matched, openTag, script) => { const devFlag = hasInjectedDevFlag ? `` : devInjectionCode hasInjectedDevFlag = true if (script) { return `${devFlag}${openTag}${rewriteImports( root, script, importer, resolver )}</script>` } else { const srcAttr = openTag.match(srcRE) if (srcAttr) { // register script as a import dep for hmr const importee = cleanUrl( slash(path.resolve('/', srcAttr[1] || srcAttr[2])) ) debugHmr(` ${importer} imports ${importee}`) ensureMapEntry(importerMap, importee).add(importer) } return `${devFlag}${matched}` } }) } app.use(async (ctx, next) => { await next() if (ctx.status === 304) { return } if (ctx.path === '/index.html') { let html = await readBody(ctx.body) if (html && rewriteCache.has(html)) { debug('/index.html: serving from cache') ctx.body = rewriteCache.get(html) } else if (html) { ctx.body = await rewriteIndex(html) rewriteCache.set(html, ctx.body) } return } // we are doing the js rewrite after all other middlewares have finished; // this allows us to post-process javascript produced by user middlewares // regardless of the extension of the original files. if ( ctx.body && ctx.response.is('js') && !ctx.url.endsWith('.map') && // skip internal client !ctx.path.startsWith(hmrClientPublicPath) && // only need to rewrite for <script> part in vue files !((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type != null) ) { const content = await readBody(ctx.body) if (!ctx.query.t && rewriteCache.has(content)) { debug(`(cached) ${ctx.url}`) ctx.body = rewriteCache.get(content) } else { await initLexer ctx.body = rewriteImports( root, content!, ctx.path, resolver, ctx.query.t ) rewriteCache.set(content, ctx.body) } } else { debug(`(skipped) ${ctx.url}`) } }) // bust module rewrite cache on file change watcher.on('change', (file) => { const publicPath = resolver.fileToRequest(file) debug(`${publicPath}: cache busted`) rewriteCache.del(publicPath) }) } export function rewriteImports( root: string, source: string, importer: string, resolver: InternalResolver, timestamp?: string ) { if (typeof source !== 'string') { source = String(source) } try { let imports: ImportSpecifier[] = [] try { imports = parseImports(source)[0] } catch (e) { console.error( chalk.yellow( `[vite] failed to parse ${chalk.cyan( importer )} for import rewrite.\nIf you are using ` + `JSX, make sure to named the file with the .jsx extension.` ) ) } if (imports.length) { debug(`${importer}: rewriting`) const s = new MagicString(source) let hasReplaced = false const prevImportees = importeeMap.get(importer) const currentImportees = new Set<string>() importeeMap.set(importer, currentImportees) for (let i = 0; i < imports.length; i++) { const { s: start, e: end, d: dynamicIndex } = imports[i] let id = source.substring(start, end) let hasLiteralDynamicId = false if (dynamicIndex >= 0) { const literalIdMatch = id.match(/^(?:'([^']+)'|"([^"]+)")$/) if (literalIdMatch) { hasLiteralDynamicId = true id = literalIdMatch[1] || literalIdMatch[2] } } if (dynamicIndex === -1 || hasLiteralDynamicId) { // do not rewrite external imports if (isExternalUrl(id)) { continue } let resolved if (id === hmrClientId) { resolved = hmrClientPublicPath if (!/.vue$|.vue\?type=/.test(importer)) { // the user explicit imports the HMR API in a js file // making the module hot. rewriteFileWithHMR(root, source, importer, resolver, s) // we rewrite the hot.accept call hasReplaced = true } } else { resolved = resolveImport(root, importer, id, resolver, timestamp) } if (resolved !== id) { debug(` "${id}" --> "${resolved}"`) s.overwrite( start, end, hasLiteralDynamicId ? `'${resolved}'` : resolved ) hasReplaced = true } // save the import chain for hmr analysis const importee = cleanUrl(resolved) if ( importee !== importer && // no need to track hmr client or module dependencies importee !== hmrClientPublicPath ) { currentImportees.add(importee) debugHmr(` ${importer} imports ${importee}`) ensureMapEntry(importerMap, importee).add(importer) } } else { console.log(`[vite] ignored dynamic import(${id})`) } } // since the importees may have changed due to edits, // check if we need to remove this importer from certain importees if (prevImportees) { prevImportees.forEach((importee) => { if (!currentImportees.has(importee)) { const importers = importerMap.get(importee) if (importers) { importers.delete(importer) } } }) } if (!hasReplaced) { debug(` no imports rewritten.`) } return hasReplaced ? s.toString() : source } else { debug(`${importer}: no imports found.`) } return source } catch (e) { console.error( `[vite] Error: module imports rewrite failed for ${importer}.\n`, e ) debug(source) return source } } const bareImportRE = /^[^\/\.]/ const jsSrcRE = /\.(?:(?:j|t)sx?|vue)$/ export const resolveImport = ( root: string, importer: string, id: string, resolver: InternalResolver, timestamp?: string ): string => { id = resolver.alias(id) || id if (bareImportRE.test(id)) { // directly resolve bare module names to its entry path so that relative // imports from it (including source map urls) can work correctly let resolvedModulePath = resolveBareModule(root, id, importer) const ext = path.extname(resolvedModulePath) if (ext && !jsSrcRE.test(ext)) { resolvedModulePath += `?import` } return `/@modules/${resolvedModulePath}` } else { let { pathname, query } = resolveRelativeRequest(importer, id) // append an extension to extension-less imports if (!path.extname(pathname)) { const file = resolver.requestToFile(pathname) const indexMatch = file.match(/\/index\.\w+$/) if (indexMatch) { pathname = pathname.replace(/\/(index)?$/, '') + indexMatch[0] } else { pathname += path.extname(file) } } // mark non-src imports if (!jsSrcRE.test(pathname)) { query += `${query ? `&` : `?`}import` } // force re-fetch dirty imports by appending timestamp if (timestamp) { const dirtyFiles = hmrDirtyFilesMap.get(timestamp) // only force re-fetch if this is a marked dirty file (in the import // chain of the changed file) or a vue part request (made by a dirty // vue main request) if ((dirtyFiles && dirtyFiles.has(pathname)) || /\.vue\?type/.test(id)) { query += `${query ? `&` : `?`}t=${timestamp}` } } return pathname + query } }
src/node/server/serverPluginModuleRewrite.ts
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001978470099857077, 0.00017202910385094583, 0.0001645195734454319, 0.00017131732602138072, 0.00000610699862590991 ]
{ "id": 4, "code_window": [ "}\n", "\n", "export async function optimizeDeps(config: OptimizeOptions, asCommand = false) {\n", " const log = asCommand ? console.log : require('debug')('vite:optimize')\n", " const root = config.root || process.cwd()\n", " // warn presence of web_modules\n", " if (fs.existsSync(path.join(root, 'web_modules'))) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export async function optimizeDeps(\n", " config: ResolvedConfig & { force?: boolean },\n", " asCommand = false\n", ") {\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 24 }
import fs from 'fs-extra' import path from 'path' import { createHash } from 'crypto' import { ResolvedConfig } from './config' import type Rollup from 'rollup' import { createResolver, supportedExts, resolveNodeModuleEntry } from './resolver' import { createBaseRollupPlugins } from './build' import { resolveFrom, lookupFile } from './utils' import { init, parse } from 'es-module-lexer' import chalk from 'chalk' import { Ora } from 'ora' const KNOWN_IGNORE_LIST = new Set(['tailwindcss']) export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache` export interface OptimizeOptions extends ResolvedConfig { force?: boolean } export async function optimizeDeps(config: OptimizeOptions, asCommand = false) { const log = asCommand ? console.log : require('debug')('vite:optimize') const root = config.root || process.cwd() // warn presence of web_modules if (fs.existsSync(path.join(root, 'web_modules'))) { console.warn( chalk.yellow( `[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` + `from web_modules is no longer supported.` ) ) } const cacheDir = path.join(root, OPTIMIZE_CACHE_DIR) const hashPath = path.join(cacheDir, 'hash') const depHash = getDepHash(root, config.__path) if (!config.force) { let prevhash try { prevhash = await fs.readFile(hashPath, 'utf-8') } catch (e) {} // hash is consistent, no need to re-bundle if (prevhash === depHash) { log('Hash is consistent. Skipping. Use --force to override.') return } } await fs.remove(cacheDir) await fs.ensureDir(cacheDir) const pkg = lookupFile(root, [`package.json`]) if (!pkg) { log(`package.json not found. Skipping.`) return } const deps = Object.keys(JSON.parse(pkg).dependencies || {}) if (!deps.length) { await fs.writeFile(hashPath, depHash) log(`No dependencies listed in package.json. Skipping.`) return } const resolver = createResolver(root, config.resolvers, config.alias) // Determine deps to optimize. The goal is to only pre-bundle deps that falls // under one of the following categories: // 1. Is CommonJS module // 2. Has imports to relative files (e.g. lodash-es, lit-html) // 3. Has imports to bare modules that are not in the project's own deps // (i.e. esm that imports its own dependencies, e.g. styled-components) await init const qualifiedDeps = deps.filter((id) => { if (KNOWN_IGNORE_LIST.has(id)) { return false } const entry = resolveNodeModuleEntry(root, id) if (!entry) { return false } if (!supportedExts.includes(path.extname(entry))) { return false } const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8') const [imports, exports] = parse(content) if (!exports.length) { // no exports, likely a commonjs module return true } for (const { s, e } of imports) { let i = content.slice(s, e).trim() i = resolver.alias(i) || i if (i.startsWith('.') || !deps.includes(i)) { return true } } }) if (!qualifiedDeps.length) { await fs.writeFile(hashPath, depHash) log(`No listed dependency requires optimization. Skipping.`) return } if (!asCommand) { // This is auto run on server start - let the user know that we are // pre-optimizing deps console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`)) } let spinner: Ora | undefined const msg = asCommand ? `Pre-bundling dependencies to speed up dev server page load...` : `Pre-bundling them to speed up dev server page load...\n` + ` (this will be run only when your dependencies have changed)` if (process.env.DEBUG || process.env.NODE_ENV === 'test') { console.log(msg) } else { spinner = require('ora')(msg + '\n').start() } try { // Non qualified deps are marked as externals, since they will be preserved // and resolved from their original node_modules locations. const preservedDeps = deps.filter((id) => !qualifiedDeps.includes(id)) const input = qualifiedDeps.reduce((entries, name) => { entries[name] = name return entries }, {} as Record<string, string>) const rollup = require('rollup') as typeof Rollup const bundle = await rollup.rollup({ input, external: preservedDeps, treeshake: { moduleSideEffects: 'no-external' }, onwarn(warning, warn) { if (warning.code !== 'CIRCULAR_DEPENDENCY') { warn(warning) } }, ...config.rollupInputOptions, plugins: await createBaseRollupPlugins(root, resolver, config) }) const { output } = await bundle.generate({ ...config.rollupOutputOptions, format: 'es', exports: 'named', chunkFileNames: 'common/[name]-[hash].js' }) spinner && spinner.stop() const optimized = [] for (const chunk of output) { if (chunk.type === 'chunk') { const fileName = chunk.fileName const filePath = path.join(cacheDir, fileName) await fs.ensureDir(path.dirname(filePath)) await fs.writeFile(filePath, chunk.code) if (!fileName.startsWith('common/')) { optimized.push(fileName.replace(/\.js$/, '')) } } } console.log( `Optimized modules:\n${optimized .map((id) => chalk.yellowBright(id)) .join(`, `)}` ) await fs.writeFile(hashPath, depHash) } catch (e) { spinner && spinner.stop() if (asCommand) { throw e } else { console.error(chalk.red(`[vite] Dep optimization failed with error:`)) console.error(e) } } } const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'] let cachedHash: string | undefined export function getDepHash( root: string, configPath: string | undefined ): string { if (cachedHash) { return cachedHash } let content = lookupFile(root, lockfileFormats) || '' const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}') content += JSON.stringify(pkg.dependencies) // also take config into account if (configPath) { content += fs.readFileSync(configPath, 'utf-8') } return createHash('sha1').update(content).digest('base64') }
src/node/depOptimizer.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.9982319474220276, 0.5367448925971985, 0.00017334021686110646, 0.7581847906112671, 0.46880415081977844 ]
{ "id": 4, "code_window": [ "}\n", "\n", "export async function optimizeDeps(config: OptimizeOptions, asCommand = false) {\n", " const log = asCommand ? console.log : require('debug')('vite:optimize')\n", " const root = config.root || process.cwd()\n", " // warn presence of web_modules\n", " if (fs.existsSync(path.join(root, 'web_modules'))) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export async function optimizeDeps(\n", " config: ResolvedConfig & { force?: boolean },\n", " asCommand = false\n", ") {\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 24 }
--- name: Bug report about: Create a report to help us improve title: '' labels: 'bug: pending triage' assignees: '' --- <!-- Before you continue... If you just upgraded Vite and suddenly everything stops working, try opening the Network tab in your browser devtools, tick "disable cache" and refresh the page. --> > Do NOT ignore this template or your issue will have a very high chance to be closed without comment. ## Describe the bug A clear and concise description of what the bug is. ## Reproduction Please provide a link to a repo that can reproduce the problem you ran into. A reproduction is **required** unless you are absolutely sure that the the problem is obvious and the information you provided is enough for us to understand what the problem is. If a report has only vague description (e.g. just a generic error message) and has no reproduction, it will be closed immediately. ## System Info - **required** `vite` version: - **required** Operating System: - **required** Node version: - Optional: - npm/yarn version - Installed `vue` version (from `yarn.lock` or `package-lock.json`) - Installed `@vue/compiler-sfc` version ## Logs (Optional if provided reproduction) 1. Run `vite` or `vite build` with the `--debug` flag. 2. Provide the error log here.
.github/ISSUE_TEMPLATE/bug_report.md
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017575731908436865, 0.00017013218894135207, 0.00016454716387670487, 0.00017055307398550212, 0.000004631946012523258 ]
{ "id": 4, "code_window": [ "}\n", "\n", "export async function optimizeDeps(config: OptimizeOptions, asCommand = false) {\n", " const log = asCommand ? console.log : require('debug')('vite:optimize')\n", " const root = config.root || process.cwd()\n", " // warn presence of web_modules\n", " if (fs.existsSync(path.join(root, 'web_modules'))) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export async function optimizeDeps(\n", " config: ResolvedConfig & { force?: boolean },\n", " asCommand = false\n", ") {\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 24 }
<template> <h2>Static Asset Handling</h2> <p> Fonts should be italic if font asset reference from CSS works. </p> <p class="asset-import"> Path for assets import from js: <code>{{ filepath }}</code> </p> <p> Relative asset reference in template: <img src="./testAssets.png" style="width: 30px;" /> </p> <p> Absolute asset reference in template: <img src="/public/icon.png" style="width: 30px;" /> </p> <div class="css-bg"> <span style="background: #fff;">CSS background</span> </div> <div class="css-bg-data-uri"> <span style="background: #fff;">CSS background with Data URI</span> </div> </template> <script> import filepath from './testAssets.png' export default { data() { return { filepath } } } </script> <style> @font-face { font-family: 'Inter'; font-style: italic; font-weight: 400; font-display: swap; src: url('fonts/Inter-Italic.woff2') format('woff2'), url('fonts/Inter-Italic.woff') format('woff'); } body { font-family: 'Inter'; } .css-bg { background: url(/public/icon.png); background-size: 10px; } .css-bg-data-uri { background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=); background-size: 10px; } </style>
playground/TestAssets.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00018308563448954374, 0.000174280910869129, 0.000167720383615233, 0.00017445418052375317, 0.000005158357907930622 ]
{ "id": 4, "code_window": [ "}\n", "\n", "export async function optimizeDeps(config: OptimizeOptions, asCommand = false) {\n", " const log = asCommand ? console.log : require('debug')('vite:optimize')\n", " const root = config.root || process.cwd()\n", " // warn presence of web_modules\n", " if (fs.existsSync(path.join(root, 'web_modules'))) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`\n", "\n", "export async function optimizeDeps(\n", " config: ResolvedConfig & { force?: boolean },\n", " asCommand = false\n", ") {\n" ], "file_path": "src/node/depOptimizer.ts", "type": "replace", "edit_start_line_idx": 24 }
<template src="./template.html"></template> <script src="./script.ts"></script> <style src="./style.css" scoped></style>
playground/src-import/TestBlockSrcImport.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017108260362874717, 0.00017108260362874717, 0.00017108260362874717, 0.00017108260362874717, 0 ]
{ "id": 5, "code_window": [ " }\n", "\n", " const resolver = createResolver(root, config.resolvers, config.alias)\n", "\n", " // Determine deps to optimize. The goal is to only pre-bundle deps that falls\n", " // under one of the following categories:\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { include, exclude } = config.optimizeDeps || {}\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 70 }
const start = Date.now() const argv = require('minimist')(process.argv.slice(2)) // make sure to set debug flag before requiring anything if (argv.debug) { process.env.DEBUG = `vite:` + (argv.debug === true ? '*' : argv.debug) try { // this is only present during local development require('source-map-support').install() } catch (e) {} } import os from 'os' import chalk from 'chalk' import { UserConfig, resolveConfig } from './config' function logHelp() { console.log(` Usage: vite [command] [args] [--options] Commands: vite Start server in current directory. vite serve [root=cwd] Start server in target directory. vite build [root=cwd] Build target directory. Options: --help, -h [boolean] show help --version, -v [boolean] show version --config, -c [string] use specified config file --serviceWorker, -sw [boolean] configure service worker caching (default: false) --port [number] port to use for serve --open [boolean] open browser on server start --base [string] public base path for build (default: /) --outDir [string] output directory for build (default: dist) --assetsDir [string] directory under outDir to place assets in (default: assets) --assetsInlineLimit [number] static asset base64 inline threshold in bytes (default: 4096) --sourcemap [boolean] output source maps for build (default: false) --minify [boolean | 'terser' | 'esbuild'] enable/disable minification, or specify minifier to use. (default: 'terser') --ssr [boolean] build for server-side rendering --jsx ['vue' | 'preact' | 'react'] choose jsx preset (default: 'vue') --jsx-factory [string] (default: React.createElement) --jsx-fragment [string] (default: React.Fragment) `) } console.log(chalk.cyan(`vite v${require('../package.json').version}`)) ;(async () => { if (argv.help || argv.h) { logHelp() return } else if (argv.version || argv.v) { // noop, already logged return } const options = await resolveOptions() if (!options.command || options.command === 'serve') { runServe(options) } else if (options.command === 'build') { runBuild(options) } else if (options.command === 'optimize') { runOptimize(options) } else { console.error(chalk.red(`unknown command: ${options.command}`)) process.exit(1) } })() async function resolveOptions() { // shorthand for serviceWorker option if (argv['sw']) { argv.serviceWorker = argv['sw'] } // map jsx args if (argv['jsx-factory']) { ;(argv.jsx || (argv.jsx = {})).factory = argv['jsx-factory'] } if (argv['jsx-fragment']) { ;(argv.jsx || (argv.jsx = {})).fragment = argv['jsx-fragment'] } // cast xxx=true | false into actual booleans Object.keys(argv).forEach((key) => { if (argv[key] === 'false') { argv[key] = false } if (argv[key] === 'true') { argv[key] = true } }) // command if (argv._[0]) { argv.command = argv._[0] } // normalize root // assumes all commands are in the form of `vite [command] [root]` if (argv._[1] && !argv.root) { argv.root = argv._[1] } const userConfig = await resolveConfig(argv.config || argv.c) if (userConfig) { return { ...userConfig, ...argv // cli options take higher priority } } return argv } async function runServe( options: UserConfig & { port?: number open?: boolean } ) { await require('../dist').optimizeDeps(options) const server = require('../dist').createServer(options) let port = options.port || 3000 server.on('error', (e: Error & { code?: string }) => { if (e.code === 'EADDRINUSE') { console.log(`Port ${port} is in use, trying another one...`) setTimeout(() => { server.close() server.listen(++port) }, 100) } else { console.error(chalk.red(`[vite] server error:`)) console.error(e) } }) server.listen(port, () => { console.log() console.log(` Dev server running at:`) const interfaces = os.networkInterfaces() Object.keys(interfaces).forEach((key) => { ;(interfaces[key] || []) .filter((details) => details.family === 'IPv4') .map((detail) => { return { type: detail.address.includes('127.0.0.1') ? 'Local: ' : 'Network: ', ip: detail.address.replace('127.0.0.1', 'localhost') } }) .forEach((address: { type?: String; ip?: String }) => { const url = `http://${address.ip}:${chalk.bold(port)}/` console.log(` > ${address.type} ${chalk.cyan(url)}`) }) }) console.log() require('debug')('vite:server')(`server ready in ${Date.now() - start}ms.`) if (options.open) { require('./utils/openBrowser').openBrowser(`http://localhost:${port}`) } }) } async function runBuild(options: UserConfig) { try { await require('../dist').build(options) process.exit(0) } catch (err) { console.error(chalk.red(`[vite] Build errored out.`)) console.error(err) process.exit(1) } } async function runOptimize(options: UserConfig) { try { await require('../dist').optimizeDeps(options, true /* as cli command */) process.exit(0) } catch (err) { console.error(chalk.red(`[vite] Dep optimization errored out.`)) console.error(err) process.exit(1) } }
src/node/cli.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0011884759878739715, 0.00027217555907554924, 0.00016716093523427844, 0.0001718543062452227, 0.000253489357419312 ]
{ "id": 5, "code_window": [ " }\n", "\n", " const resolver = createResolver(root, config.resolvers, config.alias)\n", "\n", " // Determine deps to optimize. The goal is to only pre-bundle deps that falls\n", " // under one of the following categories:\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { include, exclude } = config.optimizeDeps || {}\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 70 }
<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="count++">count is: {{ count }}</button> <p>Edit <code>components/HelloWorld.vue</code> to test hot module replacement.</p> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, data() { return { count: 0 } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
create-vite-app/template-vue/components/HelloWorld.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001758122816681862, 0.0001712215453153476, 0.00016762093582656235, 0.00017072647460736334, 0.0000029931570679764263 ]
{ "id": 5, "code_window": [ " }\n", "\n", " const resolver = createResolver(root, config.resolvers, config.alias)\n", "\n", " // Determine deps to optimize. The goal is to only pre-bundle deps that falls\n", " // under one of the following categories:\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { include, exclude } = config.optimizeDeps || {}\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 70 }
#app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }
create-vite-app/template-vue/index.css
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017084344290196896, 0.00017084344290196896, 0.00017084344290196896, 0.00017084344290196896, 0 ]
{ "id": 5, "code_window": [ " }\n", "\n", " const resolver = createResolver(root, config.resolvers, config.alias)\n", "\n", " // Determine deps to optimize. The goal is to only pre-bundle deps that falls\n", " // under one of the following categories:\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { include, exclude } = config.optimizeDeps || {}\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 70 }
semi: false singleQuote: true printWidth: 80 trailingComma: none
.prettierrc
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017646812193561345, 0.00017646812193561345, 0.00017646812193561345, 0.00017646812193561345, 0 ]
{ "id": 6, "code_window": [ " // 3. Has imports to bare modules that are not in the project's own deps\n", " // (i.e. esm that imports its own dependencies, e.g. styled-components)\n", " await init\n", " const qualifiedDeps = deps.filter((id) => {\n", " if (KNOWN_IGNORE_LIST.has(id)) {\n", " return false\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (include && !include.includes(id)) {\n", " return false\n", " }\n", " if (exclude && exclude.includes(id)) {\n", " return false\n", " }\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 79 }
import fs from 'fs-extra' import path from 'path' import { createHash } from 'crypto' import { ResolvedConfig } from './config' import type Rollup from 'rollup' import { createResolver, supportedExts, resolveNodeModuleEntry } from './resolver' import { createBaseRollupPlugins } from './build' import { resolveFrom, lookupFile } from './utils' import { init, parse } from 'es-module-lexer' import chalk from 'chalk' import { Ora } from 'ora' const KNOWN_IGNORE_LIST = new Set(['tailwindcss']) export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache` export interface OptimizeOptions extends ResolvedConfig { force?: boolean } export async function optimizeDeps(config: OptimizeOptions, asCommand = false) { const log = asCommand ? console.log : require('debug')('vite:optimize') const root = config.root || process.cwd() // warn presence of web_modules if (fs.existsSync(path.join(root, 'web_modules'))) { console.warn( chalk.yellow( `[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` + `from web_modules is no longer supported.` ) ) } const cacheDir = path.join(root, OPTIMIZE_CACHE_DIR) const hashPath = path.join(cacheDir, 'hash') const depHash = getDepHash(root, config.__path) if (!config.force) { let prevhash try { prevhash = await fs.readFile(hashPath, 'utf-8') } catch (e) {} // hash is consistent, no need to re-bundle if (prevhash === depHash) { log('Hash is consistent. Skipping. Use --force to override.') return } } await fs.remove(cacheDir) await fs.ensureDir(cacheDir) const pkg = lookupFile(root, [`package.json`]) if (!pkg) { log(`package.json not found. Skipping.`) return } const deps = Object.keys(JSON.parse(pkg).dependencies || {}) if (!deps.length) { await fs.writeFile(hashPath, depHash) log(`No dependencies listed in package.json. Skipping.`) return } const resolver = createResolver(root, config.resolvers, config.alias) // Determine deps to optimize. The goal is to only pre-bundle deps that falls // under one of the following categories: // 1. Is CommonJS module // 2. Has imports to relative files (e.g. lodash-es, lit-html) // 3. Has imports to bare modules that are not in the project's own deps // (i.e. esm that imports its own dependencies, e.g. styled-components) await init const qualifiedDeps = deps.filter((id) => { if (KNOWN_IGNORE_LIST.has(id)) { return false } const entry = resolveNodeModuleEntry(root, id) if (!entry) { return false } if (!supportedExts.includes(path.extname(entry))) { return false } const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8') const [imports, exports] = parse(content) if (!exports.length) { // no exports, likely a commonjs module return true } for (const { s, e } of imports) { let i = content.slice(s, e).trim() i = resolver.alias(i) || i if (i.startsWith('.') || !deps.includes(i)) { return true } } }) if (!qualifiedDeps.length) { await fs.writeFile(hashPath, depHash) log(`No listed dependency requires optimization. Skipping.`) return } if (!asCommand) { // This is auto run on server start - let the user know that we are // pre-optimizing deps console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`)) } let spinner: Ora | undefined const msg = asCommand ? `Pre-bundling dependencies to speed up dev server page load...` : `Pre-bundling them to speed up dev server page load...\n` + ` (this will be run only when your dependencies have changed)` if (process.env.DEBUG || process.env.NODE_ENV === 'test') { console.log(msg) } else { spinner = require('ora')(msg + '\n').start() } try { // Non qualified deps are marked as externals, since they will be preserved // and resolved from their original node_modules locations. const preservedDeps = deps.filter((id) => !qualifiedDeps.includes(id)) const input = qualifiedDeps.reduce((entries, name) => { entries[name] = name return entries }, {} as Record<string, string>) const rollup = require('rollup') as typeof Rollup const bundle = await rollup.rollup({ input, external: preservedDeps, treeshake: { moduleSideEffects: 'no-external' }, onwarn(warning, warn) { if (warning.code !== 'CIRCULAR_DEPENDENCY') { warn(warning) } }, ...config.rollupInputOptions, plugins: await createBaseRollupPlugins(root, resolver, config) }) const { output } = await bundle.generate({ ...config.rollupOutputOptions, format: 'es', exports: 'named', chunkFileNames: 'common/[name]-[hash].js' }) spinner && spinner.stop() const optimized = [] for (const chunk of output) { if (chunk.type === 'chunk') { const fileName = chunk.fileName const filePath = path.join(cacheDir, fileName) await fs.ensureDir(path.dirname(filePath)) await fs.writeFile(filePath, chunk.code) if (!fileName.startsWith('common/')) { optimized.push(fileName.replace(/\.js$/, '')) } } } console.log( `Optimized modules:\n${optimized .map((id) => chalk.yellowBright(id)) .join(`, `)}` ) await fs.writeFile(hashPath, depHash) } catch (e) { spinner && spinner.stop() if (asCommand) { throw e } else { console.error(chalk.red(`[vite] Dep optimization failed with error:`)) console.error(e) } } } const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'] let cachedHash: string | undefined export function getDepHash( root: string, configPath: string | undefined ): string { if (cachedHash) { return cachedHash } let content = lookupFile(root, lockfileFormats) || '' const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}') content += JSON.stringify(pkg.dependencies) // also take config into account if (configPath) { content += fs.readFileSync(configPath, 'utf-8') } return createHash('sha1').update(content).digest('base64') }
src/node/depOptimizer.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.9994465708732605, 0.18927378952503204, 0.00016985213733278215, 0.000271136115770787, 0.3766362965106964 ]
{ "id": 6, "code_window": [ " // 3. Has imports to bare modules that are not in the project's own deps\n", " // (i.e. esm that imports its own dependencies, e.g. styled-components)\n", " await init\n", " const qualifiedDeps = deps.filter((id) => {\n", " if (KNOWN_IGNORE_LIST.has(id)) {\n", " return false\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (include && !include.includes(id)) {\n", " return false\n", " }\n", " if (exclude && exclude.includes(id)) {\n", " return false\n", " }\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 79 }
<template> <h2>Scoped CSS</h2> <div class="style-scoped">&lt;style scoped&gt;: only this should be purple</div> </template> <style scoped> div { color: rgb(138, 43, 226); } </style>
playground/TestScopedCss.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001741805754136294, 0.00017403214587830007, 0.0001738837017910555, 0.00017403214587830007, 1.4843681128695607e-7 ]
{ "id": 6, "code_window": [ " // 3. Has imports to bare modules that are not in the project's own deps\n", " // (i.e. esm that imports its own dependencies, e.g. styled-components)\n", " await init\n", " const qualifiedDeps = deps.filter((id) => {\n", " if (KNOWN_IGNORE_LIST.has(id)) {\n", " return false\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (include && !include.includes(id)) {\n", " return false\n", " }\n", " if (exclude && exclude.includes(id)) {\n", " return false\n", " }\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 79 }
<h2>SFC Src Imports</h2> <div class="src-imports-script">{{ msg }}</div> <div class="src-imports-style">This should be light gray</div>
playground/src-import/template.html
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017265880887862295, 0.00017265880887862295, 0.00017265880887862295, 0.00017265880887862295, 0 ]
{ "id": 6, "code_window": [ " // 3. Has imports to bare modules that are not in the project's own deps\n", " // (i.e. esm that imports its own dependencies, e.g. styled-components)\n", " await init\n", " const qualifiedDeps = deps.filter((id) => {\n", " if (KNOWN_IGNORE_LIST.has(id)) {\n", " return false\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (include && !include.includes(id)) {\n", " return false\n", " }\n", " if (exclude && exclude.includes(id)) {\n", " return false\n", " }\n" ], "file_path": "src/node/depOptimizer.ts", "type": "add", "edit_start_line_idx": 79 }
<template> <h2>TypeScript</h2> <p class="ts-self">{{ m }}</p> <p>This should be 1 -> <span class="ts-import">{{ n }}</span></p> </template> <script lang="ts"> import { defineComponent } from 'vue' import { n } from './testTs' const m: string = 'from ts' export default defineComponent({ data() { return { n, m } } }) </script>
playground/ts/TestTs.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017128254694398493, 0.0001698952546576038, 0.00016883360513020307, 0.0001695696118986234, 0.0000010259503824272542 ]
{ "id": 7, "code_window": [ " root = process.cwd(),\n", " plugins = [],\n", " resolvers = [],\n", " alias = {},\n", " transforms = []\n", " } = config\n", "\n", " const app = new Koa()\n", " const server = http.createServer(app.callback())\n", " const watcher = chokidar.watch(root, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " transforms = [],\n", " optimizeDeps = {}\n" ], "file_path": "src/node/server/index.ts", "type": "replace", "edit_start_line_idx": 36 }
import fs from 'fs-extra' import path from 'path' import { createHash } from 'crypto' import { ResolvedConfig } from './config' import type Rollup from 'rollup' import { createResolver, supportedExts, resolveNodeModuleEntry } from './resolver' import { createBaseRollupPlugins } from './build' import { resolveFrom, lookupFile } from './utils' import { init, parse } from 'es-module-lexer' import chalk from 'chalk' import { Ora } from 'ora' const KNOWN_IGNORE_LIST = new Set(['tailwindcss']) export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache` export interface OptimizeOptions extends ResolvedConfig { force?: boolean } export async function optimizeDeps(config: OptimizeOptions, asCommand = false) { const log = asCommand ? console.log : require('debug')('vite:optimize') const root = config.root || process.cwd() // warn presence of web_modules if (fs.existsSync(path.join(root, 'web_modules'))) { console.warn( chalk.yellow( `[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` + `from web_modules is no longer supported.` ) ) } const cacheDir = path.join(root, OPTIMIZE_CACHE_DIR) const hashPath = path.join(cacheDir, 'hash') const depHash = getDepHash(root, config.__path) if (!config.force) { let prevhash try { prevhash = await fs.readFile(hashPath, 'utf-8') } catch (e) {} // hash is consistent, no need to re-bundle if (prevhash === depHash) { log('Hash is consistent. Skipping. Use --force to override.') return } } await fs.remove(cacheDir) await fs.ensureDir(cacheDir) const pkg = lookupFile(root, [`package.json`]) if (!pkg) { log(`package.json not found. Skipping.`) return } const deps = Object.keys(JSON.parse(pkg).dependencies || {}) if (!deps.length) { await fs.writeFile(hashPath, depHash) log(`No dependencies listed in package.json. Skipping.`) return } const resolver = createResolver(root, config.resolvers, config.alias) // Determine deps to optimize. The goal is to only pre-bundle deps that falls // under one of the following categories: // 1. Is CommonJS module // 2. Has imports to relative files (e.g. lodash-es, lit-html) // 3. Has imports to bare modules that are not in the project's own deps // (i.e. esm that imports its own dependencies, e.g. styled-components) await init const qualifiedDeps = deps.filter((id) => { if (KNOWN_IGNORE_LIST.has(id)) { return false } const entry = resolveNodeModuleEntry(root, id) if (!entry) { return false } if (!supportedExts.includes(path.extname(entry))) { return false } const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8') const [imports, exports] = parse(content) if (!exports.length) { // no exports, likely a commonjs module return true } for (const { s, e } of imports) { let i = content.slice(s, e).trim() i = resolver.alias(i) || i if (i.startsWith('.') || !deps.includes(i)) { return true } } }) if (!qualifiedDeps.length) { await fs.writeFile(hashPath, depHash) log(`No listed dependency requires optimization. Skipping.`) return } if (!asCommand) { // This is auto run on server start - let the user know that we are // pre-optimizing deps console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`)) } let spinner: Ora | undefined const msg = asCommand ? `Pre-bundling dependencies to speed up dev server page load...` : `Pre-bundling them to speed up dev server page load...\n` + ` (this will be run only when your dependencies have changed)` if (process.env.DEBUG || process.env.NODE_ENV === 'test') { console.log(msg) } else { spinner = require('ora')(msg + '\n').start() } try { // Non qualified deps are marked as externals, since they will be preserved // and resolved from their original node_modules locations. const preservedDeps = deps.filter((id) => !qualifiedDeps.includes(id)) const input = qualifiedDeps.reduce((entries, name) => { entries[name] = name return entries }, {} as Record<string, string>) const rollup = require('rollup') as typeof Rollup const bundle = await rollup.rollup({ input, external: preservedDeps, treeshake: { moduleSideEffects: 'no-external' }, onwarn(warning, warn) { if (warning.code !== 'CIRCULAR_DEPENDENCY') { warn(warning) } }, ...config.rollupInputOptions, plugins: await createBaseRollupPlugins(root, resolver, config) }) const { output } = await bundle.generate({ ...config.rollupOutputOptions, format: 'es', exports: 'named', chunkFileNames: 'common/[name]-[hash].js' }) spinner && spinner.stop() const optimized = [] for (const chunk of output) { if (chunk.type === 'chunk') { const fileName = chunk.fileName const filePath = path.join(cacheDir, fileName) await fs.ensureDir(path.dirname(filePath)) await fs.writeFile(filePath, chunk.code) if (!fileName.startsWith('common/')) { optimized.push(fileName.replace(/\.js$/, '')) } } } console.log( `Optimized modules:\n${optimized .map((id) => chalk.yellowBright(id)) .join(`, `)}` ) await fs.writeFile(hashPath, depHash) } catch (e) { spinner && spinner.stop() if (asCommand) { throw e } else { console.error(chalk.red(`[vite] Dep optimization failed with error:`)) console.error(e) } } } const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'] let cachedHash: string | undefined export function getDepHash( root: string, configPath: string | undefined ): string { if (cachedHash) { return cachedHash } let content = lookupFile(root, lockfileFormats) || '' const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}') content += JSON.stringify(pkg.dependencies) // also take config into account if (configPath) { content += fs.readFileSync(configPath, 'utf-8') } return createHash('sha1').update(content).digest('base64') }
src/node/depOptimizer.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.9840213656425476, 0.1429213285446167, 0.00016375893028452992, 0.00017984831356443465, 0.3276987075805664 ]
{ "id": 7, "code_window": [ " root = process.cwd(),\n", " plugins = [],\n", " resolvers = [],\n", " alias = {},\n", " transforms = []\n", " } = config\n", "\n", " const app = new Koa()\n", " const server = http.createServer(app.callback())\n", " const watcher = chokidar.watch(root, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " transforms = [],\n", " optimizeDeps = {}\n" ], "file_path": "src/node/server/index.ts", "type": "replace", "edit_start_line_idx": 36 }
MIT License Copyright (c) 2019-present, Yuxi (Evan) You Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
LICENSE
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017870613373816013, 0.00017546927847433835, 0.00017369113629683852, 0.00017401057993993163, 0.0000022925112261873437 ]
{ "id": 7, "code_window": [ " root = process.cwd(),\n", " plugins = [],\n", " resolvers = [],\n", " alias = {},\n", " transforms = []\n", " } = config\n", "\n", " const app = new Koa()\n", " const server = http.createServer(app.callback())\n", " const watcher = chokidar.watch(root, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " transforms = [],\n", " optimizeDeps = {}\n" ], "file_path": "src/node/server/index.ts", "type": "replace", "edit_start_line_idx": 36 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vite App</title> </head> <body> <div id="root"></div> <script type="module" src="./main.jsx"></script> </body> </html>
create-vite-app/template-react/src/index.html
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017343660874757916, 0.00017270978423766792, 0.0001719829742796719, 0.00017270978423766792, 7.26817233953625e-7 ]
{ "id": 7, "code_window": [ " root = process.cwd(),\n", " plugins = [],\n", " resolvers = [],\n", " alias = {},\n", " transforms = []\n", " } = config\n", "\n", " const app = new Koa()\n", " const server = http.createServer(app.callback())\n", " const watcher = chokidar.watch(root, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " transforms = [],\n", " optimizeDeps = {}\n" ], "file_path": "src/node/server/index.ts", "type": "replace", "edit_start_line_idx": 36 }
import { render } from 'preact' import { Test } from './testTsx.tsx' const Component = () => <div> Rendered from Preact JSX <Test count={1337} /> </div> export function renderPreact(el) { render(<Component/>, el) }
playground/testJsx.jsx
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00017787415708880872, 0.00017660215962678194, 0.00017533016216475517, 0.00017660215962678194, 0.0000012719974620267749 ]
{ "id": 8, "code_window": [ " ]\n", " resolvedPlugins.forEach((m) => m(context))\n", "\n", " return server\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const listen = server.listen.bind(server)\n", " server.listen = (async (...args: any[]) => {\n", " if (optimizeDeps.auto !== false) {\n", " await require('../depOptimizer').optimizeDeps(config)\n", " }\n", " return listen(...args)\n", " }) as any\n", "\n" ], "file_path": "src/node/server/index.ts", "type": "add", "edit_start_line_idx": 71 }
import http, { Server } from 'http' import Koa from 'koa' import chokidar from 'chokidar' import { createResolver, InternalResolver } from '../resolver' import { moduleRewritePlugin } from './serverPluginModuleRewrite' import { moduleResolvePlugin } from './serverPluginModuleResolve' import { vuePlugin } from './serverPluginVue' import { hmrPlugin, HMRWatcher } from './serverPluginHmr' import { serveStaticPlugin } from './serverPluginServeStatic' import { jsonPlugin } from './serverPluginJson' import { cssPlugin } from './serverPluginCss' import { assetPathPlugin } from './serverPluginAssets' import { esbuildPlugin } from './serverPluginEsbuild' import { ServerConfig } from '../config' import { createServerTransformPlugin } from '../transform' import { serviceWorkerPlugin } from './serverPluginServiceWorker' export { rewriteImports } from './serverPluginModuleRewrite' export type ServerPlugin = (ctx: ServerPluginContext) => void export interface ServerPluginContext { root: string app: Koa server: Server watcher: HMRWatcher resolver: InternalResolver config: ServerConfig & { __path?: string } } export function createServer(config: ServerConfig = {}): Server { const { root = process.cwd(), plugins = [], resolvers = [], alias = {}, transforms = [] } = config const app = new Koa() const server = http.createServer(app.callback()) const watcher = chokidar.watch(root, { ignored: [/node_modules/] }) as HMRWatcher const resolver = createResolver(root, resolvers, alias) const context = { root, app, server, watcher, resolver, config } const resolvedPlugins = [ ...plugins, serviceWorkerPlugin, hmrPlugin, moduleRewritePlugin, moduleResolvePlugin, vuePlugin, esbuildPlugin, jsonPlugin, cssPlugin, assetPathPlugin, ...(transforms.length ? [createServerTransformPlugin(transforms)] : []), serveStaticPlugin ] resolvedPlugins.forEach((m) => m(context)) return server }
src/node/server/index.ts
1
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.09741362184286118, 0.013506090268492699, 0.0001661872083786875, 0.001841984922066331, 0.03172609210014343 ]
{ "id": 8, "code_window": [ " ]\n", " resolvedPlugins.forEach((m) => m(context))\n", "\n", " return server\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const listen = server.listen.bind(server)\n", " server.listen = (async (...args: any[]) => {\n", " if (optimizeDeps.auto !== false) {\n", " await require('../depOptimizer').optimizeDeps(config)\n", " }\n", " return listen(...args)\n", " }) as any\n", "\n" ], "file_path": "src/node/server/index.ts", "type": "add", "edit_start_line_idx": 71 }
<template> <h2>JSON</h2> <pre class="json">Imported JSON: {{ json }}</pre> </template> <script> import json from './testJsonImport.json' export default { data: () => ({ json }) } </script>
playground/TestJsonImport.vue
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.0001752455864334479, 0.00017427100101485848, 0.0001732964301481843, 0.00017427100101485848, 9.74578142631799e-7 ]
{ "id": 8, "code_window": [ " ]\n", " resolvedPlugins.forEach((m) => m(context))\n", "\n", " return server\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const listen = server.listen.bind(server)\n", " server.listen = (async (...args: any[]) => {\n", " if (optimizeDeps.auto !== false) {\n", " await require('../depOptimizer').optimizeDeps(config)\n", " }\n", " return listen(...args)\n", " }) as any\n", "\n" ], "file_path": "src/node/server/index.ts", "type": "add", "edit_start_line_idx": 71 }
import path from 'path' import { ServerPlugin } from '.' const send = require('koa-send') const debug = require('debug')('vite:history') export const seenUrls = new Set() export const serveStaticPlugin: ServerPlugin = ({ root, app, resolver, config }) => { app.use((ctx, next) => { // short circuit requests that have already been explicitly handled if (ctx.body || ctx.status !== 404) { return } return next() }) // history API fallback app.use((ctx, next) => { if (ctx.method !== 'GET') { debug(`not redirecting ${ctx.url} (not GET)`) return next() } const accept = ctx.headers && ctx.headers.accept if (typeof accept !== 'string') { debug(`not redirecting ${ctx.url} (no headers.accept)`) return next() } if (accept.includes('application/json')) { debug(`not redirecting ${ctx.url} (json)`) return next() } if (!(accept.includes('text/html') || accept.includes('*/*'))) { debug(`not redirecting ${ctx.url} (not accepting html)`) return next() } const ext = path.extname(ctx.path) if (ext && !accept.includes('text/html')) { debug(`not redirecting ${ctx.url} (has file extension)`) return next() } debug(`redirecting ${ctx.url} to /index.html`) ctx.url = '/index.html' return next() }) if (!config.serviceWorker) { app.use(async (ctx, next) => { await next() // the first request to the server should never 304 if (seenUrls.has(ctx.url) && ctx.fresh) { ctx.status = 304 } seenUrls.add(ctx.url) }) } app.use(require('koa-etag')()) app.use((ctx, next) => { const redirect = resolver.requestToFile(ctx.path) if (!redirect.startsWith(root)) { // resolver resolved to a file that is outside of project root, // manually send here return send(ctx, redirect, { root: '/' }) } return next() }) app.use(require('koa-static')(root)) }
src/node/server/serverPluginServeStatic.ts
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00023139191034715623, 0.00017971194756682962, 0.00016741041326895356, 0.0001715813559712842, 0.000019236480511608534 ]
{ "id": 8, "code_window": [ " ]\n", " resolvedPlugins.forEach((m) => m(context))\n", "\n", " return server\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const listen = server.listen.bind(server)\n", " server.listen = (async (...args: any[]) => {\n", " if (optimizeDeps.auto !== false) {\n", " await require('../depOptimizer').optimizeDeps(config)\n", " }\n", " return listen(...args)\n", " }) as any\n", "\n" ], "file_path": "src/node/server/index.ts", "type": "add", "edit_start_line_idx": 71 }
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
.github/ISSUE_TEMPLATE/feature_request.md
0
https://github.com/vitejs/vite/commit/57c1b6691c06408cc56b4625e3245ed2de32b317
[ 0.00018145267677027732, 0.0001736097183311358, 0.0001658957335166633, 0.00017348077381029725, 0.000006351750016619917 ]
{ "id": 0, "code_window": [ "// Type definitions for react-tag-autocomplete 5.6\n", "// Project: https://github.com/i-like-robots/react-tags#readme\n", "// Definitions by: James Lismore <https://github.com/jlismore>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.8\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Rahul Sagore <https://github.com/Rahul-Sagore>\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 3 }
import * as React from "react"; import ReactTags, { TagComponentProps } from "react-tag-autocomplete"; class TestRequired extends React.Component { render() { const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; return ( <ReactTags handleAddition={onAddTag} handleDelete={onDeleteTag} /> ); } } class TestAll extends React.Component { render() { const classNamesObj = { root: "react-tags", rootFocused: "is-focused", selected: "react-tags__selected", selectedTag: "react-tags__selected-tag", selectedTagName: "react-tags__selected-tag-name", search: "react-tags__search", searchInput: "react-tags__search-input", suggestions: "react-tags__suggestions", suggestionActive: "is-active", suggestionDisabled: "is-disabled" }; const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; const onBlur = () => {}; const onFocus = () => {}; const onInputChange = (input: string) => {}; const inputAttributes = { maxLength: 10 }; const suggestions = [ { id: 3, name: "Bananas" }, { id: 4, name: "Mangos" }, { id: 5, name: "Lemons" }, { id: 6, name: "Apricots", disabled: true } ]; const tagComponent = (props: TagComponentProps) => ( <button onClick={props.onDelete}>{props.tag.name}</button> ); const tags = [{ id: 1, name: "Apples" }, { id: 2, name: "Pears" }]; return ( <ReactTags allowBackspace={false} allowNew={false} autofocus={false} autoresize={false} classNames={classNamesObj} delimiterChars={[",", " "]} delimiters={[9, 13]} handleAddition={onAddTag} handleBlur={onBlur} handleDelete={onDeleteTag} handleFocus={onFocus} handleInputChange={onInputChange} inputAttributes={inputAttributes} maxSuggestionsLength={10} minQueryLength={5} placeholder="" suggestions={suggestions} tagComponent={tagComponent} tags={tags} /> ); } }
types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00023197574773803353, 0.0001943655515788123, 0.00017226641648449004, 0.00018372114573139697, 0.00002260118526464794 ]
{ "id": 0, "code_window": [ "// Type definitions for react-tag-autocomplete 5.6\n", "// Project: https://github.com/i-like-robots/react-tags#readme\n", "// Definitions by: James Lismore <https://github.com/jlismore>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.8\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Rahul Sagore <https://github.com/Rahul-Sagore>\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for react-native-scrollable-tab-view 0.8 // Project: https://github.com/brentvatne/react-native-scrollable-tab-view // Definitions by: CaiHuan <https://github.com/CaiHuan> // Egor Shulga <https://github.com/egorshulga> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; import { Animated, ScrollViewProps, ViewStyle, TextStyle, StyleProp } from 'react-native'; export interface ScrollableTabViewProperties extends React.Props<ScrollableTabView> { /** * accept 1 argument props and should return a component * to use as the tab bar. The component has goToPage, tabs, activeTab and ref added to the props, * and should implement setAnimationValue to be able to animate itself along with the tab content. * You can manually pass the props to the TabBar component. */ renderTabBar?: ((props: TabBarProps) => JSX.Element) | false; /** * Defaults to "top". * "bottom" to position the tab bar below content. * "overlayTop" or "overlayBottom" for a semitransparent tab bar that overlays content. Custom * tab bars must consume a style prop on their outer element to support this feature: style={this.props.style}. */ tabBarPosition?: 'top' | 'bottom' | 'overlayTop' | 'overlayBottom'; /** * function to call when tab changes, should accept 1 argument which is * an Object containing two keys: i: the index of the tab that is selected, ref: the ref of the * tab that is selected */ onChangeTab?(value: ChangeTabProperties): void; /** * function to call when the pages are sliding, * should accept 1 argument which is an Float number representing the page position in the slide frame. */ onScroll?(value: number): void; /** * disables horizontal dragging to scroll between tabs, default is false. */ locked?: boolean; /** * the index of the initially selected tab, defaults to 0 === first tab */ initialPage?: number; /** * set selected tab(can be buggy see * https://github.com/skv-headless/react-native-scrollable-tab-view/issues/126 */ page?: number; /** * style of the default tab bar's underline */ tabBarUnderlineStyle?: StyleProp<ViewStyle>; /** * color of the default tab bar's background, defaults to white */ tabBarBackgroundColor?: string; /** * color of the default tab bar's text when active, defaults to navy */ tabBarActiveTextColor?: string; /** * color of the default tab bar's text when inactive, defaults to black */ tabBarInactiveTextColor?: string; /** * additional styles to the tab bar's text */ tabBarTextStyle?: StyleProp<TextStyle>; /** * style (View.propTypes.style) */ style?: StyleProp<ViewStyle>; /** * props that are applied to root ScrollView/ViewPagerAndroid. * Note that overriding defaults set by the library may break functionality; see the source for details. */ contentProps?: ScrollViewProps; /** * on tab press change tab without animation. */ scrollWithoutAnimation?: boolean; /** * pre-render nearby # sibling, Infinity === render all * the siblings, default to 0 === render current page. */ prerenderingSiblingsNumber?: number; } export type TabBarProps<T = {}> = T & { goToPage?: (pageNumber: number) => void; tabs?: JSX.Element[]; activeTab?: number; scrollValue?: Animated.Value; containerWidth?: number; }; export interface ChangeTabProperties { // currentPage i: number; // currentPage object ref: JSX.Element; // previousPage from: number; } export default class ScrollableTabView extends React.Component<ScrollableTabViewProperties> { } // Each top-level child component should have a tabLabel prop // that can be used by the tab bar component to render out the labels. export type TabProps<T = {}> = T & { tabLabel: React.ReactChild; }; export interface DefaultTabBarProps { backgroundColor?: string; activeTextColor?: string; inactiveTextColor?: string; textStyle?: TextStyle; tabStyle?: ViewStyle; renderTab?: RenderTabProperties; underlineStyle?: ViewStyle; } export type RenderTabProperties = (name: string, pageIndex: number, isTabActive: boolean, goToPage: (pageNumber: number) => void) => JSX.Element; export class DefaultTabBar extends React.Component<TabBarProps<DefaultTabBarProps>> { } export interface ScrollableTabBarProps extends DefaultTabBarProps { scrollOffset?: number; style?: ViewStyle; tabsContainerStyle?: ViewStyle; } export class ScrollableTabBar extends React.Component<TabBarProps<ScrollableTabBarProps>> { }
types/react-native-scrollable-tab-view/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00035791847039945424, 0.0001859652402345091, 0.0001652616774663329, 0.000169736536918208, 0.000045972941734362394 ]
{ "id": 0, "code_window": [ "// Type definitions for react-tag-autocomplete 5.6\n", "// Project: https://github.com/i-like-robots/react-tags#readme\n", "// Definitions by: James Lismore <https://github.com/jlismore>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.8\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Rahul Sagore <https://github.com/Rahul-Sagore>\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 3 }
{ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, "array-type": false, "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, "comment-format": false, "dt-header": false, "npm-naming": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-for-in-array": false, "no-inferrable-types": false, "no-internal-module": false, "no-irregular-whitespace": false, "no-mergeable-namespace": false, "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, "no-reference-import": false, "no-relative-import-in-test": false, "no-self-import": false, "no-single-declare-module": false, "no-string-throw": false, "no-unnecessary-callback-wrapper": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-useless-files": false, "no-var-keyword": false, "no-var-requires": false, "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, "only-arrow-functions": false, "prefer-conditional-expression": false, "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, "prefer-template": false, "radix": false, "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, "trim-file": false, "triple-equals": false, "typedef-whitespace": false, "unified-signatures": false, "void-return": false, "whitespace": false } }
types/camo/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017694311100058258, 0.00017408969870302826, 0.00017199003195855767, 0.0001736605045152828, 0.0000016412953982580802 ]
{ "id": 0, "code_window": [ "// Type definitions for react-tag-autocomplete 5.6\n", "// Project: https://github.com/i-like-robots/react-tags#readme\n", "// Definitions by: James Lismore <https://github.com/jlismore>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.8\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Rahul Sagore <https://github.com/Rahul-Sagore>\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for type-detect v4.0.x // Project: https://github.com/chaijs/type-detect // Definitions by: Bart van der Schoor <https://github.com/Bartvds> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function typeDetect(obj: any): string; export = typeDetect;
types/type-detect/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00027999599114991724, 0.00027999599114991724, 0.00027999599114991724, 0.00027999599114991724, 0 ]
{ "id": 1, "code_window": [ " * Optional event handler when the input changes. Receives the current input value.\n", " */\n", " handleInputChange?: (input: string) => void;\n", " /**\n", " * An object containing additional attributes that will be applied to the underlying <input /> field.\n", " */\n", " inputAttributes?: { [key: string]: any };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Optional validation function that determines if tag should be added to tags. Receives a tag object. Should return a boolean.\n", " */\n", " handleValidate?: (tag: Tag) => boolean;\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 83 }
import * as React from "react"; import ReactTags, { TagComponentProps } from "react-tag-autocomplete"; class TestRequired extends React.Component { render() { const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; return ( <ReactTags handleAddition={onAddTag} handleDelete={onDeleteTag} /> ); } } class TestAll extends React.Component { render() { const classNamesObj = { root: "react-tags", rootFocused: "is-focused", selected: "react-tags__selected", selectedTag: "react-tags__selected-tag", selectedTagName: "react-tags__selected-tag-name", search: "react-tags__search", searchInput: "react-tags__search-input", suggestions: "react-tags__suggestions", suggestionActive: "is-active", suggestionDisabled: "is-disabled" }; const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; const onBlur = () => {}; const onFocus = () => {}; const onInputChange = (input: string) => {}; const inputAttributes = { maxLength: 10 }; const suggestions = [ { id: 3, name: "Bananas" }, { id: 4, name: "Mangos" }, { id: 5, name: "Lemons" }, { id: 6, name: "Apricots", disabled: true } ]; const tagComponent = (props: TagComponentProps) => ( <button onClick={props.onDelete}>{props.tag.name}</button> ); const tags = [{ id: 1, name: "Apples" }, { id: 2, name: "Pears" }]; return ( <ReactTags allowBackspace={false} allowNew={false} autofocus={false} autoresize={false} classNames={classNamesObj} delimiterChars={[",", " "]} delimiters={[9, 13]} handleAddition={onAddTag} handleBlur={onBlur} handleDelete={onDeleteTag} handleFocus={onFocus} handleInputChange={onInputChange} inputAttributes={inputAttributes} maxSuggestionsLength={10} minQueryLength={5} placeholder="" suggestions={suggestions} tagComponent={tagComponent} tags={tags} /> ); } }
types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.9730502963066101, 0.1410834938287735, 0.0001685675379121676, 0.00017790232959669083, 0.33967897295951843 ]
{ "id": 1, "code_window": [ " * Optional event handler when the input changes. Receives the current input value.\n", " */\n", " handleInputChange?: (input: string) => void;\n", " /**\n", " * An object containing additional attributes that will be applied to the underlying <input /> field.\n", " */\n", " inputAttributes?: { [key: string]: any };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Optional validation function that determines if tag should be added to tags. Receives a tag object. Should return a boolean.\n", " */\n", " handleValidate?: (tag: Tag) => boolean;\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 83 }
declare namespace pc { /** * @name pc.SoundInstance * @class A pc.SoundInstance plays a {@link pc.Sound} * @param {pc.SoundManager} manager The sound manager * @param {pc.Sound} sound The sound to play * @param {Object} options Options for the instance * @param {Number} [options.volume=1] The playback volume, between 0 and 1. * @param {Number} [options.pitch=1] The relative pitch, default of 1, plays at normal pitch. * @param {Boolean} [options.loop=false] Whether the sound should loop when it reaches the end or not. * @param {Number} [options.startTime=0] The time from which the playback will start. Default is 0 to start at the beginning. * @param {Number} [options.duration=null] The total time after the startTime when playback will stop or restart if loop is true. * @param {Function} [options.onPlay=null] Function called when the instance starts playing. * @param {Function} [options.onPause=null] Function called when the instance is paused. * @param {Function} [options.onResume=null] Function called when the instance is resumed. * @param {Function} [options.onStop=null] Function called when the instance is stopped. * @param {Function} [options.onEnd=null] Function called when the instance ends. * @property {Number} volume The volume modifier to play the sound with. In range 0-1. * @property {Number} pitch The pitch modifier to play the sound with. Must be larger than 0.01 * @property {Number} startTime The start time from which the sound will start playing. * @property {Number} currentTime Gets or sets the current time of the sound that is playing. If the value provided is bigger than the duration of the instance it will wrap from the beginning. * @property {Number} duration The duration of the sound that the instance will play starting from startTime. * @property {Boolean} loop If true the instance will restart when it finishes playing * @property {Boolean} isPlaying Returns true if the instance is currently playing. * @property {Boolean} isPaused Returns true if the instance is currently paused. * @property {Boolean} isStopped Returns true if the instance is currently stopped. * @property {Boolean} isSuspended Returns true if the instance is currently suspended because the window is not focused. * @property {AudioBufferSourceNode} source Gets the source that plays the sound resource. If the Web Audio API is not supported the type of source is <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio" target="_blank">Audio</a>. Source is only available after calling play. * @property {pc.Sound} sound The sound resource that the instance will play. */ class SoundInstance { constructor(manager: pc.SoundManager, sound: pc.Sound, options: { volume?: number; pitch?: number; loop?: boolean; startTime?: number; duration?: number; onPlay?: Function; onPause?: Function; onResume?: Function; onStop?: Function; onEnd?: Function; }) volume: number; pitch: number; startTime: number; currentTime: number; duration: number; loop: boolean; isPlaying: boolean; isPaused: boolean; isStopped: boolean; isSuspended: boolean; source: AudioBufferSourceNode; sound: pc.Sound; /** * @function * @private * @name pc.SoundInstance#_initializeNodes * @description Creates internal audio nodes and connects them */ private _initializeNodes(): void; /** * @function * @name pc.SoundInstance#play * @description Begins playback of sound. If the sound is not loaded this will return false. * If the sound is already playing this will restart the sound. * @returns {Boolean} True if the sound was started. */ play(): boolean; /** * @function * @name pc.SoundInstance#pause * @description Pauses playback of sound. Call resume() to resume playback from the same position. * @returns {Boolean} Returns true if the sound was paused */ pause(): boolean; /** * @function * @name pc.SoundInstance#resume * @description Resumes playback of the sound. Playback resumes at the point that the audio was paused * @returns {Boolean} Returns true if the sound was resumed. */ resume(): void; /** * @function * @name pc.SoundInstance#stop * @description Stops playback of sound. Calling play() again will restart playback from the beginning of the sound. */ stop(): boolean; /** * @function * @name pc.SoundInstance#setExternalNodes * @description Connects external Web Audio API nodes. You need to pass * the first node of the node graph that you created externally and the last node of that graph. The first * node will be connected to the audio source and the last node will be connected to the destination of the * AudioContext (e.g. speakers). Requires Web Audio API support. * @param {AudioNode} firstNode The first node that will be connected to the audio source of sound instances. * @param {AudioNode} [lastNode] The last node that will be connected to the destination of the AudioContext. * If unspecified then the firstNode will be connected to the destination instead. * @example * var context = app.systems.sound.context; * var analyzer = context.createAnalyzer(); * var distortion = context.createWaveShaper(); * var filter = context.createBiquadFilter(); * analyzer.connect(distortion); * distortion.connect(filter); * instance.setExternalNodes(analyzer, filter); */ setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void; /** * @function * @name pc.SoundInstance#clearExternalNodes * @description Clears any external nodes set by {@link pc.SoundInstance#setExternalNodes}. */ clearExternalNodes(): void; /** * @function * @name pc.SoundInstance#getExternalNodes * @description Gets any external nodes set by {@link pc.SoundInstance#setExternalNodes}. * @return {AudioNode[]} Returns an array that contains the two nodes set by {@link pc.SoundInstance#setExternalNodes}. */ getExternalNodes(): AudioNode[]; /** * @private * @function * @description Creates the source for the instance */ private _createSource(): AudioBufferSourceNode; /** * @private * @function * @name pc.SoundInstance#_updateCurrentTime * @description Sets the current time taking into account the time the instance started playing, the current pitch and the current time offset. */ private _updateCurrentTime(): void; /** * @private * @function * @name pc.SoundInstance#_onManagerDestroy * @description Handle the manager's 'destroy' event. */ private _onManagerDestroy(): void; /** * @private * @function * @name pc.SoundInstance#_onManagerVolumeChange * @description Handle the manager's 'volumechange' event. */ private _onManagerVolumeChange(): void; /** * @private * @function * @name pc.SoundInstance#_onManagerSuspend * @description Handle the manager's 'suspend' event. */ private _onManagerSuspend(): void; /** * @private * @function * @name pc.SoundInstance#_onManagerResume * @description Handle the manager's 'resume' event. */ private _onManagerResume(): void; // Events /** * @function * @name pc.SoundInstance#on * @description Attach an event handler to an event * @param {String} name Name of the event to bind the callback to * @param {Function} callback Function that is called when event is fired. Note the callback is limited to 8 arguments. * @param {Object} [scope] Object to use as 'this' when the event is fired, defaults to current this * @example * obj.on('test', function (a, b) { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console */ on(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function * @name pc.SoundInstance#off * @description Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event, * if scope is not provided then all events with the callback will be unbound. * @param {String} [name] Name of the event to unbind * @param {Function} [callback] Function to be unbound * @param {Object} [scope] Scope that was used as the this when the event is fired * @example * var handler = function () { * }; * obj.on('test', handler); * * obj.off(); // Removes all events * obj.off('test'); // Removes all events called 'test' * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this */ off(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function * @name pc.SoundInstance#fire * @description Fire an event, all additional arguments are passed on to the event listener * @param {Object} name Name of event to fire * @param {*} [...] Arguments that are passed to the event handler * @example * obj.fire('test', 'This is the message'); */ fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; /** * @function * @name pc.SoundInstance#once * @description Attach an event handler to an event. This handler will be removed after being fired once. * @param {String} name Name of the event to bind the callback to * @param {Function} callback Function that is called when event is fired. Note the callback is limited to 8 arguments. * @param {Object} [scope] Object to use as 'this' when the event is fired, defaults to current this * @example * obj.once('test', function (a, b) { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ once(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function * @name pc.SoundInstance#hasEvent * @description Test if there are any handlers bound to an event name * @param {String} name The name of the event to test * @example * obj.on('test', function () { }); // bind an event to 'test' * obj.hasEvent('test'); // returns true */ hasEvent(name: string): boolean; } }
types/playcanvas/engine/sound/instance.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.0011901067337021232, 0.0002458134840708226, 0.00016406150825787336, 0.0001707354822428897, 0.0002019821695284918 ]
{ "id": 1, "code_window": [ " * Optional event handler when the input changes. Receives the current input value.\n", " */\n", " handleInputChange?: (input: string) => void;\n", " /**\n", " * An object containing additional attributes that will be applied to the underlying <input /> field.\n", " */\n", " inputAttributes?: { [key: string]: any };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Optional validation function that determines if tag should be added to tags. Receives a tag object. Should return a boolean.\n", " */\n", " handleValidate?: (tag: Tag) => boolean;\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 83 }
import stream = require("stream"); import Stream = stream.Duplex; import series = require("stream-series"); var stream1 = new Stream(); var stream2 = new Stream(); var stream3 = new Stream(); var orderedStream = series(stream1, stream3, stream2); console.log(orderedStream.toString());
types/stream-series/stream-series-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.0001780730381142348, 0.00017543451394885778, 0.00017279598978348076, 0.00017543451394885778, 0.000002638524165377021 ]
{ "id": 1, "code_window": [ " * Optional event handler when the input changes. Receives the current input value.\n", " */\n", " handleInputChange?: (input: string) => void;\n", " /**\n", " * An object containing additional attributes that will be applied to the underlying <input /> field.\n", " */\n", " inputAttributes?: { [key: string]: any };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Optional validation function that determines if tag should be added to tags. Receives a tag object. Should return a boolean.\n", " */\n", " handleValidate?: (tag: Tag) => boolean;\n" ], "file_path": "types/react-tag-autocomplete/index.d.ts", "type": "add", "edit_start_line_idx": 83 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "viewerjs-tests.ts" ] }
types/viewerjs/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.0001732417440507561, 0.0001728219649521634, 0.00017248732910957187, 0.00017273685079999268, 3.138152635528968e-7 ]
{ "id": 2, "code_window": [ " const onAddTag = (tag: { id: string | number; name: string }) => {};\n", " const onDeleteTag = (i: number) => {};\n", " const onBlur = () => {};\n", " const onFocus = () => {};\n", " const onInputChange = (input: string) => {};\n", " const inputAttributes = { maxLength: 10 };\n", " const suggestions = [\n", " { id: 3, name: \"Bananas\" },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const onValidate = (tag: { id: string | number; name: string }) => true;\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 32 }
import * as React from "react"; import ReactTags, { TagComponentProps } from "react-tag-autocomplete"; class TestRequired extends React.Component { render() { const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; return ( <ReactTags handleAddition={onAddTag} handleDelete={onDeleteTag} /> ); } } class TestAll extends React.Component { render() { const classNamesObj = { root: "react-tags", rootFocused: "is-focused", selected: "react-tags__selected", selectedTag: "react-tags__selected-tag", selectedTagName: "react-tags__selected-tag-name", search: "react-tags__search", searchInput: "react-tags__search-input", suggestions: "react-tags__suggestions", suggestionActive: "is-active", suggestionDisabled: "is-disabled" }; const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; const onBlur = () => {}; const onFocus = () => {}; const onInputChange = (input: string) => {}; const inputAttributes = { maxLength: 10 }; const suggestions = [ { id: 3, name: "Bananas" }, { id: 4, name: "Mangos" }, { id: 5, name: "Lemons" }, { id: 6, name: "Apricots", disabled: true } ]; const tagComponent = (props: TagComponentProps) => ( <button onClick={props.onDelete}>{props.tag.name}</button> ); const tags = [{ id: 1, name: "Apples" }, { id: 2, name: "Pears" }]; return ( <ReactTags allowBackspace={false} allowNew={false} autofocus={false} autoresize={false} classNames={classNamesObj} delimiterChars={[",", " "]} delimiters={[9, 13]} handleAddition={onAddTag} handleBlur={onBlur} handleDelete={onDeleteTag} handleFocus={onFocus} handleInputChange={onInputChange} inputAttributes={inputAttributes} maxSuggestionsLength={10} minQueryLength={5} placeholder="" suggestions={suggestions} tagComponent={tagComponent} tags={tags} /> ); } }
types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.9991986155509949, 0.8252852559089661, 0.00016891572158783674, 0.9970827698707581, 0.3434334099292755 ]
{ "id": 2, "code_window": [ " const onAddTag = (tag: { id: string | number; name: string }) => {};\n", " const onDeleteTag = (i: number) => {};\n", " const onBlur = () => {};\n", " const onFocus = () => {};\n", " const onInputChange = (input: string) => {};\n", " const inputAttributes = { maxLength: 10 };\n", " const suggestions = [\n", " { id: 3, name: \"Bananas\" },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const onValidate = (tag: { id: string | number; name: string }) => true;\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 32 }
{ "compilerOptions": { "module": "commonjs", "lib": ["dom", "es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "jsx": "react", "typeRoots": ["../"], "paths": { "@storybook/react": ["storybook__react"] }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "components/Marked.d.ts", "storybook-readme-tests.tsx" ] }
types/storybook-readme/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017582353029865772, 0.00017448060680180788, 0.00017370140994898975, 0.00017391685105394572, 9.536616971672629e-7 ]
{ "id": 2, "code_window": [ " const onAddTag = (tag: { id: string | number; name: string }) => {};\n", " const onDeleteTag = (i: number) => {};\n", " const onBlur = () => {};\n", " const onFocus = () => {};\n", " const onInputChange = (input: string) => {};\n", " const inputAttributes = { maxLength: 10 };\n", " const suggestions = [\n", " { id: 3, name: \"Bananas\" },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const onValidate = (tag: { id: string | number; name: string }) => true;\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 32 }
import { bindAll } from "../fp"; export = bindAll;
types/lodash/fp/bindAll.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017337560711894184, 0.00017337560711894184, 0.00017337560711894184, 0.00017337560711894184, 0 ]
{ "id": 2, "code_window": [ " const onAddTag = (tag: { id: string | number; name: string }) => {};\n", " const onDeleteTag = (i: number) => {};\n", " const onBlur = () => {};\n", " const onFocus = () => {};\n", " const onInputChange = (input: string) => {};\n", " const inputAttributes = { maxLength: 10 };\n", " const suggestions = [\n", " { id: 3, name: \"Bananas\" },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const onValidate = (tag: { id: string | number; name: string }) => true;\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 32 }
var obj = { 'first_name': 'John', 'last_name': 'Doe' }; dot.move('first_name', 'contact.firstname', obj); dot.move('last_name', 'contact.lastname', obj); var src = { name: 'John', stuff: { phone: { brand: 'iphone', version: 6 } } }; var tgt = { name: 'Brandon' }; dot.copy('stuff.phone', 'wanna.haves.phone', src, tgt, [(arg: any) => { return arg; }]); dot.transfer('stuff.phone', 'wanna.haves.phone', src, tgt); var row = { 'id': 2, 'contact.name.first': 'John', 'contact.name.last': 'Doe', 'contact.email': '[email protected]', 'contact.info.about.me': 'classified', 'devices[0]': 'mobile', 'devices[1]': 'laptop', 'some.other.things.0': 'this', 'some.other.things.1': 'that' }; dot.object(row, (arg: any) => { return arg; }); dot.str('this.is.my.string', 'value', tgt); var newObj = { some: { nested: { value: 'Hi there!' } }, breath: { value: 'Hello' } }; var val = dot.pick('some.nested.value', newObj); console.log(val); // Set a new value val = dot.str('breath.value', 'World', newObj); // Replacing with a new object val = dot.set('breath', { value: 'Goodbye' }, newObj); // Pick & Remove the value val = dot.pick('some.nested.value', newObj, true); // shorthand val = dot.remove('some.nested.value', newObj); // or use the alias `del` val = dot.del('some.nested.value', newObj); // convert object to dot object var result = {}; dot.dot({ test: 'something' }, result); result = dot.dot({ test: 'something' }); var dotWithArrow = new dot('=>');
types/dot-object/dot-object-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017385417595505714, 0.000172257365193218, 0.00017055991338565946, 0.00017196181579492986, 0.0000010735532214312116 ]
{ "id": 3, "code_window": [ " handleDelete={onDeleteTag}\n", " handleFocus={onFocus}\n", " handleInputChange={onInputChange}\n", " inputAttributes={inputAttributes}\n", " maxSuggestionsLength={10}\n", " minQueryLength={5}\n", " placeholder=\"\"\n", " suggestions={suggestions}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " handleValidate={onValidate}\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 57 }
import * as React from "react"; import ReactTags, { TagComponentProps } from "react-tag-autocomplete"; class TestRequired extends React.Component { render() { const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; return ( <ReactTags handleAddition={onAddTag} handleDelete={onDeleteTag} /> ); } } class TestAll extends React.Component { render() { const classNamesObj = { root: "react-tags", rootFocused: "is-focused", selected: "react-tags__selected", selectedTag: "react-tags__selected-tag", selectedTagName: "react-tags__selected-tag-name", search: "react-tags__search", searchInput: "react-tags__search-input", suggestions: "react-tags__suggestions", suggestionActive: "is-active", suggestionDisabled: "is-disabled" }; const onAddTag = (tag: { id: string | number; name: string }) => {}; const onDeleteTag = (i: number) => {}; const onBlur = () => {}; const onFocus = () => {}; const onInputChange = (input: string) => {}; const inputAttributes = { maxLength: 10 }; const suggestions = [ { id: 3, name: "Bananas" }, { id: 4, name: "Mangos" }, { id: 5, name: "Lemons" }, { id: 6, name: "Apricots", disabled: true } ]; const tagComponent = (props: TagComponentProps) => ( <button onClick={props.onDelete}>{props.tag.name}</button> ); const tags = [{ id: 1, name: "Apples" }, { id: 2, name: "Pears" }]; return ( <ReactTags allowBackspace={false} allowNew={false} autofocus={false} autoresize={false} classNames={classNamesObj} delimiterChars={[",", " "]} delimiters={[9, 13]} handleAddition={onAddTag} handleBlur={onBlur} handleDelete={onDeleteTag} handleFocus={onFocus} handleInputChange={onInputChange} inputAttributes={inputAttributes} maxSuggestionsLength={10} minQueryLength={5} placeholder="" suggestions={suggestions} tagComponent={tagComponent} tags={tags} /> ); } }
types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.7988837957382202, 0.11794011294841766, 0.00016952854639384896, 0.0018324998673051596, 0.278067946434021 ]
{ "id": 3, "code_window": [ " handleDelete={onDeleteTag}\n", " handleFocus={onFocus}\n", " handleInputChange={onInputChange}\n", " inputAttributes={inputAttributes}\n", " maxSuggestionsLength={10}\n", " minQueryLength={5}\n", " placeholder=\"\"\n", " suggestions={suggestions}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " handleValidate={onValidate}\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 57 }
export namespace Cert { const enum TYPE { NONE = 0, X509 = 1, HOSTKEY_LIBSSH2 = 2, STRARRAY = 3 } const enum SSH { MD5 = 1, SHA1 = 2 } } export class Cert { certType: Cert.TYPE; }
types/nodegit/cert.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.0004911232390441, 0.0003305284189991653, 0.000169933628058061, 0.0003305284189991653, 0.00016059480549301952 ]
{ "id": 3, "code_window": [ " handleDelete={onDeleteTag}\n", " handleFocus={onFocus}\n", " handleInputChange={onInputChange}\n", " inputAttributes={inputAttributes}\n", " maxSuggestionsLength={10}\n", " minQueryLength={5}\n", " placeholder=\"\"\n", " suggestions={suggestions}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " handleValidate={onValidate}\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 57 }
{ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, "array-type": false, "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, "comment-format": false, "dt-header": false, "npm-naming": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-for-in-array": false, "no-inferrable-types": false, "no-internal-module": false, "no-irregular-whitespace": false, "no-mergeable-namespace": false, "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, "no-reference-import": false, "no-relative-import-in-test": false, "no-self-import": false, "no-single-declare-module": false, "no-string-throw": false, "no-unnecessary-callback-wrapper": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-useless-files": false, "no-var-keyword": false, "no-var-requires": false, "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, "only-arrow-functions": false, "prefer-conditional-expression": false, "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, "prefer-template": false, "radix": false, "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, "trim-file": false, "triple-equals": false, "typedef-whitespace": false, "unified-signatures": false, "void-return": false, "whitespace": false } }
types/mapbox-gl/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017189790378324687, 0.00017020267841871828, 0.00016768088971730322, 0.00017052511975634843, 0.0000011954539331782144 ]
{ "id": 3, "code_window": [ " handleDelete={onDeleteTag}\n", " handleFocus={onFocus}\n", " handleInputChange={onInputChange}\n", " inputAttributes={inputAttributes}\n", " maxSuggestionsLength={10}\n", " minQueryLength={5}\n", " placeholder=\"\"\n", " suggestions={suggestions}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " handleValidate={onValidate}\n" ], "file_path": "types/react-tag-autocomplete/react-tag-autocomplete-tests.tsx", "type": "add", "edit_start_line_idx": 57 }
{ "private": true, "dependencies": { "inversify": "^2.0.1" } }
types/inversify-devtools/package.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9df5095d72ce281a0bbd9cb33a36ba26ba2afaa6
[ 0.00017108063912019134, 0.00017108063912019134, 0.00017108063912019134, 0.00017108063912019134, 0 ]
{ "id": 0, "code_window": [ " hideScope?: boolean;\n", " hideTag?: boolean;\n", " hideValue?: boolean;\n", " query: string;\n", "}\n", "const SearchField = ({\n", " filter,\n", " datasource,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti?: boolean;\n", " allowCustomValue?: boolean;\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 35 }
import { css } from '@emotion/css'; import { uniq } from 'lodash'; import React, { useState, useEffect, useMemo } from 'react'; import useAsync from 'react-use/lib/useAsync'; import { SelectableValue } from '@grafana/data'; import { FetchError, getTemplateSrv, isFetchError } from '@grafana/runtime'; import { Select, HorizontalGroup, useStyles2 } from '@grafana/ui'; import { notifyApp } from '../_importedDependencies/actions/appNotification'; import { createErrorNotification } from '../_importedDependencies/core/appNotification'; import { dispatch } from '../_importedDependencies/store'; import { TraceqlFilter, TraceqlSearchScope } from '../dataquery.gen'; import { TempoDatasource } from '../datasource'; import { operators as allOperators, stringOperators, numberOperators, keywordOperators } from '../traceql/traceql'; import { filterScopedTag, operatorSelectableValue } from './utils'; const getStyles = () => ({ dropdown: css({ boxShadow: 'none', }), }); interface Props { filter: TraceqlFilter; datasource: TempoDatasource; updateFilter: (f: TraceqlFilter) => void; setError: (error: FetchError) => void; isTagsLoading?: boolean; tags: string[]; hideScope?: boolean; hideTag?: boolean; hideValue?: boolean; query: string; } const SearchField = ({ filter, datasource, updateFilter, isTagsLoading, tags, setError, hideScope, hideTag, hideValue, query, }: Props) => { const styles = useStyles2(getStyles); const scopedTag = useMemo(() => filterScopedTag(filter), [filter]); // We automatically change the operator to the regex op when users select 2 or more values // However, they expect this to be automatically rolled back to the previous operator once // there's only one value selected, so we store the previous operator and value const [prevOperator, setPrevOperator] = useState(filter.operator); const [prevValue, setPrevValue] = useState(filter.value); const updateOptions = async () => { try { return filter.tag ? await datasource.languageProvider.getOptionsV2(scopedTag, query) : []; } catch (error) { // Display message if Tempo is connected but search 404's if (isFetchError(error) && error?.status === 404) { setError(error); } else if (error instanceof Error) { dispatch(notifyApp(createErrorNotification('Error', error))); } } return []; }; const { loading: isLoadingValues, value: options } = useAsync(updateOptions, [ scopedTag, datasource.languageProvider, setError, query, ]); // Add selected option if it doesn't exist in the current list of options if (filter.value && !Array.isArray(filter.value) && options && !options.find((o) => o.value === filter.value)) { options.push({ label: filter.value.toString(), value: filter.value.toString(), type: filter.valueType }); } useEffect(() => { if ( Array.isArray(filter.value) && filter.value.length > 1 && filter.operator !== '=~' && filter.operator !== '!~' ) { setPrevOperator(filter.operator); updateFilter({ ...filter, operator: '=~' }); } if (Array.isArray(filter.value) && filter.value.length <= 1 && (prevValue?.length || 0) > 1) { updateFilter({ ...filter, operator: prevOperator, value: filter.value[0] }); } }, [prevValue, prevOperator, updateFilter, filter]); useEffect(() => { setPrevValue(filter.value); }, [filter.value]); const scopeOptions = Object.values(TraceqlSearchScope) .filter((s) => s !== TraceqlSearchScope.Intrinsic) .map((t) => ({ label: t, value: t })); // If all values have type string or int/float use a focused list of operators instead of all operators const optionsOfFirstType = options?.filter((o) => o.type === options[0]?.type); const uniqueOptionType = options?.length === optionsOfFirstType?.length ? options?.[0]?.type : undefined; let operatorList = allOperators; switch (uniqueOptionType) { case 'keyword': operatorList = keywordOperators; break; case 'string': operatorList = stringOperators; break; case 'int': case 'float': operatorList = numberOperators; } /** * Add to a list of options the current template variables. * * @param options a list of options * @returns the list of given options plus the template variables */ const withTemplateVariableOptions = (options: SelectableValue[] | undefined) => { const templateVariables = getTemplateSrv().getVariables(); return [...(options || []), ...templateVariables.map((v) => ({ label: `$${v.name}`, value: `$${v.name}` }))]; }; return ( <HorizontalGroup spacing={'none'} width={'auto'}> {!hideScope && ( <Select className={styles.dropdown} inputId={`${filter.id}-scope`} options={withTemplateVariableOptions(scopeOptions)} value={filter.scope} onChange={(v) => { updateFilter({ ...filter, scope: v?.value }); }} placeholder="Select scope" aria-label={`select ${filter.id} scope`} /> )} {!hideTag && ( <Select className={styles.dropdown} inputId={`${filter.id}-tag`} isLoading={isTagsLoading} // Add the current tag to the list if it doesn't exist in the tags prop, otherwise the field will be empty even though the state has a value options={withTemplateVariableOptions( (filter.tag !== undefined ? uniq([filter.tag, ...tags]) : tags).map((t) => ({ label: t, value: t, })) )} value={filter.tag} onChange={(v) => { updateFilter({ ...filter, tag: v?.value, value: [] }); }} placeholder="Select tag" isClearable aria-label={`select ${filter.id} tag`} allowCustomValue={true} /> )} <Select className={styles.dropdown} inputId={`${filter.id}-operator`} options={withTemplateVariableOptions(operatorList.map(operatorSelectableValue))} value={filter.operator} onChange={(v) => { updateFilter({ ...filter, operator: v?.value }); }} isClearable={false} aria-label={`select ${filter.id} operator`} allowCustomValue={true} width={8} /> {!hideValue && ( <Select className={styles.dropdown} inputId={`${filter.id}-value`} isLoading={isLoadingValues} options={withTemplateVariableOptions(options)} value={filter.value} onChange={(val) => { if (Array.isArray(val)) { updateFilter({ ...filter, value: val.map((v) => v.value), valueType: val[0]?.type || uniqueOptionType }); } else { updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType }); } }} placeholder="Select value" isClearable={false} aria-label={`select ${filter.id} value`} allowCustomValue={true} isMulti allowCreateWhileLoading /> )} </HorizontalGroup> ); }; export default SearchField;
public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx
1
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.9982576966285706, 0.29377710819244385, 0.0001683767040958628, 0.00039519372512586415, 0.44268178939819336 ]
{ "id": 0, "code_window": [ " hideScope?: boolean;\n", " hideTag?: boolean;\n", " hideValue?: boolean;\n", " query: string;\n", "}\n", "const SearchField = ({\n", " filter,\n", " datasource,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti?: boolean;\n", " allowCustomValue?: boolean;\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 35 }
package api import ( "context" "errors" "net/http" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/auth/identity" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/services/ngalert/notifier" ) type NotificationSrv struct { logger log.Logger receiverService ReceiverService muteTimingService MuteTimingService // defined in api_provisioning.go } type ReceiverService interface { GetReceiver(ctx context.Context, q models.GetReceiverQuery, u identity.Requester) (definitions.GettableApiReceiver, error) GetReceivers(ctx context.Context, q models.GetReceiversQuery, u identity.Requester) ([]definitions.GettableApiReceiver, error) } func (srv *NotificationSrv) RouteGetTimeInterval(c *contextmodel.ReqContext, name string) response.Response { muteTimeInterval, err := srv.muteTimingService.GetMuteTiming(c.Req.Context(), name, c.OrgID) if err != nil { return errorToResponse(err) } return response.JSON(http.StatusOK, muteTimeInterval) // TODO convert to timing interval } func (srv *NotificationSrv) RouteGetTimeIntervals(c *contextmodel.ReqContext) response.Response { muteTimeIntervals, err := srv.muteTimingService.GetMuteTimings(c.Req.Context(), c.OrgID) if err != nil { return errorToResponse(err) } return response.JSON(http.StatusOK, muteTimeIntervals) // TODO convert to timing interval } func (srv *NotificationSrv) RouteGetReceiver(c *contextmodel.ReqContext, name string) response.Response { q := models.GetReceiverQuery{ OrgID: c.SignedInUser.OrgID, Name: name, Decrypt: c.QueryBool("decrypt"), } receiver, err := srv.receiverService.GetReceiver(c.Req.Context(), q, c.SignedInUser) if err != nil { if errors.Is(err, notifier.ErrNotFound) { return ErrResp(http.StatusNotFound, err, "receiver not found") } if errors.Is(err, notifier.ErrPermissionDenied) { return ErrResp(http.StatusForbidden, err, "permission denied") } return ErrResp(http.StatusInternalServerError, err, "failed to get receiver") } return response.JSON(http.StatusOK, receiver) } func (srv *NotificationSrv) RouteGetReceivers(c *contextmodel.ReqContext) response.Response { q := models.GetReceiversQuery{ OrgID: c.SignedInUser.OrgID, Names: c.QueryStrings("names"), Limit: c.QueryInt("limit"), Offset: c.QueryInt("offset"), Decrypt: c.QueryBool("decrypt"), } receivers, err := srv.receiverService.GetReceivers(c.Req.Context(), q, c.SignedInUser) if err != nil { if errors.Is(err, notifier.ErrPermissionDenied) { return ErrResp(http.StatusForbidden, err, "permission denied") } return ErrResp(http.StatusInternalServerError, err, "failed to get receiver groups") } return response.JSON(http.StatusOK, receivers) }
pkg/services/ngalert/api/api_notifications.go
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0001739287981763482, 0.0001713858509901911, 0.00016940590285230428, 0.00017110542103182524, 0.0000016858575691003352 ]
{ "id": 0, "code_window": [ " hideScope?: boolean;\n", " hideTag?: boolean;\n", " hideValue?: boolean;\n", " query: string;\n", "}\n", "const SearchField = ({\n", " filter,\n", " datasource,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti?: boolean;\n", " allowCustomValue?: boolean;\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 35 }
# Changelog This is not a direct replacement of Grafana's "add to changelog" label. This is a manually managed document used by docs and PMs to know what to add to "What's New" documents. Adding a PR to a changelog item is recommended but not necessary as some changes require more than one PR. **Expected contributors: engineers once something noteworthy has been merged.** ## Scope Glossary ### `[CHANGED]` The CHANGED label is for features that has changed in a visible/impactful way, e.g. "[CHANGED] Time series visualization added in cloud rules editor. [#54950](https://github.com/grafana/grafana/pull/54950)" ### `[NEW]` The NEW label is for a new functionality or a change that is big enough to stand on its own feet. E.g. "[NEW] Provisioning now supports Terraform." ### `[DEPRECATED]` The DEPRECATED label is for a feature is planned for deprecation. We should ideally tell customers about those 1 or 2 versions before removing the feature. ### `[REMOVED]` Self explanatory. ## Next (9.3) ## 9.2 # Previous use of that CHANGELOG, will be removed soon ## Items that happened somewhere between 9.0 and 9.2 - [CHANGE] Rule API to reject request to update rules that affects provisioned rules #50835 - [FEATURE] Add first Grafana reserved label, grafana_folder is created during runtime and stores an alert's folder/namespace title #50262 - [FEATURE] use optimistic lock by version field when updating alert rules #50274 - [BUGFIX] State manager to use tick time to determine stale states #50991 - [ENHANCEMENT] Scheduler: Drop ticks if rule evaluation is too slow and adds a metric grafana_alerting_schedule_rule_evaluations_missed_total to track missed evaluations per rule #48885 - [ENHANCEMENT] Ticker to tick at predictable time #50197 - [ENHANCEMENT] Migration: Don't stop the migration when failing to parse alert rule tags #51253 - [ENHANCEMENT] Prevent evaluation if "for" shorter than "evaluate" #51797 ## 9.0.0 - [ENHANCEMENT] Scheduler: Ticker expose new metrics. In legacy, metrics are prefixed with `legacy_` #47828, #48190 - `grafana_alerting_ticker_last_consumed_tick_timestamp_seconds` - `grafana_alerting_ticker_next_tick_timestamp_seconds` - `grafana_alerting_ticker_interval_seconds` - [ENHANCEMENT] Create folder 'General Alerting' when Grafana starts from the scratch #48866 - [ENHANCEMENT] Rule changes authorization logic to use UID folder scope instead of ID scope #48970 - [ENHANCEMENT] Scheduler: ticker to support stopping #48142 - [ENHANCEMENT] Optional custom title and description for OpsGenie #50131 - [ENHANCEMENT] Scheduler: Adds new metrics to track rules that might be scheduled #49874 - `grafana_alerting_schedule_alert_rules ` - `grafana_alerting_schedule_alert_rules_hash ` - [CHANGE] Scheduler: Renaming of metrics to make them consistent with similar metrics exposed by the component #49874 - `grafana_alerting_get_alert_rules_duration_seconds` to `grafana_alerting_schedule_periodic_duration_seconds` - `grafana_alerting_schedule_periodic_duration_seconds` to `grafana_alerting_schedule_query_alert_rules_duration_seconds` - [FEATURE] Indicate whether routes are provisioned when GETting Alertmanager configuration #47857 - [FEATURE] Indicate whether contact point is provisioned when GETting Alertmanager configuration #48323 - [FEATURE] Indicate whether alert rule is provisioned when GETting the rule #48458 - [FEATURE] Alert rules with associated panels will take screenshots. #49293 #49338 #49374 #49377 #49378 #49379 #49381 #49385 #49439 #49445 - [FEATURE] Persistent order of alert rules in a group #50051 - [BUGFIX] Migration: ignore alerts that do not belong to any existing organization\dashboard #49192 - [BUGFIX] Allow anonymous access to alerts #49203 - [BUGFIX] RBAC: replace create\update\delete actions for notification policies by alert.notifications:write #49185 - [BUGFIX] Fix access to alerts for Viewer role with editor permissions in folder #49270 - [BUGFIX] Alerting: Remove double quotes from double quoted matchers #50038 - [BUGFIX] Alerting: rules API to not detect difference between nil and empty map (Annotations, Labels) #50192 ## 8.5.3 - [BUGFIX] Migration: Remove data source disabled property when migrating alerts #48559 ## 8.5.2 - [FEATURE] Migration: Adds `force_migration` as a flag to prevent truncating the unified alerting tables as we migrate. #48526 - [BUGFIX] Use `NaN` and do not panic when captured alert values are empty #48370 ## 8.5.1 - [BUGFIX] Silences: Invalid silences created through the API made grafana panic, they are now validated. #46892 - [ENHANCEMENT] Migration: Migrate each legacy notification channel to its own contact point, use nested routes to reproduce multi-channel alerts #47291 ## 8.5.0 - [CHANGE] Prometheus Compatible API: Use float-like values for `api/prometheus/grafana/api/v1/alerts` and `api/prometheus/grafana/api/v1/rules` instead of the evaluation string #47216 - [CHANGE] Notification URL points to alert view page instead of alert edit page. #47752 - [BUGFIX] (Legacy) Templates: Parse notification templates using all the matches of the alert rule when going from `Alerting` to `OK` in legacy alerting #47355 - [BUGFIX] Scheduler: Fix state manager to support OK option of `AlertRule.ExecErrState` #47670 - [ENHANCEMENT] Templates: Enable the use of classic condition values in templates #46971
pkg/services/ngalert/CHANGELOG.md
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0001752444077283144, 0.00016809310181997716, 0.00016294493980240077, 0.0001678323169471696, 0.000003612747377701453 ]
{ "id": 0, "code_window": [ " hideScope?: boolean;\n", " hideTag?: boolean;\n", " hideValue?: boolean;\n", " query: string;\n", "}\n", "const SearchField = ({\n", " filter,\n", " datasource,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti?: boolean;\n", " allowCustomValue?: boolean;\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 35 }
/** * Type representing a tag in a trace span or fields of a log. */ export type TraceKeyValuePair<T = any> = { key: string; value: T; }; /** * Type representing a log in a span. */ export type TraceLog = { // Millisecond epoch time timestamp: number; fields: TraceKeyValuePair[]; }; export type TraceSpanReference = { traceID: string; spanID: string; tags?: TraceKeyValuePair[]; }; /** * This describes the structure of the dataframe that should be returned from a tracing data source to show trace * in a TraceView component. */ export interface TraceSpanRow { traceID: string; spanID: string; parentSpanID: string | undefined; operationName: string; serviceName: string; serviceTags: TraceKeyValuePair[]; // Millisecond epoch time startTime: number; // Milliseconds duration: number; logs?: TraceLog[]; references?: TraceSpanReference[]; // Note: To mark spen as having error add tag error: true tags?: TraceKeyValuePair[]; kind?: string; statusCode?: number; statusMessage?: string; instrumentationLibraryName?: string; instrumentationLibraryVersion?: string; traceState?: string; warnings?: string[]; stackTraces?: string[]; // Specify custom color of the error icon errorIconColor?: string; }
packages/grafana-data/src/types/trace.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00032538617961108685, 0.00020397327898535877, 0.0001685996976448223, 0.00017043869593180716, 0.00005722996502299793 ]
{ "id": 1, "code_window": [ " hideScope,\n", " hideTag,\n", " hideValue,\n", " query,\n", "}: Props) => {\n", " const styles = useStyles2(getStyles);\n", " const scopedTag = useMemo(() => filterScopedTag(filter), [filter]);\n", " // We automatically change the operator to the regex op when users select 2 or more values\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti = true,\n", " allowCustomValue = true,\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 47 }
import { css } from '@emotion/css'; import { uniq } from 'lodash'; import React, { useState, useEffect, useMemo } from 'react'; import useAsync from 'react-use/lib/useAsync'; import { SelectableValue } from '@grafana/data'; import { FetchError, getTemplateSrv, isFetchError } from '@grafana/runtime'; import { Select, HorizontalGroup, useStyles2 } from '@grafana/ui'; import { notifyApp } from '../_importedDependencies/actions/appNotification'; import { createErrorNotification } from '../_importedDependencies/core/appNotification'; import { dispatch } from '../_importedDependencies/store'; import { TraceqlFilter, TraceqlSearchScope } from '../dataquery.gen'; import { TempoDatasource } from '../datasource'; import { operators as allOperators, stringOperators, numberOperators, keywordOperators } from '../traceql/traceql'; import { filterScopedTag, operatorSelectableValue } from './utils'; const getStyles = () => ({ dropdown: css({ boxShadow: 'none', }), }); interface Props { filter: TraceqlFilter; datasource: TempoDatasource; updateFilter: (f: TraceqlFilter) => void; setError: (error: FetchError) => void; isTagsLoading?: boolean; tags: string[]; hideScope?: boolean; hideTag?: boolean; hideValue?: boolean; query: string; } const SearchField = ({ filter, datasource, updateFilter, isTagsLoading, tags, setError, hideScope, hideTag, hideValue, query, }: Props) => { const styles = useStyles2(getStyles); const scopedTag = useMemo(() => filterScopedTag(filter), [filter]); // We automatically change the operator to the regex op when users select 2 or more values // However, they expect this to be automatically rolled back to the previous operator once // there's only one value selected, so we store the previous operator and value const [prevOperator, setPrevOperator] = useState(filter.operator); const [prevValue, setPrevValue] = useState(filter.value); const updateOptions = async () => { try { return filter.tag ? await datasource.languageProvider.getOptionsV2(scopedTag, query) : []; } catch (error) { // Display message if Tempo is connected but search 404's if (isFetchError(error) && error?.status === 404) { setError(error); } else if (error instanceof Error) { dispatch(notifyApp(createErrorNotification('Error', error))); } } return []; }; const { loading: isLoadingValues, value: options } = useAsync(updateOptions, [ scopedTag, datasource.languageProvider, setError, query, ]); // Add selected option if it doesn't exist in the current list of options if (filter.value && !Array.isArray(filter.value) && options && !options.find((o) => o.value === filter.value)) { options.push({ label: filter.value.toString(), value: filter.value.toString(), type: filter.valueType }); } useEffect(() => { if ( Array.isArray(filter.value) && filter.value.length > 1 && filter.operator !== '=~' && filter.operator !== '!~' ) { setPrevOperator(filter.operator); updateFilter({ ...filter, operator: '=~' }); } if (Array.isArray(filter.value) && filter.value.length <= 1 && (prevValue?.length || 0) > 1) { updateFilter({ ...filter, operator: prevOperator, value: filter.value[0] }); } }, [prevValue, prevOperator, updateFilter, filter]); useEffect(() => { setPrevValue(filter.value); }, [filter.value]); const scopeOptions = Object.values(TraceqlSearchScope) .filter((s) => s !== TraceqlSearchScope.Intrinsic) .map((t) => ({ label: t, value: t })); // If all values have type string or int/float use a focused list of operators instead of all operators const optionsOfFirstType = options?.filter((o) => o.type === options[0]?.type); const uniqueOptionType = options?.length === optionsOfFirstType?.length ? options?.[0]?.type : undefined; let operatorList = allOperators; switch (uniqueOptionType) { case 'keyword': operatorList = keywordOperators; break; case 'string': operatorList = stringOperators; break; case 'int': case 'float': operatorList = numberOperators; } /** * Add to a list of options the current template variables. * * @param options a list of options * @returns the list of given options plus the template variables */ const withTemplateVariableOptions = (options: SelectableValue[] | undefined) => { const templateVariables = getTemplateSrv().getVariables(); return [...(options || []), ...templateVariables.map((v) => ({ label: `$${v.name}`, value: `$${v.name}` }))]; }; return ( <HorizontalGroup spacing={'none'} width={'auto'}> {!hideScope && ( <Select className={styles.dropdown} inputId={`${filter.id}-scope`} options={withTemplateVariableOptions(scopeOptions)} value={filter.scope} onChange={(v) => { updateFilter({ ...filter, scope: v?.value }); }} placeholder="Select scope" aria-label={`select ${filter.id} scope`} /> )} {!hideTag && ( <Select className={styles.dropdown} inputId={`${filter.id}-tag`} isLoading={isTagsLoading} // Add the current tag to the list if it doesn't exist in the tags prop, otherwise the field will be empty even though the state has a value options={withTemplateVariableOptions( (filter.tag !== undefined ? uniq([filter.tag, ...tags]) : tags).map((t) => ({ label: t, value: t, })) )} value={filter.tag} onChange={(v) => { updateFilter({ ...filter, tag: v?.value, value: [] }); }} placeholder="Select tag" isClearable aria-label={`select ${filter.id} tag`} allowCustomValue={true} /> )} <Select className={styles.dropdown} inputId={`${filter.id}-operator`} options={withTemplateVariableOptions(operatorList.map(operatorSelectableValue))} value={filter.operator} onChange={(v) => { updateFilter({ ...filter, operator: v?.value }); }} isClearable={false} aria-label={`select ${filter.id} operator`} allowCustomValue={true} width={8} /> {!hideValue && ( <Select className={styles.dropdown} inputId={`${filter.id}-value`} isLoading={isLoadingValues} options={withTemplateVariableOptions(options)} value={filter.value} onChange={(val) => { if (Array.isArray(val)) { updateFilter({ ...filter, value: val.map((v) => v.value), valueType: val[0]?.type || uniqueOptionType }); } else { updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType }); } }} placeholder="Select value" isClearable={false} aria-label={`select ${filter.id} value`} allowCustomValue={true} isMulti allowCreateWhileLoading /> )} </HorizontalGroup> ); }; export default SearchField;
public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx
1
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.9990882873535156, 0.33299773931503296, 0.00017341561033390462, 0.0014916068175807595, 0.4696263372898102 ]
{ "id": 1, "code_window": [ " hideScope,\n", " hideTag,\n", " hideValue,\n", " query,\n", "}: Props) => {\n", " const styles = useStyles2(getStyles);\n", " const scopedTag = useMemo(() => filterScopedTag(filter), [filter]);\n", " // We automatically change the operator to the regex op when users select 2 or more values\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti = true,\n", " allowCustomValue = true,\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 47 }
import { AsyncThunk, createAsyncThunk } from '@reduxjs/toolkit'; import { isEmpty } from 'lodash'; import { locationService } from '@grafana/runtime'; import { AlertmanagerAlert, AlertManagerCortexConfig, AlertmanagerGroup, ExternalAlertmanagerConfig, ExternalAlertmanagersResponse, Matcher, Receiver, Silence, SilenceCreatePayload, TestReceiversAlert, } from 'app/plugins/datasource/alertmanager/types'; import { FolderDTO, NotifierDTO, StoreState, ThunkResult } from 'app/types'; import { CombinedRuleGroup, CombinedRuleNamespace, PromBasedDataSource, RuleIdentifier, RuleNamespace, RulerDataSourceConfig, RuleWithLocation, StateHistoryItem, } from 'app/types/unified-alerting'; import { PostableRulerRuleGroupDTO, PromApplication, RulerRuleDTO, RulerRulesConfigDTO, } from 'app/types/unified-alerting-dto'; import { backendSrv } from '../../../../core/services/backend_srv'; import { logInfo, LogMessages, withPerformanceLogging, withPromRulesMetadataLogging, withRulerRulesMetadataLogging, } from '../Analytics'; import { addAlertManagers, createOrUpdateSilence, deleteAlertManagerConfig, expireSilence, fetchAlertGroups, fetchAlerts, fetchExternalAlertmanagerConfig, fetchExternalAlertmanagers, fetchSilences, testReceivers, updateAlertManagerConfig, } from '../api/alertmanager'; import { alertmanagerApi } from '../api/alertmanagerApi'; import { fetchAnnotations } from '../api/annotations'; import { discoverFeatures } from '../api/buildInfo'; import { fetchNotifiers } from '../api/grafana'; import { FetchPromRulesFilter, fetchRules } from '../api/prometheus'; import { deleteNamespace, deleteRulerRulesGroup, fetchRulerRules, FetchRulerRulesFilter, setRulerRuleGroup, } from '../api/ruler'; import { RuleFormType, RuleFormValues } from '../types/rule-form'; import { addDefaultsToAlertmanagerConfig, removeMuteTimingFromRoute } from '../utils/alertmanager'; import { getAllRulesSourceNames, getRulesDataSource, getRulesSourceName, GRAFANA_RULES_SOURCE_NAME, } from '../utils/datasource'; import { makeAMLink } from '../utils/misc'; import { AsyncRequestMapSlice, withAppEvents, withSerializedError } from '../utils/redux'; import * as ruleId from '../utils/rule-id'; import { getRulerClient } from '../utils/rulerClient'; import { getAlertInfo, isRulerNotSupportedResponse } from '../utils/rules'; import { safeParseDurationstr } from '../utils/time'; function getDataSourceConfig(getState: () => unknown, rulesSourceName: string) { const dataSources = (getState() as StoreState).unifiedAlerting.dataSources; const dsConfig = dataSources[rulesSourceName]?.result; if (!dsConfig) { throw new Error(`Data source configuration is not available for "${rulesSourceName}" data source`); } return dsConfig; } function getDataSourceRulerConfig(getState: () => unknown, rulesSourceName: string) { const dsConfig = getDataSourceConfig(getState, rulesSourceName); if (!dsConfig.rulerConfig) { throw new Error(`Ruler API is not available for ${rulesSourceName}`); } return dsConfig.rulerConfig; } export const fetchPromRulesAction = createAsyncThunk( 'unifiedalerting/fetchPromRules', async ( { rulesSourceName, filter, limitAlerts, matcher, state, identifier, }: { rulesSourceName: string; filter?: FetchPromRulesFilter; limitAlerts?: number; matcher?: Matcher[]; state?: string[]; identifier?: RuleIdentifier; }, thunkAPI ): Promise<RuleNamespace[]> => { await thunkAPI.dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName })); const fetchRulesWithLogging = withPromRulesMetadataLogging( fetchRules, `[${rulesSourceName}] Prometheus rules loaded`, { dataSourceName: rulesSourceName, thunk: 'unifiedalerting/fetchPromRules' } ); return await withSerializedError( fetchRulesWithLogging(rulesSourceName, filter, limitAlerts, matcher, state, identifier) ); } ); export const fetchExternalAlertmanagersAction = createAsyncThunk( 'unifiedAlerting/fetchExternalAlertmanagers', (): Promise<ExternalAlertmanagersResponse> => { return withSerializedError(fetchExternalAlertmanagers()); } ); export const fetchExternalAlertmanagersConfigAction = createAsyncThunk( 'unifiedAlerting/fetchExternAlertmanagersConfig', (): Promise<ExternalAlertmanagerConfig> => { return withSerializedError(fetchExternalAlertmanagerConfig()); } ); export const fetchRulerRulesAction = createAsyncThunk( 'unifiedalerting/fetchRulerRules', async ( { rulesSourceName, filter, }: { rulesSourceName: string; filter?: FetchRulerRulesFilter; }, { dispatch, getState } ): Promise<RulerRulesConfigDTO | null> => { await dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName })); const rulerConfig = getDataSourceRulerConfig(getState, rulesSourceName); const fetchRulerRulesWithLogging = withRulerRulesMetadataLogging( fetchRulerRules, `[${rulesSourceName}] Ruler rules loaded`, { dataSourceName: rulesSourceName, thunk: 'unifiedalerting/fetchRulerRules', } ); return await withSerializedError(fetchRulerRulesWithLogging(rulerConfig, filter)); } ); export function fetchPromAndRulerRulesAction({ rulesSourceName, identifier, filter, limitAlerts, matcher, state, }: { rulesSourceName: string; identifier?: RuleIdentifier; filter?: FetchPromRulesFilter; limitAlerts?: number; matcher?: Matcher[]; state?: string[]; }): ThunkResult<Promise<void>> { return async (dispatch, getState) => { await dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName })); const dsConfig = getDataSourceConfig(getState, rulesSourceName); await dispatch(fetchPromRulesAction({ rulesSourceName, identifier, filter, limitAlerts, matcher, state })); if (dsConfig.rulerConfig) { await dispatch(fetchRulerRulesAction({ rulesSourceName })); } }; } export const fetchSilencesAction = createAsyncThunk( 'unifiedalerting/fetchSilences', (alertManagerSourceName: string): Promise<Silence[]> => { const fetchSilencesWithLogging = withPerformanceLogging( fetchSilences, `[${alertManagerSourceName}] Silences loaded`, { dataSourceName: alertManagerSourceName, thunk: 'unifiedalerting/fetchSilences', } ); return withSerializedError(fetchSilencesWithLogging(alertManagerSourceName)); } ); // this will only trigger ruler rules fetch if rules are not loaded yet and request is not in flight export function fetchRulerRulesIfNotFetchedYet(rulesSourceName: string): ThunkResult<void> { return (dispatch, getStore) => { const { rulerRules } = getStore().unifiedAlerting; const resp = rulerRules[rulesSourceName]; const emptyResults = isEmpty(resp?.result); if (emptyResults && !(resp && isRulerNotSupportedResponse(resp)) && !resp?.loading) { dispatch(fetchRulerRulesAction({ rulesSourceName })); } }; } // TODO: memoize this or move to RTK Query so we can cache results! export function fetchAllPromBuildInfoAction(): ThunkResult<Promise<void>> { return async (dispatch) => { const allRequests = getAllRulesSourceNames().map((rulesSourceName) => dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName })) ); await Promise.allSettled(allRequests); }; } export const fetchRulesSourceBuildInfoAction = createAsyncThunk( 'unifiedalerting/fetchPromBuildinfo', async ({ rulesSourceName }: { rulesSourceName: string }): Promise<PromBasedDataSource> => { return withSerializedError<PromBasedDataSource>( (async (): Promise<PromBasedDataSource> => { if (rulesSourceName === GRAFANA_RULES_SOURCE_NAME) { return { name: GRAFANA_RULES_SOURCE_NAME, id: GRAFANA_RULES_SOURCE_NAME, rulerConfig: { dataSourceName: GRAFANA_RULES_SOURCE_NAME, apiVersion: 'legacy', }, }; } const ds = getRulesDataSource(rulesSourceName); if (!ds) { throw new Error(`Missing data source configuration for ${rulesSourceName}`); } const { id, name } = ds; const discoverFeaturesWithLogging = withPerformanceLogging( discoverFeatures, `[${rulesSourceName}] Rules source features discovered`, { dataSourceName: rulesSourceName, thunk: 'unifiedalerting/fetchPromBuildinfo', } ); const buildInfo = await discoverFeaturesWithLogging(name); const rulerConfig: RulerDataSourceConfig | undefined = buildInfo.features.rulerApiEnabled ? { dataSourceName: name, apiVersion: buildInfo.application === PromApplication.Cortex ? 'legacy' : 'config', } : undefined; return { name: name, id: id, rulerConfig, }; })() ); }, { condition: ({ rulesSourceName }, { getState }) => { const dataSources: AsyncRequestMapSlice<PromBasedDataSource> = (getState() as StoreState).unifiedAlerting .dataSources; const hasLoaded = Boolean(dataSources[rulesSourceName]?.result); const hasError = Boolean(dataSources[rulesSourceName]?.error); return !(hasLoaded || hasError); }, } ); interface FetchPromRulesRulesActionProps { filter?: FetchPromRulesFilter; limitAlerts?: number; matcher?: Matcher[]; state?: string[]; } export function fetchAllPromAndRulerRulesAction( force = false, options: FetchPromRulesRulesActionProps = {} ): ThunkResult<Promise<void>> { return async (dispatch, getStore) => { const allStartLoadingTs = performance.now(); await Promise.allSettled( getAllRulesSourceNames().map(async (rulesSourceName) => { await dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName })); const { promRules, rulerRules, dataSources } = getStore().unifiedAlerting; const dataSourceConfig = dataSources[rulesSourceName].result; if (!dataSourceConfig) { return; } const shouldLoadProm = force || !promRules[rulesSourceName]?.loading; const shouldLoadRuler = (force || !rulerRules[rulesSourceName]?.loading) && Boolean(dataSourceConfig.rulerConfig); await Promise.allSettled([ shouldLoadProm && dispatch(fetchPromRulesAction({ rulesSourceName, ...options })), shouldLoadRuler && dispatch(fetchRulerRulesAction({ rulesSourceName })), ]); }) ); logInfo('All Prom and Ruler rules loaded', { loadTimeMs: (performance.now() - allStartLoadingTs).toFixed(0), }); }; } export function fetchAllPromRulesAction(force = false): ThunkResult<void> { return async (dispatch, getStore) => { const { promRules } = getStore().unifiedAlerting; getAllRulesSourceNames().map((rulesSourceName) => { if (force || !promRules[rulesSourceName]?.loading) { dispatch(fetchPromRulesAction({ rulesSourceName })); } }); }; } export const fetchEditableRuleAction = createAsyncThunk( 'unifiedalerting/fetchEditableRule', (ruleIdentifier: RuleIdentifier, thunkAPI): Promise<RuleWithLocation | null> => { const rulerConfig = getDataSourceRulerConfig(thunkAPI.getState, ruleIdentifier.ruleSourceName); return withSerializedError(getRulerClient(rulerConfig).findEditableRule(ruleIdentifier)); } ); export function deleteRulesGroupAction( namespace: CombinedRuleNamespace, ruleGroup: CombinedRuleGroup ): ThunkResult<void> { return async (dispatch, getState) => { withAppEvents( (async () => { const sourceName = getRulesSourceName(namespace.rulesSource); const rulerConfig = getDataSourceRulerConfig(getState, sourceName); await deleteRulerRulesGroup(rulerConfig, namespace.name, ruleGroup.name); await dispatch(fetchPromAndRulerRulesAction({ rulesSourceName: sourceName })); })(), { successMessage: 'Group deleted' } ); }; } export function deleteRuleAction( ruleIdentifier: RuleIdentifier, options: { navigateTo?: string } = {} ): ThunkResult<void> { /* * fetch the rules group from backend, delete group if it is found and+ * reload ruler rules */ return async (dispatch, getState) => { await dispatch(fetchRulesSourceBuildInfoAction({ rulesSourceName: ruleIdentifier.ruleSourceName })); withAppEvents( (async () => { const rulerConfig = getDataSourceRulerConfig(getState, ruleIdentifier.ruleSourceName); const rulerClient = getRulerClient(rulerConfig); const ruleWithLocation = await rulerClient.findEditableRule(ruleIdentifier); if (!ruleWithLocation) { throw new Error('Rule not found.'); } await rulerClient.deleteRule(ruleWithLocation); // refetch rules for this rules source await dispatch(fetchPromAndRulerRulesAction({ rulesSourceName: ruleWithLocation.ruleSourceName })); if (options.navigateTo) { locationService.replace(options.navigateTo); } })(), { successMessage: 'Rule deleted.', } ); }; } export const saveRuleFormAction = createAsyncThunk( 'unifiedalerting/saveRuleForm', ( { values, existing, redirectOnSave, evaluateEvery, }: { values: RuleFormValues; existing?: RuleWithLocation; redirectOnSave?: string; initialAlertRuleName?: string; evaluateEvery: string; }, thunkAPI ): Promise<void> => withAppEvents( withSerializedError( (async () => { const { type } = values; // TODO getRulerConfig should be smart enough to provide proper rulerClient implementation // For the dataSourceName specified // in case of system (cortex/loki) let identifier: RuleIdentifier; if (type === RuleFormType.cloudAlerting || type === RuleFormType.cloudRecording) { if (!values.dataSourceName) { throw new Error('The Data source has not been defined.'); } const rulerConfig = getDataSourceRulerConfig(thunkAPI.getState, values.dataSourceName); const rulerClient = getRulerClient(rulerConfig); identifier = await rulerClient.saveLotexRule(values, evaluateEvery, existing); await thunkAPI.dispatch(fetchRulerRulesAction({ rulesSourceName: values.dataSourceName })); // in case of grafana managed } else if (type === RuleFormType.grafana) { const rulerConfig = getDataSourceRulerConfig(thunkAPI.getState, GRAFANA_RULES_SOURCE_NAME); const rulerClient = getRulerClient(rulerConfig); identifier = await rulerClient.saveGrafanaRule(values, evaluateEvery, existing); await thunkAPI.dispatch(fetchRulerRulesAction({ rulesSourceName: GRAFANA_RULES_SOURCE_NAME })); } else { throw new Error('Unexpected rule form type'); } logInfo(LogMessages.successSavingAlertRule, { type, isNew: (!existing).toString() }); if (redirectOnSave) { locationService.push(redirectOnSave); } else { // if the identifier comes up empty (this happens when Grafana managed rule moves to another namespace or group) const stringifiedIdentifier = ruleId.stringifyIdentifier(identifier); if (!stringifiedIdentifier) { locationService.push('/alerting/list'); return; } // redirect to edit page const newLocation = `/alerting/${encodeURIComponent(stringifiedIdentifier)}/edit`; if (locationService.getLocation().pathname !== newLocation) { locationService.replace(newLocation); } else { // refresh the details of the current editable rule after saving thunkAPI.dispatch(fetchEditableRuleAction(identifier)); } } })() ), { successMessage: existing ? `Rule "${values.name}" updated.` : `Rule "${values.name}" saved.`, errorMessage: 'Failed to save rule', } ) ); export const fetchGrafanaNotifiersAction = createAsyncThunk( 'unifiedalerting/fetchGrafanaNotifiers', (): Promise<NotifierDTO[]> => withSerializedError(fetchNotifiers()) ); export const fetchGrafanaAnnotationsAction = createAsyncThunk( 'unifiedalerting/fetchGrafanaAnnotations', (alertId: string): Promise<StateHistoryItem[]> => withSerializedError(fetchAnnotations(alertId)) ); interface UpdateAlertManagerConfigActionOptions { alertManagerSourceName: string; oldConfig: AlertManagerCortexConfig; // it will be checked to make sure it didn't change in the meanwhile newConfig: AlertManagerCortexConfig; successMessage?: string; // show toast on success redirectPath?: string; // where to redirect on success redirectSearch?: string; // additional redirect query params } export const updateAlertManagerConfigAction = createAsyncThunk<void, UpdateAlertManagerConfigActionOptions, {}>( 'unifiedalerting/updateAMConfig', ( { alertManagerSourceName, oldConfig, newConfig, successMessage, redirectPath, redirectSearch }, thunkAPI ): Promise<void> => withAppEvents( withSerializedError( (async () => { const latestConfig = await thunkAPI .dispatch(alertmanagerApi.endpoints.getAlertmanagerConfiguration.initiate(alertManagerSourceName)) .unwrap(); const isLatestConfigEmpty = isEmpty(latestConfig.alertmanager_config) && isEmpty(latestConfig.template_files); const oldLastConfigsDiffer = JSON.stringify(latestConfig) !== JSON.stringify(oldConfig); if (!isLatestConfigEmpty && oldLastConfigsDiffer) { throw new Error( 'A newer Alertmanager configuration is available. Please reload the page and try again to not overwrite recent changes.' ); } await updateAlertManagerConfig(alertManagerSourceName, addDefaultsToAlertmanagerConfig(newConfig)); thunkAPI.dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration'])); if (redirectPath) { const options = new URLSearchParams(redirectSearch ?? ''); locationService.push(makeAMLink(redirectPath, alertManagerSourceName, options)); } })() ), { successMessage, } ) ); export const fetchAmAlertsAction = createAsyncThunk( 'unifiedalerting/fetchAmAlerts', (alertManagerSourceName: string): Promise<AlertmanagerAlert[]> => withSerializedError(fetchAlerts(alertManagerSourceName, [], true, true, true)) ); export const expireSilenceAction = (alertManagerSourceName: string, silenceId: string): ThunkResult<void> => { return async (dispatch) => { await withAppEvents(expireSilence(alertManagerSourceName, silenceId), { successMessage: 'Silence expired.', }); dispatch(fetchSilencesAction(alertManagerSourceName)); dispatch(fetchAmAlertsAction(alertManagerSourceName)); }; }; type UpdateSilenceActionOptions = { alertManagerSourceName: string; payload: SilenceCreatePayload; exitOnSave: boolean; successMessage?: string; }; export const createOrUpdateSilenceAction = createAsyncThunk<void, UpdateSilenceActionOptions, {}>( 'unifiedalerting/updateSilence', ({ alertManagerSourceName, payload, exitOnSave, successMessage }): Promise<void> => withAppEvents( withSerializedError( (async () => { await createOrUpdateSilence(alertManagerSourceName, payload); if (exitOnSave) { locationService.push(makeAMLink('/alerting/silences', alertManagerSourceName)); } })() ), { successMessage, } ) ); export const deleteReceiverAction = (receiverName: string, alertManagerSourceName: string): ThunkResult<void> => { return async (dispatch) => { const config = await dispatch( alertmanagerApi.endpoints.getAlertmanagerConfiguration.initiate(alertManagerSourceName) ).unwrap(); if (!config) { throw new Error(`Config for ${alertManagerSourceName} not found`); } if (!config.alertmanager_config.receivers?.find((receiver) => receiver.name === receiverName)) { throw new Error(`Cannot delete receiver ${receiverName}: not found in config.`); } const newConfig: AlertManagerCortexConfig = { ...config, alertmanager_config: { ...config.alertmanager_config, receivers: config.alertmanager_config.receivers.filter((receiver) => receiver.name !== receiverName), }, }; return dispatch( updateAlertManagerConfigAction({ newConfig, oldConfig: config, alertManagerSourceName, successMessage: 'Contact point deleted.', }) ); }; }; export const deleteTemplateAction = (templateName: string, alertManagerSourceName: string): ThunkResult<void> => { return async (dispatch) => { const config = await dispatch( alertmanagerApi.endpoints.getAlertmanagerConfiguration.initiate(alertManagerSourceName) ).unwrap(); if (!config) { throw new Error(`Config for ${alertManagerSourceName} not found`); } if (typeof config.template_files?.[templateName] !== 'string') { throw new Error(`Cannot delete template ${templateName}: not found in config.`); } const newTemplates = { ...config.template_files }; delete newTemplates[templateName]; const newConfig: AlertManagerCortexConfig = { ...config, alertmanager_config: { ...config.alertmanager_config, templates: config.alertmanager_config.templates?.filter((existing) => existing !== templateName), }, template_files: newTemplates, }; return dispatch( updateAlertManagerConfigAction({ newConfig, oldConfig: config, alertManagerSourceName, successMessage: 'Template deleted.', }) ); }; }; export const fetchFolderAction = createAsyncThunk( 'unifiedalerting/fetchFolder', (uid: string): Promise<FolderDTO> => withSerializedError(backendSrv.getFolderByUid(uid, { withAccessControl: true })) ); export const fetchFolderIfNotFetchedAction = (uid: string): ThunkResult<void> => { return (dispatch, getState) => { if (!getState().unifiedAlerting.folders[uid]?.dispatched) { dispatch(fetchFolderAction(uid)); } }; }; export const fetchAlertGroupsAction = createAsyncThunk( 'unifiedalerting/fetchAlertGroups', (alertManagerSourceName: string): Promise<AlertmanagerGroup[]> => { return withSerializedError(fetchAlertGroups(alertManagerSourceName)); } ); export const deleteAlertManagerConfigAction = createAsyncThunk( 'unifiedalerting/deleteAlertManagerConfig', async (alertManagerSourceName: string, thunkAPI): Promise<void> => { return withAppEvents( withSerializedError( (async () => { await deleteAlertManagerConfig(alertManagerSourceName); await thunkAPI.dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration'])); })() ), { errorMessage: 'Failed to reset Alertmanager configuration', successMessage: 'Alertmanager configuration reset.', } ); } ); export const deleteMuteTimingAction = (alertManagerSourceName: string, muteTimingName: string): ThunkResult<void> => { return async (dispatch) => { const config = await dispatch( alertmanagerApi.endpoints.getAlertmanagerConfiguration.initiate(alertManagerSourceName) ).unwrap(); const muteIntervals = config?.alertmanager_config?.mute_time_intervals?.filter(({ name }) => name !== muteTimingName) ?? []; if (config) { withAppEvents( dispatch( updateAlertManagerConfigAction({ alertManagerSourceName, oldConfig: config, newConfig: { ...config, alertmanager_config: { ...config.alertmanager_config, route: config.alertmanager_config.route ? removeMuteTimingFromRoute(muteTimingName, config.alertmanager_config?.route) : undefined, mute_time_intervals: muteIntervals, }, }, }) ), { successMessage: `Deleted "${muteTimingName}" from Alertmanager configuration`, errorMessage: 'Failed to delete mute timing', } ); } }; }; interface TestReceiversOptions { alertManagerSourceName: string; receivers: Receiver[]; alert?: TestReceiversAlert; } export const testReceiversAction = createAsyncThunk( 'unifiedalerting/testReceivers', ({ alertManagerSourceName, receivers, alert }: TestReceiversOptions): Promise<void> => { return withAppEvents(withSerializedError(testReceivers(alertManagerSourceName, receivers, alert)), { errorMessage: 'Failed to send test alert.', successMessage: 'Test alert sent.', }); } ); interface UpdateNamespaceAndGroupOptions { rulesSourceName: string; namespaceName: string; groupName: string; newNamespaceName: string; newGroupName: string; groupInterval?: string; folderUid?: string; } export const rulesInSameGroupHaveInvalidFor = (rules: RulerRuleDTO[], everyDuration: string) => { return rules.filter((rule: RulerRuleDTO) => { const { forDuration } = getAlertInfo(rule, everyDuration); const forNumber = safeParseDurationstr(forDuration); const everyNumber = safeParseDurationstr(everyDuration); return forNumber !== 0 && forNumber < everyNumber; }); }; // allows renaming namespace, renaming group and changing group interval, all in one go export const updateLotexNamespaceAndGroupAction: AsyncThunk< void, UpdateNamespaceAndGroupOptions, { state: StoreState } > = createAsyncThunk<void, UpdateNamespaceAndGroupOptions, { state: StoreState }>( 'unifiedalerting/updateLotexNamespaceAndGroup', async (options: UpdateNamespaceAndGroupOptions, thunkAPI): Promise<void> => { return withAppEvents( withSerializedError( (async () => { const { rulesSourceName, namespaceName, groupName, newNamespaceName, newGroupName, groupInterval, folderUid, } = options; const rulerConfig = getDataSourceRulerConfig(thunkAPI.getState, rulesSourceName); // fetch rules and perform sanity checks const rulesResult = await fetchRulerRules(rulerConfig); const existingNamespace = Boolean(rulesResult[namespaceName]); if (!existingNamespace) { throw new Error(`Namespace "${namespaceName}" not found.`); } const existingGroup = rulesResult[namespaceName].find((group) => group.name === groupName); if (!existingGroup) { throw new Error(`Group "${groupName}" not found.`); } const newGroupAlreadyExists = Boolean( rulesResult[namespaceName].find((group) => group.name === newGroupName) ); if (newGroupName !== groupName && newGroupAlreadyExists) { throw new Error(`Group "${newGroupName}" already exists in namespace "${namespaceName}".`); } const newNamespaceAlreadyExists = Boolean(rulesResult[newNamespaceName]); if (newNamespaceName !== namespaceName && newNamespaceAlreadyExists) { throw new Error(`Namespace "${newNamespaceName}" already exists.`); } if ( newNamespaceName === namespaceName && groupName === newGroupName && groupInterval === existingGroup.interval ) { throw new Error('Nothing changed.'); } // validation for new groupInterval if (groupInterval !== existingGroup.interval) { const notValidRules = rulesInSameGroupHaveInvalidFor(existingGroup.rules, groupInterval ?? '1m'); if (notValidRules.length > 0) { throw new Error( `These alerts belonging to this group will have an invalid 'For' value: ${notValidRules .map((rule) => { const { alertName } = getAlertInfo(rule, groupInterval ?? ''); return alertName; }) .join(',')}` ); } } // if renaming namespace - make new copies of all groups, then delete old namespace if (newNamespaceName !== namespaceName) { for (const group of rulesResult[namespaceName]) { await setRulerRuleGroup( rulerConfig, newNamespaceName, group.name === groupName ? { ...group, name: newGroupName, interval: groupInterval, } : group ); } await deleteNamespace(rulerConfig, folderUid || namespaceName); // if only modifying group... } else { // save updated group await setRulerRuleGroup(rulerConfig, folderUid || namespaceName, { ...existingGroup, name: newGroupName, interval: groupInterval, }); // if group name was changed, delete old group if (newGroupName !== groupName) { await deleteRulerRulesGroup(rulerConfig, folderUid || namespaceName, groupName); } } // refetch all rules await thunkAPI.dispatch(fetchRulerRulesAction({ rulesSourceName })); })() ), { errorMessage: 'Failed to update namespace / group', successMessage: 'Update successful', } ); } ); interface UpdateRulesOrderOptions { rulesSourceName: string; namespaceName: string; groupName: string; newRules: RulerRuleDTO[]; folderUid: string; } export const updateRulesOrder = createAsyncThunk( 'unifiedalerting/updateRulesOrderForGroup', async (options: UpdateRulesOrderOptions, thunkAPI): Promise<void> => { return withAppEvents( withSerializedError( (async () => { const { rulesSourceName, namespaceName, groupName, newRules, folderUid } = options; const rulerConfig = getDataSourceRulerConfig(thunkAPI.getState, rulesSourceName); const rulesResult = await fetchRulerRules(rulerConfig); const existingGroup = rulesResult[namespaceName].find((group) => group.name === groupName); if (!existingGroup) { throw new Error(`Group "${groupName}" not found.`); } const payload: PostableRulerRuleGroupDTO = { name: existingGroup.name, interval: existingGroup.interval, rules: newRules, }; await setRulerRuleGroup(rulerConfig, folderUid ?? namespaceName, payload); await thunkAPI.dispatch(fetchRulerRulesAction({ rulesSourceName })); })() ), { errorMessage: 'Failed to update namespace / group', successMessage: 'Update successful', } ); } ); export const addExternalAlertmanagersAction = createAsyncThunk( 'unifiedAlerting/addExternalAlertmanagers', async (alertmanagerConfig: ExternalAlertmanagerConfig, thunkAPI): Promise<void> => { return withAppEvents( withSerializedError( (async () => { await addAlertManagers(alertmanagerConfig); thunkAPI.dispatch(fetchExternalAlertmanagersConfigAction()); })() ), { errorMessage: 'Failed adding alertmanagers', successMessage: 'Alertmanagers updated', } ); } );
public/app/features/alerting/unified/state/actions.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0013444095384329557, 0.0001921967777889222, 0.0001646501332288608, 0.00017563308938406408, 0.0001288822095375508 ]
{ "id": 1, "code_window": [ " hideScope,\n", " hideTag,\n", " hideValue,\n", " query,\n", "}: Props) => {\n", " const styles = useStyles2(getStyles);\n", " const scopedTag = useMemo(() => filterScopedTag(filter), [filter]);\n", " // We automatically change the operator to the regex op when users select 2 or more values\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti = true,\n", " allowCustomValue = true,\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 47 }
package routes import ( "context" "encoding/json" "net/http" "net/url" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana/pkg/tsdb/cloudwatch/models" "github.com/grafana/grafana/pkg/tsdb/cloudwatch/models/resources" "github.com/grafana/grafana/pkg/tsdb/cloudwatch/services" ) func DimensionKeysHandler(ctx context.Context, pluginCtx backend.PluginContext, reqCtxFactory models.RequestContextFactoryFunc, parameters url.Values) ([]byte, *models.HttpError) { dimensionKeysRequest, err := resources.GetDimensionKeysRequest(parameters) if err != nil { return nil, models.NewHttpError("error in DimensionKeyHandler", http.StatusBadRequest, err) } service, err := newListMetricsService(ctx, pluginCtx, reqCtxFactory, dimensionKeysRequest.Region) if err != nil { return nil, models.NewHttpError("error in DimensionKeyHandler", http.StatusInternalServerError, err) } var response []resources.ResourceResponse[string] switch dimensionKeysRequest.Type() { case resources.FilterDimensionKeysRequest: response, err = service.GetDimensionKeysByDimensionFilter(ctx, dimensionKeysRequest) default: response, err = services.GetHardCodedDimensionKeysByNamespace(dimensionKeysRequest.Namespace) } if err != nil { return nil, models.NewHttpError("error in DimensionKeyHandler", http.StatusInternalServerError, err) } jsonResponse, err := json.Marshal(response) if err != nil { return nil, models.NewHttpError("error in DimensionKeyHandler", http.StatusInternalServerError, err) } return jsonResponse, nil } // newListMetricsService is an list metrics service factory. // // Stubbable by tests. var newListMetricsService = func(ctx context.Context, pluginCtx backend.PluginContext, reqCtxFactory models.RequestContextFactoryFunc, region string) (models.ListMetricsProvider, error) { metricClient, err := reqCtxFactory(ctx, pluginCtx, region) if err != nil { return nil, err } return services.NewListMetricsService(metricClient.MetricsClientProvider), nil }
pkg/tsdb/cloudwatch/routes/dimension_keys.go
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0001785371860023588, 0.0001742649037623778, 0.00016907058306969702, 0.00017450799350626767, 0.0000029487523534044158 ]
{ "id": 1, "code_window": [ " hideScope,\n", " hideTag,\n", " hideValue,\n", " query,\n", "}: Props) => {\n", " const styles = useStyles2(getStyles);\n", " const scopedTag = useMemo(() => filterScopedTag(filter), [filter]);\n", " // We automatically change the operator to the regex op when users select 2 or more values\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti = true,\n", " allowCustomValue = true,\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "add", "edit_start_line_idx": 47 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M12,2C6.5,2,2,6.5,2,12c0,2.3,0.8,4.5,2.3,6.3l-2,2c-0.4,0.4-0.4,1,0,1.4C2.5,21.9,2.7,22,3,22h9c5.5,0,10-4.5,10-10S17.5,2,12,2z M8,13c-0.6,0-1-0.4-1-1s0.4-1,1-1s1,0.4,1,1S8.6,13,8,13z M12,13c-0.6,0-1-0.4-1-1s0.4-1,1-1s1,0.4,1,1S12.6,13,12,13z M16,13c-0.6,0-1-0.4-1-1s0.4-1,1-1s1,0.4,1,1S16.6,13,16,13z"/></svg>
public/img/icons/solid/comment-dots.svg
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00017151118663605303, 0.00017151118663605303, 0.00017151118663605303, 0.00017151118663605303, 0 ]
{ "id": 2, "code_window": [ " updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType });\n", " }\n", " }}\n", " placeholder=\"Select value\"\n", " isClearable={false}\n", " aria-label={`select ${filter.id} value`}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " isClearable={true}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 197 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { CoreApp, GrafanaTheme2 } from '@grafana/data'; import { config, FetchError, getTemplateSrv, reportInteraction } from '@grafana/runtime'; import { Alert, Button, HorizontalGroup, Select, useStyles2 } from '@grafana/ui'; import { notifyApp } from '../_importedDependencies/actions/appNotification'; import { createErrorNotification } from '../_importedDependencies/core/appNotification'; import { RawQuery } from '../_importedDependencies/datasources/prometheus/RawQuery'; import { dispatch } from '../_importedDependencies/store'; import { TraceqlFilter, TraceqlSearchScope } from '../dataquery.gen'; import { TempoDatasource } from '../datasource'; import { TempoQueryBuilderOptions } from '../traceql/TempoQueryBuilderOptions'; import { traceqlGrammar } from '../traceql/traceql'; import { TempoQuery } from '../types'; import DurationInput from './DurationInput'; import { GroupByField } from './GroupByField'; import InlineSearchField from './InlineSearchField'; import SearchField from './SearchField'; import TagsInput from './TagsInput'; import { filterScopedTag, filterTitle, generateQueryFromFilters, replaceAt } from './utils'; interface Props { datasource: TempoDatasource; query: TempoQuery; onChange: (value: TempoQuery) => void; onBlur?: () => void; onClearResults: () => void; app?: CoreApp; } const hardCodedFilterIds = ['min-duration', 'max-duration', 'status']; const TraceQLSearch = ({ datasource, query, onChange, onClearResults, app }: Props) => { const styles = useStyles2(getStyles); const [error, setError] = useState<Error | FetchError | null>(null); const [isTagsLoading, setIsTagsLoading] = useState(true); const [traceQlQuery, setTraceQlQuery] = useState<string>(''); const templateSrv = getTemplateSrv(); const updateFilter = useCallback( (s: TraceqlFilter) => { const copy = { ...query }; copy.filters ||= []; const indexOfFilter = copy.filters.findIndex((f) => f.id === s.id); if (indexOfFilter >= 0) { // update in place if the filter already exists, for consistency and to avoid UI bugs copy.filters = replaceAt(copy.filters, indexOfFilter, s); } else { copy.filters.push(s); } onChange(copy); }, [onChange, query] ); const deleteFilter = (s: TraceqlFilter) => { onChange({ ...query, filters: query.filters.filter((f) => f.id !== s.id) }); }; useEffect(() => { setTraceQlQuery(generateQueryFromFilters(query.filters || [])); }, [query]); const findFilter = useCallback((id: string) => query.filters?.find((f) => f.id === id), [query.filters]); useEffect(() => { const fetchTags = async () => { try { await datasource.languageProvider.start(); setIsTagsLoading(false); } catch (error) { if (error instanceof Error) { dispatch(notifyApp(createErrorNotification('Error', error))); } } }; fetchTags(); }, [datasource]); useEffect(() => { // Initialize state with configured static filters that already have a value from the config datasource.search?.filters ?.filter((f) => f.value) .forEach((f) => { if (!findFilter(f.id)) { updateFilter(f); } }); }, [datasource.search?.filters, findFilter, updateFilter]); // filter out tags that already exist in the static fields const staticTags = datasource.search?.filters?.map((f) => f.tag) || []; staticTags.push('duration'); staticTags.push('traceDuration'); // Dynamic filters are all filters that don't match the ID of a filter in the datasource configuration // The duration and status fields are a special case since its selector is hard-coded const dynamicFilters = (query.filters || []).filter( (f) => !hardCodedFilterIds.includes(f.id) && (datasource.search?.filters?.findIndex((sf) => sf.id === f.id) || 0) === -1 && f.id !== 'duration-type' ); return ( <> <div className={styles.container}> <div> {datasource.search?.filters?.map( (f) => f.tag && ( <InlineSearchField key={f.id} label={filterTitle(f)} tooltip={`Filter your search by ${filterScopedTag( f )}. To modify the default filters shown for search visit the Tempo datasource configuration page.`} > <SearchField filter={findFilter(f.id) || f} datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> ) )} <InlineSearchField label={'Status'}> <SearchField filter={ findFilter('status') || { id: 'status', tag: 'status', scope: TraceqlSearchScope.Intrinsic, operator: '=', } } datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> <InlineSearchField label={'Duration'} tooltip="The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h" > <HorizontalGroup spacing={'none'}> <Select options={[ { label: 'span', value: 'span' }, { label: 'trace', value: 'trace' }, ]} value={findFilter('duration-type')?.value ?? 'span'} onChange={(v) => { const filter = findFilter('duration-type') || { id: 'duration-type', value: 'span', }; updateFilter({ ...filter, value: v?.value }); }} aria-label={'duration type'} /> <DurationInput filter={ findFilter('min-duration') || { id: 'min-duration', tag: 'duration', operator: '>', valueType: 'duration', } } operators={['>', '>=']} updateFilter={updateFilter} /> <DurationInput filter={ findFilter('max-duration') || { id: 'max-duration', tag: 'duration', operator: '<', valueType: 'duration', } } operators={['<', '<=']} updateFilter={updateFilter} /> </HorizontalGroup> </InlineSearchField> <InlineSearchField label={'Tags'}> <TagsInput filters={dynamicFilters} datasource={datasource} setError={setError} updateFilter={updateFilter} deleteFilter={deleteFilter} staticTags={staticTags} isTagsLoading={isTagsLoading} query={traceQlQuery} requireTagAndValue={true} /> </InlineSearchField> {config.featureToggles.metricsSummary && ( <GroupByField datasource={datasource} onChange={onChange} query={query} isTagsLoading={isTagsLoading} /> )} </div> <div className={styles.rawQueryContainer}> <RawQuery query={templateSrv.replace(traceQlQuery)} lang={{ grammar: traceqlGrammar, name: 'traceql' }} /> <Button variant="secondary" size="sm" onClick={() => { reportInteraction('grafana_traces_copy_to_traceql_clicked', { app: app ?? '', grafana_version: config.buildInfo.version, location: 'search_tab', }); onClearResults(); const traceQlQuery = generateQueryFromFilters(query.filters || []); onChange({ ...query, query: traceQlQuery, queryType: 'traceql', }); }} > Edit in TraceQL </Button> </div> <TempoQueryBuilderOptions onChange={onChange} query={query} /> </div> {error ? ( <Alert title="Unable to connect to Tempo search" severity="info" className={styles.alert}> Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the <a href={`/datasources/edit/${datasource.uid}`}>datasource settings</a>. </Alert> ) : null} </> ); }; export default TraceQLSearch; const getStyles = (theme: GrafanaTheme2) => ({ alert: css({ maxWidth: '75ch', marginTop: theme.spacing(2), }), container: css({ display: 'flex', gap: '4px', flexWrap: 'wrap', flexDirection: 'column', }), rawQueryContainer: css({ alignItems: 'center', backgroundColor: theme.colors.background.secondary, display: 'flex', justifyContent: 'space-between', padding: theme.spacing(1), }), });
public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx
1
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00591165479272604, 0.0007825976936146617, 0.00016546128608752042, 0.00020762489293701947, 0.0012415265664458275 ]
{ "id": 2, "code_window": [ " updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType });\n", " }\n", " }}\n", " placeholder=\"Select value\"\n", " isClearable={false}\n", " aria-label={`select ${filter.id} value`}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " isClearable={true}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 197 }
import { css } from '@emotion/css'; import { subDays } from 'date-fns'; import { Location } from 'history'; import React, { useCallback, useEffect, useState } from 'react'; import { FormProvider, useForm, useFormContext, Validate } from 'react-hook-form'; import { useLocation } from 'react-router-dom'; import AutoSizer from 'react-virtualized-auto-sizer'; import { GrafanaTheme2 } from '@grafana/data'; import { isFetchError } from '@grafana/runtime'; import { Alert, Button, CollapsableSection, Field, FieldSet, Input, LinkButton, Spinner, Tab, TabsBar, useStyles2, Stack, } from '@grafana/ui'; import { useCleanup } from 'app/core/hooks/useCleanup'; import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types'; import { useDispatch } from 'app/types'; import { AlertField, TemplatePreviewErrors, TemplatePreviewResponse, TemplatePreviewResult, usePreviewTemplateMutation, } from '../../api/templateApi'; import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector'; import { updateAlertManagerConfigAction } from '../../state/actions'; import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource'; import { makeAMLink } from '../../utils/misc'; import { initialAsyncRequestState } from '../../utils/redux'; import { ensureDefine } from '../../utils/templates'; import { ProvisionedResource, ProvisioningAlert } from '../Provisioning'; import { PayloadEditor } from './PayloadEditor'; import { TemplateDataDocs } from './TemplateDataDocs'; import { TemplateEditor } from './TemplateEditor'; import { snippets } from './editor/templateDataSuggestions'; export interface TemplateFormValues { name: string; content: string; } export const defaults: TemplateFormValues = Object.freeze({ name: '', content: '', }); interface Props { existing?: TemplateFormValues; config: AlertManagerCortexConfig; alertManagerSourceName: string; provenance?: string; } export const isDuplicating = (location: Location) => location.pathname.endsWith('/duplicate'); const DEFAULT_PAYLOAD = `[ { "annotations": { "summary": "Instance instance1 has been down for more than 5 minutes" }, "labels": { "instance": "instance1" }, "startsAt": "${subDays(new Date(), 1).toISOString()}" }] `; export const TemplateForm = ({ existing, alertManagerSourceName, config, provenance }: Props) => { const styles = useStyles2(getStyles); const dispatch = useDispatch(); useCleanup((state) => (state.unifiedAlerting.saveAMConfig = initialAsyncRequestState)); const { loading, error } = useUnifiedAlertingSelector((state) => state.saveAMConfig); const location = useLocation(); const isduplicating = isDuplicating(location); const [payload, setPayload] = useState(DEFAULT_PAYLOAD); const [payloadFormatError, setPayloadFormatError] = useState<string | null>(null); const [view, setView] = useState<'content' | 'preview'>('content'); const onPayloadError = () => setView('preview'); const submit = (values: TemplateFormValues) => { // wrap content in "define" if it's not already wrapped, in case user did not do it/ // it's not obvious that this is needed for template to work const content = ensureDefine(values.name, values.content); // add new template to template map const template_files = { ...config.template_files, [values.name]: content, }; // delete existing one (if name changed, otherwise it was overwritten in previous step) if (existing && existing.name !== values.name) { delete template_files[existing.name]; } // make sure name for the template is configured on the alertmanager config object const templates = [ ...(config.alertmanager_config.templates ?? []).filter((name) => name !== existing?.name), values.name, ]; const newConfig: AlertManagerCortexConfig = { template_files, alertmanager_config: { ...config.alertmanager_config, templates, }, }; dispatch( updateAlertManagerConfigAction({ alertManagerSourceName, newConfig, oldConfig: config, successMessage: 'Template saved.', redirectPath: '/alerting/notifications', }) ); }; const formApi = useForm<TemplateFormValues>({ mode: 'onSubmit', defaultValues: existing ?? defaults, }); const { handleSubmit, register, formState: { errors }, getValues, setValue, watch, } = formApi; const validateNameIsUnique: Validate<string, TemplateFormValues> = (name: string) => { return !config.template_files[name] || existing?.name === name ? true : 'Another template with this name already exists.'; }; const isGrafanaAlertManager = alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME; return ( <FormProvider {...formApi}> <form onSubmit={handleSubmit(submit)}> <h4>{existing && !isduplicating ? 'Edit notification template' : 'Create notification template'}</h4> {error && ( <Alert severity="error" title="Error saving template"> {error.message || (isFetchError(error) && error.data?.message) || String(error)} </Alert> )} {provenance && <ProvisioningAlert resource={ProvisionedResource.Template} />} <FieldSet disabled={Boolean(provenance)}> <Field label="Template name" error={errors?.name?.message} invalid={!!errors.name?.message} required> <Input {...register('name', { required: { value: true, message: 'Required.' }, validate: { nameIsUnique: validateNameIsUnique }, })} placeholder="Give your template a name" width={42} autoFocus={true} /> </Field> <TemplatingGuideline /> <div className={styles.editorsWrapper}> <div className={styles.contentContainer}> <TabsBar> <Tab label="Content" active={view === 'content'} onChangeTab={() => setView('content')} /> {isGrafanaAlertManager && ( <Tab label="Preview" active={view === 'preview'} onChangeTab={() => setView('preview')} /> )} </TabsBar> <div className={styles.contentContainerEditor}> <AutoSizer> {({ width }) => ( <> {view === 'content' ? ( <div> <Field error={errors?.content?.message} invalid={!!errors.content?.message} required> <div className={styles.editWrapper}> <TemplateEditor value={getValues('content')} width={width} height={363} onBlur={(value) => setValue('content', value)} /> </div> </Field> <div className={styles.buttons}> {loading && ( <Button disabled={true} icon="spinner" variant="primary"> Saving... </Button> )} {!loading && ( <Button type="submit" variant="primary"> Save template </Button> )} <LinkButton disabled={loading} href={makeAMLink('alerting/notifications', alertManagerSourceName)} variant="secondary" type="button" > Cancel </LinkButton> </div> </div> ) : ( <TemplatePreview width={width} payload={payload} templateName={watch('name')} setPayloadFormatError={setPayloadFormatError} payloadFormatError={payloadFormatError} /> )} </> )} </AutoSizer> </div> </div> {isGrafanaAlertManager && ( <PayloadEditor payload={payload} setPayload={setPayload} defaultPayload={DEFAULT_PAYLOAD} setPayloadFormatError={setPayloadFormatError} payloadFormatError={payloadFormatError} onPayloadError={onPayloadError} /> )} </div> </FieldSet> <CollapsableSection label="Data cheat sheet" isOpen={false} className={styles.collapsableSection}> <TemplateDataDocs /> </CollapsableSection> </form> </FormProvider> ); }; function TemplatingGuideline() { const styles = useStyles2(getStyles); return ( <Alert title="Templating guideline" severity="info"> <Stack direction="row"> <div> Grafana uses Go templating language to create notification messages. <br /> To find out more about templating please visit our documentation. </div> <div> <LinkButton href="https://grafana.com/docs/grafana/latest/alerting/manage-notifications/template-notifications/" target="_blank" icon="external-link-alt" variant="secondary" > Templating documentation </LinkButton> </div> </Stack> <div className={styles.snippets}> To make templating easier, we provide a few snippets in the content editor to help you speed up your workflow. <div className={styles.code}> {Object.values(snippets) .map((s) => s.label) .join(', ')} </div> </div> </Alert> ); } function getResultsToRender(results: TemplatePreviewResult[]) { const filteredResults = results.filter((result) => result.text.trim().length > 0); const moreThanOne = filteredResults.length > 1; const preview = (result: TemplatePreviewResult) => { const previewForLabel = `Preview for ${result.name}:`; const separatorStart = '='.repeat(previewForLabel.length).concat('>'); const separatorEnd = '<'.concat('='.repeat(previewForLabel.length)); if (moreThanOne) { return `${previewForLabel}\n${separatorStart}${result.text}${separatorEnd}\n`; } else { return `${separatorStart}${result.text}${separatorEnd}\n`; } }; return filteredResults .map((result: TemplatePreviewResult) => { return preview(result); }) .join(`\n`); } function getErrorsToRender(results: TemplatePreviewErrors[]) { return results .map((result: TemplatePreviewErrors) => { if (result.name) { return `ERROR in ${result.name}:\n`.concat(`${result.kind}\n${result.message}\n`); } else { return `ERROR:\n${result.kind}\n${result.message}\n`; } }) .join(`\n`); } export const PREVIEW_NOT_AVAILABLE = 'Preview request failed. Check if the payload data has the correct structure.'; function getPreviewTorender( isPreviewError: boolean, payloadFormatError: string | null, data: TemplatePreviewResponse | undefined ) { // ERRORS IN JSON OR IN REQUEST (endpoint not available, for example) const previewErrorRequest = isPreviewError ? PREVIEW_NOT_AVAILABLE : undefined; const somethingWasWrong: boolean = isPreviewError || Boolean(payloadFormatError); const errorToRender = payloadFormatError || previewErrorRequest; //PREVIEW : RESULTS AND ERRORS const previewResponseResults = data?.results; const previewResponseErrors = data?.errors; const previewResultsToRender = previewResponseResults ? getResultsToRender(previewResponseResults) : ''; const previewErrorsToRender = previewResponseErrors ? getErrorsToRender(previewResponseErrors) : ''; if (somethingWasWrong) { return errorToRender; } else { return `${previewResultsToRender}\n${previewErrorsToRender}`; } } export function TemplatePreview({ payload, templateName, payloadFormatError, setPayloadFormatError, width, }: { payload: string; templateName: string; payloadFormatError: string | null; setPayloadFormatError: (value: React.SetStateAction<string | null>) => void; width: number; }) { const styles = useStyles2(getStyles); const { watch } = useFormContext<TemplateFormValues>(); const templateContent = watch('content'); const [trigger, { data, isError: isPreviewError, isLoading }] = usePreviewTemplateMutation(); const previewToRender = getPreviewTorender(isPreviewError, payloadFormatError, data); const onPreview = useCallback(() => { try { const alertList: AlertField[] = JSON.parse(payload); JSON.stringify([...alertList]); // check if it's iterable, in order to be able to add more data trigger({ template: templateContent, alerts: alertList, name: templateName }); setPayloadFormatError(null); } catch (e) { setPayloadFormatError(e instanceof Error ? e.message : 'Invalid JSON.'); } }, [templateContent, templateName, payload, setPayloadFormatError, trigger]); useEffect(() => onPreview(), [onPreview]); return ( <div style={{ width: `${width}px` }} className={styles.preview.wrapper}> {isLoading && ( <> <Spinner inline={true} /> Loading preview... </> )} <pre className={styles.preview.result} data-testid="payloadJSON"> {previewToRender} </pre> <Button onClick={onPreview} className={styles.preview.button} icon="arrow-up" type="button" variant="secondary"> Refresh preview </Button> </div> ); } const getStyles = (theme: GrafanaTheme2) => ({ contentContainer: css` flex: 1; margin-bottom: ${theme.spacing(6)}; `, contentContainerEditor: css` flex:1; display: flex; padding-top: 10px; gap: ${theme.spacing(2)}; flex-direction: row; align-items: flex-start; flex-wrap: wrap; ${theme.breakpoints.up('xxl')} { flex - wrap: nowrap; } min-width: 450px; height: 363px; `, snippets: css` margin-top: ${theme.spacing(2)}; font-size: ${theme.typography.bodySmall.fontSize}; `, code: css` color: ${theme.colors.text.secondary}; font-weight: ${theme.typography.fontWeightBold}; `, buttons: css` display: flex; & > * + * { margin-left: ${theme.spacing(1)}; } margin-top: -7px; `, textarea: css` max-width: 758px; `, editWrapper: css` display: flex; width: 100% heigth:100%; position: relative; `, toggle: css` color: theme.colors.text.secondary, marginRight: ${theme.spacing(1)}`, preview: { wrapper: css` display: flex; width: 100% heigth:100%; position: relative; flex-direction: column; `, result: css` width: 100%; height: 363px; `, button: css` flex: none; width: fit-content; margin-top: -6px; `, }, collapsableSection: css` width: fit-content; `, editorsWrapper: css` display: flex; flex: 1; flex-wrap: wrap; gap: ${theme.spacing(1)}; `, });
public/app/features/alerting/unified/components/receivers/TemplateForm.tsx
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00017591255891602486, 0.00017016363563016057, 0.00016245624283328652, 0.00017052754992619157, 0.0000028419487989594927 ]
{ "id": 2, "code_window": [ " updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType });\n", " }\n", " }}\n", " placeholder=\"Select value\"\n", " isClearable={false}\n", " aria-label={`select ${filter.id} value`}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " isClearable={true}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 197 }
import { Matcher, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { select } from 'react-select-event'; import { byRole } from 'testing-library-selector'; // Used to select an option or options from a Select in unit tests export const selectOptionInTest = async ( input: HTMLElement, optionOrOptions: string | RegExp | Array<string | RegExp> ) => await waitFor(() => select(input, optionOrOptions, { container: document.body })); // Finds the parent of the Select so you can assert if it has a value export const getSelectParent = (input: HTMLElement) => input.parentElement?.parentElement?.parentElement?.parentElement?.parentElement; export const clickSelectOption = async (selectElement: HTMLElement, optionText: string): Promise<void> => { await userEvent.click(byRole('combobox').get(selectElement)); await selectOptionInTest(selectElement, optionText); }; export const clickSelectOptionMatch = async (selectElement: HTMLElement, optionText: Matcher): Promise<void> => { await userEvent.click(byRole('combobox').get(selectElement)); await selectOptionInTest(selectElement, optionText as string); };
public/test/helpers/selectOptionInTest.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00034045317443087697, 0.0002564531459938735, 0.00016637571388855577, 0.00026253052055835724, 0.00007119663496268913 ]
{ "id": 2, "code_window": [ " updateFilter({ ...filter, value: val?.value, valueType: val?.type || uniqueOptionType });\n", " }\n", " }}\n", " placeholder=\"Select value\"\n", " isClearable={false}\n", " aria-label={`select ${filter.id} value`}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " isClearable={true}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 197 }
import { Graph } from './dag'; describe('Directed acyclic graph', () => { describe('Given a graph with nodes with different links in between them', () => { const dag = new Graph(); const nodeA = dag.createNode('A'); const nodeB = dag.createNode('B'); const nodeC = dag.createNode('C'); const nodeD = dag.createNode('D'); const nodeE = dag.createNode('E'); const nodeF = dag.createNode('F'); const nodeG = dag.createNode('G'); const nodeH = dag.createNode('H'); const nodeI = dag.createNode('I'); dag.link([nodeB, nodeC, nodeD, nodeE, nodeF, nodeG, nodeH], nodeA); dag.link([nodeC, nodeD, nodeE, nodeF, nodeI], nodeB); dag.link([nodeD, nodeE, nodeF, nodeG], nodeC); dag.link([nodeE, nodeF], nodeD); dag.link([nodeF, nodeG], nodeE); //printGraph(dag); it('nodes in graph should have expected edges', () => { expect(nodeA.inputEdges).toHaveLength(7); expect(nodeA.outputEdges).toHaveLength(0); expect(nodeA.edges).toHaveLength(7); expect(nodeB.inputEdges).toHaveLength(5); expect(nodeB.outputEdges).toHaveLength(1); expect(nodeB.edges).toHaveLength(6); expect(nodeC.inputEdges).toHaveLength(4); expect(nodeC.outputEdges).toHaveLength(2); expect(nodeC.edges).toHaveLength(6); expect(nodeD.inputEdges).toHaveLength(2); expect(nodeD.outputEdges).toHaveLength(3); expect(nodeD.edges).toHaveLength(5); expect(nodeE.inputEdges).toHaveLength(2); expect(nodeE.outputEdges).toHaveLength(4); expect(nodeE.edges).toHaveLength(6); expect(nodeF.inputEdges).toHaveLength(0); expect(nodeF.outputEdges).toHaveLength(5); expect(nodeF.edges).toHaveLength(5); expect(nodeG.inputEdges).toHaveLength(0); expect(nodeG.outputEdges).toHaveLength(3); expect(nodeG.edges).toHaveLength(3); expect(nodeH.inputEdges).toHaveLength(0); expect(nodeH.outputEdges).toHaveLength(1); expect(nodeH.edges).toHaveLength(1); expect(nodeI.inputEdges).toHaveLength(0); expect(nodeI.outputEdges).toHaveLength(1); expect(nodeI.edges).toHaveLength(1); expect(nodeA.getEdgeFrom(nodeB)).not.toBeUndefined(); expect(nodeB.getEdgeTo(nodeA)).not.toBeUndefined(); }); it('when optimizing input edges for node A should return node B and H', () => { const actual = nodeA.getOptimizedInputEdges().map((e) => e.inputNode); expect(actual).toHaveLength(2); expect(actual).toEqual(expect.arrayContaining([nodeB, nodeH])); }); it('when optimizing input edges for node B should return node C', () => { const actual = nodeB.getOptimizedInputEdges().map((e) => e.inputNode); expect(actual).toHaveLength(2); expect(actual).toEqual(expect.arrayContaining([nodeC, nodeI])); }); it('when optimizing input edges for node C should return node D', () => { const actual = nodeC.getOptimizedInputEdges().map((e) => e.inputNode); expect(actual).toHaveLength(1); expect(actual).toEqual(expect.arrayContaining([nodeD])); }); it('when optimizing input edges for node D should return node E', () => { const actual = nodeD.getOptimizedInputEdges().map((e) => e.inputNode); expect(actual).toHaveLength(1); expect(actual).toEqual(expect.arrayContaining([nodeE])); }); it('when optimizing input edges for node E should return node F and G', () => { const actual = nodeE.getOptimizedInputEdges().map((e) => e.inputNode); expect(actual).toHaveLength(2); expect(actual).toEqual(expect.arrayContaining([nodeF, nodeG])); }); it('when optimizing input edges for node F should return zero nodes', () => { const actual = nodeF.getOptimizedInputEdges(); expect(actual).toHaveLength(0); }); it('when optimizing input edges for node G should return zero nodes', () => { const actual = nodeG.getOptimizedInputEdges(); expect(actual).toHaveLength(0); }); it('when optimizing input edges for node H should return zero nodes', () => { const actual = nodeH.getOptimizedInputEdges(); expect(actual).toHaveLength(0); }); it('when linking non-existing input node with existing output node should throw error', () => { expect(() => { dag.link('non-existing', 'A'); }).toThrowError("cannot link input node named non-existing since it doesn't exist in graph"); }); it('when linking existing input node with non-existing output node should throw error', () => { expect(() => { dag.link('A', 'non-existing'); }).toThrowError("cannot link output node named non-existing since it doesn't exist in graph"); }); }); });
public/app/core/utils/dag.test.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00017654724069871008, 0.00017355910676997155, 0.00016774324467405677, 0.0001737345301080495, 0.0000022402596187021118 ]
{ "id": 3, "code_window": [ " aria-label={`select ${filter.id} value`}\n", " allowCustomValue={true}\n", " isMulti\n", " allowCreateWhileLoading\n", " />\n", " )}\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " allowCustomValue={allowCustomValue}\n", " isMulti={isMulti}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 199 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { CoreApp, GrafanaTheme2 } from '@grafana/data'; import { config, FetchError, getTemplateSrv, reportInteraction } from '@grafana/runtime'; import { Alert, Button, HorizontalGroup, Select, useStyles2 } from '@grafana/ui'; import { notifyApp } from '../_importedDependencies/actions/appNotification'; import { createErrorNotification } from '../_importedDependencies/core/appNotification'; import { RawQuery } from '../_importedDependencies/datasources/prometheus/RawQuery'; import { dispatch } from '../_importedDependencies/store'; import { TraceqlFilter, TraceqlSearchScope } from '../dataquery.gen'; import { TempoDatasource } from '../datasource'; import { TempoQueryBuilderOptions } from '../traceql/TempoQueryBuilderOptions'; import { traceqlGrammar } from '../traceql/traceql'; import { TempoQuery } from '../types'; import DurationInput from './DurationInput'; import { GroupByField } from './GroupByField'; import InlineSearchField from './InlineSearchField'; import SearchField from './SearchField'; import TagsInput from './TagsInput'; import { filterScopedTag, filterTitle, generateQueryFromFilters, replaceAt } from './utils'; interface Props { datasource: TempoDatasource; query: TempoQuery; onChange: (value: TempoQuery) => void; onBlur?: () => void; onClearResults: () => void; app?: CoreApp; } const hardCodedFilterIds = ['min-duration', 'max-duration', 'status']; const TraceQLSearch = ({ datasource, query, onChange, onClearResults, app }: Props) => { const styles = useStyles2(getStyles); const [error, setError] = useState<Error | FetchError | null>(null); const [isTagsLoading, setIsTagsLoading] = useState(true); const [traceQlQuery, setTraceQlQuery] = useState<string>(''); const templateSrv = getTemplateSrv(); const updateFilter = useCallback( (s: TraceqlFilter) => { const copy = { ...query }; copy.filters ||= []; const indexOfFilter = copy.filters.findIndex((f) => f.id === s.id); if (indexOfFilter >= 0) { // update in place if the filter already exists, for consistency and to avoid UI bugs copy.filters = replaceAt(copy.filters, indexOfFilter, s); } else { copy.filters.push(s); } onChange(copy); }, [onChange, query] ); const deleteFilter = (s: TraceqlFilter) => { onChange({ ...query, filters: query.filters.filter((f) => f.id !== s.id) }); }; useEffect(() => { setTraceQlQuery(generateQueryFromFilters(query.filters || [])); }, [query]); const findFilter = useCallback((id: string) => query.filters?.find((f) => f.id === id), [query.filters]); useEffect(() => { const fetchTags = async () => { try { await datasource.languageProvider.start(); setIsTagsLoading(false); } catch (error) { if (error instanceof Error) { dispatch(notifyApp(createErrorNotification('Error', error))); } } }; fetchTags(); }, [datasource]); useEffect(() => { // Initialize state with configured static filters that already have a value from the config datasource.search?.filters ?.filter((f) => f.value) .forEach((f) => { if (!findFilter(f.id)) { updateFilter(f); } }); }, [datasource.search?.filters, findFilter, updateFilter]); // filter out tags that already exist in the static fields const staticTags = datasource.search?.filters?.map((f) => f.tag) || []; staticTags.push('duration'); staticTags.push('traceDuration'); // Dynamic filters are all filters that don't match the ID of a filter in the datasource configuration // The duration and status fields are a special case since its selector is hard-coded const dynamicFilters = (query.filters || []).filter( (f) => !hardCodedFilterIds.includes(f.id) && (datasource.search?.filters?.findIndex((sf) => sf.id === f.id) || 0) === -1 && f.id !== 'duration-type' ); return ( <> <div className={styles.container}> <div> {datasource.search?.filters?.map( (f) => f.tag && ( <InlineSearchField key={f.id} label={filterTitle(f)} tooltip={`Filter your search by ${filterScopedTag( f )}. To modify the default filters shown for search visit the Tempo datasource configuration page.`} > <SearchField filter={findFilter(f.id) || f} datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> ) )} <InlineSearchField label={'Status'}> <SearchField filter={ findFilter('status') || { id: 'status', tag: 'status', scope: TraceqlSearchScope.Intrinsic, operator: '=', } } datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> <InlineSearchField label={'Duration'} tooltip="The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h" > <HorizontalGroup spacing={'none'}> <Select options={[ { label: 'span', value: 'span' }, { label: 'trace', value: 'trace' }, ]} value={findFilter('duration-type')?.value ?? 'span'} onChange={(v) => { const filter = findFilter('duration-type') || { id: 'duration-type', value: 'span', }; updateFilter({ ...filter, value: v?.value }); }} aria-label={'duration type'} /> <DurationInput filter={ findFilter('min-duration') || { id: 'min-duration', tag: 'duration', operator: '>', valueType: 'duration', } } operators={['>', '>=']} updateFilter={updateFilter} /> <DurationInput filter={ findFilter('max-duration') || { id: 'max-duration', tag: 'duration', operator: '<', valueType: 'duration', } } operators={['<', '<=']} updateFilter={updateFilter} /> </HorizontalGroup> </InlineSearchField> <InlineSearchField label={'Tags'}> <TagsInput filters={dynamicFilters} datasource={datasource} setError={setError} updateFilter={updateFilter} deleteFilter={deleteFilter} staticTags={staticTags} isTagsLoading={isTagsLoading} query={traceQlQuery} requireTagAndValue={true} /> </InlineSearchField> {config.featureToggles.metricsSummary && ( <GroupByField datasource={datasource} onChange={onChange} query={query} isTagsLoading={isTagsLoading} /> )} </div> <div className={styles.rawQueryContainer}> <RawQuery query={templateSrv.replace(traceQlQuery)} lang={{ grammar: traceqlGrammar, name: 'traceql' }} /> <Button variant="secondary" size="sm" onClick={() => { reportInteraction('grafana_traces_copy_to_traceql_clicked', { app: app ?? '', grafana_version: config.buildInfo.version, location: 'search_tab', }); onClearResults(); const traceQlQuery = generateQueryFromFilters(query.filters || []); onChange({ ...query, query: traceQlQuery, queryType: 'traceql', }); }} > Edit in TraceQL </Button> </div> <TempoQueryBuilderOptions onChange={onChange} query={query} /> </div> {error ? ( <Alert title="Unable to connect to Tempo search" severity="info" className={styles.alert}> Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the <a href={`/datasources/edit/${datasource.uid}`}>datasource settings</a>. </Alert> ) : null} </> ); }; export default TraceQLSearch; const getStyles = (theme: GrafanaTheme2) => ({ alert: css({ maxWidth: '75ch', marginTop: theme.spacing(2), }), container: css({ display: 'flex', gap: '4px', flexWrap: 'wrap', flexDirection: 'column', }), rawQueryContainer: css({ alignItems: 'center', backgroundColor: theme.colors.background.secondary, display: 'flex', justifyContent: 'space-between', padding: theme.spacing(1), }), });
public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx
1
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0028922061901539564, 0.00036367957363836467, 0.0001612912310520187, 0.00017205861513502896, 0.0005399222136475146 ]
{ "id": 3, "code_window": [ " aria-label={`select ${filter.id} value`}\n", " allowCustomValue={true}\n", " isMulti\n", " allowCreateWhileLoading\n", " />\n", " )}\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " allowCustomValue={allowCustomValue}\n", " isMulti={isMulti}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 199 }
package searchstore import ( "bytes" "fmt" "strings" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/search/model" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" ) // Builder defaults to returning a SQL query to get a list of all dashboards // in default order, but can be modified by applying filters. type Builder struct { // List of FilterWhere/FilterGroupBy/FilterOrderBy/FilterLeftJoin // to modify the query. Filters []any Dialect migrator.Dialect Features featuremgmt.FeatureToggles params []any sql bytes.Buffer } // ToSQL builds the SQL query and returns it as a string, together with the SQL parameters. func (b *Builder) ToSQL(limit, page int64) (string, []any) { b.params = make([]any, 0) b.sql = bytes.Buffer{} b.buildSelect() b.sql.WriteString("( ") orderQuery := b.applyFilters() b.sql.WriteString(b.Dialect.LimitOffset(limit, (page-1)*limit) + `) AS ids INNER JOIN dashboard ON ids.id = dashboard.id`) b.sql.WriteString("\n") if b.Features.IsEnabledGlobally(featuremgmt.FlagNestedFolders) { b.sql.WriteString( `LEFT OUTER JOIN folder ON folder.uid = dashboard.folder_uid AND folder.org_id = dashboard.org_id`) } else { b.sql.WriteString(` LEFT OUTER JOIN dashboard AS folder ON folder.id = dashboard.folder_id`) } b.sql.WriteString(` LEFT OUTER JOIN dashboard_tag ON dashboard.id = dashboard_tag.dashboard_id`) b.sql.WriteString("\n") b.sql.WriteString(orderQuery) return b.sql.String(), b.params } func (b *Builder) buildSelect() { var recQuery string var recQueryParams []any b.sql.WriteString( `SELECT dashboard.id, dashboard.uid, dashboard.title, dashboard.slug, dashboard_tag.term, dashboard.is_folder, dashboard.folder_id, folder.uid AS folder_uid, `) if b.Features.IsEnabledGlobally(featuremgmt.FlagNestedFolders) { b.sql.WriteString(` folder.title AS folder_slug,`) } else { b.sql.WriteString(` folder.slug AS folder_slug,`) } b.sql.WriteString(` folder.title AS folder_title `) for _, f := range b.Filters { if f, ok := f.(model.FilterSelect); ok { b.sql.WriteString(fmt.Sprintf(", %s", f.Select())) } if f, ok := f.(model.FilterWith); ok { recQuery, recQueryParams = f.With() } } b.sql.WriteString(` FROM `) if recQuery == "" { return } // prepend recursive queries var bf bytes.Buffer bf.WriteString(recQuery) bf.WriteString(b.sql.String()) b.sql = bf b.params = append(recQueryParams, b.params...) } func (b *Builder) applyFilters() (ordering string) { joins := []string{} orderJoins := []string{} wheres := []string{} whereParams := []any{} groups := []string{} groupParams := []any{} orders := []string{} for _, f := range b.Filters { if f, ok := f.(model.FilterLeftJoin); ok { s := f.LeftJoin() if s != "" { joins = append(joins, fmt.Sprintf(" LEFT OUTER JOIN %s ", s)) } } if f, ok := f.(model.FilterWhere); ok { sql, params := f.Where() if sql != "" { wheres = append(wheres, sql) whereParams = append(whereParams, params...) } } if f, ok := f.(model.FilterGroupBy); ok { sql, params := f.GroupBy() if sql != "" { groups = append(groups, sql) groupParams = append(groupParams, params...) } } if f, ok := f.(model.FilterOrderBy); ok { if f, ok := f.(model.FilterLeftJoin); ok { orderJoins = append(orderJoins, fmt.Sprintf(" LEFT OUTER JOIN %s ", f.LeftJoin())) } orders = append(orders, f.OrderBy()) } } b.sql.WriteString("SELECT dashboard.id FROM dashboard") b.sql.WriteString(strings.Join(joins, "")) if len(wheres) > 0 { b.sql.WriteString(fmt.Sprintf(" WHERE %s", strings.Join(wheres, " AND "))) b.params = append(b.params, whereParams...) } if len(orders) < 1 { orders = append(orders, TitleSorter{}.OrderBy()) } if len(groups) > 0 { cols := make([]string, 0, len(orders)+len(groups)) for _, o := range orders { o := strings.TrimSuffix(o, " DESC") o = strings.TrimSuffix(o, " ASC") exists := false for _, g := range groups { if g == o { exists = true break } } if !exists { cols = append(cols, o) } } cols = append(cols, groups...) b.sql.WriteString(fmt.Sprintf(" GROUP BY %s", strings.Join(cols, ", "))) b.params = append(b.params, groupParams...) } orderByCols := []string{} for _, o := range orders { orderByCols = append(orderByCols, b.Dialect.OrderBy(o)) } orderBy := fmt.Sprintf(" ORDER BY %s", strings.Join(orderByCols, ", ")) b.sql.WriteString(orderBy) order := strings.Join(orderJoins, "") order += orderBy return order }
pkg/services/sqlstore/searchstore/builder.go
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0015505023766309023, 0.00024287131964229047, 0.00016485940432175994, 0.00017029033915605396, 0.0003003339224960655 ]
{ "id": 3, "code_window": [ " aria-label={`select ${filter.id} value`}\n", " allowCustomValue={true}\n", " isMulti\n", " allowCreateWhileLoading\n", " />\n", " )}\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " allowCustomValue={allowCustomValue}\n", " isMulti={isMulti}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 199 }
import { FieldColorModeId, VisualizationSuggestionsBuilder, VisualizationSuggestion, DataTransformerID, } from '@grafana/data'; import { GraphDrawStyle, GraphFieldConfig, GraphGradientMode, LegendDisplayMode, LineInterpolation, StackingMode, } from '@grafana/schema'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { SuggestionName } from 'app/types/suggestions'; import { Options } from './panelcfg.gen'; export class TimeSeriesSuggestionsSupplier { getSuggestionsForData(builder: VisualizationSuggestionsBuilder) { const { dataSummary } = builder; if (!dataSummary.hasTimeField || !dataSummary.hasNumberField || dataSummary.rowCountTotal < 2) { return; } const list = builder.getListAppender<Options, GraphFieldConfig>({ name: SuggestionName.LineChart, pluginId: 'timeseries', options: { legend: { calcs: [], displayMode: LegendDisplayMode.Hidden, placement: 'right', showLegend: false, }, }, fieldConfig: { defaults: { custom: {}, }, overrides: [], }, cardOptions: { previewModifier: (s) => { if (s.fieldConfig?.defaults.custom?.drawStyle !== GraphDrawStyle.Bars) { s.fieldConfig!.defaults.custom!.lineWidth = Math.max(s.fieldConfig!.defaults.custom!.lineWidth ?? 1, 2); } }, }, }); const maxBarsCount = 100; list.append({ name: SuggestionName.LineChart, }); if (dataSummary.rowCountMax < 200) { list.append({ name: SuggestionName.LineChartSmooth, fieldConfig: { defaults: { custom: { lineInterpolation: LineInterpolation.Smooth, }, }, overrides: [], }, }); } // Single series suggestions if (dataSummary.numberFieldCount === 1) { list.append({ name: SuggestionName.AreaChart, fieldConfig: { defaults: { custom: { fillOpacity: 25, }, }, overrides: [], }, }); list.append({ name: SuggestionName.LineChartGradientColorScheme, fieldConfig: { defaults: { color: { mode: FieldColorModeId.ContinuousGrYlRd, }, custom: { gradientMode: GraphGradientMode.Scheme, lineInterpolation: LineInterpolation.Smooth, lineWidth: 3, fillOpacity: 20, }, }, overrides: [], }, }); if (dataSummary.rowCountMax < maxBarsCount) { list.append({ name: SuggestionName.BarChart, fieldConfig: { defaults: { custom: { drawStyle: GraphDrawStyle.Bars, fillOpacity: 100, lineWidth: 1, gradientMode: GraphGradientMode.Hue, }, }, overrides: [], }, }); list.append({ name: SuggestionName.BarChartGradientColorScheme, fieldConfig: { defaults: { color: { mode: FieldColorModeId.ContinuousGrYlRd, }, custom: { drawStyle: GraphDrawStyle.Bars, fillOpacity: 90, lineWidth: 1, gradientMode: GraphGradientMode.Scheme, }, }, overrides: [], }, }); } return; } // Multiple series suggestions list.append({ name: SuggestionName.AreaChartStacked, fieldConfig: { defaults: { custom: { fillOpacity: 25, stacking: { mode: StackingMode.Normal, group: 'A', }, }, }, overrides: [], }, }); list.append({ name: SuggestionName.AreaChartStackedPercent, fieldConfig: { defaults: { custom: { fillOpacity: 25, stacking: { mode: StackingMode.Percent, group: 'A', }, }, }, overrides: [], }, }); if (dataSummary.rowCountTotal / dataSummary.numberFieldCount < maxBarsCount) { list.append({ name: SuggestionName.BarChartStacked, fieldConfig: { defaults: { custom: { drawStyle: GraphDrawStyle.Bars, fillOpacity: 100, lineWidth: 1, gradientMode: GraphGradientMode.Hue, stacking: { mode: StackingMode.Normal, group: 'A', }, }, }, overrides: [], }, }); list.append({ name: SuggestionName.BarChartStackedPercent, fieldConfig: { defaults: { custom: { drawStyle: GraphDrawStyle.Bars, fillOpacity: 100, lineWidth: 1, gradientMode: GraphGradientMode.Hue, stacking: { mode: StackingMode.Percent, group: 'A', }, }, }, overrides: [], }, }); } } } // This will try to get a suggestion that will add a long to wide conversion export function getPrepareTimeseriesSuggestion(panelId: number): VisualizationSuggestion | undefined { const panel = getDashboardSrv().getCurrent()?.getPanelById(panelId); if (panel) { const transformations = panel.transformations ? [...panel.transformations] : []; transformations.push({ id: DataTransformerID.prepareTimeSeries, options: { format: 'wide', }, }); return { name: 'Transform to wide time series format', pluginId: 'timeseries', transformations, }; } return undefined; }
public/app/plugins/panel/timeseries/suggestions.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.000175130830029957, 0.0001724349131109193, 0.0001655867527006194, 0.00017298597958870232, 0.000002395838919255766 ]
{ "id": 3, "code_window": [ " aria-label={`select ${filter.id} value`}\n", " allowCustomValue={true}\n", " isMulti\n", " allowCreateWhileLoading\n", " />\n", " )}\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " allowCustomValue={allowCustomValue}\n", " isMulti={isMulti}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/SearchField.tsx", "type": "replace", "edit_start_line_idx": 199 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2, toOption } from '@grafana/data'; import { EditorRows, FlexItem } from '@grafana/experimental'; import { AutoSizeInput, IconButton, Select, useStyles2 } from '@grafana/ui'; import { PrometheusDatasource } from '../../datasource'; import { binaryScalarDefs } from '../binaryScalarOperations'; import { PromVisualQueryBinary } from '../types'; import { PromQueryBuilder } from './PromQueryBuilder'; export interface NestedQueryProps { nestedQuery: PromVisualQueryBinary; datasource: PrometheusDatasource; index: number; onChange: (index: number, update: PromVisualQueryBinary) => void; onRemove: (index: number) => void; onRunQuery: () => void; showExplain: boolean; } export const NestedQuery = React.memo<NestedQueryProps>((props) => { const { nestedQuery, index, datasource, onChange, onRemove, onRunQuery, showExplain } = props; const styles = useStyles2(getStyles); return ( <div className={styles.card}> <div className={styles.header}> <div className={styles.name}>Operator</div> <Select width="auto" options={operators} value={toOption(nestedQuery.operator)} onChange={(value) => { onChange(index, { ...nestedQuery, operator: value.value!, }); }} /> <div className={styles.name}>Vector matches</div> <div className={styles.vectorMatchWrapper}> <Select<PromVisualQueryBinary['vectorMatchesType']> width="auto" value={nestedQuery.vectorMatchesType || 'on'} allowCustomValue options={[ { value: 'on', label: 'on' }, { value: 'ignoring', label: 'ignoring' }, ]} onChange={(val) => { onChange(index, { ...nestedQuery, vectorMatchesType: val.value, }); }} /> <AutoSizeInput className={styles.vectorMatchInput} minWidth={20} defaultValue={nestedQuery.vectorMatches} onCommitChange={(evt) => { onChange(index, { ...nestedQuery, vectorMatches: evt.currentTarget.value, vectorMatchesType: nestedQuery.vectorMatchesType || 'on', }); }} /> </div> <FlexItem grow={1} /> <IconButton name="times" size="sm" onClick={() => onRemove(index)} tooltip="Remove match" /> </div> <div className={styles.body}> <EditorRows> <PromQueryBuilder showExplain={showExplain} query={nestedQuery.query} datasource={datasource} onRunQuery={onRunQuery} onChange={(update) => { onChange(index, { ...nestedQuery, query: update }); }} /> </EditorRows> </div> </div> ); }); const operators = binaryScalarDefs.map((def) => ({ label: def.sign, value: def.sign })); NestedQuery.displayName = 'NestedQuery'; const getStyles = (theme: GrafanaTheme2) => { return { card: css({ label: 'card', display: 'flex', flexDirection: 'column', gap: theme.spacing(0.5), }), header: css({ label: 'header', padding: theme.spacing(0.5, 0.5, 0.5, 1), gap: theme.spacing(1), display: 'flex', alignItems: 'center', }), name: css({ label: 'name', whiteSpace: 'nowrap', }), body: css({ label: 'body', paddingLeft: theme.spacing(2), }), vectorMatchInput: css({ label: 'vectorMatchInput', marginLeft: -1, }), vectorMatchWrapper: css({ label: 'vectorMatchWrapper', display: 'flex', }), }; };
packages/grafana-prometheus/src/querybuilder/components/NestedQuery.tsx
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.00021448201732710004, 0.00017495083739049733, 0.00016584717377554625, 0.0001707709743641317, 0.000011978528164036106 ]
{ "id": 4, "code_window": [ " tags={[]}\n", " hideScope={true}\n", " hideTag={true}\n", " query={traceQlQuery}\n", " />\n", " </InlineSearchField>\n", " <InlineSearchField\n", " label={'Duration'}\n", " tooltip=\"The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti={false}\n", " allowCustomValue={false}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx", "type": "add", "edit_start_line_idx": 153 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { CoreApp, GrafanaTheme2 } from '@grafana/data'; import { config, FetchError, getTemplateSrv, reportInteraction } from '@grafana/runtime'; import { Alert, Button, HorizontalGroup, Select, useStyles2 } from '@grafana/ui'; import { notifyApp } from '../_importedDependencies/actions/appNotification'; import { createErrorNotification } from '../_importedDependencies/core/appNotification'; import { RawQuery } from '../_importedDependencies/datasources/prometheus/RawQuery'; import { dispatch } from '../_importedDependencies/store'; import { TraceqlFilter, TraceqlSearchScope } from '../dataquery.gen'; import { TempoDatasource } from '../datasource'; import { TempoQueryBuilderOptions } from '../traceql/TempoQueryBuilderOptions'; import { traceqlGrammar } from '../traceql/traceql'; import { TempoQuery } from '../types'; import DurationInput from './DurationInput'; import { GroupByField } from './GroupByField'; import InlineSearchField from './InlineSearchField'; import SearchField from './SearchField'; import TagsInput from './TagsInput'; import { filterScopedTag, filterTitle, generateQueryFromFilters, replaceAt } from './utils'; interface Props { datasource: TempoDatasource; query: TempoQuery; onChange: (value: TempoQuery) => void; onBlur?: () => void; onClearResults: () => void; app?: CoreApp; } const hardCodedFilterIds = ['min-duration', 'max-duration', 'status']; const TraceQLSearch = ({ datasource, query, onChange, onClearResults, app }: Props) => { const styles = useStyles2(getStyles); const [error, setError] = useState<Error | FetchError | null>(null); const [isTagsLoading, setIsTagsLoading] = useState(true); const [traceQlQuery, setTraceQlQuery] = useState<string>(''); const templateSrv = getTemplateSrv(); const updateFilter = useCallback( (s: TraceqlFilter) => { const copy = { ...query }; copy.filters ||= []; const indexOfFilter = copy.filters.findIndex((f) => f.id === s.id); if (indexOfFilter >= 0) { // update in place if the filter already exists, for consistency and to avoid UI bugs copy.filters = replaceAt(copy.filters, indexOfFilter, s); } else { copy.filters.push(s); } onChange(copy); }, [onChange, query] ); const deleteFilter = (s: TraceqlFilter) => { onChange({ ...query, filters: query.filters.filter((f) => f.id !== s.id) }); }; useEffect(() => { setTraceQlQuery(generateQueryFromFilters(query.filters || [])); }, [query]); const findFilter = useCallback((id: string) => query.filters?.find((f) => f.id === id), [query.filters]); useEffect(() => { const fetchTags = async () => { try { await datasource.languageProvider.start(); setIsTagsLoading(false); } catch (error) { if (error instanceof Error) { dispatch(notifyApp(createErrorNotification('Error', error))); } } }; fetchTags(); }, [datasource]); useEffect(() => { // Initialize state with configured static filters that already have a value from the config datasource.search?.filters ?.filter((f) => f.value) .forEach((f) => { if (!findFilter(f.id)) { updateFilter(f); } }); }, [datasource.search?.filters, findFilter, updateFilter]); // filter out tags that already exist in the static fields const staticTags = datasource.search?.filters?.map((f) => f.tag) || []; staticTags.push('duration'); staticTags.push('traceDuration'); // Dynamic filters are all filters that don't match the ID of a filter in the datasource configuration // The duration and status fields are a special case since its selector is hard-coded const dynamicFilters = (query.filters || []).filter( (f) => !hardCodedFilterIds.includes(f.id) && (datasource.search?.filters?.findIndex((sf) => sf.id === f.id) || 0) === -1 && f.id !== 'duration-type' ); return ( <> <div className={styles.container}> <div> {datasource.search?.filters?.map( (f) => f.tag && ( <InlineSearchField key={f.id} label={filterTitle(f)} tooltip={`Filter your search by ${filterScopedTag( f )}. To modify the default filters shown for search visit the Tempo datasource configuration page.`} > <SearchField filter={findFilter(f.id) || f} datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> ) )} <InlineSearchField label={'Status'}> <SearchField filter={ findFilter('status') || { id: 'status', tag: 'status', scope: TraceqlSearchScope.Intrinsic, operator: '=', } } datasource={datasource} setError={setError} updateFilter={updateFilter} tags={[]} hideScope={true} hideTag={true} query={traceQlQuery} /> </InlineSearchField> <InlineSearchField label={'Duration'} tooltip="The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h" > <HorizontalGroup spacing={'none'}> <Select options={[ { label: 'span', value: 'span' }, { label: 'trace', value: 'trace' }, ]} value={findFilter('duration-type')?.value ?? 'span'} onChange={(v) => { const filter = findFilter('duration-type') || { id: 'duration-type', value: 'span', }; updateFilter({ ...filter, value: v?.value }); }} aria-label={'duration type'} /> <DurationInput filter={ findFilter('min-duration') || { id: 'min-duration', tag: 'duration', operator: '>', valueType: 'duration', } } operators={['>', '>=']} updateFilter={updateFilter} /> <DurationInput filter={ findFilter('max-duration') || { id: 'max-duration', tag: 'duration', operator: '<', valueType: 'duration', } } operators={['<', '<=']} updateFilter={updateFilter} /> </HorizontalGroup> </InlineSearchField> <InlineSearchField label={'Tags'}> <TagsInput filters={dynamicFilters} datasource={datasource} setError={setError} updateFilter={updateFilter} deleteFilter={deleteFilter} staticTags={staticTags} isTagsLoading={isTagsLoading} query={traceQlQuery} requireTagAndValue={true} /> </InlineSearchField> {config.featureToggles.metricsSummary && ( <GroupByField datasource={datasource} onChange={onChange} query={query} isTagsLoading={isTagsLoading} /> )} </div> <div className={styles.rawQueryContainer}> <RawQuery query={templateSrv.replace(traceQlQuery)} lang={{ grammar: traceqlGrammar, name: 'traceql' }} /> <Button variant="secondary" size="sm" onClick={() => { reportInteraction('grafana_traces_copy_to_traceql_clicked', { app: app ?? '', grafana_version: config.buildInfo.version, location: 'search_tab', }); onClearResults(); const traceQlQuery = generateQueryFromFilters(query.filters || []); onChange({ ...query, query: traceQlQuery, queryType: 'traceql', }); }} > Edit in TraceQL </Button> </div> <TempoQueryBuilderOptions onChange={onChange} query={query} /> </div> {error ? ( <Alert title="Unable to connect to Tempo search" severity="info" className={styles.alert}> Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the <a href={`/datasources/edit/${datasource.uid}`}>datasource settings</a>. </Alert> ) : null} </> ); }; export default TraceQLSearch; const getStyles = (theme: GrafanaTheme2) => ({ alert: css({ maxWidth: '75ch', marginTop: theme.spacing(2), }), container: css({ display: 'flex', gap: '4px', flexWrap: 'wrap', flexDirection: 'column', }), rawQueryContainer: css({ alignItems: 'center', backgroundColor: theme.colors.background.secondary, display: 'flex', justifyContent: 'space-between', padding: theme.spacing(1), }), });
public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx
1
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.9936455488204956, 0.03820064663887024, 0.0001646947202971205, 0.0002687768719624728, 0.18403925001621246 ]
{ "id": 4, "code_window": [ " tags={[]}\n", " hideScope={true}\n", " hideTag={true}\n", " query={traceQlQuery}\n", " />\n", " </InlineSearchField>\n", " <InlineSearchField\n", " label={'Duration'}\n", " tooltip=\"The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti={false}\n", " allowCustomValue={false}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx", "type": "add", "edit_start_line_idx": 153 }
import { render, RenderResult, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { TestProvider } from 'test/helpers/TestProvider'; import { PluginType, escapeStringForRegex } from '@grafana/data'; import { locationService } from '@grafana/runtime'; import { getRouteComponentProps } from 'app/core/navigation/__mocks__/routeProps'; import { RouteDescriptor } from 'app/core/navigation/types'; import { configureStore } from 'app/store/configureStore'; import { getCatalogPluginMock, getPluginsStateMock } from '../__mocks__'; import { fetchRemotePlugins } from '../state/actions'; import { PluginAdminRoutes, CatalogPlugin, ReducerState, RequestStatus } from '../types'; import BrowsePage from './Browse'; jest.mock('@grafana/runtime', () => { const original = jest.requireActual('@grafana/runtime'); const mockedRuntime = { ...original }; mockedRuntime.config.bootData.user.isGrafanaAdmin = true; mockedRuntime.config.buildInfo.version = 'v8.1.0'; return mockedRuntime; }); const renderBrowse = ( path = '/plugins', plugins: CatalogPlugin[] = [], pluginsStateOverride?: ReducerState ): RenderResult => { const store = configureStore({ plugins: pluginsStateOverride || getPluginsStateMock(plugins) }); locationService.push(path); const props = getRouteComponentProps({ route: { routeName: PluginAdminRoutes.Home } as RouteDescriptor, }); return render( <TestProvider store={store}> <BrowsePage {...props} /> </TestProvider> ); }; describe('Browse list of plugins', () => { describe('when filtering', () => { it('should list installed plugins by default', async () => { const { queryByText } = renderBrowse('/plugins', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 4', isInstalled: false }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 1')).toBeInTheDocument(); expect(queryByText('Plugin 2')).toBeInTheDocument(); expect(queryByText('Plugin 3')).toBeInTheDocument(); expect(queryByText('Plugin 4')).toBeNull(); }); it('should list all plugins (including core plugins) when filtering by all', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&filterByType=all', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: false }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 4', isInstalled: true, isCore: true }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 2')).toBeInTheDocument(); expect(queryByText('Plugin 3')).toBeInTheDocument(); // Core plugins should still be listed expect(queryByText('Plugin 4')).toBeInTheDocument(); }); it('should list installed plugins (including core plugins) when filtering by installed', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=installed', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: false }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 4', isInstalled: true, isCore: true }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 3')).toBeInTheDocument(); expect(queryByText('Plugin 4')).toBeInTheDocument(); // Not showing not installed plugins expect(queryByText('Plugin 2')).not.toBeInTheDocument(); }); it('should list all plugins (including disabled plugins) when filtering by all', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&filterByType=all', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: false }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 4', isInstalled: true, isDisabled: true }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 2')).toBeInTheDocument(); expect(queryByText('Plugin 3')).toBeInTheDocument(); expect(queryByText('Plugin 4')).toBeInTheDocument(); }); it('should list installed plugins (including disabled plugins) when filtering by installed', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=installed', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: false }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 4', isInstalled: true, isDisabled: true }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 3')).toBeInTheDocument(); expect(queryByText('Plugin 4')).toBeInTheDocument(); // Not showing not installed plugins expect(queryByText('Plugin 2')).not.toBeInTheDocument(); }); it('should list enterprise plugins when querying for them', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&q=wavefront', [ getCatalogPluginMock({ id: 'wavefront', name: 'Wavefront', isInstalled: true, isEnterprise: true }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', isInstalled: true, isCore: true }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', isInstalled: true }), ]); await waitFor(() => expect(queryByText('Wavefront')).toBeInTheDocument()); // Should not show plugins that don't match the query expect(queryByText('Plugin 2')).not.toBeInTheDocument(); expect(queryByText('Plugin 3')).not.toBeInTheDocument(); }); it('should list only datasource plugins when filtering by datasource', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&filterByType=datasource', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.datasource }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', type: PluginType.panel }), ]); await waitFor(() => expect(queryByText('Plugin 2')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 1')).not.toBeInTheDocument(); expect(queryByText('Plugin 3')).not.toBeInTheDocument(); }); it('should list only panel plugins when filtering by panel', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&filterByType=panel', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.datasource }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', type: PluginType.panel }), ]); await waitFor(() => expect(queryByText('Plugin 3')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 1')).not.toBeInTheDocument(); expect(queryByText('Plugin 2')).not.toBeInTheDocument(); }); it('should list only app plugins when filtering by app', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&filterByType=app', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.datasource }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', type: PluginType.panel }), ]); await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 2')).not.toBeInTheDocument(); expect(queryByText('Plugin 3')).not.toBeInTheDocument(); }); }); describe('when searching', () => { it('should only list plugins matching search', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&q=matches', [ getCatalogPluginMock({ id: 'matches-the-search', name: 'Matches the search' }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', }), ]); await waitFor(() => expect(queryByText('Matches the search')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 2')).not.toBeInTheDocument(); expect(queryByText('Plugin 3')).not.toBeInTheDocument(); }); it('should handle escaped regex characters in the search query (e.g. "(" )', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&q=' + escapeStringForRegex('graph (old)'), [ getCatalogPluginMock({ id: 'graph', name: 'Graph (old)' }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2' }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3' }), ]); await waitFor(() => expect(queryByText('Graph (old)')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 2')).not.toBeInTheDocument(); expect(queryByText('Plugin 3')).not.toBeInTheDocument(); }); it('should be possible to filter plugins by type', async () => { const { queryByText } = renderBrowse('/plugins?filterByType=datasource&filterBy=all', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', type: PluginType.datasource }), ]); await waitFor(() => expect(queryByText('Plugin 3')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 1')).not.toBeInTheDocument(); expect(queryByText('Plugin 2')).not.toBeInTheDocument(); }); it('should be possible to filter plugins both by type and a keyword', async () => { const { queryByText } = renderBrowse('/plugins?filterByType=datasource&filterBy=all&q=Foo', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.datasource }), getCatalogPluginMock({ id: 'plugin-3', name: 'Foo plugin', type: PluginType.datasource }), ]); await waitFor(() => expect(queryByText('Foo plugin')).toBeInTheDocument()); // Other plugin types shouldn't be shown expect(queryByText('Plugin 1')).not.toBeInTheDocument(); expect(queryByText('Plugin 2')).not.toBeInTheDocument(); }); it('should list all available plugins if the keyword is empty', async () => { const { queryByText } = renderBrowse('/plugins?filterBy=all&q=', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', type: PluginType.app }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2', type: PluginType.panel }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3', type: PluginType.datasource }), ]); // We did not filter for any specific plugin type, so all plugins should be shown await waitFor(() => expect(queryByText('Plugin 1')).toBeInTheDocument()); expect(queryByText('Plugin 2')).toBeInTheDocument(); expect(queryByText('Plugin 3')).toBeInTheDocument(); }); }); describe('when sorting', () => { it('should sort plugins by name in ascending alphabetical order', async () => { const { findByTestId } = renderBrowse('/plugins?filterBy=all', [ getCatalogPluginMock({ id: 'wavefront', name: 'Wavefront' }), getCatalogPluginMock({ id: 'redis-application', name: 'Redis Application' }), getCatalogPluginMock({ id: 'zabbix', name: 'Zabbix' }), getCatalogPluginMock({ id: 'diagram', name: 'Diagram' }), getCatalogPluginMock({ id: 'acesvg', name: 'ACE.SVG' }), ]); const pluginList = await findByTestId('plugin-list'); const pluginHeadings = within(pluginList).queryAllByRole('heading'); expect(pluginHeadings.map((heading) => heading.innerHTML)).toStrictEqual([ 'ACE.SVG', 'Diagram', 'Redis Application', 'Wavefront', 'Zabbix', ]); }); it('should sort plugins by name in descending alphabetical order', async () => { const { findByTestId } = renderBrowse('/plugins?filterBy=all&sortBy=nameDesc', [ getCatalogPluginMock({ id: 'wavefront', name: 'Wavefront' }), getCatalogPluginMock({ id: 'redis-application', name: 'Redis Application' }), getCatalogPluginMock({ id: 'zabbix', name: 'Zabbix' }), getCatalogPluginMock({ id: 'diagram', name: 'Diagram' }), getCatalogPluginMock({ id: 'acesvg', name: 'ACE.SVG' }), ]); const pluginList = await findByTestId('plugin-list'); const pluginHeadings = within(pluginList).queryAllByRole('heading'); expect(pluginHeadings.map((heading) => heading.innerHTML)).toStrictEqual([ 'Zabbix', 'Wavefront', 'Redis Application', 'Diagram', 'ACE.SVG', ]); }); it('should sort plugins by date in ascending updated order', async () => { const { findByTestId } = renderBrowse('/plugins?filterBy=all&sortBy=updated', [ getCatalogPluginMock({ id: '1', name: 'Wavefront', updatedAt: '2021-04-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '2', name: 'Redis Application', updatedAt: '2021-02-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '3', name: 'Zabbix', updatedAt: '2021-01-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '4', name: 'Diagram', updatedAt: '2021-05-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '5', name: 'ACE.SVG', updatedAt: '2021-02-01T00:00:00.000Z' }), ]); const pluginList = await findByTestId('plugin-list'); const pluginHeadings = within(pluginList).queryAllByRole('heading'); expect(pluginHeadings.map((heading) => heading.innerHTML)).toStrictEqual([ 'Diagram', 'Wavefront', 'Redis Application', 'ACE.SVG', 'Zabbix', ]); }); it('should sort plugins by date in ascending published order', async () => { const { findByTestId } = renderBrowse('/plugins?filterBy=all&sortBy=published', [ getCatalogPluginMock({ id: '1', name: 'Wavefront', publishedAt: '2021-04-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '2', name: 'Redis Application', publishedAt: '2021-02-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '3', name: 'Zabbix', publishedAt: '2021-01-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '4', name: 'Diagram', publishedAt: '2021-05-01T00:00:00.000Z' }), getCatalogPluginMock({ id: '5', name: 'ACE.SVG', publishedAt: '2021-02-01T00:00:00.000Z' }), ]); const pluginList = await findByTestId('plugin-list'); const pluginHeadings = within(pluginList).queryAllByRole('heading'); expect(pluginHeadings.map((heading) => heading.innerHTML)).toStrictEqual([ 'Diagram', 'Wavefront', 'Redis Application', 'ACE.SVG', 'Zabbix', ]); }); it('should sort plugins by number of downloads in ascending order', async () => { const { findByTestId } = renderBrowse('/plugins?filterBy=all&sortBy=downloads', [ getCatalogPluginMock({ id: '1', name: 'Wavefront', downloads: 30 }), getCatalogPluginMock({ id: '2', name: 'Redis Application', downloads: 10 }), getCatalogPluginMock({ id: '3', name: 'Zabbix', downloads: 50 }), getCatalogPluginMock({ id: '4', name: 'Diagram', downloads: 20 }), getCatalogPluginMock({ id: '5', name: 'ACE.SVG', downloads: 40 }), ]); const pluginList = await findByTestId('plugin-list'); const pluginHeadings = within(pluginList).queryAllByRole('heading'); expect(pluginHeadings.map((heading) => heading.innerHTML)).toStrictEqual([ 'Zabbix', 'ACE.SVG', 'Wavefront', 'Diagram', 'Redis Application', ]); }); }); describe('when GCOM api is not available', () => { it('should disable the All / Installed filter', async () => { const plugins = [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 2', isInstalled: true }), getCatalogPluginMock({ id: 'plugin-4', name: 'Plugin 3', isInstalled: true }), ]; const state = getPluginsStateMock(plugins); // Mock the store like if the remote plugins request was rejected const stateOverride = { ...state, requests: { ...state.requests, [fetchRemotePlugins.typePrefix]: { status: RequestStatus.Rejected, }, }, }; // The radio input for the filters should be disabled const { getByRole } = renderBrowse('/plugins', [], stateOverride); await waitFor(() => expect(getByRole('radio', { name: 'Installed' })).toBeDisabled()); }); }); it('should be possible to switch between display modes', async () => { const { findByTestId, getByRole, getByTitle, queryByText } = renderBrowse('/plugins?filterBy=all', [ getCatalogPluginMock({ id: 'plugin-1', name: 'Plugin 1' }), getCatalogPluginMock({ id: 'plugin-2', name: 'Plugin 2' }), getCatalogPluginMock({ id: 'plugin-3', name: 'Plugin 3' }), ]); await findByTestId('plugin-list'); const listOptionTitle = 'Display plugins in list'; const gridOptionTitle = 'Display plugins in a grid layout'; const listOption = getByRole('radio', { name: listOptionTitle }); const listOptionLabel = getByTitle(listOptionTitle); const gridOption = getByRole('radio', { name: gridOptionTitle }); const gridOptionLabel = getByTitle(gridOptionTitle); // All options should be visible expect(listOptionLabel).toBeVisible(); expect(gridOptionLabel).toBeVisible(); // The default display mode should be "grid" expect(gridOption).toBeChecked(); expect(listOption).not.toBeChecked(); // Switch to "list" view await userEvent.click(listOption); expect(gridOption).not.toBeChecked(); expect(listOption).toBeChecked(); // All plugins are still visible expect(queryByText('Plugin 1')).toBeInTheDocument(); expect(queryByText('Plugin 2')).toBeInTheDocument(); expect(queryByText('Plugin 3')).toBeInTheDocument(); }); });
public/app/features/plugins/admin/pages/Browse.test.tsx
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0001765600172802806, 0.0001712917728582397, 0.00016272244101855904, 0.00017150015628430992, 0.000002668364459168515 ]
{ "id": 4, "code_window": [ " tags={[]}\n", " hideScope={true}\n", " hideTag={true}\n", " query={traceQlQuery}\n", " />\n", " </InlineSearchField>\n", " <InlineSearchField\n", " label={'Duration'}\n", " tooltip=\"The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti={false}\n", " allowCustomValue={false}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx", "type": "add", "edit_start_line_idx": 153 }
import { TemplateSrvDependencies } from 'app/features/templating/template_srv'; import { getFilteredVariables, getVariables, getVariableWithName } from '../../app/features/variables/state/selectors'; import { StoreState } from '../../app/types'; export const getTemplateSrvDependencies = (state: StoreState): TemplateSrvDependencies => ({ getFilteredVariables: (filter) => getFilteredVariables(filter, state), getVariableWithName: (name) => getVariableWithName(name, state), getVariables: () => getVariables(state), });
public/test/helpers/getTemplateSrvDependencies.ts
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0001734481775201857, 0.00016997288912534714, 0.00016649760073050857, 0.00016997288912534714, 0.0000034752883948385715 ]
{ "id": 4, "code_window": [ " tags={[]}\n", " hideScope={true}\n", " hideTag={true}\n", " query={traceQlQuery}\n", " />\n", " </InlineSearchField>\n", " <InlineSearchField\n", " label={'Duration'}\n", " tooltip=\"The trace or span duration, i.e. end - start time of the trace/span. Accepted units are ns, ms, s, m, h\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isMulti={false}\n", " allowCustomValue={false}\n" ], "file_path": "public/app/plugins/datasource/tempo/SearchTraceQLEditor/TraceQLSearch.tsx", "type": "add", "edit_start_line_idx": 153 }
package jwt import ( "context" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "net/http" "net/http/httptest" "os" "strings" "testing" "time" jose "github.com/go-jose/go-jose/v3" "github.com/go-jose/go-jose/v3/jwt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tests/testsuite" ) type scenarioContext struct { ctx context.Context cfg *setting.Cfg authJWTSvc *AuthService } type cachingScenarioContext struct { scenarioContext reqCount *int } type configureFunc func(*testing.T, *setting.Cfg) type scenarioFunc func(*testing.T, scenarioContext) type cachingScenarioFunc func(*testing.T, cachingScenarioContext) const subject = "foo-subj" func TestMain(m *testing.M) { testsuite.Run(m) } func TestVerifyUsingPKIXPublicKeyFile(t *testing.T) { key := rsaKeys[0] unknownKey := rsaKeys[1] scenario(t, "verifies a token", func(t *testing.T, sc scenarioContext) { token := sign(t, key, jwt.Claims{ Subject: subject, }, nil) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }, configurePKIXPublicKeyFile) scenario(t, "rejects a token signed by unknown key", func(t *testing.T, sc scenarioContext) { token := sign(t, unknownKey, jwt.Claims{ Subject: subject, }, nil) _, err := sc.authJWTSvc.Verify(sc.ctx, token) require.Error(t, err) }, configurePKIXPublicKeyFile) publicKeyID := "some-key-id" scenario(t, "verifies a token with a specified kid", func(t *testing.T, sc scenarioContext) { token := sign(t, key, jwt.Claims{ Subject: subject, }, (&jose.SignerOptions{}).WithHeader("kid", publicKeyID)) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }, configurePKIXPublicKeyFile, func(t *testing.T, cfg *setting.Cfg) { t.Helper() cfg.JWTAuth.KeyID = publicKeyID }) } func TestVerifyUsingJWKSetFile(t *testing.T) { configure := func(t *testing.T, cfg *setting.Cfg) { t.Helper() file, err := os.CreateTemp(os.TempDir(), "jwk-*.json") require.NoError(t, err) t.Cleanup(func() { if err := os.Remove(file.Name()); err != nil { panic(err) } }) require.NoError(t, json.NewEncoder(file).Encode(jwksPublic)) require.NoError(t, file.Close()) cfg.JWTAuth.JWKSetFile = file.Name() } scenario(t, "verifies a token signed with a key from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, &jwKeys[0], jwt.Claims{Subject: subject}, nil) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }, configure) scenario(t, "verifies a token signed with another key from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, &jwKeys[1], jwt.Claims{Subject: subject}, nil) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }, configure) scenario(t, "rejects a token signed with a key not from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, jwKeys[2], jwt.Claims{Subject: subject}, nil) _, err := sc.authJWTSvc.Verify(sc.ctx, token) require.Error(t, err) }, configure) } func TestVerifyUsingJWKSetURL(t *testing.T) { t.Run("should refuse to start with non-https URL", func(t *testing.T) { var err error _, err = initAuthService(t, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.JWKSetURL = "https://example.com/.well-known/jwks.json" }) require.NoError(t, err) _, err = initAuthService(t, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.JWKSetURL = "http://example.com/.well-known/jwks.json" }) require.NoError(t, err) _, err = initAuthService(t, func(t *testing.T, cfg *setting.Cfg) { cfg.Env = setting.Prod cfg.JWTAuth.JWKSetURL = "http://example.com/.well-known/jwks.json" }) require.Error(t, err) }) jwkHTTPScenario(t, "verifies a token signed with a key from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, &jwKeys[0], jwt.Claims{Subject: subject}, nil) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }) jwkHTTPScenario(t, "verifies a token signed with another key from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, &jwKeys[1], jwt.Claims{Subject: subject}, nil) verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }) jwkHTTPScenario(t, "rejects a token signed with a key not from the set", func(t *testing.T, sc scenarioContext) { token := sign(t, jwKeys[2], jwt.Claims{Subject: subject}, nil) _, err := sc.authJWTSvc.Verify(sc.ctx, token) require.Error(t, err) }) } func TestCachingJWKHTTPResponse(t *testing.T) { jwkCachingScenario(t, "caches the jwk response", func(t *testing.T, sc cachingScenarioContext) { for i := 0; i < 5; i++ { token := sign(t, &jwKeys[0], jwt.Claims{Subject: subject}, nil) _, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err, "verify call %d", i+1) } assert.Equal(t, 1, *sc.reqCount) }) jwkCachingScenario(t, "respects TTL setting (while cached)", func(t *testing.T, sc cachingScenarioContext) { var err error token0 := sign(t, &jwKeys[0], jwt.Claims{Subject: subject}, nil) token1 := sign(t, &jwKeys[1], jwt.Claims{Subject: subject}, nil) _, err = sc.authJWTSvc.Verify(sc.ctx, token0) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, token1) require.Error(t, err) assert.Equal(t, 1, *sc.reqCount) }, func(t *testing.T, cfg *setting.Cfg) { // Arbitrary high value, several times what the test should take. cfg.JWTAuth.CacheTTL = time.Minute }) jwkCachingScenario(t, "does not cache the response when TTL is zero", func(t *testing.T, sc cachingScenarioContext) { for i := 0; i < 2; i++ { _, err := sc.authJWTSvc.Verify(sc.ctx, sign(t, &jwKeys[i], jwt.Claims{Subject: subject}, nil)) require.NoError(t, err, "verify call %d", i+1) } assert.Equal(t, 2, *sc.reqCount) }, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.CacheTTL = 0 }) } func TestSignatureWithNoneAlgorithm(t *testing.T) { scenario(t, "rejects a token signed with \"none\" algorithm", func(t *testing.T, sc scenarioContext) { token := signNone(t, jwt.Claims{Subject: "foo"}) _, err := sc.authJWTSvc.Verify(sc.ctx, token) require.Error(t, err) }, configurePKIXPublicKeyFile) } func TestClaimValidation(t *testing.T) { key := rsaKeys[0] scenario(t, "validates iss field for equality", func(t *testing.T, sc scenarioContext) { tokenValid := sign(t, key, jwt.Claims{Issuer: "http://foo"}, nil) tokenInvalid := sign(t, key, jwt.Claims{Issuer: "http://bar"}, nil) _, err := sc.authJWTSvc.Verify(sc.ctx, tokenValid) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, tokenInvalid) require.Error(t, err) }, configurePKIXPublicKeyFile, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.ExpectClaims = `{"iss": "http://foo"}` }) scenario(t, "validates sub field for equality", func(t *testing.T, sc scenarioContext) { var err error tokenValid := sign(t, key, jwt.Claims{Subject: "foo"}, nil) tokenInvalid := sign(t, key, jwt.Claims{Subject: "bar"}, nil) _, err = sc.authJWTSvc.Verify(sc.ctx, tokenValid) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, tokenInvalid) require.Error(t, err) }, configurePKIXPublicKeyFile, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.ExpectClaims = `{"sub": "foo"}` }) scenario(t, "validates aud field for inclusion", func(t *testing.T, sc scenarioContext) { var err error _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Audience: []string{"bar", "foo"}}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Audience: []string{"foo", "bar", "baz"}}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Audience: []string{"foo"}}, nil)) require.Error(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Audience: []string{"bar", "baz"}}, nil)) require.Error(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Audience: []string{"baz"}}, nil)) require.Error(t, err) }, configurePKIXPublicKeyFile, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.ExpectClaims = `{"aud": ["foo", "bar"]}` }) scenario(t, "validates non-registered (custom) claims for equality", func(t *testing.T, sc scenarioContext) { var err error _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, map[string]any{"my-str": "foo", "my-number": 123}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, map[string]any{"my-str": "bar", "my-number": 123}, nil)) require.Error(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, map[string]any{"my-str": "foo", "my-number": 100}, nil)) require.Error(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, map[string]any{"my-str": "foo"}, nil)) require.Error(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, map[string]any{"my-number": 123}, nil)) require.Error(t, err) }, configurePKIXPublicKeyFile, func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.ExpectClaims = `{"my-str": "foo", "my-number": 123}` }) scenario(t, "validates exp claim of the token", func(t *testing.T, sc scenarioContext) { var err error _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour))}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{Expiry: jwt.NewNumericDate(time.Now().Add(-time.Hour))}, nil)) require.Error(t, err) }, configurePKIXPublicKeyFile) scenario(t, "validates nbf claim of the token", func(t *testing.T, sc scenarioContext) { var err error _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Hour))}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{NotBefore: jwt.NewNumericDate(time.Now().Add(time.Hour))}, nil)) require.Error(t, err) }, configurePKIXPublicKeyFile) scenario(t, "validates iat claim of the token", func(t *testing.T, sc scenarioContext) { var err error _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Hour))}, nil)) require.NoError(t, err) _, err = sc.authJWTSvc.Verify(sc.ctx, sign(t, key, jwt.Claims{IssuedAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}, nil)) require.Error(t, err) }, configurePKIXPublicKeyFile) } func jwkHTTPScenario(t *testing.T, desc string, fn scenarioFunc, cbs ...configureFunc) { t.Helper() t.Run(desc, func(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := json.NewEncoder(w).Encode(jwksPublic); err != nil { panic(err) } })) t.Cleanup(ts.Close) configure := func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.JWKSetURL = ts.URL } runner := scenarioRunner(func(t *testing.T, sc scenarioContext) { keySet := sc.authJWTSvc.keySet.(*keySetHTTP) keySet.client = ts.Client() fn(t, sc) }, append([]configureFunc{configure}, cbs...)...) runner(t) }) } func jwkCachingScenario(t *testing.T, desc string, fn cachingScenarioFunc, cbs ...configureFunc) { t.Helper() t.Run(desc, func(t *testing.T) { var reqCount int // We run a server that each call responds differently. ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if reqCount++; reqCount > 2 { panic("calling more than two times is not supported") } jwks := jose.JSONWebKeySet{ Keys: []jose.JSONWebKey{jwksPublic.Keys[reqCount-1]}, } if err := json.NewEncoder(w).Encode(jwks); err != nil { panic(err) } })) t.Cleanup(ts.Close) configure := func(t *testing.T, cfg *setting.Cfg) { cfg.JWTAuth.JWKSetURL = ts.URL cfg.JWTAuth.CacheTTL = time.Hour } runner := scenarioRunner(func(t *testing.T, sc scenarioContext) { keySet := sc.authJWTSvc.keySet.(*keySetHTTP) keySet.client = ts.Client() fn(t, cachingScenarioContext{scenarioContext: sc, reqCount: &reqCount}) }, append([]configureFunc{configure}, cbs...)...) runner(t) }) } func TestBase64Paddings(t *testing.T) { key := rsaKeys[0] scenario(t, "verifies a token with base64 padding (non compliant rfc7515#section-2 but accepted)", func(t *testing.T, sc scenarioContext) { token := sign(t, key, jwt.Claims{ Subject: subject, }, nil) var tokenParts []string for i, part := range strings.Split(token, ".") { // Create parts with different padding numbers to test multiple cases. tokenParts = append(tokenParts, part+strings.Repeat(string(base64.StdPadding), i)) } token = strings.Join(tokenParts, ".") verifiedClaims, err := sc.authJWTSvc.Verify(sc.ctx, token) require.NoError(t, err) assert.Equal(t, verifiedClaims["sub"], subject) }, configurePKIXPublicKeyFile) } func scenario(t *testing.T, desc string, fn scenarioFunc, cbs ...configureFunc) { t.Helper() t.Run(desc, scenarioRunner(fn, cbs...)) } func initAuthService(t *testing.T, cbs ...configureFunc) (*AuthService, error) { t.Helper() cfg := setting.NewCfg() cfg.JWTAuth.Enabled = true cfg.JWTAuth.ExpectClaims = "{}" for _, cb := range cbs { cb(t, cfg) } service := newService(cfg, remotecache.NewFakeStore(t)) err := service.init() return service, err } func scenarioRunner(fn scenarioFunc, cbs ...configureFunc) func(t *testing.T) { return func(t *testing.T) { authJWTSvc, err := initAuthService(t, cbs...) require.NoError(t, err) fn(t, scenarioContext{ ctx: context.Background(), cfg: authJWTSvc.Cfg, authJWTSvc: authJWTSvc, }) } } func configurePKIXPublicKeyFile(t *testing.T, cfg *setting.Cfg) { t.Helper() file, err := os.CreateTemp(os.TempDir(), "public-key-*.pem") require.NoError(t, err) t.Cleanup(func() { if err := os.Remove(file.Name()); err != nil { panic(err) } }) blockBytes, err := x509.MarshalPKIXPublicKey(rsaKeys[0].Public()) require.NoError(t, err) require.NoError(t, pem.Encode(file, &pem.Block{ Type: "PUBLIC KEY", Bytes: blockBytes, })) require.NoError(t, file.Close()) cfg.JWTAuth.KeyFile = file.Name() }
pkg/services/auth/jwt/auth_test.go
0
https://github.com/grafana/grafana/commit/b81c3ab9c1231103466658f03bd83d2e1b86304d
[ 0.0002947137109003961, 0.00017315405420958996, 0.00016415257414337248, 0.00017049959569703788, 0.000018467308109393343 ]
{ "id": 0, "code_window": [ "import loopback from 'loopback';\n", "import _ from 'lodash';\n", "import jwt from 'jsonwebtoken';\n", "import generate from 'nanoid/generate';\n", "\n", "import { homeLocation } from '../../config/env';\n", "\n", "import { fixCompletedChallengeItem } from '../utils';\n", "import { themes } from '../utils/themes';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { homeLocation, apiLocation } from '../../config/env';\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 19 }
COMPOSE_PROJECT_NAME=freecodecamp MONGOHQ_URL='mongodb://localhost:27017/freecodecamp' ROLLBAR_APP_ID='my-rollbar-app-id' AUTH0_CLIENT_ID=stuff AUTH0_CLIENT_SECRET=stuff AUTH0_DOMAIN=stuff SESSION_SECRET=secretstuff COOKIE_SECRET='this is a secret' JWT_SECRET='a very long secret' STRIPE_PUBLIC=pk_from_stipe_dashboard STRIPE_SECRET=sk_from_stipe_dashboard PEER=stuff DEBUG=true IMAGE_BASE_URL='https://s3.amazonaws.com/freecodecamp/images/' HOME_LOCATION='http://localhost:8000'
sample.env
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.0004606269649229944, 0.00026598075055517256, 0.00016336528642568737, 0.00017395001486875117, 0.00013770346413366497 ]
{ "id": 0, "code_window": [ "import loopback from 'loopback';\n", "import _ from 'lodash';\n", "import jwt from 'jsonwebtoken';\n", "import generate from 'nanoid/generate';\n", "\n", "import { homeLocation } from '../../config/env';\n", "\n", "import { fixCompletedChallengeItem } from '../utils';\n", "import { themes } from '../utils/themes';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { homeLocation, apiLocation } from '../../config/env';\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 19 }
extends ../layout block content .panel.panel-info .panel-body.text-center h1 You have successfully been unsubscribed. h2 Whatever you do, keep coding! :) if unsubscribeId .col-xs-12.col-md-8.col-md-offset-2 a.btn.btn-primary.btn-lg.btn-block(href='/resubscribe/#{unsubscribeId}') You can click here to resubscribe
server/views/resources/unsubscribed.jade
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00016716490790713578, 0.00016716490790713578, 0.00016716490790713578, 0.00016716490790713578, 0 ]
{ "id": 0, "code_window": [ "import loopback from 'loopback';\n", "import _ from 'lodash';\n", "import jwt from 'jsonwebtoken';\n", "import generate from 'nanoid/generate';\n", "\n", "import { homeLocation } from '../../config/env';\n", "\n", "import { fixCompletedChallengeItem } from '../utils';\n", "import { themes } from '../utils/themes';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { homeLocation, apiLocation } from '../../config/env';\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 19 }
# Contributor's Guide We welcome pull requests from freeCodeCamp campers (our students) and seasoned JavaScript developers alike! Follow these steps to contribute: 1. Find an issue that needs assistance by searching for the [Help Wanted](https://github.com/freeCodeCamp/freeCodeCamp/labels/help%20wanted) tag. 2. Let us know you are working on it by posting a comment on the issue. 3. Follow the instructions in this guide to start working on the issue. Remember to feel free to ask for help in our [Contributors](https://gitter.im/FreeCodeCamp/Contributors) Gitter room. Working on your first Pull Request? You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github) ###### If you've found a bug that is not on the board, [follow these steps](README.md#found-a-bug). -------------------------------------------------------------------------------- ## Quick Reference |command|description| |---|---| | `npm run test` | run all JS tests in the system, including client, server, lint and challenge tests | | `npm run test-challenges` | run all challenge tests (for each challenge JSON file, run all `tests` against all `solutions`) | | `npm run seed` <br>&nbsp;&nbsp;(<small>or</small> `node seed/index.js`) | parses all the challenge JSON files and saves them into MongoDB (code is inside [seed/index.js](seed/index.js)) | | `npm run commit` | interactive tool to help you build a good commit message | | `npm run unpack` | extract challenges from `seed/challenges` into `unpacked` subdirectory, one HTML page per challenge - see [Unpack and Repack](#unpack-and-repack) | | `npm run repack` | repack challenges from `unpacked` subdirectory into `seed/challenges` | ## Table of Contents ### [Setup](#setup) - [Prerequisites](#prerequisites) - [Forking the Project](#forking-the-project) - [Create a Branch](#create-a-branch) - [Set Up Linting](#set-up-linting) - [Set Up MailHog](#set-up-mailhog) - [Set Up freeCodeCamp](#set-up-freecodecamp) ### [Make Changes](#make-changes) - [Unpack and Repack](#unpack-and-repack) - [Challenge Template](#challenge-template) - [Run The Test Suite](#run-the-test-suite) ### Submit - [Creating a Pull Request](#creating-a-pull-request) - [Common Steps](#common-steps) - [How We Review and Merge Pull Requests](#how-we-review-and-merge-pull-requests) - [How We Close Stale Issues](#how-we-close-stale-issues) - [Next Steps](#next-steps) - [Other Resources](#other-resources) ## Setup ### Prerequisites | Prerequisite | Version | | ------------------------------------------- | ------- | | [MongoDB Community Server](https://docs.mongodb.com/manual/administration/install-community/) | `~ ^3` | | [MailHog](https://github.com/mailhog/MailHog) | `~ ^1` | | [Node.js](http://nodejs.org) | `~ ^8.9.3` | | npm (comes with Node) | `~ ^5` | > _Updating to the latest releases is recommended_. If Node.js or MongoDB is already installed on your machine, run the following commands to validate the versions: ```shell node -v mongo --version ``` To check your MongoDB version on Windows, you have to locate the installation directory. It is probably located at something like `C:\Program Files\MongoDB\Server\3.4\` where 3.4 is your version number. If your versions are lower than the prerequisite versions, you should update. Platform-specific guides to setting up a development environment: - [How to clone and setup the freeCodeCamp website on a Windows pc](https://forum.freecodecamp.org/t/how-to-clone-and-setup-the-free-code-camp-website-on-a-windows-pc/19366) - [How to Clone and Setup the freeCodeCamp Website on a Mac](https://forum.freecodecamp.org/t/how-to-clone-and-setup-the-freecodecamp-website-on-a-mac/78450) ### Forking the Project #### Setting Up Your System 1. Install [Git](https://git-scm.com/) or your favorite Git client. 2. (Optional) [Setup an SSH Key](https://help.github.com/articles/generating-an-ssh-key/) for GitHub. #### Forking freeCodeCamp 1. Go to the top level freeCodeCamp repository: <https://github.com/freeCodeCamp/freeCodeCamp> 2. Click the "Fork" Button in the upper right hand corner of the interface ([More Details Here](https://help.github.com/articles/fork-a-repo/)) 3. After the repository (repo) has been forked, you will be taken to your copy of the freeCodeCamp repo at <https://github.com/yourUsername/freeCodeCamp> #### Cloning Your Fork 1. Open a Terminal / Command Line / Bash Shell in your projects directory (_i.e.: `/yourprojectdirectory/`_) 2. Clone your fork of freeCodeCamp ```shell $ git clone https://github.com/yourUsername/freeCodeCamp.git ``` **(make sure to replace `yourUsername` with your GitHub username)** This will download the entire freeCodeCamp repo to your projects directory. #### Setup Your Upstream 1. Change directory to the new freeCodeCamp directory (`cd freeCodeCamp`) 2. Add a remote to the official freeCodeCamp repo: ```shell $ git remote add upstream https://github.com/freeCodeCamp/freeCodeCamp.git ``` Congratulations, you now have a local copy of the freeCodeCamp repo! #### Maintaining Your Fork Now that you have a copy of your fork, there is work you will need to do to keep it current. ##### Rebasing from Upstream Do this prior to every time you create a branch for a PR: 1. Make sure you are on the `staging` branch ```shell $ git status On branch staging Your branch is up-to-date with 'origin/staging'. ``` If your aren't on `staging`, resolve outstanding files / commits and checkout the `staging` branch ```shell $ git checkout staging ``` 2. Do a pull with rebase against `upstream` ```shell $ git pull --rebase upstream staging ``` This will pull down all of the changes to the official staging branch, without making an additional commit in your local repo. 3. (_Optional_) Force push your updated staging branch to your GitHub fork ```shell $ git push origin staging --force ``` This will overwrite the staging branch of your fork. ### Create a Branch Before you start working, you will need to create a separate branch specific to the issue / feature you're working on. You will push your work to this branch. #### Naming Your Branch Name the branch something like `fix/xxx` or `feature/xxx` where `xxx` is a short description of the changes or feature you are attempting to add. For example `fix/email-login` would be a branch where you fix something specific to email login. #### Adding Your Branch To create a branch on your local machine (and switch to this branch): ```shell $ git checkout -b [name_of_your_new_branch] ``` and to push to GitHub: ```shell $ git push origin [name_of_your_new_branch] ``` **If you need more help with branching, take a look at [this](https://github.com/Kunena/Kunena-Forum/wiki/Create-a-new-branch-with-git-and-manage-branches).** ### Set Up Linting You should have [ESLint running in your editor](http://eslint.org/docs/user-guide/integrations.html), and it will highlight anything doesn't conform to [freeCodeCamp's JavaScript Style Guide](http://forum.freecodecamp.org/t/free-code-camp-javascript-style-guide/19121) (you can find a summary of those rules [here](https://github.com/freeCodeCamp/freeCodeCamp/blob/staging/.eslintrc)). > Please do not ignore any linting errors, as they are meant to **help** you and to ensure a clean and simple code base. ### Set Up MailHog To be able to create a user and log into your development copy, you need to set up MailHog. MailHog is a local SMTP mail server that will catch the emails your freeCodeCamp instance is sending. How you install and run MailHog is dependent upon your OS. - [MacOS](#macos) - [Windows](#windows) - [Linux](#linux) - [Using MailHog](#using-mailhog) #### macOS Here is how to set up MailHog on macOS with [Homebrew](https://brew.sh/): ```bash brew install mailhog brew services start mailhog ``` #### Windows Download the latest MailHog version from [MailHog's official repository](https://github.com/mailhog/MailHog/releases). Click on the link for your Windows version (32 or 64 bit) and .exe file will be downloaded to your computer. Once it finishes downloading, click on the file. You will probably get a Windows firewall notification where you will have to allow access to MailHog. Once you do, a standard Windows command line prompt will open with MailHog already running. To close MailHog, close the command prompt. To run it again, click on the same .exe file. You don't need to download a new one. #### Linux First install Go. For Debian-based systems like Ubuntu and Linux Mint, run: ```bash sudo apt-get install golang ``` For CentOS, Fedora, Red Hat Linux, and other RPM-based systems, run: ```bash sudo dnf install golang ``` Or: ```bash sudo yum install golang ``` Set the path for Go: ```bash echo "export GOPATH=$HOME/go" >> ~/.profile echo 'export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin' >> ~/.profile source ~/.profile ``` Then install and run MailHog: ```bash go get github.com/mailhog/MailHog sudo cp /home/$(whoami)/go/bin/MailHog /usr/local/bin/mailhog mailhog ``` #### Using MailHog Once you have installed MailHog and started it running you need to open your MailHog inbox in your browser, open a new tab or window and navigate to [http://localhost:8025](http://localhost:8025). You should now see a screen like below: ![MailHog Screenshot 1](docs/images/1.jpg) When your freeCodeCamp installation sends an email you will see it appear here. Like below: ![MailHog Screenshot 2](docs/images/2.jpg) Open the mail and you should see two tabs where you can view the content - plain text and source. Make sure you are on the plain text tab. ![MailHog Screenshot 3](docs/images/3.jpg) Any links in the email should be clickable. For any other questions related to MailHog or for instructions on custom configurations, check out the [MailHog](https://github.com/mailhog/MailHog) repository. ### Set Up freeCodeCamp Once you have freeCodeCamp cloned, before you start the application, you first need to install all of the dependencies: ```bash # Install NPM dependencies npm install ``` Then you need to add the private environment variables (API Keys): ```bash # Create a copy of the "sample.env" and name it as ".env". # Populate it with the necessary API keys and secrets: # macOS / Linux cp sample.env .env # Windows copy sample.env .env ``` Then edit the `.env` file and modify the API keys only for services that you will use. Note: Not all keys are required, to run the app locally, however `MONGOHQ_URL` is the most important one. Unless you have MongoDB running in a setup different than the defaults, the URL in the sample.env should work fine. You can leave the other keys as they are. Keep in mind if you want to use more services you'll have to get your own API keys for those services and edit those entries accordingly in the .env file. Now you will need to start MongoDB, and then seed the database, then you can start the application: ```bash # Start the mongo server in a separate terminal # On OS X: mongod # If you are using Windows, you have to instead specify the full path to the mongod binary # Make sure to replace 3.4 with the version you have installed "C:\Program Files\MongoDB\Server\3.4\bin\mongod" # Initialize freeCodeCamp # This will seed the database for the first time. # This command should only be run once. npm run only-once # Start the application without a backend server npm run develop # If you require the backend server to be operational (persisted user interations/api calls) # Use this command instead # Note: This command requires that you have a correctly seeded mongodb instance running # Note: If you are runnoing the backend server inside a docker container, use the command above npm run develop-server ``` Now navigate to your browser and open <http://localhost:8000>. If the app loads, congratulations – you're all set. Otherwise, let us know by asking in the [Contributors chat room](https://gitter.im/FreeCodeCamp/Contributors) on Gitter. There might be an error in the console of your browser or in Bash / Terminal / Command Line that will help identify the problem. If the app launches but you are encountering errors with the UI itself, for example if fonts are not being loaded or if the code editor is not displaying properly, you may try the following: ```bash # Remove all installed node modules rm -rf node_modules # Reinstall npm packages npm install # Seed the database node seed # Re-start the application npm run develop ``` ### Setup freeCodeCamp using Docker #### Isolated Use this if you just want to work on freeCodeCamp. You will need to have [docker](https://docs.docker.com/install/) and [docker-compose](https://docs.docker.com/compose/install/) installed before executing the commands below. Setup: ```bash docker-compose run --rm freecodecamp npm install docker-compose run --rm freecodecamp npm run only-once ``` Run: ```bash docker-compose up ``` #### Shared Use this if you want to work on other services that will run alongside of freeCodeCamp, using the database directly. An example is the [open-api](https://github.com/freeCodeCamp/open-api) project. ```bash docker-compose -f docker-compose.yml -f docker-compose-shared.yml up ``` ### Creating a New User To create a new user, you will need to perform the following steps: - run MailHog if you haven't set up yet check [set-up-mailhog](#set-up-mailhog) - run `npm run develop` and navigated to [http://localhost:8000](http://localhost:8000/) - Click over the Sign-Up link situated on the right corner of the navigation bar. - Write your email over the input and press the button "get a sign in link" this will send an email with the login URL into MailHog. - The last step is to check your inbox in MailHog for a new email from "[email protected]" click over the URL inside of it you will be redirected and logged in into the app. ### Make Changes This bit is up to you! #### How to find the code in the freeCodeCamp codebase to fix/edit The best way to find out any code you wish to change/add or remove is using the GitHub search bar at the top of the repository page. For example, you could search for a challenge name and the results will display all the files along with line numbers. Then you can proceed to the files and verify this is the area that you were looking forward to edit. Always feel free to reach out to the chat room when you are not certain of any thing specific in the code. ### Run The Test Suite When you're ready to share your code, run the test suite: ```shell $ npm test ``` and ensure all tests pass. ### Creating a Pull Request #### What is a Pull Request? A pull request (PR) is a method of submitting proposed changes to the freeCodeCamp repo (or any repo, for that matter). You will make changes to copies of the files which make up freeCodeCamp in a personal fork, then apply to have them accepted by freeCodeCamp proper. #### Need Help? freeCodeCamp Issue Mods and staff are on hand to assist with Pull Request related issues in our [Contributors chat room](https://gitter.im/FreeCodeCamp/Contributors). #### Important: ALWAYS EDIT ON A BRANCH Take away only one thing from this document: Never, **EVER** make edits to the `staging` branch. ALWAYS make a new branch BEFORE you edit files. This is critical, because if your PR is not accepted, your copy of staging will be forever sullied and the only way to fix it is to delete your fork and re-fork. #### Methods There are two methods of creating a pull request for freeCodeCamp: - Editing files on a local clone (recommended) - Editing files via the GitHub Interface ##### Method 1: Editing via your Local Fork _(Recommended)_ This is the recommended method. Read about [How to Setup and Maintain a Local Instance of freeCodeCamp](#maintaining-your-fork). 1. Perform the maintenance step of rebasing `staging`. 2. Ensure you are on the `staging` branch using `git status`: $ git status On branch staging Your branch is up-to-date with 'origin/staging'. nothing to commit, working directory clean 3. If you are not on staging or your working directory is not clean, resolve any outstanding files/commits and checkout staging `git checkout staging` 4. Create a branch off of `staging` with git: `git checkout -B branch/name-here` **Note:** Branch naming is important. Use a name like `fix/short-fix-description` or `feature/short-feature-description`. 5. Edit your file(s) locally with the editor of your choice. 6. Check your `git status` to see unstaged files. 7. Add your edited files: `git add path/to/filename.ext` You can also do: `git add .` to add all unstaged files. Take care, though, because you can accidentally add files you don't want added. Review your `git status` first. 8. Commit your edits: We have a [tool](https://commitizen.github.io/cz-cli/) that helps you to make standard commit messages. Execute `npm run commit` and follow the steps. 9. [Squash your commits](http://forum.freecodecamp.org/t/how-to-squash-multiple-commits-into-one-with-git/13231) if there are more than one. 10. If you would want to add/remove changes to previous commit, add the files as in Step 5 earlier, and use `git commit --amend` or `git commit --amend --no-edit` (for keeping the same commit message). 11. Push your commits to your GitHub Fork: `git push origin branch/name-here` 12. Go to [Common Steps](#common-steps) ##### Method 2: Editing via the GitHub Interface Note: Editing via the GitHub Interface is not recommended, since it is not possible to update your fork via GitHub's interface without deleting and recreating your fork. Read the [Wiki article](http://forum.freecodecamp.org/t/how-to-make-a-pull-request-on-free-code-camp/19114) for further information ### Common Steps 1. Once the edits have been committed, you will be prompted to create a pull request on your fork's GitHub Page. 2. By default, all pull requests should be against the freeCodeCamp main repo, `staging` branch. **Make sure that your Base Fork is set to freeCodeCamp/freeCodeCamp when raising a Pull Request.** ![fork-instructions](./docs/images/fork-instructions.png) 3. Submit a [pull request](http://forum.freecodecamp.org/t/how-to-contribute-via-a-pull-request/19368) from your branch to freeCodeCamp's `staging` branch. 4. In the body of your PR include a more detailed summary of the changes you made and why. - If the PR is meant to fix an existing bug/issue then, at the end of your PR's description, append the keyword `closes` and #xxxx (where xxxx is the issue number). Example: `closes #1337`. This tells GitHub to close the existing issue, if the PR is merged. 5. Indicate if you have tested on a local copy of the site or not. ### How We Review and Merge Pull Requests freeCodeCamp has a team of volunteer Issue Moderators. These Issue Moderators routinely go through open pull requests in a process called [Quality Assurance](https://en.wikipedia.org/wiki/Quality_assurance) (QA). 1. If an Issue Moderator QA's a pull request and confirms that the new code does what it is supposed without seeming to introduce any new bugs, they will comment "LGTM" which means "Looks good to me." 2. Another Issue Moderator will QA the same pull request. Once they have also confirmed that the new code does what it is supposed to without seeming to introduce any new bugs, they will merge the pull request. If you would like to apply to join our Issue Moderator team, message [@quincylarson](https://gitter.im/quincylarson) with links to 5 of your pull requests that have been accepted and 5 issues where you have helped someone else through commenting or QA'ing. ### How We Close Stale Issues We will close any issues or pull requests that have been inactive for more than 15 days, except those that match the following criteria: - bugs that are confirmed - pull requests that are waiting on other pull requests to be merged - features that are a part of a GitHub project ### Next Steps #### If your PR is accepted Once your PR is accepted, you may delete the branch you created to submit it. This keeps your working fork clean. You can do this with a press of a button on the GitHub PR interface. You can delete the local copy of the branch with: `git branch -D branch/to-delete-name` #### If your PR is rejected Don't despair! You should receive solid feedback from the Issue Moderators as to why it was rejected and what changes are needed. Many Pull Requests, especially first Pull Requests, require correction or updating. If you have used the GitHub interface to create your PR, you will need to close your PR, create a new branch, and re-submit. If you have a local copy of the repo, you can make the requested changes and amend your commit with: `git commit --amend` This will update your existing commit. When you push it to your fork you will need to do a force push to overwrite your old commit: `git push --force` Be sure to post in the PR conversation that you have made the requested changes. ### Other Resources - Bugs and Issues: - [Searching for Your Issue on GitHub](http://forum.freecodecamp.org/t/searching-for-existing-issues/19139) - [Creating a New GitHub Issue](http://forum.freecodecamp.org/t/creating-a-new-github-issue/18392) - [Select Issues for Contributing Using Labels](http://forum.freecodecamp.org/t/free-code-camp-issue-labels/19556) - Miscellaneous: - [How to clone the freeCodeCamp website on a Windows PC](http://forum.freecodecamp.org/t/how-to-clone-and-setup-the-free-code-camp-website-on-a-windows-pc/19366) - [How to log in to your local freeCodeCamp site using GitHub](http://forum.freecodecamp.org/t/how-to-log-in-to-your-local-instance-of-free-code-camp/19552) - [Writing great git commit messages](http://forum.freecodecamp.org/t/writing-good-git-commit-messages/13210) - [Contributor Chat Support](https://gitter.im/FreeCodeCamp/Contributors) - for the freeCodeCamp repositories, and running a local instance
CONTRIBUTING.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00047575385542586446, 0.0001784955384209752, 0.00016294153465423733, 0.0001693017256911844, 0.00005031870387028903 ]
{ "id": 0, "code_window": [ "import loopback from 'loopback';\n", "import _ from 'lodash';\n", "import jwt from 'jsonwebtoken';\n", "import generate from 'nanoid/generate';\n", "\n", "import { homeLocation } from '../../config/env';\n", "\n", "import { fixCompletedChallengeItem } from '../utils';\n", "import { themes } from '../utils/themes';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { homeLocation, apiLocation } from '../../config/env';\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 19 }
import { Observable } from 'rx'; export default function(Block) { Block.on('dataSourceAttached', () => { Block.findOne$ = Observable.fromNodeCallback(Block.findOne, Block); Block.findById$ = Observable.fromNodeCallback(Block.findById, Block); Block.find$ = Observable.fromNodeCallback(Block.find, Block); }); }
common/models/block.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00017498542729299515, 0.00017438683426007628, 0.00017378822667524219, 0.00017438683426007628, 5.986003088764846e-7 ]
{ "id": 1, "code_window": [ " `;\n", " }\n", " const { id: loginToken, created: emailAuthLinkTTL } = token;\n", " const loginEmail = this.getEncodedEmail(newEmail ? newEmail : null);\n", " const host = homeLocation;\n", " const mailOptions = {\n", " type: 'email',\n", " to: newEmail ? newEmail : this.email,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const host = apiLocation;\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 598 }
module.exports = { homeLocation: process.env.HOME_LOCATION };
config/env.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.0009448161581531167, 0.0009448161581531167, 0.0009448161581531167, 0.0009448161581531167, 0 ]
{ "id": 1, "code_window": [ " `;\n", " }\n", " const { id: loginToken, created: emailAuthLinkTTL } = token;\n", " const loginEmail = this.getEncodedEmail(newEmail ? newEmail : null);\n", " const host = homeLocation;\n", " const mailOptions = {\n", " type: 'email',\n", " to: newEmail ? newEmail : this.email,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const host = apiLocation;\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 598 }
// // Popovers // -------------------------------------------------- .popover { position: absolute; top: 0; left: 0; z-index: @zindex-popover; display: none; max-width: @popover-max-width; padding: 1px; // Reset font and text propertes given new insertion method font-size: @font-size-base; font-weight: normal; line-height: @line-height-base; text-align: left; background-color: @popover-bg; background-clip: padding-box; border: 1px solid @popover-fallback-border-color; border: 1px solid @popover-border-color; border-radius: @border-radius-large; .box-shadow(0 5px 10px rgba(0,0,0,.2)); // Overrides for proper insertion white-space: normal; // Offset the popover to account for the popover arrow &.top { margin-top: -@popover-arrow-width; } &.right { margin-left: @popover-arrow-width; } &.bottom { margin-top: @popover-arrow-width; } &.left { margin-left: -@popover-arrow-width; } } .popover-title { margin: 0; // reset heading margin padding: 8px 14px; font-size: @font-size-base; background-color: @popover-title-bg; border-bottom: 1px solid darken(@popover-title-bg, 5%); border-radius: (@border-radius-large - 1) (@border-radius-large - 1) 0 0; } .popover-content { padding: 9px 14px; } // Arrows // // .arrow is outer, .arrow:after is inner .popover > .arrow { &, &:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } } .popover > .arrow { border-width: @popover-arrow-outer-width; } .popover > .arrow:after { border-width: @popover-arrow-width; content: ""; } .popover { &.top > .arrow { left: 50%; margin-left: -@popover-arrow-outer-width; border-bottom-width: 0; border-top-color: @popover-arrow-outer-fallback-color; // IE8 fallback border-top-color: @popover-arrow-outer-color; bottom: -@popover-arrow-outer-width; &:after { content: " "; bottom: 1px; margin-left: -@popover-arrow-width; border-bottom-width: 0; border-top-color: @popover-arrow-color; } } &.right > .arrow { top: 50%; left: -@popover-arrow-outer-width; margin-top: -@popover-arrow-outer-width; border-left-width: 0; border-right-color: @popover-arrow-outer-fallback-color; // IE8 fallback border-right-color: @popover-arrow-outer-color; &:after { content: " "; left: 1px; bottom: -@popover-arrow-width; border-left-width: 0; border-right-color: @popover-arrow-color; } } &.bottom > .arrow { left: 50%; margin-left: -@popover-arrow-outer-width; border-top-width: 0; border-bottom-color: @popover-arrow-outer-fallback-color; // IE8 fallback border-bottom-color: @popover-arrow-outer-color; top: -@popover-arrow-outer-width; &:after { content: " "; top: 1px; margin-left: -@popover-arrow-width; border-top-width: 0; border-bottom-color: @popover-arrow-color; } } &.left > .arrow { top: 50%; right: -@popover-arrow-outer-width; margin-top: -@popover-arrow-outer-width; border-right-width: 0; border-left-color: @popover-arrow-outer-fallback-color; // IE8 fallback border-left-color: @popover-arrow-outer-color; &:after { content: " "; right: 1px; border-right-width: 0; border-left-color: @popover-arrow-color; bottom: -@popover-arrow-width; } } }
client/less/lib/bootstrap/popovers.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.000178258225787431, 0.00017342418141197413, 0.0001692099031060934, 0.0001729499053908512, 0.000002496755314496113 ]
{ "id": 1, "code_window": [ " `;\n", " }\n", " const { id: loginToken, created: emailAuthLinkTTL } = token;\n", " const loginEmail = this.getEncodedEmail(newEmail ? newEmail : null);\n", " const host = homeLocation;\n", " const mailOptions = {\n", " type: 'email',\n", " to: newEmail ? newEmail : this.email,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const host = apiLocation;\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 598 }
import { Observable } from 'rx'; import { combineEpics, ofType } from 'redux-epic'; import { pick } from 'lodash'; import { types, refetchCompletedChallenges, updateUserBackendComplete, updateMyPortfolioComplete, updateMyProfileUIComplete } from './'; import { makeToast } from '../../../Toasts/redux'; import { doActionOnError, usernameSelector, userSelector, createErrorObservable } from '../../../redux'; import { updateUserEmail, updateMultipleUserFlags, regresPortfolio, optoUpdatePortfolio, updateLocalProfileUI } from '../../../entities'; import { postJSON$ } from '../../../../utils/ajax-stream'; const endpoints = { email: '/update-my-email', projects: '/update-my-projects', username: '/update-my-username' }; function backendUserUpdateEpic(actions$, { getState }) { const start = actions$::ofType(types.updateUserBackend.start); const server = start .flatMap(({ payload }) => { const userMap = userSelector(getState()); const { username } = userMap; const flagsToCheck = Object.keys(payload); const valuesToCheck = pick(userMap, flagsToCheck); const oldValues = { ...flagsToCheck.reduce((accu, current) => ({ ...accu, [current]: '' })), ...valuesToCheck }; const valuesToUpdate = flagsToCheck.reduce((accu, current) => { if (payload[current] !== valuesToCheck[current]) { return { ...accu, [current]: payload[current] }; } return accu; }, {}); if (!Object.keys(valuesToUpdate).length) { return Observable.of( makeToast({ message: 'No changes in settings detected' }) ); } const { app: { csrfToken: _csrf } } = getState(); let body = { _csrf }; let endpoint = '/update-flags'; const updateKeys = Object.keys(valuesToUpdate); if (updateKeys.length === 1 && updateKeys[0] in endpoints) { // there is a specific route for this update const flag = updateKeys[0]; endpoint = endpoints[flag]; body = { ...body, [flag]: valuesToUpdate[flag] }; } else { body = { ...body, values: valuesToUpdate }; } return postJSON$(endpoint, body) .map(updateUserBackendComplete) .catch( doActionOnError( () => updateMultipleUserFlags({ username, flags: oldValues }) ) ); }); const optimistic = start .flatMap(({ payload }) => { const username = usernameSelector(getState()); return Observable.of( updateMultipleUserFlags({ username, flags: payload }) ); }); const complete = actions$::ofType(types.updateUserBackend.complete) .flatMap(({ payload: { message } }) => Observable.if( () => message.includes('project'), Observable.of(refetchCompletedChallenges(), makeToast({ message })), Observable.of(makeToast({ message })) ) ); return Observable.merge(server, optimistic, complete); } function refetchCompletedChallengesEpic(actions$, { getState }) { return actions$::ofType(types.refetchCompletedChallenges.start) .flatMap(() => { const { app: { csrfToken: _csrf } } = getState(); const username = usernameSelector(getState()); return postJSON$('/refetch-user-completed-challenges', { _csrf }) .map(({ completedChallenges }) => updateMultipleUserFlags({ username, flags: { completedChallenges } }) ) .catch(createErrorObservable); }); } function updateMyPortfolioEpic(actions$, { getState }) { const edit = actions$::ofType(types.updateMyPortfolio.start); const remove = actions$::ofType(types.deletePortfolio.start); const serverEdit = edit .flatMap(({ payload }) => { const { id } = payload; const { app: { csrfToken: _csrf, username } } = getState(); return postJSON$('/update-my-portfolio', { _csrf, portfolio: payload }) .map(updateMyPortfolioComplete) .catch(doActionOnError(() => regresPortfolio({ username, id }))); }); const optimisticEdit = edit .map(({ payload }) => { const username = usernameSelector(getState()); return optoUpdatePortfolio({ username, portfolio: payload }); }); const complete = actions$::ofType(types.updateMyPortfolio.complete) .flatMap(({ payload: { message } }) => Observable.of(makeToast({ message })) ); const serverRemove = remove .flatMap(({ payload: { portfolio } }) => { const { app: { csrfToken: _csrf } } = getState(); return postJSON$('/update-my-portfolio', { _csrf, portfolio }) .map(updateMyPortfolioComplete) .catch( doActionOnError( () => makeToast({ message: 'Something went wrong removing a portfolio item.' }) ) ); }); const optimisticRemove = remove .flatMap(({ payload: { portfolio: { id } } }) => { const username = usernameSelector(getState()); return Observable.of(regresPortfolio({ username, id })); }); return Observable.merge( serverEdit, optimisticEdit, complete, serverRemove, optimisticRemove ); } function updateUserEmailEpic(actions, { getState }) { return actions::ofType(types.updateMyEmail) .flatMap(({ payload: email }) => { const { app: { user: username, csrfToken: _csrf }, entities: { user: userMap } } = getState(); const { email: oldEmail } = userMap[username] || {}; const body = { _csrf, email }; const optimisticUpdate = Observable.just( updateUserEmail(username, email) ); const ajaxUpdate = postJSON$('/update-my-email', body) .catch(doActionOnError(() => oldEmail ? updateUserEmail(username, oldEmail) : null )) .filter(Boolean); return Observable.merge(optimisticUpdate, ajaxUpdate); }); } function updateMyProfileUIEpic(action$, { getState }) { const toggle = action$::ofType(types.updateMyProfileUI.start); const server = toggle.flatMap(({payload: { profileUI }}) => { const state = getState(); const { csrfToken: _csrf } = state.app; const username = usernameSelector(state); const oldUI = { ...userSelector(state).profileUI }; return postJSON$('/update-my-profile-ui', { _csrf, profileUI }) .map(updateMyProfileUIComplete) .catch( doActionOnError( () => Observable.of( makeToast({ message: 'Something went wrong saving your privacy settings, ' + 'please try again.' }), updateLocalProfileUI({username, profileUI: oldUI }) ) ) ); }); const optimistic = toggle.flatMap(({payload: { profileUI }}) => { const username = usernameSelector(getState()); return Observable.of(updateLocalProfileUI({username, profileUI})); }); return Observable.merge(server, optimistic); } export default combineEpics( backendUserUpdateEpic, refetchCompletedChallengesEpic, updateMyPortfolioEpic, updateUserEmailEpic, updateMyProfileUIEpic );
common/app/routes/Settings/redux/update-user-epic.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.0001754987461026758, 0.00017241512250620872, 0.00016648044402245432, 0.00017319666221737862, 0.0000025576835014362587 ]
{ "id": 1, "code_window": [ " `;\n", " }\n", " const { id: loginToken, created: emailAuthLinkTTL } = token;\n", " const loginEmail = this.getEncodedEmail(newEmail ? newEmail : null);\n", " const host = homeLocation;\n", " const mailOptions = {\n", " type: 'email',\n", " to: newEmail ? newEmail : this.email,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const host = apiLocation;\n" ], "file_path": "common/models/user.js", "type": "replace", "edit_start_line_idx": 598 }
import { Observable } from 'rx'; import { ofType } from 'redux-epic'; import { fetchMessagesComplete, fetchMessagesError } from './'; import { types as app } from '../../redux'; import { getJSON$ } from '../../../utils/ajax-stream.js'; export default function getMessagesEpic(actions) { return actions::ofType(app.appMounted) .flatMap(() => getJSON$('/api/users/get-messages') .map(fetchMessagesComplete) .catch(err => Observable.of(fetchMessagesError(err))) ); }
common/app/Flash/redux/get-messages-epic.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00017542095156386495, 0.00017537538951728493, 0.0001753298274707049, 0.00017537538951728493, 4.556204658001661e-8 ]
{ "id": 2, "code_window": [ "module.exports = {\n", " homeLocation: process.env.HOME_LOCATION\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " homeLocation: process.env.HOME_LOCATION,\n", " apiLocation: process.env.API_LOCATION\n" ], "file_path": "config/env.js", "type": "replace", "edit_start_line_idx": 1 }
module.exports = { homeLocation: process.env.HOME_LOCATION };
config/env.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.996624231338501, 0.996624231338501, 0.996624231338501, 0.996624231338501, 0 ]
{ "id": 2, "code_window": [ "module.exports = {\n", " homeLocation: process.env.HOME_LOCATION\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " homeLocation: process.env.HOME_LOCATION,\n", " apiLocation: process.env.API_LOCATION\n" ], "file_path": "config/env.js", "type": "replace", "edit_start_line_idx": 1 }
import { Observable } from 'rx'; import MouseTrap from 'mousetrap'; import { push } from 'redux-first-router'; import { toggleNightMode, hardGoTo } from '../../common/app/redux'; import { aboutUrl, donateUrl, forumUrl, githubUrl } from '../../common/utils/constantStrings.json'; function bindKey(key, actionCreator) { return Observable.fromEventPattern( h => MouseTrap.bind(key, h), h => MouseTrap.unbind(key, h) ) .map(actionCreator); } const softRedirects = { 'g n n': '/challenges/next-challenge', 'g n m': '/map', 'g n o': '/settings' }; export default function mouseTrapSaga(actions) { const traps = [ ...Object.keys(softRedirects) .map(key => bindKey(key, () => push(softRedirects[key]))), bindKey( 'g n a', () => hardGoTo(aboutUrl) ), bindKey( 'g n r', () => hardGoTo(githubUrl) ), bindKey( 'g n d', () => hardGoTo(donateUrl) ), bindKey( 'g n w', () => hardGoTo(forumUrl) ), bindKey('g t n', toggleNightMode) ]; return Observable.merge(traps).takeUntil(actions.last()); }
client/epics/mouse-trap-epic.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.0002504836884327233, 0.00018276041373610497, 0.00016603973926976323, 0.00017006840789690614, 0.000030336470445035957 ]
{ "id": 2, "code_window": [ "module.exports = {\n", " homeLocation: process.env.HOME_LOCATION\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " homeLocation: process.env.HOME_LOCATION,\n", " apiLocation: process.env.API_LOCATION\n" ], "file_path": "config/env.js", "type": "replace", "edit_start_line_idx": 1 }
// // Glyphicons for Bootstrap // // Since icons are fonts, they can be placed anywhere text is placed and are // thus automatically sized to match the surrounding child. To use, create an // inline element with the appropriate classes, like so: // // <a href="#"><span class="glyphicon glyphicon-star"></span> Star</a> // Import the fonts @font-face { font-family: 'Glyphicons Halflings'; src: url('@{icon-font-path}@{icon-font-name}.eot'); src: url('@{icon-font-path}@{icon-font-name}.eot?#iefix') format('embedded-opentype'), url('@{icon-font-path}@{icon-font-name}.woff') format('woff'), url('@{icon-font-path}@{icon-font-name}.ttf') format('truetype'), url('@{icon-font-path}@{icon-font-name}.svg#@{icon-font-svg-id}') format('svg'); } // Catchall baseclass .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } // Individual icons .glyphicon-asterisk { &:before { content: "\2a"; } } .glyphicon-plus { &:before { content: "\2b"; } } .glyphicon-euro, .glyphicon-eur { &:before { content: "\20ac"; } } .glyphicon-minus { &:before { content: "\2212"; } } .glyphicon-cloud { &:before { content: "\2601"; } } .glyphicon-envelope { &:before { content: "\2709"; } } .glyphicon-pencil { &:before { content: "\270f"; } } .glyphicon-glass { &:before { content: "\e001"; } } .glyphicon-music { &:before { content: "\e002"; } } .glyphicon-search { &:before { content: "\e003"; } } .glyphicon-heart { &:before { content: "\e005"; } } .glyphicon-star { &:before { content: "\e006"; } } .glyphicon-star-empty { &:before { content: "\e007"; } } .glyphicon-user { &:before { content: "\e008"; } } .glyphicon-film { &:before { content: "\e009"; } } .glyphicon-th-large { &:before { content: "\e010"; } } .glyphicon-th { &:before { content: "\e011"; } } .glyphicon-th-list { &:before { content: "\e012"; } } .glyphicon-ok { &:before { content: "\e013"; } } .glyphicon-remove { &:before { content: "\e014"; } } .glyphicon-zoom-in { &:before { content: "\e015"; } } .glyphicon-zoom-out { &:before { content: "\e016"; } } .glyphicon-off { &:before { content: "\e017"; } } .glyphicon-signal { &:before { content: "\e018"; } } .glyphicon-cog { &:before { content: "\e019"; } } .glyphicon-trash { &:before { content: "\e020"; } } .glyphicon-home { &:before { content: "\e021"; } } .glyphicon-file { &:before { content: "\e022"; } } .glyphicon-time { &:before { content: "\e023"; } } .glyphicon-road { &:before { content: "\e024"; } } .glyphicon-download-alt { &:before { content: "\e025"; } } .glyphicon-download { &:before { content: "\e026"; } } .glyphicon-upload { &:before { content: "\e027"; } } .glyphicon-inbox { &:before { content: "\e028"; } } .glyphicon-play-circle { &:before { content: "\e029"; } } .glyphicon-repeat { &:before { content: "\e030"; } } .glyphicon-refresh { &:before { content: "\e031"; } } .glyphicon-list-alt { &:before { content: "\e032"; } } .glyphicon-lock { &:before { content: "\e033"; } } .glyphicon-flag { &:before { content: "\e034"; } } .glyphicon-headphones { &:before { content: "\e035"; } } .glyphicon-volume-off { &:before { content: "\e036"; } } .glyphicon-volume-down { &:before { content: "\e037"; } } .glyphicon-volume-up { &:before { content: "\e038"; } } .glyphicon-qrcode { &:before { content: "\e039"; } } .glyphicon-barcode { &:before { content: "\e040"; } } .glyphicon-tag { &:before { content: "\e041"; } } .glyphicon-tags { &:before { content: "\e042"; } } .glyphicon-book { &:before { content: "\e043"; } } .glyphicon-bookmark { &:before { content: "\e044"; } } .glyphicon-print { &:before { content: "\e045"; } } .glyphicon-camera { &:before { content: "\e046"; } } .glyphicon-font { &:before { content: "\e047"; } } .glyphicon-bold { &:before { content: "\e048"; } } .glyphicon-italic { &:before { content: "\e049"; } } .glyphicon-text-height { &:before { content: "\e050"; } } .glyphicon-text-width { &:before { content: "\e051"; } } .glyphicon-align-left { &:before { content: "\e052"; } } .glyphicon-align-center { &:before { content: "\e053"; } } .glyphicon-align-right { &:before { content: "\e054"; } } .glyphicon-align-justify { &:before { content: "\e055"; } } .glyphicon-list { &:before { content: "\e056"; } } .glyphicon-indent-left { &:before { content: "\e057"; } } .glyphicon-indent-right { &:before { content: "\e058"; } } .glyphicon-facetime-video { &:before { content: "\e059"; } } .glyphicon-picture { &:before { content: "\e060"; } } .glyphicon-map-marker { &:before { content: "\e062"; } } .glyphicon-adjust { &:before { content: "\e063"; } } .glyphicon-tint { &:before { content: "\e064"; } } .glyphicon-edit { &:before { content: "\e065"; } } .glyphicon-share { &:before { content: "\e066"; } } .glyphicon-check { &:before { content: "\e067"; } } .glyphicon-move { &:before { content: "\e068"; } } .glyphicon-step-backward { &:before { content: "\e069"; } } .glyphicon-fast-backward { &:before { content: "\e070"; } } .glyphicon-backward { &:before { content: "\e071"; } } .glyphicon-play { &:before { content: "\e072"; } } .glyphicon-pause { &:before { content: "\e073"; } } .glyphicon-stop { &:before { content: "\e074"; } } .glyphicon-forward { &:before { content: "\e075"; } } .glyphicon-fast-forward { &:before { content: "\e076"; } } .glyphicon-step-forward { &:before { content: "\e077"; } } .glyphicon-eject { &:before { content: "\e078"; } } .glyphicon-chevron-left { &:before { content: "\e079"; } } .glyphicon-chevron-right { &:before { content: "\e080"; } } .glyphicon-plus-sign { &:before { content: "\e081"; } } .glyphicon-minus-sign { &:before { content: "\e082"; } } .glyphicon-remove-sign { &:before { content: "\e083"; } } .glyphicon-ok-sign { &:before { content: "\e084"; } } .glyphicon-question-sign { &:before { content: "\e085"; } } .glyphicon-info-sign { &:before { content: "\e086"; } } .glyphicon-screenshot { &:before { content: "\e087"; } } .glyphicon-remove-circle { &:before { content: "\e088"; } } .glyphicon-ok-circle { &:before { content: "\e089"; } } .glyphicon-ban-circle { &:before { content: "\e090"; } } .glyphicon-arrow-left { &:before { content: "\e091"; } } .glyphicon-arrow-right { &:before { content: "\e092"; } } .glyphicon-arrow-up { &:before { content: "\e093"; } } .glyphicon-arrow-down { &:before { content: "\e094"; } } .glyphicon-share-alt { &:before { content: "\e095"; } } .glyphicon-resize-full { &:before { content: "\e096"; } } .glyphicon-resize-small { &:before { content: "\e097"; } } .glyphicon-exclamation-sign { &:before { content: "\e101"; } } .glyphicon-gift { &:before { content: "\e102"; } } .glyphicon-leaf { &:before { content: "\e103"; } } .glyphicon-fire { &:before { content: "\e104"; } } .glyphicon-eye-open { &:before { content: "\e105"; } } .glyphicon-eye-close { &:before { content: "\e106"; } } .glyphicon-warning-sign { &:before { content: "\e107"; } } .glyphicon-plane { &:before { content: "\e108"; } } .glyphicon-calendar { &:before { content: "\e109"; } } .glyphicon-random { &:before { content: "\e110"; } } .glyphicon-comment { &:before { content: "\e111"; } } .glyphicon-magnet { &:before { content: "\e112"; } } .glyphicon-chevron-up { &:before { content: "\e113"; } } .glyphicon-chevron-down { &:before { content: "\e114"; } } .glyphicon-retweet { &:before { content: "\e115"; } } .glyphicon-shopping-cart { &:before { content: "\e116"; } } .glyphicon-folder-close { &:before { content: "\e117"; } } .glyphicon-folder-open { &:before { content: "\e118"; } } .glyphicon-resize-vertical { &:before { content: "\e119"; } } .glyphicon-resize-horizontal { &:before { content: "\e120"; } } .glyphicon-hdd { &:before { content: "\e121"; } } .glyphicon-bullhorn { &:before { content: "\e122"; } } .glyphicon-bell { &:before { content: "\e123"; } } .glyphicon-certificate { &:before { content: "\e124"; } } .glyphicon-thumbs-up { &:before { content: "\e125"; } } .glyphicon-thumbs-down { &:before { content: "\e126"; } } .glyphicon-hand-right { &:before { content: "\e127"; } } .glyphicon-hand-left { &:before { content: "\e128"; } } .glyphicon-hand-up { &:before { content: "\e129"; } } .glyphicon-hand-down { &:before { content: "\e130"; } } .glyphicon-circle-arrow-right { &:before { content: "\e131"; } } .glyphicon-circle-arrow-left { &:before { content: "\e132"; } } .glyphicon-circle-arrow-up { &:before { content: "\e133"; } } .glyphicon-circle-arrow-down { &:before { content: "\e134"; } } .glyphicon-globe { &:before { content: "\e135"; } } .glyphicon-wrench { &:before { content: "\e136"; } } .glyphicon-tasks { &:before { content: "\e137"; } } .glyphicon-filter { &:before { content: "\e138"; } } .glyphicon-briefcase { &:before { content: "\e139"; } } .glyphicon-fullscreen { &:before { content: "\e140"; } } .glyphicon-dashboard { &:before { content: "\e141"; } } .glyphicon-paperclip { &:before { content: "\e142"; } } .glyphicon-heart-empty { &:before { content: "\e143"; } } .glyphicon-link { &:before { content: "\e144"; } } .glyphicon-phone { &:before { content: "\e145"; } } .glyphicon-pushpin { &:before { content: "\e146"; } } .glyphicon-usd { &:before { content: "\e148"; } } .glyphicon-gbp { &:before { content: "\e149"; } } .glyphicon-sort { &:before { content: "\e150"; } } .glyphicon-sort-by-alphabet { &:before { content: "\e151"; } } .glyphicon-sort-by-alphabet-alt { &:before { content: "\e152"; } } .glyphicon-sort-by-order { &:before { content: "\e153"; } } .glyphicon-sort-by-order-alt { &:before { content: "\e154"; } } .glyphicon-sort-by-attributes { &:before { content: "\e155"; } } .glyphicon-sort-by-attributes-alt { &:before { content: "\e156"; } } .glyphicon-unchecked { &:before { content: "\e157"; } } .glyphicon-expand { &:before { content: "\e158"; } } .glyphicon-collapse-down { &:before { content: "\e159"; } } .glyphicon-collapse-up { &:before { content: "\e160"; } } .glyphicon-log-in { &:before { content: "\e161"; } } .glyphicon-flash { &:before { content: "\e162"; } } .glyphicon-log-out { &:before { content: "\e163"; } } .glyphicon-new-window { &:before { content: "\e164"; } } .glyphicon-record { &:before { content: "\e165"; } } .glyphicon-save { &:before { content: "\e166"; } } .glyphicon-open { &:before { content: "\e167"; } } .glyphicon-saved { &:before { content: "\e168"; } } .glyphicon-import { &:before { content: "\e169"; } } .glyphicon-export { &:before { content: "\e170"; } } .glyphicon-send { &:before { content: "\e171"; } } .glyphicon-floppy-disk { &:before { content: "\e172"; } } .glyphicon-floppy-saved { &:before { content: "\e173"; } } .glyphicon-floppy-remove { &:before { content: "\e174"; } } .glyphicon-floppy-save { &:before { content: "\e175"; } } .glyphicon-floppy-open { &:before { content: "\e176"; } } .glyphicon-credit-card { &:before { content: "\e177"; } } .glyphicon-transfer { &:before { content: "\e178"; } } .glyphicon-cutlery { &:before { content: "\e179"; } } .glyphicon-header { &:before { content: "\e180"; } } .glyphicon-compressed { &:before { content: "\e181"; } } .glyphicon-earphone { &:before { content: "\e182"; } } .glyphicon-phone-alt { &:before { content: "\e183"; } } .glyphicon-tower { &:before { content: "\e184"; } } .glyphicon-stats { &:before { content: "\e185"; } } .glyphicon-sd-video { &:before { content: "\e186"; } } .glyphicon-hd-video { &:before { content: "\e187"; } } .glyphicon-subtitles { &:before { content: "\e188"; } } .glyphicon-sound-stereo { &:before { content: "\e189"; } } .glyphicon-sound-dolby { &:before { content: "\e190"; } } .glyphicon-sound-5-1 { &:before { content: "\e191"; } } .glyphicon-sound-6-1 { &:before { content: "\e192"; } } .glyphicon-sound-7-1 { &:before { content: "\e193"; } } .glyphicon-copyright-mark { &:before { content: "\e194"; } } .glyphicon-registration-mark { &:before { content: "\e195"; } } .glyphicon-cloud-download { &:before { content: "\e197"; } } .glyphicon-cloud-upload { &:before { content: "\e198"; } } .glyphicon-tree-conifer { &:before { content: "\e199"; } } .glyphicon-tree-deciduous { &:before { content: "\e200"; } }
client/less/lib/bootstrap/glyphicons.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00016932014841586351, 0.00016665831208229065, 0.00016422334010712802, 0.00016673526261001825, 0.0000013245775107861846 ]
{ "id": 2, "code_window": [ "module.exports = {\n", " homeLocation: process.env.HOME_LOCATION\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " homeLocation: process.env.HOME_LOCATION,\n", " apiLocation: process.env.API_LOCATION\n" ], "file_path": "config/env.js", "type": "replace", "edit_start_line_idx": 1 }
const githubRegex = (/github/i); const providerHash = { facebook: ({ id }) => id, github: ({ username }) => username, twitter: ({ username }) => username, linkedin({ _json }) { return _json && _json.publicProfileUrl || null; }, google: ({ id }) => id }; export function getUsernameFromProvider(provider, profile) { return typeof providerHash[provider] === 'function' ? providerHash[provider](profile) : null; } // createProfileAttributes(provider: String, profile: {}) => Object export function createUserUpdatesFromProfile(provider, profile) { if (githubRegex.test(provider)) { return createProfileAttributesFromGithub(profile); } return { [getSocialProvider(provider)]: getUsernameFromProvider( getSocialProvider(provider), profile ) }; } // createProfileAttributes(profile) => profileUpdate function createProfileAttributesFromGithub(profile) { const { profileUrl: githubProfile, username, _json: { avatar_url: picture, blog: website, location, bio, name } = {} } = profile; return { name, username: username.toLowerCase(), location, bio, website, picture, githubProfile }; } export function getSocialProvider(provider) { return provider.split('-')[0]; }
server/utils/auth.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00016946729738265276, 0.00016784993931651115, 0.00016671395860612392, 0.00016764510655775666, 0.0000010626015409798129 ]
{ "id": 3, "code_window": [ "IMAGE_BASE_URL='https://s3.amazonaws.com/freecodecamp/images/'\n", "\n", "HOME_LOCATION='http://localhost:8000'\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "API_LOCATION='http://localhost:3000'" ], "file_path": "sample.env", "type": "add", "edit_start_line_idx": 22 }
/** * * Any ref to fixCompletedChallengesItem should be removed post * a db migration to fix all completedChallenges * */ import { Observable } from 'rx'; import uuid from 'uuid/v4'; import moment from 'moment'; import dedent from 'dedent'; import debugFactory from 'debug'; import { isEmail } from 'validator'; import path from 'path'; import loopback from 'loopback'; import _ from 'lodash'; import jwt from 'jsonwebtoken'; import generate from 'nanoid/generate'; import { homeLocation } from '../../config/env'; import { fixCompletedChallengeItem } from '../utils'; import { themes } from '../utils/themes'; import { saveUser, observeMethod } from '../../server/utils/rx.js'; import { blacklistedUsernames } from '../../server/utils/constants.js'; import { wrapHandledError } from '../../server/utils/create-handled-error.js'; import { getEmailSender } from '../../server/utils/url-utils.js'; import { normaliseUserFields, getProgress, publicUserProps } from '../../server/utils/publicUserProps'; const log = debugFactory('fcc:models:user'); const BROWNIEPOINTS_TIMEOUT = [1, 'hour']; const nanoidCharSet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const createEmailError = redirectTo => wrapHandledError( new Error('email format is invalid'), { type: 'info', message: 'Please check to make sure the email is a valid email address.', redirectTo } ); function destroyAll(id, Model) { return Observable.fromNodeCallback( Model.destroyAll, Model )({ userId: id }); } function buildCompletedChallengesUpdate(completedChallenges, project) { const key = Object.keys(project)[0]; const solutions = project[key]; const solutionKeys = Object.keys(solutions); const currentCompletedChallenges = [ ...completedChallenges.map(fixCompletedChallengeItem) ]; const currentCompletedProjects = currentCompletedChallenges .filter(({id}) => solutionKeys.includes(id)); const now = Date.now(); const update = solutionKeys.reduce((update, currentId) => { const indexOfCurrentId = _.findIndex( update, ({id}) => id === currentId ); const isCurrentlyCompleted = indexOfCurrentId !== -1; if (isCurrentlyCompleted) { update[indexOfCurrentId] = { ..._.find(update, ({id}) => id === currentId), solution: solutions[currentId] }; } if (!isCurrentlyCompleted) { return [ ...update, { id: currentId, solution: solutions[currentId], challengeType: 3, completedDate: now } ]; } return update; }, currentCompletedProjects); const updatedExisting = _.uniqBy( [ ...update, ...currentCompletedChallenges ], 'id' ); return { updated: updatedExisting, isNewCompletionCount: updatedExisting.length - completedChallenges.length }; } function isTheSame(val1, val2) { return val1 === val2; } const renderSignUpEmail = loopback.template(path.join( __dirname, '..', '..', 'server', 'views', 'emails', 'user-request-sign-up.ejs' )); const renderSignInEmail = loopback.template(path.join( __dirname, '..', '..', 'server', 'views', 'emails', 'user-request-sign-in.ejs' )); const renderEmailChangeEmail = loopback.template(path.join( __dirname, '..', '..', 'server', 'views', 'emails', 'user-request-update-email.ejs' )); function getAboutProfile({ username, githubProfile: github, progressTimestamps = [], bio }) { return { username, github, browniePoints: progressTimestamps.length, bio }; } function nextTick(fn) { return process.nextTick(fn); } function getWaitPeriod(ttl) { const fiveMinutesAgo = moment().subtract(5, 'minutes'); const lastEmailSentAt = moment(new Date(ttl || null)); const isWaitPeriodOver = ttl ? lastEmailSentAt.isBefore(fiveMinutesAgo) : true; if (!isWaitPeriodOver) { const minutesLeft = 5 - (moment().minutes() - lastEmailSentAt.minutes()); return minutesLeft; } return 0; } function getWaitMessage(ttl) { const minutesLeft = getWaitPeriod(ttl); if (minutesLeft <= 0) { return null; } const timeToWait = minutesLeft ? `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}` : 'a few seconds'; return dedent` Please wait ${timeToWait} to resend an authentication link. `; } module.exports = function(User) { // set salt factor for passwords User.settings.saltWorkFactor = 5; // set user.rand to random number User.definition.rawProperties.rand.default = User.definition.properties.rand.default = function() { return Math.random(); }; // increase user accessToken ttl to 900 days User.settings.ttl = 900 * 24 * 60 * 60 * 1000; // username should not be in blacklist User.validatesExclusionOf('username', { in: blacklistedUsernames, message: 'is taken' }); // username should be unique User.validatesUniquenessOf('username'); User.settings.emailVerificationRequired = false; User.on('dataSourceAttached', () => { User.findOne$ = Observable.fromNodeCallback(User.findOne, User); User.update$ = Observable.fromNodeCallback(User.updateAll, User); User.count$ = Observable.fromNodeCallback(User.count, User); User.create$ = Observable.fromNodeCallback( User.create.bind(User) ); User.prototype.createAccessToken$ = Observable.fromNodeCallback( User.prototype.createAccessToken ); }); User.observe('before save', function(ctx) { const beforeCreate = Observable.of(ctx) .filter(({ isNewInstance }) => isNewInstance) // User.create .map(({ instance }) => instance) .flatMap(user => { // note(berks): we now require all new users to supply an email // this was not always the case if ( typeof user.email !== 'string' || !isEmail(user.email) ) { throw createEmailError(); } // assign random username to new users // actual usernames will come from github // use full uuid to ensure uniqueness user.username = 'fcc' + uuid(); if (!user.externalId) { user.externalId = uuid(); } if (!user.unsubscribeId) { user.unsubscribeId = generate(nanoidCharSet, 20); } if (!user.progressTimestamps) { user.progressTimestamps = []; } if (user.progressTimestamps.length === 0) { user.progressTimestamps.push(Date.now()); } return Observable.fromPromise(User.doesExist(null, user.email)) .do(exists => { if (exists) { throw wrapHandledError( new Error('user already exists'), { redirectTo: `${homeLocation}/signin`, message: dedent` The ${user.email} email address is already associated with an account. Try signing in with it here instead. ` } ); } }); }) .ignoreElements(); const updateOrSave = Observable.of(ctx) // not new .filter(({ isNewInstance }) => !isNewInstance) .map(({ instance }) => instance) // is update or save user .filter(Boolean) .do(user => { // Some old accounts will not have emails associated with theme // we verify only if the email field is populated if (user.email && !isEmail(user.email)) { throw createEmailError(); } user.username = user.username.trim().toLowerCase(); user.email = typeof user.email === 'string' ? user.email.trim().toLowerCase() : user.email; if (!user.progressTimestamps) { user.progressTimestamps = []; } if (user.progressTimestamps.length === 0) { user.progressTimestamps.push(Date.now()); } if (!user.externalId) { user.externalId = uuid(); } if (!user.unsubscribeId) { user.unsubscribeId = generate(nanoidCharSet, 20); } }) .ignoreElements(); return Observable.merge(beforeCreate, updateOrSave) .toPromise(); }); // remove lingering user identities before deleting user User.observe('before delete', function(ctx, next) { const UserIdentity = User.app.models.UserIdentity; const UserCredential = User.app.models.UserCredential; log('removing user', ctx.where); var id = ctx.where && ctx.where.id ? ctx.where.id : null; if (!id) { return next(); } return Observable.combineLatest( destroyAll(id, UserIdentity), destroyAll(id, UserCredential), function(identData, credData) { return { identData: identData, credData: credData }; } ) .subscribe( function(data) { log('deleted', data); }, function(err) { log('error deleting user %s stuff', id, err); next(err); }, function() { log('user stuff deleted for user %s', id); next(); } ); }); log('setting up user hooks'); // overwrite lb confirm User.confirm = function(uid, token, redirectTo) { return this.findById(uid) .then(user => { if (!user) { throw wrapHandledError( new Error(`User not found: ${uid}`), { // standard oops type: 'info', redirectTo } ); } if (user.verificationToken !== token) { throw wrapHandledError( new Error(`Invalid token: ${token}`), { type: 'info', message: dedent` Looks like you have clicked an invalid link. Please sign in and request a fresh one. `, redirectTo } ); } return user.update$({ email: user.newEmail, emailVerified: true, emailVerifyTTL: null, newEmail: null, verificationToken: null }).toPromise(); }); }; function manualReload() { this.reload((err, instance) => { if (err) { throw Error('failed to reload user instance'); } Object.assign(this, instance); log('user reloaded from db'); }); } User.prototype.manualReload = manualReload; User.prototype.loginByRequest = function loginByRequest(req, res) { const { query: { emailChange } } = req; const createToken = this.createAccessToken$() .do(accessToken => { const config = { signed: !!req.signedCookies, maxAge: accessToken.ttl, domain: process.env.COOKIE_DOMAIN || 'localhost' }; if (accessToken && accessToken.id) { const jwtAccess = jwt.sign({accessToken}, process.env.JWT_SECRET); res.cookie('jwt_access_token', jwtAccess, config); res.cookie('access_token', accessToken.id, config); res.cookie('userId', accessToken.userId, config); } }); let data = { emailVerified: true, emailAuthLinkTTL: null, emailVerifyTTL: null }; if (emailChange && this.newEmail) { data = { ...data, email: this.newEmail, newEmail: null }; } const updateUser = this.update$(data); return Observable.combineLatest( createToken, updateUser, req.logIn(this), (accessToken) => accessToken, ); }; User.afterRemote('logout', function({req, res}, result, next) { const config = { signed: !!req.signedCookies, domain: process.env.COOKIE_DOMAIN || 'localhost' }; res.clearCookie('jwt_access_token', config); res.clearCookie('access_token', config); res.clearCookie('userId', config); res.clearCookie('_csrf', config); next(); }); User.doesExist = function doesExist(username, email) { if (!username && (!email || !isEmail(email))) { return Promise.resolve(false); } log('checking existence'); // check to see if username is on blacklist if (username && blacklistedUsernames.indexOf(username) !== -1) { return Promise.resolve(true); } var where = {}; if (username) { where.username = username.toLowerCase(); } else { where.email = email ? email.toLowerCase() : email; } log('where', where); return User.count(where) .then(count => count > 0); }; User.remoteMethod( 'doesExist', { description: 'checks whether a user exists using email or username', accepts: [ { arg: 'username', type: 'string' }, { arg: 'email', type: 'string' } ], returns: [ { arg: 'exists', type: 'boolean' } ], http: { path: '/exists', verb: 'get' } } ); User.about = function about(username, cb) { if (!username) { // Zalgo!! return nextTick(() => { cb(null, {}); }); } return User.findOne({ where: { username } }, (err, user) => { if (err) { return cb(err); } if (!user || user.username !== username) { return cb(null, {}); } const aboutUser = getAboutProfile(user); return cb(null, aboutUser); }); }; User.remoteMethod( 'about', { description: 'get public info about user', accepts: [ { arg: 'username', type: 'string' } ], returns: [ { arg: 'about', type: 'object' } ], http: { path: '/about', verb: 'get' } } ); User.prototype.createAuthToken = function createAuthToken({ ttl } = {}) { return Observable.fromNodeCallback( this.authTokens.create.bind(this.authTokens) )({ ttl }); }; User.prototype.createDonation = function createDonation(donation = {}) { return Observable.fromNodeCallback( this.donations.create.bind(this.donations) )(donation) .do(() => this.update$({ $set: { isDonating: true }, $push: { donationEmails: donation.email } }) ) .do(() => this.manualReload()); }; User.prototype.getEncodedEmail = function getEncodedEmail(email) { if (!email) { return null; } return Buffer(email).toString('base64'); }; User.decodeEmail = email => Buffer(email, 'base64').toString(); function requestAuthEmail(isSignUp, newEmail) { return Observable.defer(() => { const messageOrNull = getWaitMessage(this.emailAuthLinkTTL); if (messageOrNull) { throw wrapHandledError( new Error('request is throttled'), { type: 'info', message: messageOrNull } ); } // create a temporary access token with ttl for 15 minutes return this.createAuthToken({ ttl: 15 * 60 * 1000 }); }) .flatMap(token => { let renderAuthEmail = renderSignInEmail; let subject = 'Your sign in link for freeCodeCamp.org'; if (isSignUp) { renderAuthEmail = renderSignUpEmail; subject = 'Your sign in link for your new freeCodeCamp.org account'; } if (newEmail) { renderAuthEmail = renderEmailChangeEmail; subject = dedent` Please confirm your updated email address for freeCodeCamp.org `; } const { id: loginToken, created: emailAuthLinkTTL } = token; const loginEmail = this.getEncodedEmail(newEmail ? newEmail : null); const host = homeLocation; const mailOptions = { type: 'email', to: newEmail ? newEmail : this.email, from: getEmailSender(), subject, text: renderAuthEmail({ host, loginEmail, loginToken, emailChange: !!newEmail }) }; return Observable.forkJoin( User.email.send$(mailOptions), this.update$({ emailAuthLinkTTL }) ); }) .map(() => dedent` Check your email and click the link we sent you to confirm you email. ` ); } User.prototype.requestAuthEmail = requestAuthEmail; User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) { const currentEmail = this.email; const isOwnEmail = isTheSame(newEmail, currentEmail); const isResendUpdateToSameEmail = isTheSame(newEmail, this.newEmail); const isLinkSentWithinLimit = getWaitMessage(this.emailVerifyTTL); const isVerifiedEmail = this.emailVerified; if (isOwnEmail && isVerifiedEmail) { // email is already associated and verified with this account throw wrapHandledError( new Error('email is already verified'), { type: 'info', message: ` ${newEmail} is already associated with this account. You can update a new email address instead.` } ); } if (isResendUpdateToSameEmail && isLinkSentWithinLimit) { // trying to update with the same newEmail and // confirmation email is still valid throw wrapHandledError( new Error(), { type: 'info', message: dedent` We have already sent an email confirmation request to ${newEmail}. ${isLinkSentWithinLimit}` } ); } if (!isEmail('' + newEmail)) { throw createEmailError(); } // newEmail is not associated with this user, and // this attempt to change email is the first or // previous attempts have expired if ( !isOwnEmail || (isOwnEmail && !isVerifiedEmail) || (isResendUpdateToSameEmail && !isLinkSentWithinLimit) ) { const updateConfig = { newEmail, emailVerified: false, emailVerifyTTL: new Date() }; // defer prevents the promise from firing prematurely (before subscribe) return Observable.defer(() => User.doesExist(null, newEmail)) .do(exists => { if (exists && !isOwnEmail) { // newEmail is not associated with this account, // but is associated with different account throw wrapHandledError( new Error('email already in use'), { type: 'info', message: `${newEmail} is already associated with another account.` } ); } }) .flatMap(()=>{ return Observable.forkJoin( this.update$(updateConfig), this.requestAuthEmail(false, newEmail), (_, message) => message ) .doOnNext(() => this.manualReload()); }); } else { return 'Something unexpected happened whilst updating your email.'; } }; function requestCompletedChallenges() { return this.getCompletedChallenges$(); } User.prototype.requestCompletedChallenges = requestCompletedChallenges; User.prototype.requestUpdateFlags = function requestUpdateFlags(values) { const flagsToCheck = Object.keys(values); const valuesToCheck = _.pick({ ...this }, flagsToCheck); const valuesToUpdate = flagsToCheck .filter(flag => !isTheSame(values[flag], valuesToCheck[flag])); if (!valuesToUpdate.length) { return Observable.of(dedent` No property in ${JSON.stringify(flagsToCheck, null, 2)} will introduce a change in this user. ` ) .map(() => dedent`Your settings have not been updated.`); } return Observable.from(valuesToUpdate) .flatMap(flag => Observable.of({ flag, newValue: values[flag] })) .toArray() .flatMap(updates => { return Observable.forkJoin( Observable.from(updates) .flatMap(({ flag, newValue }) => { return Observable.fromPromise(User.doesExist(null, this.email)) .flatMap(() => this.update$({ [flag]: newValue })); }) ); }) .doOnNext(() => this.manualReload()) .map(() => dedent` We have successfully updated your account. `); }; User.prototype.updateMyPortfolio = function updateMyPortfolio(portfolioItem, deleteRequest) { const currentPortfolio = this.portfolio.slice(0); const pIndex = _.findIndex( currentPortfolio, p => p.id === portfolioItem.id ); let updatedPortfolio = []; if (deleteRequest) { updatedPortfolio = currentPortfolio.filter( p => p.id !== portfolioItem.id ); } else if (pIndex === -1) { updatedPortfolio = currentPortfolio.concat([ portfolioItem ]); } else { updatedPortfolio = [ ...currentPortfolio ]; updatedPortfolio[pIndex] = { ...portfolioItem }; } return this.update$({ portfolio: updatedPortfolio }) .do(() => this.manualReload()) .map(() => dedent` Your portfolio has been updated. `); }; User.prototype.updateMyProjects = function updateMyProjects(project) { const updateData = { $set: {} }; return this.getCompletedChallenges$() .flatMap(() => { const { updated, isNewCompletionCount } = buildCompletedChallengesUpdate( this.completedChallenges, project ); updateData.$set.completedChallenges = updated; if (isNewCompletionCount) { let points = []; // give points a length of isNewCompletionCount points[isNewCompletionCount - 1] = true; updateData.$push = {}; updateData.$push.progressTimestamps = { $each: points.map(() => Date.now()) }; } return this.update$(updateData); }) .doOnNext(() => this.manualReload() ) .map(() => dedent` Your projects have been updated. `); }; User.prototype.updateMyProfileUI = function updateMyProfileUI(profileUI) { const oldUI = { ...this.profileUI }; const update = { profileUI: { ...oldUI, ...profileUI } }; return this.update$(update) .doOnNext(() => this.manualReload()) .map(() => dedent` Your privacy settings have been updated. `); }; User.prototype.updateMyUsername = function updateMyUsername(newUsername) { return Observable.defer( () => { const isOwnUsername = isTheSame(newUsername, this.username); if (isOwnUsername) { return Observable.of(dedent` ${newUsername} is already associated with this account. `); } return Observable.fromPromise(User.doesExist(newUsername)); } ) .flatMap(boolOrMessage => { if (typeof boolOrMessage === 'string') { return Observable.of(boolOrMessage); } if (boolOrMessage) { return Observable.of(dedent` ${newUsername} is already associated with a different account. `); } return this.update$({ username: newUsername }) .do(() => this.manualReload()) .map(() => dedent` Your username has been updated successfully. `); }); }; function prepUserForPublish(user, profileUI) { const { about, calendar, completedChallenges, isDonating, location, name, points, portfolio, streak, username, yearsTopContributor } = user; const { isLocked = true, showAbout = false, showCerts = false, showDonation = false, showHeatMap = false, showLocation = false, showName = false, showPoints = false, showPortfolio = false, showTimeLine = false } = profileUI; if (isLocked) { return { isLocked, profileUI, username }; } return { ...user, about: showAbout ? about : '', calendar: showHeatMap ? calendar : {}, completedChallenges: showCerts && showTimeLine ? completedChallenges : [], isDonating: showDonation ? isDonating : null, location: showLocation ? location : '', name: showName ? name : '', points: showPoints ? points : null, portfolio: showPortfolio ? portfolio : [], streak: showHeatMap ? streak : {}, yearsTopContributor: yearsTopContributor }; } User.getPublicProfile = function getPublicProfile(username, cb) { return User.findOne$({ where: { username }}) .flatMap(user => { if (!user) { return Observable.of({}); } const { completedChallenges, progressTimestamps, timezone, profileUI } = user; const allUser = { ..._.pick(user, publicUserProps), isGithub: !!user.githubProfile, isLinkedIn: !!user.linkedIn, isTwitter: !!user.twitter, isWebsite: !!user.website, points: progressTimestamps.length, completedChallenges, ...getProgress(progressTimestamps, timezone), ...normaliseUserFields(user) }; const publicUser = prepUserForPublish(allUser, profileUI); return Observable.of({ entities: { user: { [user.username]: { ...publicUser } } }, result: user.username }); }) .subscribe( user => cb(null, user), cb ); }; User.remoteMethod('getPublicProfile', { accepts: { arg: 'username', type: 'string', required: true }, returns: [ { arg: 'user', type: 'object', root: true } ], http: { path: '/get-public-profile', verb: 'GET' } }); User.giveBrowniePoints = function giveBrowniePoints(receiver, giver, data = {}, dev = false, cb) { const findUser = observeMethod(User, 'findOne'); if (!receiver) { return nextTick(() => { cb( new TypeError(`receiver should be a string but got ${ receiver }`) ); }); } if (!giver) { return nextTick(() => { cb(new TypeError(`giver should be a string but got ${ giver }`)); }); } let temp = moment(); const browniePoints = temp .subtract.apply(temp, BROWNIEPOINTS_TIMEOUT) .valueOf(); const user$ = findUser({ where: { username: receiver }}); return user$ .tapOnNext((user) => { if (!user) { throw new Error(`could not find receiver for ${ receiver }`); } }) .flatMap(({ progressTimestamps = [] }) => { return Observable.from(progressTimestamps); }) // filter out non objects .filter((timestamp) => !!timestamp || typeof timestamp === 'object') // filterout timestamps older then an hour .filter(({ timestamp = 0 }) => { return timestamp >= browniePoints; }) // filter out brownie points given by giver .filter((browniePoint) => { return browniePoint.giver === giver; }) // no results means this is the first brownie point given by giver // so return -1 to indicate receiver should receive point .first({ defaultValue: -1 }) .flatMap((browniePointsFromGiver) => { if (browniePointsFromGiver === -1) { return user$.flatMap((user) => { user.progressTimestamps.push({ giver, timestamp: Date.now(), ...data }); return saveUser(user); }); } return Observable.throw( new Error(`${ giver } already gave ${ receiver } points`) ); }) .subscribe( (user) => { return cb( null, getAboutProfile(user), dev ? { giver, receiver, data } : null ); }, (e) => cb(e, null, dev ? { giver, receiver, data } : null), () => { log('brownie points assigned completed'); } ); }; User.remoteMethod( 'giveBrowniePoints', { description: 'Give this user brownie points', accepts: [ { arg: 'receiver', type: 'string', required: true }, { arg: 'giver', type: 'string', required: true }, { arg: 'data', type: 'object' }, { arg: 'debug', type: 'boolean' } ], returns: [ { arg: 'about', type: 'object' }, { arg: 'debug', type: 'object' } ], http: { path: '/give-brownie-points', verb: 'POST' } } ); User.themes = themes; User.prototype.updateTheme = function updateTheme(theme) { if (!this.constructor.themes[theme]) { const err = wrapHandledError( new Error('Theme is not valid.'), { Type: 'info', message: err.message } ); return Promise.reject(err); } return this.update$({ theme }) .doOnNext(() => this.manualReload()) .toPromise(); }; // deprecated. remove once live User.remoteMethod( 'updateTheme', { description: 'updates the users chosen theme', accepts: [ { arg: 'theme', type: 'string', required: true } ], returns: [ { arg: 'status', type: 'object' } ], http: { path: '/update-theme', verb: 'POST' } } ); // user.updateTo$(updateData: Object) => Observable[Number] User.prototype.update$ = function update$(updateData) { const id = this.getId(); const updateOptions = { allowExtendedOperators: true }; if ( !updateData || typeof updateData !== 'object' || !Object.keys(updateData).length ) { return Observable.throw(new Error( dedent` updateData must be an object with at least one key, but got ${updateData} with ${Object.keys(updateData).length} `.split('\n').join(' ') )); } return this.constructor.update$({ id }, updateData, updateOptions); }; User.prototype.getPoints$ = function getPoints$() { const id = this.getId(); const filter = { where: { id }, fields: { progressTimestamps: true } }; return this.constructor.findOne$(filter) .map(user => { this.progressTimestamps = user.progressTimestamps; return user.progressTimestamps; }); }; User.prototype.getCompletedChallenges$ = function getCompletedChallenges$() { const id = this.getId(); const filter = { where: { id }, fields: { completedChallenges: true } }; return this.constructor.findOne$(filter) .map(user => { this.completedChallenges = user.completedChallenges; return user.completedChallenges; }); }; User.getMessages = messages => Promise.resolve(messages); User.remoteMethod('getMessages', { http: { verb: 'get', path: '/get-messages' }, accepts: { arg: 'messages', type: 'object', http: ctx => ctx.req.flash() }, returns: [ { arg: 'messages', type: 'object', root: true } ] }); };
common/models/user.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.3535957634449005, 0.00316884508356452, 0.0001638524845475331, 0.0001699550193734467, 0.03239699453115463 ]
{ "id": 3, "code_window": [ "IMAGE_BASE_URL='https://s3.amazonaws.com/freecodecamp/images/'\n", "\n", "HOME_LOCATION='http://localhost:8000'\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "API_LOCATION='http://localhost:3000'" ], "file_path": "sample.env", "type": "add", "edit_start_line_idx": 22 }
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="600.000000pt" height="600.000000pt" viewBox="0 0 600.000000 600.000000" preserveAspectRatio="xMidYMid meet"> <metadata> Created by potrace 1.15, written by Peter Selinger 2001-2017 </metadata> <g transform="translate(0.000000,600.000000) scale(0.100000,-0.100000)" fill="#006400" stroke="none"> <path d="M0 3000 l0 -3000 3000 0 3000 0 0 3000 0 3000 -3000 0 -3000 0 0 -3000z m1565 1504 c13 -8 28 -29 34 -46 16 -46 -6 -83 -142 -226 -143 -152 -228 -268 -301 -411 -122 -241 -176 -471 -176 -761 0 -319 54 -567 180 -825 75 -154 157 -269 299 -418 118 -125 157 -186 145 -232 -8 -34 -59 -75 -93 -75 -83 0 -215 113 -367 316 -199 264 -305 511 -366 851 -20 112 -23 161 -22 383 0 239 1 263 26 381 66 306 188 557 396 816 176 217 305 301 387 247z m2840 -3 c64 -29 145 -102 236 -211 287 -347 421 -684 460 -1158 41 -503 -98 -959 -414 -1352 -137 -171 -269 -280 -337 -280 -29 0 -77 27 -90 49 -29 54 -7 92 137 243 168 176 267 319 344 497 194 452 178 1048 -40 1496 -85 174 -168 288 -343 472 -49 51 -93 104 -98 118 -22 57 -5 106 45 133 28 16 54 14 100 -7z m-1729 -165 c162 -43 314 -169 383 -317 38 -82 48 -118 91 -344 25 -128 48 -187 84 -210 45 -30 114 3 129 62 7 33 -10 100 -44 167 -16 33 -29 67 -29 78 0 56 115 -21 230 -153 161 -187 217 -361 208 -644 -6 -162 -29 -250 -100 -369 -73 -123 -291 -316 -357 -316 -18 0 -51 24 -51 37 0 3 28 35 61 71 122 133 168 222 176 340 8 121 -31 247 -100 320 -17 17 -39 32 -49 32 -16 0 -16 -3 -4 -38 7 -20 17 -56 21 -80 6 -39 4 -45 -28 -77 -32 -32 -40 -35 -92 -35 -112 0 -130 32 -121 210 6 118 5 128 -17 175 -39 81 -133 165 -184 165 -26 0 -32 -33 -10 -47 32 -20 47 -58 47 -123 0 -101 -32 -155 -152 -260 -153 -134 -188 -194 -188 -324 0 -174 84 -328 208 -383 39 -17 52 -28 50 -41 -6 -30 -70 -19 -171 30 -161 78 -280 190 -356 338 -53 101 -74 185 -75 300 -1 159 38 253 240 576 178 286 221 392 212 531 -7 109 -81 238 -159 279 -30 15 -39 48 -16 57 24 10 113 6 163 -7z m1435 -2395 c32 -32 39 -46 39 -77 0 -51 -18 -83 -59 -111 l-34 -23 -1049 0 c-1143 0 -1080 -3 -1127 56 -14 18 -21 41 -21 72 0 38 5 50 39 83 l39 39 1067 0 1067 0 39 -39z"/> </g> </svg>
public/images/freeCodeCamp-puck.svg
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00018906244076788425, 0.00017381524958182126, 0.00016578991198912263, 0.00017020432278513908, 0.000009002168553706724 ]
{ "id": 3, "code_window": [ "IMAGE_BASE_URL='https://s3.amazonaws.com/freecodecamp/images/'\n", "\n", "HOME_LOCATION='http://localhost:8000'\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "API_LOCATION='http://localhost:3000'" ], "file_path": "sample.env", "type": "add", "edit_start_line_idx": 22 }
// // Pagination (multiple pages) // -------------------------------------------------- .pagination { display: inline-block; padding-left: 0; margin: @line-height-computed 0; border-radius: @border-radius-base; > li { display: inline; // Remove list-style and block-level defaults > a, > span { position: relative; float: left; // Collapse white-space padding: @padding-base-vertical @padding-base-horizontal; line-height: @line-height-base; text-decoration: none; color: @pagination-color; background-color: @pagination-bg; border: 1px solid @pagination-border; margin-left: -1px; } &:first-child { > a, > span { margin-left: 0; .border-left-radius(@border-radius-base); } } &:last-child { > a, > span { .border-right-radius(@border-radius-base); } } } > li > a, > li > span { &:hover, &:focus { color: @pagination-hover-color; background-color: @pagination-hover-bg; border-color: @pagination-hover-border; } } > .active > a, > .active > span { &, &:hover, &:focus { z-index: 2; color: @pagination-active-color; background-color: @pagination-active-bg; border-color: @pagination-active-border; cursor: default; } } > .disabled { > span, > span:hover, > span:focus, > a, > a:hover, > a:focus { color: @pagination-disabled-color; background-color: @pagination-disabled-bg; border-color: @pagination-disabled-border; cursor: @cursor-disabled; } } } // Sizing // -------------------------------------------------- // Large .pagination-lg { .pagination-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @border-radius-large); } // Small .pagination-sm { .pagination-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @border-radius-small); }
client/less/lib/bootstrap/pagination.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00017548319010529667, 0.00017123256111517549, 0.00016627437435090542, 0.00017163943266496062, 0.0000024180526452255435 ]
{ "id": 3, "code_window": [ "IMAGE_BASE_URL='https://s3.amazonaws.com/freecodecamp/images/'\n", "\n", "HOME_LOCATION='http://localhost:8000'\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "API_LOCATION='http://localhost:3000'" ], "file_path": "sample.env", "type": "add", "edit_start_line_idx": 22 }
import Stripe from 'stripe'; import keys from '../../config/secrets'; export default function donateBoot(app, done) { let stripe = false; const { User } = app.models; const api = app.loopback.Router(); const donateRouter = app.loopback.Router(); const subscriptionPlans = [500, 1000, 3500, 5000, 25000].reduce( (accu, current) => ({ ...accu, [current]: { amount: current, interval: 'month', product: { name: 'Monthly Donation to freeCodeCamp.org - ' + `Thank you ($${current / 100})` }, currency: 'usd', id: `monthly-donation-${current}` } }), {} ); function connectToStripe() { return new Promise(function(resolve) { // connect to stripe API stripe = Stripe(keys.stripe.secret); // parse stripe plans stripe.plans.list({}, function(err, plans) { if (err) { throw err; } const requiredPlans = Object.keys(subscriptionPlans).map( key => subscriptionPlans[key].id ); const availablePlans = plans.data.map(plan => plan.id); requiredPlans.forEach(planId => { if (!availablePlans.includes(planId)) { const key = planId.split('-').slice(-1)[0]; createStripePlan(subscriptionPlans[key]); } }); }); resolve(); }); } function createStripePlan(plan) { stripe.plans.create(plan, function(err) { if (err) { console.log(err); throw err; } console.log(`${plan.id} created`); return; }); } function createStripeDonation(req, res) { const { user, body } = req; if (!body || !body.amount) { return res.status(400).send({ error: 'Amount Required' }); } const { amount, token: {email, id} } = body; const fccUser = user ? Promise.resolve(user) : User.create$({ email }).toPromise(); let donatingUser = {}; let donation = { email, amount, provider: 'stripe', startDate: new Date(Date.now()).toISOString() }; return fccUser.then( user => { donatingUser = user; return stripe.customers .create({ email, card: id }); }) .then(customer => { donation.customerId = customer.id; return stripe.subscriptions.create({ customer: customer.id, items: [ { plan: `monthly-donation-${amount}` } ] }); }) .then(subscription => { donation.subscriptionId = subscription.id; return res.send(subscription); }) .then(() => { donatingUser.createDonation(donation).toPromise() .catch(err => { throw new Error(err); }); }) .catch(err => { if (err.type === 'StripeCardError') { return res.status(402).send({ error: err.message }); } return res.status(500).send({ error: 'Donation Failed' }); }); } const pubKey = keys.stripe.public; const secKey = keys.stripe.secret; const secretInvalid = !secKey || secKey === 'sk_from_stipe_dashboard'; const publicInvalid = !pubKey || pubKey === 'pk_from_stipe_dashboard'; if (secretInvalid || publicInvalid) { if (process.env.NODE_ENV === 'production') { throw new Error('Stripe API keys are required to boot the server!'); } console.info('No Stripe API keys were found, moving on...'); done(); } else { api.post('/charge-stripe', createStripeDonation); donateRouter.use('/donate', api); app.use(donateRouter); app.use('/external', donateRouter); connectToStripe().then(done); } }
server/boot/donate.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/fec10caf67c6d44a39492ec7fcef6fba1a890260
[ 0.00018596812151372433, 0.00017143369768746197, 0.00016718565893825144, 0.00017006517737172544, 0.000004757395799970254 ]
{ "id": 0, "code_window": [ "\n", "\tif err := teamguardian.CanAdmin(orgId, teamId, c.SignedInUser); err != nil {\n", "\t\treturn Error(403, \"Not allowed to update team member\", err)\n", "\t}\n", "\n", "\tcmd.TeamId = teamId\n", "\tcmd.UserId = c.ParamsInt64(\":userId\")\n", "\tcmd.OrgId = orgId\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif c.OrgRole != m.ROLE_ADMIN {\n", "\t\tcmd.ProtectLastAdmin = true\n", "\t}\n", "\n" ], "file_path": "pkg/api/team_members.go", "type": "add", "edit_start_line_idx": 69 }
package sqlstore import ( "context" "fmt" "testing" . "github.com/smartystreets/goconvey/convey" m "github.com/grafana/grafana/pkg/models" ) func TestTeamCommandsAndQueries(t *testing.T) { Convey("Testing Team commands & queries", t, func() { InitTestDB(t) Convey("Given saved users and two teams", func() { var userIds []int64 for i := 0; i < 5; i++ { userCmd := &m.CreateUserCommand{ Email: fmt.Sprint("user", i, "@test.com"), Name: fmt.Sprint("user", i), Login: fmt.Sprint("loginuser", i), } err := CreateUser(context.Background(), userCmd) So(err, ShouldBeNil) userIds = append(userIds, userCmd.Result.Id) } var testOrgId int64 = 1 group1 := m.CreateTeamCommand{OrgId: testOrgId, Name: "group1 name", Email: "[email protected]"} group2 := m.CreateTeamCommand{OrgId: testOrgId, Name: "group2 name", Email: "[email protected]"} err := CreateTeam(&group1) So(err, ShouldBeNil) err = CreateTeam(&group2) So(err, ShouldBeNil) Convey("Should be able to create teams and add users", func() { query := &m.SearchTeamsQuery{OrgId: testOrgId, Name: "group1 name", Page: 1, Limit: 10} err = SearchTeams(query) So(err, ShouldBeNil) So(query.Page, ShouldEqual, 1) team1 := query.Result.Teams[0] So(team1.Name, ShouldEqual, "group1 name") So(team1.Email, ShouldEqual, "[email protected]") So(team1.OrgId, ShouldEqual, testOrgId) err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: team1.Id, UserId: userIds[0]}) So(err, ShouldBeNil) err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: team1.Id, UserId: userIds[1], External: true}) So(err, ShouldBeNil) q1 := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team1.Id} err = GetTeamMembers(q1) So(err, ShouldBeNil) So(q1.Result, ShouldHaveLength, 2) So(q1.Result[0].TeamId, ShouldEqual, team1.Id) So(q1.Result[0].Login, ShouldEqual, "loginuser0") So(q1.Result[0].OrgId, ShouldEqual, testOrgId) So(q1.Result[1].TeamId, ShouldEqual, team1.Id) So(q1.Result[1].Login, ShouldEqual, "loginuser1") So(q1.Result[1].OrgId, ShouldEqual, testOrgId) So(q1.Result[1].External, ShouldEqual, true) q2 := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team1.Id, External: true} err = GetTeamMembers(q2) So(err, ShouldBeNil) So(q2.Result, ShouldHaveLength, 1) So(q2.Result[0].TeamId, ShouldEqual, team1.Id) So(q2.Result[0].Login, ShouldEqual, "loginuser1") So(q2.Result[0].OrgId, ShouldEqual, testOrgId) So(q2.Result[0].External, ShouldEqual, true) }) Convey("Should be able to update users in a team", func() { userId := userIds[0] team := group1.Result addMemberCmd := m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: team.Id, UserId: userId} err = AddTeamMember(&addMemberCmd) So(err, ShouldBeNil) qBeforeUpdate := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team.Id} err = GetTeamMembers(qBeforeUpdate) So(err, ShouldBeNil) So(qBeforeUpdate.Result[0].Permission, ShouldEqual, 0) err = UpdateTeamMember(&m.UpdateTeamMemberCommand{ UserId: userId, OrgId: testOrgId, TeamId: team.Id, Permission: m.PERMISSION_ADMIN, }) So(err, ShouldBeNil) qAfterUpdate := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team.Id} err = GetTeamMembers(qAfterUpdate) So(err, ShouldBeNil) So(qAfterUpdate.Result[0].Permission, ShouldEqual, m.PERMISSION_ADMIN) }) Convey("Should default to member permission level when updating a user with invalid permission level", func() { userID := userIds[0] team := group1.Result addMemberCmd := m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: team.Id, UserId: userID} err = AddTeamMember(&addMemberCmd) So(err, ShouldBeNil) qBeforeUpdate := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team.Id} err = GetTeamMembers(qBeforeUpdate) So(err, ShouldBeNil) So(qBeforeUpdate.Result[0].Permission, ShouldEqual, 0) invalidPermissionLevel := m.PERMISSION_EDIT err = UpdateTeamMember(&m.UpdateTeamMemberCommand{ UserId: userID, OrgId: testOrgId, TeamId: team.Id, Permission: invalidPermissionLevel, }) So(err, ShouldBeNil) qAfterUpdate := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: team.Id} err = GetTeamMembers(qAfterUpdate) So(err, ShouldBeNil) So(qAfterUpdate.Result[0].Permission, ShouldEqual, 0) }) Convey("Shouldn't be able to update a user not in the team.", func() { err = UpdateTeamMember(&m.UpdateTeamMemberCommand{ UserId: 1, OrgId: testOrgId, TeamId: group1.Result.Id, Permission: m.PERMISSION_ADMIN, }) So(err, ShouldEqual, m.ErrTeamMemberNotFound) }) Convey("Should be able to search for teams", func() { query := &m.SearchTeamsQuery{OrgId: testOrgId, Query: "group", Page: 1} err = SearchTeams(query) So(err, ShouldBeNil) So(len(query.Result.Teams), ShouldEqual, 2) So(query.Result.TotalCount, ShouldEqual, 2) query2 := &m.SearchTeamsQuery{OrgId: testOrgId, Query: ""} err = SearchTeams(query2) So(err, ShouldBeNil) So(len(query2.Result.Teams), ShouldEqual, 2) }) Convey("Should be able to return all teams a user is member of", func() { groupId := group2.Result.Id err := AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: groupId, UserId: userIds[0]}) So(err, ShouldBeNil) query := &m.GetTeamsByUserQuery{OrgId: testOrgId, UserId: userIds[0]} err = GetTeamsByUser(query) So(err, ShouldBeNil) So(len(query.Result), ShouldEqual, 1) So(query.Result[0].Name, ShouldEqual, "group2 name") So(query.Result[0].Email, ShouldEqual, "[email protected]") }) Convey("Should be able to remove users from a group", func() { err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[0]}) So(err, ShouldBeNil) err = RemoveTeamMember(&m.RemoveTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[0]}) So(err, ShouldBeNil) q2 := &m.GetTeamMembersQuery{OrgId: testOrgId, TeamId: group1.Result.Id} err = GetTeamMembers(q2) So(err, ShouldBeNil) So(len(q2.Result), ShouldEqual, 0) }) Convey("When ProtectLastAdmin is set to true", func() { err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[0], Permission: m.PERMISSION_ADMIN}) So(err, ShouldBeNil) Convey("A user should not be able to remove the last admin", func() { err = RemoveTeamMember(&m.RemoveTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[0], ProtectLastAdmin: true}) So(err, ShouldEqual, m.ErrLastTeamAdmin) }) Convey("A user should be able to remove an admin if there are other admins", func() { err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[1], Permission: m.PERMISSION_ADMIN}) err = RemoveTeamMember(&m.RemoveTeamMemberCommand{OrgId: testOrgId, TeamId: group1.Result.Id, UserId: userIds[0], ProtectLastAdmin: true}) So(err, ShouldEqual, nil) }) }) Convey("Should be able to remove a group with users and permissions", func() { groupId := group2.Result.Id err := AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: groupId, UserId: userIds[1]}) So(err, ShouldBeNil) err = AddTeamMember(&m.AddTeamMemberCommand{OrgId: testOrgId, TeamId: groupId, UserId: userIds[2]}) So(err, ShouldBeNil) err = testHelperUpdateDashboardAcl(1, m.DashboardAcl{DashboardId: 1, OrgId: testOrgId, Permission: m.PERMISSION_EDIT, TeamId: groupId}) So(err, ShouldBeNil) err = DeleteTeam(&m.DeleteTeamCommand{OrgId: testOrgId, Id: groupId}) So(err, ShouldBeNil) query := &m.GetTeamByIdQuery{OrgId: testOrgId, Id: groupId} err = GetTeamById(query) So(err, ShouldEqual, m.ErrTeamNotFound) permQuery := &m.GetDashboardAclInfoListQuery{DashboardId: 1, OrgId: testOrgId} err = GetDashboardAclInfoList(permQuery) So(err, ShouldBeNil) So(len(permQuery.Result), ShouldEqual, 0) }) }) }) }
pkg/services/sqlstore/team_test.go
1
https://github.com/grafana/grafana/commit/c420af16b14e586b96d190e52f13805e0491e16a
[ 0.012030134908854961, 0.002555122831836343, 0.00017206236952915788, 0.0013112487504258752, 0.003060355316847563 ]
{ "id": 0, "code_window": [ "\n", "\tif err := teamguardian.CanAdmin(orgId, teamId, c.SignedInUser); err != nil {\n", "\t\treturn Error(403, \"Not allowed to update team member\", err)\n", "\t}\n", "\n", "\tcmd.TeamId = teamId\n", "\tcmd.UserId = c.ParamsInt64(\":userId\")\n", "\tcmd.OrgId = orgId\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tif c.OrgRole != m.ROLE_ADMIN {\n", "\t\tcmd.ProtectLastAdmin = true\n", "\t}\n", "\n" ], "file_path": "pkg/api/team_members.go", "type": "add", "edit_start_line_idx": 69 }
// Copyright 2015 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. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix const ( R_OK = 0x4 W_OK = 0x2 X_OK = 0x1 )
vendor/golang.org/x/sys/unix/constants.go
0
https://github.com/grafana/grafana/commit/c420af16b14e586b96d190e52f13805e0491e16a
[ 0.00017601254512555897, 0.00017195277905557305, 0.00016789301298558712, 0.00017195277905557305, 0.000004059766069985926 ]