@sanity/plugin-kit

6.0.47.0.0
dist/_chunks-es/verify-common.js
+dist/_chunks-es/verify-common.jsNew file
+145
Index: package/dist/_chunks-es/verify-common.js
===================================================================
--- package/dist/_chunks-es/verify-common.js
+++ package/dist/_chunks-es/verify-common.js
@@ -0,0 +1,145 @@
+import { a as urls } from "./constants.js";
+import { n as sharedFlags_default, t as log_default } from "./log.js";
+import { P as fileExists, W as mergedPackages } from "./package.js";
+import chalk from "chalk";
+import path from "path";
+import outdent from "outdent";
+import childProcess from "child_process";
+import { ESLint } from "eslint";
+import * as ts from "@typescript/typescript6";
+import npmRunPath from "npm-run-path";
+const removedImportSuffix = `imports where removed in Sanity v3. Please refer to the migration guide: ${urls.migrationGuideStudio}, or new API-reference docs: ${urls.refDocs}`;
+async function validateImports({ basePath }) {
+	log_default.debug("Running ESLint with Sanity Studio import hints...");
+	let eslint = new ESLint({
+		cwd: basePath,
+		overrideConfig: {
+			ignorePatterns: ["node_modules"],
+			rules: { "no-restricted-imports": ["error", { patterns: [
+				...mergedPackages.map((packageName) => ({
+					group: [`${packageName}*`],
+					message: `Use sanity instead of ${packageName}.`
+				})),
+				{
+					group: ["config:*"],
+					message: `config: imports are no longer supported. Please see the new plugin API for alternatives: ${urls.migrationGuideStudio}`
+				},
+				{
+					group: ["part:*"],
+					message: `part: ${removedImportSuffix}`
+				},
+				{
+					group: ["all:part:*"],
+					message: `all:part: ${removedImportSuffix}`
+				},
+				{
+					group: ["sanity:*"],
+					message: `sanity: ${removedImportSuffix}`
+				}
+			] }] }
+		}
+	});
+	try {
+		let onlyImportErrors = (await eslint.lintFiles([path.join(basePath, "**/*.{js,jsx,ts,tsx}")])).map((r) => {
+			let limitErrors = r.messages.filter((m) => m.ruleId === "no-restricted-imports");
+			return {
+				...r,
+				messages: limitErrors,
+				errorCount: limitErrors.length
+			};
+		}).filter((r) => r.errorCount);
+		if (onlyImportErrors.length) return [await (await eslint.loadFormatter("stylish")).format(onlyImportErrors) + outdent`
+        ESLint detected Studio V2 imports that are no longer available.
+        It is recommended configure @sanity/eslint-config-no-v2-imports for ESLint.
+
+        Run:
+        npm install --save-dev @sanity/eslint-config-no-v2-imports
+
+        In .eslintrc add:
+        "extends": ["@sanity/no-v2-imports"]
+
+        This way, V2-imports can be identified directly in the IDE, or using eslint CLI.
+        For more, see ${urls.linterPackage}
+
+        If the plugin package does not use eslint, disable this check.
+    `];
+	} catch (e) {
+		return log_default.error("Failed to run eslint check", e), [outdent`
+        Failed to run ESLint. Is ESLint configured?
+
+        If the package does not use eslint, disable this check.
+    `];
+	}
+	return [];
+}
+async function readTSConfig(options) {
+	let { basePath, filename } = options, filePath = path.resolve(basePath, filename);
+	if (!await fileExists(filePath)) return;
+	let { config } = ts.readConfigFile(filePath, ts.sys.readFile);
+	if (config) return ts.parseJsonConfigFileContent(config, ts.sys, basePath);
+}
+function parseCommand(commandString) {
+	let commandAndArg = commandString.replace(/ +/g, " ").split(" ");
+	return {
+		command: commandAndArg[0],
+		args: commandAndArg.length > 1 ? commandAndArg.slice(1) : []
+	};
+}
+async function runCommand(commandString) {
+	log_default.info(`Running command: ${commandString}`);
+	let { command, args } = parseCommand(commandString), options = {
+		stdio: "inherit",
+		env: npmRunPath.env()
+	};
+	return options = process.platform === "win32" ? {
+		...options,
+		shell: !0
+	} : options, new Promise((resolve, reject) => {
+		childProcess.spawn(command, args, options).on("error", reject).on("close", (exitCode) => {
+			resolve({ code: exitCode ?? 0 });
+		});
+	});
+}
+const verifyFlags = {
+	...sharedFlags_default,
+	single: {
+		default: !1,
+		type: "boolean"
+	}
+};
+function disableCheckText(checkKey) {
+	return chalk.grey(outdent`
+              To skip this validation add the following to your package.json:
+              "sanityPlugin": {
+                 "verifyPackage": {
+                    "${checkKey}": false
+                 }
+              }
+          `.trimStart());
+}
+function createValidator(verifyConfig, flags, errors) {
+	return async function(checkKey, task) {
+		if (verifyConfig[checkKey] !== !1) {
+			let result = await task();
+			if (result?.length) {
+				result.push(disableCheckText(checkKey));
+				let errorMessage = result.join("\n\n");
+				errors.push(errorMessage), log_default.error("\n" + errorMessage + "\n----------------------------------------------------------");
+			}
+		}
+		if (flags.single && errors.length) throw Error(outdent`Detected outstanding upgrade issues.
+
+        Fail-fast (--single) mode enabled, stopping validation here.
+        `);
+	};
+}
+async function runTscMaybe(verifyConfig, ts) {
+	if (ts && verifyConfig.tsc !== !1) {
+		log_default.info("All checks ok, running TypeScript compiler.");
+		let { code } = await runCommand("tsc --build");
+		if (code !== 0) throw Error("Compilation failed. See output above.\n\n" + disableCheckText("tsc"));
+	}
+}
+export { validateImports as a, readTSConfig as i, runTscMaybe as n, verifyFlags as r, createValidator as t };
+
+//# sourceMappingURL=verify-common.js.map
\ No newline at end of file