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.

2181 lines
81 KiB

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