215ad6858a2e1db72b45122d44b538fabc087eb8d7f72e632037cb2ad8da838a4271bc7d14e456ca6fae5e9edaef5d46a80ee833d37d2599d11f0f613fc91b 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2. var _chunkK625S6OXcjs = require('./chunk-K625S6OX.cjs');
  3. // src/core/unplugin.ts
  4. var _unplugin = require('unplugin');
  5. // src/core/ctx.ts
  6. var _path = require('path');
  7. var _fs = require('fs');
  8. var _utils = require('@antfu/utils');
  9. var _pluginutils = require('@rollup/pluginutils');
  10. var _localpkg = require('local-pkg');
  11. var _addons = require('unimport/addons');
  12. var _unimport = require('unimport');
  13. var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
  14. // src/core/eslintrc.ts
  15. function generateESLintConfigs(imports, eslintrc) {
  16. const eslintConfigs = { globals: {} };
  17. imports.map((i) => {
  18. var _a;
  19. return (_a = i.as) != null ? _a : i.name;
  20. }).filter(Boolean).sort().forEach((name) => {
  21. eslintConfigs.globals[name] = eslintrc.globalsPropValue || true;
  22. });
  23. const jsonBody = JSON.stringify(eslintConfigs, null, 2);
  24. return jsonBody;
  25. }
  26. // src/core/resolvers.ts
  27. function normalizeImport(info, name) {
  28. if (typeof info === "string") {
  29. return {
  30. name: "default",
  31. as: name,
  32. from: info
  33. };
  34. }
  35. if ("path" in info) {
  36. return {
  37. from: info.path,
  38. as: info.name,
  39. name: info.importName,
  40. sideEffects: info.sideEffects
  41. };
  42. }
  43. return _chunkK625S6OXcjs.__spreadValues.call(void 0, {
  44. name,
  45. as: name
  46. }, info);
  47. }
  48. async function firstMatchedResolver(resolvers, fullname) {
  49. let name = fullname;
  50. for (const resolver of resolvers) {
  51. if (typeof resolver === "object" && resolver.type === "directive") {
  52. if (name.startsWith("v"))
  53. name = name.slice(1);
  54. else
  55. continue;
  56. }
  57. const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
  58. if (resolved)
  59. return normalizeImport(resolved, fullname);
  60. }
  61. }
  62. function resolversAddon(resolvers) {
  63. return {
  64. async matchImports(names, matched) {
  65. if (!resolvers.length)
  66. return;
  67. const dynamic = [];
  68. const sideEffects = [];
  69. await Promise.all([...names].map(async (name) => {
  70. const matchedImport = matched.find((i) => i.as === name);
  71. if (matchedImport) {
  72. if ("sideEffects" in matchedImport)
  73. sideEffects.push(..._utils.toArray.call(void 0, matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
  74. return;
  75. }
  76. const resolved = await firstMatchedResolver(resolvers, name);
  77. if (resolved)
  78. dynamic.push(resolved);
  79. if (resolved == null ? void 0 : resolved.sideEffects)
  80. sideEffects.push(..._utils.toArray.call(void 0, resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
  81. }));
  82. if (dynamic.length) {
  83. this.dynamicImports.push(...dynamic);
  84. this.invalidate();
  85. }
  86. if (dynamic.length || sideEffects.length)
  87. return [...matched, ...dynamic, ...sideEffects];
  88. }
  89. };
  90. }
  91. // src/core/ctx.ts
  92. function createContext(options = {}, root = process.cwd()) {
  93. var _a, _b;
  94. const imports = flattenImports(options.imports, options.presetOverriding);
  95. (_a = options.ignore) == null ? void 0 : _a.forEach((name) => {
  96. const i = imports.find((i2) => i2.as === name);
  97. if (i)
  98. i.disabled = true;
  99. });
  100. const {
  101. dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript")
  102. } = options;
  103. const dirs = (_b = options.dirs) == null ? void 0 : _b.map((dir) => _path.resolve.call(void 0, root, dir));
  104. const eslintrc = options.eslintrc || {};
  105. eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
  106. eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
  107. eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
  108. const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
  109. const unimport = _unimport.createUnimport.call(void 0, {
  110. imports,
  111. presets: [],
  112. addons: [
  113. ...options.vueTemplate ? [_addons.vueTemplateAddon.call(void 0, )] : [],
  114. resolversAddon(resolvers),
  115. {
  116. declaration(dts2) {
  117. if (!dts2.endsWith("\n"))
  118. dts2 += "\n";
  119. return `// Generated by 'unplugin-auto-import'
  120. ${dts2}`;
  121. }
  122. }
  123. ]
  124. });
  125. const filter = _pluginutils.createFilter.call(void 0,
  126. options.include || [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
  127. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
  128. );
  129. const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
  130. function generateDTS(file) {
  131. const dir = _path.dirname.call(void 0, file);
  132. return unimport.generateTypeDeclarations({
  133. resolvePath: (i) => {
  134. if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
  135. const related = _utils.slash.call(void 0, _path.relative.call(void 0, dir, i.from).replace(/\.ts$/, ""));
  136. return !related.startsWith(".") ? `./${related}` : related;
  137. }
  138. return i.from;
  139. }
  140. });
  141. }
  142. async function generateESLint() {
  143. return generateESLintConfigs(await unimport.getImports(), eslintrc);
  144. }
  145. const writeConfigFilesThrottled = _utils.throttle.call(void 0, 500, writeConfigFiles, { noLeading: false });
  146. let lastDTS;
  147. let lastESLint;
  148. async function writeConfigFiles() {
  149. const promises = [];
  150. if (dts) {
  151. promises.push(
  152. generateDTS(dts).then((content) => {
  153. if (content !== lastDTS) {
  154. lastDTS = content;
  155. return _fs.promises.writeFile(dts, content, "utf-8");
  156. }
  157. })
  158. );
  159. }
  160. if (eslintrc.enabled && eslintrc.filepath) {
  161. promises.push(
  162. generateESLint().then((content) => {
  163. if (content !== lastESLint) {
  164. lastESLint = content;
  165. return _fs.promises.writeFile(eslintrc.filepath, content, "utf-8");
  166. }
  167. })
  168. );
  169. }
  170. return Promise.all(promises);
  171. }
  172. async function scanDirs() {
  173. if (dirs == null ? void 0 : dirs.length) {
  174. await unimport.modifyDynamicImports(async (imports2) => {
  175. const exports = await _unimport.scanDirExports.call(void 0, dirs);
  176. exports.forEach((i) => i.__source = "dir");
  177. return [
  178. ...imports2.filter((i) => i.__source !== "dir"),
  179. ...exports
  180. ];
  181. });
  182. }
  183. writeConfigFilesThrottled();
  184. }
  185. async function transform(code, id) {
  186. const s = new (0, _magicstring2.default)(code);
  187. await unimport.injectImports(s, id);
  188. if (!s.hasChanged())
  189. return;
  190. writeConfigFilesThrottled();
  191. return {
  192. code: s.toString(),
  193. map: s.generateMap({ source: id, includeContent: true })
  194. };
  195. }
  196. if (!imports.length && !resolvers.length)
  197. console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
  198. return {
  199. root,
  200. dirs,
  201. filter,
  202. scanDirs,
  203. writeConfigFiles,
  204. writeConfigFilesThrottled,
  205. transform,
  206. generateDTS,
  207. generateESLint
  208. };
  209. }
  210. function flattenImports(map, overriding = false) {
  211. const flat = {};
  212. _utils.toArray.call(void 0, map).forEach((definition) => {
  213. if (typeof definition === "string") {
  214. if (!_chunkK625S6OXcjs.presets[definition])
  215. throw new Error(`[auto-import] preset ${definition} not found`);
  216. const preset = _chunkK625S6OXcjs.presets[definition];
  217. definition = typeof preset === "function" ? preset() : preset;
  218. }
  219. for (const mod of Object.keys(definition)) {
  220. for (const id of definition[mod]) {
  221. const meta = {
  222. from: mod
  223. };
  224. let name;
  225. if (Array.isArray(id)) {
  226. name = id[1];
  227. meta.name = id[0];
  228. meta.as = id[1];
  229. } else {
  230. name = id;
  231. meta.name = id;
  232. meta.as = id;
  233. }
  234. if (flat[name] && !overriding)
  235. throw new Error(`[auto-import] identifier ${name} already defined with ${flat[name].from}`);
  236. flat[name] = meta;
  237. }
  238. }
  239. });
  240. return Object.values(flat);
  241. }
  242. // src/core/unplugin.ts
  243. var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
  244. let ctx = createContext(options);
  245. return {
  246. name: "unplugin-auto-import",
  247. enforce: "post",
  248. transformInclude(id) {
  249. return ctx.filter(id);
  250. },
  251. async transform(code, id) {
  252. return ctx.transform(code, id);
  253. },
  254. async buildStart() {
  255. await ctx.scanDirs();
  256. },
  257. async buildEnd() {
  258. await ctx.writeConfigFiles();
  259. },
  260. vite: {
  261. async handleHotUpdate({ file }) {
  262. var _a;
  263. if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => file.startsWith(dir)))
  264. await ctx.scanDirs();
  265. },
  266. async configResolved(config) {
  267. if (ctx.root !== config.root) {
  268. ctx = createContext(options, config.root);
  269. await ctx.scanDirs();
  270. }
  271. }
  272. }
  273. };
  274. });
  275. exports.unplugin_default = unplugin_default;