pinia.cjs 74 KB

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