@quantajs/core
Version:
A compact, scalable, and developer-friendly state management library designed for any JavaScript environment. It includes a reactivity system that enables efficient and flexible data handling, making complex state management easy.
1,358 lines (1,353 loc) • 37.8 kB
JavaScript
/*! MIT License
Copyright (c) 2025 QuantaJS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var G = /* @__PURE__ */ ((s) => (s[s.DEBUG = 0] = "DEBUG", s[s.INFO = 1] = "INFO", s[s.WARN = 2] = "WARN", s[s.ERROR = 3] = "ERROR", s[s.SILENT = 4] = "SILENT", s))(G || {});
class P {
config;
isNode;
hasConsole;
constructor(r = {}) {
this.config = {
level: 1,
prefix: "",
timestamp: !0,
colors: !0,
...r
}, this.isNode = this.detectNodeEnvironment(), this.hasConsole = this.detectConsole();
}
/**
* Detect if running in Node.js environment
*/
detectNodeEnvironment() {
return typeof process < "u" && !!process.versions && !!process.versions.node;
}
/**
* Detect if console is available
*/
detectConsole() {
return typeof console < "u" && typeof console.log == "function";
}
/**
* Get timestamp string
*/
getTimestamp() {
if (!this.config.timestamp) return "";
try {
return `[${(/* @__PURE__ */ new Date()).toISOString()}] `;
} catch {
return "";
}
}
/**
* Get color codes for different log levels (Node.js only)
*/
getColorCode(r) {
return !this.config.colors || !this.isNode ? "" : {
0: "\x1B[36m",
// Cyan
1: "\x1B[32m",
// Green
2: "\x1B[33m",
// Yellow
3: "\x1B[31m"
// Red
}[r] || "";
}
/**
* Reset color code (Node.js only)
*/
getResetCode() {
return this.config.colors && this.isNode ? "\x1B[0m" : "";
}
/**
* Get level name
*/
getLevelName(r) {
const e = {
0: "DEBUG",
1: "INFO",
2: "WARN",
3: "ERROR"
};
return r in e ? e[r] : "LOG";
}
/**
* Format message with prefix, timestamp, and colors
*/
formatMessage(r, e) {
const t = this.getTimestamp(), n = this.config.prefix ? `[${this.config.prefix}] ` : "", o = `[${this.getLevelName(r)}]`, a = this.getColorCode(r), f = this.getResetCode();
return `${a}${t}${n}${o} ${e}${f}`;
}
/**
* Safe console method execution
*/
safeConsoleCall(r, e, ...t) {
if (this.hasConsole)
try {
const n = console[r] || console.log;
typeof n == "function" && n(e, ...t);
} catch {
try {
console.log && typeof console.log == "function" && console.log(e, ...t);
} catch {
}
}
}
/**
* Check if logging is enabled for the given level
*/
shouldLog(r) {
return r >= this.config.level;
}
/**
* Debug level logging
*/
debug(r, ...e) {
if (!this.shouldLog(
0
/* DEBUG */
)) return;
const t = this.formatMessage(0, r);
this.safeConsoleCall("debug", t, ...e);
}
/**
* Info level logging (alias for log)
*/
info(r, ...e) {
this.log(r, ...e);
}
/**
* Standard logging
*/
log(r, ...e) {
if (!this.shouldLog(
1
/* INFO */
)) return;
const t = this.formatMessage(1, r);
this.safeConsoleCall("log", t, ...e);
}
/**
* Warning level logging
*/
warn(r, ...e) {
if (!this.shouldLog(
2
/* WARN */
)) return;
const t = this.formatMessage(2, r);
this.safeConsoleCall("warn", t, ...e);
}
/**
* Error level logging
*/
error(r, ...e) {
if (!this.shouldLog(
3
/* ERROR */
)) return;
const t = this.formatMessage(3, r);
this.safeConsoleCall("error", t, ...e);
}
/**
* Update logger configuration
*/
configure(r) {
this.config = { ...this.config, ...r };
}
/**
* Set log level
*/
setLevel(r) {
this.config.level = r;
}
/**
* Get current log level
*/
getLevel() {
return this.config.level;
}
/**
* Create a child logger with a prefix
*/
child(r) {
const e = this.config.prefix ? `${this.config.prefix}:${r}` : r;
return new P({
...this.config,
prefix: e
});
}
}
const i = new P(), ne = (s) => new P(s);
class _ {
subscribers;
constructor() {
this.subscribers = /* @__PURE__ */ new Set();
}
depend(r) {
try {
r && this.subscribers.add(r);
} catch (e) {
i.error(
`Dependency: Failed to add dependency: ${e instanceof Error ? e.message : String(e)}`
);
}
}
notify(r) {
try {
new Set(this.subscribers).forEach((t) => {
try {
r !== void 0 ? t(r) : t();
} catch (n) {
i.warn(
// Warn only—isolated: Don't break other subs
`Dependency: Subscriber callback failed: ${n instanceof Error ? n.message : String(n)}`
);
}
});
} catch (e) {
i.error(
`Dependency: Failed to notify subscribers: ${e instanceof Error ? e.message : String(e)}`
);
}
}
remove(r) {
try {
this.subscribers.delete(r);
} catch (e) {
i.error(
`Dependency: Failed to remove dependency: ${e instanceof Error ? e.message : String(e)}`
);
}
}
clear() {
try {
this.subscribers.clear();
} catch (r) {
i.error(
`Dependency: Failed to clear dependencies: ${r instanceof Error ? r.message : String(r)}`
);
}
}
get getSubscribers() {
return new Set(this.subscribers);
}
}
const N = /* @__PURE__ */ new WeakMap();
function V(s, r, e) {
i.debug(
`DeepTrigger: Entry - Bubbling from ${String(r)} on ${String(s)}`
);
try {
let t = s;
const n = /* @__PURE__ */ new Set();
for (; ; ) {
if (n.has(t)) {
i.warn(
`DeepTrigger: Cycle detected in bubble chain from ${String(r)}`
);
break;
}
n.add(t);
const o = N.get(t);
if (i.debug(
`DeepTrigger: Checking parent for ${String(t)}: ${o ? "Found" : "None"}`
), !o) break;
const { parent: a, key: f } = o;
if (a === t) break;
const g = e.get(a), h = g?.[f] ? "Yes" : "No";
i.debug(
`DeepTrigger: Parent ${String(a)} has dep on ${String(f)}? ${h}`
), g?.[f] && (g[f].notify(), i.debug(
`DeepTrigger: Bubbled ${String(f)} on ${String(a)}`
)), t = a;
}
} catch (t) {
i.error(
`DeepTrigger: Bubble failed for ${String(r)}: ${t instanceof Error ? t.message : String(t)}`
);
}
}
const F = /* @__PURE__ */ new WeakMap();
let O = null, Q = !1;
const m = [];
function E(s, r) {
try {
const e = F.get(s);
if (e && e[r]) {
const t = e[r].getSubscribers;
t.size > 0 && t.forEach((o) => {
if (!Q) {
if (m.includes(o)) {
const a = `Circular dependency detected: Effect "${o.name || "anonymous"}" triggered itself. Stack trace: ${m.map((g) => g.name || "anonymous").join(" -> ")}`;
i.error(`Effect: ${a}`);
const f = [...m, o].map(
(g) => g.name || "anonymous"
);
throw i.error(
`Effect: Circular dependency path: ${f.join(
" -> "
)}`
), new Error(a);
}
try {
o();
} catch (a) {
throw i.error(
`Effect: Failed to execute effect "${o.name || "anonymous"}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
}
});
}
V(s, r, F);
} catch (e) {
throw i.error(
`Effect: Trigger failed for property "${String(r)}": ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
function $(s, r) {
try {
let e = F.get(s);
e || F.set(s, e = {}), e[r] || (e[r] = new _()), O && e[r].depend(O);
} catch (e) {
throw i.error(
`Effect: Failed to track dependency for property "${String(r)}": ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
function j(s) {
const r = () => {
if (m.includes(s)) {
const e = `Circular dependency detected: Effect "${s.name || "anonymous"}" triggered itself. Stack trace: ${m.map((n) => n.name || "anonymous").join(" -> ")}`;
i.error(`Effect: ${e}`);
const t = [...m, s].map(
(n) => n.name || "anonymous"
);
throw i.error(
`Effect: Circular dependency path: ${t.join(" -> ")}`
), i.error(
`Effect: Current effect stack depth: ${m.length}`
), new Error(e);
}
try {
m.push(s), O = s, s();
} catch (e) {
throw i.error(
`Effect: Effect "${s.name || "anonymous"}" failed: ${e instanceof Error ? e.message : String(e)}`
), i.error(
`Effect: Effect stack at failure: ${m.map((t) => t.name || "anonymous").join(" -> ")}`
), e;
} finally {
m.pop(), O = m[m.length - 1] || null;
}
};
return r(), r;
}
const H = (s) => {
try {
let r, e = !0;
const t = j(() => {
try {
r = s(), e = !1;
} catch (o) {
throw i.error(
`Computed: Failed to compute value: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}), n = {
get value() {
try {
return e && t(), $(n, "value"), r;
} catch (o) {
throw i.error(
`Computed: Failed to get computed value: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}
};
return n;
} catch (r) {
throw i.error(
`Computed: Failed to create computed value: ${r instanceof Error ? r.message : String(r)}`
), r;
}
};
class K {
listeners = /* @__PURE__ */ new Set();
stores = /* @__PURE__ */ new Map();
emit(r) {
this.listeners.forEach((e) => e(r));
}
subscribe(r) {
return this.listeners.add(r), this.stores.forEach((e, t) => {
r({ type: "STORE_INIT", payload: { name: t, store: e } });
}), () => {
this.listeners.delete(r);
};
}
stateMap = /* @__PURE__ */ new WeakMap();
registerStore(r, e) {
this.stores.set(r, e), e.state && this.stateMap.set(e.state, r), this.emit({ type: "STORE_INIT", payload: { name: r, store: e } });
}
getStoreName(r) {
return this.stateMap.get(r);
}
notifyStateChange(r, e, t, n) {
let o = r;
const a = [String(e)];
let f = this.stateMap.get(o);
if (!f && n) {
let g = 0;
const h = 50;
for (; !f && g < h; ) {
const c = n.get(o);
if (!c) break;
a.unshift(String(c.key)), o = c.parent, f = this.stateMap.get(o), g++;
}
}
f && this.emit({
type: "STATE_CHANGE",
payload: {
storeName: f,
path: a.join("."),
value: t
}
});
}
notifyActionCall(r, e, t) {
this.emit({
type: "ACTION_CALL",
payload: { storeName: r, actionName: e, args: t }
});
}
}
const R = new K();
typeof window < "u" && (window.__QUANTA_DEVTOOLS__ = R);
const k = /* @__PURE__ */ new WeakMap();
function Y(s) {
if (k.has(s))
return k.get(s);
const r = new Proxy(s, {
get(e, t) {
try {
if (t === "size")
return $(e, "size"), e.size;
if (t === "get") {
const n = Reflect.get(e, t);
return (o) => {
try {
const a = n.call(e, o);
return $(e, o), a;
} catch (a) {
throw i.error(
`Reactive: Failed to get collection value for key "${String(o)}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
};
}
if (t === "set" || t === "add" || t === "delete") {
const n = Reflect.get(e, t);
return (...o) => {
try {
const a = n.apply(e, o);
if (E(e, "size"), t === "set") {
const [f] = o;
E(e, f), R.notifyStateChange(
e,
f,
o[1],
N
);
}
return a;
} catch (a) {
throw i.error(
`Reactive: Failed to execute collection operation "${String(t)}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
};
}
if (t === "clear") {
const n = Reflect.get(e, t);
return () => {
try {
const o = n.apply(e);
return E(e, "size"), R.notifyStateChange(
e,
"clear",
void 0,
N
), o;
} catch (o) {
throw i.error(
`Reactive: Failed to clear collection: ${o instanceof Error ? o.message : String(o)}`
), o;
}
};
}
return $(e, t), Reflect.get(e, t);
} catch (n) {
throw i.error(
`Reactive: Failed to access collection property "${String(t)}": ${n instanceof Error ? n.message : String(n)}`
), n;
}
}
});
return k.set(s, r), r;
}
function B(s) {
try {
if (k.has(s))
return k.get(s);
if (s instanceof Map || s instanceof Set)
return Y(s);
const r = new Proxy(s, {
get(e, t, n) {
try {
const o = Reflect.get(e, t, n);
if (t === "size" && (e instanceof Map || e instanceof Set))
return $(e, "size"), o;
if ($(e, t), typeof o == "object" && o !== null) {
const a = B(o);
return (typeof t == "string" || typeof t == "symbol") && (N.set(o, { parent: e, key: t }), i.debug(
`Reactive: Set parent for raw ${String(t)} (${String(o)}) on ${String(e)}`
)), a;
}
return o;
} catch (o) {
throw i.error(
`Reactive: Failed to get property "${String(t)}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
},
set(e, t, n, o) {
try {
const a = e[t], f = Reflect.set(e, t, n, o);
if (a !== n || isNaN(a) && isNaN(n)) {
if (E(e, t), typeof n == "object" && n !== null) {
const g = B(n);
V(g, t, F);
}
R.notifyStateChange(e, t, n, N);
}
return f;
} catch (a) {
throw i.error(
`Reactive: Failed to set property "${String(t)}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
},
deleteProperty(e, t) {
try {
const n = t in e, o = Reflect.deleteProperty(e, t);
return n && (E(e, t), R.notifyStateChange(
e,
t,
void 0,
N
)), o;
} catch (n) {
throw i.error(
`Reactive: Failed to delete property "${String(t)}": ${n instanceof Error ? n.message : String(n)}`
), n;
}
},
has(e, t) {
try {
return $(e, t), Reflect.has(e, t);
} catch (n) {
throw i.error(
`Reactive: Failed to check property "${String(t)}" existence: ${n instanceof Error ? n.message : String(n)}`
), n;
}
},
ownKeys(e) {
try {
return $(e, "keys"), Reflect.ownKeys(e);
} catch (t) {
throw i.error(
`Reactive: Failed to get own keys: ${t instanceof Error ? t.message : String(t)}`
), t;
}
},
getOwnPropertyDescriptor(e, t) {
try {
return $(e, t), Reflect.getOwnPropertyDescriptor(e, t);
} catch (n) {
throw i.error(
`Reactive: Failed to get property descriptor for "${String(t)}": ${n instanceof Error ? n.message : String(n)}`
), n;
}
}
});
return k.set(s, r), r;
} catch (r) {
throw i.error(
`Reactive: Failed to create reactive object: ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
const X = (s) => {
try {
return B(s);
} catch (r) {
throw i.error(
`Reactive: Failed to create reactive object: ${r instanceof Error ? r.message : String(r)}`
), r;
}
}, Z = (s, r, e = {}) => {
const { deep: t = !1, immediate: n = !0 } = e;
let o;
if (t) {
const a = (c) => JSON.stringify(c);
let f = null;
const g = 100, h = () => {
try {
const c = s(), l = a(c);
if (o === void 0)
n && r(c, c);
else {
const S = a(o);
l !== S && r(c, o);
}
o = c;
} catch (c) {
i.warn(
`Watch (deep): Poll failed: ${c instanceof Error ? c.message : String(c)}`
);
}
};
return h(), f = setInterval(h, g), () => {
f && (clearInterval(f), f = null);
};
} else
try {
return j(() => {
try {
const f = s();
n && o === void 0 ? r(f, f) : o !== void 0 && f !== o && r(f, o), o = f;
} catch (f) {
throw i.error(
`Watch: Failed to execute watch source function: ${f instanceof Error ? f.message : String(f)}`
), f;
}
});
} catch (a) {
throw i.error(
`Watch: Failed to create watcher: ${a instanceof Error ? a.message : String(a)}`
), a;
}
}, ee = (s) => {
try {
const r = new Proxy(s, {
get(e, t, n) {
try {
if (t in e.state)
return Reflect.get(e.state, t);
if (t in e.getters) {
const o = Reflect.get(e.getters, t);
try {
return o && typeof o == "object" && "value" in o ? o.value : typeof o == "function" ? o.bind(r) : o;
} catch (a) {
return i.warn(
`FlattenStore: getter read failed for "${String(t)}": ${String(a)}`
), o;
}
}
return t in e.actions ? Reflect.get(e.actions, t) : Reflect.get(e, t, n);
} catch (o) {
throw i.error(
`FlattenStore: Failed to get property "${t}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
},
set(e, t, n, o) {
try {
const a = t in e.state;
(a ? Reflect.set(e.state, t, n) : Reflect.set(e, t, n, o)) && a && (E(e.state, t), e.notifyAll?.());
const g = Reflect.set(
e,
t,
n,
o
);
return e.notifyAll?.(), g;
} catch (a) {
throw i.error(
`FlattenStore: Failed to set property "${t}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
}
});
return r;
} catch (r) {
throw i.error(
`FlattenStore: Failed to create flattened store: ${r instanceof Error ? r.message : String(r)}`
), r;
}
};
function re(s, r) {
let e, t;
const n = ((...o) => {
try {
t = o, e && clearTimeout(e), e = setTimeout(() => {
try {
t && (s(...t), t = void 0);
} catch (a) {
throw i.error(
`Debounce: Failed to execute debounced function: ${a instanceof Error ? a.message : String(a)}`
), a;
}
}, r);
} catch (a) {
throw i.error(
`Debounce: Failed to schedule debounced function: ${a instanceof Error ? a.message : String(a)}`
), a;
}
});
return n.flush = () => {
try {
e && (clearTimeout(e), e = void 0), t && (s(...t), t = void 0);
} catch (o) {
throw i.error(
`Debounce: Failed to flush debounced function: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}, n.cancel = () => {
try {
e && (clearTimeout(e), e = void 0), t = void 0;
} catch (o) {
throw i.error(
`Debounce: Failed to cancel debounced function: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}, n;
}
function te(s, r, e, t, n) {
const {
adapter: o,
serialize: a = JSON.stringify,
deserialize: f = JSON.parse,
debounceMs: g = 300,
include: h,
exclude: c,
transform: l,
version: S = 1,
migrations: D = {},
onError: T,
validator: C
} = t;
let M = !1, x = !1, v = null, p = null;
const q = () => {
const u = s();
let d = { ...u };
return h && (d = h.reduce((y, b) => (b in u && (y[b] = u[b]), y), {})), c && c.forEach((y) => delete d[y]), l?.out && (d = l.out(d)), C && !C(d) ? (i.warn(
`Persistence: Slice validation failed for ${n || "store"}—skipping watch trigger`
), null) : d;
}, A = re(async () => {
if (!M)
try {
const u = s();
let d = { ...u };
if (h && (d = h.reduce((w, I) => (I in u && (w[I] = u[I]), w), {})), c && c.forEach((w) => delete d[w]), l?.out && (d = l.out(d)), C && !C(d))
throw new Error("Data validation failed before saving");
const y = {
data: d,
version: S,
timestamp: Date.now(),
storeName: n || "anonymous"
}, b = a(y);
await o.write(b), i.debug(
`Persistence: Saved slice for ${n || "store"}`
);
} catch (u) {
const d = u instanceof Error ? u : new Error(String(u));
T?.(d, "write"), console.warn(`Failed to persist state: ${d.message}`);
}
}, g), z = async () => {
try {
M = !0;
const u = await o.read();
if (u) {
const d = f(u);
let { data: y, version: b } = d;
if (b < S)
for (let w = b + 1; w <= S; w++)
D[w] && (y = D[w](y));
if (l?.in && (y = l.in(y)), C && !C(y))
throw new Error("Loaded data failed validation");
r(y), e();
}
x = !0;
} catch (u) {
const d = u instanceof Error ? u : new Error(String(u));
T?.(d, "read"), console.warn(
`Failed to load persisted state: ${d.message}`
), x = !0;
} finally {
M = !1;
}
}, L = () => {
o.subscribe && !v && (v = o.subscribe((u) => {
if (!M && x) {
M = !0;
try {
const d = f(u);
let y = d.data || d;
l?.in && (y = l.in(y)), r(y), e();
} catch (d) {
console.warn("Cross-tab sync failed:", d);
} finally {
M = !1;
}
}
}));
}, U = () => {
if (!p)
try {
p = Z(
() => {
if (M) return null;
const u = q();
return u ? a({ data: u }) : null;
},
() => {
x && A();
},
{ deep: !0 }
), i.debug(
`Persistence: Auto-save watcher active for ${n || "store"}`
);
} catch (u) {
const d = u instanceof Error ? u : new Error(String(u));
T?.(d, "watch-setup"), i.warn(
`Persistence: Auto-save setup failed for ${n || "store"}: ${d.message}`
);
}
};
return z().then(() => {
U(), L();
}), {
async save() {
await A.flush();
},
load: z,
async clear() {
try {
p && (p(), p = null), await o.remove(), v && (v(), v = null);
} catch (u) {
const d = u instanceof Error ? u : new Error(String(u));
throw T?.(d, "remove"), d;
}
},
getAdapter() {
return o;
},
isRehydrated() {
return x;
},
destroy() {
p && (p(), p = null), v && (v(), v = null), A.cancel();
}
};
}
class oe {
migrations = /* @__PURE__ */ new Map();
constructor(r = []) {
r.forEach((e) => {
this.addMigration(e.version, e.migrate);
});
}
/**
* Add a migration function for a specific version
*/
addMigration(r, e) {
this.migrations.set(r, e), i.log(`Migration: Added migration for version ${r}`);
}
/**
* Remove a migration for a specific version
*/
removeMigration(r) {
const e = this.migrations.has(r);
this.migrations.delete(r), e ? i.log(`Migration: Removed migration for version ${r}`) : i.warn(
`Migration: No migration found for version ${r} to remove`
);
}
/**
* Get all available migration versions
*/
getVersions() {
return Array.from(this.migrations.keys()).sort((r, e) => r - e);
}
/**
* Check if a migration exists for a specific version
*/
hasMigration(r) {
return this.migrations.has(r);
}
/**
* Get the highest migration version
*/
getHighestVersion() {
const r = this.getVersions();
return r.length > 0 ? Math.max(...r) : 0;
}
/**
* Apply migrations from current version to target version
*/
migrate(r, e, t) {
if (e === t)
return r;
if (e > t)
throw new Error(
`Cannot migrate from version ${e} to ${t} (downgrade not supported)`
);
i.log(
`Migration: Starting migration from version ${e} to ${t}`
);
let n = r;
for (let o = e + 1; o <= t; o++) {
const a = this.migrations.get(o);
if (a)
try {
i.log(
`Migration: Applying migration for version ${o}`
), n = a(n), i.log(
`Migration: Successfully applied migration for version ${o}`
);
} catch (f) {
const g = `Migration ${o} failed: ${f instanceof Error ? f.message : String(f)}`;
throw i.warn(g), new Error(g);
}
else
i.log(
`Migration: No migration found for version ${o}, skipping`
);
}
return i.log(
`Migration: Successfully completed migration from version ${e} to ${t}`
), n;
}
/**
* Validate that all migrations can be applied successfully
*/
validateMigrations() {
i.log("Migration: Starting migration validation...");
const r = [], e = this.getVersions();
if (e.length === 0)
return i.log("Migration: No migrations to validate"), { valid: !0, errors: [] };
i.log(`Migration: Validating ${e.length} migrations`);
const t = { test: !0 };
for (let o = 0; o < e.length - 1; o++) {
const a = e[o], f = e[o + 1];
try {
i.log(
`Migration: Testing migration from version ${a} to ${f}`
), this.migrate(t, a, f), i.log(
`Migration: Successfully validated migration from version ${a} to ${f}`
);
} catch (g) {
const h = `Migration from ${a} to ${f} failed: ${g instanceof Error ? g.message : String(g)}`;
i.warn(h), r.push(h);
}
}
const n = r.length === 0;
return n ? i.log("Migration: All migrations validated successfully") : i.warn(
`Migration: Validation failed with ${r.length} errors`
), {
valid: n,
errors: r
};
}
}
function se(s) {
const r = new oe();
return s.migrations ? (i.log(
`Migration: Creating migration manager with ${Object.keys(s.migrations).length} migrations`
), Object.entries(s.migrations).forEach(([e, t]) => {
const n = parseInt(e, 10);
isNaN(n) ? i.warn(
`Migration: Invalid version number "${e}", skipping`
) : r.addMigration(n, t);
})) : i.log("Migration: Creating migration manager with no migrations"), r;
}
const ie = {
/**
* Add a new property with default value
*/
addProperty(s, r) {
return (e) => (i.log(
`Migration: Added property "${String(s)}" with default value:`,
r
), {
...e,
[s]: r
});
},
/**
* Remove a property
*/
removeProperty(s) {
return (r) => {
const { [s]: e, ...t } = r;
return i.log(
`Migration: Removed property "${String(s)}" with value:`,
e
), t;
};
},
/**
* Rename a property
*/
renameProperty(s, r) {
return (e) => {
const { [s]: t, ...n } = e;
return i.log(
`Migration: Renamed property "${String(s)}" to "${String(r)}" with value:`,
t
), {
...n,
[r]: t
};
};
},
/**
* Transform a property value
*/
transformProperty(s, r) {
return (e) => {
const t = e[s], n = r(t);
return i.log(
`Migration: Transformed property "${String(s)}" from:`,
t,
"to:",
n
), {
...e,
[s]: n
};
};
}
};
class ae {
constructor(r) {
if (this.key = r, typeof window > "u" || !window.localStorage)
throw new Error(
"LocalStorage is not available in this environment"
);
}
read() {
try {
const r = localStorage.getItem(this.key);
return r ? JSON.parse(r) : null;
} catch (r) {
return i.warn(
`Failed to read from localStorage: ${r instanceof Error ? r.message : String(r)}`
), null;
}
}
write(r) {
try {
localStorage.setItem(this.key, JSON.stringify(r));
} catch (e) {
throw e instanceof Error && e.name === "QuotaExceededError" && i.warn("LocalStorage quota exceeded"), e;
}
}
remove() {
localStorage.removeItem(this.key);
}
subscribe(r) {
const e = (t) => {
if (t.key === this.key && t.newValue)
try {
r(JSON.parse(t.newValue));
} catch (n) {
i.warn("Failed to parse storage event data:", n);
}
};
return window.addEventListener("storage", e), () => window.removeEventListener("storage", e);
}
}
class ce {
constructor(r) {
if (this.key = r, typeof window > "u" || !window.sessionStorage)
throw new Error(
"SessionStorage is not available in this environment"
);
}
read() {
try {
const r = sessionStorage.getItem(this.key);
return r ? JSON.parse(r) : null;
} catch (r) {
return i.warn(
`Failed to read from sessionStorage: ${r instanceof Error ? r.message : String(r)}`
), null;
}
}
write(r) {
try {
sessionStorage.setItem(this.key, JSON.stringify(r));
} catch (e) {
throw e instanceof Error && e.name === "QuotaExceededError" && i.warn("SessionStorage quota exceeded"), e;
}
}
remove() {
sessionStorage.removeItem(this.key);
}
subscribe(r) {
const e = (t) => {
if (t.key === this.key && t.newValue)
try {
r(JSON.parse(t.newValue));
} catch (n) {
i.warn("Failed to parse storage event data:", n);
}
};
return window.addEventListener("storage", e), () => window.removeEventListener("storage", e);
}
}
class le {
constructor(r, e = "quantajs", t = "stores", n = 1) {
this.key = r, this.dbName = e, this.storeName = t, this.version = n;
}
async read() {
try {
const t = (await this.openDB()).transaction([this.storeName], "readonly").objectStore(this.storeName);
return new Promise((n, o) => {
const a = t.get(this.key);
a.onsuccess = () => n(a.result?.data || null), a.onerror = () => o(a.error);
});
} catch (r) {
return i.warn(
`IndexedDB read failed: ${r instanceof Error ? r.message : String(r)}`
), null;
}
}
async write(r) {
const n = (await this.openDB()).transaction([this.storeName], "readwrite").objectStore(this.storeName);
return new Promise((o, a) => {
const f = {
key: this.key,
data: r,
timestamp: Date.now()
}, g = n.put(f);
g.onsuccess = () => o(), g.onerror = () => a(g.error);
});
}
async remove() {
const t = (await this.openDB()).transaction([this.storeName], "readwrite").objectStore(this.storeName);
return new Promise((n, o) => {
const a = t.delete(this.key);
a.onsuccess = () => n(), a.onerror = () => o(a.error);
});
}
async openDB() {
return new Promise((r, e) => {
const t = indexedDB.open(this.dbName, this.version);
t.onupgradeneeded = () => {
const n = t.result;
n.objectStoreNames.contains(this.storeName) || n.createObjectStore(this.storeName, { keyPath: "key" });
}, t.onsuccess = () => r(t.result), t.onerror = () => e(t.error);
});
}
}
const W = /* @__PURE__ */ new Map(), J = /* @__PURE__ */ new WeakMap(), fe = (s, r) => {
try {
if (W.has(s)) {
const c = `Store with name "${s}" already exists.`;
throw i.error(`Store: ${c}`), new Error(c);
}
const e = r.state(), t = X(e);
Object.keys(t).forEach((c) => {
const l = t[c];
}), i.debug(
`Store ${s}: Pre-touched deps: ${Object.keys(F.get(t) || {})}`
);
const n = new _();
(() => {
try {
j(() => {
for (const c in t) {
const l = t[c];
}
n.notify(t);
}), i.debug(
`Watcher: Tracked top-level deps: ${Object.keys(F.get(t) || {})}`
);
} catch (c) {
i.warn(
`createStore: Failed to register deep watcher for store "${s}": ${c instanceof Error ? c.message : String(c)}`
);
}
})();
const o = {};
if (r.getters)
for (const c in r.getters)
try {
const l = r.getters[c];
o[c] = H(() => l(t));
} catch (l) {
throw i.error(
`Store: Failed to create getter "${String(c)}" for store "${s}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
let a = null;
if (r.persist)
try {
a = te(
() => t,
(c) => {
try {
for (const l in c)
t[l] !== c[l] && (t[l] = c[l], E(t, l));
} catch (l) {
throw i.error(
`Store: Persistence state update failed for store "${s}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
},
() => n.notify(),
r.persist,
s
);
} catch (c) {
throw i.error(
`Store: Failed to set up persistence for store "${s}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
const f = /* @__PURE__ */ new Set(), g = {
state: t,
getters: o,
actions: {},
subscribe: (c) => {
try {
return f.add(c), n.depend(c), () => {
try {
f.delete(c), n.remove(c);
} catch (l) {
i.error(
`Store: Failed to remove subscriber from store "${s}": ${l instanceof Error ? l.message : String(l)}`
);
}
};
} catch (l) {
throw i.error(
`Store: Failed to add subscriber to store "${s}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
},
notifyAll: () => {
try {
const c = g.state;
f.forEach((l) => {
try {
l(c);
} catch (S) {
i.warn(
`Store: Subscriber callback failed for "${s}": ${S instanceof Error ? S.message : String(S)}`
);
}
});
} catch (c) {
i.error(
`Store: notifyAll failed for "${s}": ${c instanceof Error ? c.message : String(c)}`
);
}
},
$reset: () => {
try {
const c = J.get(g);
if (!c) {
const l = `Initial state not found for store "${s}"`;
throw i.error(`Store: ${l}`), new Error(l);
}
for (const l in c)
g.state[l] !== c[l] && (g.state[l] = c[l], E(g.state, l));
for (const l in g.state)
l in c || (delete g.state[l], E(g.state, l));
} catch (c) {
throw i.error(
`Store: Failed to reset store "${s}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
},
$persist: a,
$destroy: () => {
try {
g.$persist?.destroy?.(), n.clear(), f.clear(), i.debug(`Store: Destroyed "${s}"`);
} catch (c) {
i.error(
`Store: Destroy failed for "${s}": ${c instanceof Error ? c.message : String(c)}`
);
}
}
};
J.set(g, e);
const h = ee(g);
if (r.actions)
for (const c in r.actions)
try {
const S = r.actions[c].bind(h);
g.actions[c] = (...D) => (R.notifyActionCall(s, c, D), S(...D));
} catch (l) {
throw i.error(
`Store: Failed to create action "${String(c)}" for store "${s}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
return W.set(s, h), R.registerStore(s, g), h;
} catch (e) {
throw i.error(
`Store: Failed to create store "${s}": ${e instanceof Error ? e.message : String(e)}`
), e;
}
};
function ge(s) {
try {
const r = W.get(s);
if (!r) {
const e = `Store with name "${s}" does not exist.`;
throw i.error(`Store: ${e}`), new Error(e);
}
return r;
} catch (r) {
throw i.error(
`Store: Failed to retrieve store "${s}": ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
export {
ie as CommonMigrations,
le as IndexedDBAdapter,
ae as LocalStorageAdapter,
G as LogLevel,
P as Logger,
oe as MigrationManager,
ce as SessionStorageAdapter,
H as computed,
ne as createLogger,
se as createMigrationManager,
te as createPersistenceManager,
fe as createStore,
i as logger,
X as reactive,
ge as useStore,
Z as watch
};