@histoire/vendors 0.15.8 → 0.16.5

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