UNPKG

beesbuild

Version:

构建工具链

267 lines (265 loc) 9.61 kB
"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( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var stdin_exports = {}; __export(stdin_exports, { createTypesProject: () => createTypesProject, typesBuild: () => typesBuild }); module.exports = __toCommonJS(stdin_exports); var import_path = __toESM(require("path")); var compiler = __toESM(require("@vue/compiler-sfc")); var import_chalk_unified = __toESM(require("chalk-unified")); var import_utils = require("@beesbuild/utils"); var import_fs_extra = require("fs-extra"); var import_ts_morph = require("ts-morph"); var import_fast_glob = __toESM(require("fast-glob")); var import_defu = require("defu"); var import_variables = require("../variables.cjs"); var import_utils2 = require("./utils.cjs"); var import_vue_tsc = require("./vue-tsc.cjs"); var import_parseSfc = require("./parseSfc.cjs"); function compileVueFile(file, flag = true) { var _a, _b, _c; const result = { lang: "js" }; try { const errors = []; const content = (0, import_fs_extra.readFileSync)(import_path.default.join(file), "utf-8"); const hasTsNoCheck = content.includes("@ts-nocheck"); const sfc = flag ? compiler.parse(content, { templateParseOptions: { // there are no components at SFC parsing level isNativeTag: () => true, // preserve all whitespaces isPreTag: () => true, parseMode: "sfc", onError: e => { errors.push(e); }, comments: true } }) : (0, import_parseSfc.parse)(content); const { script, scriptSetup } = sfc.descriptor; if (script || scriptSetup) { result.content = (hasTsNoCheck ? "// @ts-nocheck\n" : "") + ((_a = script == null ? void 0 : script.content) != null ? _a : ""); const lang = (_c = (_b = scriptSetup == null ? void 0 : scriptSetup.lang) != null ? _b : script == null ? void 0 : script.lang) != null ? _c : "js"; if (scriptSetup) { const compiled = compiler.compileScript(sfc.descriptor, { id: "xxx", isProd: true }); result.content += compiled.content; result.imports = compiled.imports; } result.lang = lang; } } catch (e) { handleCatch(e); } function handleCatch(e) { console.error(import_path.default.basename(file), "error:compileVueFile"); console.error(e, "error:compileVueFile"); } return result; } function createTypesProject(ctx) { const { compilerOptions, tsConfigFilePath, rootDir, entries, output, typesCacheDir, entryFilepath, isVue } = (0, import_utils2.handleTypeOption)(ctx); const options = { compilerOptions, // 是否跳过添加指定 tsconfig.json 中的源文件。 skipAddingFilesFromTsConfig: true // 提供 ts 配置文件路径并从 tsconfig 添加文件时,跳过解析文件依赖项。 // skipFileDependencyResolution: true, // 跳过加载 lib 文件。与编译器 API 不同,ts-morph 不会从 node_modules 文件夹加载它们,而是从其他一些 JS 代码加载它们,并使用假路径来表示它们的存在。如果您想使用自定义 lib 文件文件夹路径,请使用 libFolderPath 选项提供一个路径。 // skipLoadingLibFiles: true, // 用于加载 lib 文件的文件夹。 // libFolderPath: undefined, // 是否使用内存文件系统。 // useInMemoryFileSystem: false, // 创建解析主机以指定自定义模块和/或类型引用指令解析。 // resolutionHost: undefined, }; if ((0, import_fs_extra.existsSync)(tsConfigFilePath)) { options.tsConfigFilePath = tsConfigFilePath; } const project = new import_ts_morph.Project(options); function addSourceFiles() { if (isVue) return []; const typingsDtsPath = import_path.default.resolve(rootDir, "typings", "env.d.ts"); if ((0, import_fs_extra.existsSync)(typingsDtsPath)) project.addSourceFileAtPath(typingsDtsPath); const extIncludes = ["jsx", "js", "tsx", "ts", "dts"]; const sourceFiles = []; for (const { input: filePath } of entries) { const { ext } = (0, import_utils.parseManifest)(filePath, rootDir); if (ext === "vue") { const { lang, content } = compileVueFile(filePath); if (content) { const createFilePath = import_path.default.join(`${import_path.default.relative(rootDir, filePath)}.${lang}`); const sourceFile = project.createSourceFile(createFilePath, content); sourceFiles.push(sourceFile); } } else if (extIncludes.includes(ext)) { const sourceFile = project.addSourceFileAtPath(filePath); sourceFiles.push(sourceFile); } } return sourceFiles; } function typeCheck(check) { var _a; if (check !== true && ((_a = ctx.argv) == null ? void 0 : _a.debug)) return; if (isVue) { try { (0, import_vue_tsc.vueTsc)(ctx, { noEmit: true }); } catch (e) { import_utils.consola.error(e); const err = new Error(`\u751F\u6210dts\u5931\u8D25\u3002${ctx.options.stub}`); import_utils.consola.error(err); } return; } const diagnostics = project.getPreEmitDiagnostics().filter(diagnostic => { const code = diagnostic.getCode(); let message = diagnostic.getMessageText(); if (typeof message !== "string") { message = message.getMessageText(); } return !(code === 6307 && message.includes("Projects must list all files or use an 'include' pattern")); }); if (diagnostics.length > 0) { const aaa = project.formatDiagnosticsWithColorAndContext(diagnostics); import_utils.consola.error(aaa); const err = new Error(`\u751F\u6210dts\u5931\u8D25\u3002${ctx.options.stub}`); import_utils.consola.error(err); } } function generate(options2) { var _a; if (isVue) return (0, import_vue_tsc.vueTsc)(ctx); const emitOptions = (0, import_defu.defu)({ emitOnlyDtsFiles: true, customTransformers: {} }, options2); const result = project.emitToMemory(emitOptions); if ((_a = ctx.argv) == null ? void 0 : _a.debug) { for (const file of result.getFiles()) { const p = import_path.default.relative(rootDir, file.filePath); import_utils.consola.success(import_chalk_unified.default.green(`Definition for file: ${import_chalk_unified.default.bold(p)} generated`)); } } return result.saveFiles(); } function copyFiles() { let src = import_path.default.resolve(rootDir, ".", import_variables.BUILD_CACHE_DIR, output.name); const files = import_fast_glob.default.sync(`./*.d.ts`, { cwd: src, onlyFiles: true, deep: 1, absolute: true }); const directories = import_fast_glob.default.sync(`./*`, { cwd: src, onlyDirectories: true, deep: 1, absolute: true }); if (files.length === 0 && directories.length === 1) { src = directories[0]; } import_utils.consola.info(import_chalk_unified.default.cyan(`Start for copy types file: ${import_path.default.relative(rootDir, src)} generated`)); return (0, import_fs_extra.copy)(src, output.path, { overwrite: true }); } return { typesCacheDir, entryFilepath, output, options, project, addSourceFiles, typeCheck, generate, copy: copyFiles, isVue }; } const typesBuild = async ctx => { const types = createTypesProject(ctx); types.addSourceFiles(); import_utils.consola.success("Added source types files"); if (!types.isVue) { types.typeCheck(); import_utils.consola.success("Type check passed!"); } try { await types.generate(); import_utils.consola.success(import_chalk_unified.default.green("Generate types files success")); } catch (e) { import_utils.consola.error(import_chalk_unified.default.green("Generate types files fail")); import_utils.consola.error(e); } finally { await types.copy(); import_utils.consola.success(import_chalk_unified.default.green("Copy types files success")); } return types; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createTypesProject, typesBuild });