chunk-5MUHROAQ.js 26 KB

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