├── .github └── workflows │ ├── build.yml │ └── publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── docs ├── select_typescript.png └── summary.gif ├── extension ├── .vscodeignore ├── README.md ├── logo.png └── package.json ├── package.json ├── prettier.config.js ├── src ├── constants.ts ├── decorator.ts ├── index.ts ├── logger.ts ├── plugin.ts ├── service.ts ├── types.ts └── utils.ts ├── tests ├── demo │ ├── .vscode │ │ └── settings.json │ ├── index.ts │ ├── package.json │ └── tsconfig.json └── units │ └── utils.spec.ts ├── tsconfig.json └── yarn.lock /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | runs-on: windows-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Use Node.js 12.x 15 | uses: actions/setup-node@v1 16 | with: 17 | node-version: 12.x 18 | - name: Install yarn 19 | run: npm install -g yarn 20 | - name: Bootstrap 21 | run: yarn bootstrap:all 22 | - name: Lint 23 | run: yarn lint 24 | - name: "Build" 25 | run: yarn build 26 | - name: "Build extension" 27 | run: yarn build:extension 28 | - name: Upload build 29 | uses: actions/upload-artifact@v2 30 | with: 31 | name: ts-plugin 32 | path: ./dist 33 | - name: Upload extension build 34 | uses: actions/upload-artifact@v2 35 | with: 36 | name: vscode-plugin 37 | path: ./extension/*.vsix 38 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: [ '*' ] 6 | 7 | jobs: 8 | publish: 9 | runs-on: windows-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Use Node.js 12.x 13 | uses: actions/setup-node@v1 14 | with: 15 | node-version: 12.x 16 | - name: Install yarn 17 | run: npm install -g yarn 18 | - name: Install deps 19 | run: yarn 20 | - name: Lint 21 | run: yarn lint 22 | - name: "Build" 23 | run: yarn build 24 | - name: Publish 25 | uses: JS-DevTools/npm-publish@v1 26 | with: 27 | token: ${{ secrets.NPM_TOKEN }} 28 | publish-extension: 29 | runs-on: windows-latest 30 | needs: publish 31 | steps: 32 | - uses: actions/checkout@v2 33 | - name: Use Node.js 12.x 34 | uses: actions/setup-node@v1 35 | with: 36 | node-version: 12.x 37 | - name: Install yarn 38 | run: npm install -g yarn 39 | - name: Bootstrap 40 | run: yarn bootstrap:release 41 | - name: Install lastest extension 42 | run: yarn add ts-string-literal-enum-plugin 43 | working-directory: ./extension 44 | - name: Build 45 | run: yarn build:release 46 | - name: Publish VSCode extension 47 | run: yarn vsce publish -p ${{ secrets.AZURE_DEVOPS_ACCESS_TOKEN }} 48 | working-directory: ./extension -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | *.vsix -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 HearTao 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ts-string-literal-enum-plugin 2 | 3 | A tool that converts enums to string literal enum with only one click. Build with ❤️. 4 | 5 | ## Usages 6 | 7 | ![Usages](docs/summary.gif) 8 | 9 | 10 | ## Install 11 | 12 | ### As VSCode extension 13 | 14 | You can see [ts-string-literal-enum-plugin](https://marketplace.visualstudio.com/items?itemName=kingwl.ts-string-literal-enum-plugin). 15 | 16 | ### As typescript plugin 17 | 18 | 1. Install package 19 | 20 | `yarn add ts-string-literal-enum-plugin` or `npm i ts-string-literal-enum-plugin` 21 | 22 | 2. Update tsconfig 23 | 24 | ```json 25 | 26 | { 27 | "compilerOptions": { 28 | "plugins": [{ 29 | "name": "ts-string-literal-enum-plugin", 30 | }] 31 | } 32 | } 33 | 34 | ``` 35 | 36 | 3. Use TypeScript from `node_modules` 37 | 38 | ![select_typescript_version](docs/select_typescript.png) 39 | 40 | Note: you can learn more at [here](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions) 41 | 42 | 4. Enjoy :XD 43 | -------------------------------------------------------------------------------- /docs/select_typescript.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HearTao/ts-string-literal-enum-plugin/039375d445f6ec4d72f540997f14bd44f01b612e/docs/select_typescript.png -------------------------------------------------------------------------------- /docs/summary.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HearTao/ts-string-literal-enum-plugin/039375d445f6ec4d72f540997f14bd44f01b612e/docs/summary.gif -------------------------------------------------------------------------------- /extension/.vscodeignore: -------------------------------------------------------------------------------- 1 | **/*.ts 2 | **/*.map 3 | **/*.txt 4 | **/tsconfig.json 5 | **/yarn.lock 6 | **/*.config.js 7 | **/extension 8 | **/tests 9 | **/*.log 10 | **/.github 11 | **/node_modules 12 | **/.vscode-test 13 | !node_modules/ts-string-literal-enum-plugin/dist/*.js 14 | !node_modules/ts-string-literal-enum-plugin/package.json 15 | !./dist/*.js 16 | !./img/logo.png 17 | -------------------------------------------------------------------------------- /extension/README.md: -------------------------------------------------------------------------------- 1 | # ts-string-literal-enum-plugin 2 | 3 | A tool that converts enums to string literal enum with only one click. Build with ❤️. 4 | 5 | ### Usages 6 | 7 | ![Usages](https://github.com/HearTao/ts-string-literal-enum-plugin/raw/main/docs/summary.gif) 8 | 9 | -------------------------------------------------------------------------------- /extension/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HearTao/ts-string-literal-enum-plugin/039375d445f6ec4d72f540997f14bd44f01b612e/extension/logo.png -------------------------------------------------------------------------------- /extension/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-string-literal-enum-plugin", 3 | "displayName": "Typescript string literal enums Tools", 4 | "description": "Useful refactor of string literal enums with TypeScript.", 5 | "publisher": "kingwl", 6 | "icon": "logo.png", 7 | "version": "0.0.3", 8 | "license": "MIT", 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/HearTao/ts-string-literal-enum-plugin.git" 12 | }, 13 | "engines": { 14 | "vscode": "^1.34.0" 15 | }, 16 | "main": "./dist/index.js", 17 | "keywords": [ 18 | "typescript", 19 | "ts", 20 | "enum" 21 | ], 22 | "categories": [ 23 | "Programming Languages" 24 | ], 25 | "contributes": { 26 | "typescriptServerPlugins": [ 27 | { 28 | "name": "ts-string-literal-enum-plugin", 29 | "enableForWorkspaceTypeScriptVersions": true 30 | } 31 | ] 32 | }, 33 | "activationEvents": [ 34 | "onLanguage:typescript", 35 | "onLanguage:typescriptreact" 36 | ], 37 | "scripts": { 38 | "postinstall": "node ./node_modules/vscode/bin/install", 39 | "build": "vsce package" 40 | }, 41 | "devDependencies": { 42 | "typescript": "^4.1.2", 43 | "vsce": "^1.81.1", 44 | "vscode": "^1.1.5" 45 | }, 46 | "dependencies": { 47 | "ts-string-literal-enum-plugin": "*" 48 | }, 49 | "extensionDependencies": [ 50 | "vscode.typescript" 51 | ] 52 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-string-literal-enum-plugin", 3 | "version": "0.0.3", 4 | "main": "./dist/index.js", 5 | "types": "./dist/index.d.ts", 6 | "repository": "git@github.com:HearTao/ts-string-literal-enum-plugin.git", 7 | "author": "kingwl ", 8 | "license": "MIT", 9 | "devDependencies": { 10 | "@types/microsoft__typescript-etw": "^0.1.1", 11 | "open-typescript": "^4.3.0-dev.20210303", 12 | "prettier": "^2.2.1", 13 | "typescript": "^4.2.2" 14 | }, 15 | "scripts": { 16 | "build": "tsc", 17 | "build:extension": "cd extension && yarn build", 18 | "build:release": "yarn build:extension", 19 | "bootstrap:demo": "cd tests/demo && yarn --no-lockfile", 20 | "bootstrap:extension": "cd extension && yarn --no-lockfile", 21 | "bootstrap:all": "yarn && yarn bootstrap:demo && yarn bootstrap:extension", 22 | "bootstrap:release": "yarn bootstrap:extension", 23 | "link:demo": "cd tests/demo && yarn link ts-string-literal-enum-plugin", 24 | "link:extension": "cd extension && yarn link ts-string-literal-enum-plugin", 25 | "link:all": "yarn link && yarn link:demo && yarn link:extension", 26 | "lint": "prettier -c --config ./prettier.config.js ./src/**/*.{ts,tsx} ./tests/**/*.{ts,tsx}", 27 | "prettier": "yarn lint --write" 28 | }, 29 | "files": [ 30 | "dist" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: 'typescript', 3 | semi: true, 4 | singleQuote: false, 5 | jsxSingleQuote: false, 6 | bracketSpacing: true, 7 | tabWidth: 4, 8 | useTabs: false, 9 | trailingComma: 'none', 10 | proseWrap: 'always', 11 | arrowParens: 'avoid', 12 | endOfLine: 'crlf' 13 | }; 14 | -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | export const pluginName = "ts-string-literal-enum-plugin"; 2 | 3 | export const refactorName = "convertStringLiteralEnums"; 4 | export const refactorDescriptions = 5 | "Convert enum declaration into stirng literal"; 6 | 7 | export const convertEnumIntoStringLiteralActionName = 8 | "convertEnumIntoStringLiteralActionName"; 9 | export const convertEnumIntoStringLiteralActionDescription = 10 | "Convert Enum declaration into string literal enum."; 11 | 12 | export const convertEnumMemberIntoStringLiteralActionName = 13 | "convertEnumMemberIntoStringLiteralActionName"; 14 | export const convertEnumMemberIntoStringLiteralActionDescription = 15 | "Convert Enum member into string literal enum."; 16 | -------------------------------------------------------------------------------- /src/decorator.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | 3 | type LanguageServiceMethodWrapper = ( 4 | delegate: ts.LanguageService[K], 5 | info?: ts.server.PluginCreateInfo 6 | ) => ts.LanguageService[K]; 7 | 8 | export interface ICustomizedLanguageServie { 9 | getApplicableRefactors: ts.LanguageService["getApplicableRefactors"]; 10 | getEditsForRefactor: ts.LanguageService["getEditsForRefactor"]; 11 | } 12 | 13 | export class RefactorLanguageServiceProxy { 14 | private readonly _wrappers: Array<{ 15 | name: keyof ts.LanguageService; 16 | wrapper: LanguageServiceMethodWrapper; 17 | }> = []; 18 | 19 | constructor( 20 | private readonly customizedLanguageServie: ICustomizedLanguageServie 21 | ) { 22 | this.tryAdaptGetApplicableRefactors(); 23 | this.tryAdaptGetEditsForRefactor(); 24 | } 25 | 26 | decorate(languageService: ts.LanguageService) { 27 | const intercept: Partial = Object.create(null); 28 | 29 | for (const { name, wrapper } of this._wrappers) { 30 | (intercept[name] as any) = wrapper( 31 | languageService[name]!.bind(languageService) 32 | ); 33 | } 34 | 35 | languageService.getApplicableRefactors; 36 | 37 | return new Proxy(languageService, { 38 | get: (target: any, property: string | symbol) => { 39 | return (intercept as any)[property] || target[property]; 40 | } 41 | }); 42 | } 43 | 44 | private tryAdaptGetApplicableRefactors() { 45 | this.wrap( 46 | "getApplicableRefactors", 47 | delegate => ( 48 | fileName: string, 49 | positionOrRange: number | ts.TextRange, 50 | preferences: ts.UserPreferences | undefined, 51 | triggerReason?: ts.RefactorTriggerReason 52 | ) => { 53 | const original = delegate( 54 | fileName, 55 | positionOrRange, 56 | preferences, 57 | triggerReason 58 | ); 59 | const customized = this.customizedLanguageServie.getApplicableRefactors( 60 | fileName, 61 | positionOrRange, 62 | preferences, 63 | triggerReason 64 | ); 65 | return original.concat(customized); 66 | } 67 | ); 68 | } 69 | 70 | private tryAdaptGetEditsForRefactor() { 71 | this.wrap( 72 | "getEditsForRefactor", 73 | delegate => ( 74 | fileName: string, 75 | formatOptions: ts.FormatCodeSettings, 76 | positionOrRange: number | ts.TextRange, 77 | refactorName: string, 78 | actionName: string, 79 | preferences: ts.UserPreferences | undefined 80 | ) => { 81 | const result = this.customizedLanguageServie.getEditsForRefactor( 82 | fileName, 83 | formatOptions, 84 | positionOrRange, 85 | refactorName, 86 | actionName, 87 | preferences 88 | ); 89 | if (result) { 90 | return result; 91 | } 92 | 93 | return delegate( 94 | fileName, 95 | formatOptions, 96 | positionOrRange, 97 | refactorName, 98 | actionName, 99 | preferences 100 | ); 101 | } 102 | ); 103 | } 104 | private wrap( 105 | name: K, 106 | wrapper: LanguageServiceMethodWrapper 107 | ) { 108 | this._wrappers.push({ name, wrapper }); 109 | return this; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | import { StringLiteralEnumPlugin } from "./plugin"; 3 | 4 | export = (mod: { typescript: typeof ts }) => 5 | new StringLiteralEnumPlugin(mod.typescript); 6 | -------------------------------------------------------------------------------- /src/logger.ts: -------------------------------------------------------------------------------- 1 | import { pluginName } from "./constants"; 2 | import type * as ts from "typescript/lib/tsserverlibrary"; 3 | 4 | export class LanguageServiceLogger { 5 | constructor(private readonly info: ts.server.PluginCreateInfo) {} 6 | 7 | public log(msg: string | undefined) { 8 | if (msg) { 9 | this.info.project.projectService.logger.info( 10 | `[${pluginName}] ${msg}` 11 | ); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/plugin.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | import { LanguageServiceLogger } from "./logger"; 3 | import { RefactorLanguageServiceProxy } from "./decorator"; 4 | import { CustomizedLanguageService } from "./service"; 5 | import { SynchronizedConfiguration } from "./types"; 6 | 7 | export class StringLiteralEnumPlugin { 8 | private logger?: LanguageServiceLogger; 9 | 10 | constructor(private readonly typescript: typeof ts) {} 11 | 12 | create(info: ts.server.PluginCreateInfo) { 13 | const config: SynchronizedConfiguration = info.config ?? {}; 14 | this.logger = new LanguageServiceLogger(info); 15 | this.logger.log("create config: " + JSON.stringify(config)); 16 | 17 | return new RefactorLanguageServiceProxy( 18 | new CustomizedLanguageService(info, this.typescript, this.logger) 19 | ).decorate(info.languageService); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/service.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | import "open-typescript"; 3 | 4 | import { 5 | convertEnumIntoStringLiteralActionName, 6 | convertEnumMemberIntoStringLiteralActionName, 7 | refactorDescriptions, 8 | refactorName 9 | } from "./constants"; 10 | import { ICustomizedLanguageServie } from "./decorator"; 11 | import { LanguageServiceLogger } from "./logger"; 12 | import { 13 | EnumOrEnumMember, 14 | Err, 15 | Ok, 16 | OkType, 17 | RefactorContext, 18 | Result 19 | } from "./types"; 20 | import { 21 | assert, 22 | getPositionOfPositionOrRange, 23 | isConvertibleEnumMember, 24 | kindToActionNameAndDesc 25 | } from "./utils"; 26 | 27 | export class CustomizedLanguageService implements ICustomizedLanguageServie { 28 | constructor( 29 | private readonly info: ts.server.PluginCreateInfo, 30 | private readonly typescript: typeof ts, 31 | private readonly logger: LanguageServiceLogger 32 | ) {} 33 | 34 | getApplicableRefactors( 35 | fileName: string, 36 | positionOrRange: number | ts.TextRange, 37 | preferences: ts.UserPreferences | undefined 38 | ): ts.ApplicableRefactorInfo[] { 39 | const context = this.getRefactorContext(fileName); 40 | if (!context) { 41 | this.logger.log("Cannot construct refactor context"); 42 | return []; 43 | } 44 | 45 | const ts = this.typescript; 46 | const { file } = context; 47 | const targetInfo = this.getTargetInfo( 48 | file, 49 | getPositionOfPositionOrRange(positionOrRange) 50 | ); 51 | 52 | if (targetInfo.type !== OkType.Ok) { 53 | this.logger.log(targetInfo.reason); 54 | if ( 55 | !preferences?.provideRefactorNotApplicableReason || 56 | !targetInfo.extra 57 | ) { 58 | return []; 59 | } 60 | 61 | const [actionName, actionDescription] = kindToActionNameAndDesc( 62 | targetInfo.extra, 63 | ts 64 | ); 65 | return [ 66 | { 67 | name: refactorName, 68 | description: refactorDescriptions, 69 | actions: [ 70 | { 71 | name: actionName, 72 | description: actionDescription, 73 | notApplicableReason: targetInfo.reason 74 | } 75 | ] 76 | } 77 | ]; 78 | } 79 | 80 | const [actionName, actionDescription] = kindToActionNameAndDesc( 81 | targetInfo.value.kind, 82 | ts 83 | ); 84 | return [ 85 | { 86 | name: refactorName, 87 | description: refactorDescriptions, 88 | actions: [ 89 | { 90 | name: actionName, 91 | description: actionDescription 92 | } 93 | ] 94 | } 95 | ]; 96 | } 97 | 98 | getEditsForRefactor( 99 | fileName: string, 100 | formatOptions: ts.FormatCodeSettings, 101 | positionOrRange: number | ts.TextRange, 102 | refactor: string, 103 | actionName: string, 104 | preferences: ts.UserPreferences | undefined 105 | ) { 106 | if ( 107 | refactor !== refactorName || 108 | (actionName !== convertEnumIntoStringLiteralActionName && 109 | actionName !== convertEnumMemberIntoStringLiteralActionName) 110 | ) { 111 | return undefined; 112 | } 113 | 114 | const context = this.getRefactorContext(fileName); 115 | if (!context) { 116 | this.logger.log("Cannot construct refactor context"); 117 | return undefined; 118 | } 119 | 120 | const ts = this.typescript; 121 | const { file } = context; 122 | 123 | const targetInfo = this.getTargetInfo( 124 | file, 125 | getPositionOfPositionOrRange(positionOrRange) 126 | ); 127 | if (targetInfo.type !== OkType.Ok) { 128 | this.logger.log(targetInfo.reason); 129 | return undefined; 130 | } 131 | 132 | return this.doInTextChanges( 133 | formatOptions, 134 | preferences, 135 | changeTracker => { 136 | if (ts.isEnumDeclaration(targetInfo.value)) { 137 | this.doChangesForEnumDeclaration( 138 | file, 139 | targetInfo.value, 140 | changeTracker 141 | ); 142 | } else { 143 | this.doChangesForEnumMember( 144 | file, 145 | targetInfo.value, 146 | changeTracker 147 | ); 148 | } 149 | } 150 | ); 151 | } 152 | 153 | doInTextChanges( 154 | formatOptions: ts.FormatCodeSettings, 155 | preferences: ts.UserPreferences | undefined, 156 | cb: (changeTracker: ts.textChanges.ChangeTracker) => void 157 | ) { 158 | const formatContext = this.typescript.formatting.getFormatContext( 159 | formatOptions, 160 | this.info.languageServiceHost 161 | ); 162 | const textChangesContext: ts.textChanges.TextChangesContext = { 163 | formatContext, 164 | host: this.info.languageServiceHost, 165 | preferences: preferences || {} 166 | }; 167 | 168 | const edits = this.typescript.textChanges.ChangeTracker.with( 169 | textChangesContext, 170 | cb 171 | ); 172 | 173 | return { 174 | edits 175 | }; 176 | } 177 | 178 | getTargetInfo( 179 | file: ts.SourceFile, 180 | pos: number 181 | ): Result { 182 | const ts = this.typescript; 183 | if (file.isDeclarationFile) { 184 | return Err("Cannot convert in d.ts files"); 185 | } 186 | 187 | const currentToken = ts.getTokenAtPosition(file, pos); 188 | if ( 189 | !ts.isStringLiteral(currentToken) && 190 | !ts.isIdentifier(currentToken) 191 | ) { 192 | return Err("Cannot find string or identifier in selection"); 193 | } 194 | if ( 195 | (!ts.isEnumDeclaration(currentToken.parent) && 196 | !ts.isEnumMember(currentToken.parent)) || 197 | currentToken.parent.name !== currentToken 198 | ) { 199 | return Err("Cannot find enum declaration in selection"); 200 | } 201 | 202 | if (ts.isEnumDeclaration(currentToken.parent)) { 203 | if (!currentToken.parent.members.some(isConvertibleEnumMember)) { 204 | return Err( 205 | "Enum declaration cannot be convert", 206 | currentToken.parent.kind 207 | ); 208 | } 209 | return Ok(currentToken.parent); 210 | } else { 211 | if (!isConvertibleEnumMember(currentToken.parent)) { 212 | return Err( 213 | "Enum member cannot be convert", 214 | currentToken.parent.kind 215 | ); 216 | } 217 | return Ok(currentToken.parent); 218 | } 219 | } 220 | 221 | doChangesForEnumDeclaration( 222 | file: ts.SourceFile, 223 | enumDecl: ts.EnumDeclaration, 224 | changeTracker: ts.textChanges.ChangeTracker 225 | ) { 226 | enumDecl.members 227 | .filter(isConvertibleEnumMember) 228 | .forEach(member => 229 | this.doChangesForEnumMember(file, member, changeTracker) 230 | ); 231 | } 232 | 233 | doChangesForEnumMember( 234 | file: ts.SourceFile, 235 | enumMember: ts.EnumMember, 236 | changeTracker: ts.textChanges.ChangeTracker 237 | ) { 238 | const ts = this.typescript; 239 | assert(!enumMember.initializer, "Enum member cannot have initializer"); 240 | assert( 241 | ts.isIdentifier(enumMember.name) || 242 | ts.isStringLiteral(enumMember.name), 243 | "Name of Enum member can only be identifier or string literal" 244 | ); 245 | 246 | changeTracker.replaceNode( 247 | file, 248 | enumMember, 249 | ts.factory.updateEnumMember( 250 | enumMember, 251 | enumMember.name, 252 | ts.factory.createStringLiteral(enumMember.name.text) 253 | ) 254 | ); 255 | } 256 | 257 | getRefactorContext(fileName: string): RefactorContext | undefined { 258 | const program = this.info.languageService.getProgram(); 259 | if (!program) { 260 | this.logger.log("Cannot find program"); 261 | return undefined; 262 | } 263 | 264 | const file = program.getSourceFile(fileName); 265 | if (!file) { 266 | this.logger.log("Cannot find source file"); 267 | return undefined; 268 | } 269 | 270 | return { 271 | file, 272 | program 273 | }; 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | 3 | export interface SynchronizedConfiguration {} 4 | 5 | export interface RefactorContext { 6 | program: ts.Program; 7 | file: ts.SourceFile; 8 | } 9 | 10 | export enum OkType { 11 | Ok, 12 | Err 13 | } 14 | 15 | export interface IOk { 16 | type: OkType.Ok; 17 | value: T; 18 | } 19 | 20 | export interface IError { 21 | type: OkType.Err; 22 | reason?: string; 23 | extra?: E; 24 | } 25 | 26 | export type Result = IOk | IError; 27 | 28 | export function Ok(value: T): IOk { 29 | return { 30 | type: OkType.Ok, 31 | value 32 | }; 33 | } 34 | 35 | export function Err(reason?: string, extra?: E): IError { 36 | return { 37 | type: OkType.Err, 38 | reason, 39 | extra 40 | }; 41 | } 42 | 43 | export type EnumOrEnumMember = ts.EnumMember | ts.EnumDeclaration; 44 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript/lib/tsserverlibrary"; 2 | import { 3 | convertEnumIntoStringLiteralActionDescription, 4 | convertEnumIntoStringLiteralActionName, 5 | convertEnumMemberIntoStringLiteralActionDescription, 6 | convertEnumMemberIntoStringLiteralActionName 7 | } from "./constants"; 8 | 9 | export function getPositionOfPositionOrRange( 10 | positionOrRange: number | ts.TextRange 11 | ) { 12 | return typeof positionOrRange === "number" 13 | ? positionOrRange 14 | : positionOrRange.pos; 15 | } 16 | 17 | export function kindToActionNameAndDesc( 18 | kind: ts.SyntaxKind.EnumMember | ts.SyntaxKind.EnumDeclaration, 19 | typescript: typeof ts 20 | ) { 21 | return kind === typescript.SyntaxKind.EnumDeclaration 22 | ? ([ 23 | convertEnumIntoStringLiteralActionName, 24 | convertEnumIntoStringLiteralActionDescription 25 | ] as const) 26 | : ([ 27 | convertEnumMemberIntoStringLiteralActionName, 28 | convertEnumMemberIntoStringLiteralActionDescription 29 | ] as const); 30 | } 31 | 32 | export function isConvertibleEnumMember(enumMember: ts.EnumMember) { 33 | return !enumMember.initializer; 34 | } 35 | 36 | export function assert(v: any, message?: string): asserts v { 37 | if (!v) { 38 | throw new Error(message ?? "Assertion failed"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests/demo/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules\\typescript\\lib" 3 | } -------------------------------------------------------------------------------- /tests/demo/index.ts: -------------------------------------------------------------------------------- 1 | enum F1 { 2 | A, 3 | B 4 | } 5 | 6 | enum F2 { 7 | A 8 | } 9 | 10 | enum F3 {} 11 | 12 | enum F4 { 13 | A, 14 | B, 15 | C = "c" 16 | } 17 | 18 | enum F5 { 19 | A = 1, 20 | B, 21 | C = "c" 22 | } 23 | 24 | enum F6 { 25 | A = "A", 26 | B = "B" 27 | } 28 | 29 | enum F7 { 30 | A = 1 31 | } 32 | -------------------------------------------------------------------------------- /tests/demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "typescript": "^4.2.2", 4 | "ts-string-literal-enum-plugin": "file:../.." 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /tests/demo/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "plugins": [{ 4 | "name": "ts-string-literal-enum-plugin", 5 | }] 6 | } 7 | } -------------------------------------------------------------------------------- /tests/units/utils.spec.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HearTao/ts-string-literal-enum-plugin/039375d445f6ec4d72f540997f14bd44f01b612e/tests/units/utils.spec.ts -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "alwaysStrict": true, 5 | "moduleResolution": "node", 6 | "target": "ES6", 7 | "module": "commonjs", 8 | "outDir": "dist", 9 | "declaration": true, 10 | "sourceMap": true 11 | }, 12 | "include": [ 13 | "src" 14 | ] 15 | } -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | "@types/microsoft__typescript-etw@^0.1.1": 6 | version "0.1.1" 7 | resolved "https://registry.yarnpkg.com/@types/microsoft__typescript-etw/-/microsoft__typescript-etw-0.1.1.tgz#f2c9d835858827422f3b5885f9afb0cbdad95381" 8 | integrity sha512-zdgHyZJEwbFKI6zhOqWPsNMhlrAk6qMrn9VMA6VQtRt/F+jNJKeaHIMysuO9oTLv0fWcli0gwUrMv8MeFyb3Sw== 9 | 10 | open-typescript@^4.3.0-dev.20210303: 11 | version "4.3.0-dev.20210303" 12 | resolved "https://registry.yarnpkg.com/open-typescript/-/open-typescript-4.3.0-dev.20210303.tgz#1cf96b002457daf99ba0120df3b534a8062d1629" 13 | integrity sha512-SO637zV8ziRnVMTvIRWgTyzjs+sowRMJEv6ZqW8tQ/6LpalVPf5fwTLWF4rNkXVN6Cnb6l9Py76Dv+vJy2yKJg== 14 | 15 | prettier@^2.2.1: 16 | version "2.2.1" 17 | resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.2.1.tgz#795a1a78dd52f073da0cd42b21f9c91381923ff5" 18 | integrity sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q== 19 | 20 | typescript@^4.2.2: 21 | version "4.2.2" 22 | resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.2.tgz#1450f020618f872db0ea17317d16d8da8ddb8c4c" 23 | integrity sha512-tbb+NVrLfnsJy3M59lsDgrzWIflR4d4TIUjz+heUnHZwdF7YsrMTKoRERiIvI2lvBG95dfpLxB21WZhys1bgaQ== 24 | --------------------------------------------------------------------------------