initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
declare function translateOptions({ cache, cacheFile, cacheLocation, cacheStrategy, config, env, errorOnUnmatchedPattern, eslintrc, ext, fix, fixDryRun, fixType, global, ignore, ignorePath, ignorePattern, inlineConfig, parser, parserOptions, plugin, quiet, reportUnusedDisableDirectives, resolvePluginsRelativeTo, rule, rulesdir, }: any): {
allowInlineConfig: any;
cache: any;
cacheLocation: any;
cacheStrategy: any;
errorOnUnmatchedPattern: any;
extensions: any;
fix: any;
fixTypes: any;
ignore: any;
ignorePath: any;
overrideConfig: {
env: any;
globals: any;
ignorePatterns: any;
parser: any;
parserOptions: any;
plugins: any;
rules: any;
};
overrideConfigFile: any;
reportUnusedDisableDirectives: string | undefined;
resolvePluginsRelativeTo: any;
rulePaths: any;
useEslintrc: any;
};
export { translateOptions };

View File

@@ -0,0 +1,95 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cli_exports = {};
__export(cli_exports, {
translateOptions: () => translateOptions
});
module.exports = __toCommonJS(cli_exports);
function quietFixPredicate(message) {
return message.severity === 2;
}
function translateOptions({
cache,
cacheFile,
cacheLocation,
cacheStrategy,
config,
env,
errorOnUnmatchedPattern,
eslintrc,
ext,
fix,
fixDryRun,
fixType,
global,
ignore,
ignorePath,
ignorePattern,
inlineConfig,
parser,
parserOptions,
plugin,
quiet,
reportUnusedDisableDirectives,
resolvePluginsRelativeTo,
rule,
rulesdir
}) {
return {
allowInlineConfig: inlineConfig,
cache,
cacheLocation: cacheLocation || cacheFile,
cacheStrategy,
errorOnUnmatchedPattern,
extensions: ext,
fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),
fixTypes: fixType,
ignore,
ignorePath,
overrideConfig: {
env: env && env.reduce((obj, name) => {
obj[name] = true;
return obj;
}, {}),
globals: global && global.reduce((obj, name) => {
if (name.endsWith(":true")) {
obj[name.slice(0, -5)] = "writable";
} else {
obj[name] = "readonly";
}
return obj;
}, {}),
ignorePatterns: ignorePattern,
parser,
parserOptions,
plugins: plugin,
rules: rule
},
overrideConfigFile: config,
reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0,
resolvePluginsRelativeTo,
rulePaths: rulesdir,
useEslintrc: eslintrc
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
translateOptions
});
//# sourceMappingURL=cli.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/checkers/eslint/cli.ts"],"sourcesContent":["/* eslint-disable */\n\n/**\n * This file is directly copied from https://github.com/eslint/eslint/blob/6f940c3ce715327f282c197d0f71b91848e5d83d/lib/cli.js\n *\n * Usually, developer rarely use JS programming API to run ESLint. So we let\n * developers to write their own ESLint commands just like in CI or lint-staged.\n * And the config will be translated and pass to `new ESLint(translatedOptions)`.\n * So in build mode, it's the same as the command you pass in.\n * In dev mode, some flag will be ignored (such as `max-warnings`) because it\n * will be only respected in ESLint CLI.\n */\n\n// @ts-expect-error\nfunction quietFixPredicate(message) {\n return message.severity === 2\n}\n\nexport function translateOptions({\n cache,\n cacheFile,\n cacheLocation,\n cacheStrategy,\n config,\n env,\n errorOnUnmatchedPattern,\n eslintrc,\n ext,\n fix,\n fixDryRun,\n fixType,\n global,\n ignore,\n ignorePath,\n ignorePattern,\n inlineConfig,\n parser,\n parserOptions,\n plugin,\n quiet,\n reportUnusedDisableDirectives,\n resolvePluginsRelativeTo,\n rule,\n rulesdir,\n}: any) {\n return {\n allowInlineConfig: inlineConfig,\n cache,\n cacheLocation: cacheLocation || cacheFile,\n cacheStrategy,\n errorOnUnmatchedPattern,\n extensions: ext,\n fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),\n fixTypes: fixType,\n ignore,\n ignorePath,\n overrideConfig: {\n env:\n env &&\n // @ts-expect-error\n env.reduce((obj, name) => {\n obj[name] = true\n return obj\n }, {}),\n globals:\n global &&\n // @ts-expect-error\n global.reduce((obj, name) => {\n if (name.endsWith(':true')) {\n obj[name.slice(0, -5)] = 'writable'\n } else {\n obj[name] = 'readonly'\n }\n return obj\n }, {}),\n ignorePatterns: ignorePattern,\n parser,\n parserOptions,\n plugins: plugin,\n rules: rule,\n },\n overrideConfigFile: config,\n reportUnusedDisableDirectives: reportUnusedDisableDirectives ? 'error' : void 0,\n resolvePluginsRelativeTo,\n rulePaths: rulesdir,\n useEslintrc: eslintrc,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,SAAS,kBAAkB,SAAS;AAClC,SAAO,QAAQ,aAAa;AAC9B;AAEO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAQ;AACN,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,eAAe,iBAAiB;AAAA,IAChC;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ,MAAM,OAAO,eAAe,QAAQ,oBAAoB;AAAA,IACxD,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,KACE,OAEA,IAAI,OAAO,CAAC,KAAK,SAAS;AACxB,YAAI,QAAQ;AACZ,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AAAA,MACP,SACE,UAEA,OAAO,OAAO,CAAC,KAAK,SAAS;AAC3B,YAAI,KAAK,SAAS,OAAO,GAAG;AAC1B,cAAI,KAAK,MAAM,GAAG,EAAE,KAAK;AAAA,QAC3B,OAAO;AACL,cAAI,QAAQ;AAAA,QACd;AACA,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AAAA,MACP,gBAAgB;AAAA,MAChB;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,IACA,oBAAoB;AAAA,IACpB,+BAA+B,gCAAgC,UAAU;AAAA,IACzE;AAAA,IACA,WAAW;AAAA,IACX,aAAa;AAAA,EACf;AACF;","names":[]}

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class EslintChecker extends Checker<'eslint'> {
constructor();
init(): void;
}
export { EslintChecker, createServeAndBuild };

View File

@@ -0,0 +1,169 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var main_exports = {};
__export(main_exports, {
EslintChecker: () => EslintChecker,
createServeAndBuild: () => createServeAndBuild
});
module.exports = __toCommonJS(main_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_chokidar = __toESM(require("chokidar"), 1);
var import_eslint = require("eslint");
var import_path = __toESM(require("path"), 1);
var import_url = require("url");
var import_worker_threads = require("worker_threads");
var import_Checker = require("../../Checker.js");
var import_FileDiagnosticManager = require("../../FileDiagnosticManager.js");
var import_logger = require("../../logger.js");
var import_types = require("../../types.js");
var import_cli = require("./cli.js");
var import_options = require("./options.js");
const __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
const manager = new import_FileDiagnosticManager.FileDiagnosticManager();
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
var _a;
if (!pluginConfig.eslint)
return;
const options = import_options.options.parse(pluginConfig.eslint.lintCommand);
const translatedOptions = (0, import_cli.translateOptions)(options);
const logLevel = (() => {
var _a2;
if (typeof pluginConfig.eslint !== "object")
return void 0;
const userLogLevel = (_a2 = pluginConfig.eslint.dev) == null ? void 0 : _a2.logLevel;
if (!userLogLevel)
return void 0;
const map = {
error: import_types.DiagnosticLevel.Error,
warning: import_types.DiagnosticLevel.Warning
};
return userLogLevel.map((l) => map[l]);
})();
const eslintOptions = {
cwd: root,
...translatedOptions,
...(_a = pluginConfig.eslint.dev) == null ? void 0 : _a.overrideConfig
};
const eslint = new import_eslint.ESLint(eslintOptions);
const dispatchDiagnostics = () => {
var _a2;
const diagnostics2 = (0, import_logger.filterLogLevel)(manager.getDiagnostics(), logLevel);
if (terminal) {
diagnostics2.forEach((d) => {
(0, import_logger.consoleLog)((0, import_logger.diagnosticToTerminalLog)(d, "ESLint"));
});
const errorCount = diagnostics2.filter((d) => d.level === import_types.DiagnosticLevel.Error).length;
const warningCount = diagnostics2.filter((d) => d.level === import_types.DiagnosticLevel.Warning).length;
(0, import_logger.consoleLog)((0, import_logger.composeCheckerSummary)("ESLint", errorCount, warningCount));
}
if (overlay) {
(_a2 = import_worker_threads.parentPort) == null ? void 0 : _a2.postMessage({
type: import_types.ACTION_TYPES.overlayError,
payload: (0, import_logger.toViteCustomPayload)(
"eslint",
diagnostics2.map((d) => (0, import_logger.diagnosticToRuntimeError)(d))
)
});
}
};
const handleFileChange = async (filePath, type) => {
const extension = import_path.default.extname(filePath);
const { extensions } = eslintOptions;
const hasExtensionsConfig = Array.isArray(extensions);
if (hasExtensionsConfig && !extensions.includes(extension))
return;
const isChangedFileIgnored = await eslint.isPathIgnored(filePath);
if (isChangedFileIgnored)
return;
const absPath = import_path.default.resolve(root, filePath);
if (type === "unlink") {
manager.updateByFileId(absPath, []);
} else if (type === "change") {
const diagnosticsOfChangedFile = await eslint.lintFiles(filePath);
const newDiagnostics = diagnosticsOfChangedFile.map((d) => (0, import_logger.normalizeEslintDiagnostic)(d)).flat(1);
manager.updateByFileId(absPath, newDiagnostics);
}
dispatchDiagnostics();
};
const files = options._.slice(1);
const diagnostics = await eslint.lintFiles(files);
manager.initWith(diagnostics.map((p) => (0, import_logger.normalizeEslintDiagnostic)(p)).flat(1));
dispatchDiagnostics();
const watcher = import_chokidar.default.watch([], {
cwd: root,
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(files);
watcher.on("change", async (filePath) => {
handleFileChange(filePath, "change");
});
watcher.on("unlink", async (filePath) => {
handleFileChange(filePath, "unlink");
});
}
};
};
class EslintChecker extends import_Checker.Checker {
constructor() {
super({
name: "eslint",
absFilePath: __filename2,
build: {
buildBin: (pluginConfig) => {
if (pluginConfig.eslint) {
const { lintCommand } = pluginConfig.eslint;
return ["eslint", lintCommand.split(" ").slice(1)];
}
return ["eslint", [""]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const eslintChecker = new EslintChecker();
eslintChecker.prepare();
eslintChecker.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
EslintChecker,
createServeAndBuild
});
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,45 @@
/**
* The options object parsed by Optionator.
* @typedef {Object} ParsedCLIOptions
* @property {boolean} cache Only check changed files
* @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location
* @property {string} [cacheLocation] Path to the cache file or directory
* @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache
* @property {boolean} [color] Force enabling/disabling of color
* @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present
* @property {boolean} debug Output debugging information
* @property {string[]} [env] Specify environments
* @property {boolean} envInfo Output execution environment information
* @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched
* @property {boolean} eslintrc Disable use of configuration from .eslintrc.*
* @property {string[]} [ext] Specify JavaScript file extensions
* @property {boolean} fix Automatically fix problems
* @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system
* @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout)
* @property {string} format Use a specific output format
* @property {string[]} [global] Define global variables
* @property {boolean} [help] Show help
* @property {boolean} ignore Disable use of ignore files and patterns
* @property {string} [ignorePath] Specify path of ignore file
* @property {string[]} [ignorePattern] Pattern of files to ignore (in addition to those in .eslintignore)
* @property {boolean} init Run config initialization wizard
* @property {boolean} inlineConfig Prevent comments from changing config or rules
* @property {number} maxWarnings Number of warnings to trigger nonzero exit code
* @property {string} [outputFile] Specify file to write report to
* @property {string} [parser] Specify the parser to be used
* @property {Object} [parserOptions] Specify parser options
* @property {string[]} [plugin] Specify plugins
* @property {string} [printConfig] Print the configuration for the given file
* @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable directives
* @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default
* @property {Object} [rule] Specify rules
* @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins
* @property {boolean} stdin Lint code provided on <STDIN>
* @property {string} [stdinFilename] Specify filename to process STDIN as
* @property {boolean} quiet Report errors only
* @property {boolean} [version] Output the version number
* @property {string[]} _ Positional filenames or patterns
*/
declare const options: any;
export { options };

View File

@@ -0,0 +1,296 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var options_exports = {};
__export(options_exports, {
options: () => options
});
module.exports = __toCommonJS(options_exports);
var import_optionator = __toESM(require("optionator"), 1);
const options = (0, import_optionator.default)({
prepend: "eslint [options] file.js [file.js] [dir]",
defaults: {
concatRepeatedArrays: true,
mergeRepeatedObjects: true
},
options: [
{
heading: "Basic configuration"
},
{
option: "eslintrc",
type: "Boolean",
default: "true",
description: "Disable use of configuration from .eslintrc.*"
},
{
option: "config",
alias: "c",
type: "path::String",
description: "Use this configuration, overriding .eslintrc.* config options if present"
},
{
option: "env",
type: "[String]",
description: "Specify environments"
},
{
option: "ext",
type: "[String]",
description: "Specify JavaScript file extensions"
},
{
option: "global",
type: "[String]",
description: "Define global variables"
},
{
option: "parser",
type: "String",
description: "Specify the parser to be used"
},
{
option: "parser-options",
type: "Object",
description: "Specify parser options"
},
{
option: "resolve-plugins-relative-to",
type: "path::String",
description: "A folder where plugins should be resolved from, CWD by default"
},
{
heading: "Specifying rules and plugins"
},
{
option: "plugin",
type: "[String]",
description: "Specify plugins"
},
{
option: "rule",
type: "Object",
description: "Specify rules"
},
{
option: "rulesdir",
type: "[path::String]",
description: "Load additional rules from this directory. Deprecated: Use rules from plugins"
},
{
heading: "Fixing problems"
},
{
option: "fix",
type: "Boolean",
default: false,
description: "Automatically fix problems"
},
{
option: "fix-dry-run",
type: "Boolean",
default: false,
description: "Automatically fix problems without saving the changes to the file system"
},
{
option: "fix-type",
type: "Array",
description: "Specify the types of fixes to apply (directive, problem, suggestion, layout)"
},
{
heading: "Ignoring files"
},
{
option: "ignore-path",
type: "path::String",
description: "Specify path of ignore file"
},
{
option: "ignore",
type: "Boolean",
default: "true",
description: "Disable use of ignore files and patterns"
},
{
option: "ignore-pattern",
type: "[String]",
description: "Pattern of files to ignore (in addition to those in .eslintignore)",
concatRepeatedArrays: [
true,
{
oneValuePerFlag: true
}
]
},
{
heading: "Using stdin"
},
{
option: "stdin",
type: "Boolean",
default: "false",
description: "Lint code provided on <STDIN>"
},
{
option: "stdin-filename",
type: "String",
description: "Specify filename to process STDIN as"
},
{
heading: "Handling warnings"
},
{
option: "quiet",
type: "Boolean",
default: "false",
description: "Report errors only"
},
{
option: "max-warnings",
type: "Int",
default: "-1",
description: "Number of warnings to trigger nonzero exit code"
},
{
heading: "Output"
},
{
option: "output-file",
alias: "o",
type: "path::String",
description: "Specify file to write report to"
},
{
option: "format",
alias: "f",
type: "String",
default: "stylish",
description: "Use a specific output format"
},
{
option: "color",
type: "Boolean",
alias: "no-color",
description: "Force enabling/disabling of color"
},
{
heading: "Inline configuration comments"
},
{
option: "inline-config",
type: "Boolean",
default: "true",
description: "Prevent comments from changing config or rules"
},
{
option: "report-unused-disable-directives",
type: "Boolean",
default: void 0,
description: "Adds reported errors for unused eslint-disable directives"
},
{
heading: "Caching"
},
{
option: "cache",
type: "Boolean",
default: "false",
description: "Only check changed files"
},
{
option: "cache-file",
type: "path::String",
default: ".eslintcache",
description: "Path to the cache file. Deprecated: use --cache-location"
},
{
option: "cache-location",
type: "path::String",
description: "Path to the cache file or directory"
},
{
option: "cache-strategy",
dependsOn: ["cache"],
type: "String",
default: "metadata",
enum: ["metadata", "content"],
description: "Strategy to use for detecting changed files in the cache"
},
{
heading: "Miscellaneous"
},
{
option: "init",
type: "Boolean",
default: "false",
description: "Run config initialization wizard"
},
{
option: "env-info",
type: "Boolean",
default: "false",
description: "Output execution environment information"
},
{
option: "error-on-unmatched-pattern",
type: "Boolean",
default: "true",
description: "Prevent errors when pattern is unmatched"
},
{
option: "exit-on-fatal-error",
type: "Boolean",
default: "false",
description: "Exit with exit code 2 in case of fatal error"
},
{
option: "debug",
type: "Boolean",
default: false,
description: "Output debugging information"
},
{
option: "help",
alias: "h",
type: "Boolean",
description: "Show help"
},
{
option: "version",
alias: "v",
type: "Boolean",
description: "Output the version number"
},
{
option: "print-config",
type: "path::String",
description: "Print the configuration for the given file"
}
]
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
options
});
//# sourceMappingURL=options.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class StylelintChecker extends Checker<'stylelint'> {
constructor();
init(): void;
}
export { StylelintChecker, createServeAndBuild };

View File

@@ -0,0 +1,156 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var main_exports = {};
__export(main_exports, {
StylelintChecker: () => StylelintChecker,
createServeAndBuild: () => createServeAndBuild
});
module.exports = __toCommonJS(main_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_chokidar = __toESM(require("chokidar"), 1);
var import_stylelint = __toESM(require("stylelint"), 1);
var import_options = require("./options.js");
var import_path = __toESM(require("path"), 1);
var import_url = require("url");
var import_worker_threads = require("worker_threads");
var import_Checker = require("../../Checker.js");
var import_FileDiagnosticManager = require("../../FileDiagnosticManager.js");
var import_logger = require("../../logger.js");
var import_types = require("../../types.js");
const manager = new import_FileDiagnosticManager.FileDiagnosticManager();
let createServeAndBuild;
const __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
var _a;
if (!pluginConfig.stylelint)
return;
const translatedOptions = (0, import_options.translateOptions)(pluginConfig.stylelint.lintCommand);
const logLevel = (() => {
var _a2;
if (typeof pluginConfig.stylelint !== "object")
return void 0;
const userLogLevel = (_a2 = pluginConfig.stylelint.dev) == null ? void 0 : _a2.logLevel;
if (!userLogLevel)
return void 0;
const map = {
error: import_types.DiagnosticLevel.Error,
warning: import_types.DiagnosticLevel.Warning
};
return userLogLevel.map((l) => map[l]);
})();
const dispatchDiagnostics = () => {
var _a2;
const diagnostics2 = (0, import_logger.filterLogLevel)(manager.getDiagnostics(), logLevel);
if (terminal) {
diagnostics2.forEach((d) => {
(0, import_logger.consoleLog)((0, import_logger.diagnosticToTerminalLog)(d, "Stylelint"));
});
const errorCount = diagnostics2.filter((d) => d.level === import_types.DiagnosticLevel.Error).length;
const warningCount = diagnostics2.filter((d) => d.level === import_types.DiagnosticLevel.Warning).length;
(0, import_logger.consoleLog)((0, import_logger.composeCheckerSummary)("Stylelint", errorCount, warningCount));
}
if (overlay) {
(_a2 = import_worker_threads.parentPort) == null ? void 0 : _a2.postMessage({
type: import_types.ACTION_TYPES.overlayError,
payload: (0, import_logger.toViteCustomPayload)(
"stylelint",
diagnostics2.map((d) => (0, import_logger.diagnosticToRuntimeError)(d))
)
});
}
};
const handleFileChange = async (filePath, type) => {
const absPath = import_path.default.resolve(root, filePath);
if (type === "unlink") {
manager.updateByFileId(absPath, []);
} else if (type === "change") {
const { results: diagnosticsOfChangedFile } = await import_stylelint.default.lint({ files: filePath });
const newDiagnostics = diagnosticsOfChangedFile.map((d) => (0, import_logger.normalizeStylelintDiagnostic)(d)).flat(1);
manager.updateByFileId(absPath, newDiagnostics);
}
dispatchDiagnostics();
};
const { results: diagnostics } = await import_stylelint.default.lint({
cwd: root,
...translatedOptions,
...(_a = pluginConfig.stylelint.dev) == null ? void 0 : _a.overrideConfig
});
manager.initWith(diagnostics.map((p) => (0, import_logger.normalizeStylelintDiagnostic)(p)).flat(1));
dispatchDiagnostics();
const watcher = import_chokidar.default.watch([], {
cwd: root,
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(translatedOptions.files);
watcher.on("change", async (filePath) => {
handleFileChange(filePath, "change");
});
watcher.on("unlink", async (filePath) => {
handleFileChange(filePath, "unlink");
});
}
};
};
class StylelintChecker extends import_Checker.Checker {
constructor() {
super({
name: "stylelint",
absFilePath: __filename2,
build: {
buildBin: (pluginConfig) => {
if (pluginConfig.stylelint) {
const { lintCommand } = pluginConfig.stylelint;
return ["stylelint", lintCommand.split(" ").slice(1)];
}
return ["stylelint", [""]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const stylelintChecker = new StylelintChecker();
stylelintChecker.prepare();
stylelintChecker.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
StylelintChecker,
createServeAndBuild
});
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import Stylelint__default from 'stylelint';
declare const translateOptions: (command: string) => Stylelint__default.LinterOptions;
export { translateOptions };

View File

@@ -0,0 +1,256 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var options_exports = {};
__export(options_exports, {
translateOptions: () => translateOptions
});
module.exports = __toCommonJS(options_exports);
var import_meow = __toESM(require("meow"), 1);
const EXIT_CODE_ERROR = 2;
const translateOptions = (command) => {
const result = (0, import_meow.default)({
autoHelp: false,
autoVersion: false,
help: `
Usage: stylelint [input] [options]
Input: Files(s), glob(s), or nothing to use stdin.
If an input argument is wrapped in quotation marks, it will be passed to
globby for cross-platform glob support. node_modules are always ignored.
You can also pass no input and use stdin, instead.
Options:
--config
Path to a specific configuration file (JSON, YAML, or CommonJS), or the
name of a module in node_modules that points to one. If no --config
argument is provided, stylelint will search for configuration files in
the following places, in this order:
- a stylelint property in package.json
- a .stylelintrc file (with or without filename extension:
.json, .yaml, .yml, and .js are available)
- a stylelint.config.js file exporting a JS object
The search will begin in the working directory and move up the directory
tree until a configuration file is found.
--config-basedir
An absolute path to the directory that relative paths defining "extends"
and "plugins" are *relative to*. Only necessary if these values are
relative paths.
--print-config
Print the configuration for the given path.
--ignore-path, -i
Path to a file containing patterns that describe files to ignore. The
path can be absolute or relative to process.cwd(). By default, stylelint
looks for .stylelintignore in process.cwd().
--ignore-pattern, --ip
Pattern of files to ignore (in addition to those in .stylelintignore)
--fix
Automatically fix problems of certain rules.
--custom-syntax
Module name or path to a JS file exporting a PostCSS-compatible syntax.
--stdin
Accept stdin input even if it is empty.
--stdin-filename
A filename to assign stdin input.
--ignore-disables, --id
Ignore stylelint-disable comments.
--disable-default-ignores, --di
Allow linting of node_modules.
--cache [default: false]
Store the info about processed files in order to only operate on the
changed ones the next time you run stylelint. By default, the cache
is stored in "./.stylelintcache". To adjust this, use --cache-location.
--cache-location [default: '.stylelintcache']
Path to a file or directory to be used for the cache location.
Default is "./.stylelintcache". If a directory is specified, a cache
file will be created inside the specified folder, with a name derived
from a hash of the current working directory.
If the directory for the cache does not exist, make sure you add a trailing "/"
on *nix systems or "\\" on Windows. Otherwise the path will be assumed to be a file.
--formatter, -f [default: "string"]
The output formatter: "compact", "json", "tap", "unix" or "verbose"
--custom-formatter
Path to a JS file exporting a custom formatting function.
--quiet, -q
Only register problems for rules with an "error"-level severity (ignore
"warning"-level).
--color
--no-color
Force enabling/disabling of color.
--report-needless-disables, --rd
Also report errors for stylelint-disable comments that are not blocking a lint warning.
The process will exit with code ${EXIT_CODE_ERROR} if needless disables are found.
--report-invalid-scope-disables, --risd
Report stylelint-disable comments that used for rules that don't exist within the configuration object.
The process will exit with code ${EXIT_CODE_ERROR} if invalid scope disables are found.
--report-descriptionless-disables, --rdd
Report stylelint-disable comments without a description.
The process will exit with code ${EXIT_CODE_ERROR} if descriptionless disables are found.
--max-warnings, --mw
Number of warnings above which the process will exit with code ${EXIT_CODE_ERROR}.
Useful when setting "defaultSeverity" to "warning" and expecting the
process to fail on warnings (e.g. CI build).
--output-file, -o
Path of file to write report.
--version, -v
Show the currently installed version of stylelint.
--allow-empty-input, --aei
When glob pattern matches no files, the process will exit without throwing an error.
`,
flags: {
allowEmptyInput: {
alias: "aei",
type: "boolean"
},
cache: {
type: "boolean"
},
cacheLocation: {
type: "string"
},
color: {
type: "boolean"
},
config: {
type: "string"
},
configBasedir: {
type: "string"
},
customFormatter: {
type: "string"
},
customSyntax: {
type: "string"
},
disableDefaultIgnores: {
alias: "di",
type: "boolean"
},
fix: {
type: "boolean"
},
formatter: {
alias: "f",
default: "json",
type: "string"
},
help: {
alias: "h",
type: "boolean"
},
ignoreDisables: {
alias: "id",
type: "boolean"
},
ignorePath: {
alias: "i",
type: "string"
},
ignorePattern: {
alias: "ip",
type: "string",
isMultiple: true
},
maxWarnings: {
alias: "mw",
type: "number"
},
outputFile: {
alias: "o",
type: "string"
},
printConfig: {
type: "boolean"
},
quiet: {
alias: "q",
type: "boolean"
},
reportDescriptionlessDisables: {
alias: "rdd",
type: "boolean"
},
reportInvalidScopeDisables: {
alias: "risd",
type: "boolean"
},
reportNeedlessDisables: {
alias: "rd",
type: "boolean"
},
stdin: {
type: "boolean"
},
stdinFilename: {
type: "string"
},
syntax: {
alias: "s",
type: "string"
},
version: {
alias: "v",
type: "boolean"
}
},
argv: command.split(" ").filter((item) => !!item)
});
return {
...Object.fromEntries(
Object.entries(result.flags).filter(
([key]) => [
"files",
"globbyOptions",
"cache",
"cacheLocation",
"code",
"codeFilename",
"config",
"configFile",
"configBasedir",
"cwd",
"ignoreDisables",
"ignorePath",
"ignorePattern",
"reportDescriptionlessDisables",
"reportNeedlessDisables",
"reportInvalidScopeDisables",
"maxWarnings",
"customSyntax",
"formatter",
"disableDefaultIgnores",
"fix",
"allowEmptyInput",
"quiet"
].includes(key)
)
),
formatter: result.flags.formatter === "string" ? "json" : result.flags.formatter,
files: result.input[1]
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
translateOptions
});
//# sourceMappingURL=options.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class TscChecker extends Checker<'typescript'> {
constructor();
init(): void;
}
export { TscChecker, createServeAndBuild };

View File

@@ -0,0 +1,169 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var main_exports = {};
__export(main_exports, {
TscChecker: () => TscChecker,
createServeAndBuild: () => createServeAndBuild
});
module.exports = __toCommonJS(main_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_os = __toESM(require("os"), 1);
var import_path = __toESM(require("path"), 1);
var import_tiny_invariant = __toESM(require("tiny-invariant"), 1);
var import_typescript = __toESM(require("typescript"), 1);
var import_url = require("url");
var import_worker_threads = require("worker_threads");
var import_Checker = require("../../Checker.js");
var import_logger = require("../../logger.js");
var import_types = require("../../types.js");
const __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let currDiagnostics = [];
return {
config: async ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
configureServer({ root }) {
(0, import_tiny_invariant.default)(pluginConfig.typescript, "config.typescript should be `false`");
const finalConfig = pluginConfig.typescript === true ? { root, tsconfigPath: "tsconfig.json" } : {
root: pluginConfig.typescript.root ?? root,
tsconfigPath: pluginConfig.typescript.tsconfigPath ?? "tsconfig.json"
};
let configFile;
configFile = import_typescript.default.findConfigFile(finalConfig.root, import_typescript.default.sys.fileExists, finalConfig.tsconfigPath);
if (configFile === void 0) {
throw Error(
`Failed to find a valid tsconfig.json: ${finalConfig.tsconfigPath} at ${finalConfig.root} is not a valid tsconfig`
);
}
let logChunk = "";
const reportDiagnostic = (diagnostic) => {
const normalizedDiagnostic = (0, import_logger.normalizeTsDiagnostic)(diagnostic);
if (normalizedDiagnostic === null) {
return;
}
currDiagnostics.push((0, import_logger.diagnosticToRuntimeError)(normalizedDiagnostic));
logChunk += import_os.default.EOL + (0, import_logger.diagnosticToTerminalLog)(normalizedDiagnostic, "TypeScript");
};
const reportWatchStatusChanged = (diagnostic, newLine, options, errorCount) => {
var _a;
if (diagnostic.code === 6031)
return;
switch (diagnostic.code) {
case 6031:
case 6032:
logChunk = "";
currDiagnostics = [];
return;
case 6193:
case 6194:
if (overlay) {
(_a = import_worker_threads.parentPort) == null ? void 0 : _a.postMessage({
type: import_types.ACTION_TYPES.overlayError,
payload: (0, import_logger.toViteCustomPayload)("typescript", currDiagnostics)
});
}
}
(0, import_logger.ensureCall)(() => {
if (errorCount === 0) {
logChunk = "";
}
if (terminal) {
(0, import_logger.consoleLog)(
logChunk + import_os.default.EOL + (0, import_logger.wrapCheckerSummary)("TypeScript", diagnostic.messageText.toString())
);
}
});
};
const createProgram = import_typescript.default.createEmitAndSemanticDiagnosticsBuilderProgram;
if (typeof pluginConfig.typescript === "object" && pluginConfig.typescript.buildMode) {
const host = import_typescript.default.createSolutionBuilderWithWatchHost(
import_typescript.default.sys,
createProgram,
reportDiagnostic,
void 0,
reportWatchStatusChanged
);
import_typescript.default.createSolutionBuilderWithWatch(host, [configFile], {}).build();
} else {
const host = import_typescript.default.createWatchCompilerHost(
configFile,
{ noEmit: true },
import_typescript.default.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
import_typescript.default.createWatchProgram(host);
}
}
};
};
class TscChecker extends import_Checker.Checker {
constructor() {
super({
name: "typescript",
absFilePath: __filename2,
build: {
buildBin: (config) => {
if (typeof config.typescript === "object") {
const { root, tsconfigPath, buildMode } = config.typescript;
let args = [buildMode ? "-b" : "--noEmit"];
if (tsconfigPath) {
const fullConfigPath = root ? import_path.default.join(root, tsconfigPath) : tsconfigPath;
if (buildMode) {
args = args.concat([fullConfigPath]);
} else {
args = args.concat(["-p", fullConfigPath]);
}
}
return ["tsc", args];
}
return ["tsc", ["--noEmit"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const tscChecker = new TscChecker();
tscChecker.prepare();
tscChecker.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TscChecker,
createServeAndBuild
});
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
import * as vscode_languageserver_node from 'vscode-languageserver/node';
import { Duplex } from 'stream';
import { VLS } from 'vls';
import { DiagnosticSeverity, Logger } from 'vscode-languageserver/node.js';
import { URI } from 'vscode-uri';
import { NormalizedDiagnostic } from '../../logger.js';
import { DeepPartial } from '../../types.js';
import { VlsOptions } from './initParams.js';
import '@babel/code-frame';
import 'vite';
import 'vscode-languageclient';
import 'eslint';
import 'stylelint';
import 'vscode-languageclient/node';
import 'typescript';
import 'worker_threads';
declare type LogLevel = typeof logLevels[number];
declare const logLevels: readonly ["ERROR", "WARN", "INFO", "HINT"];
declare const logLevel2Severity: {
ERROR: 1;
WARN: 2;
INFO: 3;
HINT: 4;
};
interface DiagnosticOptions {
watch: boolean;
verbose: boolean;
config: DeepPartial<VlsOptions> | null;
onDispatchDiagnostics?: (normalized: NormalizedDiagnostic[]) => void;
onDispatchDiagnosticsSummary?: (errorCount: number, warningCount: number) => void;
}
declare function diagnostics(workspace: string | null, logLevel: LogLevel, options?: DiagnosticOptions): Promise<void>;
declare class NullLogger implements Logger {
error(_message: string): void;
warn(_message: string): void;
info(_message: string): void;
log(_message: string): void;
}
declare class TestStream extends Duplex {
_write(chunk: string, _encoding: string, done: () => void): void;
_read(_size: number): void;
}
declare function prepareClientConnection(workspaceUri: URI, severity: DiagnosticSeverity, options: DiagnosticOptions): Promise<{
clientConnection: vscode_languageserver_node.ProtocolConnection;
serverConnection: vscode_languageserver_node.Connection;
vls: VLS;
up: TestStream;
down: TestStream;
logger: NullLogger;
}>;
export { DiagnosticOptions, LogLevel, TestStream, diagnostics, logLevel2Severity, logLevels, prepareClientConnection };

View File

@@ -0,0 +1,326 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var diagnostics_exports = {};
__export(diagnostics_exports, {
TestStream: () => TestStream,
diagnostics: () => diagnostics,
logLevel2Severity: () => logLevel2Severity,
logLevels: () => logLevels,
prepareClientConnection: () => prepareClientConnection
});
module.exports = __toCommonJS(diagnostics_exports);
var import_chalk = __toESM(require("chalk"), 1);
var import_chokidar = __toESM(require("chokidar"), 1);
var import_fast_glob = __toESM(require("fast-glob"), 1);
var import_fs = __toESM(require("fs"), 1);
var import_os = __toESM(require("os"), 1);
var import_path = __toESM(require("path"), 1);
var import_stream = require("stream");
var import_vls = require("vls");
var import_node = require("vscode-languageserver/node.js");
var import_vscode_uri = __toESM(require("vscode-uri"), 1);
var import_logger = require("../../logger.js");
var import_initParams = require("./initParams.js");
var import_FileDiagnosticManager = require("../../FileDiagnosticManager.js");
const { URI } = import_vscode_uri.default;
var DOC_VERSION = /* @__PURE__ */ ((DOC_VERSION2) => {
DOC_VERSION2[DOC_VERSION2["init"] = -1] = "init";
return DOC_VERSION2;
})(DOC_VERSION || {});
const logLevels = ["ERROR", "WARN", "INFO", "HINT"];
let disposeSuppressConsole;
let initialVueFilesCount = 0;
let initialVueFilesTick = 0;
const fileDiagnosticManager = new import_FileDiagnosticManager.FileDiagnosticManager();
const logLevel2Severity = {
ERROR: import_node.DiagnosticSeverity.Error,
WARN: import_node.DiagnosticSeverity.Warning,
INFO: import_node.DiagnosticSeverity.Information,
HINT: import_node.DiagnosticSeverity.Hint
};
async function diagnostics(workspace, logLevel, options = { watch: false, verbose: false, config: null }) {
var _a;
if (options.verbose) {
console.log("====================================");
console.log("Getting Vetur diagnostics");
}
let workspaceUri;
if (workspace) {
const absPath = import_path.default.resolve(process.cwd(), workspace);
console.log(`Loading Vetur in workspace path: ${import_chalk.default.green(absPath)}`);
workspaceUri = URI.file(absPath);
} else {
console.log(`Loading Vetur in current directory: ${import_chalk.default.green(process.cwd())}`);
workspaceUri = URI.file(process.cwd());
}
const result = await getDiagnostics(workspaceUri, logLevel2Severity[logLevel], options);
if (options.verbose) {
console.log("====================================");
}
if (!options.watch && typeof result === "object" && result !== null) {
const { initialErrorCount, initialWarningCount } = result;
(_a = options == null ? void 0 : options.onDispatchDiagnosticsSummary) == null ? void 0 : _a.call(options, initialErrorCount, initialWarningCount);
process.exit(initialErrorCount > 0 ? 1 : 0);
}
}
class NullLogger {
error(_message) {
}
warn(_message) {
}
info(_message) {
}
log(_message) {
}
}
class TestStream extends import_stream.Duplex {
_write(chunk, _encoding, done) {
this.emit("data", chunk);
done();
}
_read(_size) {
}
}
function suppressConsole() {
let disposed = false;
const rawConsoleLog = console.log;
console.log = () => {
};
return () => {
if (disposed)
return;
disposed = true;
console.log = rawConsoleLog;
};
}
async function prepareClientConnection(workspaceUri, severity, options) {
const up = new TestStream();
const down = new TestStream();
const logger = new NullLogger();
const clientConnection = (0, import_node.createProtocolConnection)(
new import_node.StreamMessageReader(down),
new import_node.StreamMessageWriter(up),
logger
);
const serverConnection = (0, import_node.createConnection)(
new import_node.StreamMessageReader(up),
new import_node.StreamMessageWriter(down)
);
serverConnection.sendDiagnostics = async (publishDiagnostics) => {
var _a, _b;
disposeSuppressConsole == null ? void 0 : disposeSuppressConsole();
if (publishDiagnostics.version === -1 /* init */) {
return;
}
const absFilePath = URI.parse(publishDiagnostics.uri).fsPath;
publishDiagnostics.diagnostics = filterDiagnostics(publishDiagnostics.diagnostics, severity);
const nextDiagnosticInFile = await (0, import_logger.normalizePublishDiagnosticParams)(publishDiagnostics);
fileDiagnosticManager.updateByFileId(absFilePath, nextDiagnosticInFile);
const normalized = fileDiagnosticManager.getDiagnostics();
const errorCount = normalized.filter((d) => d.level === import_node.DiagnosticSeverity.Error).length;
const warningCount = normalized.filter((d) => d.level === import_node.DiagnosticSeverity.Warning).length;
initialVueFilesTick++;
if (initialVueFilesTick >= initialVueFilesCount) {
(_a = options.onDispatchDiagnostics) == null ? void 0 : _a.call(options, normalized);
(_b = options.onDispatchDiagnosticsSummary) == null ? void 0 : _b.call(options, errorCount, warningCount);
}
};
const vls = new import_vls.VLS(serverConnection);
vls.validateTextDocument = async (textDocument, cancellationToken) => {
const diagnostics2 = await vls.doValidate(textDocument, cancellationToken);
if (diagnostics2) {
vls.lspConnection.sendDiagnostics({
uri: textDocument.uri,
version: textDocument.version,
diagnostics: diagnostics2
});
}
};
serverConnection.onInitialize(async (params) => {
await vls.init(params);
if (options.verbose) {
console.log("Vetur initialized");
console.log("====================================");
}
return {
capabilities: vls.capabilities
};
});
vls.listen();
clientConnection.listen();
const initParams = (0, import_initParams.getInitParams)(workspaceUri);
if (options.config) {
mergeDeep(initParams.initializationOptions.config, options.config);
}
await clientConnection.sendRequest(import_node.InitializeRequest.type, initParams);
return { clientConnection, serverConnection, vls, up, down, logger };
}
function extToGlobs(exts) {
return exts.map((e) => "**/*" + e);
}
const watchedDidChangeContent = [".vue"];
const watchedDidChangeWatchedFiles = [".js", ".ts", ".json"];
const watchedDidChangeContentGlob = extToGlobs(watchedDidChangeContent);
async function getDiagnostics(workspaceUri, severity, options) {
const { clientConnection } = await prepareClientConnection(workspaceUri, severity, options);
const files = import_fast_glob.default.sync([...watchedDidChangeContentGlob], {
cwd: workspaceUri.fsPath,
ignore: ["node_modules/**"]
});
if (files.length === 0) {
console.log("[VLS checker] No input files");
return { initialWarningCount: 0, initialErrorCount: 0 };
}
if (options.verbose) {
console.log("");
console.log("Getting diagnostics from: ", files, "\n");
}
const absFilePaths = files.map((f) => import_path.default.resolve(workspaceUri.fsPath, f));
disposeSuppressConsole = suppressConsole();
initialVueFilesCount = absFilePaths.length;
let initialErrorCount = 0;
let initialWarningCount = 0;
await Promise.all(
absFilePaths.map(async (absFilePath) => {
const fileText = await import_fs.default.promises.readFile(absFilePath, "utf-8");
clientConnection.sendNotification(import_node.DidOpenTextDocumentNotification.type, {
textDocument: {
languageId: "vue",
uri: URI.file(absFilePath).toString(),
version: -1 /* init */,
text: fileText
}
});
if (options.watch)
return;
try {
let diagnostics2 = await clientConnection.sendRequest("$/getDiagnostics", {
uri: URI.file(absFilePath).toString(),
version: -1 /* init */
});
diagnostics2 = filterDiagnostics(diagnostics2, severity);
let logChunk = "";
if (diagnostics2.length > 0) {
logChunk += import_os.default.EOL + diagnostics2.map(
(d) => (0, import_logger.diagnosticToTerminalLog)(
(0, import_logger.normalizeLspDiagnostic)({
diagnostic: d,
absFilePath,
fileText
}),
"VLS"
)
).join(import_os.default.EOL);
diagnostics2.forEach((d) => {
if (d.severity === import_node.DiagnosticSeverity.Error) {
initialErrorCount++;
}
if (d.severity === import_node.DiagnosticSeverity.Warning) {
initialWarningCount++;
}
});
}
console.log(logChunk);
return { initialErrorCount, initialWarningCount };
} catch (err) {
console.error(err.stack);
return { initialErrorCount, initialWarningCount };
}
})
);
if (!options.watch) {
return { initialErrorCount, initialWarningCount };
}
await Promise.all(
absFilePaths.map(async (absFilePath) => {
const fileText = await import_fs.default.promises.readFile(absFilePath, "utf-8");
clientConnection.sendNotification(import_node.DidOpenTextDocumentNotification.type, {
textDocument: {
languageId: "vue",
uri: URI.file(absFilePath).toString(),
version: -1 /* init */,
text: fileText
}
});
})
);
const watcher = import_chokidar.default.watch([], {
ignored: (path2) => path2.includes("node_modules")
});
watcher.add(workspaceUri.fsPath);
watcher.on("all", async (event, filePath) => {
const extname = import_path.default.extname(filePath);
if (!filePath.endsWith(".vue"))
return;
const fileContent = await import_fs.default.promises.readFile(filePath, "utf-8");
clientConnection.sendNotification(import_node.DidChangeTextDocumentNotification.type, {
textDocument: {
uri: URI.file(filePath).toString(),
version: Date.now()
},
contentChanges: [{ text: fileContent }]
});
if (watchedDidChangeWatchedFiles.includes(extname)) {
clientConnection.sendNotification(import_node.DidChangeWatchedFilesNotification.type, {
changes: [
{
uri: URI.file(filePath).toString(),
type: event === "add" ? 1 : event === "unlink" ? 3 : 2
}
]
});
}
});
return null;
}
function isObject(item) {
return item && typeof item === "object" && !Array.isArray(item);
}
function mergeDeep(target, source) {
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key])
Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return target;
}
function filterDiagnostics(diagnostics2, severity) {
return diagnostics2.filter((r) => r.source !== "eslint-plugin-vue").filter((r) => r.severity && r.severity <= severity);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TestStream,
diagnostics,
logLevel2Severity,
logLevels,
prepareClientConnection
});
//# sourceMappingURL=diagnostics.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
import { URI } from 'vscode-uri';
import { InitializeParams } from 'vscode-languageserver/node';
declare type VlsOptions = ReturnType<typeof getDefaultVLSConfig>;
declare function getInitParams(workspaceUri: URI): InitializeParams;
declare function getDefaultVLSConfig(): {
vetur: {
ignoreProjectWarning: boolean;
useWorkspaceDependencies: boolean;
validation: {
template: boolean;
templateProps: boolean;
interpolation: boolean;
style: boolean;
script: boolean;
};
completion: {
autoImport: boolean;
tagCasing: string;
scaffoldSnippetSources: {
workspace: string;
user: string;
vetur: string;
};
};
grammar: {
customBlocks: {};
};
format: {
enable: boolean;
options: {
tabSize: number;
useTabs: boolean;
};
defaultFormatter: {};
defaultFormatterOptions: {};
scriptInitialIndent: boolean;
styleInitialIndent: boolean;
};
languageFeatures: {
codeActions: boolean;
updateImportOnFileMove: boolean;
semanticTokens: boolean;
};
trace: {
server: string;
};
dev: {
vlsPath: string;
vlsPort: number;
logLevel: string;
};
experimental: {
templateInterpolationService: boolean;
};
};
css: {};
html: {
suggest: {};
};
javascript: {
format: {};
};
typescript: {
tsdk: null;
format: {};
};
emmet: {};
stylusSupremacy: {};
};
export { VlsOptions, getDefaultVLSConfig, getInitParams };

View File

@@ -0,0 +1,120 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var initParams_exports = {};
__export(initParams_exports, {
getDefaultVLSConfig: () => getDefaultVLSConfig,
getInitParams: () => getInitParams
});
module.exports = __toCommonJS(initParams_exports);
function getInitParams(workspaceUri) {
const defaultVLSConfig = getDefaultVLSConfig();
defaultVLSConfig.vetur.validation = {
template: true,
style: true,
script: true,
interpolation: true,
templateProps: true
};
defaultVLSConfig.vetur.experimental = {
templateInterpolationService: true
};
const init = {
rootPath: workspaceUri.fsPath,
rootUri: workspaceUri.toString(),
processId: process.pid,
capabilities: {},
initializationOptions: {
config: defaultVLSConfig
}
};
return init;
}
function getDefaultVLSConfig() {
return {
vetur: {
ignoreProjectWarning: false,
useWorkspaceDependencies: false,
validation: {
template: true,
templateProps: true,
interpolation: true,
style: true,
script: true
},
completion: {
autoImport: false,
tagCasing: "initial",
scaffoldSnippetSources: {
workspace: "\u{1F4BC}",
user: "\u{1F5D2}\uFE0F",
vetur: "\u270C"
}
},
grammar: {
customBlocks: {}
},
format: {
enable: true,
options: {
tabSize: 2,
useTabs: false
},
defaultFormatter: {},
defaultFormatterOptions: {},
scriptInitialIndent: false,
styleInitialIndent: false
},
languageFeatures: {
codeActions: true,
updateImportOnFileMove: true,
semanticTokens: true
},
trace: {
server: "off"
},
dev: {
vlsPath: "",
vlsPort: -1,
logLevel: "INFO"
},
experimental: {
templateInterpolationService: false
}
},
css: {},
html: {
suggest: {}
},
javascript: {
format: {}
},
typescript: {
tsdk: null,
format: {}
},
emmet: {},
stylusSupremacy: {}
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getDefaultVLSConfig,
getInitParams
});
//# sourceMappingURL=initParams.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/checkers/vls/initParams.ts"],"sourcesContent":["import type { URI } from 'vscode-uri'\n\nimport type { InitializeParams } from 'vscode-languageserver/node'\n\nexport type VlsOptions = ReturnType<typeof getDefaultVLSConfig>\n\nexport function getInitParams(workspaceUri: URI): InitializeParams {\n const defaultVLSConfig = getDefaultVLSConfig()\n\n defaultVLSConfig.vetur.validation = {\n template: true,\n style: true,\n script: true,\n interpolation: true,\n templateProps: true,\n }\n defaultVLSConfig.vetur.experimental = {\n templateInterpolationService: true,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const init: InitializeParams = {\n rootPath: workspaceUri.fsPath,\n rootUri: workspaceUri.toString(),\n processId: process.pid,\n capabilities: {},\n initializationOptions: {\n config: defaultVLSConfig,\n },\n } as InitializeParams\n\n return init\n}\n\nexport function getDefaultVLSConfig() {\n return {\n vetur: {\n ignoreProjectWarning: false,\n useWorkspaceDependencies: false,\n validation: {\n template: true,\n templateProps: true,\n interpolation: true,\n style: true,\n script: true,\n },\n completion: {\n autoImport: false,\n tagCasing: 'initial',\n scaffoldSnippetSources: {\n workspace: '💼',\n user: '🗒️',\n vetur: '✌',\n },\n },\n grammar: {\n customBlocks: {},\n },\n format: {\n enable: true,\n options: {\n tabSize: 2,\n useTabs: false,\n },\n defaultFormatter: {},\n defaultFormatterOptions: {},\n scriptInitialIndent: false,\n styleInitialIndent: false,\n },\n languageFeatures: {\n codeActions: true,\n updateImportOnFileMove: true,\n semanticTokens: true,\n },\n trace: {\n server: 'off',\n },\n dev: {\n vlsPath: '',\n vlsPort: -1,\n logLevel: 'INFO',\n },\n experimental: {\n templateInterpolationService: false,\n },\n },\n css: {},\n html: {\n suggest: {},\n },\n javascript: {\n format: {},\n },\n typescript: {\n tsdk: null,\n format: {},\n },\n emmet: {},\n stylusSupremacy: {},\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,SAAS,cAAc,cAAqC;AACjE,QAAM,mBAAmB,oBAAoB;AAE7C,mBAAiB,MAAM,aAAa;AAAA,IAClC,UAAU;AAAA,IACV,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,eAAe;AAAA,IACf,eAAe;AAAA,EACjB;AACA,mBAAiB,MAAM,eAAe;AAAA,IACpC,8BAA8B;AAAA,EAChC;AAGA,QAAM,OAAyB;AAAA,IAC7B,UAAU,aAAa;AAAA,IACvB,SAAS,aAAa,SAAS;AAAA,IAC/B,WAAW,QAAQ;AAAA,IACnB,cAAc,CAAC;AAAA,IACf,uBAAuB;AAAA,MACrB,QAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,sBAAsB;AACpC,SAAO;AAAA,IACL,OAAO;AAAA,MACL,sBAAsB;AAAA,MACtB,0BAA0B;AAAA,MAC1B,YAAY;AAAA,QACV,UAAU;AAAA,QACV,eAAe;AAAA,QACf,eAAe;AAAA,QACf,OAAO;AAAA,QACP,QAAQ;AAAA,MACV;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,wBAAwB;AAAA,UACtB,WAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,QACT;AAAA,MACF;AAAA,MACA,SAAS;AAAA,QACP,cAAc,CAAC;AAAA,MACjB;AAAA,MACA,QAAQ;AAAA,QACN,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,SAAS;AAAA,UACT,SAAS;AAAA,QACX;AAAA,QACA,kBAAkB,CAAC;AAAA,QACnB,yBAAyB,CAAC;AAAA,QAC1B,qBAAqB;AAAA,QACrB,oBAAoB;AAAA,MACtB;AAAA,MACA,kBAAkB;AAAA,QAChB,aAAa;AAAA,QACb,wBAAwB;AAAA,QACxB,gBAAgB;AAAA,MAClB;AAAA,MACA,OAAO;AAAA,QACL,QAAQ;AAAA,MACV;AAAA,MACA,KAAK;AAAA,QACH,SAAS;AAAA,QACT,SAAS;AAAA,QACT,UAAU;AAAA,MACZ;AAAA,MACA,cAAc;AAAA,QACZ,8BAA8B;AAAA,MAChC;AAAA,IACF;AAAA,IACA,KAAK,CAAC;AAAA,IACN,MAAM;AAAA,MACJ,SAAS,CAAC;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,OAAO,CAAC;AAAA,IACR,iBAAiB,CAAC;AAAA,EACpB;AACF;","names":[]}

View File

@@ -0,0 +1,19 @@
import { Checker } from '../../Checker.js';
import { CreateDiagnostic } from '../../types.js';
import 'vite';
import '../../worker.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import './initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare const createDiagnostic: CreateDiagnostic<'vls'>;
declare class VlsChecker extends Checker<'vls'> {
constructor();
init(): void;
}
export { VlsChecker, createDiagnostic, createServeAndBuild };

View File

@@ -0,0 +1,120 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var main_exports = {};
__export(main_exports, {
VlsChecker: () => VlsChecker,
createDiagnostic: () => createDiagnostic,
createServeAndBuild: () => createServeAndBuild
});
module.exports = __toCommonJS(main_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_os = __toESM(require("os"), 1);
var import_url = require("url");
var import_worker_threads = require("worker_threads");
var import_Checker = require("../../Checker.js");
var import_logger = require("../../logger.js");
var import_types = require("../../types.js");
var import_diagnostics = require("./diagnostics.js");
const __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let command;
return {
config: ({ enableOverlay, enableTerminal, env }) => {
overlay = enableOverlay;
terminal = enableTerminal;
command = env.command;
},
async configureServer({ root }) {
const workDir = root;
const onDispatchDiagnosticsSummary = (errorCount, warningCount) => {
if (!terminal)
return;
(0, import_logger.consoleLog)((0, import_logger.composeCheckerSummary)("VLS", errorCount, warningCount));
};
const onDispatchDiagnostics = (normalized) => {
var _a;
if (overlay && command === "serve") {
(_a = import_worker_threads.parentPort) == null ? void 0 : _a.postMessage({
type: import_types.ACTION_TYPES.overlayError,
payload: (0, import_logger.toViteCustomPayload)("vls", (0, import_logger.diagnosticToRuntimeError)(normalized))
});
}
if (terminal) {
(0, import_logger.consoleLog)(normalized.map((d) => (0, import_logger.diagnosticToTerminalLog)(d, "VLS")).join(import_os.default.EOL));
}
};
const vlsConfig = pluginConfig == null ? void 0 : pluginConfig.vls;
await (0, import_diagnostics.diagnostics)(workDir, "WARN", {
onDispatchDiagnostics,
onDispatchDiagnosticsSummary,
watch: true,
verbose: false,
config: typeof vlsConfig === "object" ? vlsConfig : null
});
}
};
};
class VlsChecker extends import_Checker.Checker {
constructor() {
super({
name: "vls",
absFilePath: __filename2,
build: {
buildBin: (config) => {
if (typeof config.vls === "object") {
return [
"vti",
[
"diagnostics",
'"' + JSON.stringify(config.vls).replace(/[\\"]/g, "\\$&") + '"'
]
];
}
return ["vti", ["diagnostics"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const vlsChecker = new VlsChecker();
vlsChecker.prepare();
vlsChecker.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
VlsChecker,
createDiagnostic,
createServeAndBuild
});
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,2 @@
"use strict";
//# sourceMappingURL=typings.d.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View File

@@ -0,0 +1,18 @@
import { Checker } from '../../Checker.js';
import 'vite';
import '../../worker.js';
import '../../types.js';
import 'worker_threads';
import 'eslint';
import 'stylelint';
import '../vls/initParams.js';
import 'vscode-uri';
import 'vscode-languageserver/node';
declare let createServeAndBuild: any;
declare class VueTscChecker extends Checker<'vueTsc'> {
constructor();
init(): void;
}
export { VueTscChecker, createServeAndBuild };

View File

@@ -0,0 +1,162 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var main_exports = {};
__export(main_exports, {
VueTscChecker: () => VueTscChecker,
createServeAndBuild: () => createServeAndBuild
});
module.exports = __toCommonJS(main_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_module = require("module");
var import_os = __toESM(require("os"), 1);
var import_path = __toESM(require("path"), 1);
var import_tiny_invariant = __toESM(require("tiny-invariant"), 1);
var import_url = require("url");
var import_worker_threads = require("worker_threads");
var import_Checker = require("../../Checker.js");
var import_logger = require("../../logger.js");
var import_types = require("../../types.js");
var import_prepareVueTsc = require("./prepareVueTsc.js");
const _require = (0, import_module.createRequire)(importMetaUrl);
const __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
let createServeAndBuild;
const createDiagnostic = (pluginConfig) => {
let overlay = true;
let terminal = true;
let currDiagnostics = [];
return {
config: ({ enableOverlay, enableTerminal }) => {
overlay = enableOverlay;
terminal = enableTerminal;
},
async configureServer({ root }) {
(0, import_tiny_invariant.default)(pluginConfig.vueTsc, "config.vueTsc should be `false`");
const { targetTsDir } = await (0, import_prepareVueTsc.prepareVueTsc)();
const vueTs = _require(import_path.default.resolve(targetTsDir, "lib/tsc.js"));
const finalConfig = pluginConfig.vueTsc === true ? { root, tsconfigPath: "tsconfig.json" } : {
root: pluginConfig.vueTsc.root ?? root,
tsconfigPath: pluginConfig.vueTsc.tsconfigPath ?? "tsconfig.json"
};
let configFile;
configFile = vueTs.findConfigFile(
finalConfig.root,
vueTs.sys.fileExists,
finalConfig.tsconfigPath
);
if (configFile === void 0) {
throw Error(
`Failed to find a valid tsconfig.json: ${finalConfig.tsconfigPath} at ${finalConfig.root} is not a valid tsconfig`
);
}
let logChunk = "";
const reportDiagnostic = (diagnostic) => {
const normalizedDiagnostic = (0, import_logger.normalizeVueTscDiagnostic)(diagnostic);
if (normalizedDiagnostic === null) {
return;
}
currDiagnostics.push((0, import_logger.diagnosticToRuntimeError)(normalizedDiagnostic));
logChunk += import_os.default.EOL + (0, import_logger.diagnosticToTerminalLog)(normalizedDiagnostic, "vue-tsc");
};
const reportWatchStatusChanged = (diagnostic, newLine, options, errorCount) => {
var _a;
if (diagnostic.code === 6031)
return;
switch (diagnostic.code) {
case 6031:
case 6032:
logChunk = "";
currDiagnostics = [];
return;
case 6193:
case 6194:
if (overlay) {
(_a = import_worker_threads.parentPort) == null ? void 0 : _a.postMessage({
type: import_types.ACTION_TYPES.overlayError,
payload: (0, import_logger.toViteCustomPayload)("vue-tsc", currDiagnostics)
});
}
}
(0, import_logger.ensureCall)(() => {
if (errorCount === 0) {
logChunk = "";
}
if (terminal) {
(0, import_logger.consoleLog)(
logChunk + import_os.default.EOL + (0, import_logger.wrapCheckerSummary)("vue-tsc", diagnostic.messageText.toString())
);
}
});
};
const createProgram = vueTs.createSemanticDiagnosticsBuilderProgram;
const host = vueTs.createWatchCompilerHost(
configFile,
{ noEmit: true },
vueTs.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
vueTs.createWatchProgram(host);
}
};
};
class VueTscChecker extends import_Checker.Checker {
constructor() {
super({
name: "vueTsc",
absFilePath: __filename2,
build: {
buildBin: (config) => {
if (typeof config.vueTsc === "object") {
const { root, tsconfigPath } = config.vueTsc;
let args = ["--noEmit"];
if (tsconfigPath) {
const fullConfigPath = root ? import_path.default.join(root, tsconfigPath) : tsconfigPath;
args = args.concat(["-p", fullConfigPath]);
}
return ["vue-tsc", args];
}
return ["vue-tsc", ["--noEmit"]];
}
},
createDiagnostic
});
}
init() {
const _createServeAndBuild = super.initMainThread();
createServeAndBuild = _createServeAndBuild;
super.initWorkerThread();
}
}
const tscChecker = new VueTscChecker();
tscChecker.prepare();
tscChecker.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
VueTscChecker,
createServeAndBuild
});
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
declare function prepareVueTsc(): {
targetTsDir: string;
};
export { prepareVueTsc };

View File

@@ -0,0 +1,141 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var prepareVueTsc_exports = {};
__export(prepareVueTsc_exports, {
prepareVueTsc: () => prepareVueTsc
});
module.exports = __toCommonJS(prepareVueTsc_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
var import_fs = __toESM(require("fs"), 1);
var import_module = require("module");
var import_path = __toESM(require("path"), 1);
var import_url = require("url");
const _require = (0, import_module.createRequire)(importMetaUrl);
const _filename = (0, import_url.fileURLToPath)(importMetaUrl);
const _dirname = (0, import_path.dirname)(_filename);
let proxyPath;
let createProgramFunction;
try {
proxyPath = _require.resolve("vue-tsc/out/index");
createProgramFunction = "createProgram";
} catch (e) {
proxyPath = _require.resolve("vue-tsc/out/proxy");
createProgramFunction = "createProgramProxy";
}
const textToReplace = [
{
target: `ts.supportedTSExtensions = [[".ts", ".tsx", ".d.ts"], [".cts", ".d.cts"], [".mts", ".d.mts"]];`,
replacement: `ts.supportedTSExtensions = [[".ts", ".tsx", ".d.ts"], [".cts", ".d.cts"], [".mts", ".d.mts"], [".vue"]];`
},
{
target: `ts.supportedJSExtensions = [[".js", ".jsx"], [".mjs"], [".cjs"]];`,
replacement: `ts.supportedJSExtensions = [[".js", ".jsx"], [".mjs"], [".cjs"], [".vue"]];`
},
{
target: `var allSupportedExtensions = [[".ts", ".tsx", ".d.ts", ".js", ".jsx"], [".cts", ".d.cts", ".cjs"], [".mts", ".d.mts", ".mjs"]];`,
replacement: `var allSupportedExtensions = [[".ts", ".tsx", ".d.ts", ".js", ".jsx"], [".cts", ".d.cts", ".cjs"], [".mts", ".d.mts", ".mjs"], [".vue"]];`
},
{
target: `function createIncrementalProgram(_a) {`,
replacement: `function createIncrementalProgram(_a) { console.error('incremental mode is not yet supported'); throw 'incremental mode is not yet supported';`
},
{
target: `function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {`,
replacement: `function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { return require(${JSON.stringify(
proxyPath
)}).${createProgramFunction}(...arguments);`
},
{
target: `ts.executeCommandLine(ts.sys, ts.noop, ts.sys.args);`,
replacement: `module.exports = ts`
}
];
function prepareVueTsc() {
const targetTsDir = import_path.default.resolve(_dirname, "typescript-vue-tsc");
const vueTscFlagFile = import_path.default.resolve(targetTsDir, "vue-tsc-resolve-path");
let shouldPrepare = true;
const targetDirExist = import_fs.default.existsSync(targetTsDir);
if (targetDirExist) {
try {
const targetTsVersion = _require(import_path.default.resolve(targetTsDir, "package.json")).version;
const currTsVersion = _require("typescript/package.json").version;
if (targetTsVersion === currTsVersion && import_fs.default.existsSync(vueTscFlagFile) && import_fs.default.readFileSync(vueTscFlagFile, "utf8") === proxyPath) {
shouldPrepare = true;
}
} catch {
shouldPrepare = true;
}
}
if (shouldPrepare) {
rimraf(targetTsDir);
import_fs.default.mkdirSync(targetTsDir);
const sourceTsDir = import_path.default.resolve(_require.resolve("typescript"), "../..");
copyDirRecursively(sourceTsDir, targetTsDir);
import_fs.default.writeFileSync(vueTscFlagFile, proxyPath);
const tscJs = _require.resolve(import_path.default.resolve(targetTsDir, "lib/tsc.js"));
modifyFileText(tscJs, textToReplace);
}
return { targetTsDir };
}
function modifyFileText(filePath, textToReplace2) {
const text = import_fs.default.readFileSync(filePath, "utf8");
let newText = text;
for (const { target, replacement } of textToReplace2) {
newText = newText.replace(target, replacement);
}
import_fs.default.writeFileSync(filePath, newText);
}
function copyDirRecursively(src, dest) {
const files = import_fs.default.readdirSync(src, { withFileTypes: true });
for (const file of files) {
const srcPath = import_path.default.join(src, file.name);
const destPath = import_path.default.join(dest, file.name);
if (file.isDirectory()) {
import_fs.default.mkdirSync(destPath, { recursive: true });
copyDirRecursively(srcPath, destPath);
} else {
import_fs.default.copyFileSync(srcPath, destPath);
}
}
}
function rimraf(dir_path) {
if (import_fs.default.existsSync(dir_path)) {
import_fs.default.readdirSync(dir_path).forEach((entry) => {
const entry_path = import_path.default.join(dir_path, entry);
if (import_fs.default.lstatSync(entry_path).isDirectory()) {
rimraf(entry_path);
} else {
import_fs.default.unlinkSync(entry_path);
}
});
import_fs.default.rmdirSync(dir_path);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
prepareVueTsc
});
//# sourceMappingURL=prepareVueTsc.js.map

File diff suppressed because one or more lines are too long