chunk-BJ3IUMIZ.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. import {
  2. DIRECTIVE_IMPORT_PREFIX,
  3. DISABLE_COMMENT,
  4. getNameFromFilePath,
  5. getTransformedPath,
  6. matchGlobs,
  7. normalizeComponetInfo,
  8. parseId,
  9. pascalCase,
  10. resolveAlias,
  11. shouldTransform,
  12. stringifyComponentImport
  13. } from "./chunk-IN2W2XFC.mjs";
  14. import {
  15. __spreadProps,
  16. __spreadValues
  17. } from "./chunk-ZKNUHGJ4.mjs";
  18. // src/core/unplugin.ts
  19. import { existsSync as existsSync2 } from "fs";
  20. import { createUnplugin } from "unplugin";
  21. import { createFilter } from "@rollup/pluginutils";
  22. import chokidar from "chokidar";
  23. // src/core/context.ts
  24. import { relative as relative2 } from "path";
  25. import Debug5 from "debug";
  26. import { slash as slash3, throttle, toArray as toArray2 } from "@antfu/utils";
  27. // src/core/options.ts
  28. import { join, resolve } from "path";
  29. import { slash, toArray } from "@antfu/utils";
  30. import { getPackageInfoSync, isPackageExists as isPackageExists2 } from "local-pkg";
  31. // src/core/type-imports/detect.ts
  32. import { isPackageExists } from "local-pkg";
  33. import { notNullish } from "@antfu/utils";
  34. // src/core/type-imports/index.ts
  35. var TypeImportPresets = [
  36. {
  37. from: "vue-router",
  38. names: [
  39. "RouterView",
  40. "RouterLink"
  41. ]
  42. },
  43. {
  44. from: "vue-starport",
  45. names: [
  46. "Starport",
  47. "StarportCarrier"
  48. ]
  49. }
  50. ];
  51. // src/core/type-imports/detect.ts
  52. function detectTypeImports() {
  53. return TypeImportPresets.map((i) => isPackageExists(i.from) ? i : void 0).filter(notNullish);
  54. }
  55. function resolveTypeImports(imports) {
  56. return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
  57. }
  58. // src/core/options.ts
  59. var defaultOptions = {
  60. dirs: "src/components",
  61. extensions: "vue",
  62. deep: true,
  63. dts: isPackageExists2("typescript"),
  64. directoryAsNamespace: false,
  65. collapseSamePrefixes: false,
  66. globalNamespaces: [],
  67. resolvers: [],
  68. importPathTransform: (v) => v,
  69. allowOverrides: false
  70. };
  71. function normalizeResolvers(resolvers) {
  72. return toArray(resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
  73. }
  74. function resolveOptions(options, root) {
  75. var _a;
  76. const resolved = Object.assign({}, defaultOptions, options);
  77. resolved.resolvers = normalizeResolvers(resolved.resolvers);
  78. resolved.extensions = toArray(resolved.extensions);
  79. if (resolved.globs) {
  80. resolved.globs = toArray(resolved.globs).map((glob) => slash(resolve(root, glob)));
  81. resolved.resolvedDirs = [];
  82. } else {
  83. const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
  84. resolved.dirs = toArray(resolved.dirs);
  85. resolved.resolvedDirs = resolved.dirs.map((i) => slash(resolve(root, i)));
  86. resolved.globs = resolved.resolvedDirs.map(
  87. (i) => resolved.deep ? slash(join(i, `**/*.${extsGlob}`)) : slash(join(i, `*.${extsGlob}`))
  88. );
  89. if (!resolved.extensions.length)
  90. throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
  91. }
  92. resolved.dts = !resolved.dts ? false : resolve(
  93. root,
  94. typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
  95. );
  96. if (!resolved.types && resolved.dts)
  97. resolved.types = detectTypeImports();
  98. resolved.types = resolved.types || [];
  99. resolved.root = root;
  100. resolved.version = (_a = resolved.version) != null ? _a : getVueVersion(root);
  101. if (resolved.version < 2 || resolved.version >= 4)
  102. throw new Error(`[unplugin-vue-components] unsupported version: ${resolved.version}`);
  103. resolved.transformer = options.transformer || `vue${Math.trunc(resolved.version)}`;
  104. resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : resolved.version >= 3;
  105. return resolved;
  106. }
  107. function getVueVersion(root) {
  108. var _a;
  109. const raw = ((_a = getPackageInfoSync("vue", { paths: [root] })) == null ? void 0 : _a.version) || "3";
  110. const version = +raw.split(".").slice(0, 2).join(".");
  111. if (version === 2.7)
  112. return 2.7;
  113. else if (version < 2.7)
  114. return 2;
  115. return 3;
  116. }
  117. // src/core/fs/glob.ts
  118. import fg from "fast-glob";
  119. import Debug from "debug";
  120. var debug = Debug("unplugin-vue-components:glob");
  121. function searchComponents(ctx) {
  122. var _a;
  123. debug(`started with: [${ctx.options.globs.join(", ")}]`);
  124. const root = ctx.root;
  125. const files = fg.sync(ctx.options.globs, {
  126. ignore: ["node_modules"],
  127. onlyFiles: true,
  128. cwd: root,
  129. absolute: true
  130. });
  131. if (!files.length && !((_a = ctx.options.resolvers) == null ? void 0 : _a.length))
  132. console.warn("[unplugin-vue-components] no components found");
  133. debug(`${files.length} components found.`);
  134. ctx.addComponents(files);
  135. }
  136. // src/core/declaration.ts
  137. import { dirname, isAbsolute, relative } from "path";
  138. import { existsSync } from "fs";
  139. import { readFile, writeFile } from "fs/promises";
  140. import { notNullish as notNullish2, slash as slash2 } from "@antfu/utils";
  141. var multilineCommentsRE = new RegExp("\\/\\*.*?\\*\\/", "gms");
  142. var singlelineCommentsRE = /\/\/.*$/gm;
  143. function extractImports(code) {
  144. return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
  145. }
  146. function parseDeclaration(code) {
  147. var _a, _b;
  148. if (!code)
  149. return;
  150. code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
  151. const imports = {
  152. component: {},
  153. directive: {}
  154. };
  155. const componentDeclaration = (_a = new RegExp("export\\s+interface\\s+GlobalComponents\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _a[0];
  156. if (componentDeclaration)
  157. imports.component = extractImports(componentDeclaration);
  158. const directiveDeclaration = (_b = new RegExp("export\\s+interface\\s+ComponentCustomProperties\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _b[0];
  159. if (directiveDeclaration)
  160. imports.directive = extractImports(directiveDeclaration);
  161. return imports;
  162. }
  163. function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
  164. if (!name)
  165. return void 0;
  166. path = getTransformedPath(path, importPathTransform);
  167. const related = isAbsolute(path) ? `./${relative(dirname(filepath), path)}` : path;
  168. const entry = `typeof import('${slash2(related)}')['${importName || "default"}']`;
  169. return [name, entry];
  170. }
  171. function stringifyComponentsInfo(filepath, components, importPathTransform) {
  172. return Object.fromEntries(
  173. components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(notNullish2)
  174. );
  175. }
  176. function getDeclarationImports(ctx, filepath) {
  177. const component = stringifyComponentsInfo(filepath, [
  178. ...Object.values(__spreadValues(__spreadValues({}, ctx.componentNameMap), ctx.componentCustomMap)),
  179. ...resolveTypeImports(ctx.options.types)
  180. ], ctx.options.importPathTransform);
  181. const directive = stringifyComponentsInfo(
  182. filepath,
  183. Object.values(ctx.directiveCustomMap),
  184. ctx.options.importPathTransform
  185. );
  186. if (Object.keys(component).length + Object.keys(directive).length === 0)
  187. return;
  188. return { component, directive };
  189. }
  190. function stringifyDeclarationImports(imports) {
  191. return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
  192. if (!/^\w+$/.test(name))
  193. name = `'${name}'`;
  194. return `${name}: ${v}`;
  195. });
  196. }
  197. function getDeclaration(ctx, filepath, originalImports) {
  198. const imports = getDeclarationImports(ctx, filepath);
  199. if (!imports)
  200. return;
  201. const declarations = {
  202. component: stringifyDeclarationImports(__spreadValues(__spreadValues({}, originalImports == null ? void 0 : originalImports.component), imports.component)),
  203. directive: stringifyDeclarationImports(__spreadValues(__spreadValues({}, originalImports == null ? void 0 : originalImports.directive), imports.directive))
  204. };
  205. const head = ctx.options.version === 2.7 ? `export {}
  206. declare module 'vue' {` : `import '@vue/runtime-core'
  207. export {}
  208. declare module '@vue/runtime-core' {`;
  209. let code = `// generated by unplugin-vue-components
  210. // We suggest you to commit this file into source control
  211. // Read more: https://github.com/vuejs/core/pull/3399
  212. ${head}`;
  213. if (Object.keys(declarations.component).length > 0) {
  214. code += `
  215. export interface GlobalComponents {
  216. ${declarations.component.join("\n ")}
  217. }`;
  218. }
  219. if (Object.keys(declarations.directive).length > 0) {
  220. code += `
  221. export interface ComponentCustomProperties {
  222. ${declarations.directive.join("\n ")}
  223. }`;
  224. }
  225. code += "\n}\n";
  226. return code;
  227. }
  228. async function writeDeclaration(ctx, filepath, removeUnused = false) {
  229. const originalContent = existsSync(filepath) ? await readFile(filepath, "utf-8") : "";
  230. const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
  231. const code = getDeclaration(ctx, filepath, originalImports);
  232. if (!code)
  233. return;
  234. if (code !== originalContent)
  235. await writeFile(filepath, code, "utf-8");
  236. }
  237. // src/core/transformer.ts
  238. import Debug4 from "debug";
  239. import MagicString from "magic-string";
  240. // src/core/transforms/component.ts
  241. import Debug2 from "debug";
  242. var debug2 = Debug2("unplugin-vue-components:transform:component");
  243. var resolveVue2 = (code, s) => {
  244. const results = [];
  245. for (const match of code.matchAll(/\b(_c|h)\([\s\n\t]*['"](.+?)["']([,)])/g)) {
  246. const [full, renderFunctionName, matchedName, append] = match;
  247. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  248. const start = match.index;
  249. const end = start + full.length;
  250. results.push({
  251. rawName: matchedName,
  252. replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
  253. });
  254. }
  255. }
  256. return results;
  257. };
  258. var resolveVue3 = (code, s) => {
  259. const results = [];
  260. for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) {
  261. const matchedName = match[1];
  262. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  263. const start = match.index;
  264. const end = start + match[0].length;
  265. results.push({
  266. rawName: matchedName,
  267. replace: (resolved) => s.overwrite(start, end, resolved)
  268. });
  269. }
  270. }
  271. return results;
  272. };
  273. async function transformComponent(code, transformer2, s, ctx, sfcPath) {
  274. let no = 0;
  275. const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
  276. for (const { rawName, replace } of results) {
  277. debug2(`| ${rawName}`);
  278. const name = pascalCase(rawName);
  279. ctx.updateUsageMap(sfcPath, [name]);
  280. const component = await ctx.findComponent(name, "component", [sfcPath]);
  281. if (component) {
  282. const varName = `__unplugin_components_${no}`;
  283. s.prepend(`${stringifyComponentImport(__spreadProps(__spreadValues({}, component), { as: varName }), ctx)};
  284. `);
  285. no += 1;
  286. replace(varName);
  287. }
  288. }
  289. debug2(`^ (${no})`);
  290. }
  291. // src/core/transforms/directive/index.ts
  292. import Debug3 from "debug";
  293. // src/core/transforms/directive/vue2.ts
  294. import { importModule, isPackageExists as isPackageExists3 } from "local-pkg";
  295. var getRenderFnStart = (program) => {
  296. var _a, _b;
  297. const renderFn = program.body.find(
  298. (node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
  299. );
  300. const start = (_b = (_a = renderFn == null ? void 0 : renderFn.declarations[0].init) == null ? void 0 : _a.body) == null ? void 0 : _b.start;
  301. if (start === null || start === void 0)
  302. throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
  303. return start + 1;
  304. };
  305. async function resolveVue22(code, s) {
  306. var _a, _b, _c;
  307. if (!isPackageExists3("@babel/parser"))
  308. throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
  309. const { parse } = await importModule("@babel/parser");
  310. const { program } = parse(code, {
  311. sourceType: "module"
  312. });
  313. const nodes = [];
  314. const { walk } = await import("./src-WRIQ2NEL.mjs");
  315. walk(program, {
  316. enter(node) {
  317. if (node.type === "CallExpression")
  318. nodes.push(node);
  319. }
  320. });
  321. if (nodes.length === 0)
  322. return [];
  323. let _renderStart;
  324. const getRenderStart = () => {
  325. if (_renderStart !== void 0)
  326. return _renderStart;
  327. return _renderStart = getRenderFnStart(program);
  328. };
  329. const results = [];
  330. for (const node of nodes) {
  331. const { callee, arguments: args } = node;
  332. if (callee.type !== "Identifier" || callee.name !== "_c" || ((_a = args[1]) == null ? void 0 : _a.type) !== "ObjectExpression")
  333. continue;
  334. const directives = (_b = args[1].properties.find(
  335. (property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
  336. )) == null ? void 0 : _b.value;
  337. if (!directives || directives.type !== "ArrayExpression")
  338. continue;
  339. for (const directive of directives.elements) {
  340. if ((directive == null ? void 0 : directive.type) !== "ObjectExpression")
  341. continue;
  342. const nameNode = (_c = directive.properties.find(
  343. (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
  344. )) == null ? void 0 : _c.value;
  345. if ((nameNode == null ? void 0 : nameNode.type) !== "StringLiteral")
  346. continue;
  347. const name = nameNode.value;
  348. if (!name || name.startsWith("_"))
  349. continue;
  350. results.push({
  351. rawName: name,
  352. replace: (resolved) => {
  353. s.prependLeft(getRenderStart(), `
  354. this.$options.directives["${name}"] = ${resolved};`);
  355. }
  356. });
  357. }
  358. }
  359. return results;
  360. }
  361. // src/core/transforms/directive/vue3.ts
  362. function resolveVue32(code, s) {
  363. const results = [];
  364. for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
  365. const matchedName = match[1];
  366. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  367. const start = match.index;
  368. const end = start + match[0].length;
  369. results.push({
  370. rawName: matchedName,
  371. replace: (resolved) => s.overwrite(start, end, resolved)
  372. });
  373. }
  374. }
  375. return results;
  376. }
  377. // src/core/transforms/directive/index.ts
  378. var debug3 = Debug3("unplugin-vue-components:transform:directive");
  379. async function transformDirective(code, transformer2, s, ctx, sfcPath) {
  380. let no = 0;
  381. const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
  382. for (const { rawName, replace } of results) {
  383. debug3(`| ${rawName}`);
  384. const name = `${DIRECTIVE_IMPORT_PREFIX}${pascalCase(rawName)}`;
  385. ctx.updateUsageMap(sfcPath, [name]);
  386. const directive = await ctx.findComponent(name, "directive", [sfcPath]);
  387. if (!directive)
  388. continue;
  389. const varName = `__unplugin_directives_${no}`;
  390. s.prepend(`${stringifyComponentImport(__spreadProps(__spreadValues({}, directive), { as: varName }), ctx)};
  391. `);
  392. no += 1;
  393. replace(varName);
  394. }
  395. debug3(`^ (${no})`);
  396. }
  397. // src/core/transformer.ts
  398. var debug4 = Debug4("unplugin-vue-components:transformer");
  399. function transformer(ctx, transformer2) {
  400. return async (code, id, path) => {
  401. ctx.searchGlob();
  402. const sfcPath = ctx.normalizePath(path);
  403. debug4(sfcPath);
  404. const s = new MagicString(code);
  405. await transformComponent(code, transformer2, s, ctx, sfcPath);
  406. if (ctx.options.directives)
  407. await transformDirective(code, transformer2, s, ctx, sfcPath);
  408. s.prepend(DISABLE_COMMENT);
  409. const result = { code: s.toString() };
  410. if (ctx.sourcemap)
  411. result.map = s.generateMap({ source: id, includeContent: true });
  412. return result;
  413. };
  414. }
  415. // src/core/context.ts
  416. var debug5 = {
  417. components: Debug5("unplugin-vue-components:context:components"),
  418. search: Debug5("unplugin-vue-components:context:search"),
  419. hmr: Debug5("unplugin-vue-components:context:hmr"),
  420. decleration: Debug5("unplugin-vue-components:decleration"),
  421. env: Debug5("unplugin-vue-components:env")
  422. };
  423. var Context = class {
  424. constructor(rawOptions) {
  425. this.rawOptions = rawOptions;
  426. this.transformer = void 0;
  427. this._componentPaths = /* @__PURE__ */ new Set();
  428. this._componentNameMap = {};
  429. this._componentUsageMap = {};
  430. this._componentCustomMap = {};
  431. this._directiveCustomMap = {};
  432. this.root = process.cwd();
  433. this.sourcemap = true;
  434. this.alias = {};
  435. this._searched = false;
  436. this.options = resolveOptions(rawOptions, this.root);
  437. this.generateDeclaration = throttle(500, this._generateDeclaration.bind(this), { noLeading: false });
  438. this.setTransformer(this.options.transformer);
  439. }
  440. setRoot(root) {
  441. if (this.root === root)
  442. return;
  443. debug5.env("root", root);
  444. this.root = root;
  445. this.options = resolveOptions(this.rawOptions, this.root);
  446. }
  447. setTransformer(name) {
  448. debug5.env("transformer", name);
  449. this.transformer = transformer(this, name || "vue3");
  450. }
  451. transform(code, id) {
  452. const { path, query } = parseId(id);
  453. return this.transformer(code, id, path, query);
  454. }
  455. setupViteServer(server) {
  456. if (this._server === server)
  457. return;
  458. this._server = server;
  459. this.setupWatcher(server.watcher);
  460. }
  461. setupWatcher(watcher) {
  462. const { globs } = this.options;
  463. watcher.on("unlink", (path) => {
  464. if (!matchGlobs(path, globs))
  465. return;
  466. path = slash3(path);
  467. this.removeComponents(path);
  468. this.onUpdate(path);
  469. });
  470. watcher.on("add", (path) => {
  471. if (!matchGlobs(path, globs))
  472. return;
  473. path = slash3(path);
  474. this.addComponents(path);
  475. this.onUpdate(path);
  476. });
  477. }
  478. setupWatcherWebpack(watcher, emitUpdate) {
  479. const { globs } = this.options;
  480. watcher.on("unlink", (path) => {
  481. if (!matchGlobs(path, globs))
  482. return;
  483. path = slash3(path);
  484. this.removeComponents(path);
  485. emitUpdate(path, "unlink");
  486. });
  487. watcher.on("add", (path) => {
  488. if (!matchGlobs(path, globs))
  489. return;
  490. path = slash3(path);
  491. this.addComponents(path);
  492. emitUpdate(path, "add");
  493. });
  494. }
  495. updateUsageMap(path, paths) {
  496. if (!this._componentUsageMap[path])
  497. this._componentUsageMap[path] = /* @__PURE__ */ new Set();
  498. paths.forEach((p) => {
  499. this._componentUsageMap[path].add(p);
  500. });
  501. }
  502. addComponents(paths) {
  503. debug5.components("add", paths);
  504. const size = this._componentPaths.size;
  505. toArray2(paths).forEach((p) => this._componentPaths.add(p));
  506. if (this._componentPaths.size !== size) {
  507. this.updateComponentNameMap();
  508. return true;
  509. }
  510. return false;
  511. }
  512. addCustomComponents(info) {
  513. if (info.as)
  514. this._componentCustomMap[info.as] = info;
  515. }
  516. addCustomDirectives(info) {
  517. if (info.as)
  518. this._directiveCustomMap[info.as] = info;
  519. }
  520. removeComponents(paths) {
  521. debug5.components("remove", paths);
  522. const size = this._componentPaths.size;
  523. toArray2(paths).forEach((p) => this._componentPaths.delete(p));
  524. if (this._componentPaths.size !== size) {
  525. this.updateComponentNameMap();
  526. return true;
  527. }
  528. return false;
  529. }
  530. onUpdate(path) {
  531. this.generateDeclaration();
  532. if (!this._server)
  533. return;
  534. const payload = {
  535. type: "update",
  536. updates: []
  537. };
  538. const timestamp = +new Date();
  539. const name = pascalCase(getNameFromFilePath(path, this.options));
  540. Object.entries(this._componentUsageMap).forEach(([key, values]) => {
  541. if (values.has(name)) {
  542. const r = `/${slash3(relative2(this.root, key))}`;
  543. payload.updates.push({
  544. acceptedPath: r,
  545. path: r,
  546. timestamp,
  547. type: "js-update"
  548. });
  549. }
  550. });
  551. if (payload.updates.length)
  552. this._server.ws.send(payload);
  553. }
  554. updateComponentNameMap() {
  555. this._componentNameMap = {};
  556. Array.from(this._componentPaths).forEach((path) => {
  557. const name = pascalCase(getNameFromFilePath(path, this.options));
  558. if (this._componentNameMap[name] && !this.options.allowOverrides) {
  559. console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
  560. return;
  561. }
  562. this._componentNameMap[name] = {
  563. as: name,
  564. from: path
  565. };
  566. });
  567. }
  568. async findComponent(name, type, excludePaths = []) {
  569. let info = this._componentNameMap[name];
  570. if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
  571. return info;
  572. for (const resolver of this.options.resolvers) {
  573. if (resolver.type !== type)
  574. continue;
  575. const result = await resolver.resolve(type === "directive" ? name.slice(DIRECTIVE_IMPORT_PREFIX.length) : name);
  576. if (!result)
  577. continue;
  578. if (typeof result === "string") {
  579. info = {
  580. as: name,
  581. from: result
  582. };
  583. } else {
  584. info = __spreadValues({
  585. as: name
  586. }, normalizeComponetInfo(result));
  587. }
  588. if (type === "component")
  589. this.addCustomComponents(info);
  590. else if (type === "directive")
  591. this.addCustomDirectives(info);
  592. return info;
  593. }
  594. return void 0;
  595. }
  596. normalizePath(path) {
  597. var _a, _b, _c;
  598. return resolveAlias(path, ((_b = (_a = this.viteConfig) == null ? void 0 : _a.resolve) == null ? void 0 : _b.alias) || ((_c = this.viteConfig) == null ? void 0 : _c.alias) || []);
  599. }
  600. relative(path) {
  601. if (path.startsWith("/") && !path.startsWith(this.root))
  602. return slash3(path.slice(1));
  603. return slash3(relative2(this.root, path));
  604. }
  605. searchGlob() {
  606. if (this._searched)
  607. return;
  608. searchComponents(this);
  609. debug5.search(this._componentNameMap);
  610. this._searched = true;
  611. }
  612. _generateDeclaration(removeUnused = !this._server) {
  613. if (!this.options.dts)
  614. return;
  615. debug5.decleration("generating");
  616. return writeDeclaration(this, this.options.dts, removeUnused);
  617. }
  618. get componentNameMap() {
  619. return this._componentNameMap;
  620. }
  621. get componentCustomMap() {
  622. return this._componentCustomMap;
  623. }
  624. get directiveCustomMap() {
  625. return this._directiveCustomMap;
  626. }
  627. };
  628. // src/core/unplugin.ts
  629. var PLUGIN_NAME = "unplugin:webpack";
  630. var unplugin_default = createUnplugin((options = {}) => {
  631. const filter = createFilter(
  632. options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
  633. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
  634. );
  635. const ctx = new Context(options);
  636. const api = {
  637. async findComponent(name, filename) {
  638. return await ctx.findComponent(name, "component", filename ? [filename] : []);
  639. },
  640. stringifyImport(info) {
  641. return stringifyComponentImport(info, ctx);
  642. }
  643. };
  644. return {
  645. name: "unplugin-vue-components",
  646. enforce: "post",
  647. api,
  648. transformInclude(id) {
  649. return filter(id);
  650. },
  651. async transform(code, id) {
  652. if (!shouldTransform(code))
  653. return null;
  654. try {
  655. const result = await ctx.transform(code, id);
  656. ctx.generateDeclaration();
  657. return result;
  658. } catch (e) {
  659. this.error(e);
  660. }
  661. },
  662. vite: {
  663. configResolved(config) {
  664. ctx.setRoot(config.root);
  665. ctx.sourcemap = true;
  666. if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
  667. ctx.setTransformer("vue2");
  668. if (ctx.options.dts) {
  669. ctx.searchGlob();
  670. if (!existsSync2(ctx.options.dts))
  671. ctx.generateDeclaration();
  672. }
  673. if (config.build.watch && config.command === "build")
  674. ctx.setupWatcher(chokidar.watch(ctx.options.globs));
  675. },
  676. configureServer(server) {
  677. ctx.setupViteServer(server);
  678. }
  679. },
  680. webpack(compiler) {
  681. let watcher;
  682. let fileDepQueue = [];
  683. compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
  684. if (!watcher && compiler.watching) {
  685. watcher = compiler.watching;
  686. ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path, type) => {
  687. fileDepQueue.push({ path, type });
  688. process.nextTick(() => {
  689. watcher.invalidate();
  690. });
  691. });
  692. }
  693. });
  694. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  695. if (fileDepQueue.length) {
  696. fileDepQueue.forEach(({ path, type }) => {
  697. if (type === "unlink")
  698. compilation.fileDependencies.delete(path);
  699. else
  700. compilation.fileDependencies.add(path);
  701. });
  702. fileDepQueue = [];
  703. }
  704. });
  705. }
  706. };
  707. });
  708. export {
  709. unplugin_default
  710. };