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.

2035 lines
73 KiB

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