Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dev-overlay-handle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@svelte-vitals/vite': minor
---

Add a dev-time SvelteKit handle, `svelteVitalsHandle` (exported from `@svelte-vitals/vite/hooks`). Added to `src/hooks.server.ts`, it analyzes each visited page's rendered `<head>` in dev and prints SEO warnings for the current route to the terminal — request-driven, dev-only, and never mutates the response.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ jobs:
> [!NOTE]
> Code scanning only displays results that carry a file location, so project-scoped checks that aren't tied to a route file (`robots.txt`, `sitemap`, `<html lang>`) don't appear as alerts in the Security tab. They are still reported by the `github`, `console`, and `json` reporters — keep one of those in your pipeline if you rely on those checks.

### Dev overlay (request-driven)

Get SEO feedback while developing: add the dev handle to `src/hooks.server.ts` and svelte-vitals analyzes each page's **rendered** `<head>` as you navigate, printing warnings for the current route to your dev-server terminal. It sees real values, so dynamic routes (`{data.title}`) are checked against what actually renders.

```ts
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { svelteVitalsHandle } from '@svelte-vitals/vite/hooks';

export const handle = sequence(svelteVitalsHandle());
```

It runs in `dev` only (a no-op in production builds) and never modifies the response — it only reads the rendered HTML. Coverage follows navigation: a route is checked when you visit it, and re-warned only when its findings change.

`svelteVitalsHandle` accepts a focused subset of the plugin options — `metaComponents` and per-rule `rules` overrides (e.g. `svelteVitalsHandle({ rules: { SEO008: 'off' } })`). Analysis errors are swallowed so a tool bug never breaks a request; set the `SVELTE_VITALS_DEBUG` env var to surface them in the terminal while debugging.

### Exit codes

| Code | Meaning |
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"test": "pnpm -r test",
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"check:publish": "pnpm --filter @svelte-vitals/core --filter svelte-vitals exec publint",
"check:publish": "pnpm --filter @svelte-vitals/core --filter @svelte-vitals/vite --filter svelte-vitals exec publint",
"release": "changeset publish",
"changeset": "changeset"
},
Expand Down
13 changes: 13 additions & 0 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./hooks": {
"types": "./dist/hooks/index.d.ts",
"import": "./dist/hooks/index.js"
}
},
"main": "./dist/index.js",
Expand All @@ -39,14 +43,23 @@
},
"dependencies": {
"@svelte-vitals/core": "workspace:*",
"esm-env": "catalog:",
"node-html-parser": "catalog:",
"tinyglobby": "catalog:"
},
"peerDependencies": {
"@sveltejs/kit": "catalog:",
"vite": "catalog:"
},
"peerDependenciesMeta": {
"@sveltejs/kit": {
"optional": true
}
},
"devDependencies": {
"@sveltejs/kit": "catalog:",
"@types/node": "catalog:",
"svelte": "catalog:",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
"vite": "catalog:"
}
}
29 changes: 29 additions & 0 deletions packages/vite/src/hooks/format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { isPenalized, effectiveSeverity, type Config, type Result, type Severity } from '@svelte-vitals/core';

const GLYPH: Record<Severity, string> = { critical: '✗', warning: '⚠', info: '·' };
const RANK: Record<Severity, number> = { critical: 0, warning: 1, info: 2 };

function penalized(results: Result[], config: Config): Result[] {
return results.filter((r) => isPenalized(r.detection, config.treatDynamicAs));
}

/** Compact terminal report for one route's penalized findings; '' when the route is clean. */
export function formatDevReport(route: string, results: Result[], config: Config): string {
const failing = penalized(results, config).sort(
(a, b) => RANK[effectiveSeverity(a, config)] - RANK[effectiveSeverity(b, config)] || a.id.localeCompare(b.id)
);
if (failing.length === 0) return '';
const lines = [`[svelte-vitals] ${route}`];
for (const r of failing) {
lines.push(` ${GLYPH[effectiveSeverity(r, config)]} ${r.id} ${r.message}`);
}
return lines.join('\n');
}

/** Stable signature of a route's penalized findings, so a route is re-printed only when it changes. */
export function findingSignature(results: Result[], config: Config): string {
return penalized(results, config)
.map((r) => `${r.id}:${effectiveSeverity(r, config)}:${r.detection.presence}:${r.detection.value}`)
.sort()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
.join('|');
}
82 changes: 82 additions & 0 deletions packages/vite/src/hooks/handle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { DEV } from 'esm-env';
import type { Handle } from '@sveltejs/kit';
import {
allRules,
applyRuleSeverities,
defineConfig,
runRules,
selectRules,
type Config,
type Project,
type ResolvedHead,
type Rule
} from '@svelte-vitals/core';
import { parseHtmlHead } from '../providers/rendered/parse-html.js';
import { findingSignature, formatDevReport } from './format.js';
import type { SvelteVitalsHookOptions } from './options.js';

async function analyzeAndWarn(
html: string,
route: string,
rules: Rule[],
config: Config,
lastSignature: Map<string, string>
): Promise<void> {
try {
const { tags, htmlLang } = parseHtmlHead(html);
const head: ResolvedHead = { route, source: 'rendered', tags, file: route };
// robots/sitemap are not page-scoped, so mark them present to suppress SEO006/SEO007;
// htmlLang comes from the rendered document so SEO009 is evaluated against reality.
const project: Project = { hasRobotsTxt: true, hasSitemap: true, htmlLang };
const results = applyRuleSeverities(await runRules(rules, { heads: [head], project, config }), config);

const signature = findingSignature(results, config);
if (lastSignature.get(route) === signature) return;
lastSignature.set(route, signature);

const report = formatDevReport(route, results, config);
if (report) console.warn(report);
} catch (err) {
// Dev tooling must never break the request: swallow any parse/rule error.
// Set SVELTE_VITALS_DEBUG to surface tool-internal errors while debugging.
if (globalThis.process?.env?.SVELTE_VITALS_DEBUG) {
console.warn('[svelte-vitals] dev analysis failed:', err);
}
}
}

/**
* SvelteKit `handle` that prints SEO warnings for each visited page's rendered `<head>`,
* in dev only. Add it to `src/hooks.server.ts`, e.g. `sequence(svelteVitalsHandle())`.
*/
export function svelteVitalsHandle(options: SvelteVitalsHookOptions = {}): Handle {
// Dev-only. `DEV` (esm-env) resolves statically to `true` under the dev server and
// `false` in production builds; on non-Node runtimes (edge) its fallback reads no
// bare `process`, so it stays `false`. Everywhere but dev this handle is a no-op,
// and we skip building the rule set entirely.
if (!DEV) return ({ event, resolve }) => resolve(event);

// treatDynamicAs/failOn intentionally left at defaults: rendered HTML never yields
// `dynamic` values (so treatDynamicAs is moot) and this handle reports rather than
// gates (so failOn is unused).
const config = defineConfig({
metaComponents: options.metaComponents ?? [],
rules: options.rules ?? {}
});
const rules = selectRules(allRules, config);
const lastSignature = new Map<string, string>();

return ({ event, resolve }) => {
let buffer = '';
return resolve(event, {
transformPageChunk: ({ html, done }) => {
buffer += html;
// Observe-only: return the chunk unchanged and never block the response on
// analysis. We fire-and-forget on the final chunk; analyzeAndWarn swallows
// its own errors, so the floating promise can never reject.
if (done) void analyzeAndWarn(buffer, event.route.id ?? event.url.pathname, rules, config, lastSignature);
return html;
}
});
};
}
2 changes: 2 additions & 0 deletions packages/vite/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { svelteVitalsHandle } from './handle.js';
export type { SvelteVitalsHookOptions } from './options.js';
9 changes: 9 additions & 0 deletions packages/vite/src/hooks/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { RuleSetting } from '@svelte-vitals/core';

/** Options for the dev-time SvelteKit handle. A focused subset of the plugin options. */
export interface SvelteVitalsHookOptions {
/** Component names treated as meta sources (design §11 layer 4). Mirrors the plugin option. */
metaComponents?: string[];
/** Per-rule overrides keyed by rule id, e.g. `{ SEO008: 'off' }`. Mirrors the plugin option. */
rules?: Record<string, RuleSetting>;
}
82 changes: 82 additions & 0 deletions packages/vite/test/dev-format.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { describe, it, expect } from 'vitest';
import { formatDevReport, findingSignature } from '../src/hooks/format.js';
import { defineConfig, type Result } from '@svelte-vitals/core';

const config = defineConfig({});

const failing: Result[] = [
{
id: 'SEO003',
severity: 'warning',
detection: { presence: 'none', value: 'absent' },
route: '/p',
message: 'Missing <link rel="canonical">'
},
{
id: 'SEO001',
severity: 'critical',
detection: { presence: 'none', value: 'absent' },
route: '/p',
message: 'Missing <title>'
}
];

const passing: Result[] = [
{
id: 'SEO001',
severity: 'critical',
detection: { presence: 'own', value: 'static' },
route: '/p',
message: '<title>'
}
];

describe('formatDevReport', () => {
it('lists only penalized findings, most-severe first, under a route header', () => {
const out = formatDevReport('/p', failing, config);
const lines = out.split('\n');
expect(lines[0]).toBe('[svelte-vitals] /p');
expect(lines[1]).toBe(' ✗ SEO001 Missing <title>');
expect(lines[2]).toBe(' ⚠ SEO003 Missing <link rel="canonical">');
});

it('returns an empty string for a clean route', () => {
expect(formatDevReport('/p', passing, config)).toBe('');
});
});

describe('findingSignature', () => {
it('is stable regardless of input order', () => {
const reversed = [...failing].reverse();
expect(findingSignature(failing, config)).toBe(findingSignature(reversed, config));
});

it('ignores passing findings and changes when penalized findings change', () => {
expect(findingSignature(passing, config)).toBe('');
const sigA = findingSignature(failing, config);
const sigB = findingSignature([failing[0]!], config);
expect(sigA).not.toBe(sigB);
});

it('distinguishes a missing tag from an empty one (same id and severity)', () => {
const missing: Result[] = [
{
id: 'SEO001',
severity: 'critical',
detection: { presence: 'none', value: 'absent' },
route: '/p',
message: 'Missing <title>'
}
];
const empty: Result[] = [
{
id: 'SEO001',
severity: 'critical',
detection: { presence: 'own', value: 'absent' },
route: '/p',
message: 'Empty <title>'
}
];
expect(findingSignature(missing, config)).not.toBe(findingSignature(empty, config));
});
});
Loading