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.

2221 lines
83 KiB

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