index.cjs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. 'use strict';Object.defineProperty(exports, '__esModule', {value: true});
  2. const process = require('node:process');
  3. const perfectDebounce = require('perfect-debounce');
  4. const c = require('picocolors');
  5. const sirv = require('sirv');
  6. const node_path = require('node:path');
  7. const node_url = require('node:url');
  8. const fs = require('fs-extra');
  9. const node_buffer = require('node:buffer');
  10. const pluginutils = require('@rollup/pluginutils');
  11. const Debug = require('debug');
  12. const errorStackParserEs = require('error-stack-parser-es');
  13. const node_http = require('node:http');
  14. var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
  15. function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
  16. const process__default = /*#__PURE__*/_interopDefaultCompat(process);
  17. const c__default = /*#__PURE__*/_interopDefaultCompat(c);
  18. const sirv__default = /*#__PURE__*/_interopDefaultCompat(sirv);
  19. const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
  20. const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
  21. const DEFAULT_TIMEOUT = 6e4;
  22. function defaultSerialize(i) {
  23. return i;
  24. }
  25. const defaultDeserialize = defaultSerialize;
  26. const { clearTimeout, setTimeout: setTimeout$1 } = globalThis;
  27. const random = Math.random.bind(Math);
  28. function createBirpc(functions, options) {
  29. const {
  30. post,
  31. on,
  32. off = () => {
  33. },
  34. eventNames = [],
  35. serialize = defaultSerialize,
  36. deserialize = defaultDeserialize,
  37. resolver,
  38. bind = "rpc",
  39. timeout = DEFAULT_TIMEOUT
  40. } = options;
  41. const rpcPromiseMap = /* @__PURE__ */ new Map();
  42. let _promise;
  43. let closed = false;
  44. const rpc = new Proxy({}, {
  45. get(_, method) {
  46. if (method === "$functions")
  47. return functions;
  48. if (method === "$close")
  49. return close;
  50. if (method === "then" && !eventNames.includes("then") && !("then" in functions))
  51. return void 0;
  52. const sendEvent = (...args) => {
  53. post(serialize({ m: method, a: args, t: "q" }));
  54. };
  55. if (eventNames.includes(method)) {
  56. sendEvent.asEvent = sendEvent;
  57. return sendEvent;
  58. }
  59. const sendCall = async (...args) => {
  60. if (closed)
  61. throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
  62. if (_promise) {
  63. try {
  64. await _promise;
  65. } finally {
  66. _promise = void 0;
  67. }
  68. }
  69. return new Promise((resolve, reject) => {
  70. const id = nanoid();
  71. let timeoutId;
  72. if (timeout >= 0) {
  73. timeoutId = setTimeout$1(() => {
  74. try {
  75. options.onTimeoutError?.(method, args);
  76. throw new Error(`[birpc] timeout on calling "${method}"`);
  77. } catch (e) {
  78. reject(e);
  79. }
  80. rpcPromiseMap.delete(id);
  81. }, timeout);
  82. if (typeof timeoutId === "object")
  83. timeoutId = timeoutId.unref?.();
  84. }
  85. rpcPromiseMap.set(id, { resolve, reject, timeoutId, method });
  86. post(serialize({ m: method, a: args, i: id, t: "q" }));
  87. });
  88. };
  89. sendCall.asEvent = sendEvent;
  90. return sendCall;
  91. }
  92. });
  93. function close() {
  94. closed = true;
  95. rpcPromiseMap.forEach(({ reject, method }) => {
  96. reject(new Error(`[birpc] rpc is closed, cannot call "${method}"`));
  97. });
  98. rpcPromiseMap.clear();
  99. off(onMessage);
  100. }
  101. async function onMessage(data, ...extra) {
  102. const msg = deserialize(data);
  103. if (msg.t === "q") {
  104. const { m: method, a: args } = msg;
  105. let result, error;
  106. const fn = resolver ? resolver(method, functions[method]) : functions[method];
  107. if (!fn) {
  108. error = new Error(`[birpc] function "${method}" not found`);
  109. } else {
  110. try {
  111. result = await fn.apply(bind === "rpc" ? rpc : functions, args);
  112. } catch (e) {
  113. error = e;
  114. }
  115. }
  116. if (msg.i) {
  117. if (error && options.onError)
  118. options.onError(error, method, args);
  119. post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
  120. }
  121. } else {
  122. const { i: ack, r: result, e: error } = msg;
  123. const promise = rpcPromiseMap.get(ack);
  124. if (promise) {
  125. clearTimeout(promise.timeoutId);
  126. if (error)
  127. promise.reject(error);
  128. else
  129. promise.resolve(result);
  130. }
  131. rpcPromiseMap.delete(ack);
  132. }
  133. }
  134. _promise = on(onMessage);
  135. return rpc;
  136. }
  137. const cacheMap = /* @__PURE__ */ new WeakMap();
  138. function cachedMap(items, fn) {
  139. return items.map((i) => {
  140. let r = cacheMap.get(i);
  141. if (!r) {
  142. r = fn(i);
  143. cacheMap.set(i, r);
  144. }
  145. return r;
  146. });
  147. }
  148. function createBirpcGroup(functions, channels, options = {}) {
  149. const getChannels = () => typeof channels === "function" ? channels() : channels;
  150. const getClients = (channels2 = getChannels()) => cachedMap(channels2, (s) => createBirpc(functions, { ...options, ...s }));
  151. const broadcastProxy = new Proxy({}, {
  152. get(_, method) {
  153. const client = getClients();
  154. const callbacks = client.map((c) => c[method]);
  155. const sendCall = (...args) => {
  156. return Promise.all(callbacks.map((i) => i(...args)));
  157. };
  158. sendCall.asEvent = (...args) => {
  159. callbacks.map((i) => i.asEvent(...args));
  160. };
  161. return sendCall;
  162. }
  163. });
  164. function updateChannels(fn) {
  165. const channels2 = getChannels();
  166. fn?.(channels2);
  167. return getClients(channels2);
  168. }
  169. getClients();
  170. return {
  171. get clients() {
  172. return getClients();
  173. },
  174. functions,
  175. updateChannels,
  176. broadcast: broadcastProxy,
  177. /**
  178. * @deprecated use `broadcast`
  179. */
  180. // @ts-expect-error deprecated
  181. boardcast: broadcastProxy
  182. };
  183. }
  184. const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  185. function nanoid(size = 21) {
  186. let id = "";
  187. let i = size;
  188. while (i--)
  189. id += urlAlphabet[random() * 64 | 0];
  190. return id;
  191. }
  192. function createRPCServer(name, ws, functions, options = {}) {
  193. const event = `${name}:rpc`;
  194. const group = createBirpcGroup(
  195. functions,
  196. () => cachedMap(
  197. Array.from(ws?.clients || []),
  198. (channel) => {
  199. if (channel.socket.readyState === channel.socket.CLOSED)
  200. return void 0;
  201. return {
  202. on: (fn) => {
  203. function handler(data, source) {
  204. if (!source.socket)
  205. throw new Error("source.socket is undefined");
  206. if (channel.socket === source.socket)
  207. fn(data, source);
  208. }
  209. ws.on(event, handler);
  210. channel.socket.on("close", () => {
  211. ws.off(event, handler);
  212. });
  213. },
  214. post: (data) => {
  215. channel.send(event, data);
  216. }
  217. };
  218. }
  219. ).filter((c) => !!c),
  220. options
  221. );
  222. ws.on("connection", () => {
  223. group.updateChannels();
  224. });
  225. return group.broadcast;
  226. }
  227. const DIR_DIST = typeof __dirname !== "undefined" ? __dirname : node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
  228. const DIR_CLIENT = node_path.resolve(DIR_DIST, "../dist/client");
  229. const defaults = Object.freeze({
  230. ignoreUnknown: false,
  231. respectType: false,
  232. respectFunctionNames: false,
  233. respectFunctionProperties: false,
  234. unorderedObjects: true,
  235. unorderedArrays: false,
  236. unorderedSets: false,
  237. excludeKeys: void 0,
  238. excludeValues: void 0,
  239. replacer: void 0
  240. });
  241. function objectHash(object, options) {
  242. if (options) {
  243. options = { ...defaults, ...options };
  244. } else {
  245. options = defaults;
  246. }
  247. const hasher = createHasher(options);
  248. hasher.dispatch(object);
  249. return hasher.toString();
  250. }
  251. const defaultPrototypesKeys = Object.freeze([
  252. "prototype",
  253. "__proto__",
  254. "constructor"
  255. ]);
  256. function createHasher(options) {
  257. let buff = "";
  258. let context = /* @__PURE__ */ new Map();
  259. const write = (str) => {
  260. buff += str;
  261. };
  262. return {
  263. toString() {
  264. return buff;
  265. },
  266. getContext() {
  267. return context;
  268. },
  269. dispatch(value) {
  270. if (options.replacer) {
  271. value = options.replacer(value);
  272. }
  273. const type = value === null ? "null" : typeof value;
  274. return this[type](value);
  275. },
  276. object(object) {
  277. if (object && typeof object.toJSON === "function") {
  278. return this.object(object.toJSON());
  279. }
  280. const objString = Object.prototype.toString.call(object);
  281. let objType = "";
  282. const objectLength = objString.length;
  283. if (objectLength < 10) {
  284. objType = "unknown:[" + objString + "]";
  285. } else {
  286. objType = objString.slice(8, objectLength - 1);
  287. }
  288. objType = objType.toLowerCase();
  289. let objectNumber = null;
  290. if ((objectNumber = context.get(object)) === void 0) {
  291. context.set(object, context.size);
  292. } else {
  293. return this.dispatch("[CIRCULAR:" + objectNumber + "]");
  294. }
  295. if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
  296. write("buffer:");
  297. return write(object.toString("utf8"));
  298. }
  299. if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
  300. if (this[objType]) {
  301. this[objType](object);
  302. } else if (!options.ignoreUnknown) {
  303. this.unkown(object, objType);
  304. }
  305. } else {
  306. let keys = Object.keys(object);
  307. if (options.unorderedObjects) {
  308. keys = keys.sort();
  309. }
  310. let extraKeys = [];
  311. if (options.respectType !== false && !isNativeFunction(object)) {
  312. extraKeys = defaultPrototypesKeys;
  313. }
  314. if (options.excludeKeys) {
  315. keys = keys.filter((key) => {
  316. return !options.excludeKeys(key);
  317. });
  318. extraKeys = extraKeys.filter((key) => {
  319. return !options.excludeKeys(key);
  320. });
  321. }
  322. write("object:" + (keys.length + extraKeys.length) + ":");
  323. const dispatchForKey = (key) => {
  324. this.dispatch(key);
  325. write(":");
  326. if (!options.excludeValues) {
  327. this.dispatch(object[key]);
  328. }
  329. write(",");
  330. };
  331. for (const key of keys) {
  332. dispatchForKey(key);
  333. }
  334. for (const key of extraKeys) {
  335. dispatchForKey(key);
  336. }
  337. }
  338. },
  339. array(arr, unordered) {
  340. unordered = unordered === void 0 ? options.unorderedArrays !== false : unordered;
  341. write("array:" + arr.length + ":");
  342. if (!unordered || arr.length <= 1) {
  343. for (const entry of arr) {
  344. this.dispatch(entry);
  345. }
  346. return;
  347. }
  348. const contextAdditions = /* @__PURE__ */ new Map();
  349. const entries = arr.map((entry) => {
  350. const hasher = createHasher(options);
  351. hasher.dispatch(entry);
  352. for (const [key, value] of hasher.getContext()) {
  353. contextAdditions.set(key, value);
  354. }
  355. return hasher.toString();
  356. });
  357. context = contextAdditions;
  358. entries.sort();
  359. return this.array(entries, false);
  360. },
  361. date(date) {
  362. return write("date:" + date.toJSON());
  363. },
  364. symbol(sym) {
  365. return write("symbol:" + sym.toString());
  366. },
  367. unkown(value, type) {
  368. write(type);
  369. if (!value) {
  370. return;
  371. }
  372. write(":");
  373. if (value && typeof value.entries === "function") {
  374. return this.array(
  375. Array.from(value.entries()),
  376. true
  377. /* ordered */
  378. );
  379. }
  380. },
  381. error(err) {
  382. return write("error:" + err.toString());
  383. },
  384. boolean(bool) {
  385. return write("bool:" + bool);
  386. },
  387. string(string) {
  388. write("string:" + string.length + ":");
  389. write(string);
  390. },
  391. function(fn) {
  392. write("fn:");
  393. if (isNativeFunction(fn)) {
  394. this.dispatch("[native]");
  395. } else {
  396. this.dispatch(fn.toString());
  397. }
  398. if (options.respectFunctionNames !== false) {
  399. this.dispatch("function-name:" + String(fn.name));
  400. }
  401. if (options.respectFunctionProperties) {
  402. this.object(fn);
  403. }
  404. },
  405. number(number) {
  406. return write("number:" + number);
  407. },
  408. xml(xml) {
  409. return write("xml:" + xml.toString());
  410. },
  411. null() {
  412. return write("Null");
  413. },
  414. undefined() {
  415. return write("Undefined");
  416. },
  417. regexp(regex) {
  418. return write("regex:" + regex.toString());
  419. },
  420. uint8array(arr) {
  421. write("uint8array:");
  422. return this.dispatch(Array.prototype.slice.call(arr));
  423. },
  424. uint8clampedarray(arr) {
  425. write("uint8clampedarray:");
  426. return this.dispatch(Array.prototype.slice.call(arr));
  427. },
  428. int8array(arr) {
  429. write("int8array:");
  430. return this.dispatch(Array.prototype.slice.call(arr));
  431. },
  432. uint16array(arr) {
  433. write("uint16array:");
  434. return this.dispatch(Array.prototype.slice.call(arr));
  435. },
  436. int16array(arr) {
  437. write("int16array:");
  438. return this.dispatch(Array.prototype.slice.call(arr));
  439. },
  440. uint32array(arr) {
  441. write("uint32array:");
  442. return this.dispatch(Array.prototype.slice.call(arr));
  443. },
  444. int32array(arr) {
  445. write("int32array:");
  446. return this.dispatch(Array.prototype.slice.call(arr));
  447. },
  448. float32array(arr) {
  449. write("float32array:");
  450. return this.dispatch(Array.prototype.slice.call(arr));
  451. },
  452. float64array(arr) {
  453. write("float64array:");
  454. return this.dispatch(Array.prototype.slice.call(arr));
  455. },
  456. arraybuffer(arr) {
  457. write("arraybuffer:");
  458. return this.dispatch(new Uint8Array(arr));
  459. },
  460. url(url) {
  461. return write("url:" + url.toString());
  462. },
  463. map(map) {
  464. write("map:");
  465. const arr = [...map];
  466. return this.array(arr, options.unorderedSets !== false);
  467. },
  468. set(set) {
  469. write("set:");
  470. const arr = [...set];
  471. return this.array(arr, options.unorderedSets !== false);
  472. },
  473. file(file) {
  474. write("file:");
  475. return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
  476. },
  477. blob() {
  478. if (options.ignoreUnknown) {
  479. return write("[blob]");
  480. }
  481. throw new Error(
  482. 'Hashing Blob objects is currently not supported\nUse "options.replacer" or "options.ignoreUnknown"\n'
  483. );
  484. },
  485. domwindow() {
  486. return write("domwindow");
  487. },
  488. bigint(number) {
  489. return write("bigint:" + number.toString());
  490. },
  491. /* Node.js standard native objects */
  492. process() {
  493. return write("process");
  494. },
  495. timer() {
  496. return write("timer");
  497. },
  498. pipe() {
  499. return write("pipe");
  500. },
  501. tcp() {
  502. return write("tcp");
  503. },
  504. udp() {
  505. return write("udp");
  506. },
  507. tty() {
  508. return write("tty");
  509. },
  510. statwatcher() {
  511. return write("statwatcher");
  512. },
  513. securecontext() {
  514. return write("securecontext");
  515. },
  516. connection() {
  517. return write("connection");
  518. },
  519. zlib() {
  520. return write("zlib");
  521. },
  522. context() {
  523. return write("context");
  524. },
  525. nodescript() {
  526. return write("nodescript");
  527. },
  528. httpparser() {
  529. return write("httpparser");
  530. },
  531. dataview() {
  532. return write("dataview");
  533. },
  534. signal() {
  535. return write("signal");
  536. },
  537. fsevent() {
  538. return write("fsevent");
  539. },
  540. tlswrap() {
  541. return write("tlswrap");
  542. }
  543. };
  544. }
  545. const nativeFunc = "[native code] }";
  546. const nativeFuncLength = nativeFunc.length;
  547. function isNativeFunction(f) {
  548. if (typeof f !== "function") {
  549. return false;
  550. }
  551. return Function.prototype.toString.call(f).slice(-nativeFuncLength) === nativeFunc;
  552. }
  553. var __defProp$1$1 = Object.defineProperty;
  554. var __defNormalProp$1$1 = (obj, key, value) => key in obj ? __defProp$1$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  555. var __publicField$1$1 = (obj, key, value) => {
  556. __defNormalProp$1$1(obj, typeof key !== "symbol" ? key + "" : key, value);
  557. return value;
  558. };
  559. class WordArray {
  560. constructor(words, sigBytes) {
  561. __publicField$1$1(this, "words");
  562. __publicField$1$1(this, "sigBytes");
  563. words = this.words = words || [];
  564. this.sigBytes = sigBytes === void 0 ? words.length * 4 : sigBytes;
  565. }
  566. toString(encoder) {
  567. return (encoder || Hex).stringify(this);
  568. }
  569. concat(wordArray) {
  570. this.clamp();
  571. if (this.sigBytes % 4) {
  572. for (let i = 0; i < wordArray.sigBytes; i++) {
  573. const thatByte = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  574. this.words[this.sigBytes + i >>> 2] |= thatByte << 24 - (this.sigBytes + i) % 4 * 8;
  575. }
  576. } else {
  577. for (let j = 0; j < wordArray.sigBytes; j += 4) {
  578. this.words[this.sigBytes + j >>> 2] = wordArray.words[j >>> 2];
  579. }
  580. }
  581. this.sigBytes += wordArray.sigBytes;
  582. return this;
  583. }
  584. clamp() {
  585. this.words[this.sigBytes >>> 2] &= 4294967295 << 32 - this.sigBytes % 4 * 8;
  586. this.words.length = Math.ceil(this.sigBytes / 4);
  587. }
  588. clone() {
  589. return new WordArray([...this.words]);
  590. }
  591. }
  592. const Hex = {
  593. stringify(wordArray) {
  594. const hexChars = [];
  595. for (let i = 0; i < wordArray.sigBytes; i++) {
  596. const bite = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  597. hexChars.push((bite >>> 4).toString(16), (bite & 15).toString(16));
  598. }
  599. return hexChars.join("");
  600. }
  601. };
  602. const Base64 = {
  603. stringify(wordArray) {
  604. const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  605. const base64Chars = [];
  606. for (let i = 0; i < wordArray.sigBytes; i += 3) {
  607. const byte1 = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  608. const byte2 = wordArray.words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255;
  609. const byte3 = wordArray.words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255;
  610. const triplet = byte1 << 16 | byte2 << 8 | byte3;
  611. for (let j = 0; j < 4 && i * 8 + j * 6 < wordArray.sigBytes * 8; j++) {
  612. base64Chars.push(keyStr.charAt(triplet >>> 6 * (3 - j) & 63));
  613. }
  614. }
  615. return base64Chars.join("");
  616. }
  617. };
  618. const Latin1 = {
  619. parse(latin1Str) {
  620. const latin1StrLength = latin1Str.length;
  621. const words = [];
  622. for (let i = 0; i < latin1StrLength; i++) {
  623. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
  624. }
  625. return new WordArray(words, latin1StrLength);
  626. }
  627. };
  628. const Utf8 = {
  629. parse(utf8Str) {
  630. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  631. }
  632. };
  633. class BufferedBlockAlgorithm {
  634. constructor() {
  635. __publicField$1$1(this, "_data", new WordArray());
  636. __publicField$1$1(this, "_nDataBytes", 0);
  637. __publicField$1$1(this, "_minBufferSize", 0);
  638. __publicField$1$1(this, "blockSize", 512 / 32);
  639. }
  640. reset() {
  641. this._data = new WordArray();
  642. this._nDataBytes = 0;
  643. }
  644. _append(data) {
  645. if (typeof data === "string") {
  646. data = Utf8.parse(data);
  647. }
  648. this._data.concat(data);
  649. this._nDataBytes += data.sigBytes;
  650. }
  651. _doProcessBlock(_dataWords, _offset) {
  652. }
  653. _process(doFlush) {
  654. let processedWords;
  655. let nBlocksReady = this._data.sigBytes / (this.blockSize * 4);
  656. if (doFlush) {
  657. nBlocksReady = Math.ceil(nBlocksReady);
  658. } else {
  659. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  660. }
  661. const nWordsReady = nBlocksReady * this.blockSize;
  662. const nBytesReady = Math.min(nWordsReady * 4, this._data.sigBytes);
  663. if (nWordsReady) {
  664. for (let offset = 0; offset < nWordsReady; offset += this.blockSize) {
  665. this._doProcessBlock(this._data.words, offset);
  666. }
  667. processedWords = this._data.words.splice(0, nWordsReady);
  668. this._data.sigBytes -= nBytesReady;
  669. }
  670. return new WordArray(processedWords, nBytesReady);
  671. }
  672. }
  673. class Hasher extends BufferedBlockAlgorithm {
  674. update(messageUpdate) {
  675. this._append(messageUpdate);
  676. this._process();
  677. return this;
  678. }
  679. finalize(messageUpdate) {
  680. if (messageUpdate) {
  681. this._append(messageUpdate);
  682. }
  683. }
  684. }
  685. var __defProp$2 = Object.defineProperty;
  686. var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  687. var __publicField$2 = (obj, key, value) => {
  688. __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
  689. return value;
  690. };
  691. const H = [
  692. 1779033703,
  693. -1150833019,
  694. 1013904242,
  695. -1521486534,
  696. 1359893119,
  697. -1694144372,
  698. 528734635,
  699. 1541459225
  700. ];
  701. const K = [
  702. 1116352408,
  703. 1899447441,
  704. -1245643825,
  705. -373957723,
  706. 961987163,
  707. 1508970993,
  708. -1841331548,
  709. -1424204075,
  710. -670586216,
  711. 310598401,
  712. 607225278,
  713. 1426881987,
  714. 1925078388,
  715. -2132889090,
  716. -1680079193,
  717. -1046744716,
  718. -459576895,
  719. -272742522,
  720. 264347078,
  721. 604807628,
  722. 770255983,
  723. 1249150122,
  724. 1555081692,
  725. 1996064986,
  726. -1740746414,
  727. -1473132947,
  728. -1341970488,
  729. -1084653625,
  730. -958395405,
  731. -710438585,
  732. 113926993,
  733. 338241895,
  734. 666307205,
  735. 773529912,
  736. 1294757372,
  737. 1396182291,
  738. 1695183700,
  739. 1986661051,
  740. -2117940946,
  741. -1838011259,
  742. -1564481375,
  743. -1474664885,
  744. -1035236496,
  745. -949202525,
  746. -778901479,
  747. -694614492,
  748. -200395387,
  749. 275423344,
  750. 430227734,
  751. 506948616,
  752. 659060556,
  753. 883997877,
  754. 958139571,
  755. 1322822218,
  756. 1537002063,
  757. 1747873779,
  758. 1955562222,
  759. 2024104815,
  760. -2067236844,
  761. -1933114872,
  762. -1866530822,
  763. -1538233109,
  764. -1090935817,
  765. -965641998
  766. ];
  767. const W = [];
  768. class SHA256 extends Hasher {
  769. constructor() {
  770. super(...arguments);
  771. __publicField$2(this, "_hash", new WordArray([...H]));
  772. }
  773. /**
  774. * Resets the internal state of the hash object to initial values.
  775. */
  776. reset() {
  777. super.reset();
  778. this._hash = new WordArray([...H]);
  779. }
  780. _doProcessBlock(M, offset) {
  781. const H2 = this._hash.words;
  782. let a = H2[0];
  783. let b = H2[1];
  784. let c = H2[2];
  785. let d = H2[3];
  786. let e = H2[4];
  787. let f = H2[5];
  788. let g = H2[6];
  789. let h = H2[7];
  790. for (let i = 0; i < 64; i++) {
  791. if (i < 16) {
  792. W[i] = M[offset + i] | 0;
  793. } else {
  794. const gamma0x = W[i - 15];
  795. const gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
  796. const gamma1x = W[i - 2];
  797. const gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
  798. W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
  799. }
  800. const ch = e & f ^ ~e & g;
  801. const maj = a & b ^ a & c ^ b & c;
  802. const sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
  803. const sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
  804. const t1 = h + sigma1 + ch + K[i] + W[i];
  805. const t2 = sigma0 + maj;
  806. h = g;
  807. g = f;
  808. f = e;
  809. e = d + t1 | 0;
  810. d = c;
  811. c = b;
  812. b = a;
  813. a = t1 + t2 | 0;
  814. }
  815. H2[0] = H2[0] + a | 0;
  816. H2[1] = H2[1] + b | 0;
  817. H2[2] = H2[2] + c | 0;
  818. H2[3] = H2[3] + d | 0;
  819. H2[4] = H2[4] + e | 0;
  820. H2[5] = H2[5] + f | 0;
  821. H2[6] = H2[6] + g | 0;
  822. H2[7] = H2[7] + h | 0;
  823. }
  824. /**
  825. * Finishes the hash calculation and returns the hash as a WordArray.
  826. *
  827. * @param {string} messageUpdate - Additional message content to include in the hash.
  828. * @returns {WordArray} The finalised hash as a WordArray.
  829. */
  830. finalize(messageUpdate) {
  831. super.finalize(messageUpdate);
  832. const nBitsTotal = this._nDataBytes * 8;
  833. const nBitsLeft = this._data.sigBytes * 8;
  834. this._data.words[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  835. this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(
  836. nBitsTotal / 4294967296
  837. );
  838. this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  839. this._data.sigBytes = this._data.words.length * 4;
  840. this._process();
  841. return this._hash;
  842. }
  843. }
  844. function sha256base64(message) {
  845. return new SHA256().finalize(message).toString(Base64);
  846. }
  847. function hash(object, options = {}) {
  848. const hashed = typeof object === "string" ? object : objectHash(object, options);
  849. return sha256base64(hashed).slice(0, 10);
  850. }
  851. const DUMMY_LOAD_PLUGIN_NAME = "__load__";
  852. async function generateBuild(ctx, config) {
  853. const {
  854. outputDir = ".vite-inspect"
  855. } = ctx.options;
  856. const targetDir = node_path.isAbsolute(outputDir) ? outputDir : node_path.resolve(config.root, outputDir);
  857. const reportsDir = node_path.join(targetDir, "reports");
  858. await fs__default.emptyDir(targetDir);
  859. await fs__default.ensureDir(reportsDir);
  860. await fs__default.copy(DIR_CLIENT, targetDir);
  861. const isVirtual = (pluginName, transformName) => pluginName !== DUMMY_LOAD_PLUGIN_NAME && transformName !== "vite:load-fallback";
  862. function list() {
  863. return {
  864. root: config.root,
  865. modules: ctx.getModulesInfo(ctx.recorderClient, null, isVirtual),
  866. ssrModules: ctx.getModulesInfo(ctx.recorderServer, null, isVirtual)
  867. };
  868. }
  869. async function dumpModuleInfo(dir, recorder, ssr = false) {
  870. await fs__default.ensureDir(dir);
  871. return Promise.all(
  872. Object.entries(recorder.transform).map(
  873. ([id, info]) => fs__default.writeJSON(
  874. node_path.join(dir, `${hash(id)}.json`),
  875. {
  876. resolvedId: ctx.resolveId(id, ssr),
  877. transforms: info
  878. },
  879. { spaces: 2 }
  880. )
  881. )
  882. );
  883. }
  884. await Promise.all([
  885. fs__default.writeFile(
  886. node_path.join(targetDir, "index.html"),
  887. (await fs__default.readFile(node_path.join(targetDir, "index.html"), "utf-8")).replace(
  888. 'data-vite-inspect-mode="DEV"',
  889. 'data-vite-inspect-mode="BUILD"'
  890. )
  891. ),
  892. fs__default.writeJSON(
  893. node_path.join(reportsDir, "list.json"),
  894. list(),
  895. { spaces: 2 }
  896. ),
  897. fs__default.writeJSON(
  898. node_path.join(reportsDir, "metrics.json"),
  899. ctx.getPluginMetrics(false),
  900. { spaces: 2 }
  901. ),
  902. fs__default.writeJSON(
  903. node_path.join(reportsDir, "metrics-ssr.json"),
  904. ctx.getPluginMetrics(true),
  905. { spaces: 2 }
  906. ),
  907. dumpModuleInfo(node_path.join(reportsDir, "transform"), ctx.recorderClient),
  908. dumpModuleInfo(node_path.join(reportsDir, "transform-ssr"), ctx.recorderServer, true)
  909. ]);
  910. return targetDir;
  911. }
  912. var __defProp$1 = Object.defineProperty;
  913. var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  914. var __publicField$1 = (obj, key, value) => {
  915. __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
  916. return value;
  917. };
  918. class Recorder {
  919. constructor(context) {
  920. this.context = context;
  921. __publicField$1(this, "transform", {});
  922. __publicField$1(this, "resolveId", {});
  923. __publicField$1(this, "transformCounter", {});
  924. this.context = context;
  925. }
  926. recordTransform(id, info, preTransformCode) {
  927. id = this.context.normalizeId(id);
  928. if (!this.transform[id] || !this.transform[id].some((tr) => tr.result)) {
  929. this.transform[id] = [{
  930. name: DUMMY_LOAD_PLUGIN_NAME,
  931. result: preTransformCode,
  932. start: info.start,
  933. end: info.start,
  934. sourcemaps: info.sourcemaps
  935. }];
  936. this.transformCounter[id] = (this.transformCounter[id] || 0) + 1;
  937. }
  938. this.transform[id].push(info);
  939. }
  940. recordLoad(id, info) {
  941. id = this.context.normalizeId(id);
  942. this.transform[id] = [info];
  943. this.transformCounter[id] = (this.transformCounter[id] || 0) + 1;
  944. }
  945. recordResolveId(id, info) {
  946. id = this.context.normalizeId(id);
  947. if (!this.resolveId[id])
  948. this.resolveId[id] = [];
  949. this.resolveId[id].push(info);
  950. }
  951. invalidate(id) {
  952. id = this.context.normalizeId(id);
  953. delete this.transform[id];
  954. }
  955. }
  956. async function openBrowser(address) {
  957. await import('open').then((r) => r.default(address, { newInstance: true })).catch(() => {
  958. });
  959. }
  960. function removeVersionQuery(url) {
  961. if (url.includes("v=")) {
  962. return url.replace(/&v=\w+/, "").replace(/\?v=\w+/, "?").replace(/\?$/, "");
  963. }
  964. return url;
  965. }
  966. var __defProp = Object.defineProperty;
  967. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  968. var __publicField = (obj, key, value) => {
  969. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  970. return value;
  971. };
  972. class ViteInspectContext {
  973. constructor(options) {
  974. this.options = options;
  975. __publicField(this, "filter");
  976. __publicField(this, "config");
  977. __publicField(this, "recorderClient");
  978. __publicField(this, "recorderServer");
  979. this.filter = pluginutils.createFilter(options.include, options.exclude);
  980. this.recorderClient = new Recorder(this);
  981. this.recorderServer = new Recorder(this);
  982. }
  983. normalizeId(id) {
  984. if (this.options.removeVersionQuery !== false)
  985. return removeVersionQuery(id);
  986. return id;
  987. }
  988. getRecorder(ssr) {
  989. return ssr ? this.recorderServer : this.recorderClient;
  990. }
  991. resolveId(id = "", ssr = false) {
  992. if (id.startsWith("./"))
  993. id = node_path.resolve(this.config.root, id).replace(/\\/g, "/");
  994. return this.resolveIdRecursive(id, ssr);
  995. }
  996. resolveIdRecursive(id, ssr = false) {
  997. const rec = this.getRecorder(ssr);
  998. const resolved = rec.resolveId[id]?.[0]?.result;
  999. return resolved ? this.resolveIdRecursive(resolved, ssr) : id;
  1000. }
  1001. getList(server) {
  1002. const isVirtual = (pluginName) => pluginName !== DUMMY_LOAD_PLUGIN_NAME;
  1003. const getDeps = (id) => Array.from(server.moduleGraph.getModuleById(id)?.importedModules || []).map((i) => i.id || "").filter(Boolean);
  1004. return {
  1005. root: this.config.root,
  1006. modules: this.getModulesInfo(this.recorderClient, getDeps, isVirtual),
  1007. ssrModules: this.getModulesInfo(this.recorderServer, getDeps, isVirtual)
  1008. };
  1009. }
  1010. getModulesInfo(recorder, getDeps, isVirtual) {
  1011. function transformIdMap(recorder2) {
  1012. return Object.values(recorder2.resolveId).reduce((map, ids2) => {
  1013. ids2.forEach((id) => {
  1014. var _a;
  1015. map[_a = id.result] ?? (map[_a] = []);
  1016. map[id.result].push(id);
  1017. });
  1018. return map;
  1019. }, {});
  1020. }
  1021. const transformedIdMap = transformIdMap(recorder);
  1022. const ids = new Set(Object.keys(recorder.transform).concat(Object.keys(transformedIdMap)));
  1023. return Array.from(ids).sort().map((id) => {
  1024. let totalTime = 0;
  1025. const plugins = (recorder.transform[id] || []).filter((tr) => tr.result).map((transItem) => {
  1026. const delta = transItem.end - transItem.start;
  1027. totalTime += delta;
  1028. return { name: transItem.name, transform: delta };
  1029. }).concat(
  1030. // @ts-expect-error transform is optional
  1031. (transformedIdMap[id] || []).map((idItem) => {
  1032. return { name: idItem.name, resolveId: idItem.end - idItem.start };
  1033. })
  1034. );
  1035. function getSize(str) {
  1036. if (!str)
  1037. return 0;
  1038. return node_buffer.Buffer.byteLength(str, "utf8");
  1039. }
  1040. return {
  1041. id,
  1042. deps: getDeps ? getDeps(id) : [],
  1043. plugins,
  1044. virtual: isVirtual(plugins[0]?.name || "", recorder.transform[id]?.[0].name || ""),
  1045. totalTime,
  1046. invokeCount: recorder.transformCounter?.[id] || 0,
  1047. sourceSize: getSize(recorder.transform[id]?.[0]?.result),
  1048. distSize: getSize(recorder.transform[id]?.[recorder.transform[id].length - 1]?.result)
  1049. };
  1050. });
  1051. }
  1052. getPluginMetrics(ssr = false) {
  1053. const map = {};
  1054. const defaultMetricInfo = () => ({
  1055. transform: { invokeCount: 0, totalTime: 0 },
  1056. resolveId: { invokeCount: 0, totalTime: 0 }
  1057. });
  1058. this.config.plugins.forEach((i) => {
  1059. map[i.name] = {
  1060. ...defaultMetricInfo(),
  1061. name: i.name,
  1062. enforce: i.enforce
  1063. };
  1064. });
  1065. const recorder = this.getRecorder(ssr);
  1066. Object.values(recorder.transform).forEach((transformInfos) => {
  1067. transformInfos.forEach(({ name, start, end }) => {
  1068. if (name === DUMMY_LOAD_PLUGIN_NAME)
  1069. return;
  1070. if (!map[name])
  1071. map[name] = { ...defaultMetricInfo(), name };
  1072. map[name].transform.totalTime += end - start;
  1073. map[name].transform.invokeCount += 1;
  1074. });
  1075. });
  1076. Object.values(recorder.resolveId).forEach((resolveIdInfos) => {
  1077. resolveIdInfos.forEach(({ name, start, end }) => {
  1078. if (!map[name])
  1079. map[name] = { ...defaultMetricInfo(), name };
  1080. map[name].resolveId.totalTime += end - start;
  1081. map[name].resolveId.invokeCount += 1;
  1082. });
  1083. });
  1084. const metrics = Object.values(map).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
  1085. return metrics;
  1086. }
  1087. }
  1088. const debug = Debug__default("vite-plugin-inspect");
  1089. function hijackHook(plugin, name, wrapper) {
  1090. if (!plugin[name])
  1091. return;
  1092. debug(`hijack plugin "${name}"`, plugin.name);
  1093. let order = plugin.order || plugin.enforce || "normal";
  1094. const hook = plugin[name];
  1095. if ("handler" in hook) {
  1096. const oldFn = hook.handler;
  1097. order += `-${hook.order || hook.enforce || "normal"}`;
  1098. hook.handler = function(...args) {
  1099. return wrapper(oldFn, this, args, order);
  1100. };
  1101. } else if ("transform" in hook) {
  1102. const oldFn = hook.transform;
  1103. order += `-${hook.order || hook.enforce || "normal"}`;
  1104. hook.transform = function(...args) {
  1105. return wrapper(oldFn, this, args, order);
  1106. };
  1107. } else {
  1108. const oldFn = hook;
  1109. plugin[name] = function(...args) {
  1110. return wrapper(oldFn, this, args, order);
  1111. };
  1112. }
  1113. }
  1114. function hijackPlugin(plugin, ctx) {
  1115. hijackHook(plugin, "transform", async (fn, context, args, order) => {
  1116. const code = args[0];
  1117. const id = args[1];
  1118. const ssr = args[2]?.ssr;
  1119. let _result;
  1120. let error;
  1121. const start = Date.now();
  1122. try {
  1123. _result = await fn.apply(context, args);
  1124. } catch (_err) {
  1125. error = _err;
  1126. }
  1127. const end = Date.now();
  1128. const result = error ? "[Error]" : typeof _result === "string" ? _result : _result?.code;
  1129. if (ctx.filter(id)) {
  1130. const sourcemaps = typeof _result === "string" ? null : _result?.map;
  1131. const rec = ctx.getRecorder(ssr);
  1132. rec.recordTransform(id, {
  1133. name: plugin.name,
  1134. result,
  1135. start,
  1136. end,
  1137. order,
  1138. sourcemaps,
  1139. error: error ? parseError(error) : void 0
  1140. }, code);
  1141. }
  1142. if (error)
  1143. throw error;
  1144. return _result;
  1145. });
  1146. hijackHook(plugin, "load", async (fn, context, args) => {
  1147. const id = args[0];
  1148. const ssr = args[1]?.ssr;
  1149. let _result;
  1150. let error;
  1151. const start = Date.now();
  1152. try {
  1153. _result = await fn.apply(context, args);
  1154. } catch (err) {
  1155. error = err;
  1156. }
  1157. const end = Date.now();
  1158. const result = error ? "[Error]" : typeof _result === "string" ? _result : _result?.code;
  1159. const sourcemaps = typeof _result === "string" ? null : _result?.map;
  1160. if (result) {
  1161. ctx.getRecorder(ssr).recordLoad(id, {
  1162. name: plugin.name,
  1163. result,
  1164. start,
  1165. end,
  1166. sourcemaps,
  1167. error: error ? parseError(error) : void 0
  1168. });
  1169. }
  1170. if (error)
  1171. throw error;
  1172. return _result;
  1173. });
  1174. hijackHook(plugin, "resolveId", async (fn, context, args) => {
  1175. const id = args[0];
  1176. const ssr = args[2]?.ssr;
  1177. let _result;
  1178. let error;
  1179. const start = Date.now();
  1180. try {
  1181. _result = await fn.apply(context, args);
  1182. } catch (err) {
  1183. error = err;
  1184. }
  1185. const end = Date.now();
  1186. if (!ctx.filter(id)) {
  1187. if (error)
  1188. throw error;
  1189. return _result;
  1190. }
  1191. const result = error ? stringifyError(error) : typeof _result === "object" ? _result?.id : _result;
  1192. if (result && result !== id) {
  1193. ctx.getRecorder(ssr).recordResolveId(id, {
  1194. name: plugin.name,
  1195. result,
  1196. start,
  1197. end,
  1198. error
  1199. });
  1200. }
  1201. if (error)
  1202. throw error;
  1203. return _result;
  1204. });
  1205. }
  1206. function parseError(error) {
  1207. const stack = errorStackParserEs.parse(error, { allowEmpty: true });
  1208. const message = error.message || String(error);
  1209. return {
  1210. message,
  1211. stack,
  1212. raw: error
  1213. };
  1214. }
  1215. function stringifyError(err) {
  1216. return String(err.stack ? err.stack : err);
  1217. }
  1218. function createPreviewServer(staticPath) {
  1219. const server = node_http.createServer();
  1220. const statics = sirv__default(staticPath);
  1221. server.on("request", (req, res) => {
  1222. statics(req, res, () => {
  1223. res.statusCode = 404;
  1224. res.end("File not found");
  1225. });
  1226. });
  1227. server.listen(0, () => {
  1228. const { port } = server.address();
  1229. const url = `http://localhost:${port}`;
  1230. console.log(` ${c__default.green("\u279C")} ${c__default.bold("Inspect Preview Started")}: ${url}`);
  1231. openBrowser(url);
  1232. });
  1233. }
  1234. const NAME = "vite-plugin-inspect";
  1235. const isCI = !!process__default.env.CI;
  1236. function PluginInspect(options = {}) {
  1237. const {
  1238. dev = true,
  1239. build = false,
  1240. silent = false,
  1241. open: _open = false
  1242. } = options;
  1243. if (!dev && !build) {
  1244. return {
  1245. name: NAME
  1246. };
  1247. }
  1248. const ctx = new ViteInspectContext(options);
  1249. const timestampRE = /\bt=\d{13}&?\b/;
  1250. const trailingSeparatorRE = /[?&]$/;
  1251. let config;
  1252. const serverPerf = {
  1253. middleware: {}
  1254. };
  1255. function setupMiddlewarePerf(middlewares) {
  1256. let firstMiddlewareIndex = -1;
  1257. middlewares.forEach((middleware, index) => {
  1258. const { handle: originalHandle } = middleware;
  1259. if (typeof originalHandle !== "function" || !originalHandle.name)
  1260. return middleware;
  1261. middleware.handle = (...middlewareArgs) => {
  1262. var _a;
  1263. let req;
  1264. if (middlewareArgs.length === 4)
  1265. [, req] = middlewareArgs;
  1266. else
  1267. [req] = middlewareArgs;
  1268. const start = Date.now();
  1269. const url = req.url?.replace(timestampRE, "").replace(trailingSeparatorRE, "");
  1270. (_a = serverPerf.middleware)[url] ?? (_a[url] = []);
  1271. if (firstMiddlewareIndex < 0)
  1272. firstMiddlewareIndex = index;
  1273. if (index === firstMiddlewareIndex)
  1274. serverPerf.middleware[url] = [];
  1275. const result = originalHandle(...middlewareArgs);
  1276. Promise.resolve(result).then(() => {
  1277. const total = Date.now() - start;
  1278. const metrics = serverPerf.middleware[url];
  1279. serverPerf.middleware[url].push({
  1280. self: metrics.length ? Math.max(total - metrics[metrics.length - 1].total, 0) : total,
  1281. total,
  1282. name: originalHandle.name
  1283. });
  1284. });
  1285. return result;
  1286. };
  1287. Object.defineProperty(middleware.handle, "name", {
  1288. value: originalHandle.name,
  1289. configurable: true,
  1290. enumerable: true
  1291. });
  1292. return middleware;
  1293. });
  1294. }
  1295. function configureServer(server) {
  1296. const _invalidateModule = server.moduleGraph.invalidateModule;
  1297. server.moduleGraph.invalidateModule = function(...args) {
  1298. const mod = args[0];
  1299. if (mod?.id) {
  1300. ctx.recorderClient.invalidate(mod.id);
  1301. ctx.recorderServer.invalidate(mod.id);
  1302. }
  1303. return _invalidateModule.apply(this, args);
  1304. };
  1305. const base = (options.base ?? server.config.base) || "/";
  1306. server.middlewares.use(`${base}__inspect`, sirv__default(DIR_CLIENT, {
  1307. single: true,
  1308. dev: true
  1309. }));
  1310. const rpcFunctions = {
  1311. list: () => ctx.getList(server),
  1312. getIdInfo,
  1313. getPluginMetrics: (ssr = false) => ctx.getPluginMetrics(ssr),
  1314. getServerMetrics,
  1315. resolveId: (id, ssr = false) => ctx.resolveId(id, ssr),
  1316. clear: clearId,
  1317. moduleUpdated: () => {
  1318. }
  1319. };
  1320. const rpcServer = createRPCServer("vite-plugin-inspect", server.ws, rpcFunctions);
  1321. const debouncedModuleUpdated = perfectDebounce.debounce(() => {
  1322. rpcServer.moduleUpdated.asEvent();
  1323. }, 100);
  1324. server.middlewares.use((req, res, next) => {
  1325. debouncedModuleUpdated();
  1326. next();
  1327. });
  1328. function getServerMetrics() {
  1329. return serverPerf || {};
  1330. }
  1331. async function getIdInfo(id, ssr = false, clear = false) {
  1332. if (clear) {
  1333. clearId(id, ssr);
  1334. try {
  1335. await server.transformRequest(id, { ssr });
  1336. } catch {
  1337. }
  1338. }
  1339. const resolvedId = ctx.resolveId(id, ssr);
  1340. const recorder = ctx.getRecorder(ssr);
  1341. return {
  1342. resolvedId,
  1343. transforms: recorder.transform[resolvedId] || []
  1344. };
  1345. }
  1346. function clearId(_id, ssr = false) {
  1347. const id = ctx.resolveId(_id);
  1348. if (id) {
  1349. const mod = server.moduleGraph.getModuleById(id);
  1350. if (mod)
  1351. server.moduleGraph.invalidateModule(mod);
  1352. ctx.getRecorder(ssr).invalidate(id);
  1353. }
  1354. }
  1355. const _print = server.printUrls;
  1356. server.printUrls = () => {
  1357. let host = `${config.server.https ? "https" : "http"}://localhost:${config.server.port || "80"}`;
  1358. const url = server.resolvedUrls?.local[0];
  1359. if (url) {
  1360. try {
  1361. const u = new URL(url);
  1362. host = `${u.protocol}//${u.host}`;
  1363. } catch (error) {
  1364. config.logger.warn(`Parse resolved url failed: ${error}`);
  1365. }
  1366. }
  1367. _print();
  1368. if (!silent) {
  1369. const colorUrl = (url2) => c__default.green(url2.replace(/:(\d+)\//, (_, port) => `:${c__default.bold(port)}/`));
  1370. config.logger.info(` ${c__default.green("\u279C")} ${c__default.bold("Inspect")}: ${colorUrl(`${host}${base}__inspect/`)}`);
  1371. }
  1372. if (_open && !isCI) {
  1373. setTimeout(() => {
  1374. openBrowser(`${host}${base}__inspect/`);
  1375. }, 500);
  1376. }
  1377. };
  1378. return rpcFunctions;
  1379. }
  1380. const plugin = {
  1381. name: NAME,
  1382. enforce: "pre",
  1383. apply(_, { command }) {
  1384. if (command === "serve" && dev)
  1385. return true;
  1386. if (command === "build" && build)
  1387. return true;
  1388. return false;
  1389. },
  1390. configResolved(_config) {
  1391. config = ctx.config = _config;
  1392. config.plugins.forEach((plugin2) => hijackPlugin(plugin2, ctx));
  1393. const _createResolver = config.createResolver;
  1394. config.createResolver = function(...args) {
  1395. const _resolver = _createResolver.apply(this, args);
  1396. return async function(...args2) {
  1397. const id = args2[0];
  1398. const aliasOnly = args2[2];
  1399. const ssr = args2[3];
  1400. const start = Date.now();
  1401. const result = await _resolver.apply(this, args2);
  1402. const end = Date.now();
  1403. if (result && result !== id) {
  1404. const pluginName = aliasOnly ? "alias" : "vite:resolve (+alias)";
  1405. ctx.getRecorder(ssr).recordResolveId(id, { name: pluginName, result, start, end });
  1406. }
  1407. return result;
  1408. };
  1409. };
  1410. },
  1411. configureServer(server) {
  1412. const rpc = configureServer(server);
  1413. plugin.api = {
  1414. rpc
  1415. };
  1416. return () => {
  1417. setupMiddlewarePerf(server.middlewares.stack);
  1418. };
  1419. },
  1420. load: {
  1421. order: "pre",
  1422. handler(id, { ssr } = {}) {
  1423. ctx.getRecorder(ssr).invalidate(id);
  1424. return null;
  1425. }
  1426. },
  1427. handleHotUpdate({ modules, server }) {
  1428. const ids = modules.map((module) => module.id);
  1429. server.ws.send({
  1430. type: "custom",
  1431. event: "vite-plugin-inspect:update",
  1432. data: { ids }
  1433. });
  1434. },
  1435. async buildEnd() {
  1436. if (!build)
  1437. return;
  1438. const dir = await generateBuild(ctx, config);
  1439. config.logger.info(`${c__default.green("Inspect report generated at")} ${c__default.dim(`${dir}`)}`);
  1440. if (_open && !isCI)
  1441. createPreviewServer(dir);
  1442. }
  1443. };
  1444. return plugin;
  1445. }
  1446. PluginInspect.getViteInspectAPI = function(plugins) {
  1447. return plugins.find((p) => p.name === NAME)?.api;
  1448. };
  1449. exports.default = PluginInspect;