File: /var/www/indoadvisory_new/webapp/node_modules/wrangler/wrangler-dist/ProxyServerWorker.js
// ../../vendor/jsrpc/dist/index.js
Symbol.dispose || (Symbol.dispose = Symbol.for("dispose"));
Symbol.asyncDispose || (Symbol.asyncDispose = Symbol.for("asyncDispose"));
var N = navigator.userAgent === "Cloudflare-Workers" ? "cloudflare:workers" : null;
var v;
N && (v = await import(N));
var E = v ? v.RpcTarget : class {
};
function T(s9) {
switch (typeof s9) {
case "boolean":
case "number":
case "string":
return "primitive";
case "undefined":
return "undefined";
case "object":
case "function":
break;
default:
return "unsupported";
}
if (s9 === null) return "primitive";
let e = Object.getPrototypeOf(s9);
switch (e) {
case Object.prototype:
return "object";
case Function.prototype:
return "function";
case Array.prototype:
return "array";
case Date.prototype:
return "date";
case h.prototype:
return "stub";
case c.prototype:
return "rpc-promise";
default:
return v && (e == v.RpcStub.prototype || e == v.RpcPromise.prototype || e == v.RpcProperty.prototype || e == v.ServiceStub.prototype) || s9 instanceof E ? "rpc-target" : s9 instanceof Error ? "error" : "unsupported";
}
}
var y = class {
};
var f = class extends y {
constructor(t) {
super();
this.error = t;
}
call(t, r) {
return this;
}
get(t) {
return this;
}
dup() {
return this;
}
pull() {
return Promise.reject(this.error);
}
dispose() {
}
onBroken(t) {
try {
t(this.error);
} catch (r) {
Promise.resolve(r);
}
}
};
var J = new f(new Error("Attempted to use RPC stub after it has been disposed."));
var I = Symbol("realStub");
var G = { apply(s9, e, t) {
let r = s9.raw;
return new c(r.hook.call(r.pathIfPromise || [], b.fromApp(t)), []);
}, get(s9, e, t) {
let r = s9.raw;
return e === I ? r : e in c.prototype ? r[e] : typeof e == "string" ? new c(r.hook, r.pathIfPromise ? [...r.pathIfPromise, e] : [e]) : e === Symbol.dispose && (!r.pathIfPromise || r.pathIfPromise.length == 0) ? () => {
r.hook.dispose(), r.hook = J;
} : void 0;
}, has(s9, e) {
let t = s9.raw;
return e === I ? true : e in c.prototype ? e in t : typeof e == "string" ? true : e === Symbol.dispose && (!t.pathIfPromise || t.pathIfPromise.length == 0);
}, construct(s9, e) {
throw new Error("An RPC stub cannot be used as a constructor.");
}, defineProperty(s9, e, t) {
throw new Error("Can't define properties on RPC stubs.");
}, deleteProperty(s9, e) {
throw new Error("Can't delete properties on RPC stubs.");
}, getOwnPropertyDescriptor(s9, e) {
}, getPrototypeOf(s9) {
return Object.getPrototypeOf(s9.raw);
}, isExtensible(s9) {
return false;
}, ownKeys(s9) {
return [];
}, preventExtensions(s9) {
return true;
}, set(s9, e, t, r) {
throw new Error("Can't assign properties on RPC stubs.");
}, setPrototypeOf(s9, e) {
throw new Error("Can't override prototype of RPC stubs.");
} };
var h = class s extends E {
constructor(e, t) {
if (super(), !(e instanceof y)) {
let o = e;
if (o instanceof E || o instanceof Function ? e = C.create(o, void 0) : e = new w(b.fromApp(o)), t) throw new TypeError("RpcStub constructor expected one argument, received two.");
}
this.hook = e, this.pathIfPromise = t;
let r = () => {
};
return r.raw = this, new Proxy(r, G);
}
hook;
pathIfPromise;
dup() {
let e = this[I];
return e.pathIfPromise ? new s(e.hook.get(e.pathIfPromise)) : new s(e.hook.dup());
}
onRpcBroken(e) {
this[I].hook.onBroken(e);
}
};
var c = class extends h {
constructor(e, t) {
super(e, t);
}
then(e, t) {
return B(this).then(...arguments);
}
catch(e) {
return B(this).catch(...arguments);
}
finally(e) {
return B(this).finally(...arguments);
}
};
function m(s9) {
return s9[I];
}
async function B(s9) {
let { hook: e, pathIfPromise: t } = m(s9);
return t.length > 0 && (e = e.get(t)), (await e.pull()).deliverResolve();
}
var b = class s2 {
constructor(e, t, r) {
this.value = e;
this.stubs = t;
this.promises = r;
}
static fromApp(e) {
return new s2(e);
}
static forEvaluate(e, t) {
return new s2(null, e, t);
}
static deepCopyFrom(e, t, r) {
let o = new s2(null);
return o.stubs = [], o.promises = [], o.value = o.deepCopy(e, t, "value", o, true, r), o;
}
rpcTargets;
isFromApp() {
return !this.stubs;
}
getHookForRpcTarget(e, t) {
this.rpcTargets || (this.rpcTargets = /* @__PURE__ */ new Map());
let r = this.rpcTargets.get(e);
return r || (r = C.create(e, t), this.rpcTargets.set(e, r)), r;
}
deepCopy(e, t, r, o, n, i) {
let a = T(e);
switch (a) {
case "unsupported":
return e;
case "primitive":
case "date":
case "error":
case "undefined":
return e;
case "array": {
let p = e, d = p.length, l = new Array(d);
for (let u = 0; u < d; u++) l[u] = this.deepCopy(p[u], p, u, l, n, i);
return l;
}
case "object": {
let p = {}, d = e;
for (let l in d) p[l] = this.deepCopy(d[l], d, l, p, n, i);
return p;
}
case "stub":
case "rpc-promise": {
let p = e, { hook: d, pathIfPromise: l } = m(p);
return l ? p = new c(d.get(l), []) : n && (p = p.dup()), p instanceof c ? this.promises.push({ parent: o, property: r, promise: p }) : this.stubs.push(p), p;
}
case "function":
case "rpc-target": {
let p = e;
return i ? new h(i.getHookForRpcTarget(p, t).dup()) : new h(C.create(p, t));
}
default:
throw new Error("unreachable");
}
}
ensureDeepCopied() {
this.stubs === void 0 && (this.stubs = [], this.promises = [], this.value = this.deepCopy(this.value, void 0, "value", this, false, this), this.rpcTargets = void 0);
}
deliverTo(e, t, r) {
if (this.ensureDeepCopied(), this.value instanceof c) s2.deliverRpcPromiseTo(this.value, e, t, r);
else {
e[t] = this.value;
for (let o of this.promises) s2.deliverRpcPromiseTo(o.promise, o.parent, o.property, r);
}
}
static deliverRpcPromiseTo(e, t, r, o) {
let { hook: n, pathIfPromise: i } = m(e);
if (i && i.length > 0) throw new Error("property promises should have been resolved earlier");
let a = n.pull();
a instanceof s2 ? a.deliverTo(t, r, o) : o.push(a.then((p) => {
let d = [];
if (p.deliverTo(t, r, d), d.length > 0) return Promise.all(d);
}));
}
async deliverCall(e, t) {
try {
let r = [];
this.deliverTo(this, "value", r), r.length > 0 && await Promise.all(r);
let o = Function.prototype.apply.call(e, t, this.value);
return o instanceof c ? s2.fromApp(o) : s2.fromApp(await o);
} finally {
this.dispose();
}
}
async deliverResolve() {
try {
let e = [];
this.deliverTo(this, "value", e), e.length > 0 && await Promise.all(e);
let t = this.value;
return t instanceof Object && (Symbol.dispose in t || (t[Symbol.dispose] = () => this.dispose())), t;
} catch (e) {
throw this.dispose(), e;
}
}
dispose() {
this.stubs ? (this.stubs.forEach((e) => e[Symbol.dispose]()), this.promises.forEach((e) => e.promise[Symbol.dispose]())) : this.disposeImpl(this.value, void 0), this.stubs = [], this.promises = [];
}
disposeImpl(e, t) {
let r = T(e);
switch (r) {
case "unsupported":
case "primitive":
case "date":
case "error":
case "undefined":
return;
case "array": {
let o = e, n = o.length;
for (let i = 0; i < n; i++) this.disposeImpl(o[i], o);
return;
}
case "object": {
let o = e;
for (let n in o) this.disposeImpl(o[n], o);
return;
}
case "stub":
case "rpc-promise": {
let o = e, { hook: n, pathIfPromise: i } = m(o);
i || n.dispose();
return;
}
case "function":
case "rpc-target": {
let o = e;
this.getHookForRpcTarget(o, t).dispose();
return;
}
default:
return;
}
}
};
function x(s9, e) {
if (e === 0) throw new TypeError(`RPC object has no property '${s9[e]}'`);
{
let t = s9.slice(0, e).join(".");
throw new TypeError(`'${t}' has no property '${s9[e]}'`);
}
}
function H(s9, e, t, r) {
for (let o = 0; o < t.length; o++) {
e = s9;
let n = t[o];
(n === "__proto__" || n === "constructor") && x(t, o);
let i = T(s9);
switch (i) {
case "object":
case "array":
case "function":
Object.hasOwn(s9, n) || x(t, o), s9 = s9[n];
break;
case "rpc-target": {
Object.hasOwn(s9, n) && x(t, o), s9 = s9[n], (!s9 || s9 === Object.prototype[n]) && x(t, o), r = null;
break;
}
case "stub":
case "rpc-promise": {
let { hook: a, pathIfPromise: p } = m(s9);
return { hook: a, remainingPath: p ? p.concat(t.slice(o)) : t.slice(o) };
}
case "primitive":
case "date":
case "error":
case "undefined":
x(t, o);
case "unsupported": {
if (o === 0) throw new TypeError("RPC stub points at a non-serializable type.");
{
let a = t.slice(0, o).join("."), p = t.slice(0, o).join(".");
throw new TypeError(`'${a}' is not a serializable type, so property ${p} cannot be accessed.`);
}
}
default:
throw new TypeError("unreachable");
}
}
return { value: s9, parent: e, owner: r };
}
var w = class s3 extends y {
constructor(e) {
super(), this.payload = e;
}
payload;
getPayload() {
if (this.payload) return this.payload;
throw new Error("Attempted to use an RPC StubHook after it was disposed.");
}
call(e, t) {
try {
let r = this.getPayload(), o = H(r.value, void 0, e, r);
if (o.hook) return o.hook.call(o.remainingPath, t);
if (typeof o.value != "function") throw new TypeError(`'${e.join(".")}' is not a function.`);
let n = t.deliverCall(o.value, o.parent);
return new j(n.then((i) => new s3(i)));
} catch (r) {
return new f(r);
}
}
get(e) {
try {
let t = this.getPayload(), r = H(t.value, void 0, e, t);
return r.hook ? r.hook.get(r.remainingPath) : new s3(b.deepCopyFrom(r.value, r.parent, r.owner));
} catch (t) {
return new f(t);
}
}
dup() {
let e = this.getPayload();
return new s3(b.deepCopyFrom(e.value, void 0, e));
}
pull() {
return this.getPayload();
}
dispose() {
this.payload && (this.payload.dispose(), this.payload = void 0);
}
onBroken(e) {
this.payload && this.payload.value instanceof h && this.payload.value.onRpcBroken(e);
}
};
var C = class s4 extends y {
static create(e, t) {
return typeof e != "function" && (t = void 0), new s4(e, t);
}
constructor(e, t, r) {
super(), this.target = e, this.parent = t, r ? r.refcount && (this.refcount = r.refcount, ++this.refcount.count) : Symbol.dispose in e && (this.refcount = { count: 1 });
}
target;
parent;
refcount;
getTarget() {
if (this.target) return this.target;
throw new Error("Attempted to use an RPC StubHook after it was disposed.");
}
call(e, t) {
try {
let r = this.getTarget(), o = H(r, this.parent, e, null);
if (o.hook) return o.hook.call(o.remainingPath, t);
if (typeof o.value != "function") throw new TypeError(`'${e.join(".")}' is not a function.`);
let n = t.deliverCall(o.value, o.parent);
return new j(n.then((i) => new w(i)));
} catch (r) {
return new f(r);
}
}
get(e) {
try {
if (e.length == 0) throw new Error("Can't dup an RpcTarget stub as a promise.");
let t = this.getTarget(), r = H(t, this.parent, e, null);
return r.hook ? r.hook.get(r.remainingPath) : new w(b.deepCopyFrom(r.value, r.parent, r.owner));
} catch (t) {
return new f(t);
}
}
dup() {
return new s4(this.getTarget(), this.parent, this);
}
pull() {
return Promise.reject(new Error("Tried to resolve a non-promise stub."));
}
dispose() {
if (this.target) {
if (this.refcount && --this.refcount.count == 0 && Symbol.dispose in this.target) try {
this.target[Symbol.dispose]();
} catch (e) {
Promise.reject(e);
}
this.target = void 0;
}
}
onBroken(e) {
}
};
var j = class s5 extends y {
promise;
resolution;
constructor(e) {
super(), this.promise = e.then((t) => (this.resolution = t, t));
}
call(e, t) {
return new s5(this.promise.then((r) => r.call(e, t)));
}
get(e) {
return new s5(this.promise.then((t) => t.get(e)));
}
dup() {
return this.resolution ? this.resolution.dup() : new s5(this.promise.then((e) => e.dup()));
}
pull() {
return this.resolution ? this.resolution.pull() : this.promise.then((e) => e.pull());
}
dispose() {
this.resolution ? this.resolution.dispose() : this.promise.then((e) => {
e.dispose();
}, (e) => {
});
}
onBroken(e) {
this.resolution ? this.resolution.onBroken(e) : this.promise.then((t) => {
t.onBroken(e);
}, e);
}
};
var O = class {
exportStub(e) {
throw new Error("Cannot serialize RPC stubs without an RPC session.");
}
exportPromise(e) {
throw new Error("Cannot serialize RPC stubs without an RPC session.");
}
getImport(e) {
}
unexport(e) {
}
onSendError(e) {
}
};
var K = new O();
var Q = { Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError };
var R = class s6 {
constructor(e, t, r) {
this.exporter = e;
this.source = t;
this.takeOwnership = r;
}
static devaluate(e, t, r = K, o, n = true) {
let i = new s6(r, o, n);
try {
return { value: i.devaluateImpl(e, t, 0), deferredDisposals: i.deferredDisposals };
} catch (a) {
if (i.exports) try {
r.unexport(i.exports);
} catch {
}
throw i.deferredDisposals && i.deferredDisposals.forEach((p) => p.dispose()), a;
}
}
exports;
deferredDisposals;
devaluateImpl(e, t, r) {
if (r >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
let o = T(e);
switch (o) {
case "unsupported":
throw new TypeError("cannot serialize: " + e);
case "primitive":
return e;
case "object": {
let n = e, i = {};
for (let a in n) i[a] = this.devaluateImpl(n[a], n, r + 1);
return i;
}
case "array": {
let n = e, i = n.length, a = new Array(i);
for (let p = 0; p < i; p++) a[p] = this.devaluateImpl(n[p], n, r + 1);
return [a];
}
case "date":
return ["date", e.getTime()];
case "error": {
let n = e, i = this.exporter.onSendError(n);
i && (n = i);
let a = ["error", n.name, n.message];
return i && i.stack && a.push(i.stack), a;
}
case "undefined":
return ["undefined"];
case "stub":
case "rpc-promise": {
if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
let { hook: n, pathIfPromise: i } = m(e);
return this.devaluateHook(n, i);
}
case "function":
case "rpc-target": {
if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
let n = this.source.getHookForRpcTarget(e, t);
return this.devaluateHook(n, void 0);
}
default:
throw new Error("unreachable");
}
}
devaluateHook(e, t) {
let r = this.exporter.getImport(e);
if (r !== void 0) return t ? t.length > 0 ? ["pipeline", r, t] : ["pipeline", r] : (this.takeOwnership && (this.deferredDisposals || (this.deferredDisposals = []), this.deferredDisposals.push(e)), ["import", r]);
if (this.exports || (this.exports = []), t) {
if (this.source && this.source.isFromApp() || !this.takeOwnership) e = e.get(t);
else if (t.length > 0) throw new Error("RPC system bug: Unexpected uncloned promise in from-app payload.");
let o = this.exporter.exportPromise(e);
return this.exports.push(o), ["promise", o];
} else {
this.takeOwnership || (e = e.dup());
let o = this.exporter.exportStub(e);
return this.exports.push(o), ["export", o];
}
}
};
var A = class {
importStub(e) {
throw new Error("Cannot deserialize RPC stubs without an RPC session.");
}
importPromise(e) {
throw new Error("Cannot deserialize RPC stubs without an RPC session.");
}
getExport(e) {
}
};
var Y = new A();
var g = class s7 {
constructor(e) {
this.importer = e;
}
stubs = [];
promises = [];
evaluate(e) {
let t = b.forEvaluate(this.stubs, this.promises);
try {
return t.value = this.evaluateImpl(e, t, "value"), t;
} catch (r) {
throw t.dispose(), r;
}
}
evaluateImpl(e, t, r) {
if (e instanceof Array) {
if (e.length == 1 && e[0] instanceof Array) {
let o = e[0];
for (let n = 0; n < o.length; n++) o[n] = this.evaluateImpl(o[n], o, n);
return o;
} else switch (e[0]) {
case "date":
if (typeof e[1] == "number") return new Date(e[1]);
break;
case "error":
if (e.length >= 3 && typeof e[1] == "string" && typeof e[2] == "string") {
let l = Q[e[1]] || Error, u = new l(e[2]);
return typeof e[3] == "string" && (u.stack = e[3]), u;
}
break;
case "undefined":
if (e.length === 1) return;
break;
case "import":
case "pipeline":
if (e.length < 2 || e.length > 4 || typeof e[1] != "number") break;
let o = this.importer.getExport(e[1]);
if (!o) throw new Error(`no such entry on exports table: ${e[1]}`);
let n = e[0] == "pipeline", i = (l) => {
if (n) {
let u = new c(l, []);
return this.promises.push({ promise: u, parent: t, property: r }), u;
} else {
let u = new c(l, []);
return this.stubs.push(u), u;
}
};
if (e.length == 2) return i(n ? o.get([]) : o.dup());
let a = e[2];
if (!(a instanceof Array) || !a.every((l) => typeof l == "string" || typeof l == "number")) break;
if (e.length == 3) return i(o.get(a));
let p = e[3];
if (!(p instanceof Array)) break;
return p = new s7(this.importer).evaluate([p]), i(o.call(a, p));
case "export":
case "promise":
if (typeof e[1] == "number") if (e[0] == "promise") {
let l = this.importer.importPromise(e[1]), u = new c(l, []);
return this.promises.push({ parent: t, property: r, promise: u }), u;
} else {
let l = this.importer.importStub(e[1]), u = new h(l);
return this.stubs.push(u), u;
}
break;
}
throw new TypeError(`unknown special value: ${JSON.stringify(e)}`);
} else if (e instanceof Object) {
let o = e;
for (let n in o) o[n] = this.evaluateImpl(o[n], o, n);
return o;
} else return e;
}
};
var S = class {
constructor(e, t, r) {
this.session = e;
this.importId = t;
r && (this.activePull = Promise.withResolvers());
}
localRefcount = 0;
remoteRefcount = 1;
activePull;
resolution;
onBrokenRegistrations;
resolve(e) {
if (this.localRefcount == 0) {
e.dispose();
return;
}
if (this.resolution = e, this.sendRelease(), this.onBrokenRegistrations) {
for (let t of this.onBrokenRegistrations) {
let r = this.session.onBrokenCallbacks[t], o = this.session.onBrokenCallbacks.length;
e.onBroken(r), this.session.onBrokenCallbacks[o] === r ? delete this.session.onBrokenCallbacks[o] : delete this.session.onBrokenCallbacks[t];
}
this.onBrokenRegistrations = void 0;
}
this.activePull && (this.activePull.resolve(), this.activePull = void 0);
}
async awaitResolution() {
return this.activePull || (this.session.sendPull(this.importId), this.activePull = Promise.withResolvers()), await this.activePull.promise, this.resolution.pull();
}
dispose() {
this.resolution ? this.resolution.dispose() : (this.abort(new Error("RPC was canceled because the RpcPromise was disposed.")), this.sendRelease());
}
abort(e) {
this.resolution || (this.resolution = new f(e), this.activePull && (this.activePull.reject(e), this.activePull = void 0), this.onBrokenRegistrations = void 0);
}
onBroken(e) {
if (this.resolution) this.resolution.onBroken(e);
else {
let t = this.session.onBrokenCallbacks.length;
this.session.onBrokenCallbacks.push(e), this.onBrokenRegistrations || (this.onBrokenRegistrations = []), this.onBrokenRegistrations.push(t);
}
}
sendRelease() {
this.remoteRefcount > 0 && (this.session.sendRelease(this.importId, this.remoteRefcount), this.remoteRefcount = 0);
}
};
var k = class s8 extends y {
constructor(t, r) {
super();
this.isPromise = t;
++r.localRefcount, this.entry = r;
}
entry;
collectPath(t) {
return this;
}
getEntry() {
if (this.entry) return this.entry;
throw new Error("This RpcImportHook was already disposed.");
}
call(t, r) {
let o = this.getEntry();
return o.resolution ? o.resolution.call(t, r) : o.session.sendCall(o.importId, t, r);
}
get(t) {
let r = this.getEntry();
return r.resolution ? r.resolution.get(t) : r.session.sendCall(r.importId, t);
}
dup() {
return new s8(false, this.getEntry());
}
pull() {
let t = this.getEntry();
if (!this.isPromise) throw new Error("Can't pull this hook because it's not a promise hook.");
return t.resolution ? t.resolution.pull() : t.awaitResolution();
}
dispose() {
let t = this.entry;
this.entry = void 0, t && --t.localRefcount === 0 && t.dispose();
}
onBroken(t) {
this.entry && this.entry.onBroken(t);
}
};
var D = class extends k {
session;
constructor(e) {
super(false, e), this.session = e.session;
}
dispose() {
if (this.session) {
let e = this.session;
this.session = void 0, e.shutdown();
}
}
};
var F = class {
constructor(e, t, r) {
this.transport = e;
this.options = r;
this.exports.push({ hook: t, refcount: 1 }), this.imports.push(new S(this, 0, false));
let o, n = new Promise((i, a) => {
o = a;
});
this.cancelReadLoop = o, this.readLoop(n).catch((i) => this.abort(i));
}
exports = [];
reverseExports = /* @__PURE__ */ new Map();
imports = [];
abortReason;
cancelReadLoop;
nextExportId = -1;
onBatchDone;
pullCount = 0;
onBrokenCallbacks = [];
getMainImport() {
return new D(this.imports[0]);
}
shutdown() {
this.abort(new Error("RPC session was shut down by disposing the main stub"), false);
}
exportStub(e) {
if (this.abortReason) throw this.abortReason;
let t = this.reverseExports.get(e);
if (t !== void 0) return ++this.exports[t].refcount, t;
{
let r = this.nextExportId--;
return this.exports[r] = { hook: e, refcount: 1 }, this.reverseExports.set(e, r), r;
}
}
exportPromise(e) {
if (this.abortReason) throw this.abortReason;
let t = this.nextExportId--;
return this.exports[t] = { hook: e, refcount: 1 }, this.reverseExports.set(e, t), this.ensureResolvingExport(t), t;
}
unexport(e) {
for (let t of e) this.releaseExport(t, 1);
}
releaseExport(e, t) {
let r = this.exports[e];
if (!r) throw new Error(`no such export ID: ${e}`);
if (r.refcount < t) throw new Error(`refcount would go negative: ${r.refcount} < ${t}`);
r.refcount -= t, r.refcount === 0 && (delete this.exports[e], this.reverseExports.delete(r.hook), r.hook.dispose());
}
onSendError(e) {
if (this.options.onSendError) return this.options.onSendError(e);
}
ensureResolvingExport(e) {
let t = this.exports[e];
if (!t) throw new Error(`no such export ID: ${e}`);
if (!t.pull) {
let r = async () => {
let o = t.hook;
for (; ; ) {
let n = await o.pull();
if (n.value instanceof h) {
let { hook: i, pathIfPromise: a } = m(n.value);
if (a && a.length == 0 && this.getImport(o) === void 0) {
o = i;
continue;
}
}
return n;
}
};
++this.pullCount, t.pull = r().then((o) => {
let { value: n, deferredDisposals: i } = R.devaluate(o.value, void 0, this, o, false);
this.send(["resolve", e, n]), i && i?.forEach((a) => a.dispose());
}, (o) => {
this.send(["reject", e, R.devaluate(o, void 0, this).value]);
}).catch((o) => {
try {
this.send(["reject", e, R.devaluate(o, void 0, this).value]);
} catch (n) {
this.abort(n);
}
}).finally(() => {
--this.pullCount === 0 && this.onBatchDone && this.onBatchDone.resolve();
});
}
}
getImport(e) {
if (e instanceof k && e.entry && e.entry.session === this) return e.entry.importId;
}
importStub(e) {
if (this.abortReason) throw this.abortReason;
let t = this.imports[e];
return t || (t = new S(this, e, false), this.imports[e] = t), new k(false, t);
}
importPromise(e) {
if (this.abortReason) throw this.abortReason;
if (this.imports[e]) return new f(new Error("Bug in RPC system: The peer sent a promise reusing an existing export ID."));
let t = new S(this, e, true);
return this.imports[e] = t, new k(true, t);
}
getExport(e) {
return this.exports[e]?.hook;
}
send(e) {
if (this.abortReason !== void 0) return;
let t;
try {
t = JSON.stringify(e);
} catch (r) {
throw r;
}
this.transport.send(t).catch((r) => this.abort(r, false));
}
sendCall(e, t, r) {
if (this.abortReason) throw this.abortReason;
let o = ["pipeline", e, t], n;
if (r) {
let a = R.devaluate(r.value, void 0, this, r, true);
n = a.deferredDisposals, o.push(a.value[0]);
}
this.send(["push", o]), n && n?.forEach((a) => a.dispose());
let i = new S(this, this.imports.length, false);
return this.imports.push(i), new k(true, i);
}
sendPull(e) {
if (this.abortReason) throw this.abortReason;
this.send(["pull", e]);
}
sendRelease(e, t) {
this.abortReason || (this.send(["release", e, t]), delete this.imports[e]);
}
abort(e, t = true) {
if (this.abortReason === void 0) {
if (this.cancelReadLoop(e), t) try {
this.transport.send(JSON.stringify(["abort", R.devaluate(e, void 0, this)]));
} catch {
}
if (e === void 0 && (e = "undefined"), this.abortReason = e, this.onBatchDone && this.onBatchDone.reject(e), this.transport.abort) try {
this.transport.abort(e);
} catch (r) {
Promise.resolve(r);
}
for (let r in this.onBrokenCallbacks) try {
this.onBrokenCallbacks[r](e);
} catch (o) {
Promise.resolve(o);
}
for (let r in this.imports) this.imports[r].abort(e);
for (let r in this.exports) this.exports[r].hook.dispose();
}
}
async readLoop(e) {
for (; !this.abortReason; ) {
let t = JSON.parse(await Promise.race([this.transport.receive(), e]));
if (this.abortReason) break;
if (t instanceof Array) switch (t[0]) {
case "push":
if (t.length > 1) {
let r = new g(this).evaluate(t[1]);
this.exports.push({ hook: new w(r), refcount: 1 });
continue;
}
break;
case "pull": {
let r = t[1];
if (typeof r == "number") {
this.ensureResolvingExport(r);
continue;
}
break;
}
case "resolve":
case "reject": {
let r = t[1];
if (typeof r == "number" && t.length > 2) {
let o = this.imports[r];
if (o) if (t[0] == "resolve") o.resolve(new w(new g(this).evaluate(t[2])));
else {
let n = new g(this).evaluate(t[2]);
n.dispose(), o.resolve(new f(n.value));
}
else t[0] == "resolve" && new g(this).evaluate(t[2]).dispose();
continue;
}
break;
}
case "release": {
let r = t[1], o = t[2];
if (typeof r == "number" && typeof o == "number") {
this.releaseExport(r, o);
continue;
}
break;
}
case "abort": {
let r = new g(this).evaluate(t[1]);
r.dispose(), this.abort(r, false);
break;
}
}
throw new Error(`bad RPC message: ${JSON.stringify(t)}`);
}
}
async drain() {
if (this.abortReason) throw this.abortReason;
if (this.pullCount > 0) {
let { promise: e, resolve: t, reject: r } = Promise.withResolvers();
this.onBatchDone = { resolve: t, reject: r }, await e;
}
}
getStats() {
let e = { imports: 0, exports: 0 };
for (let t in this.imports) ++e.imports;
for (let t in this.exports) ++e.exports;
return e;
}
};
var P = class {
#t;
#e;
constructor(e, t, r = {}) {
let o;
t ? o = new w(b.fromApp(t)) : o = new f(new Error("This connection has no main object.")), this.#t = new F(e, o, r), this.#e = new h(this.#t.getMainImport());
}
getRemoteMain() {
return this.#e;
}
getStats() {
return this.#t.getStats();
}
drain() {
return this.#t.drain();
}
};
function z(s9, e, t) {
typeof s9 == "string" && (s9 = new WebSocket(s9));
let r = new W(s9);
return new P(r, e, t).getRemoteMain();
}
function M(s9, e, t) {
if (s9.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response("This endpoint only accepts WebSocket requests.", { status: 400 });
let r = new WebSocketPair(), o = r[0];
return o.accept(), z(o, e, t), new Response(null, { status: 101, webSocket: r[1] });
}
var W = class {
constructor(e) {
this.#t = e, e.readyState === WebSocket.CONNECTING && (this.#e = [], e.addEventListener("open", (t) => {
try {
for (let r of this.#e) e.send(r);
} catch (r) {
this.#i(r);
}
this.#e = void 0;
})), e.addEventListener("message", (t) => {
this.#s || (typeof t.data == "string" ? this.#r ? (this.#r(t.data), this.#r = void 0, this.#o = void 0) : this.#n.push(t.data) : this.#i(new TypeError("Received non-string message from WebSocket.")));
}), e.addEventListener("close", (t) => {
this.#i(new Error(`Peer closed WebSocket: ${t.code} ${t.reason}`));
}), e.addEventListener("error", (t) => {
this.#i(new Error("WebSocket connection failed."));
});
}
#t;
#e;
#r;
#o;
#n = [];
#s;
async send(e) {
this.#e === void 0 ? this.#t.send(e) : this.#e.push(e);
}
async receive() {
if (this.#n.length > 0) return this.#n.shift();
if (this.#s) throw this.#s;
return new Promise((e, t) => {
this.#r = e, this.#o = t;
});
}
abort(e) {
let t;
e instanceof Error ? t = e.message : t = `${e}`, this.#t.close(3e3, t), this.#s || (this.#s = e);
}
#i(e) {
this.#s || (this.#s = e, this.#o && (this.#o(e), this.#r = void 0, this.#o = void 0));
}
};
var $ = class {
constructor(e) {
this.#e = e;
}
#t = [];
#e;
#r = Promise.withResolvers();
async send(e) {
this.#t.push(e);
}
async receive() {
let e = this.#e.shift();
return e !== void 0 ? e : (this.#r.resolve(), new Promise((t) => {
}));
}
abort(e) {
this.#r.reject(e);
}
whenAllReceived() {
return this.#r.promise;
}
getResponseBody() {
return this.#t.join(`
`);
}
};
async function U(s9, e, t) {
if (s9.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
let r = await s9.text(), o = r === "" ? [] : r.split(`
`), n = new $(o), i = new P(n, e, t);
return await n.whenAllReceived(), await i.drain(), new Response(n.getResponseBody());
}
function We(s9, e) {
return s9.method === "POST" ? U(s9, e) : s9.headers.get("Upgrade")?.toLowerCase() === "websocket" ? M(s9, e) : new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
}
// templates/remoteBindings/ProxyServerWorker.ts
import { EmailMessage } from "cloudflare:email";
var BindingNotFoundError = class extends Error {
constructor(name) {
super(`Binding ${name ? `"${name}"` : ""} not found`);
}
};
function getExposedJSRPCBinding(request, env) {
const url = new URL(request.url);
const bindingName = url.searchParams.get("MF-Binding");
if (!bindingName) {
throw new BindingNotFoundError();
}
const targetBinding = env[bindingName];
if (!targetBinding) {
throw new BindingNotFoundError(bindingName);
}
if (targetBinding.constructor.name === "SendEmail") {
return {
async send(e) {
const message = new EmailMessage(e.from, e.to, e["EmailMessage::raw"]);
return targetBinding.send(message);
}
};
}
if (url.searchParams.has("MF-Dispatch-Namespace-Options")) {
const { name, args, options } = JSON.parse(
url.searchParams.get("MF-Dispatch-Namespace-Options")
);
return targetBinding.get(name, args, options);
}
return targetBinding;
}
function getExposedFetcher(request, env) {
const bindingName = request.headers.get("MF-Binding");
if (!bindingName) {
throw new BindingNotFoundError();
}
const targetBinding = env[bindingName];
if (!targetBinding) {
throw new BindingNotFoundError(bindingName);
}
const dispatchNamespaceOptions = request.headers.get(
"MF-Dispatch-Namespace-Options"
);
if (dispatchNamespaceOptions) {
const { name, args, options } = JSON.parse(dispatchNamespaceOptions);
return targetBinding.get(name, args, options);
}
return targetBinding;
}
function isJSRPCBinding(request) {
const url = new URL(request.url);
return request.headers.has("Upgrade") && url.searchParams.has("MF-Binding");
}
var ProxyServerWorker_default = {
async fetch(request, env) {
try {
if (isJSRPCBinding(request)) {
return We(
request,
getExposedJSRPCBinding(request, env)
);
} else {
const fetcher = getExposedFetcher(request, env);
const originalHeaders = new Headers();
for (const [name, value] of request.headers) {
if (name.startsWith("mf-header-")) {
originalHeaders.set(name.slice("mf-header-".length), value);
} else if (name === "upgrade") {
originalHeaders.set(name, value);
}
}
return fetcher.fetch(
request.headers.get("MF-URL") ?? "http://example.com",
new Request(request, {
redirect: "manual",
headers: originalHeaders
})
);
}
} catch (e) {
if (e instanceof BindingNotFoundError) {
return new Response(e.message, { status: 400 });
}
return new Response(e.message, { status: 500 });
}
}
};
export {
ProxyServerWorker_default as default
};