coaction 1.4.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1074 +1,1461 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
2
4
  var __defProp = Object.defineProperty;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
5
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
9
  var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
17
18
  };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- create: () => create,
24
- createBinder: () => createBinder,
25
- wrapStore: () => wrapStore
26
- });
27
- module.exports = __toCommonJS(index_exports);
28
-
29
- // src/create.ts
30
- var import_mutative3 = require("mutative");
31
-
32
- // src/global.ts
33
- var getGlobal = () => {
34
- let _global2;
35
- if (typeof window !== "undefined") {
36
- _global2 = window;
37
- } else if (typeof global !== "undefined") {
38
- _global2 = global;
39
- } else if (typeof self !== "undefined") {
40
- _global2 = self;
41
- } else {
42
- _global2 = {};
43
- }
44
- return _global2;
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let mutative = require("mutative");
25
+ let data_transport = require("data-transport");
26
+ let alien_signals = require("alien-signals");
27
+ let alien_signals_system = require("alien-signals/system");
28
+ alien_signals_system = __toESM(alien_signals_system);
29
+ //#region packages/core/src/global.ts
30
+ const getGlobal = () => {
31
+ let _global;
32
+ if (typeof window !== "undefined") _global = window;
33
+ else if (typeof global !== "undefined") _global = global;
34
+ else if (typeof self !== "undefined") _global = self;
35
+ else _global = {};
36
+ return _global;
37
+ };
38
+ //#endregion
39
+ //#region packages/core/src/constant.ts
40
+ const WorkerType = getGlobal().SharedWorkerGlobalScope ? "SharedWorkerInternal" : globalThis.WorkerGlobalScope ? "WebWorkerInternal" : null;
41
+ const bindSymbol = Symbol("bind");
42
+ //#endregion
43
+ //#region packages/core/src/wrapStore.ts
44
+ /**
45
+ * Convert a store object into Coaction's callable store shape.
46
+ *
47
+ * @remarks
48
+ * Framework bindings use this to attach selector-aware readers while
49
+ * preserving the underlying store API on the returned function object. Most
50
+ * applications should call {@link create} instead of using `wrapStore()`
51
+ * directly.
52
+ */
53
+ const wrapStore = (store, getState = () => store.getState()) => {
54
+ const { name, ..._store } = store;
55
+ return Object.assign({ [name]: (...args) => getState(...args) }[name], _store);
56
+ };
57
+ //#endregion
58
+ //#region packages/core/src/utils.ts
59
+ const isEqual = (x, y) => {
60
+ if (x === y) return x !== 0 || y !== 0 || 1 / x === 1 / y;
61
+ return x !== x && y !== y;
62
+ };
63
+ const isUnsafeKey = (key) => key === "__proto__" || key === "prototype" || key === "constructor";
64
+ const isUnsafePathSegment = (segment) => typeof segment === "string" && isUnsafeKey(segment);
65
+ const hasUnsafePatchPath = (path) => {
66
+ return (Array.isArray(path) ? path : typeof path === "string" ? path.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~")) : []).some(isUnsafePathSegment);
67
+ };
68
+ const sanitizePatches = (patches) => patches?.filter((patch) => !hasUnsafePatchPath(patch.path)).map((patch) => Object.prototype.hasOwnProperty.call(patch, "value") ? {
69
+ ...patch,
70
+ value: sanitizeReplacementState(patch.value)
71
+ } : patch);
72
+ const setOwnEnumerable = (target, key, value) => {
73
+ if (typeof key === "string" && isUnsafeKey(key)) return;
74
+ target[key] = value;
75
+ };
76
+ const getOwnEnumerableKeys = (source) => {
77
+ if (typeof source !== "object" || source === null) return [];
78
+ return Reflect.ownKeys(source).filter((key) => Object.prototype.propertyIsEnumerable.call(source, key));
79
+ };
80
+ const isArrayIndexKey$1 = (key) => {
81
+ if (typeof key !== "string") return false;
82
+ const index = Number(key);
83
+ return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
84
+ };
85
+ const assignOwnEnumerable = (target, source, seen = /* @__PURE__ */ new WeakMap()) => {
86
+ if (!seen.has(source)) seen.set(source, target);
87
+ for (const key of getOwnEnumerableKeys(source)) setOwnEnumerable(target, key, sanitizeReplacementState(source[key], seen));
88
+ };
89
+ const replaceOwnEnumerable = (target, source) => {
90
+ const seen = /* @__PURE__ */ new WeakMap();
91
+ seen.set(source, target);
92
+ const nextKeys = /* @__PURE__ */ new Set();
93
+ for (const key of getOwnEnumerableKeys(source)) {
94
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
95
+ if (typeof source[key] === "function") continue;
96
+ nextKeys.add(key);
97
+ }
98
+ for (const key of getOwnEnumerableKeys(target)) if (!nextKeys.has(key)) delete target[key];
99
+ nextKeys.forEach((key) => {
100
+ setOwnEnumerable(target, key, sanitizeReplacementState(source[key], seen));
101
+ });
102
+ };
103
+ const cloneOwnEnumerable = (source) => {
104
+ const target = {};
105
+ assignOwnEnumerable(target, source);
106
+ return target;
45
107
  };
46
- var _global = getGlobal();
47
-
48
- // src/constant.ts
49
- var WorkerType = _global.SharedWorkerGlobalScope ? "SharedWorkerInternal" : globalThis.WorkerGlobalScope ? "WebWorkerInternal" : null;
50
- var bindSymbol = /* @__PURE__ */ Symbol("bind");
51
- var defaultName = "default";
52
-
53
- // src/asyncClientStore.ts
54
- var import_data_transport = require("data-transport");
55
-
56
- // src/wrapStore.ts
57
- var wrapStore = (store, getState = () => store.getState()) => {
58
- const { name, ..._store } = store;
59
- return Object.assign(
60
- {
61
- [name]: (...args) => getState(...args)
62
- }[name],
63
- _store
64
- );
108
+ const sanitizeReplacementState = (source, seen = /* @__PURE__ */ new WeakMap()) => {
109
+ if (typeof source !== "object" || source === null) return source;
110
+ const cached = seen.get(source);
111
+ if (cached) return cached;
112
+ if (Array.isArray(source)) {
113
+ const target = [];
114
+ target.length = source.length;
115
+ seen.set(source, target);
116
+ for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeReplacementState(source[index], seen);
117
+ for (const key of getOwnEnumerableKeys(source)) {
118
+ if (isArrayIndexKey$1(key) || typeof key === "string" && isUnsafeKey(key)) continue;
119
+ const value = source[key];
120
+ if (typeof value === "function") continue;
121
+ setOwnEnumerable(target, key, sanitizeReplacementState(value, seen));
122
+ }
123
+ return target;
124
+ }
125
+ const prototype = Object.getPrototypeOf(source);
126
+ if (prototype !== Object.prototype && prototype !== null) return source;
127
+ const target = Object.create(prototype);
128
+ seen.set(source, target);
129
+ for (const key of getOwnEnumerableKeys(source)) {
130
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
131
+ const value = source[key];
132
+ if (typeof value === "function") continue;
133
+ setOwnEnumerable(target, key, sanitizeReplacementState(value, seen));
134
+ }
135
+ return target;
65
136
  };
66
-
67
- // src/asyncClientStore.ts
68
- var createAsyncClientStore = (createStore, asyncStoreClientOption) => {
69
- const { store: asyncClientStore, internal } = createStore({
70
- share: "client"
71
- });
72
- const transport = asyncStoreClientOption.worker ? (0, import_data_transport.createTransport)(
73
- asyncStoreClientOption.worker instanceof SharedWorker ? "SharedWorkerClient" : "WebWorkerClient",
74
- {
75
- worker: asyncStoreClientOption.worker,
76
- prefix: asyncClientStore.name
77
- }
78
- ) : asyncStoreClientOption.clientTransport;
79
- if (!transport) {
80
- throw new Error("transport is required");
81
- }
82
- asyncClientStore.transport = transport;
83
- let syncingPromise = null;
84
- let awaitingReconnectSync = false;
85
- let reconnectSequenceBaseline = null;
86
- const fullSync = async (allowLowerSequence = false) => {
87
- if (!syncingPromise) {
88
- syncingPromise = (async () => {
89
- const latest = await transport.emit("fullSync");
90
- if (typeof latest.sequence !== "number" || typeof latest.state !== "string") {
91
- throw new Error("Invalid fullSync payload");
92
- }
93
- const canApplyLowerSequence = allowLowerSequence && awaitingReconnectSync && reconnectSequenceBaseline !== null && reconnectSequenceBaseline === internal.sequence;
94
- if (latest.sequence < internal.sequence && !canApplyLowerSequence) {
95
- return;
96
- }
97
- asyncClientStore.apply(JSON.parse(latest.state));
98
- internal.sequence = latest.sequence;
99
- awaitingReconnectSync = false;
100
- reconnectSequenceBaseline = null;
101
- })().finally(() => {
102
- syncingPromise = null;
103
- });
104
- }
105
- return syncingPromise;
106
- };
107
- if (typeof transport.onConnect !== "function") {
108
- throw new Error("transport.onConnect is required");
109
- }
110
- transport.onConnect?.(() => {
111
- awaitingReconnectSync = true;
112
- reconnectSequenceBaseline = internal.sequence;
113
- void fullSync(true).catch((error) => {
114
- if (process.env.NODE_ENV === "development") {
115
- console.error(error);
116
- }
117
- });
118
- });
119
- transport.listen("update", async (options) => {
120
- let shouldFullSync = false;
121
- let allowLowerSequence = false;
122
- try {
123
- if (typeof options.sequence !== "number") {
124
- shouldFullSync = true;
125
- } else if (options.sequence <= internal.sequence) {
126
- if (awaitingReconnectSync) {
127
- shouldFullSync = true;
128
- allowLowerSequence = true;
129
- } else if (options.sequence === 0 && internal.sequence > 0) {
130
- awaitingReconnectSync = true;
131
- reconnectSequenceBaseline = internal.sequence;
132
- shouldFullSync = true;
133
- allowLowerSequence = true;
134
- } else {
135
- return;
136
- }
137
- } else if (options.sequence === internal.sequence + 1) {
138
- asyncClientStore.apply(void 0, options.patches);
139
- internal.sequence = options.sequence;
140
- awaitingReconnectSync = false;
141
- reconnectSequenceBaseline = null;
142
- return;
143
- } else {
144
- shouldFullSync = true;
145
- allowLowerSequence = awaitingReconnectSync;
146
- }
147
- if (shouldFullSync) {
148
- await fullSync(allowLowerSequence);
149
- }
150
- } catch (error) {
151
- if (!shouldFullSync) {
152
- try {
153
- await fullSync(awaitingReconnectSync);
154
- } catch (syncError) {
155
- if (process.env.NODE_ENV === "development") {
156
- console.error(syncError);
157
- }
158
- }
159
- }
160
- if (process.env.NODE_ENV === "development") {
161
- console.error(error);
162
- }
163
- }
164
- });
165
- return wrapStore(asyncClientStore, () => asyncClientStore.getState());
137
+ const sanitizeInitialStateValue = (source, seen = /* @__PURE__ */ new WeakMap()) => {
138
+ if (typeof source !== "object" || source === null) return source;
139
+ const cached = seen.get(source);
140
+ if (cached) return cached;
141
+ if (Array.isArray(source)) {
142
+ const target = [];
143
+ target.length = source.length;
144
+ seen.set(source, target);
145
+ for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeInitialStateValue(source[index], seen);
146
+ for (const key of getOwnEnumerableKeys(source)) {
147
+ if (isArrayIndexKey$1(key) || typeof key === "string" && isUnsafeKey(key)) continue;
148
+ setOwnEnumerable(target, key, sanitizeInitialStateValue(source[key], seen));
149
+ }
150
+ return target;
151
+ }
152
+ const prototype = Object.getPrototypeOf(source);
153
+ if (prototype !== Object.prototype && prototype !== null) return source;
154
+ const target = Object.create(prototype);
155
+ seen.set(source, target);
156
+ for (const key of getOwnEnumerableKeys(source)) {
157
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
158
+ setOwnEnumerable(target, key, sanitizeInitialStateValue(source[key], seen));
159
+ }
160
+ return target;
166
161
  };
167
- var emit = (store, internal, patches) => {
168
- if (store.transport && patches?.length) {
169
- internal.sequence += 1;
170
- store.transport.emit(
171
- {
172
- name: "update",
173
- respond: false
174
- },
175
- {
176
- patches,
177
- sequence: internal.sequence
178
- }
179
- );
180
- }
162
+ const areShallowEqualWithArray = (prev, next) => {
163
+ if (prev === null || next === null || prev.length !== next.length) return false;
164
+ const { length } = prev;
165
+ for (let i = 0; i < length; i += 1) {
166
+ if (Object.prototype.hasOwnProperty.call(prev, i) !== Object.prototype.hasOwnProperty.call(next, i)) return false;
167
+ if (!isEqual(prev[i], next[i])) return false;
168
+ }
169
+ return true;
181
170
  };
182
- var handleDraft = (store, internal) => {
183
- internal.rootState = internal.backupState;
184
- const [, patches, inversePatches] = internal.finalizeDraft();
185
- const finalPatches = store.patch ? store.patch({ patches, inversePatches }) : { patches, inversePatches };
186
- if (finalPatches.patches.length) {
187
- store.apply(internal.rootState, finalPatches.patches);
188
- emit(store, internal, finalPatches.patches);
189
- }
171
+ const mergeObject = (target, source, isSlice) => {
172
+ if (isSlice) {
173
+ if (typeof source === "object" && source !== null) for (const key of getOwnEnumerableKeys(source)) {
174
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
175
+ if (!Object.prototype.hasOwnProperty.call(target, key)) continue;
176
+ const sourceValue = source[key];
177
+ if (typeof sourceValue !== "object" || sourceValue === null) continue;
178
+ const targetValue = target[key];
179
+ if (typeof targetValue === "object" && targetValue !== null) assignOwnEnumerable(targetValue, sourceValue);
180
+ }
181
+ } else if (typeof source === "object" && source !== null) assignOwnEnumerable(target, source);
190
182
  };
191
-
192
- // src/getInitialState.ts
193
- var isObject = (value) => typeof value === "object" && value !== null;
194
- var isStateFactory = (value) => typeof value === "function";
195
- var hasGetState = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.getState === "function";
196
- var hasBindState = (value) => isObject(value) && !!value[bindSymbol];
197
- var formatInvalidStateMessage = (type, stateOrFn, key) => `Invalid state ${type} encountered in makeState: ${key ? `for key ${key}, ` : ""}${typeof stateOrFn}`;
198
- var getInitialState = (store, createState, internal) => {
199
- const makeState = (stateOrFn, key) => {
200
- let state;
201
- if (isStateFactory(stateOrFn)) {
202
- state = stateOrFn(store.setState, store.getState, store);
203
- } else if (isObject(stateOrFn)) {
204
- state = stateOrFn;
205
- } else {
206
- if (process.env.NODE_ENV !== "production") {
207
- throw new Error(formatInvalidStateMessage("value", stateOrFn, key));
208
- }
209
- return {};
210
- }
211
- if (hasGetState(state)) {
212
- state = state.getState();
213
- } else if (typeof state === "function") {
214
- state = state();
215
- }
216
- if (hasBindState(state)) {
217
- if (store.isSliceStore) {
218
- throw new Error(
219
- "Third-party state binding does not support Slices mode. Please inject a whole store instead."
220
- );
221
- }
222
- const binder = state[bindSymbol];
223
- const rawState = binder.bind(state);
224
- binder.handleStore(
225
- store,
226
- rawState,
227
- state,
228
- internal,
229
- key
230
- );
231
- delete state[bindSymbol];
232
- return rawState;
233
- }
234
- if (!isObject(state)) {
235
- if (process.env.NODE_ENV !== "production") {
236
- throw new Error(formatInvalidStateMessage("result", state, key));
237
- }
238
- return {};
239
- }
240
- return state;
241
- };
242
- return store.isSliceStore ? Object.entries(createState).reduce(
243
- (stateTree, [key, value]) => Object.assign(stateTree, {
244
- [key]: makeState(value, key)
245
- }),
246
- {}
247
- ) : makeState(createState);
183
+ const uuid = () => {
184
+ let timestamp = (/* @__PURE__ */ new Date()).getTime();
185
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
186
+ const randomNum = (timestamp + Math.random() * 16) % 16 | 0;
187
+ timestamp = Math.floor(timestamp / 16);
188
+ return (char === "x" ? randomNum : randomNum & 3 | 8).toString(16);
189
+ });
248
190
  };
249
-
250
- // src/utils.ts
251
- var isEqual = (x, y) => {
252
- if (x === y) {
253
- return x !== 0 || y !== 0 || 1 / x === 1 / y;
254
- }
255
- return x !== x && y !== y;
191
+ //#endregion
192
+ //#region packages/core/src/sharedState.ts
193
+ const formatPropertyPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
194
+ const isPlainObject = (value) => {
195
+ const prototype = Object.getPrototypeOf(value);
196
+ return prototype === Object.prototype || prototype === null;
256
197
  };
257
- var isUnsafeKey = (key) => key === "__proto__" || key === "prototype" || key === "constructor";
258
- var assignOwnEnumerable = (target, source) => {
259
- for (const key of Object.keys(source)) {
260
- if (isUnsafeKey(key)) {
261
- continue;
262
- }
263
- target[key] = source[key];
264
- }
198
+ const isArrayIndexKey = (key, length) => {
199
+ if (key === "") return false;
200
+ const index = Number(key);
201
+ return Number.isInteger(index) && index >= 0 && index < length && String(index) === key;
265
202
  };
266
- var areShallowEqualWithArray = (prev, next) => {
267
- if (prev === null || next === null || prev.length !== next.length) {
268
- return false;
269
- }
270
- const { length } = prev;
271
- for (let i = 0; i < length; i += 1) {
272
- if (!isEqual(prev[i], next[i])) {
273
- return false;
274
- }
275
- }
276
- return true;
203
+ const findSymbolKeyViolation = (value, path = [], seen = /* @__PURE__ */ new WeakSet()) => {
204
+ if (typeof value !== "object" || value === null) return;
205
+ if (seen.has(value)) return;
206
+ seen.add(value);
207
+ const descriptors = Object.getOwnPropertyDescriptors(value);
208
+ for (const key of getOwnEnumerableKeys(value)) {
209
+ const nextPath = [...path, key];
210
+ if (typeof key === "symbol") return {
211
+ type: "symbol-key",
212
+ path: nextPath
213
+ };
214
+ const descriptor = descriptors[key];
215
+ if (descriptor && Object.prototype.hasOwnProperty.call(descriptor, "value")) {
216
+ const violation = findSymbolKeyViolation(descriptor.value, nextPath, seen);
217
+ if (violation) return violation;
218
+ }
219
+ }
277
220
  };
278
- var mergeObject = (target, source, isSlice) => {
279
- if (isSlice) {
280
- if (typeof source === "object" && source !== null) {
281
- for (const key of Object.keys(source)) {
282
- if (isUnsafeKey(key)) {
283
- continue;
284
- }
285
- if (!Object.prototype.hasOwnProperty.call(target, key)) {
286
- continue;
287
- }
288
- const sourceValue = source[key];
289
- if (typeof sourceValue !== "object" || sourceValue === null) {
290
- continue;
291
- }
292
- const targetValue = target[key];
293
- if (typeof targetValue === "object" && targetValue !== null) {
294
- assignOwnEnumerable(targetValue, sourceValue);
295
- }
296
- }
297
- }
298
- } else {
299
- if (typeof source === "object" && source !== null) {
300
- assignOwnEnumerable(target, source);
301
- }
302
- }
221
+ const findJsonViolation = (value, path = [], ancestors = /* @__PURE__ */ new WeakSet()) => {
222
+ switch (typeof value) {
223
+ case "symbol": return {
224
+ type: "symbol-value",
225
+ path
226
+ };
227
+ case "bigint": return {
228
+ type: "bigint",
229
+ path
230
+ };
231
+ case "undefined": return {
232
+ type: "undefined",
233
+ path
234
+ };
235
+ case "function": return {
236
+ type: "function",
237
+ path
238
+ };
239
+ case "number": return Number.isFinite(value) ? void 0 : {
240
+ type: "non-finite-number",
241
+ path
242
+ };
243
+ default: break;
244
+ }
245
+ if (typeof value !== "object" || value === null) return;
246
+ if (ancestors.has(value)) return {
247
+ type: "circular-reference",
248
+ path
249
+ };
250
+ if (Array.isArray(value)) {
251
+ ancestors.add(value);
252
+ for (let index = 0; index < value.length; index += 1) if (!Object.prototype.hasOwnProperty.call(value, index)) return {
253
+ type: "array-hole",
254
+ path: [...path, index]
255
+ };
256
+ for (const key of getOwnEnumerableKeys(value)) {
257
+ const nextPath = [...path, key];
258
+ if (typeof key === "symbol") return {
259
+ type: "symbol-key",
260
+ path: nextPath
261
+ };
262
+ if (!isArrayIndexKey(key, value.length)) return {
263
+ type: "array-property",
264
+ path: nextPath
265
+ };
266
+ const violation = findJsonViolation(value[Number(key)], nextPath, ancestors);
267
+ if (violation) return violation;
268
+ }
269
+ ancestors.delete(value);
270
+ return;
271
+ }
272
+ if (!isPlainObject(value)) return {
273
+ type: "non-plain-object",
274
+ path
275
+ };
276
+ if (typeof value.toJSON === "function") return {
277
+ type: "to-json",
278
+ path
279
+ };
280
+ ancestors.add(value);
281
+ for (const key of getOwnEnumerableKeys(value)) {
282
+ const nextPath = [...path, key];
283
+ if (typeof key === "symbol") return {
284
+ type: "symbol-key",
285
+ path: nextPath
286
+ };
287
+ const child = value[key];
288
+ const violation = findJsonViolation(child, nextPath, ancestors);
289
+ if (violation) return violation;
290
+ }
291
+ ancestors.delete(value);
303
292
  };
304
- var uuid = () => {
305
- let timestamp = (/* @__PURE__ */ new Date()).getTime();
306
- const uuidTemplate = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
307
- const uuid2 = uuidTemplate.replace(/[xy]/g, (char) => {
308
- const randomNum = (timestamp + Math.random() * 16) % 16 | 0;
309
- timestamp = Math.floor(timestamp / 16);
310
- return (char === "x" ? randomNum : randomNum & 3 | 8).toString(16);
311
- });
312
- return uuid2;
293
+ const getViolationLabel = (violation) => {
294
+ switch (violation.type) {
295
+ case "bigint": return "BigInt-valued state";
296
+ case "undefined": return "Undefined-valued state";
297
+ case "function": return "Function-valued state";
298
+ case "non-finite-number": return "NaN or infinite number state";
299
+ case "non-plain-object": return "Non-plain object state";
300
+ case "circular-reference": return "Circular state reference";
301
+ case "array-hole": return "Sparse array state";
302
+ case "array-property": return "Non-index array property state";
303
+ case "to-json": return "Custom toJSON state";
304
+ default: return;
305
+ }
313
306
  };
314
-
315
- // src/getRawStateClientAction.ts
316
- var transportErrorMarker = "__coactionTransportError__";
317
- var isTransportErrorEnvelope = (value) => {
318
- if (typeof value !== "object" || value === null) {
319
- return false;
320
- }
321
- return value[transportErrorMarker] === true && typeof value.message === "string";
307
+ const validateSharedActionPaths = (state) => {
308
+ const violation = findSymbolKeyViolation(state);
309
+ if (!violation) return;
310
+ throw new Error(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPropertyPath(violation.path)}.`);
322
311
  };
323
- var isLegacyTransportErrorEnvelope = (value) => {
324
- if (typeof value !== "object" || value === null) {
325
- return false;
326
- }
327
- const candidate = value;
328
- return typeof candidate.$$Error === "string" && candidate.$$Error.length > 0 && Object.keys(candidate).length === 1;
312
+ const validateSharedStateSerializable = (state) => {
313
+ const violation = findJsonViolation(state);
314
+ if (!violation) return;
315
+ if (violation.type === "symbol-key") throw new Error(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPropertyPath(violation.path)}.`);
316
+ if (violation.type === "symbol-value") throw new Error(`Symbol-valued state is not supported in shared store mode because transport synchronization uses JSON. Found symbol value at ${formatPropertyPath(violation.path)}.`);
317
+ throw new Error(`${getViolationLabel(violation)} is not supported in shared store mode because transport synchronization uses JSON. Found unsupported value at ${formatPropertyPath(violation.path)}.`);
329
318
  };
330
- var createClientAction = ({
331
- clientExecuteSyncTimeoutMs,
332
- internal,
333
- key,
334
- store,
335
- sliceKey
336
- }) => {
337
- return (...args) => {
338
- let actionId;
339
- let done;
340
- if (store.trace) {
341
- actionId = uuid();
342
- store.trace({
343
- method: key,
344
- parameters: args,
345
- id: actionId,
346
- sliceKey
347
- });
348
- done = (result) => {
349
- store.trace({
350
- method: key,
351
- id: actionId,
352
- result,
353
- sliceKey
354
- });
355
- };
356
- }
357
- const keys = sliceKey ? [sliceKey, key] : [key];
358
- return store.transport.emit("execute", keys, args).then(async (response) => {
359
- const result = Array.isArray(response) ? response[0] : response;
360
- const sequence = Array.isArray(response) ? typeof response[1] === "number" ? response[1] : internal.sequence : internal.sequence;
361
- if (internal.sequence < sequence) {
362
- if (process.env.NODE_ENV === "development") {
363
- console.warn(
364
- `The sequence of the action is not consistent.`,
365
- sequence,
366
- internal.sequence
367
- );
368
- }
369
- await new Promise((resolve, reject) => {
370
- let settled = false;
371
- let unsubscribe = () => {
372
- };
373
- const timeoutRef = {};
374
- const cleanup = () => {
375
- unsubscribe();
376
- if (typeof timeoutRef.current !== "undefined") {
377
- clearTimeout(timeoutRef.current);
378
- }
379
- };
380
- const finishResolve = () => {
381
- if (settled) return;
382
- settled = true;
383
- cleanup();
384
- resolve();
385
- };
386
- const finishReject = (error) => {
387
- if (settled) return;
388
- settled = true;
389
- cleanup();
390
- reject(error);
391
- };
392
- unsubscribe = store.subscribe(() => {
393
- if (internal.sequence >= sequence) {
394
- finishResolve();
395
- }
396
- });
397
- timeoutRef.current = setTimeout(() => {
398
- void store.transport.emit("fullSync").then((latest) => {
399
- const next = latest;
400
- if (typeof next.state !== "string" || typeof next.sequence !== "number") {
401
- throw new Error("Invalid fullSync payload");
402
- }
403
- store.apply(JSON.parse(next.state));
404
- internal.sequence = next.sequence;
405
- if (internal.sequence >= sequence) {
406
- finishResolve();
407
- return;
408
- }
409
- finishReject(
410
- new Error(
411
- `Stale fullSync sequence: expected >= ${sequence}, got ${internal.sequence}`
412
- )
413
- );
414
- }).catch((error) => {
415
- finishReject(error);
416
- });
417
- }, clientExecuteSyncTimeoutMs);
418
- });
419
- }
420
- if (isTransportErrorEnvelope(result)) {
421
- done?.(result);
422
- throw new Error(result.message);
423
- }
424
- if (isLegacyTransportErrorEnvelope(result)) {
425
- done?.(result);
426
- throw new Error(result.$$Error);
427
- }
428
- done?.(result);
429
- return result;
430
- });
431
- };
319
+ //#endregion
320
+ //#region packages/core/src/asyncClientStore.ts
321
+ const parseFullSyncState$1 = (state) => {
322
+ const parsed = JSON.parse(state);
323
+ if (typeof parsed !== "object" || parsed === null) throw new Error("Invalid fullSync payload");
324
+ return sanitizeReplacementState(parsed);
432
325
  };
433
-
434
- // src/getRawStateLocalAction.ts
435
- var import_mutative = require("mutative");
436
- var getActionTarget = (store, sliceKey) => {
437
- return sliceKey ? store.getState()[sliceKey] : store.getState();
326
+ const clientApplyErrorMessage = "apply() cannot be called in the client store. Client stores are mirrors; use a store method to update the main store instead.";
327
+ const createAsyncClientStore = (createStore, asyncStoreClientOption) => {
328
+ const { store: asyncClientStore, internal } = createStore({ share: "client" });
329
+ let isApplyingClientState = false;
330
+ const previousAssertMutationAllowed = internal.assertMutationAllowed;
331
+ internal.assertMutationAllowed = (operation) => {
332
+ if (operation === "apply" && !isApplyingClientState) throw new Error(clientApplyErrorMessage);
333
+ previousAssertMutationAllowed?.(operation);
334
+ };
335
+ const baseApply = asyncClientStore.apply.bind(asyncClientStore);
336
+ asyncClientStore.apply = (state, patches) => {
337
+ if (!isApplyingClientState) throw new Error(clientApplyErrorMessage);
338
+ return baseApply(state, patches);
339
+ };
340
+ internal.applyClientState = (...args) => {
341
+ isApplyingClientState = true;
342
+ try {
343
+ baseApply(...args);
344
+ } finally {
345
+ isApplyingClientState = false;
346
+ }
347
+ };
348
+ const isSharedWorker = typeof SharedWorker !== "undefined" && asyncStoreClientOption.worker instanceof SharedWorker;
349
+ const transport = asyncStoreClientOption.worker ? (0, data_transport.createTransport)(isSharedWorker ? "SharedWorkerClient" : "WebWorkerClient", {
350
+ worker: asyncStoreClientOption.worker,
351
+ prefix: asyncClientStore.name
352
+ }) : asyncStoreClientOption.clientTransport;
353
+ if (!transport) throw new Error("transport is required");
354
+ asyncClientStore.transport = transport;
355
+ let syncingPromise = null;
356
+ let awaitingReconnectSync = false;
357
+ let reconnectSequenceBaseline = null;
358
+ const fullSync = async (allowLowerSequence = false) => {
359
+ if (!syncingPromise) syncingPromise = (async () => {
360
+ const latest = await transport.emit("fullSync");
361
+ if (typeof latest !== "object" || latest === null || typeof latest.sequence !== "number" || typeof latest.state !== "string") throw new Error("Invalid fullSync payload");
362
+ const canApplyLowerSequence = allowLowerSequence && awaitingReconnectSync && reconnectSequenceBaseline !== null && reconnectSequenceBaseline === internal.sequence;
363
+ if (latest.sequence < internal.sequence && !canApplyLowerSequence) return;
364
+ internal.applyClientState(parseFullSyncState$1(latest.state));
365
+ internal.sequence = latest.sequence;
366
+ awaitingReconnectSync = false;
367
+ reconnectSequenceBaseline = null;
368
+ })().finally(() => {
369
+ syncingPromise = null;
370
+ });
371
+ return syncingPromise;
372
+ };
373
+ if (typeof transport.onConnect !== "function") throw new Error("transport.onConnect is required");
374
+ transport.onConnect?.(() => {
375
+ awaitingReconnectSync = true;
376
+ reconnectSequenceBaseline = internal.sequence;
377
+ fullSync(true).catch((error) => {
378
+ if (process.env.NODE_ENV === "development") console.error(error);
379
+ });
380
+ });
381
+ transport.listen("update", async (options) => {
382
+ let shouldFullSync = false;
383
+ let allowLowerSequence = false;
384
+ try {
385
+ if (typeof options.sequence !== "number") shouldFullSync = true;
386
+ else if (options.sequence <= internal.sequence) if (awaitingReconnectSync) {
387
+ shouldFullSync = true;
388
+ allowLowerSequence = true;
389
+ } else if (options.sequence === 0 && internal.sequence > 0) {
390
+ awaitingReconnectSync = true;
391
+ reconnectSequenceBaseline = internal.sequence;
392
+ shouldFullSync = true;
393
+ allowLowerSequence = true;
394
+ } else return;
395
+ else if (options.sequence === internal.sequence + 1) {
396
+ internal.applyClientState(void 0, options.patches);
397
+ internal.sequence = options.sequence;
398
+ awaitingReconnectSync = false;
399
+ reconnectSequenceBaseline = null;
400
+ return;
401
+ } else {
402
+ shouldFullSync = true;
403
+ allowLowerSequence = awaitingReconnectSync;
404
+ }
405
+ if (shouldFullSync) await fullSync(allowLowerSequence);
406
+ } catch (error) {
407
+ if (!shouldFullSync) try {
408
+ await fullSync(awaitingReconnectSync);
409
+ } catch (syncError) {
410
+ if (process.env.NODE_ENV === "development") console.error(syncError);
411
+ }
412
+ if (process.env.NODE_ENV === "development") console.error(error);
413
+ }
414
+ });
415
+ return wrapStore(asyncClientStore, () => asyncClientStore.getState());
438
416
  };
439
- var createLocalAction = ({
440
- fn,
441
- internal,
442
- key,
443
- options,
444
- store,
445
- sliceKey
446
- }) => {
447
- return (...args) => {
448
- let actionId;
449
- let done;
450
- if (store.trace) {
451
- actionId = uuid();
452
- store.trace({
453
- method: key,
454
- parameters: args,
455
- id: actionId,
456
- sliceKey
457
- });
458
- done = (result2) => {
459
- store.trace({
460
- method: key,
461
- id: actionId,
462
- result: result2,
463
- sliceKey
464
- });
465
- };
466
- }
467
- const enablePatches = store.transport ?? options.enablePatches;
468
- if (internal.mutableInstance && !internal.isBatching && enablePatches) {
469
- let result2;
470
- const handleResult = (isDrafted2) => {
471
- handleDraft(store, internal);
472
- if (isDrafted2) {
473
- internal.backupState = internal.rootState;
474
- const [draft2, finalize2] = (0, import_mutative.create)(internal.rootState, {
475
- enablePatches: true
476
- });
477
- internal.finalizeDraft = finalize2;
478
- internal.rootState = draft2;
479
- }
480
- };
481
- const isDrafted = (0, import_mutative.isDraft)(internal.rootState);
482
- if (isDrafted) {
483
- handleResult();
484
- }
485
- internal.backupState = internal.rootState;
486
- const [draft, finalize] = (0, import_mutative.create)(internal.rootState, {
487
- enablePatches: true
488
- });
489
- internal.finalizeDraft = finalize;
490
- internal.rootState = draft;
491
- let asyncResult;
492
- try {
493
- result2 = fn.apply(getActionTarget(store, sliceKey), args);
494
- if (result2 instanceof Promise) {
495
- asyncResult = result2;
496
- }
497
- } finally {
498
- if (asyncResult) {
499
- } else {
500
- handleResult(isDrafted);
501
- }
502
- }
503
- if (asyncResult) {
504
- return asyncResult.finally(() => {
505
- const result3 = handleResult(isDrafted);
506
- done?.(result3);
507
- return result3;
508
- });
509
- }
510
- done?.(result2);
511
- return result2;
512
- }
513
- if (internal.mutableInstance && internal.actMutable) {
514
- const result2 = internal.actMutable(() => {
515
- return fn.apply(getActionTarget(store, sliceKey), args);
516
- });
517
- done?.(result2);
518
- return result2;
519
- }
520
- const result = fn.apply(getActionTarget(store, sliceKey), args);
521
- done?.(result);
522
- return result;
523
- };
417
+ const emit = (store, internal, patches) => {
418
+ const safePatches = sanitizePatches(patches);
419
+ if (store.transport && safePatches?.length) {
420
+ validateSharedStateSerializable(internal.rootState);
421
+ internal.sequence += 1;
422
+ store.transport.emit({
423
+ name: "update",
424
+ respond: false
425
+ }, {
426
+ patches: safePatches,
427
+ sequence: internal.sequence
428
+ });
429
+ }
524
430
  };
525
-
526
- // src/computed.ts
431
+ const handleDraft = (store, internal) => {
432
+ internal.rootState = internal.backupState;
433
+ const [nextState, patches, inversePatches] = internal.finalizeDraft();
434
+ if (store.share === "main") validateSharedStateSerializable(nextState);
435
+ const safePatches = sanitizePatches((store.patch ? store.patch({
436
+ patches,
437
+ inversePatches
438
+ }) : {
439
+ patches,
440
+ inversePatches
441
+ }).patches) ?? [];
442
+ if (safePatches.length) {
443
+ store.apply(internal.rootState, safePatches);
444
+ emit(store, internal, safePatches);
445
+ }
446
+ };
447
+ //#endregion
448
+ //#region packages/core/src/getInitialState.ts
449
+ const isObject = (value) => typeof value === "object" && value !== null;
450
+ const isStateFactory = (value) => typeof value === "function";
451
+ const hasGetState = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.getState === "function";
452
+ const hasBindState = (value) => isObject(value) && !!value[bindSymbol];
453
+ const formatInvalidStateMessage = (type, stateOrFn, key) => `Invalid state ${type} encountered in makeState: ${typeof key !== "undefined" ? `for key ${String(key)}, ` : ""}${typeof stateOrFn}`;
454
+ const getInitialState = (store, createState, internal) => {
455
+ const makeState = (stateOrFn, key) => {
456
+ let state;
457
+ if (isStateFactory(stateOrFn)) state = stateOrFn(store.setState, store.getState, store);
458
+ else if (isObject(stateOrFn)) state = stateOrFn;
459
+ else {
460
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("value", stateOrFn, key));
461
+ return {};
462
+ }
463
+ if (hasGetState(state)) state = state.getState();
464
+ else if (typeof state === "function") state = state();
465
+ if (hasBindState(state)) {
466
+ if (store.isSliceStore) throw new Error("Third-party state binding does not support Slices mode. Please inject a whole store instead.");
467
+ const binder = state[bindSymbol];
468
+ const rawState = binder.bind(state);
469
+ binder.handleStore(store, rawState, state, internal, key);
470
+ delete state[bindSymbol];
471
+ return rawState;
472
+ }
473
+ if (!isObject(state)) {
474
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("result", state, key));
475
+ return {};
476
+ }
477
+ return state;
478
+ };
479
+ if (!store.isSliceStore) return makeState(createState);
480
+ return getOwnEnumerableKeys(createState).reduce((stateTree, key) => {
481
+ if (typeof key === "string" && isUnsafeKey(key)) return stateTree;
482
+ setOwnEnumerable(stateTree, key, makeState(createState[key], key));
483
+ return stateTree;
484
+ }, {});
485
+ };
486
+ //#endregion
487
+ //#region packages/core/src/getRawStateClientAction.ts
488
+ const transportErrorMarker$1 = "__coactionTransportError__";
489
+ const parseFullSyncState = (state) => {
490
+ const parsed = JSON.parse(state);
491
+ if (typeof parsed !== "object" || parsed === null) throw new Error("Invalid fullSync payload");
492
+ return sanitizeReplacementState(parsed);
493
+ };
494
+ const isTransportErrorEnvelope = (value) => {
495
+ if (typeof value !== "object" || value === null) return false;
496
+ return value[transportErrorMarker$1] === true && typeof value.message === "string";
497
+ };
498
+ const isLegacyTransportErrorEnvelope = (value) => {
499
+ if (typeof value !== "object" || value === null) return false;
500
+ const candidate = value;
501
+ return typeof candidate.$$Error === "string" && candidate.$$Error.length > 0 && Object.keys(candidate).length === 1;
502
+ };
503
+ const createClientAction = ({ clientExecuteSyncTimeoutMs, internal, key, store, sliceKey }) => {
504
+ return (...args) => {
505
+ let actionId;
506
+ let done;
507
+ if (store.trace) {
508
+ actionId = uuid();
509
+ store.trace({
510
+ method: key,
511
+ parameters: args,
512
+ id: actionId,
513
+ sliceKey
514
+ });
515
+ done = (result) => {
516
+ store.trace({
517
+ method: key,
518
+ id: actionId,
519
+ result,
520
+ sliceKey
521
+ });
522
+ };
523
+ }
524
+ const traceAction = (run) => {
525
+ try {
526
+ const result = run();
527
+ if (result instanceof Promise) return result.then((value) => {
528
+ done?.(value);
529
+ return value;
530
+ }, (error) => {
531
+ done?.(error);
532
+ throw error;
533
+ });
534
+ done?.(result);
535
+ return result;
536
+ } catch (error) {
537
+ done?.(error);
538
+ throw error;
539
+ }
540
+ };
541
+ if (typeof sliceKey === "symbol") throw new Error("Symbol-keyed slice actions are not supported in client store mode.");
542
+ const keys = typeof sliceKey !== "undefined" ? [String(sliceKey), key] : [key];
543
+ return traceAction(() => store.transport.emit("execute", keys, args).then(async (response) => {
544
+ const result = Array.isArray(response) ? response[0] : response;
545
+ const sequence = Array.isArray(response) ? typeof response[1] === "number" ? response[1] : internal.sequence : internal.sequence;
546
+ if (internal.sequence < sequence) {
547
+ if (process.env.NODE_ENV === "development") console.warn(`The sequence of the action is not consistent.`, sequence, internal.sequence);
548
+ await new Promise((resolve, reject) => {
549
+ let settled = false;
550
+ let unsubscribe = () => {};
551
+ const timeoutRef = {};
552
+ const cleanup = () => {
553
+ unsubscribe();
554
+ if (typeof timeoutRef.current !== "undefined") clearTimeout(timeoutRef.current);
555
+ };
556
+ const finishResolve = () => {
557
+ if (settled) return;
558
+ settled = true;
559
+ cleanup();
560
+ resolve();
561
+ };
562
+ const finishReject = (error) => {
563
+ if (settled) return;
564
+ settled = true;
565
+ cleanup();
566
+ reject(error);
567
+ };
568
+ unsubscribe = store.subscribe(() => {
569
+ if (internal.sequence >= sequence) finishResolve();
570
+ });
571
+ timeoutRef.current = setTimeout(() => {
572
+ store.transport.emit("fullSync").then((latest) => {
573
+ if (typeof latest !== "object" || latest === null) throw new Error("Invalid fullSync payload");
574
+ const next = latest;
575
+ if (typeof next.state !== "string" || typeof next.sequence !== "number") throw new Error("Invalid fullSync payload");
576
+ if (next.sequence >= sequence) {
577
+ (internal.applyClientState ?? store.apply.bind(store))(parseFullSyncState(next.state));
578
+ internal.sequence = next.sequence;
579
+ finishResolve();
580
+ return;
581
+ }
582
+ finishReject(/* @__PURE__ */ new Error(`Stale fullSync sequence: expected >= ${sequence}, got ${next.sequence}`));
583
+ }).catch((error) => {
584
+ finishReject(error);
585
+ });
586
+ }, clientExecuteSyncTimeoutMs);
587
+ });
588
+ }
589
+ if (isTransportErrorEnvelope(result)) throw new Error(result.message);
590
+ if (isLegacyTransportErrorEnvelope(result)) throw new Error(result.$$Error);
591
+ return result;
592
+ }));
593
+ };
594
+ };
595
+ //#endregion
596
+ //#region packages/core/src/getRawStateLocalAction.ts
597
+ const getActionTarget = (store, sliceKey) => {
598
+ return typeof sliceKey !== "undefined" ? store.getState()[sliceKey] : store.getState();
599
+ };
600
+ const createLocalAction = ({ fn, internal, key, options, store, sliceKey }) => {
601
+ return (...args) => {
602
+ let actionId;
603
+ let done;
604
+ if (store.trace) {
605
+ actionId = uuid();
606
+ store.trace({
607
+ method: String(key),
608
+ parameters: args,
609
+ id: actionId,
610
+ sliceKey
611
+ });
612
+ done = (result) => {
613
+ store.trace({
614
+ method: String(key),
615
+ id: actionId,
616
+ result,
617
+ sliceKey
618
+ });
619
+ };
620
+ }
621
+ const traceAction = (run) => {
622
+ try {
623
+ const result = run();
624
+ if (result instanceof Promise) return result.then((value) => {
625
+ done?.(value);
626
+ return value;
627
+ }, (error) => {
628
+ done?.(error);
629
+ throw error;
630
+ });
631
+ done?.(result);
632
+ return result;
633
+ } catch (error) {
634
+ done?.(error);
635
+ throw error;
636
+ }
637
+ };
638
+ const enablePatches = store.transport ?? options.enablePatches;
639
+ return traceAction(() => {
640
+ if (internal.mutableInstance && !internal.isBatching && enablePatches) {
641
+ let result;
642
+ const handleResult = (isDrafted) => {
643
+ handleDraft(store, internal);
644
+ if (isDrafted) {
645
+ internal.backupState = internal.rootState;
646
+ const [draft, finalize] = (0, mutative.create)(internal.rootState, { enablePatches: true });
647
+ internal.finalizeDraft = finalize;
648
+ internal.rootState = draft;
649
+ }
650
+ };
651
+ const isDrafted = (0, mutative.isDraft)(internal.rootState);
652
+ if (isDrafted) handleResult();
653
+ internal.backupState = internal.rootState;
654
+ const [draft, finalize] = (0, mutative.create)(internal.rootState, { enablePatches: true });
655
+ internal.finalizeDraft = finalize;
656
+ internal.rootState = draft;
657
+ let asyncResult;
658
+ try {
659
+ result = fn.apply(getActionTarget(store, sliceKey), args);
660
+ if (result instanceof Promise) asyncResult = result;
661
+ } finally {
662
+ if (!asyncResult) handleResult(isDrafted);
663
+ }
664
+ if (asyncResult) return asyncResult.then((value) => {
665
+ handleResult(isDrafted);
666
+ return value;
667
+ }, (error) => {
668
+ handleResult(isDrafted);
669
+ throw error;
670
+ });
671
+ return result;
672
+ }
673
+ if (internal.mutableInstance && internal.actMutable) return internal.actMutable(() => {
674
+ return fn.apply(getActionTarget(store, sliceKey), args);
675
+ });
676
+ return fn.apply(getActionTarget(store, sliceKey), args);
677
+ });
678
+ };
679
+ };
680
+ //#endregion
681
+ //#region packages/core/src/computed.ts
682
+ const isObjectLike = (value) => typeof value === "object" && value !== null;
527
683
  var Computed = class {
528
- constructor(deps, fn) {
529
- this.deps = deps;
530
- this.fn = fn;
531
- }
684
+ deps;
685
+ fn;
686
+ constructor(deps, fn) {
687
+ this.deps = deps;
688
+ this.fn = fn;
689
+ }
690
+ createGetter({ internal }) {
691
+ const memoByReceiver = /* @__PURE__ */ new WeakMap();
692
+ const lastArgs = /* @__PURE__ */ new WeakMap();
693
+ const lastResult = /* @__PURE__ */ new WeakMap();
694
+ const fallbackReceiver = {};
695
+ const evaluate = (receiver) => {
696
+ const args = this.deps(internal.module);
697
+ if (!lastArgs.has(receiver) || !areShallowEqualWithArray(lastArgs.get(receiver), args)) lastResult.set(receiver, this.fn.apply(receiver, args));
698
+ lastArgs.set(receiver, args);
699
+ return lastResult.get(receiver);
700
+ };
701
+ return function() {
702
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
703
+ if (internal.isBatching) return evaluate(receiver);
704
+ let accessor = memoByReceiver.get(receiver);
705
+ if (!accessor) {
706
+ accessor = (0, alien_signals.computed)(() => evaluate(receiver));
707
+ memoByReceiver.set(receiver, accessor);
708
+ }
709
+ return accessor();
710
+ };
711
+ }
712
+ };
713
+ const createCachedGetter = (internal, getter) => {
714
+ const accessors = /* @__PURE__ */ new WeakMap();
715
+ const fallbackReceiver = {};
716
+ return function() {
717
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
718
+ if (internal.isBatching) return getter.call(receiver);
719
+ let accessor = accessors.get(receiver);
720
+ if (!accessor) {
721
+ accessor = (0, alien_signals.computed)(() => getter.call(receiver));
722
+ accessors.set(receiver, accessor);
723
+ }
724
+ return accessor();
725
+ };
726
+ };
727
+ const createTrackedStateReader = (internal, read, initialValue) => {
728
+ const slotSignal = (0, alien_signals.signal)(initialValue);
729
+ const slotVersionSignal = (0, alien_signals.signal)(0);
730
+ let slotVersion = 0;
731
+ (internal.signalSlots ??= /* @__PURE__ */ new Set()).add({ refresh: () => {
732
+ const nextValue = read();
733
+ slotSignal(nextValue);
734
+ if (internal.mutableInstance && isObjectLike(nextValue)) {
735
+ slotVersion += 1;
736
+ slotVersionSignal(slotVersion);
737
+ }
738
+ } });
739
+ return () => {
740
+ const currentValue = slotSignal();
741
+ if (internal.mutableInstance && isObjectLike(currentValue)) slotVersionSignal();
742
+ return read();
743
+ };
532
744
  };
533
- var defaultMemoize = (func) => {
534
- const lastArgs = /* @__PURE__ */ new WeakMap();
535
- const lastResult = /* @__PURE__ */ new WeakMap();
536
- return function() {
537
- if (!areShallowEqualWithArray(lastArgs.get(this) ?? [], arguments)) {
538
- lastResult.set(this, func.apply(this, arguments));
539
- }
540
- lastArgs.set(this, arguments);
541
- return lastResult.get(this);
542
- };
745
+ const refreshSignalSlots = (internal) => {
746
+ if (!internal.signalSlots?.size) return;
747
+ (0, alien_signals.startBatch)();
748
+ try {
749
+ internal.signalSlots.forEach((slot) => slot.refresh());
750
+ } finally {
751
+ (0, alien_signals.endBatch)();
752
+ }
543
753
  };
544
- var createSelectorCreatorWithArray = (memoize = defaultMemoize) => {
545
- return (dependenciesFunc, resultFunc) => {
546
- const memoizedResultFunc = memoize(function() {
547
- return resultFunc.apply(this, arguments);
548
- });
549
- return function() {
550
- return memoizedResultFunc.apply(
551
- this,
552
- dependenciesFunc.apply(null, [this])
553
- );
554
- };
555
- };
754
+ //#endregion
755
+ //#region packages/core/src/getRawStateStateProperty.ts
756
+ const prepareStateDescriptor = ({ descriptor, initialStateSeen, internal, key, rawState, sliceKey }) => {
757
+ const isComputed = descriptor.value instanceof Computed;
758
+ const readStateValue = () => typeof sliceKey !== "undefined" ? internal.rootState[sliceKey][key] : internal.rootState[key];
759
+ const initialValue = isComputed ? descriptor.value : sanitizeInitialStateValue(descriptor.value, initialStateSeen);
760
+ if (internal.mutableInstance) Object.defineProperty(rawState, key, {
761
+ get: () => internal.mutableInstance[key],
762
+ set: (value) => {
763
+ internal.mutableInstance[key] = value;
764
+ },
765
+ configurable: true,
766
+ enumerable: descriptor.enumerable
767
+ });
768
+ else if (!isComputed) Object.defineProperty(rawState, key, {
769
+ value: initialValue,
770
+ configurable: true,
771
+ enumerable: descriptor.enumerable,
772
+ writable: true
773
+ });
774
+ if (isComputed) {
775
+ if (internal.mutableInstance) throw new Error("Computed is not supported with mutable instance");
776
+ descriptor.get = descriptor.value.createGetter({ internal });
777
+ } else if (typeof sliceKey !== "undefined") {
778
+ const read = createTrackedStateReader(internal, readStateValue, initialValue);
779
+ descriptor.get = () => read();
780
+ descriptor.set = (value) => {
781
+ internal.rootState[sliceKey][key] = value;
782
+ };
783
+ } else {
784
+ const read = createTrackedStateReader(internal, readStateValue, initialValue);
785
+ descriptor.get = () => read();
786
+ descriptor.set = (value) => {
787
+ internal.rootState[key] = value;
788
+ };
789
+ }
790
+ delete descriptor.value;
791
+ delete descriptor.writable;
556
792
  };
557
- var createSelectorWithArray = createSelectorCreatorWithArray();
558
-
559
- // src/getRawStateStateProperty.ts
560
- var prepareStateDescriptor = ({
561
- descriptor,
562
- internal,
563
- key,
564
- rawState,
565
- sliceKey
566
- }) => {
567
- const isComputed = descriptor.value instanceof Computed;
568
- if (internal.mutableInstance) {
569
- Object.defineProperty(rawState, key, {
570
- get: () => internal.mutableInstance[key],
571
- set: (value) => {
572
- internal.mutableInstance[key] = value;
573
- },
574
- enumerable: true
575
- });
576
- } else if (!isComputed) {
577
- rawState[key] = descriptor.value;
578
- }
579
- if (isComputed) {
580
- if (internal.mutableInstance) {
581
- throw new Error("Computed is not supported with mutable instance");
582
- }
583
- const { deps, fn } = descriptor.value;
584
- const depsCallbackSelector = createSelectorWithArray(
585
- // the root state should be updated, and the computed property will be updated.
586
- () => [internal.rootState],
587
- () => {
588
- return deps(internal.module);
589
- }
590
- );
591
- const selector = createSelectorWithArray(
592
- (that) => depsCallbackSelector.call(that),
593
- fn
594
- );
595
- descriptor.get = function() {
596
- return selector.call(this);
597
- };
598
- } else if (sliceKey) {
599
- descriptor.get = () => internal.rootState[sliceKey][key];
600
- descriptor.set = (value) => {
601
- internal.rootState[sliceKey][key] = value;
602
- };
603
- } else {
604
- descriptor.get = () => internal.rootState[key];
605
- descriptor.set = (value) => {
606
- internal.rootState[key] = value;
607
- };
608
- }
609
- delete descriptor.value;
610
- delete descriptor.writable;
793
+ const prepareAccessorDescriptor = ({ descriptor, internal }) => {
794
+ if (internal.mutableInstance || typeof descriptor.get !== "function") return;
795
+ descriptor.get = createCachedGetter(internal, descriptor.get);
611
796
  };
612
-
613
- // src/getRawState.ts
614
- var defaultClientExecuteSyncTimeoutMs = 1500;
615
- var getClientExecuteSyncTimeoutMs = (options) => {
616
- const timeout = options.executeSyncTimeoutMs;
617
- if (typeof timeout === "undefined") {
618
- return defaultClientExecuteSyncTimeoutMs;
619
- }
620
- if (!Number.isFinite(timeout) || timeout < 0) {
621
- throw new Error(
622
- "executeSyncTimeoutMs must be a finite number greater than or equal to 0"
623
- );
624
- }
625
- return timeout;
797
+ //#endregion
798
+ //#region packages/core/src/getRawState.ts
799
+ const defaultClientExecuteSyncTimeoutMs = 1500;
800
+ const getClientExecuteSyncTimeoutMs = (options) => {
801
+ const timeout = options.executeSyncTimeoutMs;
802
+ if (typeof timeout === "undefined") return defaultClientExecuteSyncTimeoutMs;
803
+ if (!Number.isFinite(timeout) || timeout < 0) throw new Error("executeSyncTimeoutMs must be a finite number greater than or equal to 0");
804
+ return timeout;
626
805
  };
627
- var getRawState = (store, internal, initialState, options) => {
628
- const clientExecuteSyncTimeoutMs = getClientExecuteSyncTimeoutMs(options);
629
- const rawState = {};
630
- const handle = (_rawState, _initialState, sliceKey) => {
631
- internal.mutableInstance = internal.toMutableRaw?.(_initialState);
632
- const descriptors = Object.getOwnPropertyDescriptors(_initialState);
633
- Object.entries(descriptors).forEach(([key, descriptor]) => {
634
- if (Object.prototype.hasOwnProperty.call(descriptor, "value")) {
635
- if (typeof descriptor.value !== "function") {
636
- prepareStateDescriptor({
637
- descriptor,
638
- internal,
639
- key,
640
- rawState: _rawState,
641
- sliceKey
642
- });
643
- } else if (store.share === "client") {
644
- descriptor.value = createClientAction({
645
- clientExecuteSyncTimeoutMs,
646
- internal,
647
- key,
648
- store,
649
- sliceKey
650
- });
651
- } else {
652
- descriptor.value = createLocalAction({
653
- fn: descriptor.value,
654
- internal,
655
- key,
656
- options,
657
- store,
658
- sliceKey
659
- });
660
- }
661
- }
662
- });
663
- const slice = Object.defineProperties({}, descriptors);
664
- return slice;
665
- };
666
- if (store.isSliceStore) {
667
- internal.module = {};
668
- Object.entries(initialState).forEach(([key, value]) => {
669
- rawState[key] = {};
670
- internal.module[key] = handle(rawState[key], value, key);
671
- });
672
- } else {
673
- internal.module = handle(rawState, initialState);
674
- }
675
- return rawState;
806
+ const getRawState = (store, internal, initialState, options) => {
807
+ const clientExecuteSyncTimeoutMs = getClientExecuteSyncTimeoutMs(options);
808
+ const rawState = {};
809
+ const handle = (_rawState, _initialState, sliceKey) => {
810
+ internal.mutableInstance = internal.toMutableRaw?.(_initialState);
811
+ const initialStateSeen = /* @__PURE__ */ new WeakMap();
812
+ initialStateSeen.set(_initialState, _rawState);
813
+ const safeDescriptors = {};
814
+ const descriptors = Object.getOwnPropertyDescriptors(_initialState);
815
+ Reflect.ownKeys(descriptors).forEach((key) => {
816
+ if (typeof key === "string" && isUnsafeKey(key)) return;
817
+ safeDescriptors[key] = Reflect.get(descriptors, key);
818
+ });
819
+ Reflect.ownKeys(safeDescriptors).forEach((key) => {
820
+ const descriptor = safeDescriptors[key];
821
+ if (typeof descriptor === "undefined") return;
822
+ if (!Object.prototype.hasOwnProperty.call(descriptor, "value")) {
823
+ prepareAccessorDescriptor({
824
+ descriptor,
825
+ internal
826
+ });
827
+ return;
828
+ }
829
+ if (Object.prototype.hasOwnProperty.call(descriptor, "value")) {
830
+ if (typeof descriptor.value !== "function") {
831
+ prepareStateDescriptor({
832
+ descriptor,
833
+ initialStateSeen,
834
+ internal,
835
+ key,
836
+ rawState: _rawState,
837
+ sliceKey
838
+ });
839
+ return;
840
+ }
841
+ if (store.share === "client") {
842
+ if (typeof key !== "string") return;
843
+ descriptor.value = createClientAction({
844
+ clientExecuteSyncTimeoutMs,
845
+ internal,
846
+ key,
847
+ store,
848
+ sliceKey
849
+ });
850
+ } else descriptor.value = createLocalAction({
851
+ fn: descriptor.value,
852
+ internal,
853
+ key,
854
+ options,
855
+ store,
856
+ sliceKey
857
+ });
858
+ }
859
+ });
860
+ return Object.defineProperties({}, safeDescriptors);
861
+ };
862
+ if (store.isSliceStore) {
863
+ internal.module = {};
864
+ getOwnEnumerableKeys(initialState).forEach((key) => {
865
+ if (typeof key === "string" && isUnsafeKey(key)) return;
866
+ const sliceRawState = {};
867
+ setOwnEnumerable(rawState, key, sliceRawState);
868
+ setOwnEnumerable(internal.module, key, handle(sliceRawState, initialState[key], key));
869
+ });
870
+ } else internal.module = handle(rawState, initialState);
871
+ return rawState;
676
872
  };
677
-
678
- // src/handleState.ts
679
- var import_mutative2 = require("mutative");
680
- var handleState = (store, internal, options) => {
681
- const setState = (next, updater = (next2) => {
682
- const merge = (_next = next2) => {
683
- mergeObject(internal.rootState, _next, store.isSliceStore);
684
- };
685
- const fn = typeof next2 === "function" ? () => {
686
- const returnValue = next2(internal.module);
687
- if (returnValue instanceof Promise) {
688
- throw new Error(
689
- "setState with async function is not supported"
690
- );
691
- }
692
- if (typeof returnValue === "object" && returnValue !== null) {
693
- merge(returnValue);
694
- }
695
- } : merge;
696
- const enablePatches = store.transport ?? options.enablePatches;
697
- if (!enablePatches && internal.mutableInstance) {
698
- if (internal.actMutable) {
699
- internal.actMutable(() => {
700
- fn.apply(null);
701
- });
702
- return [];
703
- }
704
- fn.apply(null);
705
- return [];
706
- }
707
- internal.backupState = internal.rootState;
708
- let patches;
709
- let inversePatches;
710
- try {
711
- const result = (0, import_mutative2.create)(
712
- internal.rootState,
713
- (draft) => {
714
- internal.rootState = draft;
715
- return fn.apply(null);
716
- },
717
- {
718
- enablePatches: true
719
- }
720
- );
721
- patches = result[1];
722
- inversePatches = result[2];
723
- } finally {
724
- internal.rootState = internal.backupState;
725
- }
726
- const finalPatches = store.patch ? store.patch({ patches, inversePatches }) : { patches, inversePatches };
727
- if (finalPatches.patches.length) {
728
- store.apply(internal.rootState, finalPatches.patches);
729
- if (!internal.mutableInstance) {
730
- if (internal.updateImmutable) {
731
- internal.updateImmutable(internal.rootState);
732
- } else {
733
- internal.listeners.forEach((listener) => listener());
734
- }
735
- }
736
- }
737
- return [
738
- internal.rootState,
739
- finalPatches.patches,
740
- finalPatches.inversePatches
741
- ];
742
- }) => {
743
- if (store.share === "client") {
744
- throw new Error(
745
- `setState() cannot be called in the client store. To update the state, please trigger a store method with setState() instead.`
746
- );
747
- }
748
- if (internal.isBatching) {
749
- throw new Error("setState cannot be called within the updater");
750
- }
751
- internal.isBatching = true;
752
- if (!store.share && !options.enablePatches && !internal.mutableInstance) {
753
- if (typeof next === "function") {
754
- try {
755
- internal.backupState = internal.rootState;
756
- internal.rootState = (0, import_mutative2.create)(
757
- internal.rootState,
758
- (draft) => {
759
- internal.rootState = draft;
760
- return next(internal.module);
761
- }
762
- );
763
- } catch (error) {
764
- internal.rootState = internal.backupState;
765
- internal.isBatching = false;
766
- throw error;
767
- }
768
- } else {
769
- const copy = {};
770
- const rootState = internal.rootState;
771
- for (const key of Object.keys(rootState)) {
772
- copy[key] = rootState[key];
773
- }
774
- for (const key of Object.keys(next)) {
775
- copy[key] = next[key];
776
- }
777
- internal.rootState = copy;
778
- }
779
- if (internal.updateImmutable) {
780
- internal.updateImmutable(internal.rootState);
781
- } else {
782
- internal.listeners.forEach((listener) => listener());
783
- }
784
- internal.isBatching = false;
785
- return [];
786
- }
787
- let result;
788
- try {
789
- const isDrafted = internal.mutableInstance && (0, import_mutative2.isDraft)(internal.rootState);
790
- if (isDrafted) {
791
- handleDraft(store, internal);
792
- }
793
- result = updater(next);
794
- if (isDrafted) {
795
- internal.backupState = internal.rootState;
796
- const [draft, finalize] = (0, import_mutative2.create)(
797
- internal.rootState,
798
- {
799
- enablePatches: true
800
- }
801
- );
802
- internal.finalizeDraft = finalize;
803
- internal.rootState = draft;
804
- }
805
- } finally {
806
- internal.isBatching = false;
807
- }
808
- emit(store, internal, result?.[1]);
809
- return result;
810
- };
811
- const getState = (deps, selector) => deps && selector ? new Computed(deps, selector) : internal.module;
812
- return { setState, getState };
873
+ //#endregion
874
+ //#region packages/core/src/handleState.ts
875
+ const handleState = (store, internal, options) => {
876
+ const setState = (next, updater = (next) => {
877
+ const merge = (_next = next) => {
878
+ mergeObject(internal.rootState, _next, store.isSliceStore);
879
+ };
880
+ const fn = typeof next === "function" ? () => {
881
+ const returnValue = next(internal.module);
882
+ if (returnValue instanceof Promise) throw new Error("setState with async function is not supported");
883
+ if (typeof returnValue === "object" && returnValue !== null) merge(returnValue);
884
+ } : merge;
885
+ if (!(store.transport ?? options.enablePatches) && internal.mutableInstance) {
886
+ if (internal.actMutable) {
887
+ internal.actMutable(() => {
888
+ fn.apply(null);
889
+ });
890
+ return [];
891
+ }
892
+ fn.apply(null);
893
+ return [];
894
+ }
895
+ internal.backupState = internal.rootState;
896
+ let patches;
897
+ let inversePatches;
898
+ try {
899
+ const result = (0, mutative.create)(internal.rootState, (draft) => {
900
+ internal.rootState = draft;
901
+ return fn.apply(null);
902
+ }, { enablePatches: true });
903
+ if (store.share === "main") validateSharedStateSerializable(result[0]);
904
+ patches = result[1];
905
+ inversePatches = result[2];
906
+ } finally {
907
+ internal.rootState = internal.backupState;
908
+ }
909
+ const finalPatches = store.patch ? store.patch({
910
+ patches,
911
+ inversePatches
912
+ }) : {
913
+ patches,
914
+ inversePatches
915
+ };
916
+ const safePatches = sanitizePatches(finalPatches.patches) ?? [];
917
+ const safeInversePatches = sanitizePatches(finalPatches.inversePatches) ?? [];
918
+ if (safePatches.length) store.apply(internal.rootState, safePatches);
919
+ return [
920
+ internal.rootState,
921
+ safePatches,
922
+ safeInversePatches
923
+ ];
924
+ }) => {
925
+ internal.assertMutationAllowed?.("setState");
926
+ if (store.share === "client") throw new Error(`setState() cannot be called in the client store. To update the state, please trigger a store method with setState() instead.`);
927
+ if (internal.isBatching) throw new Error("setState cannot be called within the updater");
928
+ if (next === null) return [];
929
+ internal.isBatching = true;
930
+ if (!store.share && !options.enablePatches && !internal.mutableInstance) try {
931
+ if (typeof next === "function") try {
932
+ internal.backupState = internal.rootState;
933
+ internal.rootState = (0, mutative.create)(internal.rootState, (draft) => {
934
+ internal.rootState = draft;
935
+ const returnValue = next(internal.module);
936
+ if (returnValue instanceof Promise) throw new Error("setState with async function is not supported");
937
+ if (typeof returnValue === "object" && returnValue !== null) mergeObject(internal.rootState, returnValue, store.isSliceStore);
938
+ });
939
+ } catch (error) {
940
+ internal.rootState = internal.backupState;
941
+ throw error;
942
+ }
943
+ else {
944
+ const copy = cloneOwnEnumerable(internal.rootState);
945
+ if (store.isSliceStore) {
946
+ const nextRecord = next;
947
+ const copyRecord = copy;
948
+ for (const key of getOwnEnumerableKeys(nextRecord)) {
949
+ if (!Object.prototype.hasOwnProperty.call(copyRecord, key)) continue;
950
+ const sourceValue = nextRecord[key];
951
+ if (typeof sourceValue !== "object" || sourceValue === null) continue;
952
+ const targetValue = copyRecord[key];
953
+ if (typeof targetValue !== "object" || targetValue === null) continue;
954
+ const sliceCopy = cloneOwnEnumerable(targetValue);
955
+ mergeObject(sliceCopy, sourceValue);
956
+ setOwnEnumerable(copyRecord, key, sliceCopy);
957
+ }
958
+ } else mergeObject(copy, next);
959
+ internal.rootState = copy;
960
+ }
961
+ refreshSignalSlots(internal);
962
+ if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
963
+ else internal.listeners.forEach((listener) => listener());
964
+ return [];
965
+ } finally {
966
+ internal.isBatching = false;
967
+ }
968
+ let result;
969
+ try {
970
+ const isDrafted = internal.mutableInstance && (0, mutative.isDraft)(internal.rootState);
971
+ if (isDrafted) handleDraft(store, internal);
972
+ result = updater(next);
973
+ if (store.share === "main") validateSharedStateSerializable(internal.rootState);
974
+ if (isDrafted) {
975
+ internal.backupState = internal.rootState;
976
+ const [draft, finalize] = (0, mutative.create)(internal.rootState, { enablePatches: true });
977
+ internal.finalizeDraft = finalize;
978
+ internal.rootState = draft;
979
+ }
980
+ } finally {
981
+ internal.isBatching = false;
982
+ }
983
+ if (result?.length) result = [
984
+ result[0],
985
+ sanitizePatches(result[1]) ?? [],
986
+ sanitizePatches(result[2]) ?? []
987
+ ];
988
+ emit(store, internal, result?.[1]);
989
+ return result;
990
+ };
991
+ const getState = (deps, selector) => deps && selector ? new Computed(deps, selector) : internal.module;
992
+ return {
993
+ setState,
994
+ getState
995
+ };
813
996
  };
814
-
815
- // src/applyMiddlewares.ts
816
- var isStoreLike = (value) => {
817
- if (!value || typeof value !== "object") {
818
- return false;
819
- }
820
- const candidate = value;
821
- return typeof candidate.setState === "function" && typeof candidate.getState === "function" && typeof candidate.subscribe === "function" && typeof candidate.destroy === "function" && typeof candidate.apply === "function" && typeof candidate.getPureState === "function";
997
+ //#endregion
998
+ //#region packages/core/src/applyMiddlewares.ts
999
+ const isStoreLike = (value) => {
1000
+ if (!value || typeof value !== "object") return false;
1001
+ const candidate = value;
1002
+ return typeof candidate.setState === "function" && typeof candidate.getState === "function" && typeof candidate.subscribe === "function" && typeof candidate.destroy === "function" && typeof candidate.apply === "function" && typeof candidate.getPureState === "function";
822
1003
  };
823
- var applyMiddlewares = (store, middlewares) => {
824
- return middlewares.reduce((store2, middleware, index) => {
825
- if (process.env.NODE_ENV === "development") {
826
- if (typeof middleware !== "function") {
827
- throw new Error(`middlewares[${index}] should be a function`);
828
- }
829
- }
830
- const nextStore = middleware(store2);
831
- if (process.env.NODE_ENV === "development") {
832
- if (!isStoreLike(nextStore)) {
833
- throw new Error(
834
- `middlewares[${index}] should return a store-like object`
835
- );
836
- }
837
- }
838
- return nextStore;
839
- }, store);
1004
+ const applyMiddlewares = (store, middlewares) => {
1005
+ return middlewares.reduce((store, middleware, index) => {
1006
+ if (process.env.NODE_ENV === "development") {
1007
+ if (typeof middleware !== "function") throw new Error(`middlewares[${index}] should be a function`);
1008
+ }
1009
+ const nextStore = middleware(store);
1010
+ if (process.env.NODE_ENV === "development") {
1011
+ if (!isStoreLike(nextStore)) throw new Error(`middlewares[${index}] should return a store-like object`);
1012
+ }
1013
+ return nextStore;
1014
+ }, store);
840
1015
  };
841
-
842
- // src/handleMainTransport.ts
843
- var import_data_transport2 = require("data-transport");
844
- var getErrorMessage = (error) => {
845
- if (error instanceof Error) {
846
- return error.message;
847
- }
848
- return String(error);
1016
+ //#endregion
1017
+ //#region packages/core/src/handleMainTransport.ts
1018
+ const getErrorMessage = (error) => {
1019
+ if (error instanceof Error) return error.message;
1020
+ return String(error);
849
1021
  };
850
- var transportErrorMarker2 = "__coactionTransportError__";
851
- var handleMainTransport = (store, internal, storeTransport, workerType, checkEnablePatches) => {
852
- const transport = storeTransport ?? (workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal" ? (0, import_data_transport2.createTransport)(workerType, {
853
- prefix: store.name
854
- }) : void 0);
855
- if (!transport) return;
856
- if (typeof transport.onConnect !== "function") {
857
- throw new Error("transport.onConnect is required");
858
- }
859
- if (checkEnablePatches) {
860
- throw new Error(`enablePatches: true is required for the transport`);
861
- }
862
- transport.listen("execute", async (keys, args) => {
863
- let base = store.getState();
864
- let obj = base;
865
- try {
866
- for (const key of keys) {
867
- base = base[key];
868
- if (typeof base === "function") {
869
- base = base.bind(obj);
870
- }
871
- obj = base;
872
- }
873
- if (typeof base !== "function") {
874
- throw new Error("The function is not found");
875
- }
876
- const result = await base(...args);
877
- return [result, internal.sequence];
878
- } catch (error) {
879
- if (process.env.NODE_ENV === "development") {
880
- console.error(error);
881
- }
882
- return [
883
- {
884
- [transportErrorMarker2]: true,
885
- message: getErrorMessage(error)
886
- },
887
- internal.sequence
888
- ];
889
- }
890
- });
891
- transport.listen("fullSync", async () => {
892
- return {
893
- state: JSON.stringify(internal.rootState),
894
- sequence: internal.sequence
895
- };
896
- });
897
- store.transport = transport;
1022
+ const transportErrorMarker = "__coactionTransportError__";
1023
+ const handleMainTransport = (store, internal, storeTransport, workerType, checkEnablePatches) => {
1024
+ const transport = storeTransport ?? (workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal" ? (0, data_transport.createTransport)(workerType, { prefix: store.name }) : void 0);
1025
+ if (!transport) return;
1026
+ if (typeof transport.onConnect !== "function") throw new Error("transport.onConnect is required");
1027
+ if (checkEnablePatches) throw new Error(`enablePatches: true is required for the transport`);
1028
+ transport.listen("execute", async (keys, args) => {
1029
+ let base = store.getState();
1030
+ try {
1031
+ for (const key of keys) {
1032
+ if (isUnsafePathSegment(key) || typeof base !== "object" && typeof base !== "function" || base === null || !Object.prototype.hasOwnProperty.call(base, key)) throw new Error("The function is not found");
1033
+ const obj = base;
1034
+ base = base[key];
1035
+ if (typeof base === "function") base = base.bind(obj);
1036
+ }
1037
+ if (typeof base !== "function") throw new Error("The function is not found");
1038
+ return [await base(...args), internal.sequence];
1039
+ } catch (error) {
1040
+ if (process.env.NODE_ENV === "development") console.error(error);
1041
+ return [{
1042
+ [transportErrorMarker]: true,
1043
+ message: getErrorMessage(error)
1044
+ }, internal.sequence];
1045
+ }
1046
+ });
1047
+ transport.listen("fullSync", async () => {
1048
+ validateSharedStateSerializable(internal.rootState);
1049
+ return {
1050
+ state: JSON.stringify(internal.rootState),
1051
+ sequence: internal.sequence
1052
+ };
1053
+ });
1054
+ store.transport = transport;
898
1055
  };
899
-
900
- // src/create.ts
901
- var namespaceMap = /* @__PURE__ */ new Map();
902
- var hasWarnedAmbiguousFunctionMap = false;
903
- var warnAmbiguousFunctionMap = () => {
904
- if (hasWarnedAmbiguousFunctionMap || process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") {
905
- return;
906
- }
907
- hasWarnedAmbiguousFunctionMap = true;
908
- console.warn(
909
- [
910
- `sliceMode: 'auto' inferred slices from an object of functions.`,
911
- `This shape is ambiguous with a single store that only contains methods.`,
912
- `Use create({ ping() {} }, { sliceMode: 'single' }) for a plain method store,`,
913
- `or create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' }) for slices.`
914
- ].join(" ")
915
- );
1056
+ //#endregion
1057
+ //#region packages/core/src/lifecycle.ts
1058
+ const readyStores = /* @__PURE__ */ new WeakSet();
1059
+ const readyCallbacks = /* @__PURE__ */ new WeakMap();
1060
+ const onStoreReady = (store, callback) => {
1061
+ if (readyStores.has(store)) {
1062
+ callback();
1063
+ return () => void 0;
1064
+ }
1065
+ let callbacks = readyCallbacks.get(store);
1066
+ if (!callbacks) {
1067
+ callbacks = /* @__PURE__ */ new Set();
1068
+ readyCallbacks.set(store, callbacks);
1069
+ }
1070
+ callbacks.add(callback);
1071
+ return () => {
1072
+ callbacks?.delete(callback);
1073
+ };
916
1074
  };
917
- var create = (createState, options = {}) => {
918
- const checkEnablePatches = Object.hasOwnProperty.call(options, "enablePatches") && !options.enablePatches;
919
- const workerType = options.workerType ?? WorkerType;
920
- if (process.env.NODE_ENV === "development" && options.transport && options.clientTransport) {
921
- throw new Error(
922
- `transport and clientTransport cannot be used together, please use one of them.`
923
- );
924
- }
925
- const storeTransport = options.transport;
926
- const share = workerType === "WebWorkerInternal" || workerType === "SharedWorkerInternal" || storeTransport ? "main" : void 0;
927
- const createStore = ({ share: share2 }) => {
928
- const store2 = {};
929
- const internal2 = {
930
- sequence: 0,
931
- isBatching: false,
932
- listeners: /* @__PURE__ */ new Set()
933
- };
934
- const name = options.name ?? defaultName;
935
- const shouldTrackName = share2 === "main" && process.env.NODE_ENV !== "test";
936
- const releaseStoreName = () => {
937
- if (shouldTrackName) {
938
- namespaceMap.delete(name);
939
- }
940
- };
941
- if (shouldTrackName) {
942
- if (namespaceMap.get(name)) {
943
- throw new Error(`Store name '${name}' is not unique.`);
944
- }
945
- namespaceMap.set(name, true);
946
- }
947
- try {
948
- const { setState, getState } = handleState(store2, internal2, options);
949
- const subscribe = (listener) => {
950
- internal2.listeners.add(listener);
951
- return () => internal2.listeners.delete(listener);
952
- };
953
- let isDestroyed = false;
954
- const destroy = () => {
955
- if (isDestroyed) {
956
- return;
957
- }
958
- isDestroyed = true;
959
- internal2.listeners.clear();
960
- store2.transport?.dispose();
961
- releaseStoreName();
962
- };
963
- const apply = (state = internal2.rootState, patches) => {
964
- internal2.rootState = patches ? (0, import_mutative3.apply)(state, patches) : state;
965
- if (internal2.updateImmutable) {
966
- internal2.updateImmutable(internal2.rootState);
967
- } else {
968
- internal2.listeners.forEach((listener) => listener());
969
- }
970
- };
971
- const getPureState = () => internal2.rootState;
972
- const isFunctionMapObject = () => {
973
- if (typeof createState === "object" && createState !== null) {
974
- const values = Object.values(createState);
975
- return values.length > 0 && values.every((value) => typeof value === "function");
976
- }
977
- return false;
978
- };
979
- const getIsSliceStore = () => {
980
- const sliceMode = options.sliceMode ?? "auto";
981
- if (sliceMode === "single") {
982
- return false;
983
- }
984
- if (sliceMode === "slices") {
985
- if (!isFunctionMapObject()) {
986
- throw new Error(
987
- `sliceMode: 'slices' requires createState to be an object of slice functions.`
988
- );
989
- }
990
- return true;
991
- }
992
- if (isFunctionMapObject()) {
993
- warnAmbiguousFunctionMap();
994
- return true;
995
- }
996
- return false;
997
- };
998
- const isSliceStore = getIsSliceStore();
999
- Object.assign(store2, {
1000
- name,
1001
- share: share2 ?? false,
1002
- setState,
1003
- getState,
1004
- subscribe,
1005
- destroy,
1006
- apply,
1007
- isSliceStore,
1008
- getPureState
1009
- });
1010
- const middlewareStore = applyMiddlewares(
1011
- store2,
1012
- options.middlewares ?? []
1013
- );
1014
- if (middlewareStore !== store2) {
1015
- Object.assign(store2, middlewareStore);
1016
- }
1017
- const initialState = getInitialState(store2, createState, internal2);
1018
- store2.getInitialState = () => initialState;
1019
- internal2.rootState = getRawState(
1020
- store2,
1021
- internal2,
1022
- initialState,
1023
- options
1024
- );
1025
- return { store: store2, internal: internal2 };
1026
- } catch (error) {
1027
- releaseStoreName();
1028
- throw error;
1029
- }
1030
- };
1031
- if (options.clientTransport || options.worker || options.workerType === "WebWorkerClient" || options.workerType === "SharedWorkerClient") {
1032
- if (checkEnablePatches) {
1033
- throw new Error(`enablePatches: true is required for the async store`);
1034
- }
1035
- const store2 = createAsyncClientStore(
1036
- createStore,
1037
- options
1038
- );
1039
- return wrapStore(store2);
1040
- }
1041
- const { store, internal } = createStore({
1042
- share
1043
- });
1044
- handleMainTransport(
1045
- store,
1046
- internal,
1047
- storeTransport,
1048
- workerType,
1049
- checkEnablePatches
1050
- );
1051
- return wrapStore(store);
1075
+ const markStoreReady = (store) => {
1076
+ readyStores.add(store);
1077
+ const callbacks = readyCallbacks.get(store);
1078
+ if (!callbacks) return;
1079
+ readyCallbacks.delete(store);
1080
+ callbacks.forEach((callback) => callback());
1081
+ callbacks.clear();
1052
1082
  };
1053
-
1054
- // src/binder.ts
1055
- function createBinder({
1056
- handleState: handleState2,
1057
- handleStore
1058
- }) {
1059
- return ((state) => {
1060
- const { copyState, key, bind } = handleState2(state);
1061
- const value = key ? copyState[key] : copyState;
1062
- value[bindSymbol] = {
1063
- handleStore,
1064
- bind
1065
- };
1066
- return copyState;
1067
- });
1083
+ //#endregion
1084
+ //#region packages/core/src/create.ts
1085
+ const namespaceMap = /* @__PURE__ */ new Map();
1086
+ let hasWarnedAmbiguousFunctionMap = false;
1087
+ const isMainWorkerType = (workerType) => workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal";
1088
+ const isClientWorkerType = (workerType) => workerType === "SharedWorkerClient" || workerType === "WebWorkerClient";
1089
+ const validateCreateModeOptions = (options) => {
1090
+ const storeTransport = options.transport;
1091
+ const clientTransport = options.clientTransport;
1092
+ const worker = options.worker;
1093
+ const explicitWorkerType = options.workerType;
1094
+ if (storeTransport && clientTransport) throw new Error("transport and clientTransport cannot be used together, please use one authority model per store.");
1095
+ if (storeTransport && worker) throw new Error("transport and worker cannot be used together, please use one authority model per store.");
1096
+ if (clientTransport && worker) throw new Error("clientTransport and worker cannot be used together, please use one client transport source.");
1097
+ if (isMainWorkerType(explicitWorkerType) && (clientTransport || worker)) throw new Error("main workerType cannot be combined with client transport settings.");
1098
+ if (isClientWorkerType(explicitWorkerType) && storeTransport) throw new Error("client workerType cannot be combined with transport.");
1099
+ };
1100
+ const warnAmbiguousFunctionMap = () => {
1101
+ if (hasWarnedAmbiguousFunctionMap || process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") return;
1102
+ hasWarnedAmbiguousFunctionMap = true;
1103
+ console.warn([
1104
+ `sliceMode: 'auto' inferred slices from an object of functions.`,
1105
+ `This shape is ambiguous with a single store that only contains methods.`,
1106
+ `Use create({ ping() {} }, { sliceMode: 'single' }) for a plain method store,`,
1107
+ `or create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' }) for slices.`
1108
+ ].join(" "));
1109
+ };
1110
+ /**
1111
+ * Create a local store, the main side of a shared store, or a client mirror of
1112
+ * a shared store.
1113
+ *
1114
+ * @remarks
1115
+ * - Pass a {@link Slice} function for a single store.
1116
+ * - Pass an object of slice factories for a slices store.
1117
+ * - When an object input only contains functions, prefer explicit `sliceMode`
1118
+ * to avoid ambiguous inference.
1119
+ * - When `clientTransport` or `worker` is provided, returned store methods
1120
+ * become promise-returning methods because execution happens on the main
1121
+ * shared store.
1122
+ * - New semantics should prefer explicit helpers or variants over adding more
1123
+ * ambiguous `create()` input forms.
1124
+ */
1125
+ const create = (createState, options = {}) => {
1126
+ const checkEnablePatches = Object.hasOwnProperty.call(options, "enablePatches") && !options.enablePatches;
1127
+ validateCreateModeOptions(options);
1128
+ const workerType = options.workerType ?? WorkerType;
1129
+ const storeTransport = options.transport;
1130
+ const share = workerType === "WebWorkerInternal" || workerType === "SharedWorkerInternal" || storeTransport ? "main" : void 0;
1131
+ const createStore = ({ share }) => {
1132
+ const store = {};
1133
+ const internal = {
1134
+ sequence: 0,
1135
+ isBatching: false,
1136
+ listeners: /* @__PURE__ */ new Set()
1137
+ };
1138
+ internal.notifyStateChange = () => {
1139
+ refreshSignalSlots(internal);
1140
+ internal.listeners.forEach((listener) => listener());
1141
+ };
1142
+ const name = options.name ?? "default";
1143
+ const shouldTrackName = share === "main" && process.env.NODE_ENV !== "test";
1144
+ const releaseStoreName = () => {
1145
+ if (shouldTrackName) namespaceMap.delete(name);
1146
+ };
1147
+ if (shouldTrackName) {
1148
+ if (namespaceMap.get(name)) throw new Error(`Store name '${name}' is not unique.`);
1149
+ namespaceMap.set(name, true);
1150
+ }
1151
+ try {
1152
+ const { setState, getState } = handleState(store, internal, options);
1153
+ const subscribe = (listener) => {
1154
+ internal.listeners.add(listener);
1155
+ return () => internal.listeners.delete(listener);
1156
+ };
1157
+ let isDestroyed = false;
1158
+ const destroy = () => {
1159
+ if (isDestroyed) return;
1160
+ isDestroyed = true;
1161
+ internal.listeners.clear();
1162
+ store.transport?.dispose();
1163
+ releaseStoreName();
1164
+ };
1165
+ const apply = (state = internal.rootState, patches) => {
1166
+ internal.assertMutationAllowed?.("apply");
1167
+ const safePatches = sanitizePatches(patches);
1168
+ const nextState = sanitizeReplacementState(safePatches ? (0, mutative.apply)(state, safePatches) : state);
1169
+ if (store.share === "main") validateSharedStateSerializable(nextState);
1170
+ internal.rootState = nextState;
1171
+ refreshSignalSlots(internal);
1172
+ if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
1173
+ else internal.listeners.forEach((listener) => listener());
1174
+ };
1175
+ const getPureState = () => internal.rootState;
1176
+ const isFunctionMapObject = () => {
1177
+ if (typeof createState === "object" && createState !== null) {
1178
+ const values = getOwnEnumerableKeys(createState).map((key) => createState[key]);
1179
+ return values.length > 0 && values.every((value) => typeof value === "function");
1180
+ }
1181
+ return false;
1182
+ };
1183
+ const getIsSliceStore = () => {
1184
+ const sliceMode = options.sliceMode ?? "auto";
1185
+ if (sliceMode === "single") return false;
1186
+ if (sliceMode === "slices") {
1187
+ if (!isFunctionMapObject()) throw new Error(`sliceMode: 'slices' requires createState to be an object of slice functions.`);
1188
+ return true;
1189
+ }
1190
+ if (isFunctionMapObject()) {
1191
+ warnAmbiguousFunctionMap();
1192
+ return true;
1193
+ }
1194
+ return false;
1195
+ };
1196
+ const isSliceStore = getIsSliceStore();
1197
+ Object.assign(store, {
1198
+ name,
1199
+ share: share ?? false,
1200
+ setState,
1201
+ getState,
1202
+ subscribe,
1203
+ destroy,
1204
+ apply,
1205
+ isSliceStore,
1206
+ getPureState
1207
+ });
1208
+ const middlewareStore = applyMiddlewares(store, options.middlewares ?? []);
1209
+ if (middlewareStore !== store) Object.assign(store, middlewareStore);
1210
+ const initialState = getInitialState(store, createState, internal);
1211
+ if (share) validateSharedActionPaths(initialState);
1212
+ store.getInitialState = () => initialState;
1213
+ internal.rootState = getRawState(store, internal, initialState, options);
1214
+ if (share) validateSharedStateSerializable(internal.rootState);
1215
+ markStoreReady(store);
1216
+ return {
1217
+ store,
1218
+ internal
1219
+ };
1220
+ } catch (error) {
1221
+ releaseStoreName();
1222
+ throw error;
1223
+ }
1224
+ };
1225
+ if (options.clientTransport || options.worker || options.workerType === "WebWorkerClient" || options.workerType === "SharedWorkerClient") {
1226
+ if (checkEnablePatches) throw new Error(`enablePatches: true is required for the async store`);
1227
+ return wrapStore(createAsyncClientStore(createStore, options));
1228
+ }
1229
+ const { store, internal } = createStore({ share });
1230
+ handleMainTransport(store, internal, storeTransport, workerType, checkEnablePatches);
1231
+ return wrapStore(store);
1232
+ };
1233
+ //#endregion
1234
+ //#region packages/core/src/binder.ts
1235
+ const createExternalStoreAdapter = ({ handleState, handleStore }) => ((state) => {
1236
+ const { copyState, key, bind } = handleState(state);
1237
+ const value = typeof key !== "undefined" ? copyState[key] : copyState;
1238
+ Object.defineProperty(value, bindSymbol, {
1239
+ configurable: true,
1240
+ enumerable: typeof key !== "undefined",
1241
+ value: {
1242
+ handleStore,
1243
+ bind
1244
+ }
1245
+ });
1246
+ return copyState;
1247
+ });
1248
+ /**
1249
+ * Build an adapter helper for bridging an external store implementation into
1250
+ * Coaction.
1251
+ *
1252
+ * @remarks
1253
+ * Official bindings use this to integrate stores such as Redux, Jotai, Pinia,
1254
+ * Zustand, MobX, and Valtio. Binder-backed integrations are whole-store
1255
+ * adapters; they are not compatible with Coaction slices mode.
1256
+ */
1257
+ function createBinder({ handleState, handleStore }) {
1258
+ return createExternalStoreAdapter({
1259
+ handleState,
1260
+ handleStore
1261
+ });
1262
+ }
1263
+ /**
1264
+ * Define a whole-store adapter for integrating an external state runtime with
1265
+ * Coaction.
1266
+ *
1267
+ * @remarks
1268
+ * This is the stable 2.x name for adapter authors. `createBinder()` remains as
1269
+ * a compatibility alias for existing official and community integrations.
1270
+ */
1271
+ function defineExternalStoreAdapter(options) {
1272
+ return createExternalStoreAdapter(options);
1068
1273
  }
1069
- // Annotate the CommonJS export names for ESM import in node:
1070
- 0 && (module.exports = {
1071
- create,
1072
- createBinder,
1073
- wrapStore
1274
+ //#endregion
1275
+ //#region packages/core/src/reactiveTracker.ts
1276
+ const ReactiveFlags = alien_signals_system.ReactiveFlags;
1277
+ const unwatch = (node) => {
1278
+ if (!(node.flags & ReactiveFlags.Mutable)) {
1279
+ node.depsTail = void 0;
1280
+ node.flags = 0;
1281
+ purgeDeps(node);
1282
+ const sub = node.subs;
1283
+ if (sub !== void 0) unlink(sub);
1284
+ return;
1285
+ }
1286
+ if (node.depsTail !== void 0) {
1287
+ node.depsTail = void 0;
1288
+ node.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
1289
+ purgeDeps(node);
1290
+ }
1291
+ };
1292
+ const unlink = (link, sub = link.sub) => {
1293
+ const dep = link.dep;
1294
+ const prevDep = link.prevDep;
1295
+ const nextDep = link.nextDep;
1296
+ const nextSub = link.nextSub;
1297
+ const prevSub = link.prevSub;
1298
+ if (nextDep !== void 0) nextDep.prevDep = prevDep;
1299
+ else sub.depsTail = prevDep;
1300
+ if (prevDep !== void 0) prevDep.nextDep = nextDep;
1301
+ else sub.deps = nextDep;
1302
+ if (nextSub !== void 0) nextSub.prevSub = prevSub;
1303
+ else dep.subsTail = prevSub;
1304
+ if (prevSub !== void 0) prevSub.nextSub = nextSub;
1305
+ else if ((dep.subs = nextSub) === void 0) unwatch(dep);
1306
+ return nextDep;
1307
+ };
1308
+ const purgeDeps = (sub) => {
1309
+ const depsTail = sub.depsTail;
1310
+ let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
1311
+ while (dep !== void 0) dep = unlink(dep, sub);
1312
+ };
1313
+ const createReactiveTracker = () => {
1314
+ let version = 0;
1315
+ let disposed = false;
1316
+ const listeners = /* @__PURE__ */ new Set();
1317
+ const node = {
1318
+ deps: void 0,
1319
+ depsTail: void 0,
1320
+ subs: void 0,
1321
+ subsTail: void 0,
1322
+ flags: ReactiveFlags.Watching,
1323
+ fn: () => {
1324
+ if (disposed) return;
1325
+ version += 1;
1326
+ listeners.forEach((listener) => listener());
1327
+ }
1328
+ };
1329
+ const dispose = () => {
1330
+ if (disposed) return;
1331
+ disposed = true;
1332
+ listeners.clear();
1333
+ node.depsTail = void 0;
1334
+ purgeDeps(node);
1335
+ node.flags = 0;
1336
+ };
1337
+ return {
1338
+ getSnapshot: () => version,
1339
+ subscribe(listener) {
1340
+ if (disposed) return () => void 0;
1341
+ listeners.add(listener);
1342
+ return () => {
1343
+ listeners.delete(listener);
1344
+ };
1345
+ },
1346
+ track(fn) {
1347
+ if (disposed) return fn();
1348
+ node.depsTail = void 0;
1349
+ node.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck;
1350
+ const prevSub = (0, alien_signals.setActiveSub)(node);
1351
+ try {
1352
+ return fn();
1353
+ } finally {
1354
+ (0, alien_signals.setActiveSub)(prevSub);
1355
+ node.flags &= ~ReactiveFlags.RecursedCheck;
1356
+ purgeDeps(node);
1357
+ }
1358
+ },
1359
+ dispose
1360
+ };
1361
+ };
1362
+ //#endregion
1363
+ //#region packages/core/src/replaceExternalStoreState.ts
1364
+ const replaceExternalStoreState = (store, internal, source, { syncImmutable = true } = {}) => {
1365
+ const [, patches, inversePatches] = (0, mutative.create)(internal.rootState, (draft) => {
1366
+ replaceOwnEnumerable(draft, source);
1367
+ }, { enablePatches: true });
1368
+ const safePatches = sanitizePatches((store.patch ? store.patch({
1369
+ patches,
1370
+ inversePatches
1371
+ }) : {
1372
+ patches,
1373
+ inversePatches
1374
+ }).patches) ?? [];
1375
+ if (!safePatches.length) return;
1376
+ const updateImmutable = internal.updateImmutable;
1377
+ if (!syncImmutable) internal.updateImmutable = void 0;
1378
+ try {
1379
+ store.apply(internal.rootState, safePatches);
1380
+ } finally {
1381
+ internal.updateImmutable = updateImmutable;
1382
+ }
1383
+ emit(store, internal, safePatches);
1384
+ };
1385
+ //#endregion
1386
+ Object.defineProperty(exports, "computed", {
1387
+ enumerable: true,
1388
+ get: function() {
1389
+ return alien_signals.computed;
1390
+ }
1391
+ });
1392
+ exports.create = create;
1393
+ exports.createBinder = createBinder;
1394
+ exports.createReactiveTracker = createReactiveTracker;
1395
+ exports.defineExternalStoreAdapter = defineExternalStoreAdapter;
1396
+ Object.defineProperty(exports, "effect", {
1397
+ enumerable: true,
1398
+ get: function() {
1399
+ return alien_signals.effect;
1400
+ }
1401
+ });
1402
+ Object.defineProperty(exports, "effectScope", {
1403
+ enumerable: true,
1404
+ get: function() {
1405
+ return alien_signals.effectScope;
1406
+ }
1407
+ });
1408
+ Object.defineProperty(exports, "endBatch", {
1409
+ enumerable: true,
1410
+ get: function() {
1411
+ return alien_signals.endBatch;
1412
+ }
1413
+ });
1414
+ Object.defineProperty(exports, "isComputed", {
1415
+ enumerable: true,
1416
+ get: function() {
1417
+ return alien_signals.isComputed;
1418
+ }
1419
+ });
1420
+ Object.defineProperty(exports, "isEffect", {
1421
+ enumerable: true,
1422
+ get: function() {
1423
+ return alien_signals.isEffect;
1424
+ }
1425
+ });
1426
+ Object.defineProperty(exports, "isEffectScope", {
1427
+ enumerable: true,
1428
+ get: function() {
1429
+ return alien_signals.isEffectScope;
1430
+ }
1431
+ });
1432
+ Object.defineProperty(exports, "isSignal", {
1433
+ enumerable: true,
1434
+ get: function() {
1435
+ return alien_signals.isSignal;
1436
+ }
1437
+ });
1438
+ exports.onStoreReady = onStoreReady;
1439
+ exports.replaceExternalStoreState = replaceExternalStoreState;
1440
+ exports.replaceOwnEnumerable = replaceOwnEnumerable;
1441
+ exports.sanitizeInitialStateValue = sanitizeInitialStateValue;
1442
+ exports.sanitizeReplacementState = sanitizeReplacementState;
1443
+ Object.defineProperty(exports, "signal", {
1444
+ enumerable: true,
1445
+ get: function() {
1446
+ return alien_signals.signal;
1447
+ }
1448
+ });
1449
+ Object.defineProperty(exports, "startBatch", {
1450
+ enumerable: true,
1451
+ get: function() {
1452
+ return alien_signals.startBatch;
1453
+ }
1454
+ });
1455
+ Object.defineProperty(exports, "trigger", {
1456
+ enumerable: true,
1457
+ get: function() {
1458
+ return alien_signals.trigger;
1459
+ }
1074
1460
  });
1461
+ exports.wrapStore = wrapStore;