no-navigation-without-resolve false positive with Paraglide localizeHref (scaffolded by sv create)
#1492
no-navigation-without-resolve false positive with Paraglide localizeHref (scaffolded by sv create)Development PRs
Bumps eslint-plugin-svelte from 3.15.0 to 3.15.1.
Release notes
Sourced from eslint-plugin-svelte's releases.
[email protected]
Patch Changes
#1477
8c5f51eThanks@ota-meshi! - fix(no-top-level-browser-globals): false positive when browser globals appear inside TypeScript generic type parameters (e.g.$state<HTMLElement>(...)).#1467
d81b556Thanks@marekdedic! - fix(no-navigation-without-resolve): fixed nullish link shorthands not being allowed
Changelog
Sourced from eslint-plugin-svelte's changelog.
3.15.1
Patch Changes
#1477
8c5f51eThanks@ota-meshi! - fix(no-top-level-browser-globals): false positive when browser globals appear inside TypeScript generic type parameters (e.g.$state<HTMLElement>(...)).#1467
d81b556Thanks@marekdedic! - fix(no-navigation-without-resolve): fixed nullish link shorthands not being allowed
Commits
9f9f588chore: release eslint-plugin-svelte (#1475)8c5f51efix(no-top-level-browser-globals): false positive when browser globals appear...88baa0fchore(no-navigation-without-resolve): refactored the checking function to be ...d81b556fix(no-navigation-without-resolve): fixed nullish link shorthands not being a...- See full diff in compare view
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR:
@dependabot rebasewill rebase this PR@dependabot recreatewill recreate this PR, overwriting any edits that have been made to it@dependabot show <dependency name> ignore conditionswill show all of the ignore conditions of the specified dependency@dependabot ignore this major versionwill close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)@dependabot ignore this minor versionwill close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)@dependabot ignore this dependencywill close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Rebuilds svelte/no-navigation-without-resolve to check statically identifiable URL patterns while skipping unknown values by default. The new strict option also reports values the analysis cannot verify.
This is a base-path navigation policy check, not proof that a URL is broken: the rule does not know the deployment origin or routing configuration.
Docs: no-navigation-without-resolve.md
Behavior
- Check links,
<area>, SVG<a>, form actions and submit-controlformaction, plusgoto(),pushState(),replaceState(),preloadData()andpreloadCode(). - Accept query/hash-only destinations, empty URLs,
page.url, query/hash suffixes afterresolve(), and nullableResolvedPathnamevalues in URL-taking sinks. Relative URLs usually keep the base path, so they are reported only withstrict(orallowRelativePaths: false). - Respect form ownership (including explicit
formattributes), submit-control types and effectiveformmethod; skip non-submitting controls and dialog submissions. Therel="external"exemption for links/forms expresses lint policy; it does not guarantee that SvelteKit routing oruse:enhanceis bypassed. - HTTP(S) and protocol-relative URLs in navigation calls may be same-origin: skip them by default and report them as unverifiable with
strict. Report non-HTTP(S) URLs in these calls. - Check only the supported first
preloadCode()argument: a root-relative pathname on Kit 2, a route ID on Kit 3. The pathname requirement is not relaxed byallowRelativePaths. - Follow variables, reassignments,
$state(),$derived(),$props()defaults, arrays, objects,{#each}and declared TypeScript literal types. Bound recursive evaluation, handle empty-string fallbacks and null/undefined defaults, and verify bindings before treating calls as read-only. - Provide targeted diagnostics and
resolve()/asset()suggestions. Run only on SvelteKit 2.26+; deprecateignoreGoto,ignoreLinks,ignorePushStateandignoreReplaceState.
The rule documentation describes accepted patterns, strict-mode behavior and analysis limitations. One minor changeset covers the change.
Specification checks
Rechecked SvelteKit's link options, form actions and navigation API, together with the Kit 2.26 implementation for version-specific behavior.
Validation
- Full plugin test suite: 1,710 passing. TypeScript, ESLint and formatting checks pass.
Real-project check
I ran the final rule (31948b7c) on 55 popular SvelteKit repositories, without type information. Each project used SvelteKit 2.70.3 or 3.1.1, matching its declared major version (pluja/whishper uses SvelteKit 1, so the rule does not run there).
- Default mode: 1,698 reports. All are root-relative paths such as
href="/about"orgoto('/login'). 1,674 have the path written on the reported line, and I checked all 24 others by hand: they hold literal paths like`/trail/view/${id}`. The only false positive found (base || '/'in huggingface/chat-ui) is fixed in this PR. - Existing
eslint-disablecomments: these repositories have 155 comments that disable this rule. 152 of those lines are no longer reported. The other 3 are root-relative paths. One of them is a link to a backend API, and the message suggestsrel="external"for that case. - Current rule (
main,8c8a881e): 3,151 reports on the same repositories, with the same setup. - Strict mode: 3,034 reports. The extra reports are unknown values (by design) and links with spread attributes.
- Not app code: most reports in
sveltejs/kit(test apps) andsveltejs/svelte.dev(tutorial apps) come from code that is not linted in practice. - Private app: I also ran the rule with type information on a large private SvelteKit monorepo (5 apps). Default mode gives 30 reports, all root-relative literals. The current rule gives 205 reports there, and at least 107 of them are false positives.
- No crashes.
Repositories
Issues
Fixes #1314, fixes #1327, fixes #1353, fixes #1487, fixes #1492, fixes #1502, fixes #1609, fixes #1615
- #1526: by design, unknown
data.pathis reported only withstrict; declared literal types can make a value statically identifiable. - #1524 (
redirect()): not included. Waiting for sveltejs/kit#17623. - Not covered: #1324 (
<link>), #1352 (custom resolve functions; unknown results are skipped in default mode).
Issue
Before You File a Bug Report Please Confirm You Have Done The Following...
- I have tried restarting my IDE and the issue persists.
- I have updated to the latest version of the packages.
What version of ESLint are you using?
10.0.3
What version of eslint-plugin-svelte are you using?
3.15.1
What did you do?
// eslint.config.js
import prettier from 'eslint-config-prettier';
import path from 'node:path';
import { includeIgnoreFile } from '@eslint/compat';
import js from '@eslint/js';
import svelte from 'eslint-plugin-svelte';
import { defineConfig } from 'eslint/config';
import globals from 'globals';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';
const gitignorePath = path.resolve(import.meta.dirname, '.gitignore');
export default defineConfig(
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs.recommended,
prettier,
...svelte.configs.prettier,
{
languageOptions: { globals: { ...globals.browser, ...globals.node } },
rules: {
'no-undef': 'off'
}
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parserOptions: {
projectService: true,
extraFileExtensions: ['.svelte'],
parser: ts.parser,
svelteConfig
}
}
}
);
<!-- src/routes/+layout.svelte (generated by sv create) -->
<script lang="ts">
import { page } from '$app/state';
import { locales, localizeHref } from '$lib/paraglide/runtime';
import './layout.css';
import favicon from '$lib/assets/favicon.svg';
let { children } = $props();
</script>
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
{@render children()}
<div style="display:none">
{#each locales as locale} <!-- <-- also missing `(locale)` here, but that's manually very easy fixable -->
<a href={localizeHref(page.url.pathname, { locale })}>{locale}</a>
{/each}
</div>
What did you expect to happen?
localizeHref() from @inlang/paraglide-js should be recognized as a valid navigation helper (like resolve()), or the scaffolded template should use a pattern that satisfies the rule. This is the default code generated by sv create with the Paraglide addon — it errors out of the box with no user modifications.
What actually happened?
/src/routes/+layout.svelte
15:6 error Unexpected href link without resolve() svelte/no-navigation-without-resolve
Wrapping with resolve() from $app/paths causes a TypeScript error because localizeHref() returns string, not the expected "/" | `/${string}/` type
Link to GitHub Repo with Minimal Reproducible Example
bun x [email protected] create --template minimal --types ts --add prettier eslint vitest="usages:unit,component" playwright tailwindcss="plugins:typography,forms" sveltekit-adapter="adapter:auto" devtools-json paraglide="languageTags:en, es+demo:no" mcp="ide:other+setup:remote" --install bun .
Additional comments
No response
Hi, thanks for the issue. I'll need to look into this more, but first thoughts:
localizeHrefdoes not substitute kit'sresolve- e.g. it doesn't prepend the base path. Therefore the rule seems to be correct in reporting this and you should useresolve(localizeHref("..."))localizeHrefreturns a string, not a literal type, butresolveexpects a literal type - I'm not sure how to handle this, I'm only a casual user of paraglide. Could paraglide type the return value as a literal? If so, that would be the cleanest solution.
the addon generates the following code, we just need to modify it to return ResolvedPathName and the rest should fix itself. We shouldn't need to make any changes to the +layout.svelte.
/**
* High-level URL localization function optimized for client-side UI usage.
*
* This is a convenience wrapper around `localizeUrl()` that provides features
* needed in UI:
*
* - Accepts relative paths (e.g., "/about")
* - Returns relative paths when possible
* - Automatically detects current locale if not specified
* - Handles string input/output instead of URL objects
*
* @see https://inlang.com/m/gerre34r/library-inlang-paraglideJs/i18n-routing
*
* @example
* ```typescript
* // In a React/Vue/Svelte component
* const NavLink = ({ href }) => {
* // Automatically uses current locale, keeps path relative
* return <a href={localizeHref(href)}>...</a>;
* };
*
* // Examples:
* localizeHref("/about")
* // => "/de/about" (if current locale is "de")
* localizeHref("/store", { locale: "fr" })
* // => "/fr/store" (explicit locale)
*
* // Cross-origin links remain absolute
* localizeHref("https://other-site.com/about")
* // => "https://other-site.com/de/about"
* ```
*
* For server-side URL localization (e.g., in middleware), use `localizeUrl()`
* which provides more precise control over URL handling.
*
* @param {string} href - The href to localize (can be relative or absolute)
* @param {object} [options] - Options for localization
* @param {Locale} [options.locale] - Target locale. If not provided, uses `getLocale()`
* @returns {string} The localized href, relative if input was relative
*/
export function localizeHref(href, options) {
const currentLocale = getLocale();
const locale = options?.locale ?? currentLocale;
const url = new URL(href, getUrlOrigin());
const localized = localizeUrl(url, { locale });
// if the origin is identical and the href is relative,
// return the relative path
if (href.startsWith('/') && url.origin === localized.origin) {
// check for cross origin localization in which case an absolute URL must be returned.
if (locale !== currentLocale) {
const localizedCurrentLocale = localizeUrl(url, {
locale: currentLocale
});
if (localizedCurrentLocale.origin !== localized.origin) {
return localized.href;
}
}
return localized.pathname + localized.search + localized.hash;
}
return localized.href;
}maybe something like this
* @param {string} href - The href to localize (can be relative or absolute)
* @param {import("$app/types").RouteIdWithSearchOrHash | import("$app/types").PathnameWithSearchOrHash} href - The href to localize (can be relative or absolute)
* @param {object} [options] - Options for localization
* @param {Locale} [options.locale] - Target locale. If not provided, uses `getLocale()`
* @returns {string} The localized href, relative if input was relative
* @returns {import("$app/types").ResolvedPathname} The localized href, relative if input was relative */
export function localizeHref(href, options) {
const currentLocale = getLocale();
const locale = options?.locale ?? currentLocale;
const url = new URL(href, getUrlOrigin());
const localized = localizeUrl(url, { locale });
// if the origin is identical and the href is relative,
// return the relative path
if (href.startsWith('/') && url.origin === localized.origin) {
// check for cross origin localization in which case an absolute URL must be returned.
if (locale !== currentLocale) {
const localizedCurrentLocale = localizeUrl(url, {
locale: currentLocale
});
if (localizedCurrentLocale.origin !== localized.origin) {
return localized.href;
return resolve(localized.href);
}
}
return localized.pathname + localized.search + localized.hash;
return resolve(localized.pathname + localized.search + localized.hash);
}
return localized.href;
return resolve(localized.href);
}Thanks, but I don't think localization should do resolving automatically - what if you want to localize an external href?
I think it's semi-reasonable that if you localize a valid route, the result is also a valid route (which is not actually true, you could make a typo in your localization and the route would then be invalid 🤷).
However, be aware that paraglide is not just a Svelte thing, but an independent i18n project. It might be possible to do something to integrate them, but you'd need to propose this to the SvelteKit & Paraglide teams (I'm not affiliated with either, FYI)
@marekdedic Is this expected behaviour? I'm not getting linting error anymore
Hmm, that's weird. Can you look at the return type of localizeHref?
It returns strong.
Nvm, I cannot replicated it.
Regarding this issue, I think it can be closed. The fix we went with in the Svelte CLI is to just cast the output of localizeHref.
Thanks, but I think that's probably the wrong choice - you are hiding the genuine issue raised by this rule. If you know it's internal navigation, you should resolve() instead. If you know it's external navigation, you should rel="external". If you don't know, then you should leave it to the user to decide which of these 2 is correct.
The alternative is the just reimplement the paraglide fn to return the correct type.
But that's the same problem - unless you know whether the navigation is internal or external, you don't know the correct return type any more specific than string...
@marekdedic with consideration about what you said, what about this implementation?
/**
* A function to make both `paraglide` and `sveltekit` happy
*/
export const localize = <
H extends (URL & { pathname: ResolvedPathname }) | PathnameWithSearchOrHash | `http${string}`
>(
href: H,
options?: { locale: Locale }
): H extends (URL & { pathname: ResolvedPathname }) | Pathname ? ResolvedPathname : string => {
if (href instanceof URL || href.startsWith('/')) {
const url = href instanceof URL ? href : new URL(href, 'http://example.com');
const relative = url.pathname + url.search + url.hash;
const localized = localizeHref(relative, options) as PathnameWithSearchOrHash;
const resolved = resolve(localized);
return resolved;
}
// @ts-expect-error `PathnameWithSearchOrHash` is type `string` and can't be typed narrowed
return localizeHref(href, options);
};
It uses the svelte native url class type, otherwise, it checks the string for relative and absolute and return accordingly.
Thanks, I think the general idea is heading the correct way, but the logic is not exact. I think the if condition is incorrect. Look at the rule logic - it's actually pretty complicated and depends on where the value is - some places don't allow absolute URLs for example.
This issue is is stale because it missing information and has been open for 60 days with no activity.
Ugh, not stale