chunk-vite-node-client.da0a17ff.mjs 12 KB

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