chunk-XHOH7KVV.cjs 8.9 KB

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