Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix: eliminate all no-non-null-assertion and no-unused-vars lint warnings (#2312)

Andrey Goder5f2080462c36
diff --git a/apps/docsite/src/app/(preview)/playground-preview/runner.ts b/apps/docsite/src/app/(preview)/playground-preview/runner.ts
index a64d86d819..4695dbd1e7 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/runner.ts
+++ b/apps/docsite/src/app/(preview)/playground-preview/runner.ts
@@ -3,10 +3,7 @@
import {scope} from './scope';
interface BabelStandalone {
- transform(
- code: string,
- options: Record<string, unknown>,
- ): {code: string};
+ transform(code: string, options: Record<string, unknown>): {code: string};
}
/** Set by the page after loading Babel from CDN */
@@ -31,27 +28,51 @@ type RunResult =
| {Component: React.ComponentType; error?: undefined}
| {Component?: undefined; error: string; phase: RunPhase};
-const ASSET_RE = /\.(png|jpe?g|gif|svg|webp|ico|bmp|css|scss|less|sass|woff2?|ttf|eot|otf|mp4|webm|ogg|mp3|wav)$/i;
+const ASSET_RE =
+ /\.(png|jpe?g|gif|svg|webp|ico|bmp|css|scss|less|sass|woff2?|ttf|eot|otf|mp4|webm|ogg|mp3|wav)$/i;
const scopeLookup = new Map<string, Record<string, unknown>>();
for (const [key, value] of Object.entries(scope)) {
scopeLookup.set(key.toLowerCase(), value as Record<string, unknown>);
}
-function compileCode(code: string): {compiled: string; imports: ParsedImport[]} {
+function compileCode(code: string): {
+ compiled: string;
+ imports: ParsedImport[];
+} {
const imports: ParsedImport[] = [];
- const importStripper = (): {visitor: Record<string, (path: {node: Record<string, unknown>; remove: () => void}) => void>} => ({
+ const importStripper = (): {
+ visitor: Record<
+ string,
+ (path: {node: Record<string, unknown>; remove: () => void}) => void
+ >;
+ } => ({
visitor: {
- ImportDeclaration(path: {node: Record<string, unknown>; remove: () => void}) {
+ ImportDeclaration(path: {
+ node: Record<string, unknown>;
+ remove: () => void;
+ }) {
const source = (path.node.source as {value: string}).value;
const specifiers: ParsedImport['specifiers'] = [];
- for (const spec of path.node.specifiers as Array<{type: string; local: {name: string}; imported?: {name: string}}>) {
+ for (const spec of path.node.specifiers as Array<{
+ type: string;
+ local: {name: string};
+ imported?: {name: string};
+ }>) {
if (spec.type === 'ImportDefaultSpecifier') {
- specifiers.push({local: spec.local.name, imported: null, type: 'default'});
+ specifiers.push({
+ local: spec.local.name,
+ imported: null,
+ type: 'default',
+ });
} else if (spec.type === 'ImportNamespaceSpecifier') {
- specifiers.push({local: spec.local.name, imported: null, type: 'namespace'});
+ specifiers.push({
+ local: spec.local.name,
+ imported: null,
+ type: 'namespace',
+ });
} else if (spec.type === 'ImportSpecifier') {
specifiers.push({
local: spec.local.name,
@@ -64,8 +85,13 @@ function compileCode(code: string): {compiled: string; imports: ParsedImport[]}
imports.push({source, specifiers});
path.remove();
},
- ExpressionStatement(path: {node: Record<string, unknown>; remove: () => void}) {
- const expr = path.node.expression as Record<string, unknown> | undefined;
+ ExpressionStatement(path: {
+ node: Record<string, unknown>;
+ remove: () => void;
+ }) {
+ const expr = path.node.expression as
+ | Record<string, unknown>
+ | undefined;
if (
expr &&
typeof expr === 'object' &&
@@ -78,7 +104,11 @@ function compileCode(code: string): {compiled: string; imports: ParsedImport[]}
},
});
- const result = Babel!.transform(code, {
+ if (Babel == null) {
+ throw new Error('Babel has not been loaded yet — call setBabel() first');
+ }
+
+ const result = Babel.transform(code, {
filename: 'playground.tsx',
presets: [
['typescript', {isTSX: true, allExtensions: true}],
diff --git a/apps/docsite/src/components/ShowcaseThumbnail.tsx b/apps/docsite/src/components/ShowcaseThumbnail.tsx
index f258a1df69..498b33c692 100644
--- a/apps/docsite/src/components/ShowcaseThumbnail.tsx
+++ b/apps/docsite/src/components/ShowcaseThumbnail.tsx
@@ -105,10 +105,13 @@ function getShowcaseComponent(
dirName: string,
): React.LazyExoticComponent<React.ComponentType> {
const key = `${category}/${dirName}`;
- if (!componentCache.has(key)) {
- componentCache.set(key, lazyShowcase(category, dirName));
+ const cached = componentCache.get(key);
+ if (cached != null) {
+ return cached;
}
- return componentCache.get(key)!;
+ const component = lazyShowcase(category, dirName);
+ componentCache.set(key, component);
+ return component;
}
export function ShowcaseThumbnail({
diff --git a/apps/example-vite-tailwind/src/main.tsx b/apps/example-vite-tailwind/src/main.tsx
index 832c649fc7..e5e38ddc9e 100644
--- a/apps/example-vite-tailwind/src/main.tsx
+++ b/apps/example-vite-tailwind/src/main.tsx
@@ -5,6 +5,7 @@ import {createRoot} from 'react-dom/client';
import './index.css';
import App from './App';
+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- root element must exist in index.html
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
diff --git a/apps/example-vite/src/main.tsx b/apps/example-vite/src/main.tsx
index 2e2aa76547..f9354b6408 100644
--- a/apps/example-vite/src/main.tsx
+++ b/apps/example-vite/src/main.tsx
@@ -7,6 +7,7 @@ import '@xds/theme-default/theme.css';
import './index.css';
import App from './App';
+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- root element must exist in index.html
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
diff --git a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
index d54d81cc5a..7f58138f87 100644
--- a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
@@ -39,13 +39,15 @@ function buildNavTree(currentPath: string): XDSTreeListItemData[] {
const componentMap = new Map<string, XDSTreeListItemData[]>();
for (const b of blocks) {
const group = b.component;
- if (!componentMap.has(group)) {
- componentMap.set(group, []);
+ let items = componentMap.get(group);
+ if (items == null) {
+ items = [];
+ componentMap.set(group, items);
}
const shortName = b.name.includes('—')
? b.name.split('—').slice(1).join('—').trim()
: b.name;
- componentMap.get(group)!.push({
+ items.push({
id: b.href,
label: shortName,
href: basePath + b.href,
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
index 6d5df88781..354b1fac83 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
@@ -143,6 +143,8 @@ function usePerfMetrics() {
if (!scrollContainer) {
return;
}
+ // Capture narrowed reference for use in nested function closures
+ const container: HTMLElement = scrollContainer;
scrollContainer.scrollTop = 0;
const s = scrollState.current;
@@ -175,7 +177,7 @@ function usePerfMetrics() {
const elapsed = performance.now() - start;
const progress = Math.min(elapsed / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3);
- scrollContainer!.scrollTop = totalScroll * eased;
+ container.scrollTop = totalScroll * eased;
if (progress < 1) {
requestAnimationFrame(step);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
index 918aed103e..f9a73746b4 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
@@ -654,10 +654,12 @@ function DeprecationsPanel() {
const map = new Map<string, typeof deprecations>();
for (const d of deprecations) {
const key = d.file;
- if (!map.has(key)) {
- map.set(key, []);
+ let items = map.get(key);
+ if (items == null) {
+ items = [];
+ map.set(key, items);
}
- map.get(key)!.push(d);
+ items.push(d);
}
return Array.from(map.entries());
}, []);
@@ -3163,7 +3165,10 @@ function PackageGridPage({
onSelectComponent: (key: string) => void;
}) {
const [hoveredComponent, setHoveredComponent] = useState<string | null>(null);
- const pkg = LIBRARY_PACKAGES.find(p => p.key === packageKey)!;
+ const pkg = LIBRARY_PACKAGES.find(p => p.key === packageKey);
+ if (pkg == null) {
+ return null;
+ }
const totalComponents = components.reduce(
(sum, cat) => sum + cat.items.length,
0,
diff --git a/apps/sandbox/src/app/(sandbox)/page.tsx b/apps/sandbox/src/app/(sandbox)/page.tsx
index 2a06b597ee..1eb0b92592 100644
--- a/apps/sandbox/src/app/(sandbox)/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/page.tsx
@@ -67,14 +67,16 @@ export default function Home() {
}
const map = new Map<string, typeof allPages>();
for (const page of filtered) {
- if (!map.has(page.category)) {
- map.set(page.category, []);
+ let items = map.get(page.category);
+ if (items == null) {
+ items = [];
+ map.set(page.category, items);
}
- map.get(page.category)!.push(page);
+ items.push(page);
}
return categories
.filter(c => map.has(c.label))
- .map(c => ({category: c.label, pages: map.get(c.label)!}));
+ .map(c => ({category: c.label, pages: map.get(c.label) ?? []}));
}, [activeTab, filtered]);
return (
diff --git a/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
index fb90fa0f5b..95805e273b 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
@@ -493,7 +493,10 @@ export default function ColorStudioPage() {
);
const usedRoles = useMemo(
- () => new Set(palette.filter(c => c.role).map(c => c.role!)),
+ () =>
+ new Set(
+ palette.map(c => c.role).filter((r): r is ThemeRole => r != null),
+ ),
[palette],
);
diff --git a/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
index edc1e60379..54fef45870 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
+++ b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
@@ -74,10 +74,11 @@ export function useImageModeTest(
let cancelled = false;
const config = ALGO_CONFIG[algorithm];
+ const srcUrl = src;
async function detect() {
try {
- const response = await fetch(src!, {mode: 'cors'});
+ const response = await fetch(srcUrl, {mode: 'cors'});
const blob = await response.blob();
const bitmap = await createImageBitmap(blob);
diff --git a/apps/storybook/stories/ChatToolCalls.stories.tsx b/apps/storybook/stories/ChatToolCalls.stories.tsx
index 19f5e7d26e..53ce3beffa 100644
--- a/apps/storybook/stories/ChatToolCalls.stories.tsx
+++ b/apps/storybook/stories/ChatToolCalls.stories.tsx
@@ -262,7 +262,10 @@ export const Streaming: Story = {
return;
}
// Add as running
- const call = allCalls[i]!;
+ const call = allCalls[i];
+ if (call == null) {
+ return;
+ }
setCalls(prev => [
...prev,
{...call, status: 'running', duration: undefined},
@@ -273,7 +276,7 @@ export const Streaming: Story = {
setTimeout(
() => {
setCalls(prev =>
- prev.map((c, j) => (j === idx ? {...allCalls[idx]!} : c)),
+ prev.map((c, j) => (j === idx ? {...(allCalls[idx] ?? c)} : c)),
);
// Add next after completion
setTimeout(addNext, 200);
diff --git a/apps/storybook/stories/MoreMenu.stories.tsx b/apps/storybook/stories/MoreMenu.stories.tsx
index cb4bc74ac8..c4384099f3 100644
--- a/apps/storybook/stories/MoreMenu.stories.tsx
+++ b/apps/storybook/stories/MoreMenu.stories.tsx
@@ -2,7 +2,6 @@
import type {Meta, StoryObj} from '@storybook/react';
import {XDSMoreMenu} from '@xds/core/MoreMenu';
-import {XDSDropdownMenuItem} from '@xds/core/DropdownMenu';
import {XDSButton} from '@xds/core/Button';
import {
PencilIcon,
diff --git a/apps/storybook/stories/PowerSearch.stories.tsx b/apps/storybook/stories/PowerSearch.stories.tsx
index 0fcd0d6025..4c577bdc60 100644
--- a/apps/storybook/stories/PowerSearch.stories.tsx
+++ b/apps/storybook/stories/PowerSearch.stories.tsx
@@ -1217,9 +1217,12 @@ function CustomIntegerEditor({
max={1000}
value={current}
onChange={e => {
+ if (filter.operator == null) {
+ return;
+ }
onSave({
field: filter.field,
- operator: filter.operator!,
+ operator: filter.operator,
value: {type: 'integer', value: Number(e.target.value)},
});
}}
diff --git a/internal/vibe-tests/app/src/main.report.tsx b/internal/vibe-tests/app/src/main.report.tsx
index 3fb4f414ed..bf396e6c7c 100644
--- a/internal/vibe-tests/app/src/main.report.tsx
+++ b/internal/vibe-tests/app/src/main.report.tsx
@@ -20,6 +20,7 @@ const Report = lazy(() =>
import('./report/Report').then(m => ({default: m.Report})),
);
+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- root element must exist in index.html
const root = createRoot(document.getElementById('root')!);
root.render(
<Suspense fallback={<div>Loading report...</div>}>
diff --git a/internal/vibe-tests/app/src/main.tsx b/internal/vibe-tests/app/src/main.tsx
index 9e23734207..50c7e40356 100644
--- a/internal/vibe-tests/app/src/main.tsx
+++ b/internal/vibe-tests/app/src/main.tsx
@@ -28,5 +28,6 @@ function App() {
);
}
+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- root element must exist in index.html
const root = createRoot(document.getElementById('root')!);
root.render(<App />);
diff --git a/internal/vibe-tests/app/src/report/CompareView.tsx b/internal/vibe-tests/app/src/report/CompareView.tsx
index 676a949f44..b6e9e86680 100644
--- a/internal/vibe-tests/app/src/report/CompareView.tsx
+++ b/internal/vibe-tests/app/src/report/CompareView.tsx
@@ -152,11 +152,11 @@ function CostComparisonSection({
xds: `${(xdsCost.avgDurationMs / 1000).toFixed(1)}s`,
baseline: `${(baselineCost.avgDurationMs / 1000).toFixed(1)}s`,
...(isThreeWay
- ? {html: `${(htmlCost!.avgDurationMs / 1000).toFixed(1)}s`}
+ ? {html: `${((htmlCost?.avgDurationMs ?? 0) / 1000).toFixed(1)}s`}
: {}),
...(isFourWay
? {
- xdsTailwind: `${(xdsTailwindCost!.avgDurationMs / 1000).toFixed(1)}s`,
+ xdsTailwind: `${((xdsTailwindCost?.avgDurationMs ?? 0) / 1000).toFixed(1)}s`,
}
: {}),
winner: costWinner(
@@ -175,11 +175,11 @@ function CostComparisonSection({
xds: `~${xdsCost.estimatedInputTokens.toLocaleString()}`,
baseline: `~${baselineCost.estimatedInputTokens.toLocaleString()}`,
...(isThreeWay
- ? {html: `~${htmlCost!.estimatedInputTokens.toLocaleString()}`}
+ ? {html: `~${htmlCost?.estimatedInputTokens.toLocaleString()}`}
: {}),
...(isFourWay
? {
- xdsTailwind: `~${xdsTailwindCost!.estimatedInputTokens.toLocaleString()}`,
+ xdsTailwind: `~${xdsTailwindCost?.estimatedInputTokens.toLocaleString()}`,
}
: {}),
winner: costWinner(
@@ -196,11 +196,11 @@ function CostComparisonSection({
xds: `~${xdsCost.estimatedOutputTokens.toLocaleString()}`,
baseline: `~${baselineCost.estimatedOutputTokens.toLocaleString()}`,
...(isThreeWay
- ? {html: `~${htmlCost!.estimatedOutputTokens.toLocaleString()}`}
+ ? {html: `~${htmlCost?.estimatedOutputTokens.toLocaleString()}`}
: {}),
...(isFourWay
? {
- xdsTailwind: `~${xdsTailwindCost!.estimatedOutputTokens.toLocaleString()}`,
+ xdsTailwind: `~${xdsTailwindCost?.estimatedOutputTokens.toLocaleString()}`,
}
: {}),
winner: costWinner(
@@ -218,12 +218,12 @@ function CostComparisonSection({
baseline: `~${(baselineCost.estimatedInputTokens + baselineCost.estimatedOutputTokens).toLocaleString()}`,
...(isThreeWay
? {
- html: `~${(htmlCost!.estimatedInputTokens + htmlCost!.estimatedOutputTokens).toLocaleString()}`,
+ html: `~${((htmlCost?.estimatedInputTokens ?? 0) + (htmlCost?.estimatedOutputTokens ?? 0)).toLocaleString()}`,
}
: {}),
...(isFourWay
? {
- xdsTailwind: `~${(xdsTailwindCost!.estimatedInputTokens + xdsTailwindCost!.estimatedOutputTokens).toLocaleString()}`,
+ xdsTailwind: `~${((xdsTailwindCost?.estimatedInputTokens ?? 0) + (xdsTailwindCost?.estimatedOutputTokens ?? 0)).toLocaleString()}`,
}
: {}),
winner: costWinner(
@@ -244,9 +244,9 @@ function CostComparisonSection({
metric: 'Avg Output Lines',
xds: String(xdsCost.avgOutputLines),
baseline: String(baselineCost.avgOutputLines),
- ...(isThreeWay ? {html: String(htmlCost!.avgOutputLines)} : {}),
+ ...(isThreeWay ? {html: String(htmlCost?.avgOutputLines)} : {}),
...(isFourWay
- ? {xdsTailwind: String(xdsTailwindCost!.avgOutputLines)}
+ ? {xdsTailwind: String(xdsTailwindCost?.avgOutputLines)}
: {}),
winner: costWinner(
xdsCost.avgOutputLines,
@@ -261,8 +261,8 @@ function CostComparisonSection({
metric: 'Avg Docs Read',
xds: String(xdsCost.avgDocsRead),
baseline: String(baselineCost.avgDocsRead),
- ...(isThreeWay ? {html: String(htmlCost!.avgDocsRead)} : {}),
- ...(isFourWay ? {xdsTailwind: String(xdsTailwindCost!.avgDocsRead)} : {}),
+ ...(isThreeWay ? {html: String(htmlCost?.avgDocsRead)} : {}),
+ ...(isFourWay ? {xdsTailwind: String(xdsTailwindCost?.avgDocsRead)} : {}),
winner: 'tie', // not inherently better or worse
},
];
@@ -356,8 +356,8 @@ export function CompareView({comparison}: CompareViewProps) {
dimension: DIMENSION_LABELS[dim],
xdsScore: xds.averages[dim] ?? 0,
baselineScore: baseline.averages[dim] ?? 0,
- ...(isThreeWay ? {htmlScore: html!.averages[dim] ?? 0} : {}),
- ...(isFourWay ? {xdsTailwindScore: xdsTailwind!.averages[dim] ?? 0} : {}),
+ ...(isThreeWay ? {htmlScore: html?.averages[dim] ?? 0} : {}),
+ ...(isFourWay ? {xdsTailwindScore: xdsTailwind?.averages[dim] ?? 0} : {}),
delta: (xds.averages[dim] ?? 0) - (baseline.averages[dim] ?? 0),
winner: winners[dim],
}));
diff --git a/internal/vibe-tests/app/src/report/PromptDetailCard.tsx b/internal/vibe-tests/app/src/report/PromptDetailCard.tsx
index f860ec3476..1a156be734 100644
--- a/internal/vibe-tests/app/src/report/PromptDetailCard.tsx
+++ b/internal/vibe-tests/app/src/report/PromptDetailCard.tsx
@@ -42,7 +42,7 @@ function ScoreSummary({label, score}: {label: string; score: UniversalScore}) {
<ScoreItem
key={dim}
label={DIMENSION_LABELS[dim]}
- score={score[dim]!.score}
+ score={score[dim]?.score ?? 0}
/>
))}
<ScoreItem label="Overall" score={computeOverall(score)} />
@@ -55,7 +55,7 @@ function ScoreSummary({label, score}: {label: string; score: UniversalScore}) {
function Findings({score}: {score: UniversalScore}) {
const allFindings = ALL_DIMENSIONS.filter(dim => score[dim] != null).flatMap(
dim =>
- (score[dim]!.findings ?? []).map(f => ({
+ (score[dim]?.findings ?? []).map(f => ({
dimension: DIMENSION_LABELS[dim],
...f,
})),
diff --git a/internal/vibe-tests/src/build-report.ts b/internal/vibe-tests/src/build-report.ts
index a35df92a7d..7220070281 100644
--- a/internal/vibe-tests/src/build-report.ts
+++ b/internal/vibe-tests/src/build-report.ts
@@ -370,9 +370,12 @@ async function main() {
const previewManifestPath = path.join(iterDir, 'previews', 'manifest.json');
let previews: Record<string, Record<string, string>> | undefined;
if (fs.existsSync(previewManifestPath)) {
- previews = JSON.parse(fs.readFileSync(previewManifestPath, 'utf-8'));
+ const parsed: Record<string, Record<string, string>> = JSON.parse(
+ fs.readFileSync(previewManifestPath, 'utf-8'),
+ );
+ previews = parsed;
console.log(
- ` ✓ Preview manifest loaded (${Object.keys(previews!).length} prompts)`,
+ ` ✓ Preview manifest loaded (${Object.keys(parsed).length} prompts)`,
);
}
diff --git a/internal/vibe-tests/src/sampling.ts b/internal/vibe-tests/src/sampling.ts
index 91a3221185..6e2c2d5f4e 100644
--- a/internal/vibe-tests/src/sampling.ts
+++ b/internal/vibe-tests/src/sampling.ts
@@ -40,7 +40,10 @@ export function stratifiedSample(
break;
}
- const categoryPrompts = byCategory.get(category)!;
+ const categoryPrompts = byCategory.get(category);
+ if (categoryPrompts == null) {
+ continue;
+ }
const randomIndex = Math.floor(Math.random() * categoryPrompts.length);
const prompt = categoryPrompts[randomIndex];
@@ -55,7 +58,12 @@ export function stratifiedSample(
while (result.length < sampleSize && attempts < maxAttempts) {
const category = categories[categoryIndex % categories.length];
- const categoryPrompts = byCategory.get(category)!;
+ const categoryPrompts = byCategory.get(category);
+ if (categoryPrompts == null) {
+ categoryIndex++;
+ attempts++;
+ continue;
+ }
const available = categoryPrompts.filter(p => !selected.has(p.id));
if (available.length > 0) {
diff --git a/internal/vibe-tests/src/universal-aggregate.ts b/internal/vibe-tests/src/universal-aggregate.ts
index 6c2618d040..de78747162 100644
--- a/internal/vibe-tests/src/universal-aggregate.ts
+++ b/internal/vibe-tests/src/universal-aggregate.ts
@@ -268,7 +268,7 @@ async function main() {
if (hasDesignScores) {
const designScores = Object.values(byPrompt)
.filter(s => s.design != null)
- .map(s => s.design!.score);
+ .map(s => s.design?.score ?? 0);
if (designScores.length > 0) {
averages.design = Math.round(
designScores.reduce((a, b) => a + b, 0) / designScores.length,
@@ -368,7 +368,9 @@ async function main() {
console.log(`\n🌙 Dark Mode: ${darkModeRate}%`);
// Efficiency metrics summary
- const allEfficiency = Object.values(byPrompt).map(s => s.efficiency.metrics!);
+ const allEfficiency = Object.values(byPrompt)
+ .map(s => s.efficiency.metrics)
+ .filter(<T>(m: T | undefined): m is T => m != null);
if (allEfficiency.length > 0) {
const avgDecisions =
allEfficiency.reduce((s, m) => s + m.decisionsPerElement, 0) /
@@ -381,7 +383,9 @@ async function main() {
}
// Maintainability metrics summary
- const allMaint = Object.values(byPrompt).map(s => s.maintainability.metrics!);
+ const allMaint = Object.values(byPrompt)
+ .map(s => s.maintainability.metrics)
+ .filter(<T>(m: T | undefined): m is T => m != null);
if (allMaint.length > 0) {
const avgSemantic =
allMaint.reduce((s, m) => s + m.semanticRatio, 0) / allMaint.length;
diff --git a/internal/vibe-tests/src/universal-compare.ts b/internal/vibe-tests/src/universal-compare.ts
index 4df76d8910..1fbf333df3 100644
--- a/internal/vibe-tests/src/universal-compare.ts
+++ b/internal/vibe-tests/src/universal-compare.ts
@@ -387,11 +387,11 @@ async function main() {
{label: 'XDS', data: xds},
{label: 'Baseline', data: baseline},
];
- if (isThreeWay) {
- targets.push({label: 'HTML', data: htmlData!});
+ if (isThreeWay && htmlData != null) {
+ targets.push({label: 'HTML', data: htmlData});
}
- if (isFourWay) {
- targets.push({label: 'XDS+TW', data: twData!});
+ if (isFourWay && twData != null) {
+ targets.push({label: 'XDS+TW', data: twData});
}
// Use markdown-style table for CLI (simpler than box-drawing for N targets)
@@ -448,7 +448,9 @@ async function main() {
// Efficiency metrics comparison
const targetEffMetrics = targets.map(t => ({
label: t.label,
- metrics: Object.values(t.data.byPrompt).map(s => s.efficiency.metrics!),
+ metrics: Object.values(t.data.byPrompt)
+ .map(s => s.efficiency.metrics)
+ .filter(<T>(m: T | undefined): m is T => m != null),
}));
if (targetEffMetrics.every(t => t.metrics.length > 0)) {
const avgDpe = targetEffMetrics.map(
@@ -474,9 +476,9 @@ async function main() {
// Maintainability metrics comparison
const targetMaintMetrics = targets.map(t => ({
label: t.label,
- metrics: Object.values(t.data.byPrompt).map(
- s => s.maintainability.metrics!,
- ),
+ metrics: Object.values(t.data.byPrompt)
+ .map(s => s.maintainability.metrics)
+ .filter(<T>(m: T | undefined): m is T => m != null),
}));
if (targetMaintMetrics.every(t => t.metrics.length > 0)) {
const avgSem = targetMaintMetrics.map(
@@ -501,24 +503,28 @@ async function main() {
if (xds.cost && baseline.cost) {
console.log(`\n💰 Cost:`);
const costTargets = targets.filter(t => t.data.cost);
- const hasDuration = costTargets.some(t => t.data.cost!.avgDurationMs > 0);
+ const hasDuration = costTargets.some(
+ t => (t.data.cost?.avgDurationMs ?? 0) > 0,
+ );
if (hasDuration) {
const durParts = costTargets.map(
- t => `${t.label} ${(t.data.cost!.avgDurationMs / 1000).toFixed(1)}s`,
+ t =>
+ `${t.label} ${((t.data.cost?.avgDurationMs ?? 0) / 1000).toFixed(1)}s`,
);
console.log(` Avg duration: ${durParts.join(' | ')}`);
}
const linesParts = costTargets.map(
- t => `${t.label} ${t.data.cost!.avgOutputLines}`,
+ t => `${t.label} ${t.data.cost?.avgOutputLines ?? 0}`,
);
console.log(` Avg output lines: ${linesParts.join(' | ')}`);
const docsParts = costTargets.map(
- t => `${t.label} ${t.data.cost!.avgDocsRead}`,
+ t => `${t.label} ${t.data.cost?.avgDocsRead ?? 0}`,
);
console.log(` Avg docs read: ${docsParts.join(' | ')}`);
const tokenParts = costTargets.map(t => {
const total =
- t.data.cost!.estimatedInputTokens + t.data.cost!.estimatedOutputTokens;
+ (t.data.cost?.estimatedInputTokens ?? 0) +
+ (t.data.cost?.estimatedOutputTokens ?? 0);
return `${t.label} ~${total}`;
});
console.log(` Est. tokens: ${tokenParts.join(' | ')}`);
diff --git a/internal/vibe-tests/src/universal-eval.ts b/internal/vibe-tests/src/universal-eval.ts
index 3e85916e55..3fd0dc885a 100644
--- a/internal/vibe-tests/src/universal-eval.ts
+++ b/internal/vibe-tests/src/universal-eval.ts
@@ -59,7 +59,7 @@ const buildErrorsCache = new Map<string, BuildErrors | null>();
*/
export function loadBuildErrors(iterDir: string): BuildErrors | null {
if (buildErrorsCache.has(iterDir)) {
- return buildErrorsCache.get(iterDir)!;
+ return buildErrorsCache.get(iterDir) ?? null;
}
const errorsPath = _path.join(iterDir, 'build-errors.json');
diff --git a/internal/vibe-tests/src/utils.ts b/internal/vibe-tests/src/utils.ts
index c0fb28fb67..9fb455936c 100644
--- a/internal/vibe-tests/src/utils.ts
+++ b/internal/vibe-tests/src/utils.ts
@@ -140,7 +140,10 @@ export function stratifiedSample(
// First pass: one from each category
for (const category of categories) {
- const categoryPrompts = byCategory.get(category)!;
+ const categoryPrompts = byCategory.get(category);
+ if (categoryPrompts == null) {
+ continue;
+ }
const randomIndex = Math.floor(Math.random() * categoryPrompts.length);
result.push(categoryPrompts[randomIndex]);
@@ -153,7 +156,11 @@ export function stratifiedSample(
let categoryIndex = 0;
while (result.length < sampleSize) {
const category = categories[categoryIndex % categories.length];
- const categoryPrompts = byCategory.get(category)!;
+ const categoryPrompts = byCategory.get(category);
+ if (categoryPrompts == null) {
+ categoryIndex++;
+ continue;
+ }
const available = categoryPrompts.filter(p => !result.includes(p));
if (available.length > 0) {
@@ -227,9 +234,9 @@ export function ensureTsxFiles(codeDir: string): string[] {
const jsonPath = path.join(codeDir, jsonFile);
try {
- const data = JSON.parse(
- fs.readFileSync(jsonPath, 'utf-8'),
- ) as JsonResultEntry | JsonResultEntry[];
+ const data = JSON.parse(fs.readFileSync(jsonPath, 'utf-8')) as
+ | JsonResultEntry
+ | JsonResultEntry[];
// Find the depth-0 entry (initial generation, before follow-ups)
const entries = Array.isArray(data) ? data : [data];
diff --git a/packages/cli/templates/pages/ai-chat-landing/page.tsx b/packages/cli/templates/pages/ai-chat-landing/page.tsx
index c10b0e6ff7..42a7d5b7bc 100644
--- a/packages/cli/templates/pages/ai-chat-landing/page.tsx
+++ b/packages/cli/templates/pages/ai-chat-landing/page.tsx
@@ -436,8 +436,8 @@ export default function AIChatTemplate() {
input.focus();
// Select all existing content so insertText replaces it
const sel = window.getSelection();
- if (sel) {
- sel.selectAllChildren(document.activeElement!);
+ if (sel && document.activeElement) {
+ sel.selectAllChildren(document.activeElement);
}
input.insertText(prompt);
// Dispatch input event to trigger emitChange and clear placeholder
diff --git a/packages/cli/templates/pages/library/page.tsx b/packages/cli/templates/pages/library/page.tsx
index df67a98c4f..cd73f4aeb8 100644
--- a/packages/cli/templates/pages/library/page.tsx
+++ b/packages/cli/templates/pages/library/page.tsx
@@ -476,14 +476,16 @@ export default function LibraryPage() {
const order = CATEGORIES.filter(c => c !== 'All');
const map = new Map<string, LibraryItem[]>();
for (const item of filtered) {
- if (!map.has(item.category)) {
- map.set(item.category, []);
+ let group = map.get(item.category);
+ if (!group) {
+ group = [];
+ map.set(item.category, group);
}
- map.get(item.category)!.push(item);
+ group.push(item);
}
return order
.filter(cat => map.has(cat))
- .map(cat => ({category: cat, items: map.get(cat)!}));
+ .map(cat => ({category: cat, items: map.get(cat) ?? []}));
}, [activeTab, filtered]);
return (
diff --git a/packages/cli/templates/pages/table-grouped/page.tsx b/packages/cli/templates/pages/table-grouped/page.tsx
index 5638070bc4..e7c82de17c 100644
--- a/packages/cli/templates/pages/table-grouped/page.tsx
+++ b/packages/cli/templates/pages/table-grouped/page.tsx
@@ -623,10 +623,12 @@ function groupTasks(
const map = new Map<string, TaskRow[]>();
for (const task of tasks) {
const key = String(task[groupBy]) || '—';
- if (!map.has(key)) {
- map.set(key, []);
+ let group = map.get(key);
+ if (!group) {
+ group = [];
+ map.set(key, group);
}
- map.get(key)!.push(task);
+ group.push(task);
}
return map;
}
@@ -1102,8 +1104,8 @@ export default function DataTableTemplate() {
))}
</colgroup>
{groupKeys.map(key => {
- const tasks = grouped.get(key)!;
- if (tasks.length === 0) {
+ const tasks = grouped.get(key);
+ if (!tasks || tasks.length === 0) {
return null;
}
const isExpanded = expandedGroups.has(key);
diff --git a/packages/lab/src/Chart/m4.ts b/packages/lab/src/Chart/m4.ts
index bbc022c885..e50e9f47d1 100644
--- a/packages/lab/src/Chart/m4.ts
+++ b/packages/lab/src/Chart/m4.ts
@@ -89,10 +89,10 @@ export function m4Reduce(
bucket.max = point;
} else {
bucket.last = point;
- if (point.y < bucket.min!.y) {
+ if (bucket.min && point.y < bucket.min.y) {
bucket.min = point;
}
- if (point.y > bucket.max!.y) {
+ if (bucket.max && point.y > bucket.max.y) {
bucket.max = point;
}
}
@@ -103,11 +103,11 @@ export function m4Reduce(
const result: M4Point[] = [];
for (const bucket of buckets) {
- if (!bucket.first) {
+ if (!bucket.first || !bucket.min || !bucket.max || !bucket.last) {
continue;
}
- const points = [bucket.first, bucket.min!, bucket.max!, bucket.last!];
+ const points = [bucket.first, bucket.min, bucket.max, bucket.last];
// Deduplicate (some may be the same point)
const seen = new Set<M4Point>();
diff --git a/packages/lab/src/Radial/XDSRadialArea.tsx b/packages/lab/src/Radial/XDSRadialArea.tsx
index 214105b51c..3aad8b8fc3 100644
--- a/packages/lab/src/Radial/XDSRadialArea.tsx
+++ b/packages/lab/src/Radial/XDSRadialArea.tsx
@@ -61,8 +61,11 @@ export function XDSRadialArea({
}
return axes.map(key => {
- const angle = angleByAxis.get(key)!;
- const domain = axisDomains.get(key)!;
+ const angle = angleByAxis.get(key);
+ const domain = axisDomains.get(key);
+ if (angle == null || !domain) {
+ return {x: cx, y: cy, key};
+ }
const raw = typeof datum[key] === 'number' ? (datum[key] as number) : 0;
const [min, max] = domain;
const t = max > min ? (raw - min) / (max - min) : 0;
diff --git a/packages/lab/src/Radial/XDSRadialAxis.tsx b/packages/lab/src/Radial/XDSRadialAxis.tsx
index 65613516a0..29bd2e9cd4 100644
--- a/packages/lab/src/Radial/XDSRadialAxis.tsx
+++ b/packages/lab/src/Radial/XDSRadialAxis.tsx
@@ -30,7 +30,10 @@ export function XDSRadialAxis({labelOffset = 16}: XDSRadialAxisProps) {
return (
<g>
{axes.map(key => {
- const angle = angleByAxis.get(key)!;
+ const angle = angleByAxis.get(key);
+ if (angle == null) {
+ return null;
+ }
const x = cx + Math.cos(angle) * (radius + labelOffset);
const y = cy + Math.sin(angle) * (radius + labelOffset);
diff --git a/packages/lab/src/Radial/XDSRadialGrid.tsx b/packages/lab/src/Radial/XDSRadialGrid.tsx
index eb1ad95385..f43a78e348 100644
--- a/packages/lab/src/Radial/XDSRadialGrid.tsx
+++ b/packages/lab/src/Radial/XDSRadialGrid.tsx
@@ -37,9 +37,13 @@ export function XDSRadialGrid({rings = 5}: XDSRadialGridProps) {
// Draw polygon ring connecting points at this radius
const points = axes
.map(key => {
- const angle = angleByAxis.get(key)!;
+ const angle = angleByAxis.get(key);
+ if (angle == null) {
+ return '';
+ }
return `${cx + Math.cos(angle) * r},${cy + Math.sin(angle) * r}`;
})
+ .filter(Boolean)
.join(' ');
return (
<polygon
@@ -55,7 +59,10 @@ export function XDSRadialGrid({rings = 5}: XDSRadialGridProps) {
{/* Axis lines from center to each vertex */}
{axes.map(key => {
- const angle = angleByAxis.get(key)!;
+ const angle = angleByAxis.get(key);
+ if (angle == null) {
+ return null;
+ }
return (
<line
key={key}
diff --git a/packages/lab/src/SVGIcon/XDSSVGIcon.tsx b/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
index c4c9b1771f..41810963b5 100644
--- a/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
+++ b/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
@@ -339,7 +339,7 @@ export function XDSSVGIcon({
const primarySplit = splitByRole(icon.primary);
const secondarySplit = hasSecondary
- ? splitByRole(icon.secondary!)
+ ? splitByRole(icon.secondary ?? [])
: {fill: [], stroke: []};
const allSecondary = [...secondarySplit.fill, ...secondarySplit.stroke];
diff --git a/packages/lab/src/SVGIcon/pathTransforms.ts b/packages/lab/src/SVGIcon/pathTransforms.ts
index 538fb921f9..bb7b33601f 100644
--- a/packages/lab/src/SVGIcon/pathTransforms.ts
+++ b/packages/lab/src/SVGIcon/pathTransforms.ts
@@ -293,15 +293,23 @@ export function roundCorners(d: string, cornerRounding: number): string {
}
if (mIdx >= 0) {
const mCmd = cmds[mIdx];
- const mPt = getEndpoint(mCmd)!;
- const prevPt = getEndpoint(prev)!;
+ const mPt = getEndpoint(mCmd);
+ const prevPt = getEndpoint(prev);
+ if (!mPt || !prevPt) {
+ result.push(curr);
+ continue;
+ }
// Find the first L after M
let firstL = mIdx + 1;
while (firstL < cmds.length && cmds[firstL].type !== 'L') {
firstL++;
}
if (firstL < cmds.length) {
- const firstLPt = getEndpoint(cmds[firstL])!;
+ const firstLPt = getEndpoint(cmds[firstL]);
+ if (!firstLPt) {
+ result.push(curr);
+ continue;
+ }
const d1 = dist(prevPt, mPt);
const d2 = dist(mPt, firstLPt);
@@ -339,12 +347,23 @@ export function roundCorners(d: string, cornerRounding: number): string {
next &&
(next.type === 'L' || next.type === 'Z')
) {
- const prevPt = getEndpoint(prev)!;
+ const prevPt = getEndpoint(prev);
+ if (!prevPt) {
+ result.push(curr);
+ continue;
+ }
const cornerPt: Point = {x: curr.x, y: curr.y};
- const nextPt =
- next.type === 'Z'
- ? getEndpoint(cmds.find(c => c.type === 'M')!)!
- : getEndpoint(next)!;
+ let nextPt: Point | null;
+ if (next.type === 'Z') {
+ const mCmd = cmds.find(c => c.type === 'M');
+ nextPt = mCmd ? getEndpoint(mCmd) : null;
+ } else {
+ nextPt = getEndpoint(next);
+ }
+ if (!nextPt) {
+ result.push(curr);
+ continue;
+ }
const d1 = dist(prevPt, cornerPt);
const d2 = dist(cornerPt, nextPt);
diff --git a/packages/lab/src/Sankey/XDSSankeyChart.tsx b/packages/lab/src/Sankey/XDSSankeyChart.tsx
index 4fe5587b54..6e49739a7b 100644
--- a/packages/lab/src/Sankey/XDSSankeyChart.tsx
+++ b/packages/lab/src/Sankey/XDSSankeyChart.tsx
@@ -84,8 +84,11 @@ function resolveColumnCount(
}
});
while (queue.length) {
- const id = queue.shift()!;
- const col = colMap.get(id)!;
+ const id = queue.shift();
+ if (id == null) {
+ break;
+ }
+ const col = colMap.get(id) ?? 0;
for (const tgt of outEdges.get(id) || []) {
colMap.set(tgt, Math.max(colMap.get(tgt) || 0, col + 1));
inDegree.set(tgt, (inDegree.get(tgt) || 0) - 1);
diff --git a/packages/lab/src/Sankey/layout.ts b/packages/lab/src/Sankey/layout.ts
index c6fb2a39c0..a26db76f66 100644
--- a/packages/lab/src/Sankey/layout.ts
+++ b/packages/lab/src/Sankey/layout.ts
@@ -69,8 +69,11 @@ function autoColumns(
});
while (queue.length) {
- const id = queue.shift()!;
- const col = colMap.get(id)!;
+ const id = queue.shift();
+ if (id == null) {
+ break;
+ }
+ const col = colMap.get(id) ?? 0;
for (const tgt of outEdges.get(id) || []) {
const newCol = col + 1;
colMap.set(tgt, Math.max(colMap.get(tgt) || 0, newCol));
@@ -183,22 +186,27 @@ export function computeLayout(
});
});
- const layoutLinks: SankeyLinkLayout[] = links.map(link => {
- const src = layoutNodes.get(link.source)!;
- const tgt = layoutNodes.get(link.target)!;
+ const layoutLinks: SankeyLinkLayout[] = links.flatMap(link => {
+ const src = layoutNodes.get(link.source);
+ const tgt = layoutNodes.get(link.target);
+ if (!src || !tgt) {
+ return [];
+ }
const lh = link.value * valueScale;
const sourceY = src.y + src._sourceOffset;
const targetY = tgt.y + tgt._targetOffset;
src._sourceOffset += lh;
tgt._targetOffset += lh;
- return {
- source: src,
- target: tgt,
- value: link.value,
- height: lh,
- sourceY,
- targetY,
- };
+ return [
+ {
+ source: src,
+ target: tgt,
+ value: link.value,
+ height: lh,
+ sourceY,
+ targetY,
+ },
+ ];
});
return {
diff --git a/packages/lab/src/ThreeD/XDS3DSurface.tsx b/packages/lab/src/ThreeD/XDS3DSurface.tsx
index 3dcd397b56..17723871d2 100644
--- a/packages/lab/src/ThreeD/XDS3DSurface.tsx
+++ b/packages/lab/src/ThreeD/XDS3DSurface.tsx
@@ -87,10 +87,14 @@ export function XDS3DSurface({
continue;
}
- const projected = corners.map(d => {
- const nx = normalize(d![xKey] as number, xDomain);
- const ny = normalize(d![yKey] as number, yDomain);
- const nz = normalize(d![zKey] as number, zDomain);
+ const validCorners = corners.filter(
+ (c): c is Record<string, unknown> => c != null,
+ );
+
+ const projected = validCorners.map(d => {
+ const nx = normalize(d[xKey] as number, xDomain);
+ const ny = normalize(d[yKey] as number, yDomain);
+ const nz = normalize(d[zKey] as number, zDomain);
return {...project(nx, ny, nz), ny};
});
diff --git a/packages/vega/src/XDSVegaChart.tsx b/packages/vega/src/XDSVegaChart.tsx
index 43cec1d2ac..eceed166dc 100644
--- a/packages/vega/src/XDSVegaChart.tsx
+++ b/packages/vega/src/XDSVegaChart.tsx
@@ -148,7 +148,9 @@ export function XDSVegaChart({
view?.finalize();
return;
}
- onReadyRef.current?.(view!);
+ if (view) {
+ onReadyRef.current?.(view);
+ }
})
.catch(fail);
} catch (err) {