diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4aafb22..aec72af 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -55,7 +55,6 @@ "jinx-rust": "^0.1.6", "jsox": "^1.2.123", "linguist-languages": "^9.0.0", - "node-sql-parser": "^5.3.12", "php-parser": "^3.2.5", "pinia": "^3.0.3", "pinia-plugin-persistedstate": "^4.5.0", @@ -63,7 +62,6 @@ "remarkable": "^2.0.1", "sass": "^1.92.1", "sh-syntax": "^0.5.8", - "sql-formatter": "^15.6.9", "vue": "^3.5.21", "vue-i18n": "^11.1.12", "vue-pick-colors": "^1.8.0", @@ -2279,12 +2277,6 @@ "undici-types": "~7.10.0" } }, - "node_modules/@types/pegjs": { - "version": "0.10.6", - "resolved": "https://registry.npmmirror.com/@types/pegjs/-/pegjs-0.10.6.tgz", - "integrity": "sha512-eLYXDbZWXh2uxf+w8sXS8d6KSoXTswfps6fvCUuVAGN8eRpfe7h9eSRydxiSJvo9Bf+GzifsDOr9TMQlmJdmkw==", - "license": "MIT" - }, "node_modules/@types/remarkable": { "version": "2.0.8", "resolved": "https://registry.npmmirror.com/@types/remarkable/-/remarkable-2.0.8.tgz", @@ -2894,6 +2886,7 @@ "version": "2.0.1", "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, "license": "Python-2.0" }, "node_modules/asn1.js": { @@ -2982,15 +2975,6 @@ ], "license": "MIT" }, - "node_modules/big-integer": { - "version": "1.6.52", - "resolved": "https://registry.npmmirror.com/big-integer/-/big-integer-1.6.52.tgz", - "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", - "license": "Unlicense", - "engines": { - "node": ">=0.6" - } - }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmmirror.com/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -3507,12 +3491,6 @@ "url": "https://jaywcjlove.github.io/#/sponsor" } }, - "node_modules/commander": { - "version": "2.20.3", - "resolved": "https://registry.npmmirror.com/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "license": "MIT" - }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", @@ -3852,12 +3830,6 @@ "dev": true, "license": "MIT" }, - "node_modules/discontinuous-range": { - "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/discontinuous-range/-/discontinuous-range-1.0.0.tgz", - "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==", - "license": "MIT" - }, "node_modules/domain-browser": { "version": "4.22.0", "resolved": "https://registry.npmmirror.com/domain-browser/-/domain-browser-4.22.0.tgz", @@ -5340,12 +5312,6 @@ "pathe": "^2.0.1" } }, - "node_modules/moo": { - "version": "0.5.2", - "resolved": "https://registry.npmmirror.com/moo/-/moo-0.5.2.tgz", - "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==", - "license": "BSD-3-Clause" - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", @@ -5395,28 +5361,6 @@ "dev": true, "license": "MIT" }, - "node_modules/nearley": { - "version": "2.20.1", - "resolved": "https://registry.npmmirror.com/nearley/-/nearley-2.20.1.tgz", - "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==", - "license": "MIT", - "dependencies": { - "commander": "^2.19.0", - "moo": "^0.5.0", - "railroad-diagrams": "^1.0.0", - "randexp": "0.4.6" - }, - "bin": { - "nearley-railroad": "bin/nearley-railroad.js", - "nearley-test": "bin/nearley-test.js", - "nearley-unparse": "bin/nearley-unparse.js", - "nearleyc": "bin/nearleyc.js" - }, - "funding": { - "type": "individual", - "url": "https://nearley.js.org/#give-to-nearley" - } - }, "node_modules/node-addon-api": { "version": "7.1.1", "resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz", @@ -5432,19 +5376,6 @@ "optional": true, "peer": true }, - "node_modules/node-sql-parser": { - "version": "5.3.12", - "resolved": "https://registry.npmmirror.com/node-sql-parser/-/node-sql-parser-5.3.12.tgz", - "integrity": "sha512-GQBwA2e44qjbK0MzFwh5bNYefniV6cKT4KfjNDpuh/2EWipUEK1BCMc//moSidp8EF6fHB/EqJwUH9GCh9MAPg==", - "license": "Apache-2.0", - "dependencies": { - "@types/pegjs": "^0.10.0", - "big-integer": "^1.6.48" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/node-stdlib-browser": { "version": "1.3.1", "resolved": "https://registry.npmmirror.com/node-stdlib-browser/-/node-stdlib-browser-1.3.1.tgz", @@ -6103,25 +6034,6 @@ ], "license": "MIT" }, - "node_modules/railroad-diagrams": { - "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz", - "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==", - "license": "CC0-1.0" - }, - "node_modules/randexp": { - "version": "0.4.6", - "resolved": "https://registry.npmmirror.com/randexp/-/randexp-0.4.6.tgz", - "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==", - "license": "MIT", - "dependencies": { - "discontinuous-range": "1.0.0", - "ret": "~0.1.10" - }, - "engines": { - "node": ">=0.12" - } - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmmirror.com/randombytes/-/randombytes-2.1.0.tgz", @@ -6255,15 +6167,6 @@ "node": ">=4" } }, - "node_modules/ret": { - "version": "0.1.15", - "resolved": "https://registry.npmmirror.com/ret/-/ret-0.1.15.tgz", - "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", - "license": "MIT", - "engines": { - "node": ">=0.12" - } - }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz", @@ -6674,19 +6577,6 @@ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "license": "BSD-3-Clause" }, - "node_modules/sql-formatter": { - "version": "15.6.9", - "resolved": "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-15.6.9.tgz", - "integrity": "sha512-r9VKnkRfKW7jbhTgytwbM+JqmFclQYN9L58Z3UTktuy9V1f1Y+rGK3t70Truh2wIOJzvZkzobAQ2PwGjjXsr6Q==", - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1", - "nearley": "^2.20.1" - }, - "bin": { - "sql-formatter": "bin/sql-formatter-cli.cjs" - } - }, "node_modules/std-env": { "version": "3.9.0", "resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.9.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index ac9cd5e..a6d130d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -59,7 +59,6 @@ "jinx-rust": "^0.1.6", "jsox": "^1.2.123", "linguist-languages": "^9.0.0", - "node-sql-parser": "^5.3.12", "php-parser": "^3.2.5", "pinia": "^3.0.3", "pinia-plugin-persistedstate": "^4.5.0", @@ -67,7 +66,6 @@ "remarkable": "^2.0.1", "sass": "^1.92.1", "sh-syntax": "^0.5.8", - "sql-formatter": "^15.6.9", "vue": "^3.5.21", "vue-i18n": "^11.1.12", "vue-pick-colors": "^1.8.0", diff --git a/frontend/src/common/prettier/plugins/clang/index.ts b/frontend/src/common/prettier/plugins/clang/index.ts index 8ceb1cd..16361e0 100644 --- a/frontend/src/common/prettier/plugins/clang/index.ts +++ b/frontend/src/common/prettier/plugins/clang/index.ts @@ -1,23 +1,31 @@ /** - * Prettier Plugin for C/C++ formatting using clang-format WebAssembly + * Prettier Plugin for C/C++/C#/Java/Protobuf formatting using clang-format WebAssembly * - * This plugin provides support for formatting C/C++ files using the clang-format WASM implementation. - * It supports various C/C++ file extensions and common clang-format styles. + * This plugin provides support for formatting multiple languages using the clang-format WASM implementation. + * Supported languages: + * - C / C++ + * - Objective-C / Objective-C++ + * - C# + * - Java + * - Protocol Buffer (Protobuf) + * + * It supports various file extensions and common clang-format styles. */ import type { Plugin, Parser, Printer } from 'prettier'; // Import the clang-format WASM module import clangFormatInit, { format } from './clang-format-vite.js'; -const parserName = 'clang'; +const parserName = 'clang-format'; // Language configuration const languages = [ { name: 'C', aliases: ['c'], - parsers: [parserName], + parsers: ['c'], extensions: ['.c', '.h'], + filenames: ['*.c', '*.h'], aceMode: 'c_cpp', tmScope: 'source.c', linguistLanguageId: 50, @@ -26,8 +34,9 @@ const languages = [ { name: 'C++', aliases: ['cpp', 'cxx', 'cc'], - parsers: [parserName], + parsers: ['cpp'], extensions: ['.cpp', '.cxx', '.cc', '.hpp', '.hxx', '.hh', '.C', '.H'], + filenames: ['*.cpp', '*.cxx', '*.cc', '*.hpp', '*.hxx', '*.hh', '*.C', '*.H'], aceMode: 'c_cpp', tmScope: 'source.cpp', linguistLanguageId: 43, @@ -36,12 +45,57 @@ const languages = [ { name: 'Objective-C', aliases: ['objc', 'objectivec'], - parsers: [parserName], - extensions: ['.m', '.mm'], + parsers: ['objective-c'], + extensions: ['.m'], + filenames: ['*.m'], aceMode: 'objectivec', tmScope: 'source.objc', linguistLanguageId: 259, vscodeLanguageIds: ['objective-c'] + }, + { + name: 'Objective-C++', + aliases: ['objcpp', 'objectivecpp'], + parsers: ['objective-cpp'], + extensions: ['.mm'], + filenames: ['*.mm'], + aceMode: 'objectivec', + tmScope: 'source.objcpp', + linguistLanguageId: 260, + vscodeLanguageIds: ['objective-cpp'] + }, + { + name: 'C#', + aliases: ['csharp', 'cs'], + parsers: ['cs'], + extensions: ['.cs'], + filenames: ['*.cs'], + aceMode: 'csharp', + tmScope: 'source.cs', + linguistLanguageId: 42, + vscodeLanguageIds: ['csharp'] + }, + { + name: 'Java', + aliases: ['java'], + parsers: ['java'], + extensions: ['.java'], + filenames: ['*.java'], + aceMode: 'java', + tmScope: 'source.java', + linguistLanguageId: 181, + vscodeLanguageIds: ['java'] + }, + { + name: 'Protocol Buffer', + aliases: ['protobuf', 'proto'], + parsers: ['proto'], + extensions: ['.proto'], + filenames: ['*.proto'], + aceMode: 'protobuf', + tmScope: 'source.proto', + linguistLanguageId: 297, + vscodeLanguageIds: ['proto'] } ]; @@ -85,7 +139,7 @@ const clangPrinter: Printer = { const style = getClangStyle(options); // Format using clang-format (synchronous call) - const formatted = format(text, undefined, style); + const formatted = format(text, options.filename, style); return formatted.trim(); } catch (error) { @@ -129,6 +183,13 @@ const options = { { value: 'Microsoft', description: "Microsoft's style guide" }, { value: 'GNU', description: 'GNU coding standards' } ] + }, + filename: { + // since: '0.1.0', + category: 'Config', + type: 'string', + default: undefined, + description: 'Custom filename to use for web_fmt processing (affects language detection)', } }; @@ -141,7 +202,7 @@ const clangPlugin: Plugin = { printers: { [parserName]: clangPrinter, }, - options, + ...options, }; // Initialize WASM module when plugin loads diff --git a/frontend/src/common/prettier/plugins/clang/scripts/build.sh b/frontend/src/common/prettier/plugins/clang/scripts/build.sh new file mode 100644 index 0000000..0014eb5 --- /dev/null +++ b/frontend/src/common/prettier/plugins/clang/scripts/build.sh @@ -0,0 +1,44 @@ +set -Eeo pipefail + +cd $(dirname $0)/.. +project_root=$(pwd) + +rm -rf pkg +mkdir -p pkg build +cd build + +export CC=$(which clang) +export CXX=$(which clang++) + +emcmake cmake -G Ninja .. +ninja clang-format-wasm + +cd $project_root + +if [[ ! -z "${WASM_OPT}" ]]; then + wasm-opt -Os build/clang-format-esm.wasm -o build/clang-format-esm-Os.wasm + wasm-opt -Oz build/clang-format-esm.wasm -o build/clang-format-esm-Oz.wasm +fi + +SMALLEST_WASM=$(ls -Sr build/clang-format-e*.wasm | head -1) + +cp $SMALLEST_WASM pkg/clang-format.wasm +cat src/template.js build/clang-format-esm.js >pkg/clang-format.js + +# add shebang +echo '#!/usr/bin/env node' | cat - ./build/clang-format-cli.js >./pkg/clang-format-cli.cjs +cp ./build/clang-format-cli.wasm ./pkg/ + +cp ./src/clang-format.d.ts src/clang-format-*.js ./pkg/ +cp ./package.json LICENSE README.md .npmignore ./pkg/ + +# copy git-clang-format and clang-format-diff.py +cp ./build/_deps/llvm_project-src/clang/tools/clang-format/git-clang-format ./pkg/ +cp ./build/_deps/llvm_project-src/clang/tools/clang-format/clang-format-diff.py ./pkg/ + +ls -lh ./pkg + +./scripts/package.mjs ./package.json + +# make sure repo is clean +# git diff --exit-code diff --git a/frontend/src/common/prettier/plugins/clang/scripts/cli.patch b/frontend/src/common/prettier/plugins/clang/scripts/cli.patch new file mode 100644 index 0000000..aa60a50 --- /dev/null +++ b/frontend/src/common/prettier/plugins/clang/scripts/cli.patch @@ -0,0 +1,95 @@ +diff --git a/src/cli.cc b/src/cli.cc +index 2861005..69ec009 100644 +--- a/src/cli.cc ++++ b/src/cli.cc +@@ -12,7 +12,7 @@ + /// + //===----------------------------------------------------------------------===// + +-#include "../../lib/Format/MatchFilePath.h" ++#include "clang/../../lib/Format/MatchFilePath.h" + #include "clang/Basic/Diagnostic.h" + #include "clang/Basic/DiagnosticOptions.h" + #include "clang/Basic/FileManager.h" +@@ -27,6 +27,8 @@ + #include "llvm/Support/Process.h" + #include + ++#include "CustomFileSystem.h" ++ + using namespace llvm; + using clang::tooling::Replacements; + +@@ -448,9 +450,12 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) { + return true; + } + ++ auto RealFS = vfs::getRealFileSystem(); ++ auto CustomFS = new vfs::CustomFileSystem(RealFS); ++ IntrusiveRefCntPtr CustomFSPtr(CustomFS); + Expected FormatStyle = + getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer(), +- nullptr, WNoErrorList.isSet(WNoError::Unknown)); ++ CustomFSPtr.get(), WNoErrorList.isSet(WNoError::Unknown)); + if (!FormatStyle) { + llvm::errs() << toString(FormatStyle.takeError()) << "\n"; + return true; +@@ -571,10 +576,15 @@ static int dumpConfig() { + } + Code = std::move(CodeOrErr.get()); + } ++ ++ auto RealFS = vfs::getRealFileSystem(); ++ auto CustomFS = new vfs::CustomFileSystem(RealFS); ++ IntrusiveRefCntPtr CustomFSPtr(CustomFS); ++ + Expected FormatStyle = clang::format::getStyle( + Style, + FileNames.empty() || FileNames[0] == "-" ? AssumeFileName : FileNames[0], +- FallbackStyle, Code ? Code->getBuffer() : ""); ++ FallbackStyle, Code ? Code->getBuffer() : "", CustomFSPtr.get()); + if (!FormatStyle) { + llvm::errs() << toString(FormatStyle.takeError()) << "\n"; + return 1; +@@ -607,24 +617,26 @@ static bool isIgnored(StringRef FilePath) { + String Path; + String AbsPath{FilePath}; + ++ auto PathStyle = vfs::getPathStyle(); ++ + using namespace llvm::sys::path; +- make_absolute(AbsPath); +- remove_dots(AbsPath, /*remove_dot_dot=*/true); ++ vfs::make_absolute(AbsPath); ++ remove_dots(AbsPath, /*remove_dot_dot=*/true, PathStyle); + +- if (StringRef Dir{parent_path(AbsPath)}; PrevDir != Dir) { ++ if (StringRef Dir{parent_path(AbsPath, PathStyle)}; PrevDir != Dir) { + PrevDir = Dir; + + for (;;) { + Path = Dir; +- append(Path, ".clang-format-ignore"); ++ append(Path, PathStyle, ".clang-format-ignore"); + if (is_regular_file(Path)) + break; +- Dir = parent_path(Dir); ++ Dir = parent_path(Dir, PathStyle); + if (Dir.empty()) + return false; + } + +- IgnoreDir = convert_to_slash(Dir); ++ IgnoreDir = convert_to_slash(Dir, PathStyle); + + std::ifstream IgnoreFile{Path.c_str()}; + if (!IgnoreFile.good()) +@@ -644,7 +656,7 @@ static bool isIgnored(StringRef FilePath) { + if (IgnoreDir.empty()) + return false; + +- const auto Pathname{convert_to_slash(AbsPath)}; ++ const auto Pathname{convert_to_slash(AbsPath, PathStyle)}; + for (const auto &Pat : Patterns) { + const bool IsNegated = Pat[0] == '!'; + StringRef Pattern{Pat}; diff --git a/frontend/src/common/prettier/plugins/clang/scripts/gen_patch.sh b/frontend/src/common/prettier/plugins/clang/scripts/gen_patch.sh new file mode 100644 index 0000000..d929543 --- /dev/null +++ b/frontend/src/common/prettier/plugins/clang/scripts/gen_patch.sh @@ -0,0 +1,27 @@ +current_dir=$(pwd) +tmp_dir=$(mktemp -d) + +cd $tmp_dir + +git init + +cp $current_dir/build/_deps/llvm_project-src/clang/tools/clang-format/ClangFormat.cpp ./cli.cc + +git add -f . +git commit -m "init" + +cp $current_dir/src/cli.cc ./cli.cc + +git add -f . +git diff \ + --cached \ + --no-color \ + --ignore-space-at-eol \ + --no-ext-diff \ + --src-prefix=a/src/ \ + --dst-prefix=b/src/ \ + >$current_dir/scripts/cli.patch || true + +rm -rf $tmp_dir + + diff --git a/frontend/src/common/prettier/plugins/dart/extra/.npmignore b/frontend/src/common/prettier/plugins/dart/extra/.npmignore deleted file mode 100644 index 826d6ab..0000000 --- a/frontend/src/common/prettier/plugins/dart/extra/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -*.tgz -*.unopt.wasm -jsr.jsonc \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.d.ts b/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.d.ts deleted file mode 100644 index 5850092..0000000 --- a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -export function format(input: string, filename: string, config?: LayoutConfig): string; - -interface LayoutConfig { - line_width?: number; - line_ending?: "lf" | "crlf"; - language_version?: string; -} - -export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; - -export type InitOutput = unknown; - -// export type SyncInitInput = BufferSource | WebAssembly.Module; -// /** -// * Instantiates the given `module`, which can either be bytes or -// * a precompiled `WebAssembly.Module`. -// * -// * @param {SyncInitInput} module -// * -// * @returns {InitOutput} -// */ -// export function initSync(module: SyncInitInput): InitOutput; - -/** -* If `module_or_path` is {RequestInfo} or {URL}, makes a request and -* for everything else, calls `WebAssembly.instantiate` directly. -* -* @param {InitInput | Promise} module_or_path -* -* @returns {Promise} -*/ -export default function init(module_or_path?: InitInput | Promise): Promise; diff --git a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.js b/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.js deleted file mode 100644 index 57bf65b..0000000 --- a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt.js +++ /dev/null @@ -1,84 +0,0 @@ -import { format as dart_fmt, instantiate, invoke } from "./dart_fmt.mjs"; - -let wasm; - -function get_imports() {} -function init_memory() {} - -function normalize(module) { - if (!(module instanceof WebAssembly.Module)) { - return new WebAssembly.Module(module); - } - return module; -} - -export default async function (input) { - if (wasm !== undefined) return wasm; - - if (typeof input === "undefined") { - input = new URL("dart_fmt.wasm", import.meta.url); - } - const imports = get_imports(); - - if ( - typeof input === "string" || - (typeof Request === "function" && input instanceof Request) || - (typeof URL === "function" && input instanceof URL) - ) { - input = fetch(input); - } - - init_memory(imports); - - wasm = await load(await input) - .then(normalize) - .then(instantiate); - - invoke(wasm); - - return wasm; -} - -async function load(module) { - if (typeof Response === "function" && module instanceof Response) { - if ("compileStreaming" in WebAssembly) { - try { - return await WebAssembly.compileStreaming(module); - } catch (e) { - if (module.headers.get("Content-Type") != "application/wasm") { - console.warn( - "`WebAssembly.compileStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", - e, - ); - } else { - throw e; - } - } - } - - return module.arrayBuffer(); - } - - return module; -} - -export function format(source, filename = "stdin.dart", config = {}) { - const options = { lineEnding: "\n" }; - if (config.line_width) { - options.pageWidth = config.line_width; - } - if (options.line_ending === "crlf") { - options.lineEnding = "\r\n"; - } - if(options.language_version) { - options.languageVersion = options.language_version; - } - - const result = dart_fmt(source, filename, JSON.stringify(options)); - const err = result[0] === "x"; - const output = result.slice(1); - if (err) { - throw new Error(output); - } - return output; -} diff --git a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_node.js b/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_node.js deleted file mode 100644 index 1d809ae..0000000 --- a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_node.js +++ /dev/null @@ -1,10 +0,0 @@ -import fs from "node:fs/promises"; -import initAsync from "./dart_fmt.js"; - -const wasm = new URL("./dart_fmt.wasm", import.meta.url); - -export default function __wbg_init(init = fs.readFile(wasm)) { - return initAsync(init); -} - -export * from "./dart_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_vite.js b/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_vite.js deleted file mode 100644 index 070451c..0000000 --- a/frontend/src/common/prettier/plugins/dart/extra/dart_fmt_vite.js +++ /dev/null @@ -1,8 +0,0 @@ -import initAsync from "./dart_fmt.js"; -import wasm from "./dart_fmt.wasm?url"; - -export default function __wbg_init(input = wasm) { - return initAsync(input); -} - -export * from "./dart_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/dart/index.ts b/frontend/src/common/prettier/plugins/dart/index.ts index a8625f7..040984d 100644 --- a/frontend/src/common/prettier/plugins/dart/index.ts +++ b/frontend/src/common/prettier/plugins/dart/index.ts @@ -62,11 +62,10 @@ const dartPrinter: Printer = { } const text = (path as any).getValue ? (path as any).getValue() : path.node; - const filename = getDartFilename(options.filepath); const config = getDartConfig(options); // Format using dart_fmt (synchronous call) - const formatted = format(text, filename, config); + const formatted = format(text, undefined, config); return formatted.trim(); } catch (error) { @@ -77,21 +76,6 @@ const dartPrinter: Printer = { }, }; -// Helper function to get appropriate filename for dart_fmt -function getDartFilename(filepath?: string): string { - if (!filepath) { - return 'stdin.dart'; - } - - const filename = filepath.split(/[/\\]/).pop() || 'main.dart'; - - // Ensure .dart extension - if (!filename.endsWith('.dart')) { - return 'main.dart'; - } - - return filename; -} // Helper function to create Dart config from Prettier options function getDartConfig(options: any): any { diff --git a/frontend/src/common/prettier/plugins/dart/lib/build.sh b/frontend/src/common/prettier/plugins/dart/lib/build.sh new file mode 100644 index 0000000..07da5f8 --- /dev/null +++ b/frontend/src/common/prettier/plugins/dart/lib/build.sh @@ -0,0 +1,5 @@ +cd $(dirname $0)/.. + +dart compile wasm ./lib/binding.dart -o ./build/dart_fmt.wasm + + diff --git a/frontend/src/common/prettier/plugins/dart/scripts/build.sh b/frontend/src/common/prettier/plugins/dart/scripts/build.sh deleted file mode 100644 index 86a8ce9..0000000 --- a/frontend/src/common/prettier/plugins/dart/scripts/build.sh +++ /dev/null @@ -1,7 +0,0 @@ -cd $(dirname $0)/.. - -dart compile wasm ./lib/binding.dart -o ./build/dart_fmt.wasm -cp -LR ./extra/. ./build/ - -./scripts/patch.mjs ./build/dart_fmt.mjs -./scripts/package.mjs ./package.json diff --git a/frontend/src/common/prettier/plugins/dart/scripts/package.mjs b/frontend/src/common/prettier/plugins/dart/scripts/package.mjs deleted file mode 100644 index 210f62d..0000000 --- a/frontend/src/common/prettier/plugins/dart/scripts/package.mjs +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -import process from "node:process"; -import path from "node:path"; -import fs from "node:fs"; - -const pkg_path = path.resolve(process.cwd(), process.argv[2]); -const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" }); -const pkg_json = JSON.parse(pkg_text); - -// JSR - -const jsr_path = path.resolve(pkg_path, "..", "build", "jsr.jsonc"); -pkg_json.name = "@fmt/dart-fmt"; -pkg_json.exports = "./dart_fmt.js"; -pkg_json.exclude = ["!../build", "*.tgz", ".npmignore"]; -fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4)); diff --git a/frontend/src/common/prettier/plugins/dart/scripts/patch.mjs b/frontend/src/common/prettier/plugins/dart/scripts/patch.mjs deleted file mode 100644 index 39c50a2..0000000 --- a/frontend/src/common/prettier/plugins/dart/scripts/patch.mjs +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env node -import process from "node:process"; -import path from "node:path"; -import fs from "node:fs"; - -const file_path = path.resolve(process.cwd(), process.argv[2]); -let file_text = fs.readFileSync(file_path, { encoding: "utf-8" }); - -file_text = file_text.replace(`"length": (s) => s.length`, '"length": (s) => s?.length||0'); -file_text = file_text.replace('globalThis.format', 'format'); -file_text += "\nexport let format;"; - -fs.writeFileSync(file_path, file_text); \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/lua/extra/.npmignore b/frontend/src/common/prettier/plugins/lua/extra/.npmignore deleted file mode 100644 index 1ee7305..0000000 --- a/frontend/src/common/prettier/plugins/lua/extra/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.tgz -jsr.jsonc \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_node.js b/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_node.js deleted file mode 100644 index 8828ec5..0000000 --- a/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_node.js +++ /dev/null @@ -1,10 +0,0 @@ -import fs from "node:fs/promises"; -import initAsync from "./lua_fmt.js"; - -const wasm = new URL("./lua_fmt_bg.wasm", import.meta.url); - -export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) { - return initAsync(init); -} - -export * from "./lua_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_vite.js b/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_vite.js deleted file mode 100644 index 770a144..0000000 --- a/frontend/src/common/prettier/plugins/lua/extra/lua_fmt_vite.js +++ /dev/null @@ -1,8 +0,0 @@ -import initAsync from "./lua_fmt.js"; -import wasm from "./lua_fmt_bg.wasm?url"; - -export default function __wbg_init(input = { module_or_path: wasm }) { - return initAsync(input); -} - -export * from "./lua_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/lua/scripts/package.mjs b/frontend/src/common/prettier/plugins/lua/scripts/package.mjs deleted file mode 100644 index d1452f8..0000000 --- a/frontend/src/common/prettier/plugins/lua/scripts/package.mjs +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env node -import process from "node:process"; -import path from "node:path"; -import fs from "node:fs"; - -const pkg_path = path.resolve(process.cwd(), process.argv[2]); -const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" }); -const pkg_json = JSON.parse(pkg_text); - -delete pkg_json.files; - -pkg_json.main = pkg_json.module; -pkg_json.type = "module"; -pkg_json.publishConfig = { - access: "public", -}; -pkg_json.exports = { - ".": { - types: "./lua_fmt.d.ts", - node: "./lua_fmt_node.js", - default: "./lua_fmt.js", - }, - "./vite": { - types: "./lua_fmt.d.ts", - default: "./lua_fmt_vite.js", - }, - "./package.json": "./package.json", - "./*": "./*", -}; - -fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4)); - -// JSR - -const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc"); -pkg_json.name = "@fmt/lua-fmt"; -pkg_json.exports = "./lua_fmt.js"; -pkg_json.exclude = ["!**", "*.tgz"]; -fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4)); diff --git a/frontend/src/common/prettier/plugins/lua/scripts/build.sh b/frontend/src/common/prettier/plugins/lua/src/build.sh similarity index 57% rename from frontend/src/common/prettier/plugins/lua/scripts/build.sh rename to frontend/src/common/prettier/plugins/lua/src/build.sh index de4317b..00af102 100644 --- a/frontend/src/common/prettier/plugins/lua/scripts/build.sh +++ b/frontend/src/common/prettier/plugins/lua/src/build.sh @@ -4,8 +4,3 @@ crates_dir=$(pwd) cd ../.. wasm-pack build --target=web --scope=wasm-fmt crates/lua_fmt -cd $crates_dir - -cp -R ./extra/. ./pkg/ - -./scripts/package.mjs ./pkg/package.json diff --git a/frontend/src/common/prettier/plugins/sql/detect.mjs b/frontend/src/common/prettier/plugins/sql/detect.mjs deleted file mode 100644 index 297e306..0000000 --- a/frontend/src/common/prettier/plugins/sql/detect.mjs +++ /dev/null @@ -1,1180 +0,0 @@ -// SQL方言特征检测规则 -const dialectPatterns = { - mysql: [ - /\bAUTO_INCREMENT\b/i, - /\bENGINE\s*=/i, - /\bCHARSET\s*=/i, - /\bCOLLATE\s*=/i, - /\bLIMIT\s+\d+\s*OFFSET\s+\d+/i, - /\bUNSIGNED\b/i, - /\bTINYINT\b/i, - /\bMEDIUMINT\b/i, - /\bBIGINT\b/i, - /\bTEXT\b/i, - /\bLONGTEXT\b/i, - /\bMEDIUMTEXT\b/i, - /\bTINYTEXT\b/i, - /\bENUM\s*\(/i, - /\bSET\s*\(/i, - /\bIF\s*\(/i, - /\bIFNULL\s*\(/i, - /\bCONCAT\s*\(/i, - /\bGROUP_CONCAT\s*\(/i, - /\bDATE_FORMAT\s*\(/i, - /\bSTR_TO_DATE\s*\(/i, - /\bUNIX_TIMESTAMP\s*\(/i, - /\bFROM_UNIXTIME\s*\(/i, - /\bINSERT\s+IGNORE\b/i, - /\bREPLACE\s+INTO\b/i, - /\bON\s+DUPLICATE\s+KEY\s+UPDATE\b/i - ], - - postgresql: [ - /\bSERIAL\b/i, - /\bBIGSERIAL\b/i, - /\bSMALLSERIAL\b/i, - /\bBOOLEAN\b/i, - /\bTEXT\[\]/i, - /\bINTEGER\[\]/i, - /\bJSONB\b/i, - /\bUUID\b/i, - /\bINET\b/i, - /\bCIDR\b/i, - /\bMACaddr\b/i, - /\bTSVECTOR\b/i, - /\bTSQUERY\b/i, - /\bPOINT\b/i, - /\bLINE\b/i, - /\bLSEG\b/i, - /\bBOX\b/i, - /\bPATH\b/i, - /\bPOLYGON\b/i, - /\bCIRCLE\b/i, - /\bLIMIT\s+\d+\s+OFFSET\s+\d+/i, - /\bRETURNING\b/i, - /\bON\s+CONFLICT\b/i, - /\bDO\s+NOTHING\b/i, - /\bDO\s+UPDATE\s+SET\b/i, - /\bFETCH\s+FIRST\b/i, - /\bFETCH\s+NEXT\b/i, - /\bROWS\s+ONLY\b/i, - /\bWITH\s+RECURSIVE\b/i, - /\bARRAY\s*\[/i, - /\bUNNEST\s*\(/i, - /\bSTRING_AGG\s*\(/i, - /\bEXTRACT\s*\(/i, - /\bGENERATE_SERIES\s*\(/i, - /\bCOALESCE\s*\(/i, - /\bNULLIF\s*\(/i, - /\bAGE\s*\(/i, - /\bNOW\s*\(\s*\)/i, - /\bCURRENT_TIMESTAMP\b/i, - /\bCURRENT_DATE\b/i, - /\bCURRENT_TIME\b/i, - /\bINTERVAL\s+'/i, - /\bREGEXP_REPLACE\s*\(/i, - /\bREGEXP_SPLIT_TO_ARRAY\s*\(/i, - /\b\$\$[^$]*\$\$/i, - /\bCREATE\s+EXTENSION\b/i, - /\bCREATE\s+OR\s+REPLACE\s+FUNCTION\b/i, - /\bCREATE\s+OR\s+REPLACE\s+VIEW\b/i, - /\bPLPGSQL\b/i, - /\bTABLESPACE\b/i, - /\bSCHEMA\b/i - ], - - sqlite: [ - /\bPRAGMA\b/i, - /\bAUTOINCREMENT\b/i, - /\bWITHOUT\s+ROWID\b/i, - /\bSTRICT\b/i, - /\bIF\s+NOT\s+EXISTS\b/i, - /\bREPLACE\b/i, - /\bVACUUM\b/i, - /\bREINDEX\b/i, - /\bANALYZE\b/i, - /\bATTACH\s+DATABASE\b/i, - /\bDETACH\s+DATABASE\b/i, - /\bTEMP\b/i, - /\bTEMPORARY\b/i, - /\bBEGIN\s+IMMEDIATE\b/i, - /\bBEGIN\s+EXCLUSIVE\b/i, - /\bEXPLAIN\s+QUERY\s+PLAN\b/i, - /\bRANDOM\s*\(\s*\)/i, - /\bLENGTH\s*\(/i, - /\bSUBSTR\s*\(/i, - /\bREPLACE\s*\(/i, - /\bTRIM\s*\(/i, - /\bLTRIM\s*\(/i, - /\bRTRIM\s*\(/i, - /\bUPPER\s*\(/i, - /\bLOWER\s*\(/i, - /\bINSTR\s*\(/i, - /\bROUND\s*\(/i, - /\bABS\s*\(/i, - /\bMAX\s*\(/i, - /\bMIN\s*\(/i, - /\bDATE\s*\(/i, - /\bTIME\s*\(/i, - /\bDATETIME\s*\(/i, - /\bJULIANDAY\s*\(/i, - /\bSTRFTIME\s*\(/i, - /\bGLOB\s*\(/i, - /\bLIKE\s*\(/i, - /\bCAST\s*\(/i, - /\bTYPEOF\s*\(/i - ], - - transactsql: [ - /\bIDENTITY\s*\(/i, - /\bUNIQUEIDENTIFIER\b/i, - /\bNVARCHAR\b/i, - /\bNTEXT\b/i, - /\bNUMERIC\b/i, - /\bSMALLDATETIME\b/i, - /\bDATETIME2\b/i, - /\bDATETIMEOFFSET\b/i, - /\bTIME\b/i, - /\bIMAGE\b/i, - /\bMONEY\b/i, - /\bSMALLMONEY\b/i, - /\bSQL_VARIANT\b/i, - /\bTABLE\b/i, - /\bXML\b/i, - /\bGEOMETRY\b/i, - /\bGEOGRAPHY\b/i, - /\bTOP\s+\d+/i, - /\bPERCENT\b/i, - /\bWITH\s+TIES\b/i, - /\bOFFSET\s+\d+\s+ROWS/i, - /\bFETCH\s+NEXT\s+\d+\s+ROWS\s+ONLY/i, - /\bISNULL\s*\(/i, - /\bCONVERT\s*\(/i, - /\bCAST\s*\(/i, - /\bDATEDIFF\s*\(/i, - /\bDATEADD\s*\(/i, - /\bDATEPART\s*\(/i, - /\bGETDATE\s*\(\s*\)/i, - /\bGETUTCDATE\s*\(\s*\)/i, - /\bSYSDATETIME\s*\(\s*\)/i, - /\bSYSUTCDATETIME\s*\(\s*\)/i, - /\bCURRENT_TIMESTAMP\b/i, - /\bLEN\s*\(/i, - /\bLEFT\s*\(/i, - /\bRIGHT\s*\(/i, - /\bCHARINDEX\s*\(/i, - /\bPATINDEX\s*\(/i, - /\bSTUFF\s*\(/i, - /\bREVERSE\s*\(/i, - /\bREPLICATE\s*\(/i, - /\bSPACE\s*\(/i, - /\bSTR\s*\(/i, - /\bFORMAT\s*\(/i, - /\bPARSENAME\s*\(/i, - /\bQUOTENAME\s*\(/i, - /\bMERGE\b/i, - /\bWHEN\s+MATCHED\b/i, - /\bWHEN\s+NOT\s+MATCHED\b/i, - /\bUSING\b/i, - /\bOUTPUT\b/i, - /\bINSERTED\b/i, - /\bDELETED\b/i, - /\bTRUNCATE\s+TABLE\b/i, - /\bEXEC\b/i, - /\bEXECUTE\b/i, - /\bSP_EXECUTESQL\b/i, - /\bBEGIN\s+TRAN\b/i, - /\bCOMMIT\s+TRAN\b/i, - /\bROLLBACK\s+TRAN\b/i, - /\bSAVE\s+TRAN\b/i, - /\bTRY\b/i, - /\bCATCH\b/i, - /\bTHROW\b/i, - /\bRAISERROR\b/i, - /\bPRINT\b/i, - /\bSET\s+NOCOUNT\s+ON\b/i, - /\bSET\s+ANSI_NULLS\s+ON\b/i, - /\bSET\s+QUOTED_IDENTIFIER\s+ON\b/i, - /\bWITH\s+\(\s*NOLOCK\s*\)/i, - /\bROW_NUMBER\s*\(\s*\)\s+OVER\s*\(/i, - /\bRANK\s*\(\s*\)\s+OVER\s*\(/i, - /\bDENSE_RANK\s*\(\s*\)\s+OVER\s*\(/i, - /\bNTILE\s*\(/i, - /\bLAG\s*\(/i, - /\bLEAD\s*\(/i, - /\bFIRST_VALUE\s*\(/i, - /\bLAST_VALUE\s*\(/i, - /\bCTE\b/i, - /\bPIVOT\b/i, - /\bUNPIVOT\b/i, - /\bAPPLY\b/i, - /\bOUTER\s+APPLY\b/i, - /\bCROSS\s+APPLY\b/i - ], - - bigquery: [ - /\bSTRUCT\s*/i, - /\bBEFORE\s*\(\s*TIMESTAMP\s*=>/i, - /\bQUALIFY\b/i, - /\bMINUS\b/i, - /\bCONCAT\s*\(/i, - /\bCONCAT_WS\s*\(/i, - /\bSPLIT\s*\(/i, - /\bSPLIT_PART\s*\(/i, - /\bSTARTSWITH\s*\(/i, - /\bENDSWITH\s*\(/i, - /\bCONTAINS\s*\(/i, - /\bTRY_CAST\s*\(/i, - /\bTRY_TO_NUMBER\s*\(/i, - /\bTRY_TO_DECIMAL\s*\(/i, - /\bTRY_TO_DATE\s*\(/i, - /\bTRY_TO_TIME\s*\(/i, - /\bTRY_TO_TIMESTAMP\s*\(/i, - /\bTRY_TO_BINARY\s*\(/i, - /\bPARSE_JSON\s*\(/i, - /\bPARSE_XML\s*\(/i, - /\bTRY_PARSE_JSON\s*\(/i, - /\bCHECK_JSON\s*\(/i, - /\bCHECK_XML\s*\(/i, - /\bSTRIP_NULL_VALUE\s*\(/i, - /\bOBJECT_CONSTRUCT\s*\(/i, - /\bOBJECT_CONSTRUCT_KEEP_NULL\s*\(/i, - /\bOBJECT_DELETE\s*\(/i, - /\bOBJECT_INSERT\s*\(/i, - /\bOBJECT_PICK\s*\(/i, - /\bARRAY_CONSTRUCT\s*\(/i, - /\bARRAY_CONSTRUCT_COMPACT\s*\(/i, - /\bARRAY_APPEND\s*\(/i, - /\bARRAY_CAT\s*\(/i, - /\bARRAY_COMPACT\s*\(/i, - /\bARRAY_CONTAINS\s*\(/i, - /\bARRAY_DISTINCT\s*\(/i, - /\bARRAY_EXCEPT\s*\(/i, - /\bARRAY_FLATTEN\s*\(/i, - /\bARRAY_GENERATE_RANGE\s*\(/i, - /\bARRAY_INSERT\s*\(/i, - /\bARRAY_INTERSECTION\s*\(/i, - /\bARRAY_POSITION\s*\(/i, - /\bARRAY_PREPEND\s*\(/i, - /\bARRAY_REMOVE\s*\(/i, - /\bARRAY_REMOVE_AT\s*\(/i, - /\bARRAY_SIZE\s*\(/i, - /\bARRAY_SLICE\s*\(/i, - /\bARRAY_SORT\s*\(/i, - /\bARRAY_TO_STRING\s*\(/i, - /\bARRAY_UNION\s*\(/i, - /\bARRAY_UNIQUE_AGG\s*\(/i, - /\bGET\s*\(/i, - /\bGET_PATH\s*\(/i, - /\bFLATTEN\s*\(/i, - /\bCURRENT_AVAILABLE_ROLES\s*\(\s*\)/i, - /\bCURRENT_CLIENT\s*\(\s*\)/i, - /\bCURRENT_DATABASE\s*\(\s*\)/i, - /\bCURRENT_REGION\s*\(\s*\)/i, - /\bCURRENT_ROLE\s*\(\s*\)/i, - /\bCURRENT_SCHEMA\s*\(\s*\)/i, - /\bCURRENT_SCHEMAS\s*\(\s*\)/i, - /\bCURRENT_SESSION\s*\(\s*\)/i, - /\bCURRENT_STATEMENT\s*\(\s*\)/i, - /\bCURRENT_TIME\s*\(\s*\)/i, - /\bCURRENT_TIMESTAMP\s*\(\s*\)/i, - /\bCURRENT_TRANSACTION\s*\(\s*\)/i, - /\bCURRENT_USER\s*\(\s*\)/i, - /\bCURRENT_VERSION\s*\(\s*\)/i, - /\bCURRENT_WAREHOUSE\s*\(\s*\)/i, - /\bLOCALTIME\s*\(\s*\)/i, - /\bLOCALTIMESTAMP\s*\(\s*\)/i, - /\bSYSDATE\s*\(\s*\)/i, - /\bGETDATE\s*\(\s*\)/i, - /\bLAST_DAY\s*\(/i, - /\bNEXT_DAY\s*\(/i, - /\bPREVIOUS_DAY\s*\(/i, - /\bDATE_FROM_PARTS\s*\(/i, - /\bTIME_FROM_PARTS\s*\(/i, - /\bTIMESTAMP_FROM_PARTS\s*\(/i, - /\bDAYNAME\s*\(/i, - /\bMONTHNAME\s*\(/i, - /\bQUARTER\s*\(/i, - /\bYEAROFWEEK\s*\(/i, - /\bYEAROFWEEKISO\s*\(/i, - /\bWEEKOFYEAR\s*\(/i, - /\bWEEKISO\s*\(/i, - /\bDAYOFWEEK\s*\(/i, - /\bDAYOFWEEKISO\s*\(/i, - /\bDAYOFYEAR\s*\(/i, - /\bHOUR\s*\(/i, - /\bMINUTE\s*\(/i, - /\bSECOND\s*\(/i, - /\bNANOSECOND\s*\(/i, - /\bEPOCH_SECOND\s*\(/i, - /\bEPOCH_MILLISECOND\s*\(/i, - /\bEPOCH_MICROSECOND\s*\(/i, - /\bEPOCH_NANOSECOND\s*\(/i, - /\bTIMEZONE_HOUR\s*\(/i, - /\bTIMEZONE_MINUTE\s*\(/i, - /\bISO_WEEK_START\s*\(/i, - /\bISO_WEEK_END\s*\(/i, - /\bWEEK_START\s*\(/i, - /\bWEEK_END\s*\(/i, - /\bISO_YEAR_START\s*\(/i, - /\bISO_YEAR_END\s*\(/i, - /\bYEAR_START\s*\(/i, - /\bYEAR_END\s*\(/i, - /\bCONVERT_TIMEZONE\s*\(/i, - /\bIFF\s*\(/i, - /\bZEROIFNULL\s*\(/i, - /\bNULLIFZERO\s*\(/i, - /\bEQUAL_NULL\s*\(/i, - /\bBOOLAND\s*\(/i, - /\bBOOLOR\s*\(/i, - /\bBOOLXOR\s*\(/i, - /\bBOOLNOT\s*\(/i, - /\bMODE\s*\(/i, - /\bUNIFORM\s*\(/i, - /\bNORMAL\s*\(/i, - /\bSEQ1\s*\(\s*\)/i, - /\bSEQ2\s*\(\s*\)/i, - /\bSEQ4\s*\(\s*\)/i, - /\bSEQ8\s*\(\s*\)/i, - /\bUUID_STRING\s*\(\s*\)/i, - /\bRANDOM\s*\(\s*\)/i, - /\bRRANDOM\s*\(/i, - /\bZIPF\s*\(/i, - /\bHASH\s*\(/i, - /\bSHA1\s*\(/i, - /\bSHA1_HEX\s*\(/i, - /\bSHA1_BINARY\s*\(/i, - /\bSHA2\s*\(/i, - /\bSHA2_HEX\s*\(/i, - /\bSHA2_BINARY\s*\(/i, - /\bMD5\s*\(/i, - /\bMD5_HEX\s*\(/i, - /\bMD5_BINARY\s*\(/i, - /\bMD5_NUMBER\s*\(/i, - /\bMD5_NUMBER_LOWER64\s*\(/i, - /\bMD5_NUMBER_UPPER64\s*\(/i, - /\bBASE64_ENCODE\s*\(/i, - /\bBASE64_DECODE_STRING\s*\(/i, - /\bBASE64_DECODE_BINARY\s*\(/i, - /\bHEX_ENCODE\s*\(/i, - /\bHEX_DECODE_STRING\s*\(/i, - /\bHEX_DECODE_BINARY\s*\(/i, - /\bTRY_BASE64_DECODE_STRING\s*\(/i, - /\bTRY_BASE64_DECODE_BINARY\s*\(/i, - /\bTRY_HEX_DECODE_STRING\s*\(/i, - /\bTRY_HEX_DECODE_BINARY\s*\(/i, - /\bCOMPRESS\s*\(/i, - /\bDECOMPRESS_STRING\s*\(/i, - /\bDECOMPRESS_BINARY\s*\(/i - ], - - mariadb: [ - // MariaDB specific features (extends MySQL) - /\bSEQUENCE\b/i, - /\bROLE\b/i, - /\bCOLUMN_CHECK\s*\(/i, - /\bCOLUMN_GET\s*\(/i, - /\bCOLUMN_JSON\s*\(/i, - /\bDYNAMIC_COLUMN_\w+\s*\(/i, - /\bJSON_ARRAY\s*\(/i, - /\bJSON_ARRAYAGG\s*\(/i, - /\bJSON_OBJECT\s*\(/i, - /\bJSON_OBJECTAGG\s*\(/i, - /\bJSON_EXTRACT\s*\(/i, - /\bJSON_UNQUOTE\s*\(/i, - /\bJSON_VALID\s*\(/i, - /\bGIS\b/i, - /\bSPIDER\b/i, - /\bCONNECT\s+ENGINE\b/i, - /\bFEDERATEDX\b/i, - /\bCONNECTION\s*=/i, - /\bVIRTUAL\s+COLUMN\b/i, - /\bSTORED\s+COLUMN\b/i, - /\bGENERATED\s+ALWAYS\b/i, - /\bAUTO_INCREMENT\b/i, - /\bENGINE\s*=/i, - /\bCHARSET\s*=/i, - /\bCOLLATE\s*=/i - ], - - db2: [ - // IBM DB2 specific features - /\bIDENTITY\s*\(\s*START\s+WITH\b/i, - /\bGENERATED\s+ALWAYS\b/i, - /\bGENERATED\s+BY\s+DEFAULT\b/i, - /\bDECLARE\s+GLOBAL\s+TEMPORARY\s+TABLE\b/i, - /\bFINAL\s+TABLE\b/i, - /\bNEW\s+TABLE\b/i, - /\bOLD\s+TABLE\b/i, - /\bDECFLOAT\b/i, - /\bBIGINT\b/i, - /\bSMALLINT\b/i, - /\bREAL\b/i, - /\bDOUBLE\b/i, - /\bGRAPHIC\s*\(/i, - /\bVARGRAPHIC\s*\(/i, - /\bDBCLOB\s*\(/i, - /\bXML\b/i, - /\bROWID\b/i, - /\bDATE\b/i, - /\bTIME\b/i, - /\bTIMESTAMP\b/i, - /\bVALUES\s+NEXTVAL\s+FOR\b/i, - /\bVALUES\s+PREVVAL\s+FOR\b/i, - /\bFETCH\s+FIRST\s+\d+\s+ROWS\s+ONLY\b/i, - /\bFETCH\s+NEXT\s+\d+\s+ROWS\s+ONLY\b/i, - /\bROW\s+CHANGE\s+TIMESTAMP\b/i, - /\bROW\s+BEGIN\b/i, - /\bROW\s+END\b/i, - /\bSYSTEM_TIME\b/i, - /\bBUSINESS_TIME\b/i, - /\bVERSIONING\b/i, - /\bWITH\s+ORDINALITY\b/i, - /\bLATERAL\b/i, - /\bOVER\s*\(\s*PARTITION\s+BY\b/i, - /\bRANKING\b/i, - /\bAGGREGATION\b/i, - /\bNUMBERING\b/i - ], - - db2i: [ - // IBM DB2 for i specific features (AS/400) - /\bAS\/400\b/i, - /\biSeries\b/i, - /\bSYSTEM\s+i\b/i, - /\bQSYS\b/i, - /\bQTEMP\b/i, - /\bRCDFMT\b/i, - /\bDATA\s+AREA\b/i, - /\bJOURNAL\b/i, - /\bJRNL\b/i, - /\bLIBRARY\b/i, - /\bSCHEMA\b/i, - /\bCOLLECTION\b/i, - /\bMEMBER\b/i, - /\bFILE\b/i, - /\bRECORD\b/i, - /\bFIELD\b/i, - /\bKEYWORD\b/i, - /\bVALUES\b/i, - /\bRUNSQLSTM\b/i, - /\bSTRSQL\b/i, - /\bINTERACTIVE\s+SQL\b/i, - /\bSQL\s+REQUEST\b/i, - /\bSQL\s+PACKAGE\b/i, - /\bBINDING\b/i, - /\bACCESS\s+PLAN\b/i, - /\bOPTIMIZATION\b/i, - /\bSTAT_VIEW\b/i, - /\bMQT\b/i, - /\bMATERIALIZED\s+QUERY\s+TABLE\b/i, - /\bREFRESH\s+DEFERRED\b/i, - /\bREFRESH\s+IMMEDIATE\b/i, - /\bENABLE\s+QUERY\s+OPTIMIZATION\b/i, - /\bDISABLE\s+QUERY\s+OPTIMIZATION\b/i - ], - - hive: [ - // Apache Hive specific features - /\bPARTITIONED\s+BY\b/i, - /\bCLUSTERED\s+BY\b/i, - /\bSORTED\s+BY\b/i, - /\bINTO\s+\d+\s+BUCKETS\b/i, - /\bSTORED\s+AS\s+ORC\b/i, - /\bSTORED\s+AS\s+PARQUET\b/i, - /\bSTORED\s+AS\s+AVRO\b/i, - /\bSTORED\s+AS\s+RCFILE\b/i, - /\bSTORED\s+AS\s+SEQUENCEFILE\b/i, - /\bSTORED\s+AS\s+TEXTFILE\b/i, - /\bROW\s+FORMAT\s+SERDE\b/i, - /\bINPUTFORMAT\b/i, - /\bOUTPUTFORMAT\b/i, - /\bLOCATION\s+'/i, - /\bTBLPROPERTIES\s*\(/i, - /\bSERDEPROPERTIES\s*\(/i, - /\bADD\s+JAR\b/i, - /\bADD\s+FILE\b/i, - /\bADD\s+ARCHIVE\b/i, - /\bTRANSFORM\b/i, - /\bUSING\s+'/i, - /\bAS\s+\(/i, - /\bLATERAL\s+VIEW\b/i, - /\bEXPLODE\s*\(/i, - /\bPOSEXPLODE\s*\(/i, - /\bINLINE\s*\(/i, - /\bSTACK\s*\(/i, - /\bJSON_TUPLE\s*\(/i, - /\bPARSE_URL\s*\(/i, - /\bPARSE_URL_TUPLE\s*\(/i, - /\bXPATH\s*\(/i, - /\bXPATH_STRING\s*\(/i, - /\bXPATH_BOOLEAN\s*\(/i, - /\bXPATH_NUMBER\s*\(/i, - /\bXPATH_DOUBLE\s*\(/i, - /\bXPATH_FLOAT\s*\(/i, - /\bXPATH_INT\s*\(/i, - /\bXPATH_LONG\s*\(/i, - /\bXPATH_SHORT\s*\(/i, - /\bGET_JSON_OBJECT\s*\(/i, - /\bSTR_TO_MAP\s*\(/i, - /\bSENTENCES\s*\(/i, - /\bNGRAMS\s*\(/i, - /\bCONTEXT_NGRAMS\s*\(/i, - /\bWORDCOUNT\s*\(/i, - /\bCOLLECT_LIST\s*\(/i, - /\bCOLLECT_SET\s*\(/i, - /\bHISTOGRAM_NUMERIC\s*\(/i, - /\bPERCENTILE\s*\(/i, - /\bPERCENTILE_APPROX\s*\(/i, - /\bUDTF\b/i, - /\bUDAF\b/i, - /\bUDF\b/i, - /\bMAP\s* highestScore) { - bestDialect = dialect; - highestScore = score; - } - } - - // 如果没有明显的特征,尝试通用检测 - if (highestScore === 0) { - return detectGenericFeatures(normalizedSql); - } - - return bestDialect; -} - -/** - * 通用特征检测 - * @param {string} sql - SQL语句 - * @returns {string} - 检测到的SQL方言 - */ -function detectGenericFeatures(sql) { - const upperSql = sql.toUpperCase(); - - // 检测一些通用但有倾向性的特征 - if (upperSql.includes('LIMIT') && upperSql.includes('OFFSET')) { - if (upperSql.includes('AUTO_INCREMENT') || upperSql.includes('ENGINE=')) { - return 'mysql'; - } - return 'postgresql'; - } - - if (upperSql.includes('TOP ') && (upperSql.includes('IDENTITY') || upperSql.includes('NVARCHAR'))) { - return 'transactsql'; - } - - if (upperSql.includes('ROWNUM') || upperSql.includes('DUAL')) { - return 'plsql'; - } - - if (upperSql.includes('PRAGMA') || upperSql.includes('AUTOINCREMENT')) { - return 'sqlite'; - } - - if (upperSql.includes('STRUCT<') || upperSql.includes('ARRAY<')) { - return 'bigquery'; - } - - if (upperSql.includes('VARIANT') || upperSql.includes('$1') || upperSql.includes('QUALIFY')) { - return 'snowflake'; - } - - if (upperSql.includes('PARTITIONED BY') || upperSql.includes('STORED AS ORC') || upperSql.includes('LATERAL VIEW')) { - return 'hive'; - } - - if (upperSql.includes('USE KEYS') || upperSql.includes('UNNEST') && upperSql.includes('SATISFIES')) { - return 'n1ql'; - } - - if (upperSql.includes('DISTSTYLE') || upperSql.includes('SORTKEY') || upperSql.includes('DISTKEY')) { - return 'redshift'; - } - - if (upperSql.includes('COLUMNSTORE') || upperSql.includes('SHARD KEY') || upperSql.includes('REFERENCE TABLE')) { - return 'singlestoredb'; - } - - if (upperSql.includes('CACHE TABLE') || upperSql.includes('BROADCAST(') || upperSql.includes('USING DELTA')) { - return 'spark'; - } - - if (upperSql.includes('TIDB_VERSION') || upperSql.includes('AUTO_RANDOM') || upperSql.includes('AS OF TIMESTAMP')) { - return 'tidb'; - } - - if (upperSql.includes('ARRAY[') || upperSql.includes('MAP(') || upperSql.includes('APPROX_DISTINCT')) { - return 'trino'; - } - - if (upperSql.includes('DECFLOAT') || upperSql.includes('GENERATED ALWAYS') || upperSql.includes('FINAL TABLE')) { - return 'db2'; - } - - if (upperSql.includes('QSYS') || upperSql.includes('JOURNAL') || upperSql.includes('AS/400')) { - return 'db2i'; - } - - if (upperSql.includes('JSON_EXTRACT') && (upperSql.includes('ENGINE=') || upperSql.includes('SEQUENCE'))) { - return 'mariadb'; - } - - // 默认返回通用SQL - return 'sql'; -} diff --git a/frontend/src/common/prettier/plugins/sql/index.ts b/frontend/src/common/prettier/plugins/sql/index.ts new file mode 100644 index 0000000..e7ca46a --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/index.ts @@ -0,0 +1,140 @@ +/** + * Prettier Plugin for SQL formatting using SQL Format WebAssembly + * + * This plugin provides support for formatting SQL files using the SQL Format WASM implementation. + */ +import type { Plugin, Parser, Printer } from 'prettier'; + +// Import the SQL Format WASM module +import sqlFmtInit, { format, type Config } from './sql_fmt_vite.js'; + +const parserName = 'sql'; + +// Language configuration +const languages = [ + { + name: 'SQL', + aliases: ['sql'], + parsers: [parserName], + extensions: ['.sql'], + aceMode: 'sql', + tmScope: 'source.sql', + linguistLanguageId: 316, + vscodeLanguageIds: ['sql'] + } +]; + +// Parser configuration +const sqlParser: Parser = { + astFormat: parserName, + parse: (text: string) => text, + locStart: () => 0, + locEnd: (node: string) => node.length, +}; + +// Initialize SQL Format WASM module +let initPromise: Promise | null = null; +let isInitialized = false; + +function initSqlFmt(): Promise { + if (initPromise) { + return initPromise; + } + + initPromise = (async () => { + if (!isInitialized) { + await sqlFmtInit(); + isInitialized = true; + } + })(); + + return initPromise; +} + +// Printer configuration +const sqlPrinter: Printer = { + print: (path, options) => { + try { + if (!isInitialized) { + console.warn('SQL Format WASM module not initialized, returning original text'); + return (path as any).getValue ? (path as any).getValue() : path.node; + } + + const text = (path as any).getValue ? (path as any).getValue() : path.node; + const config = getSqlFmtConfig(options); + + // Format using SQL Format (synchronous call) + const formatted = format(text, 'index.sql', config); + + return formatted.trim(); + } catch (error) { + console.warn('SQL formatting failed:', error); + // Return original text if formatting fails + return (path as any).getValue ? (path as any).getValue() : path.node; + } + }, +}; + +// Helper function to create SQL Format config from Prettier options +function getSqlFmtConfig(options: any): Config { + const config: Config = {}; + + // Map Prettier options to SQL Format config + if (options.useTabs !== undefined) { + config.indent_style = options.useTabs ? 'tab' : 'space'; + } + + if (options.tabWidth !== undefined) { + config.indent_width = options.tabWidth; + } + + if (options.sqlUppercase !== undefined) { + config.uppercase = options.sqlUppercase; + } + + if (options.sqlLinesBetweenQueries !== undefined) { + config.lines_between_queries = options.sqlLinesBetweenQueries; + } + + return config; +} + +// Plugin options +const options = { + sqlUppercase: { + since: '0.0.1', + category: 'Format' as const, + type: 'boolean' as const, + default: false, + description: 'When set, changes reserved keywords to ALL CAPS' + }, + sqlLinesBetweenQueries: { + since: '0.0.1', + category: 'Format' as const, + type: 'int' as const, + default: 1, + description: 'Controls the number of line breaks after a query' + } +}; + +// Plugin definition +const sqlPlugin: Plugin = { + languages, + parsers: { + [parserName]: sqlParser, + }, + printers: { + [parserName]: sqlPrinter, + }, + options, +}; + +// Initialize the WASM module +initSqlFmt().catch(error => { + console.error('Failed to initialize SQL Format WASM module:', error); +}); + +export default sqlPlugin; +export { languages }; +export const parsers = sqlPlugin.parsers; +export const printers = sqlPlugin.printers; \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/sql/languages.js b/frontend/src/common/prettier/plugins/sql/languages.js deleted file mode 100644 index 5d09c1b..0000000 --- a/frontend/src/common/prettier/plugins/sql/languages.js +++ /dev/null @@ -1,30 +0,0 @@ -// SQL语言定义 -export const languages = [ - { - name: "SQL", - parsers: ["sql"], - extensions: [ - ".sql", - ".ddl", - ".dml", - ".hql", - ".psql", - ".plsql", - ".mysql", - ".mssql", - ".pgsql", - ".sqlite", - ".bigquery", - ".snowflake", - ".redshift", - ".db2", - ".n1ql", - ".cql" - ], - filenames: [ - "*.sql", - "*.ddl", - "*.dml" - ] - } -]; diff --git a/frontend/src/common/prettier/plugins/sql/sql.d.ts b/frontend/src/common/prettier/plugins/sql/sql.d.ts deleted file mode 100644 index c658172..0000000 --- a/frontend/src/common/prettier/plugins/sql/sql.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { AST, Option } from 'node-sql-parser'; -import { Options, ParserOptions, Plugin } from 'prettier'; -import { - FormatOptions, - FormatOptionsWithLanguage, -} from 'sql-formatter'; - -export type SqlBaseOptions = Option & - Partial< - | (FormatOptions & { dialect: string }) - | (FormatOptionsWithLanguage & { dialect?: never }) - > & { - formatter?: 'sql-formatter' | 'node-sql-parser' | 'sql-cst'; - params?: string; - paramTypes?: string; - autoDetectDialect?: boolean; - }; - -export type SqlOptions = ParserOptions & SqlBaseOptions; -export type SqlFormatOptions = Options & SqlBaseOptions; -export declare const languages: Plugin["languages"]; - -export declare const parsers: { - sql: { - parse(text: string, options?: SqlOptions): AST | string; - astFormat: 'sql'; - locStart(): number; - locEnd(): number; - }; -}; - -export declare const printers: Plugin["printers"]; - -export declare const options: Plugin["options"]; - -export declare function detectDialect(sql: string): string; - -declare const SqlPlugin: Plugin; - -export default SqlPlugin; diff --git a/frontend/src/common/prettier/plugins/sql/sql.mjs b/frontend/src/common/prettier/plugins/sql/sql.mjs deleted file mode 100644 index 57ff62c..0000000 --- a/frontend/src/common/prettier/plugins/sql/sql.mjs +++ /dev/null @@ -1,459 +0,0 @@ -import { JSOX } from 'jsox'; -import nodeSqlParser from 'node-sql-parser'; -import { - format, - formatDialect, -} from 'sql-formatter'; -import { detectDialect } from './detect.mjs'; -import { languages } from './languages.js'; - -const parser = new nodeSqlParser.Parser(); - -const SQL_FORMATTER = 'sql-formatter'; -const NODE_SQL_PARSER = 'node-sql-parser'; - -// Parsers -export const parsers = { - sql: { - parse(text, options = {}) { - const { formatter, type, database } = options; - - return formatter === SQL_FORMATTER - ? text - : parser.astify(text, { type, database }); - }, - astFormat: 'sql', - locStart: () => -1, - locEnd: () => -1, - }, -}; - -// Printers -export const printers = { - sql: { - print(path, options = {}) { - const value = path.node; - const { - formatter = SQL_FORMATTER, - type, - database, - dialect, - language, - params, - paramTypes, - autoDetectDialect = true, - ...formatOptions - } = options; - - let formatted; - - if (typeof value === 'string') { - // 准备sql-formatter选项 - const sqlFormatterOptions = { - ...formatOptions, - params: - params == null - ? undefined - : JSOX.parse(params), - paramTypes: - paramTypes == null - ? undefined - : JSOX.parse(paramTypes), - }; - - let finalLanguage = language; - let finalDialect = dialect; - - if (autoDetectDialect && !language && !dialect) { - const detectedDialect = detectDialect(value); - finalLanguage = detectedDialect; - } - - // 使用适当的格式化方法 - if (finalDialect != null) { - // 使用formatDialect方法 - formatted = formatDialect(value, { - ...sqlFormatterOptions, - dialect: JSOX.parse(finalDialect), - }); - } else { - // 使用format方法 - formatted = format(value, { - ...sqlFormatterOptions, - language: finalLanguage, - }); - } - } else { - // 使用node-sql-parser进行格式化 - formatted = parser.sqlify(value, { type, database }); - } - - return formatted + '\n'; - }, - }, -}; - -// 插件选项 -export const options = { - formatter: { - category: 'Config', - type: 'choice', - default: SQL_FORMATTER, - description: 'Choose which formatter to be used', - choices: [ - { - value: SQL_FORMATTER, - description: 'use `sql-formatter` as formatter', - }, - { - value: NODE_SQL_PARSER, - description: 'use `node-sql-parser` as formatter', - }, - ], - }, - autoDetectDialect: { - category: 'Config', - type: 'boolean', - default: true, - description: 'Automatically detect SQL dialect if language/dialect is not specified', - }, - dialect: { - category: 'Config', - type: 'string', - description: 'SQL dialect for `sql-formatter` formatDialect()', - }, - language: { - category: 'Config', - type: 'choice', - default: 'sql', - description: 'SQL dialect for `sql-formatter` format()', - choices: [ - { - value: 'sql', - description: 'Standard SQL: https://en.wikipedia.org/wiki/SQL:2011', - }, - { - value: 'bigquery', - description: - 'Google Standard SQL (Bigquery): https://cloud.google.com/bigquery', - }, - { - value: 'db2', - description: 'IBM DB2: https://www.ibm.com/products/db2', - }, - { - value: 'db2i', - description: - 'IBM DB2i (experimental): https://www.ibm.com/docs/en/i/7.5?topic=overview-db2-i', - }, - { - value: 'hive', - description: 'Apache Hive: https://hive.apache.org', - }, - { - value: 'mariadb', - description: 'MariaDB: https://mariadb.com', - }, - { - value: 'mysql', - description: 'MySQL: https://www.mysql.com', - }, - { - value: 'n1ql', - description: - 'Couchbase N1QL: https://www.couchbase.com/products/n1ql', - }, - { - value: 'plsql', - description: - 'Oracle PL/SQL: https://www.oracle.com/database/technologies/appdev/plsql.html', - }, - { - value: 'postgresql', - description: 'PostgreSQL: https://www.postgresql.org', - }, - { - value: 'redshift', - description: - 'Amazon Redshift: https://docs.aws.amazon.com/redshift/latest/dg/cm_chap_SQLCommandRef.html', - }, - { - value: 'singlestoredb', - description: - 'SingleStoreDB: https://docs.singlestore.com/db/v7.8/en/introduction/singlestore-documentation.html', - }, - { - value: 'snowflake', - description: 'Snowflake: https://docs.snowflake.com', - }, - { - value: 'spark', - description: 'Spark: https://spark.apache.org', - }, - { - value: 'sqlite', - description: 'SQLite: https://www.sqlite.org', - }, - { - value: 'transactsql', - description: - 'SQL Server Transact-SQL: https://docs.microsoft.com/en-us/sql/sql-server/', - }, - { - value: 'tsql', - description: - 'SQL Server Transact-SQL: https://docs.microsoft.com/en-us/sql/sql-server/', - }, - { - value: 'trino', - description: 'Trino: https://trino.io', - }, - ], - }, - keywordCase: { - category: 'Output', - type: 'choice', - default: 'preserve', - description: - 'Converts reserved keywords to upper- or lowercase for `sql-formatter`', - choices: [ - { - value: 'preserve', - description: 'preserves the original case of reserved keywords', - }, - { - value: 'upper', - description: 'converts reserved keywords to uppercase', - }, - { - value: 'lower', - description: 'converts reserved keywords to lowercase', - }, - ], - }, - dataTypeCase: { - category: 'Output', - type: 'choice', - default: 'preserve', - description: - 'Converts data types to upper- or lowercase for `sql-formatter`', - choices: [ - { - value: 'preserve', - description: 'preserves the original case of data types', - }, - { - value: 'upper', - description: 'converts data types to uppercase', - }, - { - value: 'lower', - description: 'converts data types to lowercase', - }, - ], - }, - functionCase: { - category: 'Output', - type: 'choice', - default: 'preserve', - description: - 'Converts functions to upper- or lowercase for `sql-formatter`', - choices: [ - { - value: 'preserve', - description: 'preserves the original case of functions', - }, - { - value: 'upper', - description: 'converts functions to uppercase', - }, - { - value: 'lower', - description: 'converts functions to lowercase', - }, - ], - }, - identifierCase: { - category: 'Output', - type: 'choice', - default: 'preserve', - description: - 'Converts identifiers to upper- or lowercase for `sql-formatter`. Only unquoted identifiers are converted. (experimental)', - choices: [ - { - value: 'preserve', - description: 'preserves the original case of identifiers', - }, - { - value: 'upper', - description: 'converts identifiers to uppercase', - }, - { - value: 'lower', - description: 'converts identifiers to lowercase', - }, - ], - }, - uppercase: { - category: 'Output', - type: 'boolean', - deprecated: '0.7.0', - description: 'Use `keywordCase` option instead', - }, - indentStyle: { - category: 'Format', - type: 'choice', - default: 'standard', - description: `Switches between different indentation styles for \`sql-formatter\`. - - Caveats of using \`"tabularLeft"\` and \`"tabularRight"\`: - - - \`tabWidth\` option is ignored. Indentation will always be 10 spaces, regardless of what is specified by \`tabWidth\``, - choices: [ - { - value: 'standard', - description: - 'indents code by the amount specified by `tabWidth` option', - }, - { - value: 'tabularLeft', - description: - 'indents in tabular style with 10 spaces, aligning keywords to left', - }, - { - value: 'tabularRight', - description: - 'indents in tabular style with 10 spaces, aligning keywords to right', - }, - ], - }, - logicalOperatorNewline: { - category: 'Format', - type: 'choice', - default: 'before', - description: - 'Decides newline placement before or after logical operators (AND, OR, XOR)', - choices: [ - { - value: 'before', - description: 'adds newline before the operator', - }, - { - value: 'after', - description: 'adds newline after the operator', - }, - ], - }, - expressionWidth: { - category: 'Format', - type: 'int', - default: 50, - description: - 'Determines maximum length of parenthesized expressions for `sql-formatter`', - }, - linesBetweenQueries: { - category: 'Format', - type: 'int', - default: 1, - description: - 'Decides how many empty lines to leave between SQL statements for `sql-formatter`', - }, - denseOperators: { - category: 'Format', - type: 'boolean', - default: false, - description: - 'Decides whitespace around operators for `sql-formatter`. Does not apply to logical operators (AND, OR, XOR).', - }, - newlineBeforeSemicolon: { - category: 'Format', - type: 'boolean', - default: false, - description: - 'Whether to place query separator (`;`) on a separate line for `sql-formatter`', - }, - params: { - category: 'Format', - type: 'string', - description: - 'Specifies `JSOX` **stringified** parameter values to fill in for placeholders inside SQL for `sql-formatter`. This option is designed to be used through API (though nothing really prevents usage from command line).', - }, - paramTypes: { - category: 'Config', - type: 'string', - description: - 'Specifies `JSOX` **stringified** parameter types to support when parsing SQL prepared statements for `sql-formatter`.', - }, - type: { - category: 'Config', - type: 'choice', - default: 'table', - description: 'Check the SQL with Authority List for `node-sql-parser`', - choices: [ - { - value: 'table', - description: '`table` mode', - }, - { - value: 'column', - description: '`column` mode', - }, - ], - }, - database: { - category: 'Config', - type: 'choice', - default: 'mysql', - description: 'SQL dialect for `node-sql-parser`', - choices: [ - { - value: 'bigquery', - description: 'BigQuery: https://cloud.google.com/bigquery', - }, - { - value: 'db2', - description: 'IBM DB2: https://www.ibm.com/analytics/db2', - }, - { - value: 'hive', - description: 'Hive: https://hive.apache.org', - }, - { - value: 'mariadb', - description: 'MariaDB: https://mariadb.com', - }, - { - value: 'mysql', - description: 'MySQL: https://www.mysql.com', - }, - { - value: 'postgresql', - description: 'PostgreSQL: https://www.postgresql.org', - }, - { - value: 'transactsql', - description: - 'TransactSQL: https://docs.microsoft.com/en-us/sql/t-sql', - }, - { - value: 'flinksql', - description: - 'FlinkSQL: https://ci.apache.org/projects/flink/flink-docs-stable', - }, - { - value: 'snowflake', - description: 'Snowflake (alpha): https://docs.snowflake.com', - }, - ], - }, -}; - -const SqlPlugin = { - languages, - parsers, - printers, - options, -}; - -export { languages }; -export default SqlPlugin; \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/sql/sql_fmt.d.ts b/frontend/src/common/prettier/plugins/sql/sql_fmt.d.ts new file mode 100644 index 0000000..41efd3b --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/sql_fmt.d.ts @@ -0,0 +1,58 @@ +/* tslint:disable */ +/* eslint-disable */ +export function format(input: string, filename: string, config?: Config): string; + +interface LayoutConfig { + indent_style?: "tab" | "space"; + indent_width?: number; +} + + +export interface Config extends LayoutConfig { + /** + * When set, changes reserved keywords to ALL CAPS + * + * Default: false + */ + uppercase?: boolean; + /** + * Controls the number of line breaks after a query + * + * Default: 1 + */ + lines_between_queries?: number; +} + + +export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; + +export interface InitOutput { + readonly memory: WebAssembly.Memory; + readonly format: (a: number, b: number, c: number, d: number, e: number, f: number) => void; + readonly __wbindgen_export_0: (a: number, b: number) => number; + readonly __wbindgen_export_1: (a: number, b: number, c: number, d: number) => number; + readonly __wbindgen_export_2: (a: number) => void; + readonly __wbindgen_add_to_stack_pointer: (a: number) => number; + readonly __wbindgen_export_3: (a: number, b: number, c: number) => void; +} + +export type SyncInitInput = BufferSource | WebAssembly.Module; +/** +* Instantiates the given `module`, which can either be bytes or +* a precompiled `WebAssembly.Module`. +* +* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated. +* +* @returns {InitOutput} +*/ +export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput; + +/** +* If `module_or_path` is {RequestInfo} or {URL}, makes a request and +* for everything else, calls `WebAssembly.instantiate` directly. +* +* @param {{ module_or_path: InitInput | Promise }} module_or_path - Passing `InitInput` directly is deprecated. +* +* @returns {Promise} +*/ +export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise } | InitInput | Promise): Promise; diff --git a/frontend/src/common/prettier/plugins/sql/sql_fmt.js b/frontend/src/common/prettier/plugins/sql/sql_fmt.js new file mode 100644 index 0000000..ebc5e2b --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/sql_fmt.js @@ -0,0 +1,524 @@ +let wasm; + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { return heap[idx]; } + +let WASM_VECTOR_LEN = 0; + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedDataViewMemory0 = null; + +function getDataViewMemory0() { + if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +let heap_next = heap.length; + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + wasm.__wbindgen_export_2(addHeapObject(e)); + } +} + +function isLikeNone(x) { + return x === undefined || x === null; +} + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches && builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); + +if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} +/** + * @param {string} input + * @param {string} filename + * @param {Config | undefined} [config] + * @returns {string} + */ +export function format(input, filename, config) { + let deferred4_0; + let deferred4_1; + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0(input, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0(filename, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + const len1 = WASM_VECTOR_LEN; + wasm.format(retptr, ptr0, len0, ptr1, len1, isLikeNone(config) ? 0 : addHeapObject(config)); + var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); + var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); + var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true); + var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true); + var ptr3 = r0; + var len3 = r1; + if (r3) { + ptr3 = 0; len3 = 0; + throw takeObject(r2); + } + deferred4_0 = ptr3; + deferred4_1 = len3; + return getStringFromWasm0(ptr3, len3); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_export_3(deferred4_0, deferred4_1, 1); + } +} + +async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } +} + +function __wbg_get_imports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) { + const ret = String(getObject(arg1)); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbg_buffer_61b7ce01341d7f88 = function(arg0) { + const ret = getObject(arg0).buffer; + return addHeapObject(ret); + }; + imports.wbg.__wbg_call_b0d8e36992d9900d = function() { return handleError(function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_done_f22c1561fa919baa = function(arg0) { + const ret = getObject(arg0).done; + return ret; + }; + imports.wbg.__wbg_entries_4f2bb9b0d701c0f6 = function(arg0) { + const ret = Object.entries(getObject(arg0)); + return addHeapObject(ret); + }; + imports.wbg.__wbg_get_9aa3dff3f0266054 = function(arg0, arg1) { + const ret = getObject(arg0)[arg1 >>> 0]; + return addHeapObject(ret); + }; + imports.wbg.__wbg_get_bbccf8970793c087 = function() { return handleError(function (arg0, arg1) { + const ret = Reflect.get(getObject(arg0), getObject(arg1)); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_instanceof_ArrayBuffer_670ddde44cdb2602 = function(arg0) { + let result; + try { + result = getObject(arg0) instanceof ArrayBuffer; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Map_98ecb30afec5acdb = function(arg0) { + let result; + try { + result = getObject(arg0) instanceof Map; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Uint8Array_28af5bc19d6acad8 = function(arg0) { + let result; + try { + result = getObject(arg0) instanceof Uint8Array; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_isArray_1ba11a930108ec51 = function(arg0) { + const ret = Array.isArray(getObject(arg0)); + return ret; + }; + imports.wbg.__wbg_isSafeInteger_12f5549b2fca23f4 = function(arg0) { + const ret = Number.isSafeInteger(getObject(arg0)); + return ret; + }; + imports.wbg.__wbg_iterator_23604bb983791576 = function() { + const ret = Symbol.iterator; + return addHeapObject(ret); + }; + imports.wbg.__wbg_length_65d1cd11729ced11 = function(arg0) { + const ret = getObject(arg0).length; + return ret; + }; + imports.wbg.__wbg_length_d65cf0786bfc5739 = function(arg0) { + const ret = getObject(arg0).length; + return ret; + }; + imports.wbg.__wbg_new_3ff5b33b1ce712df = function(arg0) { + const ret = new Uint8Array(getObject(arg0)); + return addHeapObject(ret); + }; + imports.wbg.__wbg_next_01dd9234a5bf6d05 = function() { return handleError(function (arg0) { + const ret = getObject(arg0).next(); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_next_137428deb98342b0 = function(arg0) { + const ret = getObject(arg0).next; + return addHeapObject(ret); + }; + imports.wbg.__wbg_set_23d69db4e5c66a6e = function(arg0, arg1, arg2) { + getObject(arg0).set(getObject(arg1), arg2 >>> 0); + }; + imports.wbg.__wbg_value_4c32fd138a88eee2 = function(arg0) { + const ret = getObject(arg0).value; + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_as_number = function(arg0) { + const ret = +getObject(arg0); + return ret; + }; + imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) { + const ret = arg0; + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) { + const ret = BigInt.asUintN(64, arg0); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) { + const v = getObject(arg1); + const ret = typeof(v) === 'bigint' ? v : undefined; + getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_boolean_get = function(arg0) { + const v = getObject(arg0); + const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2; + return ret; + }; + imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { + const ret = debugString(getObject(arg1)); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_error_new = function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_in = function(arg0, arg1) { + const ret = getObject(arg0) in getObject(arg1); + return ret; + }; + imports.wbg.__wbindgen_is_bigint = function(arg0) { + const ret = typeof(getObject(arg0)) === 'bigint'; + return ret; + }; + imports.wbg.__wbindgen_is_function = function(arg0) { + const ret = typeof(getObject(arg0)) === 'function'; + return ret; + }; + imports.wbg.__wbindgen_is_object = function(arg0) { + const val = getObject(arg0); + const ret = typeof(val) === 'object' && val !== null; + return ret; + }; + imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) { + const ret = getObject(arg0) === getObject(arg1); + return ret; + }; + imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) { + const ret = getObject(arg0) == getObject(arg1); + return ret; + }; + imports.wbg.__wbindgen_memory = function() { + const ret = wasm.memory; + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_number_get = function(arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof(obj) === 'number' ? obj : undefined; + getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_object_clone_ref = function(arg0) { + const ret = getObject(arg0); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); + }; + imports.wbg.__wbindgen_string_get = function(arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof(obj) === 'string' ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + + return imports; +} + +function __wbg_init_memory(imports, memory) { + +} + +function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + __wbg_init.__wbindgen_wasm_module = module; + cachedDataViewMemory0 = null; + cachedUint8ArrayMemory0 = null; + + + + return wasm; +} + +function initSync(module) { + if (wasm !== undefined) return wasm; + + + if (typeof module !== 'undefined') { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({module} = module) + } else { + console.warn('using deprecated parameters for `initSync()`; pass a single object instead') + } + } + + const imports = __wbg_get_imports(); + + __wbg_init_memory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return __wbg_finalize_init(instance, module); +} + +async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + + if (typeof module_or_path !== 'undefined') { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({module_or_path} = module_or_path) + } else { + console.warn('using deprecated parameters for the initialization function; pass a single object instead') + } + } + + if (typeof module_or_path === 'undefined') { + module_or_path = new URL('sql_fmt_bg.wasm', import.meta.url); + } + const imports = __wbg_get_imports(); + + if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { + module_or_path = fetch(module_or_path); + } + + __wbg_init_memory(imports); + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); +} + +export { initSync }; +export default __wbg_init; diff --git a/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm b/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm new file mode 100644 index 0000000..47299ed Binary files /dev/null and b/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm differ diff --git a/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm.d.ts b/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm.d.ts new file mode 100644 index 0000000..ecdf7c3 --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/sql_fmt_bg.wasm.d.ts @@ -0,0 +1,9 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export const format: (a: number, b: number, c: number, d: number, e: number, f: number) => void; +export const __wbindgen_export_0: (a: number, b: number) => number; +export const __wbindgen_export_1: (a: number, b: number, c: number, d: number) => number; +export const __wbindgen_export_2: (a: number) => void; +export const __wbindgen_add_to_stack_pointer: (a: number) => number; +export const __wbindgen_export_3: (a: number, b: number, c: number) => void; diff --git a/frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_node.js b/frontend/src/common/prettier/plugins/sql/sql_fmt_node.js similarity index 53% rename from frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_node.js rename to frontend/src/common/prettier/plugins/sql/sql_fmt_node.js index c49c6ca..221fd18 100644 --- a/frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_node.js +++ b/frontend/src/common/prettier/plugins/sql/sql_fmt_node.js @@ -1,10 +1,10 @@ import fs from "node:fs/promises"; -import initAsync from "./web_fmt.js"; +import initAsync from "./sql_fmt.js"; -const wasm = new URL("./web_fmt_bg.wasm", import.meta.url); +const wasm = new URL("./sql_fmt_bg.wasm", import.meta.url); export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) { return initAsync(init); } -export * from "./web_fmt.js"; +export * from "./sql_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/sql/sql_fmt_vite.js b/frontend/src/common/prettier/plugins/sql/sql_fmt_vite.js new file mode 100644 index 0000000..e3f6eaf --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/sql_fmt_vite.js @@ -0,0 +1,8 @@ +import initAsync from "./sql_fmt.js"; +import wasm from "./sql_fmt_bg.wasm?url"; + +export default function __wbg_init(input = { module_or_path: wasm }) { + return initAsync(input); +} + +export * from "./sql_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/sql/src/build.sh b/frontend/src/common/prettier/plugins/sql/src/build.sh new file mode 100644 index 0000000..2cfc195 --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/src/build.sh @@ -0,0 +1,3 @@ +cd $(dirname $0)/.. +wasm-pack build --target=web --scope=wasm-fmt + diff --git a/frontend/src/common/prettier/plugins/sql/src/lib.rs b/frontend/src/common/prettier/plugins/sql/src/lib.rs new file mode 100644 index 0000000..66bd168 --- /dev/null +++ b/frontend/src/common/prettier/plugins/sql/src/lib.rs @@ -0,0 +1,97 @@ +use serde::Deserialize; + +use sqlformat::{FormatOptions, QueryParams}; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub fn format(input: &str, filename: &str, config: Option) -> Result { + let _ = filename; + + let config = config + .map(|x| serde_wasm_bindgen::from_value::(x.clone())) + .transpose() + .map_err(|op| op.to_string())? + .unwrap_or_default(); + + Ok(sqlformat::format(input, &QueryParams::None, &config.into())) +} + +#[wasm_bindgen(typescript_custom_section)] +const TS_Config: &'static str = r#" +interface LayoutConfig { + indent_style?: "tab" | "space"; + indent_width?: number; +}"#; + +#[wasm_bindgen(typescript_custom_section)] +const TS_Config: &'static str = r#" +export interface Config extends LayoutConfig { + /** + * When set, changes reserved keywords to ALL CAPS + * + * Default: false + */ + uppercase?: boolean; + /** + * Controls the number of line breaks after a query + * + * Default: 1 + */ + lines_between_queries?: number; +}"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "Config")] + pub type Config; +} + +#[derive(Deserialize, Clone, Copy)] +enum IndentStyle { + #[serde(rename = "tab")] + Tab, + #[serde(rename = "space")] + Space, +} + +#[derive(Deserialize, Clone, Default)] +struct LayoutConfig { + #[serde(alias = "indentStyle")] + indent_style: Option, + #[serde(alias = "indentWidth")] + indent_width: Option, +} + +#[derive(Deserialize, Clone, Default)] +struct SQLConfig { + #[serde(flatten)] + layout: LayoutConfig, + + pub uppercase: Option, + + #[serde(alias = "linesBetweenQueries")] + pub lines_between_queries: Option, +} + +impl<'a> From for FormatOptions<'a> { + fn from(val: SQLConfig) -> Self { + let mut config = FormatOptions::default(); + + let indent_width = val.layout.indent_width.unwrap_or(2); + + if let Some(indent_style) = val.layout.indent_style { + config.indent = match indent_style { + IndentStyle::Tab => sqlformat::Indent::Tabs, + IndentStyle::Space => sqlformat::Indent::Spaces(indent_width), + }; + } + + config.uppercase = val.uppercase; + + if let Some(lines_between_queries) = val.lines_between_queries { + config.lines_between_queries = lines_between_queries; + } + + config + } +} diff --git a/frontend/src/common/prettier/plugins/web/json_fmt/extra/.npmignore b/frontend/src/common/prettier/plugins/web/json_fmt/extra/.npmignore deleted file mode 100644 index 1ee7305..0000000 --- a/frontend/src/common/prettier/plugins/web/json_fmt/extra/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.tgz -jsr.jsonc \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_node.js b/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_node.js deleted file mode 100644 index bf3f3df..0000000 --- a/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_node.js +++ /dev/null @@ -1,10 +0,0 @@ -import fs from "node:fs/promises"; -import initAsync from "./json_fmt.js"; - -const wasm = new URL("./json_fmt_bg.wasm", import.meta.url); - -export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) { - return initAsync(init); -} - -export * from "./json_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_vite.js b/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_vite.js deleted file mode 100644 index bfe6f22..0000000 --- a/frontend/src/common/prettier/plugins/web/json_fmt/extra/json_fmt_vite.js +++ /dev/null @@ -1,8 +0,0 @@ -import initAsync from "./json_fmt.js"; -import wasm from "./json_fmt_bg.wasm?url"; - -export default function __wbg_init(input = { module_or_path: wasm }) { - return initAsync(input); -} - -export * from "./json_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/web/json_fmt/scripts/package.mjs b/frontend/src/common/prettier/plugins/web/json_fmt/scripts/package.mjs deleted file mode 100644 index 1d16430..0000000 --- a/frontend/src/common/prettier/plugins/web/json_fmt/scripts/package.mjs +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env node -import process from "node:process"; -import path from "node:path"; -import fs from "node:fs"; - -const pkg_path = path.resolve(process.cwd(), process.argv[2]); -const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" }); -const pkg_json = JSON.parse(pkg_text); - -delete pkg_json.files; - -pkg_json.main = pkg_json.module; -pkg_json.type = "module"; -pkg_json.publishConfig = { - access: "public", -}; -pkg_json.exports = { - ".": { - types: "./json_fmt.d.ts", - node: "./json_fmt_node.js", - default: "./json_fmt.js", - }, - "./vite": { - types: "./json_fmt.d.ts", - default: "./json_fmt_vite.js", - }, - "./package.json": "./package.json", - "./*": "./*", -}; - -fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4)); - -// JSR - -const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc"); -pkg_json.name = "@fmt/json-fmt"; -pkg_json.exports = "./json_fmt.js"; -pkg_json.exclude = ["!**", "*.tgz"]; -fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4)); diff --git a/frontend/src/common/prettier/plugins/web/json_fmt/scripts/build.sh b/frontend/src/common/prettier/plugins/web/json_fmt/src/build.sh similarity index 57% rename from frontend/src/common/prettier/plugins/web/json_fmt/scripts/build.sh rename to frontend/src/common/prettier/plugins/web/json_fmt/src/build.sh index fb3892a..4d99ab9 100644 --- a/frontend/src/common/prettier/plugins/web/json_fmt/scripts/build.sh +++ b/frontend/src/common/prettier/plugins/web/json_fmt/src/build.sh @@ -4,8 +4,3 @@ crates_dir=$(pwd) cd ../.. wasm-pack build --target=web --scope=wasm-fmt crates/json_fmt -cd $crates_dir - -cp -R ./extra/. ./pkg/ - -./scripts/package.mjs ./pkg/package.json diff --git a/frontend/src/common/prettier/plugins/web/web_fmt/extra/.npmignore b/frontend/src/common/prettier/plugins/web/web_fmt/extra/.npmignore deleted file mode 100644 index 1ee7305..0000000 --- a/frontend/src/common/prettier/plugins/web/web_fmt/extra/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.tgz -jsr.jsonc \ No newline at end of file diff --git a/frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_vite.js b/frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_vite.js deleted file mode 100644 index b0462b9..0000000 --- a/frontend/src/common/prettier/plugins/web/web_fmt/extra/web_fmt_vite.js +++ /dev/null @@ -1,8 +0,0 @@ -import initAsync from "./web_fmt.js"; -import wasm from "./web_fmt_bg.wasm?url"; - -export default function __wbg_init(input = { module_or_path: wasm }) { - return initAsync(input); -} - -export * from "./web_fmt.js"; diff --git a/frontend/src/common/prettier/plugins/web/web_fmt/scripts/package.mjs b/frontend/src/common/prettier/plugins/web/web_fmt/scripts/package.mjs deleted file mode 100644 index c94c56b..0000000 --- a/frontend/src/common/prettier/plugins/web/web_fmt/scripts/package.mjs +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env node -import process from "node:process"; -import path from "node:path"; -import fs from "node:fs"; - -const pkg_path = path.resolve(process.cwd(), process.argv[2]); -const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" }); -const pkg_json = JSON.parse(pkg_text); - -delete pkg_json.files; - -pkg_json.main = pkg_json.module; -pkg_json.type = "module"; -pkg_json.publishConfig = { - access: "public", -}; -pkg_json.exports = { - ".": { - types: "./web_fmt.d.ts", - node: "./web_fmt_node.js", - default: "./web_fmt.js", - }, - "./vite": { - types: "./web_fmt.d.ts", - default: "./web_fmt_vite.js", - }, - "./package.json": "./package.json", - "./*": "./*", -}; - -fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4)); - -// JSR - -const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc"); -pkg_json.name = "@fmt/web-fmt"; -pkg_json.exports = "./web_fmt.js"; -pkg_json.exclude = ["!**", "*.tgz"]; -fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4)); diff --git a/frontend/src/common/prettier/plugins/web/web_fmt/scripts/build.sh b/frontend/src/common/prettier/plugins/web/web_fmt/src/build.sh similarity index 57% rename from frontend/src/common/prettier/plugins/web/web_fmt/scripts/build.sh rename to frontend/src/common/prettier/plugins/web/web_fmt/src/build.sh index 4b2ec50..bb27bb0 100644 --- a/frontend/src/common/prettier/plugins/web/web_fmt/scripts/build.sh +++ b/frontend/src/common/prettier/plugins/web/web_fmt/src/build.sh @@ -4,8 +4,3 @@ crates_dir=$(pwd) cd ../.. wasm-pack build --target=web --scope=wasm-fmt crates/web_fmt -cd $crates_dir - -cp -R ./extra/. ./pkg/ - -./scripts/package.mjs ./pkg/package.json diff --git a/frontend/src/views/editor/extensions/codeblock/lang-parser/languages.ts b/frontend/src/views/editor/extensions/codeblock/lang-parser/languages.ts index a94d9d0..cfa6873 100644 --- a/frontend/src/views/editor/extensions/codeblock/lang-parser/languages.ts +++ b/frontend/src/views/editor/extensions/codeblock/lang-parser/languages.ts @@ -39,7 +39,7 @@ import cssPrettierPlugin from "prettier/plugins/postcss" import markdownPrettierPlugin from "prettier/plugins/markdown" import yamlPrettierPlugin from "prettier/plugins/yaml" import goPrettierPlugin from "@/common/prettier/plugins/go/go.mjs" -import sqlPrettierPlugin from "@/common/prettier/plugins/sql/sql" +import sqlPrettierPlugin from "@/common/prettier/plugins/sql" import phpPrettierPlugin from "@/common/prettier/plugins/php" import javaPrettierPlugin from "@/common/prettier/plugins/java" import xmlPrettierPlugin from "@prettier/plugin-xml" @@ -115,14 +115,23 @@ export const LANGUAGES: LanguageInfo[] = [ plugins: [xmlPrettierPlugin] }), new LanguageInfo("cpp", "C++", cppLanguage.parser, ["cpp", "c"], { - parser: "clang", - plugins: [clangPrettierPlugin] + parser: "clang-format", + plugins: [clangPrettierPlugin], + options: { + filename: "index.cpp" + } }), new LanguageInfo("rs", "Rust", rustLanguage.parser, ["rs"], { parser: "jinx-rust", plugins: [rustPrettierPlugin] }), - new LanguageInfo("cs", "C#", StreamLanguage.define(csharp).parser, ["cs"]), + new LanguageInfo("cs", "C#", StreamLanguage.define(csharp).parser, ["cs"],{ + parser: "clang-format", + plugins: [clangPrettierPlugin], + options: { + filename: "index.cs" + } + }), new LanguageInfo("rb", "Ruby", StreamLanguage.define(ruby).parser, ["rb"]), new LanguageInfo("sh", "Shell", StreamLanguage.define(shell).parser, ["sh", "bat"], { parser: "sh",