版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

395 строки
12 KiB

  1. import { createRequire } from 'node:module';
  2. import { dirname } from 'node:path';
  3. import { pathToFileURL, fileURLToPath } from 'node:url';
  4. import vm from 'node:vm';
  5. import { isNodeBuiltin } from 'mlly';
  6. import { resolve } from 'pathe';
  7. import createDebug from 'debug';
  8. import { normalizeModuleId, slash, isInternalRequest, VALID_ID_PREFIX, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs';
  9. import { extractSourceMap } from './source-map.mjs';
  10. import 'node:fs';
  11. const { setTimeout, clearTimeout } = globalThis;
  12. const debugExecute = createDebug("vite-node:client:execute");
  13. const debugNative = createDebug("vite-node:client:native");
  14. const clientStub = {
  15. injectQuery: (id) => id,
  16. createHotContext() {
  17. return {
  18. accept: () => {
  19. },
  20. prune: () => {
  21. },
  22. dispose: () => {
  23. },
  24. decline: () => {
  25. },
  26. invalidate: () => {
  27. },
  28. on: () => {
  29. }
  30. };
  31. },
  32. updateStyle(id, css) {
  33. if (typeof document === "undefined")
  34. return;
  35. const element = document.getElementById(id);
  36. if (element)
  37. element.remove();
  38. const head = document.querySelector("head");
  39. const style = document.createElement("style");
  40. style.setAttribute("type", "text/css");
  41. style.id = id;
  42. style.innerHTML = css;
  43. head == null ? void 0 : head.appendChild(style);
  44. }
  45. };
  46. const DEFAULT_REQUEST_STUBS = {
  47. "/@vite/client": clientStub,
  48. "@vite/client": clientStub
  49. };
  50. class ModuleCacheMap extends Map {
  51. normalizePath(fsPath) {
  52. return normalizeModuleId(fsPath);
  53. }
  54. update(fsPath, mod) {
  55. fsPath = this.normalizePath(fsPath);
  56. if (!super.has(fsPath))
  57. super.set(fsPath, mod);
  58. else
  59. Object.assign(super.get(fsPath), mod);
  60. return this;
  61. }
  62. setByModuleId(modulePath, mod) {
  63. return super.set(modulePath, mod);
  64. }
  65. set(fsPath, mod) {
  66. return this.setByModuleId(this.normalizePath(fsPath), mod);
  67. }
  68. getByModuleId(modulePath) {
  69. if (!super.has(modulePath))
  70. super.set(modulePath, {});
  71. return super.get(modulePath);
  72. }
  73. get(fsPath) {
  74. return this.getByModuleId(this.normalizePath(fsPath));
  75. }
  76. deleteByModuleId(modulePath) {
  77. return super.delete(modulePath);
  78. }
  79. delete(fsPath) {
  80. return this.deleteByModuleId(this.normalizePath(fsPath));
  81. }
  82. invalidateModule(mod) {
  83. delete mod.evaluated;
  84. delete mod.resolving;
  85. delete mod.promise;
  86. delete mod.exports;
  87. return true;
  88. }
  89. invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
  90. for (const _id of ids) {
  91. const id = this.normalizePath(_id);
  92. if (invalidated.has(id))
  93. continue;
  94. invalidated.add(id);
  95. const mod = super.get(id);
  96. if (mod == null ? void 0 : mod.importers)
  97. this.invalidateDepTree(mod.importers, invalidated);
  98. super.delete(id);
  99. }
  100. return invalidated;
  101. }
  102. invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
  103. for (const _id of ids) {
  104. const id = this.normalizePath(_id);
  105. if (invalidated.has(id))
  106. continue;
  107. invalidated.add(id);
  108. const subIds = Array.from(super.entries()).filter(([, mod]) => {
  109. var _a;
  110. return (_a = mod.importers) == null ? void 0 : _a.has(id);
  111. }).map(([key]) => key);
  112. subIds.length && this.invalidateSubDepTree(subIds, invalidated);
  113. super.delete(id);
  114. }
  115. return invalidated;
  116. }
  117. getSourceMap(id) {
  118. const cache = this.get(id);
  119. if (cache.map)
  120. return cache.map;
  121. const map = cache.code && extractSourceMap(cache.code);
  122. if (map) {
  123. cache.map = map;
  124. return map;
  125. }
  126. return null;
  127. }
  128. }
  129. class ViteNodeRunner {
  130. constructor(options) {
  131. this.options = options;
  132. this.root = options.root ?? process.cwd();
  133. this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
  134. this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
  135. }
  136. async executeFile(file) {
  137. const url = `/@fs/${slash(resolve(file))}`;
  138. return await this.cachedRequest(url, url, []);
  139. }
  140. async executeId(rawId) {
  141. const [id, url] = await this.resolveUrl(rawId);
  142. return await this.cachedRequest(id, url, []);
  143. }
  144. async cachedRequest(id, fsPath, callstack) {
  145. const importee = callstack[callstack.length - 1];
  146. const mod = this.moduleCache.get(fsPath);
  147. if (!mod.importers)
  148. mod.importers = /* @__PURE__ */ new Set();
  149. if (importee)
  150. mod.importers.add(importee);
  151. if (callstack.includes(fsPath) && mod.exports)
  152. return mod.exports;
  153. if (mod.promise)
  154. return mod.promise;
  155. const promise = this.directRequest(id, fsPath, callstack);
  156. Object.assign(mod, { promise, evaluated: false });
  157. try {
  158. return await promise;
  159. } finally {
  160. mod.evaluated = true;
  161. }
  162. }
  163. shouldResolveId(id, _importee) {
  164. return !isInternalRequest(id) && !isNodeBuiltin(id);
  165. }
  166. async _resolveUrl(id, importer) {
  167. if (importer && id.startsWith(VALID_ID_PREFIX))
  168. importer = void 0;
  169. id = normalizeRequestId(id, this.options.base);
  170. if (!this.shouldResolveId(id))
  171. return [id, id];
  172. const { path, exists } = toFilePath(id, this.root);
  173. if (!this.options.resolveId || exists)
  174. return [id, path];
  175. const resolved = await this.options.resolveId(id, importer);
  176. const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : id;
  177. const fsPath = resolved ? resolvedId : path;
  178. return [resolvedId, fsPath];
  179. }
  180. async resolveUrl(id, importee) {
  181. const resolveKey = `resolve:${id}`;
  182. this.moduleCache.setByModuleId(resolveKey, { resolving: true });
  183. try {
  184. return await this._resolveUrl(id, importee);
  185. } finally {
  186. this.moduleCache.deleteByModuleId(resolveKey);
  187. }
  188. }
  189. async dependencyRequest(id, fsPath, callstack) {
  190. var _a;
  191. const getStack = () => {
  192. return `stack:
  193. ${[...callstack, fsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
  194. };
  195. let debugTimer;
  196. if (this.debug)
  197. debugTimer = setTimeout(() => console.warn(() => `module ${fsPath} takes over 2s to load.
  198. ${getStack()}`), 2e3);
  199. try {
  200. if (callstack.includes(fsPath)) {
  201. const depExports = (_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports;
  202. if (depExports)
  203. return depExports;
  204. throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
  205. }
  206. return await this.cachedRequest(id, fsPath, callstack);
  207. } finally {
  208. if (debugTimer)
  209. clearTimeout(debugTimer);
  210. }
  211. }
  212. async directRequest(id, fsPath, _callstack) {
  213. const moduleId = normalizeModuleId(fsPath);
  214. const callstack = [..._callstack, moduleId];
  215. const mod = this.moduleCache.getByModuleId(moduleId);
  216. const request = async (dep) => {
  217. const [id2, depFsPath] = await this.resolveUrl(dep, fsPath);
  218. return this.dependencyRequest(id2, depFsPath, callstack);
  219. };
  220. const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
  221. if (id in requestStubs)
  222. return requestStubs[id];
  223. let { code: transformed, externalize } = await this.options.fetchModule(id);
  224. if (externalize) {
  225. debugNative(externalize);
  226. const exports2 = await this.interopedImport(externalize);
  227. mod.exports = exports2;
  228. return exports2;
  229. }
  230. if (transformed == null)
  231. throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
  232. const modulePath = cleanUrl(moduleId);
  233. const href = pathToFileURL(modulePath).href;
  234. const meta = { url: href };
  235. const exports = /* @__PURE__ */ Object.create(null);
  236. Object.defineProperty(exports, Symbol.toStringTag, {
  237. value: "Module",
  238. enumerable: false,
  239. configurable: false
  240. });
  241. const cjsExports = new Proxy(exports, {
  242. get: (target, p, receiver) => {
  243. if (Reflect.has(target, p))
  244. return Reflect.get(target, p, receiver);
  245. return Reflect.get(Object.prototype, p, receiver);
  246. },
  247. getPrototypeOf: () => Object.prototype,
  248. set: (_, p, value) => {
  249. if (p === "default" && this.shouldInterop(modulePath, { default: value })) {
  250. exportAll(cjsExports, value);
  251. exports.default = value;
  252. return true;
  253. }
  254. if (!Reflect.has(exports, "default"))
  255. exports.default = {};
  256. if (isPrimitive(exports.default)) {
  257. defineExport(exports, p, () => void 0);
  258. return true;
  259. }
  260. exports.default[p] = value;
  261. if (p !== "default")
  262. defineExport(exports, p, () => value);
  263. return true;
  264. }
  265. });
  266. Object.assign(mod, { code: transformed, exports });
  267. const __filename = fileURLToPath(href);
  268. const moduleProxy = {
  269. set exports(value) {
  270. exportAll(cjsExports, value);
  271. exports.default = value;
  272. },
  273. get exports() {
  274. return cjsExports;
  275. }
  276. };
  277. let hotContext;
  278. if (this.options.createHotContext) {
  279. Object.defineProperty(meta, "hot", {
  280. enumerable: true,
  281. get: () => {
  282. var _a, _b;
  283. hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
  284. return hotContext;
  285. },
  286. set: (value) => {
  287. hotContext = value;
  288. }
  289. });
  290. }
  291. const context = this.prepareContext({
  292. __vite_ssr_import__: request,
  293. __vite_ssr_dynamic_import__: request,
  294. __vite_ssr_exports__: exports,
  295. __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
  296. __vite_ssr_import_meta__: meta,
  297. require: createRequire(href),
  298. exports: cjsExports,
  299. module: moduleProxy,
  300. __filename,
  301. __dirname: dirname(__filename)
  302. });
  303. debugExecute(__filename);
  304. if (transformed[0] === "#")
  305. transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
  306. const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
  307. const code = `${codeDefinition}${transformed}
  308. }}`;
  309. const fn = vm.runInThisContext(code, {
  310. filename: __filename,
  311. lineOffset: 0,
  312. columnOffset: -codeDefinition.length
  313. });
  314. await fn(...Object.values(context));
  315. return exports;
  316. }
  317. prepareContext(context) {
  318. return context;
  319. }
  320. shouldInterop(path, mod) {
  321. if (this.options.interopDefault === false)
  322. return false;
  323. return !path.endsWith(".mjs") && "default" in mod;
  324. }
  325. async interopedImport(path) {
  326. const importedModule = await import(path);
  327. if (!this.shouldInterop(path, importedModule))
  328. return importedModule;
  329. const { mod, defaultExport } = interopModule(importedModule);
  330. return new Proxy(mod, {
  331. get(mod2, prop) {
  332. if (prop === "default")
  333. return defaultExport;
  334. return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
  335. },
  336. has(mod2, prop) {
  337. if (prop === "default")
  338. return defaultExport !== void 0;
  339. return prop in mod2 || defaultExport && prop in defaultExport;
  340. },
  341. getOwnPropertyDescriptor(mod2, prop) {
  342. const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop);
  343. if (descriptor)
  344. return descriptor;
  345. if (prop === "default" && defaultExport !== void 0) {
  346. return {
  347. value: defaultExport,
  348. enumerable: true,
  349. configurable: true
  350. };
  351. }
  352. }
  353. });
  354. }
  355. }
  356. function interopModule(mod) {
  357. if (isPrimitive(mod)) {
  358. return {
  359. mod: { default: mod },
  360. defaultExport: mod
  361. };
  362. }
  363. let defaultExport = "default" in mod ? mod.default : mod;
  364. if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
  365. mod = defaultExport;
  366. if ("default" in defaultExport)
  367. defaultExport = defaultExport.default;
  368. }
  369. return { mod, defaultExport };
  370. }
  371. function defineExport(exports, key, value) {
  372. Object.defineProperty(exports, key, {
  373. enumerable: true,
  374. configurable: true,
  375. get: value
  376. });
  377. }
  378. function exportAll(exports, sourceModule) {
  379. if (exports === sourceModule)
  380. return;
  381. if (isPrimitive(sourceModule) || Array.isArray(sourceModule))
  382. return;
  383. for (const key in sourceModule) {
  384. if (key !== "default") {
  385. try {
  386. defineExport(exports, key, () => sourceModule[key]);
  387. } catch (_err) {
  388. }
  389. }
  390. }
  391. }
  392. export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };