Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Svelte: Fix conflicting variable names and support for +page.svelte files #30369

Merged
merged 4 commits into from
Feb 11, 2025
Merged
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
60 changes: 31 additions & 29 deletions code/frameworks/svelte-vite/src/plugins/svelte-docgen.ts
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@ import { basename, relative } from 'node:path';

import { logger } from 'storybook/internal/node-logger';

import type AST from 'estree';
import MagicString from 'magic-string';
import { replace, typescript } from 'svelte-preprocess';
import { preprocess } from 'svelte/compiler';
@@ -33,40 +34,40 @@ svelteDocParserOptions.getAstDefaultOptions = () => ({
ecmaFeatures: {},
});

// Most of the code here should probably be exported by @storybook/svelte and reused here.
// See: https://github.com/storybookjs/storybook/blob/next/app/svelte/src/server/svelte-docgen-loader.ts

// From https://github.com/sveltejs/svelte/blob/8db3e8d0297e052556f0b6dde310ef6e197b8d18/src/compiler/compile/utils/get_name_from_filename.ts
// Copied because it is not exported from the compiler
function getNameFromFilename(filename: string) {
if (!filename) {
return null;
/**
* It access the AST output of _compiled_ Svelte component file. To read the name of the default
* export - which is source of truth.
*
* In Svelte prior to `v4` component is a class. From `v5` is a function.
*/
function getComponentName(ast: ReturnType<import('rollup').PluginContext['parse']>): string {
// NOTE: Assertion, because rollup returns a type `AcornNode` for some reason, which doesn't overlap with `Program` from estree
const exportDefaultDeclaration = (ast as unknown as AST.Program).body.find(
(n) => n.type === 'ExportDefaultDeclaration'
) as AST.ExportDefaultDeclaration | undefined;

if (!exportDefaultDeclaration) {
throw new Error('Unreachable - no default export found');
}

const parts = filename.split(/[/\\]/).map(encodeURI);
// NOTE: Output differs based on svelte version and dev/prod mode

if (parts.length > 1) {
const indexMatch = parts[parts.length - 1].match(/^index(\.\w+)/);
if (indexMatch) {
parts.pop();
parts[parts.length - 1] += indexMatch[1];
}
if (exportDefaultDeclaration.declaration.type === 'Identifier') {
return exportDefaultDeclaration.declaration.name;
}

if (
exportDefaultDeclaration.declaration.type !== 'ClassDeclaration' &&
exportDefaultDeclaration.declaration.type !== 'FunctionDeclaration'
) {
throw new Error('Unreachable - not a class or a function');
}

const base = parts
.pop()
?.replace(/%/g, 'u')
.replace(/\.[^.]+$/, '')
.replace(/[^a-zA-Z_$0-9]+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
.replace(/^(\d)/, '_$1');

if (!base) {
throw new Error(`Could not derive component name from file ${filename}`);
if (!exportDefaultDeclaration.declaration.id) {
throw new Error('Unreachable - unnamed class/function');
}

return base[0].toUpperCase() + base.slice(1);
return exportDefaultDeclaration.declaration.id.name;
}

function transformToSvelteDocParserType(type: Type): JSDocType {
@@ -225,8 +226,9 @@ export async function svelteDocgen(svelteOptions: Record<string, any> = {}): Pro
componentDoc.name = basename(file);

const s = new MagicString(src);
const componentName = getNameFromFilename(resource);
s.append(`;${componentName}.__docgen = ${JSON.stringify(componentDoc)}`);
const outputAst = this.parse(src);
const componentName = getComponentName(outputAst);
s.append(`\n;${componentName}.__docgen = ${JSON.stringify(componentDoc)}`);

return {
code: s.toString(),