pinia.mjs 72 KB

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