import React, { ComponentProps, PureComponent, ReactElement, ReactNode, Component, ErrorInfo, FunctionComponent, HTMLProps } from 'react'; import { Input, Segment as Segment$1, monacoTypes, Monaco, ButtonProps, Field, PopoverContent, Switch, SelectCommonProps, InlineLabel } from '@grafana/ui'; import { DataSourceInstanceSettings, SelectableValue, DataSourceJsonData, VariableSuggestion, TimeRange, DataFrame, MetricFindValue, ThemeSpacingTokens, ScopedVars, VariableModel, DataFrameView, QueryEditorProps as QueryEditorProps$1, DataSourceSettings, RegistryItem, DataSourceApi, Registry, DataQuery as DataQuery$1, PanelData, DataQueryRequest, DataQueryResponse, LoadingState } from '@grafana/data'; import { DataSourceSrv, DataSourceWithBackend, TemplateSrv } from '@grafana/runtime'; import { JsonTree } from '@react-awesome-query-builder/ui'; import { DataQuery } from '@grafana/schema'; import { SqlLanguage } from 'sql-formatter'; import { Grammar } from 'prismjs'; import { Observable } from 'rxjs'; interface QueryEditorRowProps { label?: string; className?: string; noFillEnd?: boolean; children?: React.ReactNode; } declare const QueryEditorRow: (props: QueryEditorRowProps) => React.JSX.Element; interface DebounceInputProps extends Omit, 'ref'> { value: string; onDebounce: (debouncedInput?: string) => void; delay?: number; } declare const DebounceInput: (props: DebounceInputProps) => React.JSX.Element; interface SegmentProps extends Omit>, 'onChange'> { value: T; onDebounce: (debouncedSegment?: T) => void; delay?: number; } declare function Segment(props: SegmentProps): React.JSX.Element; interface DatePickerProps { isOpen?: boolean; onClose: () => void; onChange: (value: Date) => void; value?: Date; } declare const DatePicker: React.NamedExoticComponent; declare const formatDate: (date: Date) => string; interface DatePickerWithInputProps extends Omit, 'ref' | 'value' | 'onChange'> { value?: Date; onChange: (value: Date) => void; } declare const DatePickerWithInput: (props: DatePickerWithInputProps) => React.JSX.Element; interface Props$s { onChange: (ds: DataSourceInstanceSettings) => void; current: string | null; hideTextValue?: boolean; onBlur?: () => void; autoFocus?: boolean; openMenuOnFocus?: boolean; placeholder?: string; tracing?: boolean; mixed?: boolean; dashboard?: boolean; metrics?: boolean; annotations?: boolean; variables?: boolean; pluginId?: string; noDefault?: boolean; } interface State$1 { error?: string; } declare class DataSourcePicker extends PureComponent { dataSourceSrv: DataSourceSrv; static defaultProps: Partial; state: State$1; constructor(props: Props$s); componentDidMount(): void; onChange: (item: SelectableValue) => void; private getCurrentValue; getDataSourceOptions(): Array>; render(): React.JSX.Element; } type DataLinkConfig = { field: string; label: string; matcherRegex: string; url: string; datasourceUid?: string; }; type Props$r = { value?: DataLinkConfig[]; onChange: (value: DataLinkConfig[]) => void; }; declare const DataLinks: (props: Props$r) => React.JSX.Element; type Props$q = { value: DataLinkConfig; datasources?: Array>; onChange: (value: DataLinkConfig) => void; onDelete: () => void; suggestions: VariableSuggestion[]; className?: string; }; declare const DataLink: (props: Props$q) => React.JSX.Element; declare enum QueryEditorPropertyType { String = "string" } interface QueryEditorProperty { type: QueryEditorPropertyType; name?: string; } interface QueryEditorPropertyExpression { type: QueryEditorExpressionType.Property; property: QueryEditorProperty; } declare enum QueryEditorExpressionType { Property = "property", Operator = "operator", Or = "or", And = "and", GroupBy = "groupBy", Function = "function", FunctionParameter = "functionParameter" } interface QueryEditorGroupByExpression { type: QueryEditorExpressionType.GroupBy; property: QueryEditorProperty; } interface QueryEditorFunctionExpression { type: QueryEditorExpressionType.Function; name?: string; parameters?: QueryEditorFunctionParameterExpression[]; } interface QueryEditorFunctionParameterExpression { type: QueryEditorExpressionType.FunctionParameter; name?: string; } declare enum TokenType { Parenthesis = "delimiter.parenthesis.sql", Whitespace = "white.sql", Keyword = "keyword.sql", Delimiter = "delimiter.sql", Operator = "operator.sql", Identifier = "identifier.sql", IdentifierQuote = "identifier.quote.sql", Type = "type.sql", Function = "predefined.sql", Number = "number.sql", String = "string.sql", Variable = "variable.sql" } declare class LinkedToken { type: string; value: string; range: monacoTypes.IRange; previous: LinkedToken | null; next: LinkedToken | null; constructor(type: string, value: string, range: monacoTypes.IRange, previous: LinkedToken | null, next: LinkedToken | null); isKeyword(): boolean; isWhiteSpace(): boolean; isParenthesis(): boolean; isIdentifier(): boolean; isString(): boolean; isNumber(): boolean; isDoubleQuotedString(): boolean; isVariable(): boolean; isFunction(): boolean; isOperator(): boolean; isTemplateVariable(): boolean; is(type: TokenType, value?: string | number | boolean): boolean; getPreviousNonWhiteSpaceToken(): LinkedToken | null; getPreviousOfType(type: TokenType, value?: string): LinkedToken | null; getPreviousUntil(type: TokenType, ignoreTypes: TokenType[], value?: string): LinkedToken[] | null; getNextUntil(type: TokenType, ignoreTypes: TokenType[], value?: string): LinkedToken[] | null; getPreviousKeyword(): LinkedToken | null; getNextNonWhiteSpaceToken(): LinkedToken | null; getNextOfType(type: TokenType, value?: string): LinkedToken | null; } /** * Provides a context for suggestions resolver * @alpha */ interface PositionContext { position: monacoTypes.IPosition; kind: SuggestionKind[]; statementPosition: StatementPosition[]; currentToken: LinkedToken | null; range: monacoTypes.IRange; } type CustomSuggestion = Partial & { label: string; }; interface CustomSuggestionKind { id: string; suggestionsResolver: SuggestionsResolver; applyTo?: Array; overrideDefault?: boolean; } interface CustomStatementPlacement { id: string; name?: string; resolve: StatementPositionResolver; overrideDefault?: boolean; } type StatementPlacementProvider = () => CustomStatementPlacement[]; type SuggestionKindProvider = () => CustomSuggestionKind[]; interface ColumnDefinition { name: string; type?: string; description?: string; completion?: string; } interface SchemaDefinition { name: string; completion?: string; } interface TableDefinition { name: string; completion?: string; } interface TableIdentifier { table?: string; schema?: string; catalog?: string; } interface SQLCompletionItemProvider extends Omit { /** * Allows dialect specific functions to be added to the completion list. * @alpha */ supportedFunctions?: () => Array<{ id: string; name: string; description?: string; }>; /** * Allows dialect specific operators to be added to the completion list. * @alpha */ supportedOperators?: () => Array<{ id: string; operator: string; type: OperatorType; description?: string; }>; supportedMacros?: () => Array<{ id: string; text: string; type: MacroType; args: string[]; description?: string; }>; /** * Allows custom suggestion kinds to be defined and correlate them with StatementPosition. * @alpha */ customSuggestionKinds?: SuggestionKindProvider; /** * Allows custom statement placement definition. * @alpha */ customStatementPlacement?: StatementPlacementProvider; /** * Allows providing a custom function for resolving schemas. * It's up to the consumer to decide whether the schemas are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloaded). * @alpha */ schemas?: { resolve: () => Promise; }; /** * Allows providing a custom function for resolving db tables. * It's up to the consumer to decide whether the columns are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloaded). * @alpha */ tables?: { resolve: (TableIdentifier: TableIdentifier | null) => Promise; parseName?: (token: LinkedToken | null | undefined) => TableIdentifier; }; /** * Allows providing a custom function for resolving table. * It's up to the consumer to decide whether the columns are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloaded). * @alpha */ columns?: { resolve: (identifier?: TableIdentifier) => Promise; }; /** * TODO: Not sure whether or not we need this. Would like to avoid this kind of flexibility. * @alpha */ provideCompletionItems?: (model: monacoTypes.editor.ITextModel, position: monacoTypes.Position, context: monacoTypes.languages.CompletionContext, token: monacoTypes.CancellationToken, positionContext: PositionContext) => monacoTypes.languages.CompletionList; } interface SQLMonarchLanguage extends monacoTypes.languages.IMonarchLanguage { keywords?: string[]; builtinFunctions?: string[]; logicalOperators?: string[]; comparisonOperators?: string[]; /** Used by basic languages in the monaco registry **/ operators?: string[]; } type StatementPositionResolver = (currentToken: LinkedToken | null, previousKeyword: LinkedToken | null, previousNonWhiteSpace: LinkedToken | null, previousIsSlash: Boolean) => Boolean; type SuggestionsResolver = (positionContext: T) => Promise; type LanguageCompletionProvider = (m: Monaco, l?: SQLMonarchLanguage) => SQLCompletionItemProvider; interface LanguageDefinition extends monacoTypes.languages.ILanguageExtensionPoint { loader?: (module: any) => Promise<{ language: SQLMonarchLanguage; conf: monacoTypes.languages.LanguageConfiguration; }>; completionProvider?: (m: Monaco, language: SQLMonarchLanguage) => SQLCompletionItemProvider; formatter?: (q: string) => string; } declare enum OperatorType { Comparison = 0, Logical = 1 } declare enum MacroType { Value = 0, Filter = 1, Group = 2, Column = 3, Table = 4 } declare enum StatementPosition { Unknown = "unknown", SelectKeyword = "selectKeyword", WithKeyword = "withKeyword", AfterSelectKeyword = "afterSelectKeyword", AfterSelectArguments = "afterSelectArguments", AfterSelectFuncFirstArgument = "afterSelectFuncFirstArgument", SelectAlias = "selectAlias", AfterFromKeyword = "afterFromKeyword", AfterTable = "afterTable", SchemaFuncFirstArgument = "schemaFuncFirstArgument", SchemaFuncExtraArgument = "schemaFuncExtraArgument", FromKeyword = "fromKeyword", AfterFrom = "afterFrom", WhereKeyword = "whereKeyword", WhereComparisonOperator = "whereComparisonOperator", WhereValue = "whereValue", AfterWhereFunctionArgument = "afterWhereFunctionArgument", AfterGroupByFunctionArgument = "afterGroupByFunctionArgument", AfterWhereValue = "afterWhereValue", AfterGroupByKeywords = "afterGroupByKeywords", AfterGroupBy = "afterGroupBy", AfterOrderByKeywords = "afterOrderByKeywords", AfterOrderByFunction = "afterOrderByFunction", AfterOrderByDirection = "afterOrderByDirection", AfterIsOperator = "afterIsOperator", AfterIsNotOperator = "afterIsNotOperator", AfterSchema = "afterSchema" } declare enum SuggestionKind { Schemas = "schemas", Tables = "tables", Columns = "columns", SelectKeyword = "selectKeyword", WithKeyword = "withKeyword", FunctionsWithArguments = "functionsWithArguments", FromKeyword = "fromKeyword", WhereKeyword = "whereKeyword", GroupByKeywords = "groupByKeywords", OrderByKeywords = "orderByKeywords", FunctionsWithoutArguments = "functionsWithoutArguments", LimitKeyword = "limitKeyword", SortOrderDirectionKeyword = "sortOrderDirectionKeyword", ComparisonOperators = "comparisonOperators", LogicalOperators = "logicalOperators", SelectMacro = "selectMacro", TableMacro = "tableMacro", FilterMacro = "filterMacro", GroupMacro = "groupMacro", BoolValues = "boolValues", NullValue = "nullValue", NotKeyword = "notKeyword", TemplateVariables = "templateVariables", StarWildCard = "starWildCard" } declare enum CompletionItemPriority { High = "a", MediumHigh = "d", Medium = "g", MediumLow = "k", Low = "q" } declare enum CompletionItemKind { Method = 0, Function = 1, Constructor = 2, Field = 3, Variable = 4, Class = 5, Struct = 6, Interface = 7, Module = 8, Property = 9, Event = 10, Operator = 11, Unit = 12, Value = 13, Constant = 14, Enum = 15, EnumMember = 16, Keyword = 17, Text = 18, Color = 19, File = 20, Reference = 21, Customcolor = 22, Folder = 23, TypeParameter = 24, User = 25, Issue = 26, Snippet = 27 } declare enum CompletionItemInsertTextRule { KeepWhitespace = 1, InsertAsSnippet = 4 } declare enum SQLEditorMode { Builder = "builder", Code = "code" } interface SQLEditorProps { query: string; /** * Use for inspecting the query as it changes. I.e. for validation. */ onChange?: (q: string, processQuery: boolean) => void; onBlur?: (text: string) => void; language?: LanguageDefinition; children?: (props: { formatQuery: () => void; }) => React.ReactNode; width?: number; height?: number; } declare const SQLEditor: ({ children, onBlur, onChange, query, language, width, height, }: SQLEditorProps) => React.JSX.Element; interface TestQueryModel { query: string; tokens: Array>>; } interface StatementPositionResolverTestCase { query: TestQueryModel; position: { line: number; column: number; }; } declare const singleLineFullQuery: TestQueryModel; declare const singleLineFullQueryWithAggregation: TestQueryModel; declare const multiLineFullQuery: TestQueryModel; declare const multiLineFullQueryWithAggregation: TestQueryModel; declare const singleLineEmptyQuery: TestQueryModel; declare const singleLineTwoQueries: TestQueryModel; declare const singleLineTwoQueriesWithAggregation: TestQueryModel; declare const singleLineMultipleColumns: TestQueryModel; declare const multiLineMultipleColumns: TestQueryModel; declare const testData_multiLineFullQuery: typeof multiLineFullQuery; declare const testData_multiLineFullQueryWithAggregation: typeof multiLineFullQueryWithAggregation; declare const testData_multiLineMultipleColumns: typeof multiLineMultipleColumns; declare const testData_singleLineEmptyQuery: typeof singleLineEmptyQuery; declare const testData_singleLineFullQuery: typeof singleLineFullQuery; declare const testData_singleLineFullQueryWithAggregation: typeof singleLineFullQueryWithAggregation; declare const testData_singleLineMultipleColumns: typeof singleLineMultipleColumns; declare const testData_singleLineTwoQueries: typeof singleLineTwoQueries; declare const testData_singleLineTwoQueriesWithAggregation: typeof singleLineTwoQueriesWithAggregation; declare namespace testData { export { testData_multiLineFullQuery as multiLineFullQuery, testData_multiLineFullQueryWithAggregation as multiLineFullQueryWithAggregation, testData_multiLineMultipleColumns as multiLineMultipleColumns, testData_singleLineEmptyQuery as singleLineEmptyQuery, testData_singleLineFullQuery as singleLineFullQuery, testData_singleLineFullQueryWithAggregation as singleLineFullQueryWithAggregation, testData_singleLineMultipleColumns as singleLineMultipleColumns, testData_singleLineTwoQueries as singleLineTwoQueries, testData_singleLineTwoQueriesWithAggregation as singleLineTwoQueriesWithAggregation, }; } declare const SQLEditorTestUtils: { testData: typeof testData; testStatementPosition: (expected: StatementPosition | string, cases: StatementPositionResolverTestCase[], resolvers: () => CustomStatementPlacement[]) => void; }; declare const conf: monacoTypes.languages.LanguageConfiguration; declare const language: SQLMonarchLanguage; declare function getStandardSQLCompletionProvider(monaco: Monaco, language: SQLMonarchLanguage): SQLCompletionItemProvider; interface SqlQueryForInterpolation { dataset?: string; alias?: string; format?: QueryFormat; rawSql?: string; refId: string; hide?: boolean; } interface SQLConnectionLimits { maxOpenConns: number; maxIdleConns: number; connMaxLifetime: number; } interface SQLOptions extends SQLConnectionLimits, DataSourceJsonData { tlsAuth: boolean; tlsAuthWithCACert: boolean; timezone: string; tlsSkipVerify: boolean; user: string; database: string; url: string; timeInterval: string; } declare enum QueryFormat { Timeseries = 0, Table = 1, Logs = 2, Trace = 3, OptionMulti = 4 } declare enum EditorMode { Builder = "builder", Code = "code" } interface SQLQuery extends DataQuery { alias?: string; format?: QueryFormat; rawSql?: string; dataset?: string; catalog?: string; table?: string; sql?: SQLExpression; editorMode?: EditorMode; rawQuery?: boolean; } interface NameValue { name: string; value: string; } type SQLFilters = NameValue[]; interface SQLExpression { columns?: QueryEditorFunctionExpression[]; whereJsonTree?: JsonTree; whereString?: string; filters?: SQLFilters; groupBy?: QueryEditorGroupByExpression[]; orderBy?: QueryEditorPropertyExpression; orderByDirection?: 'ASC' | 'DESC'; limit?: number; offset?: number; } interface TableSchema { name?: string; schema?: TableFieldSchema[]; } interface TableFieldSchema { name: string; description?: string; type: string; repeated: boolean; schema: TableFieldSchema[]; } interface QueryRowFilter { filter: boolean; group: boolean; order: boolean; preview: boolean; } declare const QUERY_FORMAT_OPTIONS: { label: string; value: QueryFormat; }[]; declare const toOption: (value: string) => SelectableValue; interface ResourceSelectorProps { disabled?: boolean; className?: string; applyDefault?: boolean; } type RAQBFieldTypes = 'text' | 'number' | 'boolean' | 'datetime' | 'date' | 'time'; interface SQLSelectableValue extends SelectableValue { type?: string; raqbFieldType?: RAQBFieldTypes; } interface Aggregate { id: string; name: string; description?: string; } interface DB { init?: (datasourceId?: string) => Promise; datasets: (catalog?: string) => Promise; catalogs?: () => Promise; tables: (dataset?: string, catalog?: string, schema?: string) => Promise; fields: (query: SQLQuery, order?: boolean) => Promise; validateQuery: (query: SQLQuery, range?: TimeRange) => Promise; dsID: () => number; dispose?: (dsID?: string) => void; lookup: (path?: string) => Promise>; getSqlCompletionProvider: () => LanguageCompletionProvider; toRawSql?: (query: SQLQuery) => string; functions: () => Promise; labels?: Map<'dataset', string>; disableDatasets?: boolean; disableCatalogs?: boolean; } interface QueryEditorProps { db: DB; query: QueryWithDefaults; onChange: (query: SQLQuery) => void; range?: TimeRange; } interface ValidationResults { query: SQLQuery; rawSql?: string; error: string; isError: boolean; isValid: boolean; statistics?: { TotalBytesProcessed: number; } | null; } interface SqlQueryModel { interpolate: () => string; quoteLiteral: (v: string) => string; } interface ResponseParser { transformMetricFindResponse: (frame: DataFrame) => MetricFindValue[]; } interface MetaDefinition { name: string; completion?: string; kind: CompletionItemKind; } /** * Represents a query with all default values applied. * This is equivalent to SQLQuery since applyQueryDefaults returns SQLQuery. */ type QueryWithDefaults = SQLQuery; interface GroupByRowProps { sql: SQLExpression; onSqlChange: (sql: SQLExpression) => void; columns?: Array>; } declare function GroupByRow({ sql, columns, onSqlChange }: GroupByRowProps): React.JSX.Element; type AccessoryButtonProps = ButtonProps & {}; declare const AccessoryButton: ({ className, ...props }: AccessoryButtonProps) => React.JSX.Element; interface EditorFieldGroupProps { children?: React.ReactNode; } declare const EditorFieldGroup: ({ children }: EditorFieldGroupProps) => React.JSX.Element; interface EditorHeaderProps { children?: React.ReactNode; } declare const EditorHeader: ({ children }: EditorHeaderProps) => React.JSX.Element; interface EditorFieldProps extends ComponentProps { label: string; children: React.ReactElement; width?: number | string; optional?: boolean; tooltip?: PopoverContent; tooltipInteractive?: boolean; } declare const EditorField: (props: EditorFieldProps) => React.JSX.Element; interface EditorRowProps { children?: React.ReactNode; } declare const EditorRow: ({ children }: EditorRowProps) => React.JSX.Element; interface EditorListProps { items: Array>; renderItem: (item: Partial, onChangeItem: (item: Partial) => void, onDeleteItem: () => void) => ReactElement; onChange: (items: Array>) => void; } declare const EditorList: React.ForwardRefExoticComponent & React.RefAttributes>; interface EditorRowsProps { children?: React.ReactNode; } declare const EditorRows: ({ children }: EditorRowsProps) => React.JSX.Element; declare const EditorSwitch: (props: ComponentProps) => React.JSX.Element; interface FlexItemProps { grow?: number; shrink?: number; } declare const FlexItem: ({ grow, shrink }: FlexItemProps) => React.JSX.Element; type Direction = 'row' | 'row-reverse' | 'column' | 'column-reverse'; type AlignItems = 'stretch' | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'start' | 'end' | 'self-start' | 'self-end'; interface StackProps { children?: React.ReactNode; direction?: Direction; alignItems?: AlignItems; wrap?: boolean; gap?: ThemeSpacingTokens; } declare const EditorStack: ({ children, wrap: wrapItems, ...props }: StackProps) => React.JSX.Element; interface InlineSelectProps extends SelectCommonProps { label?: string; } declare function InlineSelect({ label: labelProp, ...props }: InlineSelectProps): React.JSX.Element; type Child = string | undefined | ReactElement<{ className?: string; invalid?: unknown; }>; interface InputGroupProps { children: Child | Child[]; } declare const InputGroup: ({ children }: InputGroupProps) => React.JSX.Element; interface SpaceProps { v?: number; h?: number; layout?: 'block' | 'inline'; } declare const Space: ({ v, h, layout }: SpaceProps) => React.JSX.Element; interface SearchFilterOptions { searchFilter?: string; } interface VariableWithMultiSupport extends VariableWithOptions { multi: boolean; includeAll: boolean; allValue?: string | null; } interface VariableWithOptions extends VariableModel { current: VariableOption; options: VariableOption[]; query: string; } interface VariableOption { selected: boolean; text: string | string[]; value: string | string[]; isNone?: boolean; } declare abstract class SqlDatasource extends DataSourceWithBackend { protected readonly templateSrv: TemplateSrv; id: number; name: string; interval: string; db: DB; dataset?: string; annotations: {}; constructor(instanceSettings: DataSourceInstanceSettings, templateSrv?: TemplateSrv); abstract getDB(dsID?: number): DB; abstract getQueryModel(target?: SQLQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars): SqlQueryModel; abstract getResponseParser(): ResponseParser; interpolateVariable: (value: string | string[] | number, variable: VariableWithMultiSupport) => string | number; interpolateVariablesInQueries(queries: SQLQuery[], scopedVars: ScopedVars): SQLQuery[]; filterQuery(query: SQLQuery): boolean; applyTemplateVariables(target: SQLQuery, scopedVars: ScopedVars): SQLQuery; clean(value: string): string; metricFindQuery(query: string, optionalOptions?: MetricFindQueryOptions): Promise; runSql(query: string, options?: RunSQLOptions): Promise>; private runMetaQuery; testDatasource(): Promise<{ status: string; message: string; }>; targetContainsTemplate(target: SQLQuery): boolean; } interface RunSQLOptions extends MetricFindQueryOptions { refId?: string; } interface MetricFindQueryOptions extends SearchFilterOptions { range?: TimeRange; } interface Props$p extends QueryEditorProps$1 { language?: SqlLanguage; } declare function SqlQueryEditor({ datasource, query, onChange, onRunQuery, range, language }: Props$p): React.JSX.Element | null; type RunQueryButtonProps = { ariaLabel?: string; queryInvalid?: boolean; invalidQueryTooltip?: PopoverContent; disabled?: boolean; queryRunning?: boolean; onClick: () => void; dataTestId?: string; }; declare const RunQueryButton: ({ ariaLabel, queryRunning, queryInvalid, invalidQueryTooltip, disabled, onClick, dataTestId, }: RunQueryButtonProps) => React.JSX.Element; interface DatasetSelectorProps extends ResourceSelectorProps { db: DB; dataset?: string; catalog?: string; value: string | null; applyDefault?: boolean; disabled?: boolean; onChange: (v: SelectableValue) => void; inputId?: string; enableCatalogs?: boolean; 'data-testid'?: string; } declare const DatasetSelector: ({ db, dataset, catalog, value, onChange, disabled, className, applyDefault, inputId, enableCatalogs, "data-testid": dataTestId, }: DatasetSelectorProps) => React.JSX.Element; interface CatalogSelectorProps { db: DB; inputId?: string; value: string | null; onChange: (catalog: string | null) => void; } declare const CatalogSelector: ({ db, inputId, value, onChange }: CatalogSelectorProps) => React.JSX.Element; interface TableSelectorProps extends ResourceSelectorProps { db: DB; dataset?: string; catalog?: string; value: string | null; query: QueryWithDefaults; onChange: (v: SelectableValue) => void; inputId?: string; enableCatalogs?: boolean; } declare const TableSelector: ({ db, dataset, catalog, value, className, onChange, inputId, enableCatalogs, }: TableSelectorProps) => React.JSX.Element; type Props$o = Omit, 'children' | 'onChange'> & { dataSourceConfig: DataSourceSettings; onChange: (config: DataSourceSettings) => void; labelWidth: number; }; declare const SecureSocksProxyToggle: ({ labelWidth, ...props }: Props$o) => any; type Props$n = { dataSourceName: string; docsLink: string; hasRequiredFields?: boolean; className?: string; }; declare const DataSourceDescription: ({ dataSourceName, docsLink, hasRequiredFields, className }: Props$n) => React.JSX.Element; type Props$m = { title: string; description?: ReactNode; isCollapsible?: boolean; isInitiallyOpen?: boolean; kind?: 'section' | 'sub-section'; className?: string; }; type Props$l = Omit; declare const ConfigSection: ({ children, ...props }: React.PropsWithChildren) => React.JSX.Element; type Props$k = Omit; declare const ConfigSubSection: ({ children, ...props }: React.PropsWithChildren) => React.JSX.Element; type Props$j = { description: string; suffix: string; feature: string; }; declare function ConfigDescriptionLink(props: Props$j): React.JSX.Element; declare enum AuthMethod { NoAuth = "NoAuth", BasicAuth = "BasicAuth", OAuthForward = "OAuthForward", CrossSiteCredentials = "CrossSiteCredentials" } interface AuthMethodSelectOption { label?: string; description?: string; } type CustomMethodId = `custom-${string}`; type CustomMethod = { id: CustomMethodId; label: string; description: string; component: ReactElement; }; type Header = { name: string; configured: boolean; }; type HeaderWithValue = Header & { value: string; }; type Props$i = { enabled: boolean; onToggle: (enabled: boolean) => void; certificateConfigured: boolean; onCertificateChange: (certificate: string) => void; onCertificateReset: () => void; tooltips?: { certificateLabel?: string; }; readOnly: boolean; }; type Props$h = { enabled: boolean; onToggle: (enabled: boolean) => void; serverName: string; clientCertificateConfigured: boolean; clientKeyConfigured: boolean; onServerNameChange: (serverName: string) => void; onClientCertificateChange: (clientCertificate: string) => void; onClientKeyChange: (clientKey: string) => void; onClientCertificateReset: () => void; onClientKeyReset: () => void; tooltips?: { serverNameLabel?: string; certificateLabel?: string; keyLabel?: string; }; readOnly: boolean; }; type Props$g = { enabled: boolean; onToggle: (enabled: boolean) => void; readOnly: boolean; }; type Props$f = { selfSignedCertificate: Omit; TLSClientAuth: Omit; skipTLSVerification: Omit; readOnly: boolean; }; declare const TLSSettings: ({ selfSignedCertificate, TLSClientAuth, skipTLSVerification, readOnly }: Props$f) => React.JSX.Element; type Props$e = { user?: string; passwordConfigured: boolean; userLabel?: string; userTooltip?: PopoverContent; userPlaceholder?: string; passwordLabel?: string; passwordTooltip?: PopoverContent; passwordPlaceholder?: string; onUserChange: (user: string) => void; onPasswordChange: (password: string) => void; onPasswordReset: () => void; readOnly: boolean; }; type Props$d = { headers: Header[]; onChange: (headers: HeaderWithValue[]) => void; readOnly: boolean; }; type Props$c = { selectedMethod: AuthMethod | CustomMethodId; mostCommonMethod?: AuthMethod | CustomMethodId; visibleMethods?: Array; defaultOptionsOverrides?: Partial>; customMethods?: CustomMethod[]; onAuthMethodSelect: (authType: AuthMethod | CustomMethodId) => void; basicAuth?: Omit; TLS?: Omit; customHeaders?: Omit; readOnly?: boolean; }; declare const Auth: ({ selectedMethod, mostCommonMethod, visibleMethods, defaultOptionsOverrides, customMethods, onAuthMethodSelect, basicAuth, TLS, customHeaders, readOnly, }: Props$c) => React.JSX.Element; type DataSourceExclusiveConfig = { readOnly: DataSourceSettings['readOnly']; url: DataSourceSettings['url']; basicAuth: DataSourceSettings['basicAuth']; basicAuthUser: DataSourceSettings['basicAuthUser']; withCredentials: DataSourceSettings['withCredentials']; }; type Config = { jsonData: DataSourceSettings['jsonData']; secureJsonData?: DataSourceSettings['secureJsonData']; secureJsonFields: DataSourceSettings['secureJsonFields']; } & Partial; type OnChangeHandler = (config: C) => void; declare function convertLegacyAuthProps({ config, onChange, }: { config: C; onChange: OnChangeHandler; }): Props$c; type Props$b = { config: C; onChange: OnChangeHandler; description?: ReactNode; urlPlaceholder?: string; urlTooltip?: PopoverContent; urlLabel?: string; className?: string; }; declare const ConnectionSettings: (props: Props$b) => JSX.Element; type Props$a = { config: C; onChange: OnChangeHandler; className?: string; }; declare const AdvancedHttpSettings: (props: Props$a) => JSX.Element; interface DatasourceConfigSchema { /** * Schema version (required) * Used for compatibility and migrations * * Example: "v2" */ schemaVersion: string; /** * Unique datasource plugin identifier * Example: "prometheus" */ pluginType: string; /** * Human-readable name */ pluginName: string; /** * Optional documentation URL */ docURL?: string; /** * SDK field packs to merge into this schema before validation. * Pack fields are prepended to `fields` in declaration order. * Plugin-declared fields with a matching ID take precedence over pack fields. * Call `resolveBaseFields()` before consuming the schema. */ baseFields?: BaseFieldRef[]; /** * Source of truth for configuration */ fields: ConfigField[]; /** * Optional UI grouping */ groups?: ConfigGroup[]; /** * Optional instructions rendered alongside the config form. */ instructions?: Instruction[]; /** * Relationships between fields */ relationships?: FieldRelationship[]; } interface Instruction { msg: string; tags?: string[]; } /** * Identifier of a built-in field pack defined by grafana/dsconfig. * Convention: `_settings`. */ type FieldPackID = 'plugin_sdk_settings' | 'aws_sdk_settings' | 'azure_sdk_settings' | 'google_sdk_settings' | 'sqleng_settings'; /** * Declares a single field pack to compose into the schema. */ interface BaseFieldRef { /** Identifier of a built-in field pack. */ from: FieldPackID; /** * Field IDs from the pack to omit entirely. * Each ID must exist in the pack (else resolution fails). */ exclude?: string[]; /** * Presentation-only overrides keyed by pack field ID. * Structural properties (id, key, valueType, target, role) cannot be patched. */ patch?: Record; } /** * Safe-to-override presentation properties for a pack field. * Only non-undefined values are applied. */ interface FieldPatch { label?: string; description?: string; placeholder?: string; defaultValue?: unknown; required?: boolean; /** When true, the field is dropped from the resolved schema. */ hidden?: boolean; } /** * Named set of ConfigField definitions provided by an SDK. * Pack field IDs are namespaced with the pack ID, e.g. `plugin_sdk_settings.url`. */ interface FieldPack { id: FieldPackID; fields: ConfigField[]; } interface ConfigField { /** * Globally unique identifier * Recommended format: dot-separated path * Example: "auth.method", "httpHeaders.item.key" */ id: string; /** * Local key used in storage or object */ key: string; /** * UI metadata */ label?: string; description?: string; docURL?: string; /** * Core type of the field */ valueType: ValueType; /** * Storage location (required for storage fields) */ target?: TargetLocation; /** * Semantic role identifying what a field represents to the SDK. * Field packs annotate their fields with roles (e.g. `endpoint.baseUrl`). */ role?: Role; /** * Dotted path prefix within the target for nested objects. * Example: for jsonData.tracesToLogs.datasourceUid, * target="jsonData", section="tracesToLogs", key="datasourceUid". */ section?: string; /** * Field kind. * @default "storage" */ kind?: FieldKind; /** * True if field belongs to array item schema */ isItemField?: boolean; /** * UI rendering hints */ ui?: FieldUI; /** * Validations rules */ validations?: FieldValidationRule[]; /** * Visibility condition (CEL expression) */ dependsOn?: Expression; /** * Always required */ required?: boolean; /** * Conditionally required */ requiredWhen?: Expression; /** * Disabled condition */ disabledWhen?: Expression; /** * Dynamic overrides */ overrides?: FieldOverride[]; /** * Declarative multi-field write side-effects. * When this field's value matches a condition, the listed target * fields are set to specified values. Typically used on virtual * selector fields (e.g. auth method dropdown). */ effects?: FieldEffect[]; /** * Item schema for array elements or map values. * Required if valueType === "array" or "map". */ item?: FieldItemSchema; /** * Legacy indexed fields (deprecated) */ repeatable?: boolean; pattern?: string; /** * Storage mapping */ storage?: StorageMapping; /** * Metadata */ tags?: string[]; examples?: unknown[]; defaultValue?: unknown; } interface FieldItemSchema { /** * Type of array items or map values. * For arrays, describes each element. * For maps, describes each value (keys are always strings). */ valueType: ValueType; /** * Sub-fields for object items. Optional even when valueType = "object" * (omitting allows an unconstrained object). */ fields?: ConfigField[]; } /** * CEL expression string */ type Expression = string; type ValueType = 'string' | 'number' | 'boolean' | 'array' | 'object' | 'map' | 'any'; type FieldKind = 'storage' | 'virtual'; type TargetLocation = 'root' | 'jsonData' | 'secureJsonData'; /** * Semantic role identifying what a field represents to the SDK. * Kept as `string` for forward compatibility with newer packs from * grafana/dsconfig; see that repo for the canonical role list. */ type Role = string; type UIComponent = 'input' | 'textarea' | 'select' | 'multiselect' | 'radio' | 'checkbox' | 'switch' | 'code' | 'keyvalue' | 'list' | 'fileUpload'; type UIWidth = 'full' | 'half'; /** * UI configuration */ interface FieldUI { component: UIComponent; multiline?: boolean; rows?: number; options?: FieldOption[]; allowCustom?: boolean; width?: UIWidth; placeholder?: string; /** * Language hint for code editor components. * Example: "promql", "logql", "traceql", "sql", "json" */ language?: string; /** * Layout row index for item fields inside object arrays. * Fields with the same row number are rendered horizontally. * Fields without a row number use auto-layout: * - ≤3 fields: all on one row * - >3 fields: each on its own row */ row?: number; /** * Accepted file types for fileUpload component. * Uses HTML accept attribute format with leading dot. * Example: [".json"] */ accept?: string[]; /** * Maps keys in an uploaded JSON file to target field IDs. * Used by fileUpload to distribute parsed values to other form fields. * Example: { "private_key": "secureJsonData.privateKey", "client_email": "jsonData.clientEmail" } */ fileMapping?: Record; } type FieldValidationRule = PatternValidationRule | RangeValidationRule | LengthValidationRule | ItemCountValidationRule | AllowedValuesValidationRule | CustomValidationRule; interface BaseValidationRule { /** * Optional stable ID for the validation rule. * Useful for docs, localization, and test snapshots. */ id?: string; /** * Human-readable validation error message. */ message?: string; } interface PatternValidationRule extends BaseValidationRule { type: 'pattern'; pattern: string; } interface RangeValidationRule extends BaseValidationRule { type: 'range'; min?: number; max?: number; } interface LengthValidationRule extends BaseValidationRule { type: 'length'; min?: number; max?: number; } interface ItemCountValidationRule extends BaseValidationRule { type: 'itemCount'; min?: number; max?: number; } interface AllowedValuesValidationRule extends BaseValidationRule { type: 'allowedValues'; values: unknown[]; } interface CustomValidationRule extends BaseValidationRule { type: 'custom'; /** * CEL expression. * * Should evaluate to true when the field value is valid. */ expression: Expression; } interface FieldOverride { /** * CEL condition */ when: Expression; defaultValue?: unknown; /** * When true, the field is disabled/read-only while this override is active. */ readOnly?: boolean; description?: string; placeholder?: string; tooltip?: string; validations?: FieldValidationRule[]; options?: FieldOption[]; /** * When present on an `isItemField` field, the value is routed to * `secureJsonData` under the resolved key instead of being stored * inline in the parent array. * * The template string supports placeholders: * - `{index}` — 0-based array position * - `{index1}` — 1-based array position * - `{item.KEY}` — value of sibling item field `KEY` * * Examples: * - `"secureHttpHeaders.{item.name}"` (ClickHouse) * - `"httpHeaderValue{index1}"` (Grafana core headers) */ secureKey?: string; } /** * Declares that when a field's value matches a condition, * listed target fields should be set to specified values. * * Use "value" in the `when` expression to refer to the field's value. */ interface FieldEffect { /** * CEL expression. Example: "value == 'basic-auth'" */ when: Expression; /** * Maps field IDs to the values they should be set to. * Must contain at least one entry. */ set: Record & { [k: string]: unknown; }; } type StorageMapping = DirectMapping | IndexedPairMapping | ComputedMapping; /** * Direct mapping */ interface DirectMapping { type: 'direct'; } /** * Indexed pair mapping (headers) */ interface IndexedPairMapping { type: 'indexedPair'; key: MappingField; value: MappingField; startIndex?: number; } /** * Computed mapping (virtual fields). * At least one of `read` or `write` must be provided. */ type ComputedMapping = { type: 'computed'; read: Expression; write?: Expression; } | { type: 'computed'; read?: Expression; write: Expression; }; /** * Mapping field */ interface MappingField { target: TargetLocation; pattern: string; } interface FieldOption { label: string; /** * Must match parent field valueType. * Must not be null. */ value: NonNullable; /** * Optional human-readable description of the option. */ description?: string; } interface ConfigGroup { id: string; title: string; description?: string; order?: number; /** * When true, the group is optional and can be collapsed/hidden by default. */ optional?: boolean; /** * References field IDs (not keys) */ fieldRefs: string[]; } type RelationshipType = 'pair' | 'group' | 'datasourceReference'; interface FieldRelationship { type: RelationshipType; /** * References field IDs */ fields: string[]; description?: string; /** * Constrains the datasource UID to a specific plugin type. * Only applicable when type is "datasourceReference". */ targetPluginType?: string; } type SecureFieldState = { type: 'unset'; } | { type: 'configured'; } | { type: 'updated'; value: string; }; interface FormState { values: Record; secure: Record; } type DatasourceConfigWizardProps = { schema: DatasourceConfigSchema; dsUid: string; dsName: string; onSuccess: (status: string, message?: string) => void; onSaving?: (saving: boolean) => void; onRetest?: () => void; onFollowup?: (intent: string) => void; healthError?: string; /** Optional render prop for custom action buttons (e.g. analyze/troubleshoot). */ renderActions?: (props: { dsUid: string; dsName: string; dsType: string; healthError?: string; }) => ReactNode; }; declare function DatasourceConfigWizard(props: DatasourceConfigWizardProps): React.JSX.Element; /** Lightweight error boundary scoped to datasource config widgets — won't crash the host UI. */ declare class DatasourceErrorBoundary extends Component<{ children: ReactNode; dsName?: string; }, { error: Error | null; }> { state: { error: Error | null; }; static getDerivedStateFromError(error: Error): { error: Error; }; componentDidCatch(error: Error, info: ErrorInfo): void; render(): string | number | boolean | Iterable | React.JSX.Element | null | undefined; } type HealthState = 'pending' | 'checking' | 'done'; interface DatasourceHealth { state: HealthState; status?: string; message?: string; } /** * Health check hook — on-demand only. * Call `checkUids(uids)` to trigger checks for specific UIDs. * Call `retry(uid)` to force re-check a single UID. * UIDs that have already been checked (or are in-flight) are automatically skipped. */ declare function useHealthChecks(): { healthMap: Record; checkUids: (uids: string[]) => void; retry: (uid: string) => void; }; declare function resolvePluginName(pluginType: string): string; type UseDatasourceSchemaResult = { schema: DatasourceConfigSchema | null; loading: boolean; error: string | null; }; declare function useDatasourceSchema(pluginType: string): UseDatasourceSchemaResult; declare function fetchConfigSchema(pluginType: string): Promise; /** * CEL (Common Expression Language) expression evaluator for schema conditions. * * Used by `dependsOn`, `requiredWhen`, `disabledWhen`, and `overrides[].when`. * Wraps @marcbachmann/cel-js with field-ID-aware context building. * * Go equivalent: github.com/google/cel-go */ /** * Build a nested context object from flat form values keyed by field IDs. * * CEL interprets dots as property access, so `jsonData.auth_method == 'oauth2'` * requires `{ jsonData: { auth_method: 'oauth2' } }`. * * This function takes flat key-value pairs (from react-hook-form `watch()`) * and builds the nested structure CEL expects. * * @param values - Flat map of form keys to values (e.g. `{ "auth_method": "oauth2", "oauth2.oauth2_type": "jwt" }`) * @param fieldIdToFormKey - Optional map from field ID to form key for translation */ declare function buildCelContext(values: Record): Record; /** * Evaluate a CEL expression against a context of field values. * Returns the boolean result, or `defaultValue` if the expression is invalid. * * @example * ```ts * evaluateCelExpression("jsonData.auth_method == 'oauth2'", { jsonData: { auth_method: 'oauth2' } }) * // => true * * evaluateCelExpression("auth_method == 'oauth2' && oauth2_type == 'jwt'", { auth_method: 'oauth2', oauth2_type: 'jwt' }) * // => true * ``` */ declare function evaluateCelExpression(expr: string, context: Record, defaultValue?: boolean): boolean; /** * Evaluate a CEL expression directly using `evaluate` (no caching). * Useful for one-off evaluations or testing. */ declare function evaluateCelDirect(expr: string, context: Record): unknown; /** * Validate that a CEL expression can be parsed without errors. * Returns true if valid, false otherwise. */ declare function isValidCelExpression(expr: string): boolean; /** * Extract all field ID references from a simple expression. * Used by `resolveRequiredFieldsGroup` to find dependency relationships. * * For simple expressions like `fieldA == 'x'`, returns `['fieldA']`. * For compound expressions like `fieldA == 'x' && fieldB == 'y'`, returns `['fieldA', 'fieldB']`. * * This uses regex extraction (not AST walking) for simplicity and speed. */ declare function extractFieldRefs(expr: string): string[]; /** * Clear the expression cache. Useful for testing. */ declare function clearExpressionCache(): void; type TroubleShootingContext = { label: string; key: string; target: string; type: string; required: boolean; description?: string; defaultValue?: unknown; options?: string[]; section?: string; dependsOn?: string; }; /** * Generate LLM hints for select fields (used when creating datasources). */ declare function generateLLMHint(schema: DatasourceConfigSchema): string; /** * Generate comprehensive structured field data for troubleshooting context. * Returns an array of field descriptors the LLM can use to render rich tables. */ declare function generateTroubleshootingFields(schema: DatasourceConfigSchema): TroubleShootingContext[]; type ProvisioningYamlOptions = { /** Include comments with field descriptions. Default: true for template, false for export. */ comments?: boolean; /** Override the emitted datasource name. */ name?: string; }; /** * Generate a Grafana provisioning YAML template from a dsconfig schema. * Emits every schema field with sensible defaults and (by default) explanatory comments. */ declare function generateProvisioningTemplate(schema: DatasourceConfigSchema, options?: ProvisioningYamlOptions): string; /** * Generate provisioning YAML from an existing Grafana datasource API response. * If a dsconfig schema is available, uses it for field ordering and comments. * If not, generates basic YAML from the raw API response. */ declare function datasourceToProvisioningYaml(ds: Record, schema: DatasourceConfigSchema | null): string; declare const formatYamlDiff: (existing: Record, body: Record) => string; declare const ROOT_CONFIG_FIELDS: readonly ["name", "type", "id", "uid", "access", "url", "basicAuth", "basicAuthUser", "user", "isDefault", "database", "withCredentials"]; type DatasourceConfig = Record; declare const buildCreateDatasourcePayload: (input: DatasourceConfig) => DatasourceConfig; declare const buildCloneDatasourcePayload: (source: DatasourceConfig, name: string) => DatasourceConfig; declare const buildUpdateDatasourcePayload: (existing: DatasourceConfig, input: DatasourceConfig) => { body: DatasourceConfig; hasChanges: boolean; }; declare function getConfigSchema(pluginType: string): Promise; /** * Pure helper functions for working with DatasourceConfigSchema. * * Types are defined in schema.ts — import them from there directly. */ /** A group paired with its resolved ConfigField objects (in fieldRefs order). */ type ResolvedGroup = { group: ConfigGroup; fields: ConfigField[]; }; /** * Group ids that denote the authentication section. Registry schemas use the * full form `authentication`; `auth` is accepted for backwards compatibility * with older/short-form schemas. */ declare const AUTH_GROUP_IDS: readonly string[]; /** Whether a group id denotes the authentication group. */ declare function isAuthGroupId(id: string): boolean; /** * Resolve a schema's groups into arrays of ConfigField objects. * If the schema has no groups, returns a single group containing all non-virtual fields. */ declare function resolveGroups(schema: DatasourceConfigSchema): ResolvedGroup[]; /** * Build a virtual "Required" group containing all required fields, any parent * fields they depend on (via `dependsOn`), and any child fields that depend on * required fields. When the schema contains an authentication group (id * `authentication` or `auth`), its fields are also pulled in (auth is * effectively required for Prometheus/Loki/Tempo style datasources). Fields * are returned in schema order and de-duplicated. * Returns `null` when the virtual group would be empty. */ declare function resolveRequiredFieldsGroup(schema: DatasourceConfigSchema): ResolvedGroup | null; /** * Unique form key for a field. Section-scoped fields (e.g. section:"logs", key:"defaultTable") * get a prefixed key ("logs.defaultTable") so they don't collide with top-level fields that * share the same key name. */ declare function formKey(field: ConfigField): string; /** * Resolve a possibly-dotted key against watchedValues from react-hook-form. * RHF's `watch()` returns nested objects for dotted Controller names * (e.g. "logs.otelEnabled" → { logs: { otelEnabled: true } }), * so a flat `obj["logs.otelEnabled"]` lookup misses. * * For dotted keys we must try the nested path **first**: react-hook-form's * Controller `onChange` writes nested objects via its internal `set()`, but * `reset()` may have created a flat dotted key with the same name. After user * interaction the nested value is authoritative; the stale flat key must not * shadow it. This mirrors RHF's own `get()` semantics (nested-first, flat * fallback). */ declare function getWatchedValue(watchedValues: Record, key: string): unknown; /** * Parse a simple CEL-like dependsOn expression: "fieldId == 'value'" or "fieldId != 'value'". * Only single comparisons are supported — no &&, ||, or parentheses. * Field IDs may contain dots and underscores (e.g. "jsonData.oauth2.oauth2_type"). * Values may be single-quoted, double-quoted, or unquoted literals (true/false/numbers). * Returns { field, value, negate } or null if unparseable. */ declare function parseDependsOn(expr: string): { field: string; value: string; negate: boolean; } | null; /** * Evaluate a parsed dependsOn condition against a value. * Handles both == and != operators. */ declare function evaluateDependsOn(parsed: { value: string; negate: boolean; }, currentValue: unknown): boolean; /** * Resolve the first matching override for a field given current form values. * Override `when` uses the same "fieldId == 'value'" syntax as dependsOn. * Returns the matching override or undefined if none match. */ declare function resolveActiveOverride(field: ConfigField, watchedValues: Record, fieldById: Map): FieldOverride | undefined; /** * Evaluate a simple computed.read expression against form values. * Supports patterns used in dsconfig schemas: * - "fieldRef == true ? 'a' : (fieldRef == true ? 'b' : 'c')" * - Simple ternary chains with equality checks * Falls back to the field's defaultValue if the expression can't be evaluated. */ declare function evaluateComputedRead(expr: string, values: Record, fields: ConfigField[]): unknown; /** * Compute initial values for all virtual fields that have storage.computed.read expressions. * Call after loading existing storage field values. */ declare function computeVirtualFieldValues(schema: DatasourceConfigSchema, existingValues: Record): Record; interface CustomHeader { id: string; name: string; value: string; configured: boolean; } type CustomHeaders = CustomHeader[]; interface Props$9 { dataSourceConfig: DataSourceSettings; onChange: (config: DataSourceSettings) => void; } interface State { headers: CustomHeaders; } declare class CustomHeadersSettings extends PureComponent { state: State; constructor(props: Props$9); updateSettings: () => void; onHeaderAdd: () => void; onHeaderChange: (headerIndex: number, value: CustomHeader) => void; onHeaderReset: (headerId: string) => void; onHeaderRemove: (headerId: string) => void; render(): React.JSX.Element; } interface QueryBuilderLabelFilter { label: string; op: string; value: string; } interface QueryBuilderOperation { id: string; params: QueryBuilderOperationParamValue[]; disabled?: boolean; } interface QueryBuilderOperationDefinition extends RegistryItem { documentation?: string; params: QueryBuilderOperationParamDef[]; defaultParams: QueryBuilderOperationParamValue[]; category: string; hideFromList?: boolean; alternativesKey?: string; /** Can be used to control operation placement when adding a new operations, lower are placed first */ orderRank?: number; renderer: QueryBuilderOperationRenderer; addOperationHandler: QueryBuilderAddOperationHandler; paramChangedHandler?: QueryBuilderOnParamChangedHandler; explainHandler?: QueryBuilderExplainOperationHandler; changeTypeHandler?: (op: QueryBuilderOperation, newDef: QueryBuilderOperationDefinition) => QueryBuilderOperation; toggleable?: boolean; } type QueryBuilderAddOperationHandler = (def: QueryBuilderOperationDefinition, query: T, modeller: VisualQueryModeller) => T; type QueryBuilderExplainOperationHandler = (op: QueryBuilderOperation, def?: QueryBuilderOperationDefinition) => string; type QueryBuilderOnParamChangedHandler = (index: number, operation: QueryBuilderOperation, operationDef: QueryBuilderOperationDefinition) => QueryBuilderOperation; type QueryBuilderOperationRenderer = (model: QueryBuilderOperation, def: QueryBuilderOperationDefinition, innerQuery: string) => string; type QueryBuilderOperationParamValue = string | number | boolean; interface QueryBuilderOperationParamDef { name: string; type: 'string' | 'number' | 'boolean'; options?: string[] | number[] | Array>; hideName?: boolean; restParam?: boolean; optional?: boolean; placeholder?: string; description?: string; minWidth?: number; editor?: FunctionComponent; runQueryOnEnter?: boolean; } interface QueryBuilderOperationParamEditorProps { value?: QueryBuilderOperationParamValue; paramDef: QueryBuilderOperationParamDef; /** Parameter index */ index: number; operation: QueryBuilderOperation; operationId: string; query: any; datasource: DataSourceApi; timeRange?: TimeRange; onChange: (index: number, value: QueryBuilderOperationParamValue) => void; onRunQuery: () => void; queryModeller: VisualQueryModeller; } declare enum QueryEditorMode { Code = "code", Builder = "builder" } type QueryStats = { bytes: number; message?: string; }; interface VisualQueryModeller { getOperationsForCategory(category: string): QueryBuilderOperationDefinition[]; getAlternativeOperations(key: string): QueryBuilderOperationDefinition[]; getCategories(): string[]; getOperationDefinition(id: string): QueryBuilderOperationDefinition | undefined; renderQuery(query: VisualQuery, nested?: boolean): string; renderLabels(labels: QueryBuilderLabelFilter[]): string; innerQueryPlaceholder: string; } interface VisualQueryBinary { operator: string; vectorMatchesType?: 'on' | 'ignoring'; vectorMatches?: string; query: T; } declare const BINARY_OPERATIONS_KEY = "Binary operations"; interface VisualQuery { metric?: string; labels: QueryBuilderLabelFilter[]; operations: QueryBuilderOperation[]; binaryQueries?: Array>; } declare abstract class QueryModellerBase implements VisualQueryModeller { protected operationsRegistry: Registry; private categories; innerQueryPlaceholder: string; constructor(operationDefinitions: QueryBuilderOperationDefinition[], innerQueryPlaceholder?: string); protected setOperationCategories(categories: string[]): void; abstract renderOperations(queryString: string, operations: QueryBuilderOperation[]): string; abstract renderBinaryQueries(queryString: string, binaryQueries?: Array>): string; abstract renderLabels(labels: QueryBuilderLabelFilter[]): string; abstract renderQuery(query: VisualQuery, nested?: boolean): string; getOperationsForCategory(category: string): QueryBuilderOperationDefinition[]; getAlternativeOperations(key: string): QueryBuilderOperationDefinition[]; getCategories(): string[]; getOperationDefinition(id: string): QueryBuilderOperationDefinition | undefined; hasBinaryOp(query: VisualQuery): boolean; } interface Props$8 { labelsFilters: QueryBuilderLabelFilter[]; onChange: (labelFilters: QueryBuilderLabelFilter[]) => void; onGetLabelNames: (forLabel: Partial) => Promise; onGetLabelValues: (forLabel: Partial) => Promise; /** If set to true, component will show error message until at least 1 filter is selected */ labelFilterRequired?: boolean; multiValueSeparator?: string; } declare function LabelFilters({ labelsFilters, onChange, onGetLabelNames, onGetLabelValues, labelFilterRequired, multiValueSeparator, }: Props$8): React.JSX.Element; interface Props$7 { title?: React.ReactNode; markdown?: string; stepNumber?: number; } declare function OperationExplainedBox({ title, stepNumber, markdown, children }: React.PropsWithChildren): React.JSX.Element; interface Props$6 { query: T; datasource: DataSourceApi; onChange: (query: T) => void; onRunQuery: () => void; queryModeller: VisualQueryModeller; explainMode?: boolean; highlightedOp?: QueryBuilderOperation; timeRange?: TimeRange; isConflictingOperation?: (operation: QueryBuilderOperation, otherOperations: QueryBuilderOperation[]) => boolean; } declare function OperationList({ query, datasource, queryModeller, onChange, onRunQuery, highlightedOp, timeRange, isConflictingOperation, }: Props$6): React.JSX.Element; interface Props$5 { query: T; queryModeller: VisualQueryModeller; explainMode?: boolean; stepNumber: number; language: { grammar: Grammar; name: string; }; onMouseEnter?: (op: QueryBuilderOperation, index: number) => void; onMouseLeave?: (op: QueryBuilderOperation, index: number) => void; } declare function OperationListExplained({ query, queryModeller, stepNumber, language, onMouseEnter, onMouseLeave, }: Props$5): React.JSX.Element; declare function OperationsEditorRow({ children }: React.PropsWithChildren<{}>): React.JSX.Element; interface Props$4 { query: TVisualQuery; datasource: DataSourceApi; queryModeller: VisualQueryModeller; buildVisualQueryFromString: (queryString: string) => { query: TVisualQuery; }; buildDataQueryFromQueryString: (queryString: string) => TDataQuery; buildQueryStringFromDataQuery: (dataQuery: TDataQuery) => string; onChange: (update: TVisualQuery) => void; data?: PanelData; } declare const QueryBuilderHints: { ({ datasource, query: visualQuery, onChange, data, queryModeller, buildVisualQueryFromString, buildDataQueryFromQueryString, buildQueryStringFromDataQuery, }: Props$4): React.JSX.Element; displayName: string; }; interface Props$3 { mode: QueryEditorMode; onChange: (mode: QueryEditorMode) => void; } declare function QueryEditorModeToggle({ mode, onChange }: Props$3): React.JSX.Element; interface Props$2 extends Omit, 'value' | 'ref'> { value?: boolean; label: string; } declare function QueryHeaderSwitch({ label, ...inputProps }: Props$2): React.JSX.Element; interface Props$1 { title: string; collapsedInfo: string[]; queryStats?: QueryStats | null; } declare function QueryOptionGroup({ title, children, collapsedInfo, queryStats }: React.PropsWithChildren): React.JSX.Element; interface Props { query: string; language: { grammar: Grammar; name: string; }; className?: string; } declare function RawQuery({ query, language, className }: Props): React.JSX.Element; interface CustomMeta { queryID: string; status: string; } interface RunningQueryInfo { queryID?: string; shouldCancel?: boolean; } declare class DatasourceWithAsyncBackend extends DataSourceWithBackend { private runningQueries; private requestCounter; private requestIdPrefix; constructor(instanceSettings: DataSourceInstanceSettings); query(request: DataQueryRequest): Observable; storeQuery(target: TQuery, queryInfo: RunningQueryInfo): void; getQuery(target: TQuery): RunningQueryInfo; removeQuery(target: TQuery): void; doSingle(target: TQuery, request: DataQueryRequest): Observable; cancel: (target: TQuery) => void; } interface RunQueryButtonsProps { enableRun?: boolean; onRunQuery: () => void; onCancelQuery: (query: TQuery) => void; query: TQuery; state?: LoadingState; } declare const RunQueryButtons: (props: RunQueryButtonsProps) => React.JSX.Element; interface RequestLoopOptions { /** * If the response needs an additional request to execute, return it here */ getNextQuery: (rsp: DataQueryResponse) => TQuery | undefined; /** * The datasource execute method */ query: (req: DataQueryRequest) => Observable; /** * Process the results */ process: (data: DataFrame[]) => DataFrame[]; /** * Check if the query should be cancelled */ shouldCancel: () => boolean; /** * Callback that gets executed when unsubscribed */ onCancel: () => void; } /** * Continue executing requests as long as `getNextQuery` returns a query */ declare function getRequestLooper(req: DataQueryRequest, options: RequestLoopOptions): Observable; export { AUTH_GROUP_IDS, AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, BINARY_OPERATIONS_KEY, CatalogSelector, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, CustomHeadersSettings, DataLink, DataLinks, DataSourceDescription, DataSourcePicker, DatasetSelector, DatasourceConfigWizard, DatasourceErrorBoundary, DatasourceWithAsyncBackend, DatePicker, DatePickerWithInput, DebounceInput, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorStack, EditorSwitch, FlexItem, GroupByRow, InlineSelect, InputGroup, LabelFilters, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, QUERY_FORMAT_OPTIONS, QueryBuilderHints, QueryEditorMode, QueryEditorModeToggle, QueryEditorRow, QueryFormat, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, ROOT_CONFIG_FIELDS, RawQuery, RunQueryButton, RunQueryButtons, SQLEditor, SQLEditorMode, SQLEditorTestUtils, SecureSocksProxyToggle, Segment, Space, SqlDatasource, SqlQueryEditor, StatementPosition, SuggestionKind, TLSSettings, TableSelector, TokenType, buildCelContext, buildCloneDatasourcePayload, buildCreateDatasourcePayload, buildUpdateDatasourcePayload, clearExpressionCache, computeVirtualFieldValues, convertLegacyAuthProps, datasourceToProvisioningYaml, evaluateCelDirect, evaluateCelExpression, evaluateComputedRead, evaluateDependsOn, extractFieldRefs, fetchConfigSchema, formKey, formatDate, formatYamlDiff, generateLLMHint, generateProvisioningTemplate, generateTroubleshootingFields, getConfigSchema, getRequestLooper, getStandardSQLCompletionProvider, getWatchedValue, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, isAuthGroupId, isValidCelExpression, parseDependsOn, resolveActiveOverride, resolveGroups, resolvePluginName, resolveRequiredFieldsGroup, toOption, useDatasourceSchema, useHealthChecks }; export type { Aggregate, AllowedValuesValidationRule, Props$c as AuthProps, BaseFieldRef, BaseValidationRule, ColumnDefinition, ComputedMapping, ConfigField, ConfigGroup, CustomMeta, CustomValidationRule, DB, DataLinkConfig, DatasourceConfigSchema, DatasourceConfigWizardProps, DatasourceHealth, DatePickerProps, DatePickerWithInputProps, DebounceInputProps, DirectMapping, Expression, FieldEffect, FieldItemSchema, FieldKind, FieldOption, FieldOverride, FieldPack, FieldPackID, FieldPatch, FieldRelationship, FieldUI, FieldValidationRule, FormState, HealthState, IndexedPairMapping, Instruction, ItemCountValidationRule, LanguageCompletionProvider, LanguageDefinition, LengthValidationRule, MappingField, MetaDefinition, NameValue, PatternValidationRule, PositionContext, Props$s as Props, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorProps, QueryRowFilter, QueryStats, QueryWithDefaults, RAQBFieldTypes, RangeValidationRule, RelationshipType, RequestLoopOptions, ResolvedGroup, ResourceSelectorProps, ResponseParser, Role, RunQueryButtonsProps, RunningQueryInfo, SQLConnectionLimits, SQLExpression, SQLFilters, SQLMonarchLanguage, SQLOptions, SQLQuery, SQLSelectableValue, SchemaDefinition, SecureFieldState, SegmentProps, SqlQueryForInterpolation, SqlQueryModel, State$1 as State, StatementPlacementProvider, StorageMapping, SuggestionKindProvider, Props$f as TLSSettingsProps, TableDefinition, TableFieldSchema, TableIdentifier, TableSchema, TargetLocation, TestQueryModel, UIComponent, UIWidth, ValidationResults, ValueType, VisualQuery, VisualQueryBinary, VisualQueryModeller };