pinia.cjs 73 KB

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