pinia.esm-browser.js 71 KB

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