From 354145d86e2fb84c7f9919e748b38a4623f3a62a Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Tue, 29 Sep 2026 14:24:30 -0400 Subject: [PATCH 1/5] feat: Substitute variables in markdown tiles --- .changeset/markdown-tile-variables.md | 6 + packages/app/src/DBDashboardPage.tsx | 2 + packages/app/src/HDXMarkdownChart.tsx | 21 +++- .../src/__tests__/HDXMarkdownChart.test.tsx | 35 ++++++ .../DBEditTimeChartForm/EditTimeChartForm.tsx | 1 + .../SQLEditor/variableCompletions.tsx | 2 + .../features/dashboard-static-filters.spec.ts | 46 +++++++ .../src/__tests__/variables.test.ts | 117 +++++++++++++++++- packages/common-utils/src/variables.ts | 60 +++++++-- 9 files changed, 280 insertions(+), 10 deletions(-) create mode 100644 .changeset/markdown-tile-variables.md create mode 100644 packages/app/src/__tests__/HDXMarkdownChart.test.tsx diff --git a/.changeset/markdown-tile-variables.md b/.changeset/markdown-tile-variables.md new file mode 100644 index 0000000000..1272dc5923 --- /dev/null +++ b/.changeset/markdown-tile-variables.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +--- + +feat: Substitute dashboard variables in markdown tiles diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 81441a79f5..2710a23cb6 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -1377,6 +1377,7 @@ const Tile = ({ title={title} toolbarItems={toolbar} config={effectiveMarkdownConfig} + variables={tileVariables} /> )} {effectiveQueriedConfig?.displayType === DisplayType.Search && @@ -1495,6 +1496,7 @@ const Tile = ({ annotations, isLive, readOnly, + tileVariables, ], ); diff --git a/packages/app/src/HDXMarkdownChart.tsx b/packages/app/src/HDXMarkdownChart.tsx index 971d6f50b5..2091f1e3d7 100644 --- a/packages/app/src/HDXMarkdownChart.tsx +++ b/packages/app/src/HDXMarkdownChart.tsx @@ -1,5 +1,7 @@ -import { memo } from 'react'; +import { memo, useMemo } from 'react'; import ReactMarkdown from 'react-markdown'; +import { ChartVariable } from '@hyperdx/common-utils/dist/types'; +import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; import ChartContainer from './components/charts/ChartContainer'; @@ -8,13 +10,28 @@ const HDXMarkdownChart = memo( config: { markdown }, title, toolbarItems, + variables, }: { title?: React.ReactNode; toolbarItems?: React.ReactNode[]; config: { markdown?: string; }; + variables?: ChartVariable[]; }) => { + const content = useMemo(() => { + if (!markdown || variables == null) return markdown ?? ''; + try { + return substituteVariables(markdown, { + variables, + inputLanguage: 'markdown', + }); + } catch { + // An unknown `${name:format}` throws; show the markdown as written. + return markdown; + } + }, [markdown, variables]); + return (
- {markdown ?? ''} + {content}
); diff --git a/packages/app/src/__tests__/HDXMarkdownChart.test.tsx b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx new file mode 100644 index 0000000000..a9bc7b4b63 --- /dev/null +++ b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx @@ -0,0 +1,35 @@ +import React from 'react'; +import { screen } from '@testing-library/react'; + +import HDXMarkdownChart from '@/HDXMarkdownChart'; + +const service = { name: 'service', values: ['api', 'web'] }; + +describe('HDXMarkdownChart', () => { + it('substitutes variable references', () => { + renderWithMantine( + , + ); + expect(screen.getByText('# Services: api, web')).toBeInTheDocument(); + }); + + it('renders the markdown as written without variables', () => { + renderWithMantine( + , + ); + expect(screen.getByText('# Services: $service')).toBeInTheDocument(); + }); + + it('renders the markdown as written when a format is unknown', () => { + renderWithMantine( + , + ); + expect(screen.getByText('${service:nope}')).toBeInTheDocument(); + }); +}); diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index 46cad955c2..fdb798e7e5 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -1090,6 +1090,7 @@ export default function EditTimeChartForm({ config={{ markdown: markdown || 'Preview', }} + variables={variables} /> diff --git a/packages/app/src/components/SQLEditor/variableCompletions.tsx b/packages/app/src/components/SQLEditor/variableCompletions.tsx index 22c53246f4..5dd03580fe 100644 --- a/packages/app/src/components/SQLEditor/variableCompletions.tsx +++ b/packages/app/src/components/SQLEditor/variableCompletions.tsx @@ -20,6 +20,8 @@ const VARIABLE_FORMAT_DESCRIPTIONS: Record = { regex: 'A regex alternation. Regex escaped. e.g. (a|b|c)', lucene: 'An OR of quoted terms, for Lucene inputs. e.g. ("a" OR "b" OR "c"). Quote the reference (field:"$var") for exact-match behavior. Leave unquoted (field:$var) for substring matching.', + markdown: + 'Comma-separated with spaces, unquoted, and markdown escaped. e.g. a, b, c', }; /** What `snippet` expands to against the variable's current selection. */ diff --git a/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts index fec1e3e1ea..f2571bade2 100644 --- a/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts @@ -197,6 +197,52 @@ test.describe( }); }); + test('substitutes the selected values into a markdown tile', async ({ + page, + }) => { + test.setTimeout(90000); + const chartName = `E2E Markdown Variables ${Date.now()}`; + + await test.step('Create a static Service filter and select one value', async () => { + await dashboardPage.createNewDashboard(); + await dashboardPage.openEditFiltersModal(); + await dashboardPage.addStaticListFilterToDashboard( + 'Service', + ['frontend', 'accounting', 'ad'], + { variableName: 'svc' }, + ); + await dashboardPage.closeFiltersModal(); + await dashboardPage.toggleFilterValue('Service', 'accounting'); + }); + + await test.step('The editor preview shows the selected value', async () => { + await dashboardPage.addTile(); + await expect(dashboardPage.chartEditor.nameInput).toBeVisible(); + await dashboardPage.chartEditor.setChartType(DisplayType.Markdown); + await dashboardPage.chartEditor.setChartName(chartName); + const editor = page.getByTestId('tile-editor-form'); + await editor + .locator('textarea[name="markdown"]') + .fill('# Services: $svc'); + await expect( + editor.getByRole('heading', { name: 'Services: accounting' }), + ).toBeVisible(); + await dashboardPage.saveTile(); + }); + + await test.step('The tile follows the selection', async () => { + const tile = dashboardPage.getTiles().filter({ hasText: chartName }); + await expect( + tile.getByRole('heading', { name: 'Services: accounting' }), + ).toBeVisible(); + + await dashboardPage.toggleFilterValue('Service', 'frontend'); + await expect( + tile.getByRole('heading', { name: 'Services: accounting, frontend' }), + ).toBeVisible(); + }); + }); + test('round-trips the options and variable name through an edit', async ({ page, }) => { diff --git a/packages/common-utils/src/__tests__/variables.test.ts b/packages/common-utils/src/__tests__/variables.test.ts index eba27788df..b6e178aee1 100644 --- a/packages/common-utils/src/__tests__/variables.test.ts +++ b/packages/common-utils/src/__tests__/variables.test.ts @@ -3,7 +3,7 @@ import { MalformedMacroArgsError, UnknownVariableError, } from '@/macroErrors'; -import type { BuilderChartConfig, ChartVariable } from '@/types'; +import { BuilderChartConfig, ChartVariable, DisplayType } from '@/types'; import { filterReferencedVariables, formatVariableValues, @@ -107,6 +107,31 @@ describe('formatVariableValues', () => { }); }); + describe('markdown', () => { + it('renders empty when nothing is selected', () => { + expect(formatVariableValues([], 'markdown')).toBe(''); + }); + + it('joins values with a comma and a space', () => { + expect(formatVariableValues(['api', 'web'], 'markdown')).toBe('api, web'); + }); + + it('escapes markdown syntax in values', () => { + expect( + formatVariableValues( + ['[x](https://e.com)', '*a_b* \\ `c`'], + 'markdown', + ), + ).toBe('\\[x\\]\\(https\\:\\/\\/e\\.com\\), \\*a\\_b\\* \\\\ \\`c\\`'); + }); + + it('replaces newlines with spaces', () => { + expect(formatVariableValues(['a\n# b\r\nc'], 'markdown')).toBe( + 'a \\# b c', + ); + }); + }); + describe('lucene', () => { it('renders an empty term when nothing is selected', () => { // Parenthesized so it stays a no-op in a field-scoped position; see the @@ -804,6 +829,63 @@ describe('substituteVariables per language', () => { }); }); +describe('substituteVariables for markdown', () => { + const markdown = (input: string, variables: ChartVariable[]) => + substituteVariables(input, { variables, inputLanguage: 'markdown' }); + + it('joins the selected values with a comma and a space by default', () => { + expect(markdown('Services: $service', [SERVICE])).toBe( + 'Services: api, web', + ); + }); + + it('renders nothing when no values are selected', () => { + expect(markdown('Services: ${service}', [EMPTY_SERVICE])).toBe( + 'Services: ', + ); + }); + + it('substitutes in headings and lines SQL would treat as comments', () => { + expect(markdown('# $service\n-- $service /* $service */', [SERVICE])).toBe( + '# api, web\n-- api, web /* api, web */', + ); + }); + + it('substitutes after an apostrophe', () => { + expect(markdown("Today's services: $service", [SERVICE])).toBe( + "Today's services: api, web", + ); + }); + + it('substitutes inside link URLs', () => { + expect(markdown('[logs](/search?where=${service:csv})', [SERVICE])).toBe( + '[logs](/search?where=api,web)', + ); + }); + + it('honors an explicit format', () => { + expect(markdown('${service:regex}', [SERVICE])).toBe('(api|web)'); + }); + + it('escapes markdown syntax in values by default', () => { + expect(markdown('$service', [variable('service', ['*prod*'])])).toBe( + '\\*prod\\*', + ); + }); + + it('leaves values unescaped with the csv format', () => { + expect( + markdown('`${service:csv}`', [variable('service', ['*prod*'])]), + ).toBe('`*prod*`'); + }); + + it('leaves unknown references and variable macros as written', () => { + expect(markdown('$nope $__filter(ServiceName, $service)', [SERVICE])).toBe( + '$nope $__filter(ServiceName, $service)', + ); + }); +}); + describe('substituteVariables for promql', () => { const promql = (input: string, variables: ChartVariable[]) => substituteVariables(input, { variables, inputLanguage: 'promql' }); @@ -1248,6 +1330,15 @@ describe('getReferencedVariableNames', () => { 'env', ]); }); + + it('skips SQL comments for SQL but not for markdown', () => { + const template = '# $service\n$env'; + expect(getReferencedVariableNames(template)).toEqual(['env']); + expect(getReferencedVariableNames(template, 'markdown')).toEqual([ + 'service', + 'env', + ]); + }); }); describe('filterReferencedVariables', () => { @@ -1332,6 +1423,30 @@ describe('filterReferencedVariables', () => { ).toEqual(variables); }); + it('keeps the variables a markdown tile references', () => { + expect( + filterReferencedVariables( + builderConfig({ + displayType: DisplayType.Markdown, + markdown: '# Service $service', + }), + variables, + ), + ).toEqual([SERVICE]); + }); + + it('ignores leftover markdown on a tile that is not markdown', () => { + expect( + filterReferencedVariables( + builderConfig({ + displayType: DisplayType.Line, + markdown: '$service', + }), + variables, + ), + ).toEqual([]); + }); + it('returns an empty array when a builder config references none of them', () => { expect( filterReferencedVariables( diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index ada287378d..6c9d6ab1ab 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -21,6 +21,7 @@ import { ChartVariable, DASHBOARD_VARIABLE_NAME_PATTERN, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, + DisplayType, PromqlExpressionList, SavedChartConfig, SearchConditionLanguage, @@ -34,6 +35,7 @@ export const VARIABLE_FORMATS = [ 'regex', 'csv', 'lucene', + 'markdown', ] as const; export type VariableFormat = (typeof VARIABLE_FORMATS)[number]; @@ -51,6 +53,15 @@ const escapeLuceneValue = (value: string) => const escapePromqlStringValue = (value: string) => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); +/** + * Backslash-escape every ASCII punctuation character (CommonMark renders each + * escape as the literal character), so a value renders as plain text rather + * than as markdown syntax. Newlines become spaces so a value can't split the + * surrounding block. + */ +const escapeMarkdownValue = (value: string) => + value.replace(/\r\n|\r|\n/g, ' ').replace(/[!-/:-@[-`{-~]/g, '\\$&'); + /** * Render a variable's selected values in the requested format. Every format * has an "empty selection" rendering that keeps the surrounding query valid. @@ -75,6 +86,8 @@ export function formatVariableValues( return values.length === 0 ? '("")' : `(${values.map(value => `"${escapeLuceneValue(value)}"`).join(' OR ')})`; + case 'markdown': + return values.map(escapeMarkdownValue).join(', '); default: format satisfies never; // Unreachable throw new Error(`Unknown variable format '${format}'`); @@ -197,7 +210,14 @@ export function findBalancedParens(input: string, start: number): number { export function scanTemplateTokens( input: string, macroNames: readonly string[], - { onMalformed = 'throw' }: { onMalformed?: 'throw' | 'skip' } = {}, + { + onMalformed = 'throw', + skipSqlComments = true, + }: { + onMalformed?: 'throw' | 'skip'; + /** Whether SQL comments are skipped over rather than scanned for references. */ + skipSqlComments?: boolean; + } = {}, ): TemplateToken[] { // Longest name first so `$__filters` isn't matched as `$__filter` + `s`, etc. const sortedMacroNames = [...macroNames].sort((a, b) => b.length - a.length); @@ -219,7 +239,7 @@ export function scanTemplateTokens( let i = 0; while (i < input.length) { // Consume any comments starting at this position - if (!inSingleQuote && !inDoubleQuote) { + if (skipSqlComments && !inSingleQuote && !inDoubleQuote) { const commentEnd = findCommentEnd(input, i); if (commentEnd > i) { text += input.slice(i, commentEnd); @@ -405,7 +425,9 @@ export function expandTemplate( // -- Variable expansion ----------------------------------------------------- -export type TemplateLanguage = NonNullable; +export type TemplateLanguage = + | NonNullable + | 'markdown'; export type VariableContext = { variables: ChartVariable[]; @@ -427,6 +449,11 @@ type LanguageSettings = { * themselves, and `csv` is the raw escape hatch that carries identifiers. */ escapeRegexForLiteral?: (rendered: string) => string; + /** + * Whether SQL comments (`--`, `#`, block comments) are skipped over rather + * than scanned for references. + */ + skipSqlComments?: boolean; }; /** Settings controlling how variables and templates are expanded for each template language. */ @@ -441,6 +468,12 @@ const LANGUAGE_SETTINGS: Record = { disableMacros: true, escapeRegexForLiteral: escapePromqlStringValue, }, + markdown: { + defaultFormat: 'markdown', + disableMacros: true, + // Markdown doesn't have SQL comments, we wouldn't want to skip # ... (a markdown header) + skipSqlComments: false, + }, }; const SETTINGS_BY_LANGUAGE = new Map(Object.entries(LANGUAGE_SETTINGS)); @@ -859,9 +892,11 @@ export function substituteVariables( ); } - if (languageSettings(ctx.inputLanguage).disableMacros) { + const settings = languageSettings(ctx.inputLanguage); + if (settings.disableMacros) { return scanTemplateTokens(input, VARIABLE_MACRO_NAMES, { onMalformed: 'skip', + skipSqlComments: settings.skipSqlComments, }) .map(token => expandVariableOnly(token, ctx)) .join(''); @@ -1061,7 +1096,10 @@ export type VariableReference = { * template written that way is reported as using the macro; expansion is what * rejects it. */ -export function getVariableReferences(input: string): VariableReference[] { +export function getVariableReferences( + input: string, + { skipSqlComments }: { skipSqlComments?: boolean } = {}, +): VariableReference[] { const references: VariableReference[] = []; /** Returns the referenced name, or undefined when the argument isn't one. */ @@ -1086,6 +1124,7 @@ export function getVariableReferences(input: string): VariableReference[] { const visit = (text: string, guardedBy?: string) => { for (const token of scanTemplateTokens(text, VARIABLE_MACRO_NAMES, { onMalformed: 'skip', + skipSqlComments, })) { if (token.kind === 'text') continue; if (token.kind !== 'macro') { @@ -1298,9 +1337,13 @@ export function validateVariableReferencesInTemplate( * Returns the names of every variable the template could reference. * Never throws: it runs over saved SQL that may be mid-edit or malformed. */ -export function getReferencedVariableNames(input: string): string[] { +export function getReferencedVariableNames( + input: string, + language: TemplateLanguage = 'sql', +): string[] { + const { skipSqlComments } = languageSettings(language); const names = new Set( - getVariableReferences(input).map(ref => ref.name), + getVariableReferences(input, { skipSqlComments }).map(ref => ref.name), ); return Array.from(names); } @@ -1333,6 +1376,9 @@ export function filterReferencedVariables( names = getBuilderVariableReferences(config).map( reference => reference.name, ); + if (config.displayType === DisplayType.Markdown && config.markdown) { + names.push(...getReferencedVariableNames(config.markdown, 'markdown')); + } } const referenced = new Set(names); From 00c6d454cc80b1e2a7097a1a67161fe60dc64fd2 Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Tue, 29 Sep 2026 14:43:16 -0400 Subject: [PATCH 2/5] feat: Show warning when markdown tile references unknown variable --- packages/app/src/DBDashboardPage.tsx | 4 +-- packages/app/src/HDXMarkdownChart.tsx | 25 +++++++++++-- .../src/__tests__/HDXMarkdownChart.test.tsx | 27 ++++++++++++++ .../features/dashboard-static-filters.spec.ts | 9 +++-- .../src/__tests__/variables.test.ts | 36 +++++++++++++++++++ packages/common-utils/src/variables.ts | 32 +++++++++++++---- 6 files changed, 120 insertions(+), 13 deletions(-) diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 2710a23cb6..5cb770da9f 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -1377,7 +1377,7 @@ const Tile = ({ title={title} toolbarItems={toolbar} config={effectiveMarkdownConfig} - variables={tileVariables} + variables={variables} /> )} {effectiveQueriedConfig?.displayType === DisplayType.Search && @@ -1496,7 +1496,7 @@ const Tile = ({ annotations, isLive, readOnly, - tileVariables, + variables, ], ); diff --git a/packages/app/src/HDXMarkdownChart.tsx b/packages/app/src/HDXMarkdownChart.tsx index 2091f1e3d7..e65eeb8632 100644 --- a/packages/app/src/HDXMarkdownChart.tsx +++ b/packages/app/src/HDXMarkdownChart.tsx @@ -1,9 +1,16 @@ import { memo, useMemo } from 'react'; import ReactMarkdown from 'react-markdown'; import { ChartVariable } from '@hyperdx/common-utils/dist/types'; -import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; +import { + substituteVariables, + validateVariableReferencesInTemplate, +} from '@hyperdx/common-utils/dist/variables'; import ChartContainer from './components/charts/ChartContainer'; +import { + hasVariableIssues, + VariableIssueIndicator, +} from './components/SQLEditor/variableValidation'; const HDXMarkdownChart = memo( ({ @@ -32,10 +39,24 @@ const HDXMarkdownChart = memo( } }, [markdown, variables]); + const toolbar = useMemo(() => { + // Without variables in scope nothing is substituted, so a `$word` is prose. + if (!markdown || !variables?.length) return toolbarItems; + const issues = validateVariableReferencesInTemplate(markdown, variables, { + subject: 'Markdown', + language: 'markdown', + }); + if (!hasVariableIssues(issues)) return toolbarItems; + return [ + , + ...(toolbarItems ?? []), + ]; + }, [markdown, variables, toolbarItems]); + return (
diff --git a/packages/app/src/__tests__/HDXMarkdownChart.test.tsx b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx index a9bc7b4b63..2d205af64b 100644 --- a/packages/app/src/__tests__/HDXMarkdownChart.test.tsx +++ b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx @@ -32,4 +32,31 @@ describe('HDXMarkdownChart', () => { ); expect(screen.getByText('${service:nope}')).toBeInTheDocument(); }); + + it('flags a reference to an unknown variable', () => { + renderWithMantine( + , + ); + expect(screen.getByTestId('variable-validation')).toHaveAccessibleName( + 'Markdown references unknown variable $nope. Available variables: service.', + ); + }); + + it('flags nothing when every reference is known', () => { + renderWithMantine( + , + ); + expect(screen.queryByTestId('variable-validation')).not.toBeInTheDocument(); + }); + + it('flags nothing without variables', () => { + renderWithMantine(); + expect(screen.queryByTestId('variable-validation')).not.toBeInTheDocument(); + }); }); diff --git a/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts index f2571bade2..9f14b47262 100644 --- a/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-static-filters.spec.ts @@ -221,9 +221,12 @@ test.describe( await dashboardPage.chartEditor.setChartType(DisplayType.Markdown); await dashboardPage.chartEditor.setChartName(chartName); const editor = page.getByTestId('tile-editor-form'); - await editor - .locator('textarea[name="markdown"]') - .fill('# Services: $svc'); + const markdownInput = editor.locator('textarea[name="markdown"]'); + await markdownInput.fill('# Services: $nope'); + await expect(editor.getByTestId('variable-validation')).toBeVisible(); + + await markdownInput.fill('# Services: $svc'); + await expect(editor.getByTestId('variable-validation')).toBeHidden(); await expect( editor.getByRole('heading', { name: 'Services: accounting' }), ).toBeVisible(); diff --git a/packages/common-utils/src/__tests__/variables.test.ts b/packages/common-utils/src/__tests__/variables.test.ts index b6e178aee1..7a767d2be1 100644 --- a/packages/common-utils/src/__tests__/variables.test.ts +++ b/packages/common-utils/src/__tests__/variables.test.ts @@ -2055,6 +2055,42 @@ describe('validateVariableReferencesInTemplate', () => { }); }); }); + + describe('for markdown', () => { + const markdown = (template: string, variables: ChartVariable[]) => + validate(template, variables, { + subject: 'Markdown', + language: 'markdown', + }); + + it('says nothing when every reference is known', () => { + expect(markdown("# $service\nToday's ${service:csv}", [SERVICE])).toEqual( + { errors: [], warnings: [] }, + ); + }); + + it('checks references in headings', () => { + expect(markdown('# $srvice', [SERVICE]).warnings).toEqual([ + 'Markdown references unknown variable $srvice. Available variables: service.', + ]); + }); + + it('warns about an unknown format', () => { + expect(markdown('${service:nope}', [SERVICE]).warnings).toEqual([ + '${service:nope} uses an unknown format, so no variables are substituted. ' + + 'Expected one of: sqlstring, regex, csv, lucene, markdown.', + ]); + }); + + it('warns that a macro is left as written', () => { + expect( + markdown('$__filter(ServiceName, $service)', [SERVICE]).warnings, + ).toEqual([ + '$__filter has no meaning in markdown — it is left as written. ' + + 'Reference the variable directly, as in $service.', + ]); + }); + }); }); describe('macros naming an unknown variable', () => { diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index 6c9d6ab1ab..f90c1e397c 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -1211,13 +1211,16 @@ export function validateVariableReferencesInTemplate( /** The sentence subject of each message, e.g. `SQL references ...`. */ subject?: string; /** The language the renderer parses this template as. */ - language?: SearchConditionLanguage; + language?: TemplateLanguage; } = {}, ): VariableReferenceIssues { const errors: string[] = []; const warnings: string[] = []; - const references = getVariableReferences(template); + const settings = languageSettings(language); + const references = getVariableReferences(template, { + skipSqlComments: settings.skipSqlComments, + }); // Attempt to expand macros, so that errors during expansion can be surfaced. if (variables != null && hasVariableMacro(template)) { @@ -1266,19 +1269,36 @@ export function validateVariableReferencesInTemplate( ); } - const settings = languageSettings(language); - // A macro-less language leaves a macro exactly as written, so writing one can // only ever have been a mistake. if (settings.disableMacros && macroReferences.length > 0) { const [{ name }] = macroReferences; + const macros = formatReferenceList(macroReferences); warnings.push( language === 'promql' - ? `${formatReferenceList(macroReferences)} has no meaning in a PromQL expression — it is left as written and sent to Prometheus verbatim. Reference the variable directly, as in {