pinia.mjs 72 KB

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