False positive with svelte/no-navigation-without-resolve using variable in a list
#1314
Development PRs
Bumps prettier from 3.8.4 to 3.9.8.
Release notes
Sourced from prettier's releases.
3.9.8
3.9.7
- Support Angular 22.2
- Fix regressions in v3.9
3.9.6
What's Changed
- Preserve quotes for methods named
new(prettier/prettier#19621 by@kovsu)- Support
import deferintypescriptparser (prettier/prettier#19624, prettier/prettier#19675 by@fisker)- Added a new official plugin
@prettier/plugin-yuku🚀 (prettier/prettier#19628, prettier/prettier#19629 by@fisker)3.9.5
3.9.4
- Angular: Format
@content(name)->@content (name)to align with other block syntax (#19499 by@fisker)3.9.3
- Markdown: Fix unexpected removal of characters in liquid syntax (prettier/prettier#19489 by
@seiyab)- TypeScript: Allow decorators to be used with declare on class fields (prettier/prettier#19492 by
@evoactivity)3.9.1
3.9.0
🔗 Prettier 3.9: Major parser upgrades and Formatting improvements
3.8.5
- Fix Flow variance annotation print (#19022 by
@marcoww6)
... (truncated)
Changelog
Sourced from prettier's changelog.
3.9.8
Markdown: Don't let Liquid objects interrupt paragraphs (#20087 by
@seiyab)<!-- Input --> If `module` is not a [`WebAssembly.Module`](https://github.com/prettier/prettier/blob/main/en-US/docs/WebAssembly/Reference/JavaScript_interface/Module) object instance, a {{jsxref("TypeError")}} is thrown. <!-- Prettier 3.9.7 --> If module is not a WebAssembly.Module object instance, a {{jsxref("TypeError")}} is thrown.3.9.7
Markdown: Prevent indentation drift in list-item code blocks (#19647, #19990 by
@Austin1serb,@giaBaoJS)<!-- Input --> [x] short first line. second paragraph at six spaces that wraps onto another line here. <!-- Prettier 3.9.6 --> short first line. second paragraph at six spaces that wraps onto another line here. <!-- Prettier 3.9.7 --> short first line. second paragraph at six spaces that wraps onto another line here.JavaScript: Fix embedded template literal idempotency (#19725 by
@fisker)
... (truncated)
Commits
4f2ab67Release 3.9.83d82af8Update Regex related dependencies (#20082)5ec8db1[3.9.x] Markdown: Don't let Liquid objects interrupt paragraphs (#20087)5b142edRelease Release@prettier/plugin-hermes@0.2.3,@prettier/plugin-oxc@0.2.3, an...0df8eb8Bump Prettier dependency to 3.9.73cf6c8cClean changelog_unreleased0449af3Release 3.9.743cd5b0Allow verify markdown test withmdxparserab8c911Fix test on Node.js v26 (#19927)4a5adf9Fix tests- Additional commits viewable in compare view
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?
9.34.0
What version of eslint-plugin-svelte are you using?
3.12.0
What did you do?
Resolved links in a list are not detected as resolved.
Minimal reproduction:
<script lang="ts">
import { resolve } from '$app/paths';
const works = resolve(`/`);
const notWorkingList = [
{ title: 'Home', url: resolve(`/`) },
{ title: 'Clients', url: resolve(`/clients`) },
];
</script>
<!-- ✅ works as expected -->
<a href={works}>Go to Home</a>
{#each notWorkingList as item (item.title)}
<!-- ❌ Found a link with a url that isn't resolved. -->
<a href={item.url}>{item.title}</a>
{/each}
This also doesn't work:
<script lang="ts">
import { resolve } from '$app/paths';
const notWorkingList = [
{ title: 'Home', url: `/` },
{ title: 'Clients', url: `/clients` },
];
</script>
{#each notWorkingList as item (item.title)}
<!-- ❌ Argument of type '[string]' is not assignable to parameter of type '[route: "/"] | [route: "/clients"] | ... -->
<a href={resolve(item.url)}>{item.title}</a>
{/each}
What did you expect to happen?
Already resolved pathnames are detected whether they are in a list or not.
What actually happened?
Error: Found a link with a url that isn't resolved.eslint
Link to GitHub Repo with Minimal Reproducible Example
Will provide later if needed.
Additional comments
Related question: How to handle dynamic values like the when shallow routing?
It also doesn’t work in combination with Paraglide JS, the localization tool recommended by the Svelte CLI. They use something like this:
<a href={localizeHref("/blog")}>Blog</a>Thanks for the report, but I'm not really sure what to do with this... Let's take the last example (and I think the rest is the same):
<a href={localizeHref("/blog")}>Blog</a>
I mean... The link isn't resolved and it doesn't seem to be an absolute URL, so I'd say the rule works as intended...
At the same time, I understand that this can seem impractical, but I'd probably just follow the same rules as when escaping values - do it at the last possible moment, ideally inside the link itself (but the rule should also work if you use a variable that is defined in the same file).
So if you are localising for internal navigation, then you should resolve. I don't really see a use-case for localising for external navigation (though I'm sure there is somebody somewhere doing that :D).
@marekdedic Thank you very much for the reply. I find the example of @cnolte not very helpful for the discussion.
Trying to follow your suggestion to "do it at the last possible moment". This does indeed work using as const
<script lang="ts">
import { resolve } from '$app/paths';
const notWorkingList = [
{ title: 'Home', url: `/` as const },
{ title: 'Clients', url: `/clients` as const },
];
</script>
{#each notWorkingList as item (item.title)}
<!-- ✅ -->
<a href={resolve(item.url)}>{item.title}</a>
{/each}
But it's confusing. Can you explain why notWorkingList.url which is a ResolvedPathname, does not work? But if it's a variable it does?
I have a nav component with a nested list, which requires to define the type beforehand. Neither as const nor as ResolvedPathname works in this case. Is there a trick to make this work?
<script lang="ts">
type MenuItem = {
title: string;
url: string;
icon?: typeof IconType;
subItems: Array<Omit<MenuItem, 'subItems'>>;
};
const items: MenuItem[] = [
{
title: m['sidebar.home'](),
url: '/',
icon: House,
subItems: [],
},
{
title: m['sidebar.clients'](),
url: '/clients',
icon: HandHeart,
subItems: [],
},
{
title: m['sidebar.documents'](),
url: '/documents',
icon: File,
subItems: [
{
title: m['document.types.unassigned'](),
url: '/documents?docsView=unassigned',
},
{
title: m['document.types.inbox'](),
url: '/documents?docsView=inbox',
},
],
},
// ...
];
</script>Ha, sorry, didn't realize there were comments by 2 people. I will look into the issue with locally defined lists, that should be similar to variables...
Maybe I should have opened a new ticket, but how do I avoid the svelte/no-navigation-without-resolve in my example?
<a href={localizeHref(resolve('/'))}>Home</a> <!-- This throws the error -->@cnolte This should solve your issue:
<a href={resolve(localizeHref('/'))}>Home</a>@marekdedic no it doesn‘t because this throws a Type error. LocalizeHref returns a string and resolve expects a valid path.
Well, that seems to me like a correct type error... localizeHref can actually return anything, not just valid paths. If you are sure that all the return values are valid, you should use a type assertion. While that may not look as clean, I think it actually better expresses that the return value of localizeHref may not be a valid path and you are asserting that in your particular case it is.
I am getting this error even when the variable is defined within the same file as the a tag:
<script lang="ts">
import HevyIcon from '$lib/icons/hevy-icon.svelte';
import StravaIcon from '$lib/icons/strava-icon.svelte';
import type { LcpResponse } from '$lib/lcp/lcp.server';
import { type Workout as LcpWorkout } from '$lib/lcp/workouts';
import Loading from '$lib/loading.svelte';
import ViewButton from '$lib/view-button.svelte';
import { Error } from '@gleich/ui';
import Section from '../../section.svelte';
import Workout from './workout.svelte';
import { resolve } from '$app/paths';
const { workouts, loading }: { workouts?: LcpResponse<LcpWorkout[]> | null; loading?: boolean } =
$props();
const stravaURL = 'https://www.strava.com/about';
const hevyURL = 'https://www.hevyapp.com';
</script>
<Section
name="Workouts"
liveData={{
sources: [
{
name: 'Strava',
icon: StravaIcon,
url: stravaURL,
iconLeftMargin: '8px',
iconRightMargin: '5px'
},
{
name: 'Hevy',
icon: HevyIcon,
url: hevyURL,
iconLeftMargin: '10px',
iconRightMargin: '8px'
}
],
updated: workouts?.updated
}}
>
{#if loading}
<Loading height={529.91} />
{:else if workouts != null}
<p>
One of my favorite things is staying active and enjoying the outdoors. I grew up in New
Hampshire hiking, biking, snowshoeing, and traveling with my family. Out of all of those
things I especially love cycling mainly through gravel cycling, road cycling, and mountain
biking. Recently I've been getting into lifting which has been a ton of fun. Below are 2 of my
most recent <a href={stravaURL} rel="external" target="_blank">Strava</a>/<a
href={hevyURL}
rel="external">Hevy</a
>
workouts:
</p>
<div class="workouts">
{#each workouts.data.slice(0, 2) as workout (workout.id)}
<div class="workout">
<Workout {workout} />
</div>
{/each}
</div>
<a class="view-more" href={resolve('/workouts')}>
<ViewButton more of="workouts" />
</a>
{:else}
<Error msg="Failed to load workout data" />
{/if}
</Section>I just bump into these issues after updating dependencies, with the new rules throwing errors all over the project. It's beyond annoying, and I can't even express how frustrated I am.
And all of this started with typed params, which were breaking changes, and now you're forcing them through linting?
I'm also using dynamic links for header menus or other sidebar menus, where you generate a dynamic list from a loop or custom data. In these cases, you can't guarantee types, or you simply want to use a basic string type, and now it throws errors all over the place.
When looking at this, it becomes ultra confusing and overly complicated, and I see no point in having a plain <a> tag when we have to deal with some resolve function or other magic.
Prev:
<a href="/"></a>
New:
<script lang="ts">
import { resolve } from '$app/paths'
</script>
<a href={resolve('/')}></a>
At this point, it would probably be best to have a built-in SvelteKit Link component that solves all this logic under the hood. All other meta frameworks have similar solutions.
Having a simple <a> tag and needing to deal with some resolve stuff has absolutely ZERO advantage over a custom Link component. So a custom component from SvelteKit would solve all this linting and resolving under the hood.
Why are these changes being forced before the docs and official tutorials are even updated?
Where is this new syntax mentioned in the documentation?
Hi, unfortunately, I don't understand the issue with params as I am not a maintainer and/or contributor to SvelteKit.
In the provided example, in the first version, your link will break if you use a base path. It won't with the second.
AFAIK SvelteKit is considering doing something like a resolve automatically for goto (not sure about a plain <a>), but that would be a breaking change, so here we are in the meantime.
Just to clarify, there's at least 2 ways to type the list.
const notWorkingList = [
{ title: 'Home', url: `/` },
{ title: 'Clients', url: `/brain` }
] as const;
or
const notWorkingList: { title: string; url: Pathname }[] = [
{ title: 'Home', url: `/` },
{ title: 'Clients', url: `/brain` }
];
resolve() must be used where the value is consumed.
I believe this can be marked as solved.
Hi, I believe there is still something to be done for this issue (overlapping with other issues). And that is making the rule not report if the TypeScript type is correct (already resolved). But I'm blocked by #1320 for that :( I've tried throwing Claude Code at it with some success but have yet to push that. Life got in the way...
@sacrosanctic This is a reduced version of the app-sidebar.svelte we have in prod. It uses a recursive list and a snippet to render menu items. I can't see how to make this work with as const (what would be the type of the snippet, not all entries are the same). I tried the Pathname type as you can see below, but it doesn't work. Can you advice how you would type this correctly?
<script lang="ts">
import * as Sidebar from '$lib/components/ui/sidebar/index.js';
import { HandHeart, type Icon as IconType } from '@lucide/svelte';
import House from '@lucide/svelte/icons/house';
import { resolve } from '$app/paths';
import type { Pathname } from '$app/types';
type MenuItem = {
title: string;
url: Pathname;
icon?: typeof IconType;
subItems: Array<Omit<MenuItem, 'subItems'>>;
};
const items: MenuItem[] = [
{
title: 'Home',
url: '/',
icon: House,
subItems: [],
},
{
title: 'Clients',
url: '/clients',
icon: HandHeart,
subItems: [
{
title: 'Active Clients',
url: '/clients/active',
icon: HandHeart,
},
],
},
];
function isActive(_url: string) {
return false;
}
function handleItemClick(item: MenuItem, event: MouseEvent) {
if (item.subItems.length > 0) {
event.preventDefault();
}
}
</script>
{#snippet menuItem(item: MenuItem)}
<Sidebar.MenuItem>
<Sidebar.MenuButton isActive={isActive(item.url)}>
{#snippet child({ props })}
<!-- ❌ Argument of type '["/" | ...] is not assignable to type '`/workflows/${string}` & {}'.-->
<a href={resolve(item.url)} {...props} onclick={(e) => handleItemClick(item, e)}>
<item.icon />
<span>
{item.title}
</span>
</a>
{/snippet}
</Sidebar.MenuButton>
</Sidebar.MenuItem>
{/snippet}
<Sidebar.Root collapsible="icon">
<Sidebar.Content class="justify-between">
<Sidebar.Group>
<Sidebar.GroupContent>
<Sidebar.Menu>
{#each items as item (item.title)}
{@render menuItem(item)}
{/each}
</Sidebar.Menu>
</Sidebar.GroupContent>
</Sidebar.Group>
</Sidebar.Content>
</Sidebar.Root>resolve() must be used where the value is consumed.
👇🏻
At this point, it would probably be best to have a built-in SvelteKit
Linkcomponent that solves all this logic under the hood. All other meta frameworks have similar solutions.
I still believe that having a simple <a> tag and needing to deal with some resolve stuff has absolutely ZERO advantage over a custom Link component.
I understand logic behind resolve but why not have an official comp for that? No need to import other things and each time i need to write link i need to deal with something.
Some of meta frameworks that have built-in Link comp:
NextNuxtGatsbySolidMetaQwik CityRemix- ...
@ivodolenc I'm afraid you'll have to take this up with the SvelteKit maintainers. Neither me (author of this lint rule), nor @ota-meshi (author of this eslint plugin) are ones AFAIK - the plugin is under the org, but is developed by volunteers outside of the Svelte/SvelteKit team.
But given this complexity in using links correctly in kit, I'd tend to agree with you.
@ivodolenc please open a separate issue
@patte cant use as const for recursive data types. I pasted this into the demo app and it works. I made some tweaks to fit the demo. Make sure you're on the latest versions of packages. Otherwise, create a repl.
<script lang="ts">
import { resolve } from '$app/paths';
import type { Pathname } from '$app/types';
type MenuItem = {
title: string;
url: Pathname;
subItems: Array<Omit<MenuItem, 'subItems'>>;
};
const items: MenuItem[] = [
{
title: 'Home',
url: '/',
subItems: []
},
{
title: 'Clients',
url: '/about',
subItems: [
{
title: 'Active Clients',
url: '/demo',
}
]
}
];
function handleItemClick(item: MenuItem, event: MouseEvent) {
if (item.subItems.length > 0) {
event.preventDefault();
}
}
</script>
{#snippet menuItem(item: MenuItem)}
<a href={resolve(item.url)} onclick={(e) => handleItemClick(item, e)}>
<span>
{item.title}
</span>
</a>
{/snippet}As there are multiple reports (in multiple issues) related to arrays and objects, I opened a new issue to track them all: #1485. I believe this can be closed as a duplicate (I don't know if duplicate is the right word since this issue was first?) @ota-meshi please?
@gleich Your issue should be fixed with #1443. If you are still seeing errors, could you please open a new issue with a minimal reproduction?
#1485 looks good because it manages multiple similar issues that could potentially be resolved together as a single issue. However, I respect the issue reported earlier and I don't want to mark this issue as a duplicate of the new issue and close it.
I think this issue can be marked as resolved when the new PR resolves #1485.