市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1620 lines
51 KiB

  1. import { computed, customRef, effectScope, getCurrentInstance, getCurrentScope, hasInjectionContext, inject, isReactive, isRef, markRaw, nextTick, onMounted, onScopeDispose, reactive, readonly, ref, shallowRef, toRaw, toRef, toRefs, toValue, unref, watch, watchEffect } from "./runtime-core.esm-bundler-Cyv4obHQ.js";
  2. /**
  3. * setActivePinia must be called to handle SSR at the top of functions like
  4. * `fetch`, `setup`, `serverPrefetch` and others
  5. */
  6. let activePinia;
  7. /**
  8. * Sets or unsets the active pinia. Used in SSR and internally when calling
  9. * actions and getters
  10. *
  11. * @param pinia - Pinia instance
  12. */
  13. const setActivePinia = (pinia) => activePinia = pinia;
  14. const piniaSymbol = Symbol();
  15. function isPlainObject(o) {
  16. return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
  17. }
  18. /**
  19. * Possible types for SubscriptionCallback
  20. */
  21. var MutationType;
  22. (function(MutationType$1) {
  23. /**
  24. * Direct mutation of the state:
  25. *
  26. * - `store.name = 'new name'`
  27. * - `store.$state.name = 'new name'`
  28. * - `store.list.push('new item')`
  29. */
  30. MutationType$1["direct"] = "direct";
  31. /**
  32. * Mutated the state with `$patch` and an object
  33. *
  34. * - `store.$patch({ name: 'newName' })`
  35. */
  36. MutationType$1["patchObject"] = "patch object";
  37. /**
  38. * Mutated the state with `$patch` and a function
  39. *
  40. * - `store.$patch(state => state.name = 'newName')`
  41. */
  42. MutationType$1["patchFunction"] = "patch function";
  43. })(MutationType || (MutationType = {}));
  44. const IS_CLIENT = typeof window !== "undefined";
  45. const _global$1 = /* @__PURE__ */ (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })();
  46. function bom(blob, { autoBom = false } = {}) {
  47. if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
  48. return blob;
  49. }
  50. function download(url, name, opts) {
  51. const xhr = new XMLHttpRequest();
  52. xhr.open("GET", url);
  53. xhr.responseType = "blob";
  54. xhr.onload = function() {
  55. saveAs(xhr.response, name, opts);
  56. };
  57. xhr.onerror = function() {
  58. console.error("could not download file");
  59. };
  60. xhr.send();
  61. }
  62. function corsEnabled(url) {
  63. const xhr = new XMLHttpRequest();
  64. xhr.open("HEAD", url, false);
  65. try {
  66. xhr.send();
  67. } catch (e) {}
  68. return xhr.status >= 200 && xhr.status <= 299;
  69. }
  70. function click(node) {
  71. try {
  72. node.dispatchEvent(new MouseEvent("click"));
  73. } catch (e) {
  74. const evt = new MouseEvent("click", {
  75. bubbles: true,
  76. cancelable: true,
  77. view: window,
  78. detail: 0,
  79. screenX: 80,
  80. screenY: 20,
  81. clientX: 80,
  82. clientY: 20,
  83. ctrlKey: false,
  84. altKey: false,
  85. shiftKey: false,
  86. metaKey: false,
  87. button: 0,
  88. relatedTarget: null
  89. });
  90. node.dispatchEvent(evt);
  91. }
  92. }
  93. const _navigator = typeof navigator === "object" ? navigator : { userAgent: "" };
  94. const isMacOSWebView = /* @__PURE__ */ (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))();
  95. const saveAs = !IS_CLIENT ? () => {} : typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : "msSaveOrOpenBlob" in _navigator ? msSaveAs : fileSaverSaveAs;
  96. function downloadSaveAs(blob, name = "download", opts) {
  97. const a = document.createElement("a");
  98. a.download = name;
  99. a.rel = "noopener";
  100. if (typeof blob === "string") {
  101. a.href = blob;
  102. if (a.origin !== location.origin) if (corsEnabled(a.href)) download(blob, name, opts);
  103. else {
  104. a.target = "_blank";
  105. click(a);
  106. }
  107. else click(a);
  108. } else {
  109. a.href = URL.createObjectURL(blob);
  110. setTimeout(function() {
  111. URL.revokeObjectURL(a.href);
  112. }, 4e4);
  113. setTimeout(function() {
  114. click(a);
  115. }, 0);
  116. }
  117. }
  118. function msSaveAs(blob, name = "download", opts) {
  119. if (typeof blob === "string") if (corsEnabled(blob)) download(blob, name, opts);
  120. else {
  121. const a = document.createElement("a");
  122. a.href = blob;
  123. a.target = "_blank";
  124. setTimeout(function() {
  125. click(a);
  126. });
  127. }
  128. else navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  129. }
  130. function fileSaverSaveAs(blob, name, opts, popup) {
  131. popup = popup || open("", "_blank");
  132. if (popup) popup.document.title = popup.document.body.innerText = "downloading...";
  133. if (typeof blob === "string") return download(blob, name, opts);
  134. const force = blob.type === "application/octet-stream";
  135. const isSafari = /constructor/i.test(String(_global$1.HTMLElement)) || "safari" in _global$1;
  136. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  137. if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") {
  138. const reader = new FileReader();
  139. reader.onloadend = function() {
  140. let url = reader.result;
  141. if (typeof url !== "string") {
  142. popup = null;
  143. throw new Error("Wrong reader.result type");
  144. }
  145. url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
  146. if (popup) popup.location.href = url;
  147. else location.assign(url);
  148. popup = null;
  149. };
  150. reader.readAsDataURL(blob);
  151. } else {
  152. const url = URL.createObjectURL(blob);
  153. if (popup) popup.location.assign(url);
  154. else location.href = url;
  155. popup = null;
  156. setTimeout(function() {
  157. URL.revokeObjectURL(url);
  158. }, 4e4);
  159. }
  160. }
  161. const { assign: assign$1 } = Object;
  162. /**
  163. * Creates a Pinia instance to be used by the application
  164. */
  165. function createPinia() {
  166. const scope = effectScope(true);
  167. const state = scope.run(() => ref({}));
  168. let _p = [];
  169. let toBeInstalled = [];
  170. const pinia = markRaw({
  171. install(app) {
  172. setActivePinia(pinia);
  173. pinia._a = app;
  174. app.provide(piniaSymbol, pinia);
  175. app.config.globalProperties.$pinia = pinia;
  176. toBeInstalled.forEach((plugin) => _p.push(plugin));
  177. toBeInstalled = [];
  178. },
  179. use(plugin) {
  180. if (!this._a) toBeInstalled.push(plugin);
  181. else _p.push(plugin);
  182. return this;
  183. },
  184. _p,
  185. _a: null,
  186. _e: scope,
  187. _s: new Map(),
  188. state
  189. });
  190. return pinia;
  191. }
  192. const noop$1 = () => {};
  193. function addSubscription(subscriptions, callback, detached, onCleanup = noop$1) {
  194. subscriptions.push(callback);
  195. const removeSubscription = () => {
  196. const idx = subscriptions.indexOf(callback);
  197. if (idx > -1) {
  198. subscriptions.splice(idx, 1);
  199. onCleanup();
  200. }
  201. };
  202. if (!detached && getCurrentScope()) onScopeDispose(removeSubscription);
  203. return removeSubscription;
  204. }
  205. function triggerSubscriptions(subscriptions, ...args) {
  206. subscriptions.slice().forEach((callback) => {
  207. callback(...args);
  208. });
  209. }
  210. const fallbackRunWithContext = (fn) => fn();
  211. /**
  212. * Marks a function as an action for `$onAction`
  213. * @internal
  214. */
  215. const ACTION_MARKER = Symbol();
  216. /**
  217. * Action name symbol. Allows to add a name to an action after defining it
  218. * @internal
  219. */
  220. const ACTION_NAME = Symbol();
  221. function mergeReactiveObjects(target, patchToApply) {
  222. if (target instanceof Map && patchToApply instanceof Map) patchToApply.forEach((value, key) => target.set(key, value));
  223. else if (target instanceof Set && patchToApply instanceof Set) patchToApply.forEach(target.add, target);
  224. for (const key in patchToApply) {
  225. if (!patchToApply.hasOwnProperty(key)) continue;
  226. const subPatch = patchToApply[key];
  227. const targetValue = target[key];
  228. if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) target[key] = mergeReactiveObjects(targetValue, subPatch);
  229. else target[key] = subPatch;
  230. }
  231. return target;
  232. }
  233. const skipHydrateSymbol = Symbol();
  234. /**
  235. * Returns whether a value should be hydrated
  236. *
  237. * @param obj - target variable
  238. * @returns true if `obj` should be hydrated
  239. */
  240. function shouldHydrate(obj) {
  241. return !isPlainObject(obj) || !Object.prototype.hasOwnProperty.call(obj, skipHydrateSymbol);
  242. }
  243. const { assign } = Object;
  244. function isComputed(o) {
  245. return !!(isRef(o) && o.effect);
  246. }
  247. function createOptionsStore(id, options, pinia, hot$1) {
  248. const { state, actions, getters } = options;
  249. const initialState = pinia.state.value[id];
  250. let store;
  251. function setup() {
  252. if (!initialState && true) pinia.state.value[id] = state ? state() : {};
  253. const localState = toRefs(pinia.state.value[id]);
  254. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  255. computedGetters[name] = markRaw(computed(() => {
  256. setActivePinia(pinia);
  257. const store$1 = pinia._s.get(id);
  258. return getters[name].call(store$1, store$1);
  259. }));
  260. return computedGetters;
  261. }, {}));
  262. }
  263. store = createSetupStore(id, setup, options, pinia, hot$1, true);
  264. return store;
  265. }
  266. function createSetupStore($id, setup, options = {}, pinia, hot$1, isOptionsStore) {
  267. let scope;
  268. const optionsForPlugin = assign({ actions: {} }, options);
  269. const $subscribeOptions = { deep: true };
  270. let isListening;
  271. let isSyncListening;
  272. let subscriptions = [];
  273. let actionSubscriptions = [];
  274. let debuggerEvents;
  275. const initialState = pinia.state.value[$id];
  276. if (!isOptionsStore && !initialState && true) pinia.state.value[$id] = {};
  277. const hotState = ref({});
  278. let activeListener;
  279. function $patch(partialStateOrMutator) {
  280. let subscriptionMutation;
  281. isListening = isSyncListening = false;
  282. if (typeof partialStateOrMutator === "function") {
  283. partialStateOrMutator(pinia.state.value[$id]);
  284. subscriptionMutation = {
  285. type: MutationType.patchFunction,
  286. storeId: $id,
  287. events: debuggerEvents
  288. };
  289. } else {
  290. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  291. subscriptionMutation = {
  292. type: MutationType.patchObject,
  293. payload: partialStateOrMutator,
  294. storeId: $id,
  295. events: debuggerEvents
  296. };
  297. }
  298. const myListenerId = activeListener = Symbol();
  299. nextTick().then(() => {
  300. if (activeListener === myListenerId) isListening = true;
  301. });
  302. isSyncListening = true;
  303. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  304. }
  305. const $reset = isOptionsStore ? function $reset$1() {
  306. const { state } = options;
  307. const newState = state ? state() : {};
  308. this.$patch(($state) => {
  309. assign($state, newState);
  310. });
  311. } : noop$1;
  312. function $dispose() {
  313. scope.stop();
  314. subscriptions = [];
  315. actionSubscriptions = [];
  316. pinia._s.delete($id);
  317. }
  318. /**
  319. * Helper that wraps function so it can be tracked with $onAction
  320. * @param fn - action to wrap
  321. * @param name - name of the action
  322. */
  323. const action = (fn, name = "") => {
  324. if (ACTION_MARKER in fn) {
  325. fn[ACTION_NAME] = name;
  326. return fn;
  327. }
  328. const wrappedAction = function() {
  329. setActivePinia(pinia);
  330. const args = Array.from(arguments);
  331. const afterCallbackList = [];
  332. const onErrorCallbackList = [];
  333. function after(callback) {
  334. afterCallbackList.push(callback);
  335. }
  336. function onError(callback) {
  337. onErrorCallbackList.push(callback);
  338. }
  339. triggerSubscriptions(actionSubscriptions, {
  340. args,
  341. name: wrappedAction[ACTION_NAME],
  342. store,
  343. after,
  344. onError
  345. });
  346. let ret;
  347. try {
  348. ret = fn.apply(this && this.$id === $id ? this : store, args);
  349. } catch (error) {
  350. triggerSubscriptions(onErrorCallbackList, error);
  351. throw error;
  352. }
  353. if (ret instanceof Promise) return ret.then((value) => {
  354. triggerSubscriptions(afterCallbackList, value);
  355. return value;
  356. }).catch((error) => {
  357. triggerSubscriptions(onErrorCallbackList, error);
  358. return Promise.reject(error);
  359. });
  360. triggerSubscriptions(afterCallbackList, ret);
  361. return ret;
  362. };
  363. wrappedAction[ACTION_MARKER] = true;
  364. wrappedAction[ACTION_NAME] = name;
  365. return wrappedAction;
  366. };
  367. const _hmrPayload = /* @__PURE__ */ markRaw({
  368. actions: {},
  369. getters: {},
  370. state: [],
  371. hotState
  372. });
  373. const partialStore = {
  374. _p: pinia,
  375. $id,
  376. $onAction: addSubscription.bind(null, actionSubscriptions),
  377. $patch,
  378. $reset,
  379. $subscribe(callback, options$1 = {}) {
  380. const removeSubscription = addSubscription(subscriptions, callback, options$1.detached, () => stopWatcher());
  381. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  382. if (options$1.flush === "sync" ? isSyncListening : isListening) callback({
  383. storeId: $id,
  384. type: MutationType.direct,
  385. events: debuggerEvents
  386. }, state);
  387. }, assign({}, $subscribeOptions, options$1)));
  388. return removeSubscription;
  389. },
  390. $dispose
  391. };
  392. const store = reactive(partialStore);
  393. pinia._s.set($id, store);
  394. const runWithContext = pinia._a && pinia._a.runWithContext || fallbackRunWithContext;
  395. const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
  396. for (const key in setupStore) {
  397. const prop = setupStore[key];
  398. if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
  399. if (!isOptionsStore) {
  400. if (initialState && shouldHydrate(prop)) if (isRef(prop)) prop.value = initialState[key];
  401. else mergeReactiveObjects(prop, initialState[key]);
  402. pinia.state.value[$id][key] = prop;
  403. }
  404. } else if (typeof prop === "function") {
  405. const actionValue = action(prop, key);
  406. setupStore[key] = actionValue;
  407. optionsForPlugin.actions[key] = prop;
  408. }
  409. }
  410. assign(store, setupStore);
  411. assign(toRaw(store), setupStore);
  412. Object.defineProperty(store, "$state", {
  413. get: () => pinia.state.value[$id],
  414. set: (state) => {
  415. $patch(($state) => {
  416. assign($state, state);
  417. });
  418. }
  419. });
  420. pinia._p.forEach((extender) => {
  421. assign(store, scope.run(() => extender({
  422. store,
  423. app: pinia._a,
  424. pinia,
  425. options: optionsForPlugin
  426. })));
  427. });
  428. if (initialState && isOptionsStore && options.hydrate) options.hydrate(store.$state, initialState);
  429. isListening = true;
  430. isSyncListening = true;
  431. return store;
  432. }
  433. /*! #__NO_SIDE_EFFECTS__ */
  434. function defineStore(id, setup, setupOptions) {
  435. let options;
  436. const isSetupStore = typeof setup === "function";
  437. options = isSetupStore ? setupOptions : setup;
  438. function useStore(pinia, hot$1) {
  439. const hasContext = hasInjectionContext();
  440. pinia = pinia || (hasContext ? inject(piniaSymbol, null) : null);
  441. if (pinia) setActivePinia(pinia);
  442. pinia = activePinia;
  443. if (!pinia._s.has(id)) if (isSetupStore) createSetupStore(id, setup, options, pinia);
  444. else createOptionsStore(id, options, pinia);
  445. const store = pinia._s.get(id);
  446. return store;
  447. }
  448. useStore.$id = id;
  449. return useStore;
  450. }
  451. const scriptRel = "modulepreload";
  452. const assetsURL = function(dep, importerUrl) {
  453. return new URL(dep, importerUrl).href;
  454. };
  455. const seen = {};
  456. const __vitePreload = function preload(baseModule, deps, importerUrl) {
  457. let promise = Promise.resolve();
  458. if (deps && deps.length > 0) {
  459. const links = document.getElementsByTagName("link");
  460. const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
  461. const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
  462. promise = Promise.allSettled(deps.map((dep) => {
  463. dep = assetsURL(dep, importerUrl);
  464. if (dep in seen) return;
  465. seen[dep] = true;
  466. const isCss = dep.endsWith(".css");
  467. const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
  468. const isBaseRelative = !!importerUrl;
  469. if (isBaseRelative) for (let i = links.length - 1; i >= 0; i--) {
  470. const link2 = links[i];
  471. if (link2.href === dep && (!isCss || link2.rel === "stylesheet")) return;
  472. }
  473. else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
  474. const link = document.createElement("link");
  475. link.rel = isCss ? "stylesheet" : scriptRel;
  476. if (!isCss) link.as = "script";
  477. link.crossOrigin = "";
  478. link.href = dep;
  479. if (cspNonce) link.setAttribute("nonce", cspNonce);
  480. document.head.appendChild(link);
  481. if (isCss) return new Promise((res, rej) => {
  482. link.addEventListener("load", res);
  483. link.addEventListener("error", () => rej(new Error(`Unable to preload CSS for ${dep}`)));
  484. });
  485. }));
  486. }
  487. function handlePreloadError(err) {
  488. const e = new Event("vite:preloadError", { cancelable: true });
  489. e.payload = err;
  490. window.dispatchEvent(e);
  491. if (!e.defaultPrevented) throw err;
  492. }
  493. return promise.then((res) => {
  494. for (const item of res || []) {
  495. if (item.status !== "rejected") continue;
  496. handlePreloadError(item.reason);
  497. }
  498. return baseModule().catch(handlePreloadError);
  499. });
  500. };
  501. function tryOnScopeDispose(fn) {
  502. if (getCurrentScope()) {
  503. onScopeDispose(fn);
  504. return true;
  505. }
  506. return false;
  507. }
  508. /* @__NO_SIDE_EFFECTS__ */
  509. function createEventHook() {
  510. const fns = /* @__PURE__ */ new Set();
  511. const off = (fn) => {
  512. fns.delete(fn);
  513. };
  514. const clear = () => {
  515. fns.clear();
  516. };
  517. const on = (fn) => {
  518. fns.add(fn);
  519. const offFn = () => off(fn);
  520. tryOnScopeDispose(offFn);
  521. return { off: offFn };
  522. };
  523. const trigger = (...args) => {
  524. return Promise.all(Array.from(fns).map((fn) => fn(...args)));
  525. };
  526. return {
  527. on,
  528. off,
  529. trigger,
  530. clear
  531. };
  532. }
  533. const localProvidedStateMap = /* @__PURE__ */ new WeakMap();
  534. const injectLocal = /* @__NO_SIDE_EFFECTS__ */ (...args) => {
  535. var _a;
  536. const key = args[0];
  537. const instance = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
  538. if (instance == null && !hasInjectionContext()) throw new Error("injectLocal must be called in setup");
  539. if (instance && localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance)) return localProvidedStateMap.get(instance)[key];
  540. return inject(...args);
  541. };
  542. const isClient = typeof window !== "undefined" && typeof document !== "undefined";
  543. const isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
  544. const toString = Object.prototype.toString;
  545. const isObject = (val) => toString.call(val) === "[object Object]";
  546. const noop = () => {};
  547. function toRef$1(...args) {
  548. if (args.length !== 1) return toRef(...args);
  549. const r = args[0];
  550. return typeof r === "function" ? readonly(customRef(() => ({
  551. get: r,
  552. set: noop
  553. }))) : ref(r);
  554. }
  555. function createFilterWrapper(filter, fn) {
  556. function wrapper(...args) {
  557. return new Promise((resolve, reject) => {
  558. Promise.resolve(filter(() => fn.apply(this, args), {
  559. fn,
  560. thisArg: this,
  561. args
  562. })).then(resolve).catch(reject);
  563. });
  564. }
  565. return wrapper;
  566. }
  567. const bypassFilter = (invoke) => {
  568. return invoke();
  569. };
  570. function pausableFilter(extendFilter = bypassFilter, options = {}) {
  571. const { initialState = "active" } = options;
  572. const isActive = toRef$1(initialState === "active");
  573. function pause() {
  574. isActive.value = false;
  575. }
  576. function resume() {
  577. isActive.value = true;
  578. }
  579. const eventFilter = (...args) => {
  580. if (isActive.value) extendFilter(...args);
  581. };
  582. return {
  583. isActive: readonly(isActive),
  584. pause,
  585. resume,
  586. eventFilter
  587. };
  588. }
  589. function pxValue(px) {
  590. return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px);
  591. }
  592. function toArray(value) {
  593. return Array.isArray(value) ? value : [value];
  594. }
  595. function cacheStringFunction(fn) {
  596. const cache = /* @__PURE__ */ Object.create(null);
  597. return (str) => {
  598. const hit = cache[str];
  599. return hit || (cache[str] = fn(str));
  600. };
  601. }
  602. const hyphenateRE = /\B([A-Z])/g;
  603. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
  604. const camelizeRE = /-(\w)/g;
  605. const camelize = cacheStringFunction((str) => {
  606. return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
  607. });
  608. function getLifeCycleTarget(target) {
  609. return target || getCurrentInstance();
  610. }
  611. function watchWithFilter(source, cb, options = {}) {
  612. const { eventFilter = bypassFilter,...watchOptions } = options;
  613. return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
  614. }
  615. function watchPausable(source, cb, options = {}) {
  616. const { eventFilter: filter, initialState = "active",...watchOptions } = options;
  617. const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState });
  618. const stop = watchWithFilter(source, cb, {
  619. ...watchOptions,
  620. eventFilter
  621. });
  622. return {
  623. stop,
  624. pause,
  625. resume,
  626. isActive
  627. };
  628. }
  629. function tryOnMounted(fn, sync = true, target) {
  630. const instance = getLifeCycleTarget(target);
  631. if (instance) onMounted(fn, target);
  632. else if (sync) fn();
  633. else nextTick(fn);
  634. }
  635. /* @__NO_SIDE_EFFECTS__ */
  636. function useToggle(initialValue = false, options = {}) {
  637. const { truthyValue = true, falsyValue = false } = options;
  638. const valueIsRef = isRef(initialValue);
  639. const _value = shallowRef(initialValue);
  640. function toggle(value) {
  641. if (arguments.length) {
  642. _value.value = value;
  643. return _value.value;
  644. } else {
  645. const truthy = toValue(truthyValue);
  646. _value.value = _value.value === truthy ? toValue(falsyValue) : truthy;
  647. return _value.value;
  648. }
  649. }
  650. if (valueIsRef) return toggle;
  651. else return [_value, toggle];
  652. }
  653. function watchImmediate(source, cb, options) {
  654. return watch(source, cb, {
  655. ...options,
  656. immediate: true
  657. });
  658. }
  659. const defaultWindow = isClient ? window : void 0;
  660. const defaultDocument = isClient ? window.document : void 0;
  661. const defaultNavigator = isClient ? window.navigator : void 0;
  662. const defaultLocation = isClient ? window.location : void 0;
  663. function unrefElement(elRef) {
  664. var _a;
  665. const plain = toValue(elRef);
  666. return (_a = plain == null ? void 0 : plain.$el) != null ? _a : plain;
  667. }
  668. function useEventListener(...args) {
  669. const cleanups = [];
  670. const cleanup = () => {
  671. cleanups.forEach((fn) => fn());
  672. cleanups.length = 0;
  673. };
  674. const register = (el, event, listener, options) => {
  675. el.addEventListener(event, listener, options);
  676. return () => el.removeEventListener(event, listener, options);
  677. };
  678. const firstParamTargets = computed(() => {
  679. const test = toArray(toValue(args[0])).filter((e) => e != null);
  680. return test.every((e) => typeof e !== "string") ? test : void 0;
  681. });
  682. const stopWatch = watchImmediate(() => {
  683. var _a, _b;
  684. return [
  685. (_b = (_a = firstParamTargets.value) == null ? void 0 : _a.map((e) => unrefElement(e))) != null ? _b : [defaultWindow].filter((e) => e != null),
  686. toArray(toValue(firstParamTargets.value ? args[1] : args[0])),
  687. toArray(unref(firstParamTargets.value ? args[2] : args[1])),
  688. toValue(firstParamTargets.value ? args[3] : args[2])
  689. ];
  690. }, ([raw_targets, raw_events, raw_listeners, raw_options]) => {
  691. cleanup();
  692. if (!(raw_targets == null ? void 0 : raw_targets.length) || !(raw_events == null ? void 0 : raw_events.length) || !(raw_listeners == null ? void 0 : raw_listeners.length)) return;
  693. const optionsClone = isObject(raw_options) ? { ...raw_options } : raw_options;
  694. cleanups.push(...raw_targets.flatMap((el) => raw_events.flatMap((event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone)))));
  695. }, { flush: "post" });
  696. const stop = () => {
  697. stopWatch();
  698. cleanup();
  699. };
  700. tryOnScopeDispose(cleanup);
  701. return stop;
  702. }
  703. /* @__NO_SIDE_EFFECTS__ */
  704. function useMounted() {
  705. const isMounted = shallowRef(false);
  706. const instance = getCurrentInstance();
  707. if (instance) onMounted(() => {
  708. isMounted.value = true;
  709. }, instance);
  710. return isMounted;
  711. }
  712. /* @__NO_SIDE_EFFECTS__ */
  713. function useSupported(callback) {
  714. const isMounted = /* @__PURE__ */ useMounted();
  715. return computed(() => {
  716. isMounted.value;
  717. return Boolean(callback());
  718. });
  719. }
  720. const ssrWidthSymbol = Symbol("vueuse-ssr-width");
  721. /* @__NO_SIDE_EFFECTS__ */
  722. function useSSRWidth() {
  723. const ssrWidth = hasInjectionContext() ? /* @__PURE__ */ injectLocal(ssrWidthSymbol, null) : null;
  724. return typeof ssrWidth === "number" ? ssrWidth : void 0;
  725. }
  726. function useMediaQuery(query, options = {}) {
  727. const { window: window$1 = defaultWindow, ssrWidth = /* @__PURE__ */ useSSRWidth() } = options;
  728. const isSupported = /* @__PURE__ */ useSupported(() => window$1 && "matchMedia" in window$1 && typeof window$1.matchMedia === "function");
  729. const ssrSupport = shallowRef(typeof ssrWidth === "number");
  730. const mediaQuery = shallowRef();
  731. const matches = shallowRef(false);
  732. const handler = (event) => {
  733. matches.value = event.matches;
  734. };
  735. watchEffect(() => {
  736. if (ssrSupport.value) {
  737. ssrSupport.value = !isSupported.value;
  738. const queryStrings = toValue(query).split(",");
  739. matches.value = queryStrings.some((queryString) => {
  740. const not = queryString.includes("not all");
  741. const minWidth = queryString.match(/\(\s*min-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
  742. const maxWidth = queryString.match(/\(\s*max-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
  743. let res = Boolean(minWidth || maxWidth);
  744. if (minWidth && res) res = ssrWidth >= pxValue(minWidth[1]);
  745. if (maxWidth && res) res = ssrWidth <= pxValue(maxWidth[1]);
  746. return not ? !res : res;
  747. });
  748. return;
  749. }
  750. if (!isSupported.value) return;
  751. mediaQuery.value = window$1.matchMedia(toValue(query));
  752. matches.value = mediaQuery.value.matches;
  753. });
  754. useEventListener(mediaQuery, "change", handler, { passive: true });
  755. return computed(() => matches.value);
  756. }
  757. const _global = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  758. const globalKey = "__vueuse_ssr_handlers__";
  759. const handlers = /* @__PURE__ */ getHandlers();
  760. function getHandlers() {
  761. if (!(globalKey in _global)) _global[globalKey] = _global[globalKey] || {};
  762. return _global[globalKey];
  763. }
  764. function getSSRHandler(key, fallback) {
  765. return handlers[key] || fallback;
  766. }
  767. /* @__NO_SIDE_EFFECTS__ */
  768. function usePreferredDark(options) {
  769. return useMediaQuery("(prefers-color-scheme: dark)", options);
  770. }
  771. function guessSerializerType(rawInit) {
  772. return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any";
  773. }
  774. const StorageSerializers = {
  775. boolean: {
  776. read: (v) => v === "true",
  777. write: (v) => String(v)
  778. },
  779. object: {
  780. read: (v) => JSON.parse(v),
  781. write: (v) => JSON.stringify(v)
  782. },
  783. number: {
  784. read: (v) => Number.parseFloat(v),
  785. write: (v) => String(v)
  786. },
  787. any: {
  788. read: (v) => v,
  789. write: (v) => String(v)
  790. },
  791. string: {
  792. read: (v) => v,
  793. write: (v) => String(v)
  794. },
  795. map: {
  796. read: (v) => new Map(JSON.parse(v)),
  797. write: (v) => JSON.stringify(Array.from(v.entries()))
  798. },
  799. set: {
  800. read: (v) => new Set(JSON.parse(v)),
  801. write: (v) => JSON.stringify(Array.from(v))
  802. },
  803. date: {
  804. read: (v) => new Date(v),
  805. write: (v) => v.toISOString()
  806. }
  807. };
  808. const customStorageEventName = "vueuse-storage";
  809. function useStorage(key, defaults, storage, options = {}) {
  810. var _a;
  811. const { flush = "pre", deep = true, listenToStorageChanges = true, writeDefaults = true, mergeDefaults = false, shallow, window: window$1 = defaultWindow, eventFilter, onError = (e) => {
  812. console.error(e);
  813. }, initOnMounted } = options;
  814. const data = (shallow ? shallowRef : ref)(typeof defaults === "function" ? defaults() : defaults);
  815. const keyComputed = computed(() => toValue(key));
  816. if (!storage) try {
  817. storage = getSSRHandler("getDefaultStorage", () => {
  818. var _a2;
  819. return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage;
  820. })();
  821. } catch (e) {
  822. onError(e);
  823. }
  824. if (!storage) return data;
  825. const rawInit = toValue(defaults);
  826. const type = guessSerializerType(rawInit);
  827. const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type];
  828. const { pause: pauseWatch, resume: resumeWatch } = watchPausable(data, (newValue) => write(newValue), {
  829. flush,
  830. deep,
  831. eventFilter
  832. });
  833. watch(keyComputed, () => update(), { flush });
  834. let firstMounted = false;
  835. const onStorageEvent = (ev) => {
  836. if (initOnMounted && !firstMounted) return;
  837. update(ev);
  838. };
  839. const onStorageCustomEvent = (ev) => {
  840. if (initOnMounted && !firstMounted) return;
  841. updateFromCustomEvent(ev);
  842. };
  843. if (window$1 && listenToStorageChanges) if (storage instanceof Storage) useEventListener(window$1, "storage", onStorageEvent, { passive: true });
  844. else useEventListener(window$1, customStorageEventName, onStorageCustomEvent);
  845. if (initOnMounted) tryOnMounted(() => {
  846. firstMounted = true;
  847. update();
  848. });
  849. else update();
  850. function dispatchWriteEvent(oldValue, newValue) {
  851. if (window$1) {
  852. const payload = {
  853. key: keyComputed.value,
  854. oldValue,
  855. newValue,
  856. storageArea: storage
  857. };
  858. window$1.dispatchEvent(storage instanceof Storage ? new StorageEvent("storage", payload) : new CustomEvent(customStorageEventName, { detail: payload }));
  859. }
  860. }
  861. function write(v) {
  862. try {
  863. const oldValue = storage.getItem(keyComputed.value);
  864. if (v == null) {
  865. dispatchWriteEvent(oldValue, null);
  866. storage.removeItem(keyComputed.value);
  867. } else {
  868. const serialized = serializer.write(v);
  869. if (oldValue !== serialized) {
  870. storage.setItem(keyComputed.value, serialized);
  871. dispatchWriteEvent(oldValue, serialized);
  872. }
  873. }
  874. } catch (e) {
  875. onError(e);
  876. }
  877. }
  878. function read(event) {
  879. const rawValue = event ? event.newValue : storage.getItem(keyComputed.value);
  880. if (rawValue == null) {
  881. if (writeDefaults && rawInit != null) storage.setItem(keyComputed.value, serializer.write(rawInit));
  882. return rawInit;
  883. } else if (!event && mergeDefaults) {
  884. const value = serializer.read(rawValue);
  885. if (typeof mergeDefaults === "function") return mergeDefaults(value, rawInit);
  886. else if (type === "object" && !Array.isArray(value)) return {
  887. ...rawInit,
  888. ...value
  889. };
  890. return value;
  891. } else if (typeof rawValue !== "string") return rawValue;
  892. else return serializer.read(rawValue);
  893. }
  894. function update(event) {
  895. if (event && event.storageArea !== storage) return;
  896. if (event && event.key == null) {
  897. data.value = rawInit;
  898. return;
  899. }
  900. if (event && event.key !== keyComputed.value) return;
  901. pauseWatch();
  902. try {
  903. const serializedData = serializer.write(data.value);
  904. if (event === void 0 || (event == null ? void 0 : event.newValue) !== serializedData) data.value = read(event);
  905. } catch (e) {
  906. onError(e);
  907. } finally {
  908. if (event) nextTick(resumeWatch);
  909. else resumeWatch();
  910. }
  911. }
  912. function updateFromCustomEvent(event) {
  913. update(event.detail);
  914. }
  915. return data;
  916. }
  917. const CSS_DISABLE_TRANS = "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}";
  918. function useColorMode(options = {}) {
  919. const { selector = "html", attribute = "class", initialValue = "auto", window: window$1 = defaultWindow, storage, storageKey = "vueuse-color-scheme", listenToStorageChanges = true, storageRef, emitAuto, disableTransition = true } = options;
  920. const modes = {
  921. auto: "",
  922. light: "light",
  923. dark: "dark",
  924. ...options.modes || {}
  925. };
  926. const preferredDark = /* @__PURE__ */ usePreferredDark({ window: window$1 });
  927. const system = computed(() => preferredDark.value ? "dark" : "light");
  928. const store = storageRef || (storageKey == null ? toRef$1(initialValue) : useStorage(storageKey, initialValue, storage, {
  929. window: window$1,
  930. listenToStorageChanges
  931. }));
  932. const state = computed(() => store.value === "auto" ? system.value : store.value);
  933. const updateHTMLAttrs = getSSRHandler("updateHTMLAttrs", (selector2, attribute2, value) => {
  934. const el = typeof selector2 === "string" ? window$1 == null ? void 0 : window$1.document.querySelector(selector2) : unrefElement(selector2);
  935. if (!el) return;
  936. const classesToAdd = /* @__PURE__ */ new Set();
  937. const classesToRemove = /* @__PURE__ */ new Set();
  938. let attributeToChange = null;
  939. if (attribute2 === "class") {
  940. const current = value.split(/\s/g);
  941. Object.values(modes).flatMap((i) => (i || "").split(/\s/g)).filter(Boolean).forEach((v) => {
  942. if (current.includes(v)) classesToAdd.add(v);
  943. else classesToRemove.add(v);
  944. });
  945. } else attributeToChange = {
  946. key: attribute2,
  947. value
  948. };
  949. if (classesToAdd.size === 0 && classesToRemove.size === 0 && attributeToChange === null) return;
  950. let style;
  951. if (disableTransition) {
  952. style = window$1.document.createElement("style");
  953. style.appendChild(document.createTextNode(CSS_DISABLE_TRANS));
  954. window$1.document.head.appendChild(style);
  955. }
  956. for (const c of classesToAdd) el.classList.add(c);
  957. for (const c of classesToRemove) el.classList.remove(c);
  958. if (attributeToChange) el.setAttribute(attributeToChange.key, attributeToChange.value);
  959. if (disableTransition) {
  960. window$1.getComputedStyle(style).opacity;
  961. document.head.removeChild(style);
  962. }
  963. });
  964. function defaultOnChanged(mode) {
  965. var _a;
  966. updateHTMLAttrs(selector, attribute, (_a = modes[mode]) != null ? _a : mode);
  967. }
  968. function onChanged(mode) {
  969. if (options.onChanged) options.onChanged(mode, defaultOnChanged);
  970. else defaultOnChanged(mode);
  971. }
  972. watch(state, onChanged, {
  973. flush: "post",
  974. immediate: true
  975. });
  976. tryOnMounted(() => onChanged(state.value));
  977. const auto = computed({
  978. get() {
  979. return emitAuto ? store.value : state.value;
  980. },
  981. set(v) {
  982. store.value = v;
  983. }
  984. });
  985. return Object.assign(auto, {
  986. store,
  987. system,
  988. state
  989. });
  990. }
  991. function useDark(options = {}) {
  992. const { valueDark = "dark", valueLight = "" } = options;
  993. const mode = useColorMode({
  994. ...options,
  995. onChanged: (mode2, defaultHandler) => {
  996. var _a;
  997. if (options.onChanged) (_a = options.onChanged) == null || _a.call(options, mode2 === "dark", defaultHandler, mode2);
  998. else defaultHandler(mode2);
  999. },
  1000. modes: {
  1001. dark: valueDark,
  1002. light: valueLight
  1003. }
  1004. });
  1005. const system = computed(() => mode.system.value);
  1006. const isDark$1 = computed({
  1007. get() {
  1008. return mode.value === "dark";
  1009. },
  1010. set(v) {
  1011. const modeVal = v ? "dark" : "light";
  1012. if (system.value === modeVal) mode.value = "auto";
  1013. else mode.value = modeVal;
  1014. }
  1015. });
  1016. return isDark$1;
  1017. }
  1018. function useResizeObserver(target, callback, options = {}) {
  1019. const { window: window$1 = defaultWindow,...observerOptions } = options;
  1020. let observer;
  1021. const isSupported = /* @__PURE__ */ useSupported(() => window$1 && "ResizeObserver" in window$1);
  1022. const cleanup = () => {
  1023. if (observer) {
  1024. observer.disconnect();
  1025. observer = void 0;
  1026. }
  1027. };
  1028. const targets = computed(() => {
  1029. const _targets = toValue(target);
  1030. return Array.isArray(_targets) ? _targets.map((el) => unrefElement(el)) : [unrefElement(_targets)];
  1031. });
  1032. const stopWatch = watch(targets, (els) => {
  1033. cleanup();
  1034. if (isSupported.value && window$1) {
  1035. observer = new ResizeObserver(callback);
  1036. for (const _el of els) if (_el) observer.observe(_el, observerOptions);
  1037. }
  1038. }, {
  1039. immediate: true,
  1040. flush: "post"
  1041. });
  1042. const stop = () => {
  1043. cleanup();
  1044. stopWatch();
  1045. };
  1046. tryOnScopeDispose(stop);
  1047. return {
  1048. isSupported,
  1049. stop
  1050. };
  1051. }
  1052. function useElementSize(target, initialSize = {
  1053. width: 0,
  1054. height: 0
  1055. }, options = {}) {
  1056. const { window: window$1 = defaultWindow, box = "content-box" } = options;
  1057. const isSVG = computed(() => {
  1058. var _a, _b;
  1059. return (_b = (_a = unrefElement(target)) == null ? void 0 : _a.namespaceURI) == null ? void 0 : _b.includes("svg");
  1060. });
  1061. const width = shallowRef(initialSize.width);
  1062. const height = shallowRef(initialSize.height);
  1063. const { stop: stop1 } = useResizeObserver(target, ([entry]) => {
  1064. const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;
  1065. if (window$1 && isSVG.value) {
  1066. const $elem = unrefElement(target);
  1067. if ($elem) {
  1068. const rect = $elem.getBoundingClientRect();
  1069. width.value = rect.width;
  1070. height.value = rect.height;
  1071. }
  1072. } else if (boxSize) {
  1073. const formatBoxSize = toArray(boxSize);
  1074. width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);
  1075. height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);
  1076. } else {
  1077. width.value = entry.contentRect.width;
  1078. height.value = entry.contentRect.height;
  1079. }
  1080. }, options);
  1081. tryOnMounted(() => {
  1082. const ele = unrefElement(target);
  1083. if (ele) {
  1084. width.value = "offsetWidth" in ele ? ele.offsetWidth : initialSize.width;
  1085. height.value = "offsetHeight" in ele ? ele.offsetHeight : initialSize.height;
  1086. }
  1087. });
  1088. const stop2 = watch(() => unrefElement(target), (ele) => {
  1089. width.value = ele ? initialSize.width : 0;
  1090. height.value = ele ? initialSize.height : 0;
  1091. });
  1092. function stop() {
  1093. stop1();
  1094. stop2();
  1095. }
  1096. return {
  1097. width,
  1098. height,
  1099. stop
  1100. };
  1101. }
  1102. function useLocalStorage(key, initialValue, options = {}) {
  1103. const { window: window$1 = defaultWindow } = options;
  1104. return useStorage(key, initialValue, window$1 == null ? void 0 : window$1.localStorage, options);
  1105. }
  1106. const DEFAULT_UNITS = [
  1107. {
  1108. max: 6e4,
  1109. value: 1e3,
  1110. name: "second"
  1111. },
  1112. {
  1113. max: 276e4,
  1114. value: 6e4,
  1115. name: "minute"
  1116. },
  1117. {
  1118. max: 72e6,
  1119. value: 36e5,
  1120. name: "hour"
  1121. },
  1122. {
  1123. max: 5184e5,
  1124. value: 864e5,
  1125. name: "day"
  1126. },
  1127. {
  1128. max: 24192e5,
  1129. value: 6048e5,
  1130. name: "week"
  1131. },
  1132. {
  1133. max: 28512e6,
  1134. value: 2592e6,
  1135. name: "month"
  1136. },
  1137. {
  1138. max: Number.POSITIVE_INFINITY,
  1139. value: 31536e6,
  1140. name: "year"
  1141. }
  1142. ];
  1143. function useVirtualList(list, options) {
  1144. const { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = "itemHeight" in options ? useVerticalVirtualList(options, list) : useHorizontalVirtualList(options, list);
  1145. return {
  1146. list: currentList,
  1147. scrollTo,
  1148. containerProps: {
  1149. ref: containerRef,
  1150. onScroll: () => {
  1151. calculateRange();
  1152. },
  1153. style: containerStyle
  1154. },
  1155. wrapperProps
  1156. };
  1157. }
  1158. function useVirtualListResources(list) {
  1159. const containerRef = shallowRef(null);
  1160. const size = useElementSize(containerRef);
  1161. const currentList = ref([]);
  1162. const source = shallowRef(list);
  1163. const state = ref({
  1164. start: 0,
  1165. end: 10
  1166. });
  1167. return {
  1168. state,
  1169. source,
  1170. currentList,
  1171. size,
  1172. containerRef
  1173. };
  1174. }
  1175. function createGetViewCapacity(state, source, itemSize) {
  1176. return (containerSize) => {
  1177. if (typeof itemSize === "number") return Math.ceil(containerSize / itemSize);
  1178. const { start = 0 } = state.value;
  1179. let sum = 0;
  1180. let capacity = 0;
  1181. for (let i = start; i < source.value.length; i++) {
  1182. const size = itemSize(i);
  1183. sum += size;
  1184. capacity = i;
  1185. if (sum > containerSize) break;
  1186. }
  1187. return capacity - start;
  1188. };
  1189. }
  1190. function createGetOffset(source, itemSize) {
  1191. return (scrollDirection) => {
  1192. if (typeof itemSize === "number") return Math.floor(scrollDirection / itemSize) + 1;
  1193. let sum = 0;
  1194. let offset = 0;
  1195. for (let i = 0; i < source.value.length; i++) {
  1196. const size = itemSize(i);
  1197. sum += size;
  1198. if (sum >= scrollDirection) {
  1199. offset = i;
  1200. break;
  1201. }
  1202. }
  1203. return offset + 1;
  1204. };
  1205. }
  1206. function createCalculateRange(type, overscan, getOffset, getViewCapacity, { containerRef, state, currentList, source }) {
  1207. return () => {
  1208. const element = containerRef.value;
  1209. if (element) {
  1210. const offset = getOffset(type === "vertical" ? element.scrollTop : element.scrollLeft);
  1211. const viewCapacity = getViewCapacity(type === "vertical" ? element.clientHeight : element.clientWidth);
  1212. const from = offset - overscan;
  1213. const to = offset + viewCapacity + overscan;
  1214. state.value = {
  1215. start: from < 0 ? 0 : from,
  1216. end: to > source.value.length ? source.value.length : to
  1217. };
  1218. currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({
  1219. data: ele,
  1220. index: index + state.value.start
  1221. }));
  1222. }
  1223. };
  1224. }
  1225. function createGetDistance(itemSize, source) {
  1226. return (index) => {
  1227. if (typeof itemSize === "number") {
  1228. const size2 = index * itemSize;
  1229. return size2;
  1230. }
  1231. const size = source.value.slice(0, index).reduce((sum, _, i) => sum + itemSize(i), 0);
  1232. return size;
  1233. };
  1234. }
  1235. function useWatchForSizes(size, list, containerRef, calculateRange) {
  1236. watch([
  1237. size.width,
  1238. size.height,
  1239. () => toValue(list),
  1240. containerRef
  1241. ], () => {
  1242. calculateRange();
  1243. });
  1244. }
  1245. function createComputedTotalSize(itemSize, source) {
  1246. return computed(() => {
  1247. if (typeof itemSize === "number") return source.value.length * itemSize;
  1248. return source.value.reduce((sum, _, index) => sum + itemSize(index), 0);
  1249. });
  1250. }
  1251. const scrollToDictionaryForElementScrollKey = {
  1252. horizontal: "scrollLeft",
  1253. vertical: "scrollTop"
  1254. };
  1255. function createScrollTo(type, calculateRange, getDistance, containerRef) {
  1256. return (index) => {
  1257. if (containerRef.value) {
  1258. containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index);
  1259. calculateRange();
  1260. }
  1261. };
  1262. }
  1263. function useHorizontalVirtualList(options, list) {
  1264. const resources = useVirtualListResources(list);
  1265. const { state, source, currentList, size, containerRef } = resources;
  1266. const containerStyle = { overflowX: "auto" };
  1267. const { itemWidth, overscan = 5 } = options;
  1268. const getViewCapacity = createGetViewCapacity(state, source, itemWidth);
  1269. const getOffset = createGetOffset(source, itemWidth);
  1270. const calculateRange = createCalculateRange("horizontal", overscan, getOffset, getViewCapacity, resources);
  1271. const getDistanceLeft = createGetDistance(itemWidth, source);
  1272. const offsetLeft = computed(() => getDistanceLeft(state.value.start));
  1273. const totalWidth = createComputedTotalSize(itemWidth, source);
  1274. useWatchForSizes(size, list, containerRef, calculateRange);
  1275. const scrollTo = createScrollTo("horizontal", calculateRange, getDistanceLeft, containerRef);
  1276. const wrapperProps = computed(() => {
  1277. return { style: {
  1278. height: "100%",
  1279. width: `${totalWidth.value - offsetLeft.value}px`,
  1280. marginLeft: `${offsetLeft.value}px`,
  1281. display: "flex"
  1282. } };
  1283. });
  1284. return {
  1285. scrollTo,
  1286. calculateRange,
  1287. wrapperProps,
  1288. containerStyle,
  1289. currentList,
  1290. containerRef
  1291. };
  1292. }
  1293. function useVerticalVirtualList(options, list) {
  1294. const resources = useVirtualListResources(list);
  1295. const { state, source, currentList, size, containerRef } = resources;
  1296. const containerStyle = { overflowY: "auto" };
  1297. const { itemHeight, overscan = 5 } = options;
  1298. const getViewCapacity = createGetViewCapacity(state, source, itemHeight);
  1299. const getOffset = createGetOffset(source, itemHeight);
  1300. const calculateRange = createCalculateRange("vertical", overscan, getOffset, getViewCapacity, resources);
  1301. const getDistanceTop = createGetDistance(itemHeight, source);
  1302. const offsetTop = computed(() => getDistanceTop(state.value.start));
  1303. const totalHeight = createComputedTotalSize(itemHeight, source);
  1304. useWatchForSizes(size, list, containerRef, calculateRange);
  1305. const scrollTo = createScrollTo("vertical", calculateRange, getDistanceTop, containerRef);
  1306. const wrapperProps = computed(() => {
  1307. return { style: {
  1308. width: "100%",
  1309. height: `${totalHeight.value - offsetTop.value}px`,
  1310. marginTop: `${offsetTop.value}px`
  1311. } };
  1312. });
  1313. return {
  1314. calculateRange,
  1315. scrollTo,
  1316. containerStyle,
  1317. wrapperProps,
  1318. currentList,
  1319. containerRef
  1320. };
  1321. }
  1322. const isDark = useDark();
  1323. const toggleDark = /* @__PURE__ */ useToggle(isDark);
  1324. const TYPE_REQUEST = "q";
  1325. const TYPE_RESPONSE = "s";
  1326. const DEFAULT_TIMEOUT = 6e4;
  1327. function defaultSerialize(i) {
  1328. return i;
  1329. }
  1330. const defaultDeserialize = defaultSerialize;
  1331. const { clearTimeout: clearTimeout$1, setTimeout: setTimeout$1 } = globalThis;
  1332. const random = Math.random.bind(Math);
  1333. function createBirpc(functions, options) {
  1334. const { post, on, off = () => {}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT } = options;
  1335. const rpcPromiseMap = /* @__PURE__ */ new Map();
  1336. let _promise;
  1337. let closed = false;
  1338. const rpc$1 = new Proxy({}, { get(_, method) {
  1339. if (method === "$functions") return functions;
  1340. if (method === "$close") return close;
  1341. if (method === "$closed") return closed;
  1342. if (method === "then" && !eventNames.includes("then") && !("then" in functions)) return void 0;
  1343. const sendEvent = (...args) => {
  1344. post(serialize({
  1345. m: method,
  1346. a: args,
  1347. t: TYPE_REQUEST
  1348. }));
  1349. };
  1350. if (eventNames.includes(method)) {
  1351. sendEvent.asEvent = sendEvent;
  1352. return sendEvent;
  1353. }
  1354. const sendCall = async (...args) => {
  1355. if (closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
  1356. if (_promise) try {
  1357. await _promise;
  1358. } finally {
  1359. _promise = void 0;
  1360. }
  1361. return new Promise((resolve, reject) => {
  1362. const id = nanoid();
  1363. let timeoutId;
  1364. if (timeout >= 0) {
  1365. timeoutId = setTimeout$1(() => {
  1366. try {
  1367. const handleResult = options.onTimeoutError?.(method, args);
  1368. if (handleResult !== true) throw new Error(`[birpc] timeout on calling "${method}"`);
  1369. } catch (e) {
  1370. reject(e);
  1371. }
  1372. rpcPromiseMap.delete(id);
  1373. }, timeout);
  1374. if (typeof timeoutId === "object") timeoutId = timeoutId.unref?.();
  1375. }
  1376. rpcPromiseMap.set(id, {
  1377. resolve,
  1378. reject,
  1379. timeoutId,
  1380. method
  1381. });
  1382. post(serialize({
  1383. m: method,
  1384. a: args,
  1385. i: id,
  1386. t: "q"
  1387. }));
  1388. });
  1389. };
  1390. sendCall.asEvent = sendEvent;
  1391. return sendCall;
  1392. } });
  1393. function close(error) {
  1394. closed = true;
  1395. rpcPromiseMap.forEach(({ reject, method }) => {
  1396. reject(error || new Error(`[birpc] rpc is closed, cannot call "${method}"`));
  1397. });
  1398. rpcPromiseMap.clear();
  1399. off(onMessage);
  1400. }
  1401. async function onMessage(data, ...extra) {
  1402. let msg;
  1403. try {
  1404. msg = deserialize(data);
  1405. } catch (e) {
  1406. if (options.onGeneralError?.(e) !== true) throw e;
  1407. return;
  1408. }
  1409. if (msg.t === TYPE_REQUEST) {
  1410. const { m: method, a: args } = msg;
  1411. let result, error;
  1412. const fn = resolver ? resolver(method, functions[method]) : functions[method];
  1413. if (!fn) error = new Error(`[birpc] function "${method}" not found`);
  1414. else try {
  1415. result = await fn.apply(bind === "rpc" ? rpc$1 : functions, args);
  1416. } catch (e) {
  1417. error = e;
  1418. }
  1419. if (msg.i) {
  1420. if (error && options.onError) options.onError(error, method, args);
  1421. if (error && options.onFunctionError) {
  1422. if (options.onFunctionError(error, method, args) === true) return;
  1423. }
  1424. if (!error) try {
  1425. post(serialize({
  1426. t: TYPE_RESPONSE,
  1427. i: msg.i,
  1428. r: result
  1429. }), ...extra);
  1430. return;
  1431. } catch (e) {
  1432. error = e;
  1433. if (options.onGeneralError?.(e, method, args) !== true) throw e;
  1434. }
  1435. try {
  1436. post(serialize({
  1437. t: TYPE_RESPONSE,
  1438. i: msg.i,
  1439. e: error
  1440. }), ...extra);
  1441. } catch (e) {
  1442. if (options.onGeneralError?.(e, method, args) !== true) throw e;
  1443. }
  1444. }
  1445. } else {
  1446. const { i: ack, r: result, e: error } = msg;
  1447. const promise = rpcPromiseMap.get(ack);
  1448. if (promise) {
  1449. clearTimeout$1(promise.timeoutId);
  1450. if (error) promise.reject(error);
  1451. else promise.resolve(result);
  1452. }
  1453. rpcPromiseMap.delete(ack);
  1454. }
  1455. }
  1456. _promise = on(onMessage);
  1457. return rpc$1;
  1458. }
  1459. const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  1460. function nanoid(size = 21) {
  1461. let id = "";
  1462. let i = size;
  1463. while (i--) id += urlAlphabet[random() * 64 | 0];
  1464. return id;
  1465. }
  1466. function createRPCClient(name, hot$1, functions = {}, options = {}) {
  1467. const event = `${name}:rpc`;
  1468. const promise = Promise.resolve(hot$1).then((r) => {
  1469. if (!r) console.warn("[vite-hot-client] Received undefined hot context, RPC calls are ignored");
  1470. return r;
  1471. });
  1472. return createBirpc(functions, {
  1473. ...options,
  1474. on: async (fn) => {
  1475. (await promise)?.on(event, fn);
  1476. },
  1477. post: async (data) => {
  1478. (await promise)?.send(event, data);
  1479. }
  1480. });
  1481. }
  1482. async function getViteClient(base = "/", warning = true) {
  1483. try {
  1484. const url = `${base}@vite/client`;
  1485. const res = await fetch(url);
  1486. const text = await res.text();
  1487. if (text.startsWith("<") || !res.headers.get("content-type")?.includes("javascript")) throw new Error("Not javascript");
  1488. return await import(
  1489. /* @vite-ignore */
  1490. url
  1491. );
  1492. } catch {
  1493. if (warning) console.error(`[vite-hot-client] Failed to import "${base}@vite/client"`);
  1494. }
  1495. return void 0;
  1496. }
  1497. async function createHotContext(path = "/____", base = "/") {
  1498. const viteClient = await getViteClient(base);
  1499. return viteClient?.createHotContext(path);
  1500. }
  1501. const dataCache = new Map();
  1502. function fetchJson(url) {
  1503. if (!dataCache.has(url)) dataCache.set(url, fetch(url).then((r) => r.json()));
  1504. return dataCache.get(url);
  1505. }
  1506. function createStaticRpcClient() {
  1507. async function getModuleTransformInfo(query, id) {
  1508. const { hash } = await __vitePreload(async () => {
  1509. const { hash: hash$1 } = await import("./dist-Dp-WpU5V.js");
  1510. return { hash: hash$1 };
  1511. }, [], import.meta.url);
  1512. return fetchJson(`./reports/${query.vite}-${query.env}/transforms/${hash(id)}.json`);
  1513. }
  1514. return {
  1515. getMetadata: () => fetchJson("./reports/metadata.json"),
  1516. getModulesList: (query) => fetchJson(`./reports/${query.vite}-${query.env}/modules.json`),
  1517. getPluginMetrics: (query) => fetchJson(`./reports/${query.vite}-${query.env}/metric-plugins.json`),
  1518. getModuleTransformInfo,
  1519. resolveId: (query, id) => getModuleTransformInfo(query, id).then((r) => r.resolvedId),
  1520. onModuleUpdated: async () => void 0,
  1521. getServerMetrics: async () => ({})
  1522. };
  1523. }
  1524. const onModuleUpdated = /* @__PURE__ */ createEventHook();
  1525. const isStaticMode = document.body.getAttribute("data-vite-inspect-mode") === "BUILD";
  1526. const hot = createHotContext("/___", `${location.pathname.split("/__inspect")[0] || ""}/`.replace(/\/\//g, "/"));
  1527. const rpc = isStaticMode ? createStaticRpcClient() : createRPCClient("vite-plugin-inspect", hot, { async onModuleUpdated() {
  1528. onModuleUpdated.trigger();
  1529. } });
  1530. function guessMode(code) {
  1531. if (code.trimStart().startsWith("<")) return "htmlmixed";
  1532. if (code.match(/^import\s/)) return "javascript";
  1533. if (code.match(/^[.#].+\{/)) return "css";
  1534. return "javascript";
  1535. }
  1536. function inspectSourcemaps({ code, sourcemaps }) {
  1537. console.info("sourcemaps", JSON.stringify(sourcemaps, null, 2));
  1538. const serialized = serializeForSourcemapsVisualizer(code, sourcemaps);
  1539. window.open(`https://evanw.github.io/source-map-visualization#${serialized}`, "_blank");
  1540. }
  1541. function safeJsonParse(str) {
  1542. try {
  1543. return JSON.parse(str);
  1544. } catch {
  1545. console.error("Failed to parse JSON", str);
  1546. return null;
  1547. }
  1548. }
  1549. function serializeForSourcemapsVisualizer(code, map) {
  1550. const encoder = new TextEncoder();
  1551. const codeArray = encoder.encode(code);
  1552. const mapArray = encoder.encode(map);
  1553. const codeLengthArray = encoder.encode(codeArray.length.toString());
  1554. const mapLengthArray = encoder.encode(mapArray.length.toString());
  1555. const combinedArray = new Uint8Array(codeLengthArray.length + 1 + codeArray.length + mapLengthArray.length + 1 + mapArray.length);
  1556. combinedArray.set(codeLengthArray);
  1557. combinedArray.set([0], codeLengthArray.length);
  1558. combinedArray.set(codeArray, codeLengthArray.length + 1);
  1559. combinedArray.set(mapLengthArray, codeLengthArray.length + 1 + codeArray.length);
  1560. combinedArray.set([0], codeLengthArray.length + 1 + codeArray.length + mapLengthArray.length);
  1561. combinedArray.set(mapArray, codeLengthArray.length + 1 + codeArray.length + mapLengthArray.length + 1);
  1562. let binary = "";
  1563. const len = combinedArray.byteLength;
  1564. for (let i = 0; i < len; i++) binary += String.fromCharCode(combinedArray[i]);
  1565. return btoa(binary);
  1566. }
  1567. const usePayloadStore = defineStore("payload", () => {
  1568. const isLoading = ref(false);
  1569. const metadata = shallowRef({ instances: [] });
  1570. const query = useLocalStorage("vite-inspect-v1-query", {
  1571. vite: "",
  1572. env: ""
  1573. }, { mergeDefaults: true });
  1574. const modules = shallowRef([]);
  1575. const queryCache = new Map();
  1576. async function init() {
  1577. metadata.value = await rpc.getMetadata();
  1578. if (!metadata.value.instances.some((i) => i.vite === query.value.vite)) query.value.vite = metadata.value.instances[0].vite;
  1579. if (!metadata.value.instances.some((i) => i.vite === query.value.vite && i.environments.includes(query.value.env))) {
  1580. const instance$1 = metadata.value.instances.find((i) => i.vite === query.value.vite);
  1581. if (instance$1) query.value.env = instance$1.environments[0] || "client";
  1582. else query.value.env = metadata.value.instances[0].environments[0] || "client";
  1583. }
  1584. await doQuery();
  1585. watch(query, async () => {
  1586. await doQuery();
  1587. }, { deep: true });
  1588. onModuleUpdated.on(() => refetch());
  1589. }
  1590. async function doQuery() {
  1591. const key = `${query.value.vite}-${query.value.env}`;
  1592. if (!queryCache.has(key)) queryCache.set(key, rpc.getModulesList(query.value));
  1593. isLoading.value = true;
  1594. modules.value = [];
  1595. try {
  1596. modules.value = Object.freeze(await queryCache.get(key));
  1597. } finally {
  1598. isLoading.value = false;
  1599. }
  1600. }
  1601. async function refetch(force = false) {
  1602. queryCache.clear();
  1603. if (force) metadata.value = await rpc.getMetadata();
  1604. await doQuery();
  1605. }
  1606. const instance = computed(() => metadata.value.instances.find((i) => i.vite === query.value.vite));
  1607. const root = computed(() => instance.value.root);
  1608. return {
  1609. init,
  1610. metadata,
  1611. query,
  1612. modules,
  1613. instance,
  1614. root,
  1615. isLoading,
  1616. isStatic: isStaticMode,
  1617. refetch
  1618. };
  1619. });
  1620. export { __vitePreload, createHotContext, createPinia, defineStore, guessMode, inspectSourcemaps, isDark, isStaticMode, onModuleUpdated, rpc, safeJsonParse, toggleDark, tryOnScopeDispose, useLocalStorage, usePayloadStore, useVirtualList };