summaryrefslogtreecommitdiff
path: root/node_modules/miniflare/dist/src/index.js
diff options
context:
space:
mode:
authorakiyamn2023-09-24 23:22:21 +1000
committerakiyamn2023-09-24 23:22:21 +1000
commit4e87195739f2a5d9a05451b48773c8afdc680765 (patch)
tree9cba501844a4a11dcbdffc4050ed8189561c55ed /node_modules/miniflare/dist/src/index.js
downloadprice-tracker-worker-4e87195739f2a5d9a05451b48773c8afdc680765.tar.gz
price-tracker-worker-4e87195739f2a5d9a05451b48773c8afdc680765.zip
Initial commit (by create-cloudflare CLI)
Diffstat (limited to 'node_modules/miniflare/dist/src/index.js')
-rw-r--r--node_modules/miniflare/dist/src/index.js8150
1 files changed, 8150 insertions, 0 deletions
diff --git a/node_modules/miniflare/dist/src/index.js b/node_modules/miniflare/dist/src/index.js
new file mode 100644
index 0000000..3347e78
--- /dev/null
+++ b/node_modules/miniflare/dist/src/index.js
@@ -0,0 +1,8150 @@
+"use strict";
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __commonJS = (cb, mod) => function __require() {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+};
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var __publicField = (obj, key, value) => {
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
+ return value;
+};
+var __accessCheck = (obj, member, msg) => {
+ if (!member.has(obj))
+ throw TypeError("Cannot " + msg);
+};
+var __privateGet = (obj, member, getter) => {
+ __accessCheck(obj, member, "read from private field");
+ return getter ? getter.call(obj) : member.get(obj);
+};
+var __privateAdd = (obj, member, value) => {
+ if (member.has(obj))
+ throw TypeError("Cannot add the same private member more than once");
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
+};
+var __privateSet = (obj, member, value, setter) => {
+ __accessCheck(obj, member, "write to private field");
+ setter ? setter.call(obj, value) : member.set(obj, value);
+ return value;
+};
+var __privateMethod = (obj, member, method) => {
+ __accessCheck(obj, member, "access private method");
+ return method;
+};
+
+// packages/miniflare/src/runtime/config/workerd.capnp.js
+var require_workerd_capnp = __commonJS({
+ "packages/miniflare/src/runtime/config/workerd.capnp.js"(exports) {
+ "use strict";
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.Extension = exports.Extension_Module = exports.TlsOptions = exports.TlsOptions_Version = exports.TlsOptions_Keypair = exports.HttpOptions = exports.HttpOptions_Header = exports.HttpOptions_Style = exports.DiskDirectory = exports.Network = exports.ExternalServer = exports.ExternalServer_Which = exports.ExternalServer_Https = exports.Worker = exports.Worker_Which = exports.Worker_DurableObjectStorage = exports.Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectNamespace = exports.Worker_DurableObjectNamespace_Which = exports.Worker_Binding = exports.Worker_Binding_Which = exports.Worker_Binding_Parameter = exports.Worker_Binding_WrappedBinding = exports.Worker_Binding_CryptoKey = exports.Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Algorithm = exports.Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Usage = exports.Worker_Binding_DurableObjectNamespaceDesignator = exports.Worker_Binding_Type = exports.Worker_Binding_Type_Which = exports.Worker_Module = exports.Worker_Module_Which = exports.ServiceDesignator = exports.Service = exports.Service_Which = exports.Socket = exports.Socket_Which = exports.Socket_Https = exports.Config = exports._capnpFileId = void 0;
+ var capnp = require("capnp-ts");
+ var capnp_ts_1 = require("capnp-ts");
+ exports._capnpFileId = "e6afd26682091c01";
+ var Config3 = class extends capnp_ts_1.Struct {
+ adoptServices(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownServices() {
+ return capnp_ts_1.Struct.disown(this.getServices());
+ }
+ getServices() {
+ return capnp_ts_1.Struct.getList(0, Config3._Services, this);
+ }
+ hasServices() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initServices(length) {
+ return capnp_ts_1.Struct.initList(0, Config3._Services, length, this);
+ }
+ setServices(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ adoptSockets(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownSockets() {
+ return capnp_ts_1.Struct.disown(this.getSockets());
+ }
+ getSockets() {
+ return capnp_ts_1.Struct.getList(1, Config3._Sockets, this);
+ }
+ hasSockets() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initSockets(length) {
+ return capnp_ts_1.Struct.initList(1, Config3._Sockets, length, this);
+ }
+ setSockets(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptV8Flags(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownV8Flags() {
+ return capnp_ts_1.Struct.disown(this.getV8Flags());
+ }
+ getV8Flags() {
+ return capnp_ts_1.Struct.getList(2, capnp.TextList, this);
+ }
+ hasV8Flags() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initV8Flags(length) {
+ return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this);
+ }
+ setV8Flags(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ adoptExtensions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ disownExtensions() {
+ return capnp_ts_1.Struct.disown(this.getExtensions());
+ }
+ getExtensions() {
+ return capnp_ts_1.Struct.getList(3, Config3._Extensions, this);
+ }
+ hasExtensions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this));
+ }
+ initExtensions(length) {
+ return capnp_ts_1.Struct.initList(3, Config3._Extensions, length, this);
+ }
+ setExtensions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ toString() {
+ return "Config_" + super.toString();
+ }
+ };
+ exports.Config = Config3;
+ Config3._capnp = { displayName: "Config", id: "8794486c76aaa7d6", size: new capnp_ts_1.ObjectSize(0, 4) };
+ var Socket_Https = class extends capnp_ts_1.Struct {
+ adoptOptions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownOptions() {
+ return capnp_ts_1.Struct.disown(this.getOptions());
+ }
+ getOptions() {
+ return capnp_ts_1.Struct.getStruct(2, HttpOptions, this);
+ }
+ hasOptions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initOptions() {
+ return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this);
+ }
+ setOptions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ adoptTlsOptions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ disownTlsOptions() {
+ return capnp_ts_1.Struct.disown(this.getTlsOptions());
+ }
+ getTlsOptions() {
+ return capnp_ts_1.Struct.getStruct(3, TlsOptions, this);
+ }
+ hasTlsOptions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this));
+ }
+ initTlsOptions() {
+ return capnp_ts_1.Struct.initStructAt(3, TlsOptions, this);
+ }
+ setTlsOptions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ toString() {
+ return "Socket_Https_" + super.toString();
+ }
+ };
+ exports.Socket_Https = Socket_Https;
+ Socket_Https._capnp = { displayName: "https", id: "de123876383cbbdc", size: new capnp_ts_1.ObjectSize(8, 5) };
+ var Socket_Which;
+ (function(Socket_Which2) {
+ Socket_Which2[Socket_Which2["HTTP"] = 0] = "HTTP";
+ Socket_Which2[Socket_Which2["HTTPS"] = 1] = "HTTPS";
+ })(Socket_Which = exports.Socket_Which || (exports.Socket_Which = {}));
+ var Socket2 = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getAddress() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setAddress(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptHttp(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownHttp() {
+ return capnp_ts_1.Struct.disown(this.getHttp());
+ }
+ getHttp() {
+ capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getStruct(2, HttpOptions, this);
+ }
+ hasHttp() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initHttp() {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this);
+ }
+ isHttp() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setHttp(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ getHttps() {
+ capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getAs(Socket_Https, this);
+ }
+ initHttps() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ return capnp_ts_1.Struct.getAs(Socket_Https, this);
+ }
+ isHttps() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setHttps() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ }
+ adoptService(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this));
+ }
+ disownService() {
+ return capnp_ts_1.Struct.disown(this.getService());
+ }
+ getService() {
+ return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this);
+ }
+ hasService() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this));
+ }
+ initService() {
+ return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this);
+ }
+ setService(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this));
+ }
+ toString() {
+ return "Socket_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Socket = Socket2;
+ Socket2.HTTP = Socket_Which.HTTP;
+ Socket2.HTTPS = Socket_Which.HTTPS;
+ Socket2._capnp = { displayName: "Socket", id: "9a0eba45530ee79f", size: new capnp_ts_1.ObjectSize(8, 5) };
+ var Service_Which;
+ (function(Service_Which2) {
+ Service_Which2[Service_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
+ Service_Which2[Service_Which2["WORKER"] = 1] = "WORKER";
+ Service_Which2[Service_Which2["NETWORK"] = 2] = "NETWORK";
+ Service_Which2[Service_Which2["EXTERNAL"] = 3] = "EXTERNAL";
+ Service_Which2[Service_Which2["DISK"] = 4] = "DISK";
+ })(Service_Which = exports.Service_Which || (exports.Service_Which = {}));
+ var Service4 = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ isUnspecified() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setUnspecified() {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ }
+ adoptWorker(value) {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownWorker() {
+ return capnp_ts_1.Struct.disown(this.getWorker());
+ }
+ getWorker() {
+ capnp_ts_1.Struct.testWhich("worker", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getStruct(1, Worker2, this);
+ }
+ hasWorker() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initWorker() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ return capnp_ts_1.Struct.initStructAt(1, Worker2, this);
+ }
+ isWorker() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setWorker(value) {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptNetwork(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownNetwork() {
+ return capnp_ts_1.Struct.disown(this.getNetwork());
+ }
+ getNetwork() {
+ capnp_ts_1.Struct.testWhich("network", capnp_ts_1.Struct.getUint16(0, this), 2, this);
+ return capnp_ts_1.Struct.getStruct(1, Network, this);
+ }
+ hasNetwork() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initNetwork() {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ return capnp_ts_1.Struct.initStructAt(1, Network, this);
+ }
+ isNetwork() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setNetwork(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptExternal(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownExternal() {
+ return capnp_ts_1.Struct.disown(this.getExternal());
+ }
+ getExternal() {
+ capnp_ts_1.Struct.testWhich("external", capnp_ts_1.Struct.getUint16(0, this), 3, this);
+ return capnp_ts_1.Struct.getStruct(1, ExternalServer2, this);
+ }
+ hasExternal() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initExternal() {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ return capnp_ts_1.Struct.initStructAt(1, ExternalServer2, this);
+ }
+ isExternal() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 3;
+ }
+ setExternal(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptDisk(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownDisk() {
+ return capnp_ts_1.Struct.disown(this.getDisk());
+ }
+ getDisk() {
+ capnp_ts_1.Struct.testWhich("disk", capnp_ts_1.Struct.getUint16(0, this), 4, this);
+ return capnp_ts_1.Struct.getStruct(1, DiskDirectory, this);
+ }
+ hasDisk() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initDisk() {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ return capnp_ts_1.Struct.initStructAt(1, DiskDirectory, this);
+ }
+ isDisk() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 4;
+ }
+ setDisk(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ toString() {
+ return "Service_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Service = Service4;
+ Service4.UNSPECIFIED = Service_Which.UNSPECIFIED;
+ Service4.WORKER = Service_Which.WORKER;
+ Service4.NETWORK = Service_Which.NETWORK;
+ Service4.EXTERNAL = Service_Which.EXTERNAL;
+ Service4.DISK = Service_Which.DISK;
+ Service4._capnp = { displayName: "Service", id: "e5c88e8bb7bcb6b9", size: new capnp_ts_1.ObjectSize(8, 2) };
+ var ServiceDesignator2 = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getEntrypoint() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setEntrypoint(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "ServiceDesignator_" + super.toString();
+ }
+ };
+ exports.ServiceDesignator = ServiceDesignator2;
+ ServiceDesignator2._capnp = { displayName: "ServiceDesignator", id: "ae8ec91cee724450", size: new capnp_ts_1.ObjectSize(0, 2) };
+ var Worker_Module_Which;
+ (function(Worker_Module_Which2) {
+ Worker_Module_Which2[Worker_Module_Which2["ES_MODULE"] = 0] = "ES_MODULE";
+ Worker_Module_Which2[Worker_Module_Which2["COMMON_JS_MODULE"] = 1] = "COMMON_JS_MODULE";
+ Worker_Module_Which2[Worker_Module_Which2["TEXT"] = 2] = "TEXT";
+ Worker_Module_Which2[Worker_Module_Which2["DATA"] = 3] = "DATA";
+ Worker_Module_Which2[Worker_Module_Which2["WASM"] = 4] = "WASM";
+ Worker_Module_Which2[Worker_Module_Which2["JSON"] = 5] = "JSON";
+ Worker_Module_Which2[Worker_Module_Which2["NODE_JS_COMPAT_MODULE"] = 6] = "NODE_JS_COMPAT_MODULE";
+ })(Worker_Module_Which = exports.Worker_Module_Which || (exports.Worker_Module_Which = {}));
+ var Worker_Module3 = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getEsModule() {
+ capnp_ts_1.Struct.testWhich("esModule", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isEsModule() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setEsModule(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ getCommonJsModule() {
+ capnp_ts_1.Struct.testWhich("commonJsModule", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isCommonJsModule() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setCommonJsModule(value) {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ getText() {
+ capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isText() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setText(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptData(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownData() {
+ return capnp_ts_1.Struct.disown(this.getData());
+ }
+ getData() {
+ capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this);
+ return capnp_ts_1.Struct.getData(1, this);
+ }
+ hasData() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initData(length) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ return capnp_ts_1.Struct.initData(1, length, this);
+ }
+ isData() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 3;
+ }
+ setData(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptWasm(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownWasm() {
+ return capnp_ts_1.Struct.disown(this.getWasm());
+ }
+ getWasm() {
+ capnp_ts_1.Struct.testWhich("wasm", capnp_ts_1.Struct.getUint16(0, this), 4, this);
+ return capnp_ts_1.Struct.getData(1, this);
+ }
+ hasWasm() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initWasm(length) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ return capnp_ts_1.Struct.initData(1, length, this);
+ }
+ isWasm() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 4;
+ }
+ setWasm(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getJson() {
+ capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 5, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isJson() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 5;
+ }
+ setJson(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ getNodeJsCompatModule() {
+ capnp_ts_1.Struct.testWhich("nodeJsCompatModule", capnp_ts_1.Struct.getUint16(0, this), 6, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isNodeJsCompatModule() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 6;
+ }
+ setNodeJsCompatModule(value) {
+ capnp_ts_1.Struct.setUint16(0, 6, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "Worker_Module_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker_Module = Worker_Module3;
+ Worker_Module3.ES_MODULE = Worker_Module_Which.ES_MODULE;
+ Worker_Module3.COMMON_JS_MODULE = Worker_Module_Which.COMMON_JS_MODULE;
+ Worker_Module3.TEXT = Worker_Module_Which.TEXT;
+ Worker_Module3.DATA = Worker_Module_Which.DATA;
+ Worker_Module3.WASM = Worker_Module_Which.WASM;
+ Worker_Module3.JSON = Worker_Module_Which.JSON;
+ Worker_Module3.NODE_JS_COMPAT_MODULE = Worker_Module_Which.NODE_JS_COMPAT_MODULE;
+ Worker_Module3._capnp = { displayName: "Module", id: "d9d87a63770a12f3", size: new capnp_ts_1.ObjectSize(8, 2) };
+ var Worker_Binding_Type_Which;
+ (function(Worker_Binding_Type_Which2) {
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["TEXT"] = 1] = "TEXT";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DATA"] = 2] = "DATA";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["JSON"] = 3] = "JSON";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["WASM"] = 4] = "WASM";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["CRYPTO_KEY"] = 5] = "CRYPTO_KEY";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["SERVICE"] = 6] = "SERVICE";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DURABLE_OBJECT_NAMESPACE"] = 7] = "DURABLE_OBJECT_NAMESPACE";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["KV_NAMESPACE"] = 8] = "KV_NAMESPACE";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2BUCKET"] = 9] = "R2BUCKET";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2ADMIN"] = 10] = "R2ADMIN";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["QUEUE"] = 11] = "QUEUE";
+ Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["ANALYTICS_ENGINE"] = 12] = "ANALYTICS_ENGINE";
+ })(Worker_Binding_Type_Which = exports.Worker_Binding_Type_Which || (exports.Worker_Binding_Type_Which = {}));
+ var Worker_Binding_Type = class extends capnp_ts_1.Struct {
+ isUnspecified() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setUnspecified() {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ }
+ isText() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setText() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ }
+ isData() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setData() {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ }
+ isJson() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 3;
+ }
+ setJson() {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ }
+ isWasm() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 4;
+ }
+ setWasm() {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ }
+ adoptCryptoKey(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownCryptoKey() {
+ return capnp_ts_1.Struct.disown(this.getCryptoKey());
+ }
+ getCryptoKey() {
+ capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 5, this);
+ return capnp_ts_1.Struct.getList(0, capnp.Uint16List, this);
+ }
+ hasCryptoKey() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initCryptoKey(length) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ return capnp_ts_1.Struct.initList(0, capnp.Uint16List, length, this);
+ }
+ isCryptoKey() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 5;
+ }
+ setCryptoKey(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ isService() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 6;
+ }
+ setService() {
+ capnp_ts_1.Struct.setUint16(0, 6, this);
+ }
+ isDurableObjectNamespace() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 7;
+ }
+ setDurableObjectNamespace() {
+ capnp_ts_1.Struct.setUint16(0, 7, this);
+ }
+ isKvNamespace() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 8;
+ }
+ setKvNamespace() {
+ capnp_ts_1.Struct.setUint16(0, 8, this);
+ }
+ isR2Bucket() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 9;
+ }
+ setR2Bucket() {
+ capnp_ts_1.Struct.setUint16(0, 9, this);
+ }
+ isR2Admin() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 10;
+ }
+ setR2Admin() {
+ capnp_ts_1.Struct.setUint16(0, 10, this);
+ }
+ isQueue() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 11;
+ }
+ setQueue() {
+ capnp_ts_1.Struct.setUint16(0, 11, this);
+ }
+ isAnalyticsEngine() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 12;
+ }
+ setAnalyticsEngine() {
+ capnp_ts_1.Struct.setUint16(0, 12, this);
+ }
+ toString() {
+ return "Worker_Binding_Type_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker_Binding_Type = Worker_Binding_Type;
+ Worker_Binding_Type.UNSPECIFIED = Worker_Binding_Type_Which.UNSPECIFIED;
+ Worker_Binding_Type.TEXT = Worker_Binding_Type_Which.TEXT;
+ Worker_Binding_Type.DATA = Worker_Binding_Type_Which.DATA;
+ Worker_Binding_Type.JSON = Worker_Binding_Type_Which.JSON;
+ Worker_Binding_Type.WASM = Worker_Binding_Type_Which.WASM;
+ Worker_Binding_Type.CRYPTO_KEY = Worker_Binding_Type_Which.CRYPTO_KEY;
+ Worker_Binding_Type.SERVICE = Worker_Binding_Type_Which.SERVICE;
+ Worker_Binding_Type.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Type_Which.DURABLE_OBJECT_NAMESPACE;
+ Worker_Binding_Type.KV_NAMESPACE = Worker_Binding_Type_Which.KV_NAMESPACE;
+ Worker_Binding_Type.R2BUCKET = Worker_Binding_Type_Which.R2BUCKET;
+ Worker_Binding_Type.R2ADMIN = Worker_Binding_Type_Which.R2ADMIN;
+ Worker_Binding_Type.QUEUE = Worker_Binding_Type_Which.QUEUE;
+ Worker_Binding_Type.ANALYTICS_ENGINE = Worker_Binding_Type_Which.ANALYTICS_ENGINE;
+ Worker_Binding_Type._capnp = { displayName: "Type", id: "8906a1296519bf8a", size: new capnp_ts_1.ObjectSize(8, 1) };
+ var Worker_Binding_DurableObjectNamespaceDesignator2 = class extends capnp_ts_1.Struct {
+ getClassName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setClassName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getServiceName() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setServiceName(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "Worker_Binding_DurableObjectNamespaceDesignator_" + super.toString();
+ }
+ };
+ exports.Worker_Binding_DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2;
+ Worker_Binding_DurableObjectNamespaceDesignator2._capnp = { displayName: "DurableObjectNamespaceDesignator", id: "804f144ff477aac7", size: new capnp_ts_1.ObjectSize(0, 2) };
+ var Worker_Binding_CryptoKey_Usage2;
+ (function(Worker_Binding_CryptoKey_Usage3) {
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["ENCRYPT"] = 0] = "ENCRYPT";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DECRYPT"] = 1] = "DECRYPT";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["SIGN"] = 2] = "SIGN";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["VERIFY"] = 3] = "VERIFY";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_KEY"] = 4] = "DERIVE_KEY";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_BITS"] = 5] = "DERIVE_BITS";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["WRAP_KEY"] = 6] = "WRAP_KEY";
+ Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["UNWRAP_KEY"] = 7] = "UNWRAP_KEY";
+ })(Worker_Binding_CryptoKey_Usage2 = exports.Worker_Binding_CryptoKey_Usage || (exports.Worker_Binding_CryptoKey_Usage = {}));
+ var Worker_Binding_CryptoKey_Algorithm_Which;
+ (function(Worker_Binding_CryptoKey_Algorithm_Which2) {
+ Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["NAME"] = 0] = "NAME";
+ Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["JSON"] = 1] = "JSON";
+ })(Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Algorithm_Which || (exports.Worker_Binding_CryptoKey_Algorithm_Which = {}));
+ var Worker_Binding_CryptoKey_Algorithm = class extends capnp_ts_1.Struct {
+ getName() {
+ capnp_ts_1.Struct.testWhich("name", capnp_ts_1.Struct.getUint16(2, this), 0, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isName() {
+ return capnp_ts_1.Struct.getUint16(2, this) === 0;
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setUint16(2, 0, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ getJson() {
+ capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(2, this), 1, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isJson() {
+ return capnp_ts_1.Struct.getUint16(2, this) === 1;
+ }
+ setJson(value) {
+ capnp_ts_1.Struct.setUint16(2, 1, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "Worker_Binding_CryptoKey_Algorithm_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(2, this);
+ }
+ };
+ exports.Worker_Binding_CryptoKey_Algorithm = Worker_Binding_CryptoKey_Algorithm;
+ Worker_Binding_CryptoKey_Algorithm.NAME = Worker_Binding_CryptoKey_Algorithm_Which.NAME;
+ Worker_Binding_CryptoKey_Algorithm.JSON = Worker_Binding_CryptoKey_Algorithm_Which.JSON;
+ Worker_Binding_CryptoKey_Algorithm._capnp = { displayName: "algorithm", id: "a1a040c5e00d7021", size: new capnp_ts_1.ObjectSize(8, 3) };
+ var Worker_Binding_CryptoKey_Which;
+ (function(Worker_Binding_CryptoKey_Which2) {
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["RAW"] = 0] = "RAW";
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["HEX"] = 1] = "HEX";
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["BASE64"] = 2] = "BASE64";
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["PKCS8"] = 3] = "PKCS8";
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["SPKI"] = 4] = "SPKI";
+ Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["JWK"] = 5] = "JWK";
+ })(Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Which || (exports.Worker_Binding_CryptoKey_Which = {}));
+ var Worker_Binding_CryptoKey = class extends capnp_ts_1.Struct {
+ adoptRaw(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownRaw() {
+ return capnp_ts_1.Struct.disown(this.getRaw());
+ }
+ getRaw() {
+ capnp_ts_1.Struct.testWhich("raw", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getData(0, this);
+ }
+ hasRaw() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initRaw(length) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ return capnp_ts_1.Struct.initData(0, length, this);
+ }
+ isRaw() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setRaw(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ getHex() {
+ capnp_ts_1.Struct.testWhich("hex", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isHex() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setHex(value) {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getBase64() {
+ capnp_ts_1.Struct.testWhich("base64", capnp_ts_1.Struct.getUint16(0, this), 2, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isBase64() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setBase64(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getPkcs8() {
+ capnp_ts_1.Struct.testWhich("pkcs8", capnp_ts_1.Struct.getUint16(0, this), 3, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isPkcs8() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 3;
+ }
+ setPkcs8(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getSpki() {
+ capnp_ts_1.Struct.testWhich("spki", capnp_ts_1.Struct.getUint16(0, this), 4, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isSpki() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 4;
+ }
+ setSpki(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getJwk() {
+ capnp_ts_1.Struct.testWhich("jwk", capnp_ts_1.Struct.getUint16(0, this), 5, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isJwk() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 5;
+ }
+ setJwk(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getAlgorithm() {
+ return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this);
+ }
+ initAlgorithm() {
+ return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this);
+ }
+ getExtractable() {
+ return capnp_ts_1.Struct.getBit(32, this, Worker_Binding_CryptoKey._capnp.defaultExtractable);
+ }
+ setExtractable(value) {
+ capnp_ts_1.Struct.setBit(32, value, this);
+ }
+ adoptUsages(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownUsages() {
+ return capnp_ts_1.Struct.disown(this.getUsages());
+ }
+ getUsages() {
+ return capnp_ts_1.Struct.getList(2, capnp.Uint16List, this);
+ }
+ hasUsages() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initUsages(length) {
+ return capnp_ts_1.Struct.initList(2, capnp.Uint16List, length, this);
+ }
+ setUsages(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ toString() {
+ return "Worker_Binding_CryptoKey_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker_Binding_CryptoKey = Worker_Binding_CryptoKey;
+ Worker_Binding_CryptoKey.RAW = Worker_Binding_CryptoKey_Which.RAW;
+ Worker_Binding_CryptoKey.HEX = Worker_Binding_CryptoKey_Which.HEX;
+ Worker_Binding_CryptoKey.BASE64 = Worker_Binding_CryptoKey_Which.BASE64;
+ Worker_Binding_CryptoKey.PKCS8 = Worker_Binding_CryptoKey_Which.PKCS8;
+ Worker_Binding_CryptoKey.SPKI = Worker_Binding_CryptoKey_Which.SPKI;
+ Worker_Binding_CryptoKey.JWK = Worker_Binding_CryptoKey_Which.JWK;
+ Worker_Binding_CryptoKey.Usage = Worker_Binding_CryptoKey_Usage2;
+ Worker_Binding_CryptoKey._capnp = { displayName: "CryptoKey", id: "b5e1bff0e57d6eb0", size: new capnp_ts_1.ObjectSize(8, 3), defaultExtractable: capnp.getBitMask(false, 0) };
+ var Worker_Binding_WrappedBinding = class extends capnp_ts_1.Struct {
+ getModuleName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setModuleName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getEntrypoint() {
+ return capnp_ts_1.Struct.getText(1, this, Worker_Binding_WrappedBinding._capnp.defaultEntrypoint);
+ }
+ setEntrypoint(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptInnerBindings(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownInnerBindings() {
+ return capnp_ts_1.Struct.disown(this.getInnerBindings());
+ }
+ getInnerBindings() {
+ return capnp_ts_1.Struct.getList(2, Worker_Binding_WrappedBinding._InnerBindings, this);
+ }
+ hasInnerBindings() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initInnerBindings(length) {
+ return capnp_ts_1.Struct.initList(2, Worker_Binding_WrappedBinding._InnerBindings, length, this);
+ }
+ setInnerBindings(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ toString() {
+ return "Worker_Binding_WrappedBinding_" + super.toString();
+ }
+ };
+ exports.Worker_Binding_WrappedBinding = Worker_Binding_WrappedBinding;
+ Worker_Binding_WrappedBinding._capnp = { displayName: "WrappedBinding", id: "e6f066b75f0ea113", size: new capnp_ts_1.ObjectSize(0, 3), defaultEntrypoint: "default" };
+ var Worker_Binding_Parameter = class extends capnp_ts_1.Struct {
+ adoptType(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownType() {
+ return capnp_ts_1.Struct.disown(this.getType());
+ }
+ getType() {
+ return capnp_ts_1.Struct.getStruct(1, Worker_Binding_Type, this);
+ }
+ hasType() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initType() {
+ return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_Type, this);
+ }
+ setType(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getOptional() {
+ return capnp_ts_1.Struct.getBit(16, this);
+ }
+ setOptional(value) {
+ capnp_ts_1.Struct.setBit(16, value, this);
+ }
+ toString() {
+ return "Worker_Binding_Parameter_" + super.toString();
+ }
+ };
+ exports.Worker_Binding_Parameter = Worker_Binding_Parameter;
+ Worker_Binding_Parameter._capnp = { displayName: "parameter", id: "dc57e1258d26d152", size: new capnp_ts_1.ObjectSize(8, 2) };
+ var Worker_Binding_Which;
+ (function(Worker_Binding_Which2) {
+ Worker_Binding_Which2[Worker_Binding_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
+ Worker_Binding_Which2[Worker_Binding_Which2["PARAMETER"] = 1] = "PARAMETER";
+ Worker_Binding_Which2[Worker_Binding_Which2["TEXT"] = 2] = "TEXT";
+ Worker_Binding_Which2[Worker_Binding_Which2["DATA"] = 3] = "DATA";
+ Worker_Binding_Which2[Worker_Binding_Which2["JSON"] = 4] = "JSON";
+ Worker_Binding_Which2[Worker_Binding_Which2["WASM_MODULE"] = 5] = "WASM_MODULE";
+ Worker_Binding_Which2[Worker_Binding_Which2["CRYPTO_KEY"] = 6] = "CRYPTO_KEY";
+ Worker_Binding_Which2[Worker_Binding_Which2["SERVICE"] = 7] = "SERVICE";
+ Worker_Binding_Which2[Worker_Binding_Which2["DURABLE_OBJECT_NAMESPACE"] = 8] = "DURABLE_OBJECT_NAMESPACE";
+ Worker_Binding_Which2[Worker_Binding_Which2["KV_NAMESPACE"] = 9] = "KV_NAMESPACE";
+ Worker_Binding_Which2[Worker_Binding_Which2["R2BUCKET"] = 10] = "R2BUCKET";
+ Worker_Binding_Which2[Worker_Binding_Which2["R2ADMIN"] = 11] = "R2ADMIN";
+ Worker_Binding_Which2[Worker_Binding_Which2["WRAPPED"] = 12] = "WRAPPED";
+ Worker_Binding_Which2[Worker_Binding_Which2["QUEUE"] = 13] = "QUEUE";
+ Worker_Binding_Which2[Worker_Binding_Which2["FROM_ENVIRONMENT"] = 14] = "FROM_ENVIRONMENT";
+ Worker_Binding_Which2[Worker_Binding_Which2["ANALYTICS_ENGINE"] = 15] = "ANALYTICS_ENGINE";
+ })(Worker_Binding_Which = exports.Worker_Binding_Which || (exports.Worker_Binding_Which = {}));
+ var Worker_Binding4 = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ isUnspecified() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setUnspecified() {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ }
+ getParameter() {
+ capnp_ts_1.Struct.testWhich("parameter", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this);
+ }
+ initParameter() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this);
+ }
+ isParameter() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setParameter() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ }
+ getText() {
+ capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isText() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setText(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptData(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownData() {
+ return capnp_ts_1.Struct.disown(this.getData());
+ }
+ getData() {
+ capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this);
+ return capnp_ts_1.Struct.getData(1, this);
+ }
+ hasData() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initData(length) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ return capnp_ts_1.Struct.initData(1, length, this);
+ }
+ isData() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 3;
+ }
+ setData(value) {
+ capnp_ts_1.Struct.setUint16(0, 3, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getJson() {
+ capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 4, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isJson() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 4;
+ }
+ setJson(value) {
+ capnp_ts_1.Struct.setUint16(0, 4, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptWasmModule(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownWasmModule() {
+ return capnp_ts_1.Struct.disown(this.getWasmModule());
+ }
+ getWasmModule() {
+ capnp_ts_1.Struct.testWhich("wasmModule", capnp_ts_1.Struct.getUint16(0, this), 5, this);
+ return capnp_ts_1.Struct.getData(1, this);
+ }
+ hasWasmModule() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initWasmModule(length) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ return capnp_ts_1.Struct.initData(1, length, this);
+ }
+ isWasmModule() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 5;
+ }
+ setWasmModule(value) {
+ capnp_ts_1.Struct.setUint16(0, 5, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptCryptoKey(value) {
+ capnp_ts_1.Struct.setUint16(0, 6, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownCryptoKey() {
+ return capnp_ts_1.Struct.disown(this.getCryptoKey());
+ }
+ getCryptoKey() {
+ capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 6, this);
+ return capnp_ts_1.Struct.getStruct(1, Worker_Binding_CryptoKey, this);
+ }
+ hasCryptoKey() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initCryptoKey() {
+ capnp_ts_1.Struct.setUint16(0, 6, this);
+ return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_CryptoKey, this);
+ }
+ isCryptoKey() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 6;
+ }
+ setCryptoKey(value) {
+ capnp_ts_1.Struct.setUint16(0, 6, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptService(value) {
+ capnp_ts_1.Struct.setUint16(0, 7, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownService() {
+ return capnp_ts_1.Struct.disown(this.getService());
+ }
+ getService() {
+ capnp_ts_1.Struct.testWhich("service", capnp_ts_1.Struct.getUint16(0, this), 7, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasService() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initService() {
+ capnp_ts_1.Struct.setUint16(0, 7, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isService() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 7;
+ }
+ setService(value) {
+ capnp_ts_1.Struct.setUint16(0, 7, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptDurableObjectNamespace(value) {
+ capnp_ts_1.Struct.setUint16(0, 8, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownDurableObjectNamespace() {
+ return capnp_ts_1.Struct.disown(this.getDurableObjectNamespace());
+ }
+ getDurableObjectNamespace() {
+ capnp_ts_1.Struct.testWhich("durableObjectNamespace", capnp_ts_1.Struct.getUint16(0, this), 8, this);
+ return capnp_ts_1.Struct.getStruct(1, Worker_Binding_DurableObjectNamespaceDesignator2, this);
+ }
+ hasDurableObjectNamespace() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initDurableObjectNamespace() {
+ capnp_ts_1.Struct.setUint16(0, 8, this);
+ return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_DurableObjectNamespaceDesignator2, this);
+ }
+ isDurableObjectNamespace() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 8;
+ }
+ setDurableObjectNamespace(value) {
+ capnp_ts_1.Struct.setUint16(0, 8, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptKvNamespace(value) {
+ capnp_ts_1.Struct.setUint16(0, 9, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownKvNamespace() {
+ return capnp_ts_1.Struct.disown(this.getKvNamespace());
+ }
+ getKvNamespace() {
+ capnp_ts_1.Struct.testWhich("kvNamespace", capnp_ts_1.Struct.getUint16(0, this), 9, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasKvNamespace() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initKvNamespace() {
+ capnp_ts_1.Struct.setUint16(0, 9, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isKvNamespace() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 9;
+ }
+ setKvNamespace(value) {
+ capnp_ts_1.Struct.setUint16(0, 9, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptR2Bucket(value) {
+ capnp_ts_1.Struct.setUint16(0, 10, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownR2Bucket() {
+ return capnp_ts_1.Struct.disown(this.getR2Bucket());
+ }
+ getR2Bucket() {
+ capnp_ts_1.Struct.testWhich("r2Bucket", capnp_ts_1.Struct.getUint16(0, this), 10, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasR2Bucket() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initR2Bucket() {
+ capnp_ts_1.Struct.setUint16(0, 10, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isR2Bucket() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 10;
+ }
+ setR2Bucket(value) {
+ capnp_ts_1.Struct.setUint16(0, 10, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptR2Admin(value) {
+ capnp_ts_1.Struct.setUint16(0, 11, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownR2Admin() {
+ return capnp_ts_1.Struct.disown(this.getR2Admin());
+ }
+ getR2Admin() {
+ capnp_ts_1.Struct.testWhich("r2Admin", capnp_ts_1.Struct.getUint16(0, this), 11, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasR2Admin() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initR2Admin() {
+ capnp_ts_1.Struct.setUint16(0, 11, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isR2Admin() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 11;
+ }
+ setR2Admin(value) {
+ capnp_ts_1.Struct.setUint16(0, 11, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptWrapped(value) {
+ capnp_ts_1.Struct.setUint16(0, 12, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownWrapped() {
+ return capnp_ts_1.Struct.disown(this.getWrapped());
+ }
+ getWrapped() {
+ capnp_ts_1.Struct.testWhich("wrapped", capnp_ts_1.Struct.getUint16(0, this), 12, this);
+ return capnp_ts_1.Struct.getStruct(1, Worker_Binding_WrappedBinding, this);
+ }
+ hasWrapped() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initWrapped() {
+ capnp_ts_1.Struct.setUint16(0, 12, this);
+ return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_WrappedBinding, this);
+ }
+ isWrapped() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 12;
+ }
+ setWrapped(value) {
+ capnp_ts_1.Struct.setUint16(0, 12, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptQueue(value) {
+ capnp_ts_1.Struct.setUint16(0, 13, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownQueue() {
+ return capnp_ts_1.Struct.disown(this.getQueue());
+ }
+ getQueue() {
+ capnp_ts_1.Struct.testWhich("queue", capnp_ts_1.Struct.getUint16(0, this), 13, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasQueue() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initQueue() {
+ capnp_ts_1.Struct.setUint16(0, 13, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isQueue() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 13;
+ }
+ setQueue(value) {
+ capnp_ts_1.Struct.setUint16(0, 13, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getFromEnvironment() {
+ capnp_ts_1.Struct.testWhich("fromEnvironment", capnp_ts_1.Struct.getUint16(0, this), 14, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isFromEnvironment() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 14;
+ }
+ setFromEnvironment(value) {
+ capnp_ts_1.Struct.setUint16(0, 14, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptAnalyticsEngine(value) {
+ capnp_ts_1.Struct.setUint16(0, 15, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownAnalyticsEngine() {
+ return capnp_ts_1.Struct.disown(this.getAnalyticsEngine());
+ }
+ getAnalyticsEngine() {
+ capnp_ts_1.Struct.testWhich("analyticsEngine", capnp_ts_1.Struct.getUint16(0, this), 15, this);
+ return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this);
+ }
+ hasAnalyticsEngine() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initAnalyticsEngine() {
+ capnp_ts_1.Struct.setUint16(0, 15, this);
+ return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this);
+ }
+ isAnalyticsEngine() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 15;
+ }
+ setAnalyticsEngine(value) {
+ capnp_ts_1.Struct.setUint16(0, 15, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ toString() {
+ return "Worker_Binding_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker_Binding = Worker_Binding4;
+ Worker_Binding4.UNSPECIFIED = Worker_Binding_Which.UNSPECIFIED;
+ Worker_Binding4.PARAMETER = Worker_Binding_Which.PARAMETER;
+ Worker_Binding4.TEXT = Worker_Binding_Which.TEXT;
+ Worker_Binding4.DATA = Worker_Binding_Which.DATA;
+ Worker_Binding4.JSON = Worker_Binding_Which.JSON;
+ Worker_Binding4.WASM_MODULE = Worker_Binding_Which.WASM_MODULE;
+ Worker_Binding4.CRYPTO_KEY = Worker_Binding_Which.CRYPTO_KEY;
+ Worker_Binding4.SERVICE = Worker_Binding_Which.SERVICE;
+ Worker_Binding4.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Which.DURABLE_OBJECT_NAMESPACE;
+ Worker_Binding4.KV_NAMESPACE = Worker_Binding_Which.KV_NAMESPACE;
+ Worker_Binding4.R2BUCKET = Worker_Binding_Which.R2BUCKET;
+ Worker_Binding4.R2ADMIN = Worker_Binding_Which.R2ADMIN;
+ Worker_Binding4.WRAPPED = Worker_Binding_Which.WRAPPED;
+ Worker_Binding4.QUEUE = Worker_Binding_Which.QUEUE;
+ Worker_Binding4.FROM_ENVIRONMENT = Worker_Binding_Which.FROM_ENVIRONMENT;
+ Worker_Binding4.ANALYTICS_ENGINE = Worker_Binding_Which.ANALYTICS_ENGINE;
+ Worker_Binding4.Type = Worker_Binding_Type;
+ Worker_Binding4.DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2;
+ Worker_Binding4.CryptoKey = Worker_Binding_CryptoKey;
+ Worker_Binding4.WrappedBinding = Worker_Binding_WrappedBinding;
+ Worker_Binding4._capnp = { displayName: "Binding", id: "8e7e492fd7e35f3e", size: new capnp_ts_1.ObjectSize(8, 2) };
+ var Worker_DurableObjectNamespace_Which;
+ (function(Worker_DurableObjectNamespace_Which2) {
+ Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["UNIQUE_KEY"] = 0] = "UNIQUE_KEY";
+ Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["EPHEMERAL_LOCAL"] = 1] = "EPHEMERAL_LOCAL";
+ })(Worker_DurableObjectNamespace_Which = exports.Worker_DurableObjectNamespace_Which || (exports.Worker_DurableObjectNamespace_Which = {}));
+ var Worker_DurableObjectNamespace = class extends capnp_ts_1.Struct {
+ getClassName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setClassName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getUniqueKey() {
+ capnp_ts_1.Struct.testWhich("uniqueKey", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ isUniqueKey() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setUniqueKey(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ isEphemeralLocal() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setEphemeralLocal() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ }
+ toString() {
+ return "Worker_DurableObjectNamespace_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker_DurableObjectNamespace = Worker_DurableObjectNamespace;
+ Worker_DurableObjectNamespace.UNIQUE_KEY = Worker_DurableObjectNamespace_Which.UNIQUE_KEY;
+ Worker_DurableObjectNamespace.EPHEMERAL_LOCAL = Worker_DurableObjectNamespace_Which.EPHEMERAL_LOCAL;
+ Worker_DurableObjectNamespace._capnp = { displayName: "DurableObjectNamespace", id: "b429dd547d15747d", size: new capnp_ts_1.ObjectSize(8, 2) };
+ var Worker_DurableObjectStorage_Which;
+ (function(Worker_DurableObjectStorage_Which2) {
+ Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["NONE"] = 0] = "NONE";
+ Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["IN_MEMORY"] = 1] = "IN_MEMORY";
+ Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["LOCAL_DISK"] = 2] = "LOCAL_DISK";
+ })(Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectStorage_Which || (exports.Worker_DurableObjectStorage_Which = {}));
+ var Worker_DurableObjectStorage = class extends capnp_ts_1.Struct {
+ isNone() {
+ return capnp_ts_1.Struct.getUint16(2, this) === 0;
+ }
+ setNone() {
+ capnp_ts_1.Struct.setUint16(2, 0, this);
+ }
+ isInMemory() {
+ return capnp_ts_1.Struct.getUint16(2, this) === 1;
+ }
+ setInMemory() {
+ capnp_ts_1.Struct.setUint16(2, 1, this);
+ }
+ getLocalDisk() {
+ capnp_ts_1.Struct.testWhich("localDisk", capnp_ts_1.Struct.getUint16(2, this), 2, this);
+ return capnp_ts_1.Struct.getText(8, this);
+ }
+ isLocalDisk() {
+ return capnp_ts_1.Struct.getUint16(2, this) === 2;
+ }
+ setLocalDisk(value) {
+ capnp_ts_1.Struct.setUint16(2, 2, this);
+ capnp_ts_1.Struct.setText(8, value, this);
+ }
+ toString() {
+ return "Worker_DurableObjectStorage_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(2, this);
+ }
+ };
+ exports.Worker_DurableObjectStorage = Worker_DurableObjectStorage;
+ Worker_DurableObjectStorage.NONE = Worker_DurableObjectStorage_Which.NONE;
+ Worker_DurableObjectStorage.IN_MEMORY = Worker_DurableObjectStorage_Which.IN_MEMORY;
+ Worker_DurableObjectStorage.LOCAL_DISK = Worker_DurableObjectStorage_Which.LOCAL_DISK;
+ Worker_DurableObjectStorage._capnp = { displayName: "durableObjectStorage", id: "cc72b3faa57827d4", size: new capnp_ts_1.ObjectSize(8, 9) };
+ var Worker_Which;
+ (function(Worker_Which2) {
+ Worker_Which2[Worker_Which2["MODULES"] = 0] = "MODULES";
+ Worker_Which2[Worker_Which2["SERVICE_WORKER_SCRIPT"] = 1] = "SERVICE_WORKER_SCRIPT";
+ Worker_Which2[Worker_Which2["INHERIT"] = 2] = "INHERIT";
+ })(Worker_Which = exports.Worker_Which || (exports.Worker_Which = {}));
+ var Worker2 = class extends capnp_ts_1.Struct {
+ adoptModules(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownModules() {
+ return capnp_ts_1.Struct.disown(this.getModules());
+ }
+ getModules() {
+ capnp_ts_1.Struct.testWhich("modules", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getList(0, Worker2._Modules, this);
+ }
+ hasModules() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initModules(length) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ return capnp_ts_1.Struct.initList(0, Worker2._Modules, length, this);
+ }
+ isModules() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setModules(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ getServiceWorkerScript() {
+ capnp_ts_1.Struct.testWhich("serviceWorkerScript", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isServiceWorkerScript() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setServiceWorkerScript(value) {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getInherit() {
+ capnp_ts_1.Struct.testWhich("inherit", capnp_ts_1.Struct.getUint16(0, this), 2, this);
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ isInherit() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 2;
+ }
+ setInherit(value) {
+ capnp_ts_1.Struct.setUint16(0, 2, this);
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getCompatibilityDate() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setCompatibilityDate(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptCompatibilityFlags(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownCompatibilityFlags() {
+ return capnp_ts_1.Struct.disown(this.getCompatibilityFlags());
+ }
+ getCompatibilityFlags() {
+ return capnp_ts_1.Struct.getList(2, capnp.TextList, this);
+ }
+ hasCompatibilityFlags() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initCompatibilityFlags(length) {
+ return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this);
+ }
+ setCompatibilityFlags(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ adoptBindings(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ disownBindings() {
+ return capnp_ts_1.Struct.disown(this.getBindings());
+ }
+ getBindings() {
+ return capnp_ts_1.Struct.getList(3, Worker2._Bindings, this);
+ }
+ hasBindings() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this));
+ }
+ initBindings(length) {
+ return capnp_ts_1.Struct.initList(3, Worker2._Bindings, length, this);
+ }
+ setBindings(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ adoptGlobalOutbound(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this));
+ }
+ disownGlobalOutbound() {
+ return capnp_ts_1.Struct.disown(this.getGlobalOutbound());
+ }
+ getGlobalOutbound() {
+ return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this, Worker2._capnp.defaultGlobalOutbound);
+ }
+ hasGlobalOutbound() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this));
+ }
+ initGlobalOutbound() {
+ return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this);
+ }
+ setGlobalOutbound(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this));
+ }
+ adoptCacheApiOutbound(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(7, this));
+ }
+ disownCacheApiOutbound() {
+ return capnp_ts_1.Struct.disown(this.getCacheApiOutbound());
+ }
+ getCacheApiOutbound() {
+ return capnp_ts_1.Struct.getStruct(7, ServiceDesignator2, this);
+ }
+ hasCacheApiOutbound() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(7, this));
+ }
+ initCacheApiOutbound() {
+ return capnp_ts_1.Struct.initStructAt(7, ServiceDesignator2, this);
+ }
+ setCacheApiOutbound(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(7, this));
+ }
+ adoptDurableObjectNamespaces(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(5, this));
+ }
+ disownDurableObjectNamespaces() {
+ return capnp_ts_1.Struct.disown(this.getDurableObjectNamespaces());
+ }
+ getDurableObjectNamespaces() {
+ return capnp_ts_1.Struct.getList(5, Worker2._DurableObjectNamespaces, this);
+ }
+ hasDurableObjectNamespaces() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(5, this));
+ }
+ initDurableObjectNamespaces(length) {
+ return capnp_ts_1.Struct.initList(5, Worker2._DurableObjectNamespaces, length, this);
+ }
+ setDurableObjectNamespaces(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(5, this));
+ }
+ getDurableObjectUniqueKeyModifier() {
+ return capnp_ts_1.Struct.getText(6, this);
+ }
+ setDurableObjectUniqueKeyModifier(value) {
+ capnp_ts_1.Struct.setText(6, value, this);
+ }
+ getDurableObjectStorage() {
+ return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this);
+ }
+ initDurableObjectStorage() {
+ return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this);
+ }
+ toString() {
+ return "Worker_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.Worker = Worker2;
+ Worker2.MODULES = Worker_Which.MODULES;
+ Worker2.SERVICE_WORKER_SCRIPT = Worker_Which.SERVICE_WORKER_SCRIPT;
+ Worker2.INHERIT = Worker_Which.INHERIT;
+ Worker2.Module = Worker_Module3;
+ Worker2.Binding = Worker_Binding4;
+ Worker2.DurableObjectNamespace = Worker_DurableObjectNamespace;
+ Worker2._capnp = { displayName: "Worker", id: "acfa77e88fd97d1c", size: new capnp_ts_1.ObjectSize(8, 9), defaultGlobalOutbound: capnp.readRawPointer(new Uint8Array([16, 5, 64, 2, 17, 5, 74, 0, 0, 255, 105, 110, 116, 101, 114, 110, 101, 116, 0, 0, 0]).buffer) };
+ var ExternalServer_Https = class extends capnp_ts_1.Struct {
+ adoptOptions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownOptions() {
+ return capnp_ts_1.Struct.disown(this.getOptions());
+ }
+ getOptions() {
+ return capnp_ts_1.Struct.getStruct(1, HttpOptions, this);
+ }
+ hasOptions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initOptions() {
+ return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this);
+ }
+ setOptions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptTlsOptions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownTlsOptions() {
+ return capnp_ts_1.Struct.disown(this.getTlsOptions());
+ }
+ getTlsOptions() {
+ return capnp_ts_1.Struct.getStruct(2, TlsOptions, this);
+ }
+ hasTlsOptions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initTlsOptions() {
+ return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this);
+ }
+ setTlsOptions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ getCertificateHost() {
+ return capnp_ts_1.Struct.getText(3, this);
+ }
+ setCertificateHost(value) {
+ capnp_ts_1.Struct.setText(3, value, this);
+ }
+ toString() {
+ return "ExternalServer_Https_" + super.toString();
+ }
+ };
+ exports.ExternalServer_Https = ExternalServer_Https;
+ ExternalServer_Https._capnp = { displayName: "https", id: "ac37e02afd3dc6db", size: new capnp_ts_1.ObjectSize(8, 4) };
+ var ExternalServer_Which;
+ (function(ExternalServer_Which2) {
+ ExternalServer_Which2[ExternalServer_Which2["HTTP"] = 0] = "HTTP";
+ ExternalServer_Which2[ExternalServer_Which2["HTTPS"] = 1] = "HTTPS";
+ })(ExternalServer_Which = exports.ExternalServer_Which || (exports.ExternalServer_Which = {}));
+ var ExternalServer2 = class extends capnp_ts_1.Struct {
+ getAddress() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setAddress(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ adoptHttp(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownHttp() {
+ return capnp_ts_1.Struct.disown(this.getHttp());
+ }
+ getHttp() {
+ capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this);
+ return capnp_ts_1.Struct.getStruct(1, HttpOptions, this);
+ }
+ hasHttp() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initHttp() {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this);
+ }
+ isHttp() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 0;
+ }
+ setHttp(value) {
+ capnp_ts_1.Struct.setUint16(0, 0, this);
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getHttps() {
+ capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this);
+ return capnp_ts_1.Struct.getAs(ExternalServer_Https, this);
+ }
+ initHttps() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ return capnp_ts_1.Struct.getAs(ExternalServer_Https, this);
+ }
+ isHttps() {
+ return capnp_ts_1.Struct.getUint16(0, this) === 1;
+ }
+ setHttps() {
+ capnp_ts_1.Struct.setUint16(0, 1, this);
+ }
+ toString() {
+ return "ExternalServer_" + super.toString();
+ }
+ which() {
+ return capnp_ts_1.Struct.getUint16(0, this);
+ }
+ };
+ exports.ExternalServer = ExternalServer2;
+ ExternalServer2.HTTP = ExternalServer_Which.HTTP;
+ ExternalServer2.HTTPS = ExternalServer_Which.HTTPS;
+ ExternalServer2._capnp = { displayName: "ExternalServer", id: "ff209f9aa352f5a4", size: new capnp_ts_1.ObjectSize(8, 4) };
+ var Network = class extends capnp_ts_1.Struct {
+ adoptAllow(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownAllow() {
+ return capnp_ts_1.Struct.disown(this.getAllow());
+ }
+ getAllow() {
+ return capnp_ts_1.Struct.getList(0, capnp.TextList, this, Network._capnp.defaultAllow);
+ }
+ hasAllow() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initAllow(length) {
+ return capnp_ts_1.Struct.initList(0, capnp.TextList, length, this);
+ }
+ setAllow(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ adoptDeny(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownDeny() {
+ return capnp_ts_1.Struct.disown(this.getDeny());
+ }
+ getDeny() {
+ return capnp_ts_1.Struct.getList(1, capnp.TextList, this);
+ }
+ hasDeny() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initDeny(length) {
+ return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this);
+ }
+ setDeny(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ adoptTlsOptions(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownTlsOptions() {
+ return capnp_ts_1.Struct.disown(this.getTlsOptions());
+ }
+ getTlsOptions() {
+ return capnp_ts_1.Struct.getStruct(2, TlsOptions, this);
+ }
+ hasTlsOptions() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initTlsOptions() {
+ return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this);
+ }
+ setTlsOptions(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ toString() {
+ return "Network_" + super.toString();
+ }
+ };
+ exports.Network = Network;
+ Network._capnp = { displayName: "Network", id: "fa42244f950c9b9c", size: new capnp_ts_1.ObjectSize(0, 3), defaultAllow: capnp.readRawPointer(new Uint8Array([16, 3, 17, 1, 14, 17, 1, 58, 63, 112, 117, 98, 108, 105, 99]).buffer) };
+ var DiskDirectory = class extends capnp_ts_1.Struct {
+ getPath() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setPath(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getWritable() {
+ return capnp_ts_1.Struct.getBit(0, this, DiskDirectory._capnp.defaultWritable);
+ }
+ setWritable(value) {
+ capnp_ts_1.Struct.setBit(0, value, this);
+ }
+ getAllowDotfiles() {
+ return capnp_ts_1.Struct.getBit(1, this, DiskDirectory._capnp.defaultAllowDotfiles);
+ }
+ setAllowDotfiles(value) {
+ capnp_ts_1.Struct.setBit(1, value, this);
+ }
+ toString() {
+ return "DiskDirectory_" + super.toString();
+ }
+ };
+ exports.DiskDirectory = DiskDirectory;
+ DiskDirectory._capnp = { displayName: "DiskDirectory", id: "9048ab22835f51c3", size: new capnp_ts_1.ObjectSize(8, 1), defaultWritable: capnp.getBitMask(false, 0), defaultAllowDotfiles: capnp.getBitMask(false, 1) };
+ var HttpOptions_Style2;
+ (function(HttpOptions_Style3) {
+ HttpOptions_Style3[HttpOptions_Style3["HOST"] = 0] = "HOST";
+ HttpOptions_Style3[HttpOptions_Style3["PROXY"] = 1] = "PROXY";
+ })(HttpOptions_Style2 = exports.HttpOptions_Style || (exports.HttpOptions_Style = {}));
+ var HttpOptions_Header = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getValue() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setValue(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "HttpOptions_Header_" + super.toString();
+ }
+ };
+ exports.HttpOptions_Header = HttpOptions_Header;
+ HttpOptions_Header._capnp = { displayName: "Header", id: "dc0394b5a6f3417e", size: new capnp_ts_1.ObjectSize(0, 2) };
+ var HttpOptions = class extends capnp_ts_1.Struct {
+ getStyle() {
+ return capnp_ts_1.Struct.getUint16(0, this, HttpOptions._capnp.defaultStyle);
+ }
+ setStyle(value) {
+ capnp_ts_1.Struct.setUint16(0, value, this);
+ }
+ getForwardedProtoHeader() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setForwardedProtoHeader(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getCfBlobHeader() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setCfBlobHeader(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ adoptInjectRequestHeaders(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ disownInjectRequestHeaders() {
+ return capnp_ts_1.Struct.disown(this.getInjectRequestHeaders());
+ }
+ getInjectRequestHeaders() {
+ return capnp_ts_1.Struct.getList(2, HttpOptions._InjectRequestHeaders, this);
+ }
+ hasInjectRequestHeaders() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this));
+ }
+ initInjectRequestHeaders(length) {
+ return capnp_ts_1.Struct.initList(2, HttpOptions._InjectRequestHeaders, length, this);
+ }
+ setInjectRequestHeaders(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this));
+ }
+ adoptInjectResponseHeaders(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ disownInjectResponseHeaders() {
+ return capnp_ts_1.Struct.disown(this.getInjectResponseHeaders());
+ }
+ getInjectResponseHeaders() {
+ return capnp_ts_1.Struct.getList(3, HttpOptions._InjectResponseHeaders, this);
+ }
+ hasInjectResponseHeaders() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this));
+ }
+ initInjectResponseHeaders(length) {
+ return capnp_ts_1.Struct.initList(3, HttpOptions._InjectResponseHeaders, length, this);
+ }
+ setInjectResponseHeaders(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this));
+ }
+ toString() {
+ return "HttpOptions_" + super.toString();
+ }
+ };
+ exports.HttpOptions = HttpOptions;
+ HttpOptions.Style = HttpOptions_Style2;
+ HttpOptions.Header = HttpOptions_Header;
+ HttpOptions._capnp = { displayName: "HttpOptions", id: "aa8dc6885da78f19", size: new capnp_ts_1.ObjectSize(8, 4), defaultStyle: capnp.getUint16Mask(0) };
+ var TlsOptions_Keypair = class extends capnp_ts_1.Struct {
+ getPrivateKey() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setPrivateKey(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getCertificateChain() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setCertificateChain(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "TlsOptions_Keypair_" + super.toString();
+ }
+ };
+ exports.TlsOptions_Keypair = TlsOptions_Keypair;
+ TlsOptions_Keypair._capnp = { displayName: "Keypair", id: "f546bf2d5d8bd13e", size: new capnp_ts_1.ObjectSize(0, 2) };
+ var TlsOptions_Version2;
+ (function(TlsOptions_Version3) {
+ TlsOptions_Version3[TlsOptions_Version3["GOOD_DEFAULT"] = 0] = "GOOD_DEFAULT";
+ TlsOptions_Version3[TlsOptions_Version3["SSL3"] = 1] = "SSL3";
+ TlsOptions_Version3[TlsOptions_Version3["TLS1DOT0"] = 2] = "TLS1DOT0";
+ TlsOptions_Version3[TlsOptions_Version3["TLS1DOT1"] = 3] = "TLS1DOT1";
+ TlsOptions_Version3[TlsOptions_Version3["TLS1DOT2"] = 4] = "TLS1DOT2";
+ TlsOptions_Version3[TlsOptions_Version3["TLS1DOT3"] = 5] = "TLS1DOT3";
+ })(TlsOptions_Version2 = exports.TlsOptions_Version || (exports.TlsOptions_Version = {}));
+ var TlsOptions = class extends capnp_ts_1.Struct {
+ adoptKeypair(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownKeypair() {
+ return capnp_ts_1.Struct.disown(this.getKeypair());
+ }
+ getKeypair() {
+ return capnp_ts_1.Struct.getStruct(0, TlsOptions_Keypair, this);
+ }
+ hasKeypair() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initKeypair() {
+ return capnp_ts_1.Struct.initStructAt(0, TlsOptions_Keypair, this);
+ }
+ setKeypair(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ getRequireClientCerts() {
+ return capnp_ts_1.Struct.getBit(0, this, TlsOptions._capnp.defaultRequireClientCerts);
+ }
+ setRequireClientCerts(value) {
+ capnp_ts_1.Struct.setBit(0, value, this);
+ }
+ getTrustBrowserCas() {
+ return capnp_ts_1.Struct.getBit(1, this, TlsOptions._capnp.defaultTrustBrowserCas);
+ }
+ setTrustBrowserCas(value) {
+ capnp_ts_1.Struct.setBit(1, value, this);
+ }
+ adoptTrustedCertificates(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ disownTrustedCertificates() {
+ return capnp_ts_1.Struct.disown(this.getTrustedCertificates());
+ }
+ getTrustedCertificates() {
+ return capnp_ts_1.Struct.getList(1, capnp.TextList, this);
+ }
+ hasTrustedCertificates() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this));
+ }
+ initTrustedCertificates(length) {
+ return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this);
+ }
+ setTrustedCertificates(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this));
+ }
+ getMinVersion() {
+ return capnp_ts_1.Struct.getUint16(2, this, TlsOptions._capnp.defaultMinVersion);
+ }
+ setMinVersion(value) {
+ capnp_ts_1.Struct.setUint16(2, value, this);
+ }
+ getCipherList() {
+ return capnp_ts_1.Struct.getText(2, this);
+ }
+ setCipherList(value) {
+ capnp_ts_1.Struct.setText(2, value, this);
+ }
+ toString() {
+ return "TlsOptions_" + super.toString();
+ }
+ };
+ exports.TlsOptions = TlsOptions;
+ TlsOptions.Keypair = TlsOptions_Keypair;
+ TlsOptions.Version = TlsOptions_Version2;
+ TlsOptions._capnp = { displayName: "TlsOptions", id: "aabb3c3778ac4311", size: new capnp_ts_1.ObjectSize(8, 3), defaultRequireClientCerts: capnp.getBitMask(false, 0), defaultTrustBrowserCas: capnp.getBitMask(false, 1), defaultMinVersion: capnp.getUint16Mask(0) };
+ var Extension_Module = class extends capnp_ts_1.Struct {
+ getName() {
+ return capnp_ts_1.Struct.getText(0, this);
+ }
+ setName(value) {
+ capnp_ts_1.Struct.setText(0, value, this);
+ }
+ getInternal() {
+ return capnp_ts_1.Struct.getBit(0, this, Extension_Module._capnp.defaultInternal);
+ }
+ setInternal(value) {
+ capnp_ts_1.Struct.setBit(0, value, this);
+ }
+ getEsModule() {
+ return capnp_ts_1.Struct.getText(1, this);
+ }
+ setEsModule(value) {
+ capnp_ts_1.Struct.setText(1, value, this);
+ }
+ toString() {
+ return "Extension_Module_" + super.toString();
+ }
+ };
+ exports.Extension_Module = Extension_Module;
+ Extension_Module._capnp = { displayName: "Module", id: "d5d16e76fdedc37d", size: new capnp_ts_1.ObjectSize(8, 2), defaultInternal: capnp.getBitMask(false, 0) };
+ var Extension2 = class extends capnp_ts_1.Struct {
+ adoptModules(value) {
+ capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ disownModules() {
+ return capnp_ts_1.Struct.disown(this.getModules());
+ }
+ getModules() {
+ return capnp_ts_1.Struct.getList(0, Extension2._Modules, this);
+ }
+ hasModules() {
+ return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this));
+ }
+ initModules(length) {
+ return capnp_ts_1.Struct.initList(0, Extension2._Modules, length, this);
+ }
+ setModules(value) {
+ capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this));
+ }
+ toString() {
+ return "Extension_" + super.toString();
+ }
+ };
+ exports.Extension = Extension2;
+ Extension2.Module = Extension_Module;
+ Extension2._capnp = { displayName: "Extension", id: "e390128a861973a6", size: new capnp_ts_1.ObjectSize(0, 1) };
+ Config3._Services = capnp.CompositeList(Service4);
+ Config3._Sockets = capnp.CompositeList(Socket2);
+ Config3._Extensions = capnp.CompositeList(Extension2);
+ Worker_Binding_WrappedBinding._InnerBindings = capnp.CompositeList(Worker_Binding4);
+ Worker2._Modules = capnp.CompositeList(Worker_Module3);
+ Worker2._Bindings = capnp.CompositeList(Worker_Binding4);
+ Worker2._DurableObjectNamespaces = capnp.CompositeList(Worker_DurableObjectNamespace);
+ HttpOptions._InjectRequestHeaders = capnp.CompositeList(HttpOptions_Header);
+ HttpOptions._InjectResponseHeaders = capnp.CompositeList(HttpOptions_Header);
+ Extension2._Modules = capnp.CompositeList(Extension_Module);
+ }
+});
+
+// packages/miniflare/src/index.ts
+var src_exports = {};
+__export(src_exports, {
+ CACHE_PLUGIN: () => CACHE_PLUGIN,
+ CACHE_PLUGIN_NAME: () => CACHE_PLUGIN_NAME,
+ CORE_PLUGIN: () => CORE_PLUGIN,
+ CORE_PLUGIN_NAME: () => CORE_PLUGIN_NAME2,
+ CacheBindings: () => CacheBindings,
+ CacheHeaders: () => CacheHeaders,
+ CacheOptionsSchema: () => CacheOptionsSchema,
+ CacheSharedOptionsSchema: () => CacheSharedOptionsSchema,
+ CloseEvent: () => CloseEvent,
+ CoreBindings: () => CoreBindings,
+ CoreHeaders: () => CoreHeaders,
+ CoreOptionsSchema: () => CoreOptionsSchema,
+ CoreSharedOptionsSchema: () => CoreSharedOptionsSchema,
+ D1OptionsSchema: () => D1OptionsSchema,
+ D1SharedOptionsSchema: () => D1SharedOptionsSchema,
+ D1_PLUGIN: () => D1_PLUGIN,
+ D1_PLUGIN_NAME: () => D1_PLUGIN_NAME,
+ DEFAULT_PERSIST_ROOT: () => DEFAULT_PERSIST_ROOT,
+ DURABLE_OBJECTS_PLUGIN: () => DURABLE_OBJECTS_PLUGIN,
+ DURABLE_OBJECTS_PLUGIN_NAME: () => DURABLE_OBJECTS_PLUGIN_NAME,
+ DURABLE_OBJECTS_STORAGE_SERVICE_NAME: () => DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
+ DeferredPromise: () => DeferredPromise,
+ DurableObjectsOptionsSchema: () => DurableObjectsOptionsSchema,
+ DurableObjectsSharedOptionsSchema: () => DurableObjectsSharedOptionsSchema,
+ ErrorEvent: () => ErrorEvent,
+ File: () => import_undici8.File,
+ FormData: () => import_undici8.FormData,
+ HEADER_CF_BLOB: () => HEADER_CF_BLOB,
+ Headers: () => import_undici8.Headers,
+ HttpOptions_Style: () => import_workerd_capnp.HttpOptions_Style,
+ JsonSchema: () => JsonSchema,
+ KVHeaders: () => KVHeaders,
+ KVLimits: () => KVLimits,
+ KVOptionsSchema: () => KVOptionsSchema,
+ KVParams: () => KVParams,
+ KVSharedOptionsSchema: () => KVSharedOptionsSchema,
+ KV_PLUGIN: () => KV_PLUGIN,
+ KV_PLUGIN_NAME: () => KV_PLUGIN_NAME,
+ LiteralSchema: () => LiteralSchema,
+ Log: () => Log,
+ LogLevel: () => LogLevel,
+ MessageEvent: () => MessageEvent,
+ Miniflare: () => Miniflare,
+ MiniflareCoreError: () => MiniflareCoreError,
+ MiniflareError: () => MiniflareError,
+ ModuleDefinitionSchema: () => ModuleDefinitionSchema,
+ ModuleRuleSchema: () => ModuleRuleSchema,
+ ModuleRuleTypeSchema: () => ModuleRuleTypeSchema,
+ Mutex: () => Mutex,
+ NoOpLog: () => NoOpLog,
+ PLUGINS: () => PLUGINS,
+ PLUGIN_ENTRIES: () => PLUGIN_ENTRIES,
+ PersistenceSchema: () => PersistenceSchema,
+ ProxyAddresses: () => ProxyAddresses,
+ ProxyClient: () => ProxyClient,
+ ProxyOps: () => ProxyOps,
+ QUEUES_PLUGIN: () => QUEUES_PLUGIN,
+ QUEUES_PLUGIN_NAME: () => QUEUES_PLUGIN_NAME,
+ QueueBindings: () => QueueBindings,
+ QueueConsumerOptionsSchema: () => QueueConsumerOptionsSchema,
+ QueueConsumerSchema: () => QueueConsumerSchema,
+ QueueConsumersSchema: () => QueueConsumersSchema,
+ QueueContentTypeSchema: () => QueueContentTypeSchema,
+ QueueIncomingMessageSchema: () => QueueIncomingMessageSchema,
+ QueuesBatchRequestSchema: () => QueuesBatchRequestSchema,
+ QueuesError: () => QueuesError,
+ QueuesOptionsSchema: () => QueuesOptionsSchema,
+ R2OptionsSchema: () => R2OptionsSchema,
+ R2SharedOptionsSchema: () => R2SharedOptionsSchema,
+ R2_PLUGIN: () => R2_PLUGIN,
+ R2_PLUGIN_NAME: () => R2_PLUGIN_NAME,
+ Request: () => Request,
+ Response: () => Response,
+ RouterError: () => RouterError,
+ Runtime: () => Runtime,
+ SERVICE_ENTRY: () => SERVICE_ENTRY,
+ SERVICE_LOOPBACK: () => SERVICE_LOOPBACK,
+ SITES_NO_CACHE_PREFIX: () => SITES_NO_CACHE_PREFIX,
+ SOCKET_ENTRY: () => SOCKET_ENTRY,
+ SharedBindings: () => SharedBindings,
+ SharedHeaders: () => SharedHeaders,
+ SiteBindings: () => SiteBindings,
+ SourceOptionsSchema: () => SourceOptionsSchema,
+ TlsOptions_Version: () => import_workerd_capnp.TlsOptions_Version,
+ TypedEventTarget: () => TypedEventTarget,
+ WORKER_BINDING_SERVICE_LOOPBACK: () => WORKER_BINDING_SERVICE_LOOPBACK,
+ WaitGroup: () => WaitGroup,
+ WebSocket: () => WebSocket,
+ WebSocketPair: () => WebSocketPair,
+ Worker_Binding_CryptoKey_Usage: () => import_workerd_capnp.Worker_Binding_CryptoKey_Usage,
+ _forceColour: () => _forceColour,
+ _formatZodError: () => _formatZodError,
+ _initialiseInstanceRegistry: () => _initialiseInstanceRegistry,
+ _transformsForContentEncoding: () => _transformsForContentEncoding,
+ base64Decode: () => base64Decode,
+ base64Encode: () => base64Encode,
+ configureEntrySocket: () => configureEntrySocket,
+ coupleWebSocket: () => coupleWebSocket,
+ createFetchMock: () => createFetchMock,
+ createHTTPReducers: () => createHTTPReducers,
+ createHTTPRevivers: () => createHTTPRevivers,
+ decodeSitesKey: () => decodeSitesKey,
+ deserialiseRegExps: () => deserialiseRegExps,
+ deserialiseSiteRegExps: () => deserialiseSiteRegExps,
+ encodeSitesKey: () => encodeSitesKey,
+ fetch: () => fetch2,
+ getAccessibleHosts: () => getAccessibleHosts,
+ getCacheServiceName: () => getCacheServiceName,
+ getGlobalServices: () => getGlobalServices,
+ getPersistPath: () => getPersistPath,
+ globsToRegExps: () => globsToRegExps,
+ isFetcherFetch: () => isFetcherFetch,
+ isR2ObjectWriteHttpMetadata: () => isR2ObjectWriteHttpMetadata,
+ isSitesRequest: () => isSitesRequest,
+ kProxyNodeBinding: () => kProxyNodeBinding,
+ kVoid: () => kVoid,
+ matchRoutes: () => matchRoutes,
+ maybeApply: () => maybeApply,
+ maybeGetSitesManifestModule: () => maybeGetSitesManifestModule,
+ maybeParseURL: () => maybeParseURL,
+ migrateDatabase: () => migrateDatabase,
+ namespaceEntries: () => namespaceEntries,
+ namespaceKeys: () => namespaceKeys,
+ normaliseDurableObject: () => normaliseDurableObject,
+ objectEntryWorker: () => objectEntryWorker,
+ parseRanges: () => parseRanges,
+ parseRoutes: () => parseRoutes,
+ parseWithReadableStreams: () => parseWithReadableStreams,
+ prefixError: () => prefixError,
+ prefixStream: () => prefixStream,
+ readPrefix: () => readPrefix,
+ reduceError: () => reduceError,
+ registerAllowUnauthorizedDispatcher: () => registerAllowUnauthorizedDispatcher,
+ sanitisePath: () => sanitisePath,
+ serialiseRegExps: () => serialiseRegExps,
+ serialiseSiteRegExps: () => serialiseSiteRegExps,
+ serializeConfig: () => serializeConfig,
+ stringifyWithStreams: () => stringifyWithStreams,
+ stripAnsi: () => stripAnsi,
+ structuredSerializableReducers: () => structuredSerializableReducers,
+ structuredSerializableRevivers: () => structuredSerializableRevivers,
+ supportedCompatibilityDate: () => import_workerd2.compatibilityDate,
+ testRegExps: () => testRegExps,
+ testSiteRegExps: () => testSiteRegExps,
+ viewToBuffer: () => viewToBuffer,
+ zAwaitable: () => zAwaitable
+});
+module.exports = __toCommonJS(src_exports);
+var import_assert11 = __toESM(require("assert"));
+var import_crypto2 = __toESM(require("crypto"));
+var import_fs17 = __toESM(require("fs"));
+var import_http7 = __toESM(require("http"));
+var import_net = __toESM(require("net"));
+var import_os2 = __toESM(require("os"));
+var import_path20 = __toESM(require("path"));
+var import_web5 = require("stream/web");
+var import_util5 = __toESM(require("util"));
+var import_zlib = __toESM(require("zlib"));
+var import_exit_hook = __toESM(require("exit-hook"));
+
+// node_modules/kleur/colors.mjs
+var FORCE_COLOR;
+var NODE_DISABLE_COLORS;
+var NO_COLOR;
+var TERM;
+var isTTY = true;
+if (typeof process !== "undefined") {
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
+ isTTY = process.stdout && process.stdout.isTTY;
+}
+var $ = {
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
+};
+function init(x, y) {
+ let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
+ let open = `\x1B[${x}m`, close = `\x1B[${y}m`;
+ return function(txt) {
+ if (!$.enabled || txt == null)
+ return txt;
+ return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
+ };
+}
+var reset = init(0, 0);
+var bold = init(1, 22);
+var dim = init(2, 22);
+var italic = init(3, 23);
+var underline = init(4, 24);
+var inverse = init(7, 27);
+var hidden = init(8, 28);
+var strikethrough = init(9, 29);
+var black = init(30, 39);
+var red = init(31, 39);
+var green = init(32, 39);
+var yellow = init(33, 39);
+var blue = init(34, 39);
+var magenta = init(35, 39);
+var cyan = init(36, 39);
+var white = init(37, 39);
+var gray = init(90, 39);
+var grey = init(90, 39);
+var bgBlack = init(40, 49);
+var bgRed = init(41, 49);
+var bgGreen = init(42, 49);
+var bgYellow = init(43, 49);
+var bgBlue = init(44, 49);
+var bgMagenta = init(45, 49);
+var bgCyan = init(46, 49);
+var bgWhite = init(47, 49);
+
+// packages/miniflare/src/index.ts
+var import_stoppable = __toESM(require("stoppable"));
+var import_undici9 = require("undici");
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/index.worker.ts
+var import_fs = __toESM(require("fs"));
+var import_path = __toESM(require("path"));
+var import_url = __toESM(require("url"));
+var contents;
+function index_worker_default() {
+ if (contents !== void 0)
+ return contents;
+ const filePath = import_path.default.join(__dirname, "workers", "shared/index.worker.js");
+ contents = import_fs.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url.default.pathToFileURL(filePath);
+ return contents;
+}
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/zod.worker.ts
+var import_fs2 = __toESM(require("fs"));
+var import_path2 = __toESM(require("path"));
+var import_url2 = __toESM(require("url"));
+var contents2;
+function zod_worker_default() {
+ if (contents2 !== void 0)
+ return contents2;
+ const filePath = import_path2.default.join(__dirname, "workers", "shared/zod.worker.js");
+ contents2 = import_fs2.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url2.default.pathToFileURL(filePath);
+ return contents2;
+}
+
+// packages/miniflare/src/index.ts
+var import_ws3 = require("ws");
+var import_zod17 = require("zod");
+
+// packages/miniflare/src/cf.ts
+var import_assert = __toESM(require("assert"));
+var import_promises = require("fs/promises");
+var import_path3 = __toESM(require("path"));
+var import_undici = require("undici");
+var defaultCfPath = import_path3.default.resolve("node_modules", ".mf", "cf.json");
+var defaultCfFetchEndpoint = "https://workers.cloudflare.com/cf.json";
+var fallbackCf = {
+ asOrganization: "",
+ asn: 395747,
+ colo: "DFW",
+ city: "Austin",
+ region: "Texas",
+ regionCode: "TX",
+ metroCode: "635",
+ postalCode: "78701",
+ country: "US",
+ continent: "NA",
+ timezone: "America/Chicago",
+ latitude: "30.27130",
+ longitude: "-97.74260",
+ clientTcpRtt: 0,
+ httpProtocol: "HTTP/1.1",
+ requestPriority: "weight=192;exclusive=0",
+ tlsCipher: "AEAD-AES128-GCM-SHA256",
+ tlsVersion: "TLSv1.3",
+ tlsClientAuth: {
+ certPresented: "0",
+ certVerified: "NONE",
+ certRevoked: "0",
+ certIssuerDN: "",
+ certSubjectDN: "",
+ certIssuerDNRFC2253: "",
+ certSubjectDNRFC2253: "",
+ certIssuerDNLegacy: "",
+ certSubjectDNLegacy: "",
+ certSerial: "",
+ certIssuerSerial: "",
+ certSKI: "",
+ certIssuerSKI: "",
+ certFingerprintSHA1: "",
+ certFingerprintSHA256: "",
+ certNotBefore: "",
+ certNotAfter: ""
+ },
+ edgeRequestKeepAliveStatus: 0,
+ hostMetadata: void 0,
+ clientTrustScore: 99,
+ botManagement: {
+ corporateProxy: false,
+ verifiedBot: false,
+ ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
+ staticResource: false,
+ detectionIds: [],
+ score: 99
+ }
+};
+var DAY = 864e5;
+var CF_DAYS = 30;
+async function setupCf(log, cf) {
+ if (!(cf ?? process.env.NODE_ENV !== "test")) {
+ return fallbackCf;
+ }
+ if (typeof cf === "object") {
+ return cf;
+ }
+ let cfPath = defaultCfPath;
+ if (typeof cf === "string") {
+ cfPath = cf;
+ }
+ try {
+ const storedCf = JSON.parse(await (0, import_promises.readFile)(cfPath, "utf8"));
+ const cfStat = await (0, import_promises.stat)(cfPath);
+ (0, import_assert.default)(Date.now() - cfStat.mtimeMs <= CF_DAYS * DAY);
+ return storedCf;
+ } catch {
+ }
+ try {
+ const res = await (0, import_undici.fetch)(defaultCfFetchEndpoint);
+ const cfText = await res.text();
+ const storedCf = JSON.parse(cfText);
+ await (0, import_promises.mkdir)(import_path3.default.dirname(cfPath), { recursive: true });
+ await (0, import_promises.writeFile)(cfPath, cfText, "utf8");
+ log.debug("Updated `Request.cf` object cache!");
+ return storedCf;
+ } catch (e) {
+ log.warn(
+ "Unable to fetch the `Request.cf` object! Falling back to a default placeholder...\n" + dim(e.cause ? e.cause.stack : e.stack)
+ );
+ return fallbackCf;
+ }
+}
+
+// packages/miniflare/src/http/fetch.ts
+var import_undici4 = require("undici");
+var import_ws2 = __toESM(require("ws"));
+
+// packages/miniflare/src/workers/cache/constants.ts
+var CacheHeaders = {
+ NAMESPACE: "cf-cache-namespace",
+ STATUS: "cf-cache-status"
+};
+var CacheBindings = {
+ MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE"
+};
+
+// packages/miniflare/src/workers/core/constants.ts
+var CoreHeaders = {
+ CUSTOM_SERVICE: "MF-Custom-Service",
+ ORIGINAL_URL: "MF-Original-URL",
+ ERROR_STACK: "MF-Experimental-Error-Stack",
+ ROUTE_OVERRIDE: "MF-Route-Override",
+ // API Proxy
+ OP: "MF-Op",
+ OP_TARGET: "MF-Op-Target",
+ OP_KEY: "MF-Op-Key",
+ OP_SYNC: "MF-Op-Sync",
+ OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size",
+ OP_RESULT_TYPE: "MF-Op-Result-Type"
+};
+var CoreBindings = {
+ SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK",
+ SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_",
+ SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK",
+ TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE",
+ TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL",
+ JSON_CF_BLOB: "CF_BLOB",
+ JSON_ROUTES: "MINIFLARE_ROUTES",
+ JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL",
+ DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT",
+ DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY"
+};
+var ProxyOps = {
+ // Get the target or a property of the target
+ GET: "GET",
+ // Call a method on the target
+ CALL: "CALL",
+ // Remove the strong reference to the target on the "heap", allowing it to be
+ // garbage collected
+ FREE: "FREE"
+};
+var ProxyAddresses = {
+ GLOBAL: 0,
+ // globalThis
+ ENV: 1,
+ // env
+ USER_START: 2
+};
+function isFetcherFetch(targetName, key) {
+ return (targetName === "Fetcher" || targetName === "DurableObject") && key === "fetch";
+}
+function isR2ObjectWriteHttpMetadata(targetName, key) {
+ return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata";
+}
+
+// packages/miniflare/src/workers/core/devalue.ts
+var import_node_assert = __toESM(require("node:assert"));
+var import_node_buffer = require("node:buffer");
+
+// node_modules/devalue/src/utils.js
+var escaped = {
+ "<": "\\u003C",
+ ">": "\\u003E",
+ "/": "\\u002F",
+ "\\": "\\\\",
+ "\b": "\\b",
+ "\f": "\\f",
+ "\n": "\\n",
+ "\r": "\\r",
+ " ": "\\t",
+ "\0": "\\u0000",
+ "\u2028": "\\u2028",
+ "\u2029": "\\u2029"
+};
+var DevalueError = class extends Error {
+ /**
+ * @param {string} message
+ * @param {string[]} keys
+ */
+ constructor(message, keys) {
+ super(message);
+ this.name = "DevalueError";
+ this.path = keys.join("");
+ }
+};
+function is_primitive(thing) {
+ return Object(thing) !== thing;
+}
+var object_proto_names = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
+function is_plain_object(thing) {
+ const proto = Object.getPrototypeOf(thing);
+ return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
+}
+function get_type(thing) {
+ return Object.prototype.toString.call(thing).slice(8, -1);
+}
+function stringify_string(str) {
+ let result = '"';
+ for (let i = 0; i < str.length; i += 1) {
+ const char = str.charAt(i);
+ const code = char.charCodeAt(0);
+ if (char === '"') {
+ result += '\\"';
+ } else if (char in escaped) {
+ result += escaped[char];
+ } else if (code <= 31) {
+ result += `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
+ } else if (code >= 55296 && code <= 57343) {
+ const next = str.charCodeAt(i + 1);
+ if (code <= 56319 && next >= 56320 && next <= 57343) {
+ result += char + str[++i];
+ } else {
+ result += `\\u${code.toString(16).toUpperCase()}`;
+ }
+ } else {
+ result += char;
+ }
+ }
+ result += '"';
+ return result;
+}
+
+// node_modules/devalue/src/constants.js
+var UNDEFINED = -1;
+var HOLE = -2;
+var NAN = -3;
+var POSITIVE_INFINITY = -4;
+var NEGATIVE_INFINITY = -5;
+var NEGATIVE_ZERO = -6;
+
+// node_modules/devalue/src/parse.js
+function parse(serialized, revivers2) {
+ return unflatten(JSON.parse(serialized), revivers2);
+}
+function unflatten(parsed, revivers2) {
+ if (typeof parsed === "number")
+ return hydrate(parsed, true);
+ if (!Array.isArray(parsed) || parsed.length === 0) {
+ throw new Error("Invalid input");
+ }
+ const values = (
+ /** @type {any[]} */
+ parsed
+ );
+ const hydrated = Array(values.length);
+ function hydrate(index, standalone = false) {
+ if (index === UNDEFINED)
+ return void 0;
+ if (index === NAN)
+ return NaN;
+ if (index === POSITIVE_INFINITY)
+ return Infinity;
+ if (index === NEGATIVE_INFINITY)
+ return -Infinity;
+ if (index === NEGATIVE_ZERO)
+ return -0;
+ if (standalone)
+ throw new Error(`Invalid input`);
+ if (index in hydrated)
+ return hydrated[index];
+ const value = values[index];
+ if (!value || typeof value !== "object") {
+ hydrated[index] = value;
+ } else if (Array.isArray(value)) {
+ if (typeof value[0] === "string") {
+ const type = value[0];
+ const reviver = revivers2?.[type];
+ if (reviver) {
+ return hydrated[index] = reviver(hydrate(value[1]));
+ }
+ switch (type) {
+ case "Date":
+ hydrated[index] = new Date(value[1]);
+ break;
+ case "Set":
+ const set = /* @__PURE__ */ new Set();
+ hydrated[index] = set;
+ for (let i = 1; i < value.length; i += 1) {
+ set.add(hydrate(value[i]));
+ }
+ break;
+ case "Map":
+ const map = /* @__PURE__ */ new Map();
+ hydrated[index] = map;
+ for (let i = 1; i < value.length; i += 2) {
+ map.set(hydrate(value[i]), hydrate(value[i + 1]));
+ }
+ break;
+ case "RegExp":
+ hydrated[index] = new RegExp(value[1], value[2]);
+ break;
+ case "Object":
+ hydrated[index] = Object(value[1]);
+ break;
+ case "BigInt":
+ hydrated[index] = BigInt(value[1]);
+ break;
+ case "null":
+ const obj = /* @__PURE__ */ Object.create(null);
+ hydrated[index] = obj;
+ for (let i = 1; i < value.length; i += 2) {
+ obj[value[i]] = hydrate(value[i + 1]);
+ }
+ break;
+ default:
+ throw new Error(`Unknown type ${type}`);
+ }
+ } else {
+ const array = new Array(value.length);
+ hydrated[index] = array;
+ for (let i = 0; i < value.length; i += 1) {
+ const n = value[i];
+ if (n === HOLE)
+ continue;
+ array[i] = hydrate(n);
+ }
+ }
+ } else {
+ const object = {};
+ hydrated[index] = object;
+ for (const key in value) {
+ const n = value[key];
+ object[key] = hydrate(n);
+ }
+ }
+ return hydrated[index];
+ }
+ return hydrate(0);
+}
+
+// node_modules/devalue/src/stringify.js
+function stringify(value, reducers2) {
+ const stringified = [];
+ const indexes = /* @__PURE__ */ new Map();
+ const custom = [];
+ for (const key in reducers2) {
+ custom.push({ key, fn: reducers2[key] });
+ }
+ const keys = [];
+ let p = 0;
+ function flatten(thing) {
+ if (typeof thing === "function") {
+ throw new DevalueError(`Cannot stringify a function`, keys);
+ }
+ if (indexes.has(thing))
+ return indexes.get(thing);
+ if (thing === void 0)
+ return UNDEFINED;
+ if (Number.isNaN(thing))
+ return NAN;
+ if (thing === Infinity)
+ return POSITIVE_INFINITY;
+ if (thing === -Infinity)
+ return NEGATIVE_INFINITY;
+ if (thing === 0 && 1 / thing < 0)
+ return NEGATIVE_ZERO;
+ const index2 = p++;
+ indexes.set(thing, index2);
+ for (const { key, fn } of custom) {
+ const value2 = fn(thing);
+ if (value2) {
+ stringified[index2] = `["${key}",${flatten(value2)}]`;
+ return index2;
+ }
+ }
+ let str = "";
+ if (is_primitive(thing)) {
+ str = stringify_primitive(thing);
+ } else {
+ const type = get_type(thing);
+ switch (type) {
+ case "Number":
+ case "String":
+ case "Boolean":
+ str = `["Object",${stringify_primitive(thing)}]`;
+ break;
+ case "BigInt":
+ str = `["BigInt",${thing}]`;
+ break;
+ case "Date":
+ str = `["Date","${thing.toISOString()}"]`;
+ break;
+ case "RegExp":
+ const { source, flags } = thing;
+ str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`;
+ break;
+ case "Array":
+ str = "[";
+ for (let i = 0; i < thing.length; i += 1) {
+ if (i > 0)
+ str += ",";
+ if (i in thing) {
+ keys.push(`[${i}]`);
+ str += flatten(thing[i]);
+ keys.pop();
+ } else {
+ str += HOLE;
+ }
+ }
+ str += "]";
+ break;
+ case "Set":
+ str = '["Set"';
+ for (const value2 of thing) {
+ str += `,${flatten(value2)}`;
+ }
+ str += "]";
+ break;
+ case "Map":
+ str = '["Map"';
+ for (const [key, value2] of thing) {
+ keys.push(
+ `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})`
+ );
+ str += `,${flatten(key)},${flatten(value2)}`;
+ }
+ str += "]";
+ break;
+ default:
+ if (!is_plain_object(thing)) {
+ throw new DevalueError(
+ `Cannot stringify arbitrary non-POJOs`,
+ keys
+ );
+ }
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
+ throw new DevalueError(
+ `Cannot stringify POJOs with symbolic keys`,
+ keys
+ );
+ }
+ if (Object.getPrototypeOf(thing) === null) {
+ str = '["null"';
+ for (const key in thing) {
+ keys.push(`.${key}`);
+ str += `,${stringify_string(key)},${flatten(thing[key])}`;
+ keys.pop();
+ }
+ str += "]";
+ } else {
+ str = "{";
+ let started = false;
+ for (const key in thing) {
+ if (started)
+ str += ",";
+ started = true;
+ keys.push(`.${key}`);
+ str += `${stringify_string(key)}:${flatten(thing[key])}`;
+ keys.pop();
+ }
+ str += "}";
+ }
+ }
+ }
+ stringified[index2] = str;
+ return index2;
+ }
+ const index = flatten(value);
+ if (index < 0)
+ return `${index}`;
+ return `[${stringified.join(",")}]`;
+}
+function stringify_primitive(thing) {
+ const type = typeof thing;
+ if (type === "string")
+ return stringify_string(thing);
+ if (thing instanceof String)
+ return stringify_string(thing.toString());
+ if (thing === void 0)
+ return UNDEFINED.toString();
+ if (thing === 0 && 1 / thing < 0)
+ return NEGATIVE_ZERO.toString();
+ if (type === "bigint")
+ return `["BigInt","${thing}"]`;
+ return String(thing);
+}
+
+// packages/miniflare/src/workers/core/devalue.ts
+var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [
+ DataView,
+ Int8Array,
+ Uint8Array,
+ Uint8ClampedArray,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ BigInt64Array,
+ BigUint64Array
+];
+var ALLOWED_ERROR_CONSTRUCTORS = [
+ EvalError,
+ RangeError,
+ ReferenceError,
+ SyntaxError,
+ TypeError,
+ URIError,
+ Error
+ // `Error` last so more specific error subclasses preferred
+];
+var structuredSerializableReducers = {
+ ArrayBuffer(value) {
+ if (value instanceof ArrayBuffer) {
+ return [import_node_buffer.Buffer.from(value).toString("base64")];
+ }
+ },
+ ArrayBufferView(value) {
+ if (ArrayBuffer.isView(value)) {
+ return [
+ value.constructor.name,
+ value.buffer,
+ value.byteOffset,
+ value.byteLength
+ ];
+ }
+ },
+ Error(value) {
+ for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) {
+ if (value instanceof ctor && value.name === ctor.name) {
+ return [value.name, value.message, value.stack, value.cause];
+ }
+ }
+ if (value instanceof Error) {
+ return ["Error", value.message, value.stack, value.cause];
+ }
+ }
+};
+var structuredSerializableRevivers = {
+ ArrayBuffer(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ const [encoded] = value;
+ (0, import_node_assert.default)(typeof encoded === "string");
+ const view = import_node_buffer.Buffer.from(encoded, "base64");
+ return view.buffer.slice(
+ view.byteOffset,
+ view.byteOffset + view.byteLength
+ );
+ },
+ ArrayBufferView(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ const [name, buffer, byteOffset, byteLength] = value;
+ (0, import_node_assert.default)(typeof name === "string");
+ (0, import_node_assert.default)(buffer instanceof ArrayBuffer);
+ (0, import_node_assert.default)(typeof byteOffset === "number");
+ (0, import_node_assert.default)(typeof byteLength === "number");
+ const ctor = globalThis[name];
+ (0, import_node_assert.default)(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor));
+ let length = byteLength;
+ if ("BYTES_PER_ELEMENT" in ctor)
+ length /= ctor.BYTES_PER_ELEMENT;
+ return new ctor(buffer, byteOffset, length);
+ },
+ Error(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ const [name, message, stack, cause] = value;
+ (0, import_node_assert.default)(typeof name === "string");
+ (0, import_node_assert.default)(typeof message === "string");
+ (0, import_node_assert.default)(stack === void 0 || typeof stack === "string");
+ const ctor = globalThis[name];
+ (0, import_node_assert.default)(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
+ const error = new ctor(message, { cause });
+ error.stack = stack;
+ return error;
+ }
+};
+function createHTTPReducers(impl) {
+ return {
+ Headers(val) {
+ if (val instanceof impl.Headers)
+ return Object.fromEntries(val);
+ },
+ Request(val) {
+ if (val instanceof impl.Request) {
+ return [val.method, val.url, val.headers, val.cf, val.body];
+ }
+ },
+ Response(val) {
+ if (val instanceof impl.Response) {
+ return [val.status, val.statusText, val.headers, val.cf, val.body];
+ }
+ }
+ };
+}
+function createHTTPRevivers(impl) {
+ return {
+ Headers(value) {
+ (0, import_node_assert.default)(typeof value === "object" && value !== null);
+ return new impl.Headers(value);
+ },
+ Request(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ const [method, url13, headers, cf, body] = value;
+ (0, import_node_assert.default)(typeof method === "string");
+ (0, import_node_assert.default)(typeof url13 === "string");
+ (0, import_node_assert.default)(headers instanceof impl.Headers);
+ (0, import_node_assert.default)(body === null || impl.isReadableStream(body));
+ return new impl.Request(url13, {
+ method,
+ headers,
+ cf,
+ // @ts-expect-error `duplex` is not required by `workerd` yet
+ duplex: body === null ? void 0 : "half",
+ body
+ });
+ },
+ Response(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ const [status, statusText, headers, cf, body] = value;
+ (0, import_node_assert.default)(typeof status === "number");
+ (0, import_node_assert.default)(typeof statusText === "string");
+ (0, import_node_assert.default)(headers instanceof impl.Headers);
+ (0, import_node_assert.default)(body === null || impl.isReadableStream(body));
+ return new impl.Response(body, {
+ status,
+ statusText,
+ headers,
+ cf
+ });
+ }
+ };
+}
+function stringifyWithStreams(impl, value, reducers2, allowUnbufferedStream) {
+ let unbufferedStream;
+ const bufferPromises = [];
+ const streamReducers = {
+ ReadableStream(value2) {
+ if (impl.isReadableStream(value2)) {
+ if (allowUnbufferedStream && unbufferedStream === void 0) {
+ unbufferedStream = value2;
+ } else {
+ bufferPromises.push(impl.bufferReadableStream(value2));
+ }
+ return true;
+ }
+ },
+ Blob(value2) {
+ if (value2 instanceof impl.Blob) {
+ bufferPromises.push(value2.arrayBuffer());
+ return true;
+ }
+ },
+ ...reducers2
+ };
+ const stringifiedValue = stringify(value, streamReducers);
+ if (bufferPromises.length === 0) {
+ return { value: stringifiedValue, unbufferedStream };
+ }
+ return Promise.all(bufferPromises).then((streamBuffers) => {
+ streamReducers.ReadableStream = function(value2) {
+ if (impl.isReadableStream(value2)) {
+ if (value2 === unbufferedStream) {
+ return true;
+ } else {
+ return streamBuffers.shift();
+ }
+ }
+ };
+ streamReducers.Blob = function(value2) {
+ if (value2 instanceof impl.Blob) {
+ const array = [streamBuffers.shift(), value2.type];
+ if (value2 instanceof impl.File) {
+ array.push(value2.name, value2.lastModified);
+ }
+ return array;
+ }
+ };
+ const stringifiedValue2 = stringify(value, streamReducers);
+ return { value: stringifiedValue2, unbufferedStream };
+ });
+}
+function parseWithReadableStreams(impl, stringified, revivers2) {
+ const streamRevivers = {
+ ReadableStream(value) {
+ if (value === true) {
+ (0, import_node_assert.default)(stringified.unbufferedStream !== void 0);
+ return stringified.unbufferedStream;
+ }
+ (0, import_node_assert.default)(value instanceof ArrayBuffer);
+ return impl.unbufferReadableStream(value);
+ },
+ Blob(value) {
+ (0, import_node_assert.default)(Array.isArray(value));
+ if (value.length === 2) {
+ const [buffer, type] = value;
+ (0, import_node_assert.default)(buffer instanceof ArrayBuffer);
+ (0, import_node_assert.default)(typeof type === "string");
+ const opts = {};
+ if (type !== "")
+ opts.type = type;
+ return new impl.Blob([buffer], opts);
+ } else {
+ (0, import_node_assert.default)(value.length === 4);
+ const [buffer, type, name, lastModified] = value;
+ (0, import_node_assert.default)(buffer instanceof ArrayBuffer);
+ (0, import_node_assert.default)(typeof type === "string");
+ (0, import_node_assert.default)(typeof name === "string");
+ (0, import_node_assert.default)(typeof lastModified === "number");
+ const opts = { lastModified };
+ if (type !== "")
+ opts.type = type;
+ return new impl.File([buffer], name, opts);
+ }
+ },
+ ...revivers2
+ };
+ return parse(stringified.value, streamRevivers);
+}
+
+// packages/miniflare/src/workers/core/routing.ts
+function matchRoutes(routes, url13) {
+ for (const route of routes) {
+ if (route.protocol && route.protocol !== url13.protocol)
+ continue;
+ if (route.allowHostnamePrefix) {
+ if (!url13.hostname.endsWith(route.hostname))
+ continue;
+ } else {
+ if (url13.hostname !== route.hostname)
+ continue;
+ }
+ const path21 = url13.pathname + url13.search;
+ if (route.allowPathSuffix) {
+ if (!path21.startsWith(route.path))
+ continue;
+ } else {
+ if (path21 !== route.path)
+ continue;
+ }
+ return route.target;
+ }
+ return null;
+}
+
+// packages/miniflare/src/workers/shared/constants.ts
+var SharedHeaders = {
+ LOG_LEVEL: "MF-Log-Level"
+};
+var SharedBindings = {
+ TEXT_NAMESPACE: "MINIFLARE_NAMESPACE",
+ DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT",
+ MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS",
+ MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK"
+};
+var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
+ LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
+ LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
+ LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
+ LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
+ LogLevel2[LogLevel2["VERBOSE"] = 5] = "VERBOSE";
+ return LogLevel2;
+})(LogLevel || {});
+
+// packages/miniflare/src/workers/shared/data.ts
+var import_node_buffer2 = require("node:buffer");
+function viewToBuffer(view) {
+ return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
+}
+function base64Encode(value) {
+ return import_node_buffer2.Buffer.from(value, "utf8").toString("base64");
+}
+function base64Decode(encoded) {
+ return import_node_buffer2.Buffer.from(encoded, "base64").toString("utf8");
+}
+var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g;
+var illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g;
+var windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
+var leadingRegexp = /^[ /\\]+/;
+var trailingRegexp = /[ /\\]+$/;
+function dotReplacement(match, g1, g2, g3) {
+ return `${g1}${"".padStart(g2.length, "_")}${g3}`;
+}
+function underscoreReplacement(match) {
+ return "".padStart(match.length, "_");
+}
+function sanitisePath(unsafe) {
+ return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255);
+}
+
+// packages/miniflare/src/workers/shared/matcher.ts
+function testRegExps(matcher, value) {
+ for (const exclude of matcher.exclude)
+ if (exclude.test(value))
+ return false;
+ for (const include of matcher.include)
+ if (include.test(value))
+ return true;
+ return false;
+}
+
+// packages/miniflare/src/workers/shared/range.ts
+var rangePrefixRegexp = /^ *bytes *=/i;
+var rangeRegexp = /^ *(?<start>\d+)? *- *(?<end>\d+)? *$/;
+function parseRanges(rangeHeader, length) {
+ const prefixMatch = rangePrefixRegexp.exec(rangeHeader);
+ if (prefixMatch === null)
+ return;
+ rangeHeader = rangeHeader.substring(prefixMatch[0].length);
+ if (rangeHeader.trimStart() === "")
+ return [];
+ const ranges = rangeHeader.split(",");
+ const result = [];
+ for (const range of ranges) {
+ const match = rangeRegexp.exec(range);
+ if (match === null)
+ return;
+ const { start, end } = match.groups;
+ if (start !== void 0 && end !== void 0) {
+ const rangeStart = parseInt(start);
+ let rangeEnd = parseInt(end);
+ if (rangeStart > rangeEnd)
+ return;
+ if (rangeStart >= length)
+ return;
+ if (rangeEnd >= length)
+ rangeEnd = length - 1;
+ result.push({ start: rangeStart, end: rangeEnd });
+ } else if (start !== void 0 && end === void 0) {
+ const rangeStart = parseInt(start);
+ if (rangeStart >= length)
+ return;
+ result.push({ start: rangeStart, end: length - 1 });
+ } else if (start === void 0 && end !== void 0) {
+ const suffix = parseInt(end);
+ if (suffix >= length)
+ return [];
+ if (suffix === 0)
+ continue;
+ result.push({ start: length - suffix, end: length - 1 });
+ } else {
+ return;
+ }
+ }
+ return result;
+}
+
+// packages/miniflare/src/workers/shared/sync.ts
+var import_node_assert2 = __toESM(require("node:assert"));
+var DeferredPromise = class extends Promise {
+ resolve;
+ reject;
+ constructor(executor = () => {
+ }) {
+ let promiseResolve;
+ let promiseReject;
+ super((resolve, reject) => {
+ promiseResolve = resolve;
+ promiseReject = reject;
+ return executor(resolve, reject);
+ });
+ this.resolve = promiseResolve;
+ this.reject = promiseReject;
+ }
+};
+var Mutex = class {
+ locked = false;
+ resolveQueue = [];
+ drainQueue = [];
+ lock() {
+ if (!this.locked) {
+ this.locked = true;
+ return;
+ }
+ return new Promise((resolve) => this.resolveQueue.push(resolve));
+ }
+ unlock() {
+ (0, import_node_assert2.default)(this.locked);
+ if (this.resolveQueue.length > 0) {
+ this.resolveQueue.shift()?.();
+ } else {
+ this.locked = false;
+ let resolve;
+ while ((resolve = this.drainQueue.shift()) !== void 0)
+ resolve();
+ }
+ }
+ get hasWaiting() {
+ return this.resolveQueue.length > 0;
+ }
+ async runWith(closure) {
+ const acquireAwaitable = this.lock();
+ if (acquireAwaitable instanceof Promise)
+ await acquireAwaitable;
+ try {
+ const awaitable = closure();
+ if (awaitable instanceof Promise)
+ return await awaitable;
+ return awaitable;
+ } finally {
+ this.unlock();
+ }
+ }
+ async drained() {
+ if (this.resolveQueue.length === 0)
+ return;
+ return new Promise((resolve) => this.drainQueue.push(resolve));
+ }
+};
+var WaitGroup = class {
+ counter = 0;
+ resolveQueue = [];
+ add() {
+ this.counter++;
+ }
+ done() {
+ (0, import_node_assert2.default)(this.counter > 0);
+ this.counter--;
+ if (this.counter === 0) {
+ let resolve;
+ while ((resolve = this.resolveQueue.shift()) !== void 0)
+ resolve();
+ }
+ }
+ wait() {
+ if (this.counter === 0)
+ return Promise.resolve();
+ return new Promise((resolve) => this.resolveQueue.push(resolve));
+ }
+};
+
+// packages/miniflare/src/workers/shared/types.ts
+function reduceError(e) {
+ return {
+ name: e?.name,
+ message: e?.message ?? String(e),
+ stack: e?.stack,
+ cause: e?.cause === void 0 ? void 0 : reduceError(e.cause)
+ };
+}
+function maybeApply(f, maybeValue) {
+ return maybeValue === void 0 ? void 0 : f(maybeValue);
+}
+
+// packages/miniflare/src/workers/kv/constants.ts
+var KVLimits = {
+ MIN_CACHE_TTL: 60,
+ MAX_LIST_KEYS: 1e3,
+ MAX_KEY_SIZE: 512,
+ MAX_VALUE_SIZE: 25 * 1024 * 1024,
+ MAX_VALUE_SIZE_TEST: 1024,
+ MAX_METADATA_SIZE: 1024
+};
+var KVParams = {
+ URL_ENCODED: "urlencoded",
+ CACHE_TTL: "cache_ttl",
+ EXPIRATION: "expiration",
+ EXPIRATION_TTL: "expiration_ttl",
+ LIST_LIMIT: "key_count_limit",
+ LIST_PREFIX: "prefix",
+ LIST_CURSOR: "cursor"
+};
+var KVHeaders = {
+ EXPIRATION: "CF-Expiration",
+ METADATA: "CF-KV-Metadata"
+};
+var SiteBindings = {
+ KV_NAMESPACE_SITE: "__STATIC_CONTENT",
+ JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST",
+ JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER"
+};
+var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/";
+function encodeSitesKey(key) {
+ return SITES_NO_CACHE_PREFIX + encodeURIComponent(key);
+}
+function decodeSitesKey(key) {
+ return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key;
+}
+function isSitesRequest(request) {
+ const url13 = new URL(request.url);
+ return url13.pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`);
+}
+function serialiseRegExp(regExp) {
+ const str = regExp.toString();
+ return str.substring(str.indexOf("/") + 1, str.lastIndexOf("/"));
+}
+function serialiseRegExps(matcher) {
+ return {
+ include: matcher.include.map(serialiseRegExp),
+ exclude: matcher.exclude.map(serialiseRegExp)
+ };
+}
+function deserialiseRegExps(matcher) {
+ return {
+ include: matcher.include.map((regExp) => new RegExp(regExp)),
+ exclude: matcher.exclude.map((regExp) => new RegExp(regExp))
+ };
+}
+function serialiseSiteRegExps(siteRegExps) {
+ return {
+ include: siteRegExps.include && serialiseRegExps(siteRegExps.include),
+ exclude: siteRegExps.exclude && serialiseRegExps(siteRegExps.exclude)
+ };
+}
+function deserialiseSiteRegExps(siteRegExps) {
+ return {
+ include: siteRegExps.include && deserialiseRegExps(siteRegExps.include),
+ exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude)
+ };
+}
+function testSiteRegExps(regExps, key) {
+ if (regExps.include !== void 0)
+ return testRegExps(regExps.include, key);
+ if (regExps.exclude !== void 0)
+ return !testRegExps(regExps.exclude, key);
+ return true;
+}
+
+// packages/miniflare/src/workers/queues/constants.ts
+var QueueBindings = {
+ SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_",
+ MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS"
+};
+
+// packages/miniflare/src/workers/shared/zod.worker.ts
+var import_node_buffer3 = require("node:buffer");
+var import_zod = require("zod");
+var import_zod2 = require("zod");
+var HEX_REGEXP = /^[0-9a-f]*$/i;
+var BASE64_REGEXP = /^[0-9a-z+/=]*$/i;
+var HexDataSchema = import_zod.z.string().regex(HEX_REGEXP).transform((hex) => import_node_buffer3.Buffer.from(hex, "hex"));
+var Base64DataSchema = import_zod.z.string().regex(BASE64_REGEXP).transform((base64) => import_node_buffer3.Buffer.from(base64, "base64"));
+
+// packages/miniflare/src/workers/queues/schemas.ts
+var QueueConsumerOptionsSchema = /* @__PURE__ */ import_zod2.z.object({
+ // https://developers.cloudflare.com/queues/platform/configuration/#consumer
+ // https://developers.cloudflare.com/queues/platform/limits/
+ maxBatchSize: import_zod2.z.number().min(0).max(100).optional(),
+ maxBatchTimeout: import_zod2.z.number().min(0).max(30).optional(),
+ // seconds
+ maxRetires: import_zod2.z.number().min(0).max(100).optional(),
+ deadLetterQueue: import_zod2.z.ostring()
+});
+var QueueConsumerSchema = /* @__PURE__ */ import_zod2.z.intersection(
+ QueueConsumerOptionsSchema,
+ import_zod2.z.object({ workerName: import_zod2.z.string() })
+);
+var QueueConsumersSchema = /* @__PURE__ */ import_zod2.z.record(QueueConsumerSchema);
+var QueueContentTypeSchema = /* @__PURE__ */ import_zod2.z.enum(["text", "json", "bytes", "v8"]).default("v8");
+var QueueIncomingMessageSchema = /* @__PURE__ */ import_zod2.z.object({
+ contentType: QueueContentTypeSchema,
+ body: Base64DataSchema,
+ // When enqueuing messages on dead-letter queues, we want to reuse the same ID
+ // and timestamp
+ id: import_zod2.z.ostring(),
+ timestamp: import_zod2.z.onumber()
+});
+var QueuesBatchRequestSchema = /* @__PURE__ */ import_zod2.z.object({
+ messages: import_zod2.z.array(QueueIncomingMessageSchema)
+});
+
+// packages/miniflare/src/http/request.ts
+var import_undici2 = require("undici");
+var kCf = Symbol("kCf");
+var Request = class extends import_undici2.Request {
+ // We should be able to use a private `#cf` property here instead of a symbol
+ // here, but we need to set this on a clone, which would otherwise lead to a
+ // "Cannot write private member to an object whose class did not declare it"
+ // error.
+ [kCf];
+ constructor(input, init2) {
+ super(input, init2);
+ this[kCf] = init2?.cf;
+ if (input instanceof Request)
+ this[kCf] ??= input.cf;
+ }
+ get cf() {
+ return this[kCf];
+ }
+ // JSDoc comment so retained when bundling types with api-extractor
+ /** @ts-expect-error `clone` is actually defined as a method internally */
+ clone() {
+ const request = super.clone();
+ Object.setPrototypeOf(request, Request.prototype);
+ request[kCf] = this[kCf];
+ return request;
+ }
+};
+
+// packages/miniflare/src/http/response.ts
+var import_undici3 = require("undici");
+var kWebSocket = Symbol("kWebSocket");
+var Response = class extends import_undici3.Response {
+ // We should be able to use a private `#webSocket` property here instead of a
+ // symbol here, but `undici` calls `this.status` in its constructor, which
+ // causes a "Cannot read private member from an object whose class did not
+ // declare it" error.
+ [kWebSocket];
+ // Override BaseResponse's static methods for building Responses to return
+ // our type instead. Ideally, we don't want to use `Object.setPrototypeOf`.
+ // Unfortunately, `error()` and `redirect()` set the internal header guard
+ // to "immutable".
+ static error() {
+ const response = import_undici3.Response.error();
+ Object.setPrototypeOf(response, Response.prototype);
+ return response;
+ }
+ static redirect(url13, status) {
+ const response = import_undici3.Response.redirect(url13, status);
+ Object.setPrototypeOf(response, Response.prototype);
+ return response;
+ }
+ static json(data, init2) {
+ const body = JSON.stringify(data);
+ const response = new Response(body, init2);
+ response.headers.set("Content-Type", "application/json");
+ return response;
+ }
+ constructor(body, init2) {
+ if (init2?.webSocket) {
+ if (init2.status !== 101) {
+ throw new RangeError(
+ "Responses with a WebSocket must have status code 101."
+ );
+ }
+ init2 = { ...init2, status: 200 };
+ }
+ super(body, init2);
+ this[kWebSocket] = init2?.webSocket ?? null;
+ }
+ // JSDoc comment so retained when bundling types with api-extractor
+ /** @ts-expect-error `status` is actually defined as a getter internally */
+ get status() {
+ return this[kWebSocket] ? 101 : super.status;
+ }
+ get webSocket() {
+ return this[kWebSocket];
+ }
+ // JSDoc comment so retained when bundling types with api-extractor
+ /** @ts-expect-error `clone` is actually defined as a method internally */
+ clone() {
+ if (this[kWebSocket]) {
+ throw new TypeError("Cannot clone a response to a WebSocket handshake.");
+ }
+ const response = super.clone();
+ Object.setPrototypeOf(response, Response.prototype);
+ return response;
+ }
+};
+
+// packages/miniflare/src/http/websocket.ts
+var import_assert2 = __toESM(require("assert"));
+var import_events = require("events");
+var import_ws = __toESM(require("ws"));
+
+// packages/miniflare/src/shared/colour.ts
+var originalEnabled = $.enabled;
+function _forceColour(enabled = originalEnabled) {
+ $.enabled = enabled;
+}
+
+// packages/miniflare/src/shared/error.ts
+var MiniflareError = class extends Error {
+ constructor(code, message, cause) {
+ super(message);
+ this.code = code;
+ this.cause = cause;
+ Object.setPrototypeOf(this, new.target.prototype);
+ this.name = `${new.target.name} [${code}]`;
+ }
+};
+var MiniflareCoreError = class extends MiniflareError {
+};
+
+// packages/miniflare/src/shared/event.ts
+var TypedEventTarget = class extends EventTarget {
+ addEventListener(type, listener, options) {
+ super.addEventListener(
+ type,
+ listener,
+ options
+ );
+ }
+ removeEventListener(type, listener, options) {
+ super.removeEventListener(
+ type,
+ listener,
+ options
+ );
+ }
+ dispatchEvent(event) {
+ return super.dispatchEvent(event);
+ }
+};
+
+// packages/miniflare/src/shared/log.ts
+var import_path4 = __toESM(require("path"));
+var cwd = process.cwd();
+var cwdNodeModules = import_path4.default.join(cwd, "node_modules");
+var LEVEL_PREFIX = {
+ [0 /* NONE */]: "",
+ [1 /* ERROR */]: "err",
+ [2 /* WARN */]: "wrn",
+ [3 /* INFO */]: "inf",
+ [4 /* DEBUG */]: "dbg",
+ [5 /* VERBOSE */]: "vrb"
+};
+var LEVEL_COLOUR = {
+ [0 /* NONE */]: reset,
+ [1 /* ERROR */]: red,
+ [2 /* WARN */]: yellow,
+ [3 /* INFO */]: green,
+ [4 /* DEBUG */]: grey,
+ [5 /* VERBOSE */]: (input) => dim(grey(input))
+};
+function prefixError(prefix, e) {
+ if (e.stack) {
+ return new Proxy(e, {
+ get(target, propertyKey, receiver) {
+ const value = Reflect.get(target, propertyKey, receiver);
+ return propertyKey === "stack" ? `${prefix}: ${value}` : value;
+ }
+ });
+ }
+ return e;
+}
+function dimInternalStackLine(line) {
+ if (line.startsWith(" at") && (!line.includes(cwd) || line.includes(cwdNodeModules))) {
+ return dim(line);
+ }
+ return line;
+}
+var Log = class {
+ constructor(level = 3 /* INFO */, opts = {}) {
+ this.level = level;
+ const prefix = opts.prefix ?? "mf";
+ const suffix = opts.suffix ?? "";
+ this.#prefix = prefix ? prefix + ":" : "";
+ this.#suffix = suffix ? ":" + suffix : "";
+ }
+ #prefix;
+ #suffix;
+ log(message) {
+ console.log(message);
+ }
+ logWithLevel(level, message) {
+ if (level <= this.level) {
+ const prefix = `[${this.#prefix}${LEVEL_PREFIX[level]}${this.#suffix}]`;
+ this.log(LEVEL_COLOUR[level](`${prefix} ${message}`));
+ }
+ }
+ error(message) {
+ if (this.level < 1 /* ERROR */) {
+ throw message;
+ } else if (message.stack) {
+ const lines = message.stack.split("\n").map(dimInternalStackLine);
+ this.logWithLevel(1 /* ERROR */, lines.join("\n"));
+ } else {
+ this.logWithLevel(1 /* ERROR */, message.toString());
+ }
+ if (message.cause) {
+ this.error(prefixError("Cause", message.cause));
+ }
+ }
+ warn(message) {
+ this.logWithLevel(2 /* WARN */, message);
+ }
+ info(message) {
+ this.logWithLevel(3 /* INFO */, message);
+ }
+ debug(message) {
+ this.logWithLevel(4 /* DEBUG */, message);
+ }
+ verbose(message) {
+ this.logWithLevel(5 /* VERBOSE */, message);
+ }
+};
+var NoOpLog = class extends Log {
+ constructor() {
+ super(0 /* NONE */);
+ }
+ log() {
+ }
+ error(message) {
+ throw message;
+ }
+};
+var ansiRegexpPattern = [
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
+].join("|");
+var ansiRegexp = new RegExp(ansiRegexpPattern, "g");
+function stripAnsi(value) {
+ return value.replace(ansiRegexp, "");
+}
+
+// packages/miniflare/src/shared/matcher.ts
+var import_glob_to_regexp = __toESM(require("glob-to-regexp"));
+function globsToRegExps(globs = []) {
+ const include = [];
+ const exclude = [];
+ const opts = { globstar: true, flags: "g" };
+ for (const glob of globs) {
+ if (glob.startsWith("!")) {
+ exclude.push(new RegExp((0, import_glob_to_regexp.default)(glob.slice(1), opts), ""));
+ } else {
+ include.push(new RegExp((0, import_glob_to_regexp.default)(glob, opts), ""));
+ }
+ }
+ return { include, exclude };
+}
+
+// packages/miniflare/src/shared/streams.ts
+var import_web = require("stream/web");
+function prefixStream(prefix, stream) {
+ const identity = new import_web.TransformStream();
+ const writer = identity.writable.getWriter();
+ void writer.write(prefix).then(() => {
+ writer.releaseLock();
+ return stream.pipeTo(identity.writable);
+ }).catch((error) => {
+ return writer.abort(error);
+ });
+ return identity.readable;
+}
+async function readPrefix(stream, prefixLength) {
+ const chunks = [];
+ let chunksLength = 0;
+ for await (const chunk of stream.values({ preventCancel: true })) {
+ chunks.push(chunk);
+ chunksLength += chunk.byteLength;
+ if (chunksLength >= prefixLength)
+ break;
+ }
+ if (chunksLength < prefixLength) {
+ throw new RangeError(
+ `Expected ${prefixLength} byte prefix, but received ${chunksLength} byte stream`
+ );
+ }
+ const atLeastPrefix = Buffer.concat(chunks, chunksLength);
+ const prefix = atLeastPrefix.subarray(0, prefixLength);
+ let rest = stream;
+ if (chunksLength > prefixLength) {
+ rest = prefixStream(atLeastPrefix.subarray(prefixLength), stream);
+ }
+ return [prefix, rest];
+}
+
+// packages/miniflare/src/shared/types.ts
+var import_zod3 = require("zod");
+function zAwaitable(type) {
+ return type.or(import_zod3.z.promise(type));
+}
+var LiteralSchema = import_zod3.z.union([
+ import_zod3.z.string(),
+ import_zod3.z.number(),
+ import_zod3.z.boolean(),
+ import_zod3.z.null()
+]);
+var JsonSchema = import_zod3.z.lazy(
+ () => import_zod3.z.union([LiteralSchema, import_zod3.z.array(JsonSchema), import_zod3.z.record(JsonSchema)])
+);
+
+// packages/miniflare/src/http/websocket.ts
+var MessageEvent = class extends Event {
+ data;
+ constructor(type, init2) {
+ super(type);
+ this.data = init2.data;
+ }
+};
+var CloseEvent = class extends Event {
+ code;
+ reason;
+ wasClean;
+ constructor(type, init2) {
+ super(type);
+ this.code = init2?.code ?? 1005;
+ this.reason = init2?.reason ?? "";
+ this.wasClean = init2?.wasClean ?? false;
+ }
+};
+var ErrorEvent = class extends Event {
+ error;
+ constructor(type, init2) {
+ super(type);
+ this.error = init2?.error ?? null;
+ }
+};
+var kPair = Symbol("kPair");
+var kAccepted = Symbol("kAccepted");
+var kCoupled = Symbol("kCoupled");
+var kClosedOutgoing = Symbol("kClosedOutgoing");
+var kClosedIncoming = Symbol("kClosedIncoming");
+var kSend = Symbol("kSend");
+var kClose = Symbol("kClose");
+var kError = Symbol("kError");
+var _dispatchQueue, _a, _b, _c, _d, _e, _queuingDispatchToPair, queuingDispatchToPair_fn;
+var _WebSocket = class extends TypedEventTarget {
+ constructor() {
+ super(...arguments);
+ __privateAdd(this, _queuingDispatchToPair);
+ __privateAdd(this, _dispatchQueue, []);
+ __publicField(this, _a);
+ __publicField(this, _b, false);
+ __publicField(this, _c, false);
+ __publicField(this, _d, false);
+ __publicField(this, _e, false);
+ }
+ get readyState() {
+ if (this[kClosedOutgoing] && this[kClosedIncoming]) {
+ return _WebSocket.READY_STATE_CLOSED;
+ } else if (this[kClosedOutgoing] || this[kClosedIncoming]) {
+ return _WebSocket.READY_STATE_CLOSING;
+ }
+ return _WebSocket.READY_STATE_OPEN;
+ }
+ accept() {
+ if (this[kCoupled]) {
+ throw new TypeError(
+ "Can't accept() WebSocket that was already used in a response."
+ );
+ }
+ if (this[kAccepted])
+ return;
+ this[kAccepted] = true;
+ if (__privateGet(this, _dispatchQueue) !== void 0) {
+ for (const event of __privateGet(this, _dispatchQueue))
+ this.dispatchEvent(event);
+ __privateSet(this, _dispatchQueue, void 0);
+ }
+ }
+ send(message) {
+ if (!this[kAccepted]) {
+ throw new TypeError(
+ "You must call accept() on this WebSocket before sending messages."
+ );
+ }
+ this[kSend](message);
+ }
+ [(_a = kPair, _b = kAccepted, _c = kCoupled, _d = kClosedOutgoing, _e = kClosedIncoming, kSend)](message) {
+ if (this[kClosedOutgoing]) {
+ throw new TypeError("Can't call WebSocket send() after close().");
+ }
+ const event = new MessageEvent("message", { data: message });
+ void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event);
+ }
+ close(code, reason) {
+ if (code) {
+ const validCode = code >= 1e3 && code < 5e3 && code !== 1004 && code !== 1005 && code !== 1006 && code !== 1015;
+ if (!validCode)
+ throw new TypeError("Invalid WebSocket close code.");
+ }
+ if (reason !== void 0 && code === void 0) {
+ throw new TypeError(
+ "If you specify a WebSocket close reason, you must also specify a code."
+ );
+ }
+ if (!this[kAccepted]) {
+ throw new TypeError(
+ "You must call accept() on this WebSocket before sending messages."
+ );
+ }
+ this[kClose](code, reason);
+ }
+ [kClose](code, reason) {
+ if (this[kClosedOutgoing])
+ throw new TypeError("WebSocket already closed");
+ const pair = this[kPair];
+ (0, import_assert2.default)(pair !== void 0);
+ this[kClosedOutgoing] = true;
+ pair[kClosedIncoming] = true;
+ const event = new CloseEvent("close", { code, reason });
+ void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event);
+ }
+ [kError](error) {
+ const event = new ErrorEvent("error", { error });
+ void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event);
+ }
+};
+var WebSocket = _WebSocket;
+_dispatchQueue = new WeakMap();
+_queuingDispatchToPair = new WeakSet();
+queuingDispatchToPair_fn = async function(event) {
+ const pair = this[kPair];
+ (0, import_assert2.default)(pair !== void 0);
+ if (pair[kAccepted]) {
+ pair.dispatchEvent(event);
+ } else {
+ (0, import_assert2.default)(__privateGet(pair, _dispatchQueue) !== void 0);
+ __privateGet(pair, _dispatchQueue).push(event);
+ }
+};
+// The Workers runtime prefixes these constants with `READY_STATE_`, unlike
+// those in the spec: https://websockets.spec.whatwg.org/#interface-definition
+__publicField(WebSocket, "READY_STATE_CONNECTING", 0);
+__publicField(WebSocket, "READY_STATE_OPEN", 1);
+__publicField(WebSocket, "READY_STATE_CLOSING", 2);
+__publicField(WebSocket, "READY_STATE_CLOSED", 3);
+var WebSocketPair = function() {
+ if (!(this instanceof WebSocketPair)) {
+ throw new TypeError(
+ "Failed to construct 'WebSocketPair': Please use the 'new' operator, this object constructor cannot be called as a function."
+ );
+ }
+ this[0] = new WebSocket();
+ this[1] = new WebSocket();
+ this[0][kPair] = this[1];
+ this[1][kPair] = this[0];
+};
+async function coupleWebSocket(ws, pair) {
+ if (pair[kCoupled]) {
+ throw new TypeError(
+ "Can't return WebSocket that was already used in a response."
+ );
+ }
+ if (pair[kAccepted]) {
+ throw new TypeError(
+ "Can't return WebSocket in a Response after calling accept()."
+ );
+ }
+ ws.on("message", (message, isBinary) => {
+ if (!pair[kClosedOutgoing]) {
+ pair[kSend](isBinary ? viewToBuffer(message) : message.toString());
+ }
+ });
+ ws.on("close", (code, reason) => {
+ if (!pair[kClosedOutgoing]) {
+ pair[kClose](code, reason.toString());
+ }
+ });
+ ws.on("error", (error) => {
+ pair[kError](error);
+ });
+ pair.addEventListener("message", (e) => {
+ ws.send(e.data);
+ });
+ pair.addEventListener("close", (e) => {
+ if (e.code === 1005) {
+ ws.close();
+ } else if (e.code === 1006) {
+ ws.terminate();
+ } else {
+ ws.close(e.code, e.reason);
+ }
+ });
+ if (ws.readyState === import_ws.default.CONNECTING) {
+ await (0, import_events.once)(ws, "open");
+ } else if (ws.readyState >= import_ws.default.CLOSING) {
+ throw new TypeError("Incoming WebSocket connection already closed.");
+ }
+ pair.accept();
+ pair[kCoupled] = true;
+}
+
+// packages/miniflare/src/http/fetch.ts
+var allowUnauthorizedDispatchers = /* @__PURE__ */ new WeakSet();
+function registerAllowUnauthorizedDispatcher(dispatcher) {
+ allowUnauthorizedDispatchers.add(dispatcher);
+}
+var ignored = ["transfer-encoding", "connection", "keep-alive", "expect"];
+function headersFromIncomingRequest(req) {
+ const entries = Object.entries(req.headers).filter(
+ (pair) => {
+ const [name, value] = pair;
+ return !ignored.includes(name) && value !== void 0;
+ }
+ );
+ return new import_undici4.Headers(Object.fromEntries(entries));
+}
+async function fetch2(input, init2) {
+ const requestInit = init2;
+ const request = new Request(input, requestInit);
+ if (request.method === "GET" && request.headers.get("upgrade") === "websocket") {
+ const url13 = new URL(request.url);
+ if (url13.protocol !== "http:" && url13.protocol !== "https:") {
+ throw new TypeError(
+ `Fetch API cannot load: ${url13.toString()}.
+Make sure you're using http(s):// URLs for WebSocket requests via fetch.`
+ );
+ }
+ url13.protocol = url13.protocol.replace("http", "ws");
+ const headers = {};
+ let protocols;
+ for (const [key, value] of request.headers.entries()) {
+ if (key.toLowerCase() === "sec-websocket-protocol") {
+ protocols = value.split(",").map((protocol) => protocol.trim());
+ } else {
+ headers[key] = value;
+ }
+ }
+ const rejectUnauthorized = requestInit?.dispatcher !== void 0 && allowUnauthorizedDispatchers.has(requestInit?.dispatcher) ? { rejectUnauthorized: false } : {};
+ const ws = new import_ws2.default(url13, protocols, {
+ followRedirects: request.redirect === "follow",
+ headers,
+ ...rejectUnauthorized
+ });
+ const headersPromise = new DeferredPromise();
+ ws.once("upgrade", (req) => {
+ headersPromise.resolve(headersFromIncomingRequest(req));
+ });
+ const [worker, client] = Object.values(new WebSocketPair());
+ await coupleWebSocket(ws, client);
+ return new Response(null, {
+ status: 101,
+ webSocket: worker,
+ headers: await headersPromise
+ });
+ }
+ const response = await (0, import_undici4.fetch)(request, {
+ dispatcher: requestInit?.dispatcher
+ });
+ return new Response(response.body, response);
+}
+
+// packages/miniflare/src/http/server.ts
+var import_promises10 = __toESM(require("fs/promises"));
+
+// packages/miniflare/src/plugins/cache/index.ts
+var import_promises3 = __toESM(require("fs/promises"));
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache.worker.ts
+var import_fs3 = __toESM(require("fs"));
+var import_path5 = __toESM(require("path"));
+var import_url3 = __toESM(require("url"));
+var contents3;
+function cache_worker_default() {
+ if (contents3 !== void 0)
+ return contents3;
+ const filePath = import_path5.default.join(__dirname, "workers", "cache/cache.worker.js");
+ contents3 = import_fs3.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url3.default.pathToFileURL(filePath);
+ return contents3;
+}
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry.worker.ts
+var import_fs4 = __toESM(require("fs"));
+var import_path6 = __toESM(require("path"));
+var import_url4 = __toESM(require("url"));
+var contents4;
+function cache_entry_worker_default() {
+ if (contents4 !== void 0)
+ return contents4;
+ const filePath = import_path6.default.join(__dirname, "workers", "cache/cache-entry.worker.js");
+ contents4 = import_fs4.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url4.default.pathToFileURL(filePath);
+ return contents4;
+}
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts
+var import_fs5 = __toESM(require("fs"));
+var import_path7 = __toESM(require("path"));
+var import_url5 = __toESM(require("url"));
+var contents5;
+function cache_entry_noop_worker_default() {
+ if (contents5 !== void 0)
+ return contents5;
+ const filePath = import_path7.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js");
+ contents5 = import_fs5.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url5.default.pathToFileURL(filePath);
+ return contents5;
+}
+
+// packages/miniflare/src/plugins/cache/index.ts
+var import_zod5 = require("zod");
+
+// packages/miniflare/src/plugins/shared/index.ts
+var import_crypto = __toESM(require("crypto"));
+var import_fs7 = require("fs");
+var import_promises2 = __toESM(require("fs/promises"));
+var import_path9 = __toESM(require("path"));
+var import_url8 = require("url");
+var import_zod4 = require("zod");
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/object-entry.worker.ts
+var import_fs6 = __toESM(require("fs"));
+var import_path8 = __toESM(require("path"));
+var import_url6 = __toESM(require("url"));
+var contents6;
+function object_entry_worker_default() {
+ if (contents6 !== void 0)
+ return contents6;
+ const filePath = import_path8.default.join(__dirname, "workers", "shared/object-entry.worker.js");
+ contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath);
+ return contents6;
+}
+
+// packages/miniflare/src/plugins/shared/constants.ts
+var SOCKET_ENTRY = "entry";
+var SERVICE_LOOPBACK = "loopback";
+var HEADER_CF_BLOB = "MF-CF-Blob";
+var WORKER_BINDING_SERVICE_LOOPBACK = {
+ name: CoreBindings.SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+};
+function objectEntryWorker(durableObjectNamespace, namespace) {
+ return {
+ compatibilityDate: "2023-07-24",
+ modules: [
+ { name: "object-entry.worker.js", esModule: object_entry_worker_default() }
+ ],
+ bindings: [
+ { name: SharedBindings.TEXT_NAMESPACE, text: namespace },
+ {
+ name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
+ durableObjectNamespace
+ }
+ ]
+ };
+}
+
+// packages/miniflare/src/plugins/shared/routing.ts
+var import_url7 = require("url");
+var RouterError = class extends MiniflareError {
+};
+function routeSpecificity(url13) {
+ const hostParts = url13.host.split(".");
+ let hostScore = hostParts.length;
+ if (hostParts[0] === "*")
+ hostScore -= 2;
+ const pathParts = url13.pathname.split("/");
+ let pathScore = pathParts.length;
+ if (pathParts[pathParts.length - 1] === "*")
+ pathScore -= 2;
+ return hostScore * 26 + pathScore;
+}
+function parseRoutes(allRoutes) {
+ const routes = [];
+ for (const [target, targetRoutes] of allRoutes) {
+ for (const route of targetRoutes) {
+ const hasProtocol = /^[a-z0-9+\-.]+:\/\//i.test(route);
+ let urlInput = route;
+ if (!hasProtocol)
+ urlInput = `https://${urlInput}`;
+ const url13 = new import_url7.URL(urlInput);
+ const specificity = routeSpecificity(url13);
+ const protocol = hasProtocol ? url13.protocol : void 0;
+ const internationalisedAllowHostnamePrefix = url13.hostname.startsWith("xn--*");
+ const allowHostnamePrefix = url13.hostname.startsWith("*") || internationalisedAllowHostnamePrefix;
+ const anyHostname = url13.hostname === "*";
+ if (allowHostnamePrefix && !anyHostname) {
+ let hostname = url13.hostname;
+ if (internationalisedAllowHostnamePrefix) {
+ hostname = (0, import_url7.domainToUnicode)(hostname);
+ }
+ url13.hostname = hostname.substring(1);
+ }
+ const allowPathSuffix = url13.pathname.endsWith("*");
+ if (allowPathSuffix) {
+ url13.pathname = url13.pathname.substring(0, url13.pathname.length - 1);
+ }
+ if (url13.search) {
+ throw new RouterError(
+ "ERR_QUERY_STRING",
+ `Route "${route}" for "${target}" contains a query string. This is not allowed.`
+ );
+ }
+ if (url13.toString().includes("*") && !anyHostname) {
+ throw new RouterError(
+ "ERR_INFIX_WILDCARD",
+ `Route "${route}" for "${target}" contains an infix wildcard. This is not allowed.`
+ );
+ }
+ routes.push({
+ target,
+ route,
+ specificity,
+ protocol,
+ allowHostnamePrefix,
+ hostname: anyHostname ? "" : url13.hostname,
+ path: url13.pathname,
+ allowPathSuffix
+ });
+ }
+ }
+ routes.sort((a, b) => {
+ if (a.specificity === b.specificity) {
+ return b.route.length - a.route.length;
+ } else {
+ return b.specificity - a.specificity;
+ }
+ });
+ return routes;
+}
+
+// packages/miniflare/src/plugins/shared/index.ts
+var DEFAULT_PERSIST_ROOT = ".mf";
+var PersistenceSchema = import_zod4.z.boolean().or(import_zod4.z.string()).optional();
+var kProxyNodeBinding = Symbol("kProxyNodeBinding");
+function namespaceKeys(namespaces) {
+ if (Array.isArray(namespaces)) {
+ return namespaces;
+ } else if (namespaces !== void 0) {
+ return Object.keys(namespaces);
+ } else {
+ return [];
+ }
+}
+function namespaceEntries(namespaces) {
+ if (Array.isArray(namespaces)) {
+ return namespaces.map((bindingName) => [bindingName, bindingName]);
+ } else if (namespaces !== void 0) {
+ return Object.entries(namespaces);
+ } else {
+ return [];
+ }
+}
+function maybeParseURL(url13) {
+ if (typeof url13 !== "string" || import_path9.default.isAbsolute(url13))
+ return;
+ try {
+ return new URL(url13);
+ } catch {
+ }
+}
+function getPersistPath(pluginName, tmpPath, persist) {
+ const memoryishPath = import_path9.default.join(tmpPath, pluginName);
+ if (persist === void 0 || persist === false) {
+ return memoryishPath;
+ }
+ const url13 = maybeParseURL(persist);
+ if (url13 !== void 0) {
+ if (url13.protocol === "memory:") {
+ return memoryishPath;
+ } else if (url13.protocol === "file:") {
+ return (0, import_url8.fileURLToPath)(url13);
+ }
+ throw new MiniflareCoreError(
+ "ERR_PERSIST_UNSUPPORTED",
+ `Unsupported "${url13.protocol}" persistence protocol for storage: ${url13.href}`
+ );
+ }
+ return persist === true ? import_path9.default.join(DEFAULT_PERSIST_ROOT, pluginName) : persist;
+}
+function durableObjectNamespaceIdFromName(uniqueKey, name) {
+ const key = import_crypto.default.createHash("sha256").update(uniqueKey).digest();
+ const nameHmac = import_crypto.default.createHmac("sha256", key).update(name).digest().subarray(0, 16);
+ const hmac = import_crypto.default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
+ return Buffer.concat([nameHmac, hmac]).toString("hex");
+}
+async function migrateDatabase(log, uniqueKey, persistPath, namespace) {
+ const sanitisedNamespace = sanitisePath(namespace);
+ const previousDir = import_path9.default.join(persistPath, sanitisedNamespace);
+ const previousPath = import_path9.default.join(previousDir, "db.sqlite");
+ const previousWalPath = import_path9.default.join(previousDir, "db.sqlite-wal");
+ if (!(0, import_fs7.existsSync)(previousPath))
+ return;
+ const id = durableObjectNamespaceIdFromName(uniqueKey, namespace);
+ const newDir = import_path9.default.join(persistPath, uniqueKey);
+ const newPath = import_path9.default.join(newDir, `${id}.sqlite`);
+ const newWalPath = import_path9.default.join(newDir, `${id}.sqlite-wal`);
+ if ((0, import_fs7.existsSync)(newPath)) {
+ log.debug(
+ `Not migrating ${previousPath} to ${newPath} as it already exists`
+ );
+ return;
+ }
+ log.debug(`Migrating ${previousPath} to ${newPath}...`);
+ await import_promises2.default.mkdir(newDir, { recursive: true });
+ try {
+ await import_promises2.default.copyFile(previousPath, newPath);
+ if ((0, import_fs7.existsSync)(previousWalPath)) {
+ await import_promises2.default.copyFile(previousWalPath, newWalPath);
+ }
+ await import_promises2.default.unlink(previousPath);
+ await import_promises2.default.unlink(previousWalPath);
+ } catch (e) {
+ log.warn(`Error migrating ${previousPath} to ${newPath}: ${e}`);
+ }
+}
+
+// packages/miniflare/src/plugins/cache/index.ts
+var CacheOptionsSchema = import_zod5.z.object({
+ cache: import_zod5.z.boolean().optional(),
+ cacheWarnUsage: import_zod5.z.boolean().optional()
+});
+var CacheSharedOptionsSchema = import_zod5.z.object({
+ cachePersist: PersistenceSchema
+});
+var CACHE_PLUGIN_NAME = "cache";
+var CACHE_STORAGE_SERVICE_NAME = `${CACHE_PLUGIN_NAME}:storage`;
+var CACHE_SERVICE_PREFIX = `${CACHE_PLUGIN_NAME}:cache`;
+var CACHE_OBJECT_CLASS_NAME = "CacheObject";
+var CACHE_OBJECT = {
+ serviceName: CACHE_SERVICE_PREFIX,
+ className: CACHE_OBJECT_CLASS_NAME
+};
+function getCacheServiceName(workerIndex) {
+ return `${CACHE_PLUGIN_NAME}:${workerIndex}`;
+}
+var CACHE_PLUGIN = {
+ options: CacheOptionsSchema,
+ sharedOptions: CacheSharedOptionsSchema,
+ getBindings() {
+ return [];
+ },
+ getNodeBindings() {
+ return {};
+ },
+ async getServices({ sharedOptions, options, workerIndex, tmpPath }) {
+ const cache = options.cache ?? true;
+ const cacheWarnUsage = options.cacheWarnUsage ?? false;
+ let entryWorker;
+ if (cache) {
+ entryWorker = {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ { name: "cache-entry.worker.js", esModule: cache_entry_worker_default() }
+ ],
+ bindings: [
+ {
+ name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
+ durableObjectNamespace: CACHE_OBJECT
+ },
+ {
+ name: CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE,
+ json: JSON.stringify(cacheWarnUsage)
+ }
+ ]
+ };
+ } else {
+ entryWorker = {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ {
+ name: "cache-entry-noop.worker.js",
+ esModule: cache_entry_noop_worker_default()
+ }
+ ]
+ };
+ }
+ const uniqueKey = `miniflare-${CACHE_OBJECT_CLASS_NAME}`;
+ const persist = sharedOptions.cachePersist;
+ const persistPath = getPersistPath(CACHE_PLUGIN_NAME, tmpPath, persist);
+ await import_promises3.default.mkdir(persistPath, { recursive: true });
+ const storageService = {
+ name: CACHE_STORAGE_SERVICE_NAME,
+ disk: { path: persistPath, writable: true }
+ };
+ const objectService = {
+ name: CACHE_SERVICE_PREFIX,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ {
+ name: "cache.worker.js",
+ esModule: cache_worker_default()
+ }
+ ],
+ durableObjectNamespaces: [
+ {
+ className: CACHE_OBJECT_CLASS_NAME,
+ uniqueKey
+ }
+ ],
+ // Store Durable Object SQL databases in persist path
+ durableObjectStorage: { localDisk: CACHE_STORAGE_SERVICE_NAME },
+ // Bind blob disk directory service to object
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_BLOBS,
+ service: { name: CACHE_STORAGE_SERVICE_NAME }
+ },
+ {
+ name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+ }
+ ]
+ }
+ };
+ const services = [
+ { name: getCacheServiceName(workerIndex), worker: entryWorker },
+ storageService,
+ objectService
+ ];
+ return services;
+ }
+};
+
+// packages/miniflare/src/plugins/core/index.ts
+var import_assert8 = __toESM(require("assert"));
+var import_fs11 = require("fs");
+var import_promises5 = __toESM(require("fs/promises"));
+var import_path13 = __toESM(require("path"));
+var import_tls = __toESM(require("tls"));
+var import_util3 = require("util");
+var import_undici7 = require("undici");
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/core/entry.worker.ts
+var import_fs8 = __toESM(require("fs"));
+var import_path10 = __toESM(require("path"));
+var import_url9 = __toESM(require("url"));
+var contents7;
+function entry_worker_default() {
+ if (contents7 !== void 0)
+ return contents7;
+ const filePath = import_path10.default.join(__dirname, "workers", "core/entry.worker.js");
+ contents7 = import_fs8.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath);
+ return contents7;
+}
+
+// packages/miniflare/src/plugins/core/index.ts
+var import_zod11 = require("zod");
+
+// packages/miniflare/src/runtime/index.ts
+var import_assert3 = __toESM(require("assert"));
+var import_child_process = __toESM(require("child_process"));
+var import_readline = __toESM(require("readline"));
+var import_stream = require("stream");
+var import_workerd2 = __toESM(require("workerd"));
+var import_zod6 = require("zod");
+
+// packages/miniflare/src/runtime/config/index.ts
+var import_capnp_ts = require("capnp-ts");
+
+// packages/miniflare/src/runtime/config/workerd.ts
+var import_workerd_capnp = __toESM(require_workerd_capnp());
+var kVoid = Symbol("kVoid");
+
+// packages/miniflare/src/runtime/config/index.ts
+var import_workerd_capnp2 = __toESM(require_workerd_capnp());
+function capitalize(str) {
+ return str.length > 0 ? str[0].toUpperCase() + str.substring(1) : str;
+}
+function encodeCapnpStruct(obj, struct) {
+ const anyStruct = struct;
+ for (const [key, value] of Object.entries(obj)) {
+ const capitalized = capitalize(key);
+ if (value instanceof Uint8Array) {
+ const newData = anyStruct[`init${capitalized}`](value.byteLength);
+ newData.copyBuffer(value);
+ } else if (Array.isArray(value)) {
+ const newList = anyStruct[`init${capitalized}`](value.length);
+ for (let i = 0; i < value.length; i++) {
+ if (typeof value[i] === "object") {
+ encodeCapnpStruct(value[i], newList.get(i));
+ } else {
+ newList.set(i, value[i]);
+ }
+ }
+ } else if (typeof value === "object") {
+ const newStruct = anyStruct[`init${capitalized}`]();
+ encodeCapnpStruct(value, newStruct);
+ } else if (value === kVoid) {
+ anyStruct[`set${capitalized}`]();
+ } else if (value !== void 0) {
+ anyStruct[`set${capitalized}`](value);
+ }
+ }
+}
+function serializeConfig(config) {
+ const message = new import_capnp_ts.Message();
+ const struct = message.initRoot(import_workerd_capnp2.Config);
+ encodeCapnpStruct(config, struct);
+ return Buffer.from(message.toArrayBuffer());
+}
+
+// packages/miniflare/src/runtime/index.ts
+var ControlMessageSchema = import_zod6.z.object({
+ event: import_zod6.z.literal("listen"),
+ socket: import_zod6.z.string(),
+ port: import_zod6.z.number()
+});
+async function waitForPort(socket, stream, options) {
+ if (options?.signal?.aborted)
+ return;
+ const lines = import_readline.default.createInterface(stream);
+ const abortListener = () => lines.close();
+ options?.signal?.addEventListener("abort", abortListener, { once: true });
+ try {
+ for await (const line of lines) {
+ const message = ControlMessageSchema.safeParse(JSON.parse(line));
+ if (message.success && message.data.socket === socket) {
+ return message.data.port;
+ }
+ }
+ } finally {
+ options?.signal?.removeEventListener("abort", abortListener);
+ }
+}
+function waitForExit(process2) {
+ return new Promise((resolve) => {
+ process2.once("exit", () => resolve());
+ });
+}
+function pipeOutput(runtime) {
+ const stdout = import_readline.default.createInterface(runtime.stdout);
+ const stderr = import_readline.default.createInterface(runtime.stderr);
+ stdout.on("line", (data) => console.log(data));
+ stderr.on("line", (data) => console.error(red(data)));
+}
+var Runtime = class {
+ constructor(opts) {
+ this.opts = opts;
+ this.#command = process.env.MINIFLARE_WORKERD_PATH ?? import_workerd2.default;
+ }
+ #command;
+ #process;
+ #processExitPromise;
+ get #args() {
+ const args = [
+ "serve",
+ // Required to use binary capnp config
+ "--binary",
+ // Required to use compatibility flags without a default-on date,
+ // (e.g. "streams_enable_constructors"), see https://github.com/cloudflare/workerd/pull/21
+ "--experimental",
+ `--socket-addr=${SOCKET_ENTRY}=${this.opts.entryHost}:${this.opts.entryPort}`,
+ `--external-addr=${SERVICE_LOOPBACK}=localhost:${this.opts.loopbackPort}`,
+ // Configure extra pipe for receiving control messages (e.g. when ready)
+ "--control-fd=3",
+ // Read config from stdin
+ "-"
+ ];
+ if (this.opts.inspectorPort !== void 0) {
+ args.push(`--inspector-addr=localhost:${this.opts.inspectorPort}`);
+ }
+ if (this.opts.verbose) {
+ args.push("--verbose");
+ }
+ return args;
+ }
+ async updateConfig(configBuffer, options) {
+ await this.dispose();
+ if (options?.entryPort !== void 0) {
+ this.opts.entryPort = options.entryPort;
+ }
+ const runtimeProcess = import_child_process.default.spawn(this.#command, this.#args, {
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
+ env: process.env
+ });
+ this.#process = runtimeProcess;
+ this.#processExitPromise = waitForExit(runtimeProcess);
+ pipeOutput(runtimeProcess);
+ const controlPipe = runtimeProcess.stdio[3];
+ (0, import_assert3.default)(controlPipe instanceof import_stream.Readable);
+ runtimeProcess.stdin.write(configBuffer);
+ runtimeProcess.stdin.end();
+ return waitForPort(SOCKET_ENTRY, controlPipe, options);
+ }
+ dispose() {
+ this.#process?.kill("SIGKILL");
+ return this.#processExitPromise;
+ }
+};
+
+// packages/miniflare/src/plugins/do/index.ts
+var import_promises4 = __toESM(require("fs/promises"));
+var import_zod7 = require("zod");
+var DurableObjectsOptionsSchema = import_zod7.z.object({
+ durableObjects: import_zod7.z.record(
+ import_zod7.z.union([
+ import_zod7.z.string(),
+ import_zod7.z.object({
+ className: import_zod7.z.string(),
+ scriptName: import_zod7.z.string().optional(),
+ // Allow `uniqueKey` to be customised. We use in Wrangler when setting
+ // up stub Durable Objects that proxy requests to Durable Objects in
+ // another `workerd` process, to ensure the IDs created by the stub
+ // object can be used by the real object too.
+ unsafeUniqueKey: import_zod7.z.string().optional()
+ })
+ ])
+ ).optional()
+});
+var DurableObjectsSharedOptionsSchema = import_zod7.z.object({
+ durableObjectsPersist: PersistenceSchema
+});
+function normaliseDurableObject(designator) {
+ const isObject = typeof designator === "object";
+ const className = isObject ? designator.className : designator;
+ const serviceName = isObject && designator.scriptName !== void 0 ? getUserServiceName(designator.scriptName) : void 0;
+ const unsafeUniqueKey = isObject ? designator.unsafeUniqueKey : void 0;
+ return { className, serviceName, unsafeUniqueKey };
+}
+var DURABLE_OBJECTS_PLUGIN_NAME = "do";
+var DURABLE_OBJECTS_STORAGE_SERVICE_NAME = `${DURABLE_OBJECTS_PLUGIN_NAME}:storage`;
+var DURABLE_OBJECTS_PLUGIN = {
+ options: DurableObjectsOptionsSchema,
+ sharedOptions: DurableObjectsSharedOptionsSchema,
+ getBindings(options) {
+ return Object.entries(options.durableObjects ?? {}).map(
+ ([name, klass]) => {
+ const { className, serviceName } = normaliseDurableObject(klass);
+ return {
+ name,
+ durableObjectNamespace: { className, serviceName }
+ };
+ }
+ );
+ },
+ getNodeBindings(options) {
+ const objects = Object.keys(options.durableObjects ?? {});
+ return Object.fromEntries(objects.map((name) => [name, kProxyNodeBinding]));
+ },
+ async getServices({ sharedOptions, tmpPath, durableObjectClassNames }) {
+ let hasDurableObjects = false;
+ for (const classNames of durableObjectClassNames.values()) {
+ if (classNames.size > 0) {
+ hasDurableObjects = true;
+ break;
+ }
+ }
+ if (!hasDurableObjects)
+ return;
+ const storagePath = getPersistPath(
+ DURABLE_OBJECTS_PLUGIN_NAME,
+ tmpPath,
+ sharedOptions.durableObjectsPersist
+ );
+ await import_promises4.default.mkdir(storagePath, { recursive: true });
+ return [
+ {
+ // Note this service will be de-duped by name if multiple Workers create
+ // it. Each Worker will have the same `sharedOptions` though, so this
+ // isn't a problem.
+ name: DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
+ disk: { path: storagePath, writable: true }
+ }
+ ];
+ }
+};
+
+// packages/miniflare/src/plugins/core/constants.ts
+var CORE_PLUGIN_NAME = "core";
+var SERVICE_ENTRY = `${CORE_PLUGIN_NAME}:entry`;
+var SERVICE_USER_PREFIX = `${CORE_PLUGIN_NAME}:user`;
+var SERVICE_BUILTIN_PREFIX = `${CORE_PLUGIN_NAME}:builtin`;
+var SERVICE_CUSTOM_PREFIX = `${CORE_PLUGIN_NAME}:custom`;
+function getUserServiceName(workerName = "") {
+ return `${SERVICE_USER_PREFIX}:${workerName}`;
+}
+var CUSTOM_SERVICE_KNOWN_OUTBOUND = "outbound";
+function getBuiltinServiceName(workerIndex, kind, bindingName) {
+ return `${SERVICE_BUILTIN_PREFIX}:${workerIndex}:${kind}${bindingName}`;
+}
+function getCustomServiceName(workerIndex, kind, bindingName) {
+ return `${SERVICE_CUSTOM_PREFIX}:${workerIndex}:${kind}${bindingName}`;
+}
+
+// packages/miniflare/src/plugins/core/modules.ts
+var import_assert4 = __toESM(require("assert"));
+var import_fs9 = require("fs");
+var import_module = require("module");
+var import_path11 = __toESM(require("path"));
+var import_url10 = require("url");
+var import_util = require("util");
+var import_acorn = require("acorn");
+var import_acorn_walk = require("acorn-walk");
+var import_zod8 = require("zod");
+var SUGGEST_BUNDLE = "If you're trying to import an npm package, you'll need to bundle your Worker first.";
+var SUGGEST_NODE = "If you're trying to import a Node.js built-in module, or an npm package that uses Node.js built-ins, you'll either need to:\n- Bundle your Worker, configuring your bundler to polyfill Node.js built-ins\n- Configure your bundler to load Workers-compatible builds by changing the main fields/conditions\n- Enable the `nodejs_compat` compatibility flag and use the `NodeJsCompatModule` module type\n- Find an alternative package that doesn't require Node.js built-ins";
+var builtinModulesWithPrefix = import_module.builtinModules.concat(
+ import_module.builtinModules.map((module2) => `node:${module2}`)
+);
+function buildStringScriptPath(workerIndex) {
+ return `script:${workerIndex}`;
+}
+var stringScriptRegexp = /^script:(\d+)$/;
+function maybeGetStringScriptPathIndex(scriptPath) {
+ const match = stringScriptRegexp.exec(scriptPath);
+ return match === null ? void 0 : parseInt(match[1]);
+}
+var ModuleRuleTypeSchema = import_zod8.z.enum([
+ "ESModule",
+ "CommonJS",
+ "NodeJsCompatModule",
+ "Text",
+ "Data",
+ "CompiledWasm"
+]);
+var ModuleRuleSchema = import_zod8.z.object({
+ type: ModuleRuleTypeSchema,
+ include: import_zod8.z.string().array(),
+ fallthrough: import_zod8.z.boolean().optional()
+});
+var ModuleDefinitionSchema = import_zod8.z.object({
+ type: ModuleRuleTypeSchema,
+ path: import_zod8.z.string(),
+ contents: import_zod8.z.string().or(import_zod8.z.instanceof(Uint8Array)).optional()
+});
+var SourceOptionsSchema = import_zod8.z.union([
+ import_zod8.z.object({
+ // Manually defined modules
+ // (used by Wrangler which has its own module collection code)
+ modules: import_zod8.z.array(ModuleDefinitionSchema),
+ // `modules` "name"s will be their paths relative to this value.
+ // This ensures file paths in stack traces are correct.
+ modulesRoot: import_zod8.z.string().optional()
+ }),
+ import_zod8.z.object({
+ script: import_zod8.z.string(),
+ // Optional script path for resolving modules, and stack traces file names
+ scriptPath: import_zod8.z.string().optional(),
+ // Automatically collect modules by parsing `script` if `true`, or treat as
+ // service-worker if `false`
+ modules: import_zod8.z.boolean().optional(),
+ // How to interpret automatically collected modules
+ modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(),
+ // `modules` "name"s will be their paths relative to this value.
+ // This ensures file paths in stack traces are correct.
+ modulesRoot: import_zod8.z.string().optional()
+ }),
+ import_zod8.z.object({
+ scriptPath: import_zod8.z.string(),
+ // Automatically collect modules by parsing `scriptPath` if `true`, or treat
+ // as service-worker if `false`
+ modules: import_zod8.z.boolean().optional(),
+ // How to interpret automatically collected modules
+ modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(),
+ // `modules` "name"s will be their paths relative to this value.
+ // This ensures file paths in stack traces are correct.
+ modulesRoot: import_zod8.z.string().optional()
+ })
+]);
+var DEFAULT_MODULE_RULES = [
+ { type: "ESModule", include: ["**/*.mjs"] },
+ { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] }
+];
+function compileModuleRules(rules) {
+ const compiledRules = [];
+ const finalisedTypes = /* @__PURE__ */ new Set();
+ for (const rule of [...rules ?? [], ...DEFAULT_MODULE_RULES]) {
+ if (finalisedTypes.has(rule.type))
+ continue;
+ compiledRules.push({
+ type: rule.type,
+ include: globsToRegExps(rule.include)
+ });
+ if (!rule.fallthrough)
+ finalisedTypes.add(rule.type);
+ }
+ return compiledRules;
+}
+function moduleName(modulesRoot, modulePath) {
+ const name = import_path11.default.relative(modulesRoot, modulePath);
+ return import_path11.default.sep === "\\" ? name.replaceAll("\\", "/") : name;
+}
+function withSourceURL(script, scriptPath) {
+ let scriptURL = scriptPath;
+ if (maybeGetStringScriptPathIndex(scriptPath) === void 0) {
+ scriptURL = (0, import_url10.pathToFileURL)(scriptPath);
+ }
+ const sourceURL = `
+//# sourceURL=${scriptURL}
+`;
+ return script + sourceURL;
+}
+function getResolveErrorPrefix(referencingPath) {
+ const relative = import_path11.default.relative("", referencingPath);
+ return `Unable to resolve "${relative}" dependency`;
+}
+var ModuleLocator = class {
+ constructor(modulesRoot, additionalModuleNames, rules, compatibilityFlags) {
+ this.modulesRoot = modulesRoot;
+ this.additionalModuleNames = additionalModuleNames;
+ this.#compiledRules = compileModuleRules(rules);
+ this.#nodejsCompat = compatibilityFlags?.includes("nodejs_compat") ?? false;
+ }
+ #compiledRules;
+ #nodejsCompat;
+ #visitedPaths = /* @__PURE__ */ new Set();
+ modules = [];
+ visitEntrypoint(code, modulePath) {
+ modulePath = import_path11.default.resolve(this.modulesRoot, modulePath);
+ if (this.#visitedPaths.has(modulePath))
+ return;
+ this.#visitedPaths.add(modulePath);
+ this.#visitJavaScriptModule(code, modulePath, "ESModule");
+ }
+ #visitJavaScriptModule(code, modulePath, type) {
+ const name = moduleName(this.modulesRoot, modulePath);
+ const module2 = createJavaScriptModule(code, name, modulePath, type);
+ this.modules.push(module2);
+ const isESM = type === "ESModule";
+ let root;
+ try {
+ root = (0, import_acorn.parse)(code, {
+ ecmaVersion: "latest",
+ sourceType: isESM ? "module" : "script",
+ locations: true
+ });
+ } catch (e) {
+ let loc = "";
+ if (e.loc?.line !== void 0) {
+ loc += `:${e.loc.line}`;
+ if (e.loc.column !== void 0)
+ loc += `:${e.loc.column}`;
+ }
+ throw new MiniflareCoreError(
+ "ERR_MODULE_PARSE",
+ `Unable to parse "${name}": ${e.message ?? e}
+ at ${modulePath}${loc}`
+ );
+ }
+ const visitors = {
+ ImportDeclaration: (node) => {
+ this.#visitModule(modulePath, name, type, node.source);
+ },
+ ExportNamedDeclaration: (node) => {
+ if (node.source != null) {
+ this.#visitModule(modulePath, name, type, node.source);
+ }
+ },
+ ExportAllDeclaration: (node) => {
+ this.#visitModule(modulePath, name, type, node.source);
+ },
+ ImportExpression: (node) => {
+ this.#visitModule(modulePath, name, type, node.source);
+ },
+ CallExpression: isESM ? void 0 : (node) => {
+ const argument = node.arguments[0];
+ if (node.callee.type === "Identifier" && node.callee.name === "require" && argument !== void 0) {
+ this.#visitModule(modulePath, name, type, argument);
+ }
+ }
+ };
+ (0, import_acorn_walk.simple)(root, visitors);
+ }
+ #visitModule(referencingPath, referencingName, referencingType, specExpression) {
+ if (maybeGetStringScriptPathIndex(referencingName) !== void 0) {
+ const prefix = getResolveErrorPrefix(referencingPath);
+ throw new MiniflareCoreError(
+ "ERR_MODULE_STRING_SCRIPT",
+ `${prefix}: imports are unsupported in string \`script\` without defined \`scriptPath\``
+ );
+ }
+ if (specExpression.type !== "Literal" || typeof specExpression.value !== "string") {
+ const modules = this.modules.map((mod) => {
+ const def = convertWorkerModule(mod);
+ return ` { type: "${def.type}", path: "${def.path}" }`;
+ });
+ const modulesConfig = ` new Miniflare({
+ ...,
+ modules: [
+${modules.join(",\n")},
+ ...
+ ]
+ })`;
+ const prefix = getResolveErrorPrefix(referencingPath);
+ let message = `${prefix}: dynamic module specifiers are unsupported.
+You must manually define your modules when constructing Miniflare:
+${dim(modulesConfig)}`;
+ if (specExpression.loc != null) {
+ const { line, column } = specExpression.loc.start;
+ message += `
+ at ${referencingPath}:${line}:${column}`;
+ }
+ throw new MiniflareCoreError("ERR_MODULE_DYNAMIC_SPEC", message);
+ }
+ const spec = specExpression.value;
+ const isNodeJsCompatModule = referencingType === "NodeJsCompatModule";
+ if (this.#nodejsCompat && spec.startsWith("node:") || spec.startsWith("cloudflare:") || spec.startsWith("workerd:") || isNodeJsCompatModule && builtinModulesWithPrefix.includes(spec) || this.additionalModuleNames.includes(spec)) {
+ return;
+ }
+ const identifier = import_path11.default.resolve(import_path11.default.dirname(referencingPath), spec);
+ const name = moduleName(this.modulesRoot, identifier);
+ if (this.#visitedPaths.has(identifier))
+ return;
+ this.#visitedPaths.add(identifier);
+ const rule = this.#compiledRules.find(
+ (rule2) => testRegExps(rule2.include, identifier)
+ );
+ if (rule === void 0) {
+ const prefix = getResolveErrorPrefix(referencingPath);
+ const isBuiltin = builtinModulesWithPrefix.includes(spec);
+ const suggestion = isBuiltin ? SUGGEST_NODE : SUGGEST_BUNDLE;
+ throw new MiniflareCoreError(
+ "ERR_MODULE_RULE",
+ `${prefix} "${spec}": no matching module rules.
+${suggestion}`
+ );
+ }
+ const data = (0, import_fs9.readFileSync)(identifier);
+ switch (rule.type) {
+ case "ESModule":
+ case "CommonJS":
+ case "NodeJsCompatModule":
+ const code = data.toString("utf8");
+ this.#visitJavaScriptModule(code, identifier, rule.type);
+ break;
+ case "Text":
+ this.modules.push({ name, text: data.toString("utf8") });
+ break;
+ case "Data":
+ this.modules.push({ name, data });
+ break;
+ case "CompiledWasm":
+ this.modules.push({ name, wasm: data });
+ break;
+ default:
+ const exhaustive = rule.type;
+ import_assert4.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
+ }
+ }
+};
+function createJavaScriptModule(code, name, modulePath, type) {
+ code = withSourceURL(code, modulePath);
+ if (type === "ESModule") {
+ return { name, esModule: code };
+ } else if (type === "CommonJS") {
+ return { name, commonJsModule: code };
+ } else if (type === "NodeJsCompatModule") {
+ return { name, nodeJsCompatModule: code };
+ }
+ const exhaustive = type;
+ import_assert4.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`);
+}
+var encoder = new import_util.TextEncoder();
+var decoder = new import_util.TextDecoder();
+function contentsToString(contents13) {
+ return typeof contents13 === "string" ? contents13 : decoder.decode(contents13);
+}
+function contentsToArray(contents13) {
+ return typeof contents13 === "string" ? encoder.encode(contents13) : contents13;
+}
+function convertModuleDefinition(modulesRoot, def) {
+ const name = moduleName(modulesRoot, def.path);
+ const contents13 = def.contents ?? (0, import_fs9.readFileSync)(def.path);
+ switch (def.type) {
+ case "ESModule":
+ case "CommonJS":
+ case "NodeJsCompatModule":
+ return createJavaScriptModule(
+ contentsToString(contents13),
+ name,
+ import_path11.default.resolve(modulesRoot, def.path),
+ def.type
+ );
+ case "Text":
+ return { name, text: contentsToString(contents13) };
+ case "Data":
+ return { name, data: contentsToArray(contents13) };
+ case "CompiledWasm":
+ return { name, wasm: contentsToArray(contents13) };
+ default:
+ const exhaustive = def.type;
+ import_assert4.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
+ }
+}
+function convertWorkerModule(mod) {
+ const path21 = mod.name;
+ (0, import_assert4.default)(path21 !== void 0);
+ const m = mod;
+ if ("esModule" in m)
+ return { path: path21, type: "ESModule" };
+ else if ("commonJsModule" in m)
+ return { path: path21, type: "CommonJS" };
+ else if ("nodeJsCompatModule" in m)
+ return { path: path21, type: "NodeJsCompatModule" };
+ else if ("text" in m)
+ return { path: path21, type: "Text" };
+ else if ("data" in m)
+ return { path: path21, type: "Data" };
+ else if ("wasm" in m)
+ return { path: path21, type: "CompiledWasm" };
+ (0, import_assert4.default)(!("json" in m), "Unreachable: json modules aren't generated");
+ const exhaustive = m;
+ import_assert4.default.fail(
+ `Unreachable: [${Object.keys(exhaustive).join(
+ ", "
+ )}] modules are unsupported`
+ );
+}
+
+// packages/miniflare/src/plugins/core/services.ts
+var import_zod9 = require("zod");
+var HttpOptionsHeaderSchema = import_zod9.z.object({
+ name: import_zod9.z.string(),
+ // name should be required
+ value: import_zod9.z.ostring()
+ // If omitted, the header will be removed
+});
+var HttpOptionsSchema = import_zod9.z.object({
+ style: import_zod9.z.nativeEnum(import_workerd_capnp.HttpOptions_Style).optional(),
+ forwardedProtoHeader: import_zod9.z.ostring(),
+ cfBlobHeader: import_zod9.z.ostring(),
+ injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(),
+ injectResponseHeaders: HttpOptionsHeaderSchema.array().optional()
+});
+var TlsOptionsKeypairSchema = import_zod9.z.object({
+ privateKey: import_zod9.z.ostring(),
+ certificateChain: import_zod9.z.ostring()
+});
+var TlsOptionsSchema = import_zod9.z.object({
+ keypair: TlsOptionsKeypairSchema.optional(),
+ requireClientCerts: import_zod9.z.oboolean(),
+ trustBrowserCas: import_zod9.z.oboolean(),
+ trustedCertificates: import_zod9.z.string().array().optional(),
+ minVersion: import_zod9.z.nativeEnum(import_workerd_capnp.TlsOptions_Version).optional(),
+ cipherList: import_zod9.z.ostring()
+});
+var NetworkSchema = import_zod9.z.object({
+ allow: import_zod9.z.string().array().optional(),
+ deny: import_zod9.z.string().array().optional(),
+ tlsOptions: TlsOptionsSchema.optional()
+});
+var ExternalServerSchema = import_zod9.z.intersection(
+ import_zod9.z.object({ address: import_zod9.z.string() }),
+ // address should be required
+ import_zod9.z.union([
+ import_zod9.z.object({ http: import_zod9.z.optional(HttpOptionsSchema) }),
+ import_zod9.z.object({
+ https: import_zod9.z.optional(
+ import_zod9.z.object({
+ options: HttpOptionsSchema.optional(),
+ tlsOptions: TlsOptionsSchema.optional(),
+ certificateHost: import_zod9.z.ostring()
+ })
+ )
+ })
+ ])
+);
+var DiskDirectorySchema = import_zod9.z.object({
+ path: import_zod9.z.string(),
+ // path should be required
+ writable: import_zod9.z.oboolean()
+});
+var ServiceFetchSchema = import_zod9.z.function().args(import_zod9.z.instanceof(Request)).returns(zAwaitable(import_zod9.z.instanceof(Response)));
+var ServiceDesignatorSchema = import_zod9.z.union([
+ import_zod9.z.string(),
+ import_zod9.z.object({ network: NetworkSchema }),
+ import_zod9.z.object({ external: ExternalServerSchema }),
+ import_zod9.z.object({ disk: DiskDirectorySchema }),
+ ServiceFetchSchema
+]);
+
+// packages/miniflare/src/plugins/core/errors/index.ts
+var import_fs10 = __toESM(require("fs"));
+var import_path12 = __toESM(require("path"));
+var import_url11 = require("url");
+var import_zod10 = require("zod");
+
+// packages/miniflare/src/plugins/core/errors/sourcemap.ts
+var import_assert5 = __toESM(require("assert"));
+
+// packages/miniflare/src/plugins/core/errors/callsite.ts
+function parseStack(stack) {
+ return stack.split("\n").slice(1).map(parseCallSite).filter((site) => site !== void 0);
+}
+function parseCallSite(line) {
+ const lineMatch = line.match(
+ /at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/
+ );
+ if (!lineMatch) {
+ return;
+ }
+ let object = null;
+ let method = null;
+ let functionName = null;
+ let typeName = null;
+ let methodName = null;
+ const isNative = lineMatch[5] === "native";
+ if (lineMatch[1]) {
+ functionName = lineMatch[1];
+ let methodStart = functionName.lastIndexOf(".");
+ if (functionName[methodStart - 1] == ".")
+ methodStart--;
+ if (methodStart > 0) {
+ object = functionName.substring(0, methodStart);
+ method = functionName.substring(methodStart + 1);
+ const objectEnd = object.indexOf(".Module");
+ if (objectEnd > 0) {
+ functionName = functionName.substring(objectEnd + 1);
+ object = object.substring(0, objectEnd);
+ }
+ }
+ }
+ if (method) {
+ typeName = object;
+ methodName = method;
+ }
+ if (method === "<anonymous>") {
+ methodName = null;
+ functionName = null;
+ }
+ return new CallSite({
+ typeName,
+ functionName,
+ methodName,
+ fileName: lineMatch[2] || null,
+ lineNumber: parseInt(lineMatch[3]) || null,
+ columnNumber: parseInt(lineMatch[4]) || null,
+ native: isNative
+ });
+}
+var CallSite = class {
+ constructor(opts) {
+ this.opts = opts;
+ }
+ getThis() {
+ return null;
+ }
+ getTypeName() {
+ return this.opts.typeName;
+ }
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ getFunction() {
+ return void 0;
+ }
+ getFunctionName() {
+ return this.opts.functionName;
+ }
+ getMethodName() {
+ return this.opts.methodName;
+ }
+ getFileName() {
+ return this.opts.fileName;
+ }
+ getScriptNameOrSourceURL() {
+ return this.opts.fileName;
+ }
+ getLineNumber() {
+ return this.opts.lineNumber;
+ }
+ getColumnNumber() {
+ return this.opts.columnNumber;
+ }
+ getEvalOrigin() {
+ return void 0;
+ }
+ isToplevel() {
+ return false;
+ }
+ isEval() {
+ return false;
+ }
+ isNative() {
+ return this.opts.native;
+ }
+ isConstructor() {
+ return false;
+ }
+ isAsync() {
+ return false;
+ }
+ isPromiseAll() {
+ return false;
+ }
+ isPromiseAny() {
+ return false;
+ }
+ getPromiseIndex() {
+ return null;
+ }
+};
+
+// packages/miniflare/src/plugins/core/errors/sourcemap.ts
+var sourceMapInstallBaseOptions = {
+ environment: "node",
+ // Don't add Node `uncaughtException` handler
+ handleUncaughtExceptions: false,
+ // Don't hook Node `require` function
+ hookRequire: false,
+ // Make sure we're using fresh copies of files (i.e. between `setOptions()`)
+ emptyCacheBetweenOperations: true,
+ // Always remove existing retrievers when calling `install()`, we should be
+ // specifying them each time we want to source map
+ overrideRetrieveFile: true,
+ overrideRetrieveSourceMap: true
+};
+var sourceMapper;
+function getSourceMapper() {
+ if (sourceMapper !== void 0)
+ return sourceMapper;
+ const originalSupport = require.cache["source-map-support"];
+ delete require.cache["source-map-support"];
+ const support = require("source-map-support");
+ require.cache["source-map-support"] = originalSupport;
+ const originalPrepareStackTrace = Error.prepareStackTrace;
+ support.install(sourceMapInstallBaseOptions);
+ const prepareStackTrace = Error.prepareStackTrace;
+ (0, import_assert5.default)(prepareStackTrace !== void 0);
+ Error.prepareStackTrace = originalPrepareStackTrace;
+ sourceMapper = (retrieveSourceMap, error) => {
+ support.install({
+ ...sourceMapInstallBaseOptions,
+ retrieveFile(file) {
+ import_assert5.default.fail(`Unexpected retrieveFile(${JSON.stringify(file)}) call`);
+ },
+ retrieveSourceMap
+ });
+ const callSites = parseStack(error.stack ?? "");
+ return prepareStackTrace(error, callSites);
+ };
+ return sourceMapper;
+}
+
+// packages/miniflare/src/plugins/core/errors/index.ts
+function maybeGetDiskFile(filePath) {
+ try {
+ const contents13 = import_fs10.default.readFileSync(filePath, "utf8");
+ return { path: filePath, contents: contents13 };
+ } catch (e) {
+ if (e.code !== "ENOENT")
+ throw e;
+ }
+}
+function maybeGetFile(workerSrcOpts, fileSpecifier) {
+ const maybeUrl = maybeParseURL(fileSpecifier);
+ if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") {
+ const filePath = (0, import_url11.fileURLToPath)(maybeUrl);
+ for (const srcOpts of workerSrcOpts) {
+ if (Array.isArray(srcOpts.modules)) {
+ const modulesRoot = srcOpts.modulesRoot ?? "";
+ for (const module2 of srcOpts.modules) {
+ if (module2.contents !== void 0 && import_path12.default.resolve(modulesRoot, module2.path) === filePath) {
+ const contents13 = contentsToString(module2.contents);
+ return { path: filePath, contents: contents13 };
+ }
+ }
+ } else if ("script" in srcOpts && "scriptPath" in srcOpts && srcOpts.script !== void 0 && srcOpts.scriptPath !== void 0) {
+ const modulesRoot = srcOpts.modules && srcOpts.modulesRoot || "";
+ if (import_path12.default.resolve(modulesRoot, srcOpts.scriptPath) === filePath) {
+ return { path: filePath, contents: srcOpts.script };
+ }
+ }
+ }
+ return maybeGetDiskFile(filePath);
+ }
+ const workerIndex = maybeGetStringScriptPathIndex(fileSpecifier);
+ if (workerIndex !== void 0) {
+ const srcOpts = workerSrcOpts[workerIndex];
+ if ("script" in srcOpts && srcOpts.script !== void 0) {
+ return { contents: srcOpts.script };
+ }
+ }
+}
+function getSourceMappedStack(workerSrcOpts, error) {
+ function retrieveSourceMap(fileSpecifier) {
+ const sourceFile = maybeGetFile(workerSrcOpts, fileSpecifier);
+ if (sourceFile?.path === void 0)
+ return null;
+ const sourceMapRegexp = /# sourceMappingURL=(.+)/g;
+ const matches = [...sourceFile.contents.matchAll(sourceMapRegexp)];
+ if (matches.length === 0)
+ return null;
+ const sourceMapMatch = matches[matches.length - 1];
+ const root = import_path12.default.dirname(sourceFile.path);
+ const sourceMapPath = import_path12.default.resolve(root, sourceMapMatch[1]);
+ const sourceMapFile = maybeGetDiskFile(sourceMapPath);
+ if (sourceMapFile === void 0)
+ return null;
+ return { map: sourceMapFile.contents, url: sourceMapFile.path };
+ }
+ return getSourceMapper()(retrieveSourceMap, error);
+}
+var JsonErrorSchema = import_zod10.z.lazy(
+ () => import_zod10.z.object({
+ message: import_zod10.z.string().optional(),
+ name: import_zod10.z.string().optional(),
+ stack: import_zod10.z.string().optional(),
+ cause: JsonErrorSchema.optional()
+ })
+);
+var ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS = [
+ EvalError,
+ RangeError,
+ ReferenceError,
+ SyntaxError,
+ TypeError,
+ URIError
+];
+function reviveError(workerSrcOpts, jsonError) {
+ let cause;
+ if (jsonError.cause !== void 0) {
+ cause = reviveError(workerSrcOpts, jsonError.cause);
+ }
+ let ctor = Error;
+ if (jsonError.name !== void 0 && jsonError.name in globalThis) {
+ const maybeCtor = globalThis[jsonError.name];
+ if (ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS.includes(maybeCtor)) {
+ ctor = maybeCtor;
+ }
+ }
+ const error = new ctor(jsonError.message, { cause });
+ if (jsonError.name !== void 0)
+ error.name = jsonError.name;
+ error.stack = jsonError.stack;
+ error.stack = getSourceMappedStack(workerSrcOpts, error);
+ return error;
+}
+async function handlePrettyErrorRequest(log, workerSrcOpts, request) {
+ const caught = JsonErrorSchema.parse(await request.json());
+ const error = reviveError(workerSrcOpts, caught);
+ log.error(error);
+ const accept = request.headers.get("Accept")?.toLowerCase() ?? "";
+ const userAgent = request.headers.get("User-Agent")?.toLowerCase() ?? "";
+ const acceptsPrettyError = !userAgent.includes("curl/") && (accept.includes("text/html") || accept.includes("*/*") || accept.includes("text/*"));
+ if (!acceptsPrettyError) {
+ return new Response(error.stack, { status: 500 });
+ }
+ const Youch = require("youch");
+ const youch = new Youch(error.cause ?? error, {
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers)
+ });
+ youch.addLink(() => {
+ return [
+ '<a href="https://developers.cloudflare.com/workers/" target="_blank" style="text-decoration:none">\u{1F4DA} Workers Docs</a>',
+ '<a href="https://discord.gg/cloudflaredev" target="_blank" style="text-decoration:none">\u{1F4AC} Workers Discord</a>'
+ ].join("");
+ });
+ return new Response(await youch.toHTML(), {
+ status: 500,
+ headers: { "Content-Type": "text/html;charset=utf-8" }
+ });
+}
+
+// packages/miniflare/src/plugins/core/proxy/client.ts
+var import_assert7 = __toESM(require("assert"));
+var import_web4 = require("stream/web");
+var import_util2 = __toESM(require("util"));
+var import_undici6 = require("undici");
+
+// packages/miniflare/src/plugins/core/proxy/fetch-sync.ts
+var import_assert6 = __toESM(require("assert"));
+var import_web2 = require("stream/web");
+var import_worker_threads = require("worker_threads");
+var DECODER = new TextDecoder();
+var WORKER_SCRIPT = (
+ /* javascript */
+ `
+const { createRequire } = require("module");
+const { workerData } = require("worker_threads");
+
+// Not using parentPort here so we can call receiveMessageOnPort() in host
+const { notifyHandle, port, filename } = workerData;
+
+// When running Miniflare from Jest, regular 'require("undici")' will fail here
+// with "Error: Cannot find module 'undici'". Instead we need to create a
+// 'require' using the '__filename' of the host... :(
+const actualRequire = createRequire(filename);
+const { Client, fetch } = actualRequire("undici");
+
+let clientUrl;
+let client;
+
+port.addEventListener("message", async (event) => {
+ const { id, method, url, headers, body } = event.data;
+ if (clientUrl !== url) {
+ clientUrl = url;
+ client = new Client(url, {
+ connect: { rejectUnauthorized: false },
+ });
+ }
+ headers["${CoreHeaders.OP_SYNC}"] = "true";
+ try {
+ // body cannot be a ReadableStream, so no need to specify duplex
+ const response = await fetch(url, { method, headers, body, dispatcher: client });
+ const responseBody = response.headers.get("${CoreHeaders.OP_RESULT_TYPE}") === "ReadableStream"
+ ? response.body
+ : await response.arrayBuffer();
+ const transferList = responseBody === null ? undefined : [responseBody];
+ port.postMessage(
+ {
+ id,
+ response: {
+ status: response.status,
+ headers: Object.fromEntries(response.headers),
+ body: responseBody,
+ }
+ },
+ transferList
+ );
+ } catch (error) {
+ try {
+ port.postMessage({ id, error });
+ } catch {
+ // If error failed to serialise, post simplified version
+ port.postMessage({ id, error: new Error(String(error)) });
+ }
+ }
+ Atomics.store(notifyHandle, /* index */ 0, /* value */ 1);
+ Atomics.notify(notifyHandle, /* index */ 0);
+});
+`
+);
+var SynchronousFetcher = class {
+ #channel;
+ #notifyHandle;
+ #worker;
+ #nextId = 0;
+ constructor() {
+ this.#channel = new import_worker_threads.MessageChannel();
+ this.#notifyHandle = new Int32Array(new SharedArrayBuffer(4));
+ }
+ #ensureWorker() {
+ if (this.#worker !== void 0)
+ return;
+ this.#worker = new import_worker_threads.Worker(WORKER_SCRIPT, {
+ eval: true,
+ workerData: {
+ notifyHandle: this.#notifyHandle,
+ port: this.#channel.port2,
+ filename: __filename
+ },
+ transferList: [this.#channel.port2]
+ });
+ }
+ fetch(url13, init2) {
+ this.#ensureWorker();
+ Atomics.store(
+ this.#notifyHandle,
+ /* index */
+ 0,
+ /* value */
+ 0
+ );
+ const id = this.#nextId++;
+ this.#channel.port1.postMessage({
+ id,
+ method: init2.method,
+ url: url13.toString(),
+ headers: init2.headers,
+ body: init2.body
+ });
+ Atomics.wait(
+ this.#notifyHandle,
+ /* index */
+ 0,
+ /* value */
+ 0
+ );
+ const message = (0, import_worker_threads.receiveMessageOnPort)(
+ this.#channel.port1
+ )?.message;
+ (0, import_assert6.default)(message?.id === id);
+ if ("response" in message) {
+ const { status, headers: rawHeaders, body } = message.response;
+ const headers = new import_undici8.Headers(rawHeaders);
+ const stack = headers.get(CoreHeaders.ERROR_STACK);
+ if (status === 500 && stack !== null && body !== null) {
+ (0, import_assert6.default)(!(body instanceof import_web2.ReadableStream));
+ const caught = JsonErrorSchema.parse(JSON.parse(DECODER.decode(body)));
+ throw reviveError([], caught);
+ }
+ return { status, headers, body };
+ } else {
+ throw message.error;
+ }
+ }
+ async dispose() {
+ await this.#worker?.terminate();
+ }
+};
+
+// packages/miniflare/src/plugins/core/proxy/types.ts
+var import_buffer = require("buffer");
+var import_consumers = require("stream/consumers");
+var import_web3 = require("stream/web");
+var import_undici5 = require("undici");
+var NODE_PLATFORM_IMPL = {
+ // Node's implementation of these classes don't quite match Workers',
+ // but they're close enough for us
+ Blob: import_buffer.Blob,
+ File: import_undici5.File,
+ Headers: import_undici5.Headers,
+ Request,
+ Response,
+ isReadableStream(value) {
+ return value instanceof import_web3.ReadableStream;
+ },
+ bufferReadableStream(stream) {
+ return (0, import_consumers.arrayBuffer)(stream);
+ },
+ unbufferReadableStream(buffer) {
+ return new import_buffer.Blob([new Uint8Array(buffer)]).stream();
+ }
+};
+
+// packages/miniflare/src/plugins/core/proxy/client.ts
+var kAddress = Symbol("kAddress");
+var kName = Symbol("kName");
+function isNativeTarget(value) {
+ return typeof value === "object" && value !== null && kAddress in value;
+}
+var TARGET_GLOBAL = {
+ [kAddress]: ProxyAddresses.GLOBAL,
+ [kName]: "global"
+};
+var TARGET_ENV = {
+ [kAddress]: ProxyAddresses.ENV,
+ [kName]: "env"
+};
+var reducers = {
+ ...structuredSerializableReducers,
+ ...createHTTPReducers(NODE_PLATFORM_IMPL),
+ Native(value) {
+ if (isNativeTarget(value))
+ return [value[kAddress], value[kName]];
+ }
+};
+var revivers = {
+ ...structuredSerializableRevivers,
+ ...createHTTPRevivers(NODE_PLATFORM_IMPL)
+ // `Native` reviver depends on `ProxyStubHandler` methods
+};
+var ProxyClient = class {
+ #bridge;
+ constructor(runtimeEntryURL, dispatchFetch) {
+ this.#bridge = new ProxyClientBridge(runtimeEntryURL, dispatchFetch);
+ }
+ // Lazily initialise proxies as required
+ #globalProxy;
+ #envProxy;
+ get global() {
+ return this.#globalProxy ??= this.#bridge.getProxy(TARGET_GLOBAL);
+ }
+ get env() {
+ return this.#envProxy ??= this.#bridge.getProxy(TARGET_ENV);
+ }
+ poisonProxies(runtimeEntryURL) {
+ this.#bridge.poisonProxies(runtimeEntryURL);
+ this.#globalProxy = void 0;
+ this.#envProxy = void 0;
+ }
+ dispose() {
+ return this.#bridge.dispose();
+ }
+};
+var ProxyClientBridge = class {
+ constructor(url13, dispatchFetch) {
+ this.url = url13;
+ this.dispatchFetch = dispatchFetch;
+ this.#finalizationRegistry = new FinalizationRegistry(this.#finalizeProxy);
+ }
+ // Each proxy stub is initialised with the version stored here. Whenever
+ // `poisonProxies()` is called, this version is incremented. Before the
+ // proxy makes any request to `workerd`, it checks the version number here
+ // matches its own internal version, and throws if not.
+ #version = 0;
+ // Whenever the `ProxyServer` returns a native target, it adds a strong
+ // reference to the "heap" in the singleton object. This prevents the object
+ // being garbage collected. To solve this, we register the native target
+ // proxies on the client in a `FinalizationRegistry`. When the proxies get
+ // garbage collected, we let the `ProxyServer` know it can release the strong
+ // "heap" reference, as we'll never be able to access it again. Importantly,
+ // we need to unregister all proxies from the registry when we poison them,
+ // as the references will be invalid, and a new object with the same address
+ // may be added to the "heap".
+ #finalizationRegistry;
+ sync = new SynchronousFetcher();
+ get version() {
+ return this.#version;
+ }
+ #finalizeProxy = async (held) => {
+ if (held.version !== this.#version)
+ return;
+ try {
+ await this.dispatchFetch(this.url, {
+ method: "DELETE",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.FREE,
+ [CoreHeaders.OP_TARGET]: held.address.toString()
+ }
+ });
+ } catch {
+ }
+ };
+ getProxy(target) {
+ const handler = new ProxyStubHandler(this, target);
+ const proxy = new Proxy(
+ { [import_util2.default.inspect.custom]: handler.inspect },
+ handler
+ );
+ const held = {
+ address: target[kAddress],
+ version: this.#version
+ };
+ this.#finalizationRegistry.register(proxy, held, this);
+ return proxy;
+ }
+ poisonProxies(url13) {
+ this.#version++;
+ if (url13 !== void 0)
+ this.url = url13;
+ this.#finalizationRegistry.unregister(this);
+ }
+ dispose() {
+ this.poisonProxies();
+ return this.sync.dispose();
+ }
+};
+var ProxyStubHandler = class {
+ constructor(bridge, target) {
+ this.bridge = bridge;
+ this.target = target;
+ this.#version = bridge.version;
+ this.#stringifiedTarget = stringify(this.target, reducers);
+ }
+ #version;
+ #stringifiedTarget;
+ #known = /* @__PURE__ */ new Map();
+ revivers = {
+ ...revivers,
+ Native: (value) => {
+ (0, import_assert7.default)(Array.isArray(value));
+ const [address, name] = value;
+ (0, import_assert7.default)(typeof address === "number");
+ (0, import_assert7.default)(typeof name === "string");
+ const target = { [kAddress]: address, [kName]: name };
+ if (name === "Promise") {
+ const resPromise = this.bridge.dispatchFetch(this.bridge.url, {
+ method: "POST",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.GET,
+ // GET without key just gets target
+ [CoreHeaders.OP_TARGET]: stringify(target, reducers)
+ }
+ });
+ return this.#parseAsyncResponse(resPromise);
+ } else {
+ return this.bridge.getProxy(target);
+ }
+ }
+ };
+ get #poisoned() {
+ return this.#version !== this.bridge.version;
+ }
+ #assertSafe() {
+ if (this.#poisoned) {
+ throw new Error(
+ "Attempted to use poisoned stub. Stubs to runtime objects must be re-created after calling `Miniflare#setOptions()` or `Miniflare#dispose()`."
+ );
+ }
+ }
+ inspect = (depth, options) => {
+ const details = { name: this.target[kName], poisoned: this.#poisoned };
+ return `ProxyStub ${import_util2.default.inspect(details, options)}`;
+ };
+ #maybeThrow(res, result, caller) {
+ if (res.status === 500) {
+ if (typeof result === "object" && result !== null) {
+ Error.captureStackTrace(result, caller);
+ }
+ throw result;
+ } else {
+ (0, import_assert7.default)(res.status === 200);
+ return result;
+ }
+ }
+ async #parseAsyncResponse(resPromise) {
+ const res = await resPromise;
+ const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE);
+ if (typeHeader === "Promise, ReadableStream")
+ return res.body;
+ (0, import_assert7.default)(typeHeader === "Promise");
+ let stringifiedResult;
+ let unbufferedStream;
+ const stringifiedSizeHeader = res.headers.get(
+ CoreHeaders.OP_STRINGIFIED_SIZE
+ );
+ if (stringifiedSizeHeader === null) {
+ stringifiedResult = await res.text();
+ } else {
+ const stringifiedSize = parseInt(stringifiedSizeHeader);
+ (0, import_assert7.default)(!Number.isNaN(stringifiedSize));
+ (0, import_assert7.default)(res.body !== null);
+ const [buffer, rest] = await readPrefix(res.body, stringifiedSize);
+ stringifiedResult = buffer.toString();
+ unbufferedStream = rest.pipeThrough(new import_web4.TransformStream());
+ }
+ const result = parseWithReadableStreams(
+ NODE_PLATFORM_IMPL,
+ { value: stringifiedResult, unbufferedStream },
+ this.revivers
+ );
+ return this.#maybeThrow(res, result, this.#parseAsyncResponse);
+ }
+ #parseSyncResponse(syncRes, caller) {
+ (0, import_assert7.default)(syncRes.body !== null);
+ (0, import_assert7.default)(syncRes.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE) === null);
+ if (syncRes.body instanceof import_web4.ReadableStream)
+ return syncRes.body;
+ const stringifiedResult = DECODER.decode(syncRes.body);
+ const result = parseWithReadableStreams(
+ NODE_PLATFORM_IMPL,
+ { value: stringifiedResult },
+ this.revivers
+ );
+ return this.#maybeThrow(syncRes, result, caller);
+ }
+ get(_target, key, _receiver) {
+ this.#assertSafe();
+ if (key === kAddress)
+ return this.target[kAddress];
+ if (key === kName)
+ return this.target[kName];
+ if (typeof key === "symbol" || key === "then")
+ return void 0;
+ const maybeKnown = this.#known.get(key);
+ if (maybeKnown !== void 0)
+ return maybeKnown;
+ const syncRes = this.bridge.sync.fetch(this.bridge.url, {
+ method: "POST",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.GET,
+ [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
+ [CoreHeaders.OP_KEY]: key
+ }
+ });
+ let result;
+ if (syncRes.headers.get(CoreHeaders.OP_RESULT_TYPE) === "Function") {
+ result = this.#createFunction(key);
+ } else {
+ result = this.#parseSyncResponse(syncRes, this.get);
+ }
+ if (
+ // Optimisation: if this property is a function, we assume constant
+ // prototypes of proxied objects, so it's never going to change
+ typeof result === "function" || // Optimisation: if this property is a reference, we assume it's never
+ // going to change. This allows us to reuse the known cache of nested
+ // objects on multiple access (e.g. reusing `env["...<bucket>"]` proxy if
+ // `getR2Bucket(<bucket>)` is called on the same bucket multiple times).
+ isNativeTarget(result) || // Once a `ReadableStream` sent across proxy, we won't be able to read it
+ // again in the server, so reuse the same stream for future accesses
+ // (e.g. accessing `R2ObjectBody#body` multiple times)
+ result instanceof import_web4.ReadableStream
+ ) {
+ this.#known.set(key, result);
+ }
+ return result;
+ }
+ has(target, key) {
+ return this.get(target, key, void 0) !== void 0;
+ }
+ #createFunction(key) {
+ let knownAsync = false;
+ const func = {
+ [key]: (...args) => {
+ const result = this.#call(key, knownAsync, args, func);
+ if (!knownAsync && result instanceof Promise)
+ knownAsync = true;
+ return result;
+ }
+ }[key];
+ return func;
+ }
+ #call(key, knownAsync, args, caller) {
+ this.#assertSafe();
+ const targetName = this.target[kName];
+ if (isFetcherFetch(targetName, key))
+ return this.#fetcherFetchCall(args);
+ const stringified = stringifyWithStreams(
+ NODE_PLATFORM_IMPL,
+ args,
+ reducers,
+ /* allowUnbufferedStream */
+ true
+ );
+ if (knownAsync || // We assume every call with `ReadableStream`/`Blob` arguments is async.
+ // Note that you can't consume `ReadableStream`/`Blob` synchronously: if
+ // you tried a similar trick to `SynchronousFetcher`, blocking the main
+ // thread with `Atomics.wait()` would prevent chunks being read. This
+ // assumption doesn't hold for `Blob`s and `FormData#{append,set}()`, but
+ // we should never expose proxies for those APIs to users.
+ stringified instanceof Promise || // (instanceof Promise if buffered `ReadableStream`/`Blob`s)
+ stringified.unbufferedStream !== void 0) {
+ return this.#asyncCall(key, stringified);
+ } else {
+ const result = this.#syncCall(key, stringified.value, caller);
+ if (isR2ObjectWriteHttpMetadata(targetName, key)) {
+ const arg = args[0];
+ (0, import_assert7.default)(arg instanceof import_undici6.Headers);
+ (0, import_assert7.default)(result instanceof import_undici6.Headers);
+ for (const [key2, value] of result)
+ arg.set(key2, value);
+ return;
+ }
+ return result;
+ }
+ }
+ #syncCall(key, stringifiedValue, caller) {
+ const argsSize = Buffer.byteLength(stringifiedValue).toString();
+ const syncRes = this.bridge.sync.fetch(this.bridge.url, {
+ method: "POST",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.CALL,
+ [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
+ [CoreHeaders.OP_KEY]: key,
+ [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize,
+ "Content-Length": argsSize
+ },
+ body: stringifiedValue
+ });
+ return this.#parseSyncResponse(syncRes, caller);
+ }
+ async #asyncCall(key, stringifiedAwaitable) {
+ const stringified = await stringifiedAwaitable;
+ let resPromise;
+ if (stringified.unbufferedStream === void 0) {
+ const argsSize = Buffer.byteLength(stringified.value).toString();
+ resPromise = this.bridge.dispatchFetch(this.bridge.url, {
+ method: "POST",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.CALL,
+ [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
+ [CoreHeaders.OP_KEY]: key,
+ [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize,
+ "Content-Length": argsSize
+ },
+ body: stringified.value
+ });
+ } else {
+ const encodedArgs = Buffer.from(stringified.value);
+ const argsSize = encodedArgs.byteLength.toString();
+ const body = prefixStream(encodedArgs, stringified.unbufferedStream);
+ resPromise = this.bridge.dispatchFetch(this.bridge.url, {
+ method: "POST",
+ headers: {
+ [CoreHeaders.OP]: ProxyOps.CALL,
+ [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
+ [CoreHeaders.OP_KEY]: key,
+ [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize
+ },
+ duplex: "half",
+ body
+ });
+ }
+ return this.#parseAsyncResponse(resPromise);
+ }
+ #fetcherFetchCall(args) {
+ const request = new Request(...args);
+ request.headers.set(CoreHeaders.OP, ProxyOps.CALL);
+ request.headers.set(CoreHeaders.OP_TARGET, this.#stringifiedTarget);
+ request.headers.set(CoreHeaders.OP_KEY, "fetch");
+ return this.bridge.dispatchFetch(request);
+ }
+};
+
+// packages/miniflare/src/plugins/core/index.ts
+var trustedCertificates = process.platform === "win32" ? Array.from(import_tls.default.rootCertificates) : [];
+if (process.env.NODE_EXTRA_CA_CERTS !== void 0) {
+ try {
+ const extra = (0, import_fs11.readFileSync)(process.env.NODE_EXTRA_CA_CERTS, "utf8");
+ const pemBegin = "-----BEGIN";
+ for (const cert of extra.split(pemBegin)) {
+ if (cert.trim() !== "")
+ trustedCertificates.push(pemBegin + cert);
+ }
+ } catch {
+ }
+}
+var encoder2 = new import_util3.TextEncoder();
+var numericCompare = new Intl.Collator(void 0, { numeric: true }).compare;
+function createFetchMock() {
+ return new import_undici7.MockAgent();
+}
+var CoreOptionsSchemaInput = import_zod11.z.intersection(
+ SourceOptionsSchema,
+ import_zod11.z.object({
+ name: import_zod11.z.string().optional(),
+ compatibilityDate: import_zod11.z.string().optional(),
+ compatibilityFlags: import_zod11.z.string().array().optional(),
+ routes: import_zod11.z.string().array().optional(),
+ bindings: import_zod11.z.record(JsonSchema).optional(),
+ wasmBindings: import_zod11.z.record(import_zod11.z.string()).optional(),
+ textBlobBindings: import_zod11.z.record(import_zod11.z.string()).optional(),
+ dataBlobBindings: import_zod11.z.record(import_zod11.z.string()).optional(),
+ serviceBindings: import_zod11.z.record(ServiceDesignatorSchema).optional(),
+ outboundService: ServiceDesignatorSchema.optional(),
+ fetchMock: import_zod11.z.instanceof(import_undici7.MockAgent).optional(),
+ unsafeEphemeralDurableObjects: import_zod11.z.boolean().optional()
+ })
+);
+var CoreOptionsSchema = CoreOptionsSchemaInput.transform((value) => {
+ const fetchMock = value.fetchMock;
+ if (fetchMock !== void 0) {
+ if (value.outboundService !== void 0) {
+ throw new MiniflareCoreError(
+ "ERR_MULTIPLE_OUTBOUNDS",
+ "Only one of `outboundService` or `fetchMock` may be specified per worker"
+ );
+ }
+ value.outboundService = (req) => fetch2(req, { dispatcher: fetchMock });
+ }
+ return value;
+});
+var CoreSharedOptionsSchema = import_zod11.z.object({
+ host: import_zod11.z.string().optional(),
+ port: import_zod11.z.number().optional(),
+ https: import_zod11.z.boolean().optional(),
+ httpsKey: import_zod11.z.string().optional(),
+ httpsKeyPath: import_zod11.z.string().optional(),
+ httpsCert: import_zod11.z.string().optional(),
+ httpsCertPath: import_zod11.z.string().optional(),
+ inspectorPort: import_zod11.z.number().optional(),
+ verbose: import_zod11.z.boolean().optional(),
+ log: import_zod11.z.instanceof(Log).optional(),
+ upstream: import_zod11.z.string().optional(),
+ // TODO: add back validation of cf object
+ cf: import_zod11.z.union([import_zod11.z.boolean(), import_zod11.z.string(), import_zod11.z.record(import_zod11.z.any())]).optional(),
+ liveReload: import_zod11.z.boolean().optional()
+});
+var CORE_PLUGIN_NAME2 = "core";
+var LIVE_RELOAD_SCRIPT_TEMPLATE = (port) => `<script defer type="application/javascript">
+(function () {
+ // Miniflare Live Reload
+ var url = new URL("/cdn-cgi/mf/reload", location.origin);
+ url.protocol = url.protocol.replace("http", "ws");
+ url.port = ${port};
+ function reload() { location.reload(); }
+ function connect(reconnected) {
+ var ws = new WebSocket(url);
+ if (reconnected) ws.onopen = reload;
+ ws.onclose = function(e) {
+ e.code === 1012 ? reload() : e.code === 1000 || e.code === 1001 || setTimeout(connect, 1000, true);
+ }
+ }
+ connect();
+})();
+</script>`;
+var SCRIPT_CUSTOM_SERVICE = `addEventListener("fetch", (event) => {
+ const request = new Request(event.request);
+ request.headers.set("${CoreHeaders.CUSTOM_SERVICE}", ${CoreBindings.TEXT_CUSTOM_SERVICE});
+ request.headers.set("${CoreHeaders.ORIGINAL_URL}", request.url);
+ event.respondWith(${CoreBindings.SERVICE_LOOPBACK}.fetch(request));
+})`;
+function getCustomServiceDesignator(workerIndex, kind, name, service) {
+ let serviceName;
+ if (typeof service === "function") {
+ serviceName = getCustomServiceName(workerIndex, kind, name);
+ } else if (typeof service === "object") {
+ serviceName = getBuiltinServiceName(workerIndex, kind, name);
+ } else {
+ serviceName = getUserServiceName(service);
+ }
+ return { name: serviceName };
+}
+function maybeGetCustomServiceService(workerIndex, kind, name, service) {
+ if (typeof service === "function") {
+ return {
+ name: getCustomServiceName(workerIndex, kind, name),
+ worker: {
+ serviceWorkerScript: SCRIPT_CUSTOM_SERVICE,
+ compatibilityDate: "2022-09-01",
+ bindings: [
+ {
+ name: CoreBindings.TEXT_CUSTOM_SERVICE,
+ text: `${workerIndex}/${kind}${name}`
+ },
+ WORKER_BINDING_SERVICE_LOOPBACK
+ ]
+ }
+ };
+ } else if (typeof service === "object") {
+ return {
+ name: getBuiltinServiceName(workerIndex, kind, name),
+ ...service
+ };
+ }
+}
+var FALLBACK_COMPATIBILITY_DATE = "2000-01-01";
+function getCurrentCompatibilityDate() {
+ const now = new Date().toISOString();
+ return now.substring(0, now.indexOf("T"));
+}
+function validateCompatibilityDate(log, compatibilityDate) {
+ if (numericCompare(compatibilityDate, getCurrentCompatibilityDate()) > 0) {
+ throw new MiniflareCoreError(
+ "ERR_FUTURE_COMPATIBILITY_DATE",
+ `Compatibility date "${compatibilityDate}" is in the future and unsupported`
+ );
+ } else if (numericCompare(compatibilityDate, import_workerd2.compatibilityDate) > 0) {
+ log.warn(
+ [
+ "The latest compatibility date supported by the installed Cloudflare Workers Runtime is ",
+ bold(`"${import_workerd2.compatibilityDate}"`),
+ ",\nbut you've requested ",
+ bold(`"${compatibilityDate}"`),
+ ". Falling back to ",
+ bold(`"${import_workerd2.compatibilityDate}"`),
+ "..."
+ ].join("")
+ );
+ return import_workerd2.compatibilityDate;
+ }
+ return compatibilityDate;
+}
+var CORE_PLUGIN = {
+ options: CoreOptionsSchema,
+ sharedOptions: CoreSharedOptionsSchema,
+ getBindings(options, workerIndex) {
+ const bindings = [];
+ if (options.bindings !== void 0) {
+ bindings.push(
+ ...Object.entries(options.bindings).map(([name, value]) => ({
+ name,
+ json: JSON.stringify(value)
+ }))
+ );
+ }
+ if (options.wasmBindings !== void 0) {
+ bindings.push(
+ ...Object.entries(options.wasmBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21).then((wasmModule) => ({ name, wasmModule }))
+ )
+ );
+ }
+ if (options.textBlobBindings !== void 0) {
+ bindings.push(
+ ...Object.entries(options.textBlobBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21, "utf8").then((text) => ({ name, text }))
+ )
+ );
+ }
+ if (options.dataBlobBindings !== void 0) {
+ bindings.push(
+ ...Object.entries(options.dataBlobBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21).then((data) => ({ name, data }))
+ )
+ );
+ }
+ if (options.serviceBindings !== void 0) {
+ bindings.push(
+ ...Object.entries(options.serviceBindings).map(([name, service]) => {
+ return {
+ name,
+ service: getCustomServiceDesignator(
+ workerIndex,
+ "#" /* UNKNOWN */,
+ name,
+ service
+ )
+ };
+ })
+ );
+ }
+ return Promise.all(bindings);
+ },
+ async getNodeBindings(options) {
+ const bindingEntries = [];
+ if (options.bindings !== void 0) {
+ bindingEntries.push(
+ ...Object.entries(options.bindings).map(([name, value]) => [
+ name,
+ JSON.parse(JSON.stringify(value))
+ ])
+ );
+ }
+ if (options.wasmBindings !== void 0) {
+ bindingEntries.push(
+ ...Object.entries(options.wasmBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21).then((buffer) => [name, new WebAssembly.Module(buffer)])
+ )
+ );
+ }
+ if (options.textBlobBindings !== void 0) {
+ bindingEntries.push(
+ ...Object.entries(options.textBlobBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21, "utf8").then((text) => [name, text])
+ )
+ );
+ }
+ if (options.dataBlobBindings !== void 0) {
+ bindingEntries.push(
+ ...Object.entries(options.dataBlobBindings).map(
+ ([name, path21]) => import_promises5.default.readFile(path21).then((buffer) => [name, viewToBuffer(buffer)])
+ )
+ );
+ }
+ if (options.serviceBindings !== void 0) {
+ bindingEntries.push(
+ ...Object.keys(options.serviceBindings).map((name) => [
+ name,
+ kProxyNodeBinding
+ ])
+ );
+ }
+ return Object.fromEntries(await Promise.all(bindingEntries));
+ },
+ async getServices({
+ log,
+ options,
+ workerBindings,
+ workerIndex,
+ durableObjectClassNames,
+ additionalModules
+ }) {
+ const additionalModuleNames = additionalModules.map(({ name: name2 }) => name2);
+ const workerScript = getWorkerScript(
+ options,
+ workerIndex,
+ additionalModuleNames
+ );
+ if ("modules" in workerScript) {
+ const subDirs = new Set(
+ workerScript.modules.map(({ name: name2 }) => import_path13.default.posix.dirname(name2))
+ );
+ subDirs.delete(".");
+ for (const module2 of additionalModules) {
+ workerScript.modules.push(module2);
+ for (const subDir of subDirs) {
+ const relativePath = import_path13.default.posix.relative(subDir, module2.name);
+ const relativePathString = JSON.stringify(relativePath);
+ workerScript.modules.push({
+ name: import_path13.default.posix.join(subDir, module2.name),
+ // TODO(someday): if we ever have additional modules without
+ // default exports, this may be a problem. For now, our only
+ // additional module is `__STATIC_CONTENT_MANIFEST` so it's fine.
+ // If needed, we could look for instances of `export default` or
+ // `as default` in the module's code as a heuristic.
+ esModule: `export * from ${relativePathString}; export { default } from ${relativePathString};`
+ });
+ }
+ }
+ }
+ const name = getUserServiceName(options.name);
+ const classNames = durableObjectClassNames.get(name);
+ const classNamesEntries = Array.from(classNames ?? []);
+ const compatibilityDate = validateCompatibilityDate(
+ log,
+ options.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE
+ );
+ const services = [
+ {
+ name,
+ worker: {
+ ...workerScript,
+ compatibilityDate,
+ compatibilityFlags: options.compatibilityFlags,
+ bindings: workerBindings,
+ durableObjectNamespaces: classNamesEntries.map(
+ ([className, unsafeUniqueKey]) => {
+ return {
+ className,
+ // This `uniqueKey` will (among other things) be used as part of the
+ // path when persisting to the file-system. `-` is invalid in
+ // JavaScript class names, but safe on filesystems (incl. Windows).
+ uniqueKey: unsafeUniqueKey ?? `${options.name ?? ""}-${className}`
+ };
+ }
+ ),
+ durableObjectStorage: classNamesEntries.length === 0 ? void 0 : options.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME },
+ globalOutbound: options.outboundService === void 0 ? void 0 : getCustomServiceDesignator(
+ workerIndex,
+ "$" /* KNOWN */,
+ CUSTOM_SERVICE_KNOWN_OUTBOUND,
+ options.outboundService
+ ),
+ cacheApiOutbound: { name: getCacheServiceName(workerIndex) }
+ }
+ }
+ ];
+ if (options.serviceBindings !== void 0) {
+ for (const [name2, service] of Object.entries(options.serviceBindings)) {
+ const maybeService = maybeGetCustomServiceService(
+ workerIndex,
+ "#" /* UNKNOWN */,
+ name2,
+ service
+ );
+ if (maybeService !== void 0)
+ services.push(maybeService);
+ }
+ }
+ if (options.outboundService !== void 0) {
+ const maybeService = maybeGetCustomServiceService(
+ workerIndex,
+ "$" /* KNOWN */,
+ CUSTOM_SERVICE_KNOWN_OUTBOUND,
+ options.outboundService
+ );
+ if (maybeService !== void 0)
+ services.push(maybeService);
+ }
+ return services;
+ }
+};
+function getGlobalServices({
+ sharedOptions,
+ allWorkerRoutes,
+ fallbackWorkerName,
+ loopbackPort,
+ log,
+ proxyBindings
+}) {
+ const workerNames = [...allWorkerRoutes.keys()];
+ const routes = parseRoutes(allWorkerRoutes);
+ const serviceEntryBindings = [
+ WORKER_BINDING_SERVICE_LOOPBACK,
+ // For converting stack-traces to pretty-error pages
+ { name: CoreBindings.JSON_ROUTES, json: JSON.stringify(routes) },
+ { name: CoreBindings.JSON_CF_BLOB, json: JSON.stringify(sharedOptions.cf) },
+ { name: CoreBindings.JSON_LOG_LEVEL, json: JSON.stringify(log.level) },
+ {
+ name: CoreBindings.SERVICE_USER_FALLBACK,
+ service: { name: getUserServiceName(fallbackWorkerName) }
+ },
+ ...workerNames.map((name) => ({
+ name: CoreBindings.SERVICE_USER_ROUTE_PREFIX + name,
+ service: { name: getUserServiceName(name) }
+ })),
+ {
+ name: CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
+ durableObjectNamespace: { className: "ProxyServer" }
+ },
+ // Add `proxyBindings` here, they'll be added to the `ProxyServer` `env`.
+ // TODO(someday): consider making the proxy server a separate worker
+ ...proxyBindings
+ ];
+ if (sharedOptions.upstream !== void 0) {
+ serviceEntryBindings.push({
+ name: CoreBindings.TEXT_UPSTREAM_URL,
+ text: sharedOptions.upstream
+ });
+ }
+ if (sharedOptions.liveReload) {
+ const liveReloadScript = LIVE_RELOAD_SCRIPT_TEMPLATE(loopbackPort);
+ serviceEntryBindings.push({
+ name: CoreBindings.DATA_LIVE_RELOAD_SCRIPT,
+ data: encoder2.encode(liveReloadScript)
+ });
+ }
+ return [
+ {
+ name: SERVICE_LOOPBACK,
+ external: { http: { cfBlobHeader: HEADER_CF_BLOB } }
+ },
+ {
+ name: SERVICE_ENTRY,
+ worker: {
+ modules: [{ name: "entry.worker.js", esModule: entry_worker_default() }],
+ compatibilityDate: "2023-04-04",
+ compatibilityFlags: ["nodejs_compat", "service_binding_extra_handlers"],
+ bindings: serviceEntryBindings,
+ durableObjectNamespaces: [
+ {
+ className: "ProxyServer",
+ uniqueKey: `${SERVICE_ENTRY}-ProxyServer`
+ }
+ ],
+ // `ProxyServer` doesn't make use of Durable Object storage
+ durableObjectStorage: { inMemory: kVoid },
+ // Always use the entrypoints cache implementation for proxying. This
+ // means if the entrypoint disables caching, proxied cache operations
+ // will be no-ops. Note we always require at least one worker to be set.
+ cacheApiOutbound: { name: "cache:0" }
+ }
+ },
+ {
+ name: "internet",
+ network: {
+ // Allow access to private/public addresses:
+ // https://github.com/cloudflare/miniflare/issues/412
+ allow: ["public", "private"],
+ deny: [],
+ tlsOptions: {
+ trustBrowserCas: true,
+ trustedCertificates
+ }
+ }
+ }
+ ];
+}
+function getWorkerScript(options, workerIndex, additionalModuleNames) {
+ const modulesRoot = ("modulesRoot" in options ? options.modulesRoot : void 0) ?? "";
+ if (Array.isArray(options.modules)) {
+ return {
+ modules: options.modules.map(
+ (module2) => convertModuleDefinition(modulesRoot, module2)
+ )
+ };
+ }
+ let code;
+ if ("script" in options && options.script !== void 0) {
+ code = options.script;
+ } else if ("scriptPath" in options && options.scriptPath !== void 0) {
+ code = (0, import_fs11.readFileSync)(options.scriptPath, "utf8");
+ } else {
+ import_assert8.default.fail("Unreachable: Workers must have code");
+ }
+ const scriptPath = options.scriptPath ?? buildStringScriptPath(workerIndex);
+ if (options.modules) {
+ const locator = new ModuleLocator(
+ modulesRoot,
+ additionalModuleNames,
+ options.modulesRules,
+ options.compatibilityFlags
+ );
+ locator.visitEntrypoint(code, scriptPath);
+ return { modules: locator.modules };
+ } else {
+ code = withSourceURL(code, scriptPath);
+ return { serviceWorkerScript: code };
+ }
+}
+
+// packages/miniflare/src/plugins/d1/index.ts
+var import_promises6 = __toESM(require("fs/promises"));
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/d1/database.worker.ts
+var import_fs12 = __toESM(require("fs"));
+var import_path14 = __toESM(require("path"));
+var import_url12 = __toESM(require("url"));
+var contents8;
+function database_worker_default() {
+ if (contents8 !== void 0)
+ return contents8;
+ const filePath = import_path14.default.join(__dirname, "workers", "d1/database.worker.js");
+ contents8 = import_fs12.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url12.default.pathToFileURL(filePath);
+ return contents8;
+}
+
+// packages/miniflare/src/plugins/d1/index.ts
+var import_zod12 = require("zod");
+var D1OptionsSchema = import_zod12.z.object({
+ d1Databases: import_zod12.z.union([import_zod12.z.record(import_zod12.z.string()), import_zod12.z.string().array()]).optional()
+});
+var D1SharedOptionsSchema = import_zod12.z.object({
+ d1Persist: PersistenceSchema
+});
+var D1_PLUGIN_NAME = "d1";
+var D1_STORAGE_SERVICE_NAME = `${D1_PLUGIN_NAME}:storage`;
+var D1_DATABASE_SERVICE_PREFIX = `${D1_PLUGIN_NAME}:db`;
+var D1_DATABASE_OBJECT_CLASS_NAME = "D1DatabaseObject";
+var D1_DATABASE_OBJECT = {
+ serviceName: D1_DATABASE_SERVICE_PREFIX,
+ className: D1_DATABASE_OBJECT_CLASS_NAME
+};
+var D1_PLUGIN = {
+ options: D1OptionsSchema,
+ sharedOptions: D1SharedOptionsSchema,
+ getBindings(options) {
+ const databases = namespaceEntries(options.d1Databases);
+ return databases.map(([name, id]) => {
+ const binding = name.startsWith("__D1_BETA__") ? (
+ // Used before Wrangler 3.3
+ {
+ service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` }
+ }
+ ) : (
+ // Used after Wrangler 3.3
+ {
+ wrapped: {
+ moduleName: "cloudflare-internal:d1-api",
+ innerBindings: [
+ {
+ name: "fetcher",
+ service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` }
+ }
+ ]
+ }
+ }
+ );
+ return { name, ...binding };
+ });
+ },
+ getNodeBindings(options) {
+ const databases = namespaceKeys(options.d1Databases);
+ return Object.fromEntries(
+ databases.map((name) => [name, kProxyNodeBinding])
+ );
+ },
+ async getServices({ options, sharedOptions, tmpPath, log }) {
+ const persist = sharedOptions.d1Persist;
+ const databases = namespaceEntries(options.d1Databases);
+ const services = databases.map(([_, id]) => ({
+ name: `${D1_DATABASE_SERVICE_PREFIX}:${id}`,
+ worker: objectEntryWorker(D1_DATABASE_OBJECT, id)
+ }));
+ if (databases.length > 0) {
+ const uniqueKey = `miniflare-${D1_DATABASE_OBJECT_CLASS_NAME}`;
+ const persistPath = getPersistPath(D1_PLUGIN_NAME, tmpPath, persist);
+ await import_promises6.default.mkdir(persistPath, { recursive: true });
+ const storageService = {
+ name: D1_STORAGE_SERVICE_NAME,
+ disk: { path: persistPath, writable: true }
+ };
+ const objectService = {
+ name: D1_DATABASE_SERVICE_PREFIX,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ {
+ name: "database.worker.js",
+ esModule: database_worker_default()
+ }
+ ],
+ durableObjectNamespaces: [
+ {
+ className: D1_DATABASE_OBJECT_CLASS_NAME,
+ uniqueKey
+ }
+ ],
+ // Store Durable Object SQL databases in persist path
+ durableObjectStorage: { localDisk: D1_STORAGE_SERVICE_NAME },
+ // Bind blob disk directory service to object
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_BLOBS,
+ service: { name: D1_STORAGE_SERVICE_NAME }
+ },
+ {
+ name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+ }
+ ]
+ }
+ };
+ services.push(storageService, objectService);
+ for (const database of databases) {
+ await migrateDatabase(log, uniqueKey, persistPath, database[1]);
+ }
+ }
+ return services;
+ }
+};
+
+// packages/miniflare/src/plugins/kv/index.ts
+var import_promises8 = __toESM(require("fs/promises"));
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/namespace.worker.ts
+var import_fs13 = __toESM(require("fs"));
+var import_path15 = __toESM(require("path"));
+var import_url13 = __toESM(require("url"));
+var contents9;
+function namespace_worker_default() {
+ if (contents9 !== void 0)
+ return contents9;
+ const filePath = import_path15.default.join(__dirname, "workers", "kv/namespace.worker.js");
+ contents9 = import_fs13.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url13.default.pathToFileURL(filePath);
+ return contents9;
+}
+
+// packages/miniflare/src/plugins/kv/index.ts
+var import_zod13 = require("zod");
+
+// packages/miniflare/src/plugins/kv/constants.ts
+var KV_PLUGIN_NAME = "kv";
+
+// packages/miniflare/src/plugins/kv/sites.ts
+var import_assert9 = __toESM(require("assert"));
+var import_promises7 = __toESM(require("fs/promises"));
+var import_path17 = __toESM(require("path"));
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/sites.worker.ts
+var import_fs14 = __toESM(require("fs"));
+var import_path16 = __toESM(require("path"));
+var import_url14 = __toESM(require("url"));
+var contents10;
+function sites_worker_default() {
+ if (contents10 !== void 0)
+ return contents10;
+ const filePath = import_path16.default.join(__dirname, "workers", "kv/sites.worker.js");
+ contents10 = import_fs14.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url14.default.pathToFileURL(filePath);
+ return contents10;
+}
+
+// packages/miniflare/src/plugins/kv/sites.ts
+async function* listKeysInDirectoryInner(rootPath, currentPath) {
+ const fileEntries = await import_promises7.default.readdir(currentPath, { withFileTypes: true });
+ for (const fileEntry of fileEntries) {
+ const filePath = import_path17.default.posix.join(currentPath, fileEntry.name);
+ if (fileEntry.isDirectory()) {
+ yield* listKeysInDirectoryInner(rootPath, filePath);
+ } else {
+ yield filePath.substring(rootPath.length + 1);
+ }
+ }
+}
+function listKeysInDirectory(rootPath) {
+ rootPath = import_path17.default.resolve(rootPath);
+ return listKeysInDirectoryInner(rootPath, rootPath);
+}
+var sitesRegExpsCache = /* @__PURE__ */ new WeakMap();
+var SERVICE_NAMESPACE_SITE = `${KV_PLUGIN_NAME}:site`;
+async function buildStaticContentManifest(sitePath, siteRegExps) {
+ const staticContentManifest = {};
+ for await (const key of listKeysInDirectory(sitePath)) {
+ if (testSiteRegExps(siteRegExps, key)) {
+ staticContentManifest[key] = encodeSitesKey(key);
+ }
+ }
+ return staticContentManifest;
+}
+async function getSitesBindings(options) {
+ const siteRegExps = {
+ include: options.siteInclude && globsToRegExps(options.siteInclude),
+ exclude: options.siteExclude && globsToRegExps(options.siteExclude)
+ };
+ sitesRegExpsCache.set(options, siteRegExps);
+ const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
+ options.sitePath,
+ siteRegExps
+ );
+ return [
+ {
+ name: SiteBindings.KV_NAMESPACE_SITE,
+ kvNamespace: { name: SERVICE_NAMESPACE_SITE }
+ },
+ {
+ name: SiteBindings.JSON_SITE_MANIFEST,
+ json: JSON.stringify(__STATIC_CONTENT_MANIFEST)
+ }
+ ];
+}
+async function getSitesNodeBindings(options) {
+ const siteRegExps = sitesRegExpsCache.get(options);
+ (0, import_assert9.default)(siteRegExps !== void 0);
+ const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
+ options.sitePath,
+ siteRegExps
+ );
+ return {
+ [SiteBindings.KV_NAMESPACE_SITE]: kProxyNodeBinding,
+ [SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST
+ };
+}
+function maybeGetSitesManifestModule(bindings) {
+ for (const binding of bindings) {
+ if (binding.name === SiteBindings.JSON_SITE_MANIFEST) {
+ (0, import_assert9.default)("json" in binding && binding.json !== void 0);
+ return { name: SiteBindings.JSON_SITE_MANIFEST, text: binding.json };
+ }
+ }
+}
+function getSitesServices(options) {
+ const siteRegExps = sitesRegExpsCache.get(options);
+ (0, import_assert9.default)(siteRegExps !== void 0);
+ const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps);
+ const persist = import_path17.default.resolve(options.sitePath);
+ const storageServiceName = `${SERVICE_NAMESPACE_SITE}:storage`;
+ const storageService = {
+ name: storageServiceName,
+ disk: { path: persist, writable: true }
+ };
+ const namespaceService = {
+ name: SERVICE_NAMESPACE_SITE,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat"],
+ modules: [
+ {
+ name: "site.worker.js",
+ esModule: sites_worker_default()
+ }
+ ],
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_BLOBS,
+ service: { name: storageServiceName }
+ },
+ {
+ name: SiteBindings.JSON_SITE_FILTER,
+ json: JSON.stringify(serialisedSiteRegExps)
+ }
+ ]
+ }
+ };
+ return [storageService, namespaceService];
+}
+
+// packages/miniflare/src/plugins/kv/index.ts
+var KVOptionsSchema = import_zod13.z.object({
+ kvNamespaces: import_zod13.z.union([import_zod13.z.record(import_zod13.z.string()), import_zod13.z.string().array()]).optional(),
+ // Workers Sites
+ sitePath: import_zod13.z.string().optional(),
+ siteInclude: import_zod13.z.string().array().optional(),
+ siteExclude: import_zod13.z.string().array().optional()
+});
+var KVSharedOptionsSchema = import_zod13.z.object({
+ kvPersist: PersistenceSchema
+});
+var SERVICE_NAMESPACE_PREFIX = `${KV_PLUGIN_NAME}:ns`;
+var KV_STORAGE_SERVICE_NAME = `${KV_PLUGIN_NAME}:storage`;
+var KV_NAMESPACE_OBJECT_CLASS_NAME = "KVNamespaceObject";
+var KV_NAMESPACE_OBJECT = {
+ serviceName: SERVICE_NAMESPACE_PREFIX,
+ className: KV_NAMESPACE_OBJECT_CLASS_NAME
+};
+function isWorkersSitesEnabled(options) {
+ return options.sitePath !== void 0;
+}
+var KV_PLUGIN = {
+ options: KVOptionsSchema,
+ sharedOptions: KVSharedOptionsSchema,
+ async getBindings(options) {
+ const namespaces = namespaceEntries(options.kvNamespaces);
+ const bindings = namespaces.map(([name, id]) => ({
+ name,
+ kvNamespace: { name: `${SERVICE_NAMESPACE_PREFIX}:${id}` }
+ }));
+ if (isWorkersSitesEnabled(options)) {
+ bindings.push(...await getSitesBindings(options));
+ }
+ return bindings;
+ },
+ async getNodeBindings(options) {
+ const namespaces = namespaceKeys(options.kvNamespaces);
+ const bindings = Object.fromEntries(
+ namespaces.map((name) => [name, kProxyNodeBinding])
+ );
+ if (isWorkersSitesEnabled(options)) {
+ Object.assign(bindings, await getSitesNodeBindings(options));
+ }
+ return bindings;
+ },
+ async getServices({ options, sharedOptions, tmpPath, log }) {
+ const persist = sharedOptions.kvPersist;
+ const namespaces = namespaceEntries(options.kvNamespaces);
+ const services = namespaces.map(([_, id]) => ({
+ name: `${SERVICE_NAMESPACE_PREFIX}:${id}`,
+ worker: objectEntryWorker(KV_NAMESPACE_OBJECT, id)
+ }));
+ if (services.length > 0) {
+ const uniqueKey = `miniflare-${KV_NAMESPACE_OBJECT_CLASS_NAME}`;
+ const persistPath = getPersistPath(KV_PLUGIN_NAME, tmpPath, persist);
+ await import_promises8.default.mkdir(persistPath, { recursive: true });
+ const storageService = {
+ name: KV_STORAGE_SERVICE_NAME,
+ disk: { path: persistPath, writable: true }
+ };
+ const objectService = {
+ name: SERVICE_NAMESPACE_PREFIX,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ {
+ name: "namespace.worker.js",
+ esModule: namespace_worker_default()
+ }
+ ],
+ durableObjectNamespaces: [
+ { className: KV_NAMESPACE_OBJECT_CLASS_NAME, uniqueKey }
+ ],
+ // Store Durable Object SQL databases in persist path
+ durableObjectStorage: { localDisk: KV_STORAGE_SERVICE_NAME },
+ // Bind blob disk directory service to object
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_BLOBS,
+ service: { name: KV_STORAGE_SERVICE_NAME }
+ },
+ {
+ name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+ }
+ ]
+ }
+ };
+ services.push(storageService, objectService);
+ for (const namespace of namespaces) {
+ await migrateDatabase(log, uniqueKey, persistPath, namespace[1]);
+ }
+ }
+ if (isWorkersSitesEnabled(options)) {
+ services.push(...getSitesServices(options));
+ }
+ return services;
+ }
+};
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/queues/broker.worker.ts
+var import_fs15 = __toESM(require("fs"));
+var import_path18 = __toESM(require("path"));
+var import_url15 = __toESM(require("url"));
+var contents11;
+function broker_worker_default() {
+ if (contents11 !== void 0)
+ return contents11;
+ const filePath = import_path18.default.join(__dirname, "workers", "queues/broker.worker.js");
+ contents11 = import_fs15.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url15.default.pathToFileURL(filePath);
+ return contents11;
+}
+
+// packages/miniflare/src/plugins/queues/index.ts
+var import_zod14 = require("zod");
+
+// packages/miniflare/src/plugins/queues/errors.ts
+var QueuesError = class extends MiniflareError {
+};
+
+// packages/miniflare/src/plugins/queues/index.ts
+var QueuesOptionsSchema = import_zod14.z.object({
+ queueProducers: import_zod14.z.union([import_zod14.z.record(import_zod14.z.string()), import_zod14.z.string().array()]).optional(),
+ queueConsumers: import_zod14.z.union([import_zod14.z.record(QueueConsumerOptionsSchema), import_zod14.z.string().array()]).optional()
+});
+var QUEUES_PLUGIN_NAME = "queues";
+var SERVICE_QUEUE_PREFIX = `${QUEUES_PLUGIN_NAME}:queue`;
+var QUEUE_BROKER_OBJECT_CLASS_NAME = "QueueBrokerObject";
+var QUEUE_BROKER_OBJECT = {
+ serviceName: SERVICE_QUEUE_PREFIX,
+ className: QUEUE_BROKER_OBJECT_CLASS_NAME
+};
+var QUEUES_PLUGIN = {
+ options: QueuesOptionsSchema,
+ getBindings(options) {
+ const queues = namespaceEntries(options.queueProducers);
+ return queues.map(([name, id]) => ({
+ name,
+ queue: { name: `${SERVICE_QUEUE_PREFIX}:${id}` }
+ }));
+ },
+ getNodeBindings(options) {
+ const queues = namespaceKeys(options.queueProducers);
+ return Object.fromEntries(queues.map((name) => [name, kProxyNodeBinding]));
+ },
+ async getServices({
+ options,
+ workerNames,
+ queueConsumers: allQueueConsumers
+ }) {
+ const queues = namespaceEntries(options.queueProducers);
+ if (queues.length === 0)
+ return [];
+ const services = queues.map(([_, id]) => ({
+ name: `${SERVICE_QUEUE_PREFIX}:${id}`,
+ worker: objectEntryWorker(QUEUE_BROKER_OBJECT, id)
+ }));
+ const uniqueKey = `miniflare-${QUEUE_BROKER_OBJECT_CLASS_NAME}`;
+ const objectService = {
+ name: SERVICE_QUEUE_PREFIX,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: [
+ "nodejs_compat",
+ "experimental",
+ "service_binding_extra_handlers"
+ ],
+ modules: [
+ { name: "broker.worker.js", esModule: broker_worker_default() }
+ ],
+ durableObjectNamespaces: [
+ { className: QUEUE_BROKER_OBJECT_CLASS_NAME, uniqueKey }
+ ],
+ // Miniflare's Queue broker is in-memory only at the moment
+ durableObjectStorage: { inMemory: kVoid },
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+ },
+ {
+ name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
+ durableObjectNamespace: {
+ className: QUEUE_BROKER_OBJECT_CLASS_NAME
+ }
+ },
+ {
+ name: QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS,
+ json: JSON.stringify(Object.fromEntries(allQueueConsumers))
+ },
+ ...workerNames.map((name) => ({
+ name: QueueBindings.SERVICE_WORKER_PREFIX + name,
+ service: { name: getUserServiceName(name) }
+ }))
+ ]
+ }
+ };
+ services.push(objectService);
+ return services;
+ }
+};
+
+// packages/miniflare/src/plugins/r2/index.ts
+var import_promises9 = __toESM(require("fs/promises"));
+
+// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/r2/bucket.worker.ts
+var import_fs16 = __toESM(require("fs"));
+var import_path19 = __toESM(require("path"));
+var import_url16 = __toESM(require("url"));
+var contents12;
+function bucket_worker_default() {
+ if (contents12 !== void 0)
+ return contents12;
+ const filePath = import_path19.default.join(__dirname, "workers", "r2/bucket.worker.js");
+ contents12 = import_fs16.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url16.default.pathToFileURL(filePath);
+ return contents12;
+}
+
+// packages/miniflare/src/plugins/r2/index.ts
+var import_zod15 = require("zod");
+var R2OptionsSchema = import_zod15.z.object({
+ r2Buckets: import_zod15.z.union([import_zod15.z.record(import_zod15.z.string()), import_zod15.z.string().array()]).optional()
+});
+var R2SharedOptionsSchema = import_zod15.z.object({
+ r2Persist: PersistenceSchema
+});
+var R2_PLUGIN_NAME = "r2";
+var R2_STORAGE_SERVICE_NAME = `${R2_PLUGIN_NAME}:storage`;
+var R2_BUCKET_SERVICE_PREFIX = `${R2_PLUGIN_NAME}:bucket`;
+var R2_BUCKET_OBJECT_CLASS_NAME = "R2BucketObject";
+var R2_BUCKET_OBJECT = {
+ serviceName: R2_BUCKET_SERVICE_PREFIX,
+ className: R2_BUCKET_OBJECT_CLASS_NAME
+};
+var R2_PLUGIN = {
+ options: R2OptionsSchema,
+ sharedOptions: R2SharedOptionsSchema,
+ getBindings(options) {
+ const buckets = namespaceEntries(options.r2Buckets);
+ return buckets.map(([name, id]) => ({
+ name,
+ r2Bucket: { name: `${R2_BUCKET_SERVICE_PREFIX}:${id}` }
+ }));
+ },
+ getNodeBindings(options) {
+ const buckets = namespaceKeys(options.r2Buckets);
+ return Object.fromEntries(buckets.map((name) => [name, kProxyNodeBinding]));
+ },
+ async getServices({ options, sharedOptions, tmpPath, log }) {
+ const persist = sharedOptions.r2Persist;
+ const buckets = namespaceEntries(options.r2Buckets);
+ const services = buckets.map(([_, id]) => ({
+ name: `${R2_BUCKET_SERVICE_PREFIX}:${id}`,
+ worker: objectEntryWorker(R2_BUCKET_OBJECT, id)
+ }));
+ if (buckets.length > 0) {
+ const uniqueKey = `miniflare-${R2_BUCKET_OBJECT_CLASS_NAME}`;
+ const persistPath = getPersistPath(R2_PLUGIN_NAME, tmpPath, persist);
+ await import_promises9.default.mkdir(persistPath, { recursive: true });
+ const storageService = {
+ name: R2_STORAGE_SERVICE_NAME,
+ disk: { path: persistPath, writable: true }
+ };
+ const objectService = {
+ name: R2_BUCKET_SERVICE_PREFIX,
+ worker: {
+ compatibilityDate: "2023-07-24",
+ compatibilityFlags: ["nodejs_compat", "experimental"],
+ modules: [
+ {
+ name: "bucket.worker.js",
+ esModule: bucket_worker_default()
+ }
+ ],
+ durableObjectNamespaces: [
+ {
+ className: R2_BUCKET_OBJECT_CLASS_NAME,
+ uniqueKey
+ }
+ ],
+ // Store Durable Object SQL databases in persist path
+ durableObjectStorage: { localDisk: R2_STORAGE_SERVICE_NAME },
+ // Bind blob disk directory service to object
+ bindings: [
+ {
+ name: SharedBindings.MAYBE_SERVICE_BLOBS,
+ service: { name: R2_STORAGE_SERVICE_NAME }
+ },
+ {
+ name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
+ service: { name: SERVICE_LOOPBACK }
+ }
+ ]
+ }
+ };
+ services.push(storageService, objectService);
+ for (const bucket of buckets) {
+ await migrateDatabase(log, uniqueKey, persistPath, bucket[1]);
+ }
+ }
+ return services;
+ }
+};
+
+// packages/miniflare/src/plugins/index.ts
+var PLUGINS = {
+ [CORE_PLUGIN_NAME2]: CORE_PLUGIN,
+ [CACHE_PLUGIN_NAME]: CACHE_PLUGIN,
+ [D1_PLUGIN_NAME]: D1_PLUGIN,
+ [DURABLE_OBJECTS_PLUGIN_NAME]: DURABLE_OBJECTS_PLUGIN,
+ [KV_PLUGIN_NAME]: KV_PLUGIN,
+ [QUEUES_PLUGIN_NAME]: QUEUES_PLUGIN,
+ [R2_PLUGIN_NAME]: R2_PLUGIN
+};
+var PLUGIN_ENTRIES = Object.entries(PLUGINS);
+
+// packages/miniflare/src/http/cert.ts
+var KEY = `
+-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEIC+umAaVUbEfPqGA9M7b5zAP7tN2eLT1bu8U8gpbaKbsoAoGCCqGSM49
+AwEHoUQDQgAEtrIEgzogjrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtC
+mCWw+vbGTBwIr/9X1S4UL1/f3zDICC7YSA==
+-----END EC PRIVATE KEY-----
+`;
+var CERT = `
+-----BEGIN CERTIFICATE-----
+MIICcDCCAhegAwIBAgIUE97EcbEWw3YZMN/ucGBSzJ/5qA4wCgYIKoZIzj0EAwIw
+VTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYDVQQHDAZBdXN0aW4x
+EzARBgNVBAoMCkNsb3VkZmxhcmUxEDAOBgNVBAsMB1dvcmtlcnMwIBcNMjMwNjIy
+MTg1ODQ3WhgPMjEyMzA1MjkxODU4NDdaMFUxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI
+DAVUZXhhczEPMA0GA1UEBwwGQXVzdGluMRMwEQYDVQQKDApDbG91ZGZsYXJlMRAw
+DgYDVQQLDAdXb3JrZXJzMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtrIEgzog
+jrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtCmCWw+vbGTBwIr/9X1S4U
+L1/f3zDICC7YSKOBwjCBvzAdBgNVHQ4EFgQUSXahTksi00c6KhUECHIY4FLW7Sow
+HwYDVR0jBBgwFoAUSXahTksi00c6KhUECHIY4FLW7SowDwYDVR0TAQH/BAUwAwEB
+/zAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUw
+CwYDVR0PBAQDAgL0MDEGA1UdJQQqMCgGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYB
+BQUHAwMGCCsGAQUFBwMIMAoGCCqGSM49BAMCA0cAMEQCIE2qnXbKTHQ8wtwI+9XR
+h4ivDyz7w7iGxn3+ccmj/CQqAiApdX/Iz/jGRzi04xFlE4GoPVG/zaMi64ckmIpE
+ez/dHA==
+-----END CERTIFICATE-----
+`;
+
+// packages/miniflare/src/http/server.ts
+async function configureEntrySocket(coreOpts) {
+ const httpOptions = {
+ // Even though we inject a `cf` object in the entry worker, allow it to
+ // be customised via `dispatchFetch`
+ cfBlobHeader: HEADER_CF_BLOB
+ };
+ let privateKey = void 0;
+ let certificateChain = void 0;
+ if ((coreOpts.httpsKey || coreOpts.httpsKeyPath) && (coreOpts.httpsCert || coreOpts.httpsCertPath)) {
+ privateKey = await valueOrFile(coreOpts.httpsKey, coreOpts.httpsKeyPath);
+ certificateChain = await valueOrFile(
+ coreOpts.httpsCert,
+ coreOpts.httpsCertPath
+ );
+ } else if (coreOpts.https) {
+ privateKey = KEY;
+ certificateChain = CERT;
+ }
+ let options;
+ if (privateKey && certificateChain) {
+ options = {
+ https: {
+ options: httpOptions,
+ tlsOptions: {
+ keypair: {
+ privateKey,
+ certificateChain
+ }
+ }
+ }
+ };
+ } else {
+ options = {
+ http: httpOptions
+ };
+ }
+ return {
+ name: SOCKET_ENTRY,
+ service: { name: SERVICE_ENTRY },
+ ...options
+ };
+}
+function valueOrFile(value, filePath) {
+ return value ?? (filePath && import_promises10.default.readFile(filePath, "utf8"));
+}
+
+// packages/miniflare/src/http/helpers.ts
+var import_os = require("os");
+function getAccessibleHosts(ipv4Only = false) {
+ const hosts = [];
+ Object.values((0, import_os.networkInterfaces)()).forEach((net2) => {
+ net2?.forEach(({ family, address }) => {
+ if (family === "IPv4" || family === 4) {
+ hosts.push(address);
+ } else if (!ipv4Only && (family === "IPv6" || family === 6)) {
+ hosts.push(`[${address}]`);
+ }
+ });
+ });
+ return hosts;
+}
+
+// packages/miniflare/src/http/index.ts
+var import_undici8 = require("undici");
+
+// packages/miniflare/src/zod-format.ts
+var import_assert10 = __toESM(require("assert"));
+var import_util4 = __toESM(require("util"));
+var kMessages = Symbol("kMessages");
+var kActual = Symbol("kActual");
+var kGroupId = Symbol("kGroupId");
+var groupColours = [
+ yellow,
+ /* (green) */
+ cyan,
+ blue,
+ magenta,
+ green
+];
+var GroupCountsMap = Map;
+function isAnnotation(value) {
+ return typeof value === "object" && value !== null && kMessages in value && kActual in value;
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null;
+}
+function arrayShallowEqual(a, b) {
+ if (a.length !== b.length)
+ return false;
+ for (let i = 0; i < a.length; i++)
+ if (a[i] !== b[i])
+ return false;
+ return true;
+}
+function issueEqual(a, b) {
+ return a.message === b.message && arrayShallowEqual(a.path, b.path);
+}
+function hasMultipleDistinctMessages(issues, atDepth) {
+ let firstIssue;
+ for (const issue of issues) {
+ if (issue.path.length < atDepth)
+ continue;
+ if (firstIssue === void 0)
+ firstIssue = issue;
+ else if (!issueEqual(firstIssue, issue))
+ return true;
+ }
+ return false;
+}
+function annotate(groupCounts, annotated, input, issue, path21, groupId) {
+ if (path21.length === 0) {
+ if (issue.code === "invalid_union") {
+ const unionIssues = issue.unionErrors.flatMap(({ issues }) => issues);
+ let newGroupId;
+ const multipleDistinct = hasMultipleDistinctMessages(
+ unionIssues,
+ // For this check, we only include messages that are deeper than our
+ // current level, so we don't include messages we'd ignore if we grouped
+ issue.path.length + 1
+ );
+ if (isRecord(input) && multipleDistinct) {
+ newGroupId = groupCounts.size;
+ groupCounts.set(newGroupId, 0);
+ }
+ for (const unionIssue of unionIssues) {
+ const unionPath = unionIssue.path.slice(issue.path.length);
+ if (multipleDistinct && unionPath.length === 0)
+ continue;
+ annotated = annotate(
+ groupCounts,
+ annotated,
+ input,
+ unionIssue,
+ unionPath,
+ newGroupId
+ );
+ }
+ return annotated;
+ }
+ const message = issue.message;
+ if (annotated !== void 0) {
+ if (isAnnotation(annotated) && !annotated[kMessages].includes(message)) {
+ annotated[kMessages].push(message);
+ }
+ return annotated;
+ }
+ if (groupId !== void 0) {
+ const current = groupCounts.get(groupId);
+ (0, import_assert10.default)(current !== void 0);
+ groupCounts.set(groupId, current + 1);
+ }
+ return {
+ [kMessages]: [message],
+ [kActual]: input,
+ [kGroupId]: groupId
+ };
+ }
+ const [head, ...tail] = path21;
+ (0, import_assert10.default)(isRecord(input), "Expected object/array input for nested issue");
+ if (annotated === void 0) {
+ if (Array.isArray(input)) {
+ annotated = new Array(input.length);
+ } else {
+ const entries = Object.keys(input).map((key) => [key, void 0]);
+ annotated = Object.fromEntries(entries);
+ }
+ }
+ (0, import_assert10.default)(isRecord(annotated), "Expected object/array for nested issue");
+ annotated[head] = annotate(
+ groupCounts,
+ annotated[head],
+ input[head],
+ issue,
+ tail,
+ groupId
+ );
+ return annotated;
+}
+function print(inspectOptions, groupCounts, annotated, indent = "", extras) {
+ const prefix = extras?.prefix ?? "";
+ const suffix = extras?.suffix ?? "";
+ if (isAnnotation(annotated)) {
+ const prefixIndent = indent + " ".repeat(prefix.length);
+ const actual = import_util4.default.inspect(annotated[kActual], inspectOptions);
+ const actualIndented = actual.split("\n").map((line, i) => i > 0 ? prefixIndent + line : line).join("\n");
+ let messageColour = red;
+ let messagePrefix = prefixIndent + "^";
+ let groupOr = "";
+ if (annotated[kGroupId] !== void 0) {
+ messageColour = groupColours[annotated[kGroupId] % groupColours.length];
+ messagePrefix += annotated[kGroupId] + 1;
+ const remaining = groupCounts.get(annotated[kGroupId]);
+ (0, import_assert10.default)(remaining !== void 0);
+ if (remaining > 1)
+ groupOr = " *or*";
+ groupCounts.set(annotated[kGroupId], remaining - 1);
+ }
+ messagePrefix += " ";
+ const messageIndent = " ".repeat(messagePrefix.length);
+ const messageIndented = annotated[kMessages].flatMap((m) => m.split("\n")).map((line, i) => i > 0 ? messageIndent + line : line).join("\n");
+ const error = messageColour(`${messagePrefix}${messageIndented}${groupOr}`);
+ return `${indent}${dim(prefix)}${actualIndented}${dim(suffix)}
+${error}`;
+ } else if (Array.isArray(annotated)) {
+ let result = `${indent}${dim(`${prefix}[`)}
+`;
+ const arrayIndent = indent + " ";
+ for (let i = 0; i < annotated.length; i++) {
+ const value = annotated[i];
+ if (value === void 0 && (i === 0 || annotated[i - 1] !== void 0)) {
+ result += `${arrayIndent}${dim("...,")}
+`;
+ }
+ if (value !== void 0) {
+ result += print(inspectOptions, groupCounts, value, arrayIndent, {
+ prefix: `/* [${i}] */ `,
+ suffix: ","
+ });
+ result += "\n";
+ }
+ }
+ result += `${indent}${dim(`]${suffix}`)}`;
+ return result;
+ } else if (isRecord(annotated)) {
+ let result = `${indent}${dim(`${prefix}{`)}
+`;
+ const objectIndent = indent + " ";
+ const entries = Object.entries(annotated);
+ for (let i = 0; i < entries.length; i++) {
+ const [key, value] = entries[i];
+ if (value === void 0 && (i === 0 || entries[i - 1][1] !== void 0)) {
+ result += `${objectIndent}${dim("...,")}
+`;
+ }
+ if (value !== void 0) {
+ result += print(inspectOptions, groupCounts, value, objectIndent, {
+ prefix: `${key}: `,
+ suffix: ","
+ });
+ result += "\n";
+ }
+ }
+ result += `${indent}${dim(`}${suffix}`)}`;
+ return result;
+ }
+ return "";
+}
+function _formatZodError(error, input) {
+ const sortedIssues = Array.from(error.issues).sort((a, b) => {
+ if (a.code !== b.code) {
+ if (a.code === "invalid_union")
+ return -1;
+ if (b.code === "invalid_union")
+ return 1;
+ }
+ return 0;
+ });
+ let annotated;
+ const groupCounts = new GroupCountsMap();
+ for (const issue of sortedIssues) {
+ annotated = annotate(groupCounts, annotated, input, issue, issue.path);
+ }
+ const inspectOptions = {
+ depth: 0,
+ colors: $.enabled
+ };
+ return print(inspectOptions, groupCounts, annotated);
+}
+
+// packages/miniflare/src/index.ts
+function hasMultipleWorkers(opts) {
+ return typeof opts === "object" && opts !== null && "workers" in opts && Array.isArray(opts.workers);
+}
+function validateOptions(opts) {
+ const sharedOpts = opts;
+ const multipleWorkers = hasMultipleWorkers(opts);
+ const workerOpts = multipleWorkers ? opts.workers : [opts];
+ if (workerOpts.length === 0) {
+ throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined");
+ }
+ const pluginSharedOpts = {};
+ const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map(
+ () => ({})
+ );
+ try {
+ for (const [key, plugin] of PLUGIN_ENTRIES) {
+ pluginSharedOpts[key] = plugin.sharedOptions?.parse(sharedOpts);
+ for (let i = 0; i < workerOpts.length; i++) {
+ const path21 = multipleWorkers ? ["workers", i] : void 0;
+ pluginWorkerOpts[i][key] = plugin.options.parse(workerOpts[i], {
+ path: path21
+ });
+ }
+ }
+ } catch (e) {
+ if (e instanceof import_zod17.z.ZodError) {
+ let formatted;
+ try {
+ formatted = _formatZodError(e, opts);
+ } catch (formatError) {
+ const title = "[Miniflare] Validation Error Format Failure";
+ const message = [
+ "### Input",
+ "```",
+ import_util5.default.inspect(opts, { depth: null }),
+ "```",
+ "",
+ "### Validation Error",
+ "```",
+ e.stack,
+ "```",
+ "",
+ "### Format Error",
+ "```",
+ typeof formatError === "object" && formatError !== null && "stack" in formatError && typeof formatError.stack === "string" ? formatError.stack : String(formatError),
+ "```"
+ ].join("\n");
+ const githubIssueUrl = new URL(
+ "https://github.com/cloudflare/miniflare/issues/new"
+ );
+ githubIssueUrl.searchParams.set("title", title);
+ githubIssueUrl.searchParams.set("body", message);
+ formatted = [
+ "Unable to format validation error.",
+ "Please open the following URL in your browser to create a GitHub issue:",
+ githubIssueUrl,
+ "",
+ message,
+ ""
+ ].join("\n");
+ }
+ const error = new MiniflareCoreError(
+ "ERR_VALIDATION",
+ `Unexpected options passed to \`new Miniflare()\` constructor:
+${formatted}`
+ );
+ Object.defineProperty(error, "cause", { get: () => e });
+ throw error;
+ }
+ throw e;
+ }
+ const names = /* @__PURE__ */ new Set();
+ for (const opts2 of pluginWorkerOpts) {
+ const name = opts2.core.name ?? "";
+ if (names.has(name)) {
+ throw new MiniflareCoreError(
+ "ERR_DUPLICATE_NAME",
+ name === "" ? "Multiple workers defined without a `name`" : `Multiple workers defined with the same \`name\`: "${name}"`
+ );
+ }
+ names.add(name);
+ }
+ return [pluginSharedOpts, pluginWorkerOpts];
+}
+function getDurableObjectClassNames(allWorkerOpts) {
+ const serviceClassNames = /* @__PURE__ */ new Map();
+ for (const workerOpts of allWorkerOpts) {
+ const workerServiceName = getUserServiceName(workerOpts.core.name);
+ for (const designator of Object.values(
+ workerOpts.do.durableObjects ?? {}
+ )) {
+ const {
+ className,
+ // Fallback to current worker service if name not defined
+ serviceName = workerServiceName,
+ unsafeUniqueKey
+ } = normaliseDurableObject(designator);
+ let classNames = serviceClassNames.get(serviceName);
+ if (classNames === void 0) {
+ classNames = /* @__PURE__ */ new Map();
+ serviceClassNames.set(serviceName, classNames);
+ }
+ if (classNames.has(className)) {
+ const existingUnsafeUniqueKey = classNames.get(className);
+ if (existingUnsafeUniqueKey !== unsafeUniqueKey) {
+ throw new MiniflareCoreError(
+ "ERR_DIFFERENT_UNIQUE_KEYS",
+ `Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
+ unsafeUniqueKey
+ )} and ${JSON.stringify(existingUnsafeUniqueKey)}`
+ );
+ }
+ } else {
+ classNames.set(className, unsafeUniqueKey);
+ }
+ }
+ }
+ return serviceClassNames;
+}
+function getQueueConsumers(allWorkerOpts) {
+ const queueConsumers = /* @__PURE__ */ new Map();
+ for (const workerOpts of allWorkerOpts) {
+ const workerName = workerOpts.core.name ?? "";
+ let workerConsumers = workerOpts.queues.queueConsumers;
+ if (workerConsumers !== void 0) {
+ if (Array.isArray(workerConsumers)) {
+ workerConsumers = Object.fromEntries(
+ workerConsumers.map((queueName) => [queueName, {}])
+ );
+ }
+ for (const [queueName, opts] of Object.entries(workerConsumers)) {
+ const existingConsumer = queueConsumers.get(queueName);
+ if (existingConsumer !== void 0) {
+ throw new QueuesError(
+ "ERR_MULTIPLE_CONSUMERS",
+ `Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"`
+ );
+ }
+ queueConsumers.set(queueName, { workerName, ...opts });
+ }
+ }
+ }
+ for (const [queueName, consumer] of queueConsumers) {
+ if (consumer.deadLetterQueue === queueName) {
+ throw new QueuesError(
+ "ERR_DEAD_LETTER_QUEUE_CYCLE",
+ `Dead letter queue for queue "${queueName}" cannot be itself`
+ );
+ }
+ }
+ return queueConsumers;
+}
+function getWorkerRoutes(allWorkerOpts) {
+ const allRoutes = /* @__PURE__ */ new Map();
+ for (const workerOpts of allWorkerOpts) {
+ const name = workerOpts.core.name ?? "";
+ (0, import_assert11.default)(!allRoutes.has(name));
+ allRoutes.set(name, workerOpts.core.routes ?? []);
+ }
+ return allRoutes;
+}
+function getProxyBindingName(plugin, worker, binding) {
+ return [
+ CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
+ plugin,
+ worker,
+ binding
+ ].join(":");
+}
+function isNativeTargetBinding(binding) {
+ return !("json" in binding || "wasmModule" in binding || "text" in binding || "data" in binding);
+}
+function buildProxyBinding(plugin, worker, binding) {
+ (0, import_assert11.default)(binding.name !== void 0);
+ const name = getProxyBindingName(plugin, worker, binding.name);
+ const proxyBinding = { ...binding, name };
+ if ("durableObjectNamespace" in proxyBinding && proxyBinding.durableObjectNamespace !== void 0) {
+ proxyBinding.durableObjectNamespace.serviceName ??= getUserServiceName(worker);
+ }
+ return proxyBinding;
+}
+function getInternalDurableObjectProxyBindings(plugin, service) {
+ if (!("worker" in service))
+ return;
+ (0, import_assert11.default)(service.worker !== void 0);
+ const serviceName = service.name;
+ (0, import_assert11.default)(serviceName !== void 0);
+ return service.worker.durableObjectNamespaces?.map(({ className }) => {
+ (0, import_assert11.default)(className !== void 0);
+ return {
+ name: getProxyBindingName(`${plugin}-internal`, serviceName, className),
+ durableObjectNamespace: { serviceName, className }
+ };
+ });
+}
+var restrictedUndiciHeaders = [
+ // From Miniflare 2:
+ // https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132
+ "transfer-encoding",
+ "connection",
+ "keep-alive",
+ "expect"
+];
+var restrictedWebSocketUpgradeHeaders = [
+ "upgrade",
+ "connection",
+ "sec-websocket-accept"
+];
+function _transformsForContentEncoding(encoding) {
+ const encoders = [];
+ if (!encoding)
+ return encoders;
+ const codings = encoding.toLowerCase().split(",").map((x) => x.trim());
+ for (const coding of codings) {
+ if (/(x-)?gzip/.test(coding)) {
+ encoders.push(import_zlib.default.createGzip());
+ } else if (/(x-)?deflate/.test(coding)) {
+ encoders.push(import_zlib.default.createDeflate());
+ } else if (coding === "br") {
+ encoders.push(import_zlib.default.createBrotliCompress());
+ } else {
+ encoders.length = 0;
+ break;
+ }
+ }
+ return encoders;
+}
+async function writeResponse(response, res) {
+ const headers = {};
+ for (const entry of response.headers) {
+ const key = entry[0].toLowerCase();
+ const value = entry[1];
+ if (key === "set-cookie") {
+ headers[key] = response.headers.getSetCookie();
+ } else {
+ headers[key] = value;
+ }
+ }
+ const encoding = headers["content-encoding"]?.toString();
+ const encoders = _transformsForContentEncoding(encoding);
+ if (encoders.length > 0) {
+ delete headers["content-length"];
+ }
+ res.writeHead(response.status, response.statusText, headers);
+ let initialStream = res;
+ for (let i = encoders.length - 1; i >= 0; i--) {
+ encoders[i].pipe(initialStream);
+ initialStream = encoders[i];
+ }
+ if (response.body) {
+ for await (const chunk of response.body) {
+ if (chunk)
+ initialStream.write(chunk);
+ }
+ }
+ initialStream.end();
+}
+function safeReadableStreamFrom(iterable) {
+ let iterator;
+ return new import_web5.ReadableStream(
+ {
+ async start() {
+ iterator = iterable[Symbol.asyncIterator]();
+ },
+ // @ts-expect-error `pull` may return anything
+ async pull(controller) {
+ try {
+ const { done, value } = await iterator.next();
+ if (done) {
+ queueMicrotask(() => controller.close());
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
+ controller.enqueue(new Uint8Array(buf));
+ }
+ } catch {
+ queueMicrotask(() => controller.close());
+ }
+ return controller.desiredSize > 0;
+ },
+ async cancel() {
+ await iterator.return?.();
+ }
+ },
+ 0
+ );
+}
+var maybeInstanceRegistry;
+function _initialiseInstanceRegistry() {
+ return maybeInstanceRegistry = /* @__PURE__ */ new Map();
+}
+var Miniflare = class {
+ #sharedOpts;
+ #workerOpts;
+ #log;
+ #host;
+ #accessibleHost;
+ #runtime;
+ #removeRuntimeExitHook;
+ #runtimeEntryURL;
+ #runtimeClient;
+ #proxyClient;
+ // Path to temporary directory for use as scratch space/"in-memory" Durable
+ // Object storage. Note this may not exist, it's up to the consumers to
+ // create this if needed. Deleted on `dispose()`.
+ #tmpPath;
+ #removeTmpPathExitHook;
+ // Mutual exclusion lock for runtime operations (i.e. initialisation and
+ // updating config). This essentially puts initialisation and future updates
+ // in a queue, ensuring they're performed in calling order.
+ #runtimeMutex;
+ // Store `#init()` `Promise`, so we can propagate initialisation errors in
+ // `ready`. We would have no way of catching these otherwise.
+ #initPromise;
+ // Aborted when dispose() is called
+ #disposeController;
+ #loopbackServer;
+ #loopbackPort;
+ #liveReloadServer;
+ #webSocketServer;
+ #webSocketExtraHeaders;
+ constructor(opts) {
+ const [sharedOpts, workerOpts] = validateOptions(opts);
+ this.#sharedOpts = sharedOpts;
+ this.#workerOpts = workerOpts;
+ if (maybeInstanceRegistry !== void 0) {
+ const object = { name: "Miniflare", stack: "" };
+ Error.captureStackTrace(object, Miniflare);
+ maybeInstanceRegistry.set(this, object.stack);
+ }
+ this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
+ this.#host = this.#sharedOpts.core.host ?? "127.0.0.1";
+ this.#accessibleHost = this.#host === "*" || this.#host === "0.0.0.0" || this.#host === "::" ? "127.0.0.1" : this.#host;
+ if (import_net.default.isIPv6(this.#accessibleHost)) {
+ this.#accessibleHost = `[${this.#accessibleHost}]`;
+ }
+ this.#liveReloadServer = new import_ws3.WebSocketServer({ noServer: true });
+ this.#webSocketServer = new import_ws3.WebSocketServer({
+ noServer: true,
+ // Disable automatic handling of `Sec-WebSocket-Protocol` header,
+ // Cloudflare Workers require users to include this header themselves in
+ // `Response`s: https://github.com/cloudflare/miniflare/issues/179
+ handleProtocols: () => false
+ });
+ this.#webSocketExtraHeaders = /* @__PURE__ */ new WeakMap();
+ this.#webSocketServer.on("headers", (headers, req) => {
+ const extra = this.#webSocketExtraHeaders.get(req);
+ this.#webSocketExtraHeaders.delete(req);
+ if (extra) {
+ for (const [key, value] of extra) {
+ if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) {
+ headers.push(`${key}: ${value}`);
+ }
+ }
+ }
+ });
+ this.#tmpPath = import_path20.default.join(
+ import_os2.default.tmpdir(),
+ `miniflare-${import_crypto2.default.randomBytes(16).toString("hex")}`
+ );
+ this.#removeTmpPathExitHook = (0, import_exit_hook.default)(() => {
+ import_fs17.default.rmSync(this.#tmpPath, { force: true, recursive: true });
+ });
+ this.#disposeController = new AbortController();
+ this.#runtimeMutex = new Mutex();
+ this.#initPromise = this.#runtimeMutex.runWith(() => this.#init()).catch((e) => {
+ maybeInstanceRegistry?.delete(this);
+ throw e;
+ });
+ }
+ #handleReload() {
+ for (const ws of this.#liveReloadServer.clients) {
+ ws.close(1012, "Service Restart");
+ }
+ for (const ws of this.#webSocketServer.clients) {
+ ws.close(1012, "Service Restart");
+ }
+ }
+ async #init() {
+ this.#loopbackServer = await this.#startLoopbackServer(0, this.#host);
+ const address = this.#loopbackServer.address();
+ (0, import_assert11.default)(address !== null && typeof address === "object");
+ this.#loopbackPort = address.port;
+ const port = this.#sharedOpts.core.port ?? 0;
+ const opts = {
+ entryHost: import_net.default.isIPv6(this.#host) ? `[${this.#host}]` : this.#host,
+ entryPort: port,
+ loopbackPort: this.#loopbackPort,
+ inspectorPort: this.#sharedOpts.core.inspectorPort,
+ verbose: this.#sharedOpts.core.verbose
+ };
+ this.#runtime = new Runtime(opts);
+ this.#removeRuntimeExitHook = (0, import_exit_hook.default)(() => void this.#runtime?.dispose());
+ await this.#assembleAndUpdateConfig();
+ }
+ async #handleLoopbackCustomService(request, customService) {
+ const slashIndex = customService.indexOf("/");
+ const workerIndex = parseInt(customService.substring(0, slashIndex));
+ const serviceKind = customService[slashIndex + 1];
+ const serviceName = customService.substring(slashIndex + 2);
+ let service;
+ if (serviceKind === "#" /* UNKNOWN */) {
+ service = this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName];
+ } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
+ service = this.#workerOpts[workerIndex]?.core.outboundService;
+ }
+ (0, import_assert11.default)(typeof service === "function");
+ try {
+ const response = await service(request);
+ return import_zod17.z.instanceof(Response).parse(response);
+ } catch (e) {
+ return new Response(e?.stack ?? e, { status: 500 });
+ }
+ }
+ get #workerSrcOpts() {
+ return this.#workerOpts.map(({ core }) => core);
+ }
+ #handleLoopback = async (req, res) => {
+ const headers = new import_undici8.Headers();
+ for (const [name, values] of Object.entries(req.headers)) {
+ if (restrictedUndiciHeaders.includes(name))
+ continue;
+ if (Array.isArray(values)) {
+ for (const value of values)
+ headers.append(name, value);
+ } else if (values !== void 0) {
+ headers.append(name, values);
+ }
+ }
+ const cfBlob = headers.get(HEADER_CF_BLOB);
+ headers.delete(HEADER_CF_BLOB);
+ (0, import_assert11.default)(!Array.isArray(cfBlob));
+ const cf = cfBlob ? JSON.parse(cfBlob) : void 0;
+ const url13 = new URL(
+ headers.get(CoreHeaders.ORIGINAL_URL) ?? req.url ?? "",
+ "http://localhost"
+ );
+ headers.delete(CoreHeaders.ORIGINAL_URL);
+ const noBody = req.method === "GET" || req.method === "HEAD";
+ const body = noBody ? void 0 : safeReadableStreamFrom(req);
+ const request = new Request(url13, {
+ method: req.method,
+ headers,
+ body,
+ duplex: "half",
+ cf
+ });
+ let response;
+ try {
+ const customService = request.headers.get(CoreHeaders.CUSTOM_SERVICE);
+ if (customService !== null) {
+ request.headers.delete(CoreHeaders.CUSTOM_SERVICE);
+ response = await this.#handleLoopbackCustomService(
+ request,
+ customService
+ );
+ } else if (url13.pathname === "/core/error") {
+ response = await handlePrettyErrorRequest(
+ this.#log,
+ this.#workerSrcOpts,
+ request
+ );
+ } else if (url13.pathname === "/core/log") {
+ const level = parseInt(request.headers.get(SharedHeaders.LOG_LEVEL));
+ (0, import_assert11.default)(
+ 0 /* NONE */ <= level && level <= 5 /* VERBOSE */,
+ `Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}`
+ );
+ const logLevel = level;
+ let message = await request.text();
+ if (!$.enabled)
+ message = stripAnsi(message);
+ this.#log.logWithLevel(logLevel, message);
+ response = new Response(null, { status: 204 });
+ }
+ } catch (e) {
+ this.#log.error(e);
+ res?.writeHead(500);
+ res?.end(e?.stack ?? String(e));
+ return;
+ }
+ if (res !== void 0) {
+ if (response === void 0) {
+ res.writeHead(404);
+ res.end();
+ } else {
+ await writeResponse(response, res);
+ }
+ }
+ return response;
+ };
+ #handleLoopbackUpgrade = async (req, socket, head) => {
+ const { pathname } = new URL(req.url ?? "", "http://localhost");
+ if (pathname === "/cdn-cgi/mf/reload") {
+ this.#liveReloadServer.handleUpgrade(req, socket, head, (ws) => {
+ this.#liveReloadServer.emit("connection", ws, req);
+ });
+ return;
+ }
+ const response = await this.#handleLoopback(req);
+ const webSocket = response?.webSocket;
+ if (response?.status === 101 && webSocket) {
+ this.#webSocketExtraHeaders.set(req, response.headers);
+ this.#webSocketServer.handleUpgrade(req, socket, head, (ws) => {
+ void coupleWebSocket(ws, webSocket);
+ this.#webSocketServer.emit("connection", ws, req);
+ });
+ return;
+ }
+ const res = new import_http7.default.ServerResponse(req);
+ (0, import_assert11.default)(socket instanceof import_net.default.Socket);
+ res.assignSocket(socket);
+ if (!response || response.ok) {
+ res.writeHead(500);
+ res.end();
+ this.#log.error(
+ new TypeError(
+ "Web Socket request did not return status 101 Switching Protocols response with Web Socket"
+ )
+ );
+ return;
+ }
+ await writeResponse(response, res);
+ };
+ #startLoopbackServer(port, hostname) {
+ if (hostname === "*") {
+ hostname = "::";
+ }
+ return new Promise((resolve) => {
+ const server = (0, import_stoppable.default)(
+ import_http7.default.createServer(this.#handleLoopback),
+ /* grace */
+ 0
+ );
+ server.on("upgrade", this.#handleLoopbackUpgrade);
+ server.listen(port, hostname, () => resolve(server));
+ });
+ }
+ #stopLoopbackServer() {
+ return new Promise((resolve, reject) => {
+ (0, import_assert11.default)(this.#loopbackServer !== void 0);
+ this.#loopbackServer.stop((err) => err ? reject(err) : resolve());
+ });
+ }
+ async #assembleConfig() {
+ const allWorkerOpts = this.#workerOpts;
+ const sharedOpts = this.#sharedOpts;
+ const loopbackPort = this.#loopbackPort;
+ (0, import_assert11.default)(loopbackPort !== void 0);
+ sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf);
+ const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts);
+ const queueConsumers = getQueueConsumers(allWorkerOpts);
+ const allWorkerRoutes = getWorkerRoutes(allWorkerOpts);
+ const workerNames = [...allWorkerRoutes.keys()];
+ const services = /* @__PURE__ */ new Map();
+ const sockets = [await configureEntrySocket(sharedOpts.core)];
+ const proxyBindings = [];
+ for (let i = 0; i < allWorkerOpts.length; i++) {
+ const workerOpts = allWorkerOpts[i];
+ const workerName = workerOpts.core.name ?? "";
+ const workerBindings = [];
+ const additionalModules = [];
+ for (const [key, plugin] of PLUGIN_ENTRIES) {
+ const pluginBindings = await plugin.getBindings(workerOpts[key], i);
+ if (pluginBindings !== void 0) {
+ for (const binding of pluginBindings) {
+ workerBindings.push(binding);
+ if (isNativeTargetBinding(binding)) {
+ proxyBindings.push(buildProxyBinding(key, workerName, binding));
+ }
+ }
+ if (key === "kv") {
+ const module2 = maybeGetSitesManifestModule(pluginBindings);
+ if (module2 !== void 0)
+ additionalModules.push(module2);
+ }
+ }
+ }
+ const pluginServicesOptionsBase = {
+ log: this.#log,
+ workerBindings,
+ workerIndex: i,
+ additionalModules,
+ tmpPath: this.#tmpPath,
+ workerNames,
+ durableObjectClassNames,
+ queueConsumers
+ };
+ for (const [key, plugin] of PLUGIN_ENTRIES) {
+ const pluginServices = await plugin.getServices({
+ ...pluginServicesOptionsBase,
+ // @ts-expect-error `CoreOptionsSchema` has required options which are
+ // missing in other plugins' options.
+ options: workerOpts[key],
+ // @ts-expect-error `QueuesPlugin` doesn't define shared options
+ sharedOptions: sharedOpts[key]
+ });
+ if (pluginServices !== void 0) {
+ for (const service of pluginServices) {
+ if (service.name !== void 0 && !services.has(service.name)) {
+ services.set(service.name, service);
+ if (key !== DURABLE_OBJECTS_PLUGIN_NAME) {
+ const maybeBindings = getInternalDurableObjectProxyBindings(
+ key,
+ service
+ );
+ if (maybeBindings !== void 0) {
+ proxyBindings.push(...maybeBindings);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ const extensions = [
+ {
+ modules: [
+ { name: "miniflare:shared", esModule: index_worker_default() },
+ { name: "miniflare:zod", esModule: zod_worker_default() }
+ ]
+ },
+ {
+ modules: [
+ {
+ name: "miniflare-internal:identity",
+ internal: true,
+ // Not accessible to user code
+ esModule: `
+ class Identity {
+ async asyncIdentity(...args) {
+ const i = args.findIndex((arg) => arg instanceof ReadableStream);
+ if (i !== -1) args[i] = args[i].pipeThrough(new TransformStream());
+ return args;
+ }
+ }
+ export default function() { return new Identity(); }
+ `
+ }
+ ]
+ }
+ ];
+ proxyBindings.push({
+ name: "IDENTITY",
+ wrapped: { moduleName: "miniflare-internal:identity" }
+ });
+ const globalServices = getGlobalServices({
+ sharedOptions: sharedOpts.core,
+ allWorkerRoutes,
+ fallbackWorkerName: this.#workerOpts[0].core.name,
+ loopbackPort,
+ log: this.#log,
+ proxyBindings
+ });
+ for (const service of globalServices) {
+ (0, import_assert11.default)(service.name !== void 0 && !services.has(service.name));
+ services.set(service.name, service);
+ }
+ return { services: Array.from(services.values()), sockets, extensions };
+ }
+ async #assembleAndUpdateConfig() {
+ const initial = !this.#runtimeEntryURL;
+ (0, import_assert11.default)(this.#runtime !== void 0);
+ const config = await this.#assembleConfig();
+ const configBuffer = serializeConfig(config);
+ const maybePort = await this.#runtime.updateConfig(configBuffer, {
+ signal: this.#disposeController.signal,
+ entryPort: maybeApply(parseInt, this.#runtimeEntryURL?.port)
+ });
+ if (this.#disposeController.signal.aborted)
+ return;
+ if (maybePort === void 0) {
+ throw new MiniflareCoreError(
+ "ERR_RUNTIME_FAILURE",
+ "The Workers runtime failed to start. There is likely additional logging output above."
+ );
+ }
+ const entrySocket = config.sockets?.[0];
+ const secure = entrySocket !== void 0 && "https" in entrySocket;
+ const previousEntry = this.#runtimeEntryURL;
+ this.#runtimeEntryURL = new URL(
+ `${secure ? "https" : "http"}://${this.#accessibleHost}:${maybePort}`
+ );
+ if (previousEntry?.toString() !== this.#runtimeEntryURL.toString()) {
+ this.#runtimeClient = new import_undici9.Client(this.#runtimeEntryURL, {
+ connect: { rejectUnauthorized: false }
+ });
+ registerAllowUnauthorizedDispatcher(this.#runtimeClient);
+ }
+ if (this.#proxyClient === void 0) {
+ this.#proxyClient = new ProxyClient(
+ this.#runtimeEntryURL,
+ this.dispatchFetch
+ );
+ } else {
+ this.#proxyClient.poisonProxies(this.#runtimeEntryURL);
+ }
+ if (!this.#runtimeMutex.hasWaiting) {
+ const ready = initial ? "Ready" : "Updated and ready";
+ const host = import_net.default.isIPv6(this.#host) ? `[${this.#host}]` : this.#host;
+ this.#log.info(
+ `${ready} on ${secure ? "https" : "http"}://${host}:${maybePort} `
+ );
+ if (initial) {
+ let hosts;
+ if (this.#host === "::" || this.#host === "*") {
+ hosts = getAccessibleHosts(false);
+ } else if (this.#host === "0.0.0.0") {
+ hosts = getAccessibleHosts(true);
+ } else {
+ hosts = [];
+ }
+ for (const h of hosts) {
+ this.#log.info(`- ${secure ? "https" : "http"}://${h}:${maybePort}`);
+ }
+ }
+ this.#handleReload();
+ }
+ }
+ async #waitForReady() {
+ await this.#initPromise;
+ await this.#runtimeMutex.drained();
+ (0, import_assert11.default)(this.#runtimeEntryURL !== void 0);
+ return new URL(this.#runtimeEntryURL.toString());
+ }
+ get ready() {
+ return this.#waitForReady();
+ }
+ #checkDisposed() {
+ if (this.#disposeController.signal.aborted) {
+ throw new MiniflareCoreError(
+ "ERR_DISPOSED",
+ "Cannot use disposed instance"
+ );
+ }
+ }
+ async #setOptions(opts) {
+ const [sharedOpts, workerOpts] = validateOptions(opts);
+ this.#sharedOpts = sharedOpts;
+ this.#workerOpts = workerOpts;
+ this.#log = this.#sharedOpts.core.log ?? this.#log;
+ await this.#assembleAndUpdateConfig();
+ }
+ setOptions(opts) {
+ this.#checkDisposed();
+ return this.#runtimeMutex.runWith(() => this.#setOptions(opts));
+ }
+ dispatchFetch = async (input, init2) => {
+ this.#checkDisposed();
+ await this.ready;
+ (0, import_assert11.default)(this.#runtimeEntryURL !== void 0);
+ (0, import_assert11.default)(this.#runtimeClient !== void 0);
+ const forward = new Request(input, init2);
+ const url13 = new URL(forward.url);
+ forward.headers.set(CoreHeaders.ORIGINAL_URL, url13.toString());
+ url13.protocol = this.#runtimeEntryURL.protocol;
+ url13.host = this.#runtimeEntryURL.host;
+ if (forward.cf) {
+ const cf = { ...fallbackCf, ...forward.cf };
+ forward.headers.set(HEADER_CF_BLOB, JSON.stringify(cf));
+ }
+ if (forward.body !== null && forward.headers.get("Content-Length") === "0") {
+ forward.headers.delete("Content-Length");
+ }
+ const forwardInit = forward;
+ forwardInit.dispatcher = this.#runtimeClient;
+ const response = await fetch2(url13, forwardInit);
+ const stack = response.headers.get(CoreHeaders.ERROR_STACK);
+ if (response.status === 500 && stack !== null) {
+ const caught = JsonErrorSchema.parse(await response.json());
+ throw reviveError(this.#workerSrcOpts, caught);
+ }
+ if (process.env.MINIFLARE_ASSERT_BODIES_CONSUMED === "true" && response.body !== null) {
+ const originalLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = Infinity;
+ const error = new Error(
+ "`body` returned from `Miniflare#dispatchFetch()` not consumed immediately"
+ );
+ Error.stackTraceLimit = originalLimit;
+ setImmediate(() => {
+ if (!response.bodyUsed)
+ throw error;
+ });
+ }
+ return response;
+ };
+ /** @internal */
+ async _getProxyClient() {
+ this.#checkDisposed();
+ await this.ready;
+ (0, import_assert11.default)(this.#proxyClient !== void 0);
+ return this.#proxyClient;
+ }
+ async getBindings(workerName) {
+ const bindings = {};
+ const proxyClient = await this._getProxyClient();
+ let workerOpts;
+ if (workerName === void 0) {
+ workerOpts = this.#workerOpts[0];
+ } else {
+ workerOpts = this.#workerOpts.find(
+ ({ core }) => (core.name ?? "") === workerName
+ );
+ if (workerOpts === void 0) {
+ throw new TypeError(`${JSON.stringify(workerName)} worker not found`);
+ }
+ }
+ workerName = workerOpts.core.name ?? "";
+ for (const [key, plugin] of PLUGIN_ENTRIES) {
+ const pluginBindings = await plugin.getNodeBindings(workerOpts[key]);
+ for (const [name, binding] of Object.entries(pluginBindings)) {
+ if (binding === kProxyNodeBinding) {
+ const proxyBindingName = getProxyBindingName(key, workerName, name);
+ const proxy = proxyClient.env[proxyBindingName];
+ (0, import_assert11.default)(
+ proxy !== void 0,
+ `Expected ${proxyBindingName} to be bound`
+ );
+ bindings[name] = proxy;
+ } else {
+ bindings[name] = binding;
+ }
+ }
+ }
+ return bindings;
+ }
+ async #getProxy(pluginName, bindingName, workerName) {
+ const proxyClient = await this._getProxyClient();
+ const proxyBindingName = getProxyBindingName(
+ pluginName,
+ // Default to entrypoint worker if none specified
+ workerName ?? this.#workerOpts[0].core.name ?? "",
+ bindingName
+ );
+ const proxy = proxyClient.env[proxyBindingName];
+ if (proxy === void 0) {
+ const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName);
+ throw new TypeError(
+ `${JSON.stringify(bindingName)} unbound in ${friendlyWorkerName} worker`
+ );
+ }
+ return proxy;
+ }
+ // TODO(someday): would be nice to define these in plugins
+ async getCaches() {
+ const proxyClient = await this._getProxyClient();
+ return proxyClient.global.caches;
+ }
+ getD1Database(bindingName, workerName) {
+ return this.#getProxy(D1_PLUGIN_NAME, bindingName, workerName);
+ }
+ getDurableObjectNamespace(bindingName, workerName) {
+ return this.#getProxy(DURABLE_OBJECTS_PLUGIN_NAME, bindingName, workerName);
+ }
+ getKVNamespace(bindingName, workerName) {
+ return this.#getProxy(KV_PLUGIN_NAME, bindingName, workerName);
+ }
+ getQueueProducer(bindingName, workerName) {
+ return this.#getProxy(QUEUES_PLUGIN_NAME, bindingName, workerName);
+ }
+ getR2Bucket(bindingName, workerName) {
+ return this.#getProxy(R2_PLUGIN_NAME, bindingName, workerName);
+ }
+ /** @internal */
+ _getInternalDurableObjectNamespace(pluginName, serviceName, className) {
+ return this.#getProxy(`${pluginName}-internal`, className, serviceName);
+ }
+ async dispose() {
+ this.#disposeController.abort();
+ try {
+ await this.ready;
+ } finally {
+ this.#removeTmpPathExitHook();
+ this.#removeRuntimeExitHook?.();
+ await this.#proxyClient?.dispose();
+ await this.#runtime?.dispose();
+ await this.#stopLoopbackServer();
+ await import_fs17.default.promises.rm(this.#tmpPath, { force: true, recursive: true });
+ maybeInstanceRegistry?.delete(this);
+ }
+ }
+};
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+ CACHE_PLUGIN,
+ CACHE_PLUGIN_NAME,
+ CORE_PLUGIN,
+ CORE_PLUGIN_NAME,
+ CacheBindings,
+ CacheHeaders,
+ CacheOptionsSchema,
+ CacheSharedOptionsSchema,
+ CloseEvent,
+ CoreBindings,
+ CoreHeaders,
+ CoreOptionsSchema,
+ CoreSharedOptionsSchema,
+ D1OptionsSchema,
+ D1SharedOptionsSchema,
+ D1_PLUGIN,
+ D1_PLUGIN_NAME,
+ DEFAULT_PERSIST_ROOT,
+ DURABLE_OBJECTS_PLUGIN,
+ DURABLE_OBJECTS_PLUGIN_NAME,
+ DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
+ DeferredPromise,
+ DurableObjectsOptionsSchema,
+ DurableObjectsSharedOptionsSchema,
+ ErrorEvent,
+ File,
+ FormData,
+ HEADER_CF_BLOB,
+ Headers,
+ HttpOptions_Style,
+ JsonSchema,
+ KVHeaders,
+ KVLimits,
+ KVOptionsSchema,
+ KVParams,
+ KVSharedOptionsSchema,
+ KV_PLUGIN,
+ KV_PLUGIN_NAME,
+ LiteralSchema,
+ Log,
+ LogLevel,
+ MessageEvent,
+ Miniflare,
+ MiniflareCoreError,
+ MiniflareError,
+ ModuleDefinitionSchema,
+ ModuleRuleSchema,
+ ModuleRuleTypeSchema,
+ Mutex,
+ NoOpLog,
+ PLUGINS,
+ PLUGIN_ENTRIES,
+ PersistenceSchema,
+ ProxyAddresses,
+ ProxyClient,
+ ProxyOps,
+ QUEUES_PLUGIN,
+ QUEUES_PLUGIN_NAME,
+ QueueBindings,
+ QueueConsumerOptionsSchema,
+ QueueConsumerSchema,
+ QueueConsumersSchema,
+ QueueContentTypeSchema,
+ QueueIncomingMessageSchema,
+ QueuesBatchRequestSchema,
+ QueuesError,
+ QueuesOptionsSchema,
+ R2OptionsSchema,
+ R2SharedOptionsSchema,
+ R2_PLUGIN,
+ R2_PLUGIN_NAME,
+ Request,
+ Response,
+ RouterError,
+ Runtime,
+ SERVICE_ENTRY,
+ SERVICE_LOOPBACK,
+ SITES_NO_CACHE_PREFIX,
+ SOCKET_ENTRY,
+ SharedBindings,
+ SharedHeaders,
+ SiteBindings,
+ SourceOptionsSchema,
+ TlsOptions_Version,
+ TypedEventTarget,
+ WORKER_BINDING_SERVICE_LOOPBACK,
+ WaitGroup,
+ WebSocket,
+ WebSocketPair,
+ Worker_Binding_CryptoKey_Usage,
+ _forceColour,
+ _formatZodError,
+ _initialiseInstanceRegistry,
+ _transformsForContentEncoding,
+ base64Decode,
+ base64Encode,
+ configureEntrySocket,
+ coupleWebSocket,
+ createFetchMock,
+ createHTTPReducers,
+ createHTTPRevivers,
+ decodeSitesKey,
+ deserialiseRegExps,
+ deserialiseSiteRegExps,
+ encodeSitesKey,
+ fetch,
+ getAccessibleHosts,
+ getCacheServiceName,
+ getGlobalServices,
+ getPersistPath,
+ globsToRegExps,
+ isFetcherFetch,
+ isR2ObjectWriteHttpMetadata,
+ isSitesRequest,
+ kProxyNodeBinding,
+ kVoid,
+ matchRoutes,
+ maybeApply,
+ maybeGetSitesManifestModule,
+ maybeParseURL,
+ migrateDatabase,
+ namespaceEntries,
+ namespaceKeys,
+ normaliseDurableObject,
+ objectEntryWorker,
+ parseRanges,
+ parseRoutes,
+ parseWithReadableStreams,
+ prefixError,
+ prefixStream,
+ readPrefix,
+ reduceError,
+ registerAllowUnauthorizedDispatcher,
+ sanitisePath,
+ serialiseRegExps,
+ serialiseSiteRegExps,
+ serializeConfig,
+ stringifyWithStreams,
+ stripAnsi,
+ structuredSerializableReducers,
+ structuredSerializableRevivers,
+ supportedCompatibilityDate,
+ testRegExps,
+ testSiteRegExps,
+ viewToBuffer,
+ zAwaitable
+});
+/*! Path sanitisation regexps adapted from node-sanitize-filename:
+ * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37
+ *
+ * Licensed under the ISC license:
+ *
+ * Copyright Parsha Pourkhomami <parshap@gmail.com>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the
+ * above copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+/*!
+ * MIT License
+ *
+ * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
+ *
+ * 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.
+ */
+/*!
+ * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)
+ *
+ * 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.
+ */
+//# sourceMappingURL=index.js.map