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.

2005 lines
73 KiB

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