@suspensive/codemods 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Viva Republica, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # Introduction
2
+
3
+ Suspensive provides a codemod to facilitate easy code modifications. This helps in managing the Suspensive codebase more effectively.
4
+
5
+ ## Usage
6
+
7
+ In your terminal, navigate into your project's folder, then run:
8
+
9
+ ```shell
10
+ npx @suspensive/codemods <transform> <path>
11
+ ```
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/bin/codemods.ts
27
+ var import_extra_typings = require("@commander-js/extra-typings");
28
+
29
+ // package.json
30
+ var package_default = {
31
+ name: "@suspensive/codemods",
32
+ version: "0.1.0",
33
+ description: "Codemods for @suspensive.",
34
+ keywords: [
35
+ "suspensive",
36
+ "codemods"
37
+ ],
38
+ homepage: "https://suspensive.org",
39
+ bugs: "https://github.com/toss/suspensive/issues",
40
+ repository: {
41
+ type: "git",
42
+ url: "git+https://github.com/toss/suspensive.git",
43
+ directory: "packages/codemods"
44
+ },
45
+ license: "MIT",
46
+ author: "Gwansik Kim <gwansik.kim@gwansik.dev>",
47
+ sideEffects: false,
48
+ type: "module",
49
+ files: [
50
+ "dist"
51
+ ],
52
+ scripts: {
53
+ build: "tsup",
54
+ "ci:attw": "attw --pack",
55
+ "ci:eslint": 'eslint "**/*.{ts,tsx,cts,mts}"',
56
+ "ci:publint": "publint --strict",
57
+ "ci:test": "vitest run --coverage --typecheck",
58
+ "ci:type": "tsc --noEmit",
59
+ clean: "rimraf ./dist && rimraf ./coverage",
60
+ prepack: "pnpm build",
61
+ "test:ui": "vitest --ui --coverage --typecheck"
62
+ },
63
+ bin: "dist/bin/codemods.cjs",
64
+ dependencies: {
65
+ "@commander-js/extra-typings": "^12.1.0",
66
+ commander: "^12.1.0",
67
+ execa: "^5.1.1",
68
+ jscodeshift: "^17.0.0",
69
+ prompts: "^2.4.2"
70
+ },
71
+ devDependencies: {
72
+ "@suspensive/eslint-config": "workspace:*",
73
+ "@suspensive/tsconfig": "workspace:*",
74
+ "@types/jscodeshift": "^0.12.0",
75
+ "@types/prompts": "^2.4.9"
76
+ },
77
+ publishConfig: {
78
+ access: "public"
79
+ }
80
+ };
81
+
82
+ // src/bin/transformRunner.ts
83
+ var import_node_path = require("path");
84
+ var import_execa = __toESM(require("execa"), 1);
85
+ var import_prompts = __toESM(require("prompts"), 1);
86
+ var TRANSFORMER_INQUIRER_CHOICES = [
87
+ {
88
+ title: "tanstack-query-import",
89
+ description: "Migrate imports to @tanstack/react-query in @suspensive/react-query (using @tanstack/react-query@5)"
90
+ }
91
+ ];
92
+ function onCancel() {
93
+ process.exit(1);
94
+ }
95
+ var jscodeshiftExecutable = require.resolve(".bin/jscodeshift");
96
+ var transformerDirectory = (0, import_node_path.join)(__dirname, "../", "../", "dist", "transforms");
97
+ async function transformRunner(transform, path) {
98
+ let transformer = transform ?? "";
99
+ let directory = path ?? "";
100
+ if (transform && !TRANSFORMER_INQUIRER_CHOICES.find((x) => x.title === transform)) {
101
+ console.error("Invalid transform choice, pick one of:");
102
+ console.error(TRANSFORMER_INQUIRER_CHOICES.map((x) => "- " + x.title).join("\n"));
103
+ process.exit(1);
104
+ }
105
+ if (!transform) {
106
+ const res = await (0, import_prompts.default)(
107
+ {
108
+ type: "select",
109
+ name: "transformer",
110
+ message: "Which transform would you like to apply?",
111
+ choices: TRANSFORMER_INQUIRER_CHOICES.reverse().map(({ title, description }) => {
112
+ return {
113
+ title,
114
+ description,
115
+ value: title
116
+ };
117
+ })
118
+ },
119
+ { onCancel }
120
+ );
121
+ transformer = res.transformer;
122
+ }
123
+ if (!path) {
124
+ const res = await (0, import_prompts.default)(
125
+ {
126
+ type: "text",
127
+ name: "path",
128
+ message: "On which files or directory should the codemods be applied?",
129
+ initial: "."
130
+ },
131
+ { onCancel }
132
+ );
133
+ directory = res.path;
134
+ }
135
+ const args = [];
136
+ args.push("--no-babel");
137
+ args.push("--ignore-pattern=**/node_modules/**");
138
+ args.push("--ignore-pattern=**/.next/**");
139
+ args.push("--extensions=tsx,ts,jsx,js");
140
+ args.push("--transform", (0, import_node_path.join)(transformerDirectory, `${transformer}.cjs`));
141
+ args.push(directory);
142
+ console.log(`Executing command: jscodeshift ${args.join(" ")}`);
143
+ const execaChildProcess = (0, import_execa.default)(jscodeshiftExecutable, args, {
144
+ env: process.stdout.isTTY ? { FORCE_COLOR: "true" } : {}
145
+ });
146
+ let lastThreeLineBreaks = "";
147
+ if (execaChildProcess.stdout) {
148
+ execaChildProcess.stdout.pipe(process.stdout);
149
+ execaChildProcess.stderr?.pipe(process.stderr);
150
+ execaChildProcess.stdout.on("data", (chunk) => {
151
+ lastThreeLineBreaks += chunk.toString("utf-8");
152
+ let cutoff = lastThreeLineBreaks.length;
153
+ for (let i = 0; i < 3; i++) {
154
+ cutoff = lastThreeLineBreaks.lastIndexOf("\n", cutoff) - 1;
155
+ }
156
+ if (cutoff > 0 && cutoff < lastThreeLineBreaks.length) {
157
+ lastThreeLineBreaks = lastThreeLineBreaks.slice(cutoff + 1);
158
+ }
159
+ });
160
+ }
161
+ try {
162
+ const result = await execaChildProcess;
163
+ if (result.failed) {
164
+ throw new Error(`jscodeshift exited with code ${result.exitCode}`);
165
+ }
166
+ } catch (error) {
167
+ console.error(error);
168
+ process.exit(1);
169
+ }
170
+ }
171
+
172
+ // src/bin/codemods.ts
173
+ var program = new import_extra_typings.Command(package_default.name);
174
+ program.description(package_default.description).version(package_default.version, "-v, --version", "Output the current version of @suspensive/codemods.").argument("[codemod]", "Codemod slug to run.").argument("[path]", "Path to source directory.").usage("[codemod] [path]").helpOption("-h, --help", "Display this help message.").action((codemod, path) => transformRunner(codemod, path));
175
+ program.parse(process.argv);
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/bin/transformRunner.ts
31
+ var transformRunner_exports = {};
32
+ __export(transformRunner_exports, {
33
+ jscodeshiftExecutable: () => jscodeshiftExecutable,
34
+ transformRunner: () => transformRunner,
35
+ transformerDirectory: () => transformerDirectory
36
+ });
37
+ module.exports = __toCommonJS(transformRunner_exports);
38
+ var import_node_path = require("path");
39
+ var import_execa = __toESM(require("execa"), 1);
40
+ var import_prompts = __toESM(require("prompts"), 1);
41
+ var TRANSFORMER_INQUIRER_CHOICES = [
42
+ {
43
+ title: "tanstack-query-import",
44
+ description: "Migrate imports to @tanstack/react-query in @suspensive/react-query (using @tanstack/react-query@5)"
45
+ }
46
+ ];
47
+ function onCancel() {
48
+ process.exit(1);
49
+ }
50
+ var jscodeshiftExecutable = require.resolve(".bin/jscodeshift");
51
+ var transformerDirectory = (0, import_node_path.join)(__dirname, "../", "../", "dist", "transforms");
52
+ async function transformRunner(transform, path) {
53
+ let transformer = transform ?? "";
54
+ let directory = path ?? "";
55
+ if (transform && !TRANSFORMER_INQUIRER_CHOICES.find((x) => x.title === transform)) {
56
+ console.error("Invalid transform choice, pick one of:");
57
+ console.error(TRANSFORMER_INQUIRER_CHOICES.map((x) => "- " + x.title).join("\n"));
58
+ process.exit(1);
59
+ }
60
+ if (!transform) {
61
+ const res = await (0, import_prompts.default)(
62
+ {
63
+ type: "select",
64
+ name: "transformer",
65
+ message: "Which transform would you like to apply?",
66
+ choices: TRANSFORMER_INQUIRER_CHOICES.reverse().map(({ title, description }) => {
67
+ return {
68
+ title,
69
+ description,
70
+ value: title
71
+ };
72
+ })
73
+ },
74
+ { onCancel }
75
+ );
76
+ transformer = res.transformer;
77
+ }
78
+ if (!path) {
79
+ const res = await (0, import_prompts.default)(
80
+ {
81
+ type: "text",
82
+ name: "path",
83
+ message: "On which files or directory should the codemods be applied?",
84
+ initial: "."
85
+ },
86
+ { onCancel }
87
+ );
88
+ directory = res.path;
89
+ }
90
+ const args = [];
91
+ args.push("--no-babel");
92
+ args.push("--ignore-pattern=**/node_modules/**");
93
+ args.push("--ignore-pattern=**/.next/**");
94
+ args.push("--extensions=tsx,ts,jsx,js");
95
+ args.push("--transform", (0, import_node_path.join)(transformerDirectory, `${transformer}.cjs`));
96
+ args.push(directory);
97
+ console.log(`Executing command: jscodeshift ${args.join(" ")}`);
98
+ const execaChildProcess = (0, import_execa.default)(jscodeshiftExecutable, args, {
99
+ env: process.stdout.isTTY ? { FORCE_COLOR: "true" } : {}
100
+ });
101
+ let lastThreeLineBreaks = "";
102
+ if (execaChildProcess.stdout) {
103
+ execaChildProcess.stdout.pipe(process.stdout);
104
+ execaChildProcess.stderr?.pipe(process.stderr);
105
+ execaChildProcess.stdout.on("data", (chunk) => {
106
+ lastThreeLineBreaks += chunk.toString("utf-8");
107
+ let cutoff = lastThreeLineBreaks.length;
108
+ for (let i = 0; i < 3; i++) {
109
+ cutoff = lastThreeLineBreaks.lastIndexOf("\n", cutoff) - 1;
110
+ }
111
+ if (cutoff > 0 && cutoff < lastThreeLineBreaks.length) {
112
+ lastThreeLineBreaks = lastThreeLineBreaks.slice(cutoff + 1);
113
+ }
114
+ });
115
+ }
116
+ try {
117
+ const result = await execaChildProcess;
118
+ if (result.failed) {
119
+ throw new Error(`jscodeshift exited with code ${result.exitCode}`);
120
+ }
121
+ } catch (error) {
122
+ console.error(error);
123
+ process.exit(1);
124
+ }
125
+ }
126
+ // Annotate the CommonJS export names for ESM import in node:
127
+ 0 && (module.exports = {
128
+ jscodeshiftExecutable,
129
+ transformRunner,
130
+ transformerDirectory
131
+ });
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/transforms/tanstack-query-import.ts
31
+ var tanstack_query_import_exports = {};
32
+ __export(tanstack_query_import_exports, {
33
+ default: () => transform
34
+ });
35
+ module.exports = __toCommonJS(tanstack_query_import_exports);
36
+
37
+ // src/utils/createParserFromPath.ts
38
+ var import_jscodeshift = __toESM(require("jscodeshift"), 1);
39
+ var import_babylon = __toESM(require("jscodeshift/parser/babylon"), 1);
40
+ var import_tsOptions = __toESM(require("jscodeshift/parser/tsOptions"), 1);
41
+ function createParserFromPath(filePath) {
42
+ const isDeclarationFile = /\.d\.[mc]?ts$/.test(filePath);
43
+ if (isDeclarationFile) {
44
+ return import_jscodeshift.default.withParser(
45
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call
46
+ (0, import_babylon.default)({
47
+ ...import_tsOptions.default,
48
+ plugins: [
49
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
50
+ ...import_tsOptions.default.plugins.filter((plugin) => plugin !== "typescript"),
51
+ ["typescript", { dts: true }]
52
+ ]
53
+ })
54
+ );
55
+ }
56
+ const isTsFile = /\.[mc]?ts$/.test(filePath);
57
+ return isTsFile ? import_jscodeshift.default.withParser("ts") : import_jscodeshift.default.withParser("tsx");
58
+ }
59
+
60
+ // src/transforms/tanstack-query-import.ts
61
+ var IMPORT_TO_CHANGE = [
62
+ "useSuspenseQuery",
63
+ "UseSuspenseQueryResult",
64
+ "UseSuspenseQueryOptions",
65
+ "useSuspenseQueries",
66
+ "SuspenseQueriesResults",
67
+ "SuspenseQueriesOptions",
68
+ "useSuspenseInfiniteQuery",
69
+ "UseSuspenseInfiniteQueryResult",
70
+ "UseSuspenseInfiniteQueryOptions",
71
+ "usePrefetchQuery",
72
+ "queryOptions",
73
+ "infiniteQueryOption"
74
+ ];
75
+ function transform(file) {
76
+ const j2 = createParserFromPath(file.path);
77
+ const root = j2(file.source);
78
+ root.find(j2.ImportDeclaration, {
79
+ source: {
80
+ value: (v) => /^@suspensive\/react-query(-\d+)?$/.test(v)
81
+ }
82
+ }).forEach((path) => {
83
+ const importSpecifiers = path.node.specifiers || [];
84
+ const importNamesToChange = importSpecifiers.filter(
85
+ (specifier) => IMPORT_TO_CHANGE.includes(specifier.local?.name ?? "")
86
+ );
87
+ const importsNamesRemained = importSpecifiers.filter(
88
+ (specifier) => !IMPORT_TO_CHANGE.includes(specifier.local?.name ?? "")
89
+ );
90
+ if (importNamesToChange.length > 0) {
91
+ const newImportStatement = j2.importDeclaration(importNamesToChange, j2.stringLiteral("@tanstack/react-query"));
92
+ path.insertBefore(newImportStatement);
93
+ }
94
+ if (importsNamesRemained.length > 0) {
95
+ const remainingSpecifiers = importSpecifiers.filter(
96
+ (specifier) => !IMPORT_TO_CHANGE.includes(specifier.local?.name ?? "")
97
+ );
98
+ const suspensiveRemainImportsStatement = j2.importDeclaration(
99
+ remainingSpecifiers,
100
+ j2.stringLiteral(path.node.source.value || "@suspensive/react-query")
101
+ );
102
+ path.insertBefore(suspensiveRemainImportsStatement);
103
+ }
104
+ j2(path).remove();
105
+ }).toSource();
106
+ return root.toSource();
107
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@suspensive/codemods",
3
+ "version": "0.1.0",
4
+ "description": "Codemods for @suspensive.",
5
+ "keywords": [
6
+ "suspensive",
7
+ "codemods"
8
+ ],
9
+ "homepage": "https://suspensive.org",
10
+ "bugs": "https://github.com/toss/suspensive/issues",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/toss/suspensive.git",
14
+ "directory": "packages/codemods"
15
+ },
16
+ "license": "MIT",
17
+ "author": "Gwansik Kim <gwansik.kim@gwansik.dev>",
18
+ "sideEffects": false,
19
+ "type": "module",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "bin": "dist/bin/codemods.cjs",
24
+ "dependencies": {
25
+ "@commander-js/extra-typings": "^12.1.0",
26
+ "commander": "^12.1.0",
27
+ "execa": "^5.1.1",
28
+ "jscodeshift": "^17.0.0",
29
+ "prompts": "^2.4.2"
30
+ },
31
+ "devDependencies": {
32
+ "@types/jscodeshift": "^0.12.0",
33
+ "@types/prompts": "^2.4.9",
34
+ "@suspensive/eslint-config": "0.0.0",
35
+ "@suspensive/tsconfig": "0.0.0-development"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "ci:attw": "attw --pack",
43
+ "ci:eslint": "eslint \"**/*.{ts,tsx,cts,mts}\"",
44
+ "ci:publint": "publint --strict",
45
+ "ci:test": "vitest run --coverage --typecheck",
46
+ "ci:type": "tsc --noEmit",
47
+ "clean": "rimraf ./dist && rimraf ./coverage",
48
+ "test:ui": "vitest --ui --coverage --typecheck"
49
+ }
50
+ }