pinia.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. import {
  2. setupDevtoolsPlugin
  3. } from "./chunk-YFT6OQ5R.js";
  4. import {
  5. computed,
  6. effectScope,
  7. getCurrentInstance,
  8. getCurrentScope,
  9. hasInjectionContext,
  10. inject,
  11. isReactive,
  12. isRef,
  13. markRaw,
  14. nextTick,
  15. onScopeDispose,
  16. reactive,
  17. ref,
  18. toRaw,
  19. toRef,
  20. toRefs,
  21. unref,
  22. watch
  23. } from "./chunk-ZIH63DMU.js";
  24. // node_modules/vue-demi/lib/index.mjs
  25. var isVue2 = false;
  26. function set(target, key, val) {
  27. if (Array.isArray(target)) {
  28. target.length = Math.max(target.length, key);
  29. target.splice(key, 1, val);
  30. return val;
  31. }
  32. target[key] = val;
  33. return val;
  34. }
  35. function del(target, key) {
  36. if (Array.isArray(target)) {
  37. target.splice(key, 1);
  38. return;
  39. }
  40. delete target[key];
  41. }
  42. // node_modules/pinia/dist/pinia.mjs
  43. var activePinia;
  44. var setActivePinia = (pinia) => activePinia = pinia;
  45. var getActivePinia = () => hasInjectionContext() && inject(piniaSymbol) || activePinia;
  46. var piniaSymbol = true ? Symbol("pinia") : (
  47. /* istanbul ignore next */
  48. Symbol()
  49. );
  50. function isPlainObject(o) {
  51. return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
  52. }
  53. var MutationType;
  54. (function(MutationType2) {
  55. MutationType2["direct"] = "direct";
  56. MutationType2["patchObject"] = "patch object";
  57. MutationType2["patchFunction"] = "patch function";
  58. })(MutationType || (MutationType = {}));
  59. var IS_CLIENT = typeof window !== "undefined";
  60. var _global = (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })();
  61. function bom(blob, { autoBom = false } = {}) {
  62. if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  63. return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
  64. }
  65. return blob;
  66. }
  67. function download(url, name, opts) {
  68. const xhr = new XMLHttpRequest();
  69. xhr.open("GET", url);
  70. xhr.responseType = "blob";
  71. xhr.onload = function() {
  72. saveAs(xhr.response, name, opts);
  73. };
  74. xhr.onerror = function() {
  75. console.error("could not download file");
  76. };
  77. xhr.send();
  78. }
  79. function corsEnabled(url) {
  80. const xhr = new XMLHttpRequest();
  81. xhr.open("HEAD", url, false);
  82. try {
  83. xhr.send();
  84. } catch (e) {
  85. }
  86. return xhr.status >= 200 && xhr.status <= 299;
  87. }
  88. function click(node) {
  89. try {
  90. node.dispatchEvent(new MouseEvent("click"));
  91. } catch (e) {
  92. const evt = document.createEvent("MouseEvents");
  93. evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  94. node.dispatchEvent(evt);
  95. }
  96. }
  97. var _navigator = typeof navigator === "object" ? navigator : { userAgent: "" };
  98. var isMacOSWebView = (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))();
  99. var saveAs = !IS_CLIENT ? () => {
  100. } : (
  101. // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  102. typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : (
  103. // Use msSaveOrOpenBlob as a second approach
  104. "msSaveOrOpenBlob" in _navigator ? msSaveAs : (
  105. // Fallback to using FileReader and a popup
  106. fileSaverSaveAs
  107. )
  108. )
  109. );
  110. function downloadSaveAs(blob, name = "download", opts) {
  111. const a = document.createElement("a");
  112. a.download = name;
  113. a.rel = "noopener";
  114. if (typeof blob === "string") {
  115. a.href = blob;
  116. if (a.origin !== location.origin) {
  117. if (corsEnabled(a.href)) {
  118. download(blob, name, opts);
  119. } else {
  120. a.target = "_blank";
  121. click(a);
  122. }
  123. } else {
  124. click(a);
  125. }
  126. } else {
  127. a.href = URL.createObjectURL(blob);
  128. setTimeout(function() {
  129. URL.revokeObjectURL(a.href);
  130. }, 4e4);
  131. setTimeout(function() {
  132. click(a);
  133. }, 0);
  134. }
  135. }
  136. function msSaveAs(blob, name = "download", opts) {
  137. if (typeof blob === "string") {
  138. if (corsEnabled(blob)) {
  139. download(blob, name, opts);
  140. } else {
  141. const a = document.createElement("a");
  142. a.href = blob;
  143. a.target = "_blank";
  144. setTimeout(function() {
  145. click(a);
  146. });
  147. }
  148. } else {
  149. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  150. }
  151. }
  152. function fileSaverSaveAs(blob, name, opts, popup) {
  153. popup = popup || open("", "_blank");
  154. if (popup) {
  155. popup.document.title = popup.document.body.innerText = "downloading...";
  156. }
  157. if (typeof blob === "string")
  158. return download(blob, name, opts);
  159. const force = blob.type === "application/octet-stream";
  160. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || "safari" in _global;
  161. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  162. if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") {
  163. const reader = new FileReader();
  164. reader.onloadend = function() {
  165. let url = reader.result;
  166. if (typeof url !== "string") {
  167. popup = null;
  168. throw new Error("Wrong reader.result type");
  169. }
  170. url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
  171. if (popup) {
  172. popup.location.href = url;
  173. } else {
  174. location.assign(url);
  175. }
  176. popup = null;
  177. };
  178. reader.readAsDataURL(blob);
  179. } else {
  180. const url = URL.createObjectURL(blob);
  181. if (popup)
  182. popup.location.assign(url);
  183. else
  184. location.href = url;
  185. popup = null;
  186. setTimeout(function() {
  187. URL.revokeObjectURL(url);
  188. }, 4e4);
  189. }
  190. }
  191. function toastMessage(message, type) {
  192. const piniaMessage = "🍍 " + message;
  193. if (typeof __VUE_DEVTOOLS_TOAST__ === "function") {
  194. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  195. } else if (type === "error") {
  196. console.error(piniaMessage);
  197. } else if (type === "warn") {
  198. console.warn(piniaMessage);
  199. } else {
  200. console.log(piniaMessage);
  201. }
  202. }
  203. function isPinia(o) {
  204. return "_a" in o && "install" in o;
  205. }
  206. function checkClipboardAccess() {
  207. if (!("clipboard" in navigator)) {
  208. toastMessage(`Your browser doesn't support the Clipboard API`, "error");
  209. return true;
  210. }
  211. }
  212. function checkNotFocusedError(error) {
  213. if (error instanceof Error && error.message.toLowerCase().includes("document is not focused")) {
  214. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', "warn");
  215. return true;
  216. }
  217. return false;
  218. }
  219. async function actionGlobalCopyState(pinia) {
  220. if (checkClipboardAccess())
  221. return;
  222. try {
  223. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  224. toastMessage("Global state copied to clipboard.");
  225. } catch (error) {
  226. if (checkNotFocusedError(error))
  227. return;
  228. toastMessage(`Failed to serialize the state. Check the console for more details.`, "error");
  229. console.error(error);
  230. }
  231. }
  232. async function actionGlobalPasteState(pinia) {
  233. if (checkClipboardAccess())
  234. return;
  235. try {
  236. loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));
  237. toastMessage("Global state pasted from clipboard.");
  238. } catch (error) {
  239. if (checkNotFocusedError(error))
  240. return;
  241. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, "error");
  242. console.error(error);
  243. }
  244. }
  245. async function actionGlobalSaveState(pinia) {
  246. try {
  247. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  248. type: "text/plain;charset=utf-8"
  249. }), "pinia-state.json");
  250. } catch (error) {
  251. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
  252. console.error(error);
  253. }
  254. }
  255. var fileInput;
  256. function getFileOpener() {
  257. if (!fileInput) {
  258. fileInput = document.createElement("input");
  259. fileInput.type = "file";
  260. fileInput.accept = ".json";
  261. }
  262. function openFile() {
  263. return new Promise((resolve, reject) => {
  264. fileInput.onchange = async () => {
  265. const files = fileInput.files;
  266. if (!files)
  267. return resolve(null);
  268. const file = files.item(0);
  269. if (!file)
  270. return resolve(null);
  271. return resolve({ text: await file.text(), file });
  272. };
  273. fileInput.oncancel = () => resolve(null);
  274. fileInput.onerror = reject;
  275. fileInput.click();
  276. });
  277. }
  278. return openFile;
  279. }
  280. async function actionGlobalOpenStateFile(pinia) {
  281. try {
  282. const open2 = getFileOpener();
  283. const result = await open2();
  284. if (!result)
  285. return;
  286. const { text, file } = result;
  287. loadStoresState(pinia, JSON.parse(text));
  288. toastMessage(`Global state imported from "${file.name}".`);
  289. } catch (error) {
  290. toastMessage(`Failed to import the state from JSON. Check the console for more details.`, "error");
  291. console.error(error);
  292. }
  293. }
  294. function loadStoresState(pinia, state) {
  295. for (const key in state) {
  296. const storeState = pinia.state.value[key];
  297. if (storeState) {
  298. Object.assign(storeState, state[key]);
  299. } else {
  300. pinia.state.value[key] = state[key];
  301. }
  302. }
  303. }
  304. function formatDisplay(display) {
  305. return {
  306. _custom: {
  307. display
  308. }
  309. };
  310. }
  311. var PINIA_ROOT_LABEL = "🍍 Pinia (root)";
  312. var PINIA_ROOT_ID = "_root";
  313. function formatStoreForInspectorTree(store) {
  314. return isPinia(store) ? {
  315. id: PINIA_ROOT_ID,
  316. label: PINIA_ROOT_LABEL
  317. } : {
  318. id: store.$id,
  319. label: store.$id
  320. };
  321. }
  322. function formatStoreForInspectorState(store) {
  323. if (isPinia(store)) {
  324. const storeNames = Array.from(store._s.keys());
  325. const storeMap = store._s;
  326. const state2 = {
  327. state: storeNames.map((storeId) => ({
  328. editable: true,
  329. key: storeId,
  330. value: store.state.value[storeId]
  331. })),
  332. getters: storeNames.filter((id) => storeMap.get(id)._getters).map((id) => {
  333. const store2 = storeMap.get(id);
  334. return {
  335. editable: false,
  336. key: id,
  337. value: store2._getters.reduce((getters, key) => {
  338. getters[key] = store2[key];
  339. return getters;
  340. }, {})
  341. };
  342. })
  343. };
  344. return state2;
  345. }
  346. const state = {
  347. state: Object.keys(store.$state).map((key) => ({
  348. editable: true,
  349. key,
  350. value: store.$state[key]
  351. }))
  352. };
  353. if (store._getters && store._getters.length) {
  354. state.getters = store._getters.map((getterName) => ({
  355. editable: false,
  356. key: getterName,
  357. value: store[getterName]
  358. }));
  359. }
  360. if (store._customProperties.size) {
  361. state.customProperties = Array.from(store._customProperties).map((key) => ({
  362. editable: true,
  363. key,
  364. value: store[key]
  365. }));
  366. }
  367. return state;
  368. }
  369. function formatEventData(events) {
  370. if (!events)
  371. return {};
  372. if (Array.isArray(events)) {
  373. return events.reduce((data, event) => {
  374. data.keys.push(event.key);
  375. data.operations.push(event.type);
  376. data.oldValue[event.key] = event.oldValue;
  377. data.newValue[event.key] = event.newValue;
  378. return data;
  379. }, {
  380. oldValue: {},
  381. keys: [],
  382. operations: [],
  383. newValue: {}
  384. });
  385. } else {
  386. return {
  387. operation: formatDisplay(events.type),
  388. key: formatDisplay(events.key),
  389. oldValue: events.oldValue,
  390. newValue: events.newValue
  391. };
  392. }
  393. }
  394. function formatMutationType(type) {
  395. switch (type) {
  396. case MutationType.direct:
  397. return "mutation";
  398. case MutationType.patchFunction:
  399. return "$patch";
  400. case MutationType.patchObject:
  401. return "$patch";
  402. default:
  403. return "unknown";
  404. }
  405. }
  406. var isTimelineActive = true;
  407. var componentStateTypes = [];
  408. var MUTATIONS_LAYER_ID = "pinia:mutations";
  409. var INSPECTOR_ID = "pinia";
  410. var { assign: assign$1 } = Object;
  411. var getStoreType = (id) => "🍍 " + id;
  412. function registerPiniaDevtools(app, pinia) {
  413. setupDevtoolsPlugin({
  414. id: "dev.esm.pinia",
  415. label: "Pinia 🍍",
  416. logo: "https://pinia.vuejs.org/logo.svg",
  417. packageName: "pinia",
  418. homepage: "https://pinia.vuejs.org",
  419. componentStateTypes,
  420. app
  421. }, (api) => {
  422. if (typeof api.now !== "function") {
  423. 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.");
  424. }
  425. api.addTimelineLayer({
  426. id: MUTATIONS_LAYER_ID,
  427. label: `Pinia 🍍`,
  428. color: 15064968
  429. });
  430. api.addInspector({
  431. id: INSPECTOR_ID,
  432. label: "Pinia 🍍",
  433. icon: "storage",
  434. treeFilterPlaceholder: "Search stores",
  435. actions: [
  436. {
  437. icon: "content_copy",
  438. action: () => {
  439. actionGlobalCopyState(pinia);
  440. },
  441. tooltip: "Serialize and copy the state"
  442. },
  443. {
  444. icon: "content_paste",
  445. action: async () => {
  446. await actionGlobalPasteState(pinia);
  447. api.sendInspectorTree(INSPECTOR_ID);
  448. api.sendInspectorState(INSPECTOR_ID);
  449. },
  450. tooltip: "Replace the state with the content of your clipboard"
  451. },
  452. {
  453. icon: "save",
  454. action: () => {
  455. actionGlobalSaveState(pinia);
  456. },
  457. tooltip: "Save the state as a JSON file"
  458. },
  459. {
  460. icon: "folder_open",
  461. action: async () => {
  462. await actionGlobalOpenStateFile(pinia);
  463. api.sendInspectorTree(INSPECTOR_ID);
  464. api.sendInspectorState(INSPECTOR_ID);
  465. },
  466. tooltip: "Import the state from a JSON file"
  467. }
  468. ],
  469. nodeActions: [
  470. {
  471. icon: "restore",
  472. tooltip: 'Reset the state (with "$reset")',
  473. action: (nodeId) => {
  474. const store = pinia._s.get(nodeId);
  475. if (!store) {
  476. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, "warn");
  477. } else if (typeof store.$reset !== "function") {
  478. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, "warn");
  479. } else {
  480. store.$reset();
  481. toastMessage(`Store "${nodeId}" reset.`);
  482. }
  483. }
  484. }
  485. ]
  486. });
  487. api.on.inspectComponent((payload, ctx) => {
  488. const proxy = payload.componentInstance && payload.componentInstance.proxy;
  489. if (proxy && proxy._pStores) {
  490. const piniaStores = payload.componentInstance.proxy._pStores;
  491. Object.values(piniaStores).forEach((store) => {
  492. payload.instanceData.state.push({
  493. type: getStoreType(store.$id),
  494. key: "state",
  495. editable: true,
  496. value: store._isOptionsAPI ? {
  497. _custom: {
  498. value: toRaw(store.$state),
  499. actions: [
  500. {
  501. icon: "restore",
  502. tooltip: "Reset the state of this store",
  503. action: () => store.$reset()
  504. }
  505. ]
  506. }
  507. } : (
  508. // NOTE: workaround to unwrap transferred refs
  509. Object.keys(store.$state).reduce((state, key) => {
  510. state[key] = store.$state[key];
  511. return state;
  512. }, {})
  513. )
  514. });
  515. if (store._getters && store._getters.length) {
  516. payload.instanceData.state.push({
  517. type: getStoreType(store.$id),
  518. key: "getters",
  519. editable: false,
  520. value: store._getters.reduce((getters, key) => {
  521. try {
  522. getters[key] = store[key];
  523. } catch (error) {
  524. getters[key] = error;
  525. }
  526. return getters;
  527. }, {})
  528. });
  529. }
  530. });
  531. }
  532. });
  533. api.on.getInspectorTree((payload) => {
  534. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  535. let stores = [pinia];
  536. stores = stores.concat(Array.from(pinia._s.values()));
  537. payload.rootNodes = (payload.filter ? stores.filter((store) => "$id" in store ? store.$id.toLowerCase().includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) : stores).map(formatStoreForInspectorTree);
  538. }
  539. });
  540. globalThis.$pinia = pinia;
  541. api.on.getInspectorState((payload) => {
  542. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  543. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  544. if (!inspectedStore) {
  545. return;
  546. }
  547. if (inspectedStore) {
  548. if (payload.nodeId !== PINIA_ROOT_ID)
  549. globalThis.$store = toRaw(inspectedStore);
  550. payload.state = formatStoreForInspectorState(inspectedStore);
  551. }
  552. }
  553. });
  554. api.on.editInspectorState((payload, ctx) => {
  555. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  556. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  557. if (!inspectedStore) {
  558. return toastMessage(`store "${payload.nodeId}" not found`, "error");
  559. }
  560. const { path } = payload;
  561. if (!isPinia(inspectedStore)) {
  562. if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) {
  563. path.unshift("$state");
  564. }
  565. } else {
  566. path.unshift("state");
  567. }
  568. isTimelineActive = false;
  569. payload.set(inspectedStore, path, payload.state.value);
  570. isTimelineActive = true;
  571. }
  572. });
  573. api.on.editComponentState((payload) => {
  574. if (payload.type.startsWith("🍍")) {
  575. const storeId = payload.type.replace(/^🍍\s*/, "");
  576. const store = pinia._s.get(storeId);
  577. if (!store) {
  578. return toastMessage(`store "${storeId}" not found`, "error");
  579. }
  580. const { path } = payload;
  581. if (path[0] !== "state") {
  582. return toastMessage(`Invalid path for store "${storeId}":
  583. ${path}
  584. Only state can be modified.`);
  585. }
  586. path[0] = "$state";
  587. isTimelineActive = false;
  588. payload.set(store, path, payload.state.value);
  589. isTimelineActive = true;
  590. }
  591. });
  592. });
  593. }
  594. function addStoreToDevtools(app, store) {
  595. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  596. componentStateTypes.push(getStoreType(store.$id));
  597. }
  598. setupDevtoolsPlugin({
  599. id: "dev.esm.pinia",
  600. label: "Pinia 🍍",
  601. logo: "https://pinia.vuejs.org/logo.svg",
  602. packageName: "pinia",
  603. homepage: "https://pinia.vuejs.org",
  604. componentStateTypes,
  605. app,
  606. settings: {
  607. logStoreChanges: {
  608. label: "Notify about new/deleted stores",
  609. type: "boolean",
  610. defaultValue: true
  611. }
  612. // useEmojis: {
  613. // label: 'Use emojis in messages ⚡️',
  614. // type: 'boolean',
  615. // defaultValue: true,
  616. // },
  617. }
  618. }, (api) => {
  619. const now = typeof api.now === "function" ? api.now.bind(api) : Date.now;
  620. store.$onAction(({ after, onError, name, args }) => {
  621. const groupId = runningActionId++;
  622. api.addTimelineEvent({
  623. layerId: MUTATIONS_LAYER_ID,
  624. event: {
  625. time: now(),
  626. title: "🛫 " + name,
  627. subtitle: "start",
  628. data: {
  629. store: formatDisplay(store.$id),
  630. action: formatDisplay(name),
  631. args
  632. },
  633. groupId
  634. }
  635. });
  636. after((result) => {
  637. activeAction = void 0;
  638. api.addTimelineEvent({
  639. layerId: MUTATIONS_LAYER_ID,
  640. event: {
  641. time: now(),
  642. title: "🛬 " + name,
  643. subtitle: "end",
  644. data: {
  645. store: formatDisplay(store.$id),
  646. action: formatDisplay(name),
  647. args,
  648. result
  649. },
  650. groupId
  651. }
  652. });
  653. });
  654. onError((error) => {
  655. activeAction = void 0;
  656. api.addTimelineEvent({
  657. layerId: MUTATIONS_LAYER_ID,
  658. event: {
  659. time: now(),
  660. logType: "error",
  661. title: "💥 " + name,
  662. subtitle: "end",
  663. data: {
  664. store: formatDisplay(store.$id),
  665. action: formatDisplay(name),
  666. args,
  667. error
  668. },
  669. groupId
  670. }
  671. });
  672. });
  673. }, true);
  674. store._customProperties.forEach((name) => {
  675. watch(() => unref(store[name]), (newValue, oldValue) => {
  676. api.notifyComponentUpdate();
  677. api.sendInspectorState(INSPECTOR_ID);
  678. if (isTimelineActive) {
  679. api.addTimelineEvent({
  680. layerId: MUTATIONS_LAYER_ID,
  681. event: {
  682. time: now(),
  683. title: "Change",
  684. subtitle: name,
  685. data: {
  686. newValue,
  687. oldValue
  688. },
  689. groupId: activeAction
  690. }
  691. });
  692. }
  693. }, { deep: true });
  694. });
  695. store.$subscribe(({ events, type }, state) => {
  696. api.notifyComponentUpdate();
  697. api.sendInspectorState(INSPECTOR_ID);
  698. if (!isTimelineActive)
  699. return;
  700. const eventData = {
  701. time: now(),
  702. title: formatMutationType(type),
  703. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  704. groupId: activeAction
  705. };
  706. if (type === MutationType.patchFunction) {
  707. eventData.subtitle = "⤵️";
  708. } else if (type === MutationType.patchObject) {
  709. eventData.subtitle = "🧩";
  710. } else if (events && !Array.isArray(events)) {
  711. eventData.subtitle = events.type;
  712. }
  713. if (events) {
  714. eventData.data["rawEvent(s)"] = {
  715. _custom: {
  716. display: "DebuggerEvent",
  717. type: "object",
  718. tooltip: "raw DebuggerEvent[]",
  719. value: events
  720. }
  721. };
  722. }
  723. api.addTimelineEvent({
  724. layerId: MUTATIONS_LAYER_ID,
  725. event: eventData
  726. });
  727. }, { detached: true, flush: "sync" });
  728. const hotUpdate = store._hotUpdate;
  729. store._hotUpdate = markRaw((newStore) => {
  730. hotUpdate(newStore);
  731. api.addTimelineEvent({
  732. layerId: MUTATIONS_LAYER_ID,
  733. event: {
  734. time: now(),
  735. title: "🔥 " + store.$id,
  736. subtitle: "HMR update",
  737. data: {
  738. store: formatDisplay(store.$id),
  739. info: formatDisplay(`HMR update`)
  740. }
  741. }
  742. });
  743. api.notifyComponentUpdate();
  744. api.sendInspectorTree(INSPECTOR_ID);
  745. api.sendInspectorState(INSPECTOR_ID);
  746. });
  747. const { $dispose } = store;
  748. store.$dispose = () => {
  749. $dispose();
  750. api.notifyComponentUpdate();
  751. api.sendInspectorTree(INSPECTOR_ID);
  752. api.sendInspectorState(INSPECTOR_ID);
  753. api.getSettings().logStoreChanges && toastMessage(`Disposed "${store.$id}" store 🗑`);
  754. };
  755. api.notifyComponentUpdate();
  756. api.sendInspectorTree(INSPECTOR_ID);
  757. api.sendInspectorState(INSPECTOR_ID);
  758. api.getSettings().logStoreChanges && toastMessage(`"${store.$id}" store installed 🆕`);
  759. });
  760. }
  761. var runningActionId = 0;
  762. var activeAction;
  763. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  764. const actions = actionNames.reduce((storeActions, actionName) => {
  765. storeActions[actionName] = toRaw(store)[actionName];
  766. return storeActions;
  767. }, {});
  768. for (const actionName in actions) {
  769. store[actionName] = function() {
  770. const _actionId = runningActionId;
  771. const trackedStore = wrapWithProxy ? new Proxy(store, {
  772. get(...args) {
  773. activeAction = _actionId;
  774. return Reflect.get(...args);
  775. },
  776. set(...args) {
  777. activeAction = _actionId;
  778. return Reflect.set(...args);
  779. }
  780. }) : store;
  781. activeAction = _actionId;
  782. const retValue = actions[actionName].apply(trackedStore, arguments);
  783. activeAction = void 0;
  784. return retValue;
  785. };
  786. }
  787. }
  788. function devtoolsPlugin({ app, store, options }) {
  789. if (store.$id.startsWith("__hot:")) {
  790. return;
  791. }
  792. store._isOptionsAPI = !!options.state;
  793. if (!store._p._testing) {
  794. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  795. const originalHotUpdate = store._hotUpdate;
  796. toRaw(store)._hotUpdate = function(newStore) {
  797. originalHotUpdate.apply(this, arguments);
  798. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  799. };
  800. }
  801. addStoreToDevtools(
  802. app,
  803. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  804. store
  805. );
  806. }
  807. function createPinia() {
  808. const scope = effectScope(true);
  809. const state = scope.run(() => ref({}));
  810. let _p = [];
  811. let toBeInstalled = [];
  812. const pinia = markRaw({
  813. install(app) {
  814. setActivePinia(pinia);
  815. if (!isVue2) {
  816. pinia._a = app;
  817. app.provide(piniaSymbol, pinia);
  818. app.config.globalProperties.$pinia = pinia;
  819. if (IS_CLIENT) {
  820. registerPiniaDevtools(app, pinia);
  821. }
  822. toBeInstalled.forEach((plugin) => _p.push(plugin));
  823. toBeInstalled = [];
  824. }
  825. },
  826. use(plugin) {
  827. if (!this._a && !isVue2) {
  828. toBeInstalled.push(plugin);
  829. } else {
  830. _p.push(plugin);
  831. }
  832. return this;
  833. },
  834. _p,
  835. // it's actually undefined here
  836. // @ts-expect-error
  837. _a: null,
  838. _e: scope,
  839. _s: /* @__PURE__ */ new Map(),
  840. state
  841. });
  842. if (IS_CLIENT && typeof Proxy !== "undefined") {
  843. pinia.use(devtoolsPlugin);
  844. }
  845. return pinia;
  846. }
  847. function disposePinia(pinia) {
  848. pinia._e.stop();
  849. pinia._s.clear();
  850. pinia._p.splice(0);
  851. pinia.state.value = {};
  852. pinia._a = null;
  853. }
  854. var isUseStore = (fn) => {
  855. return typeof fn === "function" && typeof fn.$id === "string";
  856. };
  857. function patchObject(newState, oldState) {
  858. for (const key in oldState) {
  859. const subPatch = oldState[key];
  860. if (!(key in newState)) {
  861. continue;
  862. }
  863. const targetValue = newState[key];
  864. if (isPlainObject(targetValue) && isPlainObject(subPatch) && !isRef(subPatch) && !isReactive(subPatch)) {
  865. newState[key] = patchObject(targetValue, subPatch);
  866. } else {
  867. if (isVue2) {
  868. set(newState, key, subPatch);
  869. } else {
  870. newState[key] = subPatch;
  871. }
  872. }
  873. }
  874. return newState;
  875. }
  876. function acceptHMRUpdate(initialUseStore, hot) {
  877. if (false) {
  878. return () => {
  879. };
  880. }
  881. return (newModule) => {
  882. const pinia = hot.data.pinia || initialUseStore._pinia;
  883. if (!pinia) {
  884. return;
  885. }
  886. hot.data.pinia = pinia;
  887. for (const exportName in newModule) {
  888. const useStore = newModule[exportName];
  889. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  890. const id = useStore.$id;
  891. if (id !== initialUseStore.$id) {
  892. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  893. return hot.invalidate();
  894. }
  895. const existingStore = pinia._s.get(id);
  896. if (!existingStore) {
  897. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  898. return;
  899. }
  900. useStore(pinia, existingStore);
  901. }
  902. }
  903. };
  904. }
  905. var noop = () => {
  906. };
  907. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  908. subscriptions.push(callback);
  909. const removeSubscription = () => {
  910. const idx = subscriptions.indexOf(callback);
  911. if (idx > -1) {
  912. subscriptions.splice(idx, 1);
  913. onCleanup();
  914. }
  915. };
  916. if (!detached && getCurrentScope()) {
  917. onScopeDispose(removeSubscription);
  918. }
  919. return removeSubscription;
  920. }
  921. function triggerSubscriptions(subscriptions, ...args) {
  922. subscriptions.slice().forEach((callback) => {
  923. callback(...args);
  924. });
  925. }
  926. var fallbackRunWithContext = (fn) => fn();
  927. var ACTION_MARKER = Symbol();
  928. var ACTION_NAME = Symbol();
  929. function mergeReactiveObjects(target, patchToApply) {
  930. if (target instanceof Map && patchToApply instanceof Map) {
  931. patchToApply.forEach((value, key) => target.set(key, value));
  932. } else if (target instanceof Set && patchToApply instanceof Set) {
  933. patchToApply.forEach(target.add, target);
  934. }
  935. for (const key in patchToApply) {
  936. if (!patchToApply.hasOwnProperty(key))
  937. continue;
  938. const subPatch = patchToApply[key];
  939. const targetValue = target[key];
  940. if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
  941. target[key] = mergeReactiveObjects(targetValue, subPatch);
  942. } else {
  943. target[key] = subPatch;
  944. }
  945. }
  946. return target;
  947. }
  948. var skipHydrateSymbol = true ? Symbol("pinia:skipHydration") : (
  949. /* istanbul ignore next */
  950. Symbol()
  951. );
  952. function skipHydrate(obj) {
  953. return Object.defineProperty(obj, skipHydrateSymbol, {});
  954. }
  955. function shouldHydrate(obj) {
  956. return !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  957. }
  958. var { assign } = Object;
  959. function isComputed(o) {
  960. return !!(isRef(o) && o.effect);
  961. }
  962. function createOptionsStore(id, options, pinia, hot) {
  963. const { state, actions, getters } = options;
  964. const initialState = pinia.state.value[id];
  965. let store;
  966. function setup() {
  967. if (!initialState && !hot) {
  968. if (isVue2) {
  969. set(pinia.state.value, id, state ? state() : {});
  970. } else {
  971. pinia.state.value[id] = state ? state() : {};
  972. }
  973. }
  974. const localState = hot ? (
  975. // use ref() to unwrap refs inside state TODO: check if this is still necessary
  976. toRefs(ref(state ? state() : {}).value)
  977. ) : toRefs(pinia.state.value[id]);
  978. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  979. if (name in localState) {
  980. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  981. }
  982. computedGetters[name] = markRaw(computed(() => {
  983. setActivePinia(pinia);
  984. const store2 = pinia._s.get(id);
  985. if (isVue2 && !store2._r)
  986. return;
  987. return getters[name].call(store2, store2);
  988. }));
  989. return computedGetters;
  990. }, {}));
  991. }
  992. store = createSetupStore(id, setup, options, pinia, hot, true);
  993. return store;
  994. }
  995. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  996. let scope;
  997. const optionsForPlugin = assign({ actions: {} }, options);
  998. if (!pinia._e.active) {
  999. throw new Error("Pinia destroyed");
  1000. }
  1001. const $subscribeOptions = { deep: true };
  1002. if (!isVue2) {
  1003. $subscribeOptions.onTrigger = (event) => {
  1004. if (isListening) {
  1005. debuggerEvents = event;
  1006. } else if (isListening == false && !store._hotUpdating) {
  1007. if (Array.isArray(debuggerEvents)) {
  1008. debuggerEvents.push(event);
  1009. } else {
  1010. console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.");
  1011. }
  1012. }
  1013. };
  1014. }
  1015. let isListening;
  1016. let isSyncListening;
  1017. let subscriptions = [];
  1018. let actionSubscriptions = [];
  1019. let debuggerEvents;
  1020. const initialState = pinia.state.value[$id];
  1021. if (!isOptionsStore && !initialState && !hot) {
  1022. if (isVue2) {
  1023. set(pinia.state.value, $id, {});
  1024. } else {
  1025. pinia.state.value[$id] = {};
  1026. }
  1027. }
  1028. const hotState = ref({});
  1029. let activeListener;
  1030. function $patch(partialStateOrMutator) {
  1031. let subscriptionMutation;
  1032. isListening = isSyncListening = false;
  1033. if (true) {
  1034. debuggerEvents = [];
  1035. }
  1036. if (typeof partialStateOrMutator === "function") {
  1037. partialStateOrMutator(pinia.state.value[$id]);
  1038. subscriptionMutation = {
  1039. type: MutationType.patchFunction,
  1040. storeId: $id,
  1041. events: debuggerEvents
  1042. };
  1043. } else {
  1044. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1045. subscriptionMutation = {
  1046. type: MutationType.patchObject,
  1047. payload: partialStateOrMutator,
  1048. storeId: $id,
  1049. events: debuggerEvents
  1050. };
  1051. }
  1052. const myListenerId = activeListener = Symbol();
  1053. nextTick().then(() => {
  1054. if (activeListener === myListenerId) {
  1055. isListening = true;
  1056. }
  1057. });
  1058. isSyncListening = true;
  1059. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1060. }
  1061. const $reset = isOptionsStore ? function $reset2() {
  1062. const { state } = options;
  1063. const newState = state ? state() : {};
  1064. this.$patch(($state) => {
  1065. assign($state, newState);
  1066. });
  1067. } : (
  1068. /* istanbul ignore next */
  1069. true ? () => {
  1070. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1071. } : noop
  1072. );
  1073. function $dispose() {
  1074. scope.stop();
  1075. subscriptions = [];
  1076. actionSubscriptions = [];
  1077. pinia._s.delete($id);
  1078. }
  1079. const action = (fn, name = "") => {
  1080. if (ACTION_MARKER in fn) {
  1081. fn[ACTION_NAME] = name;
  1082. return fn;
  1083. }
  1084. const wrappedAction = function() {
  1085. setActivePinia(pinia);
  1086. const args = Array.from(arguments);
  1087. const afterCallbackList = [];
  1088. const onErrorCallbackList = [];
  1089. function after(callback) {
  1090. afterCallbackList.push(callback);
  1091. }
  1092. function onError(callback) {
  1093. onErrorCallbackList.push(callback);
  1094. }
  1095. triggerSubscriptions(actionSubscriptions, {
  1096. args,
  1097. name: wrappedAction[ACTION_NAME],
  1098. store,
  1099. after,
  1100. onError
  1101. });
  1102. let ret;
  1103. try {
  1104. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1105. } catch (error) {
  1106. triggerSubscriptions(onErrorCallbackList, error);
  1107. throw error;
  1108. }
  1109. if (ret instanceof Promise) {
  1110. return ret.then((value) => {
  1111. triggerSubscriptions(afterCallbackList, value);
  1112. return value;
  1113. }).catch((error) => {
  1114. triggerSubscriptions(onErrorCallbackList, error);
  1115. return Promise.reject(error);
  1116. });
  1117. }
  1118. triggerSubscriptions(afterCallbackList, ret);
  1119. return ret;
  1120. };
  1121. wrappedAction[ACTION_MARKER] = true;
  1122. wrappedAction[ACTION_NAME] = name;
  1123. return wrappedAction;
  1124. };
  1125. const _hmrPayload = markRaw({
  1126. actions: {},
  1127. getters: {},
  1128. state: [],
  1129. hotState
  1130. });
  1131. const partialStore = {
  1132. _p: pinia,
  1133. // _s: scope,
  1134. $id,
  1135. $onAction: addSubscription.bind(null, actionSubscriptions),
  1136. $patch,
  1137. $reset,
  1138. $subscribe(callback, options2 = {}) {
  1139. const removeSubscription = addSubscription(subscriptions, callback, options2.detached, () => stopWatcher());
  1140. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1141. if (options2.flush === "sync" ? isSyncListening : isListening) {
  1142. callback({
  1143. storeId: $id,
  1144. type: MutationType.direct,
  1145. events: debuggerEvents
  1146. }, state);
  1147. }
  1148. }, assign({}, $subscribeOptions, options2)));
  1149. return removeSubscription;
  1150. },
  1151. $dispose
  1152. };
  1153. if (isVue2) {
  1154. partialStore._r = false;
  1155. }
  1156. const store = reactive(true ? assign(
  1157. {
  1158. _hmrPayload,
  1159. _customProperties: markRaw(/* @__PURE__ */ new Set())
  1160. // devtools custom properties
  1161. },
  1162. partialStore
  1163. // must be added later
  1164. // setupStore
  1165. ) : partialStore);
  1166. pinia._s.set($id, store);
  1167. const runWithContext = pinia._a && pinia._a.runWithContext || fallbackRunWithContext;
  1168. const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
  1169. for (const key in setupStore) {
  1170. const prop = setupStore[key];
  1171. if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
  1172. if (hot) {
  1173. set(hotState.value, key, toRef(setupStore, key));
  1174. } else if (!isOptionsStore) {
  1175. if (initialState && shouldHydrate(prop)) {
  1176. if (isRef(prop)) {
  1177. prop.value = initialState[key];
  1178. } else {
  1179. mergeReactiveObjects(prop, initialState[key]);
  1180. }
  1181. }
  1182. if (isVue2) {
  1183. set(pinia.state.value[$id], key, prop);
  1184. } else {
  1185. pinia.state.value[$id][key] = prop;
  1186. }
  1187. }
  1188. if (true) {
  1189. _hmrPayload.state.push(key);
  1190. }
  1191. } else if (typeof prop === "function") {
  1192. const actionValue = hot ? prop : action(prop, key);
  1193. if (isVue2) {
  1194. set(setupStore, key, actionValue);
  1195. } else {
  1196. setupStore[key] = actionValue;
  1197. }
  1198. if (true) {
  1199. _hmrPayload.actions[key] = prop;
  1200. }
  1201. optionsForPlugin.actions[key] = prop;
  1202. } else if (true) {
  1203. if (isComputed(prop)) {
  1204. _hmrPayload.getters[key] = isOptionsStore ? (
  1205. // @ts-expect-error
  1206. options.getters[key]
  1207. ) : prop;
  1208. if (IS_CLIENT) {
  1209. const getters = setupStore._getters || // @ts-expect-error: same
  1210. (setupStore._getters = markRaw([]));
  1211. getters.push(key);
  1212. }
  1213. }
  1214. }
  1215. }
  1216. if (isVue2) {
  1217. Object.keys(setupStore).forEach((key) => {
  1218. set(store, key, setupStore[key]);
  1219. });
  1220. } else {
  1221. assign(store, setupStore);
  1222. assign(toRaw(store), setupStore);
  1223. }
  1224. Object.defineProperty(store, "$state", {
  1225. get: () => hot ? hotState.value : pinia.state.value[$id],
  1226. set: (state) => {
  1227. if (hot) {
  1228. throw new Error("cannot set hotState");
  1229. }
  1230. $patch(($state) => {
  1231. assign($state, state);
  1232. });
  1233. }
  1234. });
  1235. if (true) {
  1236. store._hotUpdate = markRaw((newStore) => {
  1237. store._hotUpdating = true;
  1238. newStore._hmrPayload.state.forEach((stateKey) => {
  1239. if (stateKey in store.$state) {
  1240. const newStateTarget = newStore.$state[stateKey];
  1241. const oldStateSource = store.$state[stateKey];
  1242. if (typeof newStateTarget === "object" && isPlainObject(newStateTarget) && isPlainObject(oldStateSource)) {
  1243. patchObject(newStateTarget, oldStateSource);
  1244. } else {
  1245. newStore.$state[stateKey] = oldStateSource;
  1246. }
  1247. }
  1248. set(store, stateKey, toRef(newStore.$state, stateKey));
  1249. });
  1250. Object.keys(store.$state).forEach((stateKey) => {
  1251. if (!(stateKey in newStore.$state)) {
  1252. del(store, stateKey);
  1253. }
  1254. });
  1255. isListening = false;
  1256. isSyncListening = false;
  1257. pinia.state.value[$id] = toRef(newStore._hmrPayload, "hotState");
  1258. isSyncListening = true;
  1259. nextTick().then(() => {
  1260. isListening = true;
  1261. });
  1262. for (const actionName in newStore._hmrPayload.actions) {
  1263. const actionFn = newStore[actionName];
  1264. set(store, actionName, action(actionFn, actionName));
  1265. }
  1266. for (const getterName in newStore._hmrPayload.getters) {
  1267. const getter = newStore._hmrPayload.getters[getterName];
  1268. const getterValue = isOptionsStore ? (
  1269. // special handling of options api
  1270. computed(() => {
  1271. setActivePinia(pinia);
  1272. return getter.call(store, store);
  1273. })
  1274. ) : getter;
  1275. set(store, getterName, getterValue);
  1276. }
  1277. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1278. if (!(key in newStore._hmrPayload.getters)) {
  1279. del(store, key);
  1280. }
  1281. });
  1282. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1283. if (!(key in newStore._hmrPayload.actions)) {
  1284. del(store, key);
  1285. }
  1286. });
  1287. store._hmrPayload = newStore._hmrPayload;
  1288. store._getters = newStore._getters;
  1289. store._hotUpdating = false;
  1290. });
  1291. }
  1292. if (IS_CLIENT) {
  1293. const nonEnumerable = {
  1294. writable: true,
  1295. configurable: true,
  1296. // avoid warning on devtools trying to display this property
  1297. enumerable: false
  1298. };
  1299. ["_p", "_hmrPayload", "_getters", "_customProperties"].forEach((p) => {
  1300. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1301. });
  1302. }
  1303. if (isVue2) {
  1304. store._r = true;
  1305. }
  1306. pinia._p.forEach((extender) => {
  1307. if (IS_CLIENT) {
  1308. const extensions = scope.run(() => extender({
  1309. store,
  1310. app: pinia._a,
  1311. pinia,
  1312. options: optionsForPlugin
  1313. }));
  1314. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1315. assign(store, extensions);
  1316. } else {
  1317. assign(store, scope.run(() => extender({
  1318. store,
  1319. app: pinia._a,
  1320. pinia,
  1321. options: optionsForPlugin
  1322. })));
  1323. }
  1324. });
  1325. if (store.$state && typeof store.$state === "object" && typeof store.$state.constructor === "function" && !store.$state.constructor.toString().includes("[native code]")) {
  1326. console.warn(`[🍍]: The "state" must be a plain object. It cannot be
  1327. state: () => new MyClass()
  1328. Found in store "${store.$id}".`);
  1329. }
  1330. if (initialState && isOptionsStore && options.hydrate) {
  1331. options.hydrate(store.$state, initialState);
  1332. }
  1333. isListening = true;
  1334. isSyncListening = true;
  1335. return store;
  1336. }
  1337. function defineStore(idOrOptions, setup, setupOptions) {
  1338. let id;
  1339. let options;
  1340. const isSetupStore = typeof setup === "function";
  1341. if (typeof idOrOptions === "string") {
  1342. id = idOrOptions;
  1343. options = isSetupStore ? setupOptions : setup;
  1344. } else {
  1345. options = idOrOptions;
  1346. id = idOrOptions.id;
  1347. if (typeof id !== "string") {
  1348. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1349. }
  1350. }
  1351. function useStore(pinia, hot) {
  1352. const hasContext = hasInjectionContext();
  1353. pinia = // in test mode, ignore the argument provided as we can always retrieve a
  1354. // pinia instance with getActivePinia()
  1355. (false ? null : pinia) || (hasContext ? inject(piniaSymbol, null) : null);
  1356. if (pinia)
  1357. setActivePinia(pinia);
  1358. if (!activePinia) {
  1359. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
  1360. See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
  1361. This will fail in production.`);
  1362. }
  1363. pinia = activePinia;
  1364. if (!pinia._s.has(id)) {
  1365. if (isSetupStore) {
  1366. createSetupStore(id, setup, options, pinia);
  1367. } else {
  1368. createOptionsStore(id, options, pinia);
  1369. }
  1370. if (true) {
  1371. useStore._pinia = pinia;
  1372. }
  1373. }
  1374. const store = pinia._s.get(id);
  1375. if (hot) {
  1376. const hotId = "__hot:" + id;
  1377. const newStore = isSetupStore ? createSetupStore(hotId, setup, options, pinia, true) : createOptionsStore(hotId, assign({}, options), pinia, true);
  1378. hot._hotUpdate(newStore);
  1379. delete pinia.state.value[hotId];
  1380. pinia._s.delete(hotId);
  1381. }
  1382. if (IS_CLIENT) {
  1383. const currentInstance = getCurrentInstance();
  1384. if (currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement
  1385. !hot) {
  1386. const vm = currentInstance.proxy;
  1387. const cache = "_pStores" in vm ? vm._pStores : vm._pStores = {};
  1388. cache[id] = store;
  1389. }
  1390. }
  1391. return store;
  1392. }
  1393. useStore.$id = id;
  1394. return useStore;
  1395. }
  1396. var mapStoreSuffix = "Store";
  1397. function setMapStoreSuffix(suffix) {
  1398. mapStoreSuffix = suffix;
  1399. }
  1400. function mapStores(...stores) {
  1401. if (Array.isArray(stores[0])) {
  1402. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:
  1403. Replace
  1404. mapStores([useAuthStore, useCartStore])
  1405. with
  1406. mapStores(useAuthStore, useCartStore)
  1407. This will fail in production if not fixed.`);
  1408. stores = stores[0];
  1409. }
  1410. return stores.reduce((reduced, useStore) => {
  1411. reduced[useStore.$id + mapStoreSuffix] = function() {
  1412. return useStore(this.$pinia);
  1413. };
  1414. return reduced;
  1415. }, {});
  1416. }
  1417. function mapState(useStore, keysOrMapper) {
  1418. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1419. reduced[key] = function() {
  1420. return useStore(this.$pinia)[key];
  1421. };
  1422. return reduced;
  1423. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1424. reduced[key] = function() {
  1425. const store = useStore(this.$pinia);
  1426. const storeKey = keysOrMapper[key];
  1427. return typeof storeKey === "function" ? storeKey.call(this, store) : (
  1428. // @ts-expect-error: FIXME: should work?
  1429. store[storeKey]
  1430. );
  1431. };
  1432. return reduced;
  1433. }, {});
  1434. }
  1435. var mapGetters = mapState;
  1436. function mapActions(useStore, keysOrMapper) {
  1437. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1438. reduced[key] = function(...args) {
  1439. return useStore(this.$pinia)[key](...args);
  1440. };
  1441. return reduced;
  1442. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1443. reduced[key] = function(...args) {
  1444. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1445. };
  1446. return reduced;
  1447. }, {});
  1448. }
  1449. function mapWritableState(useStore, keysOrMapper) {
  1450. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1451. reduced[key] = {
  1452. get() {
  1453. return useStore(this.$pinia)[key];
  1454. },
  1455. set(value) {
  1456. return useStore(this.$pinia)[key] = value;
  1457. }
  1458. };
  1459. return reduced;
  1460. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1461. reduced[key] = {
  1462. get() {
  1463. return useStore(this.$pinia)[keysOrMapper[key]];
  1464. },
  1465. set(value) {
  1466. return useStore(this.$pinia)[keysOrMapper[key]] = value;
  1467. }
  1468. };
  1469. return reduced;
  1470. }, {});
  1471. }
  1472. function storeToRefs(store) {
  1473. if (isVue2) {
  1474. return toRefs(store);
  1475. } else {
  1476. const rawStore = toRaw(store);
  1477. const refs = {};
  1478. for (const key in rawStore) {
  1479. const value = rawStore[key];
  1480. if (value.effect) {
  1481. refs[key] = // ...
  1482. computed({
  1483. get: () => store[key],
  1484. set(value2) {
  1485. store[key] = value2;
  1486. }
  1487. });
  1488. } else if (isRef(value) || isReactive(value)) {
  1489. refs[key] = // ---
  1490. toRef(store, key);
  1491. }
  1492. }
  1493. return refs;
  1494. }
  1495. }
  1496. var PiniaVuePlugin = function(_Vue) {
  1497. _Vue.mixin({
  1498. beforeCreate() {
  1499. const options = this.$options;
  1500. if (options.pinia) {
  1501. const pinia = options.pinia;
  1502. if (!this._provided) {
  1503. const provideCache = {};
  1504. Object.defineProperty(this, "_provided", {
  1505. get: () => provideCache,
  1506. set: (v) => Object.assign(provideCache, v)
  1507. });
  1508. }
  1509. this._provided[piniaSymbol] = pinia;
  1510. if (!this.$pinia) {
  1511. this.$pinia = pinia;
  1512. }
  1513. pinia._a = this;
  1514. if (IS_CLIENT) {
  1515. setActivePinia(pinia);
  1516. }
  1517. if (IS_CLIENT) {
  1518. registerPiniaDevtools(pinia._a, pinia);
  1519. }
  1520. } else if (!this.$pinia && options.parent && options.parent.$pinia) {
  1521. this.$pinia = options.parent.$pinia;
  1522. }
  1523. },
  1524. destroyed() {
  1525. delete this._pStores;
  1526. }
  1527. });
  1528. };
  1529. export {
  1530. MutationType,
  1531. PiniaVuePlugin,
  1532. acceptHMRUpdate,
  1533. createPinia,
  1534. defineStore,
  1535. disposePinia,
  1536. getActivePinia,
  1537. mapActions,
  1538. mapGetters,
  1539. mapState,
  1540. mapStores,
  1541. mapWritableState,
  1542. setActivePinia,
  1543. setMapStoreSuffix,
  1544. shouldHydrate,
  1545. skipHydrate,
  1546. storeToRefs
  1547. };
  1548. /*! Bundled license information:
  1549. pinia/dist/pinia.mjs:
  1550. (*!
  1551. * pinia v2.3.1
  1552. * (c) 2025 Eduardo San Martin Morote
  1553. * @license MIT
  1554. *)
  1555. (*! #__NO_SIDE_EFFECTS__ *)
  1556. */
  1557. //# sourceMappingURL=pinia.js.map