@pob/codemods 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,13 @@
1
+ # EditorConfig helps developers define and maintain consistent
2
+ # coding styles between different editors and IDEs
3
+ # http://editorconfig.org
4
+
5
+ root = true
6
+
7
+ [*]
8
+ indent_style = space
9
+ indent_size = 2
10
+ end_of_line = lf
11
+ charset = utf-8
12
+ trim_trailing_whitespace = true
13
+ insert_final_newline = true
package/.eslintrc.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "root": true,
3
+ "extends": ["@pob/eslint-config/root-module"],
4
+ "ignorePatterns": ["/build"]
5
+ }
package/.yo-rc.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "pob": {
3
+ "app": {
4
+ "type": "node",
5
+ "testing": false
6
+ },
7
+ "project": {
8
+ "type": "app"
9
+ }
10
+ }
11
+ }
package/LICENSE ADDED
@@ -0,0 +1,2 @@
1
+ Copyright (c) 2023 Christophe Hurpeau <302891+christophehurpeau@users.noreply.github.com> (https://christophe.hurpeau.com)
2
+ All rights reserved.
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readdirSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { glob } from 'glob';
6
+ import runJscodeshift from '../lib/runJscodeshift.cjs';
7
+
8
+ const argv = process.argv.slice(2);
9
+
10
+ const transformerName = argv[0];
11
+ const globPaths = argv[1];
12
+
13
+ if (!transformerName || !globPaths) {
14
+ const transformerList = readdirSync(
15
+ new URL('../lib/transforms/', import.meta.url),
16
+ );
17
+ throw new Error(
18
+ `Usage: pob-migrate <transformer-name> <glob-paths>\n${transformerList
19
+ .map((t) => `- "${t.slice(0, -4)}"`)
20
+ .join('\n')}`,
21
+ );
22
+ }
23
+
24
+ const transformPath = fileURLToPath(
25
+ new URL(`../lib/transforms/${transformerName}.cjs`, import.meta.url),
26
+ );
27
+ const paths = glob.sync(globPaths);
28
+
29
+ if (paths.length === 0) {
30
+ throw new Error(`No files found matching ${globPaths}`);
31
+ }
32
+
33
+ const res = await runJscodeshift(transformPath, paths, {});
34
+ if (res.errors) {
35
+ process.exitCode = 1;
36
+ }
37
+ console.log('Done!');
@@ -0,0 +1,27 @@
1
+ {
2
+ "root": true,
3
+ "extends": ["@pob/eslint-config/node-module"],
4
+ "settings": {
5
+ "import/resolver": {
6
+ "node": {
7
+ "moduleDirectory": ["node_modules", "src"]
8
+ }
9
+ }
10
+ },
11
+ "overrides": [
12
+ {
13
+ "files": ["**/*.test.{cjs,js}", "__tests__/**/*.{cjs,js}"],
14
+ "env": {
15
+ "jest": true
16
+ },
17
+ "rules": {
18
+ "import/no-extraneous-dependencies": [
19
+ "error",
20
+ {
21
+ "devDependencies": true
22
+ }
23
+ ]
24
+ }
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ const { run: jscodeshift } = require('jscodeshift/src/Runner');
4
+
5
+ module.exports = (...args) => {
6
+ return jscodeshift(...args);
7
+ };
@@ -0,0 +1,145 @@
1
+ /* eslint-disable unicorn/prefer-array-some */
2
+ /* eslint-disable unicorn/no-array-method-this-argument */
3
+
4
+ 'use strict';
5
+
6
+ const { prependImport } = require('../utils/prependImport.cjs');
7
+
8
+ const jestToNodeGlobalMethods = {
9
+ test: 'test',
10
+ describe: 'describe',
11
+ it: 'it',
12
+ beforeAll: 'before',
13
+ afterAll: 'after',
14
+ beforeEach: 'beforeEach',
15
+ afterEach: 'afterEach',
16
+ };
17
+ const propertiesMap = {
18
+ toBe: { default: 'equal', not: 'notEqual' },
19
+ toStrictEqual: { default: 'equal', not: 'notEqual' },
20
+ toEqual: { default: 'equal', not: 'notEqual' },
21
+ };
22
+
23
+ // const mocks = {
24
+ // toHaveBeenCalledTimes: {
25
+ // default: 'mock.calls.length',
26
+ // },
27
+ // };
28
+
29
+ module.exports = (file, api, options) => {
30
+ if (
31
+ !(
32
+ file.path.endsWith('.test.js') ||
33
+ file.path.endsWith('.test.ts') ||
34
+ file.path.endsWith('.test.tsx')
35
+ )
36
+ ) {
37
+ throw new Error(`Invalid file: "${file.path}"`);
38
+ }
39
+
40
+ const j = api.jscodeshift.withParser('tsx');
41
+ const root = j(file.source);
42
+
43
+ function updateTopLevelMethods() {
44
+ const topLevelMethodsUsed = new Set();
45
+
46
+ root
47
+ .find(j.CallExpression, {
48
+ callee: {
49
+ type: j.Identifier.name,
50
+ name: (name) => Object.keys(jestToNodeGlobalMethods).includes(name),
51
+ },
52
+ })
53
+ .replaceWith((p) => {
54
+ const { value } = p;
55
+ topLevelMethodsUsed.add(value.callee.name);
56
+
57
+ return j.callExpression(
58
+ j.identifier(jestToNodeGlobalMethods[value.callee.name]),
59
+ value.arguments,
60
+ );
61
+ });
62
+
63
+ if (topLevelMethodsUsed.size > 0) {
64
+ prependImport(
65
+ j,
66
+ root,
67
+ j.importDeclaration(
68
+ [...topLevelMethodsUsed].map((method) =>
69
+ j.importSpecifier(j.identifier(method)),
70
+ ),
71
+ j.stringLiteral('node:test'),
72
+ ),
73
+ );
74
+ }
75
+ }
76
+
77
+ function updateAssertions() {
78
+ let hasAssertions = false;
79
+
80
+ root
81
+ .find(j.MemberExpression, {
82
+ object: {
83
+ callee: { name: 'expect' },
84
+ },
85
+ })
86
+ .forEach((memberExpressionPath) => {
87
+ const { value: memberExpression, parentPath } = memberExpressionPath;
88
+ let memberExpressionPathToReplace = memberExpressionPath;
89
+ let propertyName = memberExpression.property.name;
90
+ let not = false;
91
+ if (propertyName === 'not') {
92
+ not = true;
93
+ memberExpressionPathToReplace = parentPath;
94
+ propertyName = parentPath.value.property.name;
95
+ }
96
+
97
+ if (!propertiesMap[propertyName]) {
98
+ console.warn(`Unsupported expect property: ${propertyName}`);
99
+ return;
100
+ }
101
+
102
+ const assertPropertyName =
103
+ propertiesMap[propertyName][not ? 'not' : 'default'];
104
+ const callExpressionPath = memberExpressionPathToReplace.parentPath;
105
+
106
+ const argument0 = callExpressionPath.value.arguments[0];
107
+ const argument1 = memberExpression.object.arguments[0];
108
+
109
+ hasAssertions = true;
110
+ callExpressionPath.value.callee = j.memberExpression(
111
+ j.identifier('assert'),
112
+ j.identifier(assertPropertyName),
113
+ );
114
+ callExpressionPath.value.arguments = [argument0, argument1];
115
+ });
116
+
117
+ if (hasAssertions) {
118
+ root
119
+ .find(j.ImportDeclaration, { source: { value: 'node:assert' } })
120
+ .remove();
121
+ if (
122
+ (!root.find(j.ImportDeclaration),
123
+ { source: { value: 'node:assert/strict' } })
124
+ ) {
125
+ prependImport(
126
+ j,
127
+ root,
128
+ j.importDeclaration(
129
+ [j.importDefaultSpecifier(j.identifier('assert'))],
130
+ j.stringLiteral('node:assert/strict'),
131
+ ),
132
+ );
133
+ }
134
+ }
135
+ }
136
+
137
+ updateTopLevelMethods();
138
+ updateAssertions();
139
+
140
+ root
141
+ .find(j.ImportDeclaration, { source: { value: '@jest/globals' } })
142
+ .remove();
143
+
144
+ return root.toSource(options);
145
+ };
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ /* eslint-disable complexity */
4
+ module.exports = (file, api, options) => {
5
+ const j = api.jscodeshift.withParser('tsx');
6
+ const root = j(file.source);
7
+ let hasModifications = false;
8
+
9
+ function processFunctionComponent(path) {
10
+ const node = path.value;
11
+ const { returnType } = node;
12
+ if (returnType == null) return;
13
+ if (returnType.type !== 'TSTypeAnnotation') return;
14
+ const { typeAnnotation } = returnType;
15
+ if (typeAnnotation == null) return;
16
+
17
+ if (
18
+ typeAnnotation.type === 'TSTypeReference' &&
19
+ typeAnnotation.typeName &&
20
+ typeAnnotation.typeName.type === 'Identifier'
21
+ ) {
22
+ if (typeAnnotation.typeName.name === 'ReactElement') {
23
+ typeAnnotation.typeName.name = 'ReactNode';
24
+ hasModifications = true;
25
+ }
26
+ } else if (
27
+ typeAnnotation.type === 'TSUnionType' &&
28
+ typeAnnotation.types.every((unionTypeItem) => {
29
+ if (unionTypeItem.type === 'TSTypeReference') {
30
+ return (
31
+ unionTypeItem.typeName &&
32
+ unionTypeItem.typeName.type === 'Identifier' &&
33
+ unionTypeItem.typeName.name === 'ReactElement'
34
+ );
35
+ }
36
+
37
+ if (unionTypeItem.type === 'TSNullKeyword') {
38
+ return true;
39
+ }
40
+
41
+ return false;
42
+ })
43
+ ) {
44
+ returnType.typeAnnotation = j.tsTypeReference(j.identifier('ReactNode'));
45
+ hasModifications = true;
46
+ }
47
+ }
48
+
49
+ root.find(j.FunctionDeclaration).forEach(processFunctionComponent);
50
+
51
+ if (hasModifications) {
52
+ root.find(j.ImportDeclaration).forEach((importDeclaration) => {
53
+ const { node } = importDeclaration;
54
+ if (node.source.value !== 'react') return;
55
+ if (node.importKind !== 'type') return;
56
+
57
+ node.specifiers = node.specifiers.filter((importSpecifier) => {
58
+ if (importSpecifier.local.name !== 'ReactElement') return true;
59
+ if (importSpecifier.importKind !== 'value') return true;
60
+ return (
61
+ j(importDeclaration)
62
+ .closestScope()
63
+ // eslint-disable-next-line unicorn/no-array-method-this-argument -- not an array
64
+ .find(j.Identifier, { name: 'ReactElement' })
65
+ .filter((p) => {
66
+ if (p.value.start === importSpecifier.local.start) return false;
67
+ if (p.parentPath.value.type === 'Property' && p.name === 'key') {
68
+ return false;
69
+ }
70
+ if (p.name === 'property') return false;
71
+ return true;
72
+ })
73
+ .size() > 0
74
+ );
75
+ });
76
+ if (
77
+ !node.specifiers.some(
78
+ (specifier) =>
79
+ specifier.type === 'ImportSpecifier' &&
80
+ specifier.imported.name === 'ReactNode',
81
+ )
82
+ ) {
83
+ node.specifiers.push(j.importSpecifier(j.identifier('ReactNode')));
84
+ }
85
+ });
86
+ }
87
+
88
+ return hasModifications ? root.toSource(options) : null;
89
+ };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ exports.prependImport = (j, source, importDeclaration) => {
4
+ const existingImports = source.find(j.ImportDeclaration);
5
+ if (existingImports.length > 0) {
6
+ const firstImport = existingImports.at(0);
7
+ const firstImportNode = firstImport.nodes()[0];
8
+ if (firstImportNode?.comments) {
9
+ importDeclaration.comments = firstImportNode.comments;
10
+ firstImportNode.comments = null;
11
+ }
12
+
13
+ firstImport.insertBefore(importDeclaration);
14
+ return;
15
+ }
16
+
17
+ const firstNode = source.find(j.Program).get('body', 0).node;
18
+ const { comments } = firstNode;
19
+ if (comments?.length) {
20
+ const comment = comments[0];
21
+
22
+ // Only move comments that look like file-level comments. Ignore
23
+ // line-level and JSDoc-style comments because these probably belong
24
+ // to the first node, rather than the file.
25
+ if (
26
+ (comment.type === 'Block' || comment.type === 'CommentBlock') &&
27
+ !comment.value.startsWith('*')
28
+ ) {
29
+ importDeclaration.comments = comments;
30
+ firstNode.comments = null;
31
+ }
32
+ }
33
+
34
+ source.get('program', 'body').unshift(importDeclaration);
35
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@pob/codemods",
3
+ "version": "0.0.0",
4
+ "description": "codemods for pob",
5
+ "keywords": [],
6
+ "author": "Christophe Hurpeau <302891+christophehurpeau@users.noreply.github.com> (https://christophe.hurpeau.com)",
7
+ "license": "UNLICENSED",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/christophehurpeau/pob.git",
11
+ "directory": "@pob/codemods"
12
+ },
13
+ "homepage": "https://github.com/christophehurpeau/pob",
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20.9.0"
17
+ },
18
+ "bin": {
19
+ "pob-migrate": "./bin/migrate.mjs"
20
+ },
21
+ "main": "./lib/index.js",
22
+ "exports": {
23
+ ".": "./lib/index.js",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "install-bin": "ln -s $PWD/bin/migrate.mjs /usr/local/bin/pob-migrate",
31
+ "lint": "yarn run lint:eslint",
32
+ "lint:eslint": "yarn ../.. run eslint --report-unused-disable-directives --resolve-plugins-relative-to . --quiet @pob/codemods"
33
+ },
34
+ "pob": {},
35
+ "prettier": "@pob/root/prettier-config",
36
+ "dependencies": {
37
+ "glob": "10.3.10",
38
+ "jscodeshift": "0.15.1"
39
+ },
40
+ "devDependencies": {
41
+ "@types/jscodeshift": "0.11.11"
42
+ }
43
+ }