You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2043 lines
75 KiB

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