@poveste/vendors 0.13.1 → 0.15.0

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