Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@kikko-land/kikko

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kikko-land/kikko - npm Package Compare versions

Comparing version 0.16.0 to 0.17.0

7

CHANGELOG.md
# @kikko-land/core
## 0.17.0
### Minor Changes
- 15a9a4d: Improve performance & error msg
- a44c084: Add wa-sqlite backend
## 0.16.0

@@ -4,0 +11,0 @@

269

dist/index.es.js

@@ -1,20 +0,5 @@

import { deepEqual as K } from "fast-equals";
import { deepEqual as Z } from "fast-equals";
import { sql as S } from "@kikko-land/boono-sql";
export * from "@kikko-land/boono-sql";
const v = typeof performance < "u" ? () => performance.now() : () => Date.now(), J = (e, t) => {
const {
__state: {
sharedState: { runningState: r, dbName: a }
}
} = e;
if (r.value !== "running")
throw new Error(`Failed to start ${t()}, db ${a} is stopping`);
};
function A() {
let e = "";
const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", r = t.length;
for (let a = 0; a < 32; a++)
e += t.charAt(Math.floor(Math.random() * r));
return e;
}
const v = typeof performance < "u" ? () => performance.now() : () => Date.now();
class E extends Error {

@@ -24,3 +9,3 @@ }

}
const X = (() => {
const j = (() => {
const e = /* @__PURE__ */ new Map();

@@ -35,3 +20,3 @@ let t = !1, r;

else if (r < Date.now()) {
t = !1, r = void 0;
t = !1, r = void 0, console.log("loop stopped");
break;

@@ -41,4 +26,4 @@ }

r = void 0;
for (const [i, { toCall: s, callAfter: d }] of e.entries())
d < Date.now() && (s(), e.delete(i));
for (const [i, s] of e.entries())
s < Date.now() && (i(), e.delete(i));
}

@@ -50,9 +35,6 @@ await new Promise((i) => {

};
return (i, s) => {
const d = A();
return e.set(d, { toCall: i, callAfter: Date.now() + s }), a(), () => {
e.delete(d);
};
};
})(), V = (e, t) => {
return (i, s) => (e.set(i, Date.now() + s), a(), () => {
e.delete(i);
});
})(), M = (e, t) => {
const r = t.deduplicate === void 0 ? !0 : t.deduplicate;

@@ -72,3 +54,3 @@ return {

throw new Error(`reactiveVar ${t.label} is stopped!`);
if (!(r && K(this.__state.value, a))) {
if (!(r && Z(this.__state.value, a))) {
this.__state.value = a;

@@ -88,7 +70,7 @@ for (const i of this.__state.subscriptions)

let s;
const d = (h) => {
const f = (h) => {
s && s(), s = a(h);
};
return this.__state.subscriptions.push(d), i && d(this.__state.value), () => {
this.__state.subscriptions = this.__state.subscriptions.filter((h) => h !== d);
return this.__state.subscriptions.push(f), i && f(this.__state.value), () => {
this.__state.subscriptions = this.__state.subscriptions.filter((h) => h !== f);
};

@@ -99,3 +81,3 @@ },

`waitUntil for reactiveVar ${t.label} is stopped due to stop signal`
), d = new E(
), f = new E(
`waitUntil for reactiveVar ${t.label} is timed out`

@@ -107,6 +89,6 @@ ), h = new B(

throw new Error(`reactiveVar ${t.label} is stopped!`);
return a(this.value) ? Promise.resolve() : new Promise((l, m) => {
return a(this.value) ? Promise.resolve() : new Promise((l, d) => {
var p;
let n = !1, u = [];
const f = () => {
const m = () => {
if (!n) {

@@ -122,13 +104,13 @@ for (const T of u)

this.subscribe((T) => {
!a(T) || (f(), l());
!a(T) || (m(), l());
}, !0)
), n || o(
((p = i == null ? void 0 : i.stopIf) == null ? void 0 : p.subscribe((T) => {
!T || (f(), m(s));
!T || (m(), d(s));
}, !0)) || (() => {
})
), !n && ((i == null ? void 0 : i.timeout) === void 0 || typeof (i == null ? void 0 : i.timeout) == "number")) {
const T = X(
const T = j(
() => {
f(), m(d);
m(), d(f);
},

@@ -143,3 +125,3 @@ (i == null ? void 0 : i.timeout) === void 0 ? 12e4 : i.timeout

const T = () => {
f(), m(h);
m(), d(h);
};

@@ -161,3 +143,19 @@ this.__state.onStop.push(T), o(() => {

};
}, M = (e) => {
}, W = (e, t) => {
const {
__state: {
sharedState: { runningState: r, dbName: a }
}
} = e;
if (r.value !== "running")
throw new Error(`Failed to start ${t()}, db ${a} is stopping`);
};
function R() {
let e = "";
const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", r = t.length;
for (let a = 0; a < 32; a++)
e += t.charAt(Math.floor(Math.random() * r));
return e;
}
const P = (e) => {
const { current: t, queue: r } = e;

@@ -169,3 +167,3 @@ return `Current running transaction job: ${JSON.stringify(

)}, queue of transaction jobs: ${JSON.stringify(r, null, 2)}`;
}, ue = () => V(
}, ue = () => M(
{

@@ -176,3 +174,3 @@ queue: [],

{ label: "jobsState", deduplicate: !1 }
), Z = (e) => ({ id: e }), j = async (e, t) => {
), L = (e) => ({ id: e }), J = async (e, t) => {
const { current: r, queue: a } = e.value;

@@ -182,4 +180,4 @@ if (r || a.length > 0) {

(s) => {
var d;
return ((d = s.current) == null ? void 0 : d.id) === t.id;
var f;
return ((f = s.current) == null ? void 0 : f.id) === t.id;
},

@@ -199,5 +197,5 @@ {

...e.value,
queue: e.value.queue.filter((d) => d.id !== t.id)
queue: e.value.queue.filter((f) => f.id !== t.id)
}, s instanceof E ? new E(
`Timeout error while transaction job acquire: '${s.message}'. Is it a dead lock? ${M(
`Timeout error while transaction job acquire: '${s.message}'. Is it a dead lock? ${P(
e.value

@@ -216,3 +214,3 @@ )}, jobToAcquire: ${JSON.stringify(t, null, 2)}`

throw new Error(
`Can't release job that is not currently running, ${M(
`Can't release job that is not currently running, ${P(
e.value

@@ -233,17 +231,16 @@ )}, toRelease: ${JSON.stringify(t, null, 2)}`

}
}, W = async (e, t) => {
}, z = async (e, t) => {
let r;
if (t) {
const a = Z(t.transactionId);
t.containsTransactionStart ? await j(e, a) : await e.waitTill((i) => {
const a = L(t.transactionId);
t.containsTransactionStart ? await J(e, a) : await e.waitTill((i) => {
var s;
return ((s = i.current) == null ? void 0 : s.id) === a.id;
}), r = a;
} else
await e.waitTill((a) => {
var i;
return ((i = a.current) == null ? void 0 : i.id) === void 0;
});
} else {
const a = L(R());
await J(e, a), r = a;
}
return r;
}, P = (e, t, r) => {
}, G = (e, t, r) => {
if (t && (!r || (r == null ? void 0 : r.containsTransactionFinish) || (r == null ? void 0 : r.containsTransactionRollback)) && O(e, t), !t && r)

@@ -253,3 +250,3 @@ throw new Error("Transaction job was not started, nothing to release!");

async run(t, r, a) {
const i = v(), s = await W(t, a), h = v() - i;
const i = v(), s = await z(t, a), h = v() - i;
try {

@@ -261,7 +258,7 @@ return {

const l = [];
for (const m of r.values)
for (const d of r.values)
try {
l.push(await e.execUsual(m));
l.push(await e.execUsual(d));
} catch (n) {
throw n instanceof Error && (n.message = `Error while executing query: ${m.text} - ${n.message}`), n;
throw n instanceof Error && (n.message = `Error(${n.message}) while executing query: ${d.text.slice(0, 500)}`), n;
}

@@ -278,3 +275,3 @@ return l;

} catch (l) {
throw l instanceof Error && (l.message = `Error while executing query: ${r.query.text} - ${l.message}`), l;
throw l instanceof Error && (l.message = `Error(${l.message}) while executing query: ${r.query.text.slice(0, 500)}`), l;
}

@@ -295,3 +292,3 @@ })(),

} finally {
P(t, s, a);
G(t, s, a);
}

@@ -301,3 +298,3 @@ }

async run(t, r, a) {
const i = v(), s = await W(t, a), h = v() - i;
const i = v(), s = await z(t, a), h = v() - i;
try {

@@ -310,4 +307,4 @@ return {

return e.execUsual(l);
} catch (m) {
throw m instanceof Error && (m.message = `Error while executing query: ${l.text} - ${m.message}`), m;
} catch (d) {
throw d instanceof Error && (d.message = `Error(${d.message}) while executing query: ${l.text.slice(0, 500)}`), d;
}

@@ -318,3 +315,3 @@ }) : e.execUsualBatch(r.values);

} catch (l) {
throw l instanceof Error && (l.message = `Error while executing query: ${r.query.text} - ${l.message}`), l;
throw l instanceof Error && (l.message = `Error(${l.message}) while executing query: ${r.query.text.slice(0, 500)}`), l;
}

@@ -335,3 +332,3 @@ })(),

} finally {
P(t, s, a);
G(t, s, a);
}

@@ -345,8 +342,8 @@ }

}
const L = (e, t) => {
const U = (e, t) => {
if (!e.__state.localState.transactionState.current)
throw new Error("Not in transaction.");
const r = e.__state.localState.transactionState.current, a = [], i = (s) => (d, h) => {
const r = e.__state.localState.transactionState.current, a = [], i = (s) => (f, h) => {
if (r.id === h.id) {
t(s, d, r);
t(s, f, r);
for (const c of a)

@@ -384,3 +381,3 @@ c();

}
const re = (e) => e.filter((t) => t !== null), ae = (e) => e.reduce((t, r) => t + r, 0), U = (e) => ae(re(e)), ie = async ({
const re = (e) => e.filter((t) => t !== null), ae = (e) => e.reduce((t, r) => t + r, 0), D = (e) => ae(re(e)), ie = async ({
db: e,

@@ -394,5 +391,5 @@ queries: t,

sharedState: { dbBackend: i, logFns: s },
sharedState: d
sharedState: f
} = e.__state;
if (a.current || J(e, () => JSON.stringify(t)), r && ((p = a.current) == null ? void 0 : p.id) !== r.transactionId)
if (a.current || W(e, () => JSON.stringify(t)), r && ((p = a.current) == null ? void 0 : p.id) !== r.transactionId)
throw new Error(

@@ -455,14 +452,14 @@ `Cannot run queries in a transaction that is not the current one. Transaction opts: ${JSON.stringify(

}
}, { result: m, performance: n, textQueries: u } = await l(), f = v();
}, { result: d, performance: n, textQueries: u } = await l(), m = v();
if (!e.__state.localState.suppressLog) {
const w = (g, x) => `${g}=${(x / 1e3).toFixed(4)}`, _ = (() => {
if (t.type === "prepared") {
const g = m[0], x = [
const g = d[0], x = [
g.performance.prepareTime !== void 0 ? w(
"prepareTime",
U(m.map((b) => b.performance.prepareTime))
D(d.map((b) => b.performance.prepareTime))
) : "",
g.performance.execTime !== void 0 ? w(
"execTime",
U(m.map((b) => b.performance.execTime))
D(d.map((b) => b.performance.execTime))
) : ""

@@ -478,12 +475,12 @@ ].filter((b) => b.length !== 0).join(" ");

} else
return m.map(({ performance: g }, x) => {
return d.map(({ performance: g }, x) => {
const b = [
g.prepareTime !== void 0 ? w("prepareTime", g.prepareTime) : "",
g.execTime !== void 0 ? w("execTime", g.execTime) : ""
].filter((R) => R.length !== 0).join(" ");
return [u[x].slice(0, 1e3), b].filter((R) => R.length !== 0).join(" ");
].filter((A) => A.length !== 0).join(" ");
return [u[x].slice(0, 1e3), b].filter((A) => A.length !== 0).join(" ");
});
})(), y = (() => _.length === 1 ? _[0] : `
` + _.map((g) => `{${g}}`).join(`
`))(), Y = `%c[${e.__state.sharedState.dbName}] ` + [
`))(), K = `%c[${e.__state.sharedState.dbName}] ` + [
(T = a.current) != null && T.id ? `[tr_id=${($ = a.current) == null ? void 0 : $.id.substring(0, 6)}]` : "",

@@ -494,8 +491,8 @@ y,

(n == null ? void 0 : n.blockTime) !== void 0 ? `blockTime=${(n.blockTime / 1e3).toFixed(4)}` : "",
`totalTime=${((f - h) / 1e3).toFixed(4)}`
].filter((g) => g.length !== 0).join(" "), H = (I = d.transactionsStates.byId[(C = (F = a.current) == null ? void 0 : F.id) != null ? C : ""]) == null ? void 0 : I.i;
s.logQuery(Y, H);
`totalTime=${((m - h) / 1e3).toFixed(4)}`
].filter((g) => g.length !== 0).join(" "), X = (I = f.transactionsStates.byId[(C = (F = a.current) == null ? void 0 : F.id) != null ? C : ""]) == null ? void 0 : I.i;
s.logQuery(K, X);
}
const o = (N = d.transactionsStates.byId[(q = (Q = a.current) == null ? void 0 : Q.id) != null ? q : ""]) == null ? void 0 : N.performance;
return o && (m.some((w) => w.performance.execTime !== void 0) && (o.execTime === void 0 && (o.execTime = 0), o.execTime += m.reduce(
const o = (N = f.transactionsStates.byId[(q = (Q = a.current) == null ? void 0 : Q.id) != null ? q : ""]) == null ? void 0 : N.performance;
return o && (d.some((w) => w.performance.execTime !== void 0) && (o.execTime === void 0 && (o.execTime = 0), o.execTime += d.reduce(
(w, _) => {

@@ -506,3 +503,3 @@ var y;

0
)), m.some((w) => w.performance.prepareTime !== void 0) && (o.prepareTime === void 0 && (o.prepareTime = 0), o.prepareTime += m.reduce(
)), d.some((w) => w.performance.prepareTime !== void 0) && (o.prepareTime === void 0 && (o.prepareTime = 0), o.prepareTime += d.reduce(
(w, _) => {

@@ -513,3 +510,3 @@ var y;

0
)), n.sendTime && (o.sendTime || (o.sendTime = 0), o.sendTime += n.sendTime), n.receiveTime && (o.receiveTime || (o.receiveTime = 0), o.receiveTime += n.receiveTime), n.blockTime && (o.blockTime || (o.blockTime = 0), o.blockTime += n.blockTime)), { db: e, result: m, performance: n, queries: t };
)), n.sendTime && (o.sendTime || (o.sendTime = 0), o.sendTime += n.sendTime), n.receiveTime && (o.receiveTime || (o.receiveTime = 0), o.receiveTime += n.receiveTime), n.blockTime && (o.blockTime || (o.blockTime = 0), o.blockTime += n.blockTime)), { db: e, result: d, performance: n, queries: t };
}, k = async (e, t, r) => {

@@ -522,4 +519,4 @@ const a = [

for (const s of a) {
const d = i;
i = (h) => s({ ...h, next: d });
const f = i;
i = (h) => s({ ...h, next: f });
}

@@ -538,4 +535,4 @@ return await i({

};
let z = 0;
const G = (e, t, r) => {
let Y = 0;
const H = (e, t, r) => {
const a = e.__state.sharedState.logFns;

@@ -561,5 +558,5 @@ if (e.__state.localState.suppressLog)

localState: { transactionState: a },
sharedState: { eventsEmitter: i, transactionsStates: s, dbBackend: d, logFns: h }
sharedState: { eventsEmitter: i, transactionsStates: s, dbBackend: f, logFns: h }
} = e.__state;
if (d.isUsualTransactionDisabled)
if (f.isUsualTransactionDisabled)
throw new Error(

@@ -570,5 +567,5 @@ "Usual transactions are disabled for this type of backend. Please, use atomic transactions instead."

return await r(e);
J(e, () => "transaction");
W(e, () => "transaction");
const c = {
id: A(),
id: R(),
type: "async"

@@ -586,4 +583,4 @@ };

};
const l = v(), m = {
i: z++,
const l = v(), d = {
i: Y++,
current: c,

@@ -600,3 +597,3 @@ performance: {

};
s.byId[c.id] = m;
s.byId[c.id] = d;
try {

@@ -657,3 +654,3 @@ await i.emit("transactionWillStart", e, c), await k(

} finally {
m.performance.totalTime = v() - l, G(e, c.id, m.performance), delete s.byId[c.id];
d.performance.totalTime = v() - l, H(e, c.id, d.performance), delete s.byId[c.id];
}

@@ -678,3 +675,3 @@ }, se = () => ({

localState: { transactionState: a },
sharedState: { eventsEmitter: i, transactionsStates: s, dbBackend: d, logFns: h }
sharedState: { eventsEmitter: i, transactionsStates: s, dbBackend: f, logFns: h }
} = e.__state;

@@ -685,3 +682,3 @@ if (a.current)

);
const { inputQueries: c, afterCommits: l, afterRollbacks: m } = await (async () => {
const { inputQueries: c, afterCommits: l, afterRollbacks: d } = await (async () => {
if (Array.isArray(r))

@@ -702,6 +699,6 @@ return {

})(), n = {
id: A(),
id: R(),
type: "atomic"
}, u = {
i: z++,
i: Y++,
current: n,

@@ -728,4 +725,4 @@ performance: {

}, s.byId[n.id] = u;
const f = v(), o = [];
d.isAtomicRollbackCommitDisabled || o.push(S`BEGIN ${S.raw(t.toUpperCase())} TRANSACTION`), o.push(...c.map((p) => p.toSql())), d.isAtomicRollbackCommitDisabled || o.push(S`COMMIT`);
const m = v(), o = [];
f.isAtomicRollbackCommitDisabled || o.push(S`BEGIN ${S.raw(t.toUpperCase())} TRANSACTION`), o.push(...c.map((p) => p.toSql())), f.isAtomicRollbackCommitDisabled || o.push(S`COMMIT`);
try {

@@ -753,3 +750,3 @@ await i.emit("transactionWillStart", e, n), await i.emit("transactionStarted", e, n), await k(

try {
for (const T of m)
for (const T of d)
T();

@@ -761,5 +758,5 @@ } catch (T) {

} finally {
u.performance.totalTime = v() - f, G(e, n.id, u.performance), delete s.byId[n.id];
u.performance.totalTime = v() - m, H(e, n.id, u.performance), delete s.byId[n.id];
}
}, D = ["yellow", "cyan", "magenta"], pe = async ({
}, V = ["yellow", "cyan", "magenta"], pe = async ({
dbName: e,

@@ -772,5 +769,5 @@ plugins: t,

}) => {
const d = s || {
logQuery: (u, f) => {
const o = typeof f == "number" ? D[f % D.length] : void 0;
const f = s || {
logQuery: (u, m) => {
const o = typeof m == "number" ? V[m % V.length] : void 0;
console.debug(

@@ -783,4 +780,4 @@ ...o ? [

},
logError: (u, f) => {
console.error(u, f);
logError: (u, m) => {
console.error(u, m);
},

@@ -793,3 +790,3 @@ logTrFinish: (u) => {

}
}, h = V(
}, h = M(
"running",

@@ -802,3 +799,3 @@ { label: "runningState" }

sharedState: {
clientId: A(),
clientId: R(),
dbBackend: c,

@@ -809,3 +806,3 @@ dbName: e,

transactionsStates: { byId: {} },
logFns: d
logFns: f
},

@@ -818,7 +815,7 @@ localState: {

},
runInTransaction(u, f) {
return ne(this, (f == null ? void 0 : f.type) || "deferred", u);
runInTransaction(u, m) {
return ne(this, (m == null ? void 0 : m.type) || "deferred", u);
},
async runInAtomicTransaction(u, f) {
return await oe(this, (f == null ? void 0 : f.type) || "deferred", u);
async runInAtomicTransaction(u, m) {
return await oe(this, (m == null ? void 0 : m.type) || "deferred", u);
},

@@ -834,21 +831,21 @@ async runQueries(u) {

},
async runPreparedQuery(u, f) {
async runPreparedQuery(u, m) {
return (await k(this, {
type: "prepared",
query: u,
preparedValues: f
preparedValues: m
})).result.map(({ rows: p }) => p);
},
runAfterTransactionCommitted(u) {
return L(this, (f, o, p) => {
f === "committed" && u(o, p);
return U(this, (m, o, p) => {
m === "committed" && u(o, p);
});
},
runAfterTransactionRollbacked(u) {
L(l, (f, o, p) => {
f === "rollbacked" && u(o, p);
U(l, (m, o, p) => {
m === "rollbacked" && u(o, p);
});
}
};
let m = l;
let d = l;
const n = () => l.__state.sharedState.runningState.value;

@@ -858,4 +855,4 @@ if (n() !== "running" || (await c.initialize(), n() !== "running"))

for (const u of t || [])
m = u(m);
return await l.__state.sharedState.eventsEmitter.emit("initialized", l), m;
d = u(d);
return await l.__state.sharedState.eventsEmitter.emit("initialized", l), d;
}, he = async (e) => {

@@ -885,4 +882,4 @@ e.__state.sharedState.runningState.value = "stopping", await e.__state.sharedState.dbBackend.stop(), e.__state.sharedState.runningState.value = "stopped", queueMicrotask(() => {

E as TimeoutError,
j as acquireJob,
W as acquireWithTrJobOrWait,
J as acquireJob,
z as acquireWithTrJobOrWait,
me as buildAsyncQueryRunner,

@@ -893,6 +890,6 @@ fe as buildSyncQueryRunner,

ue as initJobsState,
A as makeId,
V as reactiveVar,
R as makeId,
M as reactiveVar,
O as releaseJob,
P as releaseTrJobIfPossible,
G as releaseTrJobIfPossible,
he as stopDb,

@@ -899,0 +896,0 @@ Te as suppressLog,

@@ -1,4 +0,4 @@

(function(h,$){typeof exports=="object"&&typeof module<"u"?$(exports,require("fast-equals"),require("@kikko-land/boono-sql")):typeof define=="function"&&define.amd?define(["exports","fast-equals","@kikko-land/boono-sql"],$):(h=typeof globalThis<"u"?globalThis:h||self,$(h.core={},h.fastEquals,h.boonoSql))})(this,function(h,$,S){"use strict";const v=typeof performance<"u"?()=>performance.now():()=>Date.now(),N=(e,t)=>{const{__state:{sharedState:{runningState:r,dbName:a}}}=e;if(r.value!=="running")throw new Error(`Failed to start ${t()}, db ${a} is stopping`)};function R(){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=t.length;for(let a=0;a<32;a++)e+=t.charAt(Math.floor(Math.random()*r));return e}class E extends Error{}class C extends Error{}const j=(()=>{const e=new Map;let t=!1,r;const a=async()=>{if(!t)for(t=!0;t;){if(e.size===0){if(!r)r=Date.now()+1e4;else if(r<Date.now()){t=!1,r=void 0;break}}else{r=void 0;for(const[i,{toCall:s,callAfter:d}]of e.entries())d<Date.now()&&(s(),e.delete(i))}await new Promise(i=>{setTimeout(()=>i(),1e3)})}};return(i,s)=>{const d=R();return e.set(d,{toCall:i,callAfter:Date.now()+s}),a(),()=>{e.delete(d)}}})(),I=(e,t)=>{const r=t.deduplicate===void 0?!0:t.deduplicate;return{__state:{subscriptions:[],value:e,isStopped:!1,onStop:[]},get isStopped(){return this.__state.isStopped},set value(a){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);if(!(r&&$.deepEqual(this.__state.value,a))){this.__state.value=a;for(const i of this.__state.subscriptions)i(a)}},get value(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return this.__state.value},subscribe(a,i=!0){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);let s;const d=T=>{s&&s(),s=a(T)};return this.__state.subscriptions.push(d),i&&d(this.__state.value),()=>{this.__state.subscriptions=this.__state.subscriptions.filter(T=>T!==d)}},waitTill(a,i){const s=new C(`waitUntil for reactiveVar ${t.label} is stopped due to stop signal`),d=new E(`waitUntil for reactiveVar ${t.label} is timed out`),T=new C(`waitUntil for reactiveVar ${t.label} is stopped due to reactive var stop`);if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return a(this.value)?Promise.resolve():new Promise((l,m)=>{var p;let n=!1,u=[];const f=()=>{if(!n){for(const w of u)w();n=!0,u=[]}},o=w=>{n?w():u.push(w)};if(n||o(this.subscribe(w=>{!a(w)||(f(),l())},!0)),n||o(((p=i==null?void 0:i.stopIf)==null?void 0:p.subscribe(w=>{!w||(f(),m(s))},!0))||(()=>{})),!n&&((i==null?void 0:i.timeout)===void 0||typeof(i==null?void 0:i.timeout)=="number")){const w=j(()=>{f(),m(d)},(i==null?void 0:i.timeout)===void 0?12e4:i.timeout);o(()=>{w()})}if(!n){const w=()=>{f(),m(T)};this.__state.onStop.push(w),o(()=>{this.__state.onStop=this.__state.onStop.filter(F=>F!==w)})}})},stop(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is already stopped!`);this.__state.subscriptions=[];for(const a of this.__state.onStop)a();this.__state.onStop=[],this.__state.isStopped=!0}}},L=e=>{const{current:t,queue:r}=e;return`Current running transaction job: ${JSON.stringify(t,null,2)}, queue of transaction jobs: ${JSON.stringify(r,null,2)}`},O=()=>I({queue:[],current:void 0},{label:"jobsState",deduplicate:!1}),ee=e=>({id:e}),B=async(e,t)=>{const{current:r,queue:a}=e.value;if(r||a.length>0){const i=e.waitTill(s=>{var d;return((d=s.current)==null?void 0:d.id)===t.id},{timeout:12e4});e.value={queue:[...a,t],current:r};try{await i}catch(s){throw e.value={...e.value,queue:e.value.queue.filter(d=>d.id!==t.id)},s instanceof E?new E(`Timeout error while transaction job acquire: '${s.message}'. Is it a dead lock? ${L(e.value)}, jobToAcquire: ${JSON.stringify(t,null,2)}`):s}}else e.value={queue:[],current:t}},D=(e,t)=>{const{current:r,queue:a}=e.value;if((r==null?void 0:r.id)!==t.id)throw new Error(`Can't release job that is not currently running, ${L(e.value)}, toRelease: ${JSON.stringify(t,null,2)}`);e.value={queue:a.slice(1),current:a[0]}},te=async e=>{try{return e.waitTill(({queue:t,current:r})=>t.length===0&&r===void 0,{timeout:12e4})}catch(t){throw t instanceof E?new E(`Timeout error while awaiting all jobs done: '${t.message}'. Is it a dead lock?`):t}},q=async(e,t)=>{let r;if(t){const a=ee(t.transactionId);t.containsTransactionStart?await B(e,a):await e.waitTill(i=>{var s;return((s=i.current)==null?void 0:s.id)===a.id}),r=a}else await e.waitTill(a=>{var i;return((i=a.current)==null?void 0:i.id)===void 0});return r},Q=(e,t,r)=>{if(t&&(!r||(r==null?void 0:r.containsTransactionFinish)||(r==null?void 0:r.containsTransactionRollback))&&D(e,t),!t&&r)throw new Error("Transaction job was not started, nothing to release!")},re=e=>({async run(t,r,a){const i=v(),s=await q(t,a),T=v()-i;try{return{result:await(async()=>{if(r.type==="usual")if("execUsual"in e){const l=[];for(const m of r.values)try{l.push(await e.execUsual(m))}catch(n){throw n instanceof Error&&(n.message=`Error while executing query: ${m.text} - ${n.message}`),n}return l}else return e.execUsualBatch(r.values);else try{return await e.execPrepared(r.query,r.preparedValues)}catch(l){throw l instanceof Error&&(l.message=`Error while executing query: ${r.query.text} - ${l.message}`),l}})(),performance:{blockTime:T}}}catch(c){if(a!=null&&a.rollbackOnFail)try{await e.rollback()}catch(l){console.error("Failed to rollback",c,l)}throw c}finally{Q(t,s,a)}}}),ae=e=>({async run(t,r,a){const i=v(),s=await q(t,a),T=v()-i;try{return{result:(()=>{if(r.type==="usual")return"execUsual"in e?r.values.map(l=>{try{return e.execUsual(l)}catch(m){throw m instanceof Error&&(m.message=`Error while executing query: ${l.text} - ${m.message}`),m}}):e.execUsualBatch(r.values);try{return e.execPrepared(r.query,r.preparedValues)}catch(l){throw l instanceof Error&&(l.message=`Error while executing query: ${r.query.text} - ${l.message}`),l}})(),performance:{blockTime:T}}}catch(c){if(a!=null&&a.rollbackOnFail)try{e.rollback()}catch(l){console.error("Failed to rollback",c,l)}throw c}finally{Q(t,s,a)}}});class U extends Error{constructor(t,r,a){super(t.message,{cause:t}),this.dbName=r,this.queries=a,this.cause=t,this.stack=t.stack,this.name="QueryRunError"}}const V=(e,t)=>{if(!e.__state.localState.transactionState.current)throw new Error("Not in transaction.");const r=e.__state.localState.transactionState.current,a=[],i=s=>(d,T)=>{if(r.id===T.id){t(s,d,r);for(const c of a)c()}};a.push(e.__state.sharedState.eventsEmitter.on("transactionCommitted",i("committed"))),a.push(e.__state.sharedState.eventsEmitter.on("transactionRollbacked",i("rollbacked")))};function ie(){const e={};return{async emit(t,...r){const a=e[t]||[];for(const i of a)await i(...r)},on(t,r){return(e[t]=e[t]||[]).push(r),()=>{const a=e[t]||[];e[t]=a.filter(i=>i!==r)}}}}const ne=e=>e.filter(t=>t!==null),se=e=>e.reduce((t,r)=>t+r,0),M=e=>se(ne(e)),oe=async({db:e,queries:t,transactionOpts:r})=>{var p,w,F,G,Y,H,K,X,Z;const{localState:{transactionState:a},sharedState:{dbBackend:i,logFns:s},sharedState:d}=e.__state;if(a.current||N(e,()=>JSON.stringify(t)),r&&((p=a.current)==null?void 0:p.id)!==r.transactionId)throw new Error(`Cannot run queries in a transaction that is not the current one. Transaction opts: ${JSON.stringify(r)}, local transaction: ${JSON.stringify(a)}`);const T=v(),c=(()=>{const y=r||(a.current?{transactionId:a.current.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}:void 0);if(t.type==="prepared"){const _=t.query.toSql();if(_._values.length!==0)throw new Error("You can't use prepared var through ${} for runPreparedQuery. Please, manually specify variables with '?'.");const g=_.preparedQuery.text;return{toExecArg:{type:"prepared",query:_.preparedQuery,preparedValues:t.preparedValues},toExecArgOpts:y,textQueries:[g]}}else{const _=t.values.map(g=>g.preparedQuery);return{toExecArg:{type:"usual",values:_},toExecArgOpts:y,textQueries:_.map(g=>g.text)}}})(),l=async()=>{try{return{...await i.execQueries(c.toExecArg,c.toExecArgOpts),textQueries:c.textQueries}}catch(y){throw y instanceof Error?new U(y,e.__state.sharedState.dbName,c.textQueries):y}},{result:m,performance:n,textQueries:u}=await l(),f=v();if(!e.__state.localState.suppressLog){const y=(b,A)=>`${b}=${(A/1e3).toFixed(4)}`,_=(()=>{if(t.type==="prepared"){const b=m[0],A=[b.performance.prepareTime!==void 0?y("prepareTime",M(m.map(k=>k.performance.prepareTime))):"",b.performance.execTime!==void 0?y("execTime",M(m.map(k=>k.performance.execTime))):""].filter(k=>k.length!==0).join(" ");return[[u[0].slice(0,1e3),`for ${t.preparedValues.length} values`,A].filter(k=>k.length!==0).join(" ")]}else return m.map(({performance:b},A)=>{const k=[b.prepareTime!==void 0?y("prepareTime",b.prepareTime):"",b.execTime!==void 0?y("execTime",b.execTime):""].filter(J=>J.length!==0).join(" ");return[u[A].slice(0,1e3),k].filter(J=>J.length!==0).join(" ")})})(),g=(()=>_.length===1?_[0]:`
(function(f,$){typeof exports=="object"&&typeof module<"u"?$(exports,require("fast-equals"),require("@kikko-land/boono-sql")):typeof define=="function"&&define.amd?define(["exports","fast-equals","@kikko-land/boono-sql"],$):(f=typeof globalThis<"u"?globalThis:f||self,$(f.core={},f.fastEquals,f.boonoSql))})(this,function(f,$,S){"use strict";const v=typeof performance<"u"?()=>performance.now():()=>Date.now();class E extends Error{}class C extends Error{}const O=(()=>{const e=new Map;let t=!1,r;const a=async()=>{if(!t)for(t=!0;t;){if(e.size===0){if(!r)r=Date.now()+1e4;else if(r<Date.now()){t=!1,r=void 0,console.log("loop stopped");break}}else{r=void 0;for(const[i,s]of e.entries())s<Date.now()&&(i(),e.delete(i))}await new Promise(i=>{setTimeout(()=>i(),1e3)})}};return(i,s)=>(e.set(i,Date.now()+s),a(),()=>{e.delete(i)})})(),I=(e,t)=>{const r=t.deduplicate===void 0?!0:t.deduplicate;return{__state:{subscriptions:[],value:e,isStopped:!1,onStop:[]},get isStopped(){return this.__state.isStopped},set value(a){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);if(!(r&&$.deepEqual(this.__state.value,a))){this.__state.value=a;for(const i of this.__state.subscriptions)i(a)}},get value(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return this.__state.value},subscribe(a,i=!0){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);let s;const h=T=>{s&&s(),s=a(T)};return this.__state.subscriptions.push(h),i&&h(this.__state.value),()=>{this.__state.subscriptions=this.__state.subscriptions.filter(T=>T!==h)}},waitTill(a,i){const s=new C(`waitUntil for reactiveVar ${t.label} is stopped due to stop signal`),h=new E(`waitUntil for reactiveVar ${t.label} is timed out`),T=new C(`waitUntil for reactiveVar ${t.label} is stopped due to reactive var stop`);if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return a(this.value)?Promise.resolve():new Promise((l,d)=>{var p;let n=!1,u=[];const m=()=>{if(!n){for(const w of u)w();n=!0,u=[]}},o=w=>{n?w():u.push(w)};if(n||o(this.subscribe(w=>{!a(w)||(m(),l())},!0)),n||o(((p=i==null?void 0:i.stopIf)==null?void 0:p.subscribe(w=>{!w||(m(),d(s))},!0))||(()=>{})),!n&&((i==null?void 0:i.timeout)===void 0||typeof(i==null?void 0:i.timeout)=="number")){const w=O(()=>{m(),d(h)},(i==null?void 0:i.timeout)===void 0?12e4:i.timeout);o(()=>{w()})}if(!n){const w=()=>{m(),d(T)};this.__state.onStop.push(w),o(()=>{this.__state.onStop=this.__state.onStop.filter(F=>F!==w)})}})},stop(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is already stopped!`);this.__state.subscriptions=[];for(const a of this.__state.onStop)a();this.__state.onStop=[],this.__state.isStopped=!0}}},L=(e,t)=>{const{__state:{sharedState:{runningState:r,dbName:a}}}=e;if(r.value!=="running")throw new Error(`Failed to start ${t()}, db ${a} is stopping`)};function R(){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=t.length;for(let a=0;a<32;a++)e+=t.charAt(Math.floor(Math.random()*r));return e}const B=e=>{const{current:t,queue:r}=e;return`Current running transaction job: ${JSON.stringify(t,null,2)}, queue of transaction jobs: ${JSON.stringify(r,null,2)}`},ee=()=>I({queue:[],current:void 0},{label:"jobsState",deduplicate:!1}),D=e=>({id:e}),q=async(e,t)=>{const{current:r,queue:a}=e.value;if(r||a.length>0){const i=e.waitTill(s=>{var h;return((h=s.current)==null?void 0:h.id)===t.id},{timeout:12e4});e.value={queue:[...a,t],current:r};try{await i}catch(s){throw e.value={...e.value,queue:e.value.queue.filter(h=>h.id!==t.id)},s instanceof E?new E(`Timeout error while transaction job acquire: '${s.message}'. Is it a dead lock? ${B(e.value)}, jobToAcquire: ${JSON.stringify(t,null,2)}`):s}}else e.value={queue:[],current:t}},U=(e,t)=>{const{current:r,queue:a}=e.value;if((r==null?void 0:r.id)!==t.id)throw new Error(`Can't release job that is not currently running, ${B(e.value)}, toRelease: ${JSON.stringify(t,null,2)}`);e.value={queue:a.slice(1),current:a[0]}},te=async e=>{try{return e.waitTill(({queue:t,current:r})=>t.length===0&&r===void 0,{timeout:12e4})}catch(t){throw t instanceof E?new E(`Timeout error while awaiting all jobs done: '${t.message}'. Is it a dead lock?`):t}},Q=async(e,t)=>{let r;if(t){const a=D(t.transactionId);t.containsTransactionStart?await q(e,a):await e.waitTill(i=>{var s;return((s=i.current)==null?void 0:s.id)===a.id}),r=a}else{const a=D(R());await q(e,a),r=a}return r},J=(e,t,r)=>{if(t&&(!r||(r==null?void 0:r.containsTransactionFinish)||(r==null?void 0:r.containsTransactionRollback))&&U(e,t),!t&&r)throw new Error("Transaction job was not started, nothing to release!")},re=e=>({async run(t,r,a){const i=v(),s=await Q(t,a),T=v()-i;try{return{result:await(async()=>{if(r.type==="usual")if("execUsual"in e){const l=[];for(const d of r.values)try{l.push(await e.execUsual(d))}catch(n){throw n instanceof Error&&(n.message=`Error(${n.message}) while executing query: ${d.text.slice(0,500)}`),n}return l}else return e.execUsualBatch(r.values);else try{return await e.execPrepared(r.query,r.preparedValues)}catch(l){throw l instanceof Error&&(l.message=`Error(${l.message}) while executing query: ${r.query.text.slice(0,500)}`),l}})(),performance:{blockTime:T}}}catch(c){if(a!=null&&a.rollbackOnFail)try{await e.rollback()}catch(l){console.error("Failed to rollback",c,l)}throw c}finally{J(t,s,a)}}}),ae=e=>({async run(t,r,a){const i=v(),s=await Q(t,a),T=v()-i;try{return{result:(()=>{if(r.type==="usual")return"execUsual"in e?r.values.map(l=>{try{return e.execUsual(l)}catch(d){throw d instanceof Error&&(d.message=`Error(${d.message}) while executing query: ${l.text.slice(0,500)}`),d}}):e.execUsualBatch(r.values);try{return e.execPrepared(r.query,r.preparedValues)}catch(l){throw l instanceof Error&&(l.message=`Error(${l.message}) while executing query: ${r.query.text.slice(0,500)}`),l}})(),performance:{blockTime:T}}}catch(c){if(a!=null&&a.rollbackOnFail)try{e.rollback()}catch(l){console.error("Failed to rollback",c,l)}throw c}finally{J(t,s,a)}}});class V extends Error{constructor(t,r,a){super(t.message,{cause:t}),this.dbName=r,this.queries=a,this.cause=t,this.stack=t.stack,this.name="QueryRunError"}}const M=(e,t)=>{if(!e.__state.localState.transactionState.current)throw new Error("Not in transaction.");const r=e.__state.localState.transactionState.current,a=[],i=s=>(h,T)=>{if(r.id===T.id){t(s,h,r);for(const c of a)c()}};a.push(e.__state.sharedState.eventsEmitter.on("transactionCommitted",i("committed"))),a.push(e.__state.sharedState.eventsEmitter.on("transactionRollbacked",i("rollbacked")))};function ie(){const e={};return{async emit(t,...r){const a=e[t]||[];for(const i of a)await i(...r)},on(t,r){return(e[t]=e[t]||[]).push(r),()=>{const a=e[t]||[];e[t]=a.filter(i=>i!==r)}}}}const ne=e=>e.filter(t=>t!==null),se=e=>e.reduce((t,r)=>t+r,0),W=e=>se(ne(e)),oe=async({db:e,queries:t,transactionOpts:r})=>{var p,w,F,Y,H,K,X,Z,j;const{localState:{transactionState:a},sharedState:{dbBackend:i,logFns:s},sharedState:h}=e.__state;if(a.current||L(e,()=>JSON.stringify(t)),r&&((p=a.current)==null?void 0:p.id)!==r.transactionId)throw new Error(`Cannot run queries in a transaction that is not the current one. Transaction opts: ${JSON.stringify(r)}, local transaction: ${JSON.stringify(a)}`);const T=v(),c=(()=>{const y=r||(a.current?{transactionId:a.current.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}:void 0);if(t.type==="prepared"){const _=t.query.toSql();if(_._values.length!==0)throw new Error("You can't use prepared var through ${} for runPreparedQuery. Please, manually specify variables with '?'.");const g=_.preparedQuery.text;return{toExecArg:{type:"prepared",query:_.preparedQuery,preparedValues:t.preparedValues},toExecArgOpts:y,textQueries:[g]}}else{const _=t.values.map(g=>g.preparedQuery);return{toExecArg:{type:"usual",values:_},toExecArgOpts:y,textQueries:_.map(g=>g.text)}}})(),l=async()=>{try{return{...await i.execQueries(c.toExecArg,c.toExecArgOpts),textQueries:c.textQueries}}catch(y){throw y instanceof Error?new V(y,e.__state.sharedState.dbName,c.textQueries):y}},{result:d,performance:n,textQueries:u}=await l(),m=v();if(!e.__state.localState.suppressLog){const y=(b,A)=>`${b}=${(A/1e3).toFixed(4)}`,_=(()=>{if(t.type==="prepared"){const b=d[0],A=[b.performance.prepareTime!==void 0?y("prepareTime",W(d.map(k=>k.performance.prepareTime))):"",b.performance.execTime!==void 0?y("execTime",W(d.map(k=>k.performance.execTime))):""].filter(k=>k.length!==0).join(" ");return[[u[0].slice(0,1e3),`for ${t.preparedValues.length} values`,A].filter(k=>k.length!==0).join(" ")]}else return d.map(({performance:b},A)=>{const k=[b.prepareTime!==void 0?y("prepareTime",b.prepareTime):"",b.execTime!==void 0?y("execTime",b.execTime):""].filter(N=>N.length!==0).join(" ");return[u[A].slice(0,1e3),k].filter(N=>N.length!==0).join(" ")})})(),g=(()=>_.length===1?_[0]:`
`+_.map(b=>`{${b}}`).join(`
`))(),pe=`%c[${e.__state.sharedState.dbName}] `+[(w=a.current)!=null&&w.id?`[tr_id=${(F=a.current)==null?void 0:F.id.substring(0,6)}]`:"",g,(n==null?void 0:n.sendTime)!==void 0?`sendTime=${(n.sendTime/1e3).toFixed(4)}`:"",(n==null?void 0:n.receiveTime)!==void 0?`receiveTime=${(n.receiveTime/1e3).toFixed(4)}`:"",(n==null?void 0:n.blockTime)!==void 0?`blockTime=${(n.blockTime/1e3).toFixed(4)}`:"",`totalTime=${((f-T)/1e3).toFixed(4)}`].filter(b=>b.length!==0).join(" "),Te=(H=d.transactionsStates.byId[(Y=(G=a.current)==null?void 0:G.id)!=null?Y:""])==null?void 0:H.i;s.logQuery(pe,Te)}const o=(Z=d.transactionsStates.byId[(X=(K=a.current)==null?void 0:K.id)!=null?X:""])==null?void 0:Z.performance;return o&&(m.some(y=>y.performance.execTime!==void 0)&&(o.execTime===void 0&&(o.execTime=0),o.execTime+=m.reduce((y,_)=>{var g;return y+((g=_.performance.execTime)!=null?g:0)},0)),m.some(y=>y.performance.prepareTime!==void 0)&&(o.prepareTime===void 0&&(o.prepareTime=0),o.prepareTime+=m.reduce((y,_)=>{var g;return y+((g=_.performance.prepareTime)!=null?g:0)},0)),n.sendTime&&(o.sendTime||(o.sendTime=0),o.sendTime+=n.sendTime),n.receiveTime&&(o.receiveTime||(o.receiveTime=0),o.receiveTime+=n.receiveTime),n.blockTime&&(o.blockTime||(o.blockTime=0),o.blockTime+=n.blockTime)),{db:e,result:m,performance:n,queries:t}},x=async(e,t,r)=>{const a=[...e.__state.localState.queriesMiddlewares,oe].reverse();let i=s=>Promise.resolve(s);for(const s of a){const d=i;i=T=>s({...T,next:d})}return await i({db:e,result:[],performance:{sendTime:void 0,receiveTime:void 0,totalTime:0},queries:t,transactionOpts:r})};let W=0;const P=(e,t,r)=>{const a=e.__state.sharedState.logFns;if(e.__state.localState.suppressLog)return;const i=[r.prepareTime===void 0?"":`prepareTime=${(r.prepareTime/1e3).toFixed(4)}`,r.execTime===void 0?"":`execTime=${(r.execTime/1e3).toFixed(4)}`,r.sendTime===void 0?"":`sendTime=${(r.sendTime/1e3).toFixed(4)}`,r.receiveTime===void 0?"":`receiveTime=${(r.receiveTime/1e3).toFixed(4)}`,r.blockTime===void 0?"":`blockTime=${(r.blockTime/1e3).toFixed(4)}`,`totalTime=${(r.totalTime/1e3).toFixed(4)}`].filter(s=>s.length!==0).join(" ");a.logTrFinish(`%c[${e.__state.sharedState.dbName}][tr_id=${t.slice(0,6)}] Transaction finished with ${i}`)},ce=async(e,t,r)=>{const{localState:{transactionState:a},sharedState:{eventsEmitter:i,transactionsStates:s,dbBackend:d,logFns:T}}=e.__state;if(d.isUsualTransactionDisabled)throw new Error("Usual transactions are disabled for this type of backend. Please, use atomic transactions instead.");if(a.current)return await r(e);N(e,()=>"transaction");const c={id:R(),type:"async"};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:c}}}};const l=v(),m={i:W++,current:c,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};s.byId[c.id]=m;try{await i.emit("transactionWillStart",e,c),await x(e,{type:"usual",values:[S.sql`BEGIN ${S.sql.raw(t.toLocaleUpperCase())} TRANSACTION`]},{transactionId:c.id,containsTransactionStart:!0,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionStarted",e,c);try{const n=await r(e);return await i.emit("transactionWillCommit",e,c),await x(e,{type:"usual",values:[S.sql`COMMIT`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionCommitted",e,c),n}catch(n){T.logError("Rollback transaction",n),await i.emit("transactionWillRollback",e,c);try{await x(e,{type:"usual",values:[S.sql`ROLLBACK`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!0,rollbackOnFail:!1,isAtomic:!1})}catch(u){T.logError("Rollback transaction failed",u)}throw await i.emit("transactionRollbacked",e,c),n}}finally{m.performance.totalTime=v()-l,P(e,c.id,m.performance),delete s.byId[c.id]}},le=()=>({__state:{queries:[],afterCommits:[],afterRollbacks:[]},addQuery(e){this.__state.queries.push(e)},afterCommit(e){this.__state.afterCommits.push(e)},afterRollback(e){this.__state.afterRollbacks.push(e)}}),ue=async(e,t,r)=>{const{localState:{transactionState:a},sharedState:{eventsEmitter:i,transactionsStates:s,dbBackend:d,logFns:T}}=e.__state;if(a.current)throw new Error("You are running atomic transaction inside of a transaction. Consider moving atomic transaction call to runAfterTransaction callback.");const{inputQueries:c,afterCommits:l,afterRollbacks:m}=await(async()=>{if(Array.isArray(r))return{inputQueries:r,afterCommits:[],afterRollbacks:[]};{const p=le();return await r(p),{inputQueries:p.__state.queries,afterCommits:p.__state.afterCommits,afterRollbacks:p.__state.afterRollbacks}}})(),n={id:R(),type:"atomic"},u={i:W++,current:n,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:n}}}},s.byId[n.id]=u;const f=v(),o=[];d.isAtomicRollbackCommitDisabled||o.push(S.sql`BEGIN ${S.sql.raw(t.toUpperCase())} TRANSACTION`),o.push(...c.map(p=>p.toSql())),d.isAtomicRollbackCommitDisabled||o.push(S.sql`COMMIT`);try{await i.emit("transactionWillStart",e,n),await i.emit("transactionStarted",e,n),await x(e,{type:"usual",values:o},{transactionId:n.id,containsTransactionStart:!0,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!0,isAtomic:!0}),await i.emit("transactionWillCommit",e,n),await i.emit("transactionCommitted",e,n);try{for(const p of l)p()}catch(p){T.logError("Error in afterCommit callback",p)}}catch(p){T.logError("Rollback transaction",p),await i.emit("transactionWillRollback",e,n),await i.emit("transactionRollbacked",e,n);try{for(const w of m)w()}catch(w){T.logError("Error in afterRollback callback",w)}throw p}finally{u.performance.totalTime=v()-f,P(e,n.id,u.performance),delete s.byId[n.id]}},z=["yellow","cyan","magenta"],de=async({dbName:e,plugins:t,queriesMiddlewares:r,dbBackend:a,suppressLog:i,logFns:s})=>{const d=s||{logQuery:(u,f)=>{const o=typeof f=="number"?z[f%z.length]:void 0;console.debug(...o?[u,`color: ${o}; background-color: #202124; padding: 2px 4px; border-radius: 2px`]:[u,"padding: 0"])},logError:(u,f)=>{console.error(u,f)},logTrFinish:u=>{console.debug(u,"color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px")}},T=I("running",{label:"runningState"}),c=(await a)({dbName:e}),l={__state:{sharedState:{clientId:R(),dbBackend:c,dbName:e,runningState:T,eventsEmitter:ie(),transactionsStates:{byId:{}},logFns:d},localState:{queriesMiddlewares:r||[],transactionState:{},suppressLog:Boolean(i)}},runInTransaction(u,f){return ce(this,(f==null?void 0:f.type)||"deferred",u)},async runInAtomicTransaction(u,f){return await ue(this,(f==null?void 0:f.type)||"deferred",u)},async runQueries(u){return(await x(this,{type:"usual",values:u.map(o=>o.toSql())})).result.map(({rows:o})=>o)},async runQuery(u){return(await this.runQueries([u]))[0]},async runPreparedQuery(u,f){return(await x(this,{type:"prepared",query:u,preparedValues:f})).result.map(({rows:p})=>p)},runAfterTransactionCommitted(u){return V(this,(f,o,p)=>{f==="committed"&&u(o,p)})},runAfterTransactionRollbacked(u){V(l,(f,o,p)=>{f==="rollbacked"&&u(o,p)})}};let m=l;const n=()=>l.__state.sharedState.runningState.value;if(n()!=="running"||(await c.initialize(),n()!=="running"))return l;for(const u of t||[])m=u(m);return await l.__state.sharedState.eventsEmitter.emit("initialized",l),m},me=async e=>{e.__state.sharedState.runningState.value="stopping",await e.__state.sharedState.dbBackend.stop(),e.__state.sharedState.runningState.value="stopped",queueMicrotask(()=>{e.__state.sharedState.runningState.stop()})},fe=(e,t)=>t({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),he=e=>({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}});h.QueryRunError=U,h.StoppedError=C,h.TimeoutError=E,h.acquireJob=B,h.acquireWithTrJobOrWait=q,h.buildAsyncQueryRunner=re,h.buildSyncQueryRunner=ae,h.getTime=v,h.initDbClient=de,h.initJobsState=O,h.makeId=R,h.reactiveVar=I,h.releaseJob=D,h.releaseTrJobIfPossible=Q,h.stopDb=me,h.suppressLog=fe,h.whenAllJobsDone=te,h.withSuppressedLog=he;for(const e in S)e!=="default"&&!h.hasOwnProperty(e)&&Object.defineProperty(h,e,{enumerable:!0,get:()=>S[e]});Object.defineProperties(h,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
`))(),pe=`%c[${e.__state.sharedState.dbName}] `+[(w=a.current)!=null&&w.id?`[tr_id=${(F=a.current)==null?void 0:F.id.substring(0,6)}]`:"",g,(n==null?void 0:n.sendTime)!==void 0?`sendTime=${(n.sendTime/1e3).toFixed(4)}`:"",(n==null?void 0:n.receiveTime)!==void 0?`receiveTime=${(n.receiveTime/1e3).toFixed(4)}`:"",(n==null?void 0:n.blockTime)!==void 0?`blockTime=${(n.blockTime/1e3).toFixed(4)}`:"",`totalTime=${((m-T)/1e3).toFixed(4)}`].filter(b=>b.length!==0).join(" "),Te=(K=h.transactionsStates.byId[(H=(Y=a.current)==null?void 0:Y.id)!=null?H:""])==null?void 0:K.i;s.logQuery(pe,Te)}const o=(j=h.transactionsStates.byId[(Z=(X=a.current)==null?void 0:X.id)!=null?Z:""])==null?void 0:j.performance;return o&&(d.some(y=>y.performance.execTime!==void 0)&&(o.execTime===void 0&&(o.execTime=0),o.execTime+=d.reduce((y,_)=>{var g;return y+((g=_.performance.execTime)!=null?g:0)},0)),d.some(y=>y.performance.prepareTime!==void 0)&&(o.prepareTime===void 0&&(o.prepareTime=0),o.prepareTime+=d.reduce((y,_)=>{var g;return y+((g=_.performance.prepareTime)!=null?g:0)},0)),n.sendTime&&(o.sendTime||(o.sendTime=0),o.sendTime+=n.sendTime),n.receiveTime&&(o.receiveTime||(o.receiveTime=0),o.receiveTime+=n.receiveTime),n.blockTime&&(o.blockTime||(o.blockTime=0),o.blockTime+=n.blockTime)),{db:e,result:d,performance:n,queries:t}},x=async(e,t,r)=>{const a=[...e.__state.localState.queriesMiddlewares,oe].reverse();let i=s=>Promise.resolve(s);for(const s of a){const h=i;i=T=>s({...T,next:h})}return await i({db:e,result:[],performance:{sendTime:void 0,receiveTime:void 0,totalTime:0},queries:t,transactionOpts:r})};let P=0;const z=(e,t,r)=>{const a=e.__state.sharedState.logFns;if(e.__state.localState.suppressLog)return;const i=[r.prepareTime===void 0?"":`prepareTime=${(r.prepareTime/1e3).toFixed(4)}`,r.execTime===void 0?"":`execTime=${(r.execTime/1e3).toFixed(4)}`,r.sendTime===void 0?"":`sendTime=${(r.sendTime/1e3).toFixed(4)}`,r.receiveTime===void 0?"":`receiveTime=${(r.receiveTime/1e3).toFixed(4)}`,r.blockTime===void 0?"":`blockTime=${(r.blockTime/1e3).toFixed(4)}`,`totalTime=${(r.totalTime/1e3).toFixed(4)}`].filter(s=>s.length!==0).join(" ");a.logTrFinish(`%c[${e.__state.sharedState.dbName}][tr_id=${t.slice(0,6)}] Transaction finished with ${i}`)},ce=async(e,t,r)=>{const{localState:{transactionState:a},sharedState:{eventsEmitter:i,transactionsStates:s,dbBackend:h,logFns:T}}=e.__state;if(h.isUsualTransactionDisabled)throw new Error("Usual transactions are disabled for this type of backend. Please, use atomic transactions instead.");if(a.current)return await r(e);L(e,()=>"transaction");const c={id:R(),type:"async"};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:c}}}};const l=v(),d={i:P++,current:c,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};s.byId[c.id]=d;try{await i.emit("transactionWillStart",e,c),await x(e,{type:"usual",values:[S.sql`BEGIN ${S.sql.raw(t.toLocaleUpperCase())} TRANSACTION`]},{transactionId:c.id,containsTransactionStart:!0,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionStarted",e,c);try{const n=await r(e);return await i.emit("transactionWillCommit",e,c),await x(e,{type:"usual",values:[S.sql`COMMIT`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionCommitted",e,c),n}catch(n){T.logError("Rollback transaction",n),await i.emit("transactionWillRollback",e,c);try{await x(e,{type:"usual",values:[S.sql`ROLLBACK`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!0,rollbackOnFail:!1,isAtomic:!1})}catch(u){T.logError("Rollback transaction failed",u)}throw await i.emit("transactionRollbacked",e,c),n}}finally{d.performance.totalTime=v()-l,z(e,c.id,d.performance),delete s.byId[c.id]}},le=()=>({__state:{queries:[],afterCommits:[],afterRollbacks:[]},addQuery(e){this.__state.queries.push(e)},afterCommit(e){this.__state.afterCommits.push(e)},afterRollback(e){this.__state.afterRollbacks.push(e)}}),ue=async(e,t,r)=>{const{localState:{transactionState:a},sharedState:{eventsEmitter:i,transactionsStates:s,dbBackend:h,logFns:T}}=e.__state;if(a.current)throw new Error("You are running atomic transaction inside of a transaction. Consider moving atomic transaction call to runAfterTransaction callback.");const{inputQueries:c,afterCommits:l,afterRollbacks:d}=await(async()=>{if(Array.isArray(r))return{inputQueries:r,afterCommits:[],afterRollbacks:[]};{const p=le();return await r(p),{inputQueries:p.__state.queries,afterCommits:p.__state.afterCommits,afterRollbacks:p.__state.afterRollbacks}}})(),n={id:R(),type:"atomic"},u={i:P++,current:n,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:n}}}},s.byId[n.id]=u;const m=v(),o=[];h.isAtomicRollbackCommitDisabled||o.push(S.sql`BEGIN ${S.sql.raw(t.toUpperCase())} TRANSACTION`),o.push(...c.map(p=>p.toSql())),h.isAtomicRollbackCommitDisabled||o.push(S.sql`COMMIT`);try{await i.emit("transactionWillStart",e,n),await i.emit("transactionStarted",e,n),await x(e,{type:"usual",values:o},{transactionId:n.id,containsTransactionStart:!0,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!0,isAtomic:!0}),await i.emit("transactionWillCommit",e,n),await i.emit("transactionCommitted",e,n);try{for(const p of l)p()}catch(p){T.logError("Error in afterCommit callback",p)}}catch(p){T.logError("Rollback transaction",p),await i.emit("transactionWillRollback",e,n),await i.emit("transactionRollbacked",e,n);try{for(const w of d)w()}catch(w){T.logError("Error in afterRollback callback",w)}throw p}finally{u.performance.totalTime=v()-m,z(e,n.id,u.performance),delete s.byId[n.id]}},G=["yellow","cyan","magenta"],de=async({dbName:e,plugins:t,queriesMiddlewares:r,dbBackend:a,suppressLog:i,logFns:s})=>{const h=s||{logQuery:(u,m)=>{const o=typeof m=="number"?G[m%G.length]:void 0;console.debug(...o?[u,`color: ${o}; background-color: #202124; padding: 2px 4px; border-radius: 2px`]:[u,"padding: 0"])},logError:(u,m)=>{console.error(u,m)},logTrFinish:u=>{console.debug(u,"color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px")}},T=I("running",{label:"runningState"}),c=(await a)({dbName:e}),l={__state:{sharedState:{clientId:R(),dbBackend:c,dbName:e,runningState:T,eventsEmitter:ie(),transactionsStates:{byId:{}},logFns:h},localState:{queriesMiddlewares:r||[],transactionState:{},suppressLog:Boolean(i)}},runInTransaction(u,m){return ce(this,(m==null?void 0:m.type)||"deferred",u)},async runInAtomicTransaction(u,m){return await ue(this,(m==null?void 0:m.type)||"deferred",u)},async runQueries(u){return(await x(this,{type:"usual",values:u.map(o=>o.toSql())})).result.map(({rows:o})=>o)},async runQuery(u){return(await this.runQueries([u]))[0]},async runPreparedQuery(u,m){return(await x(this,{type:"prepared",query:u,preparedValues:m})).result.map(({rows:p})=>p)},runAfterTransactionCommitted(u){return M(this,(m,o,p)=>{m==="committed"&&u(o,p)})},runAfterTransactionRollbacked(u){M(l,(m,o,p)=>{m==="rollbacked"&&u(o,p)})}};let d=l;const n=()=>l.__state.sharedState.runningState.value;if(n()!=="running"||(await c.initialize(),n()!=="running"))return l;for(const u of t||[])d=u(d);return await l.__state.sharedState.eventsEmitter.emit("initialized",l),d},me=async e=>{e.__state.sharedState.runningState.value="stopping",await e.__state.sharedState.dbBackend.stop(),e.__state.sharedState.runningState.value="stopped",queueMicrotask(()=>{e.__state.sharedState.runningState.stop()})},fe=(e,t)=>t({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),he=e=>({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}});f.QueryRunError=V,f.StoppedError=C,f.TimeoutError=E,f.acquireJob=q,f.acquireWithTrJobOrWait=Q,f.buildAsyncQueryRunner=re,f.buildSyncQueryRunner=ae,f.getTime=v,f.initDbClient=de,f.initJobsState=ee,f.makeId=R,f.reactiveVar=I,f.releaseJob=U,f.releaseTrJobIfPossible=J,f.stopDb=me,f.suppressLog=fe,f.whenAllJobsDone=te,f.withSuppressedLog=he;for(const e in S)e!=="default"&&!f.hasOwnProperty(e)&&Object.defineProperty(f,e,{enumerable:!0,get:()=>S[e]});Object.defineProperties(f,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
//# sourceMappingURL=index.umd.js.map

@@ -16,3 +16,3 @@ import { DeepReadonly } from "ts-essentials";

export declare const whenAllJobsDone: (jobsState: ReactiveVar<ITransactionsJobsState>) => Promise<void>;
export declare const acquireWithTrJobOrWait: (jobsState: ReactiveVar<ITransactionsJobsState>, transactionOpts?: ITransactionOpts) => Promise<ITransactionJob | undefined>;
export declare const acquireWithTrJobOrWait: (jobsState: ReactiveVar<ITransactionsJobsState>, transactionOpts?: ITransactionOpts) => Promise<ITransactionJob>;
export declare const releaseTrJobIfPossible: (jobsState: ReactiveVar<ITransactionsJobsState>, job: ITransactionJob | undefined, transactionOpts?: ITransactionOpts) => void;
{
"name": "@kikko-land/kikko",
"version": "0.16.0",
"version": "0.17.0",
"author": "Sergey Popov",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -98,3 +98,5 @@ import { IPrimitiveValue } from "@kikko-land/boono-sql";

if (e instanceof Error) {
e.message = `Error while executing query: ${q.text} - ${e.message}`;
e.message = `Error(${
e.message
}) while executing query: ${q.text.slice(0, 500)}`;
}

@@ -117,3 +119,5 @@ throw e;

if (e instanceof Error) {
e.message = `Error while executing query: ${queries.query.text} - ${e.message}`;
e.message = `Error(${
e.message
}) while executing query: ${queries.query.text.slice(0, 500)}`;
}

@@ -190,3 +194,5 @@ throw e;

if (e instanceof Error) {
e.message = `Error while executing query: ${q.text} - ${e.message}`;
e.message = `Error(${
e.message
}) while executing query: ${q.text.slice(0, 500)}`;
}

@@ -204,3 +210,5 @@ throw e;

if (e instanceof Error) {
e.message = `Error while executing query: ${queries.query.text} - ${e.message}`;
e.message = `Error(${
e.message
}) while executing query: ${queries.query.text.slice(0, 500)}`;
}

@@ -207,0 +215,0 @@ throw e;

import { deepEqual } from "fast-equals";
import { makeId } from "./utils";
export interface ReactiveVar<T> {

@@ -30,6 +28,3 @@ __state: {

const startTimeoutChecker = (() => {
const timeoutMap = new Map<
string,
{ toCall: () => void; callAfter: number }
>();
const timeoutMap = new Map<() => void, number>();

@@ -50,2 +45,3 @@ let isLoopRunning = false;

stopLoopAfter = undefined;
console.log("loop stopped");
break;

@@ -56,7 +52,7 @@ }

for (const [id, { toCall, callAfter }] of timeoutMap.entries()) {
for (const [toCall, callAfter] of timeoutMap.entries()) {
if (callAfter < Date.now()) {
toCall();
timeoutMap.delete(id);
timeoutMap.delete(toCall);
}

@@ -73,8 +69,7 @@ }

return (toCall: () => void, after: number) => {
const id = makeId();
timeoutMap.set(id, { toCall, callAfter: Date.now() + after });
timeoutMap.set(toCall, Date.now() + after);
void startLoopIfPossible();
return () => {
timeoutMap.delete(id);
timeoutMap.delete(toCall);
};

@@ -81,0 +76,0 @@ };

@@ -5,2 +5,3 @@ import { DeepReadonly } from "ts-essentials";

import { ITransactionOpts } from "./types";
import { makeId } from "./utils";

@@ -143,3 +144,9 @@ export type DistributiveOmit<

} else {
await jobsState.waitTill((state) => state.current?.id === undefined);
// We still want to add other none-transaction queries to queue
// cause SQLite is always single-threaded, and we will not have any benefits
// from running it concurrent. And, as a bonus, we will have more precise measure
// of blocking time
const newJob = buildJob(makeId());
await acquireJob(jobsState, newJob);
job = newJob;
}

@@ -146,0 +153,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc