pinia.cjs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  1. /*!
  2. * pinia v3.0.4
  3. * (c) 2025 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. 'use strict';
  7. var vue = require('vue');
  8. var devtoolsApi = require('@vue/devtools-api');
  9. const IS_CLIENT = typeof window !== 'undefined';
  10. /**
  11. * setActivePinia must be called to handle SSR at the top of functions like
  12. * `fetch`, `setup`, `serverPrefetch` and others
  13. */
  14. let activePinia;
  15. /**
  16. * Sets or unsets the active pinia. Used in SSR and internally when calling
  17. * actions and getters
  18. *
  19. * @param pinia - Pinia instance
  20. */
  21. // @ts-expect-error: cannot constrain the type of the return
  22. const setActivePinia = (pinia) => (activePinia = pinia);
  23. /**
  24. * Get the currently active pinia if there is any.
  25. */
  26. const getActivePinia = (process.env.NODE_ENV !== 'production')
  27. ? () => {
  28. const pinia = vue.hasInjectionContext() && vue.inject(piniaSymbol);
  29. if (!pinia && !IS_CLIENT) {
  30. console.error(`[🍍]: Pinia instance not found in context. This falls back to the global activePinia which exposes you to cross-request pollution on the server. Most of the time, it means you are calling "useStore()" in the wrong place.\n` +
  31. `Read https://vuejs.org/guide/reusability/composables.html to learn more`);
  32. }
  33. return pinia || activePinia;
  34. }
  35. : () => (vue.hasInjectionContext() && vue.inject(piniaSymbol)) || activePinia;
  36. const piniaSymbol = ((process.env.NODE_ENV !== 'production') ? Symbol('pinia') : /* istanbul ignore next */ Symbol());
  37. function isPlainObject(
  38. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  39. o) {
  40. return (o &&
  41. typeof o === 'object' &&
  42. Object.prototype.toString.call(o) === '[object Object]' &&
  43. typeof o.toJSON !== 'function');
  44. }
  45. // type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> }
  46. // TODO: can we change these to numbers?
  47. /**
  48. * Possible types for SubscriptionCallback
  49. */
  50. exports.MutationType = void 0;
  51. (function (MutationType) {
  52. /**
  53. * Direct mutation of the state:
  54. *
  55. * - `store.name = 'new name'`
  56. * - `store.$state.name = 'new name'`
  57. * - `store.list.push('new item')`
  58. */
  59. MutationType["direct"] = "direct";
  60. /**
  61. * Mutated the state with `$patch` and an object
  62. *
  63. * - `store.$patch({ name: 'newName' })`
  64. */
  65. MutationType["patchObject"] = "patch object";
  66. /**
  67. * Mutated the state with `$patch` and a function
  68. *
  69. * - `store.$patch(state => state.name = 'newName')`
  70. */
  71. MutationType["patchFunction"] = "patch function";
  72. // maybe reset? for $state = {} and $reset
  73. })(exports.MutationType || (exports.MutationType = {}));
  74. /*
  75. * FileSaver.js A saveAs() FileSaver implementation.
  76. *
  77. * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin
  78. * Morote.
  79. *
  80. * License : MIT
  81. */
  82. // The one and only way of getting global scope in all environments
  83. // https://stackoverflow.com/q/3277182/1008999
  84. const _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window
  85. ? window
  86. : typeof self === 'object' && self.self === self
  87. ? self
  88. : typeof global === 'object' && global.global === global
  89. ? global
  90. : typeof globalThis === 'object'
  91. ? globalThis
  92. : { HTMLElement: null })();
  93. function bom(blob, { autoBom = false } = {}) {
  94. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  95. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  96. if (autoBom &&
  97. /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  98. return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
  99. }
  100. return blob;
  101. }
  102. function download(url, name, opts) {
  103. const xhr = new XMLHttpRequest();
  104. xhr.open('GET', url);
  105. xhr.responseType = 'blob';
  106. xhr.onload = function () {
  107. saveAs(xhr.response, name, opts);
  108. };
  109. xhr.onerror = function () {
  110. console.error('could not download file');
  111. };
  112. xhr.send();
  113. }
  114. function corsEnabled(url) {
  115. const xhr = new XMLHttpRequest();
  116. // use sync to avoid popup blocker
  117. xhr.open('HEAD', url, false);
  118. try {
  119. xhr.send();
  120. }
  121. catch (e) { }
  122. return xhr.status >= 200 && xhr.status <= 299;
  123. }
  124. // `a.click()` doesn't work for all browsers (#465)
  125. function click(node) {
  126. try {
  127. node.dispatchEvent(new MouseEvent('click'));
  128. }
  129. catch (e) {
  130. const evt = new MouseEvent('click', {
  131. bubbles: true,
  132. cancelable: true,
  133. view: window,
  134. detail: 0,
  135. screenX: 80,
  136. screenY: 20,
  137. clientX: 80,
  138. clientY: 20,
  139. ctrlKey: false,
  140. altKey: false,
  141. shiftKey: false,
  142. metaKey: false,
  143. button: 0,
  144. relatedTarget: null,
  145. });
  146. node.dispatchEvent(evt);
  147. }
  148. }
  149. const _navigator = typeof navigator === 'object' ? navigator : { userAgent: '' };
  150. // Detect WebView inside a native macOS app by ruling out all browsers
  151. // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
  152. // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
  153. const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) &&
  154. /AppleWebKit/.test(_navigator.userAgent) &&
  155. !/Safari/.test(_navigator.userAgent))();
  156. const saveAs = !IS_CLIENT
  157. ? () => { } // noop
  158. : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  159. typeof HTMLAnchorElement !== 'undefined' &&
  160. 'download' in HTMLAnchorElement.prototype &&
  161. !isMacOSWebView
  162. ? downloadSaveAs
  163. : // Use msSaveOrOpenBlob as a second approach
  164. 'msSaveOrOpenBlob' in _navigator
  165. ? msSaveAs
  166. : // Fallback to using FileReader and a popup
  167. fileSaverSaveAs;
  168. function downloadSaveAs(blob, name = 'download', opts) {
  169. const a = document.createElement('a');
  170. a.download = name;
  171. a.rel = 'noopener'; // tabnabbing
  172. // TODO: detect chrome extensions & packaged apps
  173. // a.target = '_blank'
  174. if (typeof blob === 'string') {
  175. // Support regular links
  176. a.href = blob;
  177. if (a.origin !== location.origin) {
  178. if (corsEnabled(a.href)) {
  179. download(blob, name, opts);
  180. }
  181. else {
  182. a.target = '_blank';
  183. click(a);
  184. }
  185. }
  186. else {
  187. click(a);
  188. }
  189. }
  190. else {
  191. // Support blobs
  192. a.href = URL.createObjectURL(blob);
  193. setTimeout(function () {
  194. URL.revokeObjectURL(a.href);
  195. }, 4e4); // 40s
  196. setTimeout(function () {
  197. click(a);
  198. }, 0);
  199. }
  200. }
  201. function msSaveAs(blob, name = 'download', opts) {
  202. if (typeof blob === 'string') {
  203. if (corsEnabled(blob)) {
  204. download(blob, name, opts);
  205. }
  206. else {
  207. const a = document.createElement('a');
  208. a.href = blob;
  209. a.target = '_blank';
  210. setTimeout(function () {
  211. click(a);
  212. });
  213. }
  214. }
  215. else {
  216. // @ts-ignore: works on windows
  217. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  218. }
  219. }
  220. function fileSaverSaveAs(blob, name, opts, popup) {
  221. // Open a popup immediately do go around popup blocker
  222. // Mostly only available on user interaction and the fileReader is async so...
  223. popup = popup || open('', '_blank');
  224. if (popup) {
  225. popup.document.title = popup.document.body.innerText = 'downloading...';
  226. }
  227. if (typeof blob === 'string')
  228. return download(blob, name, opts);
  229. const force = blob.type === 'application/octet-stream';
  230. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global;
  231. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  232. if ((isChromeIOS || (force && isSafari) || isMacOSWebView) &&
  233. typeof FileReader !== 'undefined') {
  234. // Safari doesn't allow downloading of blob URLs
  235. const reader = new FileReader();
  236. reader.onloadend = function () {
  237. let url = reader.result;
  238. if (typeof url !== 'string') {
  239. popup = null;
  240. throw new Error('Wrong reader.result type');
  241. }
  242. url = isChromeIOS
  243. ? url
  244. : url.replace(/^data:[^;]*;/, 'data:attachment/file;');
  245. if (popup) {
  246. popup.location.href = url;
  247. }
  248. else {
  249. location.assign(url);
  250. }
  251. popup = null; // reverse-tabnabbing #460
  252. };
  253. reader.readAsDataURL(blob);
  254. }
  255. else {
  256. const url = URL.createObjectURL(blob);
  257. if (popup)
  258. popup.location.assign(url);
  259. else
  260. location.href = url;
  261. popup = null; // reverse-tabnabbing #460
  262. setTimeout(function () {
  263. URL.revokeObjectURL(url);
  264. }, 4e4); // 40s
  265. }
  266. }
  267. /**
  268. * Shows a toast or console.log
  269. *
  270. * @param message - message to log
  271. * @param type - different color of the tooltip
  272. */
  273. function toastMessage(message, type) {
  274. const piniaMessage = '🍍 ' + message;
  275. if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') {
  276. // No longer available :(
  277. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  278. }
  279. else if (type === 'error') {
  280. console.error(piniaMessage);
  281. }
  282. else if (type === 'warn') {
  283. console.warn(piniaMessage);
  284. }
  285. else {
  286. console.log(piniaMessage);
  287. }
  288. }
  289. function isPinia(o) {
  290. return '_a' in o && 'install' in o;
  291. }
  292. /**
  293. * This file contain devtools actions, they are not Pinia actions.
  294. */
  295. // ---
  296. function checkClipboardAccess() {
  297. if (!('clipboard' in navigator)) {
  298. toastMessage(`Your browser doesn't support the Clipboard API`, 'error');
  299. return true;
  300. }
  301. }
  302. function checkNotFocusedError(error) {
  303. if (error instanceof Error &&
  304. error.message.toLowerCase().includes('document is not focused')) {
  305. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn');
  306. return true;
  307. }
  308. return false;
  309. }
  310. async function actionGlobalCopyState(pinia) {
  311. if (checkClipboardAccess())
  312. return;
  313. try {
  314. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  315. toastMessage('Global state copied to clipboard.');
  316. }
  317. catch (error) {
  318. if (checkNotFocusedError(error))
  319. return;
  320. toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error');
  321. console.error(error);
  322. }
  323. }
  324. async function actionGlobalPasteState(pinia) {
  325. if (checkClipboardAccess())
  326. return;
  327. try {
  328. loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));
  329. toastMessage('Global state pasted from clipboard.');
  330. }
  331. catch (error) {
  332. if (checkNotFocusedError(error))
  333. return;
  334. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error');
  335. console.error(error);
  336. }
  337. }
  338. async function actionGlobalSaveState(pinia) {
  339. try {
  340. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  341. type: 'text/plain;charset=utf-8',
  342. }), 'pinia-state.json');
  343. }
  344. catch (error) {
  345. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
  346. console.error(error);
  347. }
  348. }
  349. let fileInput;
  350. function getFileOpener() {
  351. if (!fileInput) {
  352. fileInput = document.createElement('input');
  353. fileInput.type = 'file';
  354. fileInput.accept = '.json';
  355. }
  356. function openFile() {
  357. return new Promise((resolve, reject) => {
  358. fileInput.onchange = async () => {
  359. const files = fileInput.files;
  360. if (!files)
  361. return resolve(null);
  362. const file = files.item(0);
  363. if (!file)
  364. return resolve(null);
  365. return resolve({ text: await file.text(), file });
  366. };
  367. // @ts-ignore: TODO: changed from 4.3 to 4.4
  368. fileInput.oncancel = () => resolve(null);
  369. fileInput.onerror = reject;
  370. fileInput.click();
  371. });
  372. }
  373. return openFile;
  374. }
  375. async function actionGlobalOpenStateFile(pinia) {
  376. try {
  377. const open = getFileOpener();
  378. const result = await open();
  379. if (!result)
  380. return;
  381. const { text, file } = result;
  382. loadStoresState(pinia, JSON.parse(text));
  383. toastMessage(`Global state imported from "${file.name}".`);
  384. }
  385. catch (error) {
  386. toastMessage(`Failed to import the state from JSON. Check the console for more details.`, 'error');
  387. console.error(error);
  388. }
  389. }
  390. function loadStoresState(pinia, state) {
  391. for (const key in state) {
  392. const storeState = pinia.state.value[key];
  393. // store is already instantiated, patch it
  394. if (storeState) {
  395. Object.assign(storeState, state[key]);
  396. }
  397. else {
  398. // store is not instantiated, set the initial state
  399. pinia.state.value[key] = state[key];
  400. }
  401. }
  402. }
  403. function formatDisplay(display) {
  404. return {
  405. _custom: {
  406. display,
  407. },
  408. };
  409. }
  410. const PINIA_ROOT_LABEL = '🍍 Pinia (root)';
  411. const PINIA_ROOT_ID = '_root';
  412. function formatStoreForInspectorTree(store) {
  413. return isPinia(store)
  414. ? {
  415. id: PINIA_ROOT_ID,
  416. label: PINIA_ROOT_LABEL,
  417. }
  418. : {
  419. id: store.$id,
  420. label: store.$id,
  421. };
  422. }
  423. function formatStoreForInspectorState(store) {
  424. if (isPinia(store)) {
  425. const storeNames = Array.from(store._s.keys());
  426. const storeMap = store._s;
  427. const state = {
  428. state: storeNames.map((storeId) => ({
  429. editable: true,
  430. key: storeId,
  431. value: store.state.value[storeId],
  432. })),
  433. getters: storeNames
  434. .filter((id) => storeMap.get(id)._getters)
  435. .map((id) => {
  436. const store = storeMap.get(id);
  437. return {
  438. editable: false,
  439. key: id,
  440. value: store._getters.reduce((getters, key) => {
  441. getters[key] = store[key];
  442. return getters;
  443. }, {}),
  444. };
  445. }),
  446. };
  447. return state;
  448. }
  449. const state = {
  450. state: Object.keys(store.$state).map((key) => ({
  451. editable: true,
  452. key,
  453. value: store.$state[key],
  454. })),
  455. };
  456. // avoid adding empty getters
  457. if (store._getters && store._getters.length) {
  458. state.getters = store._getters.map((getterName) => ({
  459. editable: false,
  460. key: getterName,
  461. value: store[getterName],
  462. }));
  463. }
  464. if (store._customProperties.size) {
  465. state.customProperties = Array.from(store._customProperties).map((key) => ({
  466. editable: true,
  467. key,
  468. value: store[key],
  469. }));
  470. }
  471. return state;
  472. }
  473. function formatEventData(events) {
  474. if (!events)
  475. return {};
  476. if (Array.isArray(events)) {
  477. // TODO: handle add and delete for arrays and objects
  478. return events.reduce((data, event) => {
  479. data.keys.push(event.key);
  480. data.operations.push(event.type);
  481. data.oldValue[event.key] = event.oldValue;
  482. data.newValue[event.key] = event.newValue;
  483. return data;
  484. }, {
  485. oldValue: {},
  486. keys: [],
  487. operations: [],
  488. newValue: {},
  489. });
  490. }
  491. else {
  492. return {
  493. operation: formatDisplay(events.type),
  494. key: formatDisplay(events.key),
  495. oldValue: events.oldValue,
  496. newValue: events.newValue,
  497. };
  498. }
  499. }
  500. function formatMutationType(type) {
  501. switch (type) {
  502. case exports.MutationType.direct:
  503. return 'mutation';
  504. case exports.MutationType.patchFunction:
  505. return '$patch';
  506. case exports.MutationType.patchObject:
  507. return '$patch';
  508. default:
  509. return 'unknown';
  510. }
  511. }
  512. // timeline can be paused when directly changing the state
  513. let isTimelineActive = true;
  514. const componentStateTypes = [];
  515. const MUTATIONS_LAYER_ID = 'pinia:mutations';
  516. const INSPECTOR_ID = 'pinia';
  517. const { assign: assign$1 } = Object;
  518. /**
  519. * Gets the displayed name of a store in devtools
  520. *
  521. * @param id - id of the store
  522. * @returns a formatted string
  523. */
  524. const getStoreType = (id) => '🍍 ' + id;
  525. /**
  526. * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab
  527. * as soon as it is added to the application.
  528. *
  529. * @param app - Vue application
  530. * @param pinia - pinia instance
  531. */
  532. function registerPiniaDevtools(app, pinia) {
  533. devtoolsApi.setupDevtoolsPlugin({
  534. id: 'dev.esm.pinia',
  535. label: 'Pinia 🍍',
  536. logo: 'https://pinia.vuejs.org/logo.svg',
  537. packageName: 'pinia',
  538. homepage: 'https://pinia.vuejs.org',
  539. componentStateTypes,
  540. app,
  541. }, (api) => {
  542. if (typeof api.now !== 'function') {
  543. 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.');
  544. }
  545. api.addTimelineLayer({
  546. id: MUTATIONS_LAYER_ID,
  547. label: `Pinia 🍍`,
  548. color: 0xe5df88,
  549. });
  550. api.addInspector({
  551. id: INSPECTOR_ID,
  552. label: 'Pinia 🍍',
  553. icon: 'storage',
  554. treeFilterPlaceholder: 'Search stores',
  555. actions: [
  556. {
  557. icon: 'content_copy',
  558. action: () => {
  559. actionGlobalCopyState(pinia);
  560. },
  561. tooltip: 'Serialize and copy the state',
  562. },
  563. {
  564. icon: 'content_paste',
  565. action: async () => {
  566. await actionGlobalPasteState(pinia);
  567. api.sendInspectorTree(INSPECTOR_ID);
  568. api.sendInspectorState(INSPECTOR_ID);
  569. },
  570. tooltip: 'Replace the state with the content of your clipboard',
  571. },
  572. {
  573. icon: 'save',
  574. action: () => {
  575. actionGlobalSaveState(pinia);
  576. },
  577. tooltip: 'Save the state as a JSON file',
  578. },
  579. {
  580. icon: 'folder_open',
  581. action: async () => {
  582. await actionGlobalOpenStateFile(pinia);
  583. api.sendInspectorTree(INSPECTOR_ID);
  584. api.sendInspectorState(INSPECTOR_ID);
  585. },
  586. tooltip: 'Import the state from a JSON file',
  587. },
  588. ],
  589. nodeActions: [
  590. {
  591. icon: 'restore',
  592. tooltip: 'Reset the state (with "$reset")',
  593. action: (nodeId) => {
  594. const store = pinia._s.get(nodeId);
  595. if (!store) {
  596. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, 'warn');
  597. }
  598. else if (typeof store.$reset !== 'function') {
  599. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, 'warn');
  600. }
  601. else {
  602. store.$reset();
  603. toastMessage(`Store "${nodeId}" reset.`);
  604. }
  605. },
  606. },
  607. ],
  608. });
  609. api.on.inspectComponent((payload) => {
  610. const proxy = (payload.componentInstance &&
  611. payload.componentInstance.proxy);
  612. if (proxy && proxy._pStores) {
  613. const piniaStores = payload.componentInstance.proxy._pStores;
  614. Object.values(piniaStores).forEach((store) => {
  615. payload.instanceData.state.push({
  616. type: getStoreType(store.$id),
  617. key: 'state',
  618. editable: true,
  619. value: store._isOptionsAPI
  620. ? {
  621. _custom: {
  622. value: vue.toRaw(store.$state),
  623. actions: [
  624. {
  625. icon: 'restore',
  626. tooltip: 'Reset the state of this store',
  627. action: () => store.$reset(),
  628. },
  629. ],
  630. },
  631. }
  632. : // NOTE: workaround to unwrap transferred refs
  633. Object.keys(store.$state).reduce((state, key) => {
  634. state[key] = store.$state[key];
  635. return state;
  636. }, {}),
  637. });
  638. if (store._getters && store._getters.length) {
  639. payload.instanceData.state.push({
  640. type: getStoreType(store.$id),
  641. key: 'getters',
  642. editable: false,
  643. value: store._getters.reduce((getters, key) => {
  644. try {
  645. getters[key] = store[key];
  646. }
  647. catch (error) {
  648. // @ts-expect-error: we just want to show it in devtools
  649. getters[key] = error;
  650. }
  651. return getters;
  652. }, {}),
  653. });
  654. }
  655. });
  656. }
  657. });
  658. api.on.getInspectorTree((payload) => {
  659. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  660. let stores = [pinia];
  661. stores = stores.concat(Array.from(pinia._s.values()));
  662. payload.rootNodes = (payload.filter
  663. ? stores.filter((store) => '$id' in store
  664. ? store.$id
  665. .toLowerCase()
  666. .includes(payload.filter.toLowerCase())
  667. : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase()))
  668. : stores).map(formatStoreForInspectorTree);
  669. }
  670. });
  671. // Expose pinia instance as $pinia to window
  672. globalThis.$pinia = pinia;
  673. api.on.getInspectorState((payload) => {
  674. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  675. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  676. ? pinia
  677. : pinia._s.get(payload.nodeId);
  678. if (!inspectedStore) {
  679. // this could be the selected store restored for a different project
  680. // so it's better not to say anything here
  681. return;
  682. }
  683. if (inspectedStore) {
  684. // Expose selected store as $store to window
  685. if (payload.nodeId !== PINIA_ROOT_ID)
  686. globalThis.$store = vue.toRaw(inspectedStore);
  687. payload.state = formatStoreForInspectorState(inspectedStore);
  688. }
  689. }
  690. });
  691. api.on.editInspectorState((payload) => {
  692. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  693. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  694. ? pinia
  695. : pinia._s.get(payload.nodeId);
  696. if (!inspectedStore) {
  697. return toastMessage(`store "${payload.nodeId}" not found`, 'error');
  698. }
  699. const { path } = payload;
  700. if (!isPinia(inspectedStore)) {
  701. // access only the state
  702. if (path.length !== 1 ||
  703. !inspectedStore._customProperties.has(path[0]) ||
  704. path[0] in inspectedStore.$state) {
  705. path.unshift('$state');
  706. }
  707. }
  708. else {
  709. // Root access, we can omit the `.value` because the devtools API does it for us
  710. path.unshift('state');
  711. }
  712. isTimelineActive = false;
  713. payload.set(inspectedStore, path, payload.state.value);
  714. isTimelineActive = true;
  715. }
  716. });
  717. api.on.editComponentState((payload) => {
  718. if (payload.type.startsWith('🍍')) {
  719. const storeId = payload.type.replace(/^🍍\s*/, '');
  720. const store = pinia._s.get(storeId);
  721. if (!store) {
  722. return toastMessage(`store "${storeId}" not found`, 'error');
  723. }
  724. const { path } = payload;
  725. if (path[0] !== 'state') {
  726. return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`);
  727. }
  728. // rewrite the first entry to be able to directly set the state as
  729. // well as any other path
  730. path[0] = '$state';
  731. isTimelineActive = false;
  732. payload.set(store, path, payload.state.value);
  733. isTimelineActive = true;
  734. }
  735. });
  736. });
  737. }
  738. function addStoreToDevtools(app, store) {
  739. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  740. componentStateTypes.push(getStoreType(store.$id));
  741. }
  742. devtoolsApi.setupDevtoolsPlugin({
  743. id: 'dev.esm.pinia',
  744. label: 'Pinia 🍍',
  745. logo: 'https://pinia.vuejs.org/logo.svg',
  746. packageName: 'pinia',
  747. homepage: 'https://pinia.vuejs.org',
  748. componentStateTypes,
  749. app,
  750. settings: {
  751. logStoreChanges: {
  752. label: 'Notify about new/deleted stores',
  753. type: 'boolean',
  754. defaultValue: true,
  755. },
  756. // useEmojis: {
  757. // label: 'Use emojis in messages ⚡️',
  758. // type: 'boolean',
  759. // defaultValue: true,
  760. // },
  761. },
  762. }, (api) => {
  763. // gracefully handle errors
  764. const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;
  765. store.$onAction(({ after, onError, name, args }) => {
  766. const groupId = runningActionId++;
  767. api.addTimelineEvent({
  768. layerId: MUTATIONS_LAYER_ID,
  769. event: {
  770. time: now(),
  771. title: '🛫 ' + name,
  772. subtitle: 'start',
  773. data: {
  774. store: formatDisplay(store.$id),
  775. action: formatDisplay(name),
  776. args,
  777. },
  778. groupId,
  779. },
  780. });
  781. after((result) => {
  782. activeAction = undefined;
  783. api.addTimelineEvent({
  784. layerId: MUTATIONS_LAYER_ID,
  785. event: {
  786. time: now(),
  787. title: '🛬 ' + name,
  788. subtitle: 'end',
  789. data: {
  790. store: formatDisplay(store.$id),
  791. action: formatDisplay(name),
  792. args,
  793. result,
  794. },
  795. groupId,
  796. },
  797. });
  798. });
  799. onError((error) => {
  800. activeAction = undefined;
  801. api.addTimelineEvent({
  802. layerId: MUTATIONS_LAYER_ID,
  803. event: {
  804. time: now(),
  805. logType: 'error',
  806. title: '💥 ' + name,
  807. subtitle: 'end',
  808. data: {
  809. store: formatDisplay(store.$id),
  810. action: formatDisplay(name),
  811. args,
  812. error,
  813. },
  814. groupId,
  815. },
  816. });
  817. });
  818. }, true);
  819. store._customProperties.forEach((name) => {
  820. vue.watch(() => vue.unref(store[name]), (newValue, oldValue) => {
  821. api.notifyComponentUpdate();
  822. api.sendInspectorState(INSPECTOR_ID);
  823. if (isTimelineActive) {
  824. api.addTimelineEvent({
  825. layerId: MUTATIONS_LAYER_ID,
  826. event: {
  827. time: now(),
  828. title: 'Change',
  829. subtitle: name,
  830. data: {
  831. newValue,
  832. oldValue,
  833. },
  834. groupId: activeAction,
  835. },
  836. });
  837. }
  838. }, { deep: true });
  839. });
  840. store.$subscribe(({ events, type }, state) => {
  841. api.notifyComponentUpdate();
  842. api.sendInspectorState(INSPECTOR_ID);
  843. if (!isTimelineActive)
  844. return;
  845. // rootStore.state[store.id] = state
  846. const eventData = {
  847. time: now(),
  848. title: formatMutationType(type),
  849. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  850. groupId: activeAction,
  851. };
  852. if (type === exports.MutationType.patchFunction) {
  853. eventData.subtitle = '⤵️';
  854. }
  855. else if (type === exports.MutationType.patchObject) {
  856. eventData.subtitle = '🧩';
  857. }
  858. else if (events && !Array.isArray(events)) {
  859. eventData.subtitle = events.type;
  860. }
  861. if (events) {
  862. eventData.data['rawEvent(s)'] = {
  863. _custom: {
  864. display: 'DebuggerEvent',
  865. type: 'object',
  866. tooltip: 'raw DebuggerEvent[]',
  867. value: events,
  868. },
  869. };
  870. }
  871. api.addTimelineEvent({
  872. layerId: MUTATIONS_LAYER_ID,
  873. event: eventData,
  874. });
  875. }, { detached: true, flush: 'sync' });
  876. const hotUpdate = store._hotUpdate;
  877. store._hotUpdate = vue.markRaw((newStore) => {
  878. hotUpdate(newStore);
  879. api.addTimelineEvent({
  880. layerId: MUTATIONS_LAYER_ID,
  881. event: {
  882. time: now(),
  883. title: '🔥 ' + store.$id,
  884. subtitle: 'HMR update',
  885. data: {
  886. store: formatDisplay(store.$id),
  887. info: formatDisplay(`HMR update`),
  888. },
  889. },
  890. });
  891. // update the devtools too
  892. api.notifyComponentUpdate();
  893. api.sendInspectorTree(INSPECTOR_ID);
  894. api.sendInspectorState(INSPECTOR_ID);
  895. });
  896. const { $dispose } = store;
  897. store.$dispose = () => {
  898. $dispose();
  899. api.notifyComponentUpdate();
  900. api.sendInspectorTree(INSPECTOR_ID);
  901. api.sendInspectorState(INSPECTOR_ID);
  902. api.getSettings().logStoreChanges &&
  903. toastMessage(`Disposed "${store.$id}" store 🗑`);
  904. };
  905. // trigger an update so it can display new registered stores
  906. api.notifyComponentUpdate();
  907. api.sendInspectorTree(INSPECTOR_ID);
  908. api.sendInspectorState(INSPECTOR_ID);
  909. api.getSettings().logStoreChanges &&
  910. toastMessage(`"${store.$id}" store installed 🆕`);
  911. });
  912. }
  913. let runningActionId = 0;
  914. let activeAction;
  915. /**
  916. * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the
  917. * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state
  918. * mutation to the action.
  919. *
  920. * @param store - store to patch
  921. * @param actionNames - list of actionst to patch
  922. */
  923. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  924. // original actions of the store as they are given by pinia. We are going to override them
  925. const actions = actionNames.reduce((storeActions, actionName) => {
  926. // use toRaw to avoid tracking #541
  927. storeActions[actionName] = vue.toRaw(store)[actionName];
  928. return storeActions;
  929. }, {});
  930. for (const actionName in actions) {
  931. store[actionName] = function () {
  932. // the running action id is incremented in a before action hook
  933. const _actionId = runningActionId;
  934. const trackedStore = wrapWithProxy
  935. ? new Proxy(store, {
  936. get(...args) {
  937. activeAction = _actionId;
  938. return Reflect.get(...args);
  939. },
  940. set(...args) {
  941. activeAction = _actionId;
  942. return Reflect.set(...args);
  943. },
  944. })
  945. : store;
  946. // For Setup Stores we need https://github.com/tc39/proposal-async-context
  947. activeAction = _actionId;
  948. const retValue = actions[actionName].apply(trackedStore, arguments);
  949. // this is safer as async actions in Setup Stores would associate mutations done outside of the action
  950. activeAction = undefined;
  951. return retValue;
  952. };
  953. }
  954. }
  955. /**
  956. * pinia.use(devtoolsPlugin)
  957. */
  958. function devtoolsPlugin({ app, store, options }) {
  959. // HMR module
  960. if (store.$id.startsWith('__hot:')) {
  961. return;
  962. }
  963. // detect option api vs setup api
  964. store._isOptionsAPI = !!options.state;
  965. // Do not overwrite actions mocked by @pinia/testing (#2298)
  966. if (!store._p._testing) {
  967. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  968. // Upgrade the HMR to also update the new actions
  969. const originalHotUpdate = store._hotUpdate;
  970. vue.toRaw(store)._hotUpdate = function (newStore) {
  971. originalHotUpdate.apply(this, arguments);
  972. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  973. };
  974. }
  975. addStoreToDevtools(app,
  976. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  977. store);
  978. }
  979. /**
  980. * Creates a Pinia instance to be used by the application
  981. */
  982. function createPinia() {
  983. const scope = vue.effectScope(true);
  984. // NOTE: here we could check the window object for a state and directly set it
  985. // if there is anything like it with Vue 3 SSR
  986. const state = scope.run(() => vue.ref({}));
  987. let _p = [];
  988. // plugins added before calling app.use(pinia)
  989. let toBeInstalled = [];
  990. const pinia = vue.markRaw({
  991. install(app) {
  992. // this allows calling useStore() outside of a component setup after
  993. // installing pinia's plugin
  994. setActivePinia(pinia);
  995. pinia._a = app;
  996. app.provide(piniaSymbol, pinia);
  997. app.config.globalProperties.$pinia = pinia;
  998. /* istanbul ignore else */
  999. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1000. registerPiniaDevtools(app, pinia);
  1001. }
  1002. toBeInstalled.forEach((plugin) => _p.push(plugin));
  1003. toBeInstalled = [];
  1004. },
  1005. use(plugin) {
  1006. if (!this._a) {
  1007. toBeInstalled.push(plugin);
  1008. }
  1009. else {
  1010. _p.push(plugin);
  1011. }
  1012. return this;
  1013. },
  1014. _p,
  1015. // it's actually undefined here
  1016. // @ts-expect-error
  1017. _a: null,
  1018. _e: scope,
  1019. _s: new Map(),
  1020. state,
  1021. });
  1022. // pinia devtools rely on dev only features so they cannot be forced unless
  1023. // the dev build of Vue is used. Avoid old browsers like IE11.
  1024. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT && typeof Proxy !== 'undefined') {
  1025. pinia.use(devtoolsPlugin);
  1026. }
  1027. return pinia;
  1028. }
  1029. /**
  1030. * Dispose a Pinia instance by stopping its effectScope and removing the state, plugins and stores. This is mostly
  1031. * useful in tests, with both a testing pinia or a regular pinia and in applications that use multiple pinia instances.
  1032. * Once disposed, the pinia instance cannot be used anymore.
  1033. *
  1034. * @param pinia - pinia instance
  1035. */
  1036. function disposePinia(pinia) {
  1037. pinia._e.stop();
  1038. pinia._s.clear();
  1039. pinia._p.splice(0);
  1040. pinia.state.value = {};
  1041. // @ts-expect-error: non valid
  1042. pinia._a = null;
  1043. }
  1044. /**
  1045. * Checks if a function is a `StoreDefinition`.
  1046. *
  1047. * @param fn - object to test
  1048. * @returns true if `fn` is a StoreDefinition
  1049. */
  1050. const isUseStore = (fn) => {
  1051. return typeof fn === 'function' && typeof fn.$id === 'string';
  1052. };
  1053. /**
  1054. * Mutates in place `newState` with `oldState` to _hot update_ it. It will
  1055. * remove any key not existing in `newState` and recursively merge plain
  1056. * objects.
  1057. *
  1058. * @param newState - new state object to be patched
  1059. * @param oldState - old state that should be used to patch newState
  1060. * @returns - newState
  1061. */
  1062. function patchObject(newState, oldState) {
  1063. // no need to go through symbols because they cannot be serialized anyway
  1064. for (const key in oldState) {
  1065. const subPatch = oldState[key];
  1066. // skip the whole sub tree
  1067. if (!(key in newState)) {
  1068. continue;
  1069. }
  1070. const targetValue = newState[key];
  1071. if (isPlainObject(targetValue) &&
  1072. isPlainObject(subPatch) &&
  1073. !vue.isRef(subPatch) &&
  1074. !vue.isReactive(subPatch)) {
  1075. newState[key] = patchObject(targetValue, subPatch);
  1076. }
  1077. else {
  1078. // objects are either a bit more complex (e.g. refs) or primitives, so we
  1079. // just set the whole thing
  1080. newState[key] = subPatch;
  1081. }
  1082. }
  1083. return newState;
  1084. }
  1085. /**
  1086. * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
  1087. *
  1088. * @example
  1089. * ```js
  1090. * const useUser = defineStore(...)
  1091. * if (import.meta.hot) {
  1092. * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
  1093. * }
  1094. * ```
  1095. *
  1096. * @param initialUseStore - return of the defineStore to hot update
  1097. * @param hot - `import.meta.hot`
  1098. */
  1099. function acceptHMRUpdate(initialUseStore, hot) {
  1100. // strip as much as possible from iife.prod
  1101. if (!(process.env.NODE_ENV !== 'production')) {
  1102. return () => { };
  1103. }
  1104. return (newModule) => {
  1105. const pinia = hot.data.pinia || initialUseStore._pinia;
  1106. if (!pinia) {
  1107. // this store is still not used
  1108. return;
  1109. }
  1110. // preserve the pinia instance across loads
  1111. hot.data.pinia = pinia;
  1112. // console.log('got data', newStore)
  1113. for (const exportName in newModule) {
  1114. const useStore = newModule[exportName];
  1115. // console.log('checking for', exportName)
  1116. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  1117. // console.log('Accepting update for', useStore.$id)
  1118. const id = useStore.$id;
  1119. if (id !== initialUseStore.$id) {
  1120. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  1121. // return import.meta.hot.invalidate()
  1122. return hot.invalidate();
  1123. }
  1124. const existingStore = pinia._s.get(id);
  1125. if (!existingStore) {
  1126. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  1127. return;
  1128. }
  1129. useStore(pinia, existingStore);
  1130. }
  1131. }
  1132. };
  1133. }
  1134. const noop = () => { };
  1135. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  1136. subscriptions.add(callback);
  1137. const removeSubscription = () => {
  1138. const isDel = subscriptions.delete(callback);
  1139. isDel && onCleanup();
  1140. };
  1141. if (!detached && vue.getCurrentScope()) {
  1142. vue.onScopeDispose(removeSubscription);
  1143. }
  1144. return removeSubscription;
  1145. }
  1146. function triggerSubscriptions(subscriptions, ...args) {
  1147. subscriptions.forEach((callback) => {
  1148. callback(...args);
  1149. });
  1150. }
  1151. const fallbackRunWithContext = (fn) => fn();
  1152. /**
  1153. * Marks a function as an action for `$onAction`
  1154. * @internal
  1155. */
  1156. const ACTION_MARKER = Symbol();
  1157. /**
  1158. * Action name symbol. Allows to add a name to an action after defining it
  1159. * @internal
  1160. */
  1161. const ACTION_NAME = Symbol();
  1162. function mergeReactiveObjects(target, patchToApply) {
  1163. // Handle Map instances
  1164. if (target instanceof Map && patchToApply instanceof Map) {
  1165. patchToApply.forEach((value, key) => target.set(key, value));
  1166. }
  1167. else if (target instanceof Set && patchToApply instanceof Set) {
  1168. // Handle Set instances
  1169. patchToApply.forEach(target.add, target);
  1170. }
  1171. // no need to go through symbols because they cannot be serialized anyway
  1172. for (const key in patchToApply) {
  1173. if (!patchToApply.hasOwnProperty(key))
  1174. continue;
  1175. const subPatch = patchToApply[key];
  1176. const targetValue = target[key];
  1177. if (isPlainObject(targetValue) &&
  1178. isPlainObject(subPatch) &&
  1179. target.hasOwnProperty(key) &&
  1180. !vue.isRef(subPatch) &&
  1181. !vue.isReactive(subPatch)) {
  1182. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1183. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1184. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1185. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1186. }
  1187. else {
  1188. // @ts-expect-error: subPatch is a valid value
  1189. target[key] = subPatch;
  1190. }
  1191. }
  1192. return target;
  1193. }
  1194. const skipHydrateSymbol = (process.env.NODE_ENV !== 'production')
  1195. ? Symbol('pinia:skipHydration')
  1196. : /* istanbul ignore next */ Symbol();
  1197. /**
  1198. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1199. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1200. *
  1201. * @param obj - target object
  1202. * @returns obj
  1203. */
  1204. function skipHydrate(obj) {
  1205. return Object.defineProperty(obj, skipHydrateSymbol, {});
  1206. }
  1207. /**
  1208. * Returns whether a value should be hydrated
  1209. *
  1210. * @param obj - target variable
  1211. * @returns true if `obj` should be hydrated
  1212. */
  1213. function shouldHydrate(obj) {
  1214. return (!isPlainObject(obj) ||
  1215. !Object.prototype.hasOwnProperty.call(obj, skipHydrateSymbol));
  1216. }
  1217. const { assign } = Object;
  1218. function isComputed(o) {
  1219. return !!(vue.isRef(o) && o.effect);
  1220. }
  1221. function createOptionsStore(id, options, pinia, hot) {
  1222. const { state, actions, getters } = options;
  1223. const initialState = pinia.state.value[id];
  1224. let store;
  1225. function setup() {
  1226. if (!initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1227. /* istanbul ignore if */
  1228. pinia.state.value[id] = state ? state() : {};
  1229. }
  1230. // avoid creating a state in pinia.state.value
  1231. const localState = (process.env.NODE_ENV !== 'production') && hot
  1232. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1233. vue.toRefs(vue.ref(state ? state() : {}).value)
  1234. : vue.toRefs(pinia.state.value[id]);
  1235. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1236. if ((process.env.NODE_ENV !== 'production') && name in localState) {
  1237. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1238. }
  1239. computedGetters[name] = vue.markRaw(vue.computed(() => {
  1240. setActivePinia(pinia);
  1241. // it was created just before
  1242. const store = pinia._s.get(id);
  1243. // allow cross using stores
  1244. // @ts-expect-error
  1245. // return getters![name].call(context, context)
  1246. // TODO: avoid reading the getter while assigning with a global variable
  1247. return getters[name].call(store, store);
  1248. }));
  1249. return computedGetters;
  1250. }, {}));
  1251. }
  1252. store = createSetupStore(id, setup, options, pinia, hot, true);
  1253. return store;
  1254. }
  1255. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1256. let scope;
  1257. const optionsForPlugin = assign({ actions: {} }, options);
  1258. /* istanbul ignore if */
  1259. if ((process.env.NODE_ENV !== 'production') && !pinia._e.active) {
  1260. throw new Error('Pinia destroyed');
  1261. }
  1262. // watcher options for $subscribe
  1263. const $subscribeOptions = { deep: true };
  1264. /* istanbul ignore else */
  1265. if ((process.env.NODE_ENV !== 'production')) {
  1266. $subscribeOptions.onTrigger = (event) => {
  1267. /* istanbul ignore else */
  1268. if (isListening) {
  1269. debuggerEvents = event;
  1270. // avoid triggering this while the store is being built and the state is being set in pinia
  1271. }
  1272. else if (isListening == false && !store._hotUpdating) {
  1273. // let patch send all the events together later
  1274. /* istanbul ignore else */
  1275. if (Array.isArray(debuggerEvents)) {
  1276. debuggerEvents.push(event);
  1277. }
  1278. else {
  1279. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1280. }
  1281. }
  1282. };
  1283. }
  1284. // internal state
  1285. let isListening; // set to true at the end
  1286. let isSyncListening; // set to true at the end
  1287. let subscriptions = new Set();
  1288. let actionSubscriptions = new Set();
  1289. let debuggerEvents;
  1290. const initialState = pinia.state.value[$id];
  1291. // avoid setting the state for option stores if it is set
  1292. // by the setup
  1293. if (!isOptionsStore && !initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1294. /* istanbul ignore if */
  1295. pinia.state.value[$id] = {};
  1296. }
  1297. const hotState = vue.ref({});
  1298. // avoid triggering too many listeners
  1299. // https://github.com/vuejs/pinia/issues/1129
  1300. let activeListener;
  1301. function $patch(partialStateOrMutator) {
  1302. let subscriptionMutation;
  1303. isListening = isSyncListening = false;
  1304. // reset the debugger events since patches are sync
  1305. /* istanbul ignore else */
  1306. if ((process.env.NODE_ENV !== 'production')) {
  1307. debuggerEvents = [];
  1308. }
  1309. if (typeof partialStateOrMutator === 'function') {
  1310. partialStateOrMutator(pinia.state.value[$id]);
  1311. subscriptionMutation = {
  1312. type: exports.MutationType.patchFunction,
  1313. storeId: $id,
  1314. events: debuggerEvents,
  1315. };
  1316. }
  1317. else {
  1318. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1319. subscriptionMutation = {
  1320. type: exports.MutationType.patchObject,
  1321. payload: partialStateOrMutator,
  1322. storeId: $id,
  1323. events: debuggerEvents,
  1324. };
  1325. }
  1326. const myListenerId = (activeListener = Symbol());
  1327. vue.nextTick().then(() => {
  1328. if (activeListener === myListenerId) {
  1329. isListening = true;
  1330. }
  1331. });
  1332. isSyncListening = true;
  1333. // because we paused the watcher, we need to manually call the subscriptions
  1334. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1335. }
  1336. const $reset = isOptionsStore
  1337. ? function $reset() {
  1338. const { state } = options;
  1339. const newState = state ? state() : {};
  1340. // we use a patch to group all changes into one single subscription
  1341. this.$patch(($state) => {
  1342. // @ts-expect-error: FIXME: shouldn't error?
  1343. assign($state, newState);
  1344. });
  1345. }
  1346. : /* istanbul ignore next */
  1347. (process.env.NODE_ENV !== 'production')
  1348. ? () => {
  1349. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1350. }
  1351. : noop;
  1352. function $dispose() {
  1353. scope.stop();
  1354. subscriptions.clear();
  1355. actionSubscriptions.clear();
  1356. pinia._s.delete($id);
  1357. }
  1358. /**
  1359. * Helper that wraps function so it can be tracked with $onAction
  1360. * @param fn - action to wrap
  1361. * @param name - name of the action
  1362. */
  1363. const action = (fn, name = '') => {
  1364. if (ACTION_MARKER in fn) {
  1365. fn[ACTION_NAME] = name;
  1366. return fn;
  1367. }
  1368. const wrappedAction = function () {
  1369. setActivePinia(pinia);
  1370. const args = Array.from(arguments);
  1371. const afterCallbackSet = new Set();
  1372. const onErrorCallbackSet = new Set();
  1373. function after(callback) {
  1374. afterCallbackSet.add(callback);
  1375. }
  1376. function onError(callback) {
  1377. onErrorCallbackSet.add(callback);
  1378. }
  1379. // @ts-expect-error
  1380. triggerSubscriptions(actionSubscriptions, {
  1381. args,
  1382. name: wrappedAction[ACTION_NAME],
  1383. store,
  1384. after,
  1385. onError,
  1386. });
  1387. let ret;
  1388. try {
  1389. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1390. // handle sync errors
  1391. }
  1392. catch (error) {
  1393. triggerSubscriptions(onErrorCallbackSet, error);
  1394. throw error;
  1395. }
  1396. if (ret instanceof Promise) {
  1397. return ret
  1398. .then((value) => {
  1399. triggerSubscriptions(afterCallbackSet, value);
  1400. return value;
  1401. })
  1402. .catch((error) => {
  1403. triggerSubscriptions(onErrorCallbackSet, error);
  1404. return Promise.reject(error);
  1405. });
  1406. }
  1407. // trigger after callbacks
  1408. triggerSubscriptions(afterCallbackSet, ret);
  1409. return ret;
  1410. };
  1411. wrappedAction[ACTION_MARKER] = true;
  1412. wrappedAction[ACTION_NAME] = name; // will be set later
  1413. // @ts-expect-error: we are intentionally limiting the returned type to just Fn
  1414. // because all the added properties are internals that are exposed through `$onAction()` only
  1415. return wrappedAction;
  1416. };
  1417. const _hmrPayload = /*#__PURE__*/ vue.markRaw({
  1418. actions: {},
  1419. getters: {},
  1420. state: [],
  1421. hotState,
  1422. });
  1423. const partialStore = {
  1424. _p: pinia,
  1425. // _s: scope,
  1426. $id,
  1427. $onAction: addSubscription.bind(null, actionSubscriptions),
  1428. $patch,
  1429. $reset,
  1430. $subscribe(callback, options = {}) {
  1431. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1432. const stopWatcher = scope.run(() => vue.watch(() => pinia.state.value[$id], (state) => {
  1433. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1434. callback({
  1435. storeId: $id,
  1436. type: exports.MutationType.direct,
  1437. events: debuggerEvents,
  1438. }, state);
  1439. }
  1440. }, assign({}, $subscribeOptions, options)));
  1441. return removeSubscription;
  1442. },
  1443. $dispose,
  1444. };
  1445. const store = vue.reactive((process.env.NODE_ENV !== 'production') || ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT)
  1446. ? assign({
  1447. _hmrPayload,
  1448. _customProperties: vue.markRaw(new Set()), // devtools custom properties
  1449. }, partialStore
  1450. // must be added later
  1451. // setupStore
  1452. )
  1453. : partialStore);
  1454. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1455. // creating infinite loops.
  1456. pinia._s.set($id, store);
  1457. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1458. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1459. const setupStore = runWithContext(() => pinia._e.run(() => (scope = vue.effectScope()).run(() => setup({ action }))));
  1460. // overwrite existing actions to support $onAction
  1461. for (const key in setupStore) {
  1462. const prop = setupStore[key];
  1463. if ((vue.isRef(prop) && !isComputed(prop)) || vue.isReactive(prop)) {
  1464. // mark it as a piece of state to be serialized
  1465. if ((process.env.NODE_ENV !== 'production') && hot) {
  1466. hotState.value[key] = vue.toRef(setupStore, key);
  1467. // createOptionStore directly sets the state in pinia.state.value so we
  1468. // can just skip that
  1469. }
  1470. else if (!isOptionsStore) {
  1471. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1472. if (initialState && shouldHydrate(prop)) {
  1473. if (vue.isRef(prop)) {
  1474. prop.value = initialState[key];
  1475. }
  1476. else {
  1477. // probably a reactive object, lets recursively assign
  1478. // @ts-expect-error: prop is unknown
  1479. mergeReactiveObjects(prop, initialState[key]);
  1480. }
  1481. }
  1482. // transfer the ref to the pinia state to keep everything in sync
  1483. pinia.state.value[$id][key] = prop;
  1484. }
  1485. /* istanbul ignore else */
  1486. if ((process.env.NODE_ENV !== 'production')) {
  1487. _hmrPayload.state.push(key);
  1488. }
  1489. // action
  1490. }
  1491. else if (typeof prop === 'function') {
  1492. const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : action(prop, key);
  1493. // this a hot module replacement store because the hotUpdate method needs
  1494. // to do it with the right context
  1495. // @ts-expect-error
  1496. setupStore[key] = actionValue;
  1497. /* istanbul ignore else */
  1498. if ((process.env.NODE_ENV !== 'production')) {
  1499. _hmrPayload.actions[key] = prop;
  1500. }
  1501. // list actions so they can be used in plugins
  1502. // @ts-expect-error
  1503. optionsForPlugin.actions[key] = prop;
  1504. }
  1505. else if ((process.env.NODE_ENV !== 'production')) {
  1506. // add getters for devtools
  1507. if (isComputed(prop)) {
  1508. _hmrPayload.getters[key] = isOptionsStore
  1509. ? // @ts-expect-error
  1510. options.getters[key]
  1511. : prop;
  1512. if (IS_CLIENT) {
  1513. const getters = setupStore._getters ||
  1514. // @ts-expect-error: same
  1515. (setupStore._getters = vue.markRaw([]));
  1516. getters.push(key);
  1517. }
  1518. }
  1519. }
  1520. }
  1521. // add the state, getters, and action properties
  1522. /* istanbul ignore if */
  1523. assign(store, setupStore);
  1524. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1525. // Make `storeToRefs()` work with `reactive()` #799
  1526. assign(vue.toRaw(store), setupStore);
  1527. // use this instead of a computed with setter to be able to create it anywhere
  1528. // without linking the computed lifespan to wherever the store is first
  1529. // created.
  1530. Object.defineProperty(store, '$state', {
  1531. get: () => ((process.env.NODE_ENV !== 'production') && hot ? hotState.value : pinia.state.value[$id]),
  1532. set: (state) => {
  1533. /* istanbul ignore if */
  1534. if ((process.env.NODE_ENV !== 'production') && hot) {
  1535. throw new Error('cannot set hotState');
  1536. }
  1537. $patch(($state) => {
  1538. // @ts-expect-error: FIXME: shouldn't error?
  1539. assign($state, state);
  1540. });
  1541. },
  1542. });
  1543. // add the hotUpdate before plugins to allow them to override it
  1544. /* istanbul ignore else */
  1545. if ((process.env.NODE_ENV !== 'production')) {
  1546. store._hotUpdate = vue.markRaw((newStore) => {
  1547. store._hotUpdating = true;
  1548. newStore._hmrPayload.state.forEach((stateKey) => {
  1549. if (stateKey in store.$state) {
  1550. const newStateTarget = newStore.$state[stateKey];
  1551. const oldStateSource = store.$state[stateKey];
  1552. if (typeof newStateTarget === 'object' &&
  1553. isPlainObject(newStateTarget) &&
  1554. isPlainObject(oldStateSource)) {
  1555. patchObject(newStateTarget, oldStateSource);
  1556. }
  1557. else {
  1558. // transfer the ref
  1559. newStore.$state[stateKey] = oldStateSource;
  1560. }
  1561. }
  1562. // patch direct access properties to allow store.stateProperty to work as
  1563. // store.$state.stateProperty
  1564. // @ts-expect-error: any type
  1565. store[stateKey] = vue.toRef(newStore.$state, stateKey);
  1566. });
  1567. // remove deleted state properties
  1568. Object.keys(store.$state).forEach((stateKey) => {
  1569. if (!(stateKey in newStore.$state)) {
  1570. // @ts-expect-error: noop if doesn't exist
  1571. delete store[stateKey];
  1572. }
  1573. });
  1574. // avoid devtools logging this as a mutation
  1575. isListening = false;
  1576. isSyncListening = false;
  1577. pinia.state.value[$id] = vue.toRef(newStore._hmrPayload, 'hotState');
  1578. isSyncListening = true;
  1579. vue.nextTick().then(() => {
  1580. isListening = true;
  1581. });
  1582. for (const actionName in newStore._hmrPayload.actions) {
  1583. const actionFn = newStore[actionName];
  1584. // @ts-expect-error: actionName is a string
  1585. store[actionName] =
  1586. //
  1587. action(actionFn, actionName);
  1588. }
  1589. // TODO: does this work in both setup and option store?
  1590. for (const getterName in newStore._hmrPayload.getters) {
  1591. const getter = newStore._hmrPayload.getters[getterName];
  1592. const getterValue = isOptionsStore
  1593. ? // special handling of options api
  1594. vue.computed(() => {
  1595. setActivePinia(pinia);
  1596. return getter.call(store, store);
  1597. })
  1598. : getter;
  1599. // @ts-expect-error: getterName is a string
  1600. store[getterName] =
  1601. //
  1602. getterValue;
  1603. }
  1604. // remove deleted getters
  1605. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1606. if (!(key in newStore._hmrPayload.getters)) {
  1607. // @ts-expect-error: noop if doesn't exist
  1608. delete store[key];
  1609. }
  1610. });
  1611. // remove old actions
  1612. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1613. if (!(key in newStore._hmrPayload.actions)) {
  1614. // @ts-expect-error: noop if doesn't exist
  1615. delete store[key];
  1616. }
  1617. });
  1618. // update the values used in devtools and to allow deleting new properties later on
  1619. store._hmrPayload = newStore._hmrPayload;
  1620. store._getters = newStore._getters;
  1621. store._hotUpdating = false;
  1622. });
  1623. }
  1624. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1625. const nonEnumerable = {
  1626. writable: true,
  1627. configurable: true,
  1628. // avoid warning on devtools trying to display this property
  1629. enumerable: false,
  1630. };
  1631. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1632. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1633. });
  1634. }
  1635. // apply all plugins
  1636. pinia._p.forEach((extender) => {
  1637. /* istanbul ignore else */
  1638. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1639. const extensions = scope.run(() => extender({
  1640. store: store,
  1641. app: pinia._a,
  1642. pinia,
  1643. options: optionsForPlugin,
  1644. }));
  1645. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1646. assign(store, extensions);
  1647. }
  1648. else {
  1649. assign(store, scope.run(() => extender({
  1650. store: store,
  1651. app: pinia._a,
  1652. pinia,
  1653. options: optionsForPlugin,
  1654. })));
  1655. }
  1656. });
  1657. if ((process.env.NODE_ENV !== 'production') &&
  1658. store.$state &&
  1659. typeof store.$state === 'object' &&
  1660. typeof store.$state.constructor === 'function' &&
  1661. !store.$state.constructor.toString().includes('[native code]')) {
  1662. console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` +
  1663. `\tstate: () => new MyClass()\n` +
  1664. `Found in store "${store.$id}".`);
  1665. }
  1666. // only apply hydrate to option stores with an initial state in pinia
  1667. if (initialState &&
  1668. isOptionsStore &&
  1669. options.hydrate) {
  1670. options.hydrate(store.$state, initialState);
  1671. }
  1672. isListening = true;
  1673. isSyncListening = true;
  1674. return store;
  1675. }
  1676. // allows unused stores to be tree shaken
  1677. /*! #__NO_SIDE_EFFECTS__ */
  1678. function defineStore(
  1679. // TODO: add proper types from above
  1680. id, setup, setupOptions) {
  1681. let options;
  1682. const isSetupStore = typeof setup === 'function';
  1683. // the option store setup will contain the actual options in this case
  1684. options = isSetupStore ? setupOptions : setup;
  1685. function useStore(pinia, hot) {
  1686. const hasContext = vue.hasInjectionContext();
  1687. pinia =
  1688. // in test mode, ignore the argument provided as we can always retrieve a
  1689. // pinia instance with getActivePinia()
  1690. ((process.env.NODE_ENV === 'test') && activePinia && activePinia._testing ? null : pinia) ||
  1691. (hasContext ? vue.inject(piniaSymbol, null) : null);
  1692. if (pinia)
  1693. setActivePinia(pinia);
  1694. if ((process.env.NODE_ENV !== 'production') && !activePinia) {
  1695. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?\n` +
  1696. `See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.\n` +
  1697. `This will fail in production.`);
  1698. }
  1699. pinia = activePinia;
  1700. if (!pinia._s.has(id)) {
  1701. // creating the store registers it in `pinia._s`
  1702. if (isSetupStore) {
  1703. createSetupStore(id, setup, options, pinia);
  1704. }
  1705. else {
  1706. createOptionsStore(id, options, pinia);
  1707. }
  1708. /* istanbul ignore else */
  1709. if ((process.env.NODE_ENV !== 'production')) {
  1710. // @ts-expect-error: not the right inferred type
  1711. useStore._pinia = pinia;
  1712. }
  1713. }
  1714. const store = pinia._s.get(id);
  1715. if ((process.env.NODE_ENV !== 'production') && hot) {
  1716. const hotId = '__hot:' + id;
  1717. const newStore = isSetupStore
  1718. ? createSetupStore(hotId, setup, options, pinia, true)
  1719. : createOptionsStore(hotId, assign({}, options), pinia, true);
  1720. hot._hotUpdate(newStore);
  1721. // cleanup the state properties and the store from the cache
  1722. delete pinia.state.value[hotId];
  1723. pinia._s.delete(hotId);
  1724. }
  1725. if ((process.env.NODE_ENV !== 'production') && IS_CLIENT) {
  1726. const currentInstance = vue.getCurrentInstance();
  1727. // save stores in instances to access them devtools
  1728. if (currentInstance &&
  1729. currentInstance.proxy &&
  1730. // avoid adding stores that are just built for hot module replacement
  1731. !hot) {
  1732. const vm = currentInstance.proxy;
  1733. const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});
  1734. cache[id] = store;
  1735. }
  1736. }
  1737. // StoreGeneric cannot be casted towards Store
  1738. return store;
  1739. }
  1740. useStore.$id = id;
  1741. return useStore;
  1742. }
  1743. let mapStoreSuffix = 'Store';
  1744. /**
  1745. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  1746. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  1747. * interface if you are using TypeScript.
  1748. *
  1749. * @param suffix - new suffix
  1750. */
  1751. function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS
  1752. ) {
  1753. mapStoreSuffix = suffix;
  1754. }
  1755. /**
  1756. * Allows using stores without the composition API (`setup()`) by generating an
  1757. * object to be spread in the `computed` field of a component. It accepts a list
  1758. * of store definitions.
  1759. *
  1760. * @example
  1761. * ```js
  1762. * export default {
  1763. * computed: {
  1764. * // other computed properties
  1765. * ...mapStores(useUserStore, useCartStore)
  1766. * },
  1767. *
  1768. * created() {
  1769. * this.userStore // store with id "user"
  1770. * this.cartStore // store with id "cart"
  1771. * }
  1772. * }
  1773. * ```
  1774. *
  1775. * @param stores - list of stores to map to an object
  1776. */
  1777. function mapStores(...stores) {
  1778. if ((process.env.NODE_ENV !== 'production') && Array.isArray(stores[0])) {
  1779. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` +
  1780. `Replace\n` +
  1781. `\tmapStores([useAuthStore, useCartStore])\n` +
  1782. `with\n` +
  1783. `\tmapStores(useAuthStore, useCartStore)\n` +
  1784. `This will fail in production if not fixed.`);
  1785. stores = stores[0];
  1786. }
  1787. return stores.reduce((reduced, useStore) => {
  1788. // @ts-expect-error: $id is added by defineStore
  1789. reduced[useStore.$id + mapStoreSuffix] = function () {
  1790. return useStore(this.$pinia);
  1791. };
  1792. return reduced;
  1793. }, {});
  1794. }
  1795. /**
  1796. * Allows using state and getters from one store without using the composition
  1797. * API (`setup()`) by generating an object to be spread in the `computed` field
  1798. * of a component.
  1799. *
  1800. * @param useStore - store to map from
  1801. * @param keysOrMapper - array or object
  1802. */
  1803. function mapState(useStore, keysOrMapper) {
  1804. return Array.isArray(keysOrMapper)
  1805. ? keysOrMapper.reduce((reduced, key) => {
  1806. reduced[key] = function () {
  1807. // @ts-expect-error: FIXME: should work?
  1808. return useStore(this.$pinia)[key];
  1809. };
  1810. return reduced;
  1811. }, {})
  1812. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1813. // @ts-expect-error
  1814. reduced[key] = function () {
  1815. const store = useStore(this.$pinia);
  1816. const storeKey = keysOrMapper[key];
  1817. // for some reason TS is unable to infer the type of storeKey to be a
  1818. // function
  1819. return typeof storeKey === 'function'
  1820. ? storeKey.call(this, store)
  1821. : // @ts-expect-error: FIXME: should work?
  1822. store[storeKey];
  1823. };
  1824. return reduced;
  1825. }, {});
  1826. }
  1827. /**
  1828. * Alias for `mapState()`. You should use `mapState()` instead.
  1829. * @deprecated use `mapState()` instead.
  1830. */
  1831. const mapGetters = mapState;
  1832. /**
  1833. * Allows directly using actions from your store without using the composition
  1834. * API (`setup()`) by generating an object to be spread in the `methods` field
  1835. * of a component.
  1836. *
  1837. * @param useStore - store to map from
  1838. * @param keysOrMapper - array or object
  1839. */
  1840. function mapActions(useStore, keysOrMapper) {
  1841. return Array.isArray(keysOrMapper)
  1842. ? keysOrMapper.reduce((reduced, key) => {
  1843. // @ts-expect-error
  1844. reduced[key] = function (...args) {
  1845. // @ts-expect-error: FIXME: should work?
  1846. return useStore(this.$pinia)[key](...args);
  1847. };
  1848. return reduced;
  1849. }, {})
  1850. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1851. // @ts-expect-error
  1852. reduced[key] = function (...args) {
  1853. // @ts-expect-error: FIXME: should work?
  1854. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1855. };
  1856. return reduced;
  1857. }, {});
  1858. }
  1859. /**
  1860. * Allows using state and getters from one store without using the composition
  1861. * API (`setup()`) by generating an object to be spread in the `computed` field
  1862. * of a component.
  1863. *
  1864. * @param useStore - store to map from
  1865. * @param keysOrMapper - array or object
  1866. */
  1867. function mapWritableState(useStore, keysOrMapper) {
  1868. return Array.isArray(keysOrMapper)
  1869. ? keysOrMapper.reduce((reduced, key) => {
  1870. reduced[key] = {
  1871. get() {
  1872. return useStore(this.$pinia)[key];
  1873. },
  1874. set(value) {
  1875. return (useStore(this.$pinia)[key] = value);
  1876. },
  1877. };
  1878. return reduced;
  1879. }, {})
  1880. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1881. reduced[key] = {
  1882. get() {
  1883. return useStore(this.$pinia)[keysOrMapper[key]];
  1884. },
  1885. set(value) {
  1886. return (useStore(this.$pinia)[keysOrMapper[key]] = value);
  1887. },
  1888. };
  1889. return reduced;
  1890. }, {});
  1891. }
  1892. /**
  1893. * Creates an object of references with all the state, getters, and plugin-added
  1894. * state properties of the store. Similar to `toRefs()` but specifically
  1895. * designed for Pinia stores so methods and non reactive properties are
  1896. * completely ignored.
  1897. *
  1898. * @param store - store to extract the refs from
  1899. */
  1900. function storeToRefs(store) {
  1901. const rawStore = vue.toRaw(store);
  1902. const refs = {};
  1903. for (const key in rawStore) {
  1904. const value = rawStore[key];
  1905. // There is no native method to check for a computed
  1906. // https://github.com/vuejs/core/pull/4165
  1907. if (value.effect) {
  1908. // @ts-expect-error: too hard to type correctly
  1909. refs[key] =
  1910. // ...
  1911. vue.computed({
  1912. get: () => store[key],
  1913. set(value) {
  1914. store[key] = value;
  1915. },
  1916. });
  1917. }
  1918. else if (vue.isRef(value) || vue.isReactive(value)) {
  1919. // @ts-expect-error: the key is state or getter
  1920. refs[key] =
  1921. // ---
  1922. vue.toRef(store, key);
  1923. }
  1924. }
  1925. return refs;
  1926. }
  1927. exports.acceptHMRUpdate = acceptHMRUpdate;
  1928. exports.createPinia = createPinia;
  1929. exports.defineStore = defineStore;
  1930. exports.disposePinia = disposePinia;
  1931. exports.getActivePinia = getActivePinia;
  1932. exports.mapActions = mapActions;
  1933. exports.mapGetters = mapGetters;
  1934. exports.mapState = mapState;
  1935. exports.mapStores = mapStores;
  1936. exports.mapWritableState = mapWritableState;
  1937. exports.setActivePinia = setActivePinia;
  1938. exports.setMapStoreSuffix = setMapStoreSuffix;
  1939. exports.shouldHydrate = shouldHydrate;
  1940. exports.skipHydrate = skipHydrate;
  1941. exports.storeToRefs = storeToRefs;