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

feat: add Svelte 4 migration #9729

Merged
merged 7 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: add Svelte 4 migration
  • Loading branch information
dummdidumm committed Apr 20, 2023
commit 1c5f9b98ad0bd6ab273b249e793eb1a773ebec40
5 changes: 5 additions & 0 deletions .changeset/lucky-coins-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-migrate': minor
---

feat: add Svelte 4 migration
73 changes: 73 additions & 0 deletions packages/migrate/migrations/svelte-4/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import colors from 'kleur';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import prompts from 'prompts';
import glob from 'tiny-glob/sync.js';
import { bail, check_git } from '../../utils.js';
import { update_js_file, update_svelte_file } from './migrate.js';

export async function migrate() {
if (!fs.existsSync('package.json')) {
bail('Please re-run this script in a directory with a package.json');
}

console.log(colors.bold().yellow('\nThis will update files in the current directory\n'));

const use_git = check_git();

const response = await prompts({
type: 'confirm',
name: 'value',
message: 'Continue?',
initial: false
});

if (!response.value) {
process.exit(1);
}

const { default: config } = fs.existsSync('svelte.config.js')
? await import(pathToFileURL(path.resolve('svelte.config.js')).href)
: { default: {} };

/** @type {string[]} */
const svelte_extensions = config.extensions ?? ['.svelte'];
const extensions = [...svelte_extensions, '.ts', '.js'];
// TODO read tsconfig/jsconfig if available? src/** will be good for 99% of cases
const files = glob(`src/**`, { filesOnly: true, dot: true }).map((file) =>
file.replace(/\\/g, '/')
);

for (const file of files) {
if (extensions.some((ext) => file.endsWith(ext))) {
if (svelte_extensions.some((ext) => file.endsWith(ext))) {
update_svelte_file(file);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would break with mdsvex .svx , safer to only do .svelte by default and maybe ask the user for other extensions that contain svelte code that is compatible with the basic regex used in update_svelte_file

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I commented that out because I think it's going to do more harm than good since .svx is probably the most common usage of it

} else {
update_js_file(file);
}
}
}

console.log(colors.bold().green('✔ Your project has been migrated'));

console.log('\nRecommended next steps:\n');

const cyan = colors.bold().cyan;

const tasks = [
use_git && cyan('git commit -m "migration to Svelte 4"'),
`Review the migration guide at TODO`,
`Read the updated docs at https://svelte.dev/docs`
].filter(Boolean);

tasks.forEach((task, i) => {
console.log(` ${i + 1}: ${task}`);
});

console.log('');

if (use_git) {
console.log(`Run ${cyan('git diff')} to review changes.\n`);
}
}
179 changes: 179 additions & 0 deletions packages/migrate/migrations/svelte-4/migrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import fs from 'node:fs';
import { Project, SourceFile, ts, Node } from 'ts-morph';

/** @param {string} file_path */
export function update_svelte_file(file_path) {
const content = fs.readFileSync(file_path, 'utf-8');
const updated = content.replace(
/<script([^]*?)>([^]+?)<\/script>(\n*)/g,
(_match, attrs, contents, whitespace) => {
return `<script${attrs}>${transform_code(contents)}</script>${whitespace}`;
}
);
fs.writeFileSync(file_path, updated, 'utf-8');
}

/** @param {string} file_path */
export function update_js_file(file_path) {
const content = fs.readFileSync(file_path, 'utf-8');
const updated = transform_code(content);
fs.writeFileSync(file_path, updated, 'utf-8');
}

/** @param {string} code */
export function transform_code(code) {
const project = new Project({ useInMemoryFileSystem: true });
const source = project.createSourceFile('svelte.ts', code);
update_imports(source);
update_typeof_svelte_component(source);
update_action_types(source);
update_action_return_types(source);
return source.getFullText();
}

// <svelte:options tag=".." /> -> <svelte:options customElement=".." />

/**
* Action<T> -> Action<T, any>
* @param {SourceFile} source
*/
function update_action_types(source) {
const imports = get_imports(source, 'svelte/action', 'Action');
for (const namedImport of imports) {
const identifiers = find_identifiers(source, namedImport.getAliasNode()?.getText() ?? 'Action');
for (const id of identifiers) {
const parent = id.getParent();
if (Node.isTypeReference(parent)) {
const type_args = parent.getTypeArguments();
if (type_args.length === 1) {
parent.addTypeArgument('any');
} else if (type_args.length === 0) {
parent.addTypeArgument('HTMLElement');
parent.addTypeArgument('any');
}
}
}
}
}

/**
* ActionReturn -> ActionReturn<any>
* @param {SourceFile} source
*/
function update_action_return_types(source) {
const imports = get_imports(source, 'svelte/action', 'ActionReturn');
for (const namedImport of imports) {
const identifiers = find_identifiers(
source,
namedImport.getAliasNode()?.getText() ?? 'ActionReturn'
);
for (const id of identifiers) {
const parent = id.getParent();
if (Node.isTypeReference(parent)) {
const type_args = parent.getTypeArguments();
if (type_args.length === 0) {
parent.addTypeArgument('any');
}
}
}
}
}

/**
* SvelteComponentTyped -> SvelteComponent
* @param {SourceFile} source
*/
function update_imports(source) {
const identifiers = find_identifiers(source, 'SvelteComponent');
const can_rename = identifiers.every((id) => {
const parent = id.getParent();
return (
(Node.isImportSpecifier(parent) &&
!parent.getAliasNode() &&
parent.getParent().getParent().getParent().getModuleSpecifier().getText() === 'svelte') ||
!is_declaration(parent)
);
});

const imports = get_imports(source, 'svelte', 'SvelteComponentTyped');
for (const namedImport of imports) {
if (can_rename) {
namedImport.renameAlias('SvelteComponent');
if (
namedImport
.getParent()
.getElements()
.some((e) => !e.getAliasNode() && e.getNameNode().getText() === 'SvelteComponent')
) {
namedImport.remove();
} else {
namedImport.setName('SvelteComponent');
namedImport.removeAlias();
}
} else {
namedImport.renameAlias('SvelteComponentTyped');
namedImport.setName('SvelteComponent');
}
}
}

/**
* typeof SvelteComponent -> typeof SvelteComponent<any>
* @param {SourceFile} source
*/
function update_typeof_svelte_component(source) {
const imports = get_imports(source, 'svelte', 'SvelteComponent');

for (const type of imports) {
if (type) {
const name = type.getAliasNode() ?? type.getNameNode();
name.findReferencesAsNodes().forEach((ref) => {
const parent = ref.getParent();
if (parent && Node.isTypeQuery(parent)) {
const id = parent.getFirstChildByKind(ts.SyntaxKind.Identifier);
if (id?.getText() === name.getText()) {
const typeArguments = parent.getTypeArguments();
if (typeArguments.length === 0) {
parent.addTypeArgument('any');
}
}
}
});
}
}
}

/**
* @param {SourceFile} source
* @param {string} from
* @param {string} name
*/
function get_imports(source, from, name) {
return source
.getImportDeclarations()
.filter((i) => i.getModuleSpecifierValue() === from)
.flatMap((i) => i.getNamedImports())
.filter((i) => i.getName() === name);
}

/**
* @param {SourceFile} source
* @param {string} name
*/
function find_identifiers(source, name) {
return source.getDescendantsOfKind(ts.SyntaxKind.Identifier).filter((i) => i.getText() === name);
}

/**
* Does not include imports
* @param {Node} node
*/
function is_declaration(node) {
return (
Node.isVariableDeclaration(node) ||
Node.isFunctionDeclaration(node) ||
Node.isClassDeclaration(node) ||
Node.isTypeAliasDeclaration(node) ||
Node.isInterfaceDeclaration(node)
);
}
120 changes: 120 additions & 0 deletions packages/migrate/migrations/svelte-4/migrate.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { test } from 'uvu';
import * as assert from 'uvu/assert';
import { transform_code } from './migrate.js';

test('Updates SvelteComponentTyped #1', () => {
const result = transform_code(
`import { SvelteComponentTyped } from 'svelte';

export class Foo extends SvelteComponentTyped<{}> {}

const bar: SvelteComponentTyped = null;`
);
assert.equal(
result,
`import { SvelteComponent } from 'svelte';

export class Foo extends SvelteComponent<{}> {}

const bar: SvelteComponent = null;`
);
});

test('Updates SvelteComponentTyped #2', () => {
const result = transform_code(
`import { SvelteComponentTyped, SvelteComponent } from 'svelte';

export class Foo extends SvelteComponentTyped<{}> {}

const bar: SvelteComponentTyped = null;
const baz: SvelteComponent = null;`
);
assert.equal(
result,
`import { SvelteComponent } from 'svelte';

export class Foo extends SvelteComponent<{}> {}

const bar: SvelteComponent = null;
const baz: SvelteComponent = null;`
);
});

test('Updates SvelteComponentTyped #3', () => {
const result = transform_code(
`import { SvelteComponentTyped } from 'svelte';

interface SvelteComponent {}

export class Foo extends SvelteComponentTyped<{}> {}

const bar: SvelteComponentTyped = null;
const baz: SvelteComponent = null;`
);
assert.equal(
result,
`import { SvelteComponent as SvelteComponentTyped } from 'svelte';

interface SvelteComponent {}

export class Foo extends SvelteComponentTyped<{}> {}

const bar: SvelteComponentTyped = null;
const baz: SvelteComponent = null;`
);
});

test('Updates typeof SvelteComponent', () => {
const result = transform_code(
`import { SvelteComponent } from 'svelte';
import { SvelteComponent as C } from 'svelte';

const a: typeof SvelteComponent = null;
function b(c: typeof SvelteComponent) {}
const c: typeof SvelteComponent<any> = null;
const d: typeof C = null;
`
);
assert.equal(
result,
`import { SvelteComponent } from 'svelte';
import { SvelteComponent as C } from 'svelte';

const a: typeof SvelteComponent<any> = null;
function b(c: typeof SvelteComponent<any>) {}
const c: typeof SvelteComponent<any> = null;
const d: typeof C<any> = null;
`
);
});

test('Updates Action and ActionReturn', () => {
const result = transform_code(
`import { Action, ActionReturn } from 'svelte/action';

const a: Action = () => {};
const b: Action<HTMLDivElement> = () => {};
const c: Action<HTMLDivElement, true> = () => {};
const d: Action<HTMLDivElement, true, {}> = () => {};
const e: ActionReturn = () => {};
const f: ActionReturn<true> = () => {};
const g: ActionReturn<true, {}> = () => {};
`
);
assert.equal(
result,

`import { Action, ActionReturn } from 'svelte/action';

const a: Action<HTMLElement, any> = () => {};
const b: Action<HTMLDivElement, any> = () => {};
const c: Action<HTMLDivElement, true> = () => {};
const d: Action<HTMLDivElement, true, {}> = () => {};
const e: ActionReturn<any> = () => {};
const f: ActionReturn<true> = () => {};
const g: ActionReturn<true, {}> = () => {};
`
);
});

test.run();
3 changes: 2 additions & 1 deletion packages/migrate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"magic-string": "^0.30.0",
"prompts": "^2.4.2",
"tiny-glob": "^0.2.9",
"typescript": "^4.9.4"
"ts-morph": "^18.0.0",
"typescript": "^5.0.4"
},
"devDependencies": {
"@types/prompts": "^2.4.1",
Expand Down
Loading