diff --git a/magic-api-spring-boot-starter/pom.xml b/magic-api-spring-boot-starter/pom.xml index 2a705d96..52fdf4d1 100644 --- a/magic-api-spring-boot-starter/pom.xml +++ b/magic-api-spring-boot-starter/pom.xml @@ -6,7 +6,7 @@ org.ssssssss magic-api-parent - 1.7.2 + 2.0.0-alpha.1 magic-api-spring-boot-starter jar diff --git a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIAutoConfiguration.java b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIAutoConfiguration.java index f9f2caa4..db4ab8ec 100644 --- a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIAutoConfiguration.java +++ b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIAutoConfiguration.java @@ -22,6 +22,7 @@ import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; @@ -29,7 +30,6 @@ import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; @@ -50,13 +50,16 @@ import org.ssssssss.magicapi.interceptor.*; import org.ssssssss.magicapi.logging.LoggerManager; import org.ssssssss.magicapi.model.Constants; import org.ssssssss.magicapi.model.DataType; +import org.ssssssss.magicapi.model.MagicEntity; import org.ssssssss.magicapi.model.Options; import org.ssssssss.magicapi.modules.*; import org.ssssssss.magicapi.provider.*; import org.ssssssss.magicapi.provider.impl.*; +import org.ssssssss.magicapi.service.MagicDynamicRegistry; +import org.ssssssss.magicapi.service.MagicResourceService; +import org.ssssssss.magicapi.service.impl.*; import org.ssssssss.magicapi.utils.ClassScanner; import org.ssssssss.magicapi.utils.Mapping; -import org.ssssssss.magicapi.utils.PathUtils; import org.ssssssss.script.MagicResourceLoader; import org.ssssssss.script.MagicScript; import org.ssssssss.script.MagicScriptEngine; @@ -70,7 +73,6 @@ import javax.servlet.http.HttpServletRequest; import javax.sql.DataSource; import java.io.File; import java.io.IOException; -import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -85,7 +87,7 @@ import java.util.function.BiFunction; @Configuration @ConditionalOnClass({RequestMappingHandlerMapping.class}) @EnableConfigurationProperties(MagicAPIProperties.class) -@Import({MagicRedisAutoConfiguration.class, MagicMongoAutoConfiguration.class, MagicSwaggerConfiguration.class, MagicJsonAutoConfiguration.class, ApplicationUriPrinter.class}) +@Import({MagicRedisAutoConfiguration.class, MagicMongoAutoConfiguration.class, MagicJsonAutoConfiguration.class, ApplicationUriPrinter.class}) @EnableWebSocket public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketConfigurer { @@ -136,6 +138,10 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon private final ObjectProvider magicNotifyServiceProvider; + private final ObjectProvider>> magicDynamicRegistriesProvider; + + private final ObjectProvider>> magicResourceStoragesProvider; + private final ObjectProvider dataSourceEncryptProvider; private final Environment environment; @@ -174,6 +180,8 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon ObjectProvider authorizationInterceptorProvider, ObjectProvider> namedTableInterceptorsProvider, ObjectProvider dataSourceEncryptProvider, + ObjectProvider>> magicDynamicRegistriesProvider, + ObjectProvider>> magicResourceStoragesProvider, Environment environment, ApplicationContext applicationContext ) { @@ -189,6 +197,8 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon this.authorizationInterceptorProvider = authorizationInterceptorProvider; this.namedTableInterceptorsProvider = namedTableInterceptorsProvider; this.dataSourceEncryptProvider = dataSourceEncryptProvider; + this.magicDynamicRegistriesProvider = magicDynamicRegistriesProvider; + this.magicResourceStoragesProvider = magicResourceStoragesProvider; this.environment = environment; this.applicationContext = applicationContext; } @@ -278,13 +288,13 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon // 配置静态资源路径 registry.addResourceHandler(web + "/**").addResourceLocations("classpath:/magic-editor/"); try { - Mapping mapping = Mapping.create(requestMappingHandlerMapping); - // 默认首页设置 - mapping.register(mapping.paths(web).build(), this, MagicAPIAutoConfiguration.class.getDeclaredMethod("redirectIndex", HttpServletRequest.class)) - // 读取配置 - .register(mapping.paths(web + "/config.json").build(), this, MagicAPIAutoConfiguration.class.getDeclaredMethod("readConfig")) - // 读取配置 - .register(mapping.paths(web + "/classes.txt").produces("text/plain").build(), this, MagicAPIAutoConfiguration.class.getDeclaredMethod("readClass")); + Mapping mapping = Mapping.create(requestMappingHandlerMapping, web, properties.getPrefix()); + // 默认首页设置 + mapping.register(mapping.paths(web).build(), this, MagicAPIAutoConfiguration.class.getDeclaredMethod("redirectIndex", HttpServletRequest.class)); + // 读取配置 + mapping.register("GET", web + "/config.json", this, MagicAPIAutoConfiguration.class.getDeclaredMethod("readConfig")); + // 读取配置 + mapping.register(mapping.paths(web + "/classes.txt").methods(RequestMethod.GET).produces("text/plain").build(), this, MagicAPIAutoConfiguration.class.getDeclaredMethod("readClass")); } catch (NoSuchMethodException ignored) { } } @@ -337,39 +347,49 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon return new DefaultSqlCache(cacheConfig.getCapacity(), cacheConfig.getTtl()); } - /** - * 注入接口映射 - */ @Bean - public MappingHandlerMapping mappingHandlerMapping() throws NoSuchMethodException { - String prefix = StringUtils.isNotBlank(properties.getPrefix()) ? PathUtils.replaceSlash("/" + properties.getPrefix() + "/") : null; - return new MappingHandlerMapping(prefix, properties.isAllowOverride()); + @ConditionalOnMissingBean + public MagicResourceService magicResourceService(Resource workspace) { + return new DefaultMagicResourceService(workspace, magicResourceStoragesProvider.getObject(), applicationContext); } @Bean - @ConditionalOnMissingBean(FunctionServiceProvider.class) - public FunctionServiceProvider functionServiceProvider(GroupServiceProvider groupServiceProvider, Resource magicResource) { - return new DefaultFunctionServiceProvider(groupServiceProvider, magicResource); + @ConditionalOnMissingBean + public ApiInfoMagicResourceStorage apiInfoMagicResourceStorage() { + return new ApiInfoMagicResourceStorage(); } - /** - * 注入分组存储service - */ @Bean - @ConditionalOnMissingBean(GroupServiceProvider.class) - public GroupServiceProvider groupServiceProvider(Resource magicResource) { - return new DefaultGroupServiceProvider(magicResource); + @ConditionalOnMissingBean + public RequestMagicDynamicRegistry magicRequestMagicDynamicRegistry(ApiInfoMagicResourceStorage apiInfoMagicResourceStorage) throws NoSuchMethodException { + return new RequestMagicDynamicRegistry(apiInfoMagicResourceStorage, Mapping.create(requestMappingHandlerMapping, properties.getWeb(), properties.getPrefix())); } - /** - * 注入接口存储service - */ @Bean - @ConditionalOnMissingBean(ApiServiceProvider.class) - public ApiServiceProvider apiServiceProvider(GroupServiceProvider groupServiceProvider, Resource magicResource) { - return new DefaultApiServiceProvider(groupServiceProvider, magicResource); + @ConditionalOnMissingBean + public FunctionInfoMagicResourceStorage functionInfoMagicResourceStorage() { + return new FunctionInfoMagicResourceStorage(); } + @Bean + @ConditionalOnMissingBean + public FunctionMagicDynamicRegistry functionMagicDynamicRegistry(FunctionInfoMagicResourceStorage functionInfoMagicResourceStorage) { + return new FunctionMagicDynamicRegistry(functionInfoMagicResourceStorage); + } + + @Bean + @ConditionalOnMissingBean + public DataSourceInfoMagicResourceStorage dataSourceInfoMagicResourceStorage() { + return new DataSourceInfoMagicResourceStorage(); + } + + @Bean + @ConditionalOnMissingBean + public DataSourceMagicDynamicRegistry dataSourceMagicDynamicRegistry(DataSourceInfoMagicResourceStorage dataSourceInfoMagicResourceStorage) { + return new DataSourceMagicDynamicRegistry(dataSourceInfoMagicResourceStorage); + } + + @Bean @ConditionalOnMissingBean(MagicNotifyService.class) public MagicNotifyService magicNotifyService() { @@ -385,26 +405,13 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon return new MagicFileBackupService(new File(properties.getBackupConfig().getLocation())); } - @Bean - public MagicFunctionManager magicFunctionManager(GroupServiceProvider groupServiceProvider, FunctionServiceProvider functionServiceProvider) { - return new MagicFunctionManager(groupServiceProvider, functionServiceProvider); - } - /** * 注入API调用Service */ @Bean @ConditionalOnMissingBean - public MagicAPIService magicAPIService(MappingHandlerMapping mappingHandlerMapping, - ApiServiceProvider apiServiceProvider, - FunctionServiceProvider functionServiceProvider, - GroupServiceProvider groupServiceProvider, - ResultProvider resultProvider, - MagicDynamicDataSource magicDynamicDataSource, - MagicFunctionManager magicFunctionManager, - Resource workspace, - MagicBackupService magicBackupService) { - return new DefaultMagicAPIService(mappingHandlerMapping, apiServiceProvider, functionServiceProvider, groupServiceProvider, resultProvider, magicDynamicDataSource, magicFunctionManager, magicNotifyServiceProvider.getObject(), properties.getClusterConfig().getInstanceId(), workspace, magicBackupService, dataSourceEncryptProvider.getIfAvailable() , properties.isThrowException()); + public MagicAPIService magicAPIService(ResultProvider resultProvider, MagicResourceService magicResourceService) { + return new DefaultMagicAPIService(resultProvider, properties.getClusterConfig().getInstanceId(), magicResourceService, properties.isThrowException()); } /** @@ -522,18 +529,15 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon @Bean public MagicConfiguration magicConfiguration(MagicDynamicDataSource dynamicDataSource, - SQLModule sqlModule, - List magicModules, + SQLModule sqlModule, + List magicModules, List languageProviders, Resource magicResource, ResultProvider resultProvider, + MagicResourceService magicResourceService, MagicAPIService magicAPIService, - ApiServiceProvider apiServiceProvider, - GroupServiceProvider groupServiceProvider, - MappingHandlerMapping mappingHandlerMapping, - FunctionServiceProvider functionServiceProvider, MagicNotifyService magicNotifyService, - MagicFunctionManager magicFunctionManager, + RequestMagicDynamicRegistry requestMagicDynamicRegistry, MagicBackupService magicBackupService) throws NoSuchMethodException { logger.info("magic-api工作目录:{}", magicResource); AsyncCall.setThreadPoolExecutorSize(properties.getThreadPoolExecutorSize()); @@ -550,10 +554,8 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon configuration.setMagicAPIService(magicAPIService); configuration.setMagicNotifyService(magicNotifyService); configuration.setInstanceId(properties.getClusterConfig().getInstanceId()); - configuration.setApiServiceProvider(apiServiceProvider); - configuration.setGroupServiceProvider(groupServiceProvider); - configuration.setMappingHandlerMapping(mappingHandlerMapping); - configuration.setFunctionServiceProvider(functionServiceProvider); + configuration.setMagicResourceService(magicResourceService); + configuration.setMagicDynamicRegistries(magicDynamicRegistriesProvider.getObject()); configuration.setMagicBackupService(magicBackupService); SecurityConfig securityConfig = properties.getSecurityConfig(); configuration.setDebugTimeout(properties.getDebugConfig().getTimeout()); @@ -568,32 +570,19 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon // 向页面传递配置信息时不传递用户名密码,增强安全性 securityConfig.setUsername(null); securityConfig.setPassword(null); - + requestMagicDynamicRegistry.setHandler(new RequestHandler(configuration, requestMagicDynamicRegistry)); // 构建UI请求处理器 String base = properties.getWeb(); - mappingHandlerMapping.setRequestMappingHandlerMapping(requestMappingHandlerMapping); - MagicDataSourceController dataSourceController = new MagicDataSourceController(configuration); + Mapping mapping = Mapping.create(requestMappingHandlerMapping, base, properties.getPrefix()); MagicWorkbenchController magicWorkbenchController = new MagicWorkbenchController(configuration, properties.getSecretKey()); if (base != null) { configuration.setEnableWeb(true); - List controllers = new ArrayList<>(Arrays.asList( - new MagicAPIController(configuration), - dataSourceController, - magicWorkbenchController, - new MagicGroupController(configuration), - new MagicFunctionController(configuration) - )); - controllers.forEach(item -> mappingHandlerMapping.registerController(item, base)); + mapping.registerController(magicWorkbenchController).registerController(new MagicResourceController(configuration)); } // 注册接收推送的接口 if (StringUtils.isNotBlank(properties.getSecretKey())) { - Mapping mapping = Mapping.create(requestMappingHandlerMapping); - RequestMappingInfo requestMappingInfo = mapping.paths(properties.getPushPath()).build(); - Method method = MagicWorkbenchController.class.getDeclaredMethod("receivePush", MultipartFile.class, String.class, Long.class, String.class); - mapping.register(requestMappingInfo, magicWorkbenchController, method); + mapping.register(mapping.paths(properties.getPushPath()).methods(RequestMethod.POST).build(), magicWorkbenchController, MagicWorkbenchController.class.getDeclaredMethod("receivePush", MultipartFile.class, String.class, Long.class, String.class)); } - // 注册数据源 - magicAPIService.registerAllDataSource(); // 设置拦截器信息 this.requestInterceptorsProvider.getIfAvailable(Collections::emptyList).forEach(interceptor -> { logger.info("注册请求拦截器:{}", interceptor.getClass()); @@ -603,16 +592,6 @@ public class MagicAPIAutoConfiguration implements WebMvcConfigurer, WebSocketCon if (this.properties.isBanner()) { configuration.printBanner(); } - configuration.setMagicFunctionManager(magicFunctionManager); - // 注册函数加载器 - magicFunctionManager.registerFunctionLoader(); - // 注册所有函数 - magicFunctionManager.registerAllFunction(); - mappingHandlerMapping.setHandler(new RequestHandler(configuration)); - mappingHandlerMapping.setMagicApiService(apiServiceProvider); - mappingHandlerMapping.setGroupServiceProvider(groupServiceProvider); - // 注册所有映射 - mappingHandlerMapping.registerAllMapping(); // 备份清理 if (properties.getBackupConfig().getMaxHistory() > 0) { long interval = properties.getBackupConfig().getMaxHistory() * 86400000L; diff --git a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIProperties.java b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIProperties.java index 040ed54a..27505957 100644 --- a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIProperties.java +++ b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicAPIProperties.java @@ -147,9 +147,6 @@ public class MagicAPIProperties { @NestedConfigurationProperty private DebugConfig debugConfig = new DebugConfig(); - @NestedConfigurationProperty - private SwaggerConfig swaggerConfig = new SwaggerConfig(); - @NestedConfigurationProperty private ResourceConfig resource = new ResourceConfig(); @@ -265,14 +262,6 @@ public class MagicAPIProperties { this.prefix = prefix; } - public SwaggerConfig getSwaggerConfig() { - return swaggerConfig; - } - - public void setSwaggerConfig(SwaggerConfig swaggerConfig) { - this.swaggerConfig = swaggerConfig; - } - public String getAutoImportModule() { return autoImportModule; } diff --git a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicSwaggerConfiguration.java b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicSwaggerConfiguration.java deleted file mode 100644 index e5596303..00000000 --- a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/MagicSwaggerConfiguration.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.ssssssss.magicapi.spring.boot.starter; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; -import org.springframework.context.annotation.Primary; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import org.ssssssss.magicapi.config.MappingHandlerMapping; -import org.ssssssss.magicapi.provider.GroupServiceProvider; -import org.ssssssss.magicapi.swagger.SwaggerEntity; -import org.ssssssss.magicapi.swagger.SwaggerProvider; -import org.ssssssss.magicapi.utils.Mapping; -import springfox.documentation.swagger.web.SwaggerResource; -import springfox.documentation.swagger.web.SwaggerResourcesProvider; - -import javax.servlet.ServletContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Swagger配置类 - * - * @author mxd - */ -@Configuration -@AutoConfigureAfter({MagicAPIAutoConfiguration.class}) -@EnableConfigurationProperties(MagicAPIProperties.class) -@ConditionalOnClass(name = "springfox.documentation.swagger.web.SwaggerResourcesProvider") -public class MagicSwaggerConfiguration { - - private final MagicAPIProperties properties; - private final ApplicationContext applicationContext; - @Autowired - @Lazy - private RequestMappingHandlerMapping requestMappingHandlerMapping; - - public MagicSwaggerConfiguration(MagicAPIProperties properties, ApplicationContext applicationContext) { - this.properties = properties; - this.applicationContext = applicationContext; - } - - - @Bean - @Primary - public SwaggerResourcesProvider magicSwaggerResourcesProvider(MappingHandlerMapping handlerMapping, GroupServiceProvider groupServiceProvider, ServletContext servletContext) throws NoSuchMethodException { - SwaggerConfig config = properties.getSwaggerConfig(); - Mapping mapping = Mapping.create(requestMappingHandlerMapping); - RequestMappingInfo requestMappingInfo = mapping.paths(config.getLocation()).build(); - - // 构建文档信息 - SwaggerProvider swaggerProvider = new SwaggerProvider(); - swaggerProvider.setGroupServiceProvider(groupServiceProvider); - swaggerProvider.setMappingHandlerMapping(handlerMapping); - swaggerProvider.setPersistenceResponseBody(properties.isPersistenceResponseBody()); - SwaggerEntity.License license = new SwaggerEntity.License("MIT", "https://gitee.com/ssssssss-team/magic-api/blob/master/LICENSE"); - swaggerProvider.setInfo(new SwaggerEntity.Info(config.getDescription(), config.getVersion(), config.getTitle(), license, config.getConcat())); - swaggerProvider.setBasePath(servletContext.getContextPath()); - - - // 注册swagger.json - mapping.register(requestMappingInfo, swaggerProvider, SwaggerProvider.class.getDeclaredMethod("swaggerJson")); - - return () -> { - List resources = new ArrayList<>(); - // 追加Magic Swagger信息 - resources.add(swaggerResource(config.getName(), config.getLocation())); - Map beans = applicationContext.getBeansOfType(SwaggerResourcesProvider.class); - // 获取已定义的文档信息 - for (Map.Entry entry : beans.entrySet()) { - if (!"magicSwaggerResourcesProvider".equalsIgnoreCase(entry.getKey())) { - resources.addAll(entry.getValue().get()); - } - } - return resources; - }; - } - - /** - * 构建 SwaggerResource - * - * @param name 名字 - * @param location 位置 - */ - private SwaggerResource swaggerResource(String name, String location) { - SwaggerResource resource = new SwaggerResource(); - resource.setName(name); - resource.setLocation(location); - resource.setSwaggerVersion("2.0"); - return resource; - } -} diff --git a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/SwaggerConfig.java b/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/SwaggerConfig.java deleted file mode 100644 index 49106abd..00000000 --- a/magic-api-spring-boot-starter/src/main/java/org/ssssssss/magicapi/spring/boot/starter/SwaggerConfig.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.ssssssss.magicapi.spring.boot.starter; - -import org.springframework.boot.context.properties.NestedConfigurationProperty; -import org.ssssssss.magicapi.swagger.SwaggerEntity; - -/** - * Swagger 配置 - * - * @author mxd - */ -public class SwaggerConfig { - - /** - * 资源名称 - */ - private String name = "MagicAPI接口"; - - /** - * 资源位置 - */ - private String location = "/v2/api-docs/magic-api/swagger2.json"; - - /** - * 文档标题 - */ - private String title = "MagicAPI Swagger Docs"; - - /** - * 文档描述 - */ - private String description = "MagicAPI 接口信息"; - - @NestedConfigurationProperty - private SwaggerEntity.Concat concat = new SwaggerEntity.Concat(); - - /** - * 文档版本 - */ - private String version = "1.0"; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public SwaggerEntity.Concat getConcat() { - return concat; - } - - public void setConcat(SwaggerEntity.Concat concat) { - this.concat = concat; - } -} diff --git a/magic-editor/pom.xml b/magic-editor/pom.xml index be4ca91d..00e2ac1f 100644 --- a/magic-editor/pom.xml +++ b/magic-editor/pom.xml @@ -6,74 +6,10 @@ org.ssssssss magic-api-parent - 1.7.2 + 2.0.0-alpha.1 magic-editor jar magic-editor magic-editor - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - exec-npm-install - generate-resources - - exec - - - npm - - install - - ${basedir}/src/console - - - - exec-npm-run-build - generate-resources - - exec - - - npm - - run - build - - ${basedir}/src/console - - - - - - - - maven-resources-plugin - 3.2.0 - - - copy-resource - generate-resources - - copy-resources - - - ${basedir}/target/classes/magic-editor - - - ${basedir}/src/console/dist - - - - - - - - diff --git a/magic-editor/src/console/.eslintrc.js b/magic-editor/src/console/.eslintrc.js deleted file mode 100644 index 8a30c962..00000000 --- a/magic-editor/src/console/.eslintrc.js +++ /dev/null @@ -1,24 +0,0 @@ -module.exports = { - root: true, - env: { - node: true - }, - 'extends': [ - 'plugin:vue/essential' - // '@vue/standard' - ], - rules: { - 'no-console': 'off', - 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', - // allow async-await - 'generator-star-spacing': 'off', - 'space-before-function-paren': 0, - "vue/no-parsing-error": [2, { - "x-invalid-end-tag": false - }], - 'space-in-parens': [0, 'never'] //小括号里面要不要有空格 - }, - parserOptions: { - parser: 'babel-eslint' - } -} diff --git a/magic-editor/src/console/.gitignore b/magic-editor/src/console/.gitignore deleted file mode 100644 index 939010af..00000000 --- a/magic-editor/src/console/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -.DS_Store -node_modules -/dist -package-lock.json - - -# local env files -.env.local -.env.*.local - -# Log files -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# Editor directories and files -.idea -.vscode -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? \ No newline at end of file diff --git a/magic-editor/src/console/.prettierrc b/magic-editor/src/console/.prettierrc deleted file mode 100644 index 494a2f8d..00000000 --- a/magic-editor/src/console/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "printWidth": 300, - "tabWidth": 2, - "singleQuote": true, - "semi": false -} \ No newline at end of file diff --git a/magic-editor/src/console/README.md b/magic-editor/src/console/README.md deleted file mode 100644 index e0cb741b..00000000 --- a/magic-editor/src/console/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# magic-editor - -本项目为`magic-api`的前端页面,单独引用请[参阅文档](http://ssssssss.org) \ No newline at end of file diff --git a/magic-editor/src/console/babel.config.js b/magic-editor/src/console/babel.config.js deleted file mode 100644 index e9558405..00000000 --- a/magic-editor/src/console/babel.config.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - presets: [ - '@vue/cli-plugin-babel/preset' - ] -} diff --git a/magic-editor/src/console/package.json b/magic-editor/src/console/package.json deleted file mode 100644 index 998637d5..00000000 --- a/magic-editor/src/console/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "magic-editor", - "version": "1.7.2", - "private": false, - "description": "magic-editor for magic-api", - "main": "dist/magic-editor.umd.min.js", - "scripts": { - "serve": "vue-cli-service serve", - "build": "vue-cli-service build", - "lint": "vue-cli-service lint", - "build:lib": "vue-cli-service build --name magic-editor --target lib --entry ./src/index.js" - }, - "dependencies": { - "axios": "^0.21.0", - "core-js": "^3.6.5", - "monaco-editor": "^0.29.1", - "qs": "^6.9.4", - "vue": "^2.6.11", - "worker-loader": "^3.0.6" - }, - "devDependencies": { - "@vue/cli-plugin-babel": "~4.5.0", - "@vue/cli-plugin-eslint": "~4.5.0", - "@vue/cli-service": "~4.5.0", - "babel-eslint": "^10.1.0", - "eslint": "^6.7.2", - "eslint-plugin-vue": "^6.2.2", - "vue-template-compiler": "^2.6.11", - "webpack": "^4.44.0" - }, - "eslintConfig": { - "root": true, - "env": { - "node": true - }, - "extends": [ - "plugin:vue/essential", - "eslint:recommended" - ], - "parserOptions": { - "parser": "babel-eslint" - }, - "rules": { - "generator-star-spacing": "off", - "no-tabs": "off", - "no-unused-vars": "off", - "no-console": "off", - "no-irregular-whitespace": "off", - "no-debugger": "off" - } - }, - "files": [ - "/dist/*", - "/src/*", - "*.js" - ], - "repository": { - "type": "git", - "url": "https://gitee.com/ssssssss-team/magic-api.git" - }, - "license": "MIT", - "bugs": { - "url": "https://gitee.com/ssssssss-team/magic-api/issues" - }, - "author": "javaxd", - "homepage": "https://ssssssss.org", - "keywords": [ - "vue", - "magic-api", - "magic-editor", - "magic-api-vue" - ] -} diff --git a/magic-editor/src/console/plugins/MonacoEditorLocalesPlugin.js b/magic-editor/src/console/plugins/MonacoEditorLocalesPlugin.js deleted file mode 100644 index 45050dca..00000000 --- a/magic-editor/src/console/plugins/MonacoEditorLocalesPlugin.js +++ /dev/null @@ -1,195 +0,0 @@ -'use strict' - -var webpackVersion = require('webpack/package.json').version; -var local = null; - -function compilerHook (compilation) { - if (webpackVersion < '4') { - compilation.plugin('succeed-module', compilationHook); - } else { - compilation.hooks.succeedModule.tap('MonacoEditorLocalesPlugin', compilationHook); - } -}; - -function compilationHook (wpModule) { - if(!wpModule.resource || !wpModule.resource.indexOf || wpModule.resource.replace(/\\+/g, "/").indexOf("esm/vs/nls.js")<0){ - return; - } - - var langStr = local.getSelectLangStr(); - - var endl = "\r\n"; - var code = wpModule._source._value; - code = code.replace("export function localize", " function _ocalize"); - - code += endl + "function localize(data, message) {"; - code += endl + " if(typeof(message) === 'string'){"; - code += endl + " var idx = localize.mapLangIdx[message] || -1;"; - code += endl + " var nlsLang = localize.mapNlsLang[localize.selectLang] || {};"; - code += endl + ""; - code += endl + " if(idx in nlsLang){"; - code += endl + " message = nlsLang[idx];"; - code += endl + " }"; - if(local.options.logUnmatched){ - code += endl + " else{"; - code += endl + " console.info('unknown lang:' + message);"; - code += endl + " }"; - } - code += endl + " }"; - code += endl + ""; - code += endl + " var args = [];"; - code += endl + " for(var i = 0; i < arguments.length; ++i){"; - code += endl + " args.push(arguments[i]);"; - code += endl + " }"; - code += endl + " args[1] = message;"; - code += endl + " return _ocalize.apply(this, args);"; - code += endl + "}"; - code += endl + "localize.selectLang = " + local.getSelectLangStr() + ";"; - if(langStr.indexOf('(') >= 0){ - code += endl + "try{ localize.selectLang = eval(localize.selectLang); }catch(ex){}"; - } - code += endl + "localize.mapLangIdx = " + JSON.stringify(local.mapLangIdx) + ";"; - code += endl + "localize.mapNlsLang = " + JSON.stringify(local.lang) + ";"; - code += endl + ""; - - wpModule._source._value = code; -}; - -function MonacoEditorLocalesPlugin(options){ - this.options = { - /** - * support languages list, .eg ["de"] - * embed language base on monaco-editor@0.14.6 - * all available embed languages: de,es,fr,it,ja,ko,ru,zh-cn,zh-tw - * just add what you need to reduce the size - */ - languages: options.languages || [], - /** - * default language name, .eg "de" - * use function string to set dynamic, .eg "$.cookie('language')" - */ - defaultLanguage: options.defaultLanguage || options.languages[0] || "", - /** - * log on console if unmatched - */ - logUnmatched: options.logUnmatched || false, - /** - * self languages map, .eg {"zh-cn": {"Find": "查找", "Search": "搜索"}, "de":{}, ... } - */ - mapLanguages: options.mapLanguages || {}, - }; - - this.langIdx = 0; - this.mapLangIdx = {}; - this.lang = {}; - this.mapEmbedLangName = {}; - this.mapEmbedLangNameSelf = {}; - - this.init(); - this.initLang(); -} - -module.exports = MonacoEditorLocalesPlugin; - -MonacoEditorLocalesPlugin.prototype.apply = function(compiler) { - local = this; - - if (webpackVersion < '4') { - compiler.plugin("compilation", compilerHook); - } else { - compiler.hooks.compilation.tap('MonacoEditorLocalesPlugin', compilerHook); - } -} - -MonacoEditorLocalesPlugin.prototype.initLang = function(){ - var arr = this.options.languages; - - for(var i = 0 ;i < arr.length; ++i){ - if(!(arr[i] in this.mapEmbedLangName)) { - return; - } - - var obj = this.mapEmbedLangName[arr[i]]; - if(!obj){ - continue; - } - - var rstObj = this.lang[arr[i]] || (this.lang[arr[i]] = {}); - this.initOneLang(rstObj, this.mapEmbedLangName["en"], obj); - - - var objSelf = this.mapEmbedLangNameSelf[arr[i]]; - if(!objSelf){ - continue; - } - this.initSelfOneLang(rstObj, objSelf); - - objSelf = this.options.mapLanguages[arr[i]]; - if(!objSelf){ - continue; - } - this.initSelfOneLang(rstObj, objSelf); - } -} - -MonacoEditorLocalesPlugin.prototype.initOneLang = function(rstObj, en, langObj){ - for (var key in en) { - // console.info("aaa:", key, ",", !!en[key], ",", !!langObj); - if (en && langObj && typeof(en[key]) === "string" && typeof(langObj[key]) === "string") { - var idx = this.getLangIdx(en[key]); - rstObj[idx] = langObj[key]; - } else if (en && langObj && en[key] && langObj[key] && typeof(en[key]) === "object" && typeof(langObj[key]) === "object") { - this.initOneLang(rstObj, en[key], langObj[key]); - } - } -} - -MonacoEditorLocalesPlugin.prototype.initSelfOneLang = function(rstObj, obj){ - for (var key in obj) { - var idx = this.getLangIdx(key); - rstObj[idx] = obj[key]; - } -} - -MonacoEditorLocalesPlugin.prototype.getSelectLangStr = function(){ - var str = this.options.defaultLanguage; - str = str.replace(/'/g, "\\'"); - str = str.replace(/\r\n/g, "\\r\\n"); - str = str.replace(/\n/g, "\\n"); - return "'" + str + "'"; - // return "'(" + str + ")'"; -} - -MonacoEditorLocalesPlugin.prototype.getLangIdx = function(en){ - if(en in this.mapLangIdx){ - return this.mapLangIdx[en]; - } - - var idx = this.langIdx; - this.mapLangIdx[en] = idx; - this.langIdx++; - - return idx; -} - -MonacoEditorLocalesPlugin.prototype.init = function(){ - //{en:index} - this.mapLangIdx = {}; - - //{de:{enIndex:"deLang"}, es:{}, ...} - this.lang = { }; - - this.mapEmbedLangName = { - "zh-cn": require("./editor.main.nls.zh-cn"), - "en": require("./editor.main.nls.en") - }; - - this.mapEmbedLangNameSelf = { - "zh-cn": { - - }, - "en": { - - } - } -} \ No newline at end of file diff --git a/magic-editor/src/console/plugins/editor.main.nls.en.js b/magic-editor/src/console/plugins/editor.main.nls.en.js deleted file mode 100644 index 93a12f53..00000000 --- a/magic-editor/src/console/plugins/editor.main.nls.en.js +++ /dev/null @@ -1,1418 +0,0 @@ -/*!----------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Version: 0.21.2(67b5a8116f3c0bace36b180e524e05bb750a16d8) - * Released under the MIT license - * https://github.com/Microsoft/vscode/blob/master/LICENSE.txt - *-----------------------------------------------------------*/ - -/*--------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------*/ -module.exports = { - "vs/base/browser/ui/actionbar/actionViewItems": [ - "{0} ({1})" - ], - "vs/base/browser/ui/findinput/findInput": [ - "input" - ], - "vs/base/browser/ui/findinput/findInputCheckboxes": [ - "Match Case", - "Match Whole Word", - "Use Regular Expression" - ], - "vs/base/browser/ui/findinput/replaceInput": [ - "input", - "Preserve Case" - ], - "vs/base/browser/ui/iconLabel/iconLabelHover": [ - "Loading..." - ], - "vs/base/browser/ui/inputbox/inputBox": [ - "Error: {0}", - "Warning: {0}", - "Info: {0}", - "for history" - ], - "vs/base/browser/ui/keybindingLabel/keybindingLabel": [ - "Unbound" - ], - "vs/base/browser/ui/menu/menu": [ - "{0} ({1})" - ], - "vs/base/browser/ui/tree/abstractTree": [ - "Clear", - "Disable Filter on Type", - "Enable Filter on Type", - "No elements found", - "Matched {0} out of {1} elements" - ], - "vs/base/common/actions": [ - "(empty)" - ], - "vs/base/common/errorMessage": [ - "{0}: {1}", - "A system error occurred ({0})", - "An unknown error occurred. Please consult the log for more details.", - "An unknown error occurred. Please consult the log for more details.", - "{0} ({1} errors in total)", - "An unknown error occurred. Please consult the log for more details." - ], - "vs/base/common/keybindingLabels": [ - "Ctrl", - "Shift", - "Alt", - "Windows", - "Ctrl", - "Shift", - "Alt", - "Super", - "Control", - "Shift", - "Alt", - "Command", - "Control", - "Shift", - "Alt", - "Windows", - "Control", - "Shift", - "Alt", - "Super" - ], - "vs/base/parts/quickinput/browser/quickInput": [ - "Back", - "Press 'Enter' to confirm your input or 'Escape' to cancel", - "{0}/{1}", - "Type to narrow down results.", - "{0} Results", - "{0} Selected", - "OK", - "Custom", - "Back ({0})", - "Back" - ], - "vs/base/parts/quickinput/browser/quickInputList": [ - "Quick Input" - ], - "vs/editor/browser/controller/coreCommands": [ - "Stick to the end even when going to longer lines", - "Stick to the end even when going to longer lines", - "Removed secondary cursors" - ], - "vs/editor/browser/controller/textAreaHandler": [ - "editor", - "The editor is not accessible at this time. Press {0} for options." - ], - "vs/editor/browser/core/keybindingCancellation": [ - "Whether the editor runs a cancellable operation, e.g. like 'Peek References'" - ], - "vs/editor/browser/editorExtensions": [ - "&&Undo", - "Undo", - "&&Redo", - "Redo", - "&&Select All", - "Select All" - ], - "vs/editor/browser/widget/codeEditorWidget": [ - "The number of cursors has been limited to {0}." - ], - "vs/editor/browser/widget/diffEditorWidget": [ - "Line decoration for inserts in the diff editor.", - "Line decoration for removals in the diff editor.", - "Cannot compare files because one file is too large." - ], - "vs/editor/browser/widget/diffReview": [ - "Icon for 'Insert' in diff review.", - "Icon for 'Remove' in diff review.", - "Icon for 'Close' in diff review.", - "Close", - "no lines changed", - "1 line changed", - "{0} lines changed", - "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", - "blank", - "{0} unchanged line {1}", - "{0} original line {1} modified line {2}", - "+ {0} modified line {1}", - "- {0} original line {1}", - "Go to Next Difference", - "Go to Previous Difference" - ], - "vs/editor/browser/widget/inlineDiffMargin": [ - "Copy deleted lines", - "Copy deleted line", - "Copy deleted line ({0})", - "Revert this change", - "Copy deleted line ({0})" - ], - "vs/editor/common/config/commonEditorConfig": [ - "Editor", - "The number of spaces a tab is equal to. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.", - "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.", - "Controls whether `#editor.tabSize#` and `#editor.insertSpaces#` will be automatically detected when a file is opened based on the file contents.", - "Remove trailing auto inserted whitespace.", - "Special handling for large files to disable certain memory intensive features.", - "Controls whether completions should be computed based on words in the document.", - "Only suggest words from the active document.", - "Suggest words from all open documents of the same language.", - "Suggest words from all open documents.", - "Controls from which documents word based completions are computed.", - "Semantic highlighting enabled for all color themes.", - "Semantic highlighting disabled for all color themes.", - "Semantic highlighting is configured by the current color theme's `semanticHighlighting` setting.", - "Controls whether the semanticHighlighting is shown for the languages that support it.", - "Keep peek editors open even when double clicking their content or when hitting `Escape`.", - "Lines above this length will not be tokenized for performance reasons", - "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.", - "Maximum file size in MB for which to compute diffs. Use 0 for no limit.", - "Controls whether the diff editor shows the diff side by side or inline.", - "When enabled, the diff editor ignores changes in leading or trailing whitespace.", - "Controls whether the diff editor shows +/- indicators for added/removed changes.", - "Controls whether the editor shows CodeLens.", - "Lines will never wrap.", - "Lines will wrap at the viewport width.", - "Lines will wrap according to the `#editor.wordWrap#` setting." - ], - "vs/editor/common/config/editorOptions": [ - "The editor will use platform APIs to detect when a Screen Reader is attached.", - "The editor will be permanently optimized for usage with a Screen Reader. Word wrapping will be disabled.", - "The editor will never be optimized for usage with a Screen Reader.", - "Controls whether the editor should run in a mode where it is optimized for screen readers. Setting to on will disable word wrapping.", - "Controls whether a space character is inserted when commenting.", - "Controls if empty lines should be ignored with toggle, add or remove actions for line comments.", - "Controls whether copying without a selection copies the current line.", - "Controls whether the cursor should jump to find matches while typing.", - "Never seed search string from the editor selection.", - "Always seed search string from the editor selection, including word at cursor position.", - "Only seed search string from the editor selection.", - "Controls whether the search string in the Find Widget is seeded from the editor selection.", - "Never turn on Find in Selection automatically (default).", - "Always turn on Find in Selection automatically.", - "Turn on Find in Selection automatically when multiple lines of content are selected.", - "Controls the condition for turning on Find in Selection automatically.", - "Controls whether the Find Widget should read or modify the shared find clipboard on macOS.", - "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.", - "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.", - "Enables/Disables font ligatures ('calt' and 'liga' font features). Change this to a string for fine-grained control of the 'font-feature-settings' CSS property.", - "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.", - "Configures font ligatures or font features. Can be either a boolean to enable/disable ligatures or a string for the value of the CSS 'font-feature-settings' property.", - "Controls the font size in pixels.", - "Only \"normal\" and \"bold\" keywords or numbers between 1 and 1000 are allowed.", - "Controls the font weight. Accepts \"normal\" and \"bold\" keywords or numbers between 1 and 1000.", - "Show peek view of the results (default)", - "Go to the primary result and show a peek view", - "Go to the primary result and enable peek-less navigation to others", - "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead.", - "Controls the behavior the 'Go to Definition'-command when multiple target locations exist.", - "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist.", - "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist.", - "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist.", - "Controls the behavior the 'Go to References'-command when multiple target locations exist.", - "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.", - "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.", - "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.", - "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.", - "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.", - "Controls whether the hover is shown.", - "Controls the delay in milliseconds after which the hover is shown.", - "Controls whether the hover should remain visible when mouse is moved over it.", - "Enables the code action lightbulb in the editor.", - "Enables the inlay hints in the editor.", - "Controls font size of inlay hints in the editor. A default of 90% of `#editor.fontSize#` is used when the configured value is less than `5` or greater than the editor font size.", - "Controls font family of inlay hints in the editor. When set to empty, the `#editor.fontFamily#` is used.", - "Controls the line height. \n - Use 0 to automatically compute the line height from the font size.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values.", - "Controls whether the minimap is shown.", - "The minimap has the same size as the editor contents (and might scroll).", - "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling).", - "The minimap will shrink as necessary to never be larger than the editor (no scrolling).", - "Controls the size of the minimap.", - "Controls the side where to render the minimap.", - "Controls when the minimap slider is shown.", - "Scale of content drawn in the minimap: 1, 2 or 3.", - "Render the actual characters on a line as opposed to color blocks.", - "Limit the width of the minimap to render at most a certain number of columns.", - "Controls the amount of space between the top edge of the editor and the first line.", - "Controls the amount of space between the bottom edge of the editor and the last line.", - "Enables a pop-up that shows parameter documentation and type information as you type.", - "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.", - "Enable quick suggestions inside strings.", - "Enable quick suggestions inside comments.", - "Enable quick suggestions outside of strings and comments.", - "Controls whether suggestions should automatically show up while typing.", - "Line numbers are not rendered.", - "Line numbers are rendered as absolute number.", - "Line numbers are rendered as distance in lines to cursor position.", - "Line numbers are rendered every 10 lines.", - "Controls the display of line numbers.", - "Number of monospace characters at which this editor ruler will render.", - "Color of this editor ruler.", - "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.", - "The vertical scrollbar will be visible only when necessary.", - "The vertical scrollbar will always be visible.", - "The vertical scrollbar will always be hidden.", - "Controls the visibility of the vertical scrollbar.", - "The horizontal scrollbar will be visible only when necessary.", - "The horizontal scrollbar will always be visible.", - "The horizontal scrollbar will always be hidden.", - "Controls the visibility of the horizontal scrollbar.", - "The width of the vertical scrollbar.", - "The height of the horizontal scrollbar.", - "Controls whether clicks scroll by page or jump to click position.", - "Controls whether to automatically show inline suggestions in the editor.", - "Controls whether bracket pair colorization is enabled or not. Use 'workbench.colorCustomizations' to override the bracket highlight colors.", - "Controls whether bracket pair guides are enabled or not.", - "Controls whether the editor should render indent guides.", - "Controls whether the editor should highlight the active indent guide.", - "Insert suggestion without overwriting text right of the cursor.", - "Insert suggestion and overwrite text right of the cursor.", - "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.", - "Controls whether filtering and sorting suggestions accounts for small typos.", - "Controls whether sorting favors words that appear close to the cursor.", - "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).", - "Controls whether an active snippet prevents quick suggestions.", - "Controls whether to show or hide icons in suggestions.", - "Controls the visibility of the status bar at the bottom of the suggest widget.", - "Controls whether to preview the suggestion outcome in the editor.", - "Controls whether suggest details show inline with the label or only in the details widget", - "This setting is deprecated. The suggest widget can now be resized.", - "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.", - "When enabled IntelliSense shows `method`-suggestions.", - "When enabled IntelliSense shows `function`-suggestions.", - "When enabled IntelliSense shows `constructor`-suggestions.", - "When enabled IntelliSense shows `deprecated`-suggestions.", - "When enabled IntelliSense shows `field`-suggestions.", - "When enabled IntelliSense shows `variable`-suggestions.", - "When enabled IntelliSense shows `class`-suggestions.", - "When enabled IntelliSense shows `struct`-suggestions.", - "When enabled IntelliSense shows `interface`-suggestions.", - "When enabled IntelliSense shows `module`-suggestions.", - "When enabled IntelliSense shows `property`-suggestions.", - "When enabled IntelliSense shows `event`-suggestions.", - "When enabled IntelliSense shows `operator`-suggestions.", - "When enabled IntelliSense shows `unit`-suggestions.", - "When enabled IntelliSense shows `value`-suggestions.", - "When enabled IntelliSense shows `constant`-suggestions.", - "When enabled IntelliSense shows `enum`-suggestions.", - "When enabled IntelliSense shows `enumMember`-suggestions.", - "When enabled IntelliSense shows `keyword`-suggestions.", - "When enabled IntelliSense shows `text`-suggestions.", - "When enabled IntelliSense shows `color`-suggestions.", - "When enabled IntelliSense shows `file`-suggestions.", - "When enabled IntelliSense shows `reference`-suggestions.", - "When enabled IntelliSense shows `customcolor`-suggestions.", - "When enabled IntelliSense shows `folder`-suggestions.", - "When enabled IntelliSense shows `typeParameter`-suggestions.", - "When enabled IntelliSense shows `snippet`-suggestions.", - "When enabled IntelliSense shows `user`-suggestions.", - "When enabled IntelliSense shows `issues`-suggestions.", - "Whether leading and trailing whitespace should always be selected.", - "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.", - "Only accept a suggestion with `Enter` when it makes a textual change.", - "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.", - "Controls the number of lines in the editor that can be read out by a screen reader at once. When we detect a screen reader we automatically set the default to be 500. Warning: this has a performance implication for numbers larger than the default.", - "Editor content", - "Use language configurations to determine when to autoclose brackets.", - "Autoclose brackets only when the cursor is to the left of whitespace.", - "Controls whether the editor should automatically close brackets after the user adds an opening bracket.", - "Remove adjacent closing quotes or brackets only if they were automatically inserted.", - "Controls whether the editor should remove adjacent closing quotes or brackets when deleting.", - "Type over closing quotes or brackets only if they were automatically inserted.", - "Controls whether the editor should type over closing quotes or brackets.", - "Use language configurations to determine when to autoclose quotes.", - "Autoclose quotes only when the cursor is to the left of whitespace.", - "Controls whether the editor should automatically close quotes after the user adds an opening quote.", - "The editor will not insert indentation automatically.", - "The editor will keep the current line's indentation.", - "The editor will keep the current line's indentation and honor language defined brackets.", - "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages.", - "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages.", - "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.", - "Use language configurations to determine when to automatically surround selections.", - "Surround with quotes but not brackets.", - "Surround with brackets but not quotes.", - "Controls whether the editor should automatically surround selections when typing quotes or brackets.", - "Emulate selection behavior of tab characters when using spaces for indentation. Selection will stick to tab stops.", - "Controls whether the editor shows CodeLens.", - "Controls the font family for CodeLens.", - "Controls the font size in pixels for CodeLens. When set to `0`, the 90% of `#editor.fontSize#` is used.", - "Controls whether the editor should render the inline color decorators and color picker.", - "Enable that the selection with the mouse and keys is doing column selection.", - "Controls whether syntax highlighting should be copied into the clipboard.", - "Control the cursor animation style.", - "Controls whether the smooth caret animation should be enabled.", - "Controls the cursor style.", - "Controls the minimal number of visible leading and trailing lines surrounding the cursor. Known as 'scrollOff' or 'scrollOffset' in some other editors.", - "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API.", - "`cursorSurroundingLines` is enforced always.", - "Controls when `cursorSurroundingLines` should be enforced.", - "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.", - "Controls whether the editor should allow moving selections via drag and drop.", - "Scrolling speed multiplier when pressing `Alt`.", - "Controls whether the editor has code folding enabled.", - "Use a language-specific folding strategy if available, else the indentation-based one.", - "Use the indentation-based folding strategy.", - "Controls the strategy for computing folding ranges.", - "Controls whether the editor should highlight folded ranges.", - "Controls whether the editor automatically collapses import ranges.", - "Controls whether clicking on the empty content after a folded line will unfold the line.", - "Controls the font family.", - "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.", - "Controls whether the editor should automatically format the line after typing.", - "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.", - "Controls whether the cursor should be hidden in the overview ruler.", - "Controls the letter spacing in pixels.", - "Controls whether the editor has linked editing enabled. Depending on the language, related symbols, e.g. HTML tags, are updated while editing.", - "Controls whether the editor should detect links and make them clickable.", - "Highlight matching brackets.", - "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.", - "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.", - "Merge multiple cursors when they are overlapping.", - "Maps to `Control` on Windows and Linux and to `Command` on macOS.", - "Maps to `Alt` on Windows and Linux and to `Option` on macOS.", - "The modifier to be used to add multiple cursors with the mouse. The Go To Definition and Open Link mouse gestures will adapt such that they do not conflict with the multicursor modifier. [Read more](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).", - "Each cursor pastes a single line of the text.", - "Each cursor pastes the full text.", - "Controls pasting when the line count of the pasted text matches the cursor count.", - "Controls whether the editor should highlight semantic symbol occurrences.", - "Controls whether a border should be drawn around the overview ruler.", - "Focus the tree when opening peek", - "Focus the editor when opening peek", - "Controls whether to focus the inline editor or the tree in the peek widget.", - "Controls whether the Go to Definition mouse gesture always opens the peek widget.", - "Controls the delay in milliseconds after which quick suggestions will show up.", - "Controls whether the editor auto renames on type.", - "Deprecated, use `editor.linkedEditing` instead.", - "Controls whether the editor should render control characters.", - "Render last line number when the file ends with a newline.", - "Highlights both the gutter and the current line.", - "Controls how the editor should render the current line highlight.", - "Controls if the editor should render the current line highlight only when the editor is focused.", - "Render whitespace characters except for single spaces between words.", - "Render whitespace characters only on selected text.", - "Render only trailing whitespace characters.", - "Controls how the editor should render whitespace characters.", - "Controls whether selections should have rounded corners.", - "Controls the number of extra characters beyond which the editor will scroll horizontally.", - "Controls whether the editor will scroll beyond the last line.", - "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.", - "Controls whether the Linux primary clipboard should be supported.", - "Controls whether the editor should highlight matches similar to the selection.", - "Always show the folding controls.", - "Only show the folding controls when the mouse is over the gutter.", - "Controls when the folding controls on the gutter are shown.", - "Controls fading out of unused code.", - "Controls strikethrough deprecated variables.", - "Show snippet suggestions on top of other suggestions.", - "Show snippet suggestions below other suggestions.", - "Show snippets suggestions with other suggestions.", - "Do not show snippet suggestions.", - "Controls whether snippets are shown with other suggestions and how they are sorted.", - "Controls whether the editor will scroll using an animation.", - "Font size for the suggest widget. When set to `0`, the value of `#editor.fontSize#` is used.", - "Line height for the suggest widget. When set to `0`, the value of `#editor.lineHeight#` is used. The minimum value is 8.", - "Controls whether suggestions should automatically show up when typing trigger characters.", - "Always select the first suggestion.", - "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently.", - "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`.", - "Controls how suggestions are pre-selected when showing the suggest list.", - "Tab complete will insert the best matching suggestion when pressing tab.", - "Disable tab completions.", - "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.", - "Enables tab completions.", - "Unusual line terminators are automatically removed.", - "Unusual line terminators are ignored.", - "Unusual line terminators prompt to be removed.", - "Remove unusual line terminators that might cause problems.", - "Inserting and deleting whitespace follows tab stops.", - "Characters that will be used as word separators when doing word related navigations or operations.", - "Lines will never wrap.", - "Lines will wrap at the viewport width.", - "Lines will wrap at `#editor.wordWrapColumn#`.", - "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`.", - "Controls how lines should wrap.", - "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.", - "No indentation. Wrapped lines begin at column 1.", - "Wrapped lines get the same indentation as the parent.", - "Wrapped lines get +1 indentation toward the parent.", - "Wrapped lines get +2 indentation toward the parent.", - "Controls the indentation of wrapped lines.", - "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width.", - "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.", - "Controls the algorithm that computes wrapping points." - ], - "vs/editor/common/editorContextKeys": [ - "Whether the editor text has focus (cursor is blinking)", - "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)", - "Whether an editor or a rich text input has focus (cursor is blinking)", - "Whether the editor is read only", - "Whether the context is a diff editor", - "Whether `editor.columnSelection` is enabled", - "Whether the editor has text selected", - "Whether the editor has multiple selections", - "Whether `Tab` will move focus out of the editor", - "Whether the editor hover is visible", - "Whether the editor is part of a larger editor (e.g. notebooks)", - "The language identifier of the editor", - "Whether the editor has a completion item provider", - "Whether the editor has a code actions provider", - "Whether the editor has a code lens provider", - "Whether the editor has a definition provider", - "Whether the editor has a declaration provider", - "Whether the editor has an implementation provider", - "Whether the editor has a type definition provider", - "Whether the editor has a hover provider", - "Whether the editor has a document highlight provider", - "Whether the editor has a document symbol provider", - "Whether the editor has a reference provider", - "Whether the editor has a rename provider", - "Whether the editor has a signature help provider", - "Whether the editor has an inline hints provider", - "Whether the editor has a document formatting provider", - "Whether the editor has a document selection formatting provider", - "Whether the editor has multiple document formatting providers", - "Whether the editor has multiple document selection formatting providers" - ], - "vs/editor/common/model/editStack": [ - "Typing" - ], - "vs/editor/common/modes/modesRegistry": [ - "Plain Text" - ], - "vs/editor/common/standaloneStrings": [ - "No selection", - "Line {0}, Column {1} ({2} selected)", - "Line {0}, Column {1}", - "{0} selections ({1} characters selected)", - "{0} selections", - "Now changing the setting `accessibilitySupport` to 'on'.", - "Now opening the Editor Accessibility documentation page.", - " in a read-only pane of a diff editor.", - " in a pane of a diff editor.", - " in a read-only code editor", - " in a code editor", - "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.", - "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.", - "The editor is configured to be optimized for usage with a Screen Reader.", - "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.", - "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.", - "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.", - "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.", - "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.", - "Press Command+H now to open a browser window with more information related to editor accessibility.", - "Press Control+H now to open a browser window with more information related to editor accessibility.", - "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.", - "Show Accessibility Help", - "Developer: Inspect Tokens", - "Go to Line/Column...", - "Show all Quick Access Providers", - "Command Palette", - "Show And Run Commands", - "Go to Symbol...", - "Go to Symbol by Category...", - "Editor content", - "Press Alt+F1 for Accessibility Options.", - "Toggle High Contrast Theme", - "Made {0} edits in {1} files" - ], - "vs/editor/common/view/editorColorRegistry": [ - "Background color for the highlight of line at the cursor position.", - "Background color for the border around the line at the cursor position.", - "Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.", - "Background color of the border around highlighted ranges.", - "Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations.", - "Background color of the border around highlighted symbols.", - "Color of the editor cursor.", - "The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.", - "Color of whitespace characters in the editor.", - "Color of the editor indentation guides.", - "Color of the active editor indentation guides.", - "Color of editor line numbers.", - "Color of editor active line number", - "Id is deprecated. Use 'editorLineNumber.activeForeground' instead.", - "Color of editor active line number", - "Color of the editor rulers.", - "Foreground color of editor CodeLens", - "Background color behind matching brackets", - "Color for matching brackets boxes", - "Color of the overview ruler border.", - "Background color of the editor overview ruler. Only used when the minimap is enabled and placed on the right side of the editor.", - "Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.", - "Border color of unnecessary (unused) source code in the editor.", - "Opacity of unnecessary (unused) source code in the editor. For example, \"#000000c0\" will render the code with 75% opacity. For high contrast themes, use the 'editorUnnecessaryCode.border' theme color to underline unnecessary code instead of fading it out.", - "Border color of ghost text in the editor.", - "Foreground color of the ghost text in the editor.", - "Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations.", - "Overview ruler marker color for errors.", - "Overview ruler marker color for warnings.", - "Overview ruler marker color for infos.", - "Foreground color of brackets (1). Requires enabling bracket pair colorization.", - "Foreground color of brackets (2). Requires enabling bracket pair colorization.", - "Foreground color of brackets (3). Requires enabling bracket pair colorization.", - "Foreground color of brackets (4). Requires enabling bracket pair colorization.", - "Foreground color of brackets (5). Requires enabling bracket pair colorization.", - "Foreground color of brackets (6). Requires enabling bracket pair colorization.", - "Foreground color of unexpected brackets." - ], - "vs/editor/contrib/anchorSelect/anchorSelect": [ - "Selection Anchor", - "Anchor set at {0}:{1}", - "Set Selection Anchor", - "Go to Selection Anchor", - "Select from Anchor to Cursor", - "Cancel Selection Anchor" - ], - "vs/editor/contrib/bracketMatching/bracketMatching": [ - "Overview ruler marker color for matching brackets.", - "Go to Bracket", - "Select to Bracket", - "Go to &&Bracket" - ], - "vs/editor/contrib/caretOperations/caretOperations": [ - "Move Selected Text Left", - "Move Selected Text Right" - ], - "vs/editor/contrib/caretOperations/transpose": [ - "Transpose Letters" - ], - "vs/editor/contrib/clipboard/clipboard": [ - "Cu&&t", - "Cut", - "Cut", - "Cut", - "&&Copy", - "Copy", - "Copy", - "Copy", - "Copy As", - "Copy As", - "&&Paste", - "Paste", - "Paste", - "Paste", - "Copy With Syntax Highlighting" - ], - "vs/editor/contrib/codeAction/codeActionCommands": [ - "Kind of the code action to run.", - "Controls when the returned actions are applied.", - "Always apply the first returned code action.", - "Apply the first returned code action if it is the only one.", - "Do not apply the returned code actions.", - "Controls if only preferred code actions should be returned.", - "An unknown error occurred while applying the code action", - "Quick Fix...", - "No code actions available", - "No preferred code actions for '{0}' available", - "No code actions for '{0}' available", - "No preferred code actions available", - "No code actions available", - "Refactor...", - "No preferred refactorings for '{0}' available", - "No refactorings for '{0}' available", - "No preferred refactorings available", - "No refactorings available", - "Source Action...", - "No preferred source actions for '{0}' available", - "No source actions for '{0}' available", - "No preferred source actions available", - "No source actions available", - "Organize Imports", - "No organize imports action available", - "Fix All", - "No fix all action available", - "Auto Fix...", - "No auto fixes available" - ], - "vs/editor/contrib/codeAction/lightBulbWidget": [ - "Show Code Actions. Preferred Quick Fix Available ({0})", - "Show Code Actions ({0})", - "Show Code Actions" - ], - "vs/editor/contrib/codelens/codelensController": [ - "Show CodeLens Commands For Current Line" - ], - "vs/editor/contrib/comment/comment": [ - "Toggle Line Comment", - "&&Toggle Line Comment", - "Add Line Comment", - "Remove Line Comment", - "Toggle Block Comment", - "Toggle &&Block Comment" - ], - "vs/editor/contrib/contextmenu/contextmenu": [ - "Show Editor Context Menu" - ], - "vs/editor/contrib/cursorUndo/cursorUndo": [ - "Cursor Undo", - "Cursor Redo" - ], - "vs/editor/contrib/find/findController": [ - "Find", - "&&Find", - "Find With Selection", - "Find Next", - "Find Previous", - "Find Next Selection", - "Find Previous Selection", - "Replace", - "&&Replace" - ], - "vs/editor/contrib/find/findWidget": [ - "Icon for 'Find in Selection' in the editor find widget.", - "Icon to indicate that the editor find widget is collapsed.", - "Icon to indicate that the editor find widget is expanded.", - "Icon for 'Replace' in the editor find widget.", - "Icon for 'Replace All' in the editor find widget.", - "Icon for 'Find Previous' in the editor find widget.", - "Icon for 'Find Next' in the editor find widget.", - "Find", - "Find", - "Previous Match", - "Next Match", - "Find in Selection", - "Close", - "Replace", - "Replace", - "Replace", - "Replace All", - "Toggle Replace", - "Only the first {0} results are highlighted, but all find operations work on the entire text.", - "{0} of {1}", - "No results", - "{0} found", - "{0} found for '{1}'", - "{0} found for '{1}', at {2}", - "{0} found for '{1}'", - "Ctrl+Enter now inserts line break instead of replacing all. You can modify the keybinding for editor.action.replaceAll to override this behavior." - ], - "vs/editor/contrib/folding/folding": [ - "Unfold", - "Unfold Recursively", - "Fold", - "Toggle Fold", - "Fold Recursively", - "Fold All Block Comments", - "Fold All Regions", - "Unfold All Regions", - "Fold All Regions Except Selected", - "Unfold All Regions Except Selected", - "Fold All", - "Unfold All", - "Go to Parent Fold", - "Go to Previous Folding Range", - "Go to Next Folding Range", - "Fold Level {0}", - "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations.", - "Color of the folding control in the editor gutter." - ], - "vs/editor/contrib/folding/foldingDecorations": [ - "Icon for expanded ranges in the editor glyph margin.", - "Icon for collapsed ranges in the editor glyph margin." - ], - "vs/editor/contrib/fontZoom/fontZoom": [ - "Editor Font Zoom In", - "Editor Font Zoom Out", - "Editor Font Zoom Reset" - ], - "vs/editor/contrib/format/format": [ - "Made 1 formatting edit on line {0}", - "Made {0} formatting edits on line {1}", - "Made 1 formatting edit between lines {0} and {1}", - "Made {0} formatting edits between lines {1} and {2}" - ], - "vs/editor/contrib/format/formatActions": [ - "Format Document", - "Format Selection" - ], - "vs/editor/contrib/gotoError/gotoError": [ - "Go to Next Problem (Error, Warning, Info)", - "Icon for goto next marker.", - "Go to Previous Problem (Error, Warning, Info)", - "Icon for goto previous marker.", - "Go to Next Problem in Files (Error, Warning, Info)", - "Next &&Problem", - "Go to Previous Problem in Files (Error, Warning, Info)", - "Previous &&Problem" - ], - "vs/editor/contrib/gotoError/gotoErrorWidget": [ - "Error", - "Warning", - "Info", - "Hint", - "{0} at {1}. ", - "{0} of {1} problems", - "{0} of {1} problem", - "Editor marker navigation widget error color.", - "Editor marker navigation widget error heading background.", - "Editor marker navigation widget warning color.", - "Editor marker navigation widget warning heading background.", - "Editor marker navigation widget info color.", - "Editor marker navigation widget info heading background.", - "Editor marker navigation widget background." - ], - "vs/editor/contrib/gotoSymbol/goToCommands": [ - "Peek", - "Definitions", - "No definition found for '{0}'", - "No definition found", - "Go to Definition", - "Open Definition to the Side", - "Peek Definition", - "Declarations", - "No declaration found for '{0}'", - "No declaration found", - "Go to Declaration", - "No declaration found for '{0}'", - "No declaration found", - "Peek Declaration", - "Type Definitions", - "No type definition found for '{0}'", - "No type definition found", - "Go to Type Definition", - "Peek Type Definition", - "Implementations", - "No implementation found for '{0}'", - "No implementation found", - "Go to Implementations", - "Peek Implementations", - "No references found for '{0}'", - "No references found", - "Go to References", - "References", - "Peek References", - "References", - "Go To Any Symbol", - "Locations", - "No results for '{0}'", - "References", - "Go to &&Definition", - "Go to &&Declaration", - "Go to &&Type Definition", - "Go to &&Implementations", - "Go to &&References" - ], - "vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition": [ - "Click to show {0} definitions." - ], - "vs/editor/contrib/gotoSymbol/peek/referencesController": [ - "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'", - "Loading...", - "{0} ({1})" - ], - "vs/editor/contrib/gotoSymbol/peek/referencesTree": [ - "{0} references", - "{0} reference", - "References" - ], - "vs/editor/contrib/gotoSymbol/peek/referencesWidget": [ - "no preview available", - "No results", - "References" - ], - "vs/editor/contrib/gotoSymbol/referencesModel": [ - "symbol in {0} on line {1} at column {2}", - "symbol in {0} on line {1} at column {2}, {3}", - "1 symbol in {0}, full path {1}", - "{0} symbols in {1}, full path {2}", - "No results found", - "Found 1 symbol in {0}", - "Found {0} symbols in {1}", - "Found {0} symbols in {1} files" - ], - "vs/editor/contrib/gotoSymbol/symbolNavigation": [ - "Whether there are symbol locations that can be navigated via keyboard-only.", - "Symbol {0} of {1}, {2} for next", - "Symbol {0} of {1}" - ], - "vs/editor/contrib/hover/hover": [ - "Show Hover", - "Show Definition Preview Hover" - ], - "vs/editor/contrib/hover/markdownHoverParticipant": [ - "Loading...", - "Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`." - ], - "vs/editor/contrib/hover/markerHoverParticipant": [ - "View Problem", - "No quick fixes available", - "Checking for quick fixes...", - "No quick fixes available", - "Quick Fix..." - ], - "vs/editor/contrib/inPlaceReplace/inPlaceReplace": [ - "Replace with Previous Value", - "Replace with Next Value" - ], - "vs/editor/contrib/indentation/indentation": [ - "Convert Indentation to Spaces", - "Convert Indentation to Tabs", - "Configured Tab Size", - "Select Tab Size for Current File", - "Indent Using Tabs", - "Indent Using Spaces", - "Detect Indentation from Content", - "Reindent Lines", - "Reindent Selected Lines" - ], - "vs/editor/contrib/inlineCompletions/ghostTextController": [ - "Whether an inline suggestion is visible", - "Whether the inline suggestion starts with whitespace", - "Show Next Inline Suggestion", - "Show Previous Inline Suggestion", - "Trigger Inline Suggestion" - ], - "vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant": [ - "Next", - "Previous", - "Accept", - "Suggestion:" - ], - "vs/editor/contrib/linesOperations/linesOperations": [ - "Copy Line Up", - "&&Copy Line Up", - "Copy Line Down", - "Co&&py Line Down", - "Duplicate Selection", - "&&Duplicate Selection", - "Move Line Up", - "Mo&&ve Line Up", - "Move Line Down", - "Move &&Line Down", - "Sort Lines Ascending", - "Sort Lines Descending", - "Trim Trailing Whitespace", - "Delete Line", - "Indent Line", - "Outdent Line", - "Insert Line Above", - "Insert Line Below", - "Delete All Left", - "Delete All Right", - "Join Lines", - "Transpose characters around the cursor", - "Transform to Uppercase", - "Transform to Lowercase", - "Transform to Title Case", - "Transform to Snake Case" - ], - "vs/editor/contrib/linkedEditing/linkedEditing": [ - "Start Linked Editing", - "Background color when the editor auto renames on type." - ], - "vs/editor/contrib/links/links": [ - "Execute command", - "Follow link", - "cmd + click", - "ctrl + click", - "option + click", - "alt + click", - "Execute command {0}", - "Failed to open this link because it is not well-formed: {0}", - "Failed to open this link because its target is missing.", - "Open Link" - ], - "vs/editor/contrib/message/messageController": [ - "Whether the editor is currently showing an inline message", - "Cannot edit in read-only editor" - ], - "vs/editor/contrib/multicursor/multicursor": [ - "Cursor added: {0}", - "Cursors added: {0}", - "Add Cursor Above", - "&&Add Cursor Above", - "Add Cursor Below", - "A&&dd Cursor Below", - "Add Cursors to Line Ends", - "Add C&&ursors to Line Ends", - "Add Cursors To Bottom", - "Add Cursors To Top", - "Add Selection To Next Find Match", - "Add &&Next Occurrence", - "Add Selection To Previous Find Match", - "Add P&&revious Occurrence", - "Move Last Selection To Next Find Match", - "Move Last Selection To Previous Find Match", - "Select All Occurrences of Find Match", - "Select All &&Occurrences", - "Change All Occurrences" - ], - "vs/editor/contrib/parameterHints/parameterHints": [ - "Trigger Parameter Hints" - ], - "vs/editor/contrib/parameterHints/parameterHintsWidget": [ - "Icon for show next parameter hint.", - "Icon for show previous parameter hint.", - "{0}, hint" - ], - "vs/editor/contrib/peekView/peekView": [ - "Whether the current code editor is embedded inside peek", - "Close", - "Background color of the peek view title area.", - "Color of the peek view title.", - "Color of the peek view title info.", - "Color of the peek view borders and arrow.", - "Background color of the peek view result list.", - "Foreground color for line nodes in the peek view result list.", - "Foreground color for file nodes in the peek view result list.", - "Background color of the selected entry in the peek view result list.", - "Foreground color of the selected entry in the peek view result list.", - "Background color of the peek view editor.", - "Background color of the gutter in the peek view editor.", - "Match highlight color in the peek view result list.", - "Match highlight color in the peek view editor.", - "Match highlight border in the peek view editor." - ], - "vs/editor/contrib/quickAccess/gotoLineQuickAccess": [ - "Open a text editor first to go to a line.", - "Go to line {0} and character {1}.", - "Go to line {0}.", - "Current Line: {0}, Character: {1}. Type a line number between 1 and {2} to navigate to.", - "Current Line: {0}, Character: {1}. Type a line number to navigate to." - ], - "vs/editor/contrib/quickAccess/gotoSymbolQuickAccess": [ - "To go to a symbol, first open a text editor with symbol information.", - "The active text editor does not provide symbol information.", - "No matching editor symbols", - "No editor symbols", - "Open to the Side", - "Open to the Bottom", - "symbols ({0})", - "properties ({0})", - "methods ({0})", - "functions ({0})", - "constructors ({0})", - "variables ({0})", - "classes ({0})", - "structs ({0})", - "events ({0})", - "operators ({0})", - "interfaces ({0})", - "namespaces ({0})", - "packages ({0})", - "type parameters ({0})", - "modules ({0})", - "properties ({0})", - "enumerations ({0})", - "enumeration members ({0})", - "strings ({0})", - "files ({0})", - "arrays ({0})", - "numbers ({0})", - "booleans ({0})", - "objects ({0})", - "keys ({0})", - "fields ({0})", - "constants ({0})" - ], - "vs/editor/contrib/rename/rename": [ - "No result.", - "An unknown error occurred while resolving rename location", - "Renaming '{0}'", - "Renaming {0}", - "Successfully renamed '{0}' to '{1}'. Summary: {2}", - "Rename failed to apply edits", - "Rename failed to compute edits", - "Rename Symbol", - "Enable/disable the ability to preview changes before renaming" - ], - "vs/editor/contrib/rename/renameInputField": [ - "Whether the rename input widget is visible", - "Rename input. Type new name and press Enter to commit.", - "{0} to Rename, {1} to Preview" - ], - "vs/editor/contrib/smartSelect/smartSelect": [ - "Expand Selection", - "&&Expand Selection", - "Shrink Selection", - "&&Shrink Selection" - ], - "vs/editor/contrib/snippet/snippetController2": [ - "Whether the editor in current in snippet mode", - "Whether there is a next tab stop when in snippet mode", - "Whether there is a previous tab stop when in snippet mode" - ], - "vs/editor/contrib/snippet/snippetVariables": [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sun", - "Mon", - "Tue", - "Wed", - "Thu", - "Fri", - "Sat", - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" - ], - "vs/editor/contrib/suggest/suggest": [ - "Whether suggestion are visible", - "Whether suggestion details are visible", - "Whether there are multiple suggestions to pick from", - "Whether inserting the current suggestion yields in a change or has everything already been typed", - "Whether suggestions are inserted when pressing Enter", - "Whether the current suggestion has insert and replace behaviour", - "Whether the default behaviour is to insert or replace", - "Whether the current suggestion supports to resolve further details" - ], - "vs/editor/contrib/suggest/suggestController": [ - "Accepting '{0}' made {1} additional edits", - "Trigger Suggest", - "Insert", - "Insert", - "Replace", - "Replace", - "Insert", - "show less", - "show more", - "Reset Suggest Widget Size" - ], - "vs/editor/contrib/suggest/suggestWidget": [ - "Background color of the suggest widget.", - "Border color of the suggest widget.", - "Foreground color of the suggest widget.", - "Foreground color of the selected entry in the suggest widget.", - "Icon foreground color of the selected entry in the suggest widget.", - "Background color of the selected entry in the suggest widget.", - "Color of the match highlights in the suggest widget.", - "Color of the match highlights in the suggest widget when an item is focused.", - "Loading...", - "No suggestions.", - "{0}, docs: {1}", - "Suggest" - ], - "vs/editor/contrib/suggest/suggestWidgetDetails": [ - "Close", - "Loading..." - ], - "vs/editor/contrib/suggest/suggestWidgetRenderer": [ - "Icon for more information in the suggest widget.", - "Read More" - ], - "vs/editor/contrib/suggest/suggestWidgetStatus": [ - "{0} ({1})" - ], - "vs/editor/contrib/symbolIcons/symbolIcons": [ - "The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget.", - "The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget." - ], - "vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode": [ - "Toggle Tab Key Moves Focus", - "Pressing Tab will now move focus to the next focusable element", - "Pressing Tab will now insert the tab character" - ], - "vs/editor/contrib/tokenization/tokenization": [ - "Developer: Force Retokenize" - ], - "vs/editor/contrib/unusualLineTerminators/unusualLineTerminators": [ - "Unusual Line Terminators", - "Detected unusual line terminators", - "The file '{0}' contains one or more unusual line terminator characters, like Line Separator (LS) or Paragraph Separator (PS).\n\nIt is recommended to remove them from the file. This can be configured via `editor.unusualLineTerminators`.", - "Remove Unusual Line Terminators", - "Ignore" - ], - "vs/editor/contrib/wordHighlighter/wordHighlighter": [ - "Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations.", - "Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations.", - "Border color of a symbol during read-access, like reading a variable.", - "Border color of a symbol during write-access, like writing to a variable.", - "Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations.", - "Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations.", - "Go to Next Symbol Highlight", - "Go to Previous Symbol Highlight", - "Trigger Symbol Highlight" - ], - "vs/editor/contrib/wordOperations/wordOperations": [ - "Delete Word" - ], - "vs/platform/actions/browser/menuEntryActionViewItem": [ - "{0} ({1})", - "{0} ({1})" - ], - "vs/platform/configuration/common/configurationRegistry": [ - "Default Language Configuration Overrides", - "Configure editor settings to be overridden for a language.", - "This setting does not support per-language configuration.", - "Cannot register an empty property", - "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", - "Cannot register '{0}'. This property is already registered." - ], - "vs/platform/contextkey/browser/contextKeyService": [ - "A command that returns information about context keys" - ], - "vs/platform/contextkey/common/contextkeys": [ - "Whether the operating system is Windows" - ], - "vs/platform/keybinding/common/abstractKeybindingService": [ - "({0}) was pressed. Waiting for second key of chord...", - "The key combination ({0}, {1}) is not a command." - ], - "vs/platform/list/browser/listService": [ - "Workbench", - "Maps to `Control` on Windows and Linux and to `Command` on macOS.", - "Maps to `Alt` on Windows and Linux and to `Option` on macOS.", - "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.", - "Controls how to open items in trees and lists using the mouse (if supported). Note that some trees and lists might choose to ignore this setting if it is not applicable.", - "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.", - "Controls tree indentation in pixels.", - "Controls whether the tree should render indent guides.", - "Controls whether lists and trees have smooth scrolling.", - "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.", - "Scrolling speed multiplier when pressing `Alt`.", - "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes.", - "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements.", - "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.", - "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter.", - "Controls whether keyboard navigation in lists and trees is automatically triggered simply by typing. If set to `false`, keyboard navigation is only triggered when executing the `list.toggleKeyboardNavigation` command, for which you can assign a keyboard shortcut.", - "Controls how tree folders are expanded when clicking the folder names. Note that some trees and lists might choose to ignore this setting if it is not applicable." - ], - "vs/platform/markers/common/markers": [ - "Error", - "Warning", - "Info" - ], - "vs/platform/quickinput/browser/commandsQuickAccess": [ - "{0}, {1}", - "recently used", - "other commands", - "Command '{0}' resulted in an error ({1})" - ], - "vs/platform/quickinput/browser/helpQuickAccess": [ - "global commands", - "editor commands", - "{0}, {1}" - ], - "vs/platform/theme/common/colorRegistry": [ - "Overall foreground color. This color is only used if not overridden by a component.", - "Overall foreground color for error messages. This color is only used if not overridden by a component.", - "The default color for icons in the workbench.", - "Overall border color for focused elements. This color is only used if not overridden by a component.", - "An extra border around elements to separate them from others for greater contrast.", - "An extra border around active elements to separate them from others for greater contrast.", - "Foreground color for links in text.", - "Foreground color for links in text when clicked on and on mouse hover.", - "Background color for code blocks in text.", - "Shadow color of widgets such as find/replace inside the editor.", - "Input box background.", - "Input box foreground.", - "Input box border.", - "Border color of activated options in input fields.", - "Background color of activated options in input fields.", - "Foreground color of activated options in input fields.", - "Input validation background color for information severity.", - "Input validation foreground color for information severity.", - "Input validation border color for information severity.", - "Input validation background color for warning severity.", - "Input validation foreground color for warning severity.", - "Input validation border color for warning severity.", - "Input validation background color for error severity.", - "Input validation foreground color for error severity.", - "Input validation border color for error severity.", - "Dropdown background.", - "Dropdown foreground.", - "Button foreground color.", - "Button background color.", - "Button background color when hovering.", - "Badge background color. Badges are small information labels, e.g. for search results count.", - "Badge foreground color. Badges are small information labels, e.g. for search results count.", - "Scrollbar shadow to indicate that the view is scrolled.", - "Scrollbar slider background color.", - "Scrollbar slider background color when hovering.", - "Scrollbar slider background color when clicked on.", - "Background color of the progress bar that can show for long running operations.", - "Background color of error text in the editor. The color must not be opaque so as not to hide underlying decorations.", - "Foreground color of error squigglies in the editor.", - "Border color of error boxes in the editor.", - "Background color of warning text in the editor. The color must not be opaque so as not to hide underlying decorations.", - "Foreground color of warning squigglies in the editor.", - "Border color of warning boxes in the editor.", - "Background color of info text in the editor. The color must not be opaque so as not to hide underlying decorations.", - "Foreground color of info squigglies in the editor.", - "Border color of info boxes in the editor.", - "Foreground color of hint squigglies in the editor.", - "Border color of hint boxes in the editor.", - "Editor background color.", - "Editor default foreground color.", - "Background color of editor widgets, such as find/replace.", - "Foreground color of editor widgets, such as find/replace.", - "Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.", - "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget.", - "Quick picker background color. The quick picker widget is the container for pickers like the command palette.", - "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette.", - "Quick picker title background color. The quick picker widget is the container for pickers like the command palette.", - "Quick picker color for grouping labels.", - "Quick picker color for grouping borders.", - "Keybinding label background color. The keybinding label is used to represent a keyboard shortcut.", - "Keybinding label foreground color. The keybinding label is used to represent a keyboard shortcut.", - "Keybinding label border color. The keybinding label is used to represent a keyboard shortcut.", - "Keybinding label border bottom color. The keybinding label is used to represent a keyboard shortcut.", - "Color of the editor selection.", - "Color of the selected text for high contrast.", - "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations.", - "Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.", - "Border color for regions with the same content as the selection.", - "Color of the current search match.", - "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations.", - "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations.", - "Border color of the current search match.", - "Border color of the other search matches.", - "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations.", - "Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.", - "Background color of the editor hover.", - "Foreground color of the editor hover.", - "Border color of the editor hover.", - "Background color of the editor hover status bar.", - "Color of active links.", - "Foreground color of inline hints", - "Background color of inline hints", - "Foreground color of inline hints for types", - "Background color of inline hints for types", - "Foreground color of inline hints for parameters", - "Background color of inline hints for parameters", - "The color used for the lightbulb actions icon.", - "The color used for the lightbulb auto fix actions icon.", - "Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations.", - "Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations.", - "Outline color for the text that got inserted.", - "Outline color for text that got removed.", - "Border color between the two text editors.", - "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views.", - "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree outline color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree icon foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree icon foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree outline color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.", - "List/Tree background when hovering over items using the mouse.", - "List/Tree foreground when hovering over items using the mouse.", - "List/Tree drag and drop background when moving items around using the mouse.", - "List/Tree foreground color of the match highlights when searching inside the list/tree.", - "List/Tree foreground color of the match highlights on actively focused items when searching inside the list/tree.", - "Background color of the type filter widget in lists and trees.", - "Outline color of the type filter widget in lists and trees.", - "Outline color of the type filter widget in lists and trees, when there are no matches.", - "Tree stroke color for the indentation guides.", - "Tree stroke color for the indentation guides.", - "Please use quickInputList.focusBackground instead", - "Quick picker foreground color for the focused item.", - "Quick picker icon foreground color for the focused item.", - "Quick picker background color for the focused item.", - "Border color of menus.", - "Foreground color of menu items.", - "Background color of menu items.", - "Foreground color of the selected menu item in menus.", - "Background color of the selected menu item in menus.", - "Border color of the selected menu item in menus.", - "Color of a separator menu item in menus.", - "Toolbar background when hovering over actions using the mouse", - "Highlight background color of a snippet tabstop.", - "Highlight border color of a snippet tabstop.", - "Highlight background color of the final tabstop of a snippet.", - "Highlight border color of the final tabstop of a snippet.", - "Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations.", - "Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations.", - "Minimap marker color for find matches.", - "Minimap marker color for repeating editor selections.", - "Minimap marker color for the editor selection.", - "Minimap marker color for errors.", - "Minimap marker color for warnings.", - "Minimap background color.", - "Opacity of foreground elements rendered in the minimap. For example, \"#000000c0\" will render the elements with 75% opacity.", - "Minimap slider background color.", - "Minimap slider background color when hovering.", - "Minimap slider background color when clicked on.", - "The color used for the problems error icon.", - "The color used for the problems warning icon.", - "The color used for the problems info icon." - ], - "vs/platform/theme/common/iconRegistry": [ - "The id of the font to use. If not set, the font that is defined first is used.", - "The font character associated with the icon definition.", - "Icon for the close action in widgets." - ], - "vs/platform/undoRedo/common/undoRedoService": [ - "The following files have been closed and modified on disk: {0}.", - "The following files have been modified in an incompatible way: {0}.", - "Could not undo '{0}' across all files. {1}", - "Could not undo '{0}' across all files. {1}", - "Could not undo '{0}' across all files because changes were made to {1}", - "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", - "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", - "Would you like to undo '{0}' across all files?", - "Undo in {0} Files", - "Undo this File", - "Cancel", - "Could not undo '{0}' because there is already an undo or redo operation running.", - "Would you like to undo '{0}'?", - "Yes", - "Cancel", - "Could not redo '{0}' across all files. {1}", - "Could not redo '{0}' across all files. {1}", - "Could not redo '{0}' across all files because changes were made to {1}", - "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", - "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", - "Could not redo '{0}' because there is already an undo or redo operation running." - ] -} \ No newline at end of file diff --git a/magic-editor/src/console/plugins/editor.main.nls.zh-cn.js b/magic-editor/src/console/plugins/editor.main.nls.zh-cn.js deleted file mode 100644 index 70f1890f..00000000 --- a/magic-editor/src/console/plugins/editor.main.nls.zh-cn.js +++ /dev/null @@ -1,1415 +0,0 @@ -/*!----------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Version: 0.21.2(67b5a8116f3c0bace36b180e524e05bb750a16d8) - * Released under the MIT license - * https://github.com/Microsoft/vscode/blob/master/LICENSE.txt - *-----------------------------------------------------------*/ - -module.exports = { - "vs/base/browser/ui/actionbar/actionViewItems": [ - "{0} ({1})", - ], - "vs/base/browser/ui/findinput/findInput": [ - "输入", - ], - "vs/base/browser/ui/findinput/findInputCheckboxes": [ - "区分大小写", - "全字匹配", - "使用正则表达式", - ], - "vs/base/browser/ui/findinput/replaceInput": [ - "输入", - "保留大小写", - ], - "vs/base/browser/ui/iconLabel/iconLabelHover": [ - "正在加载…", - ], - "vs/base/browser/ui/inputbox/inputBox": [ - "错误: {0}", - "警告: {0}", - "信息: {0}", - "for history", - ], - "vs/base/browser/ui/keybindingLabel/keybindingLabel": [ - "未绑定", - ], - "vs/base/browser/ui/menu/menu": [ - "{0} ({1})", - ], - "vs/base/browser/ui/tree/abstractTree": [ - "清除", - "禁用输入时筛选", - "启用输入时筛选", - "未找到元素", - "已匹配 {0} 个元素(共 {1} 个)", - ], - "vs/base/common/actions": [ - "(空)", - ], - "vs/base/common/errorMessage": [ - "{0}: {1}", - "发生了系统错误 ({0})", - "出现未知错误。有关详细信息,请参阅日志。", - "出现未知错误。有关详细信息,请参阅日志。", - "{0} 个(共 {1} 个错误)", - "出现未知错误。有关详细信息,请参阅日志。", - ], - "vs/base/common/keybindingLabels": [ - "Ctrl", - "Shift", - "Alt", - "Windows", - "Ctrl", - "Shift", - "Alt", - "超键", - "Control", - "Shift", - "Alt", - "Command", - "Control", - "Shift", - "Alt", - "Windows", - "Control", - "Shift", - "Alt", - "超键", - ], - "vs/base/parts/quickinput/browser/quickInput": [ - "上一步", - "按 \"Enter\" 以确认或按 \"Esc\" 以取消", - "{0}/{1}", - "在此输入可缩小结果范围。", - "{0} 个结果", - "已选 {0} 项", - "确定", - "自定义", - "后退 ({0})", - "上一步", - ], - "vs/base/parts/quickinput/browser/quickInputList": [ - "快速输入", - ], - "vs/editor/browser/controller/coreCommands": [ - "即使转到较长的行,也一直到末尾", - "即使转到较长的行,也一直到末尾", - "已删除辅助游标", - ], - "vs/editor/browser/controller/textAreaHandler": [ - "编辑器", - "现在无法访问编辑器。按 {0} 获取选项。", - ], - "vs/editor/browser/core/keybindingCancellation": [ - "编辑器是否运行可取消的操作,例如“预览引用”", - ], - "vs/editor/browser/editorExtensions": [ - "撤消(&&U)", - "撤消", - "恢复(&&R)", - "恢复", - "全选(&&S)", - "选择全部", - ], - "vs/editor/browser/widget/codeEditorWidget": [ - "光标数量被限制为 {0}。", - ], - "vs/editor/browser/widget/diffEditorWidget": [ - "差异编辑器中插入项的线条修饰。", - "差异编辑器中删除项的线条修饰。", - "文件过大,无法比较。", - ], - "vs/editor/browser/widget/diffReview": [ - "差异评审中的“插入”图标。", - "差异评审中的“删除”图标。", - "差异评审中的“关闭”图标。", - "关闭", - "未更改行", - "更改了 1 行", - "更改了 {0} 行", - "差异 {0}/ {1}: 原始行 {2},{3},修改后的行 {4},{5}", - "空白", - "{0} 未更改的行 {1}", - "{0}原始行{1}修改的行{2}", - "+ {0}修改的行{1}", - "- {0}原始行{1}", - "转至下一个差异", - "转至上一个差异", - ], - "vs/editor/browser/widget/inlineDiffMargin": [ - "复制已删除的行", - "复制已删除的行", - "复制已删除的行({0})", - "还原此更改", - "复制已删除的行({0})", - ], - "vs/editor/common/config/commonEditorConfig": [ - "编辑器", - "一个制表符等于的空格数。在 `#editor.detectIndentation#` 启用时,根据文件内容,该设置可能会被覆盖。", - "按 `Tab` 键时插入空格。该设置在 `#editor.detectIndentation#` 启用时根据文件内容可能会被覆盖。", - "控制是否在打开文件时,基于文件内容自动检测 `#editor.tabSize#` 和 `#editor.insertSpaces#`。", - "删除自动插入的尾随空白符号。", - "对大型文件进行特殊处理,禁用某些内存密集型功能。", - "控制是否根据文档中的文字计算自动完成列表。", - "仅建议活动文档中的字词。", - "建议使用同一语言的所有打开的文档中的字词。", - "建议所有打开的文档中的字词。", - "控制通过哪些文档计算基于字词的补全。", - "对所有颜色主题启用语义突出显示。", - "对所有颜色主题禁用语义突出显示。", - "语义突出显示是由当前颜色主题的 \"semanticHighlighting\" 设置配置的。", - "控制是否为支持它的语言显示语义突出显示。", - "在速览编辑器中,即使双击其中的内容或者按 `Esc` 键,也保持其打开状态。", - "由于性能原因,超过这个长度的行将不会被标记", - "超时(以毫秒为单位),之后将取消差异计算。使用0表示没有超时。", - "Maximum file size in MB for which to compute diffs. Use 0 for no limit.", - "控制差异编辑器的显示方式是并排还是内联。", - "启用后,差异编辑器将忽略前导空格或尾随空格中的更改。", - "控制差异编辑器是否为添加/删除的更改显示 +/- 指示符号。", - "控制是否在编辑器中显示 CodeLens。", - "永不换行。", - "将在视区宽度处换行。", - "将根据 `#editor.wordWrap#` 设置换行。", - ], - "vs/editor/common/config/editorOptions": [ - "编辑器将使用平台 API 以检测是否附加了屏幕阅读器。", - "编辑器将针对与屏幕阅读器搭配使用进行永久优化。将禁用自动换行。", - "编辑器将不再对屏幕阅读器的使用进行优化。", - "控制编辑器是否应在对屏幕阅读器进行了优化的模式下运行。设置为“开”将禁用自动换行。", - "控制在注释时是否插入空格字符。", - "控制在对行注释执行切换、添加或删除操作时,是否应忽略空行。", - "控制在没有选择内容时进行复制是否复制当前行。", - "控制在键入时光标是否应跳转以查找匹配项。", - "切勿为编辑器选择中的搜索字符串设定种子。", - "始终为编辑器选择中的搜索字符串设定种子,包括光标位置的字词。", - "仅为编辑器选择中的搜索字符串设定种子。", - "控制是否将编辑器选中内容作为搜索词填入到查找小组件中。", - "从不自动打开“在选定内容中查找”(默认)。", - "始终自动打开“在选定内容中查找”。", - "选择多行内容时,自动打开“在选定内容中查找”。", - "控制自动打开“在选定内容中查找”的条件。", - "控制“查找”小组件是否读取或修改 macOS 的共享查找剪贴板。", - "控制 \"查找小部件\" 是否应在编辑器顶部添加额外的行。如果为 true, 则可以在 \"查找小工具\" 可见时滚动到第一行之外。", - "控制在找不到其他匹配项时,是否自动从开头(或结尾)重新开始搜索。", - "启用/禁用字体连字(\"calt\" 和 \"liga\" 字体特性)。将此更改为字符串,可对 \"font-feature-settings\" CSS 属性进行精细控制。", - "显式 \"font-feature-settings\" CSS 属性。如果只需打开/关闭连字,可以改为传递布尔值。", - "配置字体连字或字体特性。可以是用于启用/禁用连字的布尔值,或用于设置 CSS \"font-feature-settings\" 属性值的字符串。", - "控制字体大小(像素)。", - "仅允许使用关键字“正常”和“加粗”,或使用介于 1 至 1000 之间的数字。", - "控制字体粗细。接受关键字“正常”和“加粗”,或者接受介于 1 至 1000 之间的数字。", - "显示结果的预览视图 (默认值)", - "转到主结果并显示预览视图", - "转到主结果,并对其他人启用防偷窥导航", - "此设置已弃用,请改用单独的设置,如\"editor.editor.gotoLocation.multipleDefinitions\"或\"editor.editor.gotoLocation.multipleImplementations\"。", - "控制存在多个目标位置时\"转到定义\"命令的行为。", - "控制存在多个目标位置时\"转到类型定义\"命令的行为。", - "控制存在多个目标位置时\"转到声明\"命令的行为。", - "控制存在多个目标位置时\"转到实现\"命令的行为。", - "控制存在多个目标位置时\"转到引用\"命令的行为。", - "当\"转到定义\"的结果为当前位置时将要执行的替代命令的 ID。", - "当\"转到类型定义\"的结果是当前位置时正在执行的备用命令 ID。", - "当\"转到声明\"的结果为当前位置时将要执行的替代命令的 ID。", - "当\"转到实现\"的结果为当前位置时将要执行的替代命令的 ID。", - "当\"转到引用\"的结果是当前位置时正在执行的替代命令 ID。", - "控制是否显示悬停提示。", - "控制显示悬停提示前的等待时间 (毫秒)。", - "控制当鼠标移动到悬停提示上时,其是否保持可见。", - "在编辑器中启用代码操作小灯泡提示。", - "在编辑器中启用内联提示。", - "Controls font size of inlay hints in the editor. A default of 90% of `#editor.fontSize#` is used when the configured value is less than `5` or greater than the editor font size.", - "在编辑器中控制内嵌提示的字体系列。设置为空时,使用 `#editor.fontFamily#`。", - "控制行高。\r\n - 使用 0 根据字号自动计算行高。\r\n - 介于 0 和 8 之间的值将用作字号的乘数。\r\n - 大于或等于 8 的值将用作有效值。", - "控制是否显示缩略图。", - "迷你地图的大小与编辑器内容相同(并且可能滚动)。", - "迷你地图将根据需要拉伸或缩小以填充编辑器的高度(不滚动)。", - "迷你地图将根据需要缩小,永远不会大于编辑器(不滚动)。", - "控制迷你地图的大小。", - "控制在哪一侧显示缩略图。", - "控制何时显示迷你地图滑块。", - "在迷你地图中绘制的内容比例: 1、2 或 3。", - "渲染每行的实际字符,而不是色块。", - "限制缩略图的宽度,控制其最多显示的列数。", - "控制编辑器的顶边和第一行之间的间距量。", - "控制编辑器的底边和最后一行之间的间距量。", - "在输入时显示含有参数文档和类型信息的小面板。", - "控制参数提示菜单在到达列表末尾时进行循环还是关闭。", - "在字符串内启用快速建议。", - "在注释内启用快速建议。", - "在字符串和注释外启用快速建议。", - "控制是否在键入时自动显示建议。", - "不显示行号。", - "将行号显示为绝对行数。", - "将行号显示为与光标相隔的行数。", - "每 10 行显示一次行号。", - "控制行号的显示。", - "此编辑器标尺将渲染的等宽字符数。", - "此编辑器标尺的颜色。", - "在一定数量的等宽字符后显示垂直标尺。输入多个值,显示多个标尺。若数组为空,则不绘制标尺。", - "垂直滚动条仅在必要时可见。", - "垂直滚动条将始终可见。", - "垂直滚动条将始终隐藏。", - "控制垂直滚动条的可见性。", - "水平滚动条仅在必要时可见。", - "水平滚动条将始终可见。", - "水平滚动条将始终隐藏。", - "控制水平滚动条的可见性。", - "垂直滚动条的宽度。", - "水平滚动条的高度。", - "控制单击按页滚动还是跳转到单击位置。", - "控制是否在编辑器中自动显示内联建议。", - "控制是否启用括号对着色。使用 “workbench.colorCustomizations” 替代括号突出显示颜色。", - "Controls whether bracket pair guides are enabled or not.", - "控制编辑器是否显示缩进参考线。", - "控制是否突出显示编辑器中活动的缩进参考线。", - "插入建议而不覆盖光标右侧的文本。", - "插入建议并覆盖光标右侧的文本。", - "控制接受补全时是否覆盖单词。请注意,这取决于扩展选择使用此功能。", - "控制对建议的筛选和排序是否考虑小的拼写错误。", - "控制排序时是否首选光标附近的字词。", - "控制是否在多个工作区和窗口间共享记忆的建议选项(需要 `#editor.suggestSelection#`)。", - "控制活动代码段是否阻止快速建议。", - "控制是否在建议中显示或隐藏图标。", - "控制建议小部件底部的状态栏的可见性。", - "控制是否在编辑器中预览建议结果。", - "控制建议详细信息是随标签一起显示还是仅显示在详细信息小组件中", - "此设置已弃用。现在可以调整建议小组件的大小。", - "此设置已弃用,请改用单独的设置,如\"editor.suggest.showKeywords\"或\"editor.suggest.showSnippets\"。", - "启用后,IntelliSense 将显示“方法”建议。", - "启用后,IntelliSense 将显示“函数”建议。", - "启用后,IntelliSense 将显示“构造函数”建议。", - "启用后,IntelliSense 将显示“已启用”建议。", - "启用后,IntelliSense 将显示“字段”建议。", - "启用后,IntelliSense 将显示“变量”建议。", - "启用后,IntelliSense 将显示“类”建议。", - "启用后,IntelliSense 将显示“结构”建议。", - "启用后,IntelliSense 将显示“接口”建议。", - "启用后,IntelliSense 将显示“模块”建议。", - "启用后,IntelliSense 将显示“属性”建议。", - "启用后,IntelliSense 将显示“事件”建议。", - "启用后,IntelliSense 将显示“操作符”建议。", - "启用后,IntelliSense 将显示“单位”建议。", - "启用后,IntelliSense 将显示“值”建议。", - "启用后,IntelliSense 将显示“常量”建议。", - "启用后,IntelliSense 将显示“枚举”建议。", - "启用后,IntelliSense 将显示 \"enumMember\" 建议。", - "启用后,IntelliSense 将显示“关键字”建议。", - "启用后,IntelliSense 将显示“文本”建议。", - "启用后,IntelliSense 将显示“颜色”建议。", - "启用后,IntelliSense 将显示“文件”建议。", - "启用后,IntelliSense 将显示“参考”建议。", - "启用后,IntelliSense 将显示“自定义颜色”建议。", - "启用后,IntelliSense 将显示“文件夹”建议。", - "启用后,IntelliSense 将显示 \"typeParameter\" 建议。", - "启用后,IntelliSense 将显示“片段”建议。", - "启用后,IntelliSense 将显示\"用户\"建议。", - "启用后,IntelliSense 将显示\"问题\"建议。", - "是否应始终选择前导和尾随空格。", - "控制是否应在遇到提交字符时接受建议。例如,在 JavaScript 中,半角分号 (`;`) 可以为提交字符,能够在接受建议的同时键入该字符。", - "仅当建议包含文本改动时才可使用 `Enter` 键进行接受。", - "控制除了 `Tab` 键以外, `Enter` 键是否同样可以接受建议。这能减少“插入新行”和“接受建议”命令之间的歧义。", - "控制编辑器中可由屏幕阅读器一次读出的行数。我们检测到屏幕阅读器时,会自动将默认值设置为 500。警告: 如果行数大于默认值,可能会影响性能。", - "编辑器内容", - "使用语言配置确定何时自动闭合括号。", - "仅当光标位于空白字符左侧时,才自动闭合括号。", - "控制编辑器是否在左括号后自动插入右括号。", - "仅在自动插入时才删除相邻的右引号或右括号。", - "控制在删除时编辑器是否应删除相邻的右引号或右方括号。", - "仅在自动插入时才改写右引号或右括号。", - "控制编辑器是否应改写右引号或右括号。", - "使用语言配置确定何时自动闭合引号。", - "仅当光标位于空白字符左侧时,才自动闭合引号。", - "控制编辑器是否在左引号后自动插入右引号。", - "编辑器不会自动插入缩进。", - "编辑器将保留当前行的缩进。", - "编辑器将保留当前行的缩进并遵循语言定义的括号。", - "编辑器将保留当前行的缩进、使用语言定义的括号并调用语言定义的特定 onEnterRules。", - "编辑器将保留当前行的缩进,使用语言定义的括号,调用由语言定义的特殊输入规则,并遵循由语言定义的缩进规则。", - "控制编辑器是否应在用户键入、粘贴、移动或缩进行时自动调整缩进。", - "使用语言配置确定何时自动包住所选内容。", - "使用引号而非括号来包住所选内容。", - "使用括号而非引号来包住所选内容。", - "控制在键入引号或方括号时,编辑器是否应自动将所选内容括起来。", - "在使用空格进行缩进时模拟制表符的选择行为。所选内容将始终使用制表符停止位。", - "控制是否在编辑器中显示 CodeLens。", - "控制 CodeLens 的字体系列。", - "控制 CodeLens 的字体大小(像素)。设置为 `0` 时,将使用 `#editor.fontSize#` 的 90%。", - "控制编辑器是否显示内联颜色修饰器和颜色选取器。", - "启用使用鼠标和键进行列选择。", - "控制在复制时是否同时复制语法高亮。", - "控制光标的动画样式。", - "控制是否启用平滑插入动画。", - "控制光标样式。", - "控制光标周围可见的前置行和尾随行的最小数目。在其他一些编辑器中称为 \"scrollOff\" 或 \"scrollOffset\"。", - "仅当通过键盘或 API 触发时,才会强制执行\"光标环绕行\"。", - "始终强制执行 \"cursorSurroundingLines\"", - "控制何时应强制执行\"光标环绕行\"。", - "当 `#editor.cursorStyle#` 设置为 `line` 时,控制光标的宽度。", - "控制在编辑器中是否允许通过拖放来移动选中内容。", - "按下\"Alt\"时滚动速度倍增。", - "控制编辑器是否启用了代码折叠。", - "使用特定于语言的折叠策略(如果可用),否则使用基于缩进的策略。", - "使用基于缩进的折叠策略。", - "控制计算折叠范围的策略。", - "控制编辑器是否应突出显示折叠范围。", - "控制编辑器是否自动折叠导入范围。", - "控制单击已折叠的行后面的空内容是否会展开该行。", - "控制字体系列。", - "控制编辑器是否自动格式化粘贴的内容。格式化程序必须可用,并且能针对文档中的某一范围进行格式化。", - "控制编辑器在键入一行后是否自动格式化该行。", - "控制编辑器是否应呈现垂直字形边距。字形边距最常用于调试。", - "控制是否在概览标尺中隐藏光标。", - "控制字母间距(像素)。", - "控制编辑器是否已启用链接编辑。相关符号(如 HTML 标记)在编辑时进行更新,具体由语言而定。", - "控制是否在编辑器中检测链接并使其可被点击。", - "突出显示匹配的括号。", - "对鼠标滚轮滚动事件的 `deltaX` 和 `deltaY` 乘上的系数。", - "按住 `Ctrl` 键并滚动鼠标滚轮时对编辑器字体大小进行缩放。", - "当多个光标重叠时进行合并。", - "映射为 `Ctrl` (Windows 和 Linux) 或 `Command` (macOS)。", - "映射为 `Alt` (Windows 和 Linux) 或 `Option` (macOS)。", - "在通过鼠标添加多个光标时使用的修改键。“转到定义”和“打开链接”功能所需的鼠标动作将会相应调整,不与多光标修改键冲突。[阅读详细信息](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier)。", - "每个光标粘贴一行文本。", - "每个光标粘贴全文。", - "控制粘贴时粘贴文本的行计数与光标计数相匹配。", - "控制编辑器是否突出显示语义符号的匹配项。", - "控制是否在概览标尺周围绘制边框。", - "打开速览时聚焦树", - "打开预览时将焦点放在编辑器上", - "控制是将焦点放在内联编辑器上还是放在预览小部件中的树上。", - "控制\"转到定义\"鼠标手势是否始终打开预览小部件。", - "控制显示快速建议前的等待时间 (毫秒)。", - "控制是否在编辑器中输入时自动重命名。", - "已弃用,请改用 \"editor.linkedEditing\"。", - "控制编辑器是否显示控制字符。", - "当文件以换行符结束时, 呈现最后一行的行号。", - "同时突出显示导航线和当前行。", - "控制编辑器的当前行进行高亮显示的方式。", - "控制编辑器是否仅在焦点在编辑器时突出显示当前行。", - "呈现空格字符(字词之间的单个空格除外)。", - "仅在选定文本上呈现空白字符。", - "仅呈现尾随空格字符。", - "控制编辑器在空白字符上显示符号的方式。", - "控制选区是否有圆角。", - "控制编辑器水平滚动时可以超过范围的字符数。", - "控制编辑器是否可以滚动到最后一行之后。", - "同时垂直和水平滚动时,仅沿主轴滚动。在触控板上垂直滚动时,可防止水平漂移。", - "控制是否支持 Linux 主剪贴板。", - "控制编辑器是否应突出显示与所选内容类似的匹配项。", - "始终显示折叠控件。", - "仅在鼠标位于装订线上方时显示折叠控件。", - "控制何时显示行号槽上的折叠控件。", - "控制是否淡化未使用的代码。", - "控制加删除线被弃用的变量。", - "在其他建议上方显示代码片段建议。", - "在其他建议下方显示代码片段建议。", - "在其他建议中穿插显示代码片段建议。", - "不显示代码片段建议。", - "控制代码片段是否与其他建议一起显示及其排列的位置。", - "控制编辑器是否使用动画滚动。", - "建议小部件的字号。如果设置为 `0`,则使用 `#editor.fontSize#` 的值。", - "建议小部件的行高。如果设置为 `0`,则使用 `#editor.lineHeight#` 的值。最小值为 8。", - "控制在键入触发字符后是否自动显示建议。", - "始终选择第一个建议。", - "选择最近的建议,除非进一步键入选择其他项。例如 `console. -> console.log`,因为最近补全过 `log`。", - "根据之前补全过的建议的前缀来进行选择。例如,`co -> console`、`con -> const`。", - "控制在建议列表中如何预先选择建议。", - "在按下 Tab 键时进行 Tab 补全,将插入最佳匹配建议。", - "禁用 Tab 补全。", - "在前缀匹配时进行 Tab 补全。在 \"quickSuggestions\" 未启用时体验最好。", - "启用 Tab 补全。", - "自动删除异常的行终止符。", - "忽略异常的行终止符。", - "提示删除异常的行终止符。", - "删除可能导致问题的异常行终止符。", - "根据制表位插入和删除空格。", - "执行单词相关的导航或操作时作为单词分隔符的字符。", - "永不换行。", - "将在视区宽度处换行。", - "在 `#editor.wordWrapColumn#` 处折行。", - "在视区宽度和 `#editor.wordWrapColumn#` 中的较小值处折行。", - "控制折行的方式。", - "在 `#editor.wordWrap#` 为 `wordWrapColumn` 或 `bounded` 时,控制编辑器的折行列。", - "没有缩进。折行从第 1 列开始。", - "折行的缩进量与其父级相同。", - "折行的缩进量比其父级多 1。", - "折行的缩进量比其父级多 2。", - "控制折行的缩进。", - "假定所有字符的宽度相同。这是一种快速算法,适用于等宽字体和某些字形宽度相等的文字(如拉丁字符)。", - "将包装点计算委托给浏览器。这是一个缓慢算法,可能会导致大型文件被冻结,但它在所有情况下都正常工作。", - "控制计算包裹点的算法。", - ], - "vs/editor/common/editorContextKeys": [ - "编辑器文本是否具有焦点(光标是否闪烁)", - "编辑器或编辑器小组件是否具有焦点(例如焦点在“查找”小组件中)", - "编辑器或 RTF 输入是否有焦点(光标是否闪烁)", - "编辑器是否为只读", - "上下文是否为差异编辑器", - "是否已启用 \"editor.columnSelection\"", - "编辑器是否已选定文本", - "编辑器是否有多个选择", - "\"Tab\" 是否将焦点移出编辑器", - "编辑器软键盘是否可见", - "该编辑器是否是更大的编辑器(例如笔记本)的一部分", - "编辑器的语言标识符", - "编辑器是否具有补全项提供程序", - "编辑器是否具有代码操作提供程序", - "编辑器是否具有 CodeLens 提供程序", - "编辑器是否具有定义提供程序", - "编辑器是否具有声明提供程序", - "编辑器是否具有实现提供程序", - "编辑器是否具有类型定义提供程序", - "编辑器是否具有悬停提供程序", - "编辑器是否具有文档突出显示提供程序", - "编辑器是否具有文档符号提供程序", - "编辑器是否具有引用提供程序", - "编辑器是否具有重命名提供程序", - "编辑器是否具有签名帮助提供程序", - "编辑器是否具有内联提示提供程序", - "编辑器是否具有文档格式设置提供程序", - "编辑器是否具有文档选择格式设置提供程序", - "编辑器是否具有多个文档格式设置提供程序", - "编辑器是否有多个文档选择格式设置提供程序", - ], - "vs/editor/common/model/editStack": [ - "输入", - ], - "vs/editor/common/modes/modesRegistry": [ - "纯文本", - ], - "vs/editor/common/standaloneStrings": [ - "无选择", - "行 {0}, 列 {1} (选中 {2})", - "行 {0}, 列 {1}", - "{0} 选择(已选择 {1} 个字符)", - "{0} 选择", - "现在将 \"辅助功能支持\" 设置更改为 \"打开\"。", - "现在正在打开“编辑器辅助功能”文档页。", - "在差异编辑器的只读窗格中。", - "在一个差异编辑器的窗格中。", - "在只读代码编辑器中", - "在代码编辑器中", - "若要配置编辑器,将其进行优化以最好地配合屏幕阅读器的使用,请立即按 Command+E。", - "若要配置编辑器,将其进行优化以最高效地配合屏幕阅读器的使用,按下 Ctrl+E。", - "配置编辑器,将其进行优化以最好地配合屏幕读取器的使用。", - "编辑器被配置为永远不进行优化以配合屏幕读取器的使用, 而当前不是这种情况。", - "在当前编辑器中按 Tab 会将焦点移动到下一个可聚焦的元素。通过按 {0} 切换此行为。", - "在当前编辑器中按 Tab 会将焦点移动到下一个可聚焦的元素。当前无法通过按键绑定触发命令 {0}。", - "在当前编辑器中按 Tab 将插入制表符。通过按 {0} 切换此行为。", - "在当前编辑器中按 Tab 会插入制表符。当前无法通过键绑定触发命令 {0}。", - "现在按 Command+H 打开一个浏览器窗口, 其中包含有关编辑器辅助功能的详细信息。", - "现在按 Ctrl+H 打开一个浏览器窗口, 其中包含有关编辑器辅助功能的更多信息。", - "你可以按 Esc 或 Shift+Esc 消除此工具提示并返回到编辑器。", - "显示辅助功能帮助", - "开发人员: 检查令牌", - "转到行/列...", - "显示所有快速访问提供程序", - "命令面板", - "显示并运行命令", - "转到符号...", - "按类别转到符号...", - "编辑器内容", - "按 Alt+F1 可打开辅助功能选项。", - "切换高对比度主题", - "在 {1} 个文件中进行了 {0} 次编辑", - ], - "vs/editor/common/view/editorColorRegistry": [ - "光标所在行高亮内容的背景颜色。", - "光标所在行四周边框的背景颜色。", - "背景颜色的高亮范围,喜欢通过快速打开和查找功能。颜色不能不透明,以免隐藏底层装饰。", - "高亮区域边框的背景颜色。", - "高亮显示符号的背景颜色,例如转到定义或转到下一个/上一个符号。颜色不能是不透明的,以免隐藏底层装饰。", - "高亮显示符号周围的边框的背景颜色。", - "编辑器光标颜色。", - "编辑器光标的背景色。可以自定义块型光标覆盖字符的颜色。", - "编辑器中空白字符的颜色。", - "编辑器缩进参考线的颜色。", - "编辑器活动缩进参考线的颜色。", - "编辑器行号的颜色。", - "编辑器活动行号的颜色", - "\"Id\" 已被弃用,请改用 \"editorLineNumber.activeForeground\"。", - "编辑器活动行号的颜色", - "编辑器标尺的颜色。", - "编辑器 CodeLens 的前景色", - "匹配括号的背景色", - "匹配括号外框的颜色", - "概览标尺边框的颜色。", - "编辑器概述标尺的背景色。仅当缩略图已启用且置于编辑器右侧时才使用。", - "编辑器导航线的背景色。导航线包括边缘符号和行号。", - "编辑器中不必要(未使用)的源代码的边框颜色。", - "非必须(未使用)代码的在编辑器中显示的不透明度。例如,\"#000000c0\" 将以 75% 的不透明度显示代码。对于高对比度主题,请使用 ”editorUnnecessaryCode.border“ 主题来为非必须代码添加下划线,以避免颜色淡化。", - "编辑器中虚影文本的边框颜色。", - "编辑器中虚影文本的前景色。", - "用于突出显示范围的概述标尺标记颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "概览标尺中错误标记的颜色。", - "概览标尺中警告标记的颜色。", - "概览标尺中信息标记的颜色。", - "括号的前景色(1)。需要启用括号对着色。", - "括号的前景色(2)。需要启用括号对着色。", - "括号的前景色(3)。需要启用括号对着色。", - "括号的前景色(4)。需要启用括号对着色。", - "括号的前景色(5)。需要启用括号对着色。", - "括号的前景色(6)。需要启用括号对着色。", - "方括号出现意外的前景色。", - ], - "vs/editor/contrib/anchorSelect/anchorSelect": [ - "选择定位点", - "定位点设置为 {0}:{1}", - "设置选择定位点", - "转到选择定位点", - "选择从定位点到光标", - "取消选择定位点", - ], - "vs/editor/contrib/bracketMatching/bracketMatching": [ - "概览标尺上表示匹配括号的标记颜色。", - "转到括号", - "选择括号所有内容", - "转到括号(&&B)", - ], - "vs/editor/contrib/caretOperations/caretOperations": [ - "向左移动所选文本", - "向右移动所选文本", - ], - "vs/editor/contrib/caretOperations/transpose": [ - "转置字母", - ], - "vs/editor/contrib/clipboard/clipboard": [ - "剪切(&&T)", - "剪切", - "剪切", - "剪切", - "复制(&&C)", - "复制", - "复制", - "复制", - "复制为", - "复制为", - "粘贴(&&P)", - "粘贴", - "粘贴", - "粘贴", - "复制并突出显示语法", - ], - "vs/editor/contrib/codeAction/codeActionCommands": [ - "要运行的代码操作的种类。", - "控制何时应用返回的操作。", - "始终应用第一个返回的代码操作。", - "如果仅返回的第一个代码操作,则应用该操作。", - "不要应用返回的代码操作。", - "如果只应返回首选代码操作,则应返回控件。", - "应用代码操作时发生未知错误", - "快速修复...", - "没有可用的代码操作", - "没有适用于\"{0}\"的首选代码操作", - "没有适用于\"{0}\"的代码操作", - "没有可用的首选代码操作", - "没有可用的代码操作", - "重构...", - "没有适用于\"{0}\"的首选重构", - "没有可用的\"{0}\"重构", - "没有可用的首选重构", - "没有可用的重构操作", - "源代码操作...", - "没有适用于\"{0}\"的首选源操作", - "没有适用于“ {0}”的源操作", - "没有可用的首选源操作", - "没有可用的源代码操作", - "整理 import 语句", - "没有可用的整理 import 语句操作", - "全部修复", - "没有可用的“全部修复”操作", - "自动修复...", - "没有可用的自动修复程序", - ], - "vs/editor/contrib/codeAction/lightBulbWidget": [ - "显示代码操作。首选可用的快速修复({0})", - "显示代码操作({0})", - "显示代码操作", - ], - "vs/editor/contrib/codelens/codelensController": [ - "显示当前行的 Code Lens 命令", - ], - "vs/editor/contrib/comment/comment": [ - "切换行注释", - "切换行注释(&&T)", - "添加行注释", - "删除行注释", - "切换块注释", - "切换块注释(&&B)", - ], - "vs/editor/contrib/contextmenu/contextmenu": [ - "显示编辑器上下文菜单", - ], - "vs/editor/contrib/cursorUndo/cursorUndo": [ - "光标撤消", - "光标重做", - ], - "vs/editor/contrib/find/findController": [ - "查找", - "查找(&&F)", - "查找选定内容", - "查找下一个", - "查找上一个", - "查找下一个选择", - "查找上一个选择", - "替换", - "替换(&&R)", - ], - "vs/editor/contrib/find/findWidget": [ - "编辑器查找小组件中的“在选定内容中查找”图标。", - "用于指示编辑器查找小组件已折叠的图标。", - "用于指示编辑器查找小组件已展开的图标。", - "编辑器查找小组件中的“替换”图标。", - "编辑器查找小组件中的“全部替换”图标。", - "编辑器查找小组件中的“查找上一个”图标。", - "编辑器查找小组件中的“查找下一个”图标。", - "查找", - "查找", - "上一个匹配项", - "下一个匹配项", - "在选定内容中查找", - "关闭", - "替换", - "替换", - "替换", - "全部替换", - "切换替换", - "仅高亮了前 {0} 个结果,但所有查找操作均针对全文。", - "{1} 中的 {0}", - "无结果", - "找到 {0}", - "为“{1}”找到 {0}", - "在 {2} 处找到“{1}”的 {0}", - "为“{1}”找到 {0}", - "Ctrl+Enter 现在由全部替换改为插入换行。你可以修改editor.action.replaceAll 的按键绑定以覆盖此行为。", - ], - "vs/editor/contrib/folding/folding": [ - "展开", - "以递归方式展开", - "折叠", - "切换折叠", - "以递归方式折叠", - "折叠所有块注释", - "折叠所有区域", - "展开所有区域", - "折叠除所选区域之外的所有区域", - "展开除所选区域之外的所有区域", - "全部折叠", - "全部展开", - "跳转到父级折叠", - "移至上一个折叠范围", - "移至下一个折叠范围", - "折叠级别 {0}", - "折叠范围后面的背景颜色。颜色必须设为透明,以免隐藏底层装饰。", - "编辑器装订线中折叠控件的颜色。", - ], - "vs/editor/contrib/folding/foldingDecorations": [ - "编辑器字形边距中已展开的范围的图标。", - "编辑器字形边距中已折叠的范围的图标。", - ], - "vs/editor/contrib/fontZoom/fontZoom": [ - "放大编辑器字体", - "缩小编辑器字体", - "重置编辑器字体大小", - ], - "vs/editor/contrib/format/format": [ - "在第 {0} 行进行了 1 次格式编辑", - "在第 {1} 行进行了 {0} 次格式编辑", - "第 {0} 行到第 {1} 行间进行了 1 次格式编辑", - "第 {1} 行到第 {2} 行间进行了 {0} 次格式编辑", - ], - "vs/editor/contrib/format/formatActions": [ - "格式化文档", - "格式化选定内容", - ], - "vs/editor/contrib/gotoError/gotoError": [ - "转到下一个问题 (错误、警告、信息)", - "“转到下一个”标记的图标。", - "转到上一个问题 (错误、警告、信息)", - "“转到上一个”标记的图标。", - "转到文件中的下一个问题 (错误、警告、信息)", - "下一个问题(&&P)", - "转到文件中的上一个问题 (错误、警告、信息)", - "上一个问题(&&P)", - ], - "vs/editor/contrib/gotoError/gotoErrorWidget": [ - "错误", - "警告", - "信息", - "提示", - "{1} 中的 {0}", - "{0} 个问题(共 {1} 个)", - "{0} 个问题(共 {1} 个)", - "编辑器标记导航小组件错误颜色。", - "编辑器标记导航小组件错误标题背景色。", - "编辑器标记导航小组件警告颜色。", - "编辑器标记导航小组件警告标题背景色。", - "编辑器标记导航小组件信息颜色。", - "编辑器标记导航小组件信息标题背景色。", - "编辑器标记导航小组件背景色。", - ], - "vs/editor/contrib/gotoSymbol/goToCommands": [ - "快速查看", - "定义", - "未找到“{0}”的任何定义", - "找不到定义", - "转到定义", - "打开侧边的定义", - "速览定义", - "声明", - "未找到“{0}”的声明", - "未找到声明", - "转到声明", - "未找到“{0}”的声明", - "未找到声明", - "查看声明", - "类型定义", - "未找到“{0}”的类型定义", - "未找到类型定义", - "转到类型定义", - "快速查看类型定义", - "实现", - "未找到“{0}”的实现", - "未找到实现", - "转到实现", - "查看实现", - "未找到\"{0}\"的引用", - "未找到引用", - "转到引用", - "引用", - "查看引用", - "引用", - "转到任何符号", - "位置", - "无“{0}”的结果", - "引用", - "转到定义(&&D)", - "转到声明(&&D)", - "转到类型定义(&&T)", - "转到实现(&&I)", - "转到引用(&&R)", - ], - "vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition": [ - "单击显示 {0} 个定义。", - ], - "vs/editor/contrib/gotoSymbol/peek/referencesController": [ - "引用速览是否可见,例如“速览引用”或“速览定义”", - "正在加载...", - "{0} ({1})", - ], - "vs/editor/contrib/gotoSymbol/peek/referencesTree": [ - "{0} 个引用", - "{0} 个引用", - "引用", - ], - "vs/editor/contrib/gotoSymbol/peek/referencesWidget": [ - "无可用预览", - "无结果", - "引用", - ], - "vs/editor/contrib/gotoSymbol/referencesModel": [ - "在文件 {0} 的 {1} 行 {2} 列的符号", - "{0} 中 {1} 行 {2} 列的符号,{3}", - "{0} 中有 1 个符号,完整路径: {1}", - "{1} 中有 {0} 个符号,完整路径: {2}", - "未找到结果", - "在 {0} 中找到 1 个符号", - "在 {1} 中找到 {0} 个符号", - "在 {1} 个文件中找到 {0} 个符号", - ], - "vs/editor/contrib/gotoSymbol/symbolNavigation": [ - "是否存在只能通过键盘导航的符号位置。", - "{1} 的符号 {0},下一个使用 {2}", - "{1} 的符号 {0}", - ], - "vs/editor/contrib/hover/hover": [ - "显示悬停", - "显示定义预览悬停", - ], - "vs/editor/contrib/hover/markdownHoverParticipant": [ - "正在加载...", - "出于性能原因,未对长行进行解析。解析长度阈值可通过“editor.maxTokenizationLineLength”进行配置。", - ], - "vs/editor/contrib/hover/markerHoverParticipant": [ - "查看问题", - "没有可用的快速修复", - "正在检查快速修复...", - "没有可用的快速修复", - "快速修复...", - ], - "vs/editor/contrib/inPlaceReplace/inPlaceReplace": [ - "替换为上一个值", - "替换为下一个值", - ], - "vs/editor/contrib/indentation/indentation": [ - "将缩进转换为空格", - "将缩进转换为制表符", - "已配置制表符大小", - "选择当前文件的制表符大小", - "使用 \"Tab\" 缩进", - "使用空格缩进", - "从内容中检测缩进方式", - "重新缩进行", - "重新缩进所选行", - ], - "vs/editor/contrib/inlineCompletions/ghostTextController": [ - "内联建议是否可见", - "内联建议是否以空白开头", - "显示下一个内联建议", - "显示上一个内联建议", - "触发内联建议", - ], - "vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant": [ - "下一个", - "上一个", - "接受", - "建议:", - ], - "vs/editor/contrib/linesOperations/linesOperations": [ - "向上复制行", - "向上复制一行(&&C)", - "向下复制行", - "向下复制一行(&&P)", - "重复选择", - "重复选择(&&D)", - "向上移动行", - "向上移动一行(&&V)", - "向下移动行", - "向下移动一行(&&L)", - "按升序排列行", - "按降序排列行", - "裁剪尾随空格", - "删除行", - "行缩进", - "行减少缩进", - "在上面插入行", - "在下面插入行", - "删除左侧所有内容", - "删除右侧所有内容", - "合并行", - "转置光标处的字符", - "转换为大写", - "转换为小写", - "转换为词首字母大写", - "转换为蛇形命名法", - ], - "vs/editor/contrib/linkedEditing/linkedEditing": [ - "启动链接编辑", - "编辑器根据类型自动重命名时的背景色。", - ], - "vs/editor/contrib/links/links": [ - "执行命令", - "关注链接", - "cmd + 单击", - "ctrl + 单击", - "option + 单击", - "alt + 单击", - "执行命令 {0}", - "此链接格式不正确,无法打开: {0}", - "此链接目标已丢失,无法打开。", - "打开链接", - ], - "vs/editor/contrib/message/messageController": [ - "编辑器当前是否正在显示内联消息", - "无法在只读编辑器中编辑", - ], - "vs/editor/contrib/multicursor/multicursor": [ - "添加的光标: {0}", - "添加的游标: {0}", - "在上面添加光标", - "在上面添加光标(&&A)", - "在下面添加光标", - "在下面添加光标(&&D)", - "在行尾添加光标", - "在行尾添加光标(&&U)", - "在底部添加光标", - "在顶部添加光标", - "将下一个查找匹配项添加到选择", - "添加下一个匹配项(&&N)", - "将选择内容添加到上一查找匹配项", - "添加上一个匹配项(&&R)", - "将上次选择移动到下一个查找匹配项", - "将上个选择内容移动到上一查找匹配项", - "选择所有找到的查找匹配项", - "选择所有匹配项(&&O)", - "更改所有匹配项", - ], - "vs/editor/contrib/parameterHints/parameterHints": [ - "触发参数提示", - ], - "vs/editor/contrib/parameterHints/parameterHintsWidget": [ - "“显示下一个参数”提示的图标。", - "“显示上一个参数”提示的图标。", - "{0},提示", - ], - "vs/editor/contrib/peekView/peekView": [ - "速览中是否嵌入了当前代码编辑器", - "关闭", - "速览视图标题区域背景颜色。", - "速览视图标题颜色。", - "速览视图标题信息颜色。", - "速览视图边框和箭头颜色。", - "速览视图结果列表背景色。", - "速览视图结果列表中行节点的前景色。", - "速览视图结果列表中文件节点的前景色。", - "速览视图结果列表中所选条目的背景色。", - "速览视图结果列表中所选条目的前景色。", - "速览视图编辑器背景色。", - "速览视图编辑器中装订线的背景色。", - "在速览视图结果列表中匹配突出显示颜色。", - "在速览视图编辑器中匹配突出显示颜色。", - "在速览视图编辑器中匹配项的突出显示边框。", - ], - "vs/editor/contrib/quickAccess/gotoLineQuickAccess": [ - "先打开文本编辑器然后跳转到行。", - "转到第 {0} 行第 {1} 个字符。", - "转到行 {0}。", - "当前行: {0},字符: {1}。键入要导航到的行号(介于 1 至 {2} 之间)。", - "当前行: {0},字符: {1}。 键入要导航到的行号。", - ], - "vs/editor/contrib/quickAccess/gotoSymbolQuickAccess": [ - "要转到符号,首先打开具有符号信息的文本编辑器。", - "活动文本编辑器不提供符号信息。", - "没有匹配的编辑器符号", - "没有编辑器符号", - "在侧边打开", - "在底部打开", - "符号({0})", - "属性({0})", - "方法({0})", - "函数({0})", - "构造函数 ({0})", - "变量({0})", - "类({0})", - "结构({0})", - "事件({0})", - "运算符({0})", - "接口({0})", - "命名空间({0})", - "包({0})", - "类型参数({0})", - "模块({0})", - "属性({0})", - "枚举({0})", - "枚举成员({0})", - "字符串({0})", - "文件({0})", - "数组({0})", - "数字({0})", - "布尔值({0})", - "对象({0})", - "键({0})", - "字段({0})", - "常量({0})", - ], - "vs/editor/contrib/rename/rename": [ - "无结果。", - "解析重命名位置时发生未知错误", - "正在重命名“{0}”", - "重命名 {0}", - "成功将“{0}”重命名为“{1}”。摘要: {2}", - "重命名无法应用修改", - "重命名无法计算修改", - "重命名符号", - "启用/禁用重命名之前预览更改的功能", - ], - "vs/editor/contrib/rename/renameInputField": [ - "重命名输入小组件是否可见", - "重命名输入。键入新名称并按 \"Enter\" 提交。", - "按 {0} 进行重命名,按 {1} 进行预览", - ], - "vs/editor/contrib/smartSelect/smartSelect": [ - "展开选择", - "扩大选区(&&E)", - "收起选择", - "缩小选区(&&S)", - ], - "vs/editor/contrib/snippet/snippetController2": [ - "编辑器目前是否在代码片段模式下", - "在代码片段模式下时是否存在下一制表位", - "在代码片段模式下时是否存在上一制表位", - ], - "vs/editor/contrib/snippet/snippetVariables": [ - "星期天", - "星期一", - "星期二", - "星期三", - "星期四", - "星期五", - "星期六", - "周日", - "周一", - "周二", - "周三", - "周四", - "周五", - "周六", - "一月", - "二月", - "三月", - "四月", - "5月", - "六月", - "七月", - "八月", - "九月", - "十月", - "十一月", - "十二月", - "1月", - "2月", - "3月", - "4月", - "5月", - "6月", - "7月", - "8月", - "9月", - "10月", - "11 月", - "12月", - ], - "vs/editor/contrib/suggest/suggest": [ - "建议是否可见", - "建议详细信息是否可见", - "是否存在多条建议可供选择", - "插入当前建议是否会导致更改或导致已键入所有内容", - "按 Enter 时是否会插入建议", - "当前建议是否具有插入和替换行为", - "默认行为是否是插入或替换", - "当前建议是否支持解析更多详细信息", - ], - "vs/editor/contrib/suggest/suggestController": [ - "选择“{0}”后进行了其他 {1} 次编辑", - "触发建议", - "插入", - "插入", - "替换", - "替换", - "插入", - "显示更少", - "显示更多", - "重置建议小组件大小", - ], - "vs/editor/contrib/suggest/suggestWidget": [ - "建议小组件的背景色。", - "建议小组件的边框颜色。", - "建议小组件的前景色。", - "建议小组件中所选条目的前景色。", - "建议小组件中所选条目的图标前景色。", - "建议小组件中所选条目的背景色。", - "建议小组件中匹配内容的高亮颜色。", - "当某项获得焦点时,在建议小组件中突出显示的匹配项的颜色。", - "正在加载...", - "无建议。", - "{0},文档: {1}", - "建议", - ], - "vs/editor/contrib/suggest/suggestWidgetDetails": [ - "关闭", - "正在加载…", - ], - "vs/editor/contrib/suggest/suggestWidgetRenderer": [ - "建议小组件中的详细信息的图标。", - "了解详细信息", - ], - "vs/editor/contrib/suggest/suggestWidgetStatus": [ - "{0} ({1})", - ], - "vs/editor/contrib/symbolIcons/symbolIcons": [ - "数组符号的前景色。这些符号将显示在大纲、痕迹导航栏和建议小组件中。", - "布尔符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "类符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "颜色符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "常量符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "构造函数符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "枚举符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "枚举器成员符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "事件符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "字段符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "文件符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "文件夹符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "函数符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "接口符号的前景色。这些符号将显示在大纲、痕迹导航栏和建议小组件中。", - "键符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "关键字符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "方法符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "模块符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "命名空间符号的前景颜色。这些符号出现在轮廓、痕迹导航栏和建议小部件中。", - "空符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "数字符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "对象符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "运算符符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "包符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "属性符号的前景色。这些符号出现在大纲、痕迹导航栏和建议小组件中。", - "参考符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "片段符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "字符串符号的前景颜色。这些符号出现在轮廓、痕迹导航栏和建议小部件中。", - "结构符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "文本符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "类型参数符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "单位符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - "变量符号的前景颜色。这些符号出现在大纲、痕迹导航栏和建议小部件中。", - ], - "vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode": [ - "切换 Tab 键移动焦点", - "Tab 键将移动到下一可聚焦的元素", - "Tab 键将插入制表符", - ], - "vs/editor/contrib/tokenization/tokenization": [ - "开发人员: 强制重新进行标记", - ], - "vs/editor/contrib/unusualLineTerminators/unusualLineTerminators": [ - "异常行终止符", - "检测到异常行终止符", - "文件“{0}”包含一个或多个异常的行终止符,例如行分隔符(LS)或段落分隔符(PS)。\r\n\r\n建议从文件中删除它们。可通过“editor.unusualLineTerminators”进行配置。", - "删除异常行终止符", - "忽略", - ], - "vs/editor/contrib/wordHighlighter/wordHighlighter": [ - "读取访问期间符号的背景色,例如读取变量时。颜色必须透明,以免隐藏下面的修饰效果。", - "写入访问过程中符号的背景色,例如写入变量时。颜色必须透明,以免隐藏下面的修饰效果。", - "符号在进行读取访问操作时的边框颜色,例如读取变量。", - "符号在进行写入访问操作时的边框颜色,例如写入变量。", - "用于突出显示符号的概述标尺标记颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "用于突出显示写权限符号的概述标尺标记颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "转到下一个突出显示的符号", - "转到上一个突出显示的符号", - "触发符号高亮", - ], - "vs/editor/contrib/wordOperations/wordOperations": [ - "删除 Word", - ], - "vs/platform/actions/browser/menuEntryActionViewItem": [ - "{0} ({1})", - "{0} ({1})", - ], - "vs/platform/configuration/common/configurationRegistry": [ - "默认语言配置替代", - "针对某种语言,配置替代编辑器设置。", - "此设置不支持按语言配置。", - "无法注册空属性", - "无法注册“{0}”。其符合描述特定语言编辑器设置的表达式 \"\\\\[.*\\\\]$\"。请使用 \"configurationDefaults\"。", - "无法注册“{0}”。此属性已注册。", - ], - "vs/platform/contextkey/browser/contextKeyService": [ - "用于返回上下文键的相关信息的命令", - ], - "vs/platform/contextkey/common/contextkeys": [ - "操作系统是否为 Windows", - ], - "vs/platform/keybinding/common/abstractKeybindingService": [ - "({0})已按下。正在等待按下第二个键...", - "组合键({0},{1})不是命令。", - ], - "vs/platform/list/browser/listService": [ - "工作台", - "映射为 `Ctrl` (Windows 和 Linux) 或 `Command` (macOS)。", - "映射为 `Alt` (Windows 和 Linux) 或 `Option` (macOS)。", - "在通过鼠标多选树和列表条目时使用的修改键 (例如“资源管理器”、“打开的编辑器”和“源代码管理”视图)。“在侧边打开”功能所需的鼠标动作 (若可用) 将会相应调整,不与多选修改键冲突。", - "控制如何使用鼠标打开树和列表中的项(若支持)。请注意,如果此设置不适用,某些树和列表可能会选择忽略它。", - "控制列表和树是否支持工作台中的水平滚动。警告: 打开此设置影响会影响性能。", - "控制树缩进(以像素为单位)。", - "控制树是否应呈现缩进参考线。", - "控制列表和树是否具有平滑滚动效果。", - "对鼠标滚轮滚动事件的 `deltaX` 和 `deltaY` 乘上的系数。", - "按下\"Alt\"时滚动速度倍增。", - "简单键盘导航聚焦与键盘输入相匹配的元素。仅对前缀进行匹配。", - "高亮键盘导航会突出显示与键盘输入相匹配的元素。进一步向上和向下导航将仅遍历突出显示的元素。", - "筛选器键盘导航将筛选出并隐藏与键盘输入不匹配的所有元素。", - "控制工作台中的列表和树的键盘导航样式。它可为“简单”、“突出显示”或“筛选”。", - "控制列表和树中的键盘导航是否仅通过键入自动触发。如果设置为 `false` ,键盘导航只在执行 `list.toggleKeyboardNavigation` 命令时触发,您可以为该命令指定键盘快捷方式。", - "控制在单击文件夹名称时如何扩展树文件夹。请注意,如果不适用,某些树和列表可能会选择忽略此设置。", - ], - "vs/platform/markers/common/markers": [ - "错误", - "警告", - "信息", - ], - "vs/platform/quickinput/browser/commandsQuickAccess": [ - "{0}, {1}", - "最近使用", - "其他命令", - "命令\"{0}\"导致错误 ({1})", - ], - "vs/platform/quickinput/browser/helpQuickAccess": [ - "全局命令", - "编辑器命令", - "{0}, {1}", - ], - "vs/platform/theme/common/colorRegistry": [ - "整体前景色。此颜色仅在不被组件覆盖时适用。", - "错误信息的整体前景色。此颜色仅在不被组件覆盖时适用。", - "工作台中图标的默认颜色。", - "焦点元素的整体边框颜色。此颜色仅在不被其他组件覆盖时适用。", - "在元素周围额外的一层边框,用来提高对比度从而区别其他元素。", - "在活动元素周围额外的一层边框,用来提高对比度从而区别其他元素。", - "文本中链接的前景色。", - "文本中链接在点击或鼠标悬停时的前景色 。", - "文本中代码块的背景颜色。", - "编辑器内小组件(如查找/替换)的阴影颜色。", - "输入框背景色。", - "输入框前景色。", - "输入框边框。", - "输入字段中已激活选项的边框颜色。", - "输入字段中激活选项的背景颜色。", - "输入字段中已激活的选项的前景色。", - "输入验证结果为信息级别时的背景色。", - "输入验证结果为信息级别时的前景色。", - "严重性为信息时输入验证的边框颜色。", - "严重性为警告时输入验证的背景色。", - "输入验证结果为警告级别时的前景色。", - "严重性为警告时输入验证的边框颜色。", - "输入验证结果为错误级别时的背景色。", - "输入验证结果为错误级别时的前景色。", - "严重性为错误时输入验证的边框颜色。", - "下拉列表背景色。", - "下拉列表前景色。", - "按钮前景色。", - "按钮背景色。", - "按钮在悬停时的背景颜色。", - "Badge 背景色。Badge 是小型的信息标签,如表示搜索结果数量的标签。", - "Badge 前景色。Badge 是小型的信息标签,如表示搜索结果数量的标签。", - "表示视图被滚动的滚动条阴影。", - "滚动条滑块背景色", - "滚动条滑块在悬停时的背景色", - "滚动条滑块在被点击时的背景色。", - "表示长时间操作的进度条的背景色。", - "编辑器中错误文本的背景色。颜色必须透明,以免隐藏下面的修饰效果。", - "编辑器中错误波浪线的前景色。", - "编辑器中错误框的边框颜色。", - "编辑器中警告文本的背景色。颜色必须透明,以免隐藏下面的修饰效果。", - "编辑器中警告波浪线的前景色。", - "编辑器中警告框的边框颜色。", - "编辑器中信息文本的背景色。颜色必须透明,以免隐藏下面的修饰效果。", - "编辑器中信息波浪线的前景色。", - "编辑器中信息框的边框颜色。", - "编辑器中提示波浪线的前景色。", - "编辑器中提示框的边框颜色。", - "编辑器背景色。", - "编辑器默认前景色。", - "编辑器组件(如查找/替换)背景颜色。", - "编辑器小部件的前景色,如查找/替换。", - "编辑器小部件的边框颜色。此颜色仅在小部件有边框且不被小部件重写时适用。", - "编辑器小部件大小调整条的边框颜色。此颜色仅在小部件有调整边框且不被小部件颜色覆盖时使用。", - "背景颜色快速选取器。快速选取器小部件是选取器(如命令调色板)的容器。", - "前景颜色快速选取器。快速选取器小部件是命令调色板等选取器的容器。", - "标题背景颜色快速选取器。快速选取器小部件是命令调色板等选取器的容器。", - "快速选取器分组标签的颜色。", - "快速选取器分组边框的颜色。", - "键绑定标签背景色。键绑定标签用于表示键盘快捷方式。", - "键绑定标签前景色。键绑定标签用于表示键盘快捷方式。", - "键绑定标签边框色。键绑定标签用于表示键盘快捷方式。", - "键绑定标签边框底部色。键绑定标签用于表示键盘快捷方式。", - "编辑器所选内容的颜色。", - "用以彰显高对比度的所选文本的颜色。", - "非活动编辑器中所选内容的颜色,颜色必须透明,以免隐藏下面的装饰效果。", - "具有与所选项相关内容的区域的颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "与所选项内容相同的区域的边框颜色。", - "当前搜索匹配项的颜色。", - "其他搜索匹配项的颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "限制搜索范围的颜色。颜色不能不透明,以免隐藏底层装饰。", - "当前搜索匹配项的边框颜色。", - "其他搜索匹配项的边框颜色。", - "限制搜索的范围的边框颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "在下面突出显示悬停的字词。颜色必须透明,以免隐藏下面的修饰效果。", - "编辑器悬停提示的背景颜色。", - "编辑器悬停的前景颜色。", - "光标悬停时编辑器的边框颜色。", - "编辑器悬停状态栏的背景色。", - "活动链接颜色。", - "内联提示的前景色", - "内联提示的背景色", - "Foreground color of inline hints for types", - "Background color of inline hints for types", - "Foreground color of inline hints for parameters", - "Background color of inline hints for parameters", - "用于灯泡操作图标的颜色。", - "用于灯泡自动修复操作图标的颜色。", - "已插入的文本的背景色。颜色必须透明,以免隐藏下面的修饰效果。", - "已删除的文本的背景色。颜色必须透明,以免隐藏下面的修饰效果。", - "插入的文本的轮廓颜色。", - "被删除文本的轮廓颜色。", - "两个文本编辑器之间的边框颜色。", - "差异编辑器的对角线填充颜色。对角线填充用于并排差异视图。", - "焦点项在列表或树活动时的背景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "焦点项在列表或树活动时的前景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "列表/树活动时,焦点项目的列表/树边框色。活动的列表/树具有键盘焦点,非活动的没有。", - "已选项在列表或树活动时的背景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "已选项在列表或树活动时的前景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "已选项在列表/树活动时的列表/树图标前景颜色。活动的列表/树具有键盘焦点,非活动的则没有。", - "已选项在列表或树非活动时的背景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "已选项在列表或树非活动时的前景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "已选项在列表/树非活动时的图标前景颜色。活动的列表/树具有键盘焦点,非活动的则没有。", - "非活动的列表或树控件中焦点项的背景颜色。活动的列表或树具有键盘焦点,非活动的没有。", - "列表/数非活动时,焦点项目的列表/树边框色。活动的列表/树具有键盘焦点,非活动的没有。", - "使用鼠标移动项目时,列表或树的背景颜色。", - "鼠标在项目上悬停时,列表或树的前景颜色。", - "使用鼠标移动项目时,列表或树进行拖放的背景颜色。", - "在列表或树中搜索时,其中匹配内容的高亮颜色。", - "在列表或树中搜索时,匹配活动聚焦项的突出显示内容的列表/树前景色。", - "列表和树中类型筛选器小组件的背景色。", - "列表和树中类型筛选器小组件的轮廓颜色。", - "当没有匹配项时,列表和树中类型筛选器小组件的轮廓颜色。", - "缩进参考线的树描边颜色。", - "缩进参考线的树描边颜色。", - "请改用 quickInputList.focusBackground", - "焦点项目的快速选择器前景色。", - "焦点项目的快速选取器图标前景色。", - "焦点项目的快速选择器背景色。", - "菜单的边框颜色。", - "菜单项的前景颜色。", - "菜单项的背景颜色。", - "菜单中选定菜单项的前景色。", - "菜单中所选菜单项的背景色。", - "菜单中所选菜单项的边框颜色。", - "菜单中分隔线的颜色。", - "使用鼠标悬停在操作上时显示工具栏背景", - "代码片段 Tab 位的高亮背景色。", - "代码片段 Tab 位的高亮边框颜色。", - "代码片段中最后的 Tab 位的高亮背景色。", - "代码片段中最后的制表位的高亮边框颜色。", - "用于查找匹配项的概述标尺标记颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "用于突出显示所选内容的概述标尺标记颜色。颜色必须透明,以免隐藏下面的修饰效果。", - "用于查找匹配项的迷你地图标记颜色。", - "Minimap marker color for repeating editor selections.", - "编辑器选区在迷你地图中对应的标记颜色。", - "用于错误的迷你地图标记颜色。", - "用于警告的迷你地图标记颜色。", - "迷你地图背景颜色。", - "Opacity of foreground elements rendered in the minimap. For example, \"#000000c0\" will render the elements with 75% opacity.", - "迷你地图滑块背景颜色。", - "悬停时,迷你地图滑块的背景颜色。", - "单击时,迷你地图滑块的背景颜色。", - "用于问题错误图标的颜色。", - "用于问题警告图标的颜色。", - "用于问题信息图标的颜色。", - ], - "vs/platform/theme/common/iconRegistry": [ - "要使用的字体的 ID。如果未设置,则使用最先定义的字体。", - "与图标定义关联的字体字符。", - "小组件中“关闭”操作的图标。", - ], - "vs/platform/undoRedo/common/undoRedoService": [ - "以下文件已关闭并且已在磁盘上修改: {0}。", - "以下文件已以不兼容的方式修改: {0}。", - "无法在所有文件中撤消“{0}”。{1}", - "无法在所有文件中撤消“{0}”。{1}", - "无法撤消所有文件的“{0}”,因为已更改 {1}", - "无法跨所有文件撤销“{0}”,因为 {1} 上已有一项撤消或重做操作正在运行", - "无法跨所有文件撤销“{0}”,因为同时发生了一项撤消或重做操作", - "是否要在所有文件中撤消“{0}”?", - "在 {0} 个文件中撤消", - "撤消此文件", - "取消", - "无法撤销“{0}”,因为已有一项撤消或重做操作正在运行。", - "是否要撤消“{0}”?", - "是", - "取消", - "无法在所有文件中重做“{0}”。{1}", - "无法在所有文件中重做“{0}”。{1}", - "无法对所有文件重做“{0}”,因为已更改 {1}", - "无法跨所有文件重做“{0}”,因为 {1} 上已有一项撤消或重做操作正在运行", - "无法跨所有文件重做“{0}”,因为同时发生了一项撤消或重做操作", - "无法重做“{0}”,因为已有一项撤消或重做操作正在运行。", - ] -}; \ No newline at end of file diff --git a/magic-editor/src/console/public/favicon.png b/magic-editor/src/console/public/favicon.png deleted file mode 100644 index 083443bf..00000000 Binary files a/magic-editor/src/console/public/favicon.png and /dev/null differ diff --git a/magic-editor/src/console/public/index.html b/magic-editor/src/console/public/index.html deleted file mode 100644 index 11c434a4..00000000 --- a/magic-editor/src/console/public/index.html +++ /dev/null @@ -1,160 +0,0 @@ - - - - - - - - <%= htmlWebpackPlugin.options.title %> - - - - - -
-
-
- L - o - a - d - i - n - g -
-
-
-
- - - -
- - - diff --git a/magic-editor/src/console/src/App.vue b/magic-editor/src/console/src/App.vue deleted file mode 100644 index ae3afe87..00000000 --- a/magic-editor/src/console/src/App.vue +++ /dev/null @@ -1,45 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/api/request.js b/magic-editor/src/console/src/api/request.js deleted file mode 100644 index f6f4a394..00000000 --- a/magic-editor/src/console/src/api/request.js +++ /dev/null @@ -1,194 +0,0 @@ -import axios from 'axios' -import Qs from 'qs' -import {modal} from '@/components/common/modal' -import contants from '@/scripts/contants.js' -import bus from '@/scripts/bus.js' - -const config = { - // 请求路径 - baseURL: '', - // 默认请求方法 - method: 'post', - // 请求超时时间(毫秒) - timeout: 0, - // 是否携带cookie信息 - withCredentials: true, - // 响应格式,可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' - responseType: 'json', - // 自定义添加头部 - headers: { - // ;charset=UTF-8 - 'Content-Type': 'application/x-www-form-urlencoded' - }, - // `transformRequest` 允许在向服务器发送前,修改请求数据 - // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 - // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream - transformRequest: [ - function (data) { - if(data instanceof FormData){ - return data; - } - return Qs.stringify(data, { - // a:[1,2] => a=1&a=2 - arrayFormat: 'repeat', - // a[b]:1 => a.b=1 - allowDots: true - }) - } - ], - paramsSerializer(data) { - return Qs.stringify(data, { - // a:[1,2] => a=1&a=2 - arrayFormat: 'repeat', - // a[b]:1 => a.b=1 - allowDots: true - }) - } -} - -class HttpResponse { - // 请求成功调用 code == 1的 - successHandle = null - // 请求异常,包含js异常调用 - errorHandle = null - - endHandle = null - - constructor() { - } - - // 异常回调,实际上的code != 1的 - exceptionHandle = (code, message) => { - modal.magicAlert({ - title: `请求出错,异常代码(${code})`, - content: message - }) - } - - // 调用返回成功需要注入的变量 - success(handle) { - this.successHandle = handle - return this - } - - exception(handle) { - this.exceptionHandle = handle - return this - } - - // 调用异常需要注入的变量 - error(handle) { - this.errorHandle = handle - return this - } - - end(handle) { - this.endHandle = handle; - } -} - -class HttpRequest { - _axios = null - - constructor() { - this._axios = axios.create(config) - } - - // 返回初始化过后的axios - getAxios() { - return this._axios - } - - setBaseURL(baseURL) { - config.baseURL = baseURL - } - - execute(requestConfig) { - let _config = { - baseURL: config.baseURL, - ...requestConfig - } - _config.headers = _config.headers || {}; - _config.headers[contants.HEADER_MAGIC_TOKEN] = contants.HEADER_MAGIC_TOKEN_VALUE - return this._axios.request(_config); - } - - processError(error) { - if (error.response) { - modal.magicAlert({ - title: `请求出错HttpStatus:(${error.response.status})`, - content: JSON.stringify(error.response.data || '') || `请求出错HttpStatus:(${error.response.status})` - }) - } else { - modal.magicAlert({ - title: `请求出错`, - content: error.message - }) - } - console.error(error) - } - - // 发送默认请求 - send(url, params, newConfig) { - let requestConfig = newConfig || config || {} - requestConfig.url = url - if (requestConfig.method === 'post') { - requestConfig.data = params - } else { - requestConfig.params = params - } - requestConfig.baseURL = config.baseURL - let httpResponse = new HttpResponse() - let successed = false; - let processResult = (data, response) => { - if(data instanceof Blob){ - successed = true - httpResponse.successHandle && httpResponse.successHandle(data, response) - } else if (data.code === 1) { - successed = true - httpResponse.successHandle && httpResponse.successHandle(data.data, response) - } else { - if (data.code === 401) { - bus.$emit('showLogin') - } - httpResponse.exceptionHandle && httpResponse.exceptionHandle(data.code, data.message, response) - } - } - this.execute(requestConfig) - .then(response => { - let data = response.data - let isJson = response.headers['content-type'] && response.headers['content-type'].startsWith('application/json') - if(data instanceof Blob && isJson){ - let reader = new FileReader() - reader.readAsText(data) - reader.onload = function() { - try{ - data = JSON.parse(this.result) - processResult(data, response) - }catch(e){ - console.error(e); - processResult(data, response) - } - } - return; - } - processResult(data, response) - }) - .catch((error) => { - if (typeof httpResponse.errorHandle === 'function') { - httpResponse.errorHandle(error.response.data, error.response, error) - } else { - this.processError(error) - - } - }) - .finally(() => { - if (typeof httpResponse.endHandle === 'function') { - httpResponse.endHandle(successed) - } - }) - return httpResponse - } -} - -export default new HttpRequest() diff --git a/magic-editor/src/console/src/api/web.js b/magic-editor/src/console/src/api/web.js deleted file mode 100644 index e69de29b..00000000 diff --git a/magic-editor/src/console/src/assets/JetBrainsMono-Regular.woff2 b/magic-editor/src/console/src/assets/JetBrainsMono-Regular.woff2 deleted file mode 100644 index 8c862e33..00000000 Binary files a/magic-editor/src/console/src/assets/JetBrainsMono-Regular.woff2 and /dev/null differ diff --git a/magic-editor/src/console/src/assets/iconfont/iconfont.css b/magic-editor/src/console/src/assets/iconfont/iconfont.css deleted file mode 100644 index c75f51f0..00000000 --- a/magic-editor/src/console/src/assets/iconfont/iconfont.css +++ /dev/null @@ -1,248 +0,0 @@ -@font-face { - font-family: "magic-iconfont"; /* Project id 1928593 */ - src: url('iconfont.ttf?t=1628077606269') format('truetype'); -} - -.ma-icon { - font-family: "magic-iconfont" !important; - font-size: 16px; - font-style: normal; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -.ma-icon-lock:before { - content: "\e64f"; -} - -.ma-icon-unlock:before { - content: "\e783"; -} - -.ma-icon-collapse:before { - content: "\e609"; -} - -.ma-icon-expand:before { - content: "\efad"; -} - -.ma-icon-mysql:before { - content: "\e61e"; -} - -.ma-icon-postgresql:before { - content: "\e603"; -} - -.ma-icon-oracle:before { - content: "\e7c8"; -} - -.ma-icon-event:before { - content: "\e664"; -} - -.ma-icon-sql-server:before { - content: "\e605"; -} - -.ma-icon-clickhouse:before { - content: "\ec35"; -} - -.ma-icon-todo:before { - content: "\e602"; -} - -.ma-icon-push:before { - content: "\e79d"; -} - -.ma-icon-copy:before { - content: "\ec7a"; -} - -.ma-icon-move:before { - content: "\e727"; -} - -.ma-icon-update:before { - content: "\e7e4"; -} - -.ma-icon-logout:before { - content: "\e65a"; -} - -.ma-icon-datasource:before { - content: "\e615"; -} - -.ma-icon-table:before { - content: "\e619"; -} - -.ma-icon-upload:before { - content: "\e658"; -} - -.ma-icon-download:before { - content: "\e659"; -} - -.ma-icon-http-api:before { - content: "\e6e3"; -} - -.ma-icon-function:before { - content: "\e604"; -} - -.ma-icon-search:before { - content: "\e608"; -} - -.ma-icon-refresh:before { - content: "\e747"; -} - -.ma-icon-ascending:before { - content: "\e7a7"; -} - -.ma-icon-descending:before { - content: "\e7a8"; -} - -.ma-icon-group-add:before { - content: "\e6cd"; -} - -.ma-icon-folding:before { - content: "\e647"; -} - -.ma-icon-minus:before { - content: "\e68a"; -} - -.ma-icon-plus:before { - content: "\e621"; -} - -.ma-icon-api:before { - content: "\e700"; -} - -.ma-icon-settings:before { - content: "\e786"; -} - -.ma-icon-star:before { - content: "\e601"; -} - -.ma-icon-unfold:before { - content: "\e732"; -} - -.ma-icon-fold:before { - content: "\e66b"; -} - -.ma-icon-step-over:before { - content: "\e7b2"; -} - -.ma-icon-history:before { - content: "\e668"; -} - -.ma-icon-log:before { - content: "\efac"; -} - -.ma-icon-minimize:before { - content: "\e707"; -} - -.ma-icon-save:before { - content: "\e66c"; -} - -.ma-icon-close:before { - content: "\e652"; -} - -.ma-icon-skin:before { - content: "\e606"; -} - -.ma-icon-qq:before { - content: "\e635"; -} - -.ma-icon-help:before { - content: "\e60d"; -} - -.ma-icon-git:before { - content: "\e64a"; -} - -.ma-icon-gitee:before { - content: "\e6d6"; -} - -.ma-icon-delete:before { - content: "\e607"; -} - -.ma-icon-clear:before { - content: "\e673"; -} - -.ma-icon-continue:before { - content: "\e663"; -} - -.ma-icon-format:before { - content: "\e6c1"; -} - -.ma-icon-script:before { - content: "\e61d"; -} - -.ma-icon-arrow-right:before { - content: "\e600"; -} - -.ma-icon-arrow-bottom:before { - content: "\efa2"; -} - -.ma-icon-list:before { - content: "\e679"; -} - -.ma-icon-options:before { - content: "\e60f"; -} - -.ma-icon-debug-info:before { - content: "\efa1"; -} - -.ma-icon-run:before { - content: "\e626"; -} - -.ma-icon-parameter:before { - content: "\e6e9"; -} - -.ma-icon-position:before { - content: "\e60b"; -} \ No newline at end of file diff --git a/magic-editor/src/console/src/assets/iconfont/iconfont.ttf b/magic-editor/src/console/src/assets/iconfont/iconfont.ttf deleted file mode 100644 index 9613d80b..00000000 Binary files a/magic-editor/src/console/src/assets/iconfont/iconfont.ttf and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/array.gif b/magic-editor/src/console/src/assets/images/array.gif deleted file mode 100644 index ce7b369c..00000000 Binary files a/magic-editor/src/console/src/assets/images/array.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/elbow-end.gif b/magic-editor/src/console/src/assets/images/elbow-end.gif deleted file mode 100644 index f24ddee7..00000000 Binary files a/magic-editor/src/console/src/assets/images/elbow-end.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/elbow-line.gif b/magic-editor/src/console/src/assets/images/elbow-line.gif deleted file mode 100644 index 75e6da4f..00000000 Binary files a/magic-editor/src/console/src/assets/images/elbow-line.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/elbow.gif b/magic-editor/src/console/src/assets/images/elbow.gif deleted file mode 100644 index b8f42083..00000000 Binary files a/magic-editor/src/console/src/assets/images/elbow.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/object.gif b/magic-editor/src/console/src/assets/images/object.gif deleted file mode 100644 index 8b40d072..00000000 Binary files a/magic-editor/src/console/src/assets/images/object.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/images/s.gif b/magic-editor/src/console/src/assets/images/s.gif deleted file mode 100644 index 1d11fa9a..00000000 Binary files a/magic-editor/src/console/src/assets/images/s.gif and /dev/null differ diff --git a/magic-editor/src/console/src/assets/index.css b/magic-editor/src/console/src/assets/index.css deleted file mode 100644 index f40ccfc2..00000000 --- a/magic-editor/src/console/src/assets/index.css +++ /dev/null @@ -1,350 +0,0 @@ -@font-face{ - font-family:JetBrainsMono; - src:url(JetBrainsMono-Regular.woff2) format("woff2"); - font-weight:100; - font-style:normal -} -.ma-container { - font-size: 12px; - font-family: 'JetBrainsMono','Consolas', "Courier New",monospace, '微软雅黑'; - letter-spacing: 0px; - overflow: auto; - display: flex; - flex-direction: column; - position: relative; - width: 100%; - height: 100%; - min-width: 1200px; - min-height: 600px; - --color: #000; - --empty-color: #505050; - --empty-key-color: #5263A0; - --background: #f2f2f2; - --empty-background: #B6B6B6; - --border-color: #cdcdcd; - --input-border-color: #bdbdbd; - --input-border-foucs-color: #0784DE; - --input-background: #fff; - --select-border-color: #808080; - --select-background: #e3e3e3; - --select-icon-background: #fff; - --select-option-background: #fff; - --select-hover-background: #e3f1fa; - --select-option-hover-background: #1A7DC4; - --select-option-hover-color: #fff; - --select-option-disabled-color: #c0c4cc; - --select-inputable-background: #fff; - --select-inputable-border: #bdbdbd; - --checkbox-background: #fff; - --checkbox-text-color: #fff; - --checkbox-border: #b0b0b0; - --checkbox-selected-border: #4F9EE3; - --checkbox-selected-background: #4F9EE3; - --scollbar-color: rgba(170, 170, 170, .7); - --scollbar-background: rgba(221, 221, 221, .3); - --scollbar-thumb-background: rgba(170, 170, 170, .4); - --scollbar-thumb-hover-background: rgba(170, 170, 170, .7); - --scollbar-scrollbar-corner-background: rgba(221, 221, 221, .3); - --header-title-color: #000; - --header-version-color: #333; - --header-default-color: #6e6e6e; - - --dialog-button-hover-border-color: #99a0a5; - --dialog-button-hover-background: #E3F1FA; - --dialog-button-background: #E3E3E3; - --dialog-button-border: #ADADAD; - - --dialog-border-color: #707070; - --dialog-shadow-color: #cfcfcf; - - --middle-background: #F0F0F0; - - --button-run-color: #59A869; - --button-hover-background: #d9d9d9; - --button-disabled-background: #BDBDBD; - --toolbox-border-right-color: #c0c0c0; - /* 左侧工具条边框颜色 */ - --toolbox-border-color: #c9c9c9; - /* 图标颜色 */ - --icon-color: #6e6e6e; - /* DEBUG图标颜色 */ - --icon-debug-color: #59A869; - --icon-step-color: #389FD6; - /* 选中时背景颜色 */ - --selected-background: #bdbdbd; - /* 悬浮时背景颜色 */ - --hover-background: #d9d9d9; - /* 左侧工具条列表悬浮时背景颜色 */ - --toolbox-list-hover-background: #d4d4d4; - --toolbox-background: #fff; - /* 左侧工具条列表选中时背景颜色 */ - --toolbox-list-selected-background: #d4d4d4; - /* 左侧工具条列表中图标的颜色 */ - --toolbox-list-icon-color: #aeb9c0; - /* 左侧工具条列表中span的文字颜色 */ - --toolbox-list-span-color: #999; - /* 左侧工具条列表中label的文字颜色 */ - --toolbox-list-label-color: #000; - /* 左侧工具条列表中箭头图标的颜色 */ - --toolbox-list-arrow-color: #b3b3b3; - /* 左侧工具条列表中头部图标的颜色 */ - --toolbox-list-header-icon-color: #7f7f7f; - - /* 中间选项卡边框颜色 */ - --tab-bar-border-color: #c9c9c9; - /* 底部状态条边框颜色 */ - --footer-border-color: #919191; - /* 表格边框颜色*/ - --table-col-border-color: #e5e5e5; - --table-row-border-color: #c0c0c0; - --table-even-background: #F2F5F9; - --table-hover-color: #fff; - --table-hover-background: #1A7DC4; - - - --breakpoints-background: #db5860; - --debug-line-background: #2154A6; - --breakpoint-line-background: #FAEAE6; - - --todo-color: #008DDE; - --history-select-background: #1A7DC4; - --history-select-color: #fff; - - --text-number-color: #0000FF; - --text-string-color: #008000; - --text-boolean-color: #000080; - --text-default-color: #000000; - --text-key-color: #660e7a; - --suggest-hover-background: #D6EBFF; - --suggest-hover-color: #000; - --statusbar-em-color: #007f31; - --run-log-background: #fff; - /* 日志级别颜色 */ - --log-color-info: #00cd00; - --log-color-warn: #A66F00; - --log-color-debug: #00cccc; - --log-color-error: #cd0000; - --log-color-trace: #0000EE; - --log-color-cyan: #00CCCC; - --log-color-link: #006DCC; - scrollbar-color: var(--scollbar-color) var(--scollbar-color); - scrollbar-width: thin; - outline: 0; - -} - -.ma-container pre, -.ma-container .monaco-editor{ - font-family: 'JetBrainsMono','Consolas', "Courier New",monospace, '微软雅黑'; -} - -.ma-container * { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -.ma-container label { - font-weight: normal; -} - -.ma-container .ma-logo, -.ma-container .ma-dialog-wrapper .ma-dialog .ma-dialog-header { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAA/1BMVEUIfPoENm0CHz8CIUMAAAAAAwYqKioaGhoQEBAsLCwQEBAJCQkrKysDAwMCAgL6+vr19fUWFhaJiYn8/PylpaWAgID8/PxmZmYSEhLk5ORJSUnLy8vk5OSgoKAFBQXk5OS7u7upqakmJiaqqqqDg4Pp6em5ubmQkJBNTU3x8fF4eHjn5+cBAQE5OTlwcHDm5uafn5/Nzc1+fn6lpaX09PTs7OwpKSk5OTn8/PwsLCz5+flHR0fV1dVsbGzY2NhwcHAMDAzu7u5gYGAMDAwJCQkAAAAHBwcGBgYHBwcEBAQHBwcGBgZtbGyvrq5ERERLSkp5eHgvLy8CIkQABAgABw6+8utZAAAAAWJLR0QEj2jZUQAAAAd0SU1FB+UIFBENHjcTIfEAAACNSURBVBjTY2DAAIxMSIAZKMDEggRYwQJs7CwcnFws3Dy8EAE+fgFBIWERFlExcYiAhLCklLSMrJy8giJEQElYWUVVTV1DU0tbByygK6ynb2BoZGxiKmwGFjC3sLSytrG1s3dwdILY4szi4urm7uHJ4uXNitUdPr5g4AcX8A8Ag0CES9G0BAUjgRBMzwMA2+sWGs+mksMAAAAuelRYdGRhdGU6Y3JlYXRlAAAImTMyMDLUNbDQNTIIMbC0MjS2MjbQNrCwMjAAAEGIBQ9X33PQAAAALnpUWHRkYXRlOm1vZGlmeQAACJkzMjAy1DWw0DUyCDGwtDI0tjI20DawsDIwAABBiAUPfuDbWAAAAABJRU5ErkJggg==); -} - -.ma-container input::-webkit-input-placeholder { - /* WebKit browsers */ - font-size: 12px; -} - -.ma-container input::-moz-placeholder { - /* Mozilla Firefox 19+ */ - font-size: 12px; -} - -.ma-container input:-ms-input-placeholder { - /* Internet Explorer 10+ */ - font-size: 12px; -} -.ma-container * { - scrollbar-color: var(--scollbar-thumb-background) var(--scollbar-thumb-background); - scrollbar-track-color: var(--scollbar-thumb-background); - -ms-scrollbar-track-color: var(--scollbar-thumb-background); - scrollbar-width: thin; -} -.ma-container *::-webkit-scrollbar { - width: 7px; - height: 7px; - background: var(--scollbar-background); -} - -.ma-container *::-webkit-scrollbar-thumb { - border-radius: 5px; - background: var(--scollbar-thumb-background); -} - -.ma-container *::-webkit-scrollbar-thumb:hover { - background: var(--scollbar-thumb-hover-background); -} - -.ma-container *::-webkit-scrollbar-corner { - background: var(--scollbar-scrollbar-corner-background); -} - -.ma-container .not-select { - -moz-user-select: none; - -webkit-user-select: none; - -ms-user-select: none; - -khtml-user-select: none; - user-select: none; -} - -.ma-container .monaco-editor .margin-view-overlays .codicon-folding-expanded, -.ma-container .monaco-editor .margin-view-overlays .codicon-folding-collapsed { - margin-left: 12px !important; -} - -.ma-container ul li { - list-style: none; -} - - -.ma-container .breakpoints { - background: var(--breakpoints-background); - width: 10px !important; - height: 10px !important; - right: 0px !important; - margin-left: 12px; - top: 5px; - border-radius: 5px; -} - -.ma-container .debug-line { - background: var(--debug-line-background); - color: #fff !important; -} - -.ma-container .breakpoint-line { - background: var(--breakpoint-line-background); -} -.ma-icon.ma-icon-http-api{ - color: #87CEE7 !important; -} -.ma-icon.ma-icon-function{ - color: #F3C373 !important; -} - -.ma-container .ma-button { - height: 22px; - line-height: 22px; - background: var(--dialog-button-background); - text-align: center; - padding: 0 15px; - border: 1px solid var(--dialog-button-border); - outline: 0; - cursor: pointer; - color: var(--color); -} -.ma-container .ma-button.active, -.ma-container .ma-button:hover { - background: var(--dialog-button-hover-background); - border-color: var(--dialog-button-hover-border-color); -} - -.ma-request-wrapper { - background: var(--background); - height: 100%; - width: 100%; - position: relative; -} - -.ma-api-info { - padding: 5px; - border-bottom: 1px solid var(--tab-bar-border-color); - display: flex; -} - -.ma-api-info * { - display: inline-block; -} - -.ma-api-info label { - width: 75px; - text-align: right; - padding: 0 5px; - height: 22px; - line-height: 22px; -} - -.ma-api-info > .ma-select { - width: 80px; -} - -.ma-request-wrapper > div:not(.ma-api-info) { - position: absolute; - top: 33px; - bottom: 0px; - width: 100%; - overflow: hidden; - display: inline-block; -} - -.ma-request-wrapper > div > h3 { - color: var(--color); - font-size: 12px; - font-weight: inherit; - height: 24px; - line-height: 24px; - text-align: center; - border-bottom: 1px solid var(--tab-bar-border-color); -} - -.ma-table-request-row { - display: flex; -} - -.ma-container .monaco-list .monaco-list-row.focused{ - background-color: var(--suggest-hover-background) !important; - color: var(--suggest-hover-color) !important; -} -.ma-container .monaco-list-row.focused .monaco-highlighted-label .highlight{ - color: #0097fb !important -} -.ma-container .ma-status-container em,.ma-event .ma-content em{ - color: var(--statusbar-em-color); - font-style: normal; - font-weight: bold; -} - -.ma-log pre span.log-INFO{ - color: var(--log-color-info); -} -.ma-log pre span.log-DEBUG{ - color: var(--log-color-debug); -} -.ma-log pre span.log-ERROR{ - color: var(--log-color-error); -} -.ma-log pre span.log-WARN{ - color: var(--log-color-warn); -} -.ma-log pre span.log-TRACE{ - color: var(--log-color-trace); -} -.ma-log pre span.log-cyan{ - color: var(--log-color-cyan); -} -.ma-log pre a.log-link{ - color: var(--log-color-link); -} - -/** 旋转特效 **/ -@keyframes rotate { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-bottom-panel.vue b/magic-editor/src/console/src/components/common/magic-bottom-panel.vue deleted file mode 100644 index a2e40d80..00000000 --- a/magic-editor/src/console/src/components/common/magic-bottom-panel.vue +++ /dev/null @@ -1,63 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/common/magic-checkbox.vue b/magic-editor/src/console/src/components/common/magic-checkbox.vue deleted file mode 100644 index 685405bb..00000000 --- a/magic-editor/src/console/src/components/common/magic-checkbox.vue +++ /dev/null @@ -1,82 +0,0 @@ - - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-contextmenu/Contextmenu.vue b/magic-editor/src/console/src/components/common/magic-contextmenu/Contextmenu.vue deleted file mode 100644 index f8bc588f..00000000 --- a/magic-editor/src/console/src/components/common/magic-contextmenu/Contextmenu.vue +++ /dev/null @@ -1,130 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/common/magic-contextmenu/Submenu.vue b/magic-editor/src/console/src/components/common/magic-contextmenu/Submenu.vue deleted file mode 100644 index ff443414..00000000 --- a/magic-editor/src/console/src/components/common/magic-contextmenu/Submenu.vue +++ /dev/null @@ -1,290 +0,0 @@ - - - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-contextmenu/constant.js b/magic-editor/src/console/src/components/common/magic-contextmenu/constant.js deleted file mode 100644 index ed13584b..00000000 --- a/magic-editor/src/console/src/components/common/magic-contextmenu/constant.js +++ /dev/null @@ -1,5 +0,0 @@ -export const SUBMENU_X_OFFSET = 3; -export const SUBMENU_Y_OFFSET = 0; -export const SUBMENU_OPEN_TREND_LEFT = "left"; -export const SUBMENU_OPEN_TREND_RIGHT = "right"; -export const COMPONENT_NAME = "magic-contextmenu-submenu"; diff --git a/magic-editor/src/console/src/components/common/magic-contextmenu/index.js b/magic-editor/src/console/src/components/common/magic-contextmenu/index.js deleted file mode 100644 index 420efd59..00000000 --- a/magic-editor/src/console/src/components/common/magic-contextmenu/index.js +++ /dev/null @@ -1,39 +0,0 @@ -import Vue from 'vue'; -import Contextmenu from "./Contextmenu"; -import Submenu from "./Submenu"; -import {COMPONENT_NAME} from "./constant"; - -const ContextmenuConstructor = Vue.extend(Contextmenu); -Vue.component(COMPONENT_NAME, Submenu); - -function install(Vue) { - let lastInstance = null; - const ContextmenuProxy = function (options) { - let instance = new ContextmenuConstructor(); - instance.menus = options.menus; - instance.position.x = options.x || 0; - instance.position.y = options.y || 0; - if (options.event) { - instance.position.x = options.event.clientX; - instance.position.y = options.event.clientY; - } - instance.customClass = options.customClass; - options.minWidth && (instance.style.minWidth = options.minWidth); - options.zIndex && (instance.style.zIndex = options.zIndex); - instance.destroy = options.destroy; - ContextmenuProxy.destroy(); - lastInstance = instance; - instance.$mount(); - }; - ContextmenuProxy.destroy = function (options) { - if (lastInstance) { - lastInstance.$destroy(); - lastInstance = null; - } - }; - Vue.prototype.$magicContextmenu = ContextmenuProxy; -} - -export default { - install -}; diff --git a/magic-editor/src/console/src/components/common/magic-contextmenu/util.js b/magic-editor/src/console/src/components/common/magic-contextmenu/util.js deleted file mode 100644 index ffee2483..00000000 --- a/magic-editor/src/console/src/components/common/magic-contextmenu/util.js +++ /dev/null @@ -1,24 +0,0 @@ -export function hasClass(el, className) { - if (!className) { - return true; - } - if (!el || !el.className || typeof el.className !== 'string') { - return false; - } - for (let cn of el.className.split(/\s+/)) { - if (cn === className) { - return true; - } - } - return false; -} - -export function getElementsByClassName(className) { - let els = []; - for (let el of document.getElementsByClassName(className) || []) { - els.push(el); - } - return els; -} - - diff --git a/magic-editor/src/console/src/components/common/magic-file.vue b/magic-editor/src/console/src/components/common/magic-file.vue deleted file mode 100644 index 7a55ada8..00000000 --- a/magic-editor/src/console/src/components/common/magic-file.vue +++ /dev/null @@ -1,56 +0,0 @@ - - - diff --git a/magic-editor/src/console/src/components/common/magic-input.vue b/magic-editor/src/console/src/components/common/magic-input.vue deleted file mode 100644 index 1144c932..00000000 --- a/magic-editor/src/console/src/components/common/magic-input.vue +++ /dev/null @@ -1,81 +0,0 @@ - - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-json-tree-format.vue b/magic-editor/src/console/src/components/common/magic-json-tree-format.vue deleted file mode 100644 index 77d8dfd5..00000000 --- a/magic-editor/src/console/src/components/common/magic-json-tree-format.vue +++ /dev/null @@ -1,35 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-json-tree.vue b/magic-editor/src/console/src/components/common/magic-json-tree.vue deleted file mode 100644 index fcc7324b..00000000 --- a/magic-editor/src/console/src/components/common/magic-json-tree.vue +++ /dev/null @@ -1,108 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-json.vue b/magic-editor/src/console/src/components/common/magic-json.vue deleted file mode 100644 index 2b402d44..00000000 --- a/magic-editor/src/console/src/components/common/magic-json.vue +++ /dev/null @@ -1,242 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-loading.vue b/magic-editor/src/console/src/components/common/magic-loading.vue deleted file mode 100644 index 1e79d24f..00000000 --- a/magic-editor/src/console/src/components/common/magic-loading.vue +++ /dev/null @@ -1,141 +0,0 @@ - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-select.vue b/magic-editor/src/console/src/components/common/magic-select.vue deleted file mode 100644 index 7f0e9ce2..00000000 --- a/magic-editor/src/console/src/components/common/magic-select.vue +++ /dev/null @@ -1,161 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-structure-array.vue b/magic-editor/src/console/src/components/common/magic-structure-array.vue deleted file mode 100644 index 43950745..00000000 --- a/magic-editor/src/console/src/components/common/magic-structure-array.vue +++ /dev/null @@ -1,101 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-structure-object.vue b/magic-editor/src/console/src/components/common/magic-structure-object.vue deleted file mode 100644 index acaab255..00000000 --- a/magic-editor/src/console/src/components/common/magic-structure-object.vue +++ /dev/null @@ -1,90 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-structure.vue b/magic-editor/src/console/src/components/common/magic-structure.vue deleted file mode 100644 index bd409829..00000000 --- a/magic-editor/src/console/src/components/common/magic-structure.vue +++ /dev/null @@ -1,86 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-text-icon.vue b/magic-editor/src/console/src/components/common/magic-text-icon.vue deleted file mode 100644 index c96bbe9a..00000000 --- a/magic-editor/src/console/src/components/common/magic-text-icon.vue +++ /dev/null @@ -1,44 +0,0 @@ - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-textarea.vue b/magic-editor/src/console/src/components/common/magic-textarea.vue deleted file mode 100644 index 920c4ee8..00000000 --- a/magic-editor/src/console/src/components/common/magic-textarea.vue +++ /dev/null @@ -1,42 +0,0 @@ - - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/common/magic-tree-item.vue b/magic-editor/src/console/src/components/common/magic-tree-item.vue deleted file mode 100644 index bcb015c1..00000000 --- a/magic-editor/src/console/src/components/common/magic-tree-item.vue +++ /dev/null @@ -1,27 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/magic-tree.vue b/magic-editor/src/console/src/components/common/magic-tree.vue deleted file mode 100644 index 15d984a8..00000000 --- a/magic-editor/src/console/src/components/common/magic-tree.vue +++ /dev/null @@ -1,98 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/common/modal/index.js b/magic-editor/src/console/src/components/common/modal/index.js deleted file mode 100644 index 324020c5..00000000 --- a/magic-editor/src/console/src/components/common/modal/index.js +++ /dev/null @@ -1,60 +0,0 @@ -import MagicAlert from './magic-alert.vue' -import MagicConfirm from './magic-confirm.vue' -import MagicDialog from './magic-dialog.vue' -import Vue from 'vue' - -const MagicAlertConstructor = Vue.extend(MagicAlert) -const MagicConfirmConstructor = Vue.extend(MagicConfirm) -const MagicDialogConstructor = Vue.extend(MagicDialog) - -const MagicAlertProxy = function (options) { - let instance = new MagicAlertConstructor() - instance.value = true - for (let key in options) { - if (options[key] !== undefined && options[key] !== null) { - instance[key] = options[key] - } - } - instance.$mount() - document.getElementsByClassName('ma-container')[0].append(instance.$el) -} -const MagicConfirmProxy = function (options) { - let instance = new MagicConfirmConstructor() - instance.value = true - for (let key in options) { - if (options[key] !== undefined && options[key] !== null) { - instance[key] = options[key] - } - } - instance.$mount() - document.getElementsByClassName('ma-container')[0].append(instance.$el) -} -const MagicDialogProxy = function (options) { - let instance = new MagicDialogConstructor() - instance.value = true - for (let key in options) { - if (options[key] !== undefined && options[key] !== null) { - instance[key] = options[key] - } - } - instance.$mount() - document.getElementsByClassName('ma-container')[0].append(instance.$el) -} - -function install(Vue) { - Vue.prototype.$magicAlert = MagicAlertProxy - Vue.prototype.$magicConfirm = MagicConfirmProxy - Vue.prototype.$magicDialog = MagicDialogProxy -} - -const modal = { - magicAlert: MagicAlertProxy, - magicConfirm: MagicConfirmProxy, - magicDialog: MagicDialogProxy -} - -export default { - install -} - -export {modal} diff --git a/magic-editor/src/console/src/components/common/modal/magic-alert.vue b/magic-editor/src/console/src/components/common/modal/magic-alert.vue deleted file mode 100644 index 6ad11dca..00000000 --- a/magic-editor/src/console/src/components/common/modal/magic-alert.vue +++ /dev/null @@ -1,59 +0,0 @@ - - diff --git a/magic-editor/src/console/src/components/common/modal/magic-confirm.vue b/magic-editor/src/console/src/components/common/modal/magic-confirm.vue deleted file mode 100644 index d0cd8556..00000000 --- a/magic-editor/src/console/src/components/common/modal/magic-confirm.vue +++ /dev/null @@ -1,75 +0,0 @@ - - diff --git a/magic-editor/src/console/src/components/common/modal/magic-dialog.vue b/magic-editor/src/console/src/components/common/modal/magic-dialog.vue deleted file mode 100644 index 96bf2f95..00000000 --- a/magic-editor/src/console/src/components/common/modal/magic-dialog.vue +++ /dev/null @@ -1,231 +0,0 @@ - - - diff --git a/magic-editor/src/console/src/components/editor/magic-history.vue b/magic-editor/src/console/src/components/editor/magic-history.vue deleted file mode 100644 index 361e491e..00000000 --- a/magic-editor/src/console/src/components/editor/magic-history.vue +++ /dev/null @@ -1,158 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/editor/magic-script-editor.vue b/magic-editor/src/console/src/components/editor/magic-script-editor.vue deleted file mode 100644 index 3c50b08d..00000000 --- a/magic-editor/src/console/src/components/editor/magic-script-editor.vue +++ /dev/null @@ -1,1050 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-debug.vue b/magic-editor/src/console/src/components/layout/magic-debug.vue deleted file mode 100644 index 816403ab..00000000 --- a/magic-editor/src/console/src/components/layout/magic-debug.vue +++ /dev/null @@ -1,134 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-event.vue b/magic-editor/src/console/src/components/layout/magic-event.vue deleted file mode 100644 index 8c337a8f..00000000 --- a/magic-editor/src/console/src/components/layout/magic-event.vue +++ /dev/null @@ -1,89 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-function.vue b/magic-editor/src/console/src/components/layout/magic-function.vue deleted file mode 100644 index 5bfdf3fc..00000000 --- a/magic-editor/src/console/src/components/layout/magic-function.vue +++ /dev/null @@ -1,172 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-group.vue b/magic-editor/src/console/src/components/layout/magic-group.vue deleted file mode 100644 index dd1d9eb5..00000000 --- a/magic-editor/src/console/src/components/layout/magic-group.vue +++ /dev/null @@ -1,217 +0,0 @@ - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/layout/magic-header.vue b/magic-editor/src/console/src/components/layout/magic-header.vue deleted file mode 100644 index dbbfa8c1..00000000 --- a/magic-editor/src/console/src/components/layout/magic-header.vue +++ /dev/null @@ -1,379 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-log.vue b/magic-editor/src/console/src/components/layout/magic-log.vue deleted file mode 100644 index 4cd6dc4e..00000000 --- a/magic-editor/src/console/src/components/layout/magic-log.vue +++ /dev/null @@ -1,99 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-login.vue b/magic-editor/src/console/src/components/layout/magic-login.vue deleted file mode 100644 index a05a92c8..00000000 --- a/magic-editor/src/console/src/components/layout/magic-login.vue +++ /dev/null @@ -1,68 +0,0 @@ - - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/layout/magic-option.vue b/magic-editor/src/console/src/components/layout/magic-option.vue deleted file mode 100644 index de8979fc..00000000 --- a/magic-editor/src/console/src/components/layout/magic-option.vue +++ /dev/null @@ -1,116 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-options.vue b/magic-editor/src/console/src/components/layout/magic-options.vue deleted file mode 100644 index e884265b..00000000 --- a/magic-editor/src/console/src/components/layout/magic-options.vue +++ /dev/null @@ -1,303 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-request.vue b/magic-editor/src/console/src/components/layout/magic-request.vue deleted file mode 100644 index a1c477cd..00000000 --- a/magic-editor/src/console/src/components/layout/magic-request.vue +++ /dev/null @@ -1,429 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-run.vue b/magic-editor/src/console/src/components/layout/magic-run.vue deleted file mode 100644 index 941ab610..00000000 --- a/magic-editor/src/console/src/components/layout/magic-run.vue +++ /dev/null @@ -1,223 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-search.vue b/magic-editor/src/console/src/components/layout/magic-search.vue deleted file mode 100644 index 76ba5546..00000000 --- a/magic-editor/src/console/src/components/layout/magic-search.vue +++ /dev/null @@ -1,238 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-settings.vue b/magic-editor/src/console/src/components/layout/magic-settings.vue deleted file mode 100644 index 3cef7328..00000000 --- a/magic-editor/src/console/src/components/layout/magic-settings.vue +++ /dev/null @@ -1,147 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-status-bar.vue b/magic-editor/src/console/src/components/layout/magic-status-bar.vue deleted file mode 100644 index 257896bd..00000000 --- a/magic-editor/src/console/src/components/layout/magic-status-bar.vue +++ /dev/null @@ -1,111 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/layout/magic-todo.vue b/magic-editor/src/console/src/components/layout/magic-todo.vue deleted file mode 100644 index a1232d4c..00000000 --- a/magic-editor/src/console/src/components/layout/magic-todo.vue +++ /dev/null @@ -1,152 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/magic-editor.vue b/magic-editor/src/console/src/components/magic-editor.vue deleted file mode 100644 index 5729a028..00000000 --- a/magic-editor/src/console/src/components/magic-editor.vue +++ /dev/null @@ -1,448 +0,0 @@ - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-api-list.vue b/magic-editor/src/console/src/components/resources/magic-api-list.vue deleted file mode 100644 index e3a38ba6..00000000 --- a/magic-editor/src/console/src/components/resources/magic-api-list.vue +++ /dev/null @@ -1,982 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-datasource-list.vue b/magic-editor/src/console/src/components/resources/magic-datasource-list.vue deleted file mode 100644 index 43bd907b..00000000 --- a/magic-editor/src/console/src/components/resources/magic-datasource-list.vue +++ /dev/null @@ -1,419 +0,0 @@ - - - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-function-list.vue b/magic-editor/src/console/src/components/resources/magic-function-list.vue deleted file mode 100644 index dff83b5b..00000000 --- a/magic-editor/src/console/src/components/resources/magic-function-list.vue +++ /dev/null @@ -1,883 +0,0 @@ - - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-group-choose.vue b/magic-editor/src/console/src/components/resources/magic-group-choose.vue deleted file mode 100644 index 17080524..00000000 --- a/magic-editor/src/console/src/components/resources/magic-group-choose.vue +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-recent-opened.vue b/magic-editor/src/console/src/components/resources/magic-recent-opened.vue deleted file mode 100644 index 2067b368..00000000 --- a/magic-editor/src/console/src/components/resources/magic-recent-opened.vue +++ /dev/null @@ -1,105 +0,0 @@ - - - \ No newline at end of file diff --git a/magic-editor/src/console/src/components/resources/magic-resource-choose.vue b/magic-editor/src/console/src/components/resources/magic-resource-choose.vue deleted file mode 100644 index 15f40452..00000000 --- a/magic-editor/src/console/src/components/resources/magic-resource-choose.vue +++ /dev/null @@ -1,365 +0,0 @@ - - - - - - diff --git a/magic-editor/src/console/src/components/resources/magic-resource.css b/magic-editor/src/console/src/components/resources/magic-resource.css deleted file mode 100644 index 5a6c1b87..00000000 --- a/magic-editor/src/console/src/components/resources/magic-resource.css +++ /dev/null @@ -1,109 +0,0 @@ -.ma-tree-wrapper:not(.ma-dialog-wrapper) { - text-align: left; - float: left; - border-right: 1px solid var(--toolbox-border-right-color); - overflow: auto; - width: 250px; - min-width: 250px; - background: var(--toolbox-background); - position: relative; -} - -.ma-tree-wrapper .ma-tree-item .ma-tree-item-header { - font-weight: bold; - height: 20px; - line-height: 20px; -} - -.ma-tree-wrapper .ma-tree-item .ma-tree-sub-items > * { - line-height: 20px; - /* padding-left: 17px; */ - white-space: nowrap; -} -.ma-tree-wrapper .ma-tree-item .ma-tree-item-header[dragtarget] label{ - border-color: red; -} -.ma-tree-wrapper .ma-tree-hover:hover, -.ma-tree-wrapper .ma-tree-select { - background: var(--toolbox-list-hover-background); -} - -.ma-tree-wrapper .ma-tree-item .ma-tree-sub-items > *.selected { - background: var(--toolbox-list-selected-background); -} - -.ma-tree-wrapper .ma-icon { - color: var(--toolbox-list-icon-color); - padding-right: 2px; - font-size: 14px; -} -.ma-tree-wrapper .ma-icon-arrow-bottom { - color: var(--toolbox-list-arrow-color); -} - -.ma-tree-wrapper span { - color: var(--toolbox-list-span-color); - display: inline-block; - height: 22px; - line-height: 22px; -} - -.ma-tree-wrapper .ma-icon-lock { - color: var(--toolbox-list-label-color); - margin-left: 5px; -} - -.ma-tree-wrapper label { - color: var(--toolbox-list-label-color); - display: inline-block; - border: 1px solid transparent; -} - -.ma-tree-wrapper .ma-tree-toolbar-search { - flex: 1; -} - -.ma-tree-wrapper .ma-tree-toolbar-search input { - border: none; - background: none; - height: 100%; - color: var(--input-color); -} - -.ma-tree-wrapper .ma-tree-toolbar-search input:focus { - outline: none; -} - -.ma-tree-wrapper .ma-tree-toolbar { - background: var(--background); - color: var(--toolbox-list-label-color); - border-bottom: 1px solid var(--border-color); - display: flex; - justify-content: space-between; - /* flex-direction: row-reverse; */ - padding: 1px; -} - -.ma-tree-wrapper .ma-tree-toolbar-btn { - padding: 2px; - align-self: flex-end; - display: inline-block; -} - -.ma-tree-wrapper .ma-tree-toolbar-btn:hover, -.ma-tree-wrapper .ma-tree-toolbar-btn.hover { - background: var(--toolbox-list-hover-background); -} - -.ma-tree-wrapper .ma-tree-toolbar i { - color: var(--toolbox-list-header-icon-color); -} - -.ma-tree-wrapper .ma-tree-container { - height: calc(100% - 25px); - overflow: auto; -} - -.ma-tree-wrapper .ma-icon-datasource{ - color: #089910; -} diff --git a/magic-editor/src/console/src/index.js b/magic-editor/src/console/src/index.js deleted file mode 100644 index 20ce39d2..00000000 --- a/magic-editor/src/console/src/index.js +++ /dev/null @@ -1,38 +0,0 @@ -import './assets/index.css' - -import MagicEditor from './components/magic-editor' -import MagicContextMenu from './components/common/magic-contextmenu' -import Modal from './components/common/modal' -import _Vue from 'vue' - -/* 打包组件使用 */ -import 'monaco-editor/esm/vs/editor/editor.worker.js' -import 'monaco-editor/esm/vs/language/json/json.worker.js' -import 'monaco-editor/esm/vs/language/json/workerManager' -import 'monaco-editor/esm/vs/language/json/jsonMode' - -export function install(Vue) { - if (install.installed) return - install.installed = true - Vue.component('MagicEditor', MagicEditor) - Vue.use(MagicContextMenu) - Vue.use(Modal) -} - -const plugin = { - install -} - -let GlobalVue = null -if (typeof window !== 'undefined' && window.Vue) { - GlobalVue = window.Vue -} else if (typeof global !== 'undefined' && global.Vue) { - GlobalVue = global.Vue -} else { - GlobalVue = _Vue; -} -if (GlobalVue) { - GlobalVue.use(plugin) -} - -export default MagicEditor \ No newline at end of file diff --git a/magic-editor/src/console/src/main.js b/magic-editor/src/console/src/main.js deleted file mode 100644 index fa7b1d1b..00000000 --- a/magic-editor/src/console/src/main.js +++ /dev/null @@ -1,13 +0,0 @@ -import Vue from 'vue' -import App from './App.vue' -import MagicContextMenu from './components/common/magic-contextmenu' -import Modal from './components/common/modal' - -Vue.config.productionTip = false - -Vue.use(MagicContextMenu) -Vue.use(Modal) - -new Vue({ - render: h => h(App), -}).$mount('#app') diff --git a/magic-editor/src/console/src/plugins/MagicEditorLocalesPlugin.js b/magic-editor/src/console/src/plugins/MagicEditorLocalesPlugin.js deleted file mode 100644 index 45ae1ebd..00000000 --- a/magic-editor/src/console/src/plugins/MagicEditorLocalesPlugin.js +++ /dev/null @@ -1,188 +0,0 @@ -'use strict' - -var webpackVersion = require('webpack/package.json').version; -var local = null; - -function compilerHook(compilation) { - if (webpackVersion < '4') { - compilation.plugin('succeed-module', compilationHook); - } else { - compilation.hooks.succeedModule.tap('MonacoEditorLocalesPlugin', compilationHook); - } -} - -function compilationHook(wpModule) { - if (!wpModule.resource || !wpModule.resource.indexOf || wpModule.resource.replace(/\\+/g, "/").indexOf("esm/vs/nls.js") < 0) { - return; - } - - var langStr = local.getSelectLangStr(); - - var endl = "\r\n"; - var code = wpModule._source._value; - code = code.replace("export function localize", " function _ocalize"); - - code += endl + "function localize(data, message) {"; - code += endl + " if(typeof(message) === 'string'){"; - code += endl + " var idx = localize.mapLangIdx[message] || -1;"; - code += endl + " var nlsLang = localize.mapNlsLang[localize.selectLang] || {};"; - code += endl + ""; - code += endl + " if(idx in nlsLang){"; - code += endl + " message = nlsLang[idx];"; - code += endl + " }"; - if (local.options.logUnmatched) { - code += endl + " else{"; - code += endl + " console.info('unknown lang:' + message);"; - code += endl + " }"; - } - code += endl + " }"; - code += endl + ""; - code += endl + " var args = [];"; - code += endl + " for(var i = 0; i < arguments.length; ++i){"; - code += endl + " args.push(arguments[i]);"; - code += endl + " }"; - code += endl + " args[1] = message;"; - code += endl + " return _ocalize.apply(this, args);"; - code += endl + "}"; - code += endl + "localize.selectLang = " + local.getSelectLangStr() + ";"; - if (langStr.indexOf('(') >= 0) { - code += endl + "try{ localize.selectLang = eval(localize.selectLang); }catch(ex){}"; - } - code += endl + "localize.mapLangIdx = " + JSON.stringify(local.mapLangIdx) + ";"; - code += endl + "localize.mapNlsLang = " + JSON.stringify(local.lang) + ";"; - // code += endl + "var mapSelfLang = " + JSON.stringify(local.options.mapLanguages) + ";"; - code += endl + ""; - - // wpModule._source = new OriginalSource(code, wpModule.identifier()); - wpModule._source._value = code; -} - -// const { OriginalSource } = require("webpack-sources"); -function MonacoEditorLocalesPlugin(options) { - this.options = { - /** - * support languages list, .eg ["de"] - * embed language base on monaco-editor@0.14.6 - * all available embed languages: de,es,fr,it,ja,ko,ru,zh-cn,zh-tw - * just add what you need to reduce the size - */ - languages: options.languages || [], - /** - * default language name, .eg "de" - * use function string to set dynamic, .eg "$.cookie('language')" - */ - defaultLanguage: options.defaultLanguage || options.languages[0] || "", - /** - * log on console if unmatched - */ - logUnmatched: options.logUnmatched || false, - /** - * self languages map, .eg {"zh-cn": {"Find": "查找", "Search": "搜索"}, "de":{}, ... } - */ - mapLanguages: options.mapLanguages || {}, - }; - - this.langIdx = 0; - this.mapLangIdx = {}; - this.lang = {}; - this.mapEmbedLangName = {}; - this.mapEmbedLangNameSelf = {}; - - this.init(); - this.initLang(); -} - -module.exports = MonacoEditorLocalesPlugin; - -MonacoEditorLocalesPlugin.prototype.apply = function (compiler) { - local = this; - - if (webpackVersion < '4') { - compiler.plugin("compilation", compilerHook); - } else { - compiler.hooks.compilation.tap('MonacoEditorLocalesPlugin', compilerHook); - } -} - -MonacoEditorLocalesPlugin.prototype.initLang = function () { - var arr = this.options.languages; - - for (var i = 0; i < arr.length; ++i) { - if (!(arr[i] in this.mapEmbedLangName)) { - return; - } - - var obj = this.mapEmbedLangName[arr[i]]; - if (!obj) { - continue; - } - - var rstObj = this.lang[arr[i]] || (this.lang[arr[i]] = {}); - this.initOneLang(rstObj, this.mapEmbedLangName["en"], obj); - - - var objSelf = this.mapEmbedLangNameSelf[arr[i]]; - if (!objSelf) { - continue; - } - this.initSelfOneLang(rstObj, objSelf); - - objSelf = this.options.mapLanguages[arr[i]]; - if (!objSelf) { - continue; - } - this.initSelfOneLang(rstObj, objSelf); - } -} - -MonacoEditorLocalesPlugin.prototype.initOneLang = function (rstObj, en, langObj) { - for (var key in en) { - if (en && langObj && typeof (en[key]) === "string" && typeof (langObj[key]) === "string") { - var idx = this.getLangIdx(en[key]); - rstObj[idx] = langObj[key]; - } else if (en && langObj && en[key] && langObj[key] && typeof (en[key]) === "object" && typeof (langObj[key]) === "object") { - this.initOneLang(rstObj, en[key], langObj[key]); - } - } -} - -MonacoEditorLocalesPlugin.prototype.initSelfOneLang = function (rstObj, obj) { - for (var key in obj) { - var idx = this.getLangIdx(key); - rstObj[idx] = obj[key]; - } -} - -MonacoEditorLocalesPlugin.prototype.getSelectLangStr = function () { - var str = this.options.defaultLanguage; - str = str.replace(/'/g, "\\'"); - str = str.replace(/\r\n/g, "\\r\\n"); - str = str.replace(/\n/g, "\\n"); - return "'" + str + "'"; -} - -MonacoEditorLocalesPlugin.prototype.getLangIdx = function (en) { - if (en in this.mapLangIdx) { - return this.mapLangIdx[en]; - } - - var idx = this.langIdx; - this.mapLangIdx[en] = idx; - this.langIdx++; - return idx; -} - -MonacoEditorLocalesPlugin.prototype.init = function () { - this.mapLangIdx = {}; - this.lang = {}; - - this.mapEmbedLangName = { - "en": require("./editor.main.nls.en"), - "zh-cn": require("./editor.main.nls.zh-cn") - }; - - //{"de":{"enLang":"deLang", ...}, es:{}, ...} - this.mapEmbedLangNameSelf = { - "zh-cn": {} - } -} \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/beautifier/core/directives.js b/magic-editor/src/console/src/scripts/beautifier/core/directives.js deleted file mode 100644 index 48b161ee..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/directives.js +++ /dev/null @@ -1,62 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function Directives(start_block_pattern, end_block_pattern) { - start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source; - end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source; - this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g'); - this.__directive_pattern = / (\w+)[:](\w+)/g; - - this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g'); -} - -Directives.prototype.get_directives = function(text) { - if (!text.match(this.__directives_block_pattern)) { - return null; - } - - var directives = {}; - this.__directive_pattern.lastIndex = 0; - var directive_match = this.__directive_pattern.exec(text); - - while (directive_match) { - directives[directive_match[1]] = directive_match[2]; - directive_match = this.__directive_pattern.exec(text); - } - - return directives; -}; - -Directives.prototype.readIgnored = function(input) { - return input.readUntilAfter(this.__directives_end_ignore_pattern); -}; - - -module.exports.Directives = Directives; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/inputscanner.js b/magic-editor/src/console/src/scripts/beautifier/core/inputscanner.js deleted file mode 100644 index 783d1b65..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/inputscanner.js +++ /dev/null @@ -1,192 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var regexp_has_sticky = false; - -function InputScanner(input_string) { - this.__input = input_string || ''; - this.__input_length = this.__input.length; - this.__position = 0; -} - -InputScanner.prototype.restart = function() { - this.__position = 0; -}; - -InputScanner.prototype.back = function() { - if (this.__position > 0) { - this.__position -= 1; - } -}; - -InputScanner.prototype.hasNext = function() { - return this.__position < this.__input_length; -}; - -InputScanner.prototype.next = function() { - var val = null; - if (this.hasNext()) { - val = this.__input.charAt(this.__position); - this.__position += 1; - } - return val; -}; - -InputScanner.prototype.peek = function(index) { - var val = null; - index = index || 0; - index += this.__position; - if (index >= 0 && index < this.__input_length) { - val = this.__input.charAt(index); - } - return val; -}; - -// This is a JavaScript only helper function (not in python) -// Javascript doesn't have a match method -// and not all implementation support "sticky" flag. -// If they do not support sticky then both this.match() and this.test() method -// must get the match and check the index of the match. -// If sticky is supported and set, this method will use it. -// Otherwise it will check that global is set, and fall back to the slower method. -InputScanner.prototype.__match = function(pattern, index) { - pattern.lastIndex = index; - var pattern_match = pattern.exec(this.__input); - - if (pattern_match && !(regexp_has_sticky && pattern.sticky)) { - if (pattern_match.index !== index) { - pattern_match = null; - } - } - - return pattern_match; -}; - -InputScanner.prototype.test = function(pattern, index) { - index = index || 0; - index += this.__position; - - if (index >= 0 && index < this.__input_length) { - return !!this.__match(pattern, index); - } else { - return false; - } -}; - -InputScanner.prototype.testChar = function(pattern, index) { - // test one character regex match - var val = this.peek(index); - pattern.lastIndex = 0; - return val !== null && pattern.test(val); -}; - -InputScanner.prototype.match = function(pattern) { - var pattern_match = this.__match(pattern, this.__position); - if (pattern_match) { - this.__position += pattern_match[0].length; - } else { - pattern_match = null; - } - return pattern_match; -}; - -InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) { - var val = ''; - var match; - if (starting_pattern) { - match = this.match(starting_pattern); - if (match) { - val += match[0]; - } - } - if (until_pattern && (match || !starting_pattern)) { - val += this.readUntil(until_pattern, until_after); - } - return val; -}; - -InputScanner.prototype.readUntil = function(pattern, until_after) { - var val = ''; - var match_index = this.__position; - pattern.lastIndex = this.__position; - var pattern_match = pattern.exec(this.__input); - if (pattern_match) { - match_index = pattern_match.index; - if (until_after) { - match_index += pattern_match[0].length; - } - } else { - match_index = this.__input_length; - } - - val = this.__input.substring(this.__position, match_index); - this.__position = match_index; - return val; -}; - -InputScanner.prototype.readUntilAfter = function(pattern) { - return this.readUntil(pattern, true); -}; - -InputScanner.prototype.get_regexp = function(pattern, match_from) { - var result = null; - var flags = 'g'; - if (match_from && regexp_has_sticky) { - flags = 'y'; - } - // strings are converted to regexp - if (typeof pattern === "string" && pattern !== '') { - // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); - result = new RegExp(pattern, flags); - } else if (pattern) { - result = new RegExp(pattern.source, flags); - } - return result; -}; - -InputScanner.prototype.get_literal_regexp = function(literal_string) { - return RegExp(literal_string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')); -}; - -/* css beautifier legacy helpers */ -InputScanner.prototype.peekUntilAfter = function(pattern) { - var start = this.__position; - var val = this.readUntilAfter(pattern); - this.__position = start; - return val; -}; - -InputScanner.prototype.lookBack = function(testVal) { - var start = this.__position - 1; - return start >= testVal.length && this.__input.substring(start - testVal.length, start) - .toLowerCase() === testVal; -}; - -module.exports.InputScanner = InputScanner; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/options.js b/magic-editor/src/console/src/scripts/beautifier/core/options.js deleted file mode 100644 index 9852e3cb..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/options.js +++ /dev/null @@ -1,193 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function Options(options, merge_child_field) { - this.raw_options = _mergeOpts(options, merge_child_field); - - // Support passing the source text back with no change - this.disabled = this._get_boolean('disabled'); - - this.eol = this._get_characters('eol', 'auto'); - this.end_with_newline = this._get_boolean('end_with_newline'); - this.indent_size = this._get_number('indent_size', 4); - this.indent_char = this._get_characters('indent_char', ' '); - this.indent_level = this._get_number('indent_level'); - - this.preserve_newlines = this._get_boolean('preserve_newlines', true); - this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786); - if (!this.preserve_newlines) { - this.max_preserve_newlines = 0; - } - - this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t'); - if (this.indent_with_tabs) { - this.indent_char = '\t'; - - // indent_size behavior changed after 1.8.6 - // It used to be that indent_size would be - // set to 1 for indent_with_tabs. That is no longer needed and - // actually doesn't make sense - why not use spaces? Further, - // that might produce unexpected behavior - tabs being used - // for single-column alignment. So, when indent_with_tabs is true - // and indent_size is 1, reset indent_size to 4. - if (this.indent_size === 1) { - this.indent_size = 4; - } - } - - // Backwards compat with 1.3.x - this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char')); - - this.indent_empty_lines = this._get_boolean('indent_empty_lines'); - - // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty'] - // For now, 'auto' = all off for javascript, all on for html (and inline javascript). - // other values ignored - this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']); -} - -Options.prototype._get_array = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = default_value || []; - if (typeof option_value === 'object') { - if (option_value !== null && typeof option_value.concat === 'function') { - result = option_value.concat(); - } - } else if (typeof option_value === 'string') { - result = option_value.split(/[^a-zA-Z0-9_/-]+/); - } - return result; -}; - -Options.prototype._get_boolean = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = option_value === undefined ? !!default_value : !!option_value; - return result; -}; - -Options.prototype._get_characters = function(name, default_value) { - var option_value = this.raw_options[name]; - var result = default_value || ''; - if (typeof option_value === 'string') { - result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t'); - } - return result; -}; - -Options.prototype._get_number = function(name, default_value) { - var option_value = this.raw_options[name]; - default_value = parseInt(default_value, 10); - if (isNaN(default_value)) { - default_value = 0; - } - var result = parseInt(option_value, 10); - if (isNaN(result)) { - result = default_value; - } - return result; -}; - -Options.prototype._get_selection = function(name, selection_list, default_value) { - var result = this._get_selection_list(name, selection_list, default_value); - if (result.length !== 1) { - throw new Error( - "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" + - selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); - } - - return result[0]; -}; - - -Options.prototype._get_selection_list = function(name, selection_list, default_value) { - if (!selection_list || selection_list.length === 0) { - throw new Error("Selection list cannot be empty."); - } - - default_value = default_value || [selection_list[0]]; - if (!this._is_valid_selection(default_value, selection_list)) { - throw new Error("Invalid Default Value!"); - } - - var result = this._get_array(name, default_value); - if (!this._is_valid_selection(result, selection_list)) { - throw new Error( - "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" + - selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); - } - - return result; -}; - -Options.prototype._is_valid_selection = function(result, selection_list) { - return result.length && selection_list.length && - !result.some(function(item) { return selection_list.indexOf(item) === -1; }); -}; - - -// merges child options up with the parent options object -// Example: obj = {a: 1, b: {a: 2}} -// mergeOpts(obj, 'b') -// -// Returns: {a: 2} -function _mergeOpts(allOptions, childFieldName) { - var finalOpts = {}; - allOptions = _normalizeOpts(allOptions); - var name; - - for (name in allOptions) { - if (name !== childFieldName) { - finalOpts[name] = allOptions[name]; - } - } - - //merge in the per type settings for the childFieldName - if (childFieldName && allOptions[childFieldName]) { - for (name in allOptions[childFieldName]) { - finalOpts[name] = allOptions[childFieldName][name]; - } - } - return finalOpts; -} - -function _normalizeOpts(options) { - var convertedOpts = {}; - var key; - - for (key in options) { - var newKey = key.replace(/-/g, "_"); - convertedOpts[newKey] = options[key]; - } - return convertedOpts; -} - -module.exports.Options = Options; -module.exports.normalizeOpts = _normalizeOpts; -module.exports.mergeOpts = _mergeOpts; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/output.js b/magic-editor/src/console/src/scripts/beautifier/core/output.js deleted file mode 100644 index 5d9db8a6..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/output.js +++ /dev/null @@ -1,421 +0,0 @@ -/*jshint node:true */ -/* - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function OutputLine(parent) { - this.__parent = parent; - this.__character_count = 0; - // use indent_count as a marker for this.__lines that have preserved indentation - this.__indent_count = -1; - this.__alignment_count = 0; - this.__wrap_point_index = 0; - this.__wrap_point_character_count = 0; - this.__wrap_point_indent_count = -1; - this.__wrap_point_alignment_count = 0; - - this.__items = []; -} - -OutputLine.prototype.clone_empty = function() { - var line = new OutputLine(this.__parent); - line.set_indent(this.__indent_count, this.__alignment_count); - return line; -}; - -OutputLine.prototype.item = function(index) { - if (index < 0) { - return this.__items[this.__items.length + index]; - } else { - return this.__items[index]; - } -}; - -OutputLine.prototype.has_match = function(pattern) { - for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) { - if (this.__items[lastCheckedOutput].match(pattern)) { - return true; - } - } - return false; -}; - -OutputLine.prototype.set_indent = function(indent, alignment) { - if (this.is_empty()) { - this.__indent_count = indent || 0; - this.__alignment_count = alignment || 0; - this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count); - } -}; - -OutputLine.prototype._set_wrap_point = function() { - if (this.__parent.wrap_line_length) { - this.__wrap_point_index = this.__items.length; - this.__wrap_point_character_count = this.__character_count; - this.__wrap_point_indent_count = this.__parent.next_line.__indent_count; - this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count; - } -}; - -OutputLine.prototype._should_wrap = function() { - return this.__wrap_point_index && - this.__character_count > this.__parent.wrap_line_length && - this.__wrap_point_character_count > this.__parent.next_line.__character_count; -}; - -OutputLine.prototype._allow_wrap = function() { - if (this._should_wrap()) { - this.__parent.add_new_line(); - var next = this.__parent.current_line; - next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count); - next.__items = this.__items.slice(this.__wrap_point_index); - this.__items = this.__items.slice(0, this.__wrap_point_index); - - next.__character_count += this.__character_count - this.__wrap_point_character_count; - this.__character_count = this.__wrap_point_character_count; - - if (next.__items[0] === " ") { - next.__items.splice(0, 1); - next.__character_count -= 1; - } - return true; - } - return false; -}; - -OutputLine.prototype.is_empty = function() { - return this.__items.length === 0; -}; - -OutputLine.prototype.last = function() { - if (!this.is_empty()) { - return this.__items[this.__items.length - 1]; - } else { - return null; - } -}; - -OutputLine.prototype.push = function(item) { - this.__items.push(item); - var last_newline_index = item.lastIndexOf('\n'); - if (last_newline_index !== -1) { - this.__character_count = item.length - last_newline_index; - } else { - this.__character_count += item.length; - } -}; - -OutputLine.prototype.pop = function() { - var item = null; - if (!this.is_empty()) { - item = this.__items.pop(); - this.__character_count -= item.length; - } - return item; -}; - - -OutputLine.prototype._remove_indent = function() { - if (this.__indent_count > 0) { - this.__indent_count -= 1; - this.__character_count -= this.__parent.indent_size; - } -}; - -OutputLine.prototype._remove_wrap_indent = function() { - if (this.__wrap_point_indent_count > 0) { - this.__wrap_point_indent_count -= 1; - } -}; -OutputLine.prototype.trim = function() { - while (this.last() === ' ') { - this.__items.pop(); - this.__character_count -= 1; - } -}; - -OutputLine.prototype.toString = function() { - var result = ''; - if (this.is_empty()) { - if (this.__parent.indent_empty_lines) { - result = this.__parent.get_indent_string(this.__indent_count); - } - } else { - result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count); - result += this.__items.join(''); - } - return result; -}; - -function IndentStringCache(options, baseIndentString) { - this.__cache = ['']; - this.__indent_size = options.indent_size; - this.__indent_string = options.indent_char; - if (!options.indent_with_tabs) { - this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char); - } - - // Set to null to continue support for auto detection of base indent - baseIndentString = baseIndentString || ''; - if (options.indent_level > 0) { - baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string); - } - - this.__base_string = baseIndentString; - this.__base_string_length = baseIndentString.length; -} - -IndentStringCache.prototype.get_indent_size = function(indent, column) { - var result = this.__base_string_length; - column = column || 0; - if (indent < 0) { - result = 0; - } - result += indent * this.__indent_size; - result += column; - return result; -}; - -IndentStringCache.prototype.get_indent_string = function(indent_level, column) { - var result = this.__base_string; - column = column || 0; - if (indent_level < 0) { - indent_level = 0; - result = ''; - } - column += indent_level * this.__indent_size; - this.__ensure_cache(column); - result += this.__cache[column]; - return result; -}; - -IndentStringCache.prototype.__ensure_cache = function(column) { - while (column >= this.__cache.length) { - this.__add_column(); - } -}; - -IndentStringCache.prototype.__add_column = function() { - var column = this.__cache.length; - var indent = 0; - var result = ''; - if (this.__indent_size && column >= this.__indent_size) { - indent = Math.floor(column / this.__indent_size); - column -= indent * this.__indent_size; - result = new Array(indent + 1).join(this.__indent_string); - } - if (column) { - result += new Array(column + 1).join(' '); - } - - this.__cache.push(result); -}; - -function Output(options, baseIndentString) { - this.__indent_cache = new IndentStringCache(options, baseIndentString); - this.raw = false; - this._end_with_newline = options.end_with_newline; - this.indent_size = options.indent_size; - this.wrap_line_length = options.wrap_line_length; - this.indent_empty_lines = options.indent_empty_lines; - this.__lines = []; - this.previous_line = null; - this.current_line = null; - this.next_line = new OutputLine(this); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = false; - // initialize - this.__add_outputline(); -} - -Output.prototype.__add_outputline = function() { - this.previous_line = this.current_line; - this.current_line = this.next_line.clone_empty(); - this.__lines.push(this.current_line); -}; - -Output.prototype.get_line_number = function() { - return this.__lines.length; -}; - -Output.prototype.get_indent_string = function(indent, column) { - return this.__indent_cache.get_indent_string(indent, column); -}; - -Output.prototype.get_indent_size = function(indent, column) { - return this.__indent_cache.get_indent_size(indent, column); -}; - -Output.prototype.is_empty = function() { - return !this.previous_line && this.current_line.is_empty(); -}; - -Output.prototype.add_new_line = function(force_newline) { - // never newline at the start of file - // otherwise, newline only if we didn't just add one or we're forced - if (this.is_empty() || - (!force_newline && this.just_added_newline())) { - return false; - } - - // if raw output is enabled, don't print additional newlines, - // but still return True as though you had - if (!this.raw) { - this.__add_outputline(); - } - return true; -}; - -Output.prototype.get_code = function(eol) { - this.trim(true); - - // handle some edge cases where the last tokens - // has text that ends with newline(s) - var last_item = this.current_line.pop(); - if (last_item) { - if (last_item[last_item.length - 1] === '\n') { - last_item = last_item.replace(/\n+$/g, ''); - } - this.current_line.push(last_item); - } - - if (this._end_with_newline) { - this.__add_outputline(); - } - - var sweet_code = this.__lines.join('\n'); - - if (eol === '\r\n') { - sweet_code = sweet_code.replace(/([^\r])\n/g, `$1${eol}`); - }else if (eol !== '\n') { - sweet_code = sweet_code.replace(/[\n]/g, eol); - } - return sweet_code; -}; - -Output.prototype.set_wrap_point = function() { - this.current_line._set_wrap_point(); -}; - -Output.prototype.set_indent = function(indent, alignment) { - indent = indent || 0; - alignment = alignment || 0; - - // Next line stores alignment values - this.next_line.set_indent(indent, alignment); - - // Never indent your first output indent at the start of the file - if (this.__lines.length > 1) { - this.current_line.set_indent(indent, alignment); - return true; - } - - this.current_line.set_indent(); - return false; -}; - -Output.prototype.add_raw_token = function(token) { - for (var x = 0; x < token.newlines; x++) { - this.__add_outputline(); - } - this.current_line.set_indent(-1); - this.current_line.push(token.whitespace_before); - this.current_line.push(token.text); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = false; -}; - -Output.prototype.add_token = function(printable_token) { - this.__add_space_before_token(); - this.current_line.push(printable_token); - this.space_before_token = false; - this.non_breaking_space = false; - this.previous_token_wrapped = this.current_line._allow_wrap(); -}; - -Output.prototype.__add_space_before_token = function() { - if (this.space_before_token && !this.just_added_newline()) { - if (!this.non_breaking_space) { - this.set_wrap_point(); - } - this.current_line.push(' '); - } -}; - -Output.prototype.remove_indent = function(index) { - var output_length = this.__lines.length; - while (index < output_length) { - this.__lines[index]._remove_indent(); - index++; - } - this.current_line._remove_wrap_indent(); -}; - -Output.prototype.trim = function(eat_newlines) { - eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; - - this.current_line.trim(); - - while (eat_newlines && this.__lines.length > 1 && - this.current_line.is_empty()) { - this.__lines.pop(); - this.current_line = this.__lines[this.__lines.length - 1]; - this.current_line.trim(); - } - - this.previous_line = this.__lines.length > 1 ? - this.__lines[this.__lines.length - 2] : null; -}; - -Output.prototype.just_added_newline = function() { - return this.current_line.is_empty(); -}; - -Output.prototype.just_added_blankline = function() { - return this.is_empty() || - (this.current_line.is_empty() && this.previous_line.is_empty()); -}; - -Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) { - var index = this.__lines.length - 2; - while (index >= 0) { - var potentialEmptyLine = this.__lines[index]; - if (potentialEmptyLine.is_empty()) { - break; - } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 && - potentialEmptyLine.item(-1) !== ends_with) { - this.__lines.splice(index + 1, 0, new OutputLine(this)); - this.previous_line = this.__lines[this.__lines.length - 2]; - break; - } - index--; - } -}; - -module.exports.Output = Output; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/pattern.js b/magic-editor/src/console/src/scripts/beautifier/core/pattern.js deleted file mode 100644 index efcdd341..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/pattern.js +++ /dev/null @@ -1,94 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function Pattern(input_scanner, parent) { - this._input = input_scanner; - this._starting_pattern = null; - this._match_pattern = null; - this._until_pattern = null; - this._until_after = false; - - if (parent) { - this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true); - this._match_pattern = this._input.get_regexp(parent._match_pattern, true); - this._until_pattern = this._input.get_regexp(parent._until_pattern); - this._until_after = parent._until_after; - } -} - -Pattern.prototype.read = function() { - var result = this._input.read(this._starting_pattern); - if (!this._starting_pattern || result) { - result += this._input.read(this._match_pattern, this._until_pattern, this._until_after); - } - return result; -}; - -Pattern.prototype.read_match = function() { - return this._input.match(this._match_pattern); -}; - -Pattern.prototype.until_after = function(pattern) { - var result = this._create(); - result._until_after = true; - result._until_pattern = this._input.get_regexp(pattern); - result._update(); - return result; -}; - -Pattern.prototype.until = function(pattern) { - var result = this._create(); - result._until_after = false; - result._until_pattern = this._input.get_regexp(pattern); - result._update(); - return result; -}; - -Pattern.prototype.starting_with = function(pattern) { - var result = this._create(); - result._starting_pattern = this._input.get_regexp(pattern, true); - result._update(); - return result; -}; - -Pattern.prototype.matching = function(pattern) { - var result = this._create(); - result._match_pattern = this._input.get_regexp(pattern, true); - result._update(); - return result; -}; - -Pattern.prototype._create = function() { - return new Pattern(this._input, this); -}; - -Pattern.prototype._update = function() {}; - -module.exports.Pattern = Pattern; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/templatablepattern.js b/magic-editor/src/console/src/scripts/beautifier/core/templatablepattern.js deleted file mode 100644 index 58a0a35b..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/templatablepattern.js +++ /dev/null @@ -1,211 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var Pattern = require('./pattern').Pattern; - - -var template_names = { - django: false, - erb: false, - handlebars: false, - php: false, - smarty: false -}; - -// This lets templates appear anywhere we would do a readUntil -// The cost is higher but it is pay to play. -function TemplatablePattern(input_scanner, parent) { - Pattern.call(this, input_scanner, parent); - this.__template_pattern = null; - this._disabled = Object.assign({}, template_names); - this._excluded = Object.assign({}, template_names); - - if (parent) { - this.__template_pattern = this._input.get_regexp(parent.__template_pattern); - this._excluded = Object.assign(this._excluded, parent._excluded); - this._disabled = Object.assign(this._disabled, parent._disabled); - } - var pattern = new Pattern(input_scanner); - this.__patterns = { - handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/), - handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/), - handlebars: pattern.starting_with(/{{/).until_after(/}}/), - php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/), - erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/), - // django coflicts with handlebars a bit. - django: pattern.starting_with(/{%/).until_after(/%}/), - django_value: pattern.starting_with(/{{/).until_after(/}}/), - django_comment: pattern.starting_with(/{#/).until_after(/#}/), - smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/), - smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/), - smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/) - }; -} -TemplatablePattern.prototype = new Pattern(); - -TemplatablePattern.prototype._create = function() { - return new TemplatablePattern(this._input, this); -}; - -TemplatablePattern.prototype._update = function() { - this.__set_templated_pattern(); -}; - -TemplatablePattern.prototype.disable = function(language) { - var result = this._create(); - result._disabled[language] = true; - result._update(); - return result; -}; - -TemplatablePattern.prototype.read_options = function(options) { - var result = this._create(); - for (var language in template_names) { - result._disabled[language] = options.templating.indexOf(language) === -1; - } - result._update(); - return result; -}; - -TemplatablePattern.prototype.exclude = function(language) { - var result = this._create(); - result._excluded[language] = true; - result._update(); - return result; -}; - -TemplatablePattern.prototype.read = function() { - var result = ''; - if (this._match_pattern) { - result = this._input.read(this._starting_pattern); - } else { - result = this._input.read(this._starting_pattern, this.__template_pattern); - } - var next = this._read_template(); - while (next) { - if (this._match_pattern) { - next += this._input.read(this._match_pattern); - } else { - next += this._input.readUntil(this.__template_pattern); - } - result += next; - next = this._read_template(); - } - - if (this._until_after) { - result += this._input.readUntilAfter(this._until_pattern); - } - return result; -}; - -TemplatablePattern.prototype.__set_templated_pattern = function() { - var items = []; - - if (!this._disabled.php) { - items.push(this.__patterns.php._starting_pattern.source); - } - if (!this._disabled.handlebars) { - items.push(this.__patterns.handlebars._starting_pattern.source); - } - if (!this._disabled.erb) { - items.push(this.__patterns.erb._starting_pattern.source); - } - if (!this._disabled.django) { - items.push(this.__patterns.django._starting_pattern.source); - // The starting pattern for django is more complex because it has different - // patterns for value, comment, and other sections - items.push(this.__patterns.django_value._starting_pattern.source); - items.push(this.__patterns.django_comment._starting_pattern.source); - } - if (!this._disabled.smarty) { - items.push(this.__patterns.smarty._starting_pattern.source); - } - - if (this._until_pattern) { - items.push(this._until_pattern.source); - } - this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')'); -}; - -TemplatablePattern.prototype._read_template = function() { - var resulting_string = ''; - var c = this._input.peek(); - if (c === '<') { - var peek1 = this._input.peek(1); - //if we're in a comment, do something special - // We treat all comments as literals, even more than preformatted tags - // we just look for the appropriate close tag - if (!this._disabled.php && !this._excluded.php && peek1 === '?') { - resulting_string = resulting_string || - this.__patterns.php.read(); - } - if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') { - resulting_string = resulting_string || - this.__patterns.erb.read(); - } - } else if (c === '{') { - if (!this._disabled.handlebars && !this._excluded.handlebars) { - resulting_string = resulting_string || - this.__patterns.handlebars_comment.read(); - resulting_string = resulting_string || - this.__patterns.handlebars_unescaped.read(); - resulting_string = resulting_string || - this.__patterns.handlebars.read(); - } - if (!this._disabled.django) { - // django coflicts with handlebars a bit. - if (!this._excluded.django && !this._excluded.handlebars) { - resulting_string = resulting_string || - this.__patterns.django_value.read(); - } - if (!this._excluded.django) { - resulting_string = resulting_string || - this.__patterns.django_comment.read(); - resulting_string = resulting_string || - this.__patterns.django.read(); - } - } - if (!this._disabled.smarty) { - // smarty cannot be enabled with django or handlebars enabled - if (this._disabled.django && this._disabled.handlebars) { - resulting_string = resulting_string || - this.__patterns.smarty_comment.read(); - resulting_string = resulting_string || - this.__patterns.smarty_literal.read(); - resulting_string = resulting_string || - this.__patterns.smarty.read(); - } - } - } - return resulting_string; -}; - - -module.exports.TemplatablePattern = TemplatablePattern; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/token.js b/magic-editor/src/console/src/scripts/beautifier/core/token.js deleted file mode 100644 index 13f6e901..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/token.js +++ /dev/null @@ -1,54 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function Token(type, text, newlines, whitespace_before) { - this.type = type; - this.text = text; - - // comments_before are - // comments that have a new line before them - // and may or may not have a newline after - // this is a set of comments before - this.comments_before = null; /* inline comment*/ - - - // this.comments_after = new TokenStream(); // no new line before and newline after - this.newlines = newlines || 0; - this.whitespace_before = whitespace_before || ''; - this.parent = null; - this.next = null; - this.previous = null; - this.opened = null; - this.closed = null; - this.directives = null; -} - - -module.exports.Token = Token; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/tokenizer.js b/magic-editor/src/console/src/scripts/beautifier/core/tokenizer.js deleted file mode 100644 index 24e60b1c..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/tokenizer.js +++ /dev/null @@ -1,140 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var InputScanner = require('../core/inputscanner').InputScanner; -var Token = require('../core/token').Token; -var TokenStream = require('../core/tokenstream').TokenStream; -var WhitespacePattern = require('./whitespacepattern').WhitespacePattern; - -var TOKEN = { - START: 'TK_START', - RAW: 'TK_RAW', - EOF: 'TK_EOF' -}; - -var Tokenizer = function(input_string, options) { - this._input = new InputScanner(input_string); - this._options = options || {}; - this.__tokens = null; - - this._patterns = {}; - this._patterns.whitespace = new WhitespacePattern(this._input); -}; - -Tokenizer.prototype.tokenize = function() { - this._input.restart(); - this.__tokens = new TokenStream(); - - this._reset(); - - var current; - var previous = new Token(TOKEN.START, ''); - var open_token = null; - var open_stack = []; - var comments = new TokenStream(); - - while (previous.type !== TOKEN.EOF) { - current = this._get_next_token(previous, open_token); - while (this._is_comment(current)) { - comments.add(current); - current = this._get_next_token(previous, open_token); - } - - if (!comments.isEmpty()) { - current.comments_before = comments; - comments = new TokenStream(); - } - - current.parent = open_token; - - if (this._is_opening(current)) { - open_stack.push(open_token); - open_token = current; - } else if (open_token && this._is_closing(current, open_token)) { - current.opened = open_token; - open_token.closed = current; - open_token = open_stack.pop(); - current.parent = open_token; - } - - current.previous = previous; - previous.next = current; - - this.__tokens.add(current); - previous = current; - } - - return this.__tokens; -}; - - -Tokenizer.prototype._is_first_token = function() { - return this.__tokens.isEmpty(); -}; - -Tokenizer.prototype._reset = function() {}; - -Tokenizer.prototype._get_next_token = function() { // jshint unused:false - this._readWhitespace(); - var resulting_string = this._input.read(/.+/g); - if (resulting_string) { - return this._create_token(TOKEN.RAW, resulting_string); - } else { - return this._create_token(TOKEN.EOF, ''); - } -}; - -Tokenizer.prototype._is_comment = function() { // jshint unused:false - return false; -}; - -Tokenizer.prototype._is_opening = function() { // jshint unused:false - return false; -}; - -Tokenizer.prototype._is_closing = function() { // jshint unused:false - return false; -}; - -Tokenizer.prototype._create_token = function(type, text) { - var token = new Token(type, text, - this._patterns.whitespace.newline_count, - this._patterns.whitespace.whitespace_before_token); - return token; -}; - -Tokenizer.prototype._readWhitespace = function() { - return this._patterns.whitespace.read(); -}; - - - -module.exports.Tokenizer = Tokenizer; -module.exports.TOKEN = TOKEN; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/tokenstream.js b/magic-editor/src/console/src/scripts/beautifier/core/tokenstream.js deleted file mode 100644 index 88302ffe..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/tokenstream.js +++ /dev/null @@ -1,78 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -function TokenStream(parent_token) { - // private - this.__tokens = []; - this.__tokens_length = this.__tokens.length; - this.__position = 0; - this.__parent_token = parent_token; -} - -TokenStream.prototype.restart = function() { - this.__position = 0; -}; - -TokenStream.prototype.isEmpty = function() { - return this.__tokens_length === 0; -}; - -TokenStream.prototype.hasNext = function() { - return this.__position < this.__tokens_length; -}; - -TokenStream.prototype.next = function() { - var val = null; - if (this.hasNext()) { - val = this.__tokens[this.__position]; - this.__position += 1; - } - return val; -}; - -TokenStream.prototype.peek = function(index) { - var val = null; - index = index || 0; - index += this.__position; - if (index >= 0 && index < this.__tokens_length) { - val = this.__tokens[index]; - } - return val; -}; - -TokenStream.prototype.add = function(token) { - if (this.__parent_token) { - token.parent = this.__parent_token; - } - this.__tokens.push(token); - this.__tokens_length += 1; -}; - -module.exports.TokenStream = TokenStream; diff --git a/magic-editor/src/console/src/scripts/beautifier/core/whitespacepattern.js b/magic-editor/src/console/src/scripts/beautifier/core/whitespacepattern.js deleted file mode 100644 index 4faa57e4..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/core/whitespacepattern.js +++ /dev/null @@ -1,105 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var Pattern = require('../core/pattern').Pattern; - -function WhitespacePattern(input_scanner, parent) { - Pattern.call(this, input_scanner, parent); - if (parent) { - this._line_regexp = this._input.get_regexp(parent._line_regexp); - } else { - this.__set_whitespace_patterns('', ''); - } - - this.newline_count = 0; - this.whitespace_before_token = ''; -} -WhitespacePattern.prototype = new Pattern(); - -WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) { - whitespace_chars += '\\t '; - newline_chars += '\\n\\r'; - - this._match_pattern = this._input.get_regexp( - '[' + whitespace_chars + newline_chars + ']+', true); - this._newline_regexp = this._input.get_regexp( - '\\r\\n|[' + newline_chars + ']'); -}; - -WhitespacePattern.prototype.read = function() { - this.newline_count = 0; - this.whitespace_before_token = ''; - - var resulting_string = this._input.read(this._match_pattern); - if (resulting_string === ' ') { - this.whitespace_before_token = ' '; - } else if (resulting_string) { - var matches = this.__split(this._newline_regexp, resulting_string); - this.newline_count = matches.length - 1; - this.whitespace_before_token = matches[this.newline_count]; - } - - return resulting_string; -}; - -WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) { - var result = this._create(); - result.__set_whitespace_patterns(whitespace_chars, newline_chars); - result._update(); - return result; -}; - -WhitespacePattern.prototype._create = function() { - return new WhitespacePattern(this._input, this); -}; - -WhitespacePattern.prototype.__split = function(regexp, input_string) { - regexp.lastIndex = 0; - var start_index = 0; - var result = []; - var next_match = regexp.exec(input_string); - while (next_match) { - result.push(input_string.substring(start_index, next_match.index)); - start_index = next_match.index + next_match[0].length; - next_match = regexp.exec(input_string); - } - - if (start_index < input_string.length) { - result.push(input_string.substring(start_index, input_string.length)); - } else { - result.push(''); - } - - return result; -}; - - - -module.exports.WhitespacePattern = WhitespacePattern; diff --git a/magic-editor/src/console/src/scripts/beautifier/javascript/acorn.js b/magic-editor/src/console/src/scripts/beautifier/javascript/acorn.js deleted file mode 100644 index c809b2a0..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/javascript/acorn.js +++ /dev/null @@ -1,57 +0,0 @@ -/* jshint node: true, curly: false */ -// Parts of this section of code is taken from acorn. -// -// Acorn was written by Marijn Haverbeke and released under an MIT -// license. The Unicode regexps (for identifiers and whitespace) were -// taken from [Esprima](http://esprima.org) by Ariya Hidayat. -// -// Git repositories for Acorn are available at -// -// http://marijnhaverbeke.nl/git/acorn -// https://github.com/marijnh/acorn.git - -// ## Character categories - - -'use strict'; - -// acorn used char codes to squeeze the last bit of performance out -// Beautifier is okay without that, so we're using regex -// permit # (23), $ (36), and @ (64). @ is used in ES7 decorators. -// 65 through 91 are uppercase letters. -// permit _ (95). -// 97 through 123 are lowercase letters. -var baseASCIIidentifierStartChars = "\\x23\\x24\\x40\\x41-\\x5a\\x5f\\x61-\\x7a"; - -// inside an identifier @ is not allowed but 0-9 are. -var baseASCIIidentifierChars = "\\x24\\x30-\\x39\\x41-\\x5a\\x5f\\x61-\\x7a"; - -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -var nonASCIIidentifierStartChars = "\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05d0-\\u05ea\\u05f0-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u08a0\\u08a2-\\u08ac\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097f\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c33\\u0c35-\\u0c39\\u0c3d\\u0c58\\u0c59\\u0c60\\u0c61\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d60\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e87\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f4\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f0\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1877\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191c\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19c1-\\u19c7\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u212f-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2e2f\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312d\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua697\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua78e\\ua790-\\ua793\\ua7a0-\\ua7aa\\ua7f8-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa80-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc"; -var nonASCIIidentifierChars = "\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u0620-\\u0649\\u0672-\\u06d3\\u06e7-\\u06e8\\u06fb-\\u06fc\\u0730-\\u074a\\u0800-\\u0814\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0840-\\u0857\\u08e4-\\u08fe\\u0900-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962-\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09d7\\u09df-\\u09e0\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2-\\u0ae3\\u0ae6-\\u0aef\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b56\\u0b57\\u0b5f-\\u0b60\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c01-\\u0c03\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62-\\u0c63\\u0c66-\\u0c6f\\u0c82\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2-\\u0ce3\\u0ce6-\\u0cef\\u0d02\\u0d03\\u0d46-\\u0d48\\u0d57\\u0d62-\\u0d63\\u0d66-\\u0d6f\\u0d82\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0df2\\u0df3\\u0e34-\\u0e3a\\u0e40-\\u0e45\\u0e50-\\u0e59\\u0eb4-\\u0eb9\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f41-\\u0f47\\u0f71-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1029\\u1040-\\u1049\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u170e-\\u1710\\u1720-\\u1730\\u1740-\\u1750\\u1772\\u1773\\u1780-\\u17b2\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1920-\\u192b\\u1930-\\u193b\\u1951-\\u196d\\u19b0-\\u19c0\\u19c8-\\u19c9\\u19d0-\\u19d9\\u1a00-\\u1a15\\u1a20-\\u1a53\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1b46-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c00-\\u1c22\\u1c40-\\u1c49\\u1c5b-\\u1c7d\\u1cd0-\\u1cd2\\u1d00-\\u1dbe\\u1e01-\\u1f15\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2d81-\\u2d96\\u2de0-\\u2dff\\u3021-\\u3028\\u3099\\u309a\\ua640-\\ua66d\\ua674-\\ua67d\\ua69f\\ua6f0-\\ua6f1\\ua7f8-\\ua800\\ua806\\ua80b\\ua823-\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c4\\ua8d0-\\ua8d9\\ua8f3-\\ua8f7\\ua900-\\ua909\\ua926-\\ua92d\\ua930-\\ua945\\ua980-\\ua983\\ua9b3-\\ua9c0\\uaa00-\\uaa27\\uaa40-\\uaa41\\uaa4c-\\uaa4d\\uaa50-\\uaa59\\uaa7b\\uaae0-\\uaae9\\uaaf2-\\uaaf3\\uabc0-\\uabe1\\uabec\\uabed\\uabf0-\\uabf9\\ufb20-\\ufb28\\ufe00-\\ufe0f\\ufe20-\\ufe26\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f"; -//var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -//var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -var identifierStart = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierStartChars + nonASCIIidentifierStartChars + "])"; -var identifierChars = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])*"; - -exports.identifier = new RegExp(identifierStart + identifierChars, 'g'); -exports.identifierStart = new RegExp(identifierStart); -exports.identifierMatch = new RegExp("(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])+"); - -// var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line - -// Whether a single character denotes a newline. - -exports.newline = /[\n\r\u2028\u2029]/; - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -// in javascript, these two differ -// in python they are the same, different methods are called on them -exports.lineBreak = new RegExp('\r\n|' + exports.newline.source); -exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g'); diff --git a/magic-editor/src/console/src/scripts/beautifier/javascript/beautifier.js b/magic-editor/src/console/src/scripts/beautifier/javascript/beautifier.js deleted file mode 100644 index 0cd3636b..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/javascript/beautifier.js +++ /dev/null @@ -1,1462 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var Output = require('../core/output').Output; -var Token = require('../core/token').Token; -var acorn = require('./acorn'); -var Options = require('./options').Options; -var Tokenizer = require('./tokenizer').Tokenizer; -var line_starters = require('./tokenizer').line_starters; -var positionable_operators = require('./tokenizer').positionable_operators; -var TOKEN = require('./tokenizer').TOKEN; - - -function in_array(what, arr) { - return arr.indexOf(what) !== -1; -} - -function ltrim(s) { - return s.replace(/^\s+/g, ''); -} - -function generateMapFromStrings(list) { - var result = {}; - for (var x = 0; x < list.length; x++) { - // make the mapped names underscored instead of dash - result[list[x].replace(/-/g, '_')] = list[x]; - } - return result; -} - -function reserved_word(token, word) { - return token && token.type === TOKEN.RESERVED && token.text === word; -} - -function reserved_array(token, words) { - return token && token.type === TOKEN.RESERVED && in_array(token.text, words); -} -// Unsure of what they mean, but they work. Worth cleaning up in future. -var special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async']; - -var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; - -// Generate map from array -var OPERATOR_POSITION = generateMapFromStrings(validPositionValues); - -var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline]; - -var MODE = { - BlockStatement: 'BlockStatement', // 'BLOCK' - Statement: 'Statement', // 'STATEMENT' - ObjectLiteral: 'ObjectLiteral', // 'OBJECT', - ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]', - ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)', - Conditional: 'Conditional', //'(COND-EXPRESSION)', - Expression: 'Expression' //'(EXPRESSION)' -}; - -function remove_redundant_indentation(output, frame) { - // This implementation is effective but has some issues: - // - can cause line wrap to happen too soon due to indent removal - // after wrap points are calculated - // These issues are minor compared to ugly indentation. - - if (frame.multiline_frame || - frame.mode === MODE.ForInitializer || - frame.mode === MODE.Conditional) { - return; - } - - // remove one indent from each line inside this section - output.remove_indent(frame.start_line_index); -} - -// we could use just string.split, but -// IE doesn't like returning empty strings -function split_linebreaks(s) { - //return s.split(/\x0d\x0a|\x0a/); - - s = s.replace(acorn.allLineBreaks, '\n'); - var out = [], - idx = s.indexOf("\n"); - while (idx !== -1) { - out.push(s.substring(0, idx)); - s = s.substring(idx + 1); - idx = s.indexOf("\n"); - } - if (s.length) { - out.push(s); - } - return out; -} - -function is_array(mode) { - return mode === MODE.ArrayLiteral; -} - -function is_expression(mode) { - return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]); -} - -function all_lines_start_with(lines, c) { - for (var i = 0; i < lines.length; i++) { - var line = lines[i].trim(); - if (line.charAt(0) !== c) { - return false; - } - } - return true; -} - -function each_line_matches_indent(lines, indent) { - var i = 0, - len = lines.length, - line; - for (; i < len; i++) { - line = lines[i]; - // allow empty lines to pass through - if (line && line.indexOf(indent) !== 0) { - return false; - } - } - return true; -} - - -function Beautifier(source_text, options) { - options = options || {}; - this._source_text = source_text || ''; - - this._output = null; - this._tokens = null; - this._last_last_text = null; - this._flags = null; - this._previous_flags = null; - - this._flag_store = null; - this._options = new Options(options); -} - -Beautifier.prototype.create_flags = function(flags_base, mode) { - var next_indent_level = 0; - if (flags_base) { - next_indent_level = flags_base.indentation_level; - if (!this._output.just_added_newline() && - flags_base.line_indent_level > next_indent_level) { - next_indent_level = flags_base.line_indent_level; - } - } - - var next_flags = { - mode: mode, - parent: flags_base, - last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text - last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed - declaration_statement: false, - declaration_assignment: false, - multiline_frame: false, - inline_frame: false, - if_block: false, - else_block: false, - do_block: false, - do_while: false, - import_block: false, - in_case_statement: false, // switch(..){ INSIDE HERE } - in_case: false, // we're on the exact line with "case 0:" - case_body: false, // the indented case-action block - case_block: false, // the indented case-action block is wrapped with {} - indentation_level: next_indent_level, - alignment: 0, - line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level, - start_line_index: this._output.get_line_number(), - ternary_depth: 0 - }; - return next_flags; -}; - -Beautifier.prototype._reset = function(source_text) { - var baseIndentString = source_text.match(/^[\t ]*/)[0]; - - this._last_last_text = ''; // pre-last token text - this._output = new Output(this._options, baseIndentString); - - // If testing the ignore directive, start with output disable set to true - this._output.raw = this._options.test_output_raw; - - - // Stack of parsing/formatting states, including MODE. - // We tokenize, parse, and output in an almost purely a forward-only stream of token input - // and formatted output. This makes the beautifier less accurate than full parsers - // but also far more tolerant of syntax errors. - // - // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type - // MODE.BlockStatement on the the stack, even though it could be object literal. If we later - // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";", - // most full parsers would die, but the beautifier gracefully falls back to - // MODE.BlockStatement and continues on. - this._flag_store = []; - this.set_mode(MODE.BlockStatement); - var tokenizer = new Tokenizer(source_text, this._options); - this._tokens = tokenizer.tokenize(); - return source_text; -}; - -Beautifier.prototype.beautify = function() { - // if disabled, return the input unchanged. - if (this._options.disabled) { - return this._source_text; - } - - var sweet_code; - var source_text = this._reset(this._source_text); - - var eol = this._options.eol; - if (this._options.eol === 'auto') { - eol = '\n'; - if (source_text && acorn.lineBreak.test(source_text || '')) { - eol = source_text.match(acorn.lineBreak)[0]; - } - } - - var current_token = this._tokens.next(); - while (current_token) { - this.handle_token(current_token); - - this._last_last_text = this._flags.last_token.text; - this._flags.last_token = current_token; - - current_token = this._tokens.next(); - } - - sweet_code = this._output.get_code(eol); - - return sweet_code; -}; - -Beautifier.prototype.handle_token = function(current_token, preserve_statement_flags) { - if (current_token.type === TOKEN.START_EXPR) { - this.handle_start_expr(current_token); - } else if (current_token.type === TOKEN.END_EXPR) { - this.handle_end_expr(current_token); - } else if (current_token.type === TOKEN.START_BLOCK) { - this.handle_start_block(current_token); - } else if (current_token.type === TOKEN.END_BLOCK) { - this.handle_end_block(current_token); - } else if (current_token.type === TOKEN.WORD) { - this.handle_word(current_token); - } else if (current_token.type === TOKEN.RESERVED) { - this.handle_word(current_token); - } else if (current_token.type === TOKEN.SEMICOLON) { - this.handle_semicolon(current_token); - } else if (current_token.type === TOKEN.STRING) { - this.handle_string(current_token); - } else if (current_token.type === TOKEN.EQUALS) { - this.handle_equals(current_token); - } else if (current_token.type === TOKEN.OPERATOR) { - this.handle_operator(current_token); - } else if (current_token.type === TOKEN.COMMA) { - this.handle_comma(current_token); - } else if (current_token.type === TOKEN.BLOCK_COMMENT) { - this.handle_block_comment(current_token, preserve_statement_flags); - } else if (current_token.type === TOKEN.COMMENT) { - this.handle_comment(current_token, preserve_statement_flags); - } else if (current_token.type === TOKEN.DOT) { - this.handle_dot(current_token); - } else if (current_token.type === TOKEN.EOF) { - this.handle_eof(current_token); - } else if (current_token.type === TOKEN.UNKNOWN) { - this.handle_unknown(current_token, preserve_statement_flags); - } else { - this.handle_unknown(current_token, preserve_statement_flags); - } -}; - -Beautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) { - var newlines = current_token.newlines; - var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode); - - if (current_token.comments_before) { - var comment_token = current_token.comments_before.next(); - while (comment_token) { - // The cleanest handling of inline comments is to treat them as though they aren't there. - // Just continue formatting and the behavior should be logical. - // Also ignore unknown tokens. Again, this should result in better behavior. - this.handle_whitespace_and_comments(comment_token, preserve_statement_flags); - this.handle_token(comment_token, preserve_statement_flags); - comment_token = current_token.comments_before.next(); - } - } - - if (keep_whitespace) { - for (var i = 0; i < newlines; i += 1) { - this.print_newline(i > 0, preserve_statement_flags); - } - } else { - if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) { - newlines = this._options.max_preserve_newlines; - } - - if (this._options.preserve_newlines) { - if (newlines > 1) { - this.print_newline(false, preserve_statement_flags); - for (var j = 1; j < newlines; j += 1) { - this.print_newline(true, preserve_statement_flags); - } - } - } - } - -}; - -var newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield']; - -Beautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) { - force_linewrap = (force_linewrap === undefined) ? false : force_linewrap; - - // Never wrap the first token on a line - if (this._output.just_added_newline()) { - return; - } - - var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap; - var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) || - in_array(current_token.text, positionable_operators); - - if (operatorLogicApplies) { - var shouldPrintOperatorNewline = ( - in_array(this._flags.last_token.text, positionable_operators) && - in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE) - ) || - in_array(current_token.text, positionable_operators); - shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline; - } - - if (shouldPreserveOrForce) { - this.print_newline(false, true); - } else if (this._options.wrap_line_length) { - if (reserved_array(this._flags.last_token, newline_restricted_tokens)) { - // These tokens should never have a newline inserted - // between them and the following expression. - return; - } - this._output.set_wrap_point(); - } -}; - -Beautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) { - if (!preserve_statement_flags) { - if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) { - var next_token = this._tokens.peek(); - while (this._flags.mode === MODE.Statement && - !(this._flags.if_block && reserved_word(next_token, 'else')) && - !this._flags.do_block) { - this.restore_mode(); - } - } - } - - if (this._output.add_new_line(force_newline)) { - this._flags.multiline_frame = true; - } -}; - -Beautifier.prototype.print_token_line_indentation = function(current_token) { - if (this._output.just_added_newline()) { - if (this._options.keep_array_indentation && - current_token.newlines && - (current_token.text === '[' || is_array(this._flags.mode))) { - this._output.current_line.set_indent(-1); - this._output.current_line.push(current_token.whitespace_before); - this._output.space_before_token = false; - } else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) { - this._flags.line_indent_level = this._flags.indentation_level; - } - } -}; - -Beautifier.prototype.print_token = function(current_token) { - if (this._output.raw) { - this._output.add_raw_token(current_token); - return; - } - - if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA && - this._output.just_added_newline()) { - if (this._output.previous_line.last() === ',') { - var popped = this._output.previous_line.pop(); - // if the comma was already at the start of the line, - // pull back onto that line and reprint the indentation - if (this._output.previous_line.is_empty()) { - this._output.previous_line.push(popped); - this._output.trim(true); - this._output.current_line.pop(); - this._output.trim(); - } - - // add the comma in front of the next token - this.print_token_line_indentation(current_token); - this._output.add_token(','); - this._output.space_before_token = true; - } - } - - this.print_token_line_indentation(current_token); - this._output.non_breaking_space = true; - this._output.add_token(current_token.text); - if (this._output.previous_token_wrapped) { - this._flags.multiline_frame = true; - } -}; - -Beautifier.prototype.indent = function() { - this._flags.indentation_level += 1; - this._output.set_indent(this._flags.indentation_level, this._flags.alignment); -}; - -Beautifier.prototype.deindent = function() { - if (this._flags.indentation_level > 0 && - ((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) { - this._flags.indentation_level -= 1; - this._output.set_indent(this._flags.indentation_level, this._flags.alignment); - } -}; - -Beautifier.prototype.set_mode = function(mode) { - if (this._flags) { - this._flag_store.push(this._flags); - this._previous_flags = this._flags; - } else { - this._previous_flags = this.create_flags(null, mode); - } - - this._flags = this.create_flags(this._previous_flags, mode); - this._output.set_indent(this._flags.indentation_level, this._flags.alignment); -}; - - -Beautifier.prototype.restore_mode = function() { - if (this._flag_store.length > 0) { - this._previous_flags = this._flags; - this._flags = this._flag_store.pop(); - if (this._previous_flags.mode === MODE.Statement) { - remove_redundant_indentation(this._output, this._previous_flags); - } - this._output.set_indent(this._flags.indentation_level, this._flags.alignment); - } -}; - -Beautifier.prototype.start_of_object_property = function() { - return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && ( - (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set']))); -}; - -Beautifier.prototype.start_of_statement = function(current_token) { - var start = false; - start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD; - start = start || reserved_word(this._flags.last_token, 'do'); - start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines; - start = start || reserved_word(this._flags.last_token, 'else') && - !(reserved_word(current_token, 'if') && !current_token.comments_before); - start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional)); - start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement && - !this._flags.in_case && - !(current_token.text === '--' || current_token.text === '++') && - this._last_last_text !== 'function' && - current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED); - start = start || (this._flags.mode === MODE.ObjectLiteral && ( - (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set']))); - - if (start) { - this.set_mode(MODE.Statement); - this.indent(); - - this.handle_whitespace_and_comments(current_token, true); - - // Issue #276: - // If starting a new statement with [if, for, while, do], push to a new line. - // if (a) if (b) if(c) d(); else e(); else f(); - if (!this.start_of_object_property()) { - this.allow_wrap_or_preserved_newline(current_token, - reserved_array(current_token, ['do', 'for', 'if', 'while'])); - } - return true; - } - return false; -}; - -Beautifier.prototype.handle_start_expr = function(current_token) { - // The conditional starts the statement if appropriate. - if (!this.start_of_statement(current_token)) { - this.handle_whitespace_and_comments(current_token); - } - - var next_mode = MODE.Expression; - if (current_token.text === '[') { - - if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') { - // this is array index specifier, break immediately - // a[x], fn()[x] - if (reserved_array(this._flags.last_token, line_starters)) { - this._output.space_before_token = true; - } - this.print_token(current_token); - this.set_mode(next_mode); - this.indent(); - if (this._options.space_in_paren) { - this._output.space_before_token = true; - } - return; - } - - next_mode = MODE.ArrayLiteral; - if (is_array(this._flags.mode)) { - if (this._flags.last_token.text === '[' || - (this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) { - // ], [ goes to new line - // }, [ goes to new line - if (!this._options.keep_array_indentation) { - this.print_newline(); - } - } - } - - if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR, TOKEN.DOT])) { - this._output.space_before_token = true; - } - } else { - if (this._flags.last_token.type === TOKEN.RESERVED) { - if (this._flags.last_token.text === 'for') { - this._output.space_before_token = this._options.space_before_conditional; - next_mode = MODE.ForInitializer; - } else if (in_array(this._flags.last_token.text, ['if', 'while', 'switch'])) { - this._output.space_before_token = this._options.space_before_conditional; - next_mode = MODE.Conditional; - } else if (in_array(this._flags.last_word, ['await', 'async'])) { - // Should be a space between await and an IIFE, or async and an arrow function - this._output.space_before_token = true; - } else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') { - this._output.space_before_token = false; - } else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') { - this._output.space_before_token = true; - } - } else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { - // Support of this kind of newline preservation. - // a = (b && - // (c || d)); - if (!this.start_of_object_property()) { - this.allow_wrap_or_preserved_newline(current_token); - } - } else if (this._flags.last_token.type === TOKEN.WORD) { - this._output.space_before_token = false; - - // function name() vs function name () - // function* name() vs function* name () - // async name() vs async name () - // In ES6, you can also define the method properties of an object - // var obj = {a: function() {}} - // It can be abbreviated - // var obj = {a() {}} - // var obj = { a() {}} vs var obj = { a () {}} - // var obj = { * a() {}} vs var obj = { * a () {}} - var peek_back_two = this._tokens.peek(-3); - if (this._options.space_after_named_function && peek_back_two) { - // peek starts at next character so -1 is current token - var peek_back_three = this._tokens.peek(-4); - if (reserved_array(peek_back_two, ['async', 'function']) || - (peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) { - this._output.space_before_token = true; - } else if (this._flags.mode === MODE.ObjectLiteral) { - if ((peek_back_two.text === '{' || peek_back_two.text === ',') || - (peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) { - this._output.space_before_token = true; - } - } - } - } else { - // Support preserving wrapped arrow function expressions - // a.b('c', - // () => d.e - // ) - this.allow_wrap_or_preserved_newline(current_token); - } - - // function() vs function () - // yield*() vs yield* () - // function*() vs function* () - if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) || - (this._flags.last_token.text === '*' && - (in_array(this._last_last_text, ['function', 'yield']) || - (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) { - this._output.space_before_token = this._options.space_after_anon_function; - } - } - - if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) { - this.print_newline(); - } else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) { - // do nothing on (( and )( and ][ and ]( and .( - // TODO: Consider whether forcing this is required. Review failing tests when removed. - this.allow_wrap_or_preserved_newline(current_token, current_token.newlines); - } - - this.print_token(current_token); - this.set_mode(next_mode); - if (this._options.space_in_paren) { - this._output.space_before_token = true; - } - - // In all cases, if we newline while inside an expression it should be indented. - this.indent(); -}; - -Beautifier.prototype.handle_end_expr = function(current_token) { - // statements inside expressions are not valid syntax, but... - // statements must all be closed when their container closes - while (this._flags.mode === MODE.Statement) { - this.restore_mode(); - } - - this.handle_whitespace_and_comments(current_token); - - if (this._flags.multiline_frame) { - this.allow_wrap_or_preserved_newline(current_token, - current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation); - } - - if (this._options.space_in_paren) { - if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) { - // () [] no inner space in empty parens like these, ever, ref #320 - this._output.trim(); - this._output.space_before_token = false; - } else { - this._output.space_before_token = true; - } - } - this.deindent(); - this.print_token(current_token); - this.restore_mode(); - - remove_redundant_indentation(this._output, this._previous_flags); - - // do {} while () // no statement required after - if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) { - this._previous_flags.mode = MODE.Expression; - this._flags.do_block = false; - this._flags.do_while = false; - - } -}; - -Beautifier.prototype.handle_start_block = function(current_token) { - this.handle_whitespace_and_comments(current_token); - - // Check if this is should be treated as a ObjectLiteral - var next_token = this._tokens.peek(); - var second_token = this._tokens.peek(1); - if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) { - this.set_mode(MODE.BlockStatement); - this._flags.in_case_statement = true; - } else if (this._flags.case_body) { - this.set_mode(MODE.BlockStatement); - } else if (second_token && ( - (in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) || - (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED])) - )) { - // We don't support TypeScript,but we didn't break it for a very long time. - // We'll try to keep not breaking it. - if (!in_array(this._last_last_text, ['class', 'interface'])) { - this.set_mode(MODE.ObjectLiteral); - } else { - this.set_mode(MODE.BlockStatement); - } - } else if (this._flags.last_token.type === TOKEN.OPERATOR && (this._flags.last_token.text === '=>' || this._flags.last_token.text === '->')) { - // arrow function: (param1, paramN) => { statements } - this.set_mode(MODE.BlockStatement); - } else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) || - reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default']) - ) { - // Detecting shorthand function syntax is difficult by scanning forward, - // so check the surrounding context. - // If the block is being returned, imported, export default, passed as arg, - // assigned with = or assigned in a nested object, treat as an ObjectLiteral. - this.set_mode(MODE.ObjectLiteral); - } else { - this.set_mode(MODE.BlockStatement); - } - - var empty_braces = !next_token.comments_before && next_token.text === '}'; - var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' && - this._flags.last_token.type === TOKEN.END_EXPR; - - if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so - { - // search forward for a newline wanted inside this block - var index = 0; - var check_token = null; - this._flags.inline_frame = true; - do { - index += 1; - check_token = this._tokens.peek(index - 1); - if (check_token.newlines) { - this._flags.inline_frame = false; - break; - } - } while (check_token.type !== TOKEN.EOF && - !(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token)); - } - - if ((this._options.brace_style === "expand" || - (this._options.brace_style === "none" && current_token.newlines)) && - !this._flags.inline_frame) { - if (this._flags.last_token.type !== TOKEN.OPERATOR && - (empty_anonymous_function || - this._flags.last_token.type === TOKEN.EQUALS || - (reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) { - this._output.space_before_token = true; - } else { - this.print_newline(false, true); - } - } else { // collapse || inline_frame - if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) { - if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) { - this._output.space_before_token = true; - } - - if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) { - this.allow_wrap_or_preserved_newline(current_token); - this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame; - this._flags.multiline_frame = false; - } - } - if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) { - if (this._flags.last_token.type === TOKEN.START_BLOCK && !this._flags.inline_frame) { - this.print_newline(); - } else { - this._output.space_before_token = true; - } - } - } - this.print_token(current_token); - this.indent(); - - // Except for specific cases, open braces are followed by a new line. - if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) { - this.print_newline(); - } -}; - -Beautifier.prototype.handle_end_block = function(current_token) { - // statements must all be closed when their container closes - this.handle_whitespace_and_comments(current_token); - - while (this._flags.mode === MODE.Statement) { - this.restore_mode(); - } - - var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK; - - if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first - this._output.space_before_token = true; - } else if (this._options.brace_style === "expand") { - if (!empty_braces) { - this.print_newline(); - } - } else { - // skip {} - if (!empty_braces) { - if (is_array(this._flags.mode) && this._options.keep_array_indentation) { - // we REALLY need a newline here, but newliner would skip that - this._options.keep_array_indentation = false; - this.print_newline(); - this._options.keep_array_indentation = true; - - } else { - this.print_newline(); - } - } - } - this.restore_mode(); - this.print_token(current_token); -}; - -Beautifier.prototype.handle_word = function(current_token) { - if (current_token.type === TOKEN.RESERVED) { - if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) { - current_token.type = TOKEN.WORD; - } else if (current_token.text === 'import' && this._tokens.peek().text === '(') { - current_token.type = TOKEN.WORD; - } else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) { - current_token.type = TOKEN.WORD; - } else if (this._flags.mode === MODE.ObjectLiteral) { - var next_token = this._tokens.peek(); - if (next_token.text === ':') { - current_token.type = TOKEN.WORD; - } - } - } - - if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) { - this._flags.declaration_statement = true; - } - } else if (current_token.newlines && !is_expression(this._flags.mode) && - (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) && - this._flags.last_token.type !== TOKEN.EQUALS && - (this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) { - this.handle_whitespace_and_comments(current_token); - this.print_newline(); - } else { - this.handle_whitespace_and_comments(current_token); - } - - if (this._flags.do_block && !this._flags.do_while) { - if (reserved_word(current_token, 'while')) { - // do {} ## while () - this._output.space_before_token = true; - this.print_token(current_token); - this._output.space_before_token = true; - this._flags.do_while = true; - return; - } else { - // do {} should always have while as the next word. - // if we don't see the expected while, recover - this.print_newline(); - this._flags.do_block = false; - } - } - - // if may be followed by else, or not - // Bare/inline ifs are tricky - // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e(); - if (this._flags.if_block) { - if (!this._flags.else_block && reserved_word(current_token, 'else')) { - this._flags.else_block = true; - } else { - while (this._flags.mode === MODE.Statement) { - this.restore_mode(); - } - this._flags.if_block = false; - this._flags.else_block = false; - } - } - - if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) { - this.print_newline(); - if (!this._flags.case_block && (this._flags.case_body || this._options.jslint_happy)) { - // switch cases following one another - this.deindent(); - } - this._flags.case_body = false; - - this.print_token(current_token); - this._flags.in_case = true; - return; - } - - if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { - if (!this.start_of_object_property()) { - this.allow_wrap_or_preserved_newline(current_token); - } - } - - if (reserved_word(current_token, 'function')) { - if (in_array(this._flags.last_token.text, ['}', ';']) || - (this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) { - // make sure there is a nice clean space of at least one blank line - // before a new function definition - if (!this._output.just_added_blankline() && !current_token.comments_before) { - this.print_newline(); - this.print_newline(true); - } - } - if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD) { - if (reserved_array(this._flags.last_token, ['get', 'set', 'new', 'export']) || - reserved_array(this._flags.last_token, newline_restricted_tokens)) { - this._output.space_before_token = true; - } else if (reserved_word(this._flags.last_token, 'default') && this._last_last_text === 'export') { - this._output.space_before_token = true; - } else if (this._flags.last_token.text === 'declare') { - // accomodates Typescript declare function formatting - this._output.space_before_token = true; - } else { - this.print_newline(); - } - } else if (this._flags.last_token.type === TOKEN.OPERATOR || this._flags.last_token.text === '=') { - // foo = function - this._output.space_before_token = true; - } else if (!this._flags.multiline_frame && (is_expression(this._flags.mode) || is_array(this._flags.mode))) { - // (function - } else { - this.print_newline(); - } - - this.print_token(current_token); - this._flags.last_word = current_token.text; - return; - } - - var prefix = 'NONE'; - - if (this._flags.last_token.type === TOKEN.END_BLOCK) { - - if (this._previous_flags.inline_frame) { - prefix = 'SPACE'; - } else if (!reserved_array(current_token, ['else', 'catch', 'finally', 'from'])) { - prefix = 'NEWLINE'; - } else { - if (this._options.brace_style === "expand" || - this._options.brace_style === "end-expand" || - (this._options.brace_style === "none" && current_token.newlines)) { - prefix = 'NEWLINE'; - } else { - prefix = 'SPACE'; - this._output.space_before_token = true; - } - } - } else if (this._flags.last_token.type === TOKEN.SEMICOLON && this._flags.mode === MODE.BlockStatement) { - // TODO: Should this be for STATEMENT as well? - prefix = 'NEWLINE'; - } else if (this._flags.last_token.type === TOKEN.SEMICOLON && is_expression(this._flags.mode)) { - prefix = 'SPACE'; - } else if (this._flags.last_token.type === TOKEN.STRING) { - prefix = 'SPACE'; - } else if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || - (this._flags.last_token.text === '*' && - (in_array(this._last_last_text, ['function', 'yield']) || - (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) { - prefix = 'SPACE'; - } else if (this._flags.last_token.type === TOKEN.START_BLOCK) { - if (this._flags.inline_frame) { - prefix = 'SPACE'; - } else { - prefix = 'NEWLINE'; - } - } else if (this._flags.last_token.type === TOKEN.END_EXPR) { - this._output.space_before_token = true; - prefix = 'NEWLINE'; - } - - if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') { - if (this._flags.inline_frame || this._flags.last_token.text === 'else' || this._flags.last_token.text === 'export') { - prefix = 'SPACE'; - } else { - prefix = 'NEWLINE'; - } - - } - - if (reserved_array(current_token, ['else', 'catch', 'finally'])) { - if ((!(this._flags.last_token.type === TOKEN.END_BLOCK && this._previous_flags.mode === MODE.BlockStatement) || - this._options.brace_style === "expand" || - this._options.brace_style === "end-expand" || - (this._options.brace_style === "none" && current_token.newlines)) && - !this._flags.inline_frame) { - this.print_newline(); - } else { - this._output.trim(true); - var line = this._output.current_line; - // If we trimmed and there's something other than a close block before us - // put a newline back in. Handles '} // comment' scenario. - if (line.last() !== '}') { - this.print_newline(); - } - this._output.space_before_token = true; - } - } else if (prefix === 'NEWLINE') { - if (reserved_array(this._flags.last_token, special_words)) { - // no newline between 'return nnn' - this._output.space_before_token = true; - } else if (this._flags.last_token.text === 'declare' && reserved_array(current_token, ['var', 'let', 'const'])) { - // accomodates Typescript declare formatting - this._output.space_before_token = true; - } else if (this._flags.last_token.type !== TOKEN.END_EXPR) { - if ((this._flags.last_token.type !== TOKEN.START_EXPR || !reserved_array(current_token, ['var', 'let', 'const'])) && this._flags.last_token.text !== ':') { - // no need to force newline on 'var': for (var x = 0...) - if (reserved_word(current_token, 'if') && reserved_word(current_token.previous, 'else')) { - // no newline for } else if { - this._output.space_before_token = true; - } else { - this.print_newline(); - } - } - } else if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') { - this.print_newline(); - } - } else if (this._flags.multiline_frame && is_array(this._flags.mode) && this._flags.last_token.text === ',' && this._last_last_text === '}') { - this.print_newline(); // }, in lists get a newline treatment - } else if (prefix === 'SPACE') { - this._output.space_before_token = true; - } - if (current_token.previous && (current_token.previous.type === TOKEN.WORD || current_token.previous.type === TOKEN.RESERVED)) { - this._output.space_before_token = true; - } - this.print_token(current_token); - this._flags.last_word = current_token.text; - - if (current_token.type === TOKEN.RESERVED) { - if (current_token.text === 'do') { - this._flags.do_block = true; - } else if (current_token.text === 'if') { - this._flags.if_block = true; - } else if (current_token.text === 'import') { - this._flags.import_block = true; - } else if (this._flags.import_block && reserved_word(current_token, 'from')) { - this._flags.import_block = false; - } - } -}; - -Beautifier.prototype.handle_semicolon = function(current_token) { - if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - // Semicolon can be the start (and end) of a statement - this._output.space_before_token = false; - } else { - this.handle_whitespace_and_comments(current_token); - } - - var next_token = this._tokens.peek(); - while (this._flags.mode === MODE.Statement && - !(this._flags.if_block && reserved_word(next_token, 'else')) && - !this._flags.do_block) { - this.restore_mode(); - } - - // hacky but effective for the moment - if (this._flags.import_block) { - this._flags.import_block = false; - } - this.print_token(current_token); -}; - -Beautifier.prototype.handle_string = function(current_token) { - if (current_token.text.startsWith("`") && current_token.newlines === 0 && current_token.whitespace_before === '' && (current_token.previous.text === ')' || this._flags.last_token.type === TOKEN.WORD)) { - //Conditional for detectign backtick strings - } else if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - // One difference - strings want at least a space before - this._output.space_before_token = true; - } else { - this.handle_whitespace_and_comments(current_token); - if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || this._flags.inline_frame) { - this._output.space_before_token = true; - } else if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { - if (!this.start_of_object_property()) { - this.allow_wrap_or_preserved_newline(current_token); - } - } else if ((current_token.text.startsWith("`") && this._flags.last_token.type === TOKEN.END_EXPR && (current_token.previous.text === ']' || current_token.previous.text === ')') && current_token.newlines === 0)) { - this._output.space_before_token = true; - } else { - this.print_newline(); - } - } - this.print_token(current_token); -}; - -Beautifier.prototype.handle_equals = function(current_token) { - if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - } else { - this.handle_whitespace_and_comments(current_token); - } - - if (this._flags.declaration_statement) { - // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done - this._flags.declaration_assignment = true; - } - this._output.space_before_token = true; - this.print_token(current_token); - this._output.space_before_token = true; -}; - -Beautifier.prototype.handle_comma = function(current_token) { - this.handle_whitespace_and_comments(current_token, true); - - this.print_token(current_token); - this._output.space_before_token = true; - if (this._flags.declaration_statement) { - if (is_expression(this._flags.parent.mode)) { - // do not break on comma, for(var a = 1, b = 2) - this._flags.declaration_assignment = false; - } - - if (this._flags.declaration_assignment) { - this._flags.declaration_assignment = false; - this.print_newline(false, true); - } else if (this._options.comma_first) { - // for comma-first, we want to allow a newline before the comma - // to turn into a newline after the comma, which we will fixup later - this.allow_wrap_or_preserved_newline(current_token); - } - } else if (this._flags.mode === MODE.ObjectLiteral || - (this._flags.mode === MODE.Statement && this._flags.parent.mode === MODE.ObjectLiteral)) { - if (this._flags.mode === MODE.Statement) { - this.restore_mode(); - } - - if (!this._flags.inline_frame) { - this.print_newline(); - } - } else if (this._options.comma_first) { - // EXPR or DO_BLOCK - // for comma-first, we want to allow a newline before the comma - // to turn into a newline after the comma, which we will fixup later - this.allow_wrap_or_preserved_newline(current_token); - } -}; - -Beautifier.prototype.handle_operator = function(current_token) { - var isGeneratorAsterisk = current_token.text === '*' && - (reserved_array(this._flags.last_token, ['function', 'yield']) || - (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.COMMA, TOKEN.END_BLOCK, TOKEN.SEMICOLON])) - ); - var isUnary = in_array(current_token.text, ['-', '+']) && ( - in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.START_EXPR, TOKEN.EQUALS, TOKEN.OPERATOR]) || - in_array(this._flags.last_token.text, line_starters) || - this._flags.last_token.text === ',' - ); - - if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - } else { - var preserve_statement_flags = !isGeneratorAsterisk; - this.handle_whitespace_and_comments(current_token, preserve_statement_flags); - } - - if (reserved_array(this._flags.last_token, special_words)) { - // "return" had a special handling in TK_WORD. Now we need to return the favor - this._output.space_before_token = true; - this.print_token(current_token); - return; - } - - // hack for actionscript's import .*; - if (current_token.text === '*' && this._flags.last_token.type === TOKEN.DOT) { - this.print_token(current_token); - return; - } - - if (current_token.text === '::') { - // no spaces around exotic namespacing syntax operator - this.print_token(current_token); - return; - } - - // Allow line wrapping between operators when operator_position is - // set to before or preserve - if (this._flags.last_token.type === TOKEN.OPERATOR && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) { - this.allow_wrap_or_preserved_newline(current_token); - } - - if (current_token.text === ':' && this._flags.in_case) { - this.print_token(current_token); - - this._flags.in_case = false; - this._flags.case_body = true; - if (this._tokens.peek().type !== TOKEN.START_BLOCK) { - this.indent(); - this.print_newline(); - this._flags.case_block = false; - } else { - this._flags.case_block = true; - this._output.space_before_token = true; - } - return; - } - - var space_before = true; - var space_after = true; - var in_ternary = false; - if (current_token.text === ':') { - if (this._flags.ternary_depth === 0) { - // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant. - space_before = false; - } else { - this._flags.ternary_depth -= 1; - in_ternary = true; - } - } else if (current_token.text === '?') { - this._flags.ternary_depth += 1; - } - - // let's handle the operator_position option prior to any conflicting logic - if (!isUnary && !isGeneratorAsterisk && this._options.preserve_newlines && in_array(current_token.text, positionable_operators)) { - var isColon = current_token.text === ':'; - var isTernaryColon = (isColon && in_ternary); - var isOtherColon = (isColon && !in_ternary); - - switch (this._options.operator_position) { - case OPERATOR_POSITION.before_newline: - // if the current token is : and it's not a ternary statement then we set space_before to false - this._output.space_before_token = !isOtherColon; - - this.print_token(current_token); - - if (!isColon || isTernaryColon) { - this.allow_wrap_or_preserved_newline(current_token); - } - - this._output.space_before_token = true; - return; - - case OPERATOR_POSITION.after_newline: - // if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement, - // then print a newline. - - this._output.space_before_token = true; - - if (!isColon || isTernaryColon) { - if (this._tokens.peek().newlines) { - this.print_newline(false, true); - } else { - this.allow_wrap_or_preserved_newline(current_token); - } - } else { - this._output.space_before_token = false; - } - - this.print_token(current_token); - - this._output.space_before_token = true; - return; - - case OPERATOR_POSITION.preserve_newline: - if (!isOtherColon) { - this.allow_wrap_or_preserved_newline(current_token); - } - - // if we just added a newline, or the current token is : and it's not a ternary statement, - // then we set space_before to false - space_before = !(this._output.just_added_newline() || isOtherColon); - - this._output.space_before_token = space_before; - this.print_token(current_token); - this._output.space_before_token = true; - return; - } - } - - if (isGeneratorAsterisk) { - this.allow_wrap_or_preserved_newline(current_token); - space_before = false; - var next_token = this._tokens.peek(); - space_after = next_token && in_array(next_token.type, [TOKEN.WORD, TOKEN.RESERVED]); - } else if (current_token.text === '...') { - this.allow_wrap_or_preserved_newline(current_token); - space_before = this._flags.last_token.type === TOKEN.START_BLOCK; - space_after = false; - } else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) { - // unary operators (and binary +/- pretending to be unary) special cases - if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR) { - this.allow_wrap_or_preserved_newline(current_token); - } - - space_before = false; - space_after = false; - - // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1 - // if there is a newline between -- or ++ and anything else we should preserve it. - if (current_token.newlines && (current_token.text === '--' || current_token.text === '++' || current_token.text === '~')) { - this.print_newline(false, true); - } - - if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) { - // for (;; ++i) - // ^^^ - space_before = true; - } - - if (this._flags.last_token.type === TOKEN.RESERVED) { - space_before = true; - } else if (this._flags.last_token.type === TOKEN.END_EXPR) { - space_before = !(this._flags.last_token.text === ']' && (current_token.text === '--' || current_token.text === '++')); - } else if (this._flags.last_token.type === TOKEN.OPERATOR) { - // a++ + ++b; - // a - -b - space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(this._flags.last_token.text, ['--', '-', '++', '+']); - // + and - are not unary when preceeded by -- or ++ operator - // a-- + b - // a * +b - // a - -b - if (in_array(current_token.text, ['+', '-']) && in_array(this._flags.last_token.text, ['--', '++'])) { - space_after = true; - } - } - - - if (((this._flags.mode === MODE.BlockStatement && !this._flags.inline_frame) || this._flags.mode === MODE.Statement) && - (this._flags.last_token.text === '{' || this._flags.last_token.text === ';')) { - // { foo; --i } - // foo(); --bar; - this.print_newline(); - } - } - - this._output.space_before_token = this._output.space_before_token || space_before; - this.print_token(current_token); - this._output.space_before_token = space_after; -}; - -Beautifier.prototype.handle_block_comment = function(current_token, preserve_statement_flags) { - if (this._output.raw) { - this._output.add_raw_token(current_token); - if (current_token.directives && current_token.directives.preserve === 'end') { - // If we're testing the raw output behavior, do not allow a directive to turn it off. - this._output.raw = this._options.test_output_raw; - } - return; - } - - if (current_token.directives) { - this.print_newline(false, preserve_statement_flags); - this.print_token(current_token); - if (current_token.directives.preserve === 'start') { - this._output.raw = true; - } - this.print_newline(false, true); - return; - } - - // inline block - if (!acorn.newline.test(current_token.text) && !current_token.newlines) { - this._output.space_before_token = true; - this.print_token(current_token); - this._output.space_before_token = true; - return; - } else { - this.print_block_commment(current_token, preserve_statement_flags); - } -}; - -Beautifier.prototype.print_block_commment = function(current_token, preserve_statement_flags) { - var lines = split_linebreaks(current_token.text); - var j; // iterator for this case - var javadoc = false; - var starless = false; - var lastIndent = current_token.whitespace_before; - var lastIndentLength = lastIndent.length; - - // block comment starts with a new line - this.print_newline(false, preserve_statement_flags); - - // first line always indented - this.print_token_line_indentation(current_token); - this._output.add_token(lines[0]); - this.print_newline(false, preserve_statement_flags); - - - if (lines.length > 1) { - lines = lines.slice(1); - javadoc = all_lines_start_with(lines, '*'); - starless = each_line_matches_indent(lines, lastIndent); - - if (javadoc) { - this._flags.alignment = 1; - } - - for (j = 0; j < lines.length; j++) { - if (javadoc) { - // javadoc: reformat and re-indent - this.print_token_line_indentation(current_token); - this._output.add_token(ltrim(lines[j])); - } else if (starless && lines[j]) { - // starless: re-indent non-empty content, avoiding trim - this.print_token_line_indentation(current_token); - this._output.add_token(lines[j].substring(lastIndentLength)); - } else { - // normal comments output raw - this._output.current_line.set_indent(-1); - this._output.add_token(lines[j]); - } - - // for comments on their own line or more than one line, make sure there's a new line after - this.print_newline(false, preserve_statement_flags); - } - - this._flags.alignment = 0; - } -}; - - -Beautifier.prototype.handle_comment = function(current_token, preserve_statement_flags) { - if (current_token.newlines) { - this.print_newline(false, preserve_statement_flags); - } else { - this._output.trim(true); - } - - this._output.space_before_token = true; - this.print_token(current_token); - this.print_newline(false, preserve_statement_flags); -}; - -Beautifier.prototype.handle_dot = function(current_token) { - if (this.start_of_statement(current_token)) { - // The conditional starts the statement if appropriate. - } else { - this.handle_whitespace_and_comments(current_token, true); - } - - if (reserved_array(this._flags.last_token, special_words)) { - this._output.space_before_token = false; - } else { - // allow preserved newlines before dots in general - // force newlines on dots after close paren when break_chained - for bar().baz() - this.allow_wrap_or_preserved_newline(current_token, - this._flags.last_token.text === ')' && this._options.break_chained_methods); - } - - // Only unindent chained method dot if this dot starts a new line. - // Otherwise the automatic extra indentation removal will handle the over indent - if (this._options.unindent_chained_methods && this._output.just_added_newline()) { - this.deindent(); - } - - this.print_token(current_token); -}; - -Beautifier.prototype.handle_unknown = function(current_token, preserve_statement_flags) { - this.print_token(current_token); - - if (current_token.text[current_token.text.length - 1] === '\n') { - this.print_newline(false, preserve_statement_flags); - } -}; - -Beautifier.prototype.handle_eof = function(current_token) { - // Unwind any open statements - while (this._flags.mode === MODE.Statement) { - this.restore_mode(); - } - this.handle_whitespace_and_comments(current_token); -}; - -module.exports.Beautifier = Beautifier; diff --git a/magic-editor/src/console/src/scripts/beautifier/javascript/options.js b/magic-editor/src/console/src/scripts/beautifier/javascript/options.js deleted file mode 100644 index 1234f239..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/javascript/options.js +++ /dev/null @@ -1,93 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var BaseOptions = require('../core/options').Options; - -var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; - -function Options(options) { - BaseOptions.call(this, options, 'js'); - - // compatibility, re - var raw_brace_style = this.raw_options.brace_style || null; - if (raw_brace_style === "expand-strict") { //graceful handling of deprecated option - this.raw_options.brace_style = "expand"; - } else if (raw_brace_style === "collapse-preserve-inline") { //graceful handling of deprecated option - this.raw_options.brace_style = "collapse,preserve-inline"; - } else if (this.raw_options.braces_on_own_line !== undefined) { //graceful handling of deprecated option - this.raw_options.brace_style = this.raw_options.braces_on_own_line ? "expand" : "collapse"; - // } else if (!raw_brace_style) { //Nothing exists to set it - // raw_brace_style = "collapse"; - } - - //preserve-inline in delimited string will trigger brace_preserve_inline, everything - //else is considered a brace_style and the last one only will have an effect - - var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']); - - this.brace_preserve_inline = false; //Defaults in case one or other was not specified in meta-option - this.brace_style = "collapse"; - - for (var bs = 0; bs < brace_style_split.length; bs++) { - if (brace_style_split[bs] === "preserve-inline") { - this.brace_preserve_inline = true; - } else { - this.brace_style = brace_style_split[bs]; - } - } - - this.unindent_chained_methods = this._get_boolean('unindent_chained_methods'); - this.break_chained_methods = this._get_boolean('break_chained_methods'); - this.space_in_paren = this._get_boolean('space_in_paren'); - this.space_in_empty_paren = this._get_boolean('space_in_empty_paren'); - this.jslint_happy = this._get_boolean('jslint_happy'); - this.space_after_anon_function = this._get_boolean('space_after_anon_function'); - this.space_after_named_function = this._get_boolean('space_after_named_function'); - this.keep_array_indentation = this._get_boolean('keep_array_indentation'); - this.space_before_conditional = this._get_boolean('space_before_conditional', true); - this.unescape_strings = this._get_boolean('unescape_strings'); - this.e4x = this._get_boolean('e4x'); - this.comma_first = this._get_boolean('comma_first'); - this.operator_position = this._get_selection('operator_position', validPositionValues); - - // For testing of beautify preserve:start directive - this.test_output_raw = this._get_boolean('test_output_raw'); - - // force this._options.space_after_anon_function to true if this._options.jslint_happy - if (this.jslint_happy) { - this.space_after_anon_function = true; - } - -} -Options.prototype = new BaseOptions(); - - - -module.exports.Options = Options; diff --git a/magic-editor/src/console/src/scripts/beautifier/javascript/tokenizer.js b/magic-editor/src/console/src/scripts/beautifier/javascript/tokenizer.js deleted file mode 100644 index eef730cd..00000000 --- a/magic-editor/src/console/src/scripts/beautifier/javascript/tokenizer.js +++ /dev/null @@ -1,573 +0,0 @@ -/*jshint node:true */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -'use strict'; - -var InputScanner = require('../core/inputscanner').InputScanner; -var BaseTokenizer = require('../core/tokenizer').Tokenizer; -var BASETOKEN = require('../core/tokenizer').TOKEN; -var Directives = require('../core/directives').Directives; -var acorn = require('./acorn'); -var Pattern = require('../core/pattern').Pattern; -var TemplatablePattern = require('../core/templatablepattern').TemplatablePattern; - - -function in_array(what, arr) { - return arr.indexOf(what) !== -1; -} - - -var TOKEN = { - START_EXPR: 'TK_START_EXPR', - END_EXPR: 'TK_END_EXPR', - START_BLOCK: 'TK_START_BLOCK', - END_BLOCK: 'TK_END_BLOCK', - WORD: 'TK_WORD', - RESERVED: 'TK_RESERVED', - SEMICOLON: 'TK_SEMICOLON', - STRING: 'TK_STRING', - EQUALS: 'TK_EQUALS', - OPERATOR: 'TK_OPERATOR', - COMMA: 'TK_COMMA', - BLOCK_COMMENT: 'TK_BLOCK_COMMENT', - COMMENT: 'TK_COMMENT', - DOT: 'TK_DOT', - UNKNOWN: 'TK_UNKNOWN', - START: BASETOKEN.START, - RAW: BASETOKEN.RAW, - EOF: BASETOKEN.EOF -}; - - -var directives_core = new Directives(/\/\*/, /\*\//); - -var number_pattern = /0[xX][0123456789abcdefABCDEF_]*[mMdDlLfFsSbB]?|0[oO][01234567_]*[mMdDlLfFsSbB]?|0[bB][01_]*[mMdDlLfFsSbB]?|\d[\d_]*[mMdDlLfFsSbB]|(?:\.\d[\d_]*|\d[\d_]*\.?[\d_]*)(?:[eE][+-]?[\d_]+)?/; - -var digit = /[0-9]/; - -// Dot "." must be distinguished from "..." and decimal -var dot_pattern = /[^\d.]/; - -var positionable_operators = ( - ">>> === !== " + - "<< && >= ** != == <= >> || ?? |> " + - "< / - + > : & % ? ^ | *").split(' '); - -// IMPORTANT: this must be sorted longest to shortest or tokenizing many not work. -// Also, you must update possitionable operators separately from punct -var punct = - ">>>= " + - "... >>= <<= === >>> !== **= " + - "=> -> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> " + - "= ! ? > < : / ^ - + * & % ~ |"; - -punct = punct.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); -// ?. but not if followed by a number -punct = '\\?\\.(?!\\d) ' + punct; -punct = punct.replace(/ /g, '|'); - -var punct_pattern = new RegExp(punct); - -// words which should always start on new line. -var line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(','); -var reserved_words = line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as']); -var reserved_word_pattern = new RegExp('^(?:' + reserved_words.join('|') + ')$'); - -// var template_pattern = /(?:(?:<\?php|<\?=)[\s\S]*?\?>)|(?:<%[\s\S]*?%>)/g; - -var in_html_comment; - -var Tokenizer = function(input_string, options) { - BaseTokenizer.call(this, input_string, options); - - this._patterns.whitespace = this._patterns.whitespace.matching( - /\u00A0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff/.source, - /\u2028\u2029/.source); - - var pattern_reader = new Pattern(this._input); - var templatable = new TemplatablePattern(this._input) - .read_options(this._options); - - this.__patterns = { - template: templatable, - identifier: templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch), - number: pattern_reader.matching(number_pattern), - punct: pattern_reader.matching(punct_pattern), - // comment ends just before nearest linefeed or end of file - comment: pattern_reader.starting_with(/\/\//).until(/[\n\r\u2028\u2029]/), - // /* ... */ comment ends with nearest */ or end of file - block_comment: pattern_reader.starting_with(/\/\*/).until_after(/\*\//), - html_comment_start: pattern_reader.matching(//), - include: pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak), - shebang: pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak), - xml: pattern_reader.matching(/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\]|)(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/), - single_quote: templatable.until(/['\\\n\r\u2028\u2029]/), - double_quote: templatable.until(/["\\\n\r\u2028\u2029]/), - template_text: templatable.until(/[`\\$]/), - template_expression: templatable.until(/[`}\\]/) - }; - -}; -Tokenizer.prototype = new BaseTokenizer(); - -Tokenizer.prototype._is_comment = function(current_token) { - return current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.BLOCK_COMMENT || current_token.type === TOKEN.UNKNOWN; -}; - -Tokenizer.prototype._is_opening = function(current_token) { - return current_token.type === TOKEN.START_BLOCK || current_token.type === TOKEN.START_EXPR; -}; - -Tokenizer.prototype._is_closing = function(current_token, open_token) { - return (current_token.type === TOKEN.END_BLOCK || current_token.type === TOKEN.END_EXPR) && - (open_token && ( - (current_token.text === ']' && open_token.text === '[') || - (current_token.text === ')' && open_token.text === '(') || - (current_token.text === '}' && open_token.text === '{'))); -}; - -Tokenizer.prototype._reset = function() { - in_html_comment = false; -}; - -Tokenizer.prototype._get_next_token = function(previous_token) { // jshint unused:false - var token = null; - this._readWhitespace(); - var c = this._input.peek(); - - if (c === null) { - return this._create_token(TOKEN.EOF, ''); - } - - token = token || this._read_non_javascript(c); - token = token || this._read_multi_string(c); - token = token || this._read_string(c); - token = token || this._read_word(previous_token); - token = token || this._read_singles(c); - token = token || this._read_comment(c); - token = token || this._read_regexp(c, previous_token); - token = token || this._read_xml(c, previous_token); - token = token || this._read_punctuation(); - token = token || this._create_token(TOKEN.UNKNOWN, this._input.next()); - - return token; -}; - -Tokenizer.prototype._read_word = function(previous_token) { - var resulting_string; - resulting_string = this.__patterns.identifier.read(); - if (resulting_string !== '') { - resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n'); - if (!(previous_token.type === TOKEN.DOT || - (previous_token.type === TOKEN.RESERVED && (previous_token.text === 'set' || previous_token.text === 'get'))) && - reserved_word_pattern.test(resulting_string)) { - if (resulting_string === 'in' || resulting_string === 'of') { // hack for 'in' and 'of' operators - return this._create_token(TOKEN.OPERATOR, resulting_string); - } - return this._create_token(TOKEN.RESERVED, resulting_string); - } - return this._create_token(TOKEN.WORD, resulting_string); - } - - resulting_string = this.__patterns.number.read(); - if (resulting_string !== '') { - return this._create_token(TOKEN.WORD, resulting_string); - } -}; - -Tokenizer.prototype._read_singles = function(c) { - var token = null; - if (c === '(' || c === '[') { - token = this._create_token(TOKEN.START_EXPR, c); - } else if (c === ')' || c === ']') { - token = this._create_token(TOKEN.END_EXPR, c); - } else if (c === '{') { - token = this._create_token(TOKEN.START_BLOCK, c); - } else if (c === '}') { - token = this._create_token(TOKEN.END_BLOCK, c); - } else if (c === ';') { - token = this._create_token(TOKEN.SEMICOLON, c); - } else if (c === '.' && dot_pattern.test(this._input.peek(1))) { - token = this._create_token(TOKEN.DOT, c); - } else if (c === ',') { - token = this._create_token(TOKEN.COMMA, c); - } - - if (token) { - this._input.next(); - } - return token; -}; - -Tokenizer.prototype._read_punctuation = function() { - var resulting_string = this.__patterns.punct.read(); - - if (resulting_string !== '') { - if (resulting_string === '=') { - return this._create_token(TOKEN.EQUALS, resulting_string); - } else if (resulting_string === '?.') { - return this._create_token(TOKEN.DOT, resulting_string); - } else { - return this._create_token(TOKEN.OPERATOR, resulting_string); - } - } -}; - -Tokenizer.prototype._read_non_javascript = function(c) { - var resulting_string = ''; - - if (c === '#') { - if (this._is_first_token()) { - resulting_string = this.__patterns.shebang.read(); - - if (resulting_string) { - return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n'); - } - } - - // handles extendscript #includes - resulting_string = this.__patterns.include.read(); - - if (resulting_string) { - return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n'); - } - - c = this._input.next(); - - // Spidermonkey-specific sharp variables for circular references. Considered obsolete. - var sharp = '#'; - if (this._input.hasNext() && this._input.testChar(digit)) { - do { - c = this._input.next(); - sharp += c; - } while (this._input.hasNext() && c !== '#' && c !== '='); - if (c === '#') { - // - } else if (this._input.peek() === '[' && this._input.peek(1) === ']') { - sharp += '[]'; - this._input.next(); - this._input.next(); - } else if (this._input.peek() === '{' && this._input.peek(1) === '}') { - sharp += '{}'; - this._input.next(); - this._input.next(); - } - return this._create_token(TOKEN.WORD, sharp); - } - - this._input.back(); - - } else if (c === '<' && this._is_first_token()) { - resulting_string = this.__patterns.html_comment_start.read(); - if (resulting_string) { - while (this._input.hasNext() && !this._input.testChar(acorn.newline)) { - resulting_string += this._input.next(); - } - in_html_comment = true; - return this._create_token(TOKEN.COMMENT, resulting_string); - } - } else if (in_html_comment && c === '-') { - resulting_string = this.__patterns.html_comment_end.read(); - if (resulting_string) { - in_html_comment = false; - return this._create_token(TOKEN.COMMENT, resulting_string); - } - } - - return null; -}; - -Tokenizer.prototype._read_comment = function(c) { - var token = null; - if (c === '/') { - var comment = ''; - if (this._input.peek(1) === '*') { - // peek for comment /* ... */ - comment = this.__patterns.block_comment.read(); - var directives = directives_core.get_directives(comment); - if (directives && directives.ignore === 'start') { - comment += directives_core.readIgnored(this._input); - } - comment = comment.replace(acorn.allLineBreaks, '\n'); - token = this._create_token(TOKEN.BLOCK_COMMENT, comment); - token.directives = directives; - } else if (this._input.peek(1) === '/') { - // peek for comment // ... - comment = this.__patterns.comment.read(); - token = this._create_token(TOKEN.COMMENT, comment); - } - } - return token; -}; -Tokenizer.prototype._read_multi_string = function() { - if(this._input.match(/"""/g)){ - let result = this._input.readUntilAfter(/"""/g) - return this._create_token(TOKEN.STRING, '"""' + result); - } - return null; -} -Tokenizer.prototype._read_string = function(c) { - if (c === '`' || c === "'" || c === '"') { - var resulting_string = this._input.next(); - this.has_char_escapes = false; - - if (c === '`') { - resulting_string += this._read_string_recursive('`', true, '${'); - } else { - resulting_string += this._read_string_recursive(c); - } - - if (this.has_char_escapes && this._options.unescape_strings) { - resulting_string = unescape_string(resulting_string); - } - - if (this._input.peek() === c) { - resulting_string += this._input.next(); - } - - resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n'); - - return this._create_token(TOKEN.STRING, resulting_string); - } - - return null; -}; - -Tokenizer.prototype._allow_regexp_or_xml = function(previous_token) { - // regex and xml can only appear in specific locations during parsing - return (previous_token.type === TOKEN.RESERVED && in_array(previous_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) || - (previous_token.type === TOKEN.END_EXPR && previous_token.text === ')' && - previous_token.opened.previous.type === TOKEN.RESERVED && in_array(previous_token.opened.previous.text, ['if', 'while', 'for'])) || - (in_array(previous_token.type, [TOKEN.COMMENT, TOKEN.START_EXPR, TOKEN.START_BLOCK, TOKEN.START, - TOKEN.END_BLOCK, TOKEN.OPERATOR, TOKEN.EQUALS, TOKEN.EOF, TOKEN.SEMICOLON, TOKEN.COMMA - ])); -}; - -Tokenizer.prototype._read_regexp = function(c, previous_token) { - - if (c === '/' && this._allow_regexp_or_xml(previous_token)) { - // handle regexp - // - var resulting_string = this._input.next(); - var esc = false; - - var in_char_class = false; - while (this._input.hasNext() && - ((esc || in_char_class || this._input.peek() !== c) && - !this._input.testChar(acorn.newline))) { - resulting_string += this._input.peek(); - if (!esc) { - esc = this._input.peek() === '\\'; - if (this._input.peek() === '[') { - in_char_class = true; - } else if (this._input.peek() === ']') { - in_char_class = false; - } - } else { - esc = false; - } - this._input.next(); - } - - if (this._input.peek() === c) { - resulting_string += this._input.next(); - - // regexps may have modifiers /regexp/MOD , so fetch those, too - // Only [gim] are valid, but if the user puts in garbage, do what we can to take it. - resulting_string += this._input.read(acorn.identifier); - } - return this._create_token(TOKEN.STRING, resulting_string); - } - return null; -}; - -Tokenizer.prototype._read_xml = function(c, previous_token) { - - if (this._options.e4x && c === "<" && this._allow_regexp_or_xml(previous_token)) { - var xmlStr = ''; - var match = this.__patterns.xml.read_match(); - // handle e4x xml literals - // - if (match) { - // Trim root tag to attempt to - var rootTag = match[2].replace(/^{\s+/, '{').replace(/\s+}$/, '}'); - var isCurlyRoot = rootTag.indexOf('{') === 0; - var depth = 0; - while (match) { - var isEndTag = !!match[1]; - var tagName = match[2]; - var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA["); - if (!isSingletonTag && - (tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\s+/, '{').replace(/\s+}$/, '}')))) { - if (isEndTag) { - --depth; - } else { - ++depth; - } - } - xmlStr += match[0]; - if (depth <= 0) { - break; - } - match = this.__patterns.xml.read_match(); - } - // if we didn't close correctly, keep unformatted. - if (!match) { - xmlStr += this._input.match(/[\s\S]*/g)[0]; - } - xmlStr = xmlStr.replace(acorn.allLineBreaks, '\n'); - return this._create_token(TOKEN.STRING, xmlStr); - } - } - - return null; -}; - -function unescape_string(s) { - // You think that a regex would work for this - // return s.replace(/\\x([0-9a-f]{2})/gi, function(match, val) { - // return String.fromCharCode(parseInt(val, 16)); - // }) - // However, dealing with '\xff', '\\xff', '\\\xff' makes this more fun. - var out = '', - escaped = 0; - - var input_scan = new InputScanner(s); - var matched = null; - - while (input_scan.hasNext()) { - // Keep any whitespace, non-slash characters - // also keep slash pairs. - matched = input_scan.match(/([\s]|[^\\]|\\\\)+/g); - - if (matched) { - out += matched[0]; - } - - if (input_scan.peek() === '\\') { - input_scan.next(); - if (input_scan.peek() === 'x') { - matched = input_scan.match(/x([0-9A-Fa-f]{2})/g); - } else if (input_scan.peek() === 'u') { - matched = input_scan.match(/u([0-9A-Fa-f]{4})/g); - } else { - out += '\\'; - if (input_scan.hasNext()) { - out += input_scan.next(); - } - continue; - } - - // If there's some error decoding, return the original string - if (!matched) { - return s; - } - - escaped = parseInt(matched[1], 16); - - if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) { - // we bail out on \x7f..\xff, - // leaving whole string escaped, - // as it's probably completely binary - return s; - } else if (escaped >= 0x00 && escaped < 0x20) { - // leave 0x00...0x1f escaped - out += '\\' + matched[0]; - continue; - } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) { - // single-quote, apostrophe, backslash - escape these - out += '\\' + String.fromCharCode(escaped); - } else { - out += String.fromCharCode(escaped); - } - } - } - - return out; -} - -// handle string -// -Tokenizer.prototype._read_string_recursive = function(delimiter, allow_unescaped_newlines, start_sub) { - var current_char; - var pattern; - if (delimiter === '\'') { - pattern = this.__patterns.single_quote; - } else if (delimiter === '"') { - pattern = this.__patterns.double_quote; - } else if (delimiter === '`') { - pattern = this.__patterns.template_text; - } else if (delimiter === '}') { - pattern = this.__patterns.template_expression; - } - - var resulting_string = pattern.read(); - var next = ''; - while (this._input.hasNext()) { - next = this._input.next(); - if (next === delimiter || - (!allow_unescaped_newlines && acorn.newline.test(next))) { - this._input.back(); - break; - } else if (next === '\\' && this._input.hasNext()) { - current_char = this._input.peek(); - - if (current_char === 'x' || current_char === 'u') { - this.has_char_escapes = true; - } else if (current_char === '\r' && this._input.peek(1) === '\n') { - this._input.next(); - } - next += this._input.next(); - } else if (start_sub) { - if (start_sub === '${' && next === '$' && this._input.peek() === '{') { - next += this._input.next(); - } - - if (start_sub === next) { - if (delimiter === '`') { - next += this._read_string_recursive('}', allow_unescaped_newlines, '`'); - } else { - next += this._read_string_recursive('`', allow_unescaped_newlines, '${'); - } - if (this._input.hasNext()) { - next += this._input.next(); - } - } - } - next += pattern.read(); - resulting_string += next; - } - - return resulting_string; -}; - -module.exports.Tokenizer = Tokenizer; -module.exports.TOKEN = TOKEN; -module.exports.positionable_operators = positionable_operators.slice(); -module.exports.line_starters = line_starters.slice(); diff --git a/magic-editor/src/console/src/scripts/bus.js b/magic-editor/src/console/src/scripts/bus.js deleted file mode 100644 index b7460fd8..00000000 --- a/magic-editor/src/console/src/scripts/bus.js +++ /dev/null @@ -1,35 +0,0 @@ -import Vue from 'vue' -import contants from './contants.js' -import {formatDate} from "@/scripts/utils.js"; -const statusLog = []; -const bus = new Vue() -try { - let element = document.createElement("script"); - element.src = "https://s4.cnzz.com/z_stat.php?id=1280031557&web_id=1280031557"; - element.setAttribute('async', true); - let s = document.getElementsByTagName("script")[0]; - s.parentNode.insertBefore(element, s); - element.onload = element.onreadystatechange = function () { - if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') { - bus.$emit('report', contants.MAGIC_API_VERSION); - } - } -} catch (ignored) { - -} -bus.$on('report', (eventId) => { - try { - window._czc.push(["_trackEvent",eventId,eventId]) - } catch (ignored) { - - } -}) -bus.$on('status', (content) => { - statusLog.push({ - timestamp: formatDate(new Date()), - content - }) -}) -bus.$getStatusLog = () => statusLog; -bus.$clearStatusLog = () => statusLog.length = 0 -export default bus \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/contants.js b/magic-editor/src/console/src/scripts/contants.js deleted file mode 100644 index 85402e02..00000000 --- a/magic-editor/src/console/src/scripts/contants.js +++ /dev/null @@ -1,36 +0,0 @@ -let MAGIC_API_VERSION_TEXT = process.env.VUE_APP_MA_VERSION -let MAGIC_API_VERSION = 'V' + MAGIC_API_VERSION_TEXT.replace(/\./g, '_') - -const contants = { - BASE_URL: '', //UI 对应的接口路径 - WEBSOCKET_SERVER: '', //WebSocket服务地址 - SERVER_URL: '', //接口对应的路径 - AUTO_SAVE: true, // 是否自动保存 - DECORATION_TIMEOUT: 10000, - API_DEFAULT_METHOD: 'GET', - MAGIC_API_VERSION_TEXT, - MAGIC_API_VERSION, - HEADER_REQUEST_SESSION: 'Magic-Request-Session', - HEADER_REQUEST_BREAKPOINTS: 'Magic-Request-Breakpoints', - HEADER_RESPONSE_MAGIC_CONTENT_TYPE: 'ma-content-type', - HEADER_APPLICATION_STREAM: 'application/octet-stream', - HEADER_CONTENT_DISPOSITION: 'ma-content-disposition', - HEADER_MAGIC_TOKEN: 'magic-token', - HEADER_MAGIC_TOKEN_VALUE: 'unauthorization', - IGNORE_VERSION: 'ignore-version', - RECENT_OPENED_TAB: 'recent_opened_tab', - RECENT_OPENED: 'recent_opened', - RESPONSE_CODE_DEBUG: 1000, - RESPONSE_CODE_SCRIPT_ERROR: -1000, - RESPONSE_NO_PERMISSION: -10, - LOG_MAX_ROWS: Infinity, - DEFAULT_EXPAND: true, - JDBC_DRIVERS: [], - DATASOURCE_TYPES: [], - OPTIONS: [], - EDITOR_FONT_FAMILY: 'JetBrainsMono, Consolas, "Courier New",monospace, 微软雅黑', - EDITOR_FONT_SIZE: 14, - config: {} -} - -export default contants diff --git a/magic-editor/src/console/src/scripts/editor/completion.js b/magic-editor/src/console/src/scripts/editor/completion.js deleted file mode 100644 index cf239048..00000000 --- a/magic-editor/src/console/src/scripts/editor/completion.js +++ /dev/null @@ -1,368 +0,0 @@ -import JavaClass from './java-class.js' -import tokenizer from '../parsing/tokenizer.js' -import {TokenStream} from '../parsing/index.js' -import {Parser} from '../parsing/parser.js' -import * as monaco from 'monaco-editor' -import RequestParameter from "@/scripts/editor/request-parameter"; -import {MemberAccess, MethodCall, NewStatement, VariableAccess} from "@/scripts/parsing/ast"; - -const completionImportJavaPackage = (suggestions, keyword, start, position) => { - let len = -1 - let importClass = JavaClass.getImportClass(); - if (start !== 0 && keyword && (len = importClass.length) > 0) { - keyword = keyword.toLowerCase() - JavaClass.getDefineModules().filter(module => module.toLowerCase().indexOf(keyword) > -1).forEach(module => suggestions.push({ - label: module, - filterText: module, - kind: monaco.languages.CompletionItemKind.Module, - detail: module, - insertText: module, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - })) - let set = new Set(); - for (let i = 0; i < len && suggestions.length < 100; i++) { - let clazz = importClass[i]; - let index = clazz.toLowerCase().indexOf(keyword); - if (index > -1) { - let className = clazz.substring(clazz.lastIndexOf('.') + 1); - if (index === 0) { - let content = clazz.substring(keyword.length); - let detail = content - if(content.startsWith(".")){ - detail = keyword + '.' - content = keyword.substring(keyword.lastIndexOf(".") + 1) + '.' - } else { - if(content.indexOf('.') === -1){ - suggestions.push({ - sortText: `2${className}`, - label: className, - kind: monaco.languages.CompletionItemKind.Class, - filterText: clazz, - detail: clazz, - insertText: className, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - }) - continue; - } - let text = content.substring(0, content.indexOf('.') + 1); - detail = keyword + text - content = keyword.substring(keyword.lastIndexOf(".") + 1) + text; - } - if (set.has(content)) { - continue; - } - set.add(content); - suggestions.push({ - sortText: `1${content}`, - label: content, - kind: monaco.languages.CompletionItemKind.Folder, - filterText: clazz, - detail: detail.replace(/\.$/, ''), - insertText: content, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - command: { - id: 'editor.action.triggerSuggest' - } - }) - } else if (className.toLowerCase().indexOf(keyword) > -1) { - suggestions.push({ - sortText: `2${className}`, - label: className, - kind: monaco.languages.CompletionItemKind.Class, - filterText: className, - detail: clazz, - insertText: clazz, - range: new monaco.Range(position.lineNumber, start + 1, position.lineNumber, position.column) - }) - } - } - } - } else { - JavaClass.getDefineModules().forEach(module => suggestions.push({ - label: module, - filterText: module, - kind: monaco.languages.CompletionItemKind.Module, - detail: module, - insertText: module, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - })) - } -} - -const completionImport = (suggestions, position, line, importIndex) => { - let start = line.indexOf('"') + 1; - if (start === 0) { - start = line.indexOf("'") + 1; - } - if(start === 0){ - line = line.trim().replace('import', '').trim() - completionImportJavaPackage(suggestions, line, importIndex + 1 , position) - return; - } - let text = line.substring(importIndex).trim().replace(/['|"]/g, ''); - if(text.startsWith('@')){ - if(text.indexOf(' ')> -1){ - return; - } - let finder = JavaClass.getApiFinder(); - (finder && finder() || []).forEach(it => { - let label = '@' + it.method + ':' + it.path - suggestions.push({ - sortText: label, - label: label, - kind: monaco.languages.CompletionItemKind.Reference, - filterText: label, - detail: it.name, - insertText: label, - range: new monaco.Range(position.lineNumber, start + 1, position.lineNumber, position.column) - }) - }) - finder = JavaClass.getFunctionFinder(); - (finder && finder() || []).forEach(it => { - let label = '@' + it.path - suggestions.push({ - sortText: label, - label: label, - kind: monaco.languages.CompletionItemKind.Reference, - filterText: label, - detail: it.name, - insertText: label, - range: new monaco.Range(position.lineNumber, start + 1, position.lineNumber, position.column) - }) - }) - return; - } - completionImportJavaPackage(suggestions, text, start, position) -} -const completionFunction = async (suggestions, input, env, best, isNew) => { - env = env || {} - if (best && best instanceof VariableAccess) { - if(await best.getJavaType(env) === 'java.lang.Object'){ - let importClass = JavaClass.getImportClass(); - const keyword = best.variable - importClass.forEach(clazz => { - let className = clazz.substring(clazz.lastIndexOf('.') + 1); - if(className.indexOf(keyword) > -1){ - suggestions.push({ - sortText: `${className}`, - label: className, - kind: monaco.languages.CompletionItemKind.Class, - filterText: className, - detail: clazz, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - command: { - id: 'editor.action.scrollUp1Line' - }, - insertText: className + (isNew ? '()' : ''), - additionalTextEdits: [{ - forceMoveMarkers: true, - text: `import ${clazz}\r\n`, - range: new monaco.Range(1, 0, 1, 0) - }] - }) - } - }) - } - } - JavaClass.findFunction().forEach(it => { - suggestions.push({ - sortText: it.sortText || it.fullName, - label: it.fullName, - filterText: it.name, - kind: monaco.languages.CompletionItemKind.Method, - detail: it.comment, - insertText: it.insertText, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - }) - let known = suggestions.map(it => it.detail); - let matches = input.match(/[a-zA-Z_$]+/ig) || []; - let count = matches.length; - let vars = Object.keys(env); - vars.forEach(key => { - suggestions.push({ - label: key, - filterText: key, - kind: monaco.languages.CompletionItemKind.Variable, - detail: env[key], - insertText: key, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - }) - if (count > 2) { - Array.from(new Set(matches)).filter((it, index) => index + 2 < count && known.indexOf(it) === -1 && vars.indexOf(it) === -1).map(it => { - suggestions.push({ - label: it, - filterText: it, - kind: monaco.languages.CompletionItemKind.Text, - detail: it, - insertText: it, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - }) - } -}; - -const completionMethod = async (className, suggestions) => { - let clazz = await JavaClass.loadClass(className) - let index = className.lastIndexOf('.') - let simpleName = index > 0 ? className.substring(index + 1) : className - let enums = JavaClass.findEnums(clazz); - if (enums) { - for (let j = 0; j < enums.length; j++) { - let value = enums[j]; - suggestions.push({ - label: value, - kind: monaco.languages.CompletionItemKind.Enum, - detail: value + ":" + value, - insertText: value, - sortText: ' ~~~' + value - }) - } - } - let attributes = JavaClass.findAttributes(clazz); - if (attributes) { - for (let j = 0; j < attributes.length; j++) { - let attribute = attributes[j]; - suggestions.push({ - label: attribute.name, - kind: monaco.languages.CompletionItemKind.Field, - detail: attribute.comment || (attribute.type + ":" + attribute.name), - insertText: attribute.name, - sortText: ' ~~' + attribute.name - }) - } - } - let methods = JavaClass.findMethods(clazz); - if (methods) { - let mmap = {}; - for (let j = 0; j < methods.length; j++) { - let method = methods[j]; - if (mmap[method.signature]) { - continue; - } - mmap[method.signature] = true; - let document = []; - method.comment && document.push(method.comment) - for (let j = (method.extension ? 1 : 0); j < method.parameters.length; j++) { - let param = method.parameters[j]; - document.push(`\`${param.name}\`:${(param.comment || param.type)}`) - } - document.push(`返回类型:\`${method.returnType}\``) - suggestions.push({ - sortText: method.sortText || method.fullName, - label: method.fullName, - kind: monaco.languages.CompletionItemKind.Method, - detail: `${simpleName}.${method.fullName}: ${method.returnType}`, - documentation: { value: document.join('\r\n\r\n\r\n') }, - insertText: method.insertText, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - } - } -} - -async function completionScript(suggestions, input) { - try { - let tokens = tokenizer(input); - let tokenLen = tokens.length; - if (tokenLen === 0) { - await completionFunction(suggestions, input) - return; - } - let parser = new Parser(new TokenStream(tokens)); - const { best, env } = await parser.parseBest(input.length - 1, env); - if(input.endsWith(".")){ - await completionMethod(await best.getJavaType(env), suggestions) - } else if(best) { - if (best instanceof MemberAccess || best instanceof MethodCall ) { - await completionMethod(await best.target.getJavaType(env), suggestions) - } else if(best instanceof NewStatement && best.identifier instanceof VariableAccess){ - await completionFunction(suggestions, input, env, best.identifier, true) - } else { - await completionFunction(suggestions, input, env, best) - } - } else { - await completionFunction(suggestions, input, env) - } - return suggestions; - } catch (e) { - // console.error(e) - } -} - -const quickSuggestions = [ - ['bre', 'break;', '跳出循环'], - ['con', 'continue;', '继续循环'], - ['imp', 'import $1', '导入'], - ['if', 'if (${1:condition}){\r\n\t$2\r\n}', '判断'], - ['ife', 'if (${1:condition}) {\r\n\t$2\r\n} else { \r\n\t$3\r\n}', '判断'], - ['for', 'for (item in ${1:collection}) {\r\n\t$2\r\n}', '循环集合'], - ['exit', 'exit ${1:code}, ${2:message};', '退出'], - ['logi', 'log.info($1);', 'info日志'], - ['logd', 'log.debug($1);', 'debug日志'], - ['loge', 'log.error($1);', 'error日志'], - ['logw', 'log.warn($1);', 'warn日志'], - ['ass', 'assert ${1:condition} : ${2:code}, ${3:message}', '校验参数'] -] - -const CompletionItemProvider = { - provideCompletionItems: async function (model, position) { - let value = model.getValueInRange({ - startLineNumber: 1, - startColumn: 1, - endLineNumber: position.lineNumber, - endColumn: position.column - }); - let line = model.getValueInRange({ - startLineNumber: position.lineNumber, - startColumn: 1, - endLineNumber: position.lineNumber, - endColumn: position.column - }); - let word = model.getWordUntilPosition(position); - let range = { - startLineNumber: position.lineNumber, - endLineNumber: position.lineNumber, - startColumn: word.startColumn, - endColumn: word.endColumn - } - let incomplete = false; - let suggestions = quickSuggestions.map(item => { - return { - label: item[0], - kind: monaco.languages.CompletionItemKind.Struct, - detail: item[2] || item[1], - insertText: item[1], - filterText: item[0], - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - range - } - }); - if (line.length > 1 && (line.trim().indexOf('import')) === 0) { - completionImport(suggestions, position, line, line.indexOf('import') + 6) - incomplete = true; - } else if (line.endsWith("::")) { - suggestions = ['int', 'long', 'date', 'string', 'short', 'byte', 'float', 'double', 'json','stringify', 'sql'].map(it => { - return { - label: it, - detail: `转换为${it === 'stringify' ? 'json字符串': it === 'sql' ? 'sql参数类型': it}`, - insertText: it, - kind: monaco.languages.CompletionItemKind.TypeParameter, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - } - }) - } else if (value.length > 1) { - await completionScript(suggestions, value) - } else { - await completionFunction(suggestions, value, { - ...RequestParameter.environmentFunction(), - ...JavaClass.getAutoImportClass(), - ...JavaClass.getAutoImportModule() - }) - } - return { suggestions, incomplete } - }, - triggerCharacters: ['.', ':'] -}; -export default CompletionItemProvider diff --git a/magic-editor/src/console/src/scripts/editor/dark-theme.js b/magic-editor/src/console/src/scripts/editor/dark-theme.js deleted file mode 100644 index 6ee35434..00000000 --- a/magic-editor/src/console/src/scripts/editor/dark-theme.js +++ /dev/null @@ -1,113 +0,0 @@ -export default { - editor: { - base: 'vs-dark', - rules: [ - {foreground: 'A9B7C6'}, - {token: 'keywords', foreground: 'CC7832', fontStyle: 'bold'}, - {token: 'keyword', foreground: 'CC7832', fontStyle: 'bold'}, - {token: 'number', foreground: '6897BB'}, - {token: 'string', foreground: '6A8759', fontStyle: 'bold'}, - {token: 'string.sql', foreground: '6A8759'}, - {token: 'tag.sql', foreground: 'E8BF6A'}, - {token: 'attribute.name.sql', foreground: 'BABABA'}, - {token: 'attribute.value.sql', foreground: '6A8759'}, - {token: 'predefined.sql', foreground: 'A9B7C6', fontStyle: 'italic'}, - {token: 'predefined.magicscript', foreground: 'A9B7C6', fontStyle: 'italic'}, - {token: 'key', foreground: '9876AA'}, - {token: 'string.key.json', foreground: '9876AA'}, - {token: 'string.value.json', foreground: '6A8759'}, - {token: 'keyword.json', foreground: '6897BB'}, - {token: 'operator.sql', foreground: 'CC7832', fontStyle: 'bold'}, - {token: 'string.invalid', foreground: '008000', background: 'FFCCCC'}, - {token: 'string.escape.invalid', foreground: '008000', background: 'FFCCCC'}, - {token: 'string.escape', foreground: '000080', fontStyle: 'bold'}, - {token: 'comment', foreground: '808080', fontStyle: 'italic'}, - {token: 'comment.doc', foreground: '629755', fontStyle: 'italic'}, - {token: 'comment.todo', foreground: 'A8C023', fontStyle: 'italic'}, - {token: 'string.escape', foreground: 'CC7832'} - ], - colors: { - 'editor.background': '#2B2B2B', - 'editorLineNumber.foreground': '#999999', //行号的颜色 - 'editorGutter.background': '#313335', //行号背景色 - 'editor.lineHighlightBackground': '#323232', //光标所在行的颜色 - 'dropdown.background': '#3C3F41', //右键菜单 - 'dropdown.foreground': '#BBBBBB', //右键菜单文字颜色 - 'list.activeSelectionBackground': '#4B6EAF', //右键菜单悬浮背景色 - 'list.activeSelectionForeground': '#FFFFFF', //右键菜单悬浮文字颜色 - } - }, - styles: { - 'background': '#3C3F41', - 'toolbox-background': '#3C3F41', - 'middle-background': '#313335', - 'middle-border': '#323232', - 'selected-background': '#323232', - 'hover-background': '#353739', - 'selected-color': '#fff', - 'color': '#bbb', - 'icon-color': '#AFB1B3', - 'header-title-color': '#bbb', - 'header-version-color': '#999', - 'header-default-color': '#AFB1B3', - 'button-hover-background': '#2D2F30', - 'border-color': '#323232', - 'toolbox-list-label-color': '#bbb', - 'toolbox-list-span-color': '#787878', - 'toolbox-border-color': '#323232', - 'toolbox-list-hover-background': '#0D293E', - 'toolbox-border-right-color': '#555555', - 'footer-border-color': '#323232', - 'tab-bar-border-color': '#323232', - 'input-border-color': '#646464', - 'input-border-foucs-color': '#3D6185', - 'input-background': '#45494A', - 'empty-background': '#282828', - 'empty-key-color': '#489DF6', - 'empty-color': '#A0A0A0', - 'dialog-border-color': '#282828', - 'dialog-shadow-color': '#151515', - 'dialog-button-hover-background': '#365880', - 'dialog-button-hover-border-color': '#43688C', - 'dialog-button-background': '#4C5052', - 'dialog-button-border': '#5E6060', - 'table-col-border-color': '#333638', - 'table-row-border-color': '#333638', - 'table-hover-background': '#4B6EAF', - 'debug-line-background': '#2D6099', - 'breakpoints-background': '#C75450', - 'breakpoint-line-background': '#3a2323', - 'table-even-background': '#414547', - 'button-disabled-background': '#5A5A5A', - 'select-background': '#3C3F41', - 'select-hover-background': '#3C3F41', - 'select-option-background': '#3C3F41', - 'select-option-hover-background': '#4B6EAF', - 'select-inputable-background': '#45494a', - 'select-inputable-border': 'transparent', - 'toolbox-list-header-icon-color': '#AFB1B3', - 'checkbox-background': '#43494A', - 'checkbox-border': '#6B6B6B', - 'checkbox-text-color': '#bbb', - 'checkbox-selected-background': '#43494A', - 'checkbox-selected-border': '#6B6B6B', - 'todo-color': '#A8C023', - 'log-error-color': '#CC666E', - 'text-string-color': '#6A8759', - 'text-number-color': '#6897BB', - 'text-boolean-color': '#CC7832', - 'text-property-color': '#9876aa', - 'text-key-color': '#9876aa', - 'suggest-hover-background': '#113A5C', - 'suggest-hover-color': '#fff', - 'statusbar-em-color': '#68dd9a', - 'run-log-background': '#2b2b2b', - 'log-level-info': '#ABC023', - 'log-level-error': '#CC666E', - 'log-level-debug': '#299999', - 'log-level-warn': 'unset', - 'log-level-trace': '#5394EC', - 'log-color-cyan': '#009191', - 'log-color-link': '#287BDE' - } -}; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/default-theme.js b/magic-editor/src/console/src/scripts/editor/default-theme.js deleted file mode 100644 index 697a4894..00000000 --- a/magic-editor/src/console/src/scripts/editor/default-theme.js +++ /dev/null @@ -1,40 +0,0 @@ -export default { - editor: { - base: 'vs', - rules: [ - {background: '#ffffff'}, - {token: 'keywords', foreground: '000080', fontStyle: 'bold'}, - {token: 'number', foreground: '0000FF'}, - {token: 'keyword', foreground: '000080', fontStyle: 'bold'}, - {token: 'string.sql', foreground: '008000'}, - {token: 'tag.sql', foreground: '0033B3'}, - {token: 'attribute.name.sql', foreground: '174AD4'}, - {token: 'attribute.value.sql', foreground: '067D17'}, - {token: 'predefined', foreground: '000000', fontStyle: 'italic'}, - {token: 'operator.sql', foreground: '000080', fontStyle: 'bold'}, - {token: 'key', foreground: '660E7A'}, - {token: 'string.key.json', foreground: '660E7A'}, - {token: 'string.value.json', foreground: '008000'}, - {token: 'keyword.json', foreground: '0000FF'}, - {token: 'string', foreground: '008000', fontStyle: 'bold'}, - {token: 'string.invalid', foreground: '008000', background: 'FFCCCC'}, - {token: 'string.escape.invalid', foreground: '008000', background: 'FFCCCC'}, - {token: 'string.escape', foreground: '000080', fontStyle: 'bold'}, - {token: 'comment', foreground: '808080', fontStyle: 'italic'}, - {token: 'comment.doc', foreground: '808080', fontStyle: 'italic'}, - {token: 'comment.todo', foreground: '008DDE', fontStyle: 'italic'}, - {token: 'string.escape', foreground: '000080'} - ], - colors: { - 'editor.foreground': '#000000', - 'editor.background': '#ffffff', - 'editorLineNumber.foreground': '#999999', //行号的颜色 - 'editorGutter.background': '#f0f0f0', //行号背景色 - 'editor.lineHighlightBackground': '#FFFAE3', //光标所在行的颜色 - 'dropdown.background': '#F2F2F2', //右键菜单 - 'dropdown.foreground': '#000000', //右键菜单文字颜色 - 'list.activeSelectionBackground': '#1A7DC4', //右键菜单悬浮背景色 - 'list.activeSelectionForeground': '#ffffff', //右键菜单悬浮文字颜色 - } - } -}; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/folding.js b/magic-editor/src/console/src/scripts/editor/folding.js deleted file mode 100644 index a89fad34..00000000 --- a/magic-editor/src/console/src/scripts/editor/folding.js +++ /dev/null @@ -1,155 +0,0 @@ -import * as monaco from 'monaco-editor' -let computeIndentLevel = function (line, tabSize) { - var indent = 0; - var i = 0; - var len = line.length; - while (i < len) { - var chCode = line.charCodeAt(i); - if (chCode === 32 /* Space */) { - indent++; - } else if (chCode === 9 /* Tab */) { - indent = indent - indent % tabSize + tabSize; - } else { - break; - } - i++; - } - if (i === len) { - return -1; // line only consists of whitespace - } - return indent; -} - -class RangesCollector { - constructor(foldingRangesLimit) { - this._startIndexes = []; - this._endIndexes = []; - this._indentOccurrences = []; - this._length = 0; - this._foldingRangesLimit = foldingRangesLimit; - } - - insertFirst(startLineNumber, endLineNumber, indent) { - if (startLineNumber > 0xFFFFFF || endLineNumber > 0xFFFFFF) { - return; - } - var index = this._length; - this._startIndexes[index] = startLineNumber; - this._endIndexes[index] = endLineNumber; - this._length++; - if (indent < 1000) { - this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1; - } - } - - toIndentRanges(model) { - var values = []; - if (this._length <= this._foldingRangesLimit) { - // reverse and create arrays of the exact length - var startIndexes = new Uint32Array(this._length); - var endIndexes = new Uint32Array(this._length); - for (var i = this._length - 1, k = 0; i >= 0; i--, k++) { - values.push({ - start: this._startIndexes[i], - end: this._endIndexes[i] - }); - } - } else { - var entries = 0; - var maxIndent = this._indentOccurrences.length; - for (var i = 0; i < this._indentOccurrences.length; i++) { - var n = this._indentOccurrences[i]; - if (n) { - if (n + entries > this._foldingRangesLimit) { - maxIndent = i; - break; - } - entries += n; - } - } - var tabSize = model.getOptions().tabSize; - // reverse and create arrays of the exact length - var startIndexes = new Uint32Array(this._foldingRangesLimit); - var endIndexes = new Uint32Array(this._foldingRangesLimit); - for (var i = this._length - 1, k = 0; i >= 0; i--) { - var startIndex = this._startIndexes[i]; - var lineContent = model.getLineContent(startIndex); - var indent = computeIndentLevel(lineContent, tabSize); - if (indent < maxIndent || (indent === maxIndent && entries++ < this._foldingRangesLimit)) { - values.push({ - start: startIndex, - end: this._endIndexes[i] - }); - k++; - } - } - } - return values; - } -} - -const FoldingRangeProvider = { - provideFoldingRanges: (model, context) => { - let tabSize = model.getOptions().tabSize; - let result = new RangesCollector(5000); - let previousRegions = []; - let line = model.getLineCount() + 1; - let endImport = -1; - let startImport = -1; - let imports = []; - previousRegions.push({indent: -1, endAbove: line, line: line}); - for (let line_1 = model.getLineCount(); line_1 > 0; line_1--) { - let lineContent = model.getLineContent(line_1); - if (lineContent.startsWith('import') || lineContent.trim().startsWith('import')) { - if (endImport == -1) { - endImport = line_1; - } else { - startImport = line_1 - } - } else { - if (startImport > -1 && endImport > -1) { - imports.push({ - start: startImport, - end: endImport, - kind: monaco.languages.FoldingRangeKind.Imports - }); - } - startImport = -1; - endImport = -1; - } - let indent = computeIndentLevel(lineContent, tabSize); - let previous = previousRegions[previousRegions.length - 1]; - if (indent === -1) { - continue; // only whitespace - } - if (previous.indent > indent) { - // discard all regions with larger indent - do { - previousRegions.pop(); - previous = previousRegions[previousRegions.length - 1]; - } while (previous.indent > indent); - // new folding range - var endLineNumber = previous.endAbove - 1; - if (endLineNumber - line_1 >= 1) { // needs at east size 1 - result.insertFirst(line_1, endLineNumber, indent); - } - } - if (previous.indent === indent) { - previous.endAbove = line_1; - } else { // previous.indent < indent - // new region with a bigger indent - previousRegions.push({indent: indent, endAbove: line_1, line: line_1}); - } - } - if (startImport > -1 && endImport > -1) { - imports.push({ - start: startImport, - end: endImport, - kind: monaco.languages.FoldingRangeKind.Imports - }); - } - return imports.concat(result.toIndentRanges(model)); - } -} - -export default FoldingRangeProvider; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/high-light.js b/magic-editor/src/console/src/scripts/editor/high-light.js deleted file mode 100644 index 5686bcf8..00000000 --- a/magic-editor/src/console/src/scripts/editor/high-light.js +++ /dev/null @@ -1,121 +0,0 @@ -export const HighLightOptions = { - escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, - builtinFunctions: [], - digits: /[0-9_]+/, - binarydigits: /[0-1_]+/, - hexdigits: /[[0-9a-fA-F_]+/, - regexpctl: /[(){}\[\]\$\^|\-*+?\.]/, - regexpesc: /\\(?:[bBdDfnrstvwWn0\\\/]|@regexpctl|c[A-Z]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/, - tokenizer: { - root: [ - [/\s+/, 'white'], - [/```$/, { token: 'string', next: '@codeblock' }], - [/[a-zA-Z_$][\w$]*[\s]?/, { - cases: { - '@builtinFunctions': 'predefined', - "~(new|var|if|else|for|in|return|import|break|continue|as|null|true|false|try|catch|finally|async|while|exit|asc|desc|ASC|DESC|assert|let|const|throw)[\\s]?": {token: "keywords"}, - "~(select|from|left|join|on|and|or|order|by|where|group|having|limit|offset|SELECT|FROM|LEFT|JOIN|ON|AND|OR|ORDER|BY|WHERE|GROUP|HAVING|LIMIT|OFFSET)[\\s]{1}": {token: "keywords"}, - "@default": "identifier" - } - }], - [/::[a-zA-Z]+/, 'keywords'], - [/[{}()[\]]/, '@brackets'], - [/(@digits)\.(@digits)/, 'number.float'], - [/0[xX](@hexdigits)n?/, 'number.hex'], - [/0[bB](@binarydigits)n?/, 'number.binary'], - [/(@digits)[lLbBsSdDfFmM]?/, 'number'], - [/\/\*\**/, 'comment', '@comment'], - [/\/\//, 'comment', '@commentTodo'], - [ - /\/(?=([^\\\/]|\\.)+\/([gimsuy]*)(\s*)(\.|;|,|\)|\]|\}|$))/, - {token: 'regexp', bracket: '@open', next: '@regexp'} - ], - [/[;,.]/, 'delimiter'], - [/"""/, {token: 'string', next: '@string_multi_embedded', nextEmbedded: 'mybatis'}], - [/"([^"\\]|\\.)*$/, 'string.invalid'], - [/'([^'\\]|\\.)*$/, 'string.invalid'], - [/"/, 'string', '@string_double'], - [/'/, 'string', '@string_single'], - [/`/, 'string', '@string_backtick'] - ], - comment: [ - [/\*\//, 'comment', '@popall'], - [/\S((TODO)|(todo)|(fixme)|(FIXME))\s+/, 'comment'], - [/((TODO)|(todo)|(fixme)|(FIXME))\s+[^(*/)]+/, 'comment.todo'], - [/\S/, 'comment'], - ], - commentTodo: [ - [/^/,'', '@popall'], - [/\S((TODO)|(todo)|(fixme)|(FIXME))\s+/, 'comment'], - [/((TODO)|(todo)|(fixme)|(FIXME))[ \t]+[^\n]+/, 'comment.todo','@popall'], - [/\S/, 'comment'], - ], - regexp: [ - [ - /(\{)(\d+(?:,\d*)?)(\})/, - ['regexp.escape.control', 'regexp.escape.control', 'regexp.escape.control'] - ], - [ - /(\[)(\^?)(?=(?:[^\]\\\/]|\\.)+)/, - ['regexp.escape.control', {token: 'regexp.escape.control', next: '@regexrange'}] - ], - [/(\()(\?:|\?=|\?!)/, ['regexp.escape.control', 'regexp.escape.control']], - [/[()]/, 'regexp.escape.control'], - [/@regexpctl/, 'regexp.escape.control'], - [/[^\\\/]/, 'regexp'], - [/@regexpesc/, 'regexp.escape'], - [/\\\./, 'regexp.invalid'], - [ - /(\/)([gimsuy]*)/, - [{token: 'regexp', bracket: '@close', next: '@pop'}, 'keyword.other'] - ] - ], - codeblock: [ - [/^```$/, { token: 'string', next: '@pop' }], - [/.*$/, 'variable.source'] - ], - regexrange: [ - [/-/, 'regexp.escape.control'], - [/\^/, 'regexp.invalid'], - [/@regexpesc/, 'regexp.escape'], - [/[^\]]/, 'regexp'], - [ - /\]/, - { - token: 'regexp.escape.control', - next: '@pop', - bracket: '@close' - } - ] - ], - string_multi_embedded: [ - [/[^"]+/, ''], - ['"""', {token: 'string', next: '@pop', nextEmbedded: '@pop'}] - - ], - string_double: [ - [/[^\\"]+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/"/, 'string', '@pop'] - ], - string_single: [ - [/[^\\']+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/'/, 'string', '@pop'] - ], - string_backtick: [ - [/\$\{/, { token: 'delimiter.bracket', next: '@bracketCounting' }], - [/[^\\`$]+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/`/, 'string', '@pop'] - ], - bracketCounting: [ - [/\{/, 'delimiter.bracket', '@bracketCounting'], - [/\}/, 'delimiter.bracket', '@pop'], - { include: 'root' } - ] - } -}; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/hover.js b/magic-editor/src/console/src/scripts/editor/hover.js deleted file mode 100644 index 1ac0e208..00000000 --- a/magic-editor/src/console/src/scripts/editor/hover.js +++ /dev/null @@ -1,152 +0,0 @@ -import tokenizer from '@/scripts/parsing/tokenizer.js' -import { TokenStream } from '../parsing/index.js' -import { - ClassConverter, - FunctionCall, - LinqSelect, - MapOrArrayAccess, - MemberAccess, NewStatement, - Node, - VarDefine, - VariableAccess -} from '../parsing/ast.js' -import { Parser } from '@/scripts/parsing/parser.js' -import { Range } from 'monaco-editor' -import JavaClass from "./java-class" - -const findBestMatch = (node, row, col) => { - let expressions = node.expressions().filter(it => it); - for (let index in expressions) { - let expr = expressions[index]; - if (expr instanceof FunctionCall && expr.target instanceof VariableAccess && expr.getSpan().inPosition(row, col)) { - return expr; - } - let v = findBestMatch(expr, row, col) - if (v instanceof Node) { - return v; - } - } - if (node.getSpan().inPosition(row, col)) { - return node; - } - return null; -} -const generateMethodDocument = (prefix, method, contents) => { - contents.push({value: `${prefix}${method.fullName}`}) - method.comment && contents.push({value: `${method.comment}`}) - method.parameters.forEach((param, pIndex) => { - if (pIndex > 0 || !method.extension) { - contents.push({value: `${param.name}:${(param.comment || param.type)}`}) - } - }) - contents.push({value: `返回类型:\`${method.returnType}\``}) -} - -const generateFunctionCall = (methodName, env, contents, isNew)=>{ - let functions = JavaClass.findFunction().filter(method => method.name === methodName); - if (functions.length > 0) { - generateMethodDocument('', functions[0], contents); - } else { - let value = env[methodName]; - if (value && value.indexOf('@') === 0) { - let functionName = value.substring(1); - let func = JavaClass.getOnlineFunction(functionName); - if (func) { - let parameters = Array.isArray(func.parameter) ? func.parameter : JSON.parse(func.parameter || '[]'); - parameters.forEach(it => it.comment = it.description); - generateMethodDocument('', { - fullName: methodName + " " + func.name, - comment: func.description || '', - parameters, - returnType: func.returnType - }, contents); - } - - } else { - contents.push({value: `${isNew ? '创建对象' : '访问变量'}:${methodName}`}) - contents.push({value: `类型:${value || 'unknow'}`}) - } - } -} -const HoverProvider = { - provideHover: async (model, position) => { - let value = model.getValue() - let tokens = tokenizer(value); - let tokenStream = new TokenStream(tokens); - let parser = new Parser(tokenStream) - let nodes = parser.parse(true); - let input = model.getValueInRange({ - startLineNumber: 1, - startColumn: 1, - endLineNumber: position.lineNumber, - endColumn: position.column - }); - let index = input.length; - for (let i = 0, len = nodes.length; i < len; i++) { - let best = parser.findBestMatch(nodes[i], index) - if(best){ - let env = await parser.processEnv(nodes) - let contents = []; - let line = best.getSpan().getLine(); - if (best instanceof VarDefine) { - let value = env[best.getVarName()]; - contents.push({value: `定义变量:${best.getVarName()}`}) - contents.push({value: `变量类型:${value}`}) - } else if (best instanceof ClassConverter) { - if(best.convert === 'json'){ - contents.push({value: '强制转换为`JSON`类型'}) - }else if(best.convert === 'stringify'){ - contents.push({value: '转换为`JSON`字符串'}) - }else if(best.convert === 'sql'){ - let args = best.args || [] - contents.push({value: `等同于\`new SqlParameterValue(java.sql.Types.${args[0]?.span?.getText()?.toUpperCase()},${best.target.getSpan().getText()})\``}) - }else{ - contents.push({value: `转换为\`${best.convert}\``}) - } - } else if (best instanceof VariableAccess) { - let value = env[best.getVariable()]; - if(value){ - contents.push({value: `访问变量:${best.getVariable()}`}) - contents.push({value: `变量类型:${value || 'unknow'}`}) - }else{ - generateFunctionCall(best.getVariable(), env, contents) - } - } else if (best instanceof MemberAccess) { - let javaType = await best.getTarget().getJavaType(env); - let clazz = await JavaClass.loadClass(javaType); - let memberName = best.member.getText() - JavaClass.findMethods(clazz).filter(method => method.name === memberName) - .forEach(method => generateMethodDocument(`${JavaClass.getSimpleClass(javaType)}.`,method, contents)) - JavaClass.findEnums(clazz).filter(it => it === memberName).forEach(it => { - contents.push({value: `访问枚举:\`${javaType}.${memberName}\``}) - }) - JavaClass.findAttributes(clazz).filter(attr => attr.name === memberName).forEach(it => { - contents.push({value: `访问属性:\`${javaType}.${memberName}\``}) - it.comment && contents.push({value: `${it.comment}`}) - contents.push({value: `属性类型:` + `\`${it.type}\``}) - }) - line = best.member.getLine(); - } else if (best instanceof FunctionCall) { - let target = best.target; - generateFunctionCall(target.variable, env, contents) - } else if (best instanceof NewStatement) { - let target = best.identifier; - if(target instanceof VariableAccess){ - generateFunctionCall(target, env, contents, true) - } - } else if (best instanceof MapOrArrayAccess) { - contents.push({value: `访问Map或数组`}) - } else if (best instanceof LinqSelect) { - contents.push({value: `linq查询`}) - } else { - return; - } - return { - range: new Range(line.lineNumber, line.startCol, line.endLineNumber, line.endCol + 1), - contents - }; - } - } - } -} -export default HoverProvider \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/java-class.js b/magic-editor/src/console/src/scripts/editor/java-class.js deleted file mode 100644 index 85f4e5e9..00000000 --- a/magic-editor/src/console/src/scripts/editor/java-class.js +++ /dev/null @@ -1,304 +0,0 @@ -import request from '@/api/request.js' -import contants from '@/scripts/contants.js' -import {HighLightOptions} from '@/scripts/editor/high-light.js' -import * as monaco from "monaco-editor"; - -let scriptClass = {} -let extensions = {} -let importClass = [] -let functions = [] -let autoImportModule; -let autoImportClass; - -const getWrapperClass = (target) => { - if (target === 'int' || target === 'java.lang.Integer') { - return 'java.lang.Integer'; - } - if (target === 'string' || target === 'java.lang.String') { - return 'java.lang.String'; - } - if (target === 'double' || target === 'java.lang.Double') { - return 'java.lang.Double'; - } - if (target === 'float' || target === 'java.lang.Float') { - return 'java.lang.Float'; - } - if (target === 'byte' || target === 'java.lang.Byte') { - return 'java.lang.Byte'; - } - if (target === 'short' || target === 'java.lang.Short') { - return 'java.lang.Short'; - } - if (target === 'long' || target === 'java.lang.Long') { - return 'java.lang.Long'; - } - if (target.indexOf('[]') > -1) { - return '[Ljava.lang.Object;'; - } - return target || 'java.lang.Object'; -} -const getSimpleClass = (target) => { - let index = target.lastIndexOf('.') - if (index > -1) { - return target.substring(index + 1); - } - return target; -} -const matchTypes = (parameters, args, extension) => { - if (parameters.length > 0 && parameters[parameters.length - 1].varArgs) { - return extension ? parameters.length - 1 <= args.length : parameters.length <= args.length; - } else { - return extension ? parameters.length - 1 === args.length : parameters.length === args.length; - } -} -const initClasses = function () { - return new Promise((resolve, reject) => { - request.send('classes').success(data => { - scriptClass = data.classes || {} - extensions = data.extensions || {} - functions = data.functions || [] - HighLightOptions.builtinFunctions = functions.map(it => it.name); - monaco.languages.setMonarchTokensProvider('magicscript', HighLightOptions); - resolve() - }).exception(res => { - reject() - }).error(res => { - reject() - }) - }) -} -const initImportClass = () => { - return new Promise((resolve, reject) => { - request.execute({ - url: 'classes.txt', - responseType: 'text' - }).then(e => { - const array = []; - e.data.split('\n').forEach(item => { - const tmp = item.split(':') - if (tmp.length === 1) { - array.push(tmp[0]) - } else { - array.push(...tmp[1].split(',').map(it => tmp[0] + "." + it)) - } - }) - importClass = array - resolve() - }).catch(res => { - reject() - }) - }) -} - -const padding = (num, n) => Array(n > (num + '').length ? (n - ('' + num).length - 1) : 0).join(0) + num; - -const findEnums = (clazz) => { - let enums = [] - if (clazz) { - enums = clazz.enums || []; - if (clazz.superClass) { - enums = enums.concat(findEnums(clazz.superClass)); - } - } - return enums; -} -const processMethod = (method, begin, sort) => { - method.insertText = method.name; - if (method.parameters.length > begin) { - let params = []; - let params2 = []; - for (let j = begin; j < method.parameters.length; j++) { - params.push('${' + (j + 1 - begin) + ':' + method.parameters[j].name + '}'); - if (method.parameters[j].varArgs) { - params2.push(getSimpleClass(method.parameters[j].type).replace('[]', '') + " ... " + method.parameters[j].name); - } else { - params2.push(getSimpleClass(method.parameters[j].type) + " " + method.parameters[j].name); - } - } - // if (!method.comment) { - // method.comment = getSimpleClass(method.returnType) + '.' + method.name + '(' + params2.join(', ') + ')'; - // } - method.sortText = padding(sort, 10) + method.name; - method.fullName = method.name + '(' + params2.join(', ') + ')'; - method.insertText += '(' + params.join(',') + ')'; - method.signature = method.name + params2.join(','); - } else { - method.sortText = padding(sort, 10) + method.name; - method.insertText += '()'; - method.fullName = method.name + '()'; - // if (!method.comment) { - // method.comment = getSimpleClass(method.returnType) + '.' + method.name + '()'; - // } - method.signature = method.name; - } - return method; -} -let extensionAttribute = {}; -const setExtensionAttribute = (clazz, value) => { - extensionAttribute[clazz] = value; -} -const findAttributes = (clazz) => { - let attributes = []; - if (clazz) { - attributes = clazz.attributes || []; - if (clazz.superClass) { - attributes = attributes.concat(findAttributes(clazz.superClass)); - } - if (clazz.interfaces && clazz.interfaces.length > 0) { - for (let i = 0, len = clazz.interfaces.length; i < len; i++) { - attributes = attributes.concat(findAttributes(clazz.interfaces[i])); - } - } - if (extensionAttribute[clazz.className]) { - attributes = attributes.concat(extensionAttribute[clazz.className]) - } - } - return attributes; -} -const findMethods = (clazz, sort) => { - sort = sort || 0; - let methods = []; - let _findMethod = (target, begin, sort) => { - if (target && target.methods) { - for (let i = 0, len = target.methods.length; i < len; i++) { - let method = target.methods[i]; - method = processMethod(method, begin, sort); - method.extension = begin === 1; - methods.push(method); - } - } - } - if (typeof clazz === 'string') { - clazz = scriptClass[clazz]; - } - if (clazz) { - _findMethod(clazz, 0, sort); - if (clazz.superClass) { - methods = methods.concat(findMethods(clazz.superClass, sort + 1)); - } - if (clazz.interfaces && clazz.interfaces.length > 0) { - for (let i = 0, len = clazz.interfaces.length; i < len; i++) { - methods = methods.concat(findMethods(clazz.interfaces[i], sort + 100)); - } - } - clazz = extensions[clazz.className]; - if (clazz) { - _findMethod(clazz, 1, sort + 10000); - } - } - return methods; -} - -const getExtension = (clazz) => { - return extensions[clazz] -} -const findClass = (className) => { - if (!className) { - throw new Error('className is required'); - } - let value = scriptClass[className] - if (!value) { - let index = importClass.findIndex(it => it === className) - value = importClass[index] - } - return value -} - -async function loadClass(className) { - let val = scriptClass[className]; - if (!val) { - try { - let res = await request.execute({url: '/class', data: {className}}) - let clazzs = res.data.data; - clazzs.forEach(it => { - scriptClass[it.className] = it; - }) - val = scriptClass[className] - } catch (e) { - - } - } else { - val = scriptClass[val.className] || val // fix attribute - } - return val; -} - -const findFunction = () => { - return functions.map(method => processMethod(method, 0, 1)); -} - -const initAutoImport = () => { - if (!autoImportModule && contants.config) { - let config = contants.config; - if (config.autoImportModuleList) { - autoImportModule = {}; - config.autoImportModuleList.forEach(it => { - autoImportModule[it] = it; - }) - } - let importPackages = ['java.util.', 'java.lang.'].concat((config.autoImportPackage || '').replace(/\\s/g, '').replace(/\*/g, '').split(',')); - autoImportClass = {}; - importClass.forEach(className => { - importPackages.forEach(packageName => { - if (className.indexOf(packageName) === 0 && className.indexOf(".", packageName.length) === -1) { - autoImportClass[className.substring(className.lastIndexOf('.') + 1)] = className; - } - }) - }) - } -} -const getAutoImportModule = () => { - initAutoImport(); - return autoImportModule || {} -} -const getAutoImportClass = () => { - initAutoImport(); - return autoImportClass || {} -} -const getImportClass = () => importClass; -let onlineFunctionFinder; -const setupOnlineFunction = (loader) => { - onlineFunctionFinder = loader; -} -const getOnlineFunction = (path) => { - return onlineFunctionFinder && onlineFunctionFinder(path); -} -const getDefineModules = () => Object.keys(scriptClass).filter(it => scriptClass[it].module) -let apiFinder; -const setApiFinder = (finder) => { - apiFinder = finder; -} -let functionFinder; -const setFunctionFinder = (finder) => { - functionFinder = finder; -} -const getApiFinder = () => apiFinder -const getFunctionFinder = () => functionFinder -const exportValue = { - findEnums, - findAttributes, - findMethods, - findFunction, - loadClass, - findClass, - initClasses, - initImportClass, - getWrapperClass, - matchTypes, - getAutoImportModule, - getAutoImportClass, - getExtension, - getImportClass, - getOnlineFunction, - setupOnlineFunction, - setExtensionAttribute, - getSimpleClass, - getDefineModules, - setApiFinder, - setFunctionFinder, - getApiFinder, - getFunctionFinder, - - -} -export default exportValue; diff --git a/magic-editor/src/console/src/scripts/editor/magic-script.js b/magic-editor/src/console/src/scripts/editor/magic-script.js deleted file mode 100644 index 930b7433..00000000 --- a/magic-editor/src/console/src/scripts/editor/magic-script.js +++ /dev/null @@ -1,97 +0,0 @@ -import * as monaco from 'monaco-editor'; -import {HighLightOptions} from './high-light.js'; -import CompletionItemProvider from './completion.js'; -import FoldingRangeProvider from './folding.js'; -import SignatureHelpProvider from './signature.js'; -import HoverProvider from './hover.js'; -import {initMybatis} from './mybatis.js' -const Beautifier = require('../beautifier/javascript/beautifier').Beautifier - -export const initializeMagicScript = () => { - initMybatis(); - const language = 'magicscript'; - // 注册语言 - monaco.languages.register({id: language}); - // 设置语言选项 - monaco.languages.setLanguageConfiguration(language, { - wordPattern: /(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+)/g, - brackets: [ - ['{', '}'], - ['[', ']'], - ['(', ')'], - ], - onEnterRules: [ - { - // e.g. /** | */ - beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/, - afterText: /^\s*\*\/$/, - action: { - indentAction: monaco.languages.IndentAction.IndentOutdent, - appendText: ' * ' - } - }, - { - // e.g. /** ...| - beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/, - action: { - indentAction: monaco.languages.IndentAction.None, - appendText: ' * ' - } - }, - { - // e.g. * ...| - beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/, - action: { - indentAction: monaco.languages.IndentAction.None, - appendText: '* ' - } - }, - { - // e.g. */| - beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/, - action: { - indentAction: monaco.languages.IndentAction.None, - removeText: 1 - } - } - ], - comments: { - lineComment: '//', - blockComment: ['/*', '*/'], - }, - operators: ['<=', '>=', '==', '!=', '+', '-', '*', '/', '%', '&', '|', '!', '&&', '||', '?', ':', '++', '--', '+=', '-=', '*=', '/='], - autoClosingPairs: [ - {open: '{', close: '}'}, - {open: '[', close: ']'}, - {open: '(', close: ')'}, - {open: '"""', close: '"""', notIn: ['string.multi']}, - {open: '', close: ''}, - {open: ''}, - {open: '', close: ''}, - {open: ''}, - {open: '"', close: '"', notIn: ['string']}, - {open: '\'', close: '\'', notIn: ['string']}, - {open: '/**', close: ' */', notIn: ['string'] } - ], - }) - - // 设置高亮 - monaco.languages.setMonarchTokensProvider(language, HighLightOptions); - // 设置代码提示 - monaco.languages.registerCompletionItemProvider(language, CompletionItemProvider); - // 设置折叠 - monaco.languages.registerFoldingRangeProvider(language, FoldingRangeProvider); - // 设置参数提示 - monaco.languages.registerSignatureHelpProvider(language, SignatureHelpProvider); - // 设置悬浮提示 - monaco.languages.registerHoverProvider(language, HoverProvider); - // 设置代码格式化 - monaco.languages.registerDocumentFormattingEditProvider(language, { - provideDocumentFormattingEdits(model, options, token) { - return [{ - text: new Beautifier(model.getValue()).beautify(), - range: model.getFullModelRange() - }] - } - }) -} diff --git a/magic-editor/src/console/src/scripts/editor/mybatis.js b/magic-editor/src/console/src/scripts/editor/mybatis.js deleted file mode 100644 index 11506b9d..00000000 --- a/magic-editor/src/console/src/scripts/editor/mybatis.js +++ /dev/null @@ -1,1420 +0,0 @@ -import * as monaco from 'monaco-editor' -export const initMybatis = () => { - const language = 'mybatis' - monaco.languages.register({ id: language}) - monaco.languages.setLanguageConfiguration(language, { - comments: { - lineComment: '--', - blockComment: ['/*', '*/'] - }, - brackets: [ - ['{', '}'], - ['[', ']'], - ['(', ')'] - ], - autoClosingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '"', close: '"' }, - { open: "'", close: "'" } - ], - surroundingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '"', close: '"' }, - { open: "'", close: "'" } - ] - }) - // 设置高亮 - monaco.languages.setMonarchTokensProvider(language, { - defaultToken: '', - tokenPostfix: '.sql', - ignoreCase: true, - brackets: [ - { open: '[', close: ']', token: 'delimiter.square' }, - { open: '(', close: ')', token: 'delimiter.parenthesis' } - ], - keywords: [ - 'ABORT_AFTER_WAIT', - 'ABSENT', - 'ABSOLUTE', - 'ACCENT_SENSITIVITY', - 'ACTION', - 'ACTIVATION', - 'ACTIVE', - 'ADD', - 'ADDRESS', - 'ADMIN', - 'AES', - 'AES_128', - 'AES_192', - 'AES_256', - 'AFFINITY', - 'AFTER', - 'AGGREGATE', - 'ALGORITHM', - 'ALL_CONSTRAINTS', - 'ALL_ERRORMSGS', - 'ALL_INDEXES', - 'ALL_LEVELS', - 'ALL_SPARSE_COLUMNS', - 'ALLOW_CONNECTIONS', - 'ALLOW_MULTIPLE_EVENT_LOSS', - 'ALLOW_PAGE_LOCKS', - 'ALLOW_ROW_LOCKS', - 'ALLOW_SINGLE_EVENT_LOSS', - 'ALLOW_SNAPSHOT_ISOLATION', - 'ALLOWED', - 'ALTER', - 'ANONYMOUS', - 'ANSI_DEFAULTS', - 'ANSI_NULL_DEFAULT', - 'ANSI_NULL_DFLT_OFF', - 'ANSI_NULL_DFLT_ON', - 'ANSI_NULLS', - 'ANSI_PADDING', - 'ANSI_WARNINGS', - 'APPEND', - 'APPLICATION', - 'APPLICATION_LOG', - 'ARITHABORT', - 'ARITHIGNORE', - 'AS', - 'ASC', - 'ASSEMBLY', - 'ASYMMETRIC', - 'ASYNCHRONOUS_COMMIT', - 'AT', - 'ATOMIC', - 'ATTACH', - 'ATTACH_REBUILD_LOG', - 'AUDIT', - 'AUDIT_GUID', - 'AUTHENTICATION', - 'AUTHORIZATION', - 'AUTO', - 'AUTO_CLEANUP', - 'AUTO_CLOSE', - 'AUTO_CREATE_STATISTICS', - 'AUTO_SHRINK', - 'AUTO_UPDATE_STATISTICS', - 'AUTO_UPDATE_STATISTICS_ASYNC', - 'AUTOMATED_BACKUP_PREFERENCE', - 'AUTOMATIC', - 'AVAILABILITY', - 'AVAILABILITY_MODE', - 'BACKUP', - 'BACKUP_PRIORITY', - 'BASE64', - 'BATCHSIZE', - 'BEGIN', - 'BEGIN_DIALOG', - 'BIGINT', - 'BINARY', - 'BINDING', - 'BIT', - 'BLOCKERS', - 'BLOCKSIZE', - 'BOUNDING_BOX', - 'BREAK', - 'BROKER', - 'BROKER_INSTANCE', - 'BROWSE', - 'BUCKET_COUNT', - 'BUFFER', - 'BUFFERCOUNT', - 'BULK', - 'BULK_LOGGED', - 'BY', - 'CACHE', - 'CALL', - 'CALLED', - 'CALLER', - 'CAP_CPU_PERCENT', - 'CASCADE', - 'CASE', - 'CATALOG', - 'CATCH', - 'CELLS_PER_OBJECT', - 'CERTIFICATE', - 'CHANGE_RETENTION', - 'CHANGE_TRACKING', - 'CHANGES', - 'CHAR', - 'CHARACTER', - 'CHECK', - 'CHECK_CONSTRAINTS', - 'CHECK_EXPIRATION', - 'CHECK_POLICY', - 'CHECKALLOC', - 'CHECKCATALOG', - 'CHECKCONSTRAINTS', - 'CHECKDB', - 'CHECKFILEGROUP', - 'CHECKIDENT', - 'CHECKPOINT', - 'CHECKTABLE', - 'CLASSIFIER_FUNCTION', - 'CLEANTABLE', - 'CLEANUP', - 'CLEAR', - 'CLOSE', - 'CLUSTER', - 'CLUSTERED', - 'CODEPAGE', - 'COLLATE', - 'COLLECTION', - 'COLUMN', - 'COLUMN_SET', - 'COLUMNS', - 'COLUMNSTORE', - 'COLUMNSTORE_ARCHIVE', - 'COMMIT', - 'COMMITTED', - 'COMPATIBILITY_LEVEL', - 'COMPRESSION', - 'COMPUTE', - 'CONCAT', - 'CONCAT_NULL_YIELDS_NULL', - 'CONFIGURATION', - 'CONNECT', - 'CONSTRAINT', - 'CONTAINMENT', - 'CONTENT', - 'CONTEXT', - 'CONTINUE', - 'CONTINUE_AFTER_ERROR', - 'CONTRACT', - 'CONTRACT_NAME', - 'CONTROL', - 'CONVERSATION', - 'COOKIE', - 'COPY_ONLY', - 'COUNTER', - 'CPU', - 'CREATE', - 'CREATE_NEW', - 'CREATION_DISPOSITION', - 'CREDENTIAL', - 'CRYPTOGRAPHIC', - 'CUBE', - 'CURRENT', - 'CURRENT_DATE', - 'CURSOR', - 'CURSOR_CLOSE_ON_COMMIT', - 'CURSOR_DEFAULT', - 'CYCLE', - 'DATA', - 'DATA_COMPRESSION', - 'DATA_PURITY', - 'DATABASE', - 'DATABASE_DEFAULT', - 'DATABASE_MIRRORING', - 'DATABASE_SNAPSHOT', - 'DATAFILETYPE', - 'DATE', - 'DATE_CORRELATION_OPTIMIZATION', - 'DATEFIRST', - 'DATEFORMAT', - 'DATETIME', - 'DATETIME2', - 'DATETIMEOFFSET', - 'DAY', - 'DAYOFYEAR', - 'DAYS', - 'DB_CHAINING', - 'DBCC', - 'DBREINDEX', - 'DDL_DATABASE_LEVEL_EVENTS', - 'DEADLOCK_PRIORITY', - 'DEALLOCATE', - 'DEC', - 'DECIMAL', - 'DECLARE', - 'DECRYPTION', - 'DEFAULT', - 'DEFAULT_DATABASE', - 'DEFAULT_FULLTEXT_LANGUAGE', - 'DEFAULT_LANGUAGE', - 'DEFAULT_SCHEMA', - 'DEFINITION', - 'DELAY', - 'DELAYED_DURABILITY', - 'DELETE', - 'DELETED', - 'DENSITY_VECTOR', - 'DENY', - 'DEPENDENTS', - 'DES', - 'DESC', - 'DESCRIPTION', - 'DESX', - 'DHCP', - 'DIAGNOSTICS', - 'DIALOG', - 'DIFFERENTIAL', - 'DIRECTORY_NAME', - 'DISABLE', - 'DISABLE_BROKER', - 'DISABLED', - 'DISK', - 'DISTINCT', - 'DISTRIBUTED', - 'DOCUMENT', - 'DOUBLE', - 'DROP', - 'DROP_EXISTING', - 'DROPCLEANBUFFERS', - 'DUMP', - 'DURABILITY', - 'DYNAMIC', - 'EDITION', - 'ELEMENTS', - 'ELSE', - 'EMERGENCY', - 'EMPTY', - 'EMPTYFILE', - 'ENABLE', - 'ENABLE_BROKER', - 'ENABLED', - 'ENCRYPTION', - 'END', - 'ENDPOINT', - 'ENDPOINT_URL', - 'ERRLVL', - 'ERROR', - 'ERROR_BROKER_CONVERSATIONS', - 'ERRORFILE', - 'ESCAPE', - 'ESTIMATEONLY', - 'EVENT', - 'EVENT_RETENTION_MODE', - 'EXEC', - 'EXECUTABLE', - 'EXECUTE', - 'EXIT', - 'EXPAND', - 'EXPIREDATE', - 'EXPIRY_DATE', - 'EXPLICIT', - 'EXTENDED_LOGICAL_CHECKS', - 'EXTENSION', - 'EXTERNAL', - 'EXTERNAL_ACCESS', - 'FAIL_OPERATION', - 'FAILOVER', - 'FAILOVER_MODE', - 'FAILURE_CONDITION_LEVEL', - 'FALSE', - 'FAN_IN', - 'FAST', - 'FAST_FORWARD', - 'FETCH', - 'FIELDTERMINATOR', - 'FILE', - 'FILEGROUP', - 'FILEGROWTH', - 'FILELISTONLY', - 'FILENAME', - 'FILEPATH', - 'FILESTREAM', - 'FILESTREAM_ON', - 'FILETABLE_COLLATE_FILENAME', - 'FILETABLE_DIRECTORY', - 'FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME', - 'FILETABLE_NAMESPACE', - 'FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME', - 'FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME', - 'FILLFACTOR', - 'FILTERING', - 'FIRE_TRIGGERS', - 'FIRST', - 'FIRSTROW', - 'FLOAT', - 'FMTONLY', - 'FOLLOWING', - 'FOR', - 'FORCE', - 'FORCE_FAILOVER_ALLOW_DATA_LOSS', - 'FORCE_SERVICE_ALLOW_DATA_LOSS', - 'FORCED', - 'FORCEPLAN', - 'FORCESCAN', - 'FORCESEEK', - 'FOREIGN', - 'FORMATFILE', - 'FORMSOF', - 'FORWARD_ONLY', - 'FREE', - 'FREEPROCCACHE', - 'FREESESSIONCACHE', - 'FREESYSTEMCACHE', - 'FROM', - 'FULL', - 'FULLSCAN', - 'FULLTEXT', - 'FUNCTION', - 'GB', - 'GEOGRAPHY_AUTO_GRID', - 'GEOGRAPHY_GRID', - 'GEOMETRY_AUTO_GRID', - 'GEOMETRY_GRID', - 'GET', - 'GLOBAL', - 'GO', - 'GOTO', - 'GOVERNOR', - 'GRANT', - 'GRIDS', - 'GROUP', - 'GROUP_MAX_REQUESTS', - 'HADR', - 'HASH', - 'HASHED', - 'HAVING', - 'HEADERONLY', - 'HEALTH_CHECK_TIMEOUT', - 'HELP', - 'HIERARCHYID', - 'HIGH', - 'HINT', - 'HISTOGRAM', - 'HOLDLOCK', - 'HONOR_BROKER_PRIORITY', - 'HOUR', - 'HOURS', - 'IDENTITY', - 'IDENTITY_INSERT', - 'IDENTITY_VALUE', - 'IDENTITYCOL', - 'IF', - 'IGNORE_CONSTRAINTS', - 'IGNORE_DUP_KEY', - 'IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX', - 'IGNORE_TRIGGERS', - 'IMAGE', - 'IMMEDIATE', - 'IMPERSONATE', - 'IMPLICIT_TRANSACTIONS', - 'IMPORTANCE', - 'INCLUDE', - 'INCREMENT', - 'INCREMENTAL', - 'INDEX', - 'INDEXDEFRAG', - 'INFINITE', - 'INFLECTIONAL', - 'INIT', - 'INITIATOR', - 'INPUT', - 'INPUTBUFFER', - 'INSENSITIVE', - 'INSERT', - 'INSERTED', - 'INSTEAD', - 'INT', - 'INTEGER', - 'INTO', - 'IO', - 'IP', - 'ISABOUT', - 'ISOLATION', - 'JOB', - 'KB', - 'KEEP', - 'KEEP_CDC', - 'KEEP_NULLS', - 'KEEP_REPLICATION', - 'KEEPDEFAULTS', - 'KEEPFIXED', - 'KEEPIDENTITY', - 'KEEPNULLS', - 'KERBEROS', - 'KEY', - 'KEY_SOURCE', - 'KEYS', - 'KEYSET', - 'KILL', - 'KILOBYTES_PER_BATCH', - 'LABELONLY', - 'LANGUAGE', - 'LAST', - 'LASTROW', - 'LEVEL', - 'LEVEL_1', - 'LEVEL_2', - 'LEVEL_3', - 'LEVEL_4', - 'LIFETIME', - 'LIMIT', - 'LINENO', - 'LIST', - 'LISTENER', - 'LISTENER_IP', - 'LISTENER_PORT', - 'LOAD', - 'LOADHISTORY', - 'LOB_COMPACTION', - 'LOCAL', - 'LOCAL_SERVICE_NAME', - 'LOCK_ESCALATION', - 'LOCK_TIMEOUT', - 'LOGIN', - 'LOGSPACE', - 'LOOP', - 'LOW', - 'MANUAL', - 'MARK', - 'MARK_IN_USE_FOR_REMOVAL', - 'MASTER', - 'MAX_CPU_PERCENT', - 'MAX_DISPATCH_LATENCY', - 'MAX_DOP', - 'MAX_DURATION', - 'MAX_EVENT_SIZE', - 'MAX_FILES', - 'MAX_IOPS_PER_VOLUME', - 'MAX_MEMORY', - 'MAX_MEMORY_PERCENT', - 'MAX_QUEUE_READERS', - 'MAX_ROLLOVER_FILES', - 'MAX_SIZE', - 'MAXDOP', - 'MAXERRORS', - 'MAXLENGTH', - 'MAXRECURSION', - 'MAXSIZE', - 'MAXTRANSFERSIZE', - 'MAXVALUE', - 'MB', - 'MEDIADESCRIPTION', - 'MEDIANAME', - 'MEDIAPASSWORD', - 'MEDIUM', - 'MEMBER', - 'MEMORY_OPTIMIZED', - 'MEMORY_OPTIMIZED_DATA', - 'MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT', - 'MEMORY_PARTITION_MODE', - 'MERGE', - 'MESSAGE', - 'MESSAGE_FORWARD_SIZE', - 'MESSAGE_FORWARDING', - 'MICROSECOND', - 'MILLISECOND', - 'MIN_CPU_PERCENT', - 'MIN_IOPS_PER_VOLUME', - 'MIN_MEMORY_PERCENT', - 'MINUTE', - 'MINUTES', - 'MINVALUE', - 'MIRROR', - 'MIRROR_ADDRESS', - 'MODIFY', - 'MONEY', - 'MONTH', - 'MOVE', - 'MULTI_USER', - 'MUST_CHANGE', - 'NAME', - 'NANOSECOND', - 'NATIONAL', - 'NATIVE_COMPILATION', - 'NCHAR', - 'NEGOTIATE', - 'NESTED_TRIGGERS', - 'NEW_ACCOUNT', - 'NEW_BROKER', - 'NEW_PASSWORD', - 'NEWNAME', - 'NEXT', - 'NO', - 'NO_BROWSETABLE', - 'NO_CHECKSUM', - 'NO_COMPRESSION', - 'NO_EVENT_LOSS', - 'NO_INFOMSGS', - 'NO_TRUNCATE', - 'NO_WAIT', - 'NOCHECK', - 'NOCOUNT', - 'NOEXEC', - 'NOEXPAND', - 'NOFORMAT', - 'NOINDEX', - 'NOINIT', - 'NOLOCK', - 'NON', - 'NON_TRANSACTED_ACCESS', - 'NONCLUSTERED', - 'NONE', - 'NORECOMPUTE', - 'NORECOVERY', - 'NORESEED', - 'NORESET', - 'NOREWIND', - 'NORMAL', - 'NOSKIP', - 'NOTIFICATION', - 'NOTRUNCATE', - 'NOUNLOAD', - 'NOWAIT', - 'NTEXT', - 'NTLM', - 'NUMANODE', - 'NUMERIC', - 'NUMERIC_ROUNDABORT', - 'NVARCHAR', - 'OBJECT', - 'OF', - 'OFF', - 'OFFLINE', - 'OFFSET', - 'OFFSETS', - 'OLD_ACCOUNT', - 'OLD_PASSWORD', - 'ON', - 'ON_FAILURE', - 'ONLINE', - 'ONLY', - 'OPEN', - 'OPEN_EXISTING', - 'OPENTRAN', - 'OPTIMISTIC', - 'OPTIMIZE', - 'OPTION', - 'ORDER', - 'OUT', - 'OUTPUT', - 'OUTPUTBUFFER', - 'OVER', - 'OVERRIDE', - 'OWNER', - 'OWNERSHIP', - 'PAD_INDEX', - 'PAGE', - 'PAGE_VERIFY', - 'PAGECOUNT', - 'PAGLOCK', - 'PARAMETERIZATION', - 'PARSEONLY', - 'PARTIAL', - 'PARTITION', - 'PARTITIONS', - 'PARTNER', - 'PASSWORD', - 'PATH', - 'PER_CPU', - 'PER_NODE', - 'PERCENT', - 'PERMISSION_SET', - 'PERSISTED', - 'PHYSICAL_ONLY', - 'PLAN', - 'POISON_MESSAGE_HANDLING', - 'POOL', - 'POPULATION', - 'PORT', - 'PRECEDING', - 'PRECISION', - 'PRIMARY', - 'PRIMARY_ROLE', - 'PRINT', - 'PRIOR', - 'PRIORITY', - 'PRIORITY_LEVEL', - 'PRIVATE', - 'PRIVILEGES', - 'PROC', - 'PROCCACHE', - 'PROCEDURE', - 'PROCEDURE_NAME', - 'PROCESS', - 'PROFILE', - 'PROPERTY', - 'PROPERTY_DESCRIPTION', - 'PROPERTY_INT_ID', - 'PROPERTY_SET_GUID', - 'PROVIDER', - 'PROVIDER_KEY_NAME', - 'PUBLIC', - 'PUT', - 'QUARTER', - 'QUERY', - 'QUERY_GOVERNOR_COST_LIMIT', - 'QUEUE', - 'QUEUE_DELAY', - 'QUOTED_IDENTIFIER', - 'RAISERROR', - 'RANGE', - 'RAW', - 'RC2', - 'RC4', - 'RC4_128', - 'READ', - 'READ_COMMITTED_SNAPSHOT', - 'READ_ONLY', - 'READ_ONLY_ROUTING_LIST', - 'READ_ONLY_ROUTING_URL', - 'READ_WRITE', - 'READ_WRITE_FILEGROUPS', - 'READCOMMITTED', - 'READCOMMITTEDLOCK', - 'READONLY', - 'READPAST', - 'READTEXT', - 'READUNCOMMITTED', - 'READWRITE', - 'REAL', - 'REBUILD', - 'RECEIVE', - 'RECOMPILE', - 'RECONFIGURE', - 'RECOVERY', - 'RECURSIVE', - 'RECURSIVE_TRIGGERS', - 'REFERENCES', - 'REGENERATE', - 'RELATED_CONVERSATION', - 'RELATED_CONVERSATION_GROUP', - 'RELATIVE', - 'REMOTE', - 'REMOTE_PROC_TRANSACTIONS', - 'REMOTE_SERVICE_NAME', - 'REMOVE', - 'REORGANIZE', - 'REPAIR_ALLOW_DATA_LOSS', - 'REPAIR_FAST', - 'REPAIR_REBUILD', - 'REPEATABLE', - 'REPEATABLEREAD', - 'REPLICA', - 'REPLICATION', - 'REQUEST_MAX_CPU_TIME_SEC', - 'REQUEST_MAX_MEMORY_GRANT_PERCENT', - 'REQUEST_MEMORY_GRANT_TIMEOUT_SEC', - 'REQUIRED', - 'RESAMPLE', - 'RESEED', - 'RESERVE_DISK_SPACE', - 'RESET', - 'RESOURCE', - 'RESTART', - 'RESTORE', - 'RESTRICT', - 'RESTRICTED_USER', - 'RESULT', - 'RESUME', - 'RETAINDAYS', - 'RETENTION', - 'RETURN', - 'RETURNS', - 'REVERT', - 'REVOKE', - 'REWIND', - 'REWINDONLY', - 'ROBUST', - 'ROLE', - 'ROLLBACK', - 'ROLLUP', - 'ROOT', - 'ROUTE', - 'ROW', - 'ROWCOUNT', - 'ROWGUIDCOL', - 'ROWLOCK', - 'ROWS', - 'ROWS_PER_BATCH', - 'ROWTERMINATOR', - 'ROWVERSION', - 'RSA_1024', - 'RSA_2048', - 'RSA_512', - 'RULE', - 'SAFE', - 'SAFETY', - 'SAMPLE', - 'SAVE', - 'SCHEDULER', - 'SCHEMA', - 'SCHEMA_AND_DATA', - 'SCHEMA_ONLY', - 'SCHEMABINDING', - 'SCHEME', - 'SCROLL', - 'SCROLL_LOCKS', - 'SEARCH', - 'SECOND', - 'SECONDARY', - 'SECONDARY_ONLY', - 'SECONDARY_ROLE', - 'SECONDS', - 'SECRET', - 'SECURITY_LOG', - 'SECURITYAUDIT', - 'SELECT', - 'SELECTIVE', - 'SELF', - 'SEND', - 'SENT', - 'SEQUENCE', - 'SERIALIZABLE', - 'SERVER', - 'SERVICE', - 'SERVICE_BROKER', - 'SERVICE_NAME', - 'SESSION', - 'SESSION_TIMEOUT', - 'SET', - 'SETS', - 'SETUSER', - 'SHOW_STATISTICS', - 'SHOWCONTIG', - 'SHOWPLAN', - 'SHOWPLAN_ALL', - 'SHOWPLAN_TEXT', - 'SHOWPLAN_XML', - 'SHRINKDATABASE', - 'SHRINKFILE', - 'SHUTDOWN', - 'SID', - 'SIGNATURE', - 'SIMPLE', - 'SINGLE_BLOB', - 'SINGLE_CLOB', - 'SINGLE_NCLOB', - 'SINGLE_USER', - 'SINGLETON', - 'SIZE', - 'SKIP', - 'SMALLDATETIME', - 'SMALLINT', - 'SMALLMONEY', - 'SNAPSHOT', - 'SORT_IN_TEMPDB', - 'SOURCE', - 'SPARSE', - 'SPATIAL', - 'SPATIAL_WINDOW_MAX_CELLS', - 'SPECIFICATION', - 'SPLIT', - 'SQL', - 'SQL_VARIANT', - 'SQLPERF', - 'STANDBY', - 'START', - 'START_DATE', - 'STARTED', - 'STARTUP_STATE', - 'STAT_HEADER', - 'STATE', - 'STATEMENT', - 'STATIC', - 'STATISTICAL_SEMANTICS', - 'STATISTICS', - 'STATISTICS_INCREMENTAL', - 'STATISTICS_NORECOMPUTE', - 'STATS', - 'STATS_STREAM', - 'STATUS', - 'STATUSONLY', - 'STOP', - 'STOP_ON_ERROR', - 'STOPAT', - 'STOPATMARK', - 'STOPBEFOREMARK', - 'STOPLIST', - 'STOPPED', - 'SUBJECT', - 'SUBSCRIPTION', - 'SUPPORTED', - 'SUSPEND', - 'SWITCH', - 'SYMMETRIC', - 'SYNCHRONOUS_COMMIT', - 'SYNONYM', - 'SYSNAME', - 'SYSTEM', - 'TABLE', - 'TABLERESULTS', - 'TABLESAMPLE', - 'TABLOCK', - 'TABLOCKX', - 'TAKE', - 'TAPE', - 'TARGET', - 'TARGET_RECOVERY_TIME', - 'TB', - 'TCP', - 'TEXT', - 'TEXTIMAGE_ON', - 'TEXTSIZE', - 'THEN', - 'THESAURUS', - 'THROW', - 'TIES', - 'TIME', - 'TIMEOUT', - 'TIMER', - 'TIMESTAMP', - 'TINYINT', - 'TO', - 'TOP', - 'TORN_PAGE_DETECTION', - 'TRACEOFF', - 'TRACEON', - 'TRACESTATUS', - 'TRACK_CAUSALITY', - 'TRACK_COLUMNS_UPDATED', - 'TRAN', - 'TRANSACTION', - 'TRANSFER', - 'TRANSFORM_NOISE_WORDS', - 'TRIGGER', - 'TRIPLE_DES', - 'TRIPLE_DES_3KEY', - 'TRUE', - 'TRUNCATE', - 'TRUNCATEONLY', - 'TRUSTWORTHY', - 'TRY', - 'TSQL', - 'TWO_DIGIT_YEAR_CUTOFF', - 'TYPE', - 'TYPE_WARNING', - 'UNBOUNDED', - 'UNCHECKED', - 'UNCOMMITTED', - 'UNDEFINED', - 'UNIQUE', - 'UNIQUEIDENTIFIER', - 'UNKNOWN', - 'UNLIMITED', - 'UNLOAD', - 'UNSAFE', - 'UPDATE', - 'UPDATETEXT', - 'UPDATEUSAGE', - 'UPDLOCK', - 'URL', - 'USE', - 'USED', - 'USER', - 'USEROPTIONS', - 'USING', - 'VALID_XML', - 'VALIDATION', - 'VALUE', - 'VALUES', - 'VARBINARY', - 'VARCHAR', - 'VARYING', - 'VERIFYONLY', - 'VERSION', - 'VIEW', - 'VIEW_METADATA', - 'VIEWS', - 'VISIBILITY', - 'WAIT_AT_LOW_PRIORITY', - 'WAITFOR', - 'WEEK', - 'WEIGHT', - 'WELL_FORMED_XML', - 'WHEN', - 'WHERE', - 'WHILE', - 'WINDOWS', - 'WITH', - 'WITHIN', - 'WITHOUT', - 'WITNESS', - 'WORK', - 'WORKLOAD', - 'WRITETEXT', - 'XACT_ABORT', - 'XLOCK', - 'XMAX', - 'XMIN', - 'XML', - 'XMLDATA', - 'XMLNAMESPACES', - 'XMLSCHEMA', - 'XQUERY', - 'XSINIL', - 'YEAR', - 'YMAX', - 'YMIN' - ], - operators: [ - // Logical - 'ALL', - 'AND', - 'ANY', - 'BETWEEN', - 'EXISTS', - 'IN', - 'LIKE', - 'NOT', - 'OR', - 'SOME', - // Set - 'EXCEPT', - 'INTERSECT', - 'UNION', - // Join - 'APPLY', - 'CROSS', - 'FULL', - 'INNER', - 'JOIN', - 'LEFT', - 'OUTER', - 'RIGHT', - // Predicates - 'CONTAINS', - 'FREETEXT', - 'IS', - 'NULL', - // Pivoting - 'PIVOT', - 'UNPIVOT', - // Merging - 'MATCHED' - ], - builtinFunctions: [ - // Aggregate - 'AVG', - 'CHECKSUM_AGG', - 'COUNT', - 'COUNT_BIG', - 'GROUPING', - 'GROUPING_ID', - 'MAX', - 'MIN', - 'SUM', - 'STDEV', - 'STDEVP', - 'VAR', - 'VARP', - // Analytic - 'CUME_DIST', - 'FIRST_VALUE', - 'LAG', - 'LAST_VALUE', - 'LEAD', - 'PERCENTILE_CONT', - 'PERCENTILE_DISC', - 'PERCENT_RANK', - // Collation - 'COLLATE', - 'COLLATIONPROPERTY', - 'TERTIARY_WEIGHTS', - // Azure - 'FEDERATION_FILTERING_VALUE', - // Conversion - 'CAST', - 'CONVERT', - 'PARSE', - 'TRY_CAST', - 'TRY_CONVERT', - 'TRY_PARSE', - // Cryptographic - 'ASYMKEY_ID', - 'ASYMKEYPROPERTY', - 'CERTPROPERTY', - 'CERT_ID', - 'CRYPT_GEN_RANDOM', - 'DECRYPTBYASYMKEY', - 'DECRYPTBYCERT', - 'DECRYPTBYKEY', - 'DECRYPTBYKEYAUTOASYMKEY', - 'DECRYPTBYKEYAUTOCERT', - 'DECRYPTBYPASSPHRASE', - 'ENCRYPTBYASYMKEY', - 'ENCRYPTBYCERT', - 'ENCRYPTBYKEY', - 'ENCRYPTBYPASSPHRASE', - 'HASHBYTES', - 'IS_OBJECTSIGNED', - 'KEY_GUID', - 'KEY_ID', - 'KEY_NAME', - 'SIGNBYASYMKEY', - 'SIGNBYCERT', - 'SYMKEYPROPERTY', - 'VERIFYSIGNEDBYCERT', - 'VERIFYSIGNEDBYASYMKEY', - // Cursor - 'CURSOR_STATUS', - // Datatype - 'DATALENGTH', - 'IDENT_CURRENT', - 'IDENT_INCR', - 'IDENT_SEED', - 'IDENTITY', - 'SQL_VARIANT_PROPERTY', - // Datetime - 'CURRENT_TIMESTAMP', - 'DATEADD', - 'DATEDIFF', - 'DATEFROMPARTS', - 'DATENAME', - 'DATEPART', - 'DATETIME2FROMPARTS', - 'DATETIMEFROMPARTS', - 'DATETIMEOFFSETFROMPARTS', - 'DAY', - 'EOMONTH', - 'GETDATE', - 'GETUTCDATE', - 'ISDATE', - 'MONTH', - 'SMALLDATETIMEFROMPARTS', - 'SWITCHOFFSET', - 'SYSDATETIME', - 'SYSDATETIMEOFFSET', - 'SYSUTCDATETIME', - 'TIMEFROMPARTS', - 'TODATETIMEOFFSET', - 'YEAR', - // Logical - 'CHOOSE', - 'COALESCE', - 'IIF', - 'NULLIF', - // Mathematical - 'ABS', - 'ACOS', - 'ASIN', - 'ATAN', - 'ATN2', - 'CEILING', - 'COS', - 'COT', - 'DEGREES', - 'EXP', - 'FLOOR', - 'LOG', - 'LOG10', - 'PI', - 'POWER', - 'RADIANS', - 'RAND', - 'ROUND', - 'SIGN', - 'SIN', - 'SQRT', - 'SQUARE', - 'TAN', - // Metadata - 'APP_NAME', - 'APPLOCK_MODE', - 'APPLOCK_TEST', - 'ASSEMBLYPROPERTY', - 'COL_LENGTH', - 'COL_NAME', - 'COLUMNPROPERTY', - 'DATABASE_PRINCIPAL_ID', - 'DATABASEPROPERTYEX', - 'DB_ID', - 'DB_NAME', - 'FILE_ID', - 'FILE_IDEX', - 'FILE_NAME', - 'FILEGROUP_ID', - 'FILEGROUP_NAME', - 'FILEGROUPPROPERTY', - 'FILEPROPERTY', - 'FULLTEXTCATALOGPROPERTY', - 'FULLTEXTSERVICEPROPERTY', - 'INDEX_COL', - 'INDEXKEY_PROPERTY', - 'INDEXPROPERTY', - 'OBJECT_DEFINITION', - 'OBJECT_ID', - 'OBJECT_NAME', - 'OBJECT_SCHEMA_NAME', - 'OBJECTPROPERTY', - 'OBJECTPROPERTYEX', - 'ORIGINAL_DB_NAME', - 'PARSENAME', - 'SCHEMA_ID', - 'SCHEMA_NAME', - 'SCOPE_IDENTITY', - 'SERVERPROPERTY', - 'STATS_DATE', - 'TYPE_ID', - 'TYPE_NAME', - 'TYPEPROPERTY', - // Ranking - 'DENSE_RANK', - 'NTILE', - 'RANK', - 'ROW_NUMBER', - // Replication - 'PUBLISHINGSERVERNAME', - // Rowset - 'OPENDATASOURCE', - 'OPENQUERY', - 'OPENROWSET', - 'OPENXML', - // Security - 'CERTENCODED', - 'CERTPRIVATEKEY', - 'CURRENT_USER', - 'HAS_DBACCESS', - 'HAS_PERMS_BY_NAME', - 'IS_MEMBER', - 'IS_ROLEMEMBER', - 'IS_SRVROLEMEMBER', - 'LOGINPROPERTY', - 'ORIGINAL_LOGIN', - 'PERMISSIONS', - 'PWDENCRYPT', - 'PWDCOMPARE', - 'SESSION_USER', - 'SESSIONPROPERTY', - 'SUSER_ID', - 'SUSER_NAME', - 'SUSER_SID', - 'SUSER_SNAME', - 'SYSTEM_USER', - 'USER', - 'USER_ID', - 'USER_NAME', - // String - 'ASCII', - 'CHAR', - 'CHARINDEX', - 'CONCAT', - 'DIFFERENCE', - 'FORMAT', - 'LEFT', - 'LEN', - 'LOWER', - 'LTRIM', - 'NCHAR', - 'PATINDEX', - 'QUOTENAME', - 'REPLACE', - 'REPLICATE', - 'REVERSE', - 'RIGHT', - 'RTRIM', - 'SOUNDEX', - 'SPACE', - 'STR', - 'STUFF', - 'SUBSTRING', - 'UNICODE', - 'UPPER', - // System - 'BINARY_CHECKSUM', - 'CHECKSUM', - 'CONNECTIONPROPERTY', - 'CONTEXT_INFO', - 'CURRENT_REQUEST_ID', - 'ERROR_LINE', - 'ERROR_NUMBER', - 'ERROR_MESSAGE', - 'ERROR_PROCEDURE', - 'ERROR_SEVERITY', - 'ERROR_STATE', - 'FORMATMESSAGE', - 'GETANSINULL', - 'GET_FILESTREAM_TRANSACTION_CONTEXT', - 'HOST_ID', - 'HOST_NAME', - 'ISNULL', - 'ISNUMERIC', - 'MIN_ACTIVE_ROWVERSION', - 'NEWID', - 'NEWSEQUENTIALID', - 'ROWCOUNT_BIG', - 'XACT_STATE', - // TextImage - 'TEXTPTR', - 'TEXTVALID', - // Trigger - 'COLUMNS_UPDATED', - 'EVENTDATA', - 'TRIGGER_NESTLEVEL', - 'UPDATE', - // ChangeTracking - 'CHANGETABLE', - 'CHANGE_TRACKING_CONTEXT', - 'CHANGE_TRACKING_CURRENT_VERSION', - 'CHANGE_TRACKING_IS_COLUMN_IN_MASK', - 'CHANGE_TRACKING_MIN_VALID_VERSION', - // FullTextSearch - 'CONTAINSTABLE', - 'FREETEXTTABLE', - // SemanticTextSearch - 'SEMANTICKEYPHRASETABLE', - 'SEMANTICSIMILARITYDETAILSTABLE', - 'SEMANTICSIMILARITYTABLE', - // FileStream - 'FILETABLEROOTPATH', - 'GETFILENAMESPACEPATH', - 'GETPATHLOCATOR', - 'PATHNAME', - // ServiceBroker - 'GET_TRANSMISSION_STATUS' - ], - builtinVariables: [ - // Configuration - '@@DATEFIRST', - '@@DBTS', - '@@LANGID', - '@@LANGUAGE', - '@@LOCK_TIMEOUT', - '@@MAX_CONNECTIONS', - '@@MAX_PRECISION', - '@@NESTLEVEL', - '@@OPTIONS', - '@@REMSERVER', - '@@SERVERNAME', - '@@SERVICENAME', - '@@SPID', - '@@TEXTSIZE', - '@@VERSION', - // Cursor - '@@CURSOR_ROWS', - '@@FETCH_STATUS', - // Datetime - '@@DATEFIRST', - // Metadata - '@@PROCID', - // System - '@@ERROR', - '@@IDENTITY', - '@@ROWCOUNT', - '@@TRANCOUNT', - // Stats - '@@CONNECTIONS', - '@@CPU_BUSY', - '@@IDLE', - '@@IO_BUSY', - '@@PACKET_ERRORS', - '@@PACK_RECEIVED', - '@@PACK_SENT', - '@@TIMETICKS', - '@@TOTAL_ERRORS', - '@@TOTAL_READ', - '@@TOTAL_WRITE' - ], - pseudoColumns: ['$ACTION', '$IDENTITY', '$ROWGUID', '$PARTITION'], - tokenizer: { - root: [ - { include: '@comments' }, - { include: '@whitespace' }, - { include: '@pseudoColumns' }, - { include: '@numbers' }, - { include: '@strings' }, - { include: '@complexIdentifiers' }, - { include: '@scopes' }, - [/(<)(where|set|foreach|if|trim)/, ['delimiter', { token: 'tag', next: '@xml' }]], - [/[;,.]/, 'delimiter'], - [/[()]/, '@brackets'], - [ - /[\w@#$]+/, - { - cases: { - '@keywords': 'keyword', - '@operators': 'operator', - '@builtinVariables': 'predefined', - '@builtinFunctions': 'predefined', - '@default': 'identifier' - } - } - ], - [/[<>=!%&+\-*/|~^]/, 'operator'] - ], - whitespace: [[/\s+/, 'white']], - comments: [ - [/--+.*/, 'comment'], - [/\/\*/, { token: 'comment.quote', next: '@comment' }] - ], - comment: [ - [/[^*/]+/, 'comment'], - // Not supporting nested comments, as nested comments seem to not be standard? - // i.e. http://stackoverflow.com/questions/728172/are-there-multiline-comment-delimiters-in-sql-that-are-vendor-agnostic - // [/\/\*/, { token: 'comment.quote', next: '@push' }], // nested comment not allowed :-( - [/\*\//, { token: 'comment.quote', next: '@pop' }], - [/./, 'comment'] - ], - pseudoColumns: [ - [ - /[$][A-Za-z_][\w@#$]*/, - { - cases: { - '@pseudoColumns': 'predefined', - '@default': 'identifier' - } - } - ] - ], - numbers: [ - [/0[xX][0-9a-fA-F]*/, 'number'], - [/[$][+-]*\d*(\.\d*)?/, 'number'], - [/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/, 'number'] - ], - strings: [ - [/N'/, { token: 'string', next: '@string' }], - [/'/, { token: 'string', next: '@string' }] - ], - string: [ - [/[^']+/, 'string'], - [/''/, 'string'], - [/'/, { token: 'string', next: '@pop' }] - ], - complexIdentifiers: [ - [/\[/, { token: 'identifier.quote', next: '@bracketedIdentifier' }], - [/"/, { token: 'identifier.quote', next: '@quotedIdentifier' }] - ], - bracketedIdentifier: [ - [/[^\]]+/, 'identifier'], - [/]]/, 'identifier'], - [/]/, { token: 'identifier.quote', next: '@pop' }] - ], - quotedIdentifier: [ - [/[^"]+/, 'identifier'], - [/""/, 'identifier'], - [/"/, { token: 'identifier.quote', next: '@pop' }] - ], - scopes: [ - [/BEGIN\s+(DISTRIBUTED\s+)?TRAN(SACTION)?\b/i, 'keyword'], - [/BEGIN\s+TRY\b/i, { token: 'keyword.try' }], - [/END\s+TRY\b/i, { token: 'keyword.try' }], - [/BEGIN\s+CATCH\b/i, { token: 'keyword.catch' }], - [/END\s+CATCH\b/i, { token: 'keyword.catch' }], - [/(BEGIN|CASE)\b/i, { token: 'keyword.block' }], - [/END\b/i, { token: 'keyword.block' }], - [/WHEN\b/i, { token: 'keyword.choice' }], - [/THEN\b/i, { token: 'keyword.choice' }] - ], - xml: [ - [/"([^"]*)"/, 'attribute.value'], - [/'([^']*)'/, 'attribute.value'], - [/[\w\-]+/, 'attribute.name'], - [/=/, 'delimiter'], - [ - />/, - { - token: 'delimiter', - next: '@xmlEmbedded', - nextEmbedded: 'mybatis' - } - ], - [/[ \t\r\n]+/], - [/(<\/)(where|if|set|foreach|trim)(>)/, ['delimiter', 'tag', { token: 'delimiter', next: '@pop' }]] - ], - xmlEmbedded: [ - [/<\/(where|if|set|foreach|trim)/, { token: 'tag', next: '@pop', nextEmbedded: '@pop' }], - [/[^<]+/, ''] - ] - } - }); -} \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/request-parameter.js b/magic-editor/src/console/src/scripts/editor/request-parameter.js deleted file mode 100644 index 5b867b23..00000000 --- a/magic-editor/src/console/src/scripts/editor/request-parameter.js +++ /dev/null @@ -1,5 +0,0 @@ -const RequestParameter = { - environmentFunction: ()=>{}, - setEnvironment: callback => RequestParameter.environmentFunction = callback, -} -export default RequestParameter; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/signature.js b/magic-editor/src/console/src/scripts/editor/signature.js deleted file mode 100644 index 823827d1..00000000 --- a/magic-editor/src/console/src/scripts/editor/signature.js +++ /dev/null @@ -1,75 +0,0 @@ -import JavaClass from './java-class.js' -import tokenizer from '@/scripts/parsing/tokenizer.js' -import {TokenStream} from '../parsing/index.js' -import {Parser} from '@/scripts/parsing/parser.js' -import {MethodCall} from "@/scripts/parsing/ast"; - -const SignatureHelpProvider = { - signatureHelpRetriggerCharacters: ['(', ','], - signatureHelpTriggerCharacters: ['(', ','], - provideSignatureHelp: async (model, position, token, context) => { - if (context.activeSignatureHelp) { - let helper = context.activeSignatureHelp; - helper.activeSignature += 1; - if (helper.activeSignature === helper.signatures.length) { - helper.activeSignature = 0; - } - return { - dispose: function () { - }, - value: helper - } - } - let value = model.getValueInRange({ - startLineNumber: 1, - startColumn: 1, - endLineNumber: position.lineNumber, - endColumn: position.column - }); - try { - let tokens = tokenizer(value); - let parser = new Parser(new TokenStream(tokens)); - const { best, env} = await parser.parseBest(value.length - 1); - if(best && best instanceof MethodCall){ - let target = best.target - let className = await target.getTarget().getJavaType(env); - let methodName = target.member.getText() - let methods = JavaClass.findMethods(await JavaClass.loadClass(className)); - let signatures = [] - methods.filter(it => it.name === methodName).forEach(method => { - let document = []; - for (let j = (method.extension ? 1 : 0); j < method.parameters.length; j++) { - let param = method.parameters[j]; - document.push('- ' + param.name + ':' + (param.comment || param.type)); - } - signatures.push({ - label: method.fullName, - documentation: { - value: method.comment - }, - parameters: [{ - label: 'param1', - documentation: { - value: document.join('\r\n') - } - }] - }); - }) - if (signatures.length > 0) { - return { - dispose: function () { - }, - value: { - activeParameter: 0, - activeSignature: 0, - signatures: signatures - } - } - } - } - } catch (e) { - // console.log(e); - } - } -} -export default SignatureHelpProvider \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/editor/theme.js b/magic-editor/src/console/src/scripts/editor/theme.js deleted file mode 100644 index c2538201..00000000 --- a/magic-editor/src/console/src/scripts/editor/theme.js +++ /dev/null @@ -1,13 +0,0 @@ -import * as monaco from 'monaco-editor'; - -export const Themes = {}; -export const defineTheme = (name, options) => { - options = options || {}; - let editor = options.editor || {}; - editor.base = editor.base || 'vs'; - editor.inherit = editor.inherit === undefined ? true : editor.inherit; - editor.rules = editor.rules || []; - editor.colors = editor.colors || []; - monaco.editor.defineTheme(name, editor); - Themes[name] = options.styles || {}; -} \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/hotkey.js b/magic-editor/src/console/src/scripts/hotkey.js deleted file mode 100644 index ba2af844..00000000 --- a/magic-editor/src/console/src/scripts/hotkey.js +++ /dev/null @@ -1,46 +0,0 @@ -const Key = { - Alt: 512, - Ctrl: 1024, - Shift: 2048 -} -// A-Z -new Array(26).fill(0).forEach((_item, index) => Key[String.fromCharCode(65 + index)] = 65 + index); -// F1 - F12 -new Array(12).fill(0).forEach((_item, index) => Key[`F${index + 1}`] = 112 + index); -const listeners = []; -const listener = (e) => { - for (let i = 0, len = listeners.length; i < len; i++) { - let listener = listeners[i]; - if ((listener.target.contains(e.target) || e.target === listener.target) && e.keyCode & listener.code === listener.code) { - let controlKey = e.keyCode; - controlKey |= (e.ctrlKey && Key.Ctrl || 0); - controlKey |= (e.shiftKey && Key.Shift || 0); - controlKey |= (e.altKey && Key.Alt || 0); - controlKey |= (e.metaKey && Key.Ctrl || 0); - if (controlKey == listener.code) { - e.preventDefault(); - listener.callback(); - return; - } - } - } -}; -let inited = false; -Key.init = () => document.addEventListener('keydown', listener); - -Key.bind = (target, code, callback) => { - if(!inited){ - inited = true - Key.init(); - } - if (typeof callback === 'function') { - listeners.push({target, code, callback}); - } -} -Key.unbind = () => { - listeners.length = 0; - document.removeEventListener('keydown', listener); - inited = false; - -} -export default Key; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/parsing/ast.js b/magic-editor/src/console/src/scripts/parsing/ast.js deleted file mode 100644 index 2b46ca86..00000000 --- a/magic-editor/src/console/src/scripts/parsing/ast.js +++ /dev/null @@ -1,719 +0,0 @@ -import JavaClass from '../editor/java-class.js' -import {Span, TokenType} from './index.js' - -class Node { - constructor(span) { - this.span = span; - } - - getSpan() { - return this.span; - } - - async getJavaType(env) { - await this.getExpressionsJavaType(env); - return 'java.lang.Object'; - } - - async getExpressionsJavaType(env){ - for (const expr of this.expressions().filter(it => it)) { - await expr.getJavaType(env); - } - } - - expressions() { - return [] - } - - toString() { - return this.span.getText(); - } -} - -class Expression extends Node { - constructor(span) { - super(span); - } -} - -class Literal extends Expression { - constructor(span, javaType, expressionList) { - super(span); - this.javaType = javaType; - this.expressionList = expressionList || [] - } - - expressions() { - return this.expressionList - } - - async getJavaType() { - return this.javaType; - } - - getValue(){ - const text = this.getSpan().getText() - return text.replace(/\\\\/g, '\\').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\"/g, '"').replace(/\\'/g, "\'") - } - -} - -class MethodCall extends Node { - constructor(span, target, args) { - super(span) - this.target = target - this.args = args - } - - expressions() { - return [this.target, ...this.args] - } - - getMethod(){ - return this.target; - } - - getArguments(){ - return this.args; - } - - async getJavaType(env) { - let method = this.target.member.getText() - let targetType = await this.target.getJavaType(env) - let methods = JavaClass.findMethods(targetType); - if (methods) { - for (let i = 0, len = methods.length; i < len; i++) { - let m = methods[i]; - if (m.name === method && JavaClass.matchTypes(m.parameters, this.args, m.extension)) { - return m.origin ? targetType : JavaClass.getWrapperClass(m.returnType); - } - } - } - return 'java.lang.Object'; - } - -} - -class FunctionCall extends Node { - constructor(span, target, args) { - super(span) - this.target = target; - this.args = args - } - - expressions() { - return [this.target, ...this.args] - } - - getFunction(){ - return this.target; - } - - getArguments(){ - return this.args; - } - - async getJavaType(env) { - if(this.target instanceof VariableAccess){ - const method = JavaClass.findFunction().find(method => method.name === this.target.variable) - if(method){ - return method.returnType - } - } - return await this.target.getJavaType(env); - } -} - -class MemberAccess extends Node { - constructor(span, target, optional, member, whole) { - super(span) - this.target = target; - this.optional = optional; - this.member = member - this.whole = whole; - } - - isWhole() { - return this.whole === true - } - - expressions() { - return [this.target] - } - - getTarget() { - return this.target; - } - - async getJavaType(env) { - let javaType = await this.target.getJavaType(env); - - let clazz = await JavaClass.loadClass(javaType); - let methods = clazz.methods; - if (methods) { - for (let i = 0, len = methods.length; i < len; i++) { - let method = methods[i]; - if (clazz.superClass === 'java.util.HashMap' && method.name === 'get' && method.parameters.length === 1) { - return JavaClass.getWrapperClass(method.returnType); - } - } - } - return javaType || 'java.lang.Object'; - } -} - -class VariableAccess extends Node { - constructor(span, variable) { - super(span) - this.variable = variable - } - - getVariable() { - return this.variable; - } - - async getJavaType(env) { - // @import - let value = (env && env[this.variable]); - if(!value){ - let imports = env['@import'] - for(let i = imports.length - 1; i >= 0 && !value; i--){ - value = JavaClass.findClass(imports[i] + this.variable); - } - } - return value|| 'java.lang.Object'; - } -} - -class MapOrArrayAccess extends Node { - constructor(span, target, keyOrIndex) { - super(span) - this.target = target - this.keyOrIndex = keyOrIndex - } - - async getJavaType(env) { - const javaType = await this.target.getJavaType(env) - return javaType === 'db' ? 'db' : super.getJavaType(env); - } -} - -class IfStatement extends Node { - constructor(span, condition, trueBlock, elseIfs, falseBlock) { - super(span) - this.condition = condition - this.trueBlock = trueBlock || [] - this.elseIfs = elseIfs || [] - this.falseBlock = falseBlock || [] - } - - expressions() { - return [this.condition, ...this.trueBlock, ...this.elseIfs, ...this.falseBlock] - } -} - -class WholeLiteral extends Literal { - constructor(span) { - super(span) - } -} - -class LambdaFunction extends Node { - constructor(span, parameters, childNodes) { - super(span) - this.parameters = parameters - this.childNodes = childNodes - } - - expressions() { - return [...this.childNodes] - } - - async getJavaType(env) { - if (Array.isArray(this.childNodes) && this.childNodes.length > 0) { - for (let i = 0, len = this.childNodes.length; i < len; i++) { - let node = this.childNodes[i]; - if (node instanceof Return) { - return await node.getJavaType(env); - } - } - return await this.childNodes[this.childNodes.length - 1].getJavaType(env); - } - return await super.getJavaType(env) - } -} - -class Return extends Node { - constructor(span, returnValue) { - super(span) - this.returnValue = returnValue - } - - expressions() { - return [this.returnValue] - } - - async getJavaType(env) { - return this.returnValue == null ? '' : await this.returnValue.getJavaType(env); - } -} - -class Continue extends Node { - constructor(span) { - super(span) - } -} - -class Break extends Node { - constructor(span) { - super(span) - } -} - -class Exit extends Node { - constructor(span, values) { - super(span) - this.values = values - } - - expressions() { - return this.values - } -} - -class Throw extends Node { - constructor(span, value) { - super(span) - this.value = value - } - - expressions() { - return [this.value] - } -} - -class Assert extends Node { - constructor(span, condition, values) { - super(span) - this.condition = condition - this.values = values - } - - expressions() { - return [this.condition, ...this.values] - } -} - -class NewStatement extends Node { - constructor(span, identifier, parameters) { - super(span) - this.identifier = identifier - this.parameters = parameters - } - - expressions() { - return [...this.parameters] - } - - async getJavaType(env) { - let value = env[this.identifier]; - if(!value){ - let imports = env['@import'] - for(let i = imports.length - 1; i >= 0 && !value; i--){ - value = JavaClass.findClass(imports[i] + this.identifier); - } - } - return value|| 'java.lang.Object'; - } -} - -class AsyncCall extends Node { - constructor(span, expression) { - super(span) - this.expression = expression - } - - expressions() { - return [this.expression] - } - - async getJavaType(env) { - return 'java.util.concurrent.Future'; - } -} - -class UnaryOperation extends Node { - constructor(operator, operand, atAfter) { - super(new Span(operator.getSpan(), operand.getSpan())) - this.operand = operand - this.operator = operator - this.atAfter = atAfter - } - - async getJavaType(env) { - return await this.operand.getJavaType(env); - } - -} - -class TryStatement extends Node { - constructor(span, exceptionVarNode, tryBlock, catchBlock, finallyBlock) { - super(span) - this.exceptionVarNode = exceptionVarNode; - this.tryBlock = tryBlock; - this.catchBlock = catchBlock; - this.finallyBlock = finallyBlock; - } - - expressions() { - return [...this.tryBlock, ...this.catchBlock, ...this.finallyBlock] - } -} - -class ForStatement extends Node { - constructor(span, indexOrKey, value, mapOrArray, body) { - super(span) - this.indexOrKey = indexOrKey; - this.value = value; - this.mapOrArray = mapOrArray; - this.body = body; - } - - expressions() { - return [this.mapOrArray, ...this.body] - } - -} - -class WhileStatement extends Node { - constructor(span, condition, trueBlock) { - super(span) - this.condition = condition; - this.trueBlock = trueBlock; - } - - expressions() { - return [this.condition, ...this.trueBlock] - } - -} - -class Import extends Node { - constructor(span, packageName, varName, module) { - super(span) - this.packageName = packageName; - this.varName = varName; - this.module = module; - } - - async getJavaType(env){ - if(this.packageName.endsWith('.*')) { - env['@import'].push(this.packageName.substring(0, this.packageName.length - 1)) - }else if(this.module){ - env[this.packageName] = this.packageName - }else if(this.varName){ - env[this.varName] = this.packageName - }else { - let index = this.packageName.lastIndexOf('.'); - if (index > -1) { - env[this.packageName.substring(index + 1)] = this.packageName - } - } - } - -} - -class VarDefine extends Node { - constructor(span, varName, expression, defineType) { - super(span) - this.varName = varName; - this.expression = expression; - this.defineType = defineType - } - - getVarName() { - return this.varName; - } - - expressions() { - return this.expression == null ? [] : [this.expression] - } - - async getJavaType(env) { - let type = 'java.lang.Object' - if(this.defineType){ - type = env[this.defineType] || type - }else if(this.expression){ - type = await this.expression.getJavaType(env); - } - env[this.varName] = type - return type - } -} - -class TernaryOperation extends Node { - constructor(condition, trueExpression, falseExpression) { - super(new Span(condition.getSpan(), falseExpression.getSpan())); - this.condition = condition; - this.trueExpression = trueExpression; - this.falseExpression = falseExpression; - } - - expressions() { - return [this.condition, this.trueExpression, this.falseExpression] - } -} - -class Spread extends Node { - constructor(span, target) { - super(span) - this.target = target; - } - - expressions() { - return [this.target] - } -} - -class MapLiteral extends Literal { - constructor(span, keys, values) { - super(span, 'java.util.LinkedHashMap') - this.keys = keys; - this.values = values; - } - - expressions() { - return this.values - } -} - -class ListLiteral extends Literal { - constructor(span, values) { - super(span, 'java.util.ArrayList') - this.values = values; - } - - expressions() { - return this.values - } -} - -class LanguageExpression extends Node{ - constructor(span) { - super(span); - } - - async getJavaType() { - return 'java.util.function.Function'; - } - expressions() { - return [] - } -} -class BinaryOperation extends Node { - constructor(left, operator, right, linqLevel) { - super(new Span(left.getSpan(), right.getSpan())); - this.left = left; - this.right = right; - this.operator = operator; - this.linqLevel = linqLevel; - } - - getOperator(){ - return this.operator; - } - setRightOperand(right){ - this.right = right; - } - getRightOperand() { - - return this.right - } - - expressions() { - return [this.left, this.right] - } - - async getJavaType(env) { - let lType = await this.left.getJavaType(env); - let rType = await this.right.getJavaType(env); - lType = lType.toLowerCase().substring(lType.lastIndexOf(".") + 1) - rType = rType.toLowerCase().substring(rType.lastIndexOf(".") + 1) - if (this.operator.type === TokenType.Plus || this.operator.type === TokenType.PlusEqual) { - if (lType === 'string' || rType === 'string') { - return 'java.lang.String'; - } - } - if (this.operator.type === TokenType.Equal || (this.operator.type === TokenType.Assignment && this.linqLevel > 0)) { - return 'java.lang.Boolean'; - } - if (lType === 'bigdecimal' || rType === 'bigdecimal') { - return 'java.math.BigDecimal'; - } - if (lType === 'double' || rType === 'double') { - return 'java.lang.Double'; - } - if (lType === 'float' || rType === 'float') { - return 'java.lang.Float'; - } - if (lType === 'long' || rType === 'long') { - return 'java.lang.Long'; - } - if (lType === 'integer' || rType === 'integer') { - return 'java.lang.Integer'; - } - if (lType === 'short' || rType === 'short') { - return 'java.lang.Short'; - } - if (lType === 'byte' || rType === 'byte') { - return 'java.lang.Byte'; - } - return 'java.lang.Object'; - } -} - -class LinqField extends Expression { - constructor(span, expression, alias) { - super(span) - this.expression = expression; - this.alias = alias; - } - - expressions() { - return [this.expression]; - } -} - -class LinqJoin extends Expression { - constructor(span, leftJoin, target, condition) { - super(span) - this.leftJoin = leftJoin; - this.target = target; - this.condition = condition; - } - - expressions() { - return [this.target, this.condition]; - } -} - -class LinqOrder extends Expression { - constructor(span, expression, alias, order) { - super(span) - this.expression = expression; - this.alias = alias; - this.order = order; - } - - expressions() { - return [this.expression]; - } -} - -class ClassConverter extends Expression { - constructor(span, convert, target, args) { - super(span); - this.convert = convert; - this.target = target; - this.args = args; - } - - expressions() { - return [this.target, ...this.args]; - } - - async getJavaType() { - if (this.convert == 'double') { - return 'java.lang.Double'; - } - if (this.convert == 'float') { - return 'java.lang.Float'; - } - if (this.convert == 'long') { - return 'java.lang.Long'; - } - if (this.convert == 'int') { - return 'java.lang.Integer'; - } - if (this.convert == 'short') { - return 'java.lang.Short'; - } - if (this.convert == 'byte') { - return 'java.lang.Byte'; - } - if (this.convert == 'date') { - return 'java.util.Date'; - } - return 'java.lang.Object'; - } -} - -class LinqSelect extends Expression { - constructor(span, fields, from, joins, where, groups, having, orders, limit, offset) { - super(span) - this.fields = fields; - this.from = from; - this.joins = joins; - this.where = where; - this.groups = groups; - this.having = having; - this.orders = orders; - this.limit = limit; - this.offset = offset; - } - - expressions() { - let temp = []; - if (this.where) { - temp.push(this.where) - } - if (this.having) { - temp.push(this.having) - } - return [...this.fields, this.from, ...this.joins, ...this.groups, ...temp, ...this.orders, this.limit, this.offset]; - } - - async getJavaType() { - return 'java.util.List'; - } -} - - -export { - Node, - Expression, - Literal, - Assert, - MethodCall, - FunctionCall, - MemberAccess, - VariableAccess, - MapOrArrayAccess, - IfStatement, - LambdaFunction, - Return, - Continue, - Break, - NewStatement, - AsyncCall, - UnaryOperation, - TryStatement, - ForStatement, - WhileStatement, - Import, - VarDefine, - TernaryOperation, - BinaryOperation, - Spread, - MapLiteral, - ListLiteral, - Exit, - LinqField, - LinqJoin, - LinqOrder, - LinqSelect, - WholeLiteral, - ClassConverter, - LanguageExpression, - Throw -} \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/parsing/index.js b/magic-editor/src/console/src/scripts/parsing/index.js deleted file mode 100644 index 16c28eea..00000000 --- a/magic-editor/src/console/src/scripts/parsing/index.js +++ /dev/null @@ -1,553 +0,0 @@ -class ParseException extends Error { - constructor(message, span) { - super(message) - this.name = 'ParseException' - this.span = span - } -} - -class Line { - constructor(source, start, end, lineNumber, endLineNumber, startCol, endCol) { - this.source = source; - this.start = start; - this.end = end; - this.lineNumber = lineNumber; - this.endLineNumber = endLineNumber; - this.startCol = startCol; - this.endCol = endCol; - } -} - -class Span { - constructor(source, start, end) { - if (source instanceof Span && start instanceof Span) { - this.source = source.source; - this.start = source.start; - this.end = start.end; - this.cachedText = this.source.substring(this.start, this.end); - } else { - this.source = source; - this.start = start || 0; - this.end = end || source.length; - this.cachedText = source.substring(this.start, this.end); - } - } - - getText() { - return this.cachedText; - } - - getSource() { - return this.source; - } - - getStart() { - return this.start; - } - - getEnd() { - return this.end; - } - - toString() { - return "Span [text=" + this.getText() + ", start=" + this.start + ", end=" + this.end + "]"; - } - - inPosition(position) { - return this.start <= position && this.end >= position; - } - - getLine() { - if (this.line != null) { - return this.line; - } - let lineStart = this.start; - while (lineStart < this.end) { - if (lineStart < 0) { - break; - } - let c = this.source.charAt(lineStart); - if (c === '\n') { - lineStart = lineStart + 1; - break; - } - lineStart--; - } - if (lineStart < 0) { - lineStart = 0; - } - - let lineEnd = this.end; - while (true) { - if (lineEnd > this.source.length - 1) { - break; - } - let c = this.source.charAt(lineEnd); - if (c === '\n') { - break; - } - lineEnd++; - } - - let lineNumber = 0; - let idx = lineStart; - while (idx > 0 && idx < this.end) { - let c = this.source.charAt(idx); - if (c === '\n') { - lineNumber++; - } - idx--; - } - lineNumber++; - idx = lineStart + 1; - let endLineNumber = lineNumber; - while (idx < lineEnd) { - let c = this.source.charAt(idx); - if (c === '\n') { - endLineNumber++; - } - idx++; - } - let startCol = this.start - lineStart + 1; - let endCol = startCol + this.end - this.start - 1; - this.line = new Line(this.source, lineStart, lineEnd, lineNumber, endLineNumber, startCol, endCol); - return this.line; - } -} - -const TokenType = { - Spread: {literal: '...', error: '...'}, - Period: {literal: '.', error: '.'}, - QuestionPeriod: {literal: '?.', error: '?.'}, - Comma: {literal: ',', error: ','}, - Semicolon: {literal: ';', error: ';'}, - Colon: {literal: ':', error: ':'}, - Plus: {literal: '+', error: '+'}, - Minus: {literal: '-', error: '-'}, - Asterisk: {literal: '*', error: '*'}, - ForwardSlash: {literal: '/', error: '/'}, - PostSlash: {literal: '\\', error: '\\'}, - Percentage: {literal: '%', error: '%'}, - LeftParantheses: {literal: '(', error: '('}, - RightParantheses: {literal: ')', error: ')'}, - LeftBracket: {literal: '[', error: '['}, - RightBracket: {literal: ']', error: ']'}, - LeftCurly: {literal: '{', error: '{'}, - RightCurly: {error: '}'},// 特殊待遇! - Less: {literal: '<', error: '<'}, - Greater: {literal: '>', error: '>'}, - LessEqual: {literal: '<=', error: '<='}, - GreaterEqual: {literal: '>=', error: '>='}, - Equal: {literal: '==', error: '=='}, - NotEqual: {literal: '!=', error: '!='}, - Assignment: {literal: '=', error: '='}, - PlusPlus: {literal: '++', error: '++'}, - MinusMinus: {literal: '--', error: '--'}, - PlusEqual: {literal: '+=', error: '+='}, - MinusEqual: {literal: '-=', error: '-='}, - AsteriskEqual: {literal: '*=', error: '*='}, - ForwardSlashEqual: {literal: '/=', error: '/='}, - PercentEqual: {literal: '%=', error: '%='}, - ColonColon: {literal: '::', error: '::'}, - EqualEqualEqual: {literal: '===', error: '==='}, - NotEqualEqual: {literal: '!==', error: '!=='}, - And: {literal: '&&', error: '&&'}, - Or: {literal: '||', error: '||'}, - Xor: {literal: '^', error: '^'}, - Not: {literal: '!', error: '!'}, - BitAnd: {literal:'&', error: '&'}, - BitOr: {literal:'|', error: '|'}, - BitNot: {literal:'~', error: '~'}, - LShift: {literal:'<<', error: '<<'}, - RShift: {literal:'>>', error: '>>'}, - RShift2: {literal:'>>>', error: '>>>'}, - XorEqual: {literal:'^=', error: '^=', modifiable: true}, - BitAndEqual: {literal:'&=', error: '&=', modifiable: true}, - BitOrEqual: {literal:'|=', error: '|=', modifiable: true}, - LShiftEqual: {literal:'<<=', error: '<<=', modifiable: true}, - RShiftEqual: {literal:'>>=', error: '>>=', modifiable: true}, - RShift2Equal: {literal:'>>>=', error: '>>>=', modifiable: true}, - - - SqlAnd: {literal: 'and', error: 'and'}, - SqlOr: {literal: 'or', error: 'or'}, - SqlNotEqual: {literal: '<>', error: '<>', inLinq: true}, - Questionmark: {literal: '?', error: '?'}, - DoubleQuote: {literal: '"', error: '"'}, - TripleQuote: {literal: '"""', error: '"""'}, - SingleQuote: {literal: '\'', error: '\''}, - Lambda: {error: '=> 或 ->'}, - BooleanLiteral: {error: 'true 或 false'}, - DoubleLiteral: {error: '一个 double 类型数值'}, - DecimalLiteral: {error: '一个 BigDecimal 类型数值'}, - FloatLiteral: {error: '一个 float 类型数值'}, - LongLiteral: {error: '一个 long 类型数值'}, - IntegerLiteral: {error: '一个 int 类型数值'}, - ShortLiteral: {error: '一个 short 类型数值'}, - ByteLiteral: {error: '一个 byte 类型数据'}, - CharacterLiteral: {error: '一个 char 类型数据'}, - RegexpLiteral: {error: '一个 正则表达式'}, - StringLiteral: {error: '一个 字符串'}, - NullLiteral: {error: 'null'}, - Language: {error: 'language'}, - Identifier: {error: '标识符'}, - Unknown: {error: 'unknown'} -}; -let tokenTypeValues = Object.getOwnPropertyNames(TokenType).map(e => TokenType[e]); -TokenType.getSortedValues = function () { - if (this.values) { - return this.values; - } - this.values = tokenTypeValues.sort(function (o1, o2) { - if (!o1.literal && !o2.literal) { - return 0; - } - if (!o1.literal && !!o2.literal) { - return 1; - } - if (!!o1.literal && !o2.literal) { - return -1; - } - return o2.literal.length - o1.literal.length; - }); - return this.values; -}; - -class Token { - constructor(tokenType, span, valueOrTokenStream) { - this.type = tokenType; - this.span = span; - if(valueOrTokenStream instanceof TokenStream){ - this.tokenStream = valueOrTokenStream; - }else if(valueOrTokenStream){ - this.value = valueOrTokenStream; - } - } - - getTokenType() { - return this.type; - } - - getTokenStream() { - return this.tokenStream; - } - - getSpan() { - return this.span; - } - - getText() { - return this.span.getText(); - } -} - -class LiteralToken extends Token { - constructor(tokenType, span, valueOrTokenStream) { - super(tokenType, span, valueOrTokenStream) - } - - getJavaType() { - if (this.type === TokenType.StringLiteral) { - return 'java.lang.String' - } - if (this.type === TokenType.DoubleLiteral) { - return 'java.lang.Double' - } - if (this.type === TokenType.ByteLiteral) { - return 'java.lang.Byte' - } - if (this.type === TokenType.FloatLiteral) { - return 'java.lang.Float' - } - if (this.type === TokenType.DecimalLiteral) { - return 'java.math.BigDecimal' - } - if (this.type === TokenType.IntegerLiteral) { - return 'java.lang.Integer' - } - if (this.type === TokenType.LongLiteral) { - return 'java.lang.Long' - } - if (this.type === TokenType.BooleanLiteral) { - return 'java.lang.Boolean' - } - if (this.type === TokenType.RegexpLiteral) { - return 'java.util.regex.Pattern' - } - return 'java.lang.Object' - - } -} - -class CharacterStream { - constructor(source, start, end) { - this.index = start === undefined ? 0 : start; - this.end = end === undefined ? source.length : end; - this.source = source; - this.spanStart = 0; - } - - hasMore() { - return this.index < this.end; - } - - consume() { - return this.source.charAt(this.index++); - } - - match(needle, consume) { - if (typeof needle !== 'string') { - needle = needle.literal; - } - let needleLength = needle.length; - if (needleLength + this.index > this.end) { - return false; - } - for (let i = 0, j = this.index; i < needleLength; i++, j++) { - if (this.index >= this.end) - return false; - if (needle.charAt(i) !== this.source.charAt(j)) - return false; - } - if (consume) - this.index += needleLength; - return true; - } - matchAny(strs, consume) { - for(let i=0,len = strs.length; i < len;i++){ - if(this.match(strs[i], consume)){ - return true; - } - } - return false; - } - - matchDigit(consume) { - return this.matchAny('0123456789', consume) - } - - matchIdentifierStart(consume) { - if (this.index >= this.end) - return false; - let c = this.source.charAt(this.index); - if (c.match(/[a-zA-Z0-9_\u4e00-\u9fa5]/) || c === '$' || c === '_' || c === '@') { - if (consume) - this.index++; - return true; - } - return false; - } - - matchIdentifierPart(consume) { - if (this.index >= this.end) - return false; - let c = this.source.charAt(this.index); - if (c.match(/[a-zA-Z0-9_\u4e00-\u9fa5]/) || c === '@') { - if (consume) - this.index++; - return true; - } - return false; - } - - skipWhiteSpace() { - while (this.index < this.end) { - let c = this.source.charAt(this.index); - if (c === ' ' || c === '\n' || c === '\r' || c === '\t') { - this.index++; - } else { - break; - } - } - } - - getSpan(start, end) { - return new Span(this.source, start, end); - } - - skipLine() { - while (this.index < this.end) { - if (this.source.charAt(this.index++) === '\n') { - break; - } - } - } - - skipUntil(chars) { - while (this.index < this.end) { - let matched = true; - for (let i = 0, len = chars.length; i < len && this.index + i < this.end; i++) { - if (chars.charAt(i) !== this.source.charAt(this.index + i)) { - matched = false; - break; - } - } - this.index += matched ? chars.length : 1; - if (matched) { - return true; - } - } - return false; - } - - startSpan() { - this.spanStart = this.index; - } - - endSpan(offsetOrStart, end) { - if(end !== undefined) { - return new Span(this.source, offsetOrStart, end) - } - return new Span(this.source, this.spanStart, this.index + (offsetOrStart || 0)); - } - - getPosition() { - return this.index; - } - - reset(position) { - this.index = position; - } -} - -class TokenStream { - constructor(tokens) { - this.tokens = tokens; - this.index = 0; - this.end = tokens.length; - } - - getEnd() { - return this.end > 0 && this.tokens[this.end -1] - } - - hasMore() { - return this.index < this.end; - } - - hasNext() { - return this.index + 1 < this.end; - } - - makeIndex() { - return this.index; - } - - resetIndex(index) { - this.index = index; - } - - getToken(consume) { - let token = this.tokens[this.index]; - if (consume) { - this.index++; - } - return token; - } - - consume() { - if (!this.hasMore()) { - throw new Error('Reached the end of the source.'); - } - return this.tokens[this.index++]; - } - - next() { - if (!this.hasMore()) { - throw new Error('Reached the end of the source.'); - } - return this.tokens[++this.index]; - } - - prev() { - if (this.index === 0) { - throw new Error('Reached the end of the source.'); - } - return this.tokens[--this.index]; - } - - getPrev() { - if (this.index === 0) { - throw new Error('Reached the end of the source.'); - } - return this.tokens[this.index - 1]; - } - - match(tokenOrText, consume, ignoreCase) { - if (this.index >= this.end) { - return false; - } - let match = false; - if (Array.isArray(tokenOrText)) { - for (let i = 0, len = tokenOrText.length; i < len; i++) { - if (this.match(tokenOrText[i], consume, ignoreCase)) { - return true; - } - } - } else if (typeof tokenOrText == 'string') { - if (this.tokens[this.index].getText() === tokenOrText || (ignoreCase === true && this.tokens[this.index].getText().toLowerCase() === tokenOrText.toLowerCase())) { - match = true; - } - } else { - if (this.tokens[this.index].type === tokenOrText) { - match = true; - } - } - if (match && consume) { - this.index++; - } - return match; - } - - textToString(tokenOrText) { - if (typeof tokenOrText == 'string') { - return tokenOrText; - } else if (tokenOrText instanceof Token) { - return tokenOrText.getText(); - } else if (Array.isArray(tokenOrText)) { - let arr = []; - tokenOrText.forEach(it => arr.push(this.textToString(it))); - return arr.join(",") - } else { - return tokenOrText.error; - } - } - - expect(text, ignoreCase) { - if (this.match(text, true, ignoreCase)) { - return this.tokens[this.index - 1]; - } else { - if (!this.hasMore()) { - let span = this.tokens[this.index - 1].getSpan(); - return new Token(TokenType.Unknown, span); - } else { - let token = this.tokens[this.index]; - if (text instanceof Token) { - text = text.type.error; - } - throw new ParseException("Expected '" + this.textToString(text) + "', but got '" + token.getText() + "'", token.getSpan()); - } - } - } - - hasPrev() { - return this.index > 0 - } - - getSource() { - if (this.tokens.length === 0) { - return null; - } - return this.tokens[0].getSpan().getSource(); - } -} - -export { - Span, - Token, - TokenType, - CharacterStream, - TokenStream, - LiteralToken, - ParseException -}; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/parsing/parser.js b/magic-editor/src/console/src/scripts/parsing/parser.js deleted file mode 100644 index bab02721..00000000 --- a/magic-editor/src/console/src/scripts/parsing/parser.js +++ /dev/null @@ -1,915 +0,0 @@ -import { ParseException, Span, TokenStream, TokenType} from './index.js' -import tokenizer from './tokenizer.js' -import JavaClass from '../editor/java-class.js' -import { - Assert, - AsyncCall, - BinaryOperation, - Break, - ClassConverter, - Continue, - Exit, - ForStatement, - FunctionCall, - IfStatement, - Import, - LambdaFunction, - LanguageExpression, - LinqField, - LinqJoin, - LinqOrder, - LinqSelect, - ListLiteral, - Literal, - MapLiteral, - MapOrArrayAccess, - MemberAccess, - MethodCall, - NewStatement, - Return, - Spread, - TernaryOperation, - TryStatement, - UnaryOperation, - VarDefine, - VariableAccess, - WhileStatement, - WholeLiteral, - Throw -} from './ast.js' -import RequestParameter from "@/scripts/editor/request-parameter"; - -export const keywords = ["import", "as", "var", "let", "const", "return", "break", "continue", "if", "for", "in", "new", "true", "false", "null", "else", "try", "catch", "finally", "async", "while", "exit", "and", "or", "throw"/*"assert"*/]; -export const linqKeywords = ["from", "join", "left", "group", "by", "as", "having", "and", "or", "in", "where", "on", "limit", "offset"]; -const binaryOperatorPrecedence = [ - [TokenType.Assignment], - [TokenType.RShift2Equal, TokenType.RShiftEqual, TokenType.LShiftEqual, TokenType.XorEqual, TokenType.BitOrEqual, TokenType.BitAndEqual, TokenType.PercentEqual, TokenType.ForwardSlashEqual, TokenType.AsteriskEqual, TokenType.MinusEqual, TokenType.PlusEqual], - [TokenType.Or, TokenType.SqlOr], - [TokenType.And, TokenType.SqlAnd], - [TokenType.BitOr], - [TokenType.Xor], - [TokenType.BitAnd], - [TokenType.EqualEqualEqual, TokenType.Equal, TokenType.NotEqualEqual, TokenType.NotEqual, TokenType.SqlNotEqual], - [TokenType.Less, TokenType.LessEqual, TokenType.Greater, TokenType.GreaterEqual], - [TokenType.Plus, TokenType.Minus], - [TokenType.LShift, TokenType.RShift, TokenType.RShift2], - [TokenType.Asterisk, TokenType.ForwardSlash, TokenType.Percentage] -]; -const linqBinaryOperatorPrecedence = [ - [TokenType.RShift2Equal, TokenType.RShiftEqual, TokenType.LShiftEqual, TokenType.XorEqual, TokenType.BitOrEqual, TokenType.BitAndEqual, TokenType.PercentEqual, TokenType.ForwardSlashEqual, TokenType.AsteriskEqual, TokenType.MinusEqual, TokenType.PlusEqual], - [TokenType.Or, TokenType.SqlOr], - [TokenType.And, TokenType.SqlAnd], - [TokenType.BitOr], - [TokenType.Xor], - [TokenType.BitAnd], - [TokenType.Assignment, TokenType.EqualEqualEqual, TokenType.Equal, TokenType.NotEqualEqual, TokenType.Equal, TokenType.NotEqual, TokenType.SqlNotEqual], - [TokenType.Less, TokenType.LessEqual, TokenType.Greater, TokenType.GreaterEqual], - [TokenType.Plus, TokenType.Minus], - [TokenType.LShift, TokenType.RShift, TokenType.RShift2], - [TokenType.Asterisk, TokenType.ForwardSlash, TokenType.Percentage] -] -const unaryOperators = [TokenType.MinusMinus, TokenType.PlusPlus, TokenType.BitNot, TokenType.Minus, TokenType.Plus, TokenType.Not]; - -export class Parser { - constructor(stream) { - this.stream = stream; - this.linqLevel = 0; - } - - parse(ignoreError) { - let nodes = []; - try { - while (this.stream.hasMore()) { - let node = this.parseStatement(); - if (node != null) { - this.validateNode(node); - nodes.push(node); - } - } - } catch (e) { - //console.error(e) - if (ignoreError !== true) { - throw e; - } - } - return nodes; - } - - async parseBest(position){ - let nodes = this.parse() - let env = await this.processEnv(nodes) - return { - best: this.findBestMatch(nodes[nodes.length - 1], position), - env - } - } - - async processEnv(nodes){ - let nodeLen = nodes.length - let env = { - ...RequestParameter.environmentFunction(), - ...JavaClass.getAutoImportClass(), - ...JavaClass.getAutoImportModule(), - '@import': [] - } - for (let i = 0; i < nodeLen; i++) { - await nodes[i].getJavaType(env) - } - return env - } - - validateNode(node) { - if (node instanceof Literal) { - throw new ParseException('literal cannot be used alone', node.getSpan()); - } - } - - parseStatement(expectRightCurly) { - let result = null; - if (this.stream.match("import", false)) { - result = this.parseImport(); - } else if (this.stream.match(["var", "let", "const"], false)) { - result = this.parseVarDefine(); - } else if (this.stream.match("if", false)) { - result = this.parseIfStatement(); - } else if (this.stream.match("return", false)) { - result = this.parseReturn(); - } else if (this.stream.match("for", false)) { - result = this.parseForStatement(); - } else if (this.stream.match("while", false)) { - result = this.parseWhileStatement(); - } else if (this.stream.match("continue", false)) { - result = new Continue(this.stream.consume().getSpan()); - } else if (this.stream.match("async", false)) { - result = this.parseAsync(); - } else if (this.stream.match("try", false)) { - result = this.parseTryStatement(); - } else if (this.stream.match("break", false)) { - result = new Break(this.stream.consume().getSpan()); - } else if (this.stream.match("exit", false)) { - result = this.parseExit(); - } else if (this.stream.match("throw", false)) { - result = this.parseThrow(); - } else if (this.stream.match("assert", false)) { - result = this.parseAssert(); - } else { - let index = this.stream.makeIndex(); - if (this.stream.match(TokenType.Identifier, true) && this.stream.match(TokenType.Identifier, false)) { - this.stream.resetIndex(index); - result = this.parseVarDefine(); - } - if (result == null) { - this.stream.resetIndex(index); - result = this.parseExpression(expectRightCurly); - } - } - while (this.stream.match(";", true)) { - - } - return result; - } - - checkKeyword(span) { - if (keywords.indexOf(span.getText()) > -1) { - throw new ParseException('变量名不能定义为关键字', span); - } - } - - parseThrow() { - let opening = this.stream.consume().getSpan(); - let expression = this.parseExpression(); - return new Throw(new Span(opening, this.stream.getPrev().getSpan()), expression); - } - - parseExit() { - let opening = this.stream.expect("exit").getSpan(); - let expressionList = []; - do { - expressionList.push(this.parseExpression()); - } while (this.stream.match(TokenType.Comma, true)); - return new Exit(new Span(opening, this.stream.getPrev().getSpan()), expressionList); - } - - parseAssert() { - let index = this.stream.makeIndex() - try { - let opening = this.stream.expect("assert").getSpan(); - let condition = this.parseExpression(); - this.stream.expect(TokenType.Colon); - let expressionList = []; - do { - expressionList.push(this.parseExpression()); - } while (this.stream.match(TokenType.Comma, true)); - return new Assert(new Span(opening, this.stream.getPrev().getSpan()), condition, expressionList); - } catch (e) { - this.stream.resetIndex(index) - return this.parseExpression(); - } - } - - parseImport() { - let opening = this.stream.expect("import").getSpan(); - if (this.stream.hasMore()) { - let expected = this.stream.consume(); - let packageName = null; - let isStringLiteral = expected.getTokenType() === TokenType.StringLiteral - if (isStringLiteral) { - packageName = this.createStringLiteral(expected).getValue(); - } else if (expected.type === TokenType.Identifier) { - let startSpan = expected.getSpan(); - let endSpan = null; - packageName = startSpan.getText(); - while (this.stream.match(TokenType.Period, true)){ - isStringLiteral = true; - if(this.stream.match(TokenType.Asterisk, false)){ - expected = this.stream.consume() - break; - } - expected = this.stream.expect(TokenType.Identifier) - } - if(isStringLiteral){ - endSpan = expected.getSpan(); - packageName = new Span(startSpan, endSpan).getText(); - } - } else { - throw new ParseException("Expected identifier or string, but got stream is " + expected.getTokenType().error, this.stream.getPrev().getSpan()); - } - - let varName = packageName; - if (isStringLiteral) { - if (this.stream.match("as", true)) { - expected = this.stream.expect(TokenType.Identifier); - this.checkKeyword(expected.getSpan()); - varName = expected.getSpan().getText(); - } else { - let temp = packageName; - if (!temp.startsWith("@")) { - let index = temp.lastIndexOf("."); - if (index != -1) { - temp = temp.substring(index + 1); - } - } else { - throw new ParseException("Expected as", this.stream.getPrev().getSpan()); - } - varName = temp; - } - } - return new Import(new Span(opening, expected.getSpan()), packageName, varName, !isStringLiteral); - } - throw new ParseException("Expected identifier or string, but got stream is EOF", this.stream.getPrev().getSpan()); - } - - parseReturn() { - let returnSpan = this.stream.expect("return").getSpan(); - if (this.stream.match(";", false)) return new Return(returnSpan, null); - let returnValue = this.parseExpression(); - return new Return(new Span(returnSpan, returnValue.getSpan()), returnValue); - } - - parseAsync() { - let opening = this.stream.expect("async").getSpan(); - let expression = this.parseExpression(); - return new AsyncCall(new Span(opening, this.stream.getPrev().getSpan()), expression); - } - - parseIfStatement() { - let openingIf = this.stream.expect("if").getSpan(); - let condition = this.parseExpression(); - let trueBlock = this.parseFunctionBody(); - let elseIfs = []; - let falseBlock = []; - while (this.stream.hasMore() && this.stream.match("else", true)) { - if (this.stream.hasMore() && this.stream.match("if", false)) { - let elseIfOpening = this.stream.expect("if").getSpan(); - let elseIfCondition = this.parseExpression(); - let elseIfBlock = this.parseFunctionBody(); - let elseIfSpan = new Span(elseIfOpening, elseIfBlock.length > 0 ? elseIfBlock[(elseIfBlock.length - 1)].getSpan() : elseIfOpening); - elseIfs.push(new IfStatement(elseIfSpan, elseIfCondition, elseIfBlock, [],)); - } else { - falseBlock = falseBlock.concat(this.parseFunctionBody()); - break; - } - } - let closingEnd = this.stream.getPrev().getSpan(); - - return new IfStatement(new Span(openingIf, closingEnd), condition, trueBlock, elseIfs, falseBlock); - } - - parseNewExpression(opening) { - let expression = this.parseAccessOrCall(TokenType.Identifier, true); - let span = new Span(opening.getSource(), opening.getStart(), this.stream.getPrev().getSpan().getEnd()) - if (expression instanceof MethodCall) { - return this.parseAccessOrCall(new NewStatement(span, expression.getMethod(), expression.getArguments())); - } else if (expression instanceof FunctionCall) { - return this.parseAccessOrCall(new NewStatement(span, expression.getFunction(), expression.getArguments())); - } - return this.parseAccessOrCall(new NewStatement(span, expression, [])); - // throw new ParseException("Expected MethodCall or FunctionCall or LambdaFunction", this.stream.getPrev().getSpan()); - } - - parseArguments() { - this.stream.expect(TokenType.LeftParantheses); - let args = []; - while (this.stream.hasMore() && !this.stream.match(TokenType.RightParantheses, false)) { - args.push(this.parseExpression()); - if (!this.stream.match(TokenType.RightParantheses, false)) this.stream.expect(TokenType.Comma); - } - return args; - } - - parseForStatement() { - let openingFor = this.stream.expect("for").getSpan(); - this.stream.expect("("); - let index = null; - let value = this.stream.expect(TokenType.Identifier).getSpan(); - this.checkKeyword(value); - if (this.stream.match(TokenType.Comma, true)) { - index = value; - value = this.stream.expect(TokenType.Identifier).getSpan(); - this.checkKeyword(value); - } - this.stream.expect("in"); - let mapOrArray = this.parseExpression(); - this.stream.expect(")"); - let body = this.parseFunctionBody(); - return new ForStatement(new Span(openingFor, this.stream.getPrev().getSpan()), index && index.getText(), value && value.getText(), mapOrArray, body); - } - - parseVarDefine() { - let opening = this.stream.consume().getSpan(); - let token = this.stream.expect(TokenType.Identifier); - this.checkKeyword(token.getSpan()); - let varDefine; - if (this.stream.match(TokenType.Assignment, true)) { - varDefine = new VarDefine(new Span(opening, this.stream.getPrev().getSpan()), token.getText(), this.parseExpression(), opening.getText()); - } else { - varDefine = new VarDefine(new Span(opening, this.stream.getPrev().getSpan()), token.getText(), null, opening.getText()); - } - return varDefine; - } - - parseTryStatement() { - let opening = this.stream.expect("try"); - let tryBlocks = this.parseFunctionBody(); - let catchBlocks = []; - let finallyBlocks = []; - let exception = null; - if (this.stream.match("catch", true)) { - if (this.stream.match("(", true)) { - exception = this.stream.expect(TokenType.Identifier).getText(); - this.stream.expect(")"); - } - catchBlocks = catchBlocks.concat(this.parseFunctionBody()); - } - if (this.stream.match("finally", true)) { - finallyBlocks = finallyBlocks.concat(this.parseFunctionBody()); - } - return new TryStatement(new Span(opening.getSpan(), this.stream.getPrev().getSpan()), exception, tryBlocks, catchBlocks, finallyBlocks); - } - - parseWhileStatement() { - let openingWhile = this.stream.expect("while").getSpan(); - let condition = this.parseExpression(); - let trueBlock = this.parseFunctionBody(); - let closingEnd = this.stream.getPrev().getSpan(); - - return new WhileStatement(new Span(openingWhile, closingEnd), condition, trueBlock); - } - - parseFunctionBody() { - this.stream.expect("{"); - let blocks = []; - while (this.stream.hasMore() && !this.stream.match("}", false)) { - let node = this.parseStatement(true); - if (node != null) { - this.validateNode(node); - blocks.push(node); - } - } - this.expectCloseing(); - return blocks; - } - - expectCloseing() { - if (!this.stream.hasMore()) { - // throw new ParseException("Did not find closing }.", this.stream.prev().getSpan()); - } - return this.stream.expect("}").getSpan(); - } - - parseExpression(expectRightCurly) { - return this.parseTernaryOperator(expectRightCurly); - } - - parseTernaryOperator(expectRightCurly) { - let condition = this.parseBinaryOperator(0, expectRightCurly); - if (this.stream.match(TokenType.Questionmark, true)) { - let trueExpression = this.parseTernaryOperator(expectRightCurly); - this.stream.expect(TokenType.Colon); - let falseExpression = this.parseTernaryOperator(expectRightCurly); - if (condition instanceof BinaryOperation && condition.getOperator() === TokenType.Assignment) { - condition.setRightOperand(new TernaryOperation(condition.getRightOperand(), trueExpression, falseExpression)); - return condition; - } - return new TernaryOperation(condition, trueExpression, falseExpression); - } else { - return condition; - } - } - - parseBinaryOperator(level, expectRightCurly) { - let nextLevel = level + 1; - let precedence = this.linqLevel > 0 ? linqBinaryOperatorPrecedence : binaryOperatorPrecedence; - let left = nextLevel === precedence.length ? this.parseUnaryOperator(expectRightCurly) : this.parseBinaryOperator(nextLevel, expectRightCurly); - let operators = precedence[level]; - while (this.stream.hasMore() && this.stream.match(operators, false)) { - let operator = this.stream.consume(); - if (operator.type.inLinq && this.linqLevel === 0) { - throw new ParseException(operator.getText() + " 只能在Linq中使用", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } - let right = nextLevel === precedence.length ? this.parseUnaryOperator(expectRightCurly) : this.parseBinaryOperator(nextLevel, expectRightCurly); - left = new BinaryOperation(left, operator, right, this.linqLevel); - } - return left; - } - - parseUnaryOperator(expectRightCurly) { - if (this.stream.match(unaryOperators, false)) { - return new UnaryOperation(this.stream.consume(), this.parseUnaryOperator(expectRightCurly)); - } else { - if (this.stream.match(TokenType.LeftParantheses, false)) { //( - let openSpan = this.stream.expect(TokenType.LeftParantheses).getSpan(); - let index = this.stream.makeIndex(); - let parameters = []; - while (this.stream.match(TokenType.Identifier, false)) { - let identifier = this.stream.expect(TokenType.Identifier); - parameters.push(identifier.getSpan().getText()); - if (this.stream.match(TokenType.Comma, true)) { //, - continue; - } - if (this.stream.match(TokenType.RightParantheses, true)) { //) - if (this.stream.match(TokenType.Lambda, true)) { // => - return this.parseLambdaBody(openSpan, parameters); - } - break; - } - } - if (this.stream.match(TokenType.RightParantheses, true) && this.stream.match(TokenType.Lambda, true)) { - return this.parseLambdaBody(openSpan, parameters); - } - this.stream.resetIndex(index); - let expression = this.parseExpression(); - this.stream.expect(TokenType.RightParantheses); - return this.parseAccessOrCall(expression); - } else { - let expression = this.parseAccessOrCallOrLiteral(expectRightCurly); - if (expression instanceof MemberAccess || expression instanceof VariableAccess || expression instanceof MapOrArrayAccess) { - if (this.stream.match([TokenType.PlusPlus, TokenType.MinusMinus], false)) { - return new UnaryOperation(this.stream.consume(), expression); - } - } - return expression; - } - } - } - - parseLambdaBody(openSpan, parameters) { - let index = this.stream.makeIndex(); - let childNodes = []; - try { - let expression = this.parseExpression(); - childNodes.push(new Return(new Span("return", 0, 6), expression)); - return new LambdaFunction(new Span(openSpan, expression.getSpan()), parameters, childNodes); - } catch (e) { - this.stream.resetIndex(index); - if (this.stream.match(TokenType.LeftCurly, true)) { - while (this.stream.hasMore() && !this.stream.match("}", false)) { - let node = this.parseStatement(true); - this.validateNode(node); - childNodes.push(node); - } - let closeSpan = this.expectCloseing(); - return new LambdaFunction(new Span(openSpan, closeSpan), parameters, childNodes); - } else { - let node = this.parseStatement(); - childNodes.push(new Return(new Span("return", 0, 6), node)); - return new LambdaFunction(new Span(openSpan, node.getSpan()), parameters, childNodes); - } - } - } - - parseSpreadAccess(spread) { - if (!spread) { - spread = this.stream.expect(TokenType.Spread); - } - let target = this.parseExpression(); - return new Spread(new Span(spread.getSpan(), target.getSpan()), target); - } - - parseAccessOrCall(target, isNew) { - if (target === TokenType.StringLiteral || target === TokenType.Identifier) { - let token = this.stream.expect(target); - let identifier = token.getSpan(); - if (target === TokenType.Identifier && "new" === identifier.getText()) { - return this.parseNewExpression(identifier); - } - if (target === TokenType.Identifier && this.stream.match(TokenType.Lambda, true)) { - return this.parseLambdaBody(identifier, [identifier.getText()]); - } - let result = target === TokenType.StringLiteral ? this.createStringLiteral(token) : new VariableAccess(identifier, identifier.getText()); - return this.parseAccessOrCall(result, isNew); - } else { - while (this.stream.hasMore() && this.stream.match([TokenType.LeftParantheses, TokenType.LeftBracket, TokenType.Period, TokenType.QuestionPeriod, TokenType.ColonColon], false)) { - if (this.stream.match(TokenType.ColonColon, false)) { - let open = this.stream.consume().getSpan(); - let args = []; - let identifier = this.stream.expect(TokenType.Identifier); - let closing = identifier.getSpan(); - if (this.stream.match(TokenType.LeftParantheses, false)) { - args = this.parseArguments(); - closing = this.stream.expect(TokenType.RightParantheses).getSpan(); - } - target = new ClassConverter(new Span(open, closing), identifier.getText(), target, args); - } - // function or method call - else if (this.stream.match(TokenType.LeftParantheses, false)) { - let args = this.parseArguments(); - let closingSpan = this.stream.expect(TokenType.RightParantheses).getSpan(); - if (target instanceof VariableAccess || target instanceof MapOrArrayAccess) - target = new FunctionCall(new Span(target.getSpan(), closingSpan), target, args, this.linqLevel > 0); - else if (target instanceof MemberAccess) { - target = new MethodCall(new Span(target.getSpan(), closingSpan), target, args, this.linqLevel > 0); - } else { - throw new ParseException("Expected a variable, field or method.", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } - if (isNew) { - break; - } - } - - // map or array access - else if (this.stream.match(TokenType.LeftBracket, true)) { - let keyOrIndex = this.parseExpression(); - let closingSpan = this.stream.expect(TokenType.RightBracket).getSpan(); - target = new MapOrArrayAccess(new Span(target.getSpan(), closingSpan), target, keyOrIndex); - } - - // field or method access - else if (this.stream.match([TokenType.Period, TokenType.QuestionPeriod], false)) { - let optional = this.stream.consume().getTokenType() === TokenType.QuestionPeriod; - if (this.linqLevel > 0 && this.stream.match(TokenType.Asterisk, false)) { - target = new MemberAccess(target, optional, this.stream.expect(TokenType.Asterisk).getSpan(), true); - } else { - let name = this.stream.expect([TokenType.Identifier, TokenType.SqlAnd, TokenType.SqlOr]).getSpan() - target = new MemberAccess(new Span(target.getSpan(), name), target, optional, name, false); - } - } - } - return target; - } - - } - - parseMapLiteral() { - let openCurly = this.stream.expect(TokenType.LeftCurly).getSpan(); - - let keys = []; - let values = []; - while (this.stream.hasMore() && !this.stream.match("}", false)) { - let key; - if (this.stream.hasPrev()) { - let prev = this.stream.getPrev(); - if (this.stream.match(TokenType.Spread, false) && (prev.getTokenType() === TokenType.LeftCurly || prev.getTokenType() === TokenType.Comma)) { - let spread = this.stream.expect(TokenType.Spread); - keys.push(spread); - values.push(this.parseSpreadAccess(spread)); - if (this.stream.match([TokenType.Comma, TokenType.RightCurly], false)) { - this.stream.match(TokenType.Comma, true); - } - continue; - } - } - if (this.stream.match(TokenType.StringLiteral, false)) { - key = this.stream.expect(TokenType.StringLiteral); - } else if (this.stream.match(TokenType.LeftBracket, true)) { // [key] - key = this.parseExpression() - this.stream.expect(TokenType.RightBracket); - } else { - key = this.stream.expect(TokenType.Identifier); - } - keys.push(key); - if (this.stream.match([TokenType.Comma, TokenType.RightCurly], false)) { - this.stream.match(TokenType.Comma, true); - if (key instanceof VariableAccess){ - values.push(key) - } else if (key.getTokenType() === TokenType.Identifier) { - values.push(new VariableAccess(key.getSpan(), key.getText())); - } else { - values.push(new Literal(key.getSpan(), 'java.lang.String')); - } - } else { - this.stream.expect(":"); - values.push(this.parseExpression()); - if (!this.stream.match("}", false)) { - this.stream.expect(TokenType.Comma); - } - } - } - let closeCurly = this.stream.expect("}").getSpan(); - return new MapLiteral(new Span(openCurly, closeCurly), keys, values); - } - - parseListLiteral() { - let openBracket = this.stream.expect(TokenType.LeftBracket).getSpan(); - let values = []; - while (this.stream.hasMore() && !this.stream.match(TokenType.RightBracket, false)) { - values.push(this.parseExpression()); - if (!this.stream.match(TokenType.RightBracket, false)) { - this.stream.expect(TokenType.Comma); - } - } - - let closeBracket = this.stream.expect(TokenType.RightBracket).getSpan(); - return new ListLiteral(new Span(openBracket, closeBracket), values); - } - - parseSelect() { - let opening = this.stream.expect("select", true).getSpan(); - this.linqLevel++; - let fields = this.parseLinqFields(); - this.stream.expect("from", true); - let from = this.parseLinqField(); - let joins = this.parseLinqJoins(); - let where; - if (this.stream.match("where", true, true)) { - where = this.parseExpression(); - } - let groups = this.parseGroup(); - let having; - if (this.stream.match("having", true, true)) { - having = this.parseExpression(); - } - let orders = this.parseLinqOrders(); - this.linqLevel--; - let limit,offset; - if(this.stream.match("limit", true, true)){ - limit = this.parseExpression(); - if(this.stream.match("offset", true, true)){ - offset = this.parseExpression(); - } - } - let close = this.stream.getPrev().getSpan(); - return new LinqSelect(new Span(opening, close), fields, from, joins, where, groups, having, orders, limit, offset); - } - - parseGroup() { - let groups = []; - if (this.stream.match("group", true, true)) { - this.stream.expect("by", true); - do { - let expression = this.parseExpression(); - groups.push(new LinqField(expression.getSpan(), expression, null)); - } while (this.stream.match(TokenType.Comma, true)); - } - return groups; - } - - parseLinqOrders() { - let orders = []; - if (this.stream.match("order", true, true)) { - this.stream.expect("by", true); - do { - let expression = this.parseExpression(); - let order = 1; - if (this.stream.match(["desc", "asc"], false, true)) { - if ("desc" === this.stream.consume().getText()) { - order = -1; - } - } - orders.push(new LinqOrder(new Span(expression.getSpan(), this.stream.getPrev().getSpan()), expression, null, order)); - } while (this.stream.match(TokenType.Comma, true)); - } - return orders; - } - - parseLinqField() { - let expression = this.parseExpression(); - if (this.stream.match(TokenType.Identifier, false) && !this.stream.match(linqKeywords, false, true)) { - let alias = this.stream.expect(TokenType.Identifier).getSpan(); - return new LinqField(new Span(expression.getSpan(), alias), expression, alias.getText()); - } - return new LinqField(expression.getSpan(), expression, null); - } - - parseLinqFields() { - let fields = []; - do { - let expression = this.parseExpression(); - - if (this.stream.match(TokenType.Identifier, false) && !this.stream.match(linqKeywords, false, true)) { - if (expression instanceof WholeLiteral) { - throw new ParseException("* 后边不能跟别名", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } else if (expression instanceof MemberAccess && expression.isWhole()) { - throw new ParseException(expression.getSpan().getText() + " 后边不能跟别名", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } - let alias = this.stream.consume().getSpan(); - fields.push(new LinqField(new Span(expression.getSpan(), alias), expression, alias.getText())); - } else { - fields.push(new LinqField(expression.getSpan(), expression, null)); - } - } while (this.stream.match(TokenType.Comma, true)); //, - if (fields.length === 0) { - throw new ParseException("至少要查询一个字段", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } - return fields; - } - - parseLinqJoins() { - let joins = []; - do { - let isLeft = this.stream.match("left", false); - let opeing = isLeft ? this.stream.consume().getSpan() : null; - if (this.stream.match("join", true)) { - opeing = isLeft ? opeing : this.stream.getPrev().getSpan(); - let target = this.parseLinqField(); - this.stream.expect("on"); - let condition = this.parseExpression(); - joins.push(new LinqJoin(new Span(opeing, this.stream.getPrev().getSpan()), isLeft, target, condition)); - } - } while (this.stream.match(["left", "join"], false)); - return joins; - } - - parseAccessOrCallOrLiteral(expectRightCurly) { - let expression; - if (expectRightCurly && this.stream.match("}", false)) { - return null; - } else if (this.stream.match(TokenType.Spread, false)) { - expression = this.parseSpreadAccess(); - } else if (this.stream.match(TokenType.Identifier, false)) { - if (this.stream.match("async", false)) { - expression = this.parseAsync(); - } else if (this.stream.match("select", false, true)) { - expression = this.parseSelect(); - } else { - expression = this.parseAccessOrCall(TokenType.Identifier); - } - } else if (this.stream.match(TokenType.LeftCurly, false)) { - expression = this.parseMapLiteral(); - } else if (this.stream.match(TokenType.LeftBracket, false)) { - expression = this.parseListLiteral(); - } else if (this.stream.match(TokenType.StringLiteral, false)) { - expression = this.createStringLiteral(this.stream.expect(TokenType.StringLiteral)); - } else if (this.stream.match(TokenType.BooleanLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.BooleanLiteral).getSpan(), 'java.lang.Boolean'); - } else if (this.stream.match(TokenType.DoubleLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.DoubleLiteral).getSpan(), 'java.lang.Double'); - } else if (this.stream.match(TokenType.FloatLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.FloatLiteral).getSpan(), 'java.lang.Float'); - } else if (this.stream.match(TokenType.ByteLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.ByteLiteral).getSpan(), 'java.lang.Byte'); - } else if (this.stream.match(TokenType.ShortLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.ShortLiteral).getSpan(), 'java.lang.Short'); - } else if (this.stream.match(TokenType.IntegerLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.IntegerLiteral).getSpan(), 'java.lang.Integer'); - } else if (this.stream.match(TokenType.LongLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.LongLiteral).getSpan(), 'java.lang.Long'); - } else if (this.stream.match(TokenType.DecimalLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.DecimalLiteral).getSpan(), 'java.math.BigDecimal'); - } else if (this.stream.match(TokenType.RegexpLiteral, false)) { - let token = this.stream.expect(TokenType.RegexpLiteral); - expression = new Literal(token.getSpan(), 'java.util.regex.Pattern'); - } else if (this.stream.match(TokenType.NullLiteral, false)) { - expression = new Literal(this.stream.expect(TokenType.NullLiteral).getSpan(), 'null'); - } else if (this.linqLevel > 0 && this.stream.match(TokenType.Asterisk, false)) { - expression = new WholeLiteral(this.stream.expect(TokenType.Asterisk).getSpan()); - } else if (this.stream.match(TokenType.Language, false)) { - expression = new LanguageExpression(this.stream.consume().getSpan(), this.stream.consume().getSpan()); - } - if (expression == null) { - throw new ParseException("Expected a variable, field, map, array, function or method call, or literal.", this.stream.hasMore() ? this.stream.consume().getSpan() : this.stream.getPrev().getSpan()); - } - return this.parseAccessOrCall(expression); - } - - createStringLiteral(token) { - if (token.getTokenStream() == null) { - return new Literal(token.getSpan(), 'java.lang.String'); - } - let tempStream = this.stream; - this.stream = token.getTokenStream(); - let expressions = []; - while (this.stream.hasMore()) { - expressions.push(this.parseExpression()); - } - this.stream = tempStream; - return new Literal(token.getSpan(), 'java.lang.String', expressions); - } - - findBestMatch(node, position){ - let expressions = node.expressions().filter(it => it); - for (let index in expressions) { - let best = this.findBestMatch(expressions[index], position) - if (best) { - return best; - } - } - if (node.getSpan().inPosition(position)) { - return node; - } - return null; - } - - -} - -function processBody(body, level) { - let arr = [] - let defaultParam = { - name: '', - value: '', - dataType: '', - validateType: '', - expression: '', - error: '', - description: '', - children: [], - level: level + 1, - selected: false - } - if (body instanceof MapLiteral) { - body.keys.forEach((key, index) => { - let value = body.values[index]; - let param = { - ...defaultParam, - name: key.span.getText().replace(/['"]/g, ''), - value: isSimpleObject(value) ? value.span.getText().trim() : '', - dataType: getType(value), - } - if (value instanceof MapLiteral || value instanceof ListLiteral) { - param.children = processBody(value, level + 1); - } - arr.push(param) - }); - } else if (body instanceof ListLiteral) { - if (body.values[0]) { - let value = body.values[0] - let param = { - ...defaultParam, - value: isSimpleObject(value) ? value.span.getText().trim() : '', - dataType: getType(value), - } - if (value instanceof MapLiteral || value instanceof ListLiteral) { - param.children = processBody(value, level + 1); - } - arr.push(param) - } - } - return arr; -} - -function isSimpleObject(object) { - return !(object instanceof MapLiteral || object instanceof ListLiteral) -} - -function getType(object) { - if (object instanceof MapLiteral) { - return "Object"; - } - if (object instanceof ListLiteral) { - return "Array"; - } - if (object instanceof UnaryOperation) { - object = object.operand; - } - let type = object.javaType.substring(object.javaType.lastIndexOf(".") + 1); - if (type === 'Integer' && Number(object.span.getText()) > 0x7fffffff || Number(object.span.getText()) < -0x80000000) { - return 'Long' - } - return type === 'null' ? 'Object' : type; -} - -export function parseJson(bodyStr) { - try { - JSON.parse(bodyStr) - let parser = new Parser(new TokenStream(tokenizer(bodyStr))) - let expr = parser.parseExpression(); - let reqBody = [] - reqBody.push({ - name: '', - value: '', - dataType: getType(expr), - validateType: '', - expression: '', - error: '', - description: '', - children: processBody(expr, 0), - level: 0, - selected: false - }) - return reqBody - } catch (e) { - // console.error(e) - } -} - diff --git a/magic-editor/src/console/src/scripts/parsing/tokenizer.js b/magic-editor/src/console/src/scripts/parsing/tokenizer.js deleted file mode 100644 index ac36380b..00000000 --- a/magic-editor/src/console/src/scripts/parsing/tokenizer.js +++ /dev/null @@ -1,366 +0,0 @@ -import {CharacterStream, LiteralToken, ParseException, Token, TokenStream, TokenType} from './index.js' - -const regexpToken = (stream, tokens) => { - if (tokens.length > 0) { - let token = tokens[tokens.length - 1]; - if (token instanceof LiteralToken) { - return false; - } - switch (token.getTokenType()){ - case TokenType.Comma : // , - case TokenType.Semicolon : // ; - case TokenType.Colon: // : - case TokenType.RightCurly: // } - case TokenType.LeftBracket: // [ - case TokenType.LeftParantheses: // ( - case TokenType.Assignment: // = - case TokenType.NotEqual: // != - case TokenType.EqualEqualEqual: // === - case TokenType.NotEqualEqual: // !== - case TokenType.Equal: // == - case TokenType.And: // && - case TokenType.Or: // || - case TokenType.SqlAnd: // and - case TokenType.SqlOr: // or - case TokenType.SqlNotEqual: // <> - case TokenType.Questionmark: // ? - case TokenType.Lambda: // => -> - break; - default: return false; - } - } - if (stream.match("/", false)) { - let mark = stream.getPosition(); - stream.consume(); - stream.startSpan(); - let matchedEndQuote = false; - let deep = 0; - let maybeMissForwardSlash = 0; - let maybeMissForwardSlashEnd = 0; - while (stream.hasMore()) { - // Note: escape sequences like \n are parsed in StringLiteral - if (stream.match("\\", true)) { - stream.consume(); - continue; - } - if (stream.match("[", false)) { - deep++; - maybeMissForwardSlash = stream.getPosition(); - } else if (deep > 0 && stream.match("]", false)) { - deep--; - } else if (stream.match(TokenType.ForwardSlash.literal, true)) { - if (deep === 0) { - if (stream.match("g", true)) { - } - if (stream.match("i", true)) { - } - if (stream.match("m", true)) { - } - if (stream.match("s", true)) { - } - if (stream.match("u", true)) { - } - if (stream.match("y", true)) { - } - matchedEndQuote = true; - break; - } else { - maybeMissForwardSlashEnd = stream.getPosition(); - } - } - let ch = stream.consume(); - if (ch === '\r' || ch === '\n') { - stream.reset(mark); - return false; - } - } - if (deep !== 0) { - throw new ParseException("Missing ']'", stream.getSpan(maybeMissForwardSlash, maybeMissForwardSlashEnd - 1)); - } - if (!matchedEndQuote) { - stream.reset(mark); - return false; - } - let regexpSpan = stream.endSpan(); - regexpSpan = stream.getSpan(regexpSpan.getStart() - 1, regexpSpan.getEnd()); - tokens.push(new LiteralToken(TokenType.RegexpLiteral, regexpSpan)); - return true; - } - return false; -} - -const tokenizerString = (stream, tokenType, tokens) => { - // String literal - if (stream.match(tokenType, true)) { - stream.startSpan(); - let matchedEndQuote = false; - while (stream.hasMore()) { - // Note: escape sequences like \n are parsed in StringLiteral - if (stream.match("\\", true)) { - stream.consume(); - continue; - } - if (stream.match(tokenType.literal, true)) { - matchedEndQuote = true; - break; - } - let ch = stream.consume(); - if (tokenType !== TokenType.TripleQuote && (ch === '\r' || ch === '\n')) { - throw new ParseException(tokenType.error + tokenType.error + "定义的字符串不能换行", stream.endSpan()); - } - } - if (!matchedEndQuote) { - throw new ParseException("字符串没有结束符" + tokenType.error, stream.endSpan()); - } - let stringSpan = stream.endSpan(); - stringSpan = stream.getSpan(stringSpan.getStart(), stringSpan.getEnd() - tokenType.literal.length); - tokens.push(new LiteralToken(TokenType.StringLiteral, stringSpan)); - return true; - } - return false; -}; -const autoNumberType = (span, radix) => { - let value = Number.parseInt(span.getText().substring(2).replace(/\_/g,''), radix) - if (value > 0x7fffffff || value < -0x80000000) { - return new LiteralToken(TokenType.LongLiteral, span, value); - } else if (value > 127 || value < -128) { - return new LiteralToken(TokenType.LongLiteral, span, value); - } - return new LiteralToken(TokenType.ByteLiteral, span, value); -} -const tokenizerNumber = (stream, tokens) => { - if (stream.match('0', false)) { - let index = stream.getPosition(); - stream.startSpan(); - stream.consume(); - if (stream.matchAny(['x', 'X'], true)) { - while (stream.matchDigit(true) || stream.matchAny(["A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f", "_"], true)) { - ; - } - if (stream.matchAny(["L", "l"], true)) { - let span = stream.endSpan(); - let text = span.getText(); - tokens.push(new LiteralToken(TokenType.LongLiteral, span, parseInt(text.substring(2, text.length - 1).replace(/\_/g,''), 16))); - return true; - } - tokens.push(autoNumberType(stream.endSpan(), 16)); - return true; - } else if (stream.matchAny(['b','B'], true)){ - while (stream.matchAny([ '0', '1', '_'], true)) { - ; - } - if (stream.matchAny([ "L", "l"], true)) { - let span = stream.endSpan(); - let text = span.getText(); - tokens.push(new LiteralToken(TokenType.LongLiteral, span, parseInt(text.substring(2, text.length - 1).replace(/\_/g,''), 2))); - return true; - } - tokens.push(autoNumberType(stream.endSpan(), 2)); - return true; - } - stream.reset(index); - } - if (stream.matchDigit(false)) { - let type = TokenType.IntegerLiteral; - stream.startSpan(); - while (stream.matchDigit(true) || stream.match('_', true)) { - } - if (stream.match(TokenType.Period.literal, true)) { - if (stream.hasMore()) { - type = TokenType.DoubleLiteral; - while (stream.matchDigit(true) || stream.match('_',true)) { - } - } else { - stream.reset(stream.getPosition() - 1) - } - } - if (stream.matchAny(['b', 'B'], true)) { - if (type === TokenType.DoubleLiteral) { - throw new ParseException('Byte literal can not have a decimal point.', stream.endSpan()); - } - type = TokenType.ByteLiteral; - } else if (stream.matchAny(['s', 'S'], true)) { - if (type === TokenType.DoubleLiteral) { - throw new ParseException('Short literal can not have a decimal point.', stream.endSpan()); - } - type = TokenType.ShortLiteral; - } else if (stream.matchAny(['l', 'L'], true)) { - if (type === TokenType.DoubleLiteral) { - throw new ParseException('Long literal can not have a decimal point.', stream.endSpan()); - } - type = TokenType.LongLiteral; - } else if (stream.matchAny(['f', 'F'], true)) { - type = TokenType.FloatLiteral; - } else if (stream.matchAny(['d', 'D'], true)) { - type = TokenType.DoubleLiteral; - } else if (stream.matchAny(['m', 'M'], true)) { - type = TokenType.DecimalLiteral; - } - tokens.push(new LiteralToken(type, stream.endSpan())); - return true - } - return false; -} - -const tokenizerLanguage = (stream, tokens) => { - if (stream.match("```", true)) { - stream.startSpan(); - if (stream.matchIdentifierStart(true)) { - while (stream.matchIdentifierPart(true)) { - } - let language = stream.endSpan(); - tokens.push(new Token(TokenType.Language, language)); - stream.startSpan(); - if (!stream.skipUntil("```")) { - throw new ParseException('```需要以```结尾', stream.endSpan()); - } - tokens.push(new Token(TokenType.Language, stream.endSpan(-3))); - return true; - } else { - throw new ParseException('```后需要标识语言类型', stream.endSpan()); - } - } - return false; -} -const tokenizerIdentifier = (stream, tokens) => { - if (stream.matchIdentifierStart(true)) { - stream.startSpan(); - while (stream.matchIdentifierPart(true)) { - } - let identifierSpan = stream.endSpan(); - identifierSpan = stream.getSpan(identifierSpan.getStart() - 1, identifierSpan.getEnd()); - if ("true" === identifierSpan.getText() || "false" === identifierSpan.getText()) { - tokens.push(new LiteralToken(TokenType.BooleanLiteral, identifierSpan)); - } else if ("null" === identifierSpan.getText()) { - tokens.push(new LiteralToken(TokenType.NullLiteral, identifierSpan)); - } else if (TokenType.SqlAnd.literal === identifierSpan.getText()) { - tokens.push(new Token(TokenType.SqlAnd, identifierSpan)); - } else if (TokenType.SqlOr.literal === identifierSpan.getText()) { - tokens.push(new Token(TokenType.SqlOr, identifierSpan)); - } else { - tokens.push(new Token(TokenType.Identifier, identifierSpan)); - } - return true; - } - return false; -} - -const tokenizerTemplateString = (stream, tokens)=>{ - if (stream.match("`", true)) { - let begin = stream.getPosition(); - let start = begin; - let matchedEndQuote = false; - let subTokens = []; - while (stream.hasMore()) { - if (stream.match("\\", true)) { - stream.consume(); - continue; - } - if (stream.match("`", true)) { - matchedEndQuote = true; - break; - } - if (stream.match("${", true)) { - let end = stream.getPosition(); - if (start < end - 2) { - subTokens.push(new LiteralToken(TokenType.StringLiteral, stream.endSpan(start, end - 2))); - } - subTokens.push(...tokenizer(stream, [], "}")); - start = stream.getPosition(); - continue; - } - stream.consume(); - } - let stringSpan = stream.endSpan(begin, stream.getPosition()); - let end = stream.getPosition() - 1; - if (end - start > 0) { - subTokens.push(new LiteralToken(TokenType.StringLiteral, stream.endSpan(start, end))); - } - stringSpan = stream.getSpan(stringSpan.getStart() - 1, stringSpan.getEnd()); - tokens.push(new LiteralToken(TokenType.StringLiteral, stringSpan, new TokenStream(subTokens))); - return true; - } - return false; -} - -const tokenizer = (stream, tokens, except) => { - let leftCount = 0; - let rightCount = 0; - while (stream.hasMore()) { - stream.skipWhiteSpace(); - if (except && stream.match(except, true)) { - return tokens; - } - if (stream.match("//", true)) { //注释 - stream.skipLine(); - continue; - } - if (stream.match("/*", true)) { //多行注释 - stream.skipUntil("*/"); - continue; - } - // int short double long float byte decimal - if (tokenizerNumber(stream, tokens)) { - continue; - } - // '' "" """ """ - if (tokenizerString(stream, TokenType.SingleQuote, tokens) || tokenizerString(stream, TokenType.TripleQuote, tokens) || tokenizerString(stream, TokenType.DoubleQuote, tokens)) { - continue; - } - - // regexp - if (regexpToken(stream, tokens)) { - continue; - } - // ``` ``` - if(tokenizerLanguage(stream, tokens)){ - continue; - } - // template string - if (tokenizerTemplateString(stream, tokens)) { - continue; - } - - // Identifier, keyword, boolean literal, or null literal - if(tokenizerIdentifier(stream, tokens)){ - continue; - } - // lambda - if (stream.matchAny(['=>','->'], true)) { - tokens.push(new Token(TokenType.Lambda, stream.getSpan(stream.getPosition() - 2, stream.getPosition()))); - continue; - } - let outer = false; - // Simple tokens - let sortedTokens = TokenType.getSortedValues(); - for (let i = 0, len = sortedTokens.length; i < len; i++) { - let t = sortedTokens[i]; - if (t.literal != null) { - if (stream.match(t.literal, true)) { - if (t === TokenType.LeftCurly) { - leftCount++; - } - tokens.push(new Token(t, stream.getSpan(stream.getPosition() - t.literal.length, stream.getPosition()))); - outer = true; - break; - } - } - } - if (outer) { - continue; - } - if (leftCount !== rightCount && stream.match("}", true)) { - rightCount++; - tokens.push(new Token(TokenType.RightCurly, stream.getSpan(stream.getPosition() - 1, stream.getPosition()))); - continue; - } - if (stream.hasMore()) { - throw new ParseException("Unknown token", stream.getSpan(stream.getPosition(), stream.getPosition() + 1)); - } - } - return tokens; -} - -export default (source) => { - return tokenizer(new CharacterStream(source, 0, source.length), []) -} \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/reconnecting-websocket.js b/magic-editor/src/console/src/scripts/reconnecting-websocket.js deleted file mode 100644 index a4a3f467..00000000 --- a/magic-editor/src/console/src/scripts/reconnecting-websocket.js +++ /dev/null @@ -1,382 +0,0 @@ -// MIT License: -// -// Copyright (c) 2010-2012, Joe Walnes -// -// 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. - -/** - * This behaves like a WebSocket in every way, except if it fails to connect, - * or it gets disconnected, it will repeatedly poll until it successfully connects - * again. - * - * It is API compatible, so when you have: - * ws = new WebSocket('ws://....'); - * you can replace with: - * ws = new ReconnectingWebSocket('ws://....'); - * - * The event stream will typically look like: - * onconnecting - * onopen - * onmessage - * onmessage - * onclose // lost connection - * onconnecting - * onopen // sometime later... - * onmessage - * onmessage - * etc... - * - * It is API compatible with the standard WebSocket API, apart from the following members: - * - * - `bufferedAmount` - * - `extensions` - * - `binaryType` - * - * Latest version: https://github.com/joewalnes/reconnecting-websocket/ - * - Joe Walnes - * - * Syntax - * ====== - * var socket = new ReconnectingWebSocket(url, protocols, options); - * - * Parameters - * ========== - * url - The url you are connecting to. - * protocols - Optional string or array of protocols. - * options - See below - * - * Options - * ======= - * Options can either be passed upon instantiation or set after instantiation: - * - * var socket = new ReconnectingWebSocket(url, null, { debug: true, reconnectInterval: 4000 }); - * - * or - * - * var socket = new ReconnectingWebSocket(url); - * socket.debug = true; - * socket.reconnectInterval = 4000; - * - * debug - * - Whether this instance should log debug messages. Accepts true or false. Default: false. - * - * automaticOpen - * - Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close(). - * - * reconnectInterval - * - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000. - * - * maxReconnectInterval - * - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000. - * - * reconnectDecay - * - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5. - * - * timeoutInterval - * - The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. Accepts integer. Default: 2000. - * - */ -(function (global, factory) { - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof module !== 'undefined' && module.exports) { - module.exports = factory(); - } else { - global.ReconnectingWebSocket = factory(); - } -})(this, function () { - - if (!('WebSocket' in window)) { - return; - } - - function ReconnectingWebSocket(url, protocols, options) { - - // Default settings - var settings = { - - /** Whether this instance should log debug messages. */ - debug: false, - - /** Whether or not the websocket should attempt to connect immediately upon instantiation. */ - automaticOpen: true, - - /** The number of milliseconds to delay before attempting to reconnect. */ - reconnectInterval: 1000, - /** The maximum number of milliseconds to delay a reconnection attempt. */ - maxReconnectInterval: 30000, - /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */ - reconnectDecay: 1.5, - - /** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */ - timeoutInterval: 2000, - - /** The maximum number of reconnection attempts to make. Unlimited if null. */ - maxReconnectAttempts: null, - - /** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */ - binaryType: 'blob' - } - if (!options) { - options = {}; - } - - // Overwrite and define settings with options if they exist. - for (var key in settings) { - if (typeof options[key] !== 'undefined') { - this[key] = options[key]; - } else { - this[key] = settings[key]; - } - } - - // These should be treated as read-only properties - - /** The URL as resolved by the constructor. This is always an absolute URL. Read only. */ - this.url = url; - - /** The number of attempted reconnects since starting, or the last successful connection. Read only. */ - this.reconnectAttempts = 0; - - /** - * The current state of the connection. - * Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED - * Read only. - */ - this.readyState = WebSocket.CONNECTING; - - /** - * A string indicating the name of the sub-protocol the server selected; this will be one of - * the strings specified in the protocols parameter when creating the WebSocket object. - * Read only. - */ - this.protocol = null; - - // Private state variables - - var self = this; - var ws; - var forcedClose = false; - var timedOut = false; - var eventTarget = document.createElement('div'); - - // Wire up "on*" properties as event handlers - - eventTarget.addEventListener('open', function (event) { - self.onopen(event); - }); - eventTarget.addEventListener('close', function (event) { - self.onclose(event); - }); - eventTarget.addEventListener('connecting', function (event) { - self.onconnecting(event); - }); - eventTarget.addEventListener('message', function (event) { - self.onmessage(event); - }); - eventTarget.addEventListener('error', function (event) { - self.onerror(event); - }); - - // Expose the API required by EventTarget - - this.addEventListener = eventTarget.addEventListener.bind(eventTarget); - this.removeEventListener = eventTarget.removeEventListener.bind(eventTarget); - this.dispatchEvent = eventTarget.dispatchEvent.bind(eventTarget); - - /** - * This function generates an event that is compatible with standard - * compliant browsers and IE9 - IE11 - * - * This will prevent the error: - * Object doesn't support this action - * - * http://stackoverflow.com/questions/19345392/why-arent-my-parameters-getting-passed-through-to-a-dispatched-event/19345563#19345563 - * @param s String The name that the event should use - * @param args Object an optional object that the event will use - */ - function generateEvent(s, args) { - var evt = document.createEvent("CustomEvent"); - evt.initCustomEvent(s, false, false, args); - return evt; - }; - - this.open = function (reconnectAttempt) { - ws = new WebSocket(self.url, protocols || []); - ws.binaryType = this.binaryType; - - if (reconnectAttempt) { - if (this.maxReconnectAttempts && this.reconnectAttempts > this.maxReconnectAttempts) { - return; - } - } else { - eventTarget.dispatchEvent(generateEvent('connecting')); - this.reconnectAttempts = 0; - } - - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'attempt-connect', self.url); - } - - var localWs = ws; - var timeout = setTimeout(function () { - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'connection-timeout', self.url); - } - timedOut = true; - localWs.close(); - timedOut = false; - }, self.timeoutInterval); - - ws.onopen = function (event) { - clearTimeout(timeout); - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'onopen', self.url); - } - self.protocol = ws.protocol; - self.readyState = WebSocket.OPEN; - self.reconnectAttempts = 0; - var e = generateEvent('open'); - e.isReconnect = reconnectAttempt; - reconnectAttempt = false; - eventTarget.dispatchEvent(e); - }; - - ws.onclose = function (event) { - clearTimeout(timeout); - ws = null; - if (forcedClose) { - self.readyState = WebSocket.CLOSED; - eventTarget.dispatchEvent(generateEvent('close')); - } else { - self.readyState = WebSocket.CONNECTING; - var e = generateEvent('connecting'); - e.code = event.code; - e.reason = event.reason; - e.wasClean = event.wasClean; - eventTarget.dispatchEvent(e); - if (!reconnectAttempt && !timedOut) { - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'onclose', self.url); - } - eventTarget.dispatchEvent(generateEvent('close')); - } - - var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts); - setTimeout(function () { - self.reconnectAttempts++; - self.open(true); - }, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout); - } - }; - ws.onmessage = function (event) { - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'onmessage', self.url, event.data); - } - var e = generateEvent('message'); - e.data = event.data; - eventTarget.dispatchEvent(e); - }; - ws.onerror = function (event) { - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'onerror', self.url, event); - } - eventTarget.dispatchEvent(generateEvent('error')); - }; - } - - // Whether or not to create a websocket upon instantiation - if (this.automaticOpen == true) { - this.open(false); - } - - /** - * Transmits data to the server over the WebSocket connection. - * - * @param data a text string, ArrayBuffer or Blob to send to the server. - */ - this.send = function (data) { - if (ws) { - if (self.debug || ReconnectingWebSocket.debugAll) { - console.debug('ReconnectingWebSocket', 'send', self.url, data); - } - return ws.send(data); - } else { - throw 'INVALID_STATE_ERR : Pausing to reconnect websocket'; - } - }; - - /** - * Closes the WebSocket connection or connection attempt, if any. - * If the connection is already CLOSED, this method does nothing. - */ - this.close = function (code, reason) { - // Default CLOSE_NORMAL code - if (typeof code == 'undefined') { - code = 1000; - } - forcedClose = true; - if (ws) { - ws.close(code, reason); - } - }; - - /** - * Additional public API method to refresh the connection if still open (close, re-open). - * For example, if the app suspects bad data / missed heart beats, it can try to refresh. - */ - this.refresh = function () { - if (ws) { - ws.close(); - } - }; - } - - /** - * An event listener to be called when the WebSocket connection's readyState changes to OPEN; - * this indicates that the connection is ready to send and receive data. - */ - ReconnectingWebSocket.prototype.onopen = function (event) { - }; - /** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */ - ReconnectingWebSocket.prototype.onclose = function (event) { - }; - /** An event listener to be called when a connection begins being attempted. */ - ReconnectingWebSocket.prototype.onconnecting = function (event) { - }; - /** An event listener to be called when a message is received from the server. */ - ReconnectingWebSocket.prototype.onmessage = function (event) { - }; - /** An event listener to be called when an error occurs. */ - ReconnectingWebSocket.prototype.onerror = function (event) { - }; - - /** - * Whether all instances of ReconnectingWebSocket should log debug messages. - * Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true. - */ - ReconnectingWebSocket.debugAll = false; - - ReconnectingWebSocket.CONNECTING = WebSocket.CONNECTING; - ReconnectingWebSocket.OPEN = WebSocket.OPEN; - ReconnectingWebSocket.CLOSING = WebSocket.CLOSING; - ReconnectingWebSocket.CLOSED = WebSocket.CLOSED; - - return ReconnectingWebSocket; -}); \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/store.js b/magic-editor/src/console/src/scripts/store.js deleted file mode 100644 index 99896f66..00000000 --- a/magic-editor/src/console/src/scripts/store.js +++ /dev/null @@ -1,21 +0,0 @@ -class Store { - constructor() { - } - - set(key, value) { - if (Array.isArray(value) || typeof value == 'object') { - value = JSON.stringify(value); - } - localStorage.setItem(key, value); - } - - remove(key) { - localStorage.removeItem(key) - } - - get(key) { - return localStorage.getItem(key); - } -} - -export default new Store(); \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/utils.js b/magic-editor/src/console/src/scripts/utils.js deleted file mode 100644 index e22f1c13..00000000 --- a/magic-editor/src/console/src/scripts/utils.js +++ /dev/null @@ -1,182 +0,0 @@ -import request from "@/api/request"; -const Beautifier = require('./beautifier/javascript/beautifier').Beautifier -const replaceURL = (url) => url.replace(/:?\/+/g, e => e.indexOf(':') > -1 ? e : '/'); -const isVisible = (elem) => elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); -const formatJson = (val, defaultVal) => { - if (val) { - if (typeof val == 'string') { - return new Beautifier(val).beautify() - } - if (val) { - return JSON.stringify(val, null, 4); - } - } - return defaultVal || '' -}; -const paddingZero = (val) => val < 10 ? '0' + val : val.toString(); -const formatDate = (val) => { - if (typeof val === 'number') { - if (val.toString().length === 13) { - val = new Date(val) - } else { - val = new Date(val * 1000) - } - } - if (val instanceof Date) { - var month = val.getMonth() + 1; - var day = val.getDate(); - var hour = val.getHours(); - var minute = val.getMinutes(); - var seconds = val.getSeconds(); - return val.getFullYear() + '-' + paddingZero(month) + '-' + paddingZero(day) + ' ' + paddingZero(hour) + ':' + paddingZero(minute) + ':' + paddingZero(seconds); - } - return ''; -}; -const download = (blob,filename)=>{ - let element = document.createElement('a') - let href = window.URL.createObjectURL(blob); - element.href = href; - element.download = filename; - document.body.appendChild(element); - element.click(); - document.body.removeChild(element); - window.URL.revokeObjectURL(href) -} -const requestGroup = (path, group) => { - return request.send(path, JSON.stringify({ - id: group.id, - name: group.name, - path: group.path, - type: group.type, - paths: group.paths, - options: group.options, - parentId: group.parentId - }), { - method: 'post', - headers: { - 'Content-Type': 'application/json' - }, - transformRequest: [] - }) -} -// 判断arr是否为一个数组,返回一个bool值 -const isArray = (arr) => { - return Object.prototype.toString.call(arr) === '[object Array]'; -} - -/* - * @Description 深度克隆 - * ignoreFields 忽略克隆对象字段,只针对对象有效 - */ -const deepClone = (obj, ignoreFields = []) => { - // 对常见的“非”值,直接返回原来值 - if([null, undefined, NaN, false].includes(obj)) return obj; - if(typeof obj !== "object" && typeof obj !== 'function') { - //原始类型直接返回 - return obj; - } - var o = isArray(obj) ? [] : {}; - for(let i in obj) { - if(obj.hasOwnProperty(i)){ - o[i] = typeof obj[i] === "object" ? deepClone(obj[i], ignoreFields) : obj[i]; - } - } - // 清除忽略字段 - ignoreFields.forEach(i => { - delete o[i] - }) - return o; -} - -// 展示锚点对象 -const goToAnchor = (dom) => { - if (typeof dom === 'string') { - dom = document.querySelector(dom) - } - if (dom) { - dom.scrollIntoView(true) - } -} - -/** - * 获取url中的参数 - * @param {String} variable - * @returns - */ -const getQueryVariable = (variable) => { - var query = window.location.search.substring(1) - var vars = query.split('&') - for (var i = 0; i < vars.length; i++) { - var pair = vars[i].split('=') - if (pair[0] == variable) { - return pair[1] - } - } - return false -} -const getTextNodeList = (dom) => { - const nodeList = [...dom.childNodes] - const textNodes = [] - while (nodeList.length) { - const node = nodeList.shift() - if (node.nodeType === node.TEXT_NODE) { - textNodes.push(node) - } else { - nodeList.unshift(...node.childNodes) - } - } - return textNodes -} - -const getTextInfoList = (textNodes) => { - let length = 0 - return textNodes.map(node => { - let startIdx = length, endIdx = length + node.wholeText.length - length = endIdx - return { - text: node.wholeText, - startIdx, - endIdx - } - }) -} -const getMatchList = (content, keyword) => { - const characters = [...'[]()?.+*^${}:'].reduce((r, c) => (r[c] = true, r), {}) - keyword = keyword.split('').map(s => characters[s] ? `\\${s}` : s).join('[\\s\\n]*') - const reg = new RegExp(keyword, 'gmi') - return [...content.matchAll(reg)] // matchAll结果是个迭代器,用扩展符展开得到数组 -} -const replaceMatchResult = (textNodes, textList, matchList) => { - // 对于每一个匹配结果,可能分散在多个标签中,找出这些标签,截取匹配片段并用font标签替换出 - for (let i = matchList.length - 1; i >= 0; i--) { - const match = matchList[i] - const matchStart = match.index, matchEnd = matchStart + match[0].length // 匹配结果在拼接字符串中的起止索引 - // 遍历文本信息列表,查找匹配的文本节点 - for (let textIdx = 0; textIdx < textList.length; textIdx++) { - const { text, startIdx, endIdx } = textList[textIdx] // 文本内容、文本在拼接串中开始、结束索引 - if (endIdx < matchStart) continue // 匹配的文本节点还在后面 - if (startIdx >= matchEnd) break // 匹配文本节点已经处理完了 - let textNode = textNodes[textIdx] // 这个节点中的部分或全部内容匹配到了关键词,将匹配部分截取出来进行替换 - const nodeMatchStartIdx = Math.max(0, matchStart - startIdx) // 匹配内容在文本节点内容中的开始索引 - const nodeMatchLength = Math.min(endIdx, matchEnd) - startIdx - nodeMatchStartIdx // 文本节点内容匹配关键词的长度 - if (nodeMatchStartIdx > 0) textNode = textNode.splitText(nodeMatchStartIdx) // textNode取后半部分 - if (nodeMatchLength < textNode.wholeText.length) textNode.splitText(nodeMatchLength) - const span = document.createElement('span') - span.innerText = text.substr(nodeMatchStartIdx, nodeMatchLength) - span.className = 'keyword' - textNode.parentNode.replaceChild(span, textNode) - } - } -} -const replaceKeywords = (htmlString, keyword) => { - if (!keyword) return htmlString - const div = document.createElement('div') - div.innerHTML = htmlString - const textNodes = getTextNodeList(div) - const textList = getTextInfoList(textNodes) - const content = textList.map(({ text }) => text).join('') - const matchList = getMatchList(content, keyword) - replaceMatchResult(textNodes, textList, matchList) - return div.innerHTML -} -export {replaceURL, isVisible, formatJson, formatDate, paddingZero, download, requestGroup, deepClone, goToAnchor, getQueryVariable, replaceKeywords} diff --git a/magic-editor/src/console/src/scripts/websocket.js b/magic-editor/src/console/src/scripts/websocket.js deleted file mode 100644 index bfb5cfe1..00000000 --- a/magic-editor/src/console/src/scripts/websocket.js +++ /dev/null @@ -1,45 +0,0 @@ -import bus from "@/scripts/bus"; -import ReconnectingWebSocket from './reconnecting-websocket' -function MagicWebSocket(url) { - this.listeners = {}; - this.socket = new ReconnectingWebSocket(url); - this.socket.onmessage = this.messageReceived; - bus.$on('message', (msgType, content) => { - if (content) { - this.socket.send(`${msgType},${content}`) - } else { - this.socket.send(msgType) - } - }) - this.socket.onopen = ()=> { - bus.$emit('ws_open') - } -} - -MagicWebSocket.prototype.on = function (msgType, callback) { - this.listeners[msgType] = this.listeners[msgType] || [] - this.listeners[msgType].push(callback) -} - -MagicWebSocket.prototype.messageReceived = function (e) { - let payload = e.data - let index = payload.indexOf(",") - let msgType = index === -1 ? payload : payload.substring(0, index) - let args = [] - while (index > -1) { - payload = payload.substring(index + 1) - if (payload.startsWith('[') || payload.startsWith('{')) { - args.push(JSON.parse(payload)) - break; - } - let newIndex = payload.indexOf(",", index + 1) - args.push(newIndex === -1 ? payload : payload.substring(index + 1, newIndex)) - index = newIndex - } - bus.$emit('ws_' + msgType, args) -} -MagicWebSocket.prototype.close = function () { - this.socket.close() -} - -export default MagicWebSocket \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/workers/editor.worker.js b/magic-editor/src/console/src/scripts/workers/editor.worker.js deleted file mode 100644 index 523f4278..00000000 --- a/magic-editor/src/console/src/scripts/workers/editor.worker.js +++ /dev/null @@ -1,5 +0,0 @@ -import {initialize} from 'monaco-editor/esm/vs/editor/editor.worker' - -self.onmessage = (e) => { - initialize(); -}; \ No newline at end of file diff --git a/magic-editor/src/console/src/scripts/workers/json.worker.js b/magic-editor/src/console/src/scripts/workers/json.worker.js deleted file mode 100644 index d11e91a8..00000000 --- a/magic-editor/src/console/src/scripts/workers/json.worker.js +++ /dev/null @@ -1,9 +0,0 @@ -import * as worker from 'monaco-editor/esm/vs/editor/editor.worker.js'; -import {JSONWorker} from 'monaco-editor/esm/vs/language/json/jsonWorker.js'; - -self.onmessage = function () { - // ignore the first message - worker.initialize(function (ctx, createData) { - return new JSONWorker(ctx, createData); - }); -}; \ No newline at end of file diff --git a/magic-editor/src/console/vue.config.js b/magic-editor/src/console/vue.config.js deleted file mode 100644 index 1bdcabc9..00000000 --- a/magic-editor/src/console/vue.config.js +++ /dev/null @@ -1,54 +0,0 @@ -const MonacoLocalesPlugin = require('./plugins/MonacoEditorLocalesPlugin.js') -const path = require('path') -const webpack = require('webpack') -const resolve = dir => { - return path.join(__dirname, dir) -} -// 设置环境变量,可以在全局使用 -process.env.VUE_APP_MA_VERSION = require('./package.json').version - -module.exports = { - publicPath: './', - productionSourceMap: false, - configureWebpack: { - output: { - libraryExport: 'default' - }, - module: { - rules:[{ - test: /\.worker.js$/, - exclude: /node_modules/, - use: [{ - loader: 'worker-loader', - options: { - inline: 'fallback' - } - }] - }] - }, - plugins: [ - new MonacoLocalesPlugin({ - //设置支持的语言 - languages: ['zh-cn'], - //默认语言 - defaultLanguage: 'zh-cn', - //打印不匹配的文本 - logUnmatched: false, - //自定义文本翻译 - // mapLanguages: { 'zh-cn': { 'Peek References': '查找引用', 'Go to Symbol...': '跳到变量位置', 'Command Palette': '命令面板' } } - }) - ] - }, - parallel: false, - chainWebpack: config => { - config.resolve.alias - .set('@', resolve('src')) // key,value自行定义,比如.set('@@', resolve('src/components')) - .set('public', resolve('public')) - // 移除 prefetch 插件 - config.plugins.delete('prefetch') - // 移除 preload 插件 - config.plugins.delete('preload') - config.output.globalObject('this') - config.output.filename('js/[name].[hash].js').end() - } -} diff --git a/pom.xml b/pom.xml index afc6ee8d..ad7db539 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 org.ssssssss magic-api-parent - 1.7.2 + 2.0.0-alpha.1 pom magic-api-parent auto generate http api