Skip to content

Commit

Permalink
feat: add page-state migration
Browse files Browse the repository at this point in the history
A simple, string-based migration for sveltejs/kit#13140 (tested on that repo, zero false-positives, less than five false negatives)
  • Loading branch information
dummdidumm committed Dec 12, 2024
1 parent 80990d3 commit 5272dec
Show file tree
Hide file tree
Showing 5 changed files with 290 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/polite-eyes-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-migrate': minor
---

feat: add page-state migration
1 change: 1 addition & 0 deletions packages/migrate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ npx sv migrate [migration]
| `sveltekit-2` | SvelteKit 1.0 | SvelteKit 2.0 | [Website](https://svelte.dev/docs/kit/migrating-to-sveltekit-2) |
| `svelte-4` | Svelte 3 | Svelte 4 | [Website](https://svelte.dev/docs/svelte/v4-migration-guide) |
| `svelte-5` | Svelte 4 | Svelte 5 | |
| `page-state` | `$app/stores` | `$app/state` | |
| `package` | `@sveltejs/package@1` | `@sveltejs/package@2` | [#8922](https://github.com/sveltejs/kit/pull/8922) |
| `routes` | SvelteKit pre-1.0 | SvelteKit 1.0 | [#5774](https://github.com/sveltejs/kit/discussions/5774) |

Expand Down
119 changes: 119 additions & 0 deletions packages/migrate/migrations/page-state/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import colors from 'kleur';
import fs from 'node:fs';
import process from 'node:process';
import prompts from 'prompts';
import semver from 'semver';
import glob from 'tiny-glob/sync.js';
import { bail, check_git, update_svelte_file } from '../../utils.js';
import { transform_svelte_code, update_pkg_json } 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');
}

const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));

const svelte_dep = pkg.devDependencies?.svelte ?? pkg.dependencies?.svelte;
if (svelte_dep && semver.validRange(svelte_dep) && semver.gtr('5.0.0', svelte_dep)) {
console.log(
colors
.bold()
.red('\nYou need to upgrade to Svelte version 5 first (`npx sv migrate svelte-5`).\n')
);
process.exit(1);
}

const kit_dep = pkg.devDependencies?.['@sveltejs/kit'] ?? pkg.dependencies?.['@sveltejs/kit'];
if (kit_dep && semver.validRange(kit_dep) && semver.gtr('2.0.0', kit_dep)) {
console.log(
colors
.bold()
.red('\nYou need to upgrade to SvelteKit version 2 first (`npx sv migrate sveltekit-2`).\n')
);
process.exit(1);
}

console.log(
colors
.bold()
.yellow(
'\nThis will update files in the current directory\n' +
"If you're inside a monorepo, don't run this in the root directory, rather run it in all projects independently.\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 folders = await prompts({
type: 'multiselect',
name: 'value',
message: 'Which folders should be migrated?',
choices: fs
.readdirSync('.')
.filter(
(dir) => fs.statSync(dir).isDirectory() && dir !== 'node_modules' && !dir.startsWith('.')
)
.map((dir) => ({ title: dir, value: dir, selected: true }))
});

if (!folders.value?.length) {
process.exit(1);
}

update_pkg_json();

// For some reason {folders.value.join(',')} as part of the glob doesn't work and returns less files
const files = folders.value.flatMap(
/** @param {string} folder */ (folder) =>
glob(`${folder}/**`, { filesOnly: true, dot: true })
.map((file) => file.replace(/\\/g, '/'))
.filter(
(file) =>
!file.includes('/node_modules/') &&
// We're not transforming usage inside .ts/.js files since you can't use the $store syntax there,
// and therefore have to either subscribe or pass it along, which we can't auto-migrate
file.endsWith('.svelte')
)
);

for (const file of files) {
update_svelte_file(
file,
(code) => code,
(code) => transform_svelte_code(code, { filename: file })
);
}

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

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

const cyan = colors.bold().cyan;

const tasks = [
"install the updated dependencies ('npm i' / 'pnpm i' / etc) " + use_git &&
cyan('git commit -m "migration to $app/state"')
].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`);
}
}
74 changes: 74 additions & 0 deletions packages/migrate/migrations/page-state/migrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import fs from 'node:fs';
import { update_pkg } from '../../utils.js';

export function update_pkg_json() {
fs.writeFileSync(
'package.json',
update_pkg_json_content(fs.readFileSync('package.json', 'utf8'))
);
}

/**
* @param {string} content
*/
export function update_pkg_json_content(content) {
return update_pkg(content, [['@sveltejs/kit', '^2.12.0']]);
}

/**
* @param {string} code
* @param {{ filename?: string }} options
*/
export function transform_svelte_code(code, options) {

Check failure on line 22 in packages/migrate/migrations/page-state/migrate.js

View workflow job for this annotation

GitHub Actions / lint

'options' is defined but never used. Allowed unused args must match /^_/u
// Quick check if nothing to do
if (!code.includes('$app/stores')) return code;

// Check if file is using legacy APIs - if so, we can't migrate since reactive statements would break
const lines = code.split('\n');
if (lines.some((line) => /^\s*(export let|\$:) /.test(line))) {
return code;
}

const import_match = code.match(/import\s*{([^}]+)}\s*from\s*("|')\$app\/stores\2/);
if (!import_match) return code; // nothing to do

const stores = import_match[1].split(',').map((i) => i.trim());
let modified = code.replace('$app/stores', '$app/state');

for (const store of stores) {
// if someone uses that they're deep into stores and we better not touch this file
if (store === 'getStores') return code;

const regex = new RegExp(`\\b${store}\\b`, 'g');
let match;
let count_removed = 0;

while ((match = regex.exec(modified)) !== null) {
const before = modified.slice(0, match.index);
const after = modified.slice(match.index + store.length);

if (before.slice(-1) !== '$') {
if (/[_'"]/.test(before.slice(-1))) continue; // false positive

if (store === 'updated' && after.startsWith('.check()')) {
continue; // this stays as is
}

if (
match.index - count_removed > /** @type {number} */ (import_match.index) &&
match.index - count_removed <
/** @type {number} */ (import_match.index) + import_match[0].length
) {
continue; // this is the import statement
}

return code;
}

modified = before.slice(0, -1) + store + (store === 'page' ? '' : '.current') + after;
count_removed++;
}
}

return modified;
}
91 changes: 91 additions & 0 deletions packages/migrate/migrations/page-state/migrate.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { assert, test } from 'vitest';
import { transform_svelte_code } from './migrate.js';

test('Updates $app/store #1', () => {
const result = transform_svelte_code(
`<script>
import { page } from '$app/stores';
</script>
<div>{$page.url}</div>
<button onclick={() => {
console.log($page.state);
}}></button>
`,
{}
);
assert.equal(
result,
`<script>
import { page } from '$app/state';
</script>
<div>{page.url}</div>
<button onclick={() => {
console.log(page.state);
}}></button>
`
);
});

test('Updates $app/store #2', () => {
const result = transform_svelte_code(
`<script>
import { navigating, updated } from '$app/stores';
$updated;
updated.check();
</script>
is_navigating: {$navigating}
`,
{}
);
assert.equal(
result,
`<script>
import { navigating, updated } from '$app/state';
updated.current;
updated.check();
</script>
is_navigating: {navigating.current}
`
);
});

test('Does not update $app/store #1', () => {
const input = `<script>
import { page } from '$app/stores';
$: x = $page.url;
</script>
{x}
`;
const result = transform_svelte_code(input, {});
assert.equal(result, input);
});

test('Does not update $app/store #2', () => {
const input = `<script>
import { page } from '$app/stores';
import { derived } from 'svelte/store';
const url = derived(page, ($page) => $page.url);
</script>
{$url}
`;
const result = transform_svelte_code(input, {});
assert.equal(result, input);
});

test('Does not update $app/store #3', () => {
const input = `<script>
import { page, getStores } from '$app/stores';
const x = getStores();
</script>
{$page.url}
`;
const result = transform_svelte_code(input, {});
assert.equal(result, input);
});

0 comments on commit 5272dec

Please sign in to comment.