pinia.esm-browser.js 70 KB

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