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(codemod): UseSession Hook Update ( nextAuth - migration to v4) #1159

Merged
merged 4 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://codemod-utils.s3.us-west-1.amazonaws.com/configuration_schema.json",
"name": "nextAuth/4/useSession-array-to-object-destructuring",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": ["nextAuth"],
"git": "https://github.com/codemod-com/codemod/tree/main/packages/codemods/nextAuth/useSession-array-to-Object-destrucutring"
},
"applicability": {
"from": [["nextAuth", "<", "v4"]]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Codemod Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
The `useSession` hook has been updated to return an object. This allows you to test states much more cleanly with the new status option.

### Before

```ts
const [session, loading] = useSession();
```

### After

```ts
const { data: session, status } = useSession();
const loading = status === 'loading';
```

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const [session, loading] = useSession();
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const { data: session, status } = useSession();
const loading = status === 'loading';
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "nextjs-use-session-array-to-object-destructuring",
"license": "MIT",
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "^5.2.2",
"vitest": "^1.0.1",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"files": [
"README.md",
".codemodrc.json",
"/dist/index.cjs"
],
"type": "module",
"author": "manishjha-04"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { API, FileInfo, Options } from 'jscodeshift';

function transform(
file: FileInfo,
api: API,
options: Options,
): string | undefined {
const j = api.jscodeshift;
const root = j(file.source);

// Find all variable declarations
root.find(j.VariableDeclaration).forEach((path) => {
// Iterate over each declarator in the declaration
path.node.declarations.forEach((declarator) => {
// Check if the declarator is of type VariableDeclarator
if (j.VariableDeclarator.check(declarator)) {
// Check if the declarator id is an array pattern
if (j.ArrayPattern.check(declarator.id)) {
const elements = declarator.id.elements;

// Ensure the array pattern has exactly two elements
if (
elements.length === 2 &&
j.Identifier.check(elements[0]) &&
j.Identifier.check(elements[1])
) {
const sessionVar = elements[0].name;
const loadingVar = elements[1].name;

// Check if the initializer is a call expression to useSession
if (
declarator.init &&
j.CallExpression.check(declarator.init) &&
j.Identifier.check(declarator.init.callee) &&
declarator.init.callee.name === 'useSession'
) {
// Replace the array destructuring with object destructuring
declarator.id = j.objectPattern([
j.property(
'init',
j.identifier('data'),
j.identifier(sessionVar),
),
j.property(
'init',
j.identifier('status'),
j.identifier('status'),
),
]);

// Add a new variable declaration for loading
const loadingDeclaration = j.variableDeclaration(
'const',
[
j.variableDeclarator(
j.identifier(loadingVar),
j.binaryExpression(
'===',
j.identifier('status'),
j.literal('loading'),
),
),
],
);

// Insert the new loading declaration after the current declaration
j(path).insertAfter(loadingDeclaration);

// Ensure the status property is not renamed
declarator.id.properties.forEach((property) => {
if (
j.Property.check(property) &&
j.Identifier.check(property.key) &&
property.key.name === 'status'
) {
property.shorthand = true;
}
});
}
}
}
}
});
});

return root.toSource(options);
}

export default transform;
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, it } from 'vitest';
import jscodeshift, { type API } from 'jscodeshift';
import transform from '../src/index.js';
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

const buildApi = (parser: string | undefined): API => ({
j: parser ? jscodeshift.withParser(parser) : jscodeshift,
jscodeshift: parser ? jscodeshift.withParser(parser) : jscodeshift,
stats: () => {
console.error(
'The stats function was called, which is not supported on purpose',
);
},
report: () => {
console.error(
'The report function was called, which is not supported on purpose',
);
},
});

describe('nextjs/use-session-array-to-object-destructuring', () => {
it('test #1', async () => {
const INPUT = await readFile(join(__dirname, '..', '__testfixtures__/fixture1.input.ts'), 'utf-8');
const OUTPUT = await readFile(join(__dirname, '..', '__testfixtures__/fixture1.output.ts'), 'utf-8');

const actualOutput = transform({
path: 'index.js',
source: INPUT,
},
buildApi('tsx'), {}
);

assert.deepEqual(

Check failure on line 35 in packages/codemods/nextAuth/useSession-array-to-Object-destrucutring/test/test.ts

View workflow job for this annotation

GitHub Actions / Run unit tests (ubuntu-latest, true)

packages/codemods/nextAuth/useSession-array-to-Object-destrucutring/test/test.ts > nextjs/use-session-array-to-object-destructuring > test #1

AssertionError: Expected values to be loosely deep-equal: 'const {\n' + ' data: session,\n' + ' status\n' + '} = useSession();\n' + 'const loading = status === "loading";' should loosely deep-equal 'const { data: session, status } = useSession();\n' + "const loading = status === 'loading';" - Expected + Received - const { data: session, status } = useSession(); - const loading = status === 'loading'; + const { + data: session, + status + } = useSession(); + const loading = status === "loading"; ❯ packages/codemods/nextAuth/useSession-array-to-Object-destrucutring/test/test.ts:35:12
actualOutput?.replace(/W/gm, ''),
OUTPUT.replace(/W/gm, ''),
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"useDefineForClassFields": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
"strict": true,
"strictNullChecks": true,
"incremental": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": false,
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { configDefaults, defineConfig } from 'vitest/config';

export default defineConfig({
test: {
include: [...configDefaults.include, '**/test/*.ts'],
},
});
Loading
Loading