pinia.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. import {
  2. setupDevtoolsPlugin
  3. } from "./chunk-ISH6AKKV.js";
  4. import {
  5. del,
  6. isVue2,
  7. set
  8. } from "./chunk-LRYUMHUV.js";
  9. import "./chunk-MKUMB4YM.js";
  10. import "./chunk-S6VK5PVK.js";
  11. import {
  12. computed,
  13. effectScope,
  14. getCurrentInstance,
  15. getCurrentScope,
  16. hasInjectionContext,
  17. inject,
  18. isReactive,
  19. isRef,
  20. markRaw,
  21. nextTick,
  22. onScopeDispose,
  23. reactive,
  24. ref,
  25. toRaw,
  26. toRef,
  27. toRefs,
  28. unref,
  29. watch
  30. } from "./chunk-YVHZHMSQ.js";
  31. import "./chunk-VNBICN6T.js";
  32. import "./chunk-2LSFTFF7.js";
  33. // node_modules/.pnpm/pinia@2.1.3_typescript@5.4.5_vue@3.4.27/node_modules/pinia/dist/pinia.mjs
  34. var activePinia;
  35. var setActivePinia = (pinia) => activePinia = pinia;
  36. var getActivePinia = () => hasInjectionContext() && inject(piniaSymbol) || activePinia;
  37. var piniaSymbol = true ? Symbol("pinia") : (
  38. /* istanbul ignore next */
  39. Symbol()
  40. );
  41. function isPlainObject(o) {
  42. return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
  43. }
  44. var MutationType;
  45. (function(MutationType2) {
  46. MutationType2["direct"] = "direct";
  47. MutationType2["patchObject"] = "patch object";
  48. MutationType2["patchFunction"] = "patch function";
  49. })(MutationType || (MutationType = {}));
  50. var IS_CLIENT = typeof window !== "undefined";
  51. var USE_DEVTOOLS = IS_CLIENT;
  52. var _global = (() => 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 })();
  53. function bom(blob, { autoBom = false } = {}) {
  54. if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  55. return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
  56. }
  57. return blob;
  58. }
  59. function download(url, name, opts) {
  60. const xhr = new XMLHttpRequest();
  61. xhr.open("GET", url);
  62. xhr.responseType = "blob";
  63. xhr.onload = function() {
  64. saveAs(xhr.response, name, opts);
  65. };
  66. xhr.onerror = function() {
  67. console.error("could not download file");
  68. };
  69. xhr.send();
  70. }
  71. function corsEnabled(url) {
  72. const xhr = new XMLHttpRequest();
  73. xhr.open("HEAD", url, false);
  74. try {
  75. xhr.send();
  76. } catch (e) {
  77. }
  78. return xhr.status >= 200 && xhr.status <= 299;
  79. }
  80. function click(node) {
  81. try {
  82. node.dispatchEvent(new MouseEvent("click"));
  83. } catch (e) {
  84. const evt = document.createEvent("MouseEvents");
  85. evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  86. node.dispatchEvent(evt);
  87. }
  88. }
  89. var _navigator = typeof navigator === "object" ? navigator : { userAgent: "" };
  90. var isMacOSWebView = (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))();
  91. var saveAs = !IS_CLIENT ? () => {
  92. } : (
  93. // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  94. typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : (
  95. // Use msSaveOrOpenBlob as a second approach
  96. "msSaveOrOpenBlob" in _navigator ? msSaveAs : (
  97. // Fallback to using FileReader and a popup
  98. fileSaverSaveAs
  99. )
  100. )
  101. );
  102. function downloadSaveAs(blob, name = "download", opts) {
  103. const a = document.createElement("a");
  104. a.download = name;
  105. a.rel = "noopener";
  106. if (typeof blob === "string") {
  107. a.href = blob;
  108. if (a.origin !== location.origin) {
  109. if (corsEnabled(a.href)) {
  110. download(blob, name, opts);
  111. } else {
  112. a.target = "_blank";
  113. click(a);
  114. }
  115. } else {
  116. click(a);
  117. }
  118. } else {
  119. a.href = URL.createObjectURL(blob);
  120. setTimeout(function() {
  121. URL.revokeObjectURL(a.href);
  122. }, 4e4);
  123. setTimeout(function() {
  124. click(a);
  125. }, 0);
  126. }
  127. }
  128. function msSaveAs(blob, name = "download", opts) {
  129. if (typeof blob === "string") {
  130. if (corsEnabled(blob)) {
  131. download(blob, name, opts);
  132. } else {
  133. const a = document.createElement("a");
  134. a.href = blob;
  135. a.target = "_blank";
  136. setTimeout(function() {
  137. click(a);
  138. });
  139. }
  140. } else {
  141. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  142. }
  143. }
  144. function fileSaverSaveAs(blob, name, opts, popup) {
  145. popup = popup || open("", "_blank");
  146. if (popup) {
  147. popup.document.title = popup.document.body.innerText = "downloading...";
  148. }
  149. if (typeof blob === "string")
  150. return download(blob, name, opts);
  151. const force = blob.type === "application/octet-stream";
  152. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || "safari" in _global;
  153. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  154. if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") {
  155. const reader = new FileReader();
  156. reader.onloadend = function() {
  157. let url = reader.result;
  158. if (typeof url !== "string") {
  159. popup = null;
  160. throw new Error("Wrong reader.result type");
  161. }
  162. url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
  163. if (popup) {
  164. popup.location.href = url;
  165. } else {
  166. location.assign(url);
  167. }
  168. popup = null;
  169. };
  170. reader.readAsDataURL(blob);
  171. } else {
  172. const url = URL.createObjectURL(blob);
  173. if (popup)
  174. popup.location.assign(url);
  175. else
  176. location.href = url;
  177. popup = null;
  178. setTimeout(function() {
  179. URL.revokeObjectURL(url);
  180. }, 4e4);
  181. }
  182. }
  183. function toastMessage(message, type) {
  184. const piniaMessage = "🍍 " + message;
  185. if (typeof __VUE_DEVTOOLS_TOAST__ === "function") {
  186. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  187. } else if (type === "error") {
  188. console.error(piniaMessage);
  189. } else if (type === "warn") {
  190. console.warn(piniaMessage);
  191. } else {
  192. console.log(piniaMessage);
  193. }
  194. }
  195. function isPinia(o) {
  196. return "_a" in o && "install" in o;
  197. }
  198. function checkClipboardAccess() {
  199. if (!("clipboard" in navigator)) {
  200. toastMessage(`Your browser doesn't support the Clipboard API`, "error");
  201. return true;
  202. }
  203. }
  204. function checkNotFocusedError(error) {
  205. if (error instanceof Error && error.message.toLowerCase().includes("document is not focused")) {
  206. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', "warn");
  207. return true;
  208. }
  209. return false;
  210. }
  211. async function actionGlobalCopyState(pinia) {
  212. if (checkClipboardAccess())
  213. return;
  214. try {
  215. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  216. toastMessage("Global state copied to clipboard.");
  217. } catch (error) {
  218. if (checkNotFocusedError(error))
  219. return;
  220. toastMessage(`Failed to serialize the state. Check the console for more details.`, "error");
  221. console.error(error);
  222. }
  223. }
  224. async function actionGlobalPasteState(pinia) {
  225. if (checkClipboardAccess())
  226. return;
  227. try {
  228. pinia.state.value = JSON.parse(await navigator.clipboard.readText());
  229. toastMessage("Global state pasted from clipboard.");
  230. } catch (error) {
  231. if (checkNotFocusedError(error))
  232. return;
  233. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, "error");
  234. console.error(error);
  235. }
  236. }
  237. async function actionGlobalSaveState(pinia) {
  238. try {
  239. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  240. type: "text/plain;charset=utf-8"
  241. }), "pinia-state.json");
  242. } catch (error) {
  243. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
  244. console.error(error);
  245. }
  246. }
  247. var fileInput;
  248. function getFileOpener() {
  249. if (!fileInput) {
  250. fileInput = document.createElement("input");
  251. fileInput.type = "file";
  252. fileInput.accept = ".json";
  253. }
  254. function openFile() {
  255. return new Promise((resolve, reject) => {
  256. fileInput.onchange = async () => {
  257. const files = fileInput.files;
  258. if (!files)
  259. return resolve(null);
  260. const file = files.item(0);
  261. if (!file)
  262. return resolve(null);
  263. return resolve({ text: await file.text(), file });
  264. };
  265. fileInput.oncancel = () => resolve(null);
  266. fileInput.onerror = reject;
  267. fileInput.click();
  268. });
  269. }
  270. return openFile;
  271. }
  272. async function actionGlobalOpenStateFile(pinia) {
  273. try {
  274. const open2 = await getFileOpener();
  275. const result = await open2();
  276. if (!result)
  277. return;
  278. const { text, file } = result;
  279. pinia.state.value = JSON.parse(text);
  280. toastMessage(`Global state imported from "${file.name}".`);
  281. } catch (error) {
  282. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
  283. console.error(error);
  284. }
  285. }
  286. function formatDisplay(display) {
  287. return {
  288. _custom: {
  289. display
  290. }
  291. };
  292. }
  293. var PINIA_ROOT_LABEL = "🍍 Pinia (root)";
  294. var PINIA_ROOT_ID = "_root";
  295. function formatStoreForInspectorTree(store) {
  296. return isPinia(store) ? {
  297. id: PINIA_ROOT_ID,
  298. label: PINIA_ROOT_LABEL
  299. } : {
  300. id: store.$id,
  301. label: store.$id
  302. };
  303. }
  304. function formatStoreForInspectorState(store) {
  305. if (isPinia(store)) {
  306. const storeNames = Array.from(store._s.keys());
  307. const storeMap = store._s;
  308. const state2 = {
  309. state: storeNames.map((storeId) => ({
  310. editable: true,
  311. key: storeId,
  312. value: store.state.value[storeId]
  313. })),
  314. getters: storeNames.filter((id) => storeMap.get(id)._getters).map((id) => {
  315. const store2 = storeMap.get(id);
  316. return {
  317. editable: false,
  318. key: id,
  319. value: store2._getters.reduce((getters, key) => {
  320. getters[key] = store2[key];
  321. return getters;
  322. }, {})
  323. };
  324. })
  325. };
  326. return state2;
  327. }
  328. const state = {
  329. state: Object.keys(store.$state).map((key) => ({
  330. editable: true,
  331. key,
  332. value: store.$state[key]
  333. }))
  334. };
  335. if (store._getters && store._getters.length) {
  336. state.getters = store._getters.map((getterName) => ({
  337. editable: false,
  338. key: getterName,
  339. value: store[getterName]
  340. }));
  341. }
  342. if (store._customProperties.size) {
  343. state.customProperties = Array.from(store._customProperties).map((key) => ({
  344. editable: true,
  345. key,
  346. value: store[key]
  347. }));
  348. }
  349. return state;
  350. }
  351. function formatEventData(events) {
  352. if (!events)
  353. return {};
  354. if (Array.isArray(events)) {
  355. return events.reduce((data, event) => {
  356. data.keys.push(event.key);
  357. data.operations.push(event.type);
  358. data.oldValue[event.key] = event.oldValue;
  359. data.newValue[event.key] = event.newValue;
  360. return data;
  361. }, {
  362. oldValue: {},
  363. keys: [],
  364. operations: [],
  365. newValue: {}
  366. });
  367. } else {
  368. return {
  369. operation: formatDisplay(events.type),
  370. key: formatDisplay(events.key),
  371. oldValue: events.oldValue,
  372. newValue: events.newValue
  373. };
  374. }
  375. }
  376. function formatMutationType(type) {
  377. switch (type) {
  378. case MutationType.direct:
  379. return "mutation";
  380. case MutationType.patchFunction:
  381. return "$patch";
  382. case MutationType.patchObject:
  383. return "$patch";
  384. default:
  385. return "unknown";
  386. }
  387. }
  388. var isTimelineActive = true;
  389. var componentStateTypes = [];
  390. var MUTATIONS_LAYER_ID = "pinia:mutations";
  391. var INSPECTOR_ID = "pinia";
  392. var { assign: assign$1 } = Object;
  393. var getStoreType = (id) => "🍍 " + id;
  394. function registerPiniaDevtools(app, pinia) {
  395. setupDevtoolsPlugin({
  396. id: "dev.esm.pinia",
  397. label: "Pinia 🍍",
  398. logo: "https://pinia.vuejs.org/logo.svg",
  399. packageName: "pinia",
  400. homepage: "https://pinia.vuejs.org",
  401. componentStateTypes,
  402. app
  403. }, (api) => {
  404. if (typeof api.now !== "function") {
  405. toastMessage("You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.");
  406. }
  407. api.addTimelineLayer({
  408. id: MUTATIONS_LAYER_ID,
  409. label: `Pinia 🍍`,
  410. color: 15064968
  411. });
  412. api.addInspector({
  413. id: INSPECTOR_ID,
  414. label: "Pinia 🍍",
  415. icon: "storage",
  416. treeFilterPlaceholder: "Search stores",
  417. actions: [
  418. {
  419. icon: "content_copy",
  420. action: () => {
  421. actionGlobalCopyState(pinia);
  422. },
  423. tooltip: "Serialize and copy the state"
  424. },
  425. {
  426. icon: "content_paste",
  427. action: async () => {
  428. await actionGlobalPasteState(pinia);
  429. api.sendInspectorTree(INSPECTOR_ID);
  430. api.sendInspectorState(INSPECTOR_ID);
  431. },
  432. tooltip: "Replace the state with the content of your clipboard"
  433. },
  434. {
  435. icon: "save",
  436. action: () => {
  437. actionGlobalSaveState(pinia);
  438. },
  439. tooltip: "Save the state as a JSON file"
  440. },
  441. {
  442. icon: "folder_open",
  443. action: async () => {
  444. await actionGlobalOpenStateFile(pinia);
  445. api.sendInspectorTree(INSPECTOR_ID);
  446. api.sendInspectorState(INSPECTOR_ID);
  447. },
  448. tooltip: "Import the state from a JSON file"
  449. }
  450. ],
  451. nodeActions: [
  452. {
  453. icon: "restore",
  454. tooltip: 'Reset the state (with "$reset")',
  455. action: (nodeId) => {
  456. const store = pinia._s.get(nodeId);
  457. if (!store) {
  458. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, "warn");
  459. } else if (typeof store.$reset !== "function") {
  460. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, "warn");
  461. } else {
  462. store.$reset();
  463. toastMessage(`Store "${nodeId}" reset.`);
  464. }
  465. }
  466. }
  467. ]
  468. });
  469. api.on.inspectComponent((payload, ctx) => {
  470. const proxy = payload.componentInstance && payload.componentInstance.proxy;
  471. if (proxy && proxy._pStores) {
  472. const piniaStores = payload.componentInstance.proxy._pStores;
  473. Object.values(piniaStores).forEach((store) => {
  474. payload.instanceData.state.push({
  475. type: getStoreType(store.$id),
  476. key: "state",
  477. editable: true,
  478. value: store._isOptionsAPI ? {
  479. _custom: {
  480. value: toRaw(store.$state),
  481. actions: [
  482. {
  483. icon: "restore",
  484. tooltip: "Reset the state of this store",
  485. action: () => store.$reset()
  486. }
  487. ]
  488. }
  489. } : (
  490. // NOTE: workaround to unwrap transferred refs
  491. Object.keys(store.$state).reduce((state, key) => {
  492. state[key] = store.$state[key];
  493. return state;
  494. }, {})
  495. )
  496. });
  497. if (store._getters && store._getters.length) {
  498. payload.instanceData.state.push({
  499. type: getStoreType(store.$id),
  500. key: "getters",
  501. editable: false,
  502. value: store._getters.reduce((getters, key) => {
  503. try {
  504. getters[key] = store[key];
  505. } catch (error) {
  506. getters[key] = error;
  507. }
  508. return getters;
  509. }, {})
  510. });
  511. }
  512. });
  513. }
  514. });
  515. api.on.getInspectorTree((payload) => {
  516. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  517. let stores = [pinia];
  518. stores = stores.concat(Array.from(pinia._s.values()));
  519. payload.rootNodes = (payload.filter ? stores.filter((store) => "$id" in store ? store.$id.toLowerCase().includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) : stores).map(formatStoreForInspectorTree);
  520. }
  521. });
  522. api.on.getInspectorState((payload) => {
  523. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  524. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  525. if (!inspectedStore) {
  526. return;
  527. }
  528. if (inspectedStore) {
  529. payload.state = formatStoreForInspectorState(inspectedStore);
  530. }
  531. }
  532. });
  533. api.on.editInspectorState((payload, ctx) => {
  534. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  535. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  536. if (!inspectedStore) {
  537. return toastMessage(`store "${payload.nodeId}" not found`, "error");
  538. }
  539. const { path } = payload;
  540. if (!isPinia(inspectedStore)) {
  541. if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) {
  542. path.unshift("$state");
  543. }
  544. } else {
  545. path.unshift("state");
  546. }
  547. isTimelineActive = false;
  548. payload.set(inspectedStore, path, payload.state.value);
  549. isTimelineActive = true;
  550. }
  551. });
  552. api.on.editComponentState((payload) => {
  553. if (payload.type.startsWith("🍍")) {
  554. const storeId = payload.type.replace(/^🍍\s*/, "");
  555. const store = pinia._s.get(storeId);
  556. if (!store) {
  557. return toastMessage(`store "${storeId}" not found`, "error");
  558. }
  559. const { path } = payload;
  560. if (path[0] !== "state") {
  561. return toastMessage(`Invalid path for store "${storeId}":
  562. ${path}
  563. Only state can be modified.`);
  564. }
  565. path[0] = "$state";
  566. isTimelineActive = false;
  567. payload.set(store, path, payload.state.value);
  568. isTimelineActive = true;
  569. }
  570. });
  571. });
  572. }
  573. function addStoreToDevtools(app, store) {
  574. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  575. componentStateTypes.push(getStoreType(store.$id));
  576. }
  577. setupDevtoolsPlugin({
  578. id: "dev.esm.pinia",
  579. label: "Pinia 🍍",
  580. logo: "https://pinia.vuejs.org/logo.svg",
  581. packageName: "pinia",
  582. homepage: "https://pinia.vuejs.org",
  583. componentStateTypes,
  584. app,
  585. settings: {
  586. logStoreChanges: {
  587. label: "Notify about new/deleted stores",
  588. type: "boolean",
  589. defaultValue: true
  590. }
  591. // useEmojis: {
  592. // label: 'Use emojis in messages ⚡️',
  593. // type: 'boolean',
  594. // defaultValue: true,
  595. // },
  596. }
  597. }, (api) => {
  598. const now = typeof api.now === "function" ? api.now.bind(api) : Date.now;
  599. store.$onAction(({ after, onError, name, args }) => {
  600. const groupId = runningActionId++;
  601. api.addTimelineEvent({
  602. layerId: MUTATIONS_LAYER_ID,
  603. event: {
  604. time: now(),
  605. title: "🛫 " + name,
  606. subtitle: "start",
  607. data: {
  608. store: formatDisplay(store.$id),
  609. action: formatDisplay(name),
  610. args
  611. },
  612. groupId
  613. }
  614. });
  615. after((result) => {
  616. activeAction = void 0;
  617. api.addTimelineEvent({
  618. layerId: MUTATIONS_LAYER_ID,
  619. event: {
  620. time: now(),
  621. title: "🛬 " + name,
  622. subtitle: "end",
  623. data: {
  624. store: formatDisplay(store.$id),
  625. action: formatDisplay(name),
  626. args,
  627. result
  628. },
  629. groupId
  630. }
  631. });
  632. });
  633. onError((error) => {
  634. activeAction = void 0;
  635. api.addTimelineEvent({
  636. layerId: MUTATIONS_LAYER_ID,
  637. event: {
  638. time: now(),
  639. logType: "error",
  640. title: "💥 " + name,
  641. subtitle: "end",
  642. data: {
  643. store: formatDisplay(store.$id),
  644. action: formatDisplay(name),
  645. args,
  646. error
  647. },
  648. groupId
  649. }
  650. });
  651. });
  652. }, true);
  653. store._customProperties.forEach((name) => {
  654. watch(() => unref(store[name]), (newValue, oldValue) => {
  655. api.notifyComponentUpdate();
  656. api.sendInspectorState(INSPECTOR_ID);
  657. if (isTimelineActive) {
  658. api.addTimelineEvent({
  659. layerId: MUTATIONS_LAYER_ID,
  660. event: {
  661. time: now(),
  662. title: "Change",
  663. subtitle: name,
  664. data: {
  665. newValue,
  666. oldValue
  667. },
  668. groupId: activeAction
  669. }
  670. });
  671. }
  672. }, { deep: true });
  673. });
  674. store.$subscribe(({ events, type }, state) => {
  675. api.notifyComponentUpdate();
  676. api.sendInspectorState(INSPECTOR_ID);
  677. if (!isTimelineActive)
  678. return;
  679. const eventData = {
  680. time: now(),
  681. title: formatMutationType(type),
  682. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  683. groupId: activeAction
  684. };
  685. activeAction = void 0;
  686. if (type === MutationType.patchFunction) {
  687. eventData.subtitle = "⤵️";
  688. } else if (type === MutationType.patchObject) {
  689. eventData.subtitle = "🧩";
  690. } else if (events && !Array.isArray(events)) {
  691. eventData.subtitle = events.type;
  692. }
  693. if (events) {
  694. eventData.data["rawEvent(s)"] = {
  695. _custom: {
  696. display: "DebuggerEvent",
  697. type: "object",
  698. tooltip: "raw DebuggerEvent[]",
  699. value: events
  700. }
  701. };
  702. }
  703. api.addTimelineEvent({
  704. layerId: MUTATIONS_LAYER_ID,
  705. event: eventData
  706. });
  707. }, { detached: true, flush: "sync" });
  708. const hotUpdate = store._hotUpdate;
  709. store._hotUpdate = markRaw((newStore) => {
  710. hotUpdate(newStore);
  711. api.addTimelineEvent({
  712. layerId: MUTATIONS_LAYER_ID,
  713. event: {
  714. time: now(),
  715. title: "🔥 " + store.$id,
  716. subtitle: "HMR update",
  717. data: {
  718. store: formatDisplay(store.$id),
  719. info: formatDisplay(`HMR update`)
  720. }
  721. }
  722. });
  723. api.notifyComponentUpdate();
  724. api.sendInspectorTree(INSPECTOR_ID);
  725. api.sendInspectorState(INSPECTOR_ID);
  726. });
  727. const { $dispose } = store;
  728. store.$dispose = () => {
  729. $dispose();
  730. api.notifyComponentUpdate();
  731. api.sendInspectorTree(INSPECTOR_ID);
  732. api.sendInspectorState(INSPECTOR_ID);
  733. api.getSettings().logStoreChanges && toastMessage(`Disposed "${store.$id}" store 🗑`);
  734. };
  735. api.notifyComponentUpdate();
  736. api.sendInspectorTree(INSPECTOR_ID);
  737. api.sendInspectorState(INSPECTOR_ID);
  738. api.getSettings().logStoreChanges && toastMessage(`"${store.$id}" store installed 🆕`);
  739. });
  740. }
  741. var runningActionId = 0;
  742. var activeAction;
  743. function patchActionForGrouping(store, actionNames) {
  744. const actions = actionNames.reduce((storeActions, actionName) => {
  745. storeActions[actionName] = toRaw(store)[actionName];
  746. return storeActions;
  747. }, {});
  748. for (const actionName in actions) {
  749. store[actionName] = function() {
  750. const _actionId = runningActionId;
  751. const trackedStore = new Proxy(store, {
  752. get(...args) {
  753. activeAction = _actionId;
  754. return Reflect.get(...args);
  755. },
  756. set(...args) {
  757. activeAction = _actionId;
  758. return Reflect.set(...args);
  759. }
  760. });
  761. return actions[actionName].apply(trackedStore, arguments);
  762. };
  763. }
  764. }
  765. function devtoolsPlugin({ app, store, options }) {
  766. if (store.$id.startsWith("__hot:")) {
  767. return;
  768. }
  769. if (options.state) {
  770. store._isOptionsAPI = true;
  771. }
  772. if (typeof options.state === "function") {
  773. patchActionForGrouping(
  774. // @ts-expect-error: can cast the store...
  775. store,
  776. Object.keys(options.actions)
  777. );
  778. const originalHotUpdate = store._hotUpdate;
  779. toRaw(store)._hotUpdate = function(newStore) {
  780. originalHotUpdate.apply(this, arguments);
  781. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions));
  782. };
  783. }
  784. addStoreToDevtools(
  785. app,
  786. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  787. store
  788. );
  789. }
  790. function createPinia() {
  791. const scope = effectScope(true);
  792. const state = scope.run(() => ref({}));
  793. let _p = [];
  794. let toBeInstalled = [];
  795. const pinia = markRaw({
  796. install(app) {
  797. setActivePinia(pinia);
  798. if (!isVue2) {
  799. pinia._a = app;
  800. app.provide(piniaSymbol, pinia);
  801. app.config.globalProperties.$pinia = pinia;
  802. if (USE_DEVTOOLS) {
  803. registerPiniaDevtools(app, pinia);
  804. }
  805. toBeInstalled.forEach((plugin) => _p.push(plugin));
  806. toBeInstalled = [];
  807. }
  808. },
  809. use(plugin) {
  810. if (!this._a && !isVue2) {
  811. toBeInstalled.push(plugin);
  812. } else {
  813. _p.push(plugin);
  814. }
  815. return this;
  816. },
  817. _p,
  818. // it's actually undefined here
  819. // @ts-expect-error
  820. _a: null,
  821. _e: scope,
  822. _s: /* @__PURE__ */ new Map(),
  823. state
  824. });
  825. if (USE_DEVTOOLS && typeof Proxy !== "undefined") {
  826. pinia.use(devtoolsPlugin);
  827. }
  828. return pinia;
  829. }
  830. var isUseStore = (fn) => {
  831. return typeof fn === "function" && typeof fn.$id === "string";
  832. };
  833. function patchObject(newState, oldState) {
  834. for (const key in oldState) {
  835. const subPatch = oldState[key];
  836. if (!(key in newState)) {
  837. continue;
  838. }
  839. const targetValue = newState[key];
  840. if (isPlainObject(targetValue) && isPlainObject(subPatch) && !isRef(subPatch) && !isReactive(subPatch)) {
  841. newState[key] = patchObject(targetValue, subPatch);
  842. } else {
  843. if (isVue2) {
  844. set(newState, key, subPatch);
  845. } else {
  846. newState[key] = subPatch;
  847. }
  848. }
  849. }
  850. return newState;
  851. }
  852. function acceptHMRUpdate(initialUseStore, hot) {
  853. if (false) {
  854. return () => {
  855. };
  856. }
  857. return (newModule) => {
  858. const pinia = hot.data.pinia || initialUseStore._pinia;
  859. if (!pinia) {
  860. return;
  861. }
  862. hot.data.pinia = pinia;
  863. for (const exportName in newModule) {
  864. const useStore = newModule[exportName];
  865. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  866. const id = useStore.$id;
  867. if (id !== initialUseStore.$id) {
  868. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  869. return hot.invalidate();
  870. }
  871. const existingStore = pinia._s.get(id);
  872. if (!existingStore) {
  873. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  874. return;
  875. }
  876. useStore(pinia, existingStore);
  877. }
  878. }
  879. };
  880. }
  881. var noop = () => {
  882. };
  883. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  884. subscriptions.push(callback);
  885. const removeSubscription = () => {
  886. const idx = subscriptions.indexOf(callback);
  887. if (idx > -1) {
  888. subscriptions.splice(idx, 1);
  889. onCleanup();
  890. }
  891. };
  892. if (!detached && getCurrentScope()) {
  893. onScopeDispose(removeSubscription);
  894. }
  895. return removeSubscription;
  896. }
  897. function triggerSubscriptions(subscriptions, ...args) {
  898. subscriptions.slice().forEach((callback) => {
  899. callback(...args);
  900. });
  901. }
  902. var fallbackRunWithContext = (fn) => fn();
  903. function mergeReactiveObjects(target, patchToApply) {
  904. if (target instanceof Map && patchToApply instanceof Map) {
  905. patchToApply.forEach((value, key) => target.set(key, value));
  906. }
  907. if (target instanceof Set && patchToApply instanceof Set) {
  908. patchToApply.forEach(target.add, target);
  909. }
  910. for (const key in patchToApply) {
  911. if (!patchToApply.hasOwnProperty(key))
  912. continue;
  913. const subPatch = patchToApply[key];
  914. const targetValue = target[key];
  915. if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
  916. target[key] = mergeReactiveObjects(targetValue, subPatch);
  917. } else {
  918. target[key] = subPatch;
  919. }
  920. }
  921. return target;
  922. }
  923. var skipHydrateSymbol = true ? Symbol("pinia:skipHydration") : (
  924. /* istanbul ignore next */
  925. Symbol()
  926. );
  927. var skipHydrateMap = /* @__PURE__ */ new WeakMap();
  928. function skipHydrate(obj) {
  929. return isVue2 ? (
  930. // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
  931. /* istanbul ignore next */
  932. skipHydrateMap.set(obj, 1) && obj
  933. ) : Object.defineProperty(obj, skipHydrateSymbol, {});
  934. }
  935. function shouldHydrate(obj) {
  936. return isVue2 ? (
  937. /* istanbul ignore next */
  938. !skipHydrateMap.has(obj)
  939. ) : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  940. }
  941. var { assign } = Object;
  942. function isComputed(o) {
  943. return !!(isRef(o) && o.effect);
  944. }
  945. function createOptionsStore(id, options, pinia, hot) {
  946. const { state, actions, getters } = options;
  947. const initialState = pinia.state.value[id];
  948. let store;
  949. function setup() {
  950. if (!initialState && !hot) {
  951. if (isVue2) {
  952. set(pinia.state.value, id, state ? state() : {});
  953. } else {
  954. pinia.state.value[id] = state ? state() : {};
  955. }
  956. }
  957. const localState = hot ? (
  958. // use ref() to unwrap refs inside state TODO: check if this is still necessary
  959. toRefs(ref(state ? state() : {}).value)
  960. ) : toRefs(pinia.state.value[id]);
  961. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  962. if (name in localState) {
  963. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  964. }
  965. computedGetters[name] = markRaw(computed(() => {
  966. setActivePinia(pinia);
  967. const store2 = pinia._s.get(id);
  968. if (isVue2 && !store2._r)
  969. return;
  970. return getters[name].call(store2, store2);
  971. }));
  972. return computedGetters;
  973. }, {}));
  974. }
  975. store = createSetupStore(id, setup, options, pinia, hot, true);
  976. return store;
  977. }
  978. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  979. let scope;
  980. const optionsForPlugin = assign({ actions: {} }, options);
  981. if (!pinia._e.active) {
  982. throw new Error("Pinia destroyed");
  983. }
  984. const $subscribeOptions = {
  985. deep: true
  986. // flush: 'post',
  987. };
  988. if (!isVue2) {
  989. $subscribeOptions.onTrigger = (event) => {
  990. if (isListening) {
  991. debuggerEvents = event;
  992. } else if (isListening == false && !store._hotUpdating) {
  993. if (Array.isArray(debuggerEvents)) {
  994. debuggerEvents.push(event);
  995. } else {
  996. console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.");
  997. }
  998. }
  999. };
  1000. }
  1001. let isListening;
  1002. let isSyncListening;
  1003. let subscriptions = [];
  1004. let actionSubscriptions = [];
  1005. let debuggerEvents;
  1006. const initialState = pinia.state.value[$id];
  1007. if (!isOptionsStore && !initialState && !hot) {
  1008. if (isVue2) {
  1009. set(pinia.state.value, $id, {});
  1010. } else {
  1011. pinia.state.value[$id] = {};
  1012. }
  1013. }
  1014. const hotState = ref({});
  1015. let activeListener;
  1016. function $patch(partialStateOrMutator) {
  1017. let subscriptionMutation;
  1018. isListening = isSyncListening = false;
  1019. if (true) {
  1020. debuggerEvents = [];
  1021. }
  1022. if (typeof partialStateOrMutator === "function") {
  1023. partialStateOrMutator(pinia.state.value[$id]);
  1024. subscriptionMutation = {
  1025. type: MutationType.patchFunction,
  1026. storeId: $id,
  1027. events: debuggerEvents
  1028. };
  1029. } else {
  1030. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1031. subscriptionMutation = {
  1032. type: MutationType.patchObject,
  1033. payload: partialStateOrMutator,
  1034. storeId: $id,
  1035. events: debuggerEvents
  1036. };
  1037. }
  1038. const myListenerId = activeListener = Symbol();
  1039. nextTick().then(() => {
  1040. if (activeListener === myListenerId) {
  1041. isListening = true;
  1042. }
  1043. });
  1044. isSyncListening = true;
  1045. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1046. }
  1047. const $reset = isOptionsStore ? function $reset2() {
  1048. const { state } = options;
  1049. const newState = state ? state() : {};
  1050. this.$patch(($state) => {
  1051. assign($state, newState);
  1052. });
  1053. } : (
  1054. /* istanbul ignore next */
  1055. true ? () => {
  1056. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1057. } : noop
  1058. );
  1059. function $dispose() {
  1060. scope.stop();
  1061. subscriptions = [];
  1062. actionSubscriptions = [];
  1063. pinia._s.delete($id);
  1064. }
  1065. function wrapAction(name, action) {
  1066. return function() {
  1067. setActivePinia(pinia);
  1068. const args = Array.from(arguments);
  1069. const afterCallbackList = [];
  1070. const onErrorCallbackList = [];
  1071. function after(callback) {
  1072. afterCallbackList.push(callback);
  1073. }
  1074. function onError(callback) {
  1075. onErrorCallbackList.push(callback);
  1076. }
  1077. triggerSubscriptions(actionSubscriptions, {
  1078. args,
  1079. name,
  1080. store,
  1081. after,
  1082. onError
  1083. });
  1084. let ret;
  1085. try {
  1086. ret = action.apply(this && this.$id === $id ? this : store, args);
  1087. } catch (error) {
  1088. triggerSubscriptions(onErrorCallbackList, error);
  1089. throw error;
  1090. }
  1091. if (ret instanceof Promise) {
  1092. return ret.then((value) => {
  1093. triggerSubscriptions(afterCallbackList, value);
  1094. return value;
  1095. }).catch((error) => {
  1096. triggerSubscriptions(onErrorCallbackList, error);
  1097. return Promise.reject(error);
  1098. });
  1099. }
  1100. triggerSubscriptions(afterCallbackList, ret);
  1101. return ret;
  1102. };
  1103. }
  1104. const _hmrPayload = markRaw({
  1105. actions: {},
  1106. getters: {},
  1107. state: [],
  1108. hotState
  1109. });
  1110. const partialStore = {
  1111. _p: pinia,
  1112. // _s: scope,
  1113. $id,
  1114. $onAction: addSubscription.bind(null, actionSubscriptions),
  1115. $patch,
  1116. $reset,
  1117. $subscribe(callback, options2 = {}) {
  1118. const removeSubscription = addSubscription(subscriptions, callback, options2.detached, () => stopWatcher());
  1119. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1120. if (options2.flush === "sync" ? isSyncListening : isListening) {
  1121. callback({
  1122. storeId: $id,
  1123. type: MutationType.direct,
  1124. events: debuggerEvents
  1125. }, state);
  1126. }
  1127. }, assign({}, $subscribeOptions, options2)));
  1128. return removeSubscription;
  1129. },
  1130. $dispose
  1131. };
  1132. if (isVue2) {
  1133. partialStore._r = false;
  1134. }
  1135. const store = reactive(true ? assign(
  1136. {
  1137. _hmrPayload,
  1138. _customProperties: markRaw(/* @__PURE__ */ new Set())
  1139. // devtools custom properties
  1140. },
  1141. partialStore
  1142. // must be added later
  1143. // setupStore
  1144. ) : partialStore);
  1145. pinia._s.set($id, store);
  1146. const runWithContext = pinia._a && pinia._a.runWithContext || fallbackRunWithContext;
  1147. const setupStore = pinia._e.run(() => {
  1148. scope = effectScope();
  1149. return runWithContext(() => scope.run(setup));
  1150. });
  1151. for (const key in setupStore) {
  1152. const prop = setupStore[key];
  1153. if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
  1154. if (hot) {
  1155. set(hotState.value, key, toRef(setupStore, key));
  1156. } else if (!isOptionsStore) {
  1157. if (initialState && shouldHydrate(prop)) {
  1158. if (isRef(prop)) {
  1159. prop.value = initialState[key];
  1160. } else {
  1161. mergeReactiveObjects(prop, initialState[key]);
  1162. }
  1163. }
  1164. if (isVue2) {
  1165. set(pinia.state.value[$id], key, prop);
  1166. } else {
  1167. pinia.state.value[$id][key] = prop;
  1168. }
  1169. }
  1170. if (true) {
  1171. _hmrPayload.state.push(key);
  1172. }
  1173. } else if (typeof prop === "function") {
  1174. const actionValue = hot ? prop : wrapAction(key, prop);
  1175. if (isVue2) {
  1176. set(setupStore, key, actionValue);
  1177. } else {
  1178. setupStore[key] = actionValue;
  1179. }
  1180. if (true) {
  1181. _hmrPayload.actions[key] = prop;
  1182. }
  1183. optionsForPlugin.actions[key] = prop;
  1184. } else if (true) {
  1185. if (isComputed(prop)) {
  1186. _hmrPayload.getters[key] = isOptionsStore ? (
  1187. // @ts-expect-error
  1188. options.getters[key]
  1189. ) : prop;
  1190. if (IS_CLIENT) {
  1191. const getters = setupStore._getters || // @ts-expect-error: same
  1192. (setupStore._getters = markRaw([]));
  1193. getters.push(key);
  1194. }
  1195. }
  1196. }
  1197. }
  1198. if (isVue2) {
  1199. Object.keys(setupStore).forEach((key) => {
  1200. set(store, key, setupStore[key]);
  1201. });
  1202. } else {
  1203. assign(store, setupStore);
  1204. assign(toRaw(store), setupStore);
  1205. }
  1206. Object.defineProperty(store, "$state", {
  1207. get: () => hot ? hotState.value : pinia.state.value[$id],
  1208. set: (state) => {
  1209. if (hot) {
  1210. throw new Error("cannot set hotState");
  1211. }
  1212. $patch(($state) => {
  1213. assign($state, state);
  1214. });
  1215. }
  1216. });
  1217. if (true) {
  1218. store._hotUpdate = markRaw((newStore) => {
  1219. store._hotUpdating = true;
  1220. newStore._hmrPayload.state.forEach((stateKey) => {
  1221. if (stateKey in store.$state) {
  1222. const newStateTarget = newStore.$state[stateKey];
  1223. const oldStateSource = store.$state[stateKey];
  1224. if (typeof newStateTarget === "object" && isPlainObject(newStateTarget) && isPlainObject(oldStateSource)) {
  1225. patchObject(newStateTarget, oldStateSource);
  1226. } else {
  1227. newStore.$state[stateKey] = oldStateSource;
  1228. }
  1229. }
  1230. set(store, stateKey, toRef(newStore.$state, stateKey));
  1231. });
  1232. Object.keys(store.$state).forEach((stateKey) => {
  1233. if (!(stateKey in newStore.$state)) {
  1234. del(store, stateKey);
  1235. }
  1236. });
  1237. isListening = false;
  1238. isSyncListening = false;
  1239. pinia.state.value[$id] = toRef(newStore._hmrPayload, "hotState");
  1240. isSyncListening = true;
  1241. nextTick().then(() => {
  1242. isListening = true;
  1243. });
  1244. for (const actionName in newStore._hmrPayload.actions) {
  1245. const action = newStore[actionName];
  1246. set(store, actionName, wrapAction(actionName, action));
  1247. }
  1248. for (const getterName in newStore._hmrPayload.getters) {
  1249. const getter = newStore._hmrPayload.getters[getterName];
  1250. const getterValue = isOptionsStore ? (
  1251. // special handling of options api
  1252. computed(() => {
  1253. setActivePinia(pinia);
  1254. return getter.call(store, store);
  1255. })
  1256. ) : getter;
  1257. set(store, getterName, getterValue);
  1258. }
  1259. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1260. if (!(key in newStore._hmrPayload.getters)) {
  1261. del(store, key);
  1262. }
  1263. });
  1264. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1265. if (!(key in newStore._hmrPayload.actions)) {
  1266. del(store, key);
  1267. }
  1268. });
  1269. store._hmrPayload = newStore._hmrPayload;
  1270. store._getters = newStore._getters;
  1271. store._hotUpdating = false;
  1272. });
  1273. }
  1274. if (USE_DEVTOOLS) {
  1275. const nonEnumerable = {
  1276. writable: true,
  1277. configurable: true,
  1278. // avoid warning on devtools trying to display this property
  1279. enumerable: false
  1280. };
  1281. ["_p", "_hmrPayload", "_getters", "_customProperties"].forEach((p) => {
  1282. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1283. });
  1284. }
  1285. if (isVue2) {
  1286. store._r = true;
  1287. }
  1288. pinia._p.forEach((extender) => {
  1289. if (USE_DEVTOOLS) {
  1290. const extensions = scope.run(() => extender({
  1291. store,
  1292. app: pinia._a,
  1293. pinia,
  1294. options: optionsForPlugin
  1295. }));
  1296. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1297. assign(store, extensions);
  1298. } else {
  1299. assign(store, scope.run(() => extender({
  1300. store,
  1301. app: pinia._a,
  1302. pinia,
  1303. options: optionsForPlugin
  1304. })));
  1305. }
  1306. });
  1307. if (store.$state && typeof store.$state === "object" && typeof store.$state.constructor === "function" && !store.$state.constructor.toString().includes("[native code]")) {
  1308. console.warn(`[🍍]: The "state" must be a plain object. It cannot be
  1309. state: () => new MyClass()
  1310. Found in store "${store.$id}".`);
  1311. }
  1312. if (initialState && isOptionsStore && options.hydrate) {
  1313. options.hydrate(store.$state, initialState);
  1314. }
  1315. isListening = true;
  1316. isSyncListening = true;
  1317. return store;
  1318. }
  1319. function defineStore(idOrOptions, setup, setupOptions) {
  1320. let id;
  1321. let options;
  1322. const isSetupStore = typeof setup === "function";
  1323. if (typeof idOrOptions === "string") {
  1324. id = idOrOptions;
  1325. options = isSetupStore ? setupOptions : setup;
  1326. } else {
  1327. options = idOrOptions;
  1328. id = idOrOptions.id;
  1329. if (typeof id !== "string") {
  1330. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1331. }
  1332. }
  1333. function useStore(pinia, hot) {
  1334. const hasContext = hasInjectionContext();
  1335. pinia = // in test mode, ignore the argument provided as we can always retrieve a
  1336. // pinia instance with getActivePinia()
  1337. (false ? null : pinia) || (hasContext ? inject(piniaSymbol, null) : null);
  1338. if (pinia)
  1339. setActivePinia(pinia);
  1340. if (!activePinia) {
  1341. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
  1342. const pinia = createPinia()
  1343. app.use(pinia)
  1344. This will fail in production.`);
  1345. }
  1346. pinia = activePinia;
  1347. if (!pinia._s.has(id)) {
  1348. if (isSetupStore) {
  1349. createSetupStore(id, setup, options, pinia);
  1350. } else {
  1351. createOptionsStore(id, options, pinia);
  1352. }
  1353. if (true) {
  1354. useStore._pinia = pinia;
  1355. }
  1356. }
  1357. const store = pinia._s.get(id);
  1358. if (hot) {
  1359. const hotId = "__hot:" + id;
  1360. const newStore = isSetupStore ? createSetupStore(hotId, setup, options, pinia, true) : createOptionsStore(hotId, assign({}, options), pinia, true);
  1361. hot._hotUpdate(newStore);
  1362. delete pinia.state.value[hotId];
  1363. pinia._s.delete(hotId);
  1364. }
  1365. if (IS_CLIENT) {
  1366. const currentInstance = getCurrentInstance();
  1367. if (currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement
  1368. !hot) {
  1369. const vm = currentInstance.proxy;
  1370. const cache = "_pStores" in vm ? vm._pStores : vm._pStores = {};
  1371. cache[id] = store;
  1372. }
  1373. }
  1374. return store;
  1375. }
  1376. useStore.$id = id;
  1377. return useStore;
  1378. }
  1379. var mapStoreSuffix = "Store";
  1380. function setMapStoreSuffix(suffix) {
  1381. mapStoreSuffix = suffix;
  1382. }
  1383. function mapStores(...stores) {
  1384. if (Array.isArray(stores[0])) {
  1385. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:
  1386. Replace
  1387. mapStores([useAuthStore, useCartStore])
  1388. with
  1389. mapStores(useAuthStore, useCartStore)
  1390. This will fail in production if not fixed.`);
  1391. stores = stores[0];
  1392. }
  1393. return stores.reduce((reduced, useStore) => {
  1394. reduced[useStore.$id + mapStoreSuffix] = function() {
  1395. return useStore(this.$pinia);
  1396. };
  1397. return reduced;
  1398. }, {});
  1399. }
  1400. function mapState(useStore, keysOrMapper) {
  1401. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1402. reduced[key] = function() {
  1403. return useStore(this.$pinia)[key];
  1404. };
  1405. return reduced;
  1406. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1407. reduced[key] = function() {
  1408. const store = useStore(this.$pinia);
  1409. const storeKey = keysOrMapper[key];
  1410. return typeof storeKey === "function" ? storeKey.call(this, store) : store[storeKey];
  1411. };
  1412. return reduced;
  1413. }, {});
  1414. }
  1415. var mapGetters = mapState;
  1416. function mapActions(useStore, keysOrMapper) {
  1417. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1418. reduced[key] = function(...args) {
  1419. return useStore(this.$pinia)[key](...args);
  1420. };
  1421. return reduced;
  1422. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1423. reduced[key] = function(...args) {
  1424. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1425. };
  1426. return reduced;
  1427. }, {});
  1428. }
  1429. function mapWritableState(useStore, keysOrMapper) {
  1430. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1431. reduced[key] = {
  1432. get() {
  1433. return useStore(this.$pinia)[key];
  1434. },
  1435. set(value) {
  1436. return useStore(this.$pinia)[key] = value;
  1437. }
  1438. };
  1439. return reduced;
  1440. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1441. reduced[key] = {
  1442. get() {
  1443. return useStore(this.$pinia)[keysOrMapper[key]];
  1444. },
  1445. set(value) {
  1446. return useStore(this.$pinia)[keysOrMapper[key]] = value;
  1447. }
  1448. };
  1449. return reduced;
  1450. }, {});
  1451. }
  1452. function storeToRefs(store) {
  1453. if (isVue2) {
  1454. return toRefs(store);
  1455. } else {
  1456. store = toRaw(store);
  1457. const refs = {};
  1458. for (const key in store) {
  1459. const value = store[key];
  1460. if (isRef(value) || isReactive(value)) {
  1461. refs[key] = // ---
  1462. toRef(store, key);
  1463. }
  1464. }
  1465. return refs;
  1466. }
  1467. }
  1468. var PiniaVuePlugin = function(_Vue) {
  1469. _Vue.mixin({
  1470. beforeCreate() {
  1471. const options = this.$options;
  1472. if (options.pinia) {
  1473. const pinia = options.pinia;
  1474. if (!this._provided) {
  1475. const provideCache = {};
  1476. Object.defineProperty(this, "_provided", {
  1477. get: () => provideCache,
  1478. set: (v) => Object.assign(provideCache, v)
  1479. });
  1480. }
  1481. this._provided[piniaSymbol] = pinia;
  1482. if (!this.$pinia) {
  1483. this.$pinia = pinia;
  1484. }
  1485. pinia._a = this;
  1486. if (IS_CLIENT) {
  1487. setActivePinia(pinia);
  1488. }
  1489. if (USE_DEVTOOLS) {
  1490. registerPiniaDevtools(pinia._a, pinia);
  1491. }
  1492. } else if (!this.$pinia && options.parent && options.parent.$pinia) {
  1493. this.$pinia = options.parent.$pinia;
  1494. }
  1495. },
  1496. destroyed() {
  1497. delete this._pStores;
  1498. }
  1499. });
  1500. };
  1501. export {
  1502. MutationType,
  1503. PiniaVuePlugin,
  1504. acceptHMRUpdate,
  1505. createPinia,
  1506. defineStore,
  1507. getActivePinia,
  1508. mapActions,
  1509. mapGetters,
  1510. mapState,
  1511. mapStores,
  1512. mapWritableState,
  1513. setActivePinia,
  1514. setMapStoreSuffix,
  1515. skipHydrate,
  1516. storeToRefs
  1517. };
  1518. /*! Bundled license information:
  1519. pinia/dist/pinia.mjs:
  1520. (*!
  1521. * pinia v2.1.3
  1522. * (c) 2023 Eduardo San Martin Morote
  1523. * @license MIT
  1524. *)
  1525. */
  1526. //# sourceMappingURL=pinia.js.map