pinia.cjs 73 KB

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