diff --git a/packages/app/package.json b/packages/app/package.json index 7dc5623be4..a5d35ad922 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -14,7 +14,7 @@ "build:clickhouse": "NEXT_PUBLIC_IS_LOCAL_MODE=true NEXT_PUBLIC_CLICKHOUSE_BUILD=true next build --webpack && node scripts/prepare-clickhouse-build-export.js", "run:clickhouse": "test -d out && npx rimraf tmp && mkdir tmp && cp -r out tmp/clickstack && echo 'visit http://localhost:3000/clickstack to start' && npx serve tmp -l 3000 || echo 'run build:clickhouse first'", "start": "next start", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 372 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 199 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt '**/*.{ts,tsx,css,scss}'", "lint:styles": "stylelint **/*/*.{css,scss}", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:styles --quiet", diff --git a/packages/app/src/__tests__/ChartUtils.test.ts b/packages/app/src/__tests__/ChartUtils.test.ts index 612f026a43..27b36af13e 100644 --- a/packages/app/src/__tests__/ChartUtils.test.ts +++ b/packages/app/src/__tests__/ChartUtils.test.ts @@ -1,4 +1,5 @@ import { DEFAULT_PROMQL_REDUCER } from '@hyperdx/common-utils/dist/core/promql'; +import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { BuilderChartConfigWithDateRange, DisplayType, @@ -6,6 +7,7 @@ import { SourceKind, TSource, } from '@hyperdx/common-utils/dist/types'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { ChartKeyJoiner, @@ -421,10 +423,10 @@ describe('ChartUtils', () => { ], }; - const source = { + const source = fromPartial({ kind: SourceKind.Log, severityTextExpression: 'SeverityText', - } as TSource; + }); const actual = formatResponseForTimeChart({ currentPeriodResponse: res, @@ -1339,13 +1341,13 @@ describe('ChartUtils', () => { describe('convertToTimeChartConfig', () => { it('should set granularity when granularity is auto', () => { - const config = { + const config = fromPartial({ granularity: 'auto', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const granularityFromFunction = convertToTimeChartConfig(config).granularity; @@ -1354,12 +1356,12 @@ describe('ChartUtils', () => { }); it('should set granularity when granularity is undefined', () => { - const config = { + const config = fromPartial({ dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const granularityFromFunction = convertToTimeChartConfig(config).granularity; @@ -1368,13 +1370,13 @@ describe('ChartUtils', () => { }); it('should retain the specified granularity when not auto', () => { - const config = { + const config = fromPartial({ granularity: '5 minute', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const granularityFromFunction = convertToTimeChartConfig(config).granularity; @@ -1385,17 +1387,22 @@ describe('ChartUtils', () => { // seriesLimit lives on the builder member of the ChartConfigWithDateRange // union, so narrow the result before reading it. The per-tile value is // read from the config itself (no team override anymore). - const seriesLimitOf = (seriesLimit?: number | null) => - ( - convertToTimeChartConfig({ + const seriesLimitOf = (seriesLimit?: number | null) => { + const result = convertToTimeChartConfig( + fromPartial({ granularity: '5 minute', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], ...(seriesLimit !== undefined ? { seriesLimit } : {}), - } as BuilderChartConfigWithDateRange) as BuilderChartConfigWithDateRange - ).seriesLimit; + }), + ); + if (!isBuilderChartConfig(result)) { + throw new Error('Expected builder chart config'); + } + return result.seriesLimit; + }; it('omits seriesLimit (capping disabled) when the tile has no limit', () => { expect(seriesLimitOf()).toBeUndefined(); @@ -1416,14 +1423,14 @@ describe('ChartUtils', () => { describe('convertToNumberChartConfig', () => { it('should remove granularity and groupBy from the config', () => { - const config = { + const config = fromPartial({ granularity: '5 minute', groupBy: 'ServiceName', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const convertedConfig = convertToNumberChartConfig(config); @@ -1619,13 +1626,13 @@ describe('ChartUtils', () => { describe('convertToTableChartConfig', () => { it('should remove granularity from the config', () => { - const config = { + const config = fromPartial({ granularity: '5 minute', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const convertedConfig = convertToTableChartConfig(config); @@ -1633,13 +1640,13 @@ describe('ChartUtils', () => { }); it('should apply a default sort if none is provided', () => { - const config = { + const config = fromPartial({ groupBy: 'ServiceName', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const convertedConfig = convertToTableChartConfig(config); @@ -1647,13 +1654,13 @@ describe('ChartUtils', () => { }); it('should apply a default limit if none is provided', () => { - const config = { + const config = fromPartial({ groupBy: 'ServiceName', dateRange: [ new Date('2025-11-26T00:00:00Z'), new Date('2025-11-27T00:00:00Z'), ], - } as BuilderChartConfigWithDateRange; + }); const convertedConfig = convertToTableChartConfig(config); @@ -1679,7 +1686,7 @@ describe('ChartUtils', () => { it('throws when meta is missing', () => { expect(() => formatResponseForCategoricalChart( - { data: [{ 'count()': 10 }] } as any, + fromAny({ data: [{ 'count()': 10 }] }), getColor, ), ).toThrow('No meta data found in response'); @@ -2116,19 +2123,20 @@ describe('getSelectSeriesColors', () => { }); describe('convertV1ChartConfigToV2', () => { - const metricSource = { - id: 'metric-source', - kind: SourceKind.Metric, - connection: 'connection-id', - from: { databaseName: 'default', tableName: '' }, - timestampValueExpression: 'TimeUnix', - resourceAttributesExpression: 'ResourceAttributes', - metricTables: { - gauge: 'otel_metrics_gauge', - histogram: 'otel_metrics_histogram', - sum: 'otel_metrics_sum', - }, - } as unknown as Parameters[1]['metric']; + const metricSource: Parameters[1]['metric'] = + fromPartial({ + id: 'metric-source', + kind: SourceKind.Metric, + connection: 'connection-id', + from: { databaseName: 'default', tableName: '' }, + timestampValueExpression: 'TimeUnix', + resourceAttributesExpression: 'ResourceAttributes', + metricTables: { + gauge: 'otel_metrics_gauge', + histogram: 'otel_metrics_histogram', + sum: 'otel_metrics_sum', + }, + }); const convertMetricSeries = (aggFn: 'p95' | 'p99_rate' | 'avg') => convertV1ChartConfigToV2( diff --git a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx index 804ad86341..ee2f10fb60 100644 --- a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx +++ b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx @@ -2,6 +2,7 @@ import { type DashboardTemplate, DashboardTemplateSchema, DashboardWithoutIdSchema, + DisplayType, SourceKind, } from '@hyperdx/common-utils/dist/types'; import { act, fireEvent, screen, waitFor } from '@testing-library/react'; @@ -95,7 +96,7 @@ jest.mock('../api', () => ({ // satisfy the schema without a real query. const builderTile = ( id: string, - displayType: string, + displayType: DisplayType, source: string, y: number, ) => ({ @@ -129,7 +130,7 @@ const allTileTypesTemplate: DashboardTemplate = { h: 1, config: { name: 'tile-markdown', - displayType: 'markdown', + displayType: DisplayType.Markdown, source: '', where: '', whereLanguage: 'sql', @@ -137,13 +138,13 @@ const allTileTypesTemplate: DashboardTemplate = { markdown: '## Overview', }, }, - builderTile('tile-number', 'number', 'Metrics', 1), - builderTile('tile-line', 'line', 'Metrics', 4), - builderTile('tile-stacked_bar', 'stacked_bar', 'Metrics', 7), - builderTile('tile-table', 'table', 'Traces', 10), - builderTile('tile-pie', 'pie', 'Metrics', 13), - builderTile('tile-heatmap', 'heatmap', 'Traces', 16), - builderTile('tile-search', 'search', 'Logs', 19), + builderTile('tile-number', DisplayType.Number, 'Metrics', 1), + builderTile('tile-line', DisplayType.Line, 'Metrics', 4), + builderTile('tile-stacked_bar', DisplayType.StackedBar, 'Metrics', 7), + builderTile('tile-table', DisplayType.Table, 'Traces', 10), + builderTile('tile-pie', DisplayType.Pie, 'Metrics', 13), + builderTile('tile-heatmap', DisplayType.Heatmap, 'Traces', 16), + builderTile('tile-search', DisplayType.Search, 'Logs', 19), { id: 'tile-rawsql', x: 0, @@ -152,7 +153,7 @@ const allTileTypesTemplate: DashboardTemplate = { h: 3, config: { name: 'tile-rawsql', - displayType: 'table', + displayType: DisplayType.Table, configType: 'sql', connection: 'Default', sqlTemplate: 'SELECT 1', @@ -170,7 +171,7 @@ const allTileTypesTemplate: DashboardTemplate = { whereLanguage: 'sql', }, ], -} as DashboardTemplate; +}; // A template whose only filter names a source that doesn't exist in the // workspace, so the auto-mapping effect can't resolve it and the mapping select @@ -178,7 +179,7 @@ const allTileTypesTemplate: DashboardTemplate = { const unresolvedFilterSourceTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Unresolved Filter Source', - tiles: [builderTile('tile-number', 'number', 'Metrics', 0)], + tiles: [builderTile('tile-number', DisplayType.Number, 'Metrics', 0)], filters: [ { id: 'filter-machine', @@ -196,7 +197,7 @@ const unresolvedFilterSourceTemplate = DashboardTemplateSchema.parse({ const promqlFilterTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'PromQL Label Filter', - tiles: [builderTile('tile-number', 'number', 'Metrics', 0)], + tiles: [builderTile('tile-number', DisplayType.Number, 'Metrics', 0)], filters: [ { id: 'filter-service', @@ -217,7 +218,7 @@ const promqlFilterTemplate = DashboardTemplateSchema.parse({ const promqlFilterOnLogSourceTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'PromQL Label Filter On Log Source', - tiles: [builderTile('tile-number', 'number', 'Metrics', 0)], + tiles: [builderTile('tile-number', DisplayType.Number, 'Metrics', 0)], filters: [ { id: 'filter-service', @@ -237,7 +238,7 @@ const promqlFilterOnLogSourceTemplate = DashboardTemplateSchema.parse({ const queriedFilterTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Queried Filter', - tiles: [builderTile('tile-number', 'number', 'Metrics', 0)], + tiles: [builderTile('tile-number', DisplayType.Number, 'Metrics', 0)], filters: [ { id: 'filter-service', @@ -274,7 +275,7 @@ const MISSING = 'Does Not Exist In This Workspace'; const unresolvedTileSourceTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Unresolved Tile Source', - tiles: [builderTile('tile-number', 'number', MISSING, 0)], + tiles: [builderTile('tile-number', DisplayType.Number, MISSING, 0)], }); const unresolvedConnectionTemplate = DashboardTemplateSchema.parse({ @@ -303,7 +304,7 @@ const sqlQueryFilterTemplate = (connection: string, source?: string) => DashboardTemplateSchema.parse({ version: '0.1.0', name: 'SQL Query Filter', - tiles: [builderTile('tile-number', 'number', 'Metrics', 0)], + tiles: [builderTile('tile-number', DisplayType.Number, 'Metrics', 0)], filters: [ { id: 'filter-env', @@ -325,7 +326,7 @@ const markdownStaleSourceTemplate = DashboardTemplateSchema.parse({ name: 'Markdown With Stale Source', tiles: [ markdownTileWithSource('tile-markdown', MISSING, 0), - builderTile('tile-number', 'number', 'Metrics', 1), + builderTile('tile-number', DisplayType.Number, 'Metrics', 1), ], }); @@ -761,7 +762,7 @@ describe('Dashboard import - filter source kind', () => { const adhocFilterTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Ad Hoc Filter', - tiles: [builderTile('tile-search', 'search', 'Logs', 0)], + tiles: [builderTile('tile-search', DisplayType.Search, 'Logs', 0)], filters: [ { id: 'filter-adhoc', @@ -877,7 +878,7 @@ describe('Dashboard import - data source variables', () => { const sourceVariableTemplate = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Source Variables', - tiles: [builderTile('tile-line', 'line', '$logs', 0)], + tiles: [builderTile('tile-line', DisplayType.Line, '$logs', 0)], filters: [ { id: 'ds', @@ -937,7 +938,7 @@ describe('Dashboard import - data source variables', () => { const template = DashboardTemplateSchema.parse({ version: '0.1.0', name: 'Undeclared', - tiles: [builderTile('tile-line', 'line', '$traces', 0)], + tiles: [builderTile('tile-line', DisplayType.Line, '$traces', 0)], filters: [ { id: 'svc', diff --git a/packages/app/src/__tests__/DBSearchPageQueryKey.test.tsx b/packages/app/src/__tests__/DBSearchPageQueryKey.test.tsx index 28b8a3b200..dee87aecca 100644 --- a/packages/app/src/__tests__/DBSearchPageQueryKey.test.tsx +++ b/packages/app/src/__tests__/DBSearchPageQueryKey.test.tsx @@ -7,6 +7,7 @@ import { import { DBTimeChart } from '@/components/DBTimeChart'; import SearchTotalCountChart from '@/components/SearchTotalCountChart'; +import { useQueriedChartConfig } from '@/hooks/useChartConfig'; // Mock the API and hooks jest.mock('@/hooks/useResultColumnFilterKeys', () => ({ @@ -72,11 +73,11 @@ jest.mock('@/ChartUtils', () => ({ })); describe('DBSearchPage QueryKey Consistency', () => { - let mockUseQueriedChartConfig: jest.Mock; + const mockUseQueriedChartConfig: jest.Mock = jest.mocked( + useQueriedChartConfig, + ); - beforeEach(async () => { - mockUseQueriedChartConfig = (await import('@/hooks/useChartConfig')) - .useQueriedChartConfig as any; + beforeEach(() => { mockUseQueriedChartConfig.mockClear(); }); diff --git a/packages/app/src/__tests__/KubernetesDashboardPage.test.ts b/packages/app/src/__tests__/KubernetesDashboardPage.test.ts index bdce33dc47..e4805b0c20 100644 --- a/packages/app/src/__tests__/KubernetesDashboardPage.test.ts +++ b/packages/app/src/__tests__/KubernetesDashboardPage.test.ts @@ -1,51 +1,52 @@ import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { resolveSourceIds } from '@/KubernetesDashboardPage'; describe('resolveSourceIds', () => { - const mockLogSource: TSource = { + const mockLogSource: TSource = fromPartial({ id: 'log-1', name: 'Log Source 1', kind: SourceKind.Log, connection: 'connection-1', metricSourceId: 'metric-1', - } as TSource; + }); - const mockMetricSource: TSource = { + const mockMetricSource: TSource = fromPartial({ id: 'metric-1', name: 'Metric Source 1', kind: SourceKind.Metric, connection: 'connection-1', logSourceId: 'log-1', - } as TSource; + }); - const mockMetricSourceNotCorrelated: TSource = { + const mockMetricSourceNotCorrelated: TSource = fromPartial({ id: 'metric-1-not-correlated', name: 'Metric Source Not Correlated', kind: SourceKind.Metric, connection: 'connection-1', - } as TSource; + }); - const mockLogSourceNotCorrelated: TSource = { + const mockLogSourceNotCorrelated: TSource = fromPartial({ id: 'log-1-not-correlated', name: 'Log Source Not Correlated', kind: SourceKind.Log, connection: 'connection-1', - } as TSource; + }); - const mockLogSource2: TSource = { + const mockLogSource2: TSource = fromPartial({ id: 'log-2', name: 'Log Source 2', kind: SourceKind.Log, connection: 'connection-2', - } as TSource; + }); - const mockMetricSource2: TSource = { + const mockMetricSource2: TSource = fromPartial({ id: 'metric-2', name: 'Metric Source 2', kind: SourceKind.Metric, connection: 'connection-2', - } as TSource; + }); describe('when both source IDs are provided', () => { it('should return both source IDs as-is', () => { @@ -290,18 +291,18 @@ describe('resolveSourceIds', () => { describe('edge cases', () => { it('should handle multiple sources on the same connection', () => { - const logSource3: TSource = { + const logSource3: TSource = fromPartial({ id: 'log-3', name: 'Log Source 3', kind: SourceKind.Log, connection: 'connection-1', - } as TSource; - const metricSource3: TSource = { + }); + const metricSource3: TSource = fromPartial({ id: 'metric-3', name: 'Metric Source 3', kind: SourceKind.Metric, connection: 'connection-1', - } as TSource; + }); const sources = [ mockLogSource, logSource3, diff --git a/packages/app/src/__tests__/SessionSidePanel.test.tsx b/packages/app/src/__tests__/SessionSidePanel.test.tsx index f61eff31e5..951fcfeaec 100644 --- a/packages/app/src/__tests__/SessionSidePanel.test.tsx +++ b/packages/app/src/__tests__/SessionSidePanel.test.tsx @@ -1,6 +1,7 @@ import { MantineProvider } from '@mantine/core'; import { Notifications, notifications } from '@mantine/notifications'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import SessionSidePanel from '@/SessionSidePanel'; import { @@ -82,19 +83,17 @@ function renderPanel() { diff --git a/packages/app/src/__tests__/dashboard.remote.test.ts b/packages/app/src/__tests__/dashboard.remote.test.ts index 498bab00cb..1a49f6daa1 100644 --- a/packages/app/src/__tests__/dashboard.remote.test.ts +++ b/packages/app/src/__tests__/dashboard.remote.test.ts @@ -286,10 +286,9 @@ describe('normalizeRawDashboardTileColors', () => { it('leaves unresolvable color strings in place for the schema to flag', () => { const input = { tiles: [{ config: { color: 'chart-future-magenta' } }] }; - const result = normalizeRawDashboardTileColors(input) as { - tiles: Array<{ config: { color: string } }>; - }; - expect(result.tiles[0].config.color).toBe('chart-future-magenta'); + expect(normalizeRawDashboardTileColors(input)).toMatchObject({ + tiles: [{ config: { color: 'chart-future-magenta' } }], + }); }); it('returns the input untouched when tiles is missing or non-array', () => { diff --git a/packages/app/src/__tests__/localStore.test.ts b/packages/app/src/__tests__/localStore.test.ts index daf94c5303..25b77ac6e1 100644 --- a/packages/app/src/__tests__/localStore.test.ts +++ b/packages/app/src/__tests__/localStore.test.ts @@ -1,4 +1,5 @@ -import { SavedSearch, TSource } from '@hyperdx/common-utils/dist/types'; +import { SavedSearch } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; // Mock config so we can control HDX_LOCAL_DEFAULT_SOURCES in tests jest.mock('../config', () => ({ @@ -325,10 +326,7 @@ describe('localSources', () => { const envDefaults = [{ id: 'env-src', name: 'Env Source' }]; mockedConfig.HDX_LOCAL_DEFAULT_SOURCES = JSON.stringify(envDefaults); - const stored = localSources.create({ name: 'My Source' } as Omit< - TSource, - 'id' - >); + const stored = localSources.create(fromPartial({ name: 'My Source' })); mockedUtils.parseJSON.mockClear(); const all = localSources.getAll(); diff --git a/packages/app/src/__tests__/searchFilters.test.ts b/packages/app/src/__tests__/searchFilters.test.ts index 798a4fed23..8b468d5225 100644 --- a/packages/app/src/__tests__/searchFilters.test.ts +++ b/packages/app/src/__tests__/searchFilters.test.ts @@ -1,5 +1,6 @@ import { enableMapSet } from 'immer'; import { filtersToQuery } from '@hyperdx/common-utils/dist/filters'; +import type { Filter } from '@hyperdx/common-utils/dist/types'; import { act, renderHook } from '@testing-library/react'; import { @@ -962,7 +963,7 @@ describe('searchFilters', () => { }); describe('useSearchPageFilterState', () => { - const onFilterChange = jest.fn(); + const onFilterChange = jest.fn(); it('adding filter to empty query', () => { const { result } = renderHook(() => @@ -1013,9 +1014,9 @@ describe('searchFilters', () => { result.current.setFilterValue('source_name', 'EMAIL_SERVICE'); }); - const conditions = ( - onFilterChange.mock.lastCall![0] as ConditionFilter[] - ).map(f => f.condition); + const conditions = onFilterChange.mock.lastCall![0].flatMap(f => + f.type === 'sql_ast' ? [] : [f.condition], + ); // Re-persisting must not rewrite the existing key into Map bracket form // (`message['email']`), which ClickHouse rejects for a JSON column. expect(conditions).toContain( @@ -1041,9 +1042,9 @@ describe('searchFilters', () => { result.current.setFilterValue('source_name', 'EMAIL_SERVICE'); }); - const conditions = ( - onFilterChange.mock.lastCall![0] as ConditionFilter[] - ).map(f => f.condition); + const conditions = onFilterChange.mock.lastCall![0].flatMap(f => + f.type === 'sql_ast' ? [] : [f.condition], + ); expect(conditions).toContain(arrayPathCondition); }); diff --git a/packages/app/src/__tests__/serviceDashboard.test.ts b/packages/app/src/__tests__/serviceDashboard.test.ts index 5075b0dc24..a26406425d 100644 --- a/packages/app/src/__tests__/serviceDashboard.test.ts +++ b/packages/app/src/__tests__/serviceDashboard.test.ts @@ -288,7 +288,7 @@ describe('Service Dashboard', () => { }); describe('useServiceDashboardExpressions', () => { - const mockColumns: ColumnMeta[] = [ + const mockColumns: ColumnMeta[] = fromPartial([ { name: 'Duration', type: 'UInt64' }, { name: 'TraceId', type: 'String' }, { name: 'ServiceName', type: 'String' }, @@ -296,7 +296,7 @@ describe('Service Dashboard', () => { { name: 'SpanKind', type: 'String' }, { name: 'StatusCode', type: 'String' }, { name: 'SpanAttributes', type: 'Map(String, String)' }, - ] as ColumnMeta[]; + ]); const mockJsonColumns: string[] = []; @@ -427,8 +427,8 @@ describe('Service Dashboard', () => { it('should use materialized endpoint column when available', () => { const columnsWithEndpoint: ColumnMeta[] = [ ...mockColumns, - { name: 'endpoint', type: 'String' }, - ] as ColumnMeta[]; + fromPartial({ name: 'endpoint', type: 'String' }), + ]; jest.spyOn(metadataModule, 'useJsonColumns').mockReturnValue( fromPartial({ diff --git a/packages/app/src/__tests__/source.test.ts b/packages/app/src/__tests__/source.test.ts index 0636d18f1a..44e8f6bdfa 100644 --- a/packages/app/src/__tests__/source.test.ts +++ b/packages/app/src/__tests__/source.test.ts @@ -3,6 +3,7 @@ import { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; import { ChartConfigWithOptTimestamp, NumberFormat, + RawSqlConfigWithDateRange, SourceKind, TLogSource, TTraceSource, @@ -181,10 +182,10 @@ describe('getEventBody', () => { describe('getTraceDurationNumberFormat', () => { it('returns undefined for non-trace sources', () => { - const logSource = { + const logSource = fromPartial({ kind: SourceKind.Log, id: 'log-source', - } as TLogSource; + }); const result = getTraceDurationNumberFormat(logSource, { valueExpression: 'count()', }); @@ -393,26 +394,26 @@ const NUMBER_FORMAT: NumberFormat = { output: 'number' }; function makeBuilderConfig( overrides: Partial = {}, ): ChartConfigWithOptTimestamp { - return { + return fromPartial({ connection: 'test-connection', source: TRACE_SOURCE.id, from: { databaseName: 'default', tableName: 'otel_traces' }, select: [], where: '', ...overrides, - } as unknown as ChartConfigWithOptTimestamp; + }); } function makeRawSqlConfig( - overrides: Partial = {}, + overrides: Partial = {}, ): ChartConfigWithOptTimestamp { - return { + return fromPartial({ configType: 'sql', sqlTemplate: 'SELECT 1', connection: 'test-connection', source: TRACE_SOURCE.id, ...overrides, - } as unknown as ChartConfigWithOptTimestamp; + }); } describe('useSingleSeriesNumberFormat', () => { diff --git a/packages/app/src/__tests__/useDashboardOnboarding.test.tsx b/packages/app/src/__tests__/useDashboardOnboarding.test.tsx index 545e3b9fd6..39ec74c8cb 100644 --- a/packages/app/src/__tests__/useDashboardOnboarding.test.tsx +++ b/packages/app/src/__tests__/useDashboardOnboarding.test.tsx @@ -1,4 +1,6 @@ +import { DisplayType } from '@hyperdx/common-utils/dist/types'; import { act, renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; // Local (temporary URL-state) dashboards never hit the backend, so setDashboard // must record the 'dashboard' onboarding task itself once a tile exists. These @@ -39,19 +41,19 @@ jest.mock('../api', () => ({ useCompleteOnboardingTask: () => ({ mutate }), })); -import { useDashboard } from '@/dashboard'; +import { type Dashboard, type Tile, useDashboard } from '@/dashboard'; -const tile = { +const tile: Tile = fromPartial({ id: 't1', x: 0, y: 0, w: 1, h: 1, - config: { name: 'c', source: 's', displayType: 'line', select: [] }, -}; + config: { name: 'c', source: 's', displayType: DisplayType.Line, select: [] }, +}); -function makeDashboard(tiles: unknown[]) { - return { id: '', name: 'Temp', tiles, tags: [] } as never; +function makeDashboard(tiles: Tile[]): Dashboard { + return { id: '', name: 'Temp', tiles, tags: [] }; } describe('useDashboard local-dashboard onboarding', () => { diff --git a/packages/app/src/__tests__/useMarkOnboardingTaskComplete.test.tsx b/packages/app/src/__tests__/useMarkOnboardingTaskComplete.test.tsx index 8bd6bc850e..65489432ad 100644 --- a/packages/app/src/__tests__/useMarkOnboardingTaskComplete.test.tsx +++ b/packages/app/src/__tests__/useMarkOnboardingTaskComplete.test.tsx @@ -1,13 +1,14 @@ import type { MeApiResponse } from '@hyperdx/common-utils/dist/types'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { act, renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { useMarkOnboardingTaskComplete } from '@/api'; function makeMe( completedTasks: MeApiResponse['onboardingData']['completedTasks'], -) { - return { +): MeApiResponse { + return fromPartial({ id: 'u1', email: 'a@b.com', accessKey: 'k', @@ -17,7 +18,7 @@ function makeMe( team: { id: 't1', name: 'Team' }, usageStatsEnabled: false, aiAssistantEnabled: false, - } as unknown as MeApiResponse; + }); } function setup(initialMe: MeApiResponse | null) { diff --git a/packages/app/src/__tests__/useSearchTelemetry.test.tsx b/packages/app/src/__tests__/useSearchTelemetry.test.tsx index d6877ae0c6..b945044ad9 100644 --- a/packages/app/src/__tests__/useSearchTelemetry.test.tsx +++ b/packages/app/src/__tests__/useSearchTelemetry.test.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import type { ChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; import { act, fireEvent, renderHook, screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { SearchNumRows, useSearchTelemetry } from '@/DBSearchPage'; @@ -297,10 +299,10 @@ describe('useSearchTelemetry', () => { // SearchNumRows // --------------------------------------------------------------------------- -const baseConfig = { +const baseConfig = fromPartial({ source: 'test-source', - dateRange: { from: new Date('2024-01-01'), to: new Date('2024-01-02') }, -} as any; + dateRange: [new Date('2024-01-01'), new Date('2024-01-02')], +}); describe('SearchNumRows', () => { beforeEach(() => { @@ -503,7 +505,7 @@ describe('SearchNumRows', () => { it('uses sqlConfig in the modal when provided — title says "Timeline" and content uses sqlConfig', async () => { mockExplainData = [{ rows: 50 }]; - const sqlConfig = { ...baseConfig, source: 'timeline-source' } as any; + const sqlConfig = { ...baseConfig, source: 'timeline-source' }; renderWithMantine( { it('uses plain "Generated SQL" title and rows config when no sqlConfig is passed', async () => { mockExplainData = [{ rows: 50 }]; - const rowsConfig = { ...baseConfig, source: 'rows-source' } as any; + const rowsConfig = { ...baseConfig, source: 'rows-source' }; renderWithMantine( { name: 'test-source', timestampValueExpression: 'timestamp', connection: 'test-connection', - kind: 'metric' as const, + kind: SourceKind.Metric, }); // Source with metric tables - const createSourceWithMetrics = () => ({ - ...createBaseSource(), - metricTables: { - gauge: 'gauge_table', - counter: 'counter_table', - }, - }); + // `counter` is not a MetricsDataType, so this source is deliberately invalid. + const createSourceWithMetrics = (): TSource => + fromAny({ + ...createBaseSource(), + metricTables: { + gauge: 'gauge_table', + counter: 'counter_table', + }, + }); it('returns the default table name when metricType is null', () => { - const source = createSourceWithMetrics() as unknown as TSource; + const source = createSourceWithMetrics(); expect(getMetricTableName(source)).toBe(''); expect(getMetricTableName(source, undefined)).toBe(''); }); it('returns the specific metric table when metricType is provided', () => { - const source = createSourceWithMetrics() as unknown as TSource; + const source = createSourceWithMetrics(); - expect(getMetricTableName(source, 'gauge' as MetricsDataType)).toBe( - 'gauge_table', - ); - expect(getMetricTableName(source, 'counter' as MetricsDataType)).toBe( - 'counter_table', - ); + expect(getMetricTableName(source, 'gauge')).toBe('gauge_table'); + expect(getMetricTableName(source, 'counter')).toBe('counter_table'); }); it('handles case insensitivity for metric types', () => { - const source = createSourceWithMetrics() as unknown as TSource; + const source = createSourceWithMetrics(); - expect(getMetricTableName(source, 'GAUGE' as MetricsDataType)).toBe( - 'gauge_table', - ); - expect(getMetricTableName(source, 'Counter' as MetricsDataType)).toBe( - 'counter_table', - ); + expect(getMetricTableName(source, 'GAUGE')).toBe('gauge_table'); + expect(getMetricTableName(source, 'Counter')).toBe('counter_table'); }); it('returns undefined when the requested metric type does not exist', () => { - const source = { + const source = fromPartial({ ...createBaseSource(), metricTables: { gauge: 'gauge_table', }, - } as unknown as TSource; + }); - expect( - getMetricTableName(source, 'histogram' as MetricsDataType), - ).toBeUndefined(); + expect(getMetricTableName(source, 'histogram')).toBeUndefined(); }); it('handles sources without metricTables property', () => { - const source = createBaseSource() as unknown as TSource; + const source = fromPartial(createBaseSource()); expect(getMetricTableName(source)).toBe(''); - expect( - getMetricTableName(source, 'gauge' as MetricsDataType), - ).toBeUndefined(); + expect(getMetricTableName(source, 'gauge')).toBeUndefined(); }); }); describe('getAllMetricTables', () => { const createMetricSource = (metricTables: Record): TSource => - ({ - kind: 'metric' as const, + fromAny({ + kind: SourceKind.Metric, from: { databaseName: 'test_db', tableName: '' }, connection: 'test-conn', id: 'test-id', name: 'test', timestampValueExpression: 'timestamp', metricTables, - }) as unknown as TSource; + }); it('returns empty array for non-metric source', () => { - const source = { - kind: 'log' as const, + const source = fromPartial({ + kind: SourceKind.Log, from: { databaseName: 'test_db', tableName: 'logs' }, connection: 'test-conn', id: 'test-id', name: 'test', timestampValueExpression: 'timestamp', - } as unknown as TSource; + }); expect(getAllMetricTables(source)).toEqual([]); }); it('returns empty array when metricTables is undefined', () => { - const source = { - kind: 'metric' as const, + const source = fromPartial({ + kind: SourceKind.Metric, from: { databaseName: 'test_db', tableName: '' }, connection: 'test-conn', id: 'test-id', name: 'test', timestampValueExpression: 'timestamp', - } as unknown as TSource; + }); expect(getAllMetricTables(source)).toEqual([]); }); @@ -1619,19 +1609,23 @@ describe('getColorFromCSSToken', () => { // value (and shouldn't be relied upon by JS callers). const getComputedStyleSpy = jest .spyOn(global, 'getComputedStyle') - .mockReturnValue({ - getPropertyValue: () => '#should-be-ignored', - } as unknown as CSSStyleDeclaration); + .mockReturnValue( + fromPartial({ + getPropertyValue: () => '#should-be-ignored', + }), + ); expect(getColorFromCSSToken('chart-blue')).toBe(COLORS[0]); expect(getComputedStyleSpy).not.toHaveBeenCalled(); }); it('returns the CSS variable value for semantic tokens when provided', () => { - jest.spyOn(global, 'getComputedStyle').mockReturnValue({ - getPropertyValue: (name: string) => - name === '--color-chart-success' ? '#theme-green' : '', - } as unknown as CSSStyleDeclaration); + jest.spyOn(global, 'getComputedStyle').mockReturnValue( + fromPartial({ + getPropertyValue: (name: string) => + name === '--color-chart-success' ? '#theme-green' : '', + }), + ); expect(getColorFromCSSToken('chart-success')).toBe('#theme-green'); }); diff --git a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts index 41b760f310..a8da9b70a4 100644 --- a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts @@ -1,5 +1,9 @@ +import { + isBuilderChartConfig, + isBuilderSavedChartConfig, + isRawSqlSavedChartConfig, +} from '@hyperdx/common-utils/dist/guards'; import type { - BuilderChartConfig, BuilderSavedChartConfig, RawSqlSavedChartConfig, TMetricSource, @@ -12,6 +16,7 @@ import { PromqlReducer, SourceKind, } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import type { ChartEditorFormState } from '@/components/ChartEditor/types'; import { @@ -51,7 +56,7 @@ const metricSource: TMetricSource = { connection: 'conn-1', from: { databaseName: 'db', tableName: '' }, timestampValueExpression: 'TimeUnix', - metricTables: { gauge: 'gauge_table' } as TMetricSource['metricTables'], + metricTables: fromPartial({ gauge: 'gauge_table' }), resourceAttributesExpression: 'ResourceAttributes', }; @@ -93,6 +98,16 @@ const promqlSource: TSource = { timestampValueExpression: 'Timestamp', }; +function narrow( + value: U | undefined, + guard: (v: U) => v is T, +): T { + if (value === undefined || !guard(value)) { + throw new Error('Unexpected config type'); + } + return value; +} + const seriesItem = { aggFn: 'count' as const, valueExpression: '*', @@ -274,10 +289,10 @@ describe('convertFormStateToSavedChartConfig', () => { where: 'status = 200', series: [seriesItem], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result.select).toEqual([seriesItem]); expect('series' in result).toBe(false); expect(result.source).toBe('source-log'); @@ -299,10 +314,10 @@ describe('convertFormStateToSavedChartConfig', () => { select: 'Body, SeverityText', series: [seriesItem], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result.select).toBe('Body, SeverityText'); expect('series' in result).toBe(false); }); @@ -313,10 +328,10 @@ describe('convertFormStateToSavedChartConfig', () => { select: [seriesItem], series: [], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result.select).toBe(''); expect('series' in result).toBe(false); }); @@ -332,28 +347,29 @@ describe('convertFormStateToSavedChartConfig', () => { }, ], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; - const select = result.select as (typeof seriesItem)[]; - expect(select[0]).not.toHaveProperty('metricName'); - expect(select[0]).not.toHaveProperty('metricType'); + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); + if (typeof result.select === 'string') { + throw new Error('Expected series select'); + } + expect(result.select[0]).not.toHaveProperty('metricName'); + expect(result.select[0]).not.toHaveProperty('metricType'); }); it('preserves form metricTables for metric source', () => { - const formMetricTables = { - gauge: 'gauge_table', - } as BuilderSavedChartConfig['metricTables']; + const formMetricTables: BuilderSavedChartConfig['metricTables'] = + fromPartial({ gauge: 'gauge_table' }); const form: ChartEditorFormState = { displayType: DisplayType.Line, series: [seriesItem], metricTables: formMetricTables, }; - const result = convertFormStateToSavedChartConfig( - form, - metricSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, metricSource), + isBuilderSavedChartConfig, + ); expect(result.metricTables).toEqual(formMetricTables); }); @@ -361,12 +377,12 @@ describe('convertFormStateToSavedChartConfig', () => { const form: ChartEditorFormState = { displayType: DisplayType.Line, series: [seriesItem], - metricTables: { gauge: 'gauge_table' } as any, + metricTables: fromPartial({ gauge: 'gauge_table' }), }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result.metricTables).toBeUndefined(); }); @@ -386,17 +402,20 @@ describe('convertFormStateToSavedChartConfig', () => { having, orderBy, }; - const tableResult = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const tableResult = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(tableResult.having).toBe(having); expect(tableResult.orderBy).toEqual(orderBy); - const lineResult = convertFormStateToSavedChartConfig( - { ...form, displayType: DisplayType.Line }, - logSource, - ) as BuilderSavedChartConfig; + const lineResult = narrow( + convertFormStateToSavedChartConfig( + { ...form, displayType: DisplayType.Line }, + logSource, + ), + isBuilderSavedChartConfig, + ); expect(lineResult.having).toBeUndefined(); expect(lineResult.orderBy).toBeUndefined(); }); @@ -406,10 +425,10 @@ describe('convertFormStateToSavedChartConfig', () => { displayType: DisplayType.Line, series: [seriesItem], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result.where).toBe(''); }); @@ -420,10 +439,10 @@ describe('convertFormStateToSavedChartConfig', () => { source: '', series: [], }; - const result = convertFormStateToSavedChartConfig( - form, - undefined, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, undefined), + isBuilderSavedChartConfig, + ); expect(result).toBeDefined(); expect(result.displayType).toBe(DisplayType.Markdown); expect(result.markdown).toBe('## Hello World'); @@ -438,10 +457,10 @@ describe('convertFormStateToSavedChartConfig', () => { markdown: '## With Source', series: [], }; - const result = convertFormStateToSavedChartConfig( - form, - logSource, - ) as BuilderSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, logSource), + isBuilderSavedChartConfig, + ); expect(result).toBeDefined(); expect(result.displayType).toBe(DisplayType.Markdown); expect(result.source).toBe('source-log'); @@ -541,12 +560,11 @@ describe('convertFormStateToChartConfig', () => { displayType: DisplayType.Line, series: [], }; - const result = convertFormStateToChartConfig( - form, - dateRange, - logSource, - ) as BuilderChartConfig; - expect(result?.select).toBe(logSource.defaultTableSelectExpression); + const result = narrow( + convertFormStateToChartConfig(form, dateRange, logSource), + isBuilderChartConfig, + ); + expect(result.select).toBe(logSource.defaultTableSelectExpression); }); it('uses series as select for non-Search displayType', () => { @@ -554,12 +572,11 @@ describe('convertFormStateToChartConfig', () => { displayType: DisplayType.Line, series: [seriesItem], }; - const result = convertFormStateToChartConfig( - form, - dateRange, - logSource, - ) as BuilderChartConfig; - expect(result?.select).toEqual([seriesItem]); + const result = narrow( + convertFormStateToChartConfig(form, dateRange, logSource), + isBuilderChartConfig, + ); + expect(result.select).toEqual([seriesItem]); }); it('uses form.select for Search displayType', () => { @@ -568,12 +585,11 @@ describe('convertFormStateToChartConfig', () => { select: 'Body', series: [], }; - const result = convertFormStateToChartConfig( - form, - dateRange, - logSource, - ) as BuilderChartConfig; - expect(result?.select).toBe('Body'); + const result = narrow( + convertFormStateToChartConfig(form, dateRange, logSource), + isBuilderChartConfig, + ); + expect(result.select).toBe('Body'); }); }); @@ -1197,12 +1213,12 @@ describe('validateChartForm', () => { displayType: DisplayType.Line, sqlTemplate: 'SELECT count() FROM logs', connection: 'conn-1', - alert: { + alert: fromPartial({ interval: '1h', threshold: 100, - thresholdType: 'above', + thresholdType: AlertThresholdType.ABOVE, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), undefined, setError, @@ -1225,12 +1241,12 @@ describe('validateChartForm', () => { sqlTemplate: 'SELECT toStartOfInterval(ts, INTERVAL {intervalSeconds:Int64} SECOND) AS ts, count() FROM logs WHERE ts >= fromUnixTimestamp64Milli({startDateMilliseconds:Int64}) AND ts <= fromUnixTimestamp64Milli({endDateMilliseconds:Int64}) GROUP BY ts', connection: 'conn-1', - alert: { + alert: fromPartial({ interval: '1h', threshold: 100, - thresholdType: 'above', + thresholdType: AlertThresholdType.ABOVE, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), undefined, setError, @@ -1271,12 +1287,12 @@ describe('validateChartForm', () => { sqlTemplate: 'SELECT count() FROM logs WHERE ts >= fromUnixTimestamp64Milli({startDateMilliseconds:Int64}) AND ts <= fromUnixTimestamp64Milli({endDateMilliseconds:Int64})', connection: 'conn-1', - alert: { + alert: fromPartial({ interval: '1h', threshold: 100, - thresholdType: 'above', + thresholdType: AlertThresholdType.ABOVE, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), undefined, setError, @@ -1297,12 +1313,12 @@ describe('validateChartForm', () => { sqlTemplate: 'SELECT count() FROM logs WHERE ts >= fromUnixTimestamp64Milli({startDateMilliseconds:Int64}) AND ts <= fromUnixTimestamp64Milli({endDateMilliseconds:Int64})', connection: 'conn-1', - alert: { + alert: fromPartial({ interval: '1h', threshold: 100, - thresholdType: 'above', + thresholdType: AlertThresholdType.ABOVE, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), undefined, setError, @@ -1768,12 +1784,12 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdType: AlertThresholdType.BETWEEN, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -1792,12 +1808,12 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdType: AlertThresholdType.NOT_BETWEEN, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -1814,13 +1830,13 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdMax: 5, thresholdType: AlertThresholdType.BETWEEN, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -1839,13 +1855,13 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdMax: 10, thresholdType: AlertThresholdType.BETWEEN, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -1858,13 +1874,13 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdMax: 20, thresholdType: AlertThresholdType.BETWEEN, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -1877,12 +1893,12 @@ describe('validateChartForm', () => { const errors = validateChartForm( makeForm({ source: 'source-log', - alert: { + alert: fromPartial({ interval: '1h', threshold: 10, thresholdType: AlertThresholdType.ABOVE, channel: { type: 'webhook' }, - } as ChartEditorFormState['alert'], + }), }), logSource, setError, @@ -2060,10 +2076,10 @@ describe('color round-trip (sql/promql Number tile)', () => { color: 'chart-success', series: [], }; - const result = convertFormStateToSavedChartConfig( - form, - undefined, - ) as RawSqlSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, undefined), + isRawSqlSavedChartConfig, + ); expect(result).toBeDefined(); expect(result.color).toBe('chart-success'); }); @@ -2164,10 +2180,10 @@ describe('color round-trip (sql/promql Number tile)', () => { connection: 'conn-1', series: [], }; - const result = convertFormStateToSavedChartConfig( - form, - undefined, - ) as RawSqlSavedChartConfig; + const result = narrow( + convertFormStateToSavedChartConfig(form, undefined), + isRawSqlSavedChartConfig, + ); expect(result).toBeDefined(); expect(result.color).toBeUndefined(); }); diff --git a/packages/app/src/components/ColorSwatchInput.test.tsx b/packages/app/src/components/ColorSwatchInput.test.tsx index 224cf16c01..96c0419f47 100644 --- a/packages/app/src/components/ColorSwatchInput.test.tsx +++ b/packages/app/src/components/ColorSwatchInput.test.tsx @@ -1,5 +1,6 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromAny } from '@total-typescript/shoehorn'; import { CHART_PALETTE_TOKENS, ChartPaletteToken } from '@/utils'; @@ -118,7 +119,7 @@ describe('ColorSwatchInput', () => { renderWithMantine( ('#ff0000')} onChange={onChange} />, ); @@ -149,7 +150,7 @@ describe('ColorSwatchInput', () => { const user = userEvent.setup(); renderWithMantine( ('chart-1')} onChange={jest.fn()} />, ); diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts index 4493e5466a..3d28989826 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts @@ -6,10 +6,12 @@ import { Filter, PromqlConditionFilter, PromqlExpressionList, + RawSqlConfigWithDateRange, SavedChartConfig, SourceKind, TSource, } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { ChartEditorFormState } from '@/components/ChartEditor/types'; import { @@ -57,12 +59,12 @@ const builderConfig: ChartConfigWithDateRange = { granularity: 'auto', } as ChartConfigWithDateRange; -const rawSqlConfig = { - configType: 'sql' as const, +const rawSqlConfig: RawSqlConfigWithDateRange = { + configType: 'sql', sqlTemplate: 'SELECT count() FROM logs', connection: 'clickhouse', dateRange, -} as ChartConfigWithDateRange; +}; const logSource = { kind: SourceKind.Log, @@ -146,11 +148,13 @@ describe('isQueryReady', () => { it('returns truthy for metric sources with metricTables but empty tableName', () => { expect( - isQueryReady({ - ...builderConfig, - from: { databaseName: 'default', tableName: '' }, - metricTables: { gauge: 'metrics.gauge' }, - } as ChartConfigWithDateRange), + isQueryReady( + fromPartial({ + ...builderConfig, + from: { databaseName: 'default', tableName: '' }, + metricTables: { gauge: 'metrics.gauge' }, + }), + ), ).toBeTruthy(); }); @@ -163,7 +167,7 @@ describe('isQueryReady', () => { isQueryReady({ ...rawSqlConfig, sqlTemplate: '', - } as ChartConfigWithDateRange), + }), ).toBe(false); }); diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/heatmapPaths.test.ts b/packages/app/src/components/DBHeatmapChart/__tests__/heatmapPaths.test.ts index e41b7a8f26..69905d50e4 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/heatmapPaths.test.ts +++ b/packages/app/src/components/DBHeatmapChart/__tests__/heatmapPaths.test.ts @@ -1,4 +1,5 @@ import type uPlot from 'uplot'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { gridToPlotData, @@ -44,7 +45,8 @@ class StubPath2D {} function paint(grid: HeatmapGrid, fills: number[]) { const u = { - data: [[], gridToPlotData(grid)], + // uPlot's AlignedData typing doesn't model the heatmap's nested series. + data: fromAny([[], gridToPlotData(grid)]), bbox: { left: 0, top: 0, width: 100, height: 100 }, ctx: { save: jest.fn(), @@ -57,7 +59,7 @@ function paint(grid: HeatmapGrid, fills: number[]) { const paths = heatmapPaths({ disp: { fill: { lookup: ['#000', '#fff'], values: () => fills } }, }); - paths(u as unknown as uPlot, 1, 0, 0); + paths(fromPartial(u), 1, 0, 0); return u; } diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/highlightDataPlugin.test.ts b/packages/app/src/components/DBHeatmapChart/__tests__/highlightDataPlugin.test.ts index c7e246b993..728fec7779 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/highlightDataPlugin.test.ts +++ b/packages/app/src/components/DBHeatmapChart/__tests__/highlightDataPlugin.test.ts @@ -1,4 +1,5 @@ import type uPlot from 'uplot'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { gridToPlotData, @@ -29,7 +30,8 @@ function hover( over: { offsetLeft: 5, offsetTop: 7, ...plotSize }, valToPos, posToVal, - data: [ + // uPlot's AlignedData typing doesn't model the heatmap's nested series. + data: fromAny([ [], gridToPlotData({ times: [100], @@ -37,11 +39,11 @@ function hover( yAxis: { type: 'numeric', scale: 'linear', edges: [0, 1, 3] }, cells, }), - ], + ]), }; const setCursor = plugin.hooks.setCursor; if (typeof setCursor !== 'function') throw new Error('no setCursor hook'); - setCursor(u as unknown as uPlot); + setCursor(fromPartial(u)); return onPointHighlight; } diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/selection.test.ts b/packages/app/src/components/DBHeatmapChart/__tests__/selection.test.ts index 5d329fb158..34856cc741 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/selection.test.ts +++ b/packages/app/src/components/DBHeatmapChart/__tests__/selection.test.ts @@ -1,4 +1,4 @@ -import type uPlot from 'uplot'; +import { fromPartial } from '@total-typescript/shoehorn'; import { applySelectionToChart, @@ -40,7 +40,7 @@ function makeStubU(opts?: { describe('applySelectionToChart', () => { it('clears the selection when bounds is null', () => { const u = makeStubU(); - applySelectionToChart(u as unknown as uPlot, null, 'linear'); + applySelectionToChart(fromPartial(u), null, 'linear'); expect(u.setSelect).toHaveBeenCalledTimes(1); expect(u.setSelect).toHaveBeenCalledWith( { left: 0, top: 0, width: 0, height: 0 }, @@ -51,7 +51,7 @@ describe('applySelectionToChart', () => { it('clears the selection when bounds is undefined', () => { const u = makeStubU(); - applySelectionToChart(u as unknown as uPlot, undefined, 'linear'); + applySelectionToChart(fromPartial(u), undefined, 'linear'); expect(u.setSelect).toHaveBeenCalledWith( { left: 0, top: 0, width: 0, height: 0 }, false, @@ -61,14 +61,14 @@ describe('applySelectionToChart', () => { it('returns early without calling setSelect when y scale is unpopulated', () => { const u = makeStubU({ yScale: { min: undefined, max: undefined } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 1, yMax: 5 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); expect(u.setSelect).not.toHaveBeenCalled(); }); it('converts xMin/xMax from seconds to ms before calling valToPos', () => { const u = makeStubU(); const bounds: SelectionBounds = { xMin: 5, xMax: 10, yMin: 1, yMax: 9 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); expect(u.valToPos).toHaveBeenCalledWith(5_000, 'x'); expect(u.valToPos).toHaveBeenCalledWith(10_000, 'x'); }); @@ -76,7 +76,7 @@ describe('applySelectionToChart', () => { it('passes raw y values through under linear scale', () => { const u = makeStubU({ yScale: { min: 0, max: 100 } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 5, yMax: 50 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); // y values must NOT be log-transformed under linear scale. expect(u.valToPos).toHaveBeenCalledWith(50, 'y'); expect(u.valToPos).toHaveBeenCalledWith(5, 'y'); @@ -85,7 +85,7 @@ describe('applySelectionToChart', () => { it('applies Math.log to y values under log scale', () => { const u = makeStubU({ yScale: { min: 0, max: 100 } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 1, yMax: Math.E }; - applySelectionToChart(u as unknown as uPlot, bounds, 'log'); + applySelectionToChart(fromPartial(u), bounds, 'log'); // Math.log(1) === 0, Math.log(Math.E) === 1 expect(u.valToPos).toHaveBeenCalledWith(0, 'y'); expect(u.valToPos).toHaveBeenCalledWith(1, 'y'); @@ -94,7 +94,7 @@ describe('applySelectionToChart', () => { it('clamps yMin === 0 to the chart-floor (yScaleMin) under linear scale', () => { const u = makeStubU({ yScale: { min: 2, max: 100 } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 0, yMax: 50 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); // yMin=0 should clamp UP to yScale.min (2), not pass through. expect(u.valToPos).toHaveBeenCalledWith(2, 'y'); expect(u.valToPos).not.toHaveBeenCalledWith(0, 'y'); @@ -103,7 +103,7 @@ describe('applySelectionToChart', () => { it('clamps yMin === 0 to the chart-floor (yScaleMin) under log scale', () => { const u = makeStubU({ yScale: { min: -1, max: 5 } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 0, yMax: Math.E }; - applySelectionToChart(u as unknown as uPlot, bounds, 'log'); + applySelectionToChart(fromPartial(u), bounds, 'log'); // yMin=0 (or any non-positive) bypasses Math.log and clamps to yScale.min. expect(u.valToPos).toHaveBeenCalledWith(-1, 'y'); }); @@ -111,14 +111,14 @@ describe('applySelectionToChart', () => { it('clamps yMax above the chart ceiling to yScaleMax under linear', () => { const u = makeStubU({ yScale: { min: 0, max: 10 } }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 1, yMax: 999 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); expect(u.valToPos).toHaveBeenCalledWith(10, 'y'); }); it('handles reversed xMin > xMax via Math.min/max for left/right', () => { const u = makeStubU(); const bounds: SelectionBounds = { xMin: 10, xMax: 5, yMin: 1, yMax: 9 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); // valToPos identity: xMin*1000=10000, xMax*1000=5000 // left should be Math.min(10000, 5000) = 5000, width = 10000-5000 = 5000 const call = u.setSelect.mock.calls[0][0]; @@ -134,7 +134,7 @@ describe('applySelectionToChart', () => { valToPos: (val, axis) => (axis === 'y' ? 100 - val : val), }); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 2, yMax: 8 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); const call = u.setSelect.mock.calls[0][0]; // yHighPx = 100-8 = 92, yLowPx = 100-2 = 98, height = max(0, 98-92) = 6 expect(call.top).toBe(92); @@ -144,7 +144,7 @@ describe('applySelectionToChart', () => { it('passes fireHook=false to setSelect to avoid re-entering the setSelect hook', () => { const u = makeStubU(); const bounds: SelectionBounds = { xMin: 0, xMax: 1, yMin: 1, yMax: 9 }; - applySelectionToChart(u as unknown as uPlot, bounds, 'linear'); + applySelectionToChart(fromPartial(u), bounds, 'linear'); const fireHook = u.setSelect.mock.calls[0][1]; expect(fireHook).toBe(false); }); diff --git a/packages/app/src/components/DBTable/__tests__/TableSearchInput.test.tsx b/packages/app/src/components/DBTable/__tests__/TableSearchInput.test.tsx index 3585ad08fe..7b11562c3e 100644 --- a/packages/app/src/components/DBTable/__tests__/TableSearchInput.test.tsx +++ b/packages/app/src/components/DBTable/__tests__/TableSearchInput.test.tsx @@ -802,7 +802,7 @@ describe('TableSearchMatchIndicator', () => { matchIndices: [], currentMatchIndex: 0, dedupedRows: mockDedupedRows, - tableRows: mockTableRows as any[], + tableRows: mockTableRows, getRowId, onMatchClick: jest.fn(), }; @@ -1064,7 +1064,7 @@ describe('TableSearchMatchIndicator', () => { const onMatchClick = jest.fn(); const user = userEvent.setup(); - const { container } = renderWithMantine( + renderWithMantine( { />, ); - const indicators = container.querySelectorAll('[title*="Match"]'); - await user.click(indicators[0] as HTMLElement); + const indicators = screen.getAllByTitle(/Match/); + await user.click(indicators[0]); expect(onMatchClick).toHaveBeenCalledWith(0); }); @@ -1083,7 +1083,7 @@ describe('TableSearchMatchIndicator', () => { const onMatchClick = jest.fn(); const user = userEvent.setup(); - const { container } = renderWithMantine( + renderWithMantine( { />, ); - const indicators = container.querySelectorAll('[title*="Match"]'); + const indicators = screen.getAllByTitle(/Match/); // Click second indicator - await user.click(indicators[1] as HTMLElement); + await user.click(indicators[1]); expect(onMatchClick).toHaveBeenCalledWith(1); // Click third indicator - await user.click(indicators[2] as HTMLElement); + await user.click(indicators[2]); expect(onMatchClick).toHaveBeenCalledWith(2); }); @@ -1174,7 +1174,7 @@ describe('TableSearchMatchIndicator', () => { searchQuery="test" matchIndices={largeMatchIndices} dedupedRows={largeDedupedRows} - tableRows={largeTableRows as any[]} + tableRows={largeTableRows} />, ); @@ -1282,7 +1282,7 @@ describe('TableSearchMatchIndicator', () => { searchQuery="middleware" matchIndices={[5, 6]} dedupedRows={extendedRows} - tableRows={extendedTableRows as any[]} + tableRows={extendedTableRows} currentMatchIndex={0} />, ); diff --git a/packages/app/src/components/DBTable/__tests__/sorting.test.ts b/packages/app/src/components/DBTable/__tests__/sorting.test.ts index 1d2f963a8c..58a59c3d88 100644 --- a/packages/app/src/components/DBTable/__tests__/sorting.test.ts +++ b/packages/app/src/components/DBTable/__tests__/sorting.test.ts @@ -1,7 +1,10 @@ +import { Row } from '@tanstack/react-table'; +import { fromPartial } from '@total-typescript/shoehorn'; + import { numericRowSortingFn } from '@/components/DBTable/sorting'; -function makeRow(value: unknown) { - return { getValue: (_key: string) => value } as any; +function makeRow(value: unknown): Row { + return fromPartial({ getValue: (_key: string) => value }); } describe('numericRowSortingFn', () => { diff --git a/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx b/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx index d1e3dcea03..1edc9757e6 100644 --- a/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx +++ b/packages/app/src/components/Search/__tests__/DBSearchHeatmapChart.test.tsx @@ -190,8 +190,6 @@ describe('DBSearchHeatmapChart', () => { const lastProps = deltaChartPropsLog[deltaChartPropsLog.length - 1]; expect(lastProps.legendPrefix).toBeTruthy(); expect(React.isValidElement(lastProps.legendPrefix)).toBe(true); - expect((lastProps.legendPrefix as React.ReactElement).type).toBe( - MockedColorLegend, - ); + expect(lastProps.legendPrefix).toMatchObject({ type: MockedColorLegend }); }); }); diff --git a/packages/app/src/components/Sources/SourceForm/SourceForm.stories.tsx b/packages/app/src/components/Sources/SourceForm/SourceForm.stories.tsx index e2bbaddd79..7d53950692 100644 --- a/packages/app/src/components/Sources/SourceForm/SourceForm.stories.tsx +++ b/packages/app/src/components/Sources/SourceForm/SourceForm.stories.tsx @@ -1,4 +1,4 @@ -import { http, HttpResponse } from 'msw'; +import { http, HttpResponse, PathParams } from 'msw'; import { SourceKind } from '@hyperdx/common-utils/dist/types'; import { Card } from '@mantine/core'; import type { Meta, StoryObj } from '@storybook/nextjs'; @@ -65,14 +65,20 @@ const defaultHandlers = { tables: http.get('*/api/clickhouse/tables', () => { return HttpResponse.json(mockTables); }), - createSource: http.post('*/api/sources', async ({ request }) => { - const body = (await request.json()) as Record; - return HttpResponse.json({ id: 'new-source-id', ...body }); - }), - updateSource: http.put('*/api/sources/:id', async ({ request }) => { - const body = (await request.json()) as Record; - return HttpResponse.json(body); - }), + createSource: http.post>( + '*/api/sources', + async ({ request }) => { + const body = await request.json(); + return HttpResponse.json({ id: 'new-source-id', ...body }); + }, + ), + updateSource: http.put>( + '*/api/sources/:id', + async ({ request }) => { + const body = await request.json(); + return HttpResponse.json(body); + }, + ), deleteSource: http.delete('*/api/sources/:id', () => { return HttpResponse.json({ success: true }); }), diff --git a/packages/app/src/components/__tests__/ContextFilterPills.test.ts b/packages/app/src/components/__tests__/ContextFilterPills.test.ts index ce421206f9..cfdcf96125 100644 --- a/packages/app/src/components/__tests__/ContextFilterPills.test.ts +++ b/packages/app/src/components/__tests__/ContextFilterPills.test.ts @@ -1,4 +1,5 @@ -import { TSource } from '@hyperdx/common-utils/dist/types'; +import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { buildContextWhereClause, @@ -11,9 +12,9 @@ import { import { ROW_DATA_ALIASES } from '@/components/DBRowDataPanel'; const makeLogSource = (overrides = {}): TSource => - ({ + fromPartial({ id: 'src-1', - kind: 'log', + kind: SourceKind.Log, name: 'Test Logs', from: { databaseName: 'default', tableName: 'otel_logs' }, connection: 'conn-1', @@ -23,7 +24,7 @@ const makeLogSource = (overrides = {}): TSource => eventAttributesExpression: 'LogAttributes', defaultTableSelectExpression: '*', ...overrides, - }) as unknown as TSource; + }); describe('extractQuickFilters', () => { it('creates a service pill from serviceNameExpression', () => { diff --git a/packages/app/src/components/__tests__/DBInfraPanel.buildChartConfig.test.ts b/packages/app/src/components/__tests__/DBInfraPanel.buildChartConfig.test.ts index 7e2ebdd16d..2a0620d60c 100644 --- a/packages/app/src/components/__tests__/DBInfraPanel.buildChartConfig.test.ts +++ b/packages/app/src/components/__tests__/DBInfraPanel.buildChartConfig.test.ts @@ -2,8 +2,10 @@ import { Granularity } from '@hyperdx/common-utils/dist/core/utils'; import { DisplayType, MetricsDataType, + SourceKind, TMetricSource, } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { buildChartConfig } from '@/components/DBInfraPanel'; import { INFRA_CORRELATIONS } from '@/components/infraCorrelations'; @@ -14,9 +16,9 @@ jest.mock('@/components/Sources/SourceForm', () => ({ })); jest.mock('@/components/KubeComponents', () => ({ KubeTimeline: () => null })); -const METRIC_SOURCE = { +const METRIC_SOURCE = fromPartial({ id: 'metric-source-1', - kind: 'metric', + kind: SourceKind.Metric, name: 'Metrics', connection: 'conn-1', from: { databaseName: 'default', tableName: '' }, @@ -29,7 +31,7 @@ const METRIC_SOURCE = { summary: 'otel_metrics_summary', 'exponential histogram': 'otel_metrics_exponential_histogram', }, -} as unknown as TMetricSource; +}); const DATE_RANGE: [Date, Date] = [ new Date('2026-01-01T00:00:00Z'), diff --git a/packages/app/src/components/__tests__/DBSearchPageFilters.test.tsx b/packages/app/src/components/__tests__/DBSearchPageFilters.test.tsx index 3a9f3c345b..7a118ead8e 100644 --- a/packages/app/src/components/__tests__/DBSearchPageFilters.test.tsx +++ b/packages/app/src/components/__tests__/DBSearchPageFilters.test.tsx @@ -768,9 +768,10 @@ describe('FilterGroup', () => { ); // Find and click the "Only" button for banana - const bananaRow = screen - .getByText('banana') - .closest('.filterCheckbox') as HTMLElement; + const bananaRow = screen.getByText('banana').closest('.filterCheckbox'); + if (!(bananaRow instanceof HTMLElement)) { + throw new Error('banana filter row not found'); + } const onlyButton = within(bananaRow).getByText('Only'); await userEvent.click(onlyButton); diff --git a/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx b/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx index 8d3ce6658e..acb4fa4b9f 100644 --- a/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx +++ b/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx @@ -24,7 +24,6 @@ import { TraceTotalDurationStat, useEventsAroundFocus, } from '@/components/DBTraceWaterfallChart'; -import { TimelineChart } from '@/components/TimelineChart'; import { TRACE_WATERFALL_ROW_LIMIT } from '@/components/traceWaterfallLimits'; import { TraceTriggerRow, @@ -40,6 +39,10 @@ jest.mock('@/components/traceWaterfallLimits', () => ({ TRACE_WATERFALL_ROW_LIMIT: 3, TRACE_WATERFALL_FETCH_LIMIT: 4, })); + +// Read at render time, so the hoisted mock factory can reference it. +const mockTimelineChartProps: { latest: any } = { latest: {} }; + jest.mock('@/components/TimelineChart', () => { const flattenText = (value: React.ReactNode): string => { if (value == null || typeof value === 'boolean') { @@ -62,7 +65,7 @@ jest.mock('@/components/TimelineChart', () => { }; const mockComponent = function MockTimelineChart(props: any) { - mockComponent.latestProps = props; + mockTimelineChartProps.latest = props; return (
TimelineChart @@ -74,7 +77,6 @@ jest.mock('@/components/TimelineChart', () => {
); }; - mockComponent.latestProps = {}; const MockTimelineMinimap = function MockTimelineMinimap(props: any) { MockTimelineMinimap.latestProps = props; @@ -138,7 +140,6 @@ jest.mock('@/hooks/useWaterfallSearchState', () => ({ const mockUseOffsetPaginatedQuery = jest.mocked(useOffsetPaginatedQuery); const mockUseRowWhere = jest.mocked(useRowWhere); const mockUseColumns = jest.mocked(useColumns); -const MockTimelineChart = TimelineChart as any; // Mirrors useColumns, which is disabled, so never loading, without a table. // A loading query result carries no data, so the two states are built apart. @@ -245,7 +246,7 @@ describe('DBTraceWaterfallChartContainer', () => { jest.clearAllMocks(); mockUseBrowserTraceEvents.mockImplementation(passBrowserTraceEventsThrough); mockUseRowWhere.mockReturnValue(() => ({ where: 'row-id', aliasWith: [] })); - MockTimelineChart.latestProps = {}; + mockTimelineChartProps.latest = {}; mockUseWaterfallSearchState.mockReturnValue(makeWaterfallSearchState()); setupColumnsMock({ data: [] }); }); @@ -359,8 +360,8 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); // Verify the chart received the correct data - expect(MockTimelineChart.latestProps.rows.length).toBe(1); - expect(MockTimelineChart.latestProps.rows[0]).toBeTruthy(); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows[0]).toBeTruthy(); }); it('renders TimelineChart with both trace and log data', async () => { @@ -373,9 +374,9 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); // Verify both trace and log data are present - expect(MockTimelineChart.latestProps.rows.length).toBe(2); - expect(MockTimelineChart.latestProps.rows[0]).toBeTruthy(); // Trace row - expect(MockTimelineChart.latestProps.rows[1]).toBeTruthy(); // Log row + expect(mockTimelineChartProps.latest.rows.length).toBe(2); + expect(mockTimelineChartProps.latest.rows[0]).toBeTruthy(); // Trace row + expect(mockTimelineChartProps.latest.rows[1]).toBeTruthy(); // Log row }); it.each([ @@ -390,7 +391,7 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows.length).toBe(2); + expect(mockTimelineChartProps.latest.rows.length).toBe(2); }); it.each([ @@ -408,7 +409,7 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - const logRow = MockTimelineChart.latestProps.rows.find( + const logRow = mockTimelineChartProps.latest.rows.find( (row: { type?: string }) => row.type === SourceKind.Log, ); expect(logRow.events[0].backgroundColor).toBe(expectedColor()); @@ -548,7 +549,7 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); expect(screen.queryByTestId('trace-total-stats')).not.toBeInTheDocument(); }); @@ -804,9 +805,9 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); // Verify the chart received the HTTP span with URL - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); - expect(MockTimelineChart.latestProps.rows[0]).toBeTruthy(); + expect(mockTimelineChartProps.latest.rows[0]).toBeTruthy(); expect( screen.getByText('http span https://example-api.clickhouse.com/users'), ).toBeInTheDocument(); @@ -831,7 +832,7 @@ describe('DBTraceWaterfallChartContainer', () => { }); const findRow = (type: string) => - MockTimelineChart.latestProps.rows.find( + mockTimelineChartProps.latest.rows.find( (row: { type?: string }) => row.type === type, ); @@ -892,7 +893,7 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); expect(screen.getByText(errors)).toBeInTheDocument(); - const logRow = MockTimelineChart.latestProps.rows.find( + const logRow = mockTimelineChartProps.latest.rows.find( (row: { type?: string }) => row.type === SourceKind.Log, ); const label = renderWithMantine(logRow.label); @@ -932,7 +933,7 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(null); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows).toHaveLength(1); + expect(mockTimelineChartProps.latest.rows).toHaveLength(1); }); it('renders Spans and Logs chips when log source is present', async () => { @@ -959,13 +960,13 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows.length).toBe(2); + expect(mockTimelineChartProps.latest.rows.length).toBe(2); const showLogsChip = screen.getByTestId('show-logs-chip'); await user.click(showLogsChip); await waitFor(() => { - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); }); }); @@ -975,13 +976,13 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows.length).toBe(2); + expect(mockTimelineChartProps.latest.rows.length).toBe(2); const showSpansChip = screen.getByTestId('show-spans-chip'); await user.click(showSpansChip); await waitFor(() => { - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); }); }); @@ -1055,7 +1056,7 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); // Valid spans still render — the log failure did not blank the chart. - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); // The full-chart error block is NOT shown. expect( screen.queryByText('An error occurred while fetching trace data:'), @@ -1082,7 +1083,7 @@ describe('DBTraceWaterfallChartContainer', () => { await waitForLoading(); // Spans still render (unfiltered fallback) — chart is not blanked. - expect(MockTimelineChart.latestProps.rows.length).toBe(1); + expect(mockTimelineChartProps.latest.rows.length).toBe(1); expect( screen.queryByText('An error occurred while fetching trace data:'), ).not.toBeInTheDocument(); @@ -1223,7 +1224,7 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(); await waitForLoading(); - expect(MockTimelineChart.latestProps.rows).toHaveLength(1); + expect(mockTimelineChartProps.latest.rows).toHaveLength(1); expect(screen.getByText('1 span,')).toBeInTheDocument(); }); @@ -1350,7 +1351,7 @@ describe('DBTraceWaterfallChartContainer', () => { triggerRow, })); const rowTypes = () => - MockTimelineChart.latestProps.rows.map( + mockTimelineChartProps.latest.rows.map( (row: { id: string; type?: string }) => `${row.type}:${row.id}`, ); @@ -1366,7 +1367,7 @@ describe('DBTraceWaterfallChartContainer', () => { 'trace:row-id', 'log:row-id', ]); - const [row] = MockTimelineChart.latestProps.rows; + const [row] = mockTimelineChartProps.latest.rows; expect(row.events[0].tooltip).toBe( `${triggeredBy} | Started at Jan 1 1:00:00.000 AM`, ); diff --git a/packages/app/src/components/__tests__/DashboardTableOfContents.test.tsx b/packages/app/src/components/__tests__/DashboardTableOfContents.test.tsx index 68b65419e2..a544720e94 100644 --- a/packages/app/src/components/__tests__/DashboardTableOfContents.test.tsx +++ b/packages/app/src/components/__tests__/DashboardTableOfContents.test.tsx @@ -113,7 +113,7 @@ describe('DashboardTableOfContents', () => { .spyOn(window, 'requestAnimationFrame') .mockImplementation(cb => { cb(0); - return 0 as unknown as number; + return 0; }); }); diff --git a/packages/app/src/components/__tests__/SourceForm.test.tsx b/packages/app/src/components/__tests__/SourceForm.test.tsx index 4f813df71b..af6eed736f 100644 --- a/packages/app/src/components/__tests__/SourceForm.test.tsx +++ b/packages/app/src/components/__tests__/SourceForm.test.tsx @@ -1,4 +1,5 @@ import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import '@testing-library/jest-dom'; @@ -9,7 +10,7 @@ describe('TableSourceForm Bidirectional Linking', () => { const mockOnCreate = jest.fn(); // Mock sources data - const sources = [ + const sources: Record[] = [ { id: 'trace-source-1', name: 'Trace Source 1', @@ -18,7 +19,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, ]; - const newLogSource: TSource = { + const newLogSource: TSource = fromPartial({ id: 'new-log-source', name: 'New Log Source', kind: SourceKind.Log, @@ -29,7 +30,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, timestampValueExpression: 'Timestamp', traceSourceId: 'trace-source-1', // This will trigger bidirectional linking - } as TSource; + }); // This is the bidirectional linking logic from the component const correlationFields: Record< @@ -41,22 +42,24 @@ describe('TableSourceForm Bidirectional Linking', () => { ], }; + const newSourceFields: Record = newLogSource; + // Execute the bidirectional linking logic for (const [fieldName, targetConfigs] of Object.entries( correlationFields, )) { - const targetSourceId = (newLogSource as any)[fieldName]; + const targetSourceId = newSourceFields[fieldName]; if (targetSourceId) { for (const { targetKind, targetField } of targetConfigs) { const targetSource = sources.find(s => s.id === targetSourceId); if (targetSource && targetSource.kind === targetKind) { // Only update if the target field is empty - if (!(targetSource as any)[targetField]) { + if (!targetSource[targetField]) { await mockUpdateSourceMutateAsync({ source: { ...targetSource, [targetField]: newLogSource.id, - } as TSource, + }, }); } } @@ -84,7 +87,7 @@ describe('TableSourceForm Bidirectional Linking', () => { const mockOnCreate = jest.fn(); // Mock sources data - const sources = [ + const sources: Record[] = [ { id: 'log-source-1', name: 'Log Source 1', @@ -93,7 +96,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, ]; - const newTraceSource: TSource = { + const newTraceSource: TSource = fromPartial({ id: 'new-trace-source', name: 'New Trace Source', kind: SourceKind.Trace, @@ -104,7 +107,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, timestampValueExpression: 'Timestamp', logSourceId: 'log-source-1', // This will trigger bidirectional linking - } as TSource; + }); // This is the bidirectional linking logic from the component for trace sources const correlationFields: Record< @@ -116,22 +119,24 @@ describe('TableSourceForm Bidirectional Linking', () => { ], }; + const newSourceFields: Record = newTraceSource; + // Execute the bidirectional linking logic for (const [fieldName, targetConfigs] of Object.entries( correlationFields, )) { - const targetSourceId = (newTraceSource as any)[fieldName]; + const targetSourceId = newSourceFields[fieldName]; if (targetSourceId) { for (const { targetKind, targetField } of targetConfigs) { const targetSource = sources.find(s => s.id === targetSourceId); if (targetSource && targetSource.kind === targetKind) { // Only update if the target field is empty - if (!(targetSource as any)[targetField]) { + if (!targetSource[targetField]) { await mockUpdateSourceMutateAsync({ source: { ...targetSource, [targetField]: newTraceSource.id, - } as TSource, + }, }); } } @@ -159,7 +164,7 @@ describe('TableSourceForm Bidirectional Linking', () => { const mockOnCreate = jest.fn(); // Mock sources with existing correlations - const sources = [ + const sources: Record[] = [ { id: 'log-source-1', name: 'Log Source 1', @@ -168,7 +173,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, ]; - const newTraceSource: TSource = { + const newTraceSource: TSource = fromPartial({ id: 'new-trace-source', name: 'New Trace Source', kind: SourceKind.Trace, @@ -179,7 +184,7 @@ describe('TableSourceForm Bidirectional Linking', () => { }, timestampValueExpression: 'Timestamp', logSourceId: 'log-source-1', // This should NOT establish bidirectional link - } as TSource; + }); // This is the bidirectional linking logic from the component for trace sources const correlationFields: Record< @@ -191,22 +196,24 @@ describe('TableSourceForm Bidirectional Linking', () => { ], }; + const newSourceFields: Record = newTraceSource; + // Execute the bidirectional linking logic for (const [fieldName, targetConfigs] of Object.entries( correlationFields, )) { - const targetSourceId = (newTraceSource as any)[fieldName]; + const targetSourceId = newSourceFields[fieldName]; if (targetSourceId) { for (const { targetKind, targetField } of targetConfigs) { const targetSource = sources.find(s => s.id === targetSourceId); if (targetSource && targetSource.kind === targetKind) { // Only update if the target field is empty - if (!(targetSource as any)[targetField]) { + if (!targetSource[targetField]) { await mockUpdateSourceMutateAsync({ source: { ...targetSource, [targetField]: newTraceSource.id, - } as TSource, + }, }); } } diff --git a/packages/app/src/components/__tests__/SourceSchemaPreview.test.tsx b/packages/app/src/components/__tests__/SourceSchemaPreview.test.tsx index 6b15d3e586..5770c10eea 100644 --- a/packages/app/src/components/__tests__/SourceSchemaPreview.test.tsx +++ b/packages/app/src/components/__tests__/SourceSchemaPreview.test.tsx @@ -68,10 +68,10 @@ describe('SourceSchemaPreview — controlled mode', () => { />, ); // Mantine 9 CloseButton renders without aria-label; find by its class. - const closeBtn = document.querySelector( - '.mantine-Modal-close', - ) as HTMLElement; - expect(closeBtn).toBeTruthy(); + const closeBtn = document.querySelector('.mantine-Modal-close'); + if (!(closeBtn instanceof HTMLElement)) { + throw new Error('Modal close button not found'); + } await userEvent.click(closeBtn); expect(onClose).toHaveBeenCalledTimes(1); }); diff --git a/packages/app/src/components/__tests__/SourcesList.test.tsx b/packages/app/src/components/__tests__/SourcesList.test.tsx index 50d2374b1e..3a61350001 100644 --- a/packages/app/src/components/__tests__/SourcesList.test.tsx +++ b/packages/app/src/components/__tests__/SourcesList.test.tsx @@ -21,13 +21,13 @@ const makeSource = ( name: string, overrides: Partial = {}, ): TSource => - ({ + fromPartial({ id, name, kind: SourceKind.Log, connection: 'conn-a', ...overrides, - }) as unknown as TSource; + }); describe('SourcesList section display', () => { beforeEach(() => { diff --git a/packages/app/src/components/__tests__/sourceFormUtils.test.ts b/packages/app/src/components/__tests__/sourceFormUtils.test.ts index 0d1dfecedb..ead9bc04e2 100644 --- a/packages/app/src/components/__tests__/sourceFormUtils.test.ts +++ b/packages/app/src/components/__tests__/sourceFormUtils.test.ts @@ -1,15 +1,16 @@ import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { distinctSections } from '@/components/Sources/SourceForm/sourceFormUtils'; const makeSource = (id: string, section?: string): TSource => - ({ + fromPartial({ id, name: id, kind: SourceKind.Log, connection: 'conn-a', ...(section === undefined ? {} : { section }), - }) as unknown as TSource; + }); describe('distinctSections', () => { it('returns [] for undefined sources', () => { diff --git a/packages/app/src/components/alerts/__tests__/AlertRowMenu.test.tsx b/packages/app/src/components/alerts/__tests__/AlertRowMenu.test.tsx index 31291afee9..462008c630 100644 --- a/packages/app/src/components/alerts/__tests__/AlertRowMenu.test.tsx +++ b/packages/app/src/components/alerts/__tests__/AlertRowMenu.test.tsx @@ -7,6 +7,7 @@ import { MantineProvider } from '@mantine/core'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { AlertRowMenu } from '@/components/alerts/AlertRowMenu'; import type { AlertsPageItem } from '@/types'; @@ -53,7 +54,7 @@ jest.mock('@/brand', () => ({ // so a placeholder id would throw the moment the export panel opens. const TILE_ALERT_ID = '655b1b7d9143aa1b1b73f4f4'; -const savedSearchAlert = { +const savedSearchAlert = fromPartial({ _id: 'alert-1', interval: '5m', threshold: 1, @@ -65,16 +66,16 @@ const savedSearchAlert = { createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', history: [], -} as unknown as AlertsPageItem; +}); -const tileAlert = { +const tileAlert = fromPartial({ ...savedSearchAlert, _id: 'alert-2', source: AlertSource.TILE, savedSearchId: undefined, dashboardId: 'dashboard-1', tileId: 'tile-1', -} as unknown as AlertsPageItem; +}); const inlineAlert: AlertsPageItem = { ...savedSearchAlert, diff --git a/packages/app/src/components/alerts/__tests__/EditAlertModal.test.tsx b/packages/app/src/components/alerts/__tests__/EditAlertModal.test.tsx index 72d302904e..fe2bbe7318 100644 --- a/packages/app/src/components/alerts/__tests__/EditAlertModal.test.tsx +++ b/packages/app/src/components/alerts/__tests__/EditAlertModal.test.tsx @@ -131,8 +131,9 @@ const renderModal = (alert: AlertsPageItem) => { }; const submitForm = async () => { - const saveButton = await screen.findByText('Save Alert'); - fireEvent.click(saveButton.closest('button') as HTMLButtonElement); + const saveButton = (await screen.findByText('Save Alert')).closest('button'); + if (!saveButton) throw new Error('Save Alert button not found'); + fireEvent.click(saveButton); await waitFor(() => { expect(updateAlertMutateAsync).toHaveBeenCalledTimes(1); }); diff --git a/packages/app/src/components/charts/__tests__/chartAnnotations.test.tsx b/packages/app/src/components/charts/__tests__/chartAnnotations.test.tsx index 01c5210c10..0c65e7446c 100644 --- a/packages/app/src/components/charts/__tests__/chartAnnotations.test.tsx +++ b/packages/app/src/components/charts/__tests__/chartAnnotations.test.tsx @@ -1,5 +1,5 @@ -import { ReactElement } from 'react'; -import { ReferenceLine } from 'recharts'; +import { isValidElement, ReactElement } from 'react'; +import { ReferenceLine, type ReferenceLineProps } from 'recharts'; import { type ChartAnnotation, @@ -11,17 +11,19 @@ import { resolveAnnotationSeries, } from '@/components/charts/chartAnnotations'; -// ReferenceLine element props are typed loosely; narrow for assertions. -const lineProps = (el: ReactElement) => - el.props as { - stroke: string; - strokeDasharray?: string; - strokeOpacity?: number; - x: number; - label?: { props: { value: string } }; - }; - -const labelOf = (el: ReactElement) => lineProps(el).label?.props.value; +const lineProps = (el: ReactElement) => { + if (!isValidElement(el) || el.type !== ReferenceLine) { + throw new Error('expected a ReferenceLine element'); + } + return el.props; +}; + +const labelOf = (el: ReactElement) => { + const { label } = lineProps(el); + return isValidElement<{ value: string }>(label) + ? label.props.value + : undefined; +}; // A domain wide enough that no marker clamps, and one bounded window for the // clamp cases. diff --git a/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts b/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts index 6c4f0053f0..e16e06ba97 100644 --- a/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts +++ b/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts @@ -1,5 +1,6 @@ import { MetricsDataType, + SourceKind, TMetricSource, } from '@hyperdx/common-utils/dist/types'; import { renderHook } from '@testing-library/react'; @@ -12,16 +13,16 @@ jest.mock('@/hooks/useMetadata'); const mockUseGetKeyValues = jest.mocked(useGetKeyValues); -const METRIC_SOURCE = { +const METRIC_SOURCE = fromPartial({ id: 'metric-source-1', - kind: 'metric', + kind: SourceKind.Metric, name: 'Metrics', connection: 'conn-1', from: { databaseName: 'default', tableName: '' }, timestampValueExpression: 'TimeUnix', resourceAttributesExpression: 'ResourceAttributes', metricTables: { [MetricsDataType.Gauge]: 'otel_metrics_gauge' }, -} as unknown as TMetricSource; +}); const DATE_RANGE: [Date, Date] = [ new Date('2024-01-01T00:00:00Z'), diff --git a/packages/app/src/hooks/__tests__/useChartConfig.test.tsx b/packages/app/src/hooks/__tests__/useChartConfig.test.tsx index b429b9eeff..853874ad3c 100644 --- a/packages/app/src/hooks/__tests__/useChartConfig.test.tsx +++ b/packages/app/src/hooks/__tests__/useChartConfig.test.tsx @@ -4,7 +4,6 @@ import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/browser' import { DEFAULT_PROMQL_REDUCER } from '@hyperdx/common-utils/dist/core/promql'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { - ChartConfigWithDateRange, ChartConfigWithOptDateRange, DisplayType, MetricsDataType, @@ -93,7 +92,7 @@ jest.mock('@/api', () => ({ const createMockChartConfig = ( overrides: Partial = {}, ): ChartConfigWithOptDateRange => - ({ + fromPartial({ connection: 'foo', from: { databaseName: 'default', @@ -104,7 +103,7 @@ const createMockChartConfig = ( timestampValueExpression: 'TimestampTime', groupBy: 'SeverityText', ...overrides, - }) as ChartConfigWithOptDateRange; + }); const createMockQueryResponse = (data: any[]): ResponseJSON => { return { @@ -132,14 +131,14 @@ describe('useChartConfig', () => { it('returns windows aligned to the granularity if the granularity is auto', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-10 00:00:00'), new Date('2023-01-10 01:00:00'), ], granularity: 'auto', // will be 1 minute timestampValueExpression: 'TimestampTime', - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 30, // 30s 5 * 60, // 5m @@ -174,14 +173,14 @@ describe('useChartConfig', () => { it('returns windows aligned to the granularity if the granularity is larger than the window size', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-10 00:00:00'), new Date('2023-01-10 00:10:00'), ], granularity: '1 minute', timestampValueExpression: 'TimestampTime', - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 30, // 30s 60, // 1m @@ -223,14 +222,14 @@ describe('useChartConfig', () => { it('Skips windows that would be double-queried due to alignment', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-10 00:08:00'), new Date('2023-01-10 00:10:00'), ], granularity: '1 minute', timestampValueExpression: 'TimestampTime', - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 15, // 15s ], @@ -256,7 +255,7 @@ describe('useChartConfig', () => { it('returns windows aligned to the granularity if the granularity is smaller than the window size', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-09 22:00:40'), new Date('2023-01-10 00:00:30'), @@ -264,7 +263,7 @@ describe('useChartConfig', () => { granularity: '1 minute', timestampValueExpression: 'TimestampTime', dateRangeEndInclusive: true, - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 15 * 60, // 15m 30 * 60, // 30m @@ -312,14 +311,14 @@ describe('useChartConfig', () => { it('does not return a window that starts before the overall start date', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-10 00:00:30'), new Date('2023-01-10 00:02:00'), ], granularity: '1 minute', timestampValueExpression: 'TimestampTime', - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 60, // 1m ], @@ -345,14 +344,14 @@ describe('useChartConfig', () => { it('returns a single window matching the input date range if the input date range is empty', () => { expect( getGranularityAlignedTimeWindows( - { + fromPartial({ dateRange: [ new Date('2023-01-10 00:00:30'), new Date('2023-01-10 00:00:30'), ], granularity: '1 minute', timestampValueExpression: 'TimestampTime', - } as ChartConfigWithDateRange & { granularity: string }, + }), [ 60, // 1m 5 * 60, // 5m @@ -402,7 +401,7 @@ describe('useChartConfig', () => { const createPromqlConfig = ( overrides: Partial = {}, ): ChartConfigWithOptDateRange => - ({ + fromPartial({ configType: 'promql', promqlExpression: 'e2e_service_up', connection: 'foo', @@ -412,7 +411,7 @@ describe('useChartConfig', () => { new Date('2023-01-10 01:00:00'), ], ...overrides, - }) as ChartConfigWithOptDateRange; + }); /** The server resolves the connection and table from the source alone. */ const expectOnlySourceNamed = (params: object) => { diff --git a/packages/app/src/hooks/__tests__/useDashboardContainers.test.tsx b/packages/app/src/hooks/__tests__/useDashboardContainers.test.tsx index 5751e9d66a..2402dbc63c 100644 --- a/packages/app/src/hooks/__tests__/useDashboardContainers.test.tsx +++ b/packages/app/src/hooks/__tests__/useDashboardContainers.test.tsx @@ -1,15 +1,16 @@ import { act, renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { Dashboard } from '@/dashboard'; import useDashboardContainers from '@/hooks/useDashboardContainers'; function makeDashboard(overrides: Partial = {}): Dashboard { - return { + return fromPartial({ name: 'Test Dashboard', tiles: [], containers: [], ...overrides, - } as Dashboard; + }); } function renderContainersHook(dashboard: Dashboard) { @@ -41,7 +42,7 @@ describe('useDashboardContainers', () => { ], }, ], - tiles: [ + tiles: fromPartial([ { id: 't1', containerId: 'c1', tabId: 'tab-1', x: 0, y: 0, w: 6, h: 4 }, { id: 't2', containerId: 'c1', tabId: 'tab-1', x: 6, y: 0, w: 6, h: 4 }, { @@ -54,7 +55,7 @@ describe('useDashboardContainers', () => { h: 4, }, { id: 't4', containerId: 'c1', tabId: 'tab-3', x: 0, y: 0, w: 6, h: 4 }, - ] as Dashboard['tiles'], + ]), }); it('action "delete" removes tiles belonging to the deleted tab', () => { @@ -127,7 +128,7 @@ describe('useDashboardContainers', () => { ], }, ], - tiles: [ + tiles: fromPartial([ { id: 't1', containerId: 'c1', @@ -137,7 +138,7 @@ describe('useDashboardContainers', () => { w: 6, h: 4, }, - ] as Dashboard['tiles'], + ]), }); const { hook, getDashboard } = renderContainersHook(emptyTabDashboard); @@ -164,7 +165,7 @@ describe('useDashboardContainers', () => { ], }, ], - tiles: [ + tiles: fromPartial([ { id: 't1', containerId: 'c1', @@ -183,7 +184,7 @@ describe('useDashboardContainers', () => { w: 6, h: 4, }, - ] as Dashboard['tiles'], + ]), }); const { hook, getDashboard } = renderContainersHook(twoTabDashboard); @@ -217,7 +218,7 @@ describe('useDashboardContainers', () => { collapsed: true, }, ], - tiles: [ + tiles: fromPartial([ { id: 't1', containerId: 'section-1', @@ -242,7 +243,7 @@ describe('useDashboardContainers', () => { w: 8, h: 6, }, - ] as Dashboard['tiles'], + ]), }); it('handleAddTab creates 2 tabs and assigns existing tiles to tab 1', () => { @@ -315,11 +316,11 @@ describe('useDashboardContainers', () => { ], }, ], - tiles: [ + tiles: fromPartial([ { id: 't1', containerId: 'g1', tabId: 'tab-a', x: 0, y: 0, w: 6, h: 4 }, { id: 't2', containerId: 'g1', tabId: 'tab-a', x: 6, y: 0, w: 6, h: 4 }, { id: 't3', containerId: 'g1', tabId: 'tab-b', x: 0, y: 0, w: 6, h: 4 }, - ] as Dashboard['tiles'], + ]), }); it('action="ungroup" strips containerId and tabId from all tiles across all tabs', () => { diff --git a/packages/app/src/hooks/__tests__/useDenoisedRows.test.tsx b/packages/app/src/hooks/__tests__/useDenoisedRows.test.tsx index 73cfd4f4a9..9da6b66ab0 100644 --- a/packages/app/src/hooks/__tests__/useDenoisedRows.test.tsx +++ b/packages/app/src/hooks/__tests__/useDenoisedRows.test.tsx @@ -4,6 +4,7 @@ import { TSource, } from '@hyperdx/common-utils/dist/types'; import { renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { findBodyResultColumn, useDenoisedRows } from '@/hooks/useDenoisedRows'; import { useGroupedPatterns } from '@/hooks/usePatterns'; @@ -15,12 +16,12 @@ jest.mock('@/hooks/usePatterns', () => ({ const mockUseGroupedPatterns = jest.mocked(useGroupedPatterns); -const source = { +const source = fromPartial({ id: 'logs', kind: SourceKind.Log, bodyExpression: 'Body', severityTextExpression: 'SeverityText', -} as unknown as TSource; +}); const config = (select: string): BuilderChartConfigWithDateRange => ({ select, diff --git a/packages/app/src/hooks/__tests__/useFieldExpressionGenerator.test.tsx b/packages/app/src/hooks/__tests__/useFieldExpressionGenerator.test.tsx index a7e0350770..c22bd3ff62 100644 --- a/packages/app/src/hooks/__tests__/useFieldExpressionGenerator.test.tsx +++ b/packages/app/src/hooks/__tests__/useFieldExpressionGenerator.test.tsx @@ -11,13 +11,13 @@ jest.mock('../useMetadata', () => ({ })); describe('useFieldExpressionGenerator', () => { - const mockSource = { + const mockSource = fromPartial({ from: { databaseName: 'test_db', tableName: 'traces', }, connection: 'conn1', - } as TSource; + }); beforeEach(() => { jest.clearAllMocks(); diff --git a/packages/app/src/hooks/__tests__/useMetadata.test.tsx b/packages/app/src/hooks/__tests__/useMetadata.test.tsx index 4443c78c27..352d45cc8c 100644 --- a/packages/app/src/hooks/__tests__/useMetadata.test.tsx +++ b/packages/app/src/hooks/__tests__/useMetadata.test.tsx @@ -34,7 +34,7 @@ import { useSources } from '@/source'; const createMockChartConfig = ( overrides: Partial = {}, ): BuilderChartConfigWithDateRange => - ({ + fromPartial({ timestampValueExpression: '', connection: 'foo', from: { @@ -42,10 +42,13 @@ const createMockChartConfig = ( tableName: 'traces', }, ...overrides, - }) as BuilderChartConfigWithDateRange; + }); const createMockMetadata = () => - new Metadata({} as ClickhouseClient, {} as MetadataCache); + new Metadata( + fromPartial({}), + fromPartial({}), + ); jest.mock('@/source', () => ({ useSources: jest.fn().mockReturnValue({ @@ -826,12 +829,11 @@ describe('useMultipleAllFields', () => { team = {}; mockMetadata = createMockMetadata(); jest.spyOn(metadataModule, 'getMetadata').mockReturnValue(mockMetadata); - jest.spyOn(api, 'useMe').mockImplementation( - () => - ({ - data: { team }, - isFetched: true, - }) as any, + jest.spyOn(api, 'useMe').mockImplementation(() => + fromPartial({ + data: { team }, + isFetched: true, + }), ); jest .spyOn(mockMetadata, 'getColumns') diff --git a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx index a9edd3b699..2090e42eab 100644 --- a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx +++ b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx @@ -82,7 +82,7 @@ import { queryPromqlChartConfig } from '@/utils/promqlChartQuery'; const createMockChartConfig = ( overrides: Partial = {}, ): ChartConfigWithDateRange => - ({ + fromPartial({ timestampValueExpression: 'Timestamp', connection: 'foo', from: { @@ -99,7 +99,7 @@ const createMockChartConfig = ( }, orderBy: 'Timestamp DESC', ...overrides, - }) as ChartConfigWithDateRange; + }); describe('useOffsetPaginatedQuery', () => { // Increase timeout for complex async operations diff --git a/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx b/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx index 6ab1c48c06..0f00ebebbf 100644 --- a/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx +++ b/packages/app/src/hooks/__tests__/useOnClickLinkBuilder.test.tsx @@ -200,7 +200,7 @@ describe('useOnClickLinkBuilder', () => { // Clicking the failing row fires the toast. const preventDefault = jest.fn(); - action.onClickError!({ preventDefault } as any); + action.onClickError!(fromPartial({ preventDefault })); expect(preventDefault).toHaveBeenCalledTimes(1); expect(jest.mocked(notifications.show)).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/packages/app/src/hooks/__tests__/useResizable.test.tsx b/packages/app/src/hooks/__tests__/useResizable.test.tsx index 259be9e1a6..5d422b4112 100644 --- a/packages/app/src/hooks/__tests__/useResizable.test.tsx +++ b/packages/app/src/hooks/__tests__/useResizable.test.tsx @@ -1,5 +1,7 @@ +import type { MouseEvent as ReactMouseEvent } from 'react'; import { fireEvent } from '@testing-library/dom'; import { act, render, renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import useResizable from '@/hooks/useResizable'; @@ -47,8 +49,11 @@ describe('useResizable', () => { act(() => { // Start resize at x=500 - const startEvent = new MouseEvent('mousedown', { clientX: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientX: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Move mouse to x=600 (right) const moveEvent = new MouseEvent('mousemove', { clientX: 600 }); @@ -65,8 +70,11 @@ describe('useResizable', () => { act(() => { // Start resize at x=500 - const startEvent = new MouseEvent('mousedown', { clientX: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientX: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Move mouse to x=600 (right) const moveEvent = new MouseEvent('mousemove', { clientX: 600 }); @@ -82,8 +90,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'right')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientX: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientX: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Try to resize smaller than minimum (10%) const moveEvent = new MouseEvent('mousemove', { clientX: 800 }); @@ -97,8 +108,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'left')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientX: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientX: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Try to resize larger than maximum const moveEvent = new MouseEvent('mousemove', { clientX: 1000 }); @@ -136,8 +150,11 @@ describe('useResizable', () => { act(() => { // Start resize - const startEvent = new MouseEvent('mousedown', { clientX: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientX: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); }); unmount(); @@ -187,8 +204,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'bottom')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientY: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientY: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Move mouse down by 100px const moveEvent = new MouseEvent('mousemove', { clientY: 600 }); @@ -204,8 +224,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'top')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientY: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientY: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Move mouse down by 100px const moveEvent = new MouseEvent('mousemove', { clientY: 600 }); @@ -221,8 +244,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'bottom')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientY: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientY: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Try to resize smaller than minimum (10%) const moveEvent = new MouseEvent('mousemove', { clientY: 800 }); @@ -236,8 +262,11 @@ describe('useResizable', () => { const { result } = renderHook(() => useResizable(20, 'top')); act(() => { - const startEvent = new MouseEvent('mousedown', { clientY: 500 }); - result.current.startResize(startEvent as any); + const startEvent = fromPartial>({ + clientY: 500, + preventDefault: jest.fn(), + }); + result.current.startResize(startEvent); // Try to resize larger than maximum const moveEvent = new MouseEvent('mousemove', { clientY: 1000 }); diff --git a/packages/app/src/hooks/__tests__/useServiceMap.test.ts b/packages/app/src/hooks/__tests__/useServiceMap.test.ts index 36b5c89c75..2f59d955ac 100644 --- a/packages/app/src/hooks/__tests__/useServiceMap.test.ts +++ b/packages/app/src/hooks/__tests__/useServiceMap.test.ts @@ -413,7 +413,7 @@ describe('aggregateServiceMapData', () => { }); describe('getServiceMapQuery', () => { - const source: TTraceSource = { + const source: TTraceSource = fromPartial({ id: 'src', name: 'Traces', kind: SourceKind.Trace, @@ -429,7 +429,7 @@ describe('getServiceMapQuery', () => { statusCodeExpression: 'StatusCode', durationExpression: 'Duration', durationPrecision: 9, - } as TTraceSource; + }); const dateRange: [Date, Date] = [ new Date('2024-01-01T00:00:00Z'), diff --git a/packages/app/src/hooks/__tests__/useTileSelection.test.tsx b/packages/app/src/hooks/__tests__/useTileSelection.test.tsx index d02159201f..82be16d8ed 100644 --- a/packages/app/src/hooks/__tests__/useTileSelection.test.tsx +++ b/packages/app/src/hooks/__tests__/useTileSelection.test.tsx @@ -1,4 +1,5 @@ import { act, renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { Dashboard } from '@/dashboard'; import useTileSelection from '@/hooks/useTileSelection'; @@ -16,7 +17,7 @@ function renderSelectionHook(dashboard: Dashboard) { describe('useTileSelection — handleGroupSelected', () => { it('deletes a source group that is emptied when all its tiles move to the new group', () => { - const dashboard: Dashboard = { + const dashboard: Dashboard = fromPartial({ name: 'Test', containers: [ { @@ -46,7 +47,7 @@ describe('useTileSelection — handleGroupSelected', () => { h: 4, }, ], - } as Dashboard; + }); const { hook, getDashboard } = renderSelectionHook(dashboard); act(() => { @@ -63,7 +64,7 @@ describe('useTileSelection — handleGroupSelected', () => { }); it('keeps a source group that still has remaining tiles', () => { - const dashboard: Dashboard = { + const dashboard: Dashboard = fromPartial({ name: 'Test', containers: [ { @@ -93,7 +94,7 @@ describe('useTileSelection — handleGroupSelected', () => { h: 4, }, ], - } as Dashboard; + }); const { hook, getDashboard } = renderSelectionHook(dashboard); act(() => { @@ -110,7 +111,7 @@ describe('useTileSelection — handleGroupSelected', () => { }); it('does not delete unrelated empty containers', () => { - const dashboard: Dashboard = { + const dashboard: Dashboard = fromPartial({ name: 'Test', containers: [ { @@ -129,7 +130,7 @@ describe('useTileSelection — handleGroupSelected', () => { h: 4, }, ], - } as Dashboard; + }); const { hook, getDashboard } = renderSelectionHook(dashboard); act(() => { diff --git a/packages/app/src/theme/ChartColors.stories.tsx b/packages/app/src/theme/ChartColors.stories.tsx index 6e57c9cc1a..e44df75b19 100644 --- a/packages/app/src/theme/ChartColors.stories.tsx +++ b/packages/app/src/theme/ChartColors.stories.tsx @@ -191,7 +191,7 @@ export const BarChartPreview = () => {
{values.map((value, i) => (
{ it('uses sqlExpression as displayedKey when alias is not provided', () => { const source = createBasicSource([ - { sqlExpression: 'ServiceName' } as any, // No alias + { sqlExpression: 'ServiceName' }, // No alias ]); const data = [{ ServiceName: 'api-service' }]; const meta = [{ name: 'ServiceName', type: 'String' }]; diff --git a/scripts/ci/ratchet-baseline.json b/scripts/ci/ratchet-baseline.json index b9e61835d8..ed669c65e5 100644 --- a/scripts/ci/ratchet-baseline.json +++ b/scripts/ci/ratchet-baseline.json @@ -6,7 +6,7 @@ "@source": 0 }, "app": { - "as-any": 99, + "as-any": 67, "ts-ignore": 0, "eslint-disable": 119, "@source": 0