coaction 2.1.0 → 3.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/local.mjs ADDED
@@ -0,0 +1,1138 @@
1
+ import { apply, create, isDraft } from "mutative";
2
+ import { computed, computed as computed$1, effect, effectScope, endBatch, endBatch as endBatch$1, isComputed, isEffect, isEffectScope, isSignal, signal, signal as signal$1, startBatch, startBatch as startBatch$1, trigger } from "alien-signals";
3
+ //#region packages/core/src/lifecycle.ts
4
+ const readyStores = /* @__PURE__ */ new WeakSet();
5
+ const readyCallbacks = /* @__PURE__ */ new WeakMap();
6
+ const onStoreReady = (store, callback) => {
7
+ if (readyStores.has(store)) {
8
+ callback();
9
+ return () => void 0;
10
+ }
11
+ let callbacks = readyCallbacks.get(store);
12
+ if (!callbacks) {
13
+ callbacks = /* @__PURE__ */ new Set();
14
+ readyCallbacks.set(store, callbacks);
15
+ }
16
+ callbacks.add(callback);
17
+ return () => {
18
+ callbacks?.delete(callback);
19
+ };
20
+ };
21
+ const markStoreReady = (store) => {
22
+ readyStores.add(store);
23
+ const callbacks = readyCallbacks.get(store);
24
+ if (!callbacks) return;
25
+ readyCallbacks.delete(store);
26
+ callbacks.forEach((callback) => callback());
27
+ callbacks.clear();
28
+ };
29
+ //#endregion
30
+ //#region packages/core/src/applyMiddlewares.ts
31
+ const isStoreLike = (value) => {
32
+ if (!value || typeof value !== "object") return false;
33
+ const candidate = value;
34
+ 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";
35
+ };
36
+ const applyMiddlewares = (store, middlewares) => {
37
+ return middlewares.reduce((store, middleware, index) => {
38
+ if (process.env.NODE_ENV === "development") {
39
+ if (typeof middleware !== "function") throw new Error(`middlewares[${index}] should be a function`);
40
+ }
41
+ const nextStore = middleware(store);
42
+ if (process.env.NODE_ENV === "development") {
43
+ if (!isStoreLike(nextStore)) throw new Error(`middlewares[${index}] should return a store-like object`);
44
+ }
45
+ return nextStore;
46
+ }, store);
47
+ };
48
+ //#endregion
49
+ //#region packages/core/src/utils.ts
50
+ const isEqual = (x, y) => {
51
+ if (x === y) return x !== 0 || y !== 0 || 1 / x === 1 / y;
52
+ return x !== x && y !== y;
53
+ };
54
+ const isUnsafeKey = (key) => key === "__proto__" || key === "prototype" || key === "constructor";
55
+ const isUnsafePathSegment = (segment) => typeof segment === "string" && isUnsafeKey(segment);
56
+ var UnsafePatchPathError = class extends Error {
57
+ name = "UnsafePatchPathError";
58
+ };
59
+ var StateSchemaError = class extends Error {
60
+ name = "StateSchemaError";
61
+ };
62
+ const hasUnsafePatchPath = (path) => {
63
+ return (Array.isArray(path) ? path : typeof path === "string" ? path.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~")) : []).some(isUnsafePathSegment);
64
+ };
65
+ const formatPatchPath = (path) => Array.isArray(path) ? path.map((segment) => String(segment)).join(".") : String(path);
66
+ const getUnsafePatchPaths = (patches) => patches?.filter((patch) => hasUnsafePatchPath(patch.path)) ?? [];
67
+ const assertSafePatches = (patches, source = "patches") => {
68
+ const unsafePatches = getUnsafePatchPaths(patches);
69
+ if (!unsafePatches.length) return;
70
+ const paths = unsafePatches.map((patch) => `'${formatPatchPath(patch.path)}'`).join(", ");
71
+ throw new UnsafePatchPathError(`Unsafe patch path${unsafePatches.length > 1 ? "s" : ""} ${paths} cannot be applied from ${source}.`);
72
+ };
73
+ const warnDroppedUnsafePatches = (unsafePatches, source) => {
74
+ if (process.env.NODE_ENV !== "development" || !unsafePatches.length) return;
75
+ const paths = unsafePatches.map((patch) => `'${formatPatchPath(patch.path)}'`).join(", ");
76
+ console.warn(`Coaction dropped unsafe patch path${unsafePatches.length > 1 ? "s" : ""} ${paths} from ${source}.`);
77
+ };
78
+ const sanitizePatches = (patches, options = {}) => {
79
+ if (options.warnOnDropped) warnDroppedUnsafePatches(getUnsafePatchPaths(patches), options.source ?? "patches");
80
+ return patches?.filter((patch) => !hasUnsafePatchPath(patch.path)).map((patch) => Object.prototype.hasOwnProperty.call(patch, "value") ? {
81
+ ...patch,
82
+ value: sanitizeReplacementState(patch.value)
83
+ } : patch);
84
+ };
85
+ const sanitizeCheckedPatches = (patches, source) => {
86
+ assertSafePatches(patches, source);
87
+ return sanitizePatches(patches) ?? [];
88
+ };
89
+ const setOwnEnumerable = (target, key, value) => {
90
+ if (typeof key === "string" && isUnsafeKey(key)) return;
91
+ target[key] = value;
92
+ };
93
+ const getOwnEnumerableKeys = (source) => {
94
+ if (typeof source !== "object" || source === null) return [];
95
+ return Reflect.ownKeys(source).filter((key) => Object.prototype.propertyIsEnumerable.call(source, key));
96
+ };
97
+ const getOwnSchemaKeys = (source) => {
98
+ if (typeof source !== "object" || source === null) return [];
99
+ return Reflect.ownKeys(source).filter((key) => !(typeof key === "string" && isUnsafeKey(key)));
100
+ };
101
+ const formatSchemaPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
102
+ const assertKnownSchemaKey = (knownKeys, key, path) => {
103
+ if (typeof key === "string" && isUnsafeKey(key)) return;
104
+ if (knownKeys.has(key)) return;
105
+ throw new StateSchemaError(`Unknown state key '${formatSchemaPath([...path, key])}' cannot be added after store initialization. Coaction state schema is fixed.`);
106
+ };
107
+ const assertKnownSliceObject = (key, value) => {
108
+ if (typeof value === "object" && value !== null) return;
109
+ throw new StateSchemaError(`State slice '${String(key)}' must remain an object after store initialization. Coaction slice schema is fixed.`);
110
+ };
111
+ const assertKnownSlicePresent = (source, key) => {
112
+ if (Object.prototype.hasOwnProperty.call(source, key)) return;
113
+ throw new StateSchemaError(`State slice '${String(key)}' cannot be removed after store initialization. Coaction slice schema is fixed.`);
114
+ };
115
+ const createStateSchema = (rootState, isSliceStore) => {
116
+ const rootKeys = new Set(getOwnSchemaKeys(rootState));
117
+ if (!isSliceStore) return { rootKeys };
118
+ const sliceKeys = /* @__PURE__ */ new Map();
119
+ if (typeof rootState === "object" && rootState !== null) {
120
+ const rootRecord = rootState;
121
+ rootKeys.forEach((key) => {
122
+ const slice = rootRecord[key];
123
+ if (typeof slice === "object" && slice !== null) sliceKeys.set(key, new Set(getOwnSchemaKeys(slice)));
124
+ });
125
+ }
126
+ return {
127
+ rootKeys,
128
+ sliceKeys
129
+ };
130
+ };
131
+ const assertKnownStateShape = (source, rootState, schema, isSliceStore, options = {}) => {
132
+ if (typeof source !== "object" || source === null) return;
133
+ const rootKeys = schema?.rootKeys ?? new Set(getOwnSchemaKeys(rootState));
134
+ const sourceRecord = source;
135
+ const knownSliceEntries = schema?.sliceKeys;
136
+ if (isSliceStore && options.requireSliceRoots && knownSliceEntries) knownSliceEntries.forEach((_, key) => {
137
+ assertKnownSlicePresent(sourceRecord, key);
138
+ });
139
+ for (const key of getOwnEnumerableKeys(source)) {
140
+ assertKnownSchemaKey(rootKeys, key, []);
141
+ if (!isSliceStore) continue;
142
+ const slice = sourceRecord[key];
143
+ const knownSliceKeys = schema?.sliceKeys?.get(key) ?? (typeof rootState === "object" && rootState !== null && typeof rootState[key] === "object" && rootState[key] !== null ? new Set(getOwnSchemaKeys(rootState[key])) : void 0);
144
+ if (!knownSliceKeys) continue;
145
+ assertKnownSliceObject(key, slice);
146
+ for (const sliceKey of getOwnEnumerableKeys(slice)) assertKnownSchemaKey(knownSliceKeys, sliceKey, [key]);
147
+ }
148
+ };
149
+ const isArrayIndexKey = (key) => {
150
+ if (typeof key !== "string") return false;
151
+ const index = Number(key);
152
+ return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
153
+ };
154
+ const assignOwnEnumerable = (target, source, seen = /* @__PURE__ */ new WeakMap()) => {
155
+ if (!seen.has(source)) seen.set(source, target);
156
+ for (const key of getOwnEnumerableKeys(source)) setOwnEnumerable(target, key, sanitizeReplacementState(source[key], seen));
157
+ };
158
+ const cloneOwnEnumerable = (source) => {
159
+ const target = {};
160
+ assignOwnEnumerable(target, source);
161
+ return target;
162
+ };
163
+ const sanitizeReplacementState = (source, seen = /* @__PURE__ */ new WeakMap()) => {
164
+ if (typeof source !== "object" || source === null) return source;
165
+ const cached = seen.get(source);
166
+ if (cached) return cached;
167
+ if (Array.isArray(source)) {
168
+ const target = [];
169
+ target.length = source.length;
170
+ seen.set(source, target);
171
+ for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeReplacementState(source[index], seen);
172
+ for (const key of getOwnEnumerableKeys(source)) {
173
+ if (isArrayIndexKey(key) || typeof key === "string" && isUnsafeKey(key)) continue;
174
+ const value = source[key];
175
+ if (typeof value === "function") continue;
176
+ setOwnEnumerable(target, key, sanitizeReplacementState(value, seen));
177
+ }
178
+ return target;
179
+ }
180
+ const prototype = Object.getPrototypeOf(source);
181
+ if (prototype !== Object.prototype && prototype !== null) return source;
182
+ const target = Object.create(prototype);
183
+ seen.set(source, target);
184
+ for (const key of getOwnEnumerableKeys(source)) {
185
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
186
+ const value = source[key];
187
+ if (typeof value === "function") continue;
188
+ setOwnEnumerable(target, key, sanitizeReplacementState(value, seen));
189
+ }
190
+ return target;
191
+ };
192
+ const sanitizeInitialStateValue = (source, seen = /* @__PURE__ */ new WeakMap()) => {
193
+ if (typeof source !== "object" || source === null) return source;
194
+ const cached = seen.get(source);
195
+ if (cached) return cached;
196
+ if (Array.isArray(source)) {
197
+ const target = [];
198
+ target.length = source.length;
199
+ seen.set(source, target);
200
+ for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeInitialStateValue(source[index], seen);
201
+ for (const key of getOwnEnumerableKeys(source)) {
202
+ if (isArrayIndexKey(key) || typeof key === "string" && isUnsafeKey(key)) continue;
203
+ setOwnEnumerable(target, key, sanitizeInitialStateValue(source[key], seen));
204
+ }
205
+ return target;
206
+ }
207
+ const prototype = Object.getPrototypeOf(source);
208
+ if (prototype !== Object.prototype && prototype !== null) return source;
209
+ const target = Object.create(prototype);
210
+ seen.set(source, target);
211
+ for (const key of getOwnEnumerableKeys(source)) {
212
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
213
+ setOwnEnumerable(target, key, sanitizeInitialStateValue(source[key], seen));
214
+ }
215
+ return target;
216
+ };
217
+ const areShallowEqualWithArray = (prev, next) => {
218
+ if (prev === null || next === null || prev.length !== next.length) return false;
219
+ const { length } = prev;
220
+ for (let i = 0; i < length; i += 1) {
221
+ if (Object.prototype.hasOwnProperty.call(prev, i) !== Object.prototype.hasOwnProperty.call(next, i)) return false;
222
+ if (!isEqual(prev[i], next[i])) return false;
223
+ }
224
+ return true;
225
+ };
226
+ const mergeObject = (target, source, isSlice) => {
227
+ if (isSlice) {
228
+ if (typeof source === "object" && source !== null) for (const key of getOwnEnumerableKeys(source)) {
229
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
230
+ if (!Object.prototype.hasOwnProperty.call(target, key)) continue;
231
+ const sourceValue = source[key];
232
+ if (typeof sourceValue !== "object" || sourceValue === null) continue;
233
+ const targetValue = target[key];
234
+ if (typeof targetValue === "object" && targetValue !== null) assignOwnEnumerable(targetValue, sourceValue);
235
+ }
236
+ } else if (typeof source === "object" && source !== null) assignOwnEnumerable(target, source);
237
+ };
238
+ const uuid = () => {
239
+ let timestamp = (/* @__PURE__ */ new Date()).getTime();
240
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
241
+ const randomNum = (timestamp + Math.random() * 16) % 16 | 0;
242
+ timestamp = Math.floor(timestamp / 16);
243
+ return (char === "x" ? randomNum : randomNum & 3 | 8).toString(16);
244
+ });
245
+ };
246
+ //#endregion
247
+ //#region packages/core/src/computed.ts
248
+ const isObjectLike = (value) => typeof value === "object" && value !== null;
249
+ const runComputedRead = (internal, read) => {
250
+ internal.computedReadDepth = (internal.computedReadDepth ?? 0) + 1;
251
+ try {
252
+ return read();
253
+ } finally {
254
+ internal.computedReadDepth -= 1;
255
+ }
256
+ };
257
+ var Computed = class {
258
+ deps;
259
+ fn;
260
+ constructor(deps, fn) {
261
+ this.deps = deps;
262
+ this.fn = fn;
263
+ }
264
+ createGetter({ internal }) {
265
+ const memoByReceiver = /* @__PURE__ */ new WeakMap();
266
+ const lastArgs = /* @__PURE__ */ new WeakMap();
267
+ const lastResult = /* @__PURE__ */ new WeakMap();
268
+ const fallbackReceiver = {};
269
+ const evaluate = (receiver) => {
270
+ const args = this.deps(internal.module);
271
+ if (!lastArgs.has(receiver) || !areShallowEqualWithArray(lastArgs.get(receiver), args)) lastResult.set(receiver, this.fn.apply(receiver, args));
272
+ lastArgs.set(receiver, args);
273
+ return lastResult.get(receiver);
274
+ };
275
+ return function() {
276
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
277
+ if (internal.isBatching) return evaluate(receiver);
278
+ let accessor = memoByReceiver.get(receiver);
279
+ if (!accessor) {
280
+ accessor = computed$1(() => runComputedRead(internal, () => evaluate(receiver)));
281
+ memoByReceiver.set(receiver, accessor);
282
+ }
283
+ return accessor();
284
+ };
285
+ }
286
+ };
287
+ const createCachedGetter = (internal, getter) => {
288
+ const accessors = /* @__PURE__ */ new WeakMap();
289
+ const fallbackReceiver = {};
290
+ return function() {
291
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
292
+ if (internal.isBatching) return getter.call(receiver);
293
+ let accessor = accessors.get(receiver);
294
+ if (!accessor) {
295
+ accessor = computed$1(() => runComputedRead(internal, () => getter.call(receiver)));
296
+ accessors.set(receiver, accessor);
297
+ }
298
+ return accessor();
299
+ };
300
+ };
301
+ const createTrackedStateReader = (internal, read, initialValue) => {
302
+ const slotSignal = signal$1(initialValue);
303
+ const slotVersionSignal = signal$1(0);
304
+ let slotVersion = 0;
305
+ (internal.signalSlots ??= /* @__PURE__ */ new Set()).add({ refresh: () => {
306
+ const nextValue = read();
307
+ slotSignal(nextValue);
308
+ if (internal.mutableInstance && isObjectLike(nextValue)) {
309
+ slotVersion += 1;
310
+ slotVersionSignal(slotVersion);
311
+ }
312
+ } });
313
+ return () => {
314
+ const currentValue = slotSignal();
315
+ if (internal.mutableInstance && isObjectLike(currentValue)) slotVersionSignal();
316
+ return read();
317
+ };
318
+ };
319
+ const refreshSignalSlots = (internal) => {
320
+ if (!internal.signalSlots?.size) return;
321
+ startBatch$1();
322
+ try {
323
+ internal.signalSlots.forEach((slot) => slot.refresh());
324
+ } finally {
325
+ endBatch$1();
326
+ }
327
+ };
328
+ //#endregion
329
+ //#region packages/core/src/global.ts
330
+ const getGlobal = () => {
331
+ let _global;
332
+ if (typeof window !== "undefined") _global = window;
333
+ else if (typeof global !== "undefined") _global = global;
334
+ else if (typeof self !== "undefined") _global = self;
335
+ else _global = {};
336
+ return _global;
337
+ };
338
+ getGlobal().SharedWorkerGlobalScope || globalThis.WorkerGlobalScope;
339
+ const bindSymbol = Symbol("bind");
340
+ //#endregion
341
+ //#region packages/core/src/getInitialState.ts
342
+ const isObject = (value) => typeof value === "object" && value !== null;
343
+ const isStateFactory = (value) => typeof value === "function";
344
+ const hasGetState = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.getState === "function";
345
+ const hasBindState = (value) => isObject(value) && !!value[bindSymbol];
346
+ const formatInvalidStateMessage = (type, stateOrFn, key) => `Invalid state ${type} encountered in makeState: ${typeof key !== "undefined" ? `for key ${String(key)}, ` : ""}${typeof stateOrFn}`;
347
+ const getInitialState = (store, createState, internal) => {
348
+ const makeState = (stateOrFn, key) => {
349
+ let state;
350
+ if (isStateFactory(stateOrFn)) state = stateOrFn(store.setState, store.getState, store);
351
+ else if (isObject(stateOrFn)) state = stateOrFn;
352
+ else {
353
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("value", stateOrFn, key));
354
+ return {};
355
+ }
356
+ if (hasGetState(state)) state = state.getState();
357
+ else if (typeof state === "function") state = state();
358
+ if (hasBindState(state)) {
359
+ if (store.isSliceStore) throw new Error("Third-party state binding does not support Slices mode. Please inject a whole store instead.");
360
+ const binder = state[bindSymbol];
361
+ const rawState = binder.bind(state);
362
+ binder.handleStore(store, rawState, state, internal, key);
363
+ delete state[bindSymbol];
364
+ return rawState;
365
+ }
366
+ if (!isObject(state)) {
367
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("result", state, key));
368
+ return {};
369
+ }
370
+ return state;
371
+ };
372
+ if (!store.isSliceStore) return makeState(createState);
373
+ return getOwnEnumerableKeys(createState).reduce((stateTree, key) => {
374
+ if (typeof key === "string" && isUnsafeKey(key)) return stateTree;
375
+ setOwnEnumerable(stateTree, key, makeState(createState[key], key));
376
+ return stateTree;
377
+ }, {});
378
+ };
379
+ //#endregion
380
+ //#region packages/core/src/handleDraft.ts
381
+ const handleDraft = (store, internal) => {
382
+ internal.rootState = internal.backupState;
383
+ const [, patches, inversePatches] = internal.finalizeDraft();
384
+ const safePatches = sanitizeCheckedPatches((store.patch ? store.patch({
385
+ patches,
386
+ inversePatches
387
+ }) : {
388
+ patches,
389
+ inversePatches
390
+ }).patches, "store.patch()");
391
+ if (safePatches.length) {
392
+ store.apply(internal.rootState, safePatches);
393
+ internal.emitPatches?.(safePatches);
394
+ }
395
+ };
396
+ //#endregion
397
+ //#region packages/core/src/getRawStateLocalAction.ts
398
+ const getActionTarget = (store, sliceKey) => {
399
+ return typeof sliceKey !== "undefined" ? store.getState()[sliceKey] : store.getState();
400
+ };
401
+ const createLocalAction = ({ fn, internal, key, options, store, sliceKey }) => {
402
+ return (...args) => {
403
+ internal.assertAlive?.(`action ${String(key)}`);
404
+ let actionId;
405
+ let done;
406
+ if (store.trace) {
407
+ actionId = uuid();
408
+ store.trace({
409
+ method: String(key),
410
+ parameters: args,
411
+ id: actionId,
412
+ sliceKey
413
+ });
414
+ done = (result) => {
415
+ store.trace({
416
+ method: String(key),
417
+ id: actionId,
418
+ result,
419
+ sliceKey
420
+ });
421
+ };
422
+ }
423
+ const traceAction = (run) => {
424
+ try {
425
+ const result = run();
426
+ if (result instanceof Promise) return result.then((value) => {
427
+ done?.(value);
428
+ return value;
429
+ }, (error) => {
430
+ done?.(error);
431
+ throw error;
432
+ });
433
+ done?.(result);
434
+ return result;
435
+ } catch (error) {
436
+ done?.(error);
437
+ throw error;
438
+ }
439
+ };
440
+ const enablePatches = store.transport ?? options.enablePatches;
441
+ return traceAction(() => {
442
+ if (internal.mutableInstance && !internal.isBatching && enablePatches) {
443
+ let result;
444
+ const handleResult = (isDrafted) => {
445
+ handleDraft(store, internal);
446
+ if (isDrafted) {
447
+ internal.backupState = internal.rootState;
448
+ const [draft, finalize] = create(internal.rootState, { enablePatches: true });
449
+ internal.finalizeDraft = finalize;
450
+ internal.rootState = draft;
451
+ }
452
+ };
453
+ const isDrafted = isDraft(internal.rootState);
454
+ if (isDrafted) handleResult();
455
+ internal.backupState = internal.rootState;
456
+ const [draft, finalize] = create(internal.rootState, { enablePatches: true });
457
+ internal.finalizeDraft = finalize;
458
+ internal.rootState = draft;
459
+ let asyncResult;
460
+ try {
461
+ result = fn.apply(getActionTarget(store, sliceKey), args);
462
+ if (result instanceof Promise) asyncResult = result;
463
+ } finally {
464
+ if (!asyncResult) handleResult(isDrafted);
465
+ }
466
+ if (asyncResult) return asyncResult.then((value) => {
467
+ handleResult(isDrafted);
468
+ return value;
469
+ }, (error) => {
470
+ handleResult(isDrafted);
471
+ throw error;
472
+ });
473
+ return result;
474
+ }
475
+ if (internal.mutableInstance && internal.actMutable) return internal.actMutable(() => {
476
+ return fn.apply(getActionTarget(store, sliceKey), args);
477
+ });
478
+ return fn.apply(getActionTarget(store, sliceKey), args);
479
+ });
480
+ };
481
+ };
482
+ //#endregion
483
+ //#region packages/core/src/immutableState.ts
484
+ const isImmutableStateObject = (value) => {
485
+ if (typeof value !== "object" || value === null) return false;
486
+ if (Array.isArray(value)) return true;
487
+ const prototype = Object.getPrototypeOf(value);
488
+ return prototype === Object.prototype || prototype === null;
489
+ };
490
+ const getImmutableStateSnapshot = (value, cache) => {
491
+ if (!isImmutableStateObject(value)) return value;
492
+ const cached = cache.get(value);
493
+ if (cached) return cached;
494
+ const isArray = Array.isArray(value);
495
+ const snapshot = isArray ? new Array(value.length) : Object.create(Object.getPrototypeOf(value));
496
+ cache.set(value, snapshot);
497
+ for (const key of Reflect.ownKeys(value)) {
498
+ if (isArray && key === "length") continue;
499
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
500
+ if (Object.prototype.hasOwnProperty.call(descriptor, "value")) descriptor.value = getImmutableStateSnapshot(descriptor.value, cache);
501
+ Object.defineProperty(snapshot, key, descriptor);
502
+ }
503
+ return Object.freeze(snapshot);
504
+ };
505
+ const createImmutableSnapshotPatches = (patches, cache) => patches.map((patch) => Object.prototype.hasOwnProperty.call(patch, "value") ? {
506
+ ...patch,
507
+ value: getImmutableStateSnapshot(patch.value, cache)
508
+ } : patch);
509
+ const finalizeImmutableStateSnapshot = (state, snapshot, patches, cache, sources) => {
510
+ const mapPair = (value, snapshotValue) => {
511
+ if (isImmutableStateObject(value) && isImmutableStateObject(snapshotValue)) {
512
+ cache.set(value, snapshotValue);
513
+ sources?.set(snapshotValue, value);
514
+ }
515
+ };
516
+ mapPair(state, snapshot);
517
+ for (const patch of patches) {
518
+ let value = state;
519
+ let snapshotValue = snapshot;
520
+ const ancestors = [];
521
+ if (isImmutableStateObject(snapshotValue)) ancestors.push(snapshotValue);
522
+ for (const key of patch.path) {
523
+ if (!isImmutableStateObject(value) || !isImmutableStateObject(snapshotValue)) break;
524
+ value = value[key];
525
+ snapshotValue = snapshotValue[key];
526
+ mapPair(value, snapshotValue);
527
+ if (isImmutableStateObject(snapshotValue)) ancestors.push(snapshotValue);
528
+ }
529
+ for (let index = ancestors.length - 1; index >= 0; index -= 1) if (!Object.isFrozen(ancestors[index])) Object.freeze(ancestors[index]);
530
+ }
531
+ };
532
+ const indexImmutableStateSnapshot = (state, snapshot, sources, seen = /* @__PURE__ */ new WeakSet()) => {
533
+ if (!isImmutableStateObject(state) || !isImmutableStateObject(snapshot) || seen.has(snapshot)) return;
534
+ seen.add(snapshot);
535
+ sources.set(snapshot, state);
536
+ for (const key of Reflect.ownKeys(state)) {
537
+ const stateDescriptor = Object.getOwnPropertyDescriptor(state, key);
538
+ const snapshotDescriptor = Object.getOwnPropertyDescriptor(snapshot, key);
539
+ if (stateDescriptor && snapshotDescriptor && Object.prototype.hasOwnProperty.call(stateDescriptor, "value") && Object.prototype.hasOwnProperty.call(snapshotDescriptor, "value")) indexImmutableStateSnapshot(stateDescriptor.value, snapshotDescriptor.value, sources, seen);
540
+ }
541
+ };
542
+ //#endregion
543
+ //#region packages/core/src/getRawStateStateProperty.ts
544
+ const assertImmutableStateMutationAllowed = (internal) => {
545
+ if (internal.mutableInstance || internal.isBatching) return;
546
+ throw new Error("Direct state mutation is not allowed in immutable Coaction stores. Wrap mutations in set(() => { ... }).");
547
+ };
548
+ const readonlyProxyCache = /* @__PURE__ */ new WeakMap();
549
+ const getReadonlyProxyCache = (internal) => {
550
+ let cache = readonlyProxyCache.get(internal);
551
+ if (!cache) {
552
+ cache = /* @__PURE__ */ new WeakMap();
553
+ readonlyProxyCache.set(internal, cache);
554
+ }
555
+ return cache;
556
+ };
557
+ const getPublicStateObject = (internal, value, sliceKey) => {
558
+ if (value === internal.rootState) return internal.module;
559
+ if (typeof sliceKey === "undefined" || typeof internal.rootState !== "object" || internal.rootState === null || typeof internal.module !== "object" || internal.module === null) return;
560
+ const rootState = internal.rootState;
561
+ const module = internal.module;
562
+ if (rootState[sliceKey] === value) return module[sliceKey];
563
+ };
564
+ const toReadonlyStateValue = (internal, value, sliceKey) => {
565
+ if (internal.mutableInstance || internal.isBatching || !isImmutableStateObject(value)) return value;
566
+ if (internal.computedReadDepth) {
567
+ const cache = internal.computedSnapshotCache ??= /* @__PURE__ */ new WeakMap();
568
+ if (isImmutableStateObject(internal.rootState) && !cache.has(internal.rootState)) getImmutableStateSnapshot(internal.rootState, cache);
569
+ return getImmutableStateSnapshot(value, cache);
570
+ }
571
+ const publicValue = getPublicStateObject(internal, value, sliceKey);
572
+ if (publicValue) return publicValue;
573
+ const cache = getReadonlyProxyCache(internal);
574
+ const cached = cache.get(value);
575
+ if (cached) return cached;
576
+ const proxy = new Proxy(value, {
577
+ get(target, key, receiver) {
578
+ return toReadonlyStateValue(internal, Reflect.get(target, key, receiver), sliceKey);
579
+ },
580
+ set() {
581
+ assertImmutableStateMutationAllowed(internal);
582
+ return false;
583
+ },
584
+ deleteProperty() {
585
+ assertImmutableStateMutationAllowed(internal);
586
+ return false;
587
+ },
588
+ defineProperty() {
589
+ assertImmutableStateMutationAllowed(internal);
590
+ return false;
591
+ },
592
+ setPrototypeOf() {
593
+ assertImmutableStateMutationAllowed(internal);
594
+ return false;
595
+ }
596
+ });
597
+ cache.set(value, proxy);
598
+ return proxy;
599
+ };
600
+ const toPublicComputedValue = (internal, value, sliceKey) => {
601
+ if (!isImmutableStateObject(value)) return value;
602
+ const rootSnapshot = internal.computedSnapshotCache?.get(internal.rootState);
603
+ const sources = internal.computedSnapshotSources ??= /* @__PURE__ */ new WeakMap();
604
+ let source = sources.get(value);
605
+ if (!source && Object.isFrozen(value) && rootSnapshot) {
606
+ indexImmutableStateSnapshot(internal.rootState, rootSnapshot, sources);
607
+ source = sources.get(value);
608
+ }
609
+ if (source) internal.computedIdentityRequired = true;
610
+ return source ? toReadonlyStateValue(internal, source, sliceKey) : value;
611
+ };
612
+ const prepareStateDescriptor = ({ descriptor, initialStateSeen, internal, key, rawState, sliceKey }) => {
613
+ const isComputed = descriptor.value instanceof Computed;
614
+ const readStateValue = () => typeof sliceKey !== "undefined" ? internal.rootState[sliceKey][key] : internal.rootState[key];
615
+ const initialValue = isComputed ? descriptor.value : sanitizeInitialStateValue(descriptor.value, initialStateSeen);
616
+ if (internal.mutableInstance) Object.defineProperty(rawState, key, {
617
+ get: () => internal.mutableInstance[key],
618
+ set: (value) => {
619
+ internal.mutableInstance[key] = value;
620
+ },
621
+ configurable: true,
622
+ enumerable: descriptor.enumerable
623
+ });
624
+ else if (!isComputed) Object.defineProperty(rawState, key, {
625
+ value: initialValue,
626
+ configurable: true,
627
+ enumerable: descriptor.enumerable,
628
+ writable: true
629
+ });
630
+ if (isComputed) {
631
+ if (internal.mutableInstance) throw new Error("Computed is not supported with mutable instance");
632
+ const getComputed = descriptor.value.createGetter({ internal });
633
+ descriptor.get = function() {
634
+ return toPublicComputedValue(internal, getComputed.call(this), sliceKey);
635
+ };
636
+ } else if (typeof sliceKey !== "undefined") {
637
+ const read = createTrackedStateReader(internal, readStateValue, initialValue);
638
+ descriptor.get = () => toReadonlyStateValue(internal, read(), sliceKey);
639
+ descriptor.set = (value) => {
640
+ assertImmutableStateMutationAllowed(internal);
641
+ internal.rootState[sliceKey][key] = value;
642
+ };
643
+ } else {
644
+ const read = createTrackedStateReader(internal, readStateValue, initialValue);
645
+ descriptor.get = () => toReadonlyStateValue(internal, read());
646
+ descriptor.set = (value) => {
647
+ assertImmutableStateMutationAllowed(internal);
648
+ internal.rootState[key] = value;
649
+ };
650
+ }
651
+ delete descriptor.value;
652
+ delete descriptor.writable;
653
+ };
654
+ const prepareAccessorDescriptor = ({ descriptor, internal, sliceKey }) => {
655
+ if (internal.mutableInstance || typeof descriptor.get !== "function") return;
656
+ const getComputed = createCachedGetter(internal, descriptor.get);
657
+ descriptor.get = function() {
658
+ return toPublicComputedValue(internal, getComputed.call(this), sliceKey);
659
+ };
660
+ };
661
+ //#endregion
662
+ //#region packages/core/src/getRawState.ts
663
+ const defaultClientExecuteSyncTimeoutMs = 1500;
664
+ const lockPublicStateObject = (state) => {
665
+ Object.freeze(state);
666
+ return state;
667
+ };
668
+ const getClientExecuteSyncTimeoutMs = (options) => {
669
+ const timeout = options.executeSyncTimeoutMs;
670
+ if (typeof timeout === "undefined") return defaultClientExecuteSyncTimeoutMs;
671
+ if (!Number.isFinite(timeout) || timeout < 0) throw new Error("executeSyncTimeoutMs must be a finite number greater than or equal to 0");
672
+ return timeout;
673
+ };
674
+ const getRawState = (store, internal, initialState, options, createClientAction) => {
675
+ const clientExecuteSyncTimeoutMs = getClientExecuteSyncTimeoutMs(options);
676
+ const rawState = {};
677
+ const handle = (_rawState, _initialState, sliceKey) => {
678
+ internal.mutableInstance = internal.toMutableRaw?.(_initialState);
679
+ const initialStateSeen = /* @__PURE__ */ new WeakMap();
680
+ initialStateSeen.set(_initialState, _rawState);
681
+ const safeDescriptors = {};
682
+ const descriptors = Object.getOwnPropertyDescriptors(_initialState);
683
+ Reflect.ownKeys(descriptors).forEach((key) => {
684
+ if (typeof key === "string" && isUnsafeKey(key)) return;
685
+ safeDescriptors[key] = Reflect.get(descriptors, key);
686
+ });
687
+ Reflect.ownKeys(safeDescriptors).forEach((key) => {
688
+ const descriptor = safeDescriptors[key];
689
+ if (typeof descriptor === "undefined") return;
690
+ if (!Object.prototype.hasOwnProperty.call(descriptor, "value")) {
691
+ prepareAccessorDescriptor({
692
+ descriptor,
693
+ internal,
694
+ sliceKey
695
+ });
696
+ return;
697
+ }
698
+ if (Object.prototype.hasOwnProperty.call(descriptor, "value")) {
699
+ if (typeof descriptor.value !== "function") {
700
+ prepareStateDescriptor({
701
+ descriptor,
702
+ initialStateSeen,
703
+ internal,
704
+ key,
705
+ rawState: _rawState,
706
+ sliceKey
707
+ });
708
+ return;
709
+ }
710
+ if (store.share === "client") {
711
+ if (typeof key !== "string") return;
712
+ if (!createClientAction) throw new Error("Client action runtime is not configured");
713
+ descriptor.value = createClientAction({
714
+ clientExecuteSyncTimeoutMs,
715
+ internal,
716
+ key,
717
+ store,
718
+ sliceKey
719
+ });
720
+ } else descriptor.value = createLocalAction({
721
+ fn: descriptor.value,
722
+ internal,
723
+ key,
724
+ options,
725
+ store,
726
+ sliceKey
727
+ });
728
+ }
729
+ });
730
+ return lockPublicStateObject(Object.defineProperties({}, safeDescriptors));
731
+ };
732
+ if (store.isSliceStore) {
733
+ internal.module = {};
734
+ getOwnEnumerableKeys(initialState).forEach((key) => {
735
+ if (typeof key === "string" && isUnsafeKey(key)) return;
736
+ const sliceRawState = {};
737
+ setOwnEnumerable(rawState, key, sliceRawState);
738
+ setOwnEnumerable(internal.module, key, handle(sliceRawState, initialState[key], key));
739
+ });
740
+ lockPublicStateObject(internal.module);
741
+ } else internal.module = handle(rawState, initialState);
742
+ return rawState;
743
+ };
744
+ //#endregion
745
+ //#region packages/core/src/handleState.ts
746
+ const handleState = (store, internal, options) => {
747
+ let defaultResultValidated = false;
748
+ const defaultUpdater = (next) => {
749
+ defaultResultValidated = false;
750
+ const merge = (_next = next) => {
751
+ if (_next !== next) internal.validateState?.(_next);
752
+ assertKnownStateShape(_next, internal.rootState, internal.stateSchema, store.isSliceStore);
753
+ mergeObject(internal.rootState, _next, store.isSliceStore);
754
+ };
755
+ const fn = typeof next === "function" ? () => {
756
+ const returnValue = next(internal.module);
757
+ if (returnValue instanceof Promise) {
758
+ returnValue.catch(() => void 0);
759
+ throw new Error("setState with async function is not supported");
760
+ }
761
+ if (typeof returnValue === "object" && returnValue !== null) merge(returnValue);
762
+ } : merge;
763
+ if (!(store.transport ?? options.enablePatches) && internal.mutableInstance) {
764
+ if (internal.actMutable) {
765
+ internal.actMutable(() => {
766
+ fn.apply(null);
767
+ });
768
+ defaultResultValidated = true;
769
+ return [];
770
+ }
771
+ fn.apply(null);
772
+ defaultResultValidated = true;
773
+ return [];
774
+ }
775
+ internal.backupState = internal.rootState;
776
+ let patches;
777
+ let inversePatches;
778
+ try {
779
+ const result = create(internal.rootState, (draft) => {
780
+ internal.rootState = draft;
781
+ return fn.apply(null);
782
+ }, { enablePatches: true });
783
+ assertKnownStateShape(result[0], internal.backupState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
784
+ internal.validateState?.(internal.getTransportState?.() ?? result[0]);
785
+ patches = result[1];
786
+ inversePatches = result[2];
787
+ } finally {
788
+ internal.rootState = internal.backupState;
789
+ }
790
+ const patch = store.patch;
791
+ const finalPatches = patch ? patch({
792
+ patches,
793
+ inversePatches
794
+ }) : {
795
+ patches,
796
+ inversePatches
797
+ };
798
+ if (!patch) internal.validatePatches?.(finalPatches.patches);
799
+ const safePatches = sanitizeCheckedPatches(finalPatches.patches, "store.patch()");
800
+ const safeInversePatches = sanitizeCheckedPatches(finalPatches.inversePatches, "store.patch() inverse patches");
801
+ if (safePatches.length) {
802
+ defaultResultValidated = internal.applyValidatedPatches?.(internal.rootState, safePatches, !patch) ?? false;
803
+ if (!internal.applyValidatedPatches) store.apply(internal.rootState, safePatches);
804
+ } else defaultResultValidated = true;
805
+ return [
806
+ internal.rootState,
807
+ safePatches,
808
+ safeInversePatches
809
+ ];
810
+ };
811
+ const setState = (next, updater = defaultUpdater) => {
812
+ internal.assertAlive?.("setState");
813
+ internal.assertMutationAllowed?.("setState");
814
+ 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.`);
815
+ if (internal.isBatching) throw new Error("setState cannot be called within the updater");
816
+ if (next === null) return [];
817
+ if (typeof next === "object") {
818
+ internal.validateState?.(next);
819
+ assertKnownStateShape(next, internal.rootState, internal.stateSchema, store.isSliceStore);
820
+ }
821
+ internal.isBatching = true;
822
+ if (!store.share && !options.enablePatches && !internal.mutableInstance && updater === defaultUpdater) try {
823
+ if (typeof next === "function") try {
824
+ internal.backupState = internal.rootState;
825
+ const snapshotCache = internal.computedSnapshotCache;
826
+ const snapshotSources = internal.computedIdentityRequired ? internal.computedSnapshotSources : void 0;
827
+ const snapshot = snapshotCache?.get(internal.rootState);
828
+ const updateSnapshot = Boolean(snapshot && snapshotCache);
829
+ const produced = create(internal.rootState, (draft) => {
830
+ internal.rootState = draft;
831
+ const returnValue = next(internal.module);
832
+ if (returnValue instanceof Promise) {
833
+ returnValue.catch(() => void 0);
834
+ throw new Error("setState with async function is not supported");
835
+ }
836
+ if (typeof returnValue === "object" && returnValue !== null) {
837
+ assertKnownStateShape(returnValue, internal.rootState, internal.stateSchema, store.isSliceStore);
838
+ mergeObject(internal.rootState, returnValue, store.isSliceStore);
839
+ }
840
+ }, { enablePatches: updateSnapshot });
841
+ const nextState = updateSnapshot ? produced[0] : produced;
842
+ assertKnownStateShape(nextState, internal.backupState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
843
+ if (updateSnapshot) {
844
+ const patches = produced[1];
845
+ finalizeImmutableStateSnapshot(nextState, apply(snapshot, createImmutableSnapshotPatches(patches, snapshotCache)), patches, snapshotCache, snapshotSources);
846
+ }
847
+ internal.rootState = nextState;
848
+ } catch (error) {
849
+ internal.rootState = internal.backupState;
850
+ throw error;
851
+ }
852
+ else {
853
+ const copy = cloneOwnEnumerable(internal.rootState);
854
+ if (store.isSliceStore) {
855
+ const nextRecord = next;
856
+ const copyRecord = copy;
857
+ for (const key of getOwnEnumerableKeys(nextRecord)) {
858
+ if (!Object.prototype.hasOwnProperty.call(copyRecord, key)) continue;
859
+ const sourceValue = nextRecord[key];
860
+ if (typeof sourceValue !== "object" || sourceValue === null) continue;
861
+ const targetValue = copyRecord[key];
862
+ if (typeof targetValue !== "object" || targetValue === null) continue;
863
+ const sliceCopy = cloneOwnEnumerable(targetValue);
864
+ mergeObject(sliceCopy, sourceValue);
865
+ setOwnEnumerable(copyRecord, key, sliceCopy);
866
+ }
867
+ } else mergeObject(copy, next);
868
+ assertKnownStateShape(copy, internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
869
+ internal.rootState = copy;
870
+ }
871
+ refreshSignalSlots(internal);
872
+ if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
873
+ else internal.listeners.forEach((listener) => listener());
874
+ return [];
875
+ } finally {
876
+ internal.isBatching = false;
877
+ }
878
+ let result;
879
+ try {
880
+ const isDrafted = internal.mutableInstance && isDraft(internal.rootState);
881
+ if (isDrafted) handleDraft(store, internal);
882
+ result = updater(next);
883
+ if (internal.mutableInstance) assertKnownStateShape(internal.rootState, internal.backupState ?? internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
884
+ if (!(updater === defaultUpdater && defaultResultValidated)) internal.validateState?.(internal.getTransportState?.() ?? internal.rootState);
885
+ if (isDrafted) {
886
+ internal.backupState = internal.rootState;
887
+ const [draft, finalize] = create(internal.rootState, { enablePatches: true });
888
+ internal.finalizeDraft = finalize;
889
+ internal.rootState = draft;
890
+ }
891
+ } finally {
892
+ internal.isBatching = false;
893
+ }
894
+ const trustedDefaultResult = updater === defaultUpdater && defaultResultValidated;
895
+ if (result?.length && !trustedDefaultResult) {
896
+ internal.validatePatches?.(result[1]);
897
+ result = [
898
+ result[0],
899
+ sanitizeCheckedPatches(result[1], "setState updater result"),
900
+ sanitizeCheckedPatches(result[2], "setState updater inverse result")
901
+ ];
902
+ }
903
+ if (result?.[1]) internal.emitPatches?.(result[1]);
904
+ return result;
905
+ };
906
+ const getState = (deps, selector) => deps && selector ? new Computed(deps, selector) : internal.module;
907
+ return {
908
+ setState,
909
+ getState
910
+ };
911
+ };
912
+ //#endregion
913
+ //#region packages/core/src/storeFactory.ts
914
+ const namespaceMap = /* @__PURE__ */ new Map();
915
+ let hasWarnedAmbiguousFunctionMap = false;
916
+ const warnAmbiguousFunctionMap = () => {
917
+ if (hasWarnedAmbiguousFunctionMap || process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") return;
918
+ hasWarnedAmbiguousFunctionMap = true;
919
+ console.warn([
920
+ `sliceMode: 'auto' inferred slices from an object of functions.`,
921
+ `This shape is ambiguous with a single store that only contains methods.`,
922
+ `Use create({ ping() {} }, { sliceMode: 'single' }) for a plain method store,`,
923
+ `or create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' }) for slices.`
924
+ ].join(" "));
925
+ };
926
+ const createStore = (createState, options, runtime = {}) => {
927
+ const { share, validatePatches, validateReplacementSource, validateState } = runtime;
928
+ const store = {};
929
+ const internal = {
930
+ sequence: 0,
931
+ isBatching: false,
932
+ listeners: /* @__PURE__ */ new Set(),
933
+ destroyCallbacks: /* @__PURE__ */ new Set(),
934
+ validatePatches,
935
+ validateReplacementSource,
936
+ validateState
937
+ };
938
+ internal.notifyStateChange = () => {
939
+ refreshSignalSlots(internal);
940
+ internal.listeners.forEach((listener) => listener());
941
+ };
942
+ const name = options.name ?? "default";
943
+ const shouldTrackName = share === "main" && process.env.NODE_ENV !== "test";
944
+ const releaseStoreName = () => {
945
+ if (shouldTrackName) namespaceMap.delete(name);
946
+ };
947
+ if (shouldTrackName) {
948
+ if (namespaceMap.get(name)) throw new Error(`Store name '${name}' is not unique.`);
949
+ namespaceMap.set(name, true);
950
+ }
951
+ try {
952
+ const { setState, getState } = handleState(store, internal, options);
953
+ const subscribe = (listener) => {
954
+ internal.assertAlive?.("subscribe");
955
+ internal.listeners.add(listener);
956
+ return () => internal.listeners.delete(listener);
957
+ };
958
+ let isDestroyed = false;
959
+ internal.assertAlive = (operation) => {
960
+ if (isDestroyed) throw new Error(`${operation} cannot be called after store.destroy().`);
961
+ };
962
+ const destroy = () => {
963
+ if (isDestroyed) return;
964
+ isDestroyed = true;
965
+ let firstError;
966
+ const callbacks = [...internal.destroyCallbacks ?? []];
967
+ internal.destroyCallbacks?.clear();
968
+ for (const callback of callbacks) try {
969
+ callback();
970
+ } catch (error) {
971
+ firstError ??= error;
972
+ }
973
+ internal.listeners.clear();
974
+ try {
975
+ store.transport?.dispose();
976
+ } catch (error) {
977
+ firstError ??= error;
978
+ } finally {
979
+ releaseStoreName();
980
+ }
981
+ if (firstError) throw firstError;
982
+ };
983
+ const applyState = (state, patches, prepared = false, skipFinalValidation = false) => {
984
+ internal.assertAlive?.("apply");
985
+ internal.assertMutationAllowed?.("apply");
986
+ if (patches && !prepared) validatePatches?.(patches);
987
+ if (!prepared) assertSafePatches(patches, "store.apply()");
988
+ const safePatches = prepared ? patches : sanitizePatches(patches);
989
+ const baseState = state === internal.module ? internal.rootState : state;
990
+ if (baseState !== internal.rootState) validateReplacementSource?.(baseState);
991
+ const appliedState = safePatches ? apply(baseState, safePatches) : baseState;
992
+ const nextState = prepared ? appliedState : sanitizeReplacementState(appliedState);
993
+ if (!skipFinalValidation) {
994
+ assertKnownStateShape(nextState, internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
995
+ validateState?.(internal.getTransportState?.() ?? nextState);
996
+ }
997
+ internal.rootState = nextState;
998
+ refreshSignalSlots(internal);
999
+ if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
1000
+ else internal.listeners.forEach((listener) => listener());
1001
+ };
1002
+ const apply$1 = (state = internal.rootState, patches) => applyState(state, patches);
1003
+ internal.applyValidatedPatches = (state, patches, skipFinalValidation) => {
1004
+ if (store.apply !== apply$1) {
1005
+ store.apply(state, patches);
1006
+ return false;
1007
+ }
1008
+ applyState(state, patches, true, skipFinalValidation);
1009
+ return true;
1010
+ };
1011
+ const getPureState = () => internal.rootState;
1012
+ const isFunctionMapObject = () => {
1013
+ if (typeof createState !== "object" || createState === null) return false;
1014
+ const values = getOwnEnumerableKeys(createState).map((key) => createState[key]);
1015
+ return values.length > 0 && values.every((value) => typeof value === "function");
1016
+ };
1017
+ const getIsSliceStore = () => {
1018
+ const sliceMode = options.sliceMode ?? "auto";
1019
+ if (sliceMode === "single") return false;
1020
+ if (sliceMode === "slices") {
1021
+ if (!isFunctionMapObject()) throw new Error(`sliceMode: 'slices' requires createState to be an object of slice functions.`);
1022
+ return true;
1023
+ }
1024
+ if (isFunctionMapObject()) {
1025
+ warnAmbiguousFunctionMap();
1026
+ return true;
1027
+ }
1028
+ return false;
1029
+ };
1030
+ const isSliceStore = getIsSliceStore();
1031
+ Object.assign(store, {
1032
+ name,
1033
+ share: share ?? false,
1034
+ setState,
1035
+ getState,
1036
+ subscribe,
1037
+ destroy,
1038
+ apply: apply$1,
1039
+ isSliceStore,
1040
+ getPureState
1041
+ });
1042
+ const middlewareStore = applyMiddlewares(store, options.middlewares ?? []);
1043
+ if (middlewareStore !== store) Object.assign(store, middlewareStore);
1044
+ internal.assertAlive?.("store initialization");
1045
+ if (validatePatches && store.patch) {
1046
+ const patch = store.patch.bind(store);
1047
+ store.patch = (options) => {
1048
+ const result = patch(options);
1049
+ validatePatches(result.patches);
1050
+ return result;
1051
+ };
1052
+ }
1053
+ const initialState = getInitialState(store, createState, internal);
1054
+ internal.assertAlive?.("store initialization");
1055
+ internal.sharedActionPaths = runtime.collectActionPaths?.(initialState, store.isSliceStore);
1056
+ if (!internal.getTransportState) runtime.validateInitialState?.(initialState, store.isSliceStore);
1057
+ store.getInitialState = () => initialState;
1058
+ internal.rootState = getRawState(store, internal, initialState, options, runtime.clientAction);
1059
+ if (validatePatches && store.apply !== apply$1) {
1060
+ const applyWithAdapter = store.apply.bind(store);
1061
+ store.apply = (state, patches) => {
1062
+ internal.assertAlive?.("apply");
1063
+ internal.assertMutationAllowed?.("apply");
1064
+ if (typeof state !== "undefined" && state !== internal.rootState && state !== internal.module) validateReplacementSource?.(state);
1065
+ if (patches) {
1066
+ validatePatches(patches);
1067
+ assertSafePatches(patches, "store.apply()");
1068
+ }
1069
+ applyWithAdapter(state, patches);
1070
+ };
1071
+ }
1072
+ internal.stateSchema = createStateSchema(internal.rootState, store.isSliceStore);
1073
+ validateState?.(internal.getTransportState?.() ?? internal.rootState);
1074
+ return {
1075
+ store,
1076
+ internal
1077
+ };
1078
+ } catch (error) {
1079
+ try {
1080
+ store.destroy?.();
1081
+ } catch (destroyError) {
1082
+ if (process.env.NODE_ENV === "development") console.error(destroyError);
1083
+ }
1084
+ releaseStoreName();
1085
+ throw error;
1086
+ }
1087
+ };
1088
+ //#endregion
1089
+ //#region packages/core/src/wrapStore.ts
1090
+ /**
1091
+ * Convert a store object into Coaction's callable store shape.
1092
+ *
1093
+ * @remarks
1094
+ * Framework bindings use this to attach selector-aware readers while
1095
+ * preserving the underlying store API on the returned function object. Most
1096
+ * applications should use a public `create` entry instead of calling
1097
+ * `wrapStore()` directly. Framework authors import this helper from
1098
+ * `coaction/local` or `coaction/adapter`.
1099
+ */
1100
+ const wrapStore = (store, getState = () => store.getState()) => {
1101
+ const { name, ..._store } = store;
1102
+ return Object.assign({ [name]: (...args) => getState(...args) }[name], _store);
1103
+ };
1104
+ //#endregion
1105
+ //#region packages/core/src/createLocal.ts
1106
+ /**
1107
+ * Create a store without linking the shared transport runtime.
1108
+ *
1109
+ * @remarks
1110
+ * The public `coaction/local` entry exports this implementation as `create`.
1111
+ * `createLocal` is only its internal and documentation name; it is not
1112
+ * exported by the root `coaction` entry.
1113
+ */
1114
+ const createLocal = (createState, options = {}) => {
1115
+ for (const key of [
1116
+ "clientTransport",
1117
+ "executeSyncTimeoutMs",
1118
+ "transport",
1119
+ "transportPolicy",
1120
+ "worker",
1121
+ "workerType"
1122
+ ]) if (Object.hasOwnProperty.call(options, key)) throw new Error(`Option '${key}' requires the coaction/shared entry point.`);
1123
+ const { store, internal } = createStore(createState, options);
1124
+ try {
1125
+ markStoreReady(store);
1126
+ internal.assertAlive?.("store initialization");
1127
+ } catch (error) {
1128
+ try {
1129
+ store.destroy();
1130
+ } catch (destroyError) {
1131
+ if (process.env.NODE_ENV === "development") console.error(destroyError);
1132
+ }
1133
+ throw error;
1134
+ }
1135
+ return wrapStore(store);
1136
+ };
1137
+ //#endregion
1138
+ export { computed, createLocal as create, effect, effectScope, endBatch, isComputed, isEffect, isEffectScope, isSignal, onStoreReady, signal, startBatch, trigger, wrapStore };