pinia.mjs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. /*!
  2. * pinia v2.1.4
  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 = ((process.env.NODE_ENV !== 'production') ? Symbol('pinia') : /* istanbul ignore next */ Symbol());
  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 = ((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test') && 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. pinia.state.value = 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 = await getFileOpener();
  362. const result = await open();
  363. if (!result)
  364. return;
  365. const { text, file } = result;
  366. pinia.state.value = JSON.parse(text);
  367. toastMessage(`Global state imported from "${file.name}".`);
  368. }
  369. catch (error) {
  370. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
  371. console.error(error);
  372. }
  373. }
  374. function formatDisplay(display) {
  375. return {
  376. _custom: {
  377. display,
  378. },
  379. };
  380. }
  381. const PINIA_ROOT_LABEL = '🍍 Pinia (root)';
  382. const PINIA_ROOT_ID = '_root';
  383. function formatStoreForInspectorTree(store) {
  384. return isPinia(store)
  385. ? {
  386. id: PINIA_ROOT_ID,
  387. label: PINIA_ROOT_LABEL,
  388. }
  389. : {
  390. id: store.$id,
  391. label: store.$id,
  392. };
  393. }
  394. function formatStoreForInspectorState(store) {
  395. if (isPinia(store)) {
  396. const storeNames = Array.from(store._s.keys());
  397. const storeMap = store._s;
  398. const state = {
  399. state: storeNames.map((storeId) => ({
  400. editable: true,
  401. key: storeId,
  402. value: store.state.value[storeId],
  403. })),
  404. getters: storeNames
  405. .filter((id) => storeMap.get(id)._getters)
  406. .map((id) => {
  407. const store = storeMap.get(id);
  408. return {
  409. editable: false,
  410. key: id,
  411. value: store._getters.reduce((getters, key) => {
  412. getters[key] = store[key];
  413. return getters;
  414. }, {}),
  415. };
  416. }),
  417. };
  418. return state;
  419. }
  420. const state = {
  421. state: Object.keys(store.$state).map((key) => ({
  422. editable: true,
  423. key,
  424. value: store.$state[key],
  425. })),
  426. };
  427. // avoid adding empty getters
  428. if (store._getters && store._getters.length) {
  429. state.getters = store._getters.map((getterName) => ({
  430. editable: false,
  431. key: getterName,
  432. value: store[getterName],
  433. }));
  434. }
  435. if (store._customProperties.size) {
  436. state.customProperties = Array.from(store._customProperties).map((key) => ({
  437. editable: true,
  438. key,
  439. value: store[key],
  440. }));
  441. }
  442. return state;
  443. }
  444. function formatEventData(events) {
  445. if (!events)
  446. return {};
  447. if (Array.isArray(events)) {
  448. // TODO: handle add and delete for arrays and objects
  449. return events.reduce((data, event) => {
  450. data.keys.push(event.key);
  451. data.operations.push(event.type);
  452. data.oldValue[event.key] = event.oldValue;
  453. data.newValue[event.key] = event.newValue;
  454. return data;
  455. }, {
  456. oldValue: {},
  457. keys: [],
  458. operations: [],
  459. newValue: {},
  460. });
  461. }
  462. else {
  463. return {
  464. operation: formatDisplay(events.type),
  465. key: formatDisplay(events.key),
  466. oldValue: events.oldValue,
  467. newValue: events.newValue,
  468. };
  469. }
  470. }
  471. function formatMutationType(type) {
  472. switch (type) {
  473. case MutationType.direct:
  474. return 'mutation';
  475. case MutationType.patchFunction:
  476. return '$patch';
  477. case MutationType.patchObject:
  478. return '$patch';
  479. default:
  480. return 'unknown';
  481. }
  482. }
  483. // timeline can be paused when directly changing the state
  484. let isTimelineActive = true;
  485. const componentStateTypes = [];
  486. const MUTATIONS_LAYER_ID = 'pinia:mutations';
  487. const INSPECTOR_ID = 'pinia';
  488. const { assign: assign$1 } = Object;
  489. /**
  490. * Gets the displayed name of a store in devtools
  491. *
  492. * @param id - id of the store
  493. * @returns a formatted string
  494. */
  495. const getStoreType = (id) => '🍍 ' + id;
  496. /**
  497. * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab
  498. * as soon as it is added to the application.
  499. *
  500. * @param app - Vue application
  501. * @param pinia - pinia instance
  502. */
  503. function registerPiniaDevtools(app, pinia) {
  504. setupDevtoolsPlugin({
  505. id: 'dev.esm.pinia',
  506. label: 'Pinia 🍍',
  507. logo: 'https://pinia.vuejs.org/logo.svg',
  508. packageName: 'pinia',
  509. homepage: 'https://pinia.vuejs.org',
  510. componentStateTypes,
  511. app,
  512. }, (api) => {
  513. if (typeof api.now !== 'function') {
  514. 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.');
  515. }
  516. api.addTimelineLayer({
  517. id: MUTATIONS_LAYER_ID,
  518. label: `Pinia 🍍`,
  519. color: 0xe5df88,
  520. });
  521. api.addInspector({
  522. id: INSPECTOR_ID,
  523. label: 'Pinia 🍍',
  524. icon: 'storage',
  525. treeFilterPlaceholder: 'Search stores',
  526. actions: [
  527. {
  528. icon: 'content_copy',
  529. action: () => {
  530. actionGlobalCopyState(pinia);
  531. },
  532. tooltip: 'Serialize and copy the state',
  533. },
  534. {
  535. icon: 'content_paste',
  536. action: async () => {
  537. await actionGlobalPasteState(pinia);
  538. api.sendInspectorTree(INSPECTOR_ID);
  539. api.sendInspectorState(INSPECTOR_ID);
  540. },
  541. tooltip: 'Replace the state with the content of your clipboard',
  542. },
  543. {
  544. icon: 'save',
  545. action: () => {
  546. actionGlobalSaveState(pinia);
  547. },
  548. tooltip: 'Save the state as a JSON file',
  549. },
  550. {
  551. icon: 'folder_open',
  552. action: async () => {
  553. await actionGlobalOpenStateFile(pinia);
  554. api.sendInspectorTree(INSPECTOR_ID);
  555. api.sendInspectorState(INSPECTOR_ID);
  556. },
  557. tooltip: 'Import the state from a JSON file',
  558. },
  559. ],
  560. nodeActions: [
  561. {
  562. icon: 'restore',
  563. tooltip: 'Reset the state (with "$reset")',
  564. action: (nodeId) => {
  565. const store = pinia._s.get(nodeId);
  566. if (!store) {
  567. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, 'warn');
  568. }
  569. else if (typeof store.$reset !== 'function') {
  570. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, 'warn');
  571. }
  572. else {
  573. store.$reset();
  574. toastMessage(`Store "${nodeId}" reset.`);
  575. }
  576. },
  577. },
  578. ],
  579. });
  580. api.on.inspectComponent((payload, ctx) => {
  581. const proxy = (payload.componentInstance &&
  582. payload.componentInstance.proxy);
  583. if (proxy && proxy._pStores) {
  584. const piniaStores = payload.componentInstance.proxy._pStores;
  585. Object.values(piniaStores).forEach((store) => {
  586. payload.instanceData.state.push({
  587. type: getStoreType(store.$id),
  588. key: 'state',
  589. editable: true,
  590. value: store._isOptionsAPI
  591. ? {
  592. _custom: {
  593. value: toRaw(store.$state),
  594. actions: [
  595. {
  596. icon: 'restore',
  597. tooltip: 'Reset the state of this store',
  598. action: () => store.$reset(),
  599. },
  600. ],
  601. },
  602. }
  603. : // NOTE: workaround to unwrap transferred refs
  604. Object.keys(store.$state).reduce((state, key) => {
  605. state[key] = store.$state[key];
  606. return state;
  607. }, {}),
  608. });
  609. if (store._getters && store._getters.length) {
  610. payload.instanceData.state.push({
  611. type: getStoreType(store.$id),
  612. key: 'getters',
  613. editable: false,
  614. value: store._getters.reduce((getters, key) => {
  615. try {
  616. getters[key] = store[key];
  617. }
  618. catch (error) {
  619. // @ts-expect-error: we just want to show it in devtools
  620. getters[key] = error;
  621. }
  622. return getters;
  623. }, {}),
  624. });
  625. }
  626. });
  627. }
  628. });
  629. api.on.getInspectorTree((payload) => {
  630. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  631. let stores = [pinia];
  632. stores = stores.concat(Array.from(pinia._s.values()));
  633. payload.rootNodes = (payload.filter
  634. ? stores.filter((store) => '$id' in store
  635. ? store.$id
  636. .toLowerCase()
  637. .includes(payload.filter.toLowerCase())
  638. : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase()))
  639. : stores).map(formatStoreForInspectorTree);
  640. }
  641. });
  642. api.on.getInspectorState((payload) => {
  643. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  644. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  645. ? pinia
  646. : pinia._s.get(payload.nodeId);
  647. if (!inspectedStore) {
  648. // this could be the selected store restored for a different project
  649. // so it's better not to say anything here
  650. return;
  651. }
  652. if (inspectedStore) {
  653. payload.state = formatStoreForInspectorState(inspectedStore);
  654. }
  655. }
  656. });
  657. api.on.editInspectorState((payload, ctx) => {
  658. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  659. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  660. ? pinia
  661. : pinia._s.get(payload.nodeId);
  662. if (!inspectedStore) {
  663. return toastMessage(`store "${payload.nodeId}" not found`, 'error');
  664. }
  665. const { path } = payload;
  666. if (!isPinia(inspectedStore)) {
  667. // access only the state
  668. if (path.length !== 1 ||
  669. !inspectedStore._customProperties.has(path[0]) ||
  670. path[0] in inspectedStore.$state) {
  671. path.unshift('$state');
  672. }
  673. }
  674. else {
  675. // Root access, we can omit the `.value` because the devtools API does it for us
  676. path.unshift('state');
  677. }
  678. isTimelineActive = false;
  679. payload.set(inspectedStore, path, payload.state.value);
  680. isTimelineActive = true;
  681. }
  682. });
  683. api.on.editComponentState((payload) => {
  684. if (payload.type.startsWith('🍍')) {
  685. const storeId = payload.type.replace(/^🍍\s*/, '');
  686. const store = pinia._s.get(storeId);
  687. if (!store) {
  688. return toastMessage(`store "${storeId}" not found`, 'error');
  689. }
  690. const { path } = payload;
  691. if (path[0] !== 'state') {
  692. return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`);
  693. }
  694. // rewrite the first entry to be able to directly set the state as
  695. // well as any other path
  696. path[0] = '$state';
  697. isTimelineActive = false;
  698. payload.set(store, path, payload.state.value);
  699. isTimelineActive = true;
  700. }
  701. });
  702. });
  703. }
  704. function addStoreToDevtools(app, store) {
  705. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  706. componentStateTypes.push(getStoreType(store.$id));
  707. }
  708. setupDevtoolsPlugin({
  709. id: 'dev.esm.pinia',
  710. label: 'Pinia 🍍',
  711. logo: 'https://pinia.vuejs.org/logo.svg',
  712. packageName: 'pinia',
  713. homepage: 'https://pinia.vuejs.org',
  714. componentStateTypes,
  715. app,
  716. settings: {
  717. logStoreChanges: {
  718. label: 'Notify about new/deleted stores',
  719. type: 'boolean',
  720. defaultValue: true,
  721. },
  722. // useEmojis: {
  723. // label: 'Use emojis in messages ⚡️',
  724. // type: 'boolean',
  725. // defaultValue: true,
  726. // },
  727. },
  728. }, (api) => {
  729. // gracefully handle errors
  730. const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;
  731. store.$onAction(({ after, onError, name, args }) => {
  732. const groupId = runningActionId++;
  733. api.addTimelineEvent({
  734. layerId: MUTATIONS_LAYER_ID,
  735. event: {
  736. time: now(),
  737. title: '🛫 ' + name,
  738. subtitle: 'start',
  739. data: {
  740. store: formatDisplay(store.$id),
  741. action: formatDisplay(name),
  742. args,
  743. },
  744. groupId,
  745. },
  746. });
  747. after((result) => {
  748. activeAction = undefined;
  749. api.addTimelineEvent({
  750. layerId: MUTATIONS_LAYER_ID,
  751. event: {
  752. time: now(),
  753. title: '🛬 ' + name,
  754. subtitle: 'end',
  755. data: {
  756. store: formatDisplay(store.$id),
  757. action: formatDisplay(name),
  758. args,
  759. result,
  760. },
  761. groupId,
  762. },
  763. });
  764. });
  765. onError((error) => {
  766. activeAction = undefined;
  767. api.addTimelineEvent({
  768. layerId: MUTATIONS_LAYER_ID,
  769. event: {
  770. time: now(),
  771. logType: 'error',
  772. title: '💥 ' + name,
  773. subtitle: 'end',
  774. data: {
  775. store: formatDisplay(store.$id),
  776. action: formatDisplay(name),
  777. args,
  778. error,
  779. },
  780. groupId,
  781. },
  782. });
  783. });
  784. }, true);
  785. store._customProperties.forEach((name) => {
  786. watch(() => unref(store[name]), (newValue, oldValue) => {
  787. api.notifyComponentUpdate();
  788. api.sendInspectorState(INSPECTOR_ID);
  789. if (isTimelineActive) {
  790. api.addTimelineEvent({
  791. layerId: MUTATIONS_LAYER_ID,
  792. event: {
  793. time: now(),
  794. title: 'Change',
  795. subtitle: name,
  796. data: {
  797. newValue,
  798. oldValue,
  799. },
  800. groupId: activeAction,
  801. },
  802. });
  803. }
  804. }, { deep: true });
  805. });
  806. store.$subscribe(({ events, type }, state) => {
  807. api.notifyComponentUpdate();
  808. api.sendInspectorState(INSPECTOR_ID);
  809. if (!isTimelineActive)
  810. return;
  811. // rootStore.state[store.id] = state
  812. const eventData = {
  813. time: now(),
  814. title: formatMutationType(type),
  815. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  816. groupId: activeAction,
  817. };
  818. if (type === MutationType.patchFunction) {
  819. eventData.subtitle = '⤵️';
  820. }
  821. else if (type === MutationType.patchObject) {
  822. eventData.subtitle = '🧩';
  823. }
  824. else if (events && !Array.isArray(events)) {
  825. eventData.subtitle = events.type;
  826. }
  827. if (events) {
  828. eventData.data['rawEvent(s)'] = {
  829. _custom: {
  830. display: 'DebuggerEvent',
  831. type: 'object',
  832. tooltip: 'raw DebuggerEvent[]',
  833. value: events,
  834. },
  835. };
  836. }
  837. api.addTimelineEvent({
  838. layerId: MUTATIONS_LAYER_ID,
  839. event: eventData,
  840. });
  841. }, { detached: true, flush: 'sync' });
  842. const hotUpdate = store._hotUpdate;
  843. store._hotUpdate = markRaw((newStore) => {
  844. hotUpdate(newStore);
  845. api.addTimelineEvent({
  846. layerId: MUTATIONS_LAYER_ID,
  847. event: {
  848. time: now(),
  849. title: '🔥 ' + store.$id,
  850. subtitle: 'HMR update',
  851. data: {
  852. store: formatDisplay(store.$id),
  853. info: formatDisplay(`HMR update`),
  854. },
  855. },
  856. });
  857. // update the devtools too
  858. api.notifyComponentUpdate();
  859. api.sendInspectorTree(INSPECTOR_ID);
  860. api.sendInspectorState(INSPECTOR_ID);
  861. });
  862. const { $dispose } = store;
  863. store.$dispose = () => {
  864. $dispose();
  865. api.notifyComponentUpdate();
  866. api.sendInspectorTree(INSPECTOR_ID);
  867. api.sendInspectorState(INSPECTOR_ID);
  868. api.getSettings().logStoreChanges &&
  869. toastMessage(`Disposed "${store.$id}" store 🗑`);
  870. };
  871. // trigger an update so it can display new registered stores
  872. api.notifyComponentUpdate();
  873. api.sendInspectorTree(INSPECTOR_ID);
  874. api.sendInspectorState(INSPECTOR_ID);
  875. api.getSettings().logStoreChanges &&
  876. toastMessage(`"${store.$id}" store installed 🆕`);
  877. });
  878. }
  879. let runningActionId = 0;
  880. let activeAction;
  881. /**
  882. * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the
  883. * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state
  884. * mutation to the action.
  885. *
  886. * @param store - store to patch
  887. * @param actionNames - list of actionst to patch
  888. */
  889. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  890. // original actions of the store as they are given by pinia. We are going to override them
  891. const actions = actionNames.reduce((storeActions, actionName) => {
  892. // use toRaw to avoid tracking #541
  893. storeActions[actionName] = toRaw(store)[actionName];
  894. return storeActions;
  895. }, {});
  896. for (const actionName in actions) {
  897. store[actionName] = function () {
  898. // the running action id is incremented in a before action hook
  899. const _actionId = runningActionId;
  900. const trackedStore = wrapWithProxy
  901. ? new Proxy(store, {
  902. get(...args) {
  903. activeAction = _actionId;
  904. return Reflect.get(...args);
  905. },
  906. set(...args) {
  907. activeAction = _actionId;
  908. return Reflect.set(...args);
  909. },
  910. })
  911. : store;
  912. // For Setup Stores we need https://github.com/tc39/proposal-async-context
  913. activeAction = _actionId;
  914. const retValue = actions[actionName].apply(trackedStore, arguments);
  915. // this is safer as async actions in Setup Stores would associate mutations done outside of the action
  916. activeAction = undefined;
  917. return retValue;
  918. };
  919. }
  920. }
  921. /**
  922. * pinia.use(devtoolsPlugin)
  923. */
  924. function devtoolsPlugin({ app, store, options }) {
  925. // HMR module
  926. if (store.$id.startsWith('__hot:')) {
  927. return;
  928. }
  929. // detect option api vs setup api
  930. store._isOptionsAPI = !!options.state;
  931. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  932. // Upgrade the HMR to also update the new actions
  933. const originalHotUpdate = store._hotUpdate;
  934. toRaw(store)._hotUpdate = function (newStore) {
  935. originalHotUpdate.apply(this, arguments);
  936. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  937. };
  938. addStoreToDevtools(app,
  939. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  940. store);
  941. }
  942. /**
  943. * Creates a Pinia instance to be used by the application
  944. */
  945. function createPinia() {
  946. const scope = effectScope(true);
  947. // NOTE: here we could check the window object for a state and directly set it
  948. // if there is anything like it with Vue 3 SSR
  949. const state = scope.run(() => ref({}));
  950. let _p = [];
  951. // plugins added before calling app.use(pinia)
  952. let toBeInstalled = [];
  953. const pinia = markRaw({
  954. install(app) {
  955. // this allows calling useStore() outside of a component setup after
  956. // installing pinia's plugin
  957. setActivePinia(pinia);
  958. if (!isVue2) {
  959. pinia._a = app;
  960. app.provide(piniaSymbol, pinia);
  961. app.config.globalProperties.$pinia = pinia;
  962. /* istanbul ignore else */
  963. if (USE_DEVTOOLS) {
  964. registerPiniaDevtools(app, pinia);
  965. }
  966. toBeInstalled.forEach((plugin) => _p.push(plugin));
  967. toBeInstalled = [];
  968. }
  969. },
  970. use(plugin) {
  971. if (!this._a && !isVue2) {
  972. toBeInstalled.push(plugin);
  973. }
  974. else {
  975. _p.push(plugin);
  976. }
  977. return this;
  978. },
  979. _p,
  980. // it's actually undefined here
  981. // @ts-expect-error
  982. _a: null,
  983. _e: scope,
  984. _s: new Map(),
  985. state,
  986. });
  987. // pinia devtools rely on dev only features so they cannot be forced unless
  988. // the dev build of Vue is used. Avoid old browsers like IE11.
  989. if (USE_DEVTOOLS && typeof Proxy !== 'undefined') {
  990. pinia.use(devtoolsPlugin);
  991. }
  992. return pinia;
  993. }
  994. /**
  995. * Checks if a function is a `StoreDefinition`.
  996. *
  997. * @param fn - object to test
  998. * @returns true if `fn` is a StoreDefinition
  999. */
  1000. const isUseStore = (fn) => {
  1001. return typeof fn === 'function' && typeof fn.$id === 'string';
  1002. };
  1003. /**
  1004. * Mutates in place `newState` with `oldState` to _hot update_ it. It will
  1005. * remove any key not existing in `newState` and recursively merge plain
  1006. * objects.
  1007. *
  1008. * @param newState - new state object to be patched
  1009. * @param oldState - old state that should be used to patch newState
  1010. * @returns - newState
  1011. */
  1012. function patchObject(newState, oldState) {
  1013. // no need to go through symbols because they cannot be serialized anyway
  1014. for (const key in oldState) {
  1015. const subPatch = oldState[key];
  1016. // skip the whole sub tree
  1017. if (!(key in newState)) {
  1018. continue;
  1019. }
  1020. const targetValue = newState[key];
  1021. if (isPlainObject(targetValue) &&
  1022. isPlainObject(subPatch) &&
  1023. !isRef(subPatch) &&
  1024. !isReactive(subPatch)) {
  1025. newState[key] = patchObject(targetValue, subPatch);
  1026. }
  1027. else {
  1028. // objects are either a bit more complex (e.g. refs) or primitives, so we
  1029. // just set the whole thing
  1030. if (isVue2) {
  1031. set(newState, key, subPatch);
  1032. }
  1033. else {
  1034. newState[key] = subPatch;
  1035. }
  1036. }
  1037. }
  1038. return newState;
  1039. }
  1040. /**
  1041. * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
  1042. *
  1043. * @example
  1044. * ```js
  1045. * const useUser = defineStore(...)
  1046. * if (import.meta.hot) {
  1047. * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
  1048. * }
  1049. * ```
  1050. *
  1051. * @param initialUseStore - return of the defineStore to hot update
  1052. * @param hot - `import.meta.hot`
  1053. */
  1054. function acceptHMRUpdate(initialUseStore, hot) {
  1055. // strip as much as possible from iife.prod
  1056. if (!(process.env.NODE_ENV !== 'production')) {
  1057. return () => { };
  1058. }
  1059. return (newModule) => {
  1060. const pinia = hot.data.pinia || initialUseStore._pinia;
  1061. if (!pinia) {
  1062. // this store is still not used
  1063. return;
  1064. }
  1065. // preserve the pinia instance across loads
  1066. hot.data.pinia = pinia;
  1067. // console.log('got data', newStore)
  1068. for (const exportName in newModule) {
  1069. const useStore = newModule[exportName];
  1070. // console.log('checking for', exportName)
  1071. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  1072. // console.log('Accepting update for', useStore.$id)
  1073. const id = useStore.$id;
  1074. if (id !== initialUseStore.$id) {
  1075. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  1076. // return import.meta.hot.invalidate()
  1077. return hot.invalidate();
  1078. }
  1079. const existingStore = pinia._s.get(id);
  1080. if (!existingStore) {
  1081. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  1082. return;
  1083. }
  1084. useStore(pinia, existingStore);
  1085. }
  1086. }
  1087. };
  1088. }
  1089. const noop = () => { };
  1090. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  1091. subscriptions.push(callback);
  1092. const removeSubscription = () => {
  1093. const idx = subscriptions.indexOf(callback);
  1094. if (idx > -1) {
  1095. subscriptions.splice(idx, 1);
  1096. onCleanup();
  1097. }
  1098. };
  1099. if (!detached && getCurrentScope()) {
  1100. onScopeDispose(removeSubscription);
  1101. }
  1102. return removeSubscription;
  1103. }
  1104. function triggerSubscriptions(subscriptions, ...args) {
  1105. subscriptions.slice().forEach((callback) => {
  1106. callback(...args);
  1107. });
  1108. }
  1109. const fallbackRunWithContext = (fn) => fn();
  1110. function mergeReactiveObjects(target, patchToApply) {
  1111. // Handle Map instances
  1112. if (target instanceof Map && patchToApply instanceof Map) {
  1113. patchToApply.forEach((value, key) => target.set(key, value));
  1114. }
  1115. // Handle Set instances
  1116. if (target instanceof Set && patchToApply instanceof Set) {
  1117. patchToApply.forEach(target.add, target);
  1118. }
  1119. // no need to go through symbols because they cannot be serialized anyway
  1120. for (const key in patchToApply) {
  1121. if (!patchToApply.hasOwnProperty(key))
  1122. continue;
  1123. const subPatch = patchToApply[key];
  1124. const targetValue = target[key];
  1125. if (isPlainObject(targetValue) &&
  1126. isPlainObject(subPatch) &&
  1127. target.hasOwnProperty(key) &&
  1128. !isRef(subPatch) &&
  1129. !isReactive(subPatch)) {
  1130. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1131. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1132. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1133. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1134. }
  1135. else {
  1136. // @ts-expect-error: subPatch is a valid value
  1137. target[key] = subPatch;
  1138. }
  1139. }
  1140. return target;
  1141. }
  1142. const skipHydrateSymbol = (process.env.NODE_ENV !== 'production')
  1143. ? Symbol('pinia:skipHydration')
  1144. : /* istanbul ignore next */ Symbol();
  1145. const skipHydrateMap = /*#__PURE__*/ new WeakMap();
  1146. /**
  1147. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1148. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1149. *
  1150. * @param obj - target object
  1151. * @returns obj
  1152. */
  1153. function skipHydrate(obj) {
  1154. return isVue2
  1155. ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
  1156. /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj
  1157. : Object.defineProperty(obj, skipHydrateSymbol, {});
  1158. }
  1159. /**
  1160. * Returns whether a value should be hydrated
  1161. *
  1162. * @param obj - target variable
  1163. * @returns true if `obj` should be hydrated
  1164. */
  1165. function shouldHydrate(obj) {
  1166. return isVue2
  1167. ? /* istanbul ignore next */ !skipHydrateMap.has(obj)
  1168. : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  1169. }
  1170. const { assign } = Object;
  1171. function isComputed(o) {
  1172. return !!(isRef(o) && o.effect);
  1173. }
  1174. function createOptionsStore(id, options, pinia, hot) {
  1175. const { state, actions, getters } = options;
  1176. const initialState = pinia.state.value[id];
  1177. let store;
  1178. function setup() {
  1179. if (!initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1180. /* istanbul ignore if */
  1181. if (isVue2) {
  1182. set(pinia.state.value, id, state ? state() : {});
  1183. }
  1184. else {
  1185. pinia.state.value[id] = state ? state() : {};
  1186. }
  1187. }
  1188. // avoid creating a state in pinia.state.value
  1189. const localState = (process.env.NODE_ENV !== 'production') && hot
  1190. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1191. toRefs(ref(state ? state() : {}).value)
  1192. : toRefs(pinia.state.value[id]);
  1193. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1194. if ((process.env.NODE_ENV !== 'production') && name in localState) {
  1195. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1196. }
  1197. computedGetters[name] = markRaw(computed(() => {
  1198. setActivePinia(pinia);
  1199. // it was created just before
  1200. const store = pinia._s.get(id);
  1201. // allow cross using stores
  1202. /* istanbul ignore next */
  1203. if (isVue2 && !store._r)
  1204. return;
  1205. // @ts-expect-error
  1206. // return getters![name].call(context, context)
  1207. // TODO: avoid reading the getter while assigning with a global variable
  1208. return getters[name].call(store, store);
  1209. }));
  1210. return computedGetters;
  1211. }, {}));
  1212. }
  1213. store = createSetupStore(id, setup, options, pinia, hot, true);
  1214. return store;
  1215. }
  1216. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1217. let scope;
  1218. const optionsForPlugin = assign({ actions: {} }, options);
  1219. /* istanbul ignore if */
  1220. if ((process.env.NODE_ENV !== 'production') && !pinia._e.active) {
  1221. throw new Error('Pinia destroyed');
  1222. }
  1223. // watcher options for $subscribe
  1224. const $subscribeOptions = {
  1225. deep: true,
  1226. // flush: 'post',
  1227. };
  1228. /* istanbul ignore else */
  1229. if ((process.env.NODE_ENV !== 'production') && !isVue2) {
  1230. $subscribeOptions.onTrigger = (event) => {
  1231. /* istanbul ignore else */
  1232. if (isListening) {
  1233. debuggerEvents = event;
  1234. // avoid triggering this while the store is being built and the state is being set in pinia
  1235. }
  1236. else if (isListening == false && !store._hotUpdating) {
  1237. // let patch send all the events together later
  1238. /* istanbul ignore else */
  1239. if (Array.isArray(debuggerEvents)) {
  1240. debuggerEvents.push(event);
  1241. }
  1242. else {
  1243. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1244. }
  1245. }
  1246. };
  1247. }
  1248. // internal state
  1249. let isListening; // set to true at the end
  1250. let isSyncListening; // set to true at the end
  1251. let subscriptions = [];
  1252. let actionSubscriptions = [];
  1253. let debuggerEvents;
  1254. const initialState = pinia.state.value[$id];
  1255. // avoid setting the state for option stores if it is set
  1256. // by the setup
  1257. if (!isOptionsStore && !initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1258. /* istanbul ignore if */
  1259. if (isVue2) {
  1260. set(pinia.state.value, $id, {});
  1261. }
  1262. else {
  1263. pinia.state.value[$id] = {};
  1264. }
  1265. }
  1266. const hotState = ref({});
  1267. // avoid triggering too many listeners
  1268. // https://github.com/vuejs/pinia/issues/1129
  1269. let activeListener;
  1270. function $patch(partialStateOrMutator) {
  1271. let subscriptionMutation;
  1272. isListening = isSyncListening = false;
  1273. // reset the debugger events since patches are sync
  1274. /* istanbul ignore else */
  1275. if ((process.env.NODE_ENV !== 'production')) {
  1276. debuggerEvents = [];
  1277. }
  1278. if (typeof partialStateOrMutator === 'function') {
  1279. partialStateOrMutator(pinia.state.value[$id]);
  1280. subscriptionMutation = {
  1281. type: MutationType.patchFunction,
  1282. storeId: $id,
  1283. events: debuggerEvents,
  1284. };
  1285. }
  1286. else {
  1287. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1288. subscriptionMutation = {
  1289. type: MutationType.patchObject,
  1290. payload: partialStateOrMutator,
  1291. storeId: $id,
  1292. events: debuggerEvents,
  1293. };
  1294. }
  1295. const myListenerId = (activeListener = Symbol());
  1296. nextTick().then(() => {
  1297. if (activeListener === myListenerId) {
  1298. isListening = true;
  1299. }
  1300. });
  1301. isSyncListening = true;
  1302. // because we paused the watcher, we need to manually call the subscriptions
  1303. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1304. }
  1305. const $reset = isOptionsStore
  1306. ? function $reset() {
  1307. const { state } = options;
  1308. const newState = state ? state() : {};
  1309. // we use a patch to group all changes into one single subscription
  1310. this.$patch(($state) => {
  1311. assign($state, newState);
  1312. });
  1313. }
  1314. : /* istanbul ignore next */
  1315. (process.env.NODE_ENV !== 'production')
  1316. ? () => {
  1317. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1318. }
  1319. : noop;
  1320. function $dispose() {
  1321. scope.stop();
  1322. subscriptions = [];
  1323. actionSubscriptions = [];
  1324. pinia._s.delete($id);
  1325. }
  1326. /**
  1327. * Wraps an action to handle subscriptions.
  1328. *
  1329. * @param name - name of the action
  1330. * @param action - action to wrap
  1331. * @returns a wrapped action to handle subscriptions
  1332. */
  1333. function wrapAction(name, action) {
  1334. return function () {
  1335. setActivePinia(pinia);
  1336. const args = Array.from(arguments);
  1337. const afterCallbackList = [];
  1338. const onErrorCallbackList = [];
  1339. function after(callback) {
  1340. afterCallbackList.push(callback);
  1341. }
  1342. function onError(callback) {
  1343. onErrorCallbackList.push(callback);
  1344. }
  1345. // @ts-expect-error
  1346. triggerSubscriptions(actionSubscriptions, {
  1347. args,
  1348. name,
  1349. store,
  1350. after,
  1351. onError,
  1352. });
  1353. let ret;
  1354. try {
  1355. ret = action.apply(this && this.$id === $id ? this : store, args);
  1356. // handle sync errors
  1357. }
  1358. catch (error) {
  1359. triggerSubscriptions(onErrorCallbackList, error);
  1360. throw error;
  1361. }
  1362. if (ret instanceof Promise) {
  1363. return ret
  1364. .then((value) => {
  1365. triggerSubscriptions(afterCallbackList, value);
  1366. return value;
  1367. })
  1368. .catch((error) => {
  1369. triggerSubscriptions(onErrorCallbackList, error);
  1370. return Promise.reject(error);
  1371. });
  1372. }
  1373. // trigger after callbacks
  1374. triggerSubscriptions(afterCallbackList, ret);
  1375. return ret;
  1376. };
  1377. }
  1378. const _hmrPayload = /*#__PURE__*/ markRaw({
  1379. actions: {},
  1380. getters: {},
  1381. state: [],
  1382. hotState,
  1383. });
  1384. const partialStore = {
  1385. _p: pinia,
  1386. // _s: scope,
  1387. $id,
  1388. $onAction: addSubscription.bind(null, actionSubscriptions),
  1389. $patch,
  1390. $reset,
  1391. $subscribe(callback, options = {}) {
  1392. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1393. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1394. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1395. callback({
  1396. storeId: $id,
  1397. type: MutationType.direct,
  1398. events: debuggerEvents,
  1399. }, state);
  1400. }
  1401. }, assign({}, $subscribeOptions, options)));
  1402. return removeSubscription;
  1403. },
  1404. $dispose,
  1405. };
  1406. /* istanbul ignore if */
  1407. if (isVue2) {
  1408. // start as non ready
  1409. partialStore._r = false;
  1410. }
  1411. const store = reactive((process.env.NODE_ENV !== 'production') || USE_DEVTOOLS
  1412. ? assign({
  1413. _hmrPayload,
  1414. _customProperties: markRaw(new Set()), // devtools custom properties
  1415. }, partialStore
  1416. // must be added later
  1417. // setupStore
  1418. )
  1419. : partialStore);
  1420. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1421. // creating infinite loops.
  1422. pinia._s.set($id, store);
  1423. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1424. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1425. const setupStore = pinia._e.run(() => {
  1426. scope = effectScope();
  1427. return runWithContext(() => scope.run(setup));
  1428. });
  1429. // overwrite existing actions to support $onAction
  1430. for (const key in setupStore) {
  1431. const prop = setupStore[key];
  1432. if ((isRef(prop) && !isComputed(prop)) || isReactive(prop)) {
  1433. // mark it as a piece of state to be serialized
  1434. if ((process.env.NODE_ENV !== 'production') && hot) {
  1435. set(hotState.value, key, toRef(setupStore, key));
  1436. // createOptionStore directly sets the state in pinia.state.value so we
  1437. // can just skip that
  1438. }
  1439. else if (!isOptionsStore) {
  1440. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1441. if (initialState && shouldHydrate(prop)) {
  1442. if (isRef(prop)) {
  1443. prop.value = initialState[key];
  1444. }
  1445. else {
  1446. // probably a reactive object, lets recursively assign
  1447. // @ts-expect-error: prop is unknown
  1448. mergeReactiveObjects(prop, initialState[key]);
  1449. }
  1450. }
  1451. // transfer the ref to the pinia state to keep everything in sync
  1452. /* istanbul ignore if */
  1453. if (isVue2) {
  1454. set(pinia.state.value[$id], key, prop);
  1455. }
  1456. else {
  1457. pinia.state.value[$id][key] = prop;
  1458. }
  1459. }
  1460. /* istanbul ignore else */
  1461. if ((process.env.NODE_ENV !== 'production')) {
  1462. _hmrPayload.state.push(key);
  1463. }
  1464. // action
  1465. }
  1466. else if (typeof prop === 'function') {
  1467. // @ts-expect-error: we are overriding the function we avoid wrapping if
  1468. const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : wrapAction(key, prop);
  1469. // this a hot module replacement store because the hotUpdate method needs
  1470. // to do it with the right context
  1471. /* istanbul ignore if */
  1472. if (isVue2) {
  1473. set(setupStore, key, actionValue);
  1474. }
  1475. else {
  1476. // @ts-expect-error
  1477. setupStore[key] = actionValue;
  1478. }
  1479. /* istanbul ignore else */
  1480. if ((process.env.NODE_ENV !== 'production')) {
  1481. _hmrPayload.actions[key] = prop;
  1482. }
  1483. // list actions so they can be used in plugins
  1484. // @ts-expect-error
  1485. optionsForPlugin.actions[key] = prop;
  1486. }
  1487. else if ((process.env.NODE_ENV !== 'production')) {
  1488. // add getters for devtools
  1489. if (isComputed(prop)) {
  1490. _hmrPayload.getters[key] = isOptionsStore
  1491. ? // @ts-expect-error
  1492. options.getters[key]
  1493. : prop;
  1494. if (IS_CLIENT) {
  1495. const getters = setupStore._getters ||
  1496. // @ts-expect-error: same
  1497. (setupStore._getters = markRaw([]));
  1498. getters.push(key);
  1499. }
  1500. }
  1501. }
  1502. }
  1503. // add the state, getters, and action properties
  1504. /* istanbul ignore if */
  1505. if (isVue2) {
  1506. Object.keys(setupStore).forEach((key) => {
  1507. set(store, key, setupStore[key]);
  1508. });
  1509. }
  1510. else {
  1511. assign(store, setupStore);
  1512. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1513. // Make `storeToRefs()` work with `reactive()` #799
  1514. assign(toRaw(store), setupStore);
  1515. }
  1516. // use this instead of a computed with setter to be able to create it anywhere
  1517. // without linking the computed lifespan to wherever the store is first
  1518. // created.
  1519. Object.defineProperty(store, '$state', {
  1520. get: () => ((process.env.NODE_ENV !== 'production') && hot ? hotState.value : pinia.state.value[$id]),
  1521. set: (state) => {
  1522. /* istanbul ignore if */
  1523. if ((process.env.NODE_ENV !== 'production') && hot) {
  1524. throw new Error('cannot set hotState');
  1525. }
  1526. $patch(($state) => {
  1527. assign($state, state);
  1528. });
  1529. },
  1530. });
  1531. // add the hotUpdate before plugins to allow them to override it
  1532. /* istanbul ignore else */
  1533. if ((process.env.NODE_ENV !== 'production')) {
  1534. store._hotUpdate = markRaw((newStore) => {
  1535. store._hotUpdating = true;
  1536. newStore._hmrPayload.state.forEach((stateKey) => {
  1537. if (stateKey in store.$state) {
  1538. const newStateTarget = newStore.$state[stateKey];
  1539. const oldStateSource = store.$state[stateKey];
  1540. if (typeof newStateTarget === 'object' &&
  1541. isPlainObject(newStateTarget) &&
  1542. isPlainObject(oldStateSource)) {
  1543. patchObject(newStateTarget, oldStateSource);
  1544. }
  1545. else {
  1546. // transfer the ref
  1547. newStore.$state[stateKey] = oldStateSource;
  1548. }
  1549. }
  1550. // patch direct access properties to allow store.stateProperty to work as
  1551. // store.$state.stateProperty
  1552. set(store, stateKey, toRef(newStore.$state, stateKey));
  1553. });
  1554. // remove deleted state properties
  1555. Object.keys(store.$state).forEach((stateKey) => {
  1556. if (!(stateKey in newStore.$state)) {
  1557. del(store, stateKey);
  1558. }
  1559. });
  1560. // avoid devtools logging this as a mutation
  1561. isListening = false;
  1562. isSyncListening = false;
  1563. pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState');
  1564. isSyncListening = true;
  1565. nextTick().then(() => {
  1566. isListening = true;
  1567. });
  1568. for (const actionName in newStore._hmrPayload.actions) {
  1569. const action = newStore[actionName];
  1570. set(store, actionName, wrapAction(actionName, action));
  1571. }
  1572. // TODO: does this work in both setup and option store?
  1573. for (const getterName in newStore._hmrPayload.getters) {
  1574. const getter = newStore._hmrPayload.getters[getterName];
  1575. const getterValue = isOptionsStore
  1576. ? // special handling of options api
  1577. computed(() => {
  1578. setActivePinia(pinia);
  1579. return getter.call(store, store);
  1580. })
  1581. : getter;
  1582. set(store, getterName, getterValue);
  1583. }
  1584. // remove deleted getters
  1585. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1586. if (!(key in newStore._hmrPayload.getters)) {
  1587. del(store, key);
  1588. }
  1589. });
  1590. // remove old actions
  1591. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1592. if (!(key in newStore._hmrPayload.actions)) {
  1593. del(store, key);
  1594. }
  1595. });
  1596. // update the values used in devtools and to allow deleting new properties later on
  1597. store._hmrPayload = newStore._hmrPayload;
  1598. store._getters = newStore._getters;
  1599. store._hotUpdating = false;
  1600. });
  1601. }
  1602. if (USE_DEVTOOLS) {
  1603. const nonEnumerable = {
  1604. writable: true,
  1605. configurable: true,
  1606. // avoid warning on devtools trying to display this property
  1607. enumerable: false,
  1608. };
  1609. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1610. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1611. });
  1612. }
  1613. /* istanbul ignore if */
  1614. if (isVue2) {
  1615. // mark the store as ready before plugins
  1616. store._r = true;
  1617. }
  1618. // apply all plugins
  1619. pinia._p.forEach((extender) => {
  1620. /* istanbul ignore else */
  1621. if (USE_DEVTOOLS) {
  1622. const extensions = scope.run(() => extender({
  1623. store,
  1624. app: pinia._a,
  1625. pinia,
  1626. options: optionsForPlugin,
  1627. }));
  1628. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1629. assign(store, extensions);
  1630. }
  1631. else {
  1632. assign(store, scope.run(() => extender({
  1633. store,
  1634. app: pinia._a,
  1635. pinia,
  1636. options: optionsForPlugin,
  1637. })));
  1638. }
  1639. });
  1640. if ((process.env.NODE_ENV !== 'production') &&
  1641. 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 ((process.env.NODE_ENV !== 'production') && 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. ((process.env.NODE_ENV === 'test') && activePinia && activePinia._testing ? null : pinia) ||
  1683. (hasContext ? inject(piniaSymbol, null) : null);
  1684. if (pinia)
  1685. setActivePinia(pinia);
  1686. if ((process.env.NODE_ENV !== 'production') && !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. if ((process.env.NODE_ENV !== 'production')) {
  1703. // @ts-expect-error: not the right inferred type
  1704. useStore._pinia = pinia;
  1705. }
  1706. }
  1707. const store = pinia._s.get(id);
  1708. if ((process.env.NODE_ENV !== 'production') && 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 ((process.env.NODE_ENV !== 'production') && 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 ((process.env.NODE_ENV !== 'production') && 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 };