const e = require("ready-resource"),
r = require("bundlebee"),
t = require("hypercore"),
s = require("b4a"),
i = require("hypercore/messages"),
o = require("bare-zlib"),
{ EXPERIMENTAL: n } = require("../../schema/versions"),
{ KeetContractError: a } = require("../core/contract/errors"),
u = require("./patch"),
c = require("../core/contract/index.js"),
h = require("compact-encoding"),
l = h.array(i.wire.data),
d = 12,
b = 25,
_ = "/lib/contract/index.js",
p = "/lib/core/contract/index.js"
function y(e) {
return new Promise((r, t) => {
o.gunzip(e, (e, s) => {
if (e) return t(e)
r(s)
})
})
}
module.exports = class extends e {
constructor(e, t, { hydrate: s = !1 } = {}) {
if ((super(), (this.keet = e), (this._ownsBee = !e.opts.bundlebee), e.opts.bundlebee))
this._bee = e.opts.bundlebee
else {
const s = e.opts.bundlesStore || e.rootCorestore.namespace(t)
this._bee = new r(s, { key: e._bundlesKey, length: e._bundlesLength })
}
;((this._bundles = {}), (this._routers = {}), (this._hydrate = s))
}
get core() {
return this._bee.core
}
async _open() {
if (!this._hydrate) return this._bee.ready()
let e = []
try {
const r = require("./latest-bundle.trace.js")
e = h.decode(l, await y(r))
} catch (e) {
this.keet.onerror(e, { prefix: "TRACE_LOAD_ERROR" })
}
for (const r of e)
try {
await this._bee.core.applyProof(r)
} catch (e) {
if (r.manifest) {
const e = t.key(r.manifest)
if (!s.equals(e, this._bee.core.key)) continue
}
this.keet.onerror(e, { prefix: "TRACE_APPLY_ERROR" })
}
await this._bee.ready()
}
_close() {
if (this._ownsBee) return this._bee.close()
}
async loadBundle(e) {
if (this._bundles[e]) return this._bundles[e]
if (e >= n) return ((this._bundles[e] = c), c)
const r = e < d ? d : e,
t = r >= b ? p : _,
s = await this._bee.findABI(r)
if (!s) throw a.BUNDLE_NOT_AVAILABLE(r)
const i = await this._bee.load(new URL("../..", module.url), t, s, {
map: (r, t) =>
"/lib/core/contract/helpers.js" !== r || (28 !== e && 29 !== e) ? t : u.helpers,
})
return ((this._bundles[e] = i.exports), this._bundles[e])
}
async loadRouter(e) {
return (
this._routers[e] ||
(await this.loadBundle(e), (this._routers[e] = this._bundles[e].createRouter())),
this._routers[e]
)
}
}