@dcloudio/uni-cli-shared 3.0.0-5020320260806002 → 3.0.0-5020420260811002

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