@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,124 lines (1,119 loc) • 31.2 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 W = Object.defineProperty;
var q = (n, e, r) => e in n ? W(n, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : n[e] = r;
var p = (n, e, r) => q(n, typeof e != "symbol" ? e + "" : e, r);
var V = /* @__PURE__ */ ((n) => (n[n.DEBUG = 0] = "DEBUG", n[n.INFO = 1] = "INFO", n[n.WARN = 2] = "WARN", n[n.ERROR = 3] = "ERROR", n[n.SILENT = 4] = "SILENT", n))(V || {});
class C {
constructor(e = {}) {
p(this, "config");
p(this, "isNode");
p(this, "hasConsole");
this.config = {
level: 1,
prefix: "",
timestamp: !0,
colors: !0,
...e
}, 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(e) {
return !this.config.colors || !this.isNode ? "" : {
0: "\x1B[36m",
// Cyan
1: "\x1B[32m",
// Green
2: "\x1B[33m",
// Yellow
3: "\x1B[31m"
// Red
}[e] || "";
}
/**
* Reset color code (Node.js only)
*/
getResetCode() {
return this.config.colors && this.isNode ? "\x1B[0m" : "";
}
/**
* Get level name
*/
getLevelName(e) {
const r = {
0: "DEBUG",
1: "INFO",
2: "WARN",
3: "ERROR"
};
return e in r ? r[e] : "LOG";
}
/**
* Format message with prefix, timestamp, and colors
*/
formatMessage(e, r) {
const t = this.getTimestamp(), s = this.config.prefix ? `[${this.config.prefix}] ` : "", o = `[${this.getLevelName(e)}]`, a = this.getColorCode(e), g = this.getResetCode();
return `${a}${t}${s}${o} ${r}${g}`;
}
/**
* Safe console method execution
*/
safeConsoleCall(e, r, ...t) {
if (this.hasConsole)
try {
const s = console[e] || console.log;
typeof s == "function" && s(r, ...t);
} catch {
try {
console.log && typeof console.log == "function" && console.log(r, ...t);
} catch {
}
}
}
/**
* Check if logging is enabled for the given level
*/
shouldLog(e) {
return e >= this.config.level;
}
/**
* Debug level logging
*/
debug(e, ...r) {
if (!this.shouldLog(
0
/* DEBUG */
)) return;
const t = this.formatMessage(0, e);
this.safeConsoleCall("debug", t, ...r);
}
/**
* Info level logging (alias for log)
*/
info(e, ...r) {
this.log(e, ...r);
}
/**
* Standard logging
*/
log(e, ...r) {
if (!this.shouldLog(
1
/* INFO */
)) return;
const t = this.formatMessage(1, e);
this.safeConsoleCall("log", t, ...r);
}
/**
* Warning level logging
*/
warn(e, ...r) {
if (!this.shouldLog(
2
/* WARN */
)) return;
const t = this.formatMessage(2, e);
this.safeConsoleCall("warn", t, ...r);
}
/**
* Error level logging
*/
error(e, ...r) {
if (!this.shouldLog(
3
/* ERROR */
)) return;
const t = this.formatMessage(3, e);
this.safeConsoleCall("error", t, ...r);
}
/**
* Update logger configuration
*/
configure(e) {
this.config = { ...this.config, ...e };
}
/**
* Set log level
*/
setLevel(e) {
this.config.level = e;
}
/**
* Get current log level
*/
getLevel() {
return this.config.level;
}
/**
* Create a child logger with a prefix
*/
child(e) {
const r = this.config.prefix ? `${this.config.prefix}:${e}` : e;
return new C({
...this.config,
prefix: r
});
}
}
const i = new C(), _ = (n) => new C(n);
class T {
constructor() {
p(this, "subscribers");
this.subscribers = /* @__PURE__ */ new Set();
}
depend(e) {
try {
e && this.subscribers.add(e);
} catch (r) {
throw i.error(
`Dependency: Failed to add dependency: ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
notify() {
try {
this.subscribers.forEach((e) => {
try {
e();
} catch (r) {
throw i.error(
`Dependency: Failed to notify subscriber: ${r instanceof Error ? r.message : String(r)}`
), r;
}
});
} catch (e) {
throw i.error(
`Dependency: Failed to notify subscribers: ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
remove(e) {
try {
this.subscribers.delete(e);
} catch (r) {
throw i.error(
`Dependency: Failed to remove dependency: ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
clear() {
try {
this.subscribers.clear();
} catch (e) {
throw i.error(
`Dependency: Failed to clear dependencies: ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
get getSubscribers() {
return this.subscribers;
}
}
const D = /* @__PURE__ */ new WeakMap();
let N = null, G = !1;
const y = [];
function E(n, e) {
try {
const r = D.get(n);
if (r && r[e]) {
const t = r[e].getSubscribers;
t.size > 0 && t.forEach((o) => {
if (!G) {
if (y.includes(o)) {
const a = `Circular dependency detected: Effect "${o.name || "anonymous"}" triggered itself. Stack trace: ${y.map((d) => d.name || "anonymous").join(" -> ")}`;
i.error(`Effect: ${a}`);
const g = [...y, o].map(
(d) => d.name || "anonymous"
);
throw i.error(
`Effect: Circular dependency path: ${g.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;
}
}
});
}
} catch (r) {
throw i.error(
`Effect: Trigger failed for property "${String(e)}": ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
function $(n, e) {
try {
let r = D.get(n);
r || D.set(n, r = {}), r[e] || (r[e] = new T()), N && r[e].depend(N);
} catch (r) {
throw i.error(
`Effect: Failed to track dependency for property "${String(e)}": ${r instanceof Error ? r.message : String(r)}`
), r;
}
}
function A(n) {
const e = () => {
if (y.includes(n)) {
const r = `Circular dependency detected: Effect "${n.name || "anonymous"}" triggered itself. Stack trace: ${y.map((s) => s.name || "anonymous").join(" -> ")}`;
i.error(`Effect: ${r}`);
const t = [...y, n].map(
(s) => s.name || "anonymous"
);
throw i.error(
`Effect: Circular dependency path: ${t.join(" -> ")}`
), i.error(
`Effect: Current effect stack depth: ${y.length}`
), new Error(r);
}
try {
y.push(n), N = n, n();
} catch (r) {
throw i.error(
`Effect: Effect "${n.name || "anonymous"}" failed: ${r instanceof Error ? r.message : String(r)}`
), i.error(
`Effect: Effect stack at failure: ${y.map((t) => t.name || "anonymous").join(" -> ")}`
), r;
} finally {
y.pop(), N = y[y.length - 1] || null;
}
};
return e(), e;
}
const U = (n) => {
try {
let e, r = !0;
const t = A(() => {
try {
e = n(), r = !1;
} catch (o) {
throw i.error(
`Computed: Failed to compute value: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}), s = {
get value() {
try {
return r && t(), $(s, "value"), e;
} catch (o) {
throw i.error(
`Computed: Failed to get computed value: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}
};
return s;
} catch (e) {
throw i.error(
`Computed: Failed to create computed value: ${e instanceof Error ? e.message : String(e)}`
), e;
}
};
function K(n) {
return new Proxy(n, {
get(e, r) {
try {
if (r === "size")
return $(e, "size"), e.size;
if (r === "get") {
const t = Reflect.get(e, r);
return (s) => {
try {
const o = t.call(e, s);
return $(e, s), o;
} catch (o) {
throw i.error(
`Reactive: Failed to get collection value for key "${String(s)}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
};
}
if (r === "set" || r === "add" || r === "delete") {
const t = Reflect.get(e, r);
return (...s) => {
try {
const o = t.apply(e, s);
if (E(e, "size"), r === "set") {
const [a] = s;
E(e, a);
}
return o;
} catch (o) {
throw i.error(
`Reactive: Failed to execute collection operation "${String(r)}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
};
}
if (r === "clear") {
const t = Reflect.get(e, r);
return () => {
try {
const s = t.apply(e);
return E(e, "size"), s;
} catch (s) {
throw i.error(
`Reactive: Failed to clear collection: ${s instanceof Error ? s.message : String(s)}`
), s;
}
};
}
return $(e, r), Reflect.get(e, r);
} catch (t) {
throw i.error(
`Reactive: Failed to access collection property "${String(r)}": ${t instanceof Error ? t.message : String(t)}`
), t;
}
}
});
}
function z(n) {
try {
return n instanceof Map || n instanceof Set ? K(n) : new Proxy(n, {
get(e, r, t) {
try {
const s = Reflect.get(e, r, t);
return r === "size" && (e instanceof Map || e instanceof Set) ? ($(e, "size"), s) : ($(e, r), typeof s == "object" && s !== null ? z(s) : s);
} catch (s) {
throw i.error(
`Reactive: Failed to get property "${String(r)}": ${s instanceof Error ? s.message : String(s)}`
), s;
}
},
set(e, r, t, s) {
try {
const o = e[r], a = Reflect.set(e, r, t, s);
return (o !== t || isNaN(o) && isNaN(t)) && E(e, r), a;
} catch (o) {
throw i.error(
`Reactive: Failed to set property "${String(r)}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
},
deleteProperty(e, r) {
try {
const t = r in e, s = Reflect.deleteProperty(e, r);
return t && E(e, r), s;
} catch (t) {
throw i.error(
`Reactive: Failed to delete property "${String(r)}": ${t instanceof Error ? t.message : String(t)}`
), t;
}
},
has(e, r) {
try {
return $(e, r), Reflect.has(e, r);
} catch (t) {
throw i.error(
`Reactive: Failed to check property "${String(r)}" existence: ${t instanceof Error ? t.message : String(t)}`
), t;
}
},
ownKeys(e) {
try {
return $(e, "keys"), Reflect.ownKeys(e);
} catch (r) {
throw i.error(
`Reactive: Failed to get own keys: ${r instanceof Error ? r.message : String(r)}`
), r;
}
},
getOwnPropertyDescriptor(e, r) {
try {
return $(e, r), Reflect.getOwnPropertyDescriptor(e, r);
} catch (t) {
throw i.error(
`Reactive: Failed to get property descriptor for "${String(r)}": ${t instanceof Error ? t.message : String(t)}`
), t;
}
}
});
} catch (e) {
throw i.error(
`Reactive: Failed to create reactive object: ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
const L = (n) => {
try {
return z(n);
} catch (e) {
throw i.error(
`Reactive: Failed to create reactive object: ${e instanceof Error ? e.message : String(e)}`
), e;
}
}, ee = (n, e) => {
try {
return A(() => {
try {
const t = n();
try {
e(t);
} catch (s) {
throw i.error(
`Watch: Failed to execute watch callback: ${s instanceof Error ? s.message : String(s)}`
), s;
}
} catch (t) {
throw i.error(
`Watch: Failed to execute watch source function: ${t instanceof Error ? t.message : String(t)}`
), t;
}
});
} catch (r) {
throw i.error(
`Watch: Failed to create watcher: ${r instanceof Error ? r.message : String(r)}`
), r;
}
}, Q = (n) => {
try {
return new Proxy(n, {
get(r, t, s) {
try {
if (t in r.state)
return Reflect.get(r.state, t);
if (t in r.getters) {
const o = Reflect.get(r.getters, t);
return o && typeof o == "object" && "value" in o ? o.value : o;
}
return t in r.actions ? Reflect.get(r.actions, t) : Reflect.get(r, t, s);
} catch (o) {
throw i.error(
`FlattenStore: Failed to get property "${t}": ${o instanceof Error ? o.message : String(o)}`
), o;
}
},
set(r, t, s, o) {
try {
return t in r.state ? Reflect.set(r.state, t, s) : Reflect.set(r, t, s, o);
} catch (a) {
throw i.error(
`FlattenStore: Failed to set property "${t}": ${a instanceof Error ? a.message : String(a)}`
), a;
}
}
});
} catch (e) {
throw i.error(
`FlattenStore: Failed to create flattened store: ${e instanceof Error ? e.message : String(e)}`
), e;
}
};
function H(n, e) {
let r, t;
const s = (...o) => {
try {
t = o, r && clearTimeout(r), r = setTimeout(() => {
try {
t && (n(...t), t = void 0);
} catch (a) {
throw i.error(
`Debounce: Failed to execute debounced function: ${a instanceof Error ? a.message : String(a)}`
), a;
}
}, e);
} catch (a) {
throw i.error(
`Debounce: Failed to schedule debounced function: ${a instanceof Error ? a.message : String(a)}`
), a;
}
};
return s.flush = () => {
try {
r && (clearTimeout(r), r = void 0), t && (n(...t), t = void 0);
} catch (o) {
throw i.error(
`Debounce: Failed to flush debounced function: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}, s.cancel = () => {
try {
r && (clearTimeout(r), r = void 0), t = void 0;
} catch (o) {
throw i.error(
`Debounce: Failed to cancel debounced function: ${o instanceof Error ? o.message : String(o)}`
), o;
}
}, s;
}
function X(n, e, r, t, s) {
const {
adapter: o,
serialize: a = JSON.stringify,
deserialize: g = JSON.parse,
debounceMs: d = 300,
include: l,
exclude: c,
transform: h,
version: k = 1,
migrations: P = {},
onError: w,
validator: M
} = t;
let v = !1, F = !1, b = null;
const j = H(async () => {
if (!v)
try {
const u = n();
let f = { ...u };
if (l && (f = l.reduce((S, x) => (x in u && (S[x] = u[x]), S), {})), c && c.forEach((S) => delete f[S]), h != null && h.out && (f = h.out(f)), M && !M(f))
throw new Error("Data validation failed before saving");
const m = {
data: f,
version: k,
timestamp: Date.now(),
storeName: s || "anonymous"
}, R = a(m);
await o.write(R);
} catch (u) {
const f = u instanceof Error ? u : new Error(String(u));
w == null || w(f, "write"), console.warn(`Failed to persist state: ${f.message}`);
}
}, d), I = async () => {
try {
v = !0;
const u = await o.read();
if (u) {
const f = g(u);
let { data: m, version: R } = f;
if (R < k)
for (let S = R + 1; S <= k; S++)
P[S] && (m = P[S](m));
if (h != null && h.in && (m = h.in(m)), M && !M(m))
throw new Error("Loaded data failed validation");
e(m), r();
}
F = !0;
} catch (u) {
const f = u instanceof Error ? u : new Error(String(u));
w == null || w(f, "read"), console.warn(
`Failed to load persisted state: ${f.message}`
), F = !0;
} finally {
v = !1;
}
}, J = () => {
o.subscribe && !b && (b = o.subscribe((u) => {
if (!v && F) {
v = !0;
try {
const f = g(u);
let m = f.data || f;
h != null && h.in && (m = h.in(m)), e(m), r();
} catch (f) {
console.warn("Cross-tab sync failed:", f);
} finally {
v = !1;
}
}
}));
};
return I().then(() => {
J();
}), {
async save() {
await j.flush();
},
load: I,
async clear() {
try {
await o.remove(), b && (b(), b = null);
} catch (u) {
const f = u instanceof Error ? u : new Error(String(u));
throw w == null || w(f, "remove"), f;
}
},
getAdapter() {
return o;
},
isRehydrated() {
return F;
}
};
}
class Y {
constructor(e = []) {
p(this, "migrations", /* @__PURE__ */ new Map());
e.forEach((r) => {
this.addMigration(r.version, r.migrate);
});
}
/**
* Add a migration function for a specific version
*/
addMigration(e, r) {
this.migrations.set(e, r), i.log(`Migration: Added migration for version ${e}`);
}
/**
* Remove a migration for a specific version
*/
removeMigration(e) {
const r = this.migrations.has(e);
this.migrations.delete(e), r ? i.log(`Migration: Removed migration for version ${e}`) : i.warn(
`Migration: No migration found for version ${e} to remove`
);
}
/**
* Get all available migration versions
*/
getVersions() {
return Array.from(this.migrations.keys()).sort((e, r) => e - r);
}
/**
* Check if a migration exists for a specific version
*/
hasMigration(e) {
return this.migrations.has(e);
}
/**
* Get the highest migration version
*/
getHighestVersion() {
const e = this.getVersions();
return e.length > 0 ? Math.max(...e) : 0;
}
/**
* Apply migrations from current version to target version
*/
migrate(e, r, t) {
if (r === t)
return e;
if (r > t)
throw new Error(
`Cannot migrate from version ${r} to ${t} (downgrade not supported)`
);
i.log(
`Migration: Starting migration from version ${r} to ${t}`
);
let s = e;
for (let o = r + 1; o <= t; o++) {
const a = this.migrations.get(o);
if (a)
try {
i.log(
`Migration: Applying migration for version ${o}`
), s = a(s), i.log(
`Migration: Successfully applied migration for version ${o}`
);
} catch (g) {
const d = `Migration ${o} failed: ${g instanceof Error ? g.message : String(g)}`;
throw i.warn(d), new Error(d);
}
else
i.log(
`Migration: No migration found for version ${o}, skipping`
);
}
return i.log(
`Migration: Successfully completed migration from version ${r} to ${t}`
), s;
}
/**
* Validate that all migrations can be applied successfully
*/
validateMigrations() {
i.log("Migration: Starting migration validation...");
const e = [], r = this.getVersions();
if (r.length === 0)
return i.log("Migration: No migrations to validate"), { valid: !0, errors: [] };
i.log(`Migration: Validating ${r.length} migrations`);
const t = { test: !0 };
for (let o = 0; o < r.length - 1; o++) {
const a = r[o], g = r[o + 1];
try {
i.log(
`Migration: Testing migration from version ${a} to ${g}`
), this.migrate(t, a, g), i.log(
`Migration: Successfully validated migration from version ${a} to ${g}`
);
} catch (d) {
const l = `Migration from ${a} to ${g} failed: ${d instanceof Error ? d.message : String(d)}`;
i.warn(l), e.push(l);
}
}
const s = e.length === 0;
return s ? i.log("Migration: All migrations validated successfully") : i.warn(
`Migration: Validation failed with ${e.length} errors`
), {
valid: s,
errors: e
};
}
}
function re(n) {
const e = new Y();
return n.migrations ? (i.log(
`Migration: Creating migration manager with ${Object.keys(n.migrations).length} migrations`
), Object.entries(n.migrations).forEach(([r, t]) => {
const s = parseInt(r, 10);
isNaN(s) ? i.warn(
`Migration: Invalid version number "${r}", skipping`
) : e.addMigration(s, t);
})) : i.log("Migration: Creating migration manager with no migrations"), e;
}
const te = {
/**
* Add a new property with default value
*/
addProperty(n, e) {
return (r) => (i.log(
`Migration: Added property "${String(n)}" with default value:`,
e
), {
...r,
[n]: e
});
},
/**
* Remove a property
*/
removeProperty(n) {
return (e) => {
const { [n]: r, ...t } = e;
return i.log(
`Migration: Removed property "${String(n)}" with value:`,
r
), t;
};
},
/**
* Rename a property
*/
renameProperty(n, e) {
return (r) => {
const { [n]: t, ...s } = r;
return i.log(
`Migration: Renamed property "${String(n)}" to "${String(e)}" with value:`,
t
), {
...s,
[e]: t
};
};
},
/**
* Transform a property value
*/
transformProperty(n, e) {
return (r) => {
const t = r[n], s = e(t);
return i.log(
`Migration: Transformed property "${String(n)}" from:`,
t,
"to:",
s
), {
...r,
[n]: s
};
};
}
};
class oe {
constructor(e) {
if (this.key = e, typeof window > "u" || !window.localStorage)
throw new Error(
"LocalStorage is not available in this environment"
);
}
read() {
try {
const e = localStorage.getItem(this.key);
return e ? JSON.parse(e) : null;
} catch (e) {
return i.warn(
`Failed to read from localStorage: ${e instanceof Error ? e.message : String(e)}`
), null;
}
}
write(e) {
try {
localStorage.setItem(this.key, JSON.stringify(e));
} catch (r) {
throw r instanceof Error && r.name === "QuotaExceededError" && i.warn("LocalStorage quota exceeded"), r;
}
}
remove() {
localStorage.removeItem(this.key);
}
subscribe(e) {
const r = (t) => {
if (t.key === this.key && t.newValue)
try {
e(JSON.parse(t.newValue));
} catch (s) {
i.warn("Failed to parse storage event data:", s);
}
};
return window.addEventListener("storage", r), () => window.removeEventListener("storage", r);
}
}
class ne {
constructor(e) {
if (this.key = e, typeof window > "u" || !window.sessionStorage)
throw new Error(
"SessionStorage is not available in this environment"
);
}
read() {
try {
const e = sessionStorage.getItem(this.key);
return e ? JSON.parse(e) : null;
} catch (e) {
return i.warn(
`Failed to read from sessionStorage: ${e instanceof Error ? e.message : String(e)}`
), null;
}
}
write(e) {
try {
sessionStorage.setItem(this.key, JSON.stringify(e));
} catch (r) {
throw r instanceof Error && r.name === "QuotaExceededError" && i.warn("SessionStorage quota exceeded"), r;
}
}
remove() {
sessionStorage.removeItem(this.key);
}
subscribe(e) {
const r = (t) => {
if (t.key === this.key && t.newValue)
try {
e(JSON.parse(t.newValue));
} catch (s) {
i.warn("Failed to parse storage event data:", s);
}
};
return window.addEventListener("storage", r), () => window.removeEventListener("storage", r);
}
}
class se {
constructor(e, r = "quantajs", t = "stores", s = 1) {
this.key = e, this.dbName = r, this.storeName = t, this.version = s;
}
async read() {
try {
const t = (await this.openDB()).transaction([this.storeName], "readonly").objectStore(this.storeName);
return new Promise((s, o) => {
const a = t.get(this.key);
a.onsuccess = () => {
var g;
return s(((g = a.result) == null ? void 0 : g.data) || null);
}, a.onerror = () => o(a.error);
});
} catch (e) {
return i.warn(
`IndexedDB read failed: ${e instanceof Error ? e.message : String(e)}`
), null;
}
}
async write(e) {
const s = (await this.openDB()).transaction([this.storeName], "readwrite").objectStore(this.storeName);
return new Promise((o, a) => {
const g = {
key: this.key,
data: e,
timestamp: Date.now()
}, d = s.put(g);
d.onsuccess = () => o(), d.onerror = () => a(d.error);
});
}
async remove() {
const t = (await this.openDB()).transaction([this.storeName], "readwrite").objectStore(this.storeName);
return new Promise((s, o) => {
const a = t.delete(this.key);
a.onsuccess = () => s(), a.onerror = () => o(a.error);
});
}
async openDB() {
return new Promise((e, r) => {
const t = indexedDB.open(this.dbName, this.version);
t.onupgradeneeded = () => {
const s = t.result;
s.objectStoreNames.contains(this.storeName) || s.createObjectStore(this.storeName, { keyPath: "key" });
}, t.onsuccess = () => e(t.result), t.onerror = () => r(t.error);
});
}
}
const O = /* @__PURE__ */ new Map(), B = /* @__PURE__ */ new WeakMap(), ie = (n, e) => {
try {
if (O.has(n)) {
const l = `Store with name "${n}" already exists.`;
throw i.error(`Store: ${l}`), new Error(l);
}
const r = e.state(), t = L(r), s = new T(), o = {};
if (e.getters)
for (const l in e.getters)
try {
const c = e.getters[l];
o[l] = U(
() => c(t)
);
} catch (c) {
throw i.error(
`Store: Failed to create getter "${String(l)}" for store "${n}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
let a = null;
if (e.persist)
try {
a = X(
() => t,
(l) => {
try {
for (const c in l)
t[c] !== l[c] && (t[c] = l[c], E(t, c));
} catch (c) {
throw i.error(
`Store: Persistence state update failed for store "${n}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
},
() => s.notify(),
e.persist,
n
);
} catch (l) {
throw i.error(
`Store: Failed to set up persistence for store "${n}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
const g = {
state: t,
getters: o,
actions: {},
subscribe: (l) => {
try {
return s.depend(l), () => {
try {
s.remove(l);
} catch (c) {
i.error(
`Store: Failed to remove subscriber from store "${n}": ${c instanceof Error ? c.message : String(c)}`
);
}
};
} catch (c) {
throw i.error(
`Store: Failed to add subscriber to store "${n}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
},
$reset: () => {
try {
const l = B.get(g);
if (!l) {
const c = `Initial state not found for store "${n}"`;
throw i.error(`Store: ${c}`), new Error(c);
}
for (const c in l)
g.state[c] !== l[c] && (g.state[c] = l[c], E(g.state, c));
for (const c in g.state)
c in l || (delete g.state[c], E(g.state, c));
} catch (l) {
throw i.error(
`Store: Failed to reset store "${n}": ${l instanceof Error ? l.message : String(l)}`
), l;
}
},
$persist: a
};
B.set(g, r);
const d = Q(g);
if (e.actions)
for (const l in e.actions)
try {
const c = e.actions[l];
g.actions[l] = c.bind(
d
);
} catch (c) {
throw i.error(
`Store: Failed to create action "${String(l)}" for store "${n}": ${c instanceof Error ? c.message : String(c)}`
), c;
}
return O.set(n, d), d;
} catch (r) {
throw i.error(
`Store: Failed to create store "${n}": ${r instanceof Error ? r.message : String(r)}`
), r;
}
};
function ae(n) {
try {
const e = O.get(n);
if (!e) {
const r = `Store with name "${n}" does not exist.`;
throw i.error(`Store: ${r}`), new Error(r);
}
return e;
} catch (e) {
throw i.error(
`Store: Failed to retrieve store "${n}": ${e instanceof Error ? e.message : String(e)}`
), e;
}
}
export {
te as CommonMigrations,
se as IndexedDBAdapter,
oe as LocalStorageAdapter,
V as LogLevel,
C as Logger,
Y as MigrationManager,
ne as SessionStorageAdapter,
U as computed,
_ as createLogger,
re as createMigrationManager,
X as createPersistenceManager,
ie as createStore,
i as logger,
L as reactive,
ae as useStore,
ee as watch
};