pinia.iife.js 81 KB

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