pinia.esm-browser.js 71 KB

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