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.

2059 lines
76 KiB

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