Rocky_Mountain_Vending/.pnpm-store/v10/files/9f/25273d7b42ef6b5c80f3175c1132b2cec011092b478d05ae257d50f98da1dbcc9cea8fbba2c1565133a6eb2e9d8c7a5564d3b1c76e72ac7f17bdd692bd4e52
DMleadgen 46d973904b
Initial commit: Rocky Mountain Vending website
Next.js website for Rocky Mountain Vending company featuring:
- Product catalog with Stripe integration
- Service areas and parts pages
- Admin dashboard with Clerk authentication
- SEO optimized pages with JSON-LD structured data

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-12 16:22:15 -07:00

17552 lines
594 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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;
};
// ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
var require_ignore = __commonJS({
"../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js"(exports, module2) {
function makeArray(subject) {
return Array.isArray(subject) ? subject : [subject];
}
var EMPTY = "";
var SPACE = " ";
var ESCAPE = "\\";
var REGEX_TEST_BLANK_LINE = /^\s+$/;
var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
var REGEX_SPLITALL_CRLF = /\r?\n/g;
var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
var SLASH = "/";
var TMP_KEY_IGNORE = "node-ignore";
if (typeof Symbol !== "undefined") {
TMP_KEY_IGNORE = Symbol.for("node-ignore");
}
var KEY_IGNORE = TMP_KEY_IGNORE;
var define = (object, key, value) => Object.defineProperty(object, key, { value });
var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
var RETURN_FALSE = () => false;
var sanitizeRange = (range) => range.replace(
REGEX_REGEXP_RANGE,
(match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
);
var cleanRangeBackSlash = (slashes) => {
const { length } = slashes;
return slashes.slice(0, length - length % 2);
};
var REPLACERS = [
[
// remove BOM
// TODO:
// Other similar zero-width characters?
/^\uFEFF/,
() => EMPTY
],
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/,
(match) => match.indexOf("\\") === 0 ? SPACE : EMPTY
],
// replace (\ ) with ' '
[
/\\\s/g,
() => SPACE
],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[
/[\\$.|*+(){^]/g,
(match) => `\\${match}`
],
[
// > a question mark (?) matches a single character
/(?!\\)\?/g,
() => "[^/]"
],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//,
() => "^"
],
// replace special metacharacter slash after the leading slash
[
/\//g,
() => "\\/"
],
[
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
() => "^(?:.*\\/)?"
],
// starting
[
// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/,
function startingReplacer() {
return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
}
],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
(_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
],
// normal intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule,
// coz trailing single wildcard will be handed by [trailing wildcard]
/(^|[^\\]+)(\\\*)+(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
(_, p1, p2) => {
const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
return p1 + unescaped;
}
],
[
// unescape, revert step 3 except for back slash
// For example, if a user escape a '\\*',
// after step 3, the result will be '\\\\\\*'
/\\\\\\(?=[$.|*+(){^])/g,
() => ESCAPE
],
[
// '\\\\' -> '\\'
/\\\\/g,
() => ESCAPE
],
[
// > The range notation, e.g. [a-zA-Z],
// > can be used to match one of the characters in a range.
// `\` is escaped by step 3
/(\\)?\[([^\]/]*?)(\\*)($|\])/g,
(match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
],
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*])$/,
// WTF!
// https://git-scm.com/docs/gitignore
// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
// which re-fixes #24, #38
// > If there is a separator at the end of the pattern then the pattern
// > will only match directories, otherwise the pattern can match both
// > files and directories.
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
(match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
],
// trailing wildcard
[
/(\^|\\\/)?\\\*$/,
(_, p1) => {
const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
return `${prefix}(?=$|\\/$)`;
}
]
];
var regexCache = /* @__PURE__ */ Object.create(null);
var makeRegex = (pattern, ignoreCase) => {
let source = regexCache[pattern];
if (!source) {
source = REPLACERS.reduce(
(prev, current) => prev.replace(current[0], current[1].bind(pattern)),
pattern
);
regexCache[pattern] = source;
}
return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
};
var isString = (subject) => typeof subject === "string";
var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
var IgnoreRule = class {
constructor(origin, pattern, negative, regex) {
this.origin = origin;
this.pattern = pattern;
this.negative = negative;
this.regex = regex;
}
};
var createRule = (pattern, ignoreCase) => {
const origin = pattern;
let negative = false;
if (pattern.indexOf("!") === 0) {
negative = true;
pattern = pattern.substr(1);
}
pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
const regex = makeRegex(pattern, ignoreCase);
return new IgnoreRule(
origin,
pattern,
negative,
regex
);
};
var throwError = (message, Ctor) => {
throw new Ctor(message);
};
var checkPath = (path31, originalPath, doThrow) => {
if (!isString(path31)) {
return doThrow(
`path must be a string, but got \`${originalPath}\``,
TypeError
);
}
if (!path31) {
return doThrow(`path must not be empty`, TypeError);
}
if (checkPath.isNotRelative(path31)) {
const r = "`path.relative()`d";
return doThrow(
`path should be a ${r} string, but got "${originalPath}"`,
RangeError
);
}
return true;
};
var isNotRelative = (path31) => REGEX_TEST_INVALID_PATH.test(path31);
checkPath.isNotRelative = isNotRelative;
checkPath.convert = (p) => p;
var Ignore = class {
constructor({
ignorecase = true,
ignoreCase = ignorecase,
allowRelativePaths = false
} = {}) {
define(this, KEY_IGNORE, true);
this._rules = [];
this._ignoreCase = ignoreCase;
this._allowRelativePaths = allowRelativePaths;
this._initCache();
}
_initCache() {
this._ignoreCache = /* @__PURE__ */ Object.create(null);
this._testCache = /* @__PURE__ */ Object.create(null);
}
_addPattern(pattern) {
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules);
this._added = true;
return;
}
if (checkPattern(pattern)) {
const rule = createRule(pattern, this._ignoreCase);
this._added = true;
this._rules.push(rule);
}
}
// @param {Array<string> | string | Ignore} pattern
add(pattern) {
this._added = false;
makeArray(
isString(pattern) ? splitPattern(pattern) : pattern
).forEach(this._addPattern, this);
if (this._added) {
this._initCache();
}
return this;
}
// legacy
addPattern(pattern) {
return this.add(pattern);
}
// | ignored : unignored
// negative | 0:0 | 0:1 | 1:0 | 1:1
// -------- | ------- | ------- | ------- | --------
// 0 | TEST | TEST | SKIP | X
// 1 | TESTIF | SKIP | TEST | X
// - SKIP: always skip
// - TEST: always test
// - TESTIF: only test if checkUnignored
// - X: that never happen
// @param {boolean} whether should check if the path is unignored,
// setting `checkUnignored` to `false` could reduce additional
// path matching.
// @returns {TestResult} true if a file is ignored
_testOne(path31, checkUnignored) {
let ignored2 = false;
let unignored = false;
this._rules.forEach((rule) => {
const { negative } = rule;
if (unignored === negative && ignored2 !== unignored || negative && !ignored2 && !unignored && !checkUnignored) {
return;
}
const matched = rule.regex.test(path31);
if (matched) {
ignored2 = !negative;
unignored = negative;
}
});
return {
ignored: ignored2,
unignored
};
}
// @returns {TestResult}
_test(originalPath, cache, checkUnignored, slices) {
const path31 = originalPath && checkPath.convert(originalPath);
checkPath(
path31,
originalPath,
this._allowRelativePaths ? RETURN_FALSE : throwError
);
return this._t(path31, cache, checkUnignored, slices);
}
_t(path31, cache, checkUnignored, slices) {
if (path31 in cache) {
return cache[path31];
}
if (!slices) {
slices = path31.split(SLASH);
}
slices.pop();
if (!slices.length) {
return cache[path31] = this._testOne(path31, checkUnignored);
}
const parent = this._t(
slices.join(SLASH) + SLASH,
cache,
checkUnignored,
slices
);
return cache[path31] = parent.ignored ? parent : this._testOne(path31, checkUnignored);
}
ignores(path31) {
return this._test(path31, this._ignoreCache, false).ignored;
}
createFilter() {
return (path31) => !this.ignores(path31);
}
filter(paths) {
return makeArray(paths).filter(this.createFilter());
}
// @returns {TestResult}
test(path31) {
return this._test(path31, this._testCache, true);
}
};
var factory = (options) => new Ignore(options);
var isPathValid = (path31) => checkPath(path31 && checkPath.convert(path31), path31, RETURN_FALSE);
factory.isPathValid = isPathValid;
factory.default = factory;
module2.exports = factory;
if (
// Detect `process` so that it can run in browsers.
typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")
) {
const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
checkPath.convert = makePosix;
const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
checkPath.isNotRelative = (path31) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path31) || isNotRelative(path31);
}
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js
var require_Mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js"(exports, module2) {
"use strict";
function Mime() {
this._types = /* @__PURE__ */ Object.create(null);
this._extensions = /* @__PURE__ */ Object.create(null);
for (let i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
Mime.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t) {
return t.toLowerCase();
});
type = type.toLowerCase();
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
if (ext[0] === "*") {
continue;
}
if (!force && ext in this._types) {
throw new Error(
'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
if (force || !this._extensions[type]) {
const ext = extensions[0];
this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1);
}
}
};
Mime.prototype.getType = function(path31) {
path31 = String(path31);
let last = path31.replace(/^.*[/\\]/, "").toLowerCase();
let ext = last.replace(/^.*\./, "").toLowerCase();
let hasPath = last.length < path31.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module2.exports = Mime;
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js
var require_standard = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js"(exports, module2) {
module2.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js
var require_other = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js"(exports, module2) {
module2.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js
var require_mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js"(exports, module2) {
"use strict";
var Mime = require_Mime();
module2.exports = new Mime(require_standard(), require_other());
}
});
// src/index.ts
var src_exports = {};
__export(src_exports, {
ASSETS_PLUGIN: () => ASSETS_PLUGIN,
AssetsOptionsSchema: () => AssetsOptionsSchema,
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,
DispatchFetchDispatcher: () => DispatchFetchDispatcher,
DurableObjectsOptionsSchema: () => DurableObjectsOptionsSchema,
DurableObjectsSharedOptionsSchema: () => DurableObjectsSharedOptionsSchema,
ErrorEvent: () => ErrorEvent,
File: () => import_undici4.File,
FormData: () => import_undici4.FormData,
HOST_CAPNP_CONNECT: () => HOST_CAPNP_CONNECT,
HYPERDRIVE_PLUGIN: () => HYPERDRIVE_PLUGIN,
HYPERDRIVE_PLUGIN_NAME: () => HYPERDRIVE_PLUGIN_NAME,
Headers: () => import_undici4.Headers,
HttpOptions_Style: () => HttpOptions_Style,
HyperdriveInputOptionsSchema: () => HyperdriveInputOptionsSchema,
HyperdriveSchema: () => HyperdriveSchema,
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: () => Miniflare2,
MiniflareCoreError: () => MiniflareCoreError,
MiniflareError: () => MiniflareError,
ModuleDefinitionSchema: () => ModuleDefinitionSchema,
ModuleRuleSchema: () => ModuleRuleSchema,
ModuleRuleTypeSchema: () => ModuleRuleTypeSchema,
Mutex: () => Mutex,
NoOpLog: () => NoOpLog,
PIPELINES_PLUGIN_NAME: () => PIPELINES_PLUGIN_NAME,
PIPELINE_PLUGIN: () => PIPELINE_PLUGIN,
PLUGINS: () => PLUGINS,
PLUGIN_ENTRIES: () => PLUGIN_ENTRIES,
PathSchema: () => PathSchema,
PeriodType: () => PeriodType,
PersistenceSchema: () => PersistenceSchema,
PipelineOptionsSchema: () => PipelineOptionsSchema,
ProxyAddresses: () => ProxyAddresses,
ProxyClient: () => ProxyClient,
ProxyNodeBinding: () => ProxyNodeBinding,
ProxyOps: () => ProxyOps,
QUEUES_PLUGIN: () => QUEUES_PLUGIN,
QUEUES_PLUGIN_NAME: () => QUEUES_PLUGIN_NAME,
QueueBindings: () => QueueBindings,
QueueConsumerOptionsSchema: () => QueueConsumerOptionsSchema,
QueueConsumerSchema: () => QueueConsumerSchema,
QueueConsumersSchema: () => QueueConsumersSchema,
QueueContentTypeSchema: () => QueueContentTypeSchema,
QueueIncomingMessageSchema: () => QueueIncomingMessageSchema,
QueueMessageDelaySchema: () => QueueMessageDelaySchema,
QueueProducerOptionsSchema: () => QueueProducerOptionsSchema,
QueueProducerSchema: () => QueueProducerSchema,
QueueProducersSchema: () => QueueProducersSchema,
QueuesBatchRequestSchema: () => QueuesBatchRequestSchema,
QueuesError: () => QueuesError,
QueuesOptionsSchema: () => QueuesOptionsSchema,
R2OptionsSchema: () => R2OptionsSchema,
R2SharedOptionsSchema: () => R2SharedOptionsSchema,
R2_PLUGIN: () => R2_PLUGIN,
R2_PLUGIN_NAME: () => R2_PLUGIN_NAME,
RATELIMIT_PLUGIN: () => RATELIMIT_PLUGIN,
RATELIMIT_PLUGIN_NAME: () => RATELIMIT_PLUGIN_NAME,
RatelimitConfigSchema: () => RatelimitConfigSchema,
RatelimitOptionsSchema: () => RatelimitOptionsSchema,
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,
SOCKET_ENTRY_LOCAL: () => SOCKET_ENTRY_LOCAL,
SharedBindings: () => SharedBindings,
SharedHeaders: () => SharedHeaders,
SiteBindings: () => SiteBindings,
SourceOptionsSchema: () => SourceOptionsSchema,
TlsOptions_Version: () => TlsOptions_Version,
TypedEventTarget: () => TypedEventTarget,
WORKER_BINDING_SERVICE_LOOPBACK: () => WORKER_BINDING_SERVICE_LOOPBACK,
WORKFLOWS_PLUGIN: () => WORKFLOWS_PLUGIN,
WORKFLOWS_PLUGIN_NAME: () => WORKFLOWS_PLUGIN_NAME,
WORKFLOWS_STORAGE_SERVICE_NAME: () => WORKFLOWS_STORAGE_SERVICE_NAME,
WaitGroup: () => WaitGroup,
WebSocket: () => WebSocket,
WebSocketPair: () => WebSocketPair,
Worker_Binding_CryptoKey_Usage: () => Worker_Binding_CryptoKey_Usage,
WorkflowsOptionsSchema: () => WorkflowsOptionsSchema,
WorkflowsSharedOptionsSchema: () => WorkflowsSharedOptionsSchema,
__MiniflareFunctionWrapper: () => __MiniflareFunctionWrapper,
_enableControlEndpoints: () => _enableControlEndpoints,
_forceColour: () => _forceColour,
_initialiseInstanceRegistry: () => _initialiseInstanceRegistry,
_isCyclic: () => _isCyclic,
_transformsForContentEncodingAndContentType: () => _transformsForContentEncodingAndContentType,
base64Decode: () => base64Decode,
base64Encode: () => base64Encode,
buildAssetManifest: () => buildAssetManifest,
compileModuleRules: () => compileModuleRules,
coupleWebSocket: () => coupleWebSocket,
createFetchMock: () => createFetchMock,
createHTTPReducers: () => createHTTPReducers,
createHTTPRevivers: () => createHTTPRevivers,
decodeSitesKey: () => decodeSitesKey,
deserialiseRegExps: () => deserialiseRegExps,
deserialiseSiteRegExps: () => deserialiseSiteRegExps,
encodeSitesKey: () => encodeSitesKey,
fetch: () => fetch3,
formatZodError: () => formatZodError,
getAccessibleHosts: () => getAccessibleHosts,
getAssetsBindingsNames: () => getAssetsBindingsNames,
getCacheServiceName: () => getCacheServiceName,
getDirectSocketName: () => getDirectSocketName,
getEntrySocketHttpOptions: () => getEntrySocketHttpOptions,
getFreshSourceMapSupport: () => getFreshSourceMapSupport,
getGlobalServices: () => getGlobalServices,
getMiniflareObjectBindings: () => getMiniflareObjectBindings,
getNodeCompat: () => getNodeCompat,
getPersistPath: () => getPersistPath,
getRootPath: () => getRootPath,
globsToRegExps: () => globsToRegExps,
isDurableObjectStub: () => isDurableObjectStub,
isFetcherFetch: () => isFetcherFetch,
isR2ObjectWriteHttpMetadata: () => isR2ObjectWriteHttpMetadata,
isSitesRequest: () => isSitesRequest,
kCurrentWorker: () => kCurrentWorker,
kInspectorSocket: () => kInspectorSocket,
kUnsafeEphemeralUniqueKey: () => kUnsafeEphemeralUniqueKey,
kVoid: () => kVoid,
matchRoutes: () => matchRoutes,
maybeApply: () => maybeApply,
maybeParseURL: () => maybeParseURL,
mergeWorkerOptions: () => mergeWorkerOptions,
migrateDatabase: () => migrateDatabase,
namespaceEntries: () => namespaceEntries,
namespaceKeys: () => namespaceKeys,
normaliseDurableObject: () => normaliseDurableObject,
objectEntryWorker: () => objectEntryWorker,
parseRanges: () => parseRanges,
parseRoutes: () => parseRoutes,
parseWithReadableStreams: () => parseWithReadableStreams,
parseWithRootPath: () => parseWithRootPath,
prefixError: () => prefixError,
prefixStream: () => prefixStream,
readPrefix: () => readPrefix,
reduceError: () => reduceError,
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_assert12 = __toESM(require("assert"));
var import_crypto3 = __toESM(require("crypto"));
var import_fs25 = __toESM(require("fs"));
var import_http6 = __toESM(require("http"));
var import_net = __toESM(require("net"));
var import_os2 = __toESM(require("os"));
var import_path29 = __toESM(require("path"));
var import_web5 = require("stream/web");
var import_util5 = __toESM(require("util"));
var import_zlib = __toESM(require("zlib"));
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js
var ANSI_BACKGROUND_OFFSET = 10;
var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
var wrapAnsi16m = (offset = 0) => (red3, green3, blue3) => `\x1B[${38 + offset};2;${red3};${green3};${blue3}m`;
var styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39],
// Alias of `blackBright`
grey: [90, 39],
// Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49],
// Alias of `bgBlackBright`
bgGrey: [100, 49],
// Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
var modifierNames = Object.keys(styles.modifier);
var foregroundColorNames = Object.keys(styles.color);
var backgroundColorNames = Object.keys(styles.bgColor);
var colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, "codes", {
value: codes,
enumerable: false
});
styles.color.close = "\x1B[39m";
styles.bgColor.close = "\x1B[49m";
styles.color.ansi = wrapAnsi16();
styles.color.ansi256 = wrapAnsi256();
styles.color.ansi16m = wrapAnsi16m();
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
Object.defineProperties(styles, {
rgbToAnsi256: {
value(red3, green3, blue3) {
if (red3 === green3 && green3 === blue3) {
if (red3 < 8) {
return 16;
}
if (red3 > 248) {
return 231;
}
return Math.round((red3 - 8) / 247 * 24) + 232;
}
return 16 + 36 * Math.round(red3 / 255 * 5) + 6 * Math.round(green3 / 255 * 5) + Math.round(blue3 / 255 * 5);
},
enumerable: false
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map((character) => character + character).join("");
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
integer >> 16 & 255,
integer >> 8 & 255,
integer & 255
/* eslint-enable no-bitwise */
];
},
enumerable: false
},
hexToAnsi256: {
value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
enumerable: false
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red3;
let green3;
let blue3;
if (code >= 232) {
red3 = ((code - 232) * 10 + 8) / 255;
green3 = red3;
blue3 = red3;
} else {
code -= 16;
const remainder = code % 36;
red3 = Math.floor(code / 36) / 5;
green3 = Math.floor(remainder / 6) / 5;
blue3 = remainder % 6 / 5;
}
const value = Math.max(red3, green3, blue3) * 2;
if (value === 0) {
return 30;
}
let result = 30 + (Math.round(blue3) << 2 | Math.round(green3) << 1 | Math.round(red3));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false
},
rgbToAnsi: {
value: (red3, green3, blue3) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red3, green3, blue3)),
enumerable: false
},
hexToAnsi: {
value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
enumerable: false
}
});
return styles;
}
var ansiStyles = assembleStyles();
var ansi_styles_default = ansiStyles;
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js
var import_node_process = __toESM(require("node:process"), 1);
var import_node_os = __toESM(require("node:os"), 1);
var import_node_tty = __toESM(require("node:tty"), 1);
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
var { env } = import_node_process.default;
var flagForceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
flagForceColor = 1;
}
function envForceColor() {
if ("FORCE_COLOR" in env) {
if (env.FORCE_COLOR === "true") {
return 1;
}
if (env.FORCE_COLOR === "false") {
return 0;
}
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== void 0) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
}
if ("TF_BUILD" in env && "AGENT_NAME" in env) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (import_node_process.default.platform === "win32") {
const osRelease = import_node_os.default.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env) {
if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
return 3;
}
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if (env.TERM === "xterm-kitty") {
return 3;
}
if ("TERM_PROGRAM" in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env.TERM_PROGRAM) {
case "iTerm.app": {
return version >= 3 ? 3 : 2;
}
case "Apple_Terminal": {
return 2;
}
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ("COLORTERM" in env) {
return 1;
}
return min;
}
function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options
});
return translateLevel(level);
}
var supportsColor = {
stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
};
var supports_color_default = supportsColor;
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring, replacer) {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = "";
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = "";
do {
const gotCR = string[index - 1] === "\r";
returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
endIndex = index + 1;
index = string.indexOf("\n", endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js
var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
var GENERATOR = Symbol("GENERATOR");
var STYLER = Symbol("STYLER");
var IS_EMPTY = Symbol("IS_EMPTY");
var levelMapping = [
"ansi",
"ansi",
"ansi256",
"ansi16m"
];
var styles2 = /* @__PURE__ */ Object.create(null);
var applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error("The `level` option should be an integer from 0 to 3");
}
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === void 0 ? colorLevel : options.level;
};
var chalkFactory = (options) => {
const chalk2 = (...strings) => strings.join(" ");
applyOptions(chalk2, options);
Object.setPrototypeOf(chalk2, createChalk.prototype);
return chalk2;
};
function createChalk(options) {
return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
styles2[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
Object.defineProperty(this, styleName, { value: builder });
return builder;
}
};
}
styles2.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, "visible", { value: builder });
return builder;
}
};
var getModelAnsi = (model, level, type, ...arguments_) => {
if (model === "rgb") {
if (level === "ansi16m") {
return ansi_styles_default[type].ansi16m(...arguments_);
}
if (level === "ansi256") {
return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
}
return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
}
if (model === "hex") {
return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
}
return ansi_styles_default[type][model](...arguments_);
};
var usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
styles2[model] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
styles2[bgModel] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
}
var proto = Object.defineProperties(() => {
}, {
...styles2,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
}
}
});
var createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === void 0) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
var createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
Object.setPrototypeOf(builder, proto);
builder[GENERATOR] = self;
builder[STYLER] = _styler;
builder[IS_EMPTY] = _isEmpty;
return builder;
};
var applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self[IS_EMPTY] ? "" : string;
}
let styler = self[STYLER];
if (styler === void 0) {
return string;
}
const { openAll, closeAll } = styler;
if (string.includes("\x1B")) {
while (styler !== void 0) {
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
const lfIndex = string.indexOf("\n");
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles2);
var chalk = createChalk();
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
var source_default = chalk;
// ../cli/colors.ts
var { white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default;
var brandColor = source_default.hex("#BD5B08");
var black = source_default.hex("#111");
var blue = source_default.hex("#0E838F");
var bgBlue = black.bgHex("#0E838F");
var red = source_default.hex("#AB2526");
var bgRed = black.bgHex("#AB2526");
var green = source_default.hex("#218529");
var bgGreen = black.bgHex("#218529");
var yellow = source_default.hex("#7F7322");
var bgYellow = black.bgHex("#7F7322");
// ../cli/streams.ts
var stdout = process.stdout;
var stderr = process.stderr;
// ../cli/check-macos-version.ts
var import_node_os2 = __toESM(require("node:os"));
var MINIMUM_MACOS_VERSION = "13.5.0";
function checkMacOSVersion(options) {
if (process.platform !== "darwin") {
return;
}
if (process.env.CI) {
return;
}
const release = import_node_os2.default.release();
const macOSVersion = darwinVersionToMacOSVersion(release);
if (macOSVersion && isVersionLessThan(macOSVersion, MINIMUM_MACOS_VERSION)) {
if (options.shouldThrow) {
throw new Error(
`Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (${macOSVersion}). The minimum requirement is macOS ${MINIMUM_MACOS_VERSION}+. See https://github.com/cloudflare/workerd?tab=readme-ov-file#running-workerd If you cannot upgrade your version of macOS, you could try running in a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`
);
} else {
console.warn(
`\u26A0\uFE0F Warning: Unsupported macOS version detected (${macOSVersion}). The Cloudflare Workers runtime may not work correctly on macOS versions below ${MINIMUM_MACOS_VERSION}. Consider upgrading to macOS ${MINIMUM_MACOS_VERSION}+ or using a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`
);
}
}
}
function darwinVersionToMacOSVersion(darwinVersion) {
const match = darwinVersion.match(/^(\d+)\.(\d+)\.(\d+)/);
if (!match) {
return null;
}
const major = parseInt(match[1], 10);
if (major >= 20) {
const macOSMajor = major - 9;
const minor = parseInt(match[2], 10);
const patch = parseInt(match[3], 10);
return `${macOSMajor}.${minor}.${patch}`;
}
return null;
}
function isVersionLessThan(version1, version2) {
const versionRegex = /^(\d+)\.(\d+)\.(\d+)$/;
const match1 = version1.match(versionRegex);
const match2 = version2.match(versionRegex);
if (!match1 || !match2) {
throw new Error(
`Invalid version format. Expected M.m.p format, got: ${version1}, ${version2}`
);
}
const [major1, minor1, patch1] = [
parseInt(match1[1], 10),
parseInt(match1[2], 10),
parseInt(match1[3], 10)
];
const [major2, minor2, patch2] = [
parseInt(match2[1], 10),
parseInt(match2[2], 10),
parseInt(match2[3], 10)
];
if (major1 !== major2) {
return major1 < major2;
}
if (minor1 !== minor2) {
return minor1 < minor2;
}
return patch1 < patch2;
}
// ../cli/index.ts
var status = {
error: bgRed(` ERROR `),
warning: bgYellow(` WARNING `),
info: bgBlue(` INFO `),
success: bgGreen(` SUCCESS `),
cancel: white.bgRed(` X `)
};
// src/index.ts
var import_exit_hook = __toESM(require("exit-hook"));
// ../../node_modules/.pnpm/kleur@4.1.5/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 bold2 = init(1, 22);
var dim2 = init(2, 22);
var italic = init(3, 23);
var underline = init(4, 24);
var inverse = init(7, 27);
var hidden2 = init(8, 28);
var strikethrough = init(9, 29);
var black2 = init(30, 39);
var red2 = init(31, 39);
var green2 = init(32, 39);
var yellow2 = init(33, 39);
var blue2 = init(34, 39);
var magenta = init(35, 39);
var cyan = init(36, 39);
var white2 = init(37, 39);
var gray2 = init(90, 39);
var grey = init(90, 39);
var bgBlack = init(40, 49);
var bgRed2 = init(41, 49);
var bgGreen2 = init(42, 49);
var bgYellow2 = init(43, 49);
var bgBlue2 = init(44, 49);
var bgMagenta = init(45, 49);
var bgCyan2 = init(46, 49);
var bgWhite = init(47, 49);
// src/index.ts
var import_stoppable = __toESM(require("stoppable"));
var import_undici8 = require("undici");
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/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/runner/work/workers-sdk/workers-sdk/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;
}
// src/index.ts
var import_ws3 = require("ws");
var import_zod23 = require("zod");
// 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" + dim2(e.cause ? e.cause.stack : e.stack)
);
return fallbackCf;
}
}
// src/http/fetch.ts
var undici = __toESM(require("undici"));
var import_ws2 = __toESM(require("ws"));
// 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"
};
// src/workers/core/constants.ts
var CoreHeaders = {
CUSTOM_SERVICE: "MF-Custom-Service",
ORIGINAL_URL: "MF-Original-URL",
PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret",
DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error",
ERROR_STACK: "MF-Experimental-Error-Stack",
ROUTE_OVERRIDE: "MF-Route-Override",
CF_BLOB: "MF-CF-Blob",
// API Proxy
OP_SECRET: "MF-Op-Secret",
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",
DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET",
DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET"
};
var ProxyOps = {
// Get the target or a property of the target
GET: "GET",
// Get the descriptor for a property of the target
GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR",
// Get the target's own property names
GET_OWN_KEYS: "GET_OWN_KEYS",
// 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" || targetName === "WorkerRpc") && key === "fetch";
}
function isR2ObjectWriteHttpMetadata(targetName, key) {
return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata";
}
function isDurableObjectStub(targetName) {
return targetName === "DurableObject" || targetName === "WorkerRpc";
}
// src/workers/core/devalue.ts
var import_node_assert = __toESM(require("node:assert"));
var import_node_buffer = require("node:buffer");
// ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/utils.js
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 = /* @__PURE__ */ Object.getOwnPropertyNames(
Object.prototype
).sort().join("\0");
function is_plain_object(thing) {
const proto2 = Object.getPrototypeOf(thing);
return proto2 === Object.prototype || proto2 === null || Object.getPrototypeOf(proto2) === null || Object.getOwnPropertyNames(proto2).sort().join("\0") === object_proto_names;
}
function get_type(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function get_escaped_char(char) {
switch (char) {
case '"':
return '\\"';
case "<":
return "\\u003C";
case "\\":
return "\\\\";
case "\n":
return "\\n";
case "\r":
return "\\r";
case " ":
return "\\t";
case "\b":
return "\\b";
case "\f":
return "\\f";
case "\u2028":
return "\\u2028";
case "\u2029":
return "\\u2029";
default:
return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
}
}
function stringify_string(str) {
let result = "";
let last_pos = 0;
const len = str.length;
for (let i = 0; i < len; i += 1) {
const char = str[i];
const replacement = get_escaped_char(char);
if (replacement) {
result += str.slice(last_pos, i) + replacement;
last_pos = i + 1;
}
}
return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
}
function enumerable_symbols(object) {
return Object.getOwnPropertySymbols(object).filter(
(symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable
);
}
var is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
function stringify_key(key) {
return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
}
// ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/base64.js
function encode64(arraybuffer) {
const dv = new DataView(arraybuffer);
let binaryString = "";
for (let i = 0; i < arraybuffer.byteLength; i++) {
binaryString += String.fromCharCode(dv.getUint8(i));
}
return binaryToAscii(binaryString);
}
function decode64(string) {
const binaryString = asciiToBinary(string);
const arraybuffer = new ArrayBuffer(binaryString.length);
const dv = new DataView(arraybuffer);
for (let i = 0; i < arraybuffer.byteLength; i++) {
dv.setUint8(i, binaryString.charCodeAt(i));
}
return arraybuffer;
}
var KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function asciiToBinary(data) {
if (data.length % 4 === 0) {
data = data.replace(/==?$/, "");
}
let output = "";
let buffer = 0;
let accumulatedBits = 0;
for (let i = 0; i < data.length; i++) {
buffer <<= 6;
buffer |= KEY_STRING.indexOf(data[i]);
accumulatedBits += 6;
if (accumulatedBits === 24) {
output += String.fromCharCode((buffer & 16711680) >> 16);
output += String.fromCharCode((buffer & 65280) >> 8);
output += String.fromCharCode(buffer & 255);
buffer = accumulatedBits = 0;
}
}
if (accumulatedBits === 12) {
buffer >>= 4;
output += String.fromCharCode(buffer);
} else if (accumulatedBits === 18) {
buffer >>= 2;
output += String.fromCharCode((buffer & 65280) >> 8);
output += String.fromCharCode(buffer & 255);
}
return output;
}
function binaryToAscii(str) {
let out = "";
for (let i = 0; i < str.length; i += 3) {
const groupsOfSix = [void 0, void 0, void 0, void 0];
groupsOfSix[0] = str.charCodeAt(i) >> 2;
groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4;
if (str.length > i + 1) {
groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4;
groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2;
}
if (str.length > i + 2) {
groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6;
groupsOfSix[3] = str.charCodeAt(i + 2) & 63;
}
for (let j = 0; j < groupsOfSix.length; j++) {
if (typeof groupsOfSix[j] === "undefined") {
out += "=";
} else {
out += KEY_STRING[groupsOfSix[j]];
}
}
}
return out;
}
// ../../node_modules/.pnpm/devalue@5.3.2/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/.pnpm/devalue@5.3.2/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 || typeof index !== "number") {
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;
case "Int8Array":
case "Uint8Array":
case "Uint8ClampedArray":
case "Int16Array":
case "Uint16Array":
case "Int32Array":
case "Uint32Array":
case "Float32Array":
case "Float64Array":
case "BigInt64Array":
case "BigUint64Array": {
const TypedArrayConstructor = globalThis[type];
const typedArray = new TypedArrayConstructor(hydrate(value[1]));
hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray;
break;
}
case "ArrayBuffer": {
const base64 = value[1];
const arraybuffer = decode64(base64);
hydrated[index] = arraybuffer;
break;
}
case "Temporal.Duration":
case "Temporal.Instant":
case "Temporal.PlainDate":
case "Temporal.PlainTime":
case "Temporal.PlainDateTime":
case "Temporal.PlainMonthDay":
case "Temporal.PlainYearMonth":
case "Temporal.ZonedDateTime": {
const temporalName = type.slice(9);
hydrated[index] = Temporal[temporalName].from(value[1]);
break;
}
case "URL": {
const url21 = new URL(value[1]);
hydrated[index] = url21;
break;
}
case "URLSearchParams": {
const url21 = new URLSearchParams(value[1]);
hydrated[index] = url21;
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) {
if (key === "__proto__") {
throw new Error("Cannot parse an object with a `__proto__` property");
}
const n = value[key];
object[key] = hydrate(n);
}
}
return hydrated[index];
}
return hydrate(0);
}
// ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/stringify.js
function stringify(value, reducers2) {
const stringified = [];
const indexes = /* @__PURE__ */ new Map();
const custom = [];
if (reducers2) {
for (const key of Object.getOwnPropertyNames(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 (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;
if (indexes.has(thing))
return indexes.get(thing);
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":
const valid = !isNaN(thing.getDate());
str = `["Date","${valid ? thing.toISOString() : ""}"]`;
break;
case "URL":
str = `["URL",${stringify_string(thing.toString())}]`;
break;
case "URLSearchParams":
str = `["URLSearchParams",${stringify_string(thing.toString())}]`;
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)}`;
keys.pop();
}
str += "]";
break;
case "Int8Array":
case "Uint8Array":
case "Uint8ClampedArray":
case "Int16Array":
case "Uint16Array":
case "Int32Array":
case "Uint32Array":
case "Float32Array":
case "Float64Array":
case "BigInt64Array":
case "BigUint64Array": {
const typedArray = thing;
str = '["' + type + '",' + flatten(typedArray.buffer);
const a = thing.byteOffset;
const b = a + thing.byteLength;
if (a > 0 || b !== typedArray.buffer.byteLength) {
const m = +/(\d+)/.exec(type)[1] / 8;
str += `,${a / m},${b / m}`;
}
str += "]";
break;
}
case "ArrayBuffer": {
const arraybuffer = thing;
const base64 = encode64(arraybuffer);
str = `["ArrayBuffer","${base64}"]`;
break;
}
case "Temporal.Duration":
case "Temporal.Instant":
case "Temporal.PlainDate":
case "Temporal.PlainTime":
case "Temporal.PlainDateTime":
case "Temporal.PlainMonthDay":
case "Temporal.PlainYearMonth":
case "Temporal.ZonedDateTime":
str = `["${type}",${stringify_string(thing.toString())}]`;
break;
default:
if (!is_plain_object(thing)) {
throw new DevalueError(
`Cannot stringify arbitrary non-POJOs`,
keys
);
}
if (enumerable_symbols(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(stringify_key(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(stringify_key(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);
}
// 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
];
}
},
RegExp(value) {
if (value instanceof RegExp) {
const { source, flags } = value;
const encoded = import_node_buffer.Buffer.from(source).toString("base64");
return flags ? ["RegExp", encoded, flags] : ["RegExp", encoded];
}
},
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);
},
RegExp(value) {
(0, import_node_assert.default)(Array.isArray(value));
const [name, encoded, flags] = value;
(0, import_node_assert.default)(typeof name === "string");
(0, import_node_assert.default)(typeof encoded === "string");
const source = import_node_buffer.Buffer.from(encoded, "base64").toString("utf-8");
return new RegExp(source, flags);
},
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 [...val.entries()];
},
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, url21, headers, cf, body] = value;
(0, import_node_assert.default)(typeof method === "string");
(0, import_node_assert.default)(typeof url21 === "string");
(0, import_node_assert.default)(headers instanceof impl.Headers);
(0, import_node_assert.default)(body === null || impl.isReadableStream(body));
return new impl.Request(url21, {
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 [status2, statusText, headers, cf, body] = value;
(0, import_node_assert.default)(typeof status2 === "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: status2,
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
};
if (typeof value === "function") {
value = new __MiniflareFunctionWrapper(
value
);
}
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 };
});
}
var __MiniflareFunctionWrapper = class {
constructor(fnWithProps) {
return new Proxy(this, {
get: (_, key) => {
if (key === "__miniflareWrappedFunction")
return fnWithProps;
return fnWithProps[key];
}
});
}
};
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);
}
// src/workers/core/routing.ts
function matchRoutes(routes, url21) {
for (const route of routes) {
if (route.protocol && route.protocol !== url21.protocol)
continue;
if (route.allowHostnamePrefix) {
if (!url21.hostname.endsWith(route.hostname))
continue;
} else {
if (url21.hostname !== route.hostname)
continue;
}
const path31 = url21.pathname + url21.search;
if (route.allowPathSuffix) {
if (!path31.startsWith(route.path))
continue;
} else {
if (path31 !== route.path)
continue;
}
return route.target;
}
return null;
}
// 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",
MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS",
MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS"
};
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 || {});
// 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);
}
// 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;
}
// 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;
}
// 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((resolve2, reject) => {
promiseResolve = resolve2;
promiseReject = reject;
return executor(resolve2, 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((resolve2) => this.resolveQueue.push(resolve2));
}
unlock() {
(0, import_node_assert2.default)(this.locked);
if (this.resolveQueue.length > 0) {
this.resolveQueue.shift()?.();
} else {
this.locked = false;
let resolve2;
while ((resolve2 = this.drainQueue.shift()) !== void 0)
resolve2();
}
}
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 && !this.locked)
return;
return new Promise((resolve2) => this.drainQueue.push(resolve2));
}
};
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 resolve2;
while ((resolve2 = this.resolveQueue.shift()) !== void 0)
resolve2();
}
}
wait() {
if (this.counter === 0)
return Promise.resolve();
return new Promise((resolve2) => this.resolveQueue.push(resolve2));
}
};
// 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);
}
// 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 url21 = new URL(request.url);
return url21.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;
}
function getAssetsBindingsNames(assetsKVBindingName = "__STATIC_ASSETS_CONTENT", assetsManifestBindingName = "__STATIC_ASSETS_CONTENT_MANIFEST") {
return {
ASSETS_KV_NAMESPACE: assetsKVBindingName,
ASSETS_MANIFEST: assetsManifestBindingName
};
}
// src/workers/queues/constants.ts
var QueueBindings = {
SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_",
MAYBE_JSON_QUEUE_PRODUCERS: "MINIFLARE_QUEUE_PRODUCERS",
MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS"
};
// 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"));
// src/workers/queues/schemas.ts
var QueueMessageDelaySchema = import_zod2.z.number().int().min(0).max(43200).optional();
var QueueProducerOptionsSchema = /* @__PURE__ */ import_zod2.z.object({
// https://developers.cloudflare.com/queues/platform/configuration/#producer
queueName: import_zod2.z.string(),
deliveryDelay: QueueMessageDelaySchema
});
var QueueProducerSchema = /* @__PURE__ */ import_zod2.z.intersection(
QueueProducerOptionsSchema,
import_zod2.z.object({ workerName: import_zod2.z.string() })
);
var QueueProducersSchema = /* @__PURE__ */ import_zod2.z.record(QueueProducerSchema);
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(60).optional(),
// seconds
maxRetires: import_zod2.z.number().min(0).max(100).optional(),
// deprecated
maxRetries: import_zod2.z.number().min(0).max(100).optional(),
deadLetterQueue: import_zod2.z.ostring(),
retryDelay: QueueMessageDelaySchema
}).transform((queue) => {
if (queue.maxRetires !== void 0) {
queue.maxRetries = queue.maxRetires;
}
return queue;
});
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,
delaySecs: QueueMessageDelaySchema,
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)
});
// 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;
}
};
// 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(url21, status2) {
const response = import_undici3.Response.redirect(url21, status2);
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;
}
};
// src/http/websocket.ts
var import_assert3 = __toESM(require("assert"));
var import_events = require("events");
var import_ws = __toESM(require("ws"));
// src/shared/colour.ts
var originalEnabled = $.enabled;
function _forceColour(enabled = originalEnabled) {
$.enabled = enabled;
}
// 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 {
};
// 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);
}
};
// 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 */]: red2,
[2 /* WARN */]: yellow2,
[3 /* INFO */]: green2,
[4 /* DEBUG */]: grey,
[5 /* VERBOSE */]: (input) => dim2(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 dim2(line);
}
return line;
}
var _prefix, _suffix, _beforeLogHook, _afterLogHook;
var _Log = class {
constructor(level = 3 /* INFO */, opts = {}) {
this.level = level;
__privateAdd(this, _prefix, void 0);
__privateAdd(this, _suffix, void 0);
const prefix = opts.prefix ?? "mf";
const suffix = opts.suffix ?? "";
__privateSet(this, _prefix, prefix ? prefix + ":" : "");
__privateSet(this, _suffix, suffix ? ":" + suffix : "");
}
log(message) {
var _a2, _b2;
(_a2 = __privateGet(_Log, _beforeLogHook)) == null ? void 0 : _a2.call(_Log);
console.log(message);
(_b2 = __privateGet(_Log, _afterLogHook)) == null ? void 0 : _b2.call(_Log);
}
static unstable_registerBeforeLogHook(callback) {
__privateSet(this, _beforeLogHook, callback);
}
static unstable_registerAfterLogHook(callback) {
__privateSet(this, _afterLogHook, callback);
}
logWithLevel(level, message) {
if (level <= this.level) {
const prefix = `[${__privateGet(this, _prefix)}${LEVEL_PREFIX[level]}${__privateGet(this, _suffix)}]`;
this.log(LEVEL_COLOUR[level](`${prefix} ${message}`));
}
}
error(message) {
if (this.level < 1 /* ERROR */) {
} 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 Log = _Log;
_prefix = new WeakMap();
_suffix = new WeakMap();
_beforeLogHook = new WeakMap();
_afterLogHook = new WeakMap();
__privateAdd(Log, _beforeLogHook, void 0);
__privateAdd(Log, _afterLogHook, void 0);
var NoOpLog = class extends Log {
constructor() {
super(0 /* NONE */);
}
log() {
}
error(_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, "");
}
// 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 };
}
// 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];
}
// src/shared/types.ts
var import_assert2 = __toESM(require("assert"));
var import_path5 = __toESM(require("path"));
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)])
);
var rootPath;
function parseWithRootPath(newRootPath, schema, data, params) {
rootPath = newRootPath;
try {
return schema.parse(data, params);
} finally {
rootPath = void 0;
}
}
var PathSchema = import_zod3.z.string().transform((p) => {
(0, import_assert2.default)(
rootPath !== void 0,
"Expected `PathSchema` to be parsed within `parseWithRootPath()`"
);
return import_path5.default.resolve(rootPath, p);
});
function _isCyclic(value, seen = /* @__PURE__ */ new Set()) {
if (typeof value !== "object" || value === null)
return false;
for (const child of Object.values(value)) {
if (seen.has(child))
return true;
seen.add(child);
if (_isCyclic(child, seen))
return true;
seen.delete(child);
}
return false;
}
// 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_assert3.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_assert3.default)(pair !== void 0);
if (pair[kAccepted]) {
pair.dispatchEvent(event);
} else {
(0, import_assert3.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;
}
// src/http/fetch.ts
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 undici.Headers(Object.fromEntries(entries));
}
async function fetch3(input, init2) {
const requestInit = init2;
const request = new Request(input, requestInit);
if (request.method === "GET" && request.headers.get("upgrade") === "websocket") {
const url21 = new URL(request.url);
if (url21.protocol !== "http:" && url21.protocol !== "https:") {
throw new TypeError(
`Fetch API cannot load: ${url21.toString()}.
Make sure you're using http(s):// URLs for WebSocket requests via fetch.`
);
}
url21.protocol = url21.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;
}
}
let rejectUnauthorized;
if (requestInit.dispatcher instanceof DispatchFetchDispatcher) {
requestInit.dispatcher.addHeaders(headers, url21.pathname + url21.search);
rejectUnauthorized = { rejectUnauthorized: false };
}
const ws = new import_ws2.default(url21, protocols, {
followRedirects: request.redirect === "follow",
headers,
...rejectUnauthorized
});
const responsePromise = new DeferredPromise();
ws.once("upgrade", (req) => {
const headers2 = headersFromIncomingRequest(req);
const [worker, client] = Object.values(new WebSocketPair());
const couplePromise = coupleWebSocket(ws, client);
const response2 = new Response(null, {
status: 101,
webSocket: worker,
headers: headers2
});
responsePromise.resolve(couplePromise.then(() => response2));
});
ws.once("unexpected-response", (_, req) => {
const headers2 = headersFromIncomingRequest(req);
const response2 = new Response(req, {
status: req.statusCode,
headers: headers2
});
responsePromise.resolve(response2);
});
return responsePromise;
}
const response = await undici.fetch(request, {
dispatcher: requestInit?.dispatcher
});
return new Response(response.body, response);
}
function addHeader(headers, key, value) {
if (Array.isArray(headers))
headers.push(key, value);
else
headers[key] = value;
}
var DispatchFetchDispatcher = class extends undici.Dispatcher {
/**
* @param globalDispatcher Dispatcher to use for all non-runtime requests
* (rejects unauthorised certificates)
* @param runtimeDispatcher Dispatcher to use for runtime requests
* (permits unauthorised certificates)
* @param actualRuntimeOrigin Origin to send all runtime requests to
* @param userRuntimeOrigin Origin to treat as runtime request
* (initial URL passed by user to `dispatchFetch()`)
* @param cfBlob `request.cf` blob override for runtime requests
*/
constructor(globalDispatcher, runtimeDispatcher, actualRuntimeOrigin, userRuntimeOrigin, cfBlob) {
super();
this.globalDispatcher = globalDispatcher;
this.runtimeDispatcher = runtimeDispatcher;
this.actualRuntimeOrigin = actualRuntimeOrigin;
this.userRuntimeOrigin = userRuntimeOrigin;
if (cfBlob !== void 0)
this.cfBlobJson = JSON.stringify(cfBlob);
}
cfBlobJson;
addHeaders(headers, path31) {
const originalURL = this.userRuntimeOrigin + path31;
addHeader(headers, CoreHeaders.ORIGINAL_URL, originalURL);
addHeader(headers, CoreHeaders.DISABLE_PRETTY_ERROR, "true");
if (this.cfBlobJson !== void 0) {
addHeader(headers, CoreHeaders.CF_BLOB, this.cfBlobJson);
}
}
dispatch(options, handler) {
let origin = String(options.origin);
if (origin === this.userRuntimeOrigin)
origin = this.actualRuntimeOrigin;
if (origin === this.actualRuntimeOrigin) {
options.origin = origin;
let path31 = options.path;
if (options.query !== void 0) {
const url21 = new URL(path31, "http://placeholder/");
for (const [key, value] of Object.entries(options.query)) {
url21.searchParams.append(key, value);
}
path31 = url21.pathname + url21.search;
}
options.headers ??= {};
this.addHeaders(options.headers, path31);
return this.runtimeDispatcher.dispatch(options, handler);
} else {
return this.globalDispatcher.dispatch(options, handler);
}
}
async close(callback) {
await Promise.all([
this.globalDispatcher.close(),
this.runtimeDispatcher.close()
]);
callback?.();
}
async destroy(errCallback, callback) {
let err = null;
if (typeof errCallback === "function")
callback = errCallback;
if (errCallback instanceof Error)
err = errCallback;
await Promise.all([
this.globalDispatcher.destroy(err),
this.runtimeDispatcher.destroy(err)
]);
callback?.();
}
get isMockActive() {
return this.globalDispatcher.isMockActive ?? false;
}
};
// src/http/server.ts
var import_promises2 = __toESM(require("fs/promises"));
// 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-----
`;
// src/http/server.ts
async function getEntrySocketHttpOptions(coreOpts) {
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;
}
if (privateKey && certificateChain) {
return {
https: {
tlsOptions: {
keypair: {
privateKey,
certificateChain
}
}
}
};
} else {
return { http: {} };
}
}
function valueOrFile(value, filePath) {
return value ?? (filePath && import_promises2.default.readFile(filePath, "utf8"));
}
// 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) {
hosts.push(address);
}
});
});
return hosts;
}
// src/http/index.ts
var import_undici4 = require("undici");
// src/plugins/assets/index.ts
var import_node_crypto = __toESM(require("node:crypto"));
var import_promises7 = __toESM(require("node:fs/promises"));
var import_node_path3 = __toESM(require("node:path"));
// ../workers-shared/utils/constants.ts
var HEADER_SIZE = 20;
var PATH_HASH_SIZE = 16;
var CONTENT_HASH_SIZE = 16;
var TAIL_SIZE = 8;
var PATH_HASH_OFFSET = 0;
var CONTENT_HASH_OFFSET = PATH_HASH_SIZE;
var ENTRY_SIZE = PATH_HASH_SIZE + CONTENT_HASH_SIZE + TAIL_SIZE;
var MAX_ASSET_COUNT = 2e4;
var MAX_ASSET_SIZE = 25 * 1024 * 1024;
var CF_ASSETS_IGNORE_FILENAME = ".assetsignore";
var REDIRECTS_FILENAME = "_redirects";
var HEADERS_FILENAME = "_headers";
// ../workers-shared/utils/types.ts
var import_zod4 = require("zod");
var InternalConfigSchema = import_zod4.z.object({
account_id: import_zod4.z.number().optional(),
script_id: import_zod4.z.number().optional()
});
var RouterConfigSchema = import_zod4.z.object({
invoke_user_worker_ahead_of_assets: import_zod4.z.boolean().optional(),
has_user_worker: import_zod4.z.boolean().optional(),
...InternalConfigSchema.shape
});
var MetadataStaticRedirectEntry = import_zod4.z.object({
status: import_zod4.z.number(),
to: import_zod4.z.string(),
lineNumber: import_zod4.z.number()
});
var MetadataRedirectEntry = import_zod4.z.object({
status: import_zod4.z.number(),
to: import_zod4.z.string()
});
var MetadataStaticRedirects = import_zod4.z.record(MetadataStaticRedirectEntry);
var MetadataRedirects = import_zod4.z.record(MetadataRedirectEntry);
var MetadataHeaderEntry = import_zod4.z.object({
set: import_zod4.z.record(import_zod4.z.string()).optional(),
unset: import_zod4.z.array(import_zod4.z.string()).optional()
});
var MetadataHeaders = import_zod4.z.record(MetadataHeaderEntry);
var RedirectsSchema = import_zod4.z.object({
version: import_zod4.z.literal(1),
staticRules: MetadataStaticRedirects,
rules: MetadataRedirects
}).optional();
var HeadersSchema = import_zod4.z.object({
version: import_zod4.z.literal(2),
rules: MetadataHeaders
}).optional();
var AssetConfigSchema = import_zod4.z.object({
compatibility_date: import_zod4.z.string().optional(),
compatibility_flags: import_zod4.z.array(import_zod4.z.string()).optional(),
html_handling: import_zod4.z.enum([
"auto-trailing-slash",
"force-trailing-slash",
"drop-trailing-slash",
"none"
]).optional(),
not_found_handling: import_zod4.z.enum(["single-page-application", "404-page", "none"]).optional(),
redirects: RedirectsSchema,
headers: HeadersSchema,
...InternalConfigSchema.shape
});
// ../workers-shared/utils/helpers.ts
var import_node_fs = require("node:fs");
var import_node_path = require("node:path");
var import_ignore = __toESM(require_ignore());
var import_mime = __toESM(require_mime());
var normalizeFilePath = (relativeFilepath) => {
if ((0, import_node_path.isAbsolute)(relativeFilepath)) {
throw new Error(`Expected relative path`);
}
return "/" + relativeFilepath.split(import_node_path.sep).join("/");
};
var getContentType = (absFilePath) => {
let contentType = (0, import_mime.getType)(absFilePath);
if (contentType && contentType.startsWith("text/") && !contentType.includes("charset")) {
contentType = `${contentType}; charset=utf-8`;
}
return contentType;
};
function createPatternMatcher(patterns, exclude) {
if (patterns.length === 0) {
return (_filePath) => !exclude;
} else {
const ignorer = (0, import_ignore.default)().add(patterns);
return (filePath) => ignorer.test(filePath).ignored;
}
}
function thrownIsDoesNotExistError(thrown) {
return thrown instanceof Error && "code" in thrown && thrown.code === "ENOENT";
}
function maybeGetFile(filePath) {
try {
return (0, import_node_fs.readFileSync)(filePath, "utf8");
} catch (e) {
if (!thrownIsDoesNotExistError(e)) {
throw e;
}
}
}
async function createAssetsIgnoreFunction(dir) {
const cfAssetIgnorePath = (0, import_node_path.resolve)(dir, CF_ASSETS_IGNORE_FILENAME);
const ignorePatterns = [
// Ignore the `.assetsignore` file and other metafiles by default.
// The ignore lib expects unix-style paths for its patterns
`/${CF_ASSETS_IGNORE_FILENAME}`,
`/${REDIRECTS_FILENAME}`,
`/${HEADERS_FILENAME}`
];
let assetsIgnoreFilePresent = false;
const assetsIgnore = maybeGetFile(cfAssetIgnorePath);
if (assetsIgnore !== void 0) {
assetsIgnoreFilePresent = true;
ignorePatterns.push(...assetsIgnore.split("\n"));
}
return {
assetsIgnoreFunction: createPatternMatcher(ignorePatterns, true),
assetsIgnoreFilePresent
};
}
// ../workers-shared/utils/configuration/constructConfiguration.ts
var import_node_path2 = require("node:path");
// ../workers-shared/utils/configuration/constants.ts
var REDIRECTS_VERSION = 1;
var HEADERS_VERSION = 2;
var PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([200, 301, 302, 303, 307, 308]);
var HEADER_SEPARATOR = ":";
var MAX_LINE_LENGTH = 2e3;
var MAX_HEADER_RULES = 100;
var MAX_DYNAMIC_REDIRECT_RULES = 100;
var MAX_STATIC_REDIRECT_RULES = 2e3;
var UNSET_OPERATOR = "! ";
var SPLAT_REGEX = /\*/g;
var PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
// ../workers-shared/utils/configuration/constructConfiguration.ts
function constructRedirects({
redirects,
redirectsFile,
logger
}) {
if (!redirects) {
return {};
}
const num_valid = redirects.rules.length;
const num_invalid = redirects.invalid.length;
const redirectsRelativePath = redirectsFile ? (0, import_node_path2.relative)(process.cwd(), redirectsFile) : "";
logger.log(
`\u2728 Parsed ${num_valid} valid redirect rule${num_valid === 1 ? "" : "s"}.`
);
if (num_invalid > 0) {
let invalidRedirectRulesList = ``;
for (const { line, lineNumber, message } of redirects.invalid) {
invalidRedirectRulesList += `\u25B6\uFE0E ${message}
`;
if (line) {
invalidRedirectRulesList += ` at ${redirectsRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}
`;
}
}
logger.warn(
`Found ${num_invalid} invalid redirect rule${num_invalid === 1 ? "" : "s"}:
${invalidRedirectRulesList}`
);
}
if (num_valid === 0) {
return {};
}
const staticRedirects = {};
const dynamicRedirects = {};
let canCreateStaticRule = true;
for (const rule of redirects.rules) {
if (!rule.from.match(SPLAT_REGEX) && !rule.from.match(PLACEHOLDER_REGEX)) {
if (canCreateStaticRule) {
staticRedirects[rule.from] = {
status: rule.status,
to: rule.to,
lineNumber: rule.lineNumber
};
continue;
} else {
logger.info(
`The redirect rule ${rule.from} \u2192 ${rule.status} ${rule.to} could be made more performant by bringing it above any lines with splats or placeholders.`
);
}
}
dynamicRedirects[rule.from] = { status: rule.status, to: rule.to };
canCreateStaticRule = false;
}
return {
redirects: {
version: REDIRECTS_VERSION,
staticRules: staticRedirects,
rules: dynamicRedirects
}
};
}
function constructHeaders({
headers,
headersFile,
logger
}) {
if (!headers) {
return {};
}
const num_valid = headers.rules.length;
const num_invalid = headers.invalid.length;
const headersRelativePath = headersFile ? (0, import_node_path2.relative)(process.cwd(), headersFile) : "";
logger.log(
`\u2728 Parsed ${num_valid} valid header rule${num_valid === 1 ? "" : "s"}.`
);
if (num_invalid > 0) {
let invalidHeaderRulesList = ``;
for (const { line, lineNumber, message } of headers.invalid) {
invalidHeaderRulesList += `\u25B6\uFE0E ${message}
`;
if (line) {
invalidHeaderRulesList += ` at ${headersRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}
`;
}
}
logger.warn(
`Found ${num_invalid} invalid header rule${num_invalid === 1 ? "" : "s"}:
${invalidHeaderRulesList}`
);
}
if (num_valid === 0) {
return {};
}
const rules = {};
for (const rule of headers.rules) {
rules[rule.path] = {};
if (Object.keys(rule.headers).length) {
rules[rule.path].set = rule.headers;
}
if (rule.unsetHeaders.length) {
rules[rule.path].unset = rule.unsetHeaders;
}
}
return {
headers: {
version: HEADERS_VERSION,
rules
}
};
}
// ../workers-shared/utils/configuration/validateURL.ts
var extractPathname = (path31 = "/", includeSearch, includeHash) => {
if (!path31.startsWith("/")) {
path31 = `/${path31}`;
}
const url21 = new URL(`//${path31}`, "relative://");
return `${url21.pathname}${includeSearch ? url21.search : ""}${includeHash ? url21.hash : ""}`;
};
var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
var HOST_WITH_PORT_REGEX = /.*:\d+$/;
var PATH_REGEX = /^\//;
var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSearch = false, includeHash = false) => {
const host = URL_REGEX.exec(token);
if (host && host.groups && host.groups.host) {
if (onlyRelative) {
return [
void 0,
`Only relative URLs are allowed. Skipping absolute URL ${token}.`
];
}
if (disallowPorts && host.groups.host.match(HOST_WITH_PORT_REGEX)) {
return [
void 0,
`Specifying ports is not supported. Skipping absolute URL ${token}.`
];
}
return [
`https://${host.groups.host}${extractPathname(
host.groups.path,
includeSearch,
includeHash
)}`,
void 0
];
} else {
if (!token.startsWith("/") && onlyRelative) {
token = `/${token}`;
}
const path31 = PATH_REGEX.exec(token);
if (path31) {
try {
return [extractPathname(token, includeSearch, includeHash), void 0];
} catch {
return [void 0, `Error parsing URL segment ${token}. Skipping.`];
}
}
}
return [
void 0,
onlyRelative ? "URLs should begin with a forward-slash." : 'URLs should either be relative (e.g. begin with a forward-slash), or use HTTPS (e.g. begin with "https://").'
];
};
function urlHasHost(token) {
const host = URL_REGEX.exec(token);
return Boolean(host && host.groups && host.groups.host);
}
// ../workers-shared/utils/configuration/parseHeaders.ts
var LINE_IS_PROBABLY_A_PATH = new RegExp(/^([^\s]+:\/\/|^\/)/);
function parseHeaders(input) {
const lines = input.split("\n");
const rules = [];
const invalid = [];
let rule = void 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.length === 0 || line.startsWith("#")) {
continue;
}
if (line.length > MAX_LINE_LENGTH) {
invalid.push({
message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${MAX_LINE_LENGTH}.`
});
continue;
}
if (LINE_IS_PROBABLY_A_PATH.test(line)) {
if (rules.length >= MAX_HEADER_RULES) {
invalid.push({
message: `Maximum number of rules supported is ${MAX_HEADER_RULES}. Skipping remaining ${lines.length - i} lines of file.`
});
break;
}
if (rule) {
if (isValidRule(rule)) {
rules.push({
path: rule.path,
headers: rule.headers,
unsetHeaders: rule.unsetHeaders
});
} else {
invalid.push({
line: rule.line,
lineNumber: i + 1,
message: "No headers specified"
});
}
}
const [path31, pathError] = validateUrl(line, false, true);
if (pathError) {
invalid.push({
line,
lineNumber: i + 1,
message: pathError
});
rule = void 0;
continue;
}
rule = {
path: path31,
line,
headers: {},
unsetHeaders: []
};
continue;
}
if (!line.includes(HEADER_SEPARATOR)) {
if (!rule) {
invalid.push({
line,
lineNumber: i + 1,
message: "Expected a path beginning with at least one forward-slash"
});
} else {
if (line.trim().startsWith(UNSET_OPERATOR)) {
rule.unsetHeaders.push(line.trim().replace(UNSET_OPERATOR, ""));
} else {
invalid.push({
line,
lineNumber: i + 1,
message: "Expected a colon-separated header pair (e.g. name: value)"
});
}
}
continue;
}
const [rawName, ...rawValue] = line.split(HEADER_SEPARATOR);
const name = rawName.trim().toLowerCase();
if (name.includes(" ")) {
invalid.push({
line,
lineNumber: i + 1,
message: "Header name cannot include spaces"
});
continue;
}
const value = rawValue.join(HEADER_SEPARATOR).trim();
if (name === "") {
invalid.push({
line,
lineNumber: i + 1,
message: "No header name specified"
});
continue;
}
if (value === "") {
invalid.push({
line,
lineNumber: i + 1,
message: "No header value specified"
});
continue;
}
if (!rule) {
invalid.push({
line,
lineNumber: i + 1,
message: `Path should come before header (${name}: ${value})`
});
continue;
}
const existingValues = rule.headers[name];
rule.headers[name] = existingValues ? `${existingValues}, ${value}` : value;
}
if (rule) {
if (isValidRule(rule)) {
rules.push({
path: rule.path,
headers: rule.headers,
unsetHeaders: rule.unsetHeaders
});
} else {
invalid.push({ line: rule.line, message: "No headers specified" });
}
}
return {
rules,
invalid
};
}
function isValidRule(rule) {
return Object.keys(rule.headers).length > 0 || rule.unsetHeaders.length > 0;
}
// ../workers-shared/utils/configuration/parseRedirects.ts
function parseRedirects(input) {
const lines = input.split("\n");
const rules = [];
const seen_paths = /* @__PURE__ */ new Set();
const invalid = [];
let staticRules = 0;
let dynamicRules = 0;
let canCreateStaticRule = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.length === 0 || line.startsWith("#")) {
continue;
}
if (line.length > MAX_LINE_LENGTH) {
invalid.push({
message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${MAX_LINE_LENGTH}.`
});
continue;
}
const tokens = line.split(/\s+/);
if (tokens.length < 2 || tokens.length > 3) {
invalid.push({
line,
lineNumber: i + 1,
message: `Expected exactly 2 or 3 whitespace-separated tokens. Got ${tokens.length}.`
});
continue;
}
const [str_from, str_to, str_status = "302"] = tokens;
const fromResult = validateUrl(str_from, true, true, false, false);
if (fromResult[0] === void 0) {
invalid.push({
line,
lineNumber: i + 1,
message: fromResult[1]
});
continue;
}
const from = fromResult[0];
if (canCreateStaticRule && !from.match(SPLAT_REGEX) && !from.match(PLACEHOLDER_REGEX)) {
staticRules += 1;
if (staticRules > MAX_STATIC_REDIRECT_RULES) {
invalid.push({
message: `Maximum number of static rules supported is ${MAX_STATIC_REDIRECT_RULES}. Skipping line.`
});
continue;
}
} else {
dynamicRules += 1;
canCreateStaticRule = false;
if (dynamicRules > MAX_DYNAMIC_REDIRECT_RULES) {
invalid.push({
message: `Maximum number of dynamic rules supported is ${MAX_DYNAMIC_REDIRECT_RULES}. Skipping remaining ${lines.length - i} lines of file.`
});
break;
}
}
const toResult = validateUrl(str_to, false, false, true, true);
if (toResult[0] === void 0) {
invalid.push({
line,
lineNumber: i + 1,
message: toResult[1]
});
continue;
}
const to = toResult[0];
const status2 = Number(str_status);
if (isNaN(status2) || !PERMITTED_STATUS_CODES.has(status2)) {
invalid.push({
line,
lineNumber: i + 1,
message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
});
continue;
}
if (/\/\*?$/.test(from) && /\/index(.html)?$/.test(to) && !urlHasHost(to)) {
invalid.push({
line,
lineNumber: i + 1,
message: "Infinite loop detected in this rule and has been ignored. This will cause a redirect to strip `.html` or `/index` and end up triggering this rule again. Please fix or remove this rule to silence this warning."
});
continue;
}
if (seen_paths.has(from)) {
invalid.push({
line,
lineNumber: i + 1,
message: `Ignoring duplicate rule for path ${from}.`
});
continue;
}
seen_paths.add(from);
if (status2 === 200) {
if (urlHasHost(to)) {
invalid.push({
line,
lineNumber: i + 1,
message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
});
continue;
}
}
rules.push({ from, to, status: status2, lineNumber: i + 1 });
}
return {
rules,
invalid
};
}
// ../../node_modules/.pnpm/pretty-bytes@6.1.1/node_modules/pretty-bytes/index.js
var BYTE_UNITS = [
"B",
"kB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"
];
var BIBYTE_UNITS = [
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB"
];
var BIT_UNITS = [
"b",
"kbit",
"Mbit",
"Gbit",
"Tbit",
"Pbit",
"Ebit",
"Zbit",
"Ybit"
];
var BIBIT_UNITS = [
"b",
"kibit",
"Mibit",
"Gibit",
"Tibit",
"Pibit",
"Eibit",
"Zibit",
"Yibit"
];
var toLocaleString = (number, locale, options) => {
let result = number;
if (typeof locale === "string" || Array.isArray(locale)) {
result = number.toLocaleString(locale, options);
} else if (locale === true || options !== void 0) {
result = number.toLocaleString(void 0, options);
}
return result;
};
function prettyBytes(number, options) {
if (!Number.isFinite(number)) {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}
options = {
bits: false,
binary: false,
space: true,
...options
};
const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS;
const separator = options.space ? " " : "";
if (options.signed && number === 0) {
return ` 0${separator}${UNITS[0]}`;
}
const isNegative = number < 0;
const prefix = isNegative ? "-" : options.signed ? "+" : "";
if (isNegative) {
number = -number;
}
let localeOptions;
if (options.minimumFractionDigits !== void 0) {
localeOptions = { minimumFractionDigits: options.minimumFractionDigits };
}
if (options.maximumFractionDigits !== void 0) {
localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions };
}
if (number < 1) {
const numberString2 = toLocaleString(number, options.locale, localeOptions);
return prefix + numberString2 + separator + UNITS[0];
}
const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
number /= (options.binary ? 1024 : 1e3) ** exponent;
if (!localeOptions) {
number = number.toPrecision(3);
}
const numberString = toLocaleString(Number(number), options.locale, localeOptions);
const unit = UNITS[exponent];
return prefix + numberString + separator + unit;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/assets.worker.ts
var import_fs3 = __toESM(require("fs"));
var import_path6 = __toESM(require("path"));
var import_url3 = __toESM(require("url"));
var contents3;
function assets_worker_default() {
if (contents3 !== void 0)
return contents3;
const filePath = import_path6.default.join(__dirname, "workers", "assets/assets.worker.js");
contents3 = import_fs3.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url3.default.pathToFileURL(filePath);
return contents3;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/assets-kv.worker.ts
var import_fs4 = __toESM(require("fs"));
var import_path7 = __toESM(require("path"));
var import_url4 = __toESM(require("url"));
var contents4;
function assets_kv_worker_default() {
if (contents4 !== void 0)
return contents4;
const filePath = import_path7.default.join(__dirname, "workers", "assets/assets-kv.worker.js");
contents4 = import_fs4.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url4.default.pathToFileURL(filePath);
return contents4;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/router.worker.ts
var import_fs5 = __toESM(require("fs"));
var import_path8 = __toESM(require("path"));
var import_url5 = __toESM(require("url"));
var contents5;
function router_worker_default() {
if (contents5 !== void 0)
return contents5;
const filePath = import_path8.default.join(__dirname, "workers", "assets/router.worker.js");
contents5 = import_fs5.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url5.default.pathToFileURL(filePath);
return contents5;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/rpc-proxy.worker.ts
var import_fs6 = __toESM(require("fs"));
var import_path9 = __toESM(require("path"));
var import_url6 = __toESM(require("url"));
var contents6;
function rpc_proxy_worker_default() {
if (contents6 !== void 0)
return contents6;
const filePath = import_path9.default.join(__dirname, "workers", "assets/rpc-proxy.worker.js");
contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath);
return contents6;
}
// src/plugins/core/index.ts
var import_assert9 = __toESM(require("assert"));
var import_fs16 = require("fs");
var import_promises6 = __toESM(require("fs/promises"));
var import_path19 = __toESM(require("path"));
var import_stream2 = require("stream");
var import_tls = __toESM(require("tls"));
var import_util3 = require("util");
var import_undici7 = require("undici");
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/entry.worker.ts
var import_fs7 = __toESM(require("fs"));
var import_path10 = __toESM(require("path"));
var import_url7 = __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_fs7.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url7.default.pathToFileURL(filePath);
return contents7;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/strip-cf-connecting-ip.worker.ts
var import_fs8 = __toESM(require("fs"));
var import_path11 = __toESM(require("path"));
var import_url8 = __toESM(require("url"));
var contents8;
function strip_cf_connecting_ip_worker_default() {
if (contents8 !== void 0)
return contents8;
const filePath = import_path11.default.join(__dirname, "workers", "core/strip-cf-connecting-ip.worker.js");
contents8 = import_fs8.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url8.default.pathToFileURL(filePath);
return contents8;
}
// src/plugins/core/index.ts
var import_zod12 = require("zod");
// src/runtime/index.ts
var import_assert4 = __toESM(require("assert"));
var import_child_process = __toESM(require("child_process"));
var import_events2 = require("events");
var import_readline = __toESM(require("readline"));
var import_stream = require("stream");
var import_workerd2 = __toESM(require("workerd"));
var import_zod5 = require("zod");
// ../../node_modules/.pnpm/capnp-es@0.0.7_typescript@5.7.3/node_modules/capnp-es/dist/shared/capnp-es.DAoyiaGr.mjs
var ListElementSize = /* @__PURE__ */ ((ListElementSize2) => {
ListElementSize2[ListElementSize2["VOID"] = 0] = "VOID";
ListElementSize2[ListElementSize2["BIT"] = 1] = "BIT";
ListElementSize2[ListElementSize2["BYTE"] = 2] = "BYTE";
ListElementSize2[ListElementSize2["BYTE_2"] = 3] = "BYTE_2";
ListElementSize2[ListElementSize2["BYTE_4"] = 4] = "BYTE_4";
ListElementSize2[ListElementSize2["BYTE_8"] = 5] = "BYTE_8";
ListElementSize2[ListElementSize2["POINTER"] = 6] = "POINTER";
ListElementSize2[ListElementSize2["COMPOSITE"] = 7] = "COMPOSITE";
return ListElementSize2;
})(ListElementSize || {});
var tmpWord = new DataView(new ArrayBuffer(8));
new Uint16Array(tmpWord.buffer)[0] = 258;
var DEFAULT_BUFFER_SIZE = 4096;
var DEFAULT_TRAVERSE_LIMIT = 64 << 20;
var LIST_SIZE_MASK = 7;
var MAX_BUFFER_DUMP_BYTES = 8192;
var MAX_INT32 = 2147483647;
var MAX_UINT32 = 4294967295;
var MIN_SINGLE_SEGMENT_GROWTH = 4096;
var NATIVE_LITTLE_ENDIAN = tmpWord.getUint8(0) === 2;
var PACK_SPAN_THRESHOLD = 2;
var POINTER_DOUBLE_FAR_MASK = 4;
var POINTER_TYPE_MASK = 3;
var MAX_DEPTH = MAX_INT32;
var MAX_SEGMENT_LENGTH = MAX_UINT32;
var INVARIANT_UNREACHABLE_CODE = "CAPNP-TS000 Unreachable code detected.";
function assertNever(n) {
throw new Error(INVARIANT_UNREACHABLE_CODE + ` (never block hit with: ${n})`);
}
var MSG_INVALID_FRAME_HEADER = "CAPNP-TS001 Attempted to parse an invalid message frame header; are you sure this is a Cap'n Proto message?";
var MSG_PACK_NOT_WORD_ALIGNED = "CAPNP-TS003 Attempted to pack a message that was not word-aligned.";
var MSG_SEGMENT_OUT_OF_BOUNDS = "CAPNP-TS004 Segment ID %X is out of bounds for message %s.";
var MSG_SEGMENT_TOO_SMALL = "CAPNP-TS005 First segment must have at least enough room to hold the root pointer (8 bytes).";
var PTR_ADOPT_WRONG_MESSAGE = "CAPNP-TS008 Attempted to adopt %s into a pointer in a different message %s.";
var PTR_ALREADY_ADOPTED = "CAPNP-TS009 Attempted to adopt %s more than once.";
var PTR_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS010 Attempted to set a composite list without providing a composite element size.";
var PTR_DEPTH_LIMIT_EXCEEDED = "CAPNP-TS011 Nesting depth limit exceeded for %s.";
var PTR_INIT_COMPOSITE_STRUCT = "CAPNP-TS013 Attempted to initialize a struct member from a composite list (%s).";
var PTR_INVALID_FAR_TARGET = "CAPNP-TS015 Target of a far pointer (%s) is another far pointer.";
var PTR_INVALID_LIST_SIZE = "CAPNP-TS016 Invalid list element size: %x.";
var PTR_INVALID_POINTER_TYPE = "CAPNP-TS017 Invalid pointer type: %x.";
var PTR_INVALID_UNION_ACCESS = "CAPNP-TS018 Attempted to access getter on %s for union field %s that is not currently set (wanted: %d, found: %d).";
var PTR_OFFSET_OUT_OF_BOUNDS = "CAPNP-TS019 Pointer offset %a is out of bounds for underlying buffer.";
var PTR_STRUCT_DATA_OUT_OF_BOUNDS = "CAPNP-TS020 Attempted to access out-of-bounds struct data (struct: %s, %d bytes at %a, data words: %d).";
var PTR_STRUCT_POINTER_OUT_OF_BOUNDS = "CAPNP-TS021 Attempted to access out-of-bounds struct pointer (%s, index: %d, length: %d).";
var PTR_TRAVERSAL_LIMIT_EXCEEDED = "CAPNP-TS022 Traversal limit exceeded! Slow down! %s";
var PTR_WRONG_LIST_TYPE = "CAPNP-TS023 Cannot convert %s to a %s list.";
var PTR_WRONG_POINTER_TYPE = "CAPNP-TS024 Attempted to convert pointer %s to a %s type.";
var SEG_GET_NON_ZERO_SINGLE = "CAPNP-TS035 Attempted to get a segment other than 0 (%d) from a single segment arena.";
var SEG_ID_OUT_OF_BOUNDS = "CAPNP-TS036 Attempted to get an out-of-bounds segment (%d).";
var SEG_NOT_WORD_ALIGNED = "CAPNP-TS037 Segment buffer length %d is not a multiple of 8.";
var SEG_REPLACEMENT_BUFFER_TOO_SMALL = "CAPNP-TS038 Attempted to replace a segment buffer with one that is smaller than the allocated space.";
var SEG_SIZE_OVERFLOW = `CAPNP-TS039 Requested size %x exceeds maximum value (${MAX_SEGMENT_LENGTH}).`;
var TYPE_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS040 Must provide a composite element size for composite list pointers.";
var LIST_NO_MUTABLE = "CAPNP-TS045: Cannot call mutative methods on an immutable list.";
var LIST_NO_SEARCH = "CAPNP-TS046: Search is not supported for list.";
var RPC_NULL_CLIENT = "CAPNP-TS100 Call on null client.";
function bufferToHex(buffer) {
const a = new Uint8Array(buffer);
const h = [];
for (let i = 0; i < a.byteLength; i++) {
h.push(pad(a[i].toString(16), 2));
}
return `[${h.join(" ")}]`;
}
function dumpBuffer(buffer) {
const b = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
const byteLength = Math.min(b.byteLength, MAX_BUFFER_DUMP_BYTES);
let r = format("\n=== buffer[%d] ===", byteLength);
for (let j = 0; j < byteLength; j += 16) {
r += `
${pad(j.toString(16), 8)}: `;
let s = "";
let k;
for (k = 0; k < 16 && j + k < b.byteLength; k++) {
const v = b[j + k];
r += `${pad(v.toString(16), 2)} `;
s += v > 31 && v < 255 ? String.fromCharCode(v) : "\xB7";
if (k === 7)
r += " ";
}
r += `${repeat((17 - k) * 3, " ")}${s}`;
}
r += "\n";
if (byteLength !== b.byteLength) {
r += format("=== (truncated %d bytes) ===\n", b.byteLength - byteLength);
}
return r;
}
function format(s, ...args) {
const n = s.length;
let arg;
let argIndex = 0;
let c;
let escaped = false;
let i = 0;
let leadingZero = false;
let precision;
let result = "";
function nextArg() {
return args[argIndex++];
}
function slurpNumber() {
let digits = "";
while (/\d/.test(s[i])) {
digits += s[i++];
c = s[i];
}
return digits.length > 0 ? Number.parseInt(digits, 10) : null;
}
for (; i < n; ++i) {
c = s[i];
if (escaped) {
escaped = false;
if (c === ".") {
leadingZero = false;
c = s[++i];
} else if (c === "0" && s[i + 1] === ".") {
leadingZero = true;
i += 2;
c = s[i];
} else {
leadingZero = true;
}
precision = slurpNumber();
switch (c) {
case "a": {
result += "0x" + pad(Number.parseInt(String(nextArg()), 10).toString(16), 8);
break;
}
case "b": {
result += Number.parseInt(String(nextArg()), 10).toString(2);
break;
}
case "c": {
arg = nextArg();
result += typeof arg === "string" || arg instanceof String ? arg : String.fromCharCode(Number.parseInt(String(arg), 10));
break;
}
case "d": {
result += Number.parseInt(String(nextArg()), 10);
break;
}
case "f": {
const tmp = Number.parseFloat(String(nextArg())).toFixed(
precision || 6
);
result += leadingZero ? tmp : tmp.replace(/^0/, "");
break;
}
case "j": {
result += JSON.stringify(nextArg());
break;
}
case "o": {
result += "0" + Number.parseInt(String(nextArg()), 10).toString(8);
break;
}
case "s": {
result += nextArg();
break;
}
case "x": {
result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16);
break;
}
case "X": {
result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16).toUpperCase();
break;
}
default: {
result += c;
break;
}
}
} else if (c === "%") {
escaped = true;
} else {
result += c;
}
}
return result;
}
function pad(v, width, pad2 = "0") {
return v.length >= width ? v : Array.from({ length: width - v.length + 1 }).join(pad2) + v;
}
function padToWord$1(size) {
return size + 7 & -8;
}
function repeat(times, str) {
let out = "";
let n = times;
let s = str;
if (n < 1 || n > Number.MAX_VALUE)
return out;
do {
if (n % 2)
out += s;
n = Math.floor(n / 2);
if (n)
s += s;
} while (n);
return out;
}
var ObjectSize = class {
/** The number of bytes required for the data section. */
dataByteLength;
/** The number of pointers in the object. */
pointerLength;
constructor(dataByteLength, pointerCount) {
this.dataByteLength = dataByteLength;
this.pointerLength = pointerCount;
}
toString() {
return format(
"ObjectSize_dw:%d,pc:%d",
getDataWordLength(this),
this.pointerLength
);
}
};
function getByteLength(o) {
return o.dataByteLength + o.pointerLength * 8;
}
function getDataWordLength(o) {
return o.dataByteLength / 8;
}
function getWordLength(o) {
return o.dataByteLength / 8 + o.pointerLength;
}
function padToWord(o) {
return new ObjectSize(padToWord$1(o.dataByteLength), o.pointerLength);
}
var Orphan = class {
/** If this member is not present then the orphan has already been adopted, or something went very wrong. */
_capnp;
byteOffset;
segment;
constructor(src) {
const c = getContent(src);
this.segment = c.segment;
this.byteOffset = c.byteOffset;
this._capnp = {};
this._capnp.type = getTargetPointerType(src);
switch (this._capnp.type) {
case PointerType.STRUCT: {
this._capnp.size = getTargetStructSize(src);
break;
}
case PointerType.LIST: {
this._capnp.length = getTargetListLength(src);
this._capnp.elementSize = getTargetListElementSize(src);
if (this._capnp.elementSize === ListElementSize.COMPOSITE) {
this._capnp.size = getTargetCompositeListSize(src);
}
break;
}
case PointerType.OTHER: {
this._capnp.capId = getCapabilityId(src);
break;
}
default: {
throw new Error(PTR_INVALID_POINTER_TYPE);
}
}
erasePointer(src);
}
/**
* Adopt (move) this orphan into the target pointer location. This will allocate far pointers in `dst` as needed.
*
* @param {T} dst The destination pointer.
* @returns {void}
*/
_moveTo(dst) {
if (this._capnp === void 0) {
throw new Error(format(PTR_ALREADY_ADOPTED, this));
}
if (this.segment.message !== dst.segment.message) {
throw new Error(format(PTR_ADOPT_WRONG_MESSAGE, this, dst));
}
erase(dst);
const res = initPointer(this.segment, this.byteOffset, dst);
switch (this._capnp.type) {
case PointerType.STRUCT: {
setStructPointer(res.offsetWords, this._capnp.size, res.pointer);
break;
}
case PointerType.LIST: {
let offsetWords = res.offsetWords;
if (this._capnp.elementSize === ListElementSize.COMPOSITE) {
offsetWords--;
}
setListPointer(
offsetWords,
this._capnp.elementSize,
this._capnp.length,
res.pointer,
this._capnp.size
);
break;
}
case PointerType.OTHER: {
setInterfacePointer(this._capnp.capId, res.pointer);
break;
}
default: {
throw new Error(PTR_INVALID_POINTER_TYPE);
}
}
this._capnp = void 0;
}
dispose() {
if (this._capnp === void 0) {
return;
}
switch (this._capnp.type) {
case PointerType.STRUCT: {
this.segment.fillZeroWords(
this.byteOffset,
getWordLength(this._capnp.size)
);
break;
}
case PointerType.LIST: {
const byteLength = getListByteLength(
this._capnp.elementSize,
this._capnp.length,
this._capnp.size
);
this.segment.fillZeroWords(this.byteOffset, byteLength);
break;
}
}
this._capnp = void 0;
}
[Symbol.for("nodejs.util.inspect.custom")]() {
return format(
"Orphan_%d@%a,type:%s",
this.segment.id,
this.byteOffset,
this._capnp && this._capnp.type
);
}
};
function adopt(src, p) {
src._moveTo(p);
}
function disown(p) {
return new Orphan(p);
}
function dump(p) {
return bufferToHex(p.segment.buffer.slice(p.byteOffset, p.byteOffset + 8));
}
function getListByteLength(elementSize, length, compositeSize) {
switch (elementSize) {
case ListElementSize.BIT: {
return padToWord$1(length + 7 >>> 3);
}
case ListElementSize.BYTE:
case ListElementSize.BYTE_2:
case ListElementSize.BYTE_4:
case ListElementSize.BYTE_8:
case ListElementSize.POINTER:
case ListElementSize.VOID: {
return padToWord$1(getListElementByteLength(elementSize) * length);
}
case ListElementSize.COMPOSITE: {
if (compositeSize === void 0) {
throw new Error(format(PTR_INVALID_LIST_SIZE, Number.NaN));
}
return length * padToWord$1(getByteLength(compositeSize));
}
default: {
throw new Error(PTR_INVALID_LIST_SIZE);
}
}
}
function getListElementByteLength(elementSize) {
switch (elementSize) {
case ListElementSize.BIT: {
return Number.NaN;
}
case ListElementSize.BYTE: {
return 1;
}
case ListElementSize.BYTE_2: {
return 2;
}
case ListElementSize.BYTE_4: {
return 4;
}
case ListElementSize.BYTE_8:
case ListElementSize.POINTER: {
return 8;
}
case ListElementSize.COMPOSITE: {
return Number.NaN;
}
case ListElementSize.VOID: {
return 0;
}
default: {
throw new Error(format(PTR_INVALID_LIST_SIZE, elementSize));
}
}
}
function add(offset, p) {
return new Pointer(p.segment, p.byteOffset + offset, p._capnp.depthLimit);
}
function copyFrom(src, p) {
if (p.segment === src.segment && p.byteOffset === src.byteOffset) {
return;
}
erase(p);
if (isNull(src))
return;
switch (getTargetPointerType(src)) {
case PointerType.STRUCT: {
copyFromStruct(src, p);
break;
}
case PointerType.LIST: {
copyFromList(src, p);
break;
}
case PointerType.OTHER: {
copyFromInterface(src, p);
break;
}
default: {
throw new Error(
format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p))
);
}
}
}
function erase(p) {
if (isNull(p))
return;
let c;
switch (getTargetPointerType(p)) {
case PointerType.STRUCT: {
const size = getTargetStructSize(p);
c = getContent(p);
c.segment.fillZeroWords(c.byteOffset, size.dataByteLength / 8);
for (let i = 0; i < size.pointerLength; i++) {
erase(add(i * 8, c));
}
break;
}
case PointerType.LIST: {
const elementSize = getTargetListElementSize(p);
const length = getTargetListLength(p);
let contentWords = padToWord$1(
length * getListElementByteLength(elementSize)
);
c = getContent(p);
if (elementSize === ListElementSize.POINTER) {
for (let i = 0; i < length; i++) {
erase(
new Pointer(
c.segment,
c.byteOffset + i * 8,
p._capnp.depthLimit - 1
)
);
}
break;
} else if (elementSize === ListElementSize.COMPOSITE) {
const tag = add(-8, c);
const compositeSize = getStructSize(tag);
const compositeByteLength = getByteLength(compositeSize);
contentWords = getOffsetWords(tag);
c.segment.setWordZero(c.byteOffset - 8);
for (let i = 0; i < length; i++) {
for (let j = 0; j < compositeSize.pointerLength; j++) {
erase(
new Pointer(
c.segment,
c.byteOffset + i * compositeByteLength + j * 8,
p._capnp.depthLimit - 1
)
);
}
}
}
c.segment.fillZeroWords(c.byteOffset, contentWords);
break;
}
case PointerType.OTHER: {
break;
}
default: {
throw new Error(
format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p))
);
}
}
erasePointer(p);
}
function erasePointer(p) {
if (getPointerType(p) === PointerType.FAR) {
const landingPad = followFar(p);
if (isDoubleFar(p)) {
landingPad.segment.setWordZero(landingPad.byteOffset + 8);
}
landingPad.segment.setWordZero(landingPad.byteOffset);
}
p.segment.setWordZero(p.byteOffset);
}
function followFar(p) {
const targetSegment = p.segment.message.getSegment(
p.segment.getUint32(p.byteOffset + 4)
);
const targetWordOffset = p.segment.getUint32(p.byteOffset) >>> 3;
return new Pointer(
targetSegment,
targetWordOffset * 8,
p._capnp.depthLimit - 1
);
}
function followFars(p) {
if (getPointerType(p) === PointerType.FAR) {
const landingPad = followFar(p);
if (isDoubleFar(p))
landingPad.byteOffset += 8;
return landingPad;
}
return p;
}
function getCapabilityId(p) {
return p.segment.getUint32(p.byteOffset + 4);
}
function isCompositeList(p) {
return getTargetPointerType(p) === PointerType.LIST && getTargetListElementSize(p) === ListElementSize.COMPOSITE;
}
function getContent(p, ignoreCompositeIndex) {
let c;
if (isDoubleFar(p)) {
const landingPad = followFar(p);
c = new Pointer(
p.segment.message.getSegment(getFarSegmentId(landingPad)),
getOffsetWords(landingPad) * 8
);
} else {
const target = followFars(p);
c = new Pointer(
target.segment,
target.byteOffset + 8 + getOffsetWords(target) * 8
);
}
if (isCompositeList(p))
c.byteOffset += 8;
if (!ignoreCompositeIndex && p._capnp.compositeIndex !== void 0) {
c.byteOffset -= 8;
c.byteOffset += 8 + p._capnp.compositeIndex * getByteLength(padToWord(getStructSize(c)));
}
return c;
}
function getFarSegmentId(p) {
return p.segment.getUint32(p.byteOffset + 4);
}
function getListElementSize(p) {
return p.segment.getUint32(p.byteOffset + 4) & LIST_SIZE_MASK;
}
function getListLength(p) {
return p.segment.getUint32(p.byteOffset + 4) >>> 3;
}
function getOffsetWords(p) {
const o = p.segment.getInt32(p.byteOffset);
return o & 2 ? o >> 3 : o >> 2;
}
function getPointerType(p) {
return p.segment.getUint32(p.byteOffset) & POINTER_TYPE_MASK;
}
function getStructDataWords(p) {
return p.segment.getUint16(p.byteOffset + 4);
}
function getStructPointerLength(p) {
return p.segment.getUint16(p.byteOffset + 6);
}
function getStructSize(p) {
return new ObjectSize(getStructDataWords(p) * 8, getStructPointerLength(p));
}
function getTargetCompositeListTag(p) {
const c = getContent(p);
c.byteOffset -= 8;
return c;
}
function getTargetCompositeListSize(p) {
return getStructSize(getTargetCompositeListTag(p));
}
function getTargetListElementSize(p) {
return getListElementSize(followFars(p));
}
function getTargetListLength(p) {
const t = followFars(p);
if (getListElementSize(t) === ListElementSize.COMPOSITE) {
return getOffsetWords(getTargetCompositeListTag(p));
}
return getListLength(t);
}
function getTargetPointerType(p) {
const t = getPointerType(followFars(p));
if (t === PointerType.FAR)
throw new Error(format(PTR_INVALID_FAR_TARGET, p));
return t;
}
function getTargetStructSize(p) {
return getStructSize(followFars(p));
}
function initPointer(contentSegment, contentOffset, p) {
if (p.segment !== contentSegment) {
if (!contentSegment.hasCapacity(8)) {
const landingPad2 = p.segment.allocate(16);
setFarPointer(true, landingPad2.byteOffset / 8, landingPad2.segment.id, p);
setFarPointer(false, contentOffset / 8, contentSegment.id, landingPad2);
landingPad2.byteOffset += 8;
return new PointerAllocationResult(landingPad2, 0);
}
const landingPad = contentSegment.allocate(8);
if (landingPad.segment.id !== contentSegment.id) {
throw new Error(INVARIANT_UNREACHABLE_CODE);
}
setFarPointer(false, landingPad.byteOffset / 8, landingPad.segment.id, p);
return new PointerAllocationResult(
landingPad,
(contentOffset - landingPad.byteOffset - 8) / 8
);
}
return new PointerAllocationResult(p, (contentOffset - p.byteOffset - 8) / 8);
}
function isDoubleFar(p) {
return getPointerType(p) === PointerType.FAR && (p.segment.getUint32(p.byteOffset) & POINTER_DOUBLE_FAR_MASK) !== 0;
}
function isNull(p) {
return p.segment.isWordZero(p.byteOffset);
}
function relocateTo(dst, src) {
const t = followFars(src);
const lo = t.segment.getUint8(t.byteOffset) & 3;
const hi = t.segment.getUint32(t.byteOffset + 4);
erase(dst);
const res = initPointer(
t.segment,
t.byteOffset + 8 + getOffsetWords(t) * 8,
dst
);
res.pointer.segment.setUint32(
res.pointer.byteOffset,
lo | res.offsetWords << 2
);
res.pointer.segment.setUint32(res.pointer.byteOffset + 4, hi);
erasePointer(src);
}
function setFarPointer(doubleFar, offsetWords, segmentId, p) {
const A = PointerType.FAR;
const B = doubleFar ? 1 : 0;
const C = offsetWords;
const D = segmentId;
p.segment.setUint32(p.byteOffset, A | B << 2 | C << 3);
p.segment.setUint32(p.byteOffset + 4, D);
}
function setInterfacePointer(capId, p) {
p.segment.setUint32(p.byteOffset, PointerType.OTHER);
p.segment.setUint32(p.byteOffset + 4, capId);
}
function getInterfacePointer(p) {
return p.segment.getUint32(p.byteOffset + 4);
}
function setListPointer(offsetWords, size, length, p, compositeSize) {
const A = PointerType.LIST;
const B = offsetWords;
const C = size;
let D = length;
if (size === ListElementSize.COMPOSITE) {
if (compositeSize === void 0) {
throw new TypeError(TYPE_COMPOSITE_SIZE_UNDEFINED);
}
D *= getWordLength(compositeSize);
}
p.segment.setUint32(p.byteOffset, A | B << 2);
p.segment.setUint32(p.byteOffset + 4, C | D << 3);
}
function setStructPointer(offsetWords, size, p) {
const A = PointerType.STRUCT;
const B = offsetWords;
const C = getDataWordLength(size);
const D = size.pointerLength;
p.segment.setUint32(p.byteOffset, A | B << 2);
p.segment.setUint16(p.byteOffset + 4, C);
p.segment.setUint16(p.byteOffset + 6, D);
}
function validate(pointerType, p, elementSize) {
if (isNull(p))
return;
const t = followFars(p);
const A = t.segment.getUint32(t.byteOffset) & POINTER_TYPE_MASK;
if (A !== pointerType) {
throw new Error(format(PTR_WRONG_POINTER_TYPE, p, pointerType));
}
if (elementSize !== void 0) {
const C = t.segment.getUint32(t.byteOffset + 4) & LIST_SIZE_MASK;
if (C !== elementSize) {
throw new Error(
format(PTR_WRONG_LIST_TYPE, p, ListElementSize[elementSize])
);
}
}
}
function copyFromInterface(src, dst) {
const srcCapId = getInterfacePointer(src);
if (srcCapId < 0) {
return;
}
const srcCapTable = src.segment.message._capnp.capTable;
if (!srcCapTable) {
return;
}
const client = srcCapTable[srcCapId];
if (!client) {
return;
}
const dstCapId = dst.segment.message.addCap(client);
setInterfacePointer(dstCapId, dst);
}
function copyFromList(src, dst) {
if (dst._capnp.depthLimit <= 0)
throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
const srcContent = getContent(src);
const srcElementSize = getTargetListElementSize(src);
const srcLength = getTargetListLength(src);
let srcCompositeSize;
let srcStructByteLength;
let dstContent;
if (srcElementSize === ListElementSize.POINTER) {
dstContent = dst.segment.allocate(srcLength << 3);
for (let i = 0; i < srcLength; i++) {
const srcPtr = new Pointer(
srcContent.segment,
srcContent.byteOffset + (i << 3),
src._capnp.depthLimit - 1
);
const dstPtr = new Pointer(
dstContent.segment,
dstContent.byteOffset + (i << 3),
dst._capnp.depthLimit - 1
);
copyFrom(srcPtr, dstPtr);
}
} else if (srcElementSize === ListElementSize.COMPOSITE) {
srcCompositeSize = padToWord(getTargetCompositeListSize(src));
srcStructByteLength = getByteLength(srcCompositeSize);
dstContent = dst.segment.allocate(
getByteLength(srcCompositeSize) * srcLength + 8
);
dstContent.segment.copyWord(
dstContent.byteOffset,
srcContent.segment,
srcContent.byteOffset - 8
);
if (srcCompositeSize.dataByteLength > 0) {
const wordLength = getWordLength(srcCompositeSize) * srcLength;
dstContent.segment.copyWords(
dstContent.byteOffset + 8,
srcContent.segment,
srcContent.byteOffset,
wordLength
);
}
for (let i = 0; i < srcLength; i++) {
for (let j = 0; j < srcCompositeSize.pointerLength; j++) {
const offset = i * srcStructByteLength + srcCompositeSize.dataByteLength + (j << 3);
const srcPtr = new Pointer(
srcContent.segment,
srcContent.byteOffset + offset,
src._capnp.depthLimit - 1
);
const dstPtr = new Pointer(
dstContent.segment,
dstContent.byteOffset + offset + 8,
dst._capnp.depthLimit - 1
);
copyFrom(srcPtr, dstPtr);
}
}
} else {
const byteLength = padToWord$1(
srcElementSize === ListElementSize.BIT ? srcLength + 7 >>> 3 : getListElementByteLength(srcElementSize) * srcLength
);
const wordLength = byteLength >>> 3;
dstContent = dst.segment.allocate(byteLength);
dstContent.segment.copyWords(
dstContent.byteOffset,
srcContent.segment,
srcContent.byteOffset,
wordLength
);
}
const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
setListPointer(
res.offsetWords,
srcElementSize,
srcLength,
res.pointer,
srcCompositeSize
);
}
function copyFromStruct(src, dst) {
if (dst._capnp.depthLimit <= 0)
throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
const srcContent = getContent(src);
const srcSize = getTargetStructSize(src);
const srcDataWordLength = getDataWordLength(srcSize);
const dstContent = dst.segment.allocate(getByteLength(srcSize));
dstContent.segment.copyWords(
dstContent.byteOffset,
srcContent.segment,
srcContent.byteOffset,
srcDataWordLength
);
for (let i = 0; i < srcSize.pointerLength; i++) {
const offset = srcSize.dataByteLength + i * 8;
const srcPtr = new Pointer(
srcContent.segment,
srcContent.byteOffset + offset,
src._capnp.depthLimit - 1
);
const dstPtr = new Pointer(
dstContent.segment,
dstContent.byteOffset + offset,
dst._capnp.depthLimit - 1
);
copyFrom(srcPtr, dstPtr);
}
if (dst._capnp.compositeList)
return;
const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
setStructPointer(res.offsetWords, srcSize, res.pointer);
}
function trackPointerAllocation(message, p) {
message._capnp.traversalLimit -= 8;
if (message._capnp.traversalLimit <= 0) {
throw new Error(format(PTR_TRAVERSAL_LIMIT_EXCEEDED, p));
}
}
var PointerAllocationResult = class {
offsetWords;
pointer;
constructor(pointer, offsetWords) {
this.pointer = pointer;
this.offsetWords = offsetWords;
}
};
var PointerType = /* @__PURE__ */ ((PointerType2) => {
PointerType2[PointerType2["STRUCT"] = 0] = "STRUCT";
PointerType2[PointerType2["LIST"] = 1] = "LIST";
PointerType2[PointerType2["FAR"] = 2] = "FAR";
PointerType2[PointerType2["OTHER"] = 3] = "OTHER";
return PointerType2;
})(PointerType || {});
var Pointer = class {
_capnp;
/** Offset, in bytes, from the start of the segment to the beginning of this pointer. */
byteOffset;
/**
* The starting segment for this pointer's data. In the case of a far pointer, the actual content this pointer is
* referencing will be in another segment within the same message.
*/
segment;
constructor(segment, byteOffset, depthLimit = MAX_DEPTH) {
this._capnp = { compositeList: false, depthLimit };
this.segment = segment;
this.byteOffset = byteOffset;
if (depthLimit < 1) {
throw new Error(format(PTR_DEPTH_LIMIT_EXCEEDED, this));
}
trackPointerAllocation(segment.message, this);
if (byteOffset < 0 || byteOffset > segment.byteLength) {
throw new Error(format(PTR_OFFSET_OUT_OF_BOUNDS, byteOffset));
}
}
[Symbol.toStringTag]() {
return format("Pointer_%d", this.segment.id);
}
toString() {
return format("->%d@%a%s", this.segment.id, this.byteOffset, dump(this));
}
};
__publicField(Pointer, "_capnp", {
displayName: "Pointer"
});
var _proxyHandler;
var _List = class extends Pointer {
constructor(segment, byteOffset, depthLimit) {
super(segment, byteOffset, depthLimit);
return new Proxy(this, __privateGet(_List, _proxyHandler));
}
get length() {
return getTargetListLength(this);
}
toArray() {
const length = this.length;
const res = Array.from({ length });
for (let i = 0; i < length; i++) {
res[i] = this.at(i);
}
return res;
}
get(_index) {
throw new TypeError("Cannot get from a generic list.");
}
set(_index, _value) {
throw new TypeError("Cannot set on a generic list.");
}
at(index) {
if (index < 0) {
const length = this.length;
index += length;
}
return this.get(index);
}
concat(other) {
const length = this.length;
const otherLength = other.length;
const res = Array.from({ length: length + otherLength });
for (let i = 0; i < length; i++)
res[i] = this.at(i);
for (let i = 0; i < otherLength; i++)
res[i + length] = other.at(i);
return res;
}
some(cb, _this) {
const length = this.length;
for (let i = 0; i < length; i++) {
if (cb.call(_this, this.at(i), i, this)) {
return true;
}
}
return false;
}
filter(cb, _this) {
const length = this.length;
const res = [];
for (let i = 0; i < length; i++) {
const value = this.at(i);
if (cb.call(_this, value, i, this)) {
res.push(value);
}
}
return res;
}
find(cb, _this) {
const length = this.length;
for (let i = 0; i < length; i++) {
const value = this.at(i);
if (cb.call(_this, value, i, this)) {
return value;
}
}
return void 0;
}
findIndex(cb, _this) {
const length = this.length;
for (let i = 0; i < length; i++) {
const value = this.at(i);
if (cb.call(_this, value, i, this)) {
return i;
}
}
return -1;
}
forEach(cb, _this) {
const length = this.length;
for (let i = 0; i < length; i++) {
cb.call(_this, this.at(i), i, this);
}
}
map(cb, _this) {
const length = this.length;
const res = Array.from({ length });
for (let i = 0; i < length; i++) {
res[i] = cb.call(_this, this.at(i), i, this);
}
return res;
}
flatMap(cb, _this) {
const length = this.length;
const res = [];
for (let i = 0; i < length; i++) {
const r = cb.call(_this, this.at(i), i, this);
res.push(...Array.isArray(r) ? r : [r]);
}
return res;
}
every(cb, _this) {
const length = this.length;
for (let i = 0; i < length; i++) {
if (!cb.call(_this, this.at(i), i, this)) {
return false;
}
}
return true;
}
reduce(cb, initialValue) {
let i = 0;
let res;
if (initialValue === void 0) {
res = this.at(0);
i++;
} else {
res = initialValue;
}
for (; i < this.length; i++) {
res = cb(res, this.at(i), i, this);
}
return res;
}
reduceRight(cb, initialValue) {
let i = this.length - 1;
let res;
if (initialValue === void 0) {
res = this.at(i);
i--;
} else {
res = initialValue;
}
for (; i >= 0; i--) {
res = cb(res, this.at(i), i, this);
}
return res;
}
slice(start = 0, end) {
const length = end ? Math.min(this.length, end) : this.length;
const res = Array.from({ length: length - start });
for (let i = start; i < length; i++)
res[i] = this.at(i);
return res;
}
join(separator) {
return this.toArray().join(separator);
}
toReversed() {
return this.toArray().reverse();
}
toSorted(compareFn) {
return this.toArray().sort(compareFn);
}
toSpliced(start, deleteCount, ...items) {
return this.toArray().splice(start, deleteCount, ...items);
}
fill(value, start, end) {
const length = this.length;
const s = Math.max(start ?? 0, 0);
const e = Math.min(end ?? length, length);
for (let i = s; i < e; i++) {
this.set(i, value);
}
return this;
}
copyWithin(target, start, end) {
const length = this.length;
const e = end ?? length;
const s = start < 0 ? Math.max(length + start, 0) : start;
const t = target < 0 ? Math.max(length + target, 0) : target;
const len = Math.min(e - s, length - t);
for (let i = 0; i < len; i++) {
this.set(t + i, this.at(s + i));
}
return this;
}
keys() {
const length = this.length;
return Array.from({ length }, (_, i) => i)[Symbol.iterator]();
}
values() {
return this.toArray().values();
}
entries() {
return this.toArray().entries();
}
flat(depth) {
return this.toArray().flat(depth);
}
with(index, value) {
return this.toArray().with(index, value);
}
includes(_searchElement, _fromIndex) {
throw new Error(LIST_NO_SEARCH);
}
findLast(_cb, _thisArg) {
throw new Error(LIST_NO_SEARCH);
}
findLastIndex(_cb, _t) {
throw new Error(LIST_NO_SEARCH);
}
indexOf(_searchElement, _fromIndex) {
throw new Error(LIST_NO_SEARCH);
}
lastIndexOf(_searchElement, _fromIndex) {
throw new Error(LIST_NO_SEARCH);
}
pop() {
throw new Error(LIST_NO_MUTABLE);
}
push(..._items) {
throw new Error(LIST_NO_MUTABLE);
}
reverse() {
throw new Error(LIST_NO_MUTABLE);
}
shift() {
throw new Error(LIST_NO_MUTABLE);
}
unshift(..._items) {
throw new Error(LIST_NO_MUTABLE);
}
splice(_start, _deleteCount, ..._rest) {
throw new Error(LIST_NO_MUTABLE);
}
sort(_fn) {
throw new Error(LIST_NO_MUTABLE);
}
get [Symbol.unscopables]() {
return Array.prototype[Symbol.unscopables];
}
[Symbol.iterator]() {
return this.values();
}
toJSON() {
return this.toArray();
}
toString() {
return this.join(",");
}
toLocaleString(_locales, _options) {
return this.toString();
}
[Symbol.toStringTag]() {
return "[object Array]";
}
static [Symbol.toStringTag]() {
return this._capnp.displayName;
}
};
var List = _List;
_proxyHandler = new WeakMap();
__publicField(List, "_capnp", {
displayName: "List<Generic>",
size: ListElementSize.VOID
});
__privateAdd(List, _proxyHandler, {
get(target, prop, receiver) {
const val = Reflect.get(target, prop, receiver);
if (val !== void 0)
return val;
if (typeof prop === "string") {
return target.get(+prop);
}
}
});
function initList$1(elementSize, length, l, compositeSize) {
let c;
switch (elementSize) {
case ListElementSize.BIT: {
c = l.segment.allocate(Math.ceil(length / 8));
break;
}
case ListElementSize.BYTE:
case ListElementSize.BYTE_2:
case ListElementSize.BYTE_4:
case ListElementSize.BYTE_8:
case ListElementSize.POINTER: {
c = l.segment.allocate(length * getListElementByteLength(elementSize));
break;
}
case ListElementSize.COMPOSITE: {
if (compositeSize === void 0) {
throw new Error(format(PTR_COMPOSITE_SIZE_UNDEFINED));
}
compositeSize = padToWord(compositeSize);
const byteLength = getByteLength(compositeSize) * length;
c = l.segment.allocate(byteLength + 8);
setStructPointer(length, compositeSize, c);
break;
}
case ListElementSize.VOID: {
setListPointer(0, elementSize, length, l);
return;
}
default: {
throw new Error(format(PTR_INVALID_LIST_SIZE, elementSize));
}
}
const res = initPointer(c.segment, c.byteOffset, l);
setListPointer(
res.offsetWords,
elementSize,
length,
res.pointer,
compositeSize
);
}
var Data = class extends List {
static fromPointer(pointer) {
validate(PointerType.LIST, pointer, ListElementSize.BYTE);
return this._fromPointerUnchecked(pointer);
}
static _fromPointerUnchecked(pointer) {
return new this(
pointer.segment,
pointer.byteOffset,
pointer._capnp.depthLimit
);
}
/**
* Copy the contents of `src` into this Data pointer. If `src` is smaller than the length of this pointer then the
* remaining bytes will be zeroed out. Extra bytes in `src` are ignored.
*
* @param {(ArrayBuffer | ArrayBufferView)} src The source buffer.
* @returns {void}
*/
// TODO: Would be nice to have a way to zero-copy a buffer by allocating a new segment into the message with that
// buffer data.
copyBuffer(src) {
const c = getContent(this);
const dstLength = this.length;
const srcLength = src.byteLength;
const i = src instanceof ArrayBuffer ? new Uint8Array(src) : new Uint8Array(
src.buffer,
src.byteOffset,
Math.min(dstLength, srcLength)
);
const o = new Uint8Array(c.segment.buffer, c.byteOffset, this.length);
o.set(i);
if (dstLength > srcLength) {
o.fill(0, srcLength, dstLength);
}
}
/**
* Read a byte from the specified offset.
*
* @param {number} byteOffset The byte offset to read.
* @returns {number} The byte value.
*/
get(byteOffset) {
const c = getContent(this);
return c.segment.getUint8(c.byteOffset + byteOffset);
}
/**
* Write a byte at the specified offset.
*
* @param {number} byteOffset The byte offset to set.
* @param {number} value The byte value to set.
* @returns {void}
*/
set(byteOffset, value) {
const c = getContent(this);
c.segment.setUint8(c.byteOffset + byteOffset, value);
}
/**
* Creates a **copy** of the underlying buffer data and returns it as an ArrayBuffer.
*
* To obtain a reference to the underlying buffer instead, use `toUint8Array()` or `toDataView()`.
*
* @returns {ArrayBuffer} A copy of this data buffer.
*/
toArrayBuffer() {
const c = getContent(this);
return c.segment.buffer.slice(c.byteOffset, c.byteOffset + this.length);
}
/**
* Convert this Data pointer to a DataView representing the pointer's contents.
*
* WARNING: The DataView references memory from a message segment, so do not venture outside the bounds of the
* DataView or else BAD THINGS.
*
* @returns {DataView} A live reference to the underlying buffer.
*/
toDataView() {
const c = getContent(this);
return new DataView(c.segment.buffer, c.byteOffset, this.length);
}
[Symbol.toStringTag]() {
return `Data_${super.toString()}`;
}
/**
* Convert this Data pointer to a Uint8Array representing the pointer's contents.
*
* WARNING: The Uint8Array references memory from a message segment, so do not venture outside the bounds of the
* Uint8Array or else BAD THINGS.
*
* @returns {DataView} A live reference to the underlying buffer.
*/
toUint8Array() {
const c = getContent(this);
return new Uint8Array(c.segment.buffer, c.byteOffset, this.length);
}
};
var textEncoder = new TextEncoder();
var textDecoder = new TextDecoder();
var Text = class extends List {
static fromPointer(pointer) {
validate(PointerType.LIST, pointer, ListElementSize.BYTE);
return textFromPointerUnchecked(pointer);
}
/**
* Read a utf-8 encoded string value from this pointer.
*
* @param {number} [index] The index at which to start reading; defaults to zero.
* @returns {string} The string value.
*/
get(index = 0) {
if (isNull(this))
return "";
const c = getContent(this);
return textDecoder.decode(
new Uint8Array(
c.segment.buffer,
c.byteOffset + index,
this.length - index
)
);
}
/**
* Get the number of utf-8 encoded bytes in this text. This does **not** include the NUL byte.
*
* @returns {number} The number of bytes allocated for the text.
*/
get length() {
return super.length - 1;
}
/**
* Write a utf-8 encoded string value starting at the specified index.
*
* @param {number} index The index at which to start copying the string. Note that if this is not zero the bytes
* before `index` will be left as-is. All bytes after `index` will be overwritten.
* @param {string} value The string value to set.
* @returns {void}
*/
set(index, value) {
const src = textEncoder.encode(value);
const dstLength = src.byteLength + index;
let c;
let original;
if (!isNull(this)) {
c = getContent(this);
let originalLength = this.length;
if (originalLength >= index) {
originalLength = index;
}
original = new Uint8Array(
c.segment.buffer.slice(
c.byteOffset,
c.byteOffset + Math.min(originalLength, index)
)
);
erase(this);
}
initList$1(ListElementSize.BYTE, dstLength + 1, this);
c = getContent(this);
const dst = new Uint8Array(c.segment.buffer, c.byteOffset, dstLength);
if (original)
dst.set(original);
dst.set(src, index);
}
toString() {
return this.get();
}
toJSON() {
return this.get();
}
[Symbol.toPrimitive]() {
return this.get();
}
[Symbol.toStringTag]() {
return `Text_${super.toString()}`;
}
};
function textFromPointerUnchecked(pointer) {
return new Text(
pointer.segment,
pointer.byteOffset,
pointer._capnp.depthLimit
);
}
var Struct = class extends Pointer {
/**
* Create a new pointer to a struct.
*
* @constructor {Struct}
* @param {Segment} segment The segment the pointer resides in.
* @param {number} byteOffset The offset from the beginning of the segment to the beginning of the pointer data.
* @param {any} [depthLimit=MAX_DEPTH] The nesting depth limit for this object.
* @param {number} [compositeIndex] If set, then this pointer is actually a reference to a composite list
* (`this._getPointerTargetType() === PointerType.LIST`), and this number is used as the index of the struct within
* the list. It is not valid to call `initStruct()` on a composite struct the struct contents are initialized when
* the list pointer is initialized.
*/
constructor(segment, byteOffset, depthLimit = MAX_DEPTH, compositeIndex) {
super(segment, byteOffset, depthLimit);
this._capnp.compositeIndex = compositeIndex;
this._capnp.compositeList = compositeIndex !== void 0;
}
static [Symbol.toStringTag]() {
return this._capnp.displayName;
}
[Symbol.toStringTag]() {
return `Struct_${super.toString()}${this._capnp.compositeIndex === void 0 ? "" : `,ci:${this._capnp.compositeIndex}`} > ${getContent(this).toString()}`;
}
};
__publicField(Struct, "_capnp", {
displayName: "Struct"
});
var AnyStruct = class extends Struct {
};
__publicField(AnyStruct, "_capnp", {
displayName: "AnyStruct",
id: "0",
size: new ObjectSize(0, 0)
});
var FixedAnswer = class {
struct() {
return Promise.resolve(this.structSync());
}
};
var ErrorAnswer = class extends FixedAnswer {
err;
constructor(err) {
super();
this.err = err;
}
structSync() {
throw this.err;
}
pipelineCall(_transform, _call) {
return this;
}
pipelineClose(_transform) {
throw this.err;
}
};
var ErrorClient = class {
err;
constructor(err) {
this.err = err;
}
call(_call) {
return new ErrorAnswer(this.err);
}
close() {
throw this.err;
}
};
function clientOrNull(client) {
return client ? client : new ErrorClient(new Error(RPC_NULL_CLIENT));
}
var TMP_WORD = new DataView(new ArrayBuffer(8));
function initStruct(size, s) {
if (s._capnp.compositeIndex !== void 0) {
throw new Error(format(PTR_INIT_COMPOSITE_STRUCT, s));
}
erase(s);
const c = s.segment.allocate(getByteLength(size));
const res = initPointer(c.segment, c.byteOffset, s);
setStructPointer(res.offsetWords, size, res.pointer);
}
function initStructAt(index, StructClass, p) {
const s = getPointerAs(index, StructClass, p);
initStruct(StructClass._capnp.size, s);
return s;
}
function checkPointerBounds(index, s) {
const pointerLength = getSize(s).pointerLength;
if (index < 0 || index >= pointerLength) {
throw new Error(
format(PTR_STRUCT_POINTER_OUT_OF_BOUNDS, s, index, pointerLength)
);
}
}
function getInterfaceClientOrNullAt(index, s) {
return getInterfaceClientOrNull(getPointer(index, s));
}
function getInterfaceClientOrNull(p) {
let client = null;
const capId = getInterfacePointer(p);
const capTable = p.segment.message._capnp.capTable;
if (capTable && capId >= 0 && capId < capTable.length) {
client = capTable[capId];
}
return clientOrNull(client);
}
function resize(dstSize, s) {
const srcSize = getSize(s);
const srcContent = getContent(s);
const dstContent = s.segment.allocate(getByteLength(dstSize));
dstContent.segment.copyWords(
dstContent.byteOffset,
srcContent.segment,
srcContent.byteOffset,
Math.min(getDataWordLength(srcSize), getDataWordLength(dstSize))
);
const res = initPointer(dstContent.segment, dstContent.byteOffset, s);
setStructPointer(res.offsetWords, dstSize, res.pointer);
for (let i = 0; i < Math.min(srcSize.pointerLength, dstSize.pointerLength); i++) {
const srcPtr = new Pointer(
srcContent.segment,
srcContent.byteOffset + srcSize.dataByteLength + i * 8
);
if (isNull(srcPtr)) {
continue;
}
const srcPtrTarget = followFars(srcPtr);
const srcPtrContent = getContent(srcPtr);
const dstPtr = new Pointer(
dstContent.segment,
dstContent.byteOffset + dstSize.dataByteLength + i * 8
);
if (getTargetPointerType(srcPtr) === PointerType.LIST && getTargetListElementSize(srcPtr) === ListElementSize.COMPOSITE) {
srcPtrContent.byteOffset -= 8;
}
const r = initPointer(
srcPtrContent.segment,
srcPtrContent.byteOffset,
dstPtr
);
const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
r.pointer.segment.setUint32(r.pointer.byteOffset, a | r.offsetWords << 2);
r.pointer.segment.setUint32(r.pointer.byteOffset + 4, b);
}
srcContent.segment.fillZeroWords(
srcContent.byteOffset,
getWordLength(srcSize)
);
}
function getAs(StructClass, s) {
return new StructClass(
s.segment,
s.byteOffset,
s._capnp.depthLimit,
s._capnp.compositeIndex
);
}
function getBit(bitOffset, s, defaultMask) {
const byteOffset = Math.floor(bitOffset / 8);
const bitMask = 1 << bitOffset % 8;
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
const v = ds.segment.getUint8(ds.byteOffset + byteOffset);
if (defaultMask === void 0)
return (v & bitMask) !== 0;
const defaultValue = defaultMask.getUint8(0);
return ((v ^ defaultValue) & bitMask) !== 0;
}
function getData(index, s, defaultValue) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
const l = new Data(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
if (isNull(l)) {
if (defaultValue) {
copyFrom(defaultValue, l);
} else {
initList$1(ListElementSize.BYTE, 0, l);
}
}
return l;
}
function getDataSection(s) {
return getContent(s);
}
function getFloat32(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getFloat32(ds.byteOffset + byteOffset);
}
const v = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
TMP_WORD.setUint32(0, v, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getFloat32(0, NATIVE_LITTLE_ENDIAN);
}
function getFloat64(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
TMP_WORD.setUint32(0, lo, NATIVE_LITTLE_ENDIAN);
TMP_WORD.setUint32(4, hi, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getFloat64(0, NATIVE_LITTLE_ENDIAN);
}
return ds.segment.getFloat64(ds.byteOffset + byteOffset);
}
function getInt16(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 2, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getInt16(ds.byteOffset + byteOffset);
}
const v = ds.segment.getUint16(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
TMP_WORD.setUint16(0, v, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getInt16(0, NATIVE_LITTLE_ENDIAN);
}
function getInt32(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getInt32(ds.byteOffset + byteOffset);
}
const v = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
TMP_WORD.setUint32(0, v, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getInt32(0, NATIVE_LITTLE_ENDIAN);
}
function getInt64(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, lo, NATIVE_LITTLE_ENDIAN);
TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, hi, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getBigInt64(0, NATIVE_LITTLE_ENDIAN);
}
return ds.segment.getInt64(ds.byteOffset + byteOffset);
}
function getInt8(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getInt8(ds.byteOffset + byteOffset);
}
const v = ds.segment.getUint8(ds.byteOffset + byteOffset) ^ defaultMask.getUint8(0);
TMP_WORD.setUint8(0, v);
return TMP_WORD.getInt8(0);
}
function getList(index, ListClass, s, defaultValue) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
const l = new ListClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
if (isNull(l)) {
if (defaultValue) {
copyFrom(defaultValue, l);
} else {
initList$1(ListClass._capnp.size, 0, l, ListClass._capnp.compositeSize);
}
} else if (ListClass._capnp.compositeSize !== void 0) {
const srcSize = getTargetCompositeListSize(l);
const dstSize = ListClass._capnp.compositeSize;
if (dstSize.dataByteLength > srcSize.dataByteLength || dstSize.pointerLength > srcSize.pointerLength) {
const srcContent = getContent(l);
const srcLength = getTargetListLength(l);
const dstContent = l.segment.allocate(
getByteLength(dstSize) * srcLength + 8
);
const res = initPointer(dstContent.segment, dstContent.byteOffset, l);
setListPointer(
res.offsetWords,
ListClass._capnp.size,
srcLength,
res.pointer,
dstSize
);
setStructPointer(srcLength, dstSize, dstContent);
dstContent.byteOffset += 8;
for (let i = 0; i < srcLength; i++) {
const srcElementOffset = srcContent.byteOffset + i * getByteLength(srcSize);
const dstElementOffset = dstContent.byteOffset + i * getByteLength(dstSize);
dstContent.segment.copyWords(
dstElementOffset,
srcContent.segment,
srcElementOffset,
getWordLength(srcSize)
);
for (let j = 0; j < srcSize.pointerLength; j++) {
const srcPtr = new Pointer(
srcContent.segment,
srcElementOffset + srcSize.dataByteLength + j * 8
);
const dstPtr = new Pointer(
dstContent.segment,
dstElementOffset + dstSize.dataByteLength + j * 8
);
const srcPtrTarget = followFars(srcPtr);
const srcPtrContent = getContent(srcPtr);
if (getTargetPointerType(srcPtr) === PointerType.LIST && getTargetListElementSize(srcPtr) === ListElementSize.COMPOSITE) {
srcPtrContent.byteOffset -= 8;
}
const r = initPointer(
srcPtrContent.segment,
srcPtrContent.byteOffset,
dstPtr
);
const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
r.pointer.segment.setUint32(
r.pointer.byteOffset,
a | r.offsetWords << 2
);
r.pointer.segment.setUint32(r.pointer.byteOffset + 4, b);
}
}
srcContent.segment.fillZeroWords(
srcContent.byteOffset,
getWordLength(srcSize) * srcLength
);
}
}
return l;
}
function getPointer(index, s) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
return new Pointer(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
}
function getPointerAs(index, PointerClass, s) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
return new PointerClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
}
function getPointerSection(s) {
const ps = getContent(s);
ps.byteOffset += padToWord$1(getSize(s).dataByteLength);
return ps;
}
function getSize(s) {
if (s._capnp.compositeIndex !== void 0) {
const c = getContent(s, true);
c.byteOffset -= 8;
return getStructSize(c);
}
return getTargetStructSize(s);
}
function getStruct(index, StructClass, s, defaultValue) {
const t = getPointerAs(index, StructClass, s);
if (isNull(t)) {
if (defaultValue) {
copyFrom(defaultValue, t);
} else {
initStruct(StructClass._capnp.size, t);
}
} else {
validate(PointerType.STRUCT, t);
const ts = getTargetStructSize(t);
if (ts.dataByteLength < StructClass._capnp.size.dataByteLength || ts.pointerLength < StructClass._capnp.size.pointerLength) {
resize(StructClass._capnp.size, t);
}
}
return t;
}
function getText(index, s, defaultValue) {
const t = Text.fromPointer(getPointer(index, s));
if (isNull(t) && defaultValue)
t.set(0, defaultValue);
return t.get(0);
}
function getUint16(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 2, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getUint16(ds.byteOffset + byteOffset);
}
return ds.segment.getUint16(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
}
function getUint32(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getUint32(ds.byteOffset + byteOffset);
}
return ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
}
function getUint64(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, lo, NATIVE_LITTLE_ENDIAN);
TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, hi, NATIVE_LITTLE_ENDIAN);
return TMP_WORD.getBigUint64(0, NATIVE_LITTLE_ENDIAN);
}
return ds.segment.getUint64(ds.byteOffset + byteOffset);
}
function getUint8(byteOffset, s, defaultMask) {
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
if (defaultMask === void 0) {
return ds.segment.getUint8(ds.byteOffset + byteOffset);
}
return ds.segment.getUint8(ds.byteOffset + byteOffset) ^ defaultMask.getUint8(0);
}
function initData(index, length, s) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
const l = new Data(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
erase(l);
initList$1(ListElementSize.BYTE, length, l);
return l;
}
function initList(index, ListClass, length, s) {
checkPointerBounds(index, s);
const ps = getPointerSection(s);
ps.byteOffset += index * 8;
const l = new ListClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
erase(l);
initList$1(ListClass._capnp.size, length, l, ListClass._capnp.compositeSize);
return l;
}
function setBit(bitOffset, value, s, defaultMask) {
const byteOffset = Math.floor(bitOffset / 8);
const bitMask = 1 << bitOffset % 8;
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
const b = ds.segment.getUint8(ds.byteOffset + byteOffset);
if (defaultMask !== void 0) {
value = (defaultMask.getUint8(0) & bitMask) === 0 ? value : !value;
}
ds.segment.setUint8(
ds.byteOffset + byteOffset,
value ? b | bitMask : b & ~bitMask
);
}
function setFloat32(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setFloat32(0, value, NATIVE_LITTLE_ENDIAN);
const v = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, v);
return;
}
ds.segment.setFloat32(ds.byteOffset + byteOffset, value);
}
function setFloat64(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setFloat64(0, value, NATIVE_LITTLE_ENDIAN);
const lo = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
const hi = TMP_WORD.getUint32(4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
return;
}
ds.segment.setFloat64(ds.byteOffset + byteOffset, value);
}
function setInt16(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 2, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setInt16(0, value, NATIVE_LITTLE_ENDIAN);
const v = TMP_WORD.getUint16(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint16(0, true);
ds.segment.setUint16(ds.byteOffset + byteOffset, v);
return;
}
ds.segment.setInt16(ds.byteOffset + byteOffset, value);
}
function setInt32(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setInt32(0, value, NATIVE_LITTLE_ENDIAN);
const v = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, v);
return;
}
ds.segment.setInt32(ds.byteOffset + byteOffset, value);
}
function setInt64(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setBigInt64(0, value, NATIVE_LITTLE_ENDIAN);
const lo = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
const hi = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
return;
}
ds.segment.setInt64(ds.byteOffset + byteOffset, value);
}
function setInt8(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setInt8(0, value);
const v = TMP_WORD.getUint8(0) ^ defaultMask.getUint8(0);
ds.segment.setUint8(ds.byteOffset + byteOffset, v);
return;
}
ds.segment.setInt8(ds.byteOffset + byteOffset, value);
}
function setText(index, value, s) {
Text.fromPointer(getPointer(index, s)).set(0, value);
}
function setUint16(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 2, s);
const ds = getDataSection(s);
if (defaultMask !== void 0)
value ^= defaultMask.getUint16(0, true);
ds.segment.setUint16(ds.byteOffset + byteOffset, value);
}
function setUint32(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 4, s);
const ds = getDataSection(s);
if (defaultMask !== void 0)
value ^= defaultMask.getUint32(0, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, value);
}
function setUint64(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 8, s);
const ds = getDataSection(s);
if (defaultMask !== void 0) {
TMP_WORD.setBigUint64(0, value, NATIVE_LITTLE_ENDIAN);
const lo = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
const hi = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
return;
}
ds.segment.setUint64(ds.byteOffset + byteOffset, value);
}
function setUint8(byteOffset, value, s, defaultMask) {
checkDataBounds(byteOffset, 1, s);
const ds = getDataSection(s);
if (defaultMask !== void 0)
value ^= defaultMask.getUint8(0);
ds.segment.setUint8(ds.byteOffset + byteOffset, value);
}
function testWhich(name, found, wanted, s) {
if (found !== wanted) {
throw new Error(format(PTR_INVALID_UNION_ACCESS, s, name, found, wanted));
}
}
function checkDataBounds(byteOffset, byteLength, s) {
const dataByteLength = getSize(s).dataByteLength;
if (byteOffset < 0 || byteLength < 0 || byteOffset + byteLength > dataByteLength) {
throw new Error(
format(
PTR_STRUCT_DATA_OUT_OF_BOUNDS,
s,
byteLength,
byteOffset,
dataByteLength
)
);
}
}
// ../../node_modules/.pnpm/capnp-es@0.0.7_typescript@5.7.3/node_modules/capnp-es/dist/shared/capnp-es.Cx0B_Qxd.mjs
var ArenaKind = /* @__PURE__ */ ((ArenaKind2) => {
ArenaKind2[ArenaKind2["SINGLE_SEGMENT"] = 0] = "SINGLE_SEGMENT";
ArenaKind2[ArenaKind2["MULTI_SEGMENT"] = 1] = "MULTI_SEGMENT";
return ArenaKind2;
})(ArenaKind || {});
var ArenaAllocationResult = class {
/**
* The newly allocated buffer. This buffer might be a copy of an existing segment's buffer with free space appended.
*
* @type {ArrayBuffer}
*/
buffer;
/**
* The id of the newly-allocated segment.
*
* @type {number}
*/
id;
constructor(id, buffer) {
this.id = id;
this.buffer = buffer;
}
};
var MultiSegmentArena = class {
constructor(buffers = [new ArrayBuffer(DEFAULT_BUFFER_SIZE)]) {
this.buffers = buffers;
let i = buffers.length;
while (--i >= 0) {
if ((buffers[i].byteLength & 7) !== 0) {
throw new Error(format(SEG_NOT_WORD_ALIGNED, buffers[i].byteLength));
}
}
}
kind = ArenaKind.MULTI_SEGMENT;
toString() {
return format("MultiSegmentArena_segments:%d", getNumSegments$2(this));
}
};
__publicField(MultiSegmentArena, "allocate", allocate$2);
__publicField(MultiSegmentArena, "getBuffer", getBuffer$2);
__publicField(MultiSegmentArena, "getNumSegments", getNumSegments$2);
function allocate$2(minSize, m) {
const b = new ArrayBuffer(padToWord$1(Math.max(minSize, DEFAULT_BUFFER_SIZE)));
m.buffers.push(b);
return new ArenaAllocationResult(m.buffers.length - 1, b);
}
function getBuffer$2(id, m) {
if (id < 0 || id >= m.buffers.length) {
throw new Error(format(SEG_ID_OUT_OF_BOUNDS, id));
}
return m.buffers[id];
}
function getNumSegments$2(m) {
return m.buffers.length;
}
var SingleSegmentArena = class {
buffer;
kind = ArenaKind.SINGLE_SEGMENT;
constructor(buffer = new ArrayBuffer(DEFAULT_BUFFER_SIZE)) {
if ((buffer.byteLength & 7) !== 0) {
throw new Error(format(SEG_NOT_WORD_ALIGNED, buffer.byteLength));
}
this.buffer = buffer;
}
toString() {
return format("SingleSegmentArena_len:%x", this.buffer.byteLength);
}
};
__publicField(SingleSegmentArena, "allocate", allocate$1);
__publicField(SingleSegmentArena, "getBuffer", getBuffer$1);
__publicField(SingleSegmentArena, "getNumSegments", getNumSegments$1);
function allocate$1(minSize, segments, s) {
const srcBuffer = segments.length > 0 ? segments[0].buffer : s.buffer;
minSize = minSize < MIN_SINGLE_SEGMENT_GROWTH ? MIN_SINGLE_SEGMENT_GROWTH : padToWord$1(minSize);
s.buffer = new ArrayBuffer(srcBuffer.byteLength + minSize);
new Float64Array(s.buffer).set(new Float64Array(srcBuffer));
return new ArenaAllocationResult(0, s.buffer);
}
function getBuffer$1(id, s) {
if (id !== 0)
throw new Error(format(SEG_GET_NON_ZERO_SINGLE, id));
return s.buffer;
}
function getNumSegments$1() {
return 1;
}
var Arena = class {
};
__publicField(Arena, "allocate", allocate);
__publicField(Arena, "copy", copy$1);
__publicField(Arena, "getBuffer", getBuffer);
__publicField(Arena, "getNumSegments", getNumSegments);
function allocate(minSize, segments, a) {
switch (a.kind) {
case ArenaKind.MULTI_SEGMENT: {
return MultiSegmentArena.allocate(minSize, a);
}
case ArenaKind.SINGLE_SEGMENT: {
return SingleSegmentArena.allocate(minSize, segments, a);
}
default: {
return assertNever(a);
}
}
}
function copy$1(a) {
switch (a.kind) {
case ArenaKind.MULTI_SEGMENT: {
let i = a.buffers.length;
const buffers = Array.from({ length: i });
while (--i >= 0) {
buffers[i] = a.buffers[i].slice(0);
}
return new MultiSegmentArena(buffers);
}
case ArenaKind.SINGLE_SEGMENT: {
return new SingleSegmentArena(a.buffer.slice(0));
}
default: {
return assertNever(a);
}
}
}
function getBuffer(id, a) {
switch (a.kind) {
case ArenaKind.MULTI_SEGMENT: {
return MultiSegmentArena.getBuffer(id, a);
}
case ArenaKind.SINGLE_SEGMENT: {
return SingleSegmentArena.getBuffer(id, a);
}
default: {
return assertNever(a);
}
}
}
function getNumSegments(a) {
switch (a.kind) {
case ArenaKind.MULTI_SEGMENT: {
return MultiSegmentArena.getNumSegments(a);
}
case ArenaKind.SINGLE_SEGMENT: {
return SingleSegmentArena.getNumSegments();
}
default: {
return assertNever(a);
}
}
}
function getHammingWeight(x) {
let w = x - (x >> 1 & 1431655765);
w = (w & 858993459) + (w >> 2 & 858993459);
return (w + (w >> 4) & 252645135) * 16843009 >> 24;
}
function getTagByte(a, b, c, d, e, f, g, h) {
return (a === 0 ? 0 : 1) | (b === 0 ? 0 : 2) | (c === 0 ? 0 : 4) | (d === 0 ? 0 : 8) | (e === 0 ? 0 : 16) | (f === 0 ? 0 : 32) | (g === 0 ? 0 : 64) | (h === 0 ? 0 : 128);
}
function getUnpackedByteLength(packed) {
const p = new Uint8Array(packed);
let wordCount = 0;
let lastTag = 119;
for (let i = 0; i < p.byteLength; ) {
const tag = p[i];
if (lastTag === 0) {
wordCount += tag;
i++;
lastTag = 119;
} else if (lastTag === 255) {
wordCount += tag;
i += tag * 8 + 1;
lastTag = 119;
} else {
wordCount++;
i += getHammingWeight(tag) + 1;
lastTag = tag;
}
}
return wordCount * 8;
}
function getZeroByteCount(a, b, c, d, e, f, g, h) {
return (a === 0 ? 1 : 0) + (b === 0 ? 1 : 0) + (c === 0 ? 1 : 0) + (d === 0 ? 1 : 0) + (e === 0 ? 1 : 0) + (f === 0 ? 1 : 0) + (g === 0 ? 1 : 0) + (h === 0 ? 1 : 0);
}
function pack(unpacked, byteOffset = 0, byteLength) {
if (unpacked.byteLength % 8 !== 0)
throw new Error(MSG_PACK_NOT_WORD_ALIGNED);
const src = new Uint8Array(unpacked, byteOffset, byteLength);
const dst = [];
let lastTag = 119;
let spanWordCountOffset = 0;
let rangeWordCount = 0;
for (let srcByteOffset = 0; srcByteOffset < src.byteLength; srcByteOffset += 8) {
const a = src[srcByteOffset];
const b = src[srcByteOffset + 1];
const c = src[srcByteOffset + 2];
const d = src[srcByteOffset + 3];
const e = src[srcByteOffset + 4];
const f = src[srcByteOffset + 5];
const g = src[srcByteOffset + 6];
const h = src[srcByteOffset + 7];
const tag = getTagByte(a, b, c, d, e, f, g, h);
let skipWriteWord = true;
switch (lastTag) {
case 0: {
if (tag !== 0 || rangeWordCount >= 255) {
dst.push(rangeWordCount);
rangeWordCount = 0;
skipWriteWord = false;
} else {
rangeWordCount++;
}
break;
}
case 255: {
const zeroCount = getZeroByteCount(a, b, c, d, e, f, g, h);
if (zeroCount >= PACK_SPAN_THRESHOLD || rangeWordCount >= 255) {
dst[spanWordCountOffset] = rangeWordCount;
rangeWordCount = 0;
skipWriteWord = false;
} else {
dst.push(a, b, c, d, e, f, g, h);
rangeWordCount++;
}
break;
}
default: {
skipWriteWord = false;
break;
}
}
if (skipWriteWord)
continue;
dst.push(tag);
lastTag = tag;
if (a !== 0)
dst.push(a);
if (b !== 0)
dst.push(b);
if (c !== 0)
dst.push(c);
if (d !== 0)
dst.push(d);
if (e !== 0)
dst.push(e);
if (f !== 0)
dst.push(f);
if (g !== 0)
dst.push(g);
if (h !== 0)
dst.push(h);
if (tag === 255) {
spanWordCountOffset = dst.length;
dst.push(0);
}
}
if (lastTag === 0) {
dst.push(rangeWordCount);
} else if (lastTag === 255) {
dst[spanWordCountOffset] = rangeWordCount;
}
return new Uint8Array(dst).buffer;
}
function unpack(packed) {
const src = new Uint8Array(packed);
const dst = new Uint8Array(new ArrayBuffer(getUnpackedByteLength(packed)));
let lastTag = 119;
for (let srcByteOffset = 0, dstByteOffset = 0; srcByteOffset < src.byteLength; ) {
const tag = src[srcByteOffset];
if (lastTag === 0) {
dstByteOffset += tag * 8;
srcByteOffset++;
lastTag = 119;
} else if (lastTag === 255) {
const spanByteLength = tag * 8;
dst.set(
src.subarray(srcByteOffset + 1, srcByteOffset + 1 + spanByteLength),
dstByteOffset
);
dstByteOffset += spanByteLength;
srcByteOffset += 1 + spanByteLength;
lastTag = 119;
} else {
srcByteOffset++;
for (let i = 1; i <= 128; i <<= 1) {
if ((tag & i) !== 0)
dst[dstByteOffset] = src[srcByteOffset++];
dstByteOffset++;
}
lastTag = tag;
}
}
return dst.buffer;
}
var Segment = class {
buffer;
/** The number of bytes currently allocated in the segment. */
byteLength;
/**
* This value should always be zero. It's only here to satisfy the DataView interface.
*
* In the future the Segment implementation (or a child class) may allow accessing the buffer from a nonzero offset,
* but that adds a lot of extra arithmetic.
*/
byteOffset;
[Symbol.toStringTag] = "Segment";
id;
message;
_dv;
constructor(id, message, buffer, byteLength = 0) {
this.id = id;
this.message = message;
this.buffer = buffer;
this._dv = new DataView(buffer);
this.byteOffset = 0;
this.byteLength = byteLength;
}
/**
* Attempt to allocate the requested number of bytes in this segment. If this segment is full this method will return
* a pointer to freshly allocated space in another segment from the same message.
*
* @param {number} byteLength The number of bytes to allocate, will be rounded up to the nearest word.
* @returns {Pointer} A pointer to the newly allocated space.
*/
allocate(byteLength) {
let segment = this;
byteLength = padToWord$1(byteLength);
if (byteLength > MAX_SEGMENT_LENGTH - 8) {
throw new Error(format(SEG_SIZE_OVERFLOW, byteLength));
}
if (!segment.hasCapacity(byteLength)) {
segment = segment.message.allocateSegment(byteLength);
}
const byteOffset = segment.byteLength;
segment.byteLength = segment.byteLength + byteLength;
return new Pointer(segment, byteOffset);
}
/**
* Quickly copy a word (8 bytes) from `srcSegment` into this one at the given offset.
*
* @param {number} byteOffset The offset to write the word to.
* @param {Segment} srcSegment The segment to copy the word from.
* @param {number} srcByteOffset The offset from the start of `srcSegment` to copy from.
* @returns {void}
*/
copyWord(byteOffset, srcSegment, srcByteOffset) {
const value = srcSegment._dv.getFloat64(
srcByteOffset,
NATIVE_LITTLE_ENDIAN
);
this._dv.setFloat64(byteOffset, value, NATIVE_LITTLE_ENDIAN);
}
/**
* Quickly copy words from `srcSegment` into this one.
*
* @param {number} byteOffset The offset to start copying into.
* @param {Segment} srcSegment The segment to copy from.
* @param {number} srcByteOffset The start offset to copy from.
* @param {number} wordLength The number of words to copy.
* @returns {void}
*/
copyWords(byteOffset, srcSegment, srcByteOffset, wordLength) {
const dst = new Float64Array(this.buffer, byteOffset, wordLength);
const src = new Float64Array(srcSegment.buffer, srcByteOffset, wordLength);
dst.set(src);
}
/**
* Quickly fill a number of words in the buffer with zeroes.
*
* @param {number} byteOffset The first byte to set to zero.
* @param {number} wordLength The number of words (not bytes!) to zero out.
* @returns {void}
*/
fillZeroWords(byteOffset, wordLength) {
new Float64Array(this.buffer, byteOffset, wordLength).fill(0);
}
getBigInt64(byteOffset, littleEndian) {
return this._dv.getBigInt64(byteOffset, littleEndian);
}
getBigUint64(byteOffset, littleEndian) {
return this._dv.getBigUint64(byteOffset, littleEndian);
}
/**
* Get the total number of bytes available in this segment (the size of its underlying buffer).
*
* @returns {number} The total number of bytes this segment can hold.
*/
getCapacity() {
return this.buffer.byteLength;
}
/**
* Read a float32 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getFloat32(byteOffset) {
return this._dv.getFloat32(byteOffset, true);
}
/**
* Read a float64 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getFloat64(byteOffset) {
return this._dv.getFloat64(byteOffset, true);
}
/**
* Read an int16 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getInt16(byteOffset) {
return this._dv.getInt16(byteOffset, true);
}
/**
* Read an int32 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getInt32(byteOffset) {
return this._dv.getInt32(byteOffset, true);
}
/**
* Read an int64 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getInt64(byteOffset) {
return this._dv.getBigInt64(byteOffset, true);
}
/**
* Read an int8 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getInt8(byteOffset) {
return this._dv.getInt8(byteOffset);
}
/**
* Read a uint16 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getUint16(byteOffset) {
return this._dv.getUint16(byteOffset, true);
}
/**
* Read a uint32 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getUint32(byteOffset) {
return this._dv.getUint32(byteOffset, true);
}
/**
* Read a uint64 value (as a bigint) out of this segment.
* NOTE: this does not copy the memory region, so updates to the underlying buffer will affect the returned value!
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getUint64(byteOffset) {
return this._dv.getBigUint64(byteOffset, true);
}
/**
* Read a uint8 value out of this segment.
*
* @param {number} byteOffset The offset in bytes to the value.
* @returns {number} The value.
*/
getUint8(byteOffset) {
return this._dv.getUint8(byteOffset);
}
hasCapacity(byteLength) {
return this.buffer.byteLength - this.byteLength >= byteLength;
}
/**
* Quickly check the word at the given offset to see if it is equal to zero.
*
* PERF_V8: Fastest way to do this is by reading the whole word as a `number` (float64) in the _native_ endian format
* and see if it's zero.
*
* Benchmark: http://jsben.ch/#/Pjooc
*
* @param {number} byteOffset The offset to the word.
* @returns {boolean} `true` if the word is zero.
*/
isWordZero(byteOffset) {
return this._dv.getFloat64(byteOffset, NATIVE_LITTLE_ENDIAN) === 0;
}
/**
* Swap out this segment's underlying buffer with a new one. It's assumed that the new buffer has the same content but
* more free space, otherwise all existing pointers to this segment will be hilariously broken.
*
* @param {ArrayBuffer} buffer The new buffer to use.
* @returns {void}
*/
replaceBuffer(buffer) {
if (this.buffer === buffer)
return;
if (buffer.byteLength < this.byteLength) {
throw new Error(SEG_REPLACEMENT_BUFFER_TOO_SMALL);
}
this._dv = new DataView(buffer);
this.buffer = buffer;
}
setBigInt64(byteOffset, value, littleEndian) {
this._dv.setBigInt64(byteOffset, value, littleEndian);
}
/** WARNING: This function is not yet implemented. */
setBigUint64(byteOffset, value, littleEndian) {
this._dv.setBigUint64(byteOffset, value, littleEndian);
}
/**
* Write a float32 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setFloat32(byteOffset, val) {
this._dv.setFloat32(byteOffset, val, true);
}
/**
* Write an float64 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setFloat64(byteOffset, val) {
this._dv.setFloat64(byteOffset, val, true);
}
/**
* Write an int16 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setInt16(byteOffset, val) {
this._dv.setInt16(byteOffset, val, true);
}
/**
* Write an int32 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setInt32(byteOffset, val) {
this._dv.setInt32(byteOffset, val, true);
}
/**
* Write an int8 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setInt8(byteOffset, val) {
this._dv.setInt8(byteOffset, val);
}
/**
* Write an int64 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {bigint} val The value to store.
* @returns {void}
*/
setInt64(byteOffset, val) {
this._dv.setBigInt64(byteOffset, val, true);
}
/**
* Write a uint16 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setUint16(byteOffset, val) {
this._dv.setUint16(byteOffset, val, true);
}
/**
* Write a uint32 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setUint32(byteOffset, val) {
this._dv.setUint32(byteOffset, val, true);
}
/**
* Write a uint64 value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {bigint} val The value to store.
* @returns {void}
*/
setUint64(byteOffset, val) {
this._dv.setBigUint64(byteOffset, val, true);
}
/**
* Write a uint8 (byte) value to the specified offset.
*
* @param {number} byteOffset The offset from the beginning of the buffer.
* @param {number} val The value to store.
* @returns {void}
*/
setUint8(byteOffset, val) {
this._dv.setUint8(byteOffset, val);
}
/**
* Write a zero word (8 bytes) to the specified offset. This is slightly faster than calling `setUint64` or
* `setFloat64` with a zero value.
*
* Benchmark: http://jsben.ch/#/dUdPI
*
* @param {number} byteOffset The offset of the word to set to zero.
* @returns {void}
*/
setWordZero(byteOffset) {
this._dv.setFloat64(byteOffset, 0, NATIVE_LITTLE_ENDIAN);
}
toString() {
return format(
"Segment_id:%d,off:%a,len:%a,cap:%a",
this.id,
this.byteLength,
this.byteOffset,
this.buffer.byteLength
);
}
};
var Message = class {
_capnp;
/**
* A Cap'n Proto message.
*
* SECURITY WARNING: In Node.js do not pass a Buffer's internal array buffer into this constructor. Pass the buffer
* directly and everything will be fine. If not, your message will potentially be initialized with random memory
* contents!
*
* The constructor method creates a new Message, optionally using a provided arena for segment allocation, or a buffer
* to read from.
*
* @constructor {Message}
*
* @param {AnyArena|ArrayBufferView|ArrayBuffer} [src] The source for the message.
* A value of `undefined` will cause the message to initialize with a single segment arena only big enough for the
* root pointer; it will expand as you go. This is a reasonable choice for most messages.
*
* Passing an arena will cause the message to use that arena for its segment allocation. Contents will be accepted
* as-is.
*
* Passing an array buffer view (like `DataView`, `Uint8Array` or `Buffer`) will create a **copy** of the source
* buffer; beware of the potential performance cost!
*
* @param {boolean} [packed] Whether or not the message is packed. If `true` (the default), the message will be
* unpacked.
*
* @param {boolean} [singleSegment] If true, `src` will be treated as a message consisting of a single segment without
* a framing header.
*
*/
constructor(src, packed = true, singleSegment = false) {
this._capnp = initMessage(src, packed, singleSegment);
if (src)
preallocateSegments(this);
}
allocateSegment(byteLength) {
return allocateSegment(byteLength, this);
}
/**
* Copies the contents of this message into an identical message with its own ArrayBuffers.
*
* @returns A copy of this message.
*/
copy() {
return copy(this);
}
/**
* Create a pretty-printed string dump of this message; incredibly useful for debugging.
*
* WARNING: Do not call this method on large messages!
*
* @returns {string} A big steaming pile of pretty hex digits.
*/
dump() {
return dump2(this);
}
/**
* Get a struct pointer for the root of this message. This is primarily used when reading a message; it will not
* overwrite existing data.
*
* @template T
* @param {StructCtor<T>} RootStruct The struct type to use as the root.
* @returns {T} A struct representing the root of the message.
*/
getRoot(RootStruct) {
return getRoot(RootStruct, this);
}
/**
* Get a segment by its id.
*
* This will lazily allocate the first segment if it doesn't already exist.
*
* @param {number} id The segment id.
* @returns {Segment} The requested segment.
*/
getSegment(id) {
return getSegment(id, this);
}
/**
* Initialize a new message using the provided struct type as the root.
*
* @template T
* @param {StructCtor<T>} RootStruct The struct type to use as the root.
* @returns {T} An initialized struct pointing to the root of the message.
*/
initRoot(RootStruct) {
return initRoot(RootStruct, this);
}
/**
* Set the root of the message to a copy of the given pointer. Used internally
* to make copies of pointers for default values.
*
* @param {Pointer} src The source pointer to copy.
* @returns {void}
*/
setRoot(src) {
setRoot(src, this);
}
/**
* Combine the contents of this message's segments into a single array buffer and prepend a stream framing header
* containing information about the following segment data.
*
* @returns {ArrayBuffer} An ArrayBuffer with the contents of this message.
*/
toArrayBuffer() {
return toArrayBuffer(this);
}
/**
* Like `toArrayBuffer()`, but also applies the packing algorithm to the output. This is typically what you want to
* use if you're sending the message over a network link or other slow I/O interface where size matters.
*
* @returns {ArrayBuffer} A packed message.
*/
toPackedArrayBuffer() {
return toPackedArrayBuffer(this);
}
addCap(client) {
if (!this._capnp.capTable) {
this._capnp.capTable = [];
}
const id = this._capnp.capTable.length;
this._capnp.capTable.push(client);
return id;
}
toString() {
return `Message_arena:${this._capnp.arena}`;
}
};
__publicField(Message, "allocateSegment", allocateSegment);
__publicField(Message, "dump", dump2);
__publicField(Message, "getRoot", getRoot);
__publicField(Message, "getSegment", getSegment);
__publicField(Message, "initRoot", initRoot);
__publicField(Message, "readRawPointer", readRawPointer);
__publicField(Message, "toArrayBuffer", toArrayBuffer);
__publicField(Message, "toPackedArrayBuffer", toPackedArrayBuffer);
function initMessage(src, packed = true, singleSegment = false) {
if (src === void 0) {
return {
arena: new SingleSegmentArena(),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT
};
}
if (isAnyArena(src)) {
return { arena: src, segments: [], traversalLimit: DEFAULT_TRAVERSE_LIMIT };
}
let buf = src;
if (isArrayBufferView(buf)) {
buf = buf.buffer.slice(
buf.byteOffset,
buf.byteOffset + buf.byteLength
);
}
if (packed)
buf = unpack(buf);
if (singleSegment) {
return {
arena: new SingleSegmentArena(buf),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT
};
}
return {
arena: new MultiSegmentArena(getFramedSegments(buf)),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT
};
}
function getFramedSegments(message) {
const dv = new DataView(message);
const segmentCount = dv.getUint32(0, true) + 1;
const segments = Array.from({ length: segmentCount });
let byteOffset = 4 + segmentCount * 4;
byteOffset += byteOffset % 8;
if (byteOffset + segmentCount * 4 > message.byteLength) {
throw new Error(MSG_INVALID_FRAME_HEADER);
}
for (let i = 0; i < segmentCount; i++) {
const byteLength = dv.getUint32(4 + i * 4, true) * 8;
if (byteOffset + byteLength > message.byteLength) {
throw new Error(MSG_INVALID_FRAME_HEADER);
}
segments[i] = message.slice(byteOffset, byteOffset + byteLength);
byteOffset += byteLength;
}
return segments;
}
function preallocateSegments(m) {
const numSegments = Arena.getNumSegments(m._capnp.arena);
m._capnp.segments = Array.from({ length: numSegments });
for (let i = 0; i < numSegments; i++) {
if (i === 0 && Arena.getBuffer(i, m._capnp.arena).byteLength < 8) {
throw new Error(MSG_SEGMENT_TOO_SMALL);
}
const buffer = Arena.getBuffer(i, m._capnp.arena);
const segment = new Segment(i, m, buffer, buffer.byteLength);
m._capnp.segments[i] = segment;
}
}
function isArrayBufferView(src) {
return src.byteOffset !== void 0;
}
function isAnyArena(o) {
return o.kind !== void 0;
}
function allocateSegment(byteLength, m) {
const res = Arena.allocate(byteLength, m._capnp.segments, m._capnp.arena);
let s;
if (res.id === m._capnp.segments.length) {
s = new Segment(res.id, m, res.buffer);
m._capnp.segments.push(s);
} else if (res.id < 0 || res.id > m._capnp.segments.length) {
throw new Error(format(MSG_SEGMENT_OUT_OF_BOUNDS, res.id, m));
} else {
s = m._capnp.segments[res.id];
s.replaceBuffer(res.buffer);
}
return s;
}
function dump2(m) {
let r = "";
if (m._capnp.segments.length === 0) {
return "================\nNo Segments\n================\n";
}
for (let i = 0; i < m._capnp.segments.length; i++) {
r += `================
Segment #${i}
================
`;
const { buffer, byteLength } = m._capnp.segments[i];
const b = new Uint8Array(buffer, 0, byteLength);
r += dumpBuffer(b);
}
return r;
}
function getRoot(RootStruct, m) {
const root = new RootStruct(m.getSegment(0), 0);
validate(PointerType.STRUCT, root);
const ts = getTargetStructSize(root);
if (ts.dataByteLength < RootStruct._capnp.size.dataByteLength || ts.pointerLength < RootStruct._capnp.size.pointerLength) {
resize(RootStruct._capnp.size, root);
}
return root;
}
function getSegment(id, m) {
const segmentLength = m._capnp.segments.length;
if (id === 0 && segmentLength === 0) {
const arenaSegments = Arena.getNumSegments(m._capnp.arena);
if (arenaSegments === 0) {
allocateSegment(DEFAULT_BUFFER_SIZE, m);
} else {
m._capnp.segments[0] = new Segment(
0,
m,
Arena.getBuffer(0, m._capnp.arena)
);
}
if (!m._capnp.segments[0].hasCapacity(8)) {
throw new Error(MSG_SEGMENT_TOO_SMALL);
}
m._capnp.segments[0].allocate(8);
return m._capnp.segments[0];
}
if (id < 0 || id >= segmentLength) {
throw new Error(format(MSG_SEGMENT_OUT_OF_BOUNDS, id, m));
}
return m._capnp.segments[id];
}
function initRoot(RootStruct, m) {
const root = new RootStruct(m.getSegment(0), 0);
initStruct(RootStruct._capnp.size, root);
return root;
}
function readRawPointer(data) {
return new Pointer(new Message(data).getSegment(0), 0);
}
function setRoot(src, m) {
copyFrom(src, new Pointer(m.getSegment(0), 0));
}
function toArrayBuffer(m) {
const streamFrame = getStreamFrame(m);
if (m._capnp.segments.length === 0)
getSegment(0, m);
const segments = m._capnp.segments;
const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + padToWord$1(s.byteLength), 0);
const out = new Uint8Array(new ArrayBuffer(totalLength));
let o = streamFrame.byteLength;
out.set(new Uint8Array(streamFrame));
for (const s of segments) {
const segmentLength = padToWord$1(s.byteLength);
out.set(new Uint8Array(s.buffer, 0, segmentLength), o);
o += segmentLength;
}
return out.buffer;
}
function toPackedArrayBuffer(m) {
const streamFrame = pack(getStreamFrame(m));
if (m._capnp.segments.length === 0)
m.getSegment(0);
const segments = m._capnp.segments.map(
(s) => pack(s.buffer, 0, padToWord$1(s.byteLength))
);
const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + s.byteLength, 0);
const out = new Uint8Array(new ArrayBuffer(totalLength));
let o = streamFrame.byteLength;
out.set(new Uint8Array(streamFrame));
for (const s of segments) {
out.set(new Uint8Array(s), o);
o += s.byteLength;
}
return out.buffer;
}
function getStreamFrame(m) {
const length = m._capnp.segments.length;
if (length === 0) {
return new Float64Array(1).buffer;
}
const frameLength = 4 + length * 4 + (1 - length % 2) * 4;
const out = new DataView(new ArrayBuffer(frameLength));
out.setUint32(0, length - 1, true);
for (const [i, s] of m._capnp.segments.entries()) {
out.setUint32(i * 4 + 4, s.byteLength / 8, true);
}
return out.buffer;
}
function copy(m) {
return new Message(Arena.copy(m._capnp.arena));
}
// ../../node_modules/.pnpm/capnp-es@0.0.7_typescript@5.7.3/node_modules/capnp-es/dist/shared/capnp-es.DCKndyix.mjs
function CompositeList(CompositeClass) {
return class extends List {
static _capnp = {
compositeSize: CompositeClass._capnp.size,
displayName: `List<${CompositeClass._capnp.displayName}>`,
size: ListElementSize.COMPOSITE
};
get(index) {
return new CompositeClass(
this.segment,
this.byteOffset,
this._capnp.depthLimit - 1,
index
);
}
set(index, value) {
copyFrom(value, this.get(index));
}
[Symbol.toStringTag]() {
return `Composite_${super.toString()},cls:${CompositeClass.toString()}`;
}
};
}
function _makePrimitiveMaskFn(byteLength, setter) {
return (x) => {
const dv = new DataView(new ArrayBuffer(byteLength));
setter.call(dv, 0, x, true);
return dv;
};
}
var getFloat32Mask = _makePrimitiveMaskFn(
4,
DataView.prototype.setFloat32
);
var getFloat64Mask = _makePrimitiveMaskFn(
8,
DataView.prototype.setFloat64
);
var getInt16Mask = _makePrimitiveMaskFn(
2,
DataView.prototype.setInt16
);
var getInt32Mask = _makePrimitiveMaskFn(
4,
DataView.prototype.setInt32
);
var getInt64Mask = _makePrimitiveMaskFn(
8,
DataView.prototype.setBigInt64
);
var getInt8Mask = _makePrimitiveMaskFn(1, DataView.prototype.setInt8);
var getUint16Mask = _makePrimitiveMaskFn(
2,
DataView.prototype.setUint16
);
var getUint32Mask = _makePrimitiveMaskFn(
4,
DataView.prototype.setUint32
);
var getUint64Mask = _makePrimitiveMaskFn(
8,
DataView.prototype.setBigUint64
);
var getUint8Mask = _makePrimitiveMaskFn(
1,
DataView.prototype.setUint8
);
function getBitMask(value, bitOffset) {
const dv = new DataView(new ArrayBuffer(1));
if (!value)
return dv;
dv.setUint8(0, 1 << bitOffset % 8);
return dv;
}
// ../../node_modules/.pnpm/capnp-es@0.0.7_typescript@5.7.3/node_modules/capnp-es/dist/shared/capnp-es.B1ADXvSS.mjs
var Interface = class extends Pointer {
constructor(segment, byteOffset, depthLimit = MAX_DEPTH) {
super(segment, byteOffset, depthLimit);
}
static fromPointer(p) {
return getAsInterface(p);
}
getCapId() {
return getCapID(this);
}
getClient() {
return getClient(this);
}
[Symbol.for("nodejs.util.inspect.custom")]() {
return format(
"Interface_%d@%a,%d,limit:%x",
this.segment.id,
this.byteOffset,
this.getCapId(),
this._capnp.depthLimit
);
}
};
__publicField(Interface, "_capnp", {
displayName: "Interface"
});
__publicField(Interface, "getCapID", getCapID);
__publicField(Interface, "getAsInterface", getAsInterface);
__publicField(Interface, "isInterface", isInterface);
__publicField(Interface, "getClient", getClient);
function getAsInterface(p) {
if (getTargetPointerType(p) === PointerType.OTHER) {
return new Interface(p.segment, p.byteOffset, p._capnp.depthLimit);
}
return null;
}
function isInterface(p) {
return getTargetPointerType(p) === PointerType.OTHER;
}
function getCapID(i) {
if (i.segment.getUint32(i.byteOffset) !== PointerType.OTHER) {
return -1;
}
return i.segment.getUint32(i.byteOffset + 4);
}
function getClient(i) {
const capID = getCapID(i);
const { capTable } = i.segment.message._capnp;
if (!capTable) {
return null;
}
return capTable[capID];
}
// ../../node_modules/.pnpm/capnp-es@0.0.7_typescript@5.7.3/node_modules/capnp-es/dist/index.mjs
var Void = class extends Struct {
};
__publicField(Void, "_capnp", {
displayName: "Void",
id: "0",
size: new ObjectSize(0, 0)
});
var utils = {
__proto__: null,
PointerAllocationResult,
add,
adopt,
checkDataBounds,
checkPointerBounds,
copyFrom,
copyFromInterface,
copyFromList,
copyFromStruct,
disown,
dump,
erase,
erasePointer,
followFar,
followFars,
getAs,
getBit,
getCapabilityId,
getContent,
getData,
getDataSection,
getFarSegmentId,
getFloat32,
getFloat64,
getInt16,
getInt32,
getInt64,
getInt8,
getInterfaceClientOrNull,
getInterfaceClientOrNullAt,
getInterfacePointer,
getList,
getListByteLength,
getListElementByteLength,
getListElementSize,
getListLength,
getOffsetWords,
getPointer,
getPointerAs,
getPointerSection,
getPointerType,
getSize,
getStruct,
getStructDataWords,
getStructPointerLength,
getStructSize,
getTargetCompositeListSize,
getTargetCompositeListTag,
getTargetListElementSize,
getTargetListLength,
getTargetPointerType,
getTargetStructSize,
getText,
getUint16,
getUint32,
getUint64,
getUint8,
initData,
initList,
initPointer,
initStruct,
initStructAt,
isDoubleFar,
isNull,
relocateTo,
resize,
setBit,
setFarPointer,
setFloat32,
setFloat64,
setInt16,
setInt32,
setInt64,
setInt8,
setInterfacePointer,
setListPointer,
setStructPointer,
setText,
setUint16,
setUint32,
setUint64,
setUint8,
testWhich,
trackPointerAllocation,
validate
};
function PointerList(PointerClass) {
return class extends List {
static _capnp = {
displayName: `List<${PointerClass._capnp.displayName}>`,
size: ListElementSize.POINTER
};
get(index) {
const c = getContent(this);
return new PointerClass(
c.segment,
c.byteOffset + index * 8,
this._capnp.depthLimit - 1
);
}
set(index, value) {
copyFrom(value, this.get(index));
}
[Symbol.toStringTag]() {
return `Pointer_${super.toString()},cls:${PointerClass.toString()}`;
}
};
}
var AnyPointerList = PointerList(Pointer);
var BoolList = class extends List {
get(index) {
const bitMask = 1 << index % 8;
const byteOffset = index >>> 3;
const c = getContent(this);
const v = c.segment.getUint8(c.byteOffset + byteOffset);
return (v & bitMask) !== 0;
}
set(index, value) {
const bitMask = 1 << index % 8;
const c = getContent(this);
const byteOffset = c.byteOffset + (index >>> 3);
const v = c.segment.getUint8(byteOffset);
c.segment.setUint8(byteOffset, value ? v | bitMask : v & ~bitMask);
}
[Symbol.toStringTag]() {
return `Bool_${super.toString()}`;
}
};
__publicField(BoolList, "_capnp", {
displayName: "List<boolean>",
size: ListElementSize.BIT
});
var DataList = PointerList(Data);
var Float32List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getFloat32(c.byteOffset + index * 4);
}
set(index, value) {
const c = getContent(this);
c.segment.setFloat32(c.byteOffset + index * 4, value);
}
[Symbol.toStringTag]() {
return `Float32_${super.toString()}`;
}
};
__publicField(Float32List, "_capnp", {
displayName: "List<Float32>",
size: ListElementSize.BYTE_4
});
var Float64List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getFloat64(c.byteOffset + index * 8);
}
set(index, value) {
const c = getContent(this);
c.segment.setFloat64(c.byteOffset + index * 8, value);
}
[Symbol.toStringTag]() {
return `Float64_${super.toString()}`;
}
};
__publicField(Float64List, "_capnp", {
displayName: "List<Float64>",
size: ListElementSize.BYTE_8
});
var Int8List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getInt8(c.byteOffset + index);
}
set(index, value) {
const c = getContent(this);
c.segment.setInt8(c.byteOffset + index, value);
}
[Symbol.toStringTag]() {
return `Int8_${super.toString()}`;
}
};
__publicField(Int8List, "_capnp", {
displayName: "List<Int8>",
size: ListElementSize.BYTE
});
var Int16List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getInt16(c.byteOffset + index * 2);
}
set(index, value) {
const c = getContent(this);
c.segment.setInt16(c.byteOffset + index * 2, value);
}
[Symbol.toStringTag]() {
return `Int16_${super.toString()}`;
}
};
__publicField(Int16List, "_capnp", {
displayName: "List<Int16>",
size: ListElementSize.BYTE_2
});
var Int32List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getInt32(c.byteOffset + index * 4);
}
set(index, value) {
const c = getContent(this);
c.segment.setInt32(c.byteOffset + index * 4, value);
}
[Symbol.toStringTag]() {
return `Int32_${super.toString()}`;
}
};
__publicField(Int32List, "_capnp", {
displayName: "List<Int32>",
size: ListElementSize.BYTE_4
});
var Int64List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getInt64(c.byteOffset + index * 8);
}
set(index, value) {
const c = getContent(this);
c.segment.setInt64(c.byteOffset + index * 8, value);
}
[Symbol.toStringTag]() {
return `Int64_${super.toString()}`;
}
};
__publicField(Int64List, "_capnp", {
displayName: "List<Int64>",
size: ListElementSize.BYTE_8
});
var InterfaceList = PointerList(Interface);
var TextList = class extends List {
get(index) {
const c = getContent(this);
c.byteOffset += index * 8;
return Text.fromPointer(c).get(0);
}
set(index, value) {
const c = getContent(this);
c.byteOffset += index * 8;
Text.fromPointer(c).set(0, value);
}
[Symbol.toStringTag]() {
return `Text_${super.toString()}`;
}
};
__publicField(TextList, "_capnp", {
displayName: "List<Text>",
size: ListElementSize.POINTER
});
var Uint8List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getUint8(c.byteOffset + index);
}
set(index, value) {
const c = getContent(this);
c.segment.setUint8(c.byteOffset + index, value);
}
[Symbol.toStringTag]() {
return `Uint8_${super.toString()}`;
}
};
__publicField(Uint8List, "_capnp", {
displayName: "List<Uint8>",
size: ListElementSize.BYTE
});
var Uint16List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getUint16(c.byteOffset + index * 2);
}
set(index, value) {
const c = getContent(this);
c.segment.setUint16(c.byteOffset + index * 2, value);
}
[Symbol.toStringTag]() {
return `Uint16_${super.toString()}`;
}
};
__publicField(Uint16List, "_capnp", {
displayName: "List<Uint16>",
size: ListElementSize.BYTE_2
});
var Uint32List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getUint32(c.byteOffset + index * 4);
}
set(index, value) {
const c = getContent(this);
c.segment.setUint32(c.byteOffset + index * 4, value);
}
[Symbol.toStringTag]() {
return `Uint32_${super.toString()}`;
}
};
__publicField(Uint32List, "_capnp", {
displayName: "List<Uint32>",
size: ListElementSize.BYTE_4
});
var Uint64List = class extends List {
get(index) {
const c = getContent(this);
return c.segment.getUint64(c.byteOffset + index * 8);
}
set(index, value) {
const c = getContent(this);
c.segment.setUint64(c.byteOffset + index * 8, value);
}
[Symbol.toStringTag]() {
return `Uint64_${super.toString()}`;
}
};
__publicField(Uint64List, "_capnp", {
displayName: "List<Uint64>",
size: ListElementSize.BYTE_8
});
var VoidList = PointerList(Void);
var ConnWeakRefRegistry = globalThis.FinalizationRegistry ? new FinalizationRegistry((cb) => cb()) : void 0;
// src/runtime/config/generated.ts
var _capnpFileId = BigInt("0xe6afd26682091c01");
var _Config = class extends Struct {
_adoptServices(value) {
utils.adopt(value, utils.getPointer(0, this));
}
_disownServices() {
return utils.disown(this.services);
}
/**
* List of named services defined by this server. These names are private; they are only used
* to refer to the services from elsewhere in this config file, as well as for logging and the
* like. Services are not reachable until you configure some way to make them reachable, such
* as via a Socket.
*
* If you do not define any service called "internet", one is defined implicitly, representing
* the ability to access public internet servers. An explicit definition would look like:
*
* ( name = "internet",
* network = (
* allow = ["public"], # Allows connections to publicly-routable addresses only.
* tlsOptions = (trustBrowserCas = true)
* )
* )
*
* The "internet" service backs the global `fetch()` function in a Worker, unless that Worker's
* configuration specifies some other service using the `globalOutbound` setting.
*
*/
get services() {
return utils.getList(0, _Config._Services, this);
}
_hasServices() {
return !utils.isNull(utils.getPointer(0, this));
}
_initServices(length) {
return utils.initList(0, _Config._Services, length, this);
}
set services(value) {
utils.copyFrom(value, utils.getPointer(0, this));
}
_adoptSockets(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownSockets() {
return utils.disown(this.sockets);
}
/**
* List of sockets on which this server will listen, and the services that will be exposed
* through them.
*
*/
get sockets() {
return utils.getList(1, _Config._Sockets, this);
}
_hasSockets() {
return !utils.isNull(utils.getPointer(1, this));
}
_initSockets(length) {
return utils.initList(1, _Config._Sockets, length, this);
}
set sockets(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptV8Flags(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownV8Flags() {
return utils.disown(this.v8Flags);
}
/**
* List of "command-line" flags to pass to V8, like "--expose-gc". We put these in the config
* rather than on the actual command line because for most use cases, managing these via the
* config file is probably cleaner and easier than passing on the actual CLI.
*
* WARNING: Use at your own risk. V8 flags can have all sorts of wild effects including completely
* breaking everything. V8 flags also generally do not come with any guarantee of stability
* between V8 versions. Most users should not set any V8 flags.
*
*/
get v8Flags() {
return utils.getList(2, TextList, this);
}
_hasV8Flags() {
return !utils.isNull(utils.getPointer(2, this));
}
_initV8Flags(length) {
return utils.initList(2, TextList, length, this);
}
set v8Flags(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
_adoptExtensions(value) {
utils.adopt(value, utils.getPointer(3, this));
}
_disownExtensions() {
return utils.disown(this.extensions);
}
/**
* Extensions provide capabilities to all workers. Extensions are usually prepared separately
* and are late-linked with the app using this config field.
*
*/
get extensions() {
return utils.getList(3, _Config._Extensions, this);
}
_hasExtensions() {
return !utils.isNull(utils.getPointer(3, this));
}
_initExtensions(length) {
return utils.initList(3, _Config._Extensions, length, this);
}
set extensions(value) {
utils.copyFrom(value, utils.getPointer(3, this));
}
_adoptAutogates(value) {
utils.adopt(value, utils.getPointer(4, this));
}
_disownAutogates() {
return utils.disown(this.autogates);
}
/**
* A list of gates which are enabled.
* These are used to gate features/changes in workerd and in our internal repo. See the equivalent
* config definition in our internal repo for more details.
*
*/
get autogates() {
return utils.getList(4, TextList, this);
}
_hasAutogates() {
return !utils.isNull(utils.getPointer(4, this));
}
_initAutogates(length) {
return utils.initList(4, TextList, length, this);
}
set autogates(value) {
utils.copyFrom(value, utils.getPointer(4, this));
}
/**
* If true, logs will be emitted as JSON for structured logging.
* When false, logs use the traditional human-readable format.
* This affects the format of logs from KJ_LOG and exception reporting as well as js logs.
* This won't work for logs coming from service worker syntax workers with the old module registry.
*
*/
get structuredLogging() {
return utils.getBit(0, this, _Config._capnp.defaultStructuredLogging);
}
set structuredLogging(value) {
utils.setBit(0, value, this, _Config._capnp.defaultStructuredLogging);
}
toString() {
return "Config_" + super.toString();
}
};
var Config = _Config;
__publicField(Config, "_capnp", {
displayName: "Config",
id: "8794486c76aaa7d6",
size: new ObjectSize(8, 5),
defaultStructuredLogging: getBitMask(false, 0)
});
__publicField(Config, "_Services");
__publicField(Config, "_Sockets");
__publicField(Config, "_Extensions");
var Socket_Https = class extends Struct {
_adoptOptions(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownOptions() {
return utils.disown(this.options);
}
get options() {
return utils.getStruct(2, HttpOptions, this);
}
_hasOptions() {
return !utils.isNull(utils.getPointer(2, this));
}
_initOptions() {
return utils.initStructAt(2, HttpOptions, this);
}
set options(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
_adoptTlsOptions(value) {
utils.adopt(value, utils.getPointer(3, this));
}
_disownTlsOptions() {
return utils.disown(this.tlsOptions);
}
get tlsOptions() {
return utils.getStruct(3, TlsOptions, this);
}
_hasTlsOptions() {
return !utils.isNull(utils.getPointer(3, this));
}
_initTlsOptions() {
return utils.initStructAt(3, TlsOptions, this);
}
set tlsOptions(value) {
utils.copyFrom(value, utils.getPointer(3, this));
}
toString() {
return "Socket_Https_" + super.toString();
}
};
__publicField(Socket_Https, "_capnp", {
displayName: "https",
id: "de123876383cbbdc",
size: new ObjectSize(8, 5)
});
var Socket_Which = {
/**
* Each socket has a unique name which can be used on the command line to override the socket's
* address with `--socket-addr <name>=<addr>` or `--socket-fd <name>=<fd>`.
*
*/
HTTP: 0,
/**
* Address/port on which this socket will listen. Optional; if not specified, then you will be
* required to specify the socket on the command line with with `--socket-addr <name>=<addr>` or
* `--socket-fd <name>=<fd>`.
*
* Examples:
* - "*:80": Listen on port 80 on all local IPv4 and IPv6 interfaces.
* - "1.2.3.4": Listen on the specific IPv4 address on the default port for the protocol.
* - "1.2.3.4:80": Listen on the specific IPv4 address and port.
* - "1234:5678::abcd": Listen on the specific IPv6 address on the default port for the protocol.
* - "[1234:5678::abcd]:80": Listen on the specific IPv6 address and port.
* - "unix:/path/to/socket": Listen on a Unix socket.
* - "unix-abstract:name": On Linux, listen on the given "abstract" Unix socket name.
* - "example.com:80": Perform a DNS lookup to determine the address, and then listen on it. If
* this resolves to multiple addresses, listen on all of them.
*
* (These are the formats supported by KJ's parseAddress().)
*
*/
HTTPS: 1
};
var Socket = class extends Struct {
/**
* Each socket has a unique name which can be used on the command line to override the socket's
* address with `--socket-addr <name>=<addr>` or `--socket-fd <name>=<fd>`.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
/**
* Address/port on which this socket will listen. Optional; if not specified, then you will be
* required to specify the socket on the command line with with `--socket-addr <name>=<addr>` or
* `--socket-fd <name>=<fd>`.
*
* Examples:
* - "*:80": Listen on port 80 on all local IPv4 and IPv6 interfaces.
* - "1.2.3.4": Listen on the specific IPv4 address on the default port for the protocol.
* - "1.2.3.4:80": Listen on the specific IPv4 address and port.
* - "1234:5678::abcd": Listen on the specific IPv6 address on the default port for the protocol.
* - "[1234:5678::abcd]:80": Listen on the specific IPv6 address and port.
* - "unix:/path/to/socket": Listen on a Unix socket.
* - "unix-abstract:name": On Linux, listen on the given "abstract" Unix socket name.
* - "example.com:80": Perform a DNS lookup to determine the address, and then listen on it. If
* this resolves to multiple addresses, listen on all of them.
*
* (These are the formats supported by KJ's parseAddress().)
*
*/
get address() {
return utils.getText(1, this);
}
set address(value) {
utils.setText(1, value, this);
}
_adoptHttp(value) {
utils.setUint16(0, 0, this);
utils.adopt(value, utils.getPointer(2, this));
}
_disownHttp() {
return utils.disown(this.http);
}
get http() {
utils.testWhich("http", utils.getUint16(0, this), 0, this);
return utils.getStruct(2, HttpOptions, this);
}
_hasHttp() {
return !utils.isNull(utils.getPointer(2, this));
}
_initHttp() {
utils.setUint16(0, 0, this);
return utils.initStructAt(2, HttpOptions, this);
}
get _isHttp() {
return utils.getUint16(0, this) === 0;
}
set http(value) {
utils.setUint16(0, 0, this);
utils.copyFrom(value, utils.getPointer(2, this));
}
get https() {
utils.testWhich("https", utils.getUint16(0, this), 1, this);
return utils.getAs(Socket_Https, this);
}
_initHttps() {
utils.setUint16(0, 1, this);
return utils.getAs(Socket_Https, this);
}
get _isHttps() {
return utils.getUint16(0, this) === 1;
}
set https(_) {
utils.setUint16(0, 1, this);
}
_adoptService(value) {
utils.adopt(value, utils.getPointer(4, this));
}
_disownService() {
return utils.disown(this.service);
}
/**
* Service name which should handle requests on this socket.
*
*/
get service() {
return utils.getStruct(4, ServiceDesignator, this);
}
_hasService() {
return !utils.isNull(utils.getPointer(4, this));
}
_initService() {
return utils.initStructAt(4, ServiceDesignator, this);
}
set service(value) {
utils.copyFrom(value, utils.getPointer(4, this));
}
toString() {
return "Socket_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Socket, "HTTP", Socket_Which.HTTP);
__publicField(Socket, "HTTPS", Socket_Which.HTTPS);
__publicField(Socket, "_capnp", {
displayName: "Socket",
id: "9a0eba45530ee79f",
size: new ObjectSize(8, 5)
});
var Service_Which = {
/**
* Name of the service. Used only to refer to the service from elsewhere in the config file.
* Services are not accessible unless you explicitly configure them to be, such as through a
* `Socket` or through a binding from another Worker.
*
*/
UNSPECIFIED: 0,
/**
* (This catches when someone forgets to specify one of the union members. Do not set this.)
*
*/
WORKER: 1,
/**
* A Worker!
*
*/
NETWORK: 2,
/**
* A service that implements access to a network. fetch() requests are routed according to
* the URL hostname.
*
*/
EXTERNAL: 3,
/**
* A service that forwards all requests to a specific remote server. Typically used to
* connect to a back-end server on your internal network.
*
*/
DISK: 4
};
var Service = class extends Struct {
/**
* Name of the service. Used only to refer to the service from elsewhere in the config file.
* Services are not accessible unless you explicitly configure them to be, such as through a
* `Socket` or through a binding from another Worker.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
get _isUnspecified() {
return utils.getUint16(0, this) === 0;
}
set unspecified(_) {
utils.setUint16(0, 0, this);
}
_adoptWorker(value) {
utils.setUint16(0, 1, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownWorker() {
return utils.disown(this.worker);
}
/**
* A Worker!
*
*/
get worker() {
utils.testWhich("worker", utils.getUint16(0, this), 1, this);
return utils.getStruct(1, Worker, this);
}
_hasWorker() {
return !utils.isNull(utils.getPointer(1, this));
}
_initWorker() {
utils.setUint16(0, 1, this);
return utils.initStructAt(1, Worker, this);
}
get _isWorker() {
return utils.getUint16(0, this) === 1;
}
set worker(value) {
utils.setUint16(0, 1, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptNetwork(value) {
utils.setUint16(0, 2, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownNetwork() {
return utils.disown(this.network);
}
/**
* A service that implements access to a network. fetch() requests are routed according to
* the URL hostname.
*
*/
get network() {
utils.testWhich("network", utils.getUint16(0, this), 2, this);
return utils.getStruct(1, Network, this);
}
_hasNetwork() {
return !utils.isNull(utils.getPointer(1, this));
}
_initNetwork() {
utils.setUint16(0, 2, this);
return utils.initStructAt(1, Network, this);
}
get _isNetwork() {
return utils.getUint16(0, this) === 2;
}
set network(value) {
utils.setUint16(0, 2, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptExternal(value) {
utils.setUint16(0, 3, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownExternal() {
return utils.disown(this.external);
}
/**
* A service that forwards all requests to a specific remote server. Typically used to
* connect to a back-end server on your internal network.
*
*/
get external() {
utils.testWhich("external", utils.getUint16(0, this), 3, this);
return utils.getStruct(1, ExternalServer, this);
}
_hasExternal() {
return !utils.isNull(utils.getPointer(1, this));
}
_initExternal() {
utils.setUint16(0, 3, this);
return utils.initStructAt(1, ExternalServer, this);
}
get _isExternal() {
return utils.getUint16(0, this) === 3;
}
set external(value) {
utils.setUint16(0, 3, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptDisk(value) {
utils.setUint16(0, 4, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownDisk() {
return utils.disown(this.disk);
}
/**
* An HTTP service backed by a directory on disk, supporting a basic HTTP GET/PUT. Generally
* not intended to be exposed directly to the internet; typically you want to bind this into
* a Worker that adds logic for setting Content-Type and the like.
*
*/
get disk() {
utils.testWhich("disk", utils.getUint16(0, this), 4, this);
return utils.getStruct(1, DiskDirectory, this);
}
_hasDisk() {
return !utils.isNull(utils.getPointer(1, this));
}
_initDisk() {
utils.setUint16(0, 4, this);
return utils.initStructAt(1, DiskDirectory, this);
}
get _isDisk() {
return utils.getUint16(0, this) === 4;
}
set disk(value) {
utils.setUint16(0, 4, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
toString() {
return "Service_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Service, "UNSPECIFIED", Service_Which.UNSPECIFIED);
__publicField(Service, "WORKER", Service_Which.WORKER);
__publicField(Service, "NETWORK", Service_Which.NETWORK);
__publicField(Service, "EXTERNAL", Service_Which.EXTERNAL);
__publicField(Service, "DISK", Service_Which.DISK);
__publicField(Service, "_capnp", {
displayName: "Service",
id: "e5c88e8bb7bcb6b9",
size: new ObjectSize(8, 2)
});
var ServiceDesignator_Props_Which = {
/**
* Empty object. (This is the default.)
*
*/
EMPTY: 0,
/**
* A JSON-encoded value.
*
*/
JSON: 1
};
var ServiceDesignator_Props = class extends Struct {
get _isEmpty() {
return utils.getUint16(0, this) === 0;
}
set empty(_) {
utils.setUint16(0, 0, this);
}
/**
* A JSON-encoded value.
*
*/
get json() {
utils.testWhich("json", utils.getUint16(0, this), 1, this);
return utils.getText(2, this);
}
get _isJson() {
return utils.getUint16(0, this) === 1;
}
set json(value) {
utils.setUint16(0, 1, this);
utils.setText(2, value, this);
}
toString() {
return "ServiceDesignator_Props_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(ServiceDesignator_Props, "EMPTY", ServiceDesignator_Props_Which.EMPTY);
__publicField(ServiceDesignator_Props, "JSON", ServiceDesignator_Props_Which.JSON);
__publicField(ServiceDesignator_Props, "_capnp", {
displayName: "props",
id: "f0dc90173b494522",
size: new ObjectSize(8, 3)
});
var ServiceDesignator = class extends Struct {
/**
* Name of the service in the Config.services list.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
/**
* A modules-syntax Worker can export multiple named entrypoints. `export default {` specifies
* the default entrypoint, whereas `export let foo = {` defines an entrypoint named `foo`. If
* `entrypoint` is specified here, it names an alternate entrypoint to use on the target worker,
* otherwise the default is used.
*
*/
get entrypoint() {
return utils.getText(1, this);
}
set entrypoint(value) {
utils.setText(1, value, this);
}
/**
* Value to provide in `ctx.props` in the target worker.
*
*/
get props() {
return utils.getAs(ServiceDesignator_Props, this);
}
_initProps() {
return utils.getAs(ServiceDesignator_Props, this);
}
toString() {
return "ServiceDesignator_" + super.toString();
}
};
__publicField(ServiceDesignator, "_capnp", {
displayName: "ServiceDesignator",
id: "ae8ec91cee724450",
size: new ObjectSize(8, 3)
});
var Worker_Module_Which = {
/**
* Name (or path) used to import the module.
*
*/
ES_MODULE: 0,
/**
* An ES module file with imports and exports.
*
* As with `serviceWorkerScript`, above, the value is the raw source code.
*
*/
COMMON_JS_MODULE: 1,
/**
* A common JS module, using require().
*
*/
TEXT: 2,
/**
* A raw text blob. Importing this will produce a string with the value.
*
*/
DATA: 3,
/**
* A raw data blob. Importing this will produce an ArrayBuffer with the value.
*
*/
WASM: 4,
/**
* A Wasm module. The value is a compiled binary Wasm module file. Importing this will produce
* a `WebAssembly.Module` object, which you can then instantiate.
*
*/
JSON: 5,
/**
* Importing this will produce the result of parsing the given text as JSON.
*
*/
OBSOLETE: 6,
/**
* This position used to be the nodeJsCompatModule type that has now been
* obsoleted.
*
*/
PYTHON_MODULE: 7,
/**
* A Python module. All bundles containing this value type are converted into a JS/WASM Worker
* Bundle prior to execution.
*
*/
PYTHON_REQUIREMENT: 8
};
var Worker_Module = class extends Struct {
/**
* Name (or path) used to import the module.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
/**
* An ES module file with imports and exports.
*
* As with `serviceWorkerScript`, above, the value is the raw source code.
*
*/
get esModule() {
utils.testWhich("esModule", utils.getUint16(0, this), 0, this);
return utils.getText(1, this);
}
get _isEsModule() {
return utils.getUint16(0, this) === 0;
}
set esModule(value) {
utils.setUint16(0, 0, this);
utils.setText(1, value, this);
}
/**
* A common JS module, using require().
*
*/
get commonJsModule() {
utils.testWhich("commonJsModule", utils.getUint16(0, this), 1, this);
return utils.getText(1, this);
}
get _isCommonJsModule() {
return utils.getUint16(0, this) === 1;
}
set commonJsModule(value) {
utils.setUint16(0, 1, this);
utils.setText(1, value, this);
}
/**
* A raw text blob. Importing this will produce a string with the value.
*
*/
get text() {
utils.testWhich("text", utils.getUint16(0, this), 2, this);
return utils.getText(1, this);
}
get _isText() {
return utils.getUint16(0, this) === 2;
}
set text(value) {
utils.setUint16(0, 2, this);
utils.setText(1, value, this);
}
_adoptData(value) {
utils.setUint16(0, 3, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownData() {
return utils.disown(this.data);
}
/**
* A raw data blob. Importing this will produce an ArrayBuffer with the value.
*
*/
get data() {
utils.testWhich("data", utils.getUint16(0, this), 3, this);
return utils.getData(1, this);
}
_hasData() {
return !utils.isNull(utils.getPointer(1, this));
}
_initData(length) {
utils.setUint16(0, 3, this);
return utils.initData(1, length, this);
}
get _isData() {
return utils.getUint16(0, this) === 3;
}
set data(value) {
utils.setUint16(0, 3, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptWasm(value) {
utils.setUint16(0, 4, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownWasm() {
return utils.disown(this.wasm);
}
/**
* A Wasm module. The value is a compiled binary Wasm module file. Importing this will produce
* a `WebAssembly.Module` object, which you can then instantiate.
*
*/
get wasm() {
utils.testWhich("wasm", utils.getUint16(0, this), 4, this);
return utils.getData(1, this);
}
_hasWasm() {
return !utils.isNull(utils.getPointer(1, this));
}
_initWasm(length) {
utils.setUint16(0, 4, this);
return utils.initData(1, length, this);
}
get _isWasm() {
return utils.getUint16(0, this) === 4;
}
set wasm(value) {
utils.setUint16(0, 4, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* Importing this will produce the result of parsing the given text as JSON.
*
*/
get json() {
utils.testWhich("json", utils.getUint16(0, this), 5, this);
return utils.getText(1, this);
}
get _isJson() {
return utils.getUint16(0, this) === 5;
}
set json(value) {
utils.setUint16(0, 5, this);
utils.setText(1, value, this);
}
/**
* This position used to be the nodeJsCompatModule type that has now been
* obsoleted.
*
*/
get obsolete() {
utils.testWhich("obsolete", utils.getUint16(0, this), 6, this);
return utils.getText(1, this);
}
get _isObsolete() {
return utils.getUint16(0, this) === 6;
}
set obsolete(value) {
utils.setUint16(0, 6, this);
utils.setText(1, value, this);
}
/**
* A Python module. All bundles containing this value type are converted into a JS/WASM Worker
* Bundle prior to execution.
*
*/
get pythonModule() {
utils.testWhich("pythonModule", utils.getUint16(0, this), 7, this);
return utils.getText(1, this);
}
get _isPythonModule() {
return utils.getUint16(0, this) === 7;
}
set pythonModule(value) {
utils.setUint16(0, 7, this);
utils.setText(1, value, this);
}
/**
* A Python package that is required by this bundle. The package must be supported by
* Pyodide (https://pyodide.org/en/stable/usage/packages-in-pyodide.html). All packages listed
* will be installed prior to the execution of the worker.
*
* The value of this field is ignored and should always be an empty string. Only the module
* name matters. The field should have been declared `Void`, but it's difficult to change now.
*
*/
get pythonRequirement() {
utils.testWhich("pythonRequirement", utils.getUint16(0, this), 8, this);
return utils.getText(1, this);
}
get _isPythonRequirement() {
return utils.getUint16(0, this) === 8;
}
set pythonRequirement(value) {
utils.setUint16(0, 8, this);
utils.setText(1, value, this);
}
_adoptNamedExports(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownNamedExports() {
return utils.disown(this.namedExports);
}
/**
* For commonJsModule modules, this is a list of named exports that the
* module expects to be exported once the evaluation is complete.
*
* (`commonJsModule` should have been a group containing the body and `namedExports`, but it's
* too late to change now.)
*
*/
get namedExports() {
return utils.getList(2, TextList, this);
}
_hasNamedExports() {
return !utils.isNull(utils.getPointer(2, this));
}
_initNamedExports(length) {
return utils.initList(2, TextList, length, this);
}
set namedExports(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Worker_Module_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Worker_Module, "ES_MODULE", Worker_Module_Which.ES_MODULE);
__publicField(Worker_Module, "COMMON_JS_MODULE", Worker_Module_Which.COMMON_JS_MODULE);
__publicField(Worker_Module, "TEXT", Worker_Module_Which.TEXT);
__publicField(Worker_Module, "DATA", Worker_Module_Which.DATA);
__publicField(Worker_Module, "WASM", Worker_Module_Which.WASM);
__publicField(Worker_Module, "JSON", Worker_Module_Which.JSON);
__publicField(Worker_Module, "OBSOLETE", Worker_Module_Which.OBSOLETE);
__publicField(Worker_Module, "PYTHON_MODULE", Worker_Module_Which.PYTHON_MODULE);
__publicField(Worker_Module, "PYTHON_REQUIREMENT", Worker_Module_Which.PYTHON_REQUIREMENT);
__publicField(Worker_Module, "_capnp", {
displayName: "Module",
id: "d9d87a63770a12f3",
size: new ObjectSize(8, 3)
});
var Worker_Binding_Type_Which = {
/**
* (This catches when someone forgets to specify one of the union members. Do not set this.)
*
*/
UNSPECIFIED: 0,
TEXT: 1,
DATA: 2,
JSON: 3,
WASM: 4,
CRYPTO_KEY: 5,
SERVICE: 6,
DURABLE_OBJECT_NAMESPACE: 7,
KV_NAMESPACE: 8,
R2BUCKET: 9,
R2ADMIN: 10,
QUEUE: 11,
ANALYTICS_ENGINE: 12,
HYPERDRIVE: 13,
DURABLE_OBJECT_CLASS: 14
};
var Worker_Binding_Type = class extends Struct {
get _isUnspecified() {
return utils.getUint16(0, this) === 0;
}
set unspecified(_) {
utils.setUint16(0, 0, this);
}
get _isText() {
return utils.getUint16(0, this) === 1;
}
set text(_) {
utils.setUint16(0, 1, this);
}
get _isData() {
return utils.getUint16(0, this) === 2;
}
set data(_) {
utils.setUint16(0, 2, this);
}
get _isJson() {
return utils.getUint16(0, this) === 3;
}
set json(_) {
utils.setUint16(0, 3, this);
}
get _isWasm() {
return utils.getUint16(0, this) === 4;
}
set wasm(_) {
utils.setUint16(0, 4, this);
}
_adoptCryptoKey(value) {
utils.setUint16(0, 5, this);
utils.adopt(value, utils.getPointer(0, this));
}
_disownCryptoKey() {
return utils.disown(this.cryptoKey);
}
get cryptoKey() {
utils.testWhich("cryptoKey", utils.getUint16(0, this), 5, this);
return utils.getList(
0,
Uint16List,
this
);
}
_hasCryptoKey() {
return !utils.isNull(utils.getPointer(0, this));
}
_initCryptoKey(length) {
utils.setUint16(0, 5, this);
return utils.initList(
0,
Uint16List,
length,
this
);
}
get _isCryptoKey() {
return utils.getUint16(0, this) === 5;
}
set cryptoKey(value) {
utils.setUint16(0, 5, this);
utils.copyFrom(value, utils.getPointer(0, this));
}
get _isService() {
return utils.getUint16(0, this) === 6;
}
set service(_) {
utils.setUint16(0, 6, this);
}
get _isDurableObjectNamespace() {
return utils.getUint16(0, this) === 7;
}
set durableObjectNamespace(_) {
utils.setUint16(0, 7, this);
}
get _isKvNamespace() {
return utils.getUint16(0, this) === 8;
}
set kvNamespace(_) {
utils.setUint16(0, 8, this);
}
get _isR2Bucket() {
return utils.getUint16(0, this) === 9;
}
set r2Bucket(_) {
utils.setUint16(0, 9, this);
}
get _isR2Admin() {
return utils.getUint16(0, this) === 10;
}
set r2Admin(_) {
utils.setUint16(0, 10, this);
}
get _isQueue() {
return utils.getUint16(0, this) === 11;
}
set queue(_) {
utils.setUint16(0, 11, this);
}
get _isAnalyticsEngine() {
return utils.getUint16(0, this) === 12;
}
set analyticsEngine(_) {
utils.setUint16(0, 12, this);
}
get _isHyperdrive() {
return utils.getUint16(0, this) === 13;
}
set hyperdrive(_) {
utils.setUint16(0, 13, this);
}
get _isDurableObjectClass() {
return utils.getUint16(0, this) === 14;
}
set durableObjectClass(_) {
utils.setUint16(0, 14, this);
}
toString() {
return "Worker_Binding_Type_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Worker_Binding_Type, "UNSPECIFIED", Worker_Binding_Type_Which.UNSPECIFIED);
__publicField(Worker_Binding_Type, "TEXT", Worker_Binding_Type_Which.TEXT);
__publicField(Worker_Binding_Type, "DATA", Worker_Binding_Type_Which.DATA);
__publicField(Worker_Binding_Type, "JSON", Worker_Binding_Type_Which.JSON);
__publicField(Worker_Binding_Type, "WASM", Worker_Binding_Type_Which.WASM);
__publicField(Worker_Binding_Type, "CRYPTO_KEY", Worker_Binding_Type_Which.CRYPTO_KEY);
__publicField(Worker_Binding_Type, "SERVICE", Worker_Binding_Type_Which.SERVICE);
__publicField(Worker_Binding_Type, "DURABLE_OBJECT_NAMESPACE", Worker_Binding_Type_Which.DURABLE_OBJECT_NAMESPACE);
__publicField(Worker_Binding_Type, "KV_NAMESPACE", Worker_Binding_Type_Which.KV_NAMESPACE);
__publicField(Worker_Binding_Type, "R2BUCKET", Worker_Binding_Type_Which.R2BUCKET);
__publicField(Worker_Binding_Type, "R2ADMIN", Worker_Binding_Type_Which.R2ADMIN);
__publicField(Worker_Binding_Type, "QUEUE", Worker_Binding_Type_Which.QUEUE);
__publicField(Worker_Binding_Type, "ANALYTICS_ENGINE", Worker_Binding_Type_Which.ANALYTICS_ENGINE);
__publicField(Worker_Binding_Type, "HYPERDRIVE", Worker_Binding_Type_Which.HYPERDRIVE);
__publicField(Worker_Binding_Type, "DURABLE_OBJECT_CLASS", Worker_Binding_Type_Which.DURABLE_OBJECT_CLASS);
__publicField(Worker_Binding_Type, "_capnp", {
displayName: "Type",
id: "8906a1296519bf8a",
size: new ObjectSize(8, 1)
});
var Worker_Binding_DurableObjectNamespaceDesignator = class extends Struct {
/**
* Exported class name that implements the Durable Object.
*
*/
get className() {
return utils.getText(0, this);
}
set className(value) {
utils.setText(0, value, this);
}
/**
* The service name of the worker that defines this class. If omitted, the current worker
* is assumed.
*
* Use of this field is discouraged. Instead, when accessing a different Worker's Durable
* Objects, specify a `service` binding to that worker, and have the worker implement an
* appropriate API.
*
* (This is intentionally not a ServiceDesignator because you cannot choose an alternate
* entrypoint here; the class name IS the entrypoint.)
*
*/
get serviceName() {
return utils.getText(1, this);
}
set serviceName(value) {
utils.setText(1, value, this);
}
toString() {
return "Worker_Binding_DurableObjectNamespaceDesignator_" + super.toString();
}
};
__publicField(Worker_Binding_DurableObjectNamespaceDesignator, "_capnp", {
displayName: "DurableObjectNamespaceDesignator",
id: "804f144ff477aac7",
size: new ObjectSize(0, 2)
});
var Worker_Binding_CryptoKey_Usage = {
ENCRYPT: 0,
DECRYPT: 1,
SIGN: 2,
VERIFY: 3,
DERIVE_KEY: 4,
DERIVE_BITS: 5,
WRAP_KEY: 6,
UNWRAP_KEY: 7
};
var Worker_Binding_CryptoKey_Algorithm_Which = {
/**
* Just a name, like `AES-GCM`.
*
*/
NAME: 0,
/**
* An object, encoded here as JSON.
*
*/
JSON: 1
};
var Worker_Binding_CryptoKey_Algorithm = class extends Struct {
/**
* Just a name, like `AES-GCM`.
*
*/
get name() {
utils.testWhich("name", utils.getUint16(2, this), 0, this);
return utils.getText(1, this);
}
get _isName() {
return utils.getUint16(2, this) === 0;
}
set name(value) {
utils.setUint16(2, 0, this);
utils.setText(1, value, this);
}
/**
* An object, encoded here as JSON.
*
*/
get json() {
utils.testWhich("json", utils.getUint16(2, this), 1, this);
return utils.getText(1, this);
}
get _isJson() {
return utils.getUint16(2, this) === 1;
}
set json(value) {
utils.setUint16(2, 1, this);
utils.setText(1, value, this);
}
toString() {
return "Worker_Binding_CryptoKey_Algorithm_" + super.toString();
}
which() {
return utils.getUint16(
2,
this
);
}
};
__publicField(Worker_Binding_CryptoKey_Algorithm, "NAME", Worker_Binding_CryptoKey_Algorithm_Which.NAME);
__publicField(Worker_Binding_CryptoKey_Algorithm, "JSON", Worker_Binding_CryptoKey_Algorithm_Which.JSON);
__publicField(Worker_Binding_CryptoKey_Algorithm, "_capnp", {
displayName: "algorithm",
id: "a1a040c5e00d7021",
size: new ObjectSize(8, 3)
});
var Worker_Binding_CryptoKey_Which = {
RAW: 0,
HEX: 1,
/**
* Raw key material, possibly hex or base64-encoded. Use this for symmetric keys.
*
* Hint: `raw` would typically be used with Cap'n Proto's `embed` syntax to embed an
* external binary key file. `hex` or `base64` could do that too but can also be specified
* inline.
*
*/
BASE64: 2,
/**
* Private key in PEM-encoded PKCS#8 format.
*
*/
PKCS8: 3,
/**
* Public key in PEM-encoded SPKI format.
*
*/
SPKI: 4,
/**
* Key in JSON format.
*
*/
JWK: 5
};
var _Worker_Binding_CryptoKey = class extends Struct {
_adoptRaw(value) {
utils.setUint16(0, 0, this);
utils.adopt(value, utils.getPointer(0, this));
}
_disownRaw() {
return utils.disown(this.raw);
}
get raw() {
utils.testWhich("raw", utils.getUint16(0, this), 0, this);
return utils.getData(0, this);
}
_hasRaw() {
return !utils.isNull(utils.getPointer(0, this));
}
_initRaw(length) {
utils.setUint16(0, 0, this);
return utils.initData(0, length, this);
}
get _isRaw() {
return utils.getUint16(0, this) === 0;
}
set raw(value) {
utils.setUint16(0, 0, this);
utils.copyFrom(value, utils.getPointer(0, this));
}
get hex() {
utils.testWhich("hex", utils.getUint16(0, this), 1, this);
return utils.getText(0, this);
}
get _isHex() {
return utils.getUint16(0, this) === 1;
}
set hex(value) {
utils.setUint16(0, 1, this);
utils.setText(0, value, this);
}
/**
* Raw key material, possibly hex or base64-encoded. Use this for symmetric keys.
*
* Hint: `raw` would typically be used with Cap'n Proto's `embed` syntax to embed an
* external binary key file. `hex` or `base64` could do that too but can also be specified
* inline.
*
*/
get base64() {
utils.testWhich("base64", utils.getUint16(0, this), 2, this);
return utils.getText(0, this);
}
get _isBase64() {
return utils.getUint16(0, this) === 2;
}
set base64(value) {
utils.setUint16(0, 2, this);
utils.setText(0, value, this);
}
/**
* Private key in PEM-encoded PKCS#8 format.
*
*/
get pkcs8() {
utils.testWhich("pkcs8", utils.getUint16(0, this), 3, this);
return utils.getText(0, this);
}
get _isPkcs8() {
return utils.getUint16(0, this) === 3;
}
set pkcs8(value) {
utils.setUint16(0, 3, this);
utils.setText(0, value, this);
}
/**
* Public key in PEM-encoded SPKI format.
*
*/
get spki() {
utils.testWhich("spki", utils.getUint16(0, this), 4, this);
return utils.getText(0, this);
}
get _isSpki() {
return utils.getUint16(0, this) === 4;
}
set spki(value) {
utils.setUint16(0, 4, this);
utils.setText(0, value, this);
}
/**
* Key in JSON format.
*
*/
get jwk() {
utils.testWhich("jwk", utils.getUint16(0, this), 5, this);
return utils.getText(0, this);
}
get _isJwk() {
return utils.getUint16(0, this) === 5;
}
set jwk(value) {
utils.setUint16(0, 5, this);
utils.setText(0, value, this);
}
/**
* Value for the `algorithm` parameter.
*
*/
get algorithm() {
return utils.getAs(Worker_Binding_CryptoKey_Algorithm, this);
}
_initAlgorithm() {
return utils.getAs(Worker_Binding_CryptoKey_Algorithm, this);
}
/**
* Is the Worker allowed to export this key to obtain the underlying key material? Setting
* this false ensures that the key cannot be leaked by errant JavaScript code; the key can
* only be used in WebCrypto operations.
*
*/
get extractable() {
return utils.getBit(
32,
this,
_Worker_Binding_CryptoKey._capnp.defaultExtractable
);
}
set extractable(value) {
utils.setBit(
32,
value,
this,
_Worker_Binding_CryptoKey._capnp.defaultExtractable
);
}
_adoptUsages(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownUsages() {
return utils.disown(this.usages);
}
/**
* What operations is this key permitted to be used for?
*
*/
get usages() {
return utils.getList(
2,
Uint16List,
this
);
}
_hasUsages() {
return !utils.isNull(utils.getPointer(2, this));
}
_initUsages(length) {
return utils.initList(
2,
Uint16List,
length,
this
);
}
set usages(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Worker_Binding_CryptoKey_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
var Worker_Binding_CryptoKey = _Worker_Binding_CryptoKey;
__publicField(Worker_Binding_CryptoKey, "RAW", Worker_Binding_CryptoKey_Which.RAW);
__publicField(Worker_Binding_CryptoKey, "HEX", Worker_Binding_CryptoKey_Which.HEX);
__publicField(Worker_Binding_CryptoKey, "BASE64", Worker_Binding_CryptoKey_Which.BASE64);
__publicField(Worker_Binding_CryptoKey, "PKCS8", Worker_Binding_CryptoKey_Which.PKCS8);
__publicField(Worker_Binding_CryptoKey, "SPKI", Worker_Binding_CryptoKey_Which.SPKI);
__publicField(Worker_Binding_CryptoKey, "JWK", Worker_Binding_CryptoKey_Which.JWK);
__publicField(Worker_Binding_CryptoKey, "Usage", Worker_Binding_CryptoKey_Usage);
__publicField(Worker_Binding_CryptoKey, "_capnp", {
displayName: "CryptoKey",
id: "b5e1bff0e57d6eb0",
size: new ObjectSize(8, 3),
defaultExtractable: getBitMask(false, 0)
});
var Worker_Binding_MemoryCacheLimits = class extends Struct {
get maxKeys() {
return utils.getUint32(0, this);
}
set maxKeys(value) {
utils.setUint32(0, value, this);
}
get maxValueSize() {
return utils.getUint32(4, this);
}
set maxValueSize(value) {
utils.setUint32(4, value, this);
}
get maxTotalValueSize() {
return utils.getUint64(8, this);
}
set maxTotalValueSize(value) {
utils.setUint64(8, value, this);
}
toString() {
return "Worker_Binding_MemoryCacheLimits_" + super.toString();
}
};
__publicField(Worker_Binding_MemoryCacheLimits, "_capnp", {
displayName: "MemoryCacheLimits",
id: "8d66725b0867e634",
size: new ObjectSize(16, 0)
});
var _Worker_Binding_WrappedBinding = class extends Struct {
/**
* Wrapper module name.
* The module must be an internal one (provided by extension or registered in the c++ code).
* Module will be instantitated during binding initialization phase.
*
*/
get moduleName() {
return utils.getText(0, this);
}
set moduleName(value) {
utils.setText(0, value, this);
}
/**
* Module needs to export a function with a given name (default export gets "default" name).
* The function needs to accept a single `env` argument - a dictionary with inner bindings.
* Function will be invoked during initialization phase and its return value will be used as
* resulting binding value.
*
*/
get entrypoint() {
return utils.getText(
1,
this,
_Worker_Binding_WrappedBinding._capnp.defaultEntrypoint
);
}
set entrypoint(value) {
utils.setText(1, value, this);
}
_adoptInnerBindings(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownInnerBindings() {
return utils.disown(this.innerBindings);
}
/**
* Inner bindings that will be created and passed in the env dictionary.
* These bindings shall be used to implement end-user api, and are not available to the
* binding consumers unless "re-exported" in wrapBindings function.
*
*/
get innerBindings() {
return utils.getList(
2,
_Worker_Binding_WrappedBinding._InnerBindings,
this
);
}
_hasInnerBindings() {
return !utils.isNull(utils.getPointer(2, this));
}
_initInnerBindings(length) {
return utils.initList(
2,
_Worker_Binding_WrappedBinding._InnerBindings,
length,
this
);
}
set innerBindings(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Worker_Binding_WrappedBinding_" + super.toString();
}
};
var Worker_Binding_WrappedBinding = _Worker_Binding_WrappedBinding;
__publicField(Worker_Binding_WrappedBinding, "_capnp", {
displayName: "WrappedBinding",
id: "e6f066b75f0ea113",
size: new ObjectSize(0, 3),
defaultEntrypoint: "default"
});
__publicField(Worker_Binding_WrappedBinding, "_InnerBindings");
var Worker_Binding_Parameter = class extends Struct {
_adoptType(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownType() {
return utils.disown(this.type);
}
/**
* Expected type of this parameter.
*
*/
get type() {
return utils.getStruct(1, Worker_Binding_Type, this);
}
_hasType() {
return !utils.isNull(utils.getPointer(1, this));
}
_initType() {
return utils.initStructAt(1, Worker_Binding_Type, this);
}
set type(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* If true, this binding is optional. Derived workers need not specify it, in which case
* the binding won't be present in the environment object passed to the worker.
*
* When a Worker has any non-optional parameters that haven't been filled in, then it can
* only be used for inheritance; it cannot be invoked directly.
*
*/
get optional() {
return utils.getBit(16, this);
}
set optional(value) {
utils.setBit(16, value, this);
}
toString() {
return "Worker_Binding_Parameter_" + super.toString();
}
};
__publicField(Worker_Binding_Parameter, "_capnp", {
displayName: "parameter",
id: "dc57e1258d26d152",
size: new ObjectSize(8, 6)
});
var Worker_Binding_Hyperdrive = class extends Struct {
_adoptDesignator(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownDesignator() {
return utils.disown(this.designator);
}
get designator() {
return utils.getStruct(1, ServiceDesignator, this);
}
_hasDesignator() {
return !utils.isNull(utils.getPointer(1, this));
}
_initDesignator() {
return utils.initStructAt(1, ServiceDesignator, this);
}
set designator(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
get database() {
return utils.getText(2, this);
}
set database(value) {
utils.setText(2, value, this);
}
get user() {
return utils.getText(3, this);
}
set user(value) {
utils.setText(3, value, this);
}
get password() {
return utils.getText(4, this);
}
set password(value) {
utils.setText(4, value, this);
}
get scheme() {
return utils.getText(5, this);
}
set scheme(value) {
utils.setText(5, value, this);
}
toString() {
return "Worker_Binding_Hyperdrive_" + super.toString();
}
};
__publicField(Worker_Binding_Hyperdrive, "_capnp", {
displayName: "hyperdrive",
id: "ad6c391cd55f3134",
size: new ObjectSize(8, 6)
});
var Worker_Binding_MemoryCache = class extends Struct {
/**
* The identifier associated with this cache. Any number of isolates
* can access the same in-memory cache (within the same process), and
* each worker may use any number of in-memory caches.
*
*/
get id() {
return utils.getText(1, this);
}
set id(value) {
utils.setText(1, value, this);
}
_adoptLimits(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownLimits() {
return utils.disown(this.limits);
}
get limits() {
return utils.getStruct(2, Worker_Binding_MemoryCacheLimits, this);
}
_hasLimits() {
return !utils.isNull(utils.getPointer(2, this));
}
_initLimits() {
return utils.initStructAt(2, Worker_Binding_MemoryCacheLimits, this);
}
set limits(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Worker_Binding_MemoryCache_" + super.toString();
}
};
__publicField(Worker_Binding_MemoryCache, "_capnp", {
displayName: "memoryCache",
id: "aed5760c349869da",
size: new ObjectSize(8, 6)
});
var Worker_Binding_WorkerLoader = class extends Struct {
/**
* Optional: The identifier associated with this Worker loader. Multiple Workers can bind to
* the same ID in order to access the same loader, so that if they request the same name
* from it, they'll end up sharing the same loaded Worker.
*
* (If omitted, the binding will not share a cache with any other binding.)
*
*/
get id() {
return utils.getText(1, this);
}
set id(value) {
utils.setText(1, value, this);
}
toString() {
return "Worker_Binding_WorkerLoader_" + super.toString();
}
};
__publicField(Worker_Binding_WorkerLoader, "_capnp", {
displayName: "workerLoader",
id: "a3de996091635c4d",
size: new ObjectSize(8, 6)
});
var Worker_Binding_Which = {
UNSPECIFIED: 0,
/**
* (This catches when someone forgets to specify one of the union members. Do not set this.)
*
*/
PARAMETER: 1,
/**
* Indicates that the Worker requires a binding of the given type, but it won't be specified
* here. Another Worker can inherit this Worker and fill in this binding.
*
*/
TEXT: 2,
/**
* A string.
*
*/
DATA: 3,
/**
* An ArrayBuffer.
*
*/
JSON: 4,
/**
* A value parsed from JSON.
*
*/
WASM_MODULE: 5,
/**
* A WebAssembly module. The binding will be an instance of `WebAssembly.Module`. Only
* supported when using Service Workers syntax.
*
* DEPRECATED: Please switch to ES modules syntax instead, and embed Wasm modules as modules.
*
*/
CRYPTO_KEY: 6,
/**
* A CryptoKey instance, for use with the WebCrypto API.
*
* Note that by setting `extractable = false`, you can prevent the Worker code from accessing
* or leaking the raw key material; it will only be able to use the key to perform WebCrypto
* operations.
*
*/
SERVICE: 7,
/**
* A binding representing access to an in-memory cache.
*
*/
DURABLE_OBJECT_CLASS: 19,
/**
* Binding to a named service (possibly, a worker).
*
*/
DURABLE_OBJECT_NAMESPACE: 8,
/**
* Binding to the durable object namespace implemented by the given class.
*
* In the common case that this refers to a class in the same Worker, you can specify just
* a string, like:
*
* durableObjectNamespace = "MyClass"
*
*/
KV_NAMESPACE: 9,
/**
* A KV namespace, implemented by the named service. The Worker sees a KvNamespace-typed
* binding. Requests to the namespace will be converted into HTTP requests targeting the
* given service name.
*
*/
R2BUCKET: 10,
R2ADMIN: 11,
/**
* R2 bucket and admin API bindings. Similar to KV namespaces, these turn operations into
* HTTP requests aimed at the named service.
*
*/
WRAPPED: 12,
/**
* Wraps a collection of inner bindings in a common api functionality.
*
*/
QUEUE: 13,
/**
* A Queue binding, implemented by the named service. Requests to the
* namespace will be converted into HTTP requests targeting the given
* service name.
*
*/
FROM_ENVIRONMENT: 14,
/**
* Takes the value of an environment variable from the system. The value specified here is
* the name of a system environment variable. The value of the binding is obtained by invoking
* `getenv()` with that name. If the environment variable isn't set, the binding value is
* `null`.
*
*/
ANALYTICS_ENGINE: 15,
/**
* A binding for Analytics Engine. Allows workers to store information through Analytics Engine Events.
* workerd will forward AnalyticsEngineEvents to designated service in the body of HTTP requests
* This binding is subject to change and requires the `--experimental` flag
*
*/
HYPERDRIVE: 16,
/**
* A binding for Hyperdrive. Allows workers to use Hyperdrive caching & pooling for Postgres
* databases.
*
*/
UNSAFE_EVAL: 17,
/**
* A simple binding that enables access to the UnsafeEval API.
*
*/
MEMORY_CACHE: 18,
/**
* A Durable Object class binding, without an actual storage namespace. This can be used to
* implement a facet.
*
*/
WORKER_LOADER: 20
};
var Worker_Binding = class extends Struct {
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
get _isUnspecified() {
return utils.getUint16(0, this) === 0;
}
set unspecified(_) {
utils.setUint16(0, 0, this);
}
/**
* Indicates that the Worker requires a binding of the given type, but it won't be specified
* here. Another Worker can inherit this Worker and fill in this binding.
*
*/
get parameter() {
utils.testWhich("parameter", utils.getUint16(0, this), 1, this);
return utils.getAs(Worker_Binding_Parameter, this);
}
_initParameter() {
utils.setUint16(0, 1, this);
return utils.getAs(Worker_Binding_Parameter, this);
}
get _isParameter() {
return utils.getUint16(0, this) === 1;
}
set parameter(_) {
utils.setUint16(0, 1, this);
}
/**
* A string.
*
*/
get text() {
utils.testWhich("text", utils.getUint16(0, this), 2, this);
return utils.getText(1, this);
}
get _isText() {
return utils.getUint16(0, this) === 2;
}
set text(value) {
utils.setUint16(0, 2, this);
utils.setText(1, value, this);
}
_adoptData(value) {
utils.setUint16(0, 3, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownData() {
return utils.disown(this.data);
}
/**
* An ArrayBuffer.
*
*/
get data() {
utils.testWhich("data", utils.getUint16(0, this), 3, this);
return utils.getData(1, this);
}
_hasData() {
return !utils.isNull(utils.getPointer(1, this));
}
_initData(length) {
utils.setUint16(0, 3, this);
return utils.initData(1, length, this);
}
get _isData() {
return utils.getUint16(0, this) === 3;
}
set data(value) {
utils.setUint16(0, 3, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* A value parsed from JSON.
*
*/
get json() {
utils.testWhich("json", utils.getUint16(0, this), 4, this);
return utils.getText(1, this);
}
get _isJson() {
return utils.getUint16(0, this) === 4;
}
set json(value) {
utils.setUint16(0, 4, this);
utils.setText(1, value, this);
}
_adoptWasmModule(value) {
utils.setUint16(0, 5, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownWasmModule() {
return utils.disown(this.wasmModule);
}
/**
* A WebAssembly module. The binding will be an instance of `WebAssembly.Module`. Only
* supported when using Service Workers syntax.
*
* DEPRECATED: Please switch to ES modules syntax instead, and embed Wasm modules as modules.
*
*/
get wasmModule() {
utils.testWhich("wasmModule", utils.getUint16(0, this), 5, this);
return utils.getData(1, this);
}
_hasWasmModule() {
return !utils.isNull(utils.getPointer(1, this));
}
_initWasmModule(length) {
utils.setUint16(0, 5, this);
return utils.initData(1, length, this);
}
get _isWasmModule() {
return utils.getUint16(0, this) === 5;
}
set wasmModule(value) {
utils.setUint16(0, 5, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptCryptoKey(value) {
utils.setUint16(0, 6, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownCryptoKey() {
return utils.disown(this.cryptoKey);
}
/**
* A CryptoKey instance, for use with the WebCrypto API.
*
* Note that by setting `extractable = false`, you can prevent the Worker code from accessing
* or leaking the raw key material; it will only be able to use the key to perform WebCrypto
* operations.
*
*/
get cryptoKey() {
utils.testWhich("cryptoKey", utils.getUint16(0, this), 6, this);
return utils.getStruct(1, Worker_Binding_CryptoKey, this);
}
_hasCryptoKey() {
return !utils.isNull(utils.getPointer(1, this));
}
_initCryptoKey() {
utils.setUint16(0, 6, this);
return utils.initStructAt(1, Worker_Binding_CryptoKey, this);
}
get _isCryptoKey() {
return utils.getUint16(0, this) === 6;
}
set cryptoKey(value) {
utils.setUint16(0, 6, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptService(value) {
utils.setUint16(0, 7, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownService() {
return utils.disown(this.service);
}
/**
* Binding to a named service (possibly, a worker).
*
*/
get service() {
utils.testWhich("service", utils.getUint16(0, this), 7, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasService() {
return !utils.isNull(utils.getPointer(1, this));
}
_initService() {
utils.setUint16(0, 7, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isService() {
return utils.getUint16(0, this) === 7;
}
set service(value) {
utils.setUint16(0, 7, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptDurableObjectClass(value) {
utils.setUint16(0, 19, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownDurableObjectClass() {
return utils.disown(this.durableObjectClass);
}
/**
* A Durable Object class binding, without an actual storage namespace. This can be used to
* implement a facet.
*
*/
get durableObjectClass() {
utils.testWhich(
"durableObjectClass",
utils.getUint16(0, this),
19,
this
);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasDurableObjectClass() {
return !utils.isNull(utils.getPointer(1, this));
}
_initDurableObjectClass() {
utils.setUint16(0, 19, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isDurableObjectClass() {
return utils.getUint16(0, this) === 19;
}
set durableObjectClass(value) {
utils.setUint16(0, 19, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptDurableObjectNamespace(value) {
utils.setUint16(0, 8, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownDurableObjectNamespace() {
return utils.disown(this.durableObjectNamespace);
}
/**
* Binding to the durable object namespace implemented by the given class.
*
* In the common case that this refers to a class in the same Worker, you can specify just
* a string, like:
*
* durableObjectNamespace = "MyClass"
*
*/
get durableObjectNamespace() {
utils.testWhich(
"durableObjectNamespace",
utils.getUint16(0, this),
8,
this
);
return utils.getStruct(
1,
Worker_Binding_DurableObjectNamespaceDesignator,
this
);
}
_hasDurableObjectNamespace() {
return !utils.isNull(utils.getPointer(1, this));
}
_initDurableObjectNamespace() {
utils.setUint16(0, 8, this);
return utils.initStructAt(
1,
Worker_Binding_DurableObjectNamespaceDesignator,
this
);
}
get _isDurableObjectNamespace() {
return utils.getUint16(0, this) === 8;
}
set durableObjectNamespace(value) {
utils.setUint16(0, 8, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptKvNamespace(value) {
utils.setUint16(0, 9, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownKvNamespace() {
return utils.disown(this.kvNamespace);
}
/**
* A KV namespace, implemented by the named service. The Worker sees a KvNamespace-typed
* binding. Requests to the namespace will be converted into HTTP requests targeting the
* given service name.
*
*/
get kvNamespace() {
utils.testWhich("kvNamespace", utils.getUint16(0, this), 9, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasKvNamespace() {
return !utils.isNull(utils.getPointer(1, this));
}
_initKvNamespace() {
utils.setUint16(0, 9, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isKvNamespace() {
return utils.getUint16(0, this) === 9;
}
set kvNamespace(value) {
utils.setUint16(0, 9, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptR2Bucket(value) {
utils.setUint16(0, 10, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownR2Bucket() {
return utils.disown(this.r2Bucket);
}
get r2Bucket() {
utils.testWhich("r2Bucket", utils.getUint16(0, this), 10, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasR2Bucket() {
return !utils.isNull(utils.getPointer(1, this));
}
_initR2Bucket() {
utils.setUint16(0, 10, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isR2Bucket() {
return utils.getUint16(0, this) === 10;
}
set r2Bucket(value) {
utils.setUint16(0, 10, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptR2Admin(value) {
utils.setUint16(0, 11, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownR2Admin() {
return utils.disown(this.r2Admin);
}
/**
* R2 bucket and admin API bindings. Similar to KV namespaces, these turn operations into
* HTTP requests aimed at the named service.
*
*/
get r2Admin() {
utils.testWhich("r2Admin", utils.getUint16(0, this), 11, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasR2Admin() {
return !utils.isNull(utils.getPointer(1, this));
}
_initR2Admin() {
utils.setUint16(0, 11, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isR2Admin() {
return utils.getUint16(0, this) === 11;
}
set r2Admin(value) {
utils.setUint16(0, 11, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptWrapped(value) {
utils.setUint16(0, 12, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownWrapped() {
return utils.disown(this.wrapped);
}
/**
* Wraps a collection of inner bindings in a common api functionality.
*
*/
get wrapped() {
utils.testWhich("wrapped", utils.getUint16(0, this), 12, this);
return utils.getStruct(1, Worker_Binding_WrappedBinding, this);
}
_hasWrapped() {
return !utils.isNull(utils.getPointer(1, this));
}
_initWrapped() {
utils.setUint16(0, 12, this);
return utils.initStructAt(1, Worker_Binding_WrappedBinding, this);
}
get _isWrapped() {
return utils.getUint16(0, this) === 12;
}
set wrapped(value) {
utils.setUint16(0, 12, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptQueue(value) {
utils.setUint16(0, 13, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownQueue() {
return utils.disown(this.queue);
}
/**
* A Queue binding, implemented by the named service. Requests to the
* namespace will be converted into HTTP requests targeting the given
* service name.
*
*/
get queue() {
utils.testWhich("queue", utils.getUint16(0, this), 13, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasQueue() {
return !utils.isNull(utils.getPointer(1, this));
}
_initQueue() {
utils.setUint16(0, 13, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isQueue() {
return utils.getUint16(0, this) === 13;
}
set queue(value) {
utils.setUint16(0, 13, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* Takes the value of an environment variable from the system. The value specified here is
* the name of a system environment variable. The value of the binding is obtained by invoking
* `getenv()` with that name. If the environment variable isn't set, the binding value is
* `null`.
*
*/
get fromEnvironment() {
utils.testWhich("fromEnvironment", utils.getUint16(0, this), 14, this);
return utils.getText(1, this);
}
get _isFromEnvironment() {
return utils.getUint16(0, this) === 14;
}
set fromEnvironment(value) {
utils.setUint16(0, 14, this);
utils.setText(1, value, this);
}
_adoptAnalyticsEngine(value) {
utils.setUint16(0, 15, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownAnalyticsEngine() {
return utils.disown(this.analyticsEngine);
}
/**
* A binding for Analytics Engine. Allows workers to store information through Analytics Engine Events.
* workerd will forward AnalyticsEngineEvents to designated service in the body of HTTP requests
* This binding is subject to change and requires the `--experimental` flag
*
*/
get analyticsEngine() {
utils.testWhich("analyticsEngine", utils.getUint16(0, this), 15, this);
return utils.getStruct(1, ServiceDesignator, this);
}
_hasAnalyticsEngine() {
return !utils.isNull(utils.getPointer(1, this));
}
_initAnalyticsEngine() {
utils.setUint16(0, 15, this);
return utils.initStructAt(1, ServiceDesignator, this);
}
get _isAnalyticsEngine() {
return utils.getUint16(0, this) === 15;
}
set analyticsEngine(value) {
utils.setUint16(0, 15, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* A binding for Hyperdrive. Allows workers to use Hyperdrive caching & pooling for Postgres
* databases.
*
*/
get hyperdrive() {
utils.testWhich("hyperdrive", utils.getUint16(0, this), 16, this);
return utils.getAs(Worker_Binding_Hyperdrive, this);
}
_initHyperdrive() {
utils.setUint16(0, 16, this);
return utils.getAs(Worker_Binding_Hyperdrive, this);
}
get _isHyperdrive() {
return utils.getUint16(0, this) === 16;
}
set hyperdrive(_) {
utils.setUint16(0, 16, this);
}
get _isUnsafeEval() {
return utils.getUint16(0, this) === 17;
}
set unsafeEval(_) {
utils.setUint16(0, 17, this);
}
/**
* A binding representing access to an in-memory cache.
*
*/
get memoryCache() {
utils.testWhich("memoryCache", utils.getUint16(0, this), 18, this);
return utils.getAs(Worker_Binding_MemoryCache, this);
}
_initMemoryCache() {
utils.setUint16(0, 18, this);
return utils.getAs(Worker_Binding_MemoryCache, this);
}
get _isMemoryCache() {
return utils.getUint16(0, this) === 18;
}
set memoryCache(_) {
utils.setUint16(0, 18, this);
}
/**
* A binding representing the ability to dynamically load Workers from code presented at
* runtime.
*
* A Worker loader is not just a function that loads a Worker, but also serves as a
* cache of Workers, automatically unloading Workers that are not in use. To that end, each
* Worker must have a name, and if a Worker with that name already exists, it'll be reused.
*
*/
get workerLoader() {
utils.testWhich("workerLoader", utils.getUint16(0, this), 20, this);
return utils.getAs(Worker_Binding_WorkerLoader, this);
}
_initWorkerLoader() {
utils.setUint16(0, 20, this);
return utils.getAs(Worker_Binding_WorkerLoader, this);
}
get _isWorkerLoader() {
return utils.getUint16(0, this) === 20;
}
set workerLoader(_) {
utils.setUint16(0, 20, this);
}
toString() {
return "Worker_Binding_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Worker_Binding, "UNSPECIFIED", Worker_Binding_Which.UNSPECIFIED);
__publicField(Worker_Binding, "PARAMETER", Worker_Binding_Which.PARAMETER);
__publicField(Worker_Binding, "TEXT", Worker_Binding_Which.TEXT);
__publicField(Worker_Binding, "DATA", Worker_Binding_Which.DATA);
__publicField(Worker_Binding, "JSON", Worker_Binding_Which.JSON);
__publicField(Worker_Binding, "WASM_MODULE", Worker_Binding_Which.WASM_MODULE);
__publicField(Worker_Binding, "CRYPTO_KEY", Worker_Binding_Which.CRYPTO_KEY);
__publicField(Worker_Binding, "SERVICE", Worker_Binding_Which.SERVICE);
__publicField(Worker_Binding, "DURABLE_OBJECT_CLASS", Worker_Binding_Which.DURABLE_OBJECT_CLASS);
__publicField(Worker_Binding, "DURABLE_OBJECT_NAMESPACE", Worker_Binding_Which.DURABLE_OBJECT_NAMESPACE);
__publicField(Worker_Binding, "KV_NAMESPACE", Worker_Binding_Which.KV_NAMESPACE);
__publicField(Worker_Binding, "R2BUCKET", Worker_Binding_Which.R2BUCKET);
__publicField(Worker_Binding, "R2ADMIN", Worker_Binding_Which.R2ADMIN);
__publicField(Worker_Binding, "WRAPPED", Worker_Binding_Which.WRAPPED);
__publicField(Worker_Binding, "QUEUE", Worker_Binding_Which.QUEUE);
__publicField(Worker_Binding, "FROM_ENVIRONMENT", Worker_Binding_Which.FROM_ENVIRONMENT);
__publicField(Worker_Binding, "ANALYTICS_ENGINE", Worker_Binding_Which.ANALYTICS_ENGINE);
__publicField(Worker_Binding, "HYPERDRIVE", Worker_Binding_Which.HYPERDRIVE);
__publicField(Worker_Binding, "UNSAFE_EVAL", Worker_Binding_Which.UNSAFE_EVAL);
__publicField(Worker_Binding, "MEMORY_CACHE", Worker_Binding_Which.MEMORY_CACHE);
__publicField(Worker_Binding, "WORKER_LOADER", Worker_Binding_Which.WORKER_LOADER);
__publicField(Worker_Binding, "Type", Worker_Binding_Type);
__publicField(Worker_Binding, "DurableObjectNamespaceDesignator", Worker_Binding_DurableObjectNamespaceDesignator);
__publicField(Worker_Binding, "CryptoKey", Worker_Binding_CryptoKey);
__publicField(Worker_Binding, "MemoryCacheLimits", Worker_Binding_MemoryCacheLimits);
__publicField(Worker_Binding, "WrappedBinding", Worker_Binding_WrappedBinding);
__publicField(Worker_Binding, "_capnp", {
displayName: "Binding",
id: "8e7e492fd7e35f3e",
size: new ObjectSize(8, 6)
});
var Worker_DurableObjectNamespace_ContainerOptions = class extends Struct {
/**
* Image name to be used to create the container using supported provider.
* By default, we pull the "latest" tag of this image.
*
*/
get imageName() {
return utils.getText(0, this);
}
set imageName(value) {
utils.setText(0, value, this);
}
toString() {
return "Worker_DurableObjectNamespace_ContainerOptions_" + super.toString();
}
};
__publicField(Worker_DurableObjectNamespace_ContainerOptions, "_capnp", {
displayName: "ContainerOptions",
id: "a609621a4d236cd7",
size: new ObjectSize(0, 1)
});
var Worker_DurableObjectNamespace_Which = {
/**
* Exported class name that implements the Durable Object.
*
* Changing the class name will not break compatibility with existing storage, so long as
* `uniqueKey` stays the same.
*
*/
UNIQUE_KEY: 0,
/**
* A unique, stable ID associated with this namespace. This could be a GUID, or any other
* string which does not appear anywhere else in the world.
*
* This string is used to ensure that objects of this class have unique identifiers distinct
* from objects of any other class. Object IDs are cryptographically derived from `uniqueKey`
* and validated against it. It is impossible to guess or forge a valid object ID without
* knowing the `uniqueKey`. Hence, if you keep the key secret, you can prevent anyone from
* forging IDs. However, if you don't care if users can forge valid IDs, then it's not a big
* deal if the key leaks.
*
* DO NOT LOSE this key, otherwise it may be difficult or impossible to recover stored data.
*
*/
EPHEMERAL_LOCAL: 1
};
var Worker_DurableObjectNamespace = class extends Struct {
/**
* Exported class name that implements the Durable Object.
*
* Changing the class name will not break compatibility with existing storage, so long as
* `uniqueKey` stays the same.
*
*/
get className() {
return utils.getText(0, this);
}
set className(value) {
utils.setText(0, value, this);
}
/**
* A unique, stable ID associated with this namespace. This could be a GUID, or any other
* string which does not appear anywhere else in the world.
*
* This string is used to ensure that objects of this class have unique identifiers distinct
* from objects of any other class. Object IDs are cryptographically derived from `uniqueKey`
* and validated against it. It is impossible to guess or forge a valid object ID without
* knowing the `uniqueKey`. Hence, if you keep the key secret, you can prevent anyone from
* forging IDs. However, if you don't care if users can forge valid IDs, then it's not a big
* deal if the key leaks.
*
* DO NOT LOSE this key, otherwise it may be difficult or impossible to recover stored data.
*
*/
get uniqueKey() {
utils.testWhich("uniqueKey", utils.getUint16(0, this), 0, this);
return utils.getText(1, this);
}
get _isUniqueKey() {
return utils.getUint16(0, this) === 0;
}
set uniqueKey(value) {
utils.setUint16(0, 0, this);
utils.setText(1, value, this);
}
get _isEphemeralLocal() {
return utils.getUint16(0, this) === 1;
}
set ephemeralLocal(_) {
utils.setUint16(0, 1, this);
}
/**
* By default, Durable Objects are evicted after 10 seconds of inactivity, and expire 70 seconds
* after all clients have disconnected. Some applications may want to keep their Durable Objects
* pinned to memory forever, so we provide this flag to change the default behavior.
*
* Note that this is only supported in Workerd; production Durable Objects cannot toggle eviction.
*
*/
get preventEviction() {
return utils.getBit(16, this);
}
set preventEviction(value) {
utils.setBit(16, value, this);
}
/**
* Whether or not Durable Objects in this namespace can use the `storage.sql` API to execute SQL
* queries.
*
* workerd uses SQLite to back all Durable Objects, but the SQL API is hidden by default to
* emulate behavior of traditional DO namespaces on Cloudflare that aren't SQLite-backed. This
* flag should be enabled when testing code that will run on a SQLite-backed namespace.
*
*/
get enableSql() {
return utils.getBit(17, this);
}
set enableSql(value) {
utils.setBit(17, value, this);
}
_adoptContainer(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownContainer() {
return utils.disown(this.container);
}
/**
* If present, Durable Objects in this namespace have attached containers.
* workerd will talk to the configured container engine to start containers for each
* Durable Object based on the given image. The Durable Object can access the container via the
* ctx.container API. TODO(CloudChamber): add link to docs.
*
*/
get container() {
return utils.getStruct(
2,
Worker_DurableObjectNamespace_ContainerOptions,
this
);
}
_hasContainer() {
return !utils.isNull(utils.getPointer(2, this));
}
_initContainer() {
return utils.initStructAt(
2,
Worker_DurableObjectNamespace_ContainerOptions,
this
);
}
set container(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Worker_DurableObjectNamespace_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(Worker_DurableObjectNamespace, "UNIQUE_KEY", Worker_DurableObjectNamespace_Which.UNIQUE_KEY);
__publicField(Worker_DurableObjectNamespace, "EPHEMERAL_LOCAL", Worker_DurableObjectNamespace_Which.EPHEMERAL_LOCAL);
__publicField(Worker_DurableObjectNamespace, "ContainerOptions", Worker_DurableObjectNamespace_ContainerOptions);
__publicField(Worker_DurableObjectNamespace, "_capnp", {
displayName: "DurableObjectNamespace",
id: "b429dd547d15747d",
size: new ObjectSize(8, 3)
});
var Worker_DockerConfiguration = class extends Struct {
/**
* Path to the Docker socket.
*
*/
get socketPath() {
return utils.getText(0, this);
}
set socketPath(value) {
utils.setText(0, value, this);
}
toString() {
return "Worker_DockerConfiguration_" + super.toString();
}
};
__publicField(Worker_DockerConfiguration, "_capnp", {
displayName: "DockerConfiguration",
id: "e62f96c20d9fb872",
size: new ObjectSize(0, 1)
});
var Worker_DurableObjectStorage_Which = {
/**
* Default. The worker has no Durable Objects. `durableObjectNamespaces` must be empty, or
* define all namespaces as `ephemeralLocal`, or this must be an abstract worker (meant to be
* inherited by other workers, who will specify `durableObjectStorage`).
*
*/
NONE: 0,
/**
* The `state.storage` API stores in-memory only. All stored data will persist for the
* lifetime of the process, but will be lost upon process exit.
*
* Individual objects will still shut down when idle as normal -- only data stored with the
* `state.storage` interface is persistent for the lifetime of the process.
*
* This mode is intended for local testing purposes.
*
*/
IN_MEMORY: 1,
/**
* ** EXPERIMENTAL; SUBJECT TO BACKWARDS-INCOMPATIBLE CHANGE **
*
* Durable Object data will be stored in a directory on local disk. This field is the name of
* a service, which must be a DiskDirectory service. For each Durable Object class, a
* subdirectory will be created using `uniqueKey` as the name. Within the directory, one or
* more files are created for each object, with names `<id>.<ext>`, where `.<ext>` may be any of
* a number of different extensions depending on the storage mode. (Currently, the main storage
* is a file with the extension `.sqlite`, and in certain situations extra files with the
* extensions `.sqlite-wal`, and `.sqlite-shm` may also be present.)
*
*/
LOCAL_DISK: 2
};
var Worker_DurableObjectStorage = class extends Struct {
get _isNone() {
return utils.getUint16(2, this) === 0;
}
set none(_) {
utils.setUint16(2, 0, this);
}
get _isInMemory() {
return utils.getUint16(2, this) === 1;
}
set inMemory(_) {
utils.setUint16(2, 1, this);
}
/**
* ** EXPERIMENTAL; SUBJECT TO BACKWARDS-INCOMPATIBLE CHANGE **
*
* Durable Object data will be stored in a directory on local disk. This field is the name of
* a service, which must be a DiskDirectory service. For each Durable Object class, a
* subdirectory will be created using `uniqueKey` as the name. Within the directory, one or
* more files are created for each object, with names `<id>.<ext>`, where `.<ext>` may be any of
* a number of different extensions depending on the storage mode. (Currently, the main storage
* is a file with the extension `.sqlite`, and in certain situations extra files with the
* extensions `.sqlite-wal`, and `.sqlite-shm` may also be present.)
*
*/
get localDisk() {
utils.testWhich("localDisk", utils.getUint16(2, this), 2, this);
return utils.getText(8, this);
}
get _isLocalDisk() {
return utils.getUint16(2, this) === 2;
}
set localDisk(value) {
utils.setUint16(2, 2, this);
utils.setText(8, value, this);
}
toString() {
return "Worker_DurableObjectStorage_" + super.toString();
}
which() {
return utils.getUint16(2, this);
}
};
__publicField(Worker_DurableObjectStorage, "NONE", Worker_DurableObjectStorage_Which.NONE);
__publicField(Worker_DurableObjectStorage, "IN_MEMORY", Worker_DurableObjectStorage_Which.IN_MEMORY);
__publicField(Worker_DurableObjectStorage, "LOCAL_DISK", Worker_DurableObjectStorage_Which.LOCAL_DISK);
__publicField(Worker_DurableObjectStorage, "_capnp", {
displayName: "durableObjectStorage",
id: "cc72b3faa57827d4",
size: new ObjectSize(8, 13)
});
var Worker_ContainerEngine_Which = {
/**
* No container engine configured. Container operations will not be available.
*
*/
NONE: 0,
/**
* Use local Docker daemon for container operations.
* Only used for local development and testing purposes.
*
*/
LOCAL_DOCKER: 1
};
var Worker_ContainerEngine = class extends Struct {
get _isNone() {
return utils.getUint16(4, this) === 0;
}
set none(_) {
utils.setUint16(4, 0, this);
}
_adoptLocalDocker(value) {
utils.setUint16(4, 1, this);
utils.adopt(value, utils.getPointer(12, this));
}
_disownLocalDocker() {
return utils.disown(this.localDocker);
}
/**
* Use local Docker daemon for container operations.
* Only used for local development and testing purposes.
*
*/
get localDocker() {
utils.testWhich("localDocker", utils.getUint16(4, this), 1, this);
return utils.getStruct(12, Worker_DockerConfiguration, this);
}
_hasLocalDocker() {
return !utils.isNull(utils.getPointer(12, this));
}
_initLocalDocker() {
utils.setUint16(4, 1, this);
return utils.initStructAt(12, Worker_DockerConfiguration, this);
}
get _isLocalDocker() {
return utils.getUint16(4, this) === 1;
}
set localDocker(value) {
utils.setUint16(4, 1, this);
utils.copyFrom(value, utils.getPointer(12, this));
}
toString() {
return "Worker_ContainerEngine_" + super.toString();
}
which() {
return utils.getUint16(4, this);
}
};
__publicField(Worker_ContainerEngine, "NONE", Worker_ContainerEngine_Which.NONE);
__publicField(Worker_ContainerEngine, "LOCAL_DOCKER", Worker_ContainerEngine_Which.LOCAL_DOCKER);
__publicField(Worker_ContainerEngine, "_capnp", {
displayName: "containerEngine",
id: "82de68f58dc2eb24",
size: new ObjectSize(8, 13)
});
var Worker_Which = {
/**
* The Worker is composed of ES modules that may import each other. The first module in the list
* is the main module, which exports event handlers.
*
*/
MODULES: 0,
/**
* The Worker is composed of one big script that uses global `addEventListener()` to register
* event handlers.
*
* The value of this field is the raw source code. When using Cap'n Proto text format, use the
* `embed` directive to read the code from an external file:
*
* serviceWorkerScript = embed "worker.js"
*
*/
SERVICE_WORKER_SCRIPT: 1,
/**
* Inherit the configuration of some other Worker by its service name. This Worker is a clone
* of the other worker, but various settings can be modified:
* * `bindings`, if specified, overrides specific named bindings. (Each binding listed in the
* derived worker must match the name and type of some binding in the inherited worker.)
* * `globalOutbound`, if non-null, overrides the one specified in the inherited worker.
* * `compatibilityDate` and `compatibilityFlags` CANNOT be modified; they must be null.
* * If the inherited worker defines durable object namespaces, then the derived worker must
* specify `durableObjectStorage` to specify where its instances should be stored. Each
* devived worker receives its own namespace of objects. `durableObjectUniqueKeyModifier`
* must also be specified by derived workers.
*
* This can be useful when you want to run the same Worker in multiple configurations or hooked
* up to different back-ends. Note that all derived workers run in the same isolate as the
* base worker; they differ in the content of the `env` object passed to them, which contains
* the bindings. (When using service workers syntax, the global scope contains the bindings;
* in this case each derived worker runs in its own global scope, though still in the same
* isolate.)
*
*/
INHERIT: 2
};
var _Worker = class extends Struct {
_adoptModules(value) {
utils.setUint16(0, 0, this);
utils.adopt(value, utils.getPointer(0, this));
}
_disownModules() {
return utils.disown(this.modules);
}
/**
* The Worker is composed of ES modules that may import each other. The first module in the list
* is the main module, which exports event handlers.
*
*/
get modules() {
utils.testWhich("modules", utils.getUint16(0, this), 0, this);
return utils.getList(0, _Worker._Modules, this);
}
_hasModules() {
return !utils.isNull(utils.getPointer(0, this));
}
_initModules(length) {
utils.setUint16(0, 0, this);
return utils.initList(0, _Worker._Modules, length, this);
}
get _isModules() {
return utils.getUint16(0, this) === 0;
}
set modules(value) {
utils.setUint16(0, 0, this);
utils.copyFrom(value, utils.getPointer(0, this));
}
/**
* The Worker is composed of one big script that uses global `addEventListener()` to register
* event handlers.
*
* The value of this field is the raw source code. When using Cap'n Proto text format, use the
* `embed` directive to read the code from an external file:
*
* serviceWorkerScript = embed "worker.js"
*
*/
get serviceWorkerScript() {
utils.testWhich(
"serviceWorkerScript",
utils.getUint16(0, this),
1,
this
);
return utils.getText(0, this);
}
get _isServiceWorkerScript() {
return utils.getUint16(0, this) === 1;
}
set serviceWorkerScript(value) {
utils.setUint16(0, 1, this);
utils.setText(0, value, this);
}
/**
* Inherit the configuration of some other Worker by its service name. This Worker is a clone
* of the other worker, but various settings can be modified:
* * `bindings`, if specified, overrides specific named bindings. (Each binding listed in the
* derived worker must match the name and type of some binding in the inherited worker.)
* * `globalOutbound`, if non-null, overrides the one specified in the inherited worker.
* * `compatibilityDate` and `compatibilityFlags` CANNOT be modified; they must be null.
* * If the inherited worker defines durable object namespaces, then the derived worker must
* specify `durableObjectStorage` to specify where its instances should be stored. Each
* devived worker receives its own namespace of objects. `durableObjectUniqueKeyModifier`
* must also be specified by derived workers.
*
* This can be useful when you want to run the same Worker in multiple configurations or hooked
* up to different back-ends. Note that all derived workers run in the same isolate as the
* base worker; they differ in the content of the `env` object passed to them, which contains
* the bindings. (When using service workers syntax, the global scope contains the bindings;
* in this case each derived worker runs in its own global scope, though still in the same
* isolate.)
*
*/
get inherit() {
utils.testWhich("inherit", utils.getUint16(0, this), 2, this);
return utils.getText(0, this);
}
get _isInherit() {
return utils.getUint16(0, this) === 2;
}
set inherit(value) {
utils.setUint16(0, 2, this);
utils.setText(0, value, this);
}
get compatibilityDate() {
return utils.getText(1, this);
}
set compatibilityDate(value) {
utils.setText(1, value, this);
}
_adoptCompatibilityFlags(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownCompatibilityFlags() {
return utils.disown(this.compatibilityFlags);
}
/**
* See: https://developers.cloudflare.com/workers/platform/compatibility-dates/
*
* `compatibilityDate` must be specified, unless the Worker inhits from another worker, in which
* case it must not be specified. `compatibilityFlags` can optionally be specified when
* `compatibilityDate` is specified.
*
*/
get compatibilityFlags() {
return utils.getList(2, TextList, this);
}
_hasCompatibilityFlags() {
return !utils.isNull(utils.getPointer(2, this));
}
_initCompatibilityFlags(length) {
return utils.initList(2, TextList, length, this);
}
set compatibilityFlags(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
_adoptBindings(value) {
utils.adopt(value, utils.getPointer(3, this));
}
_disownBindings() {
return utils.disown(this.bindings);
}
/**
* List of bindings, which give the Worker access to external resources and configuration
* settings.
*
* For Workers using ES modules syntax, the bindings are delivered via the `env` object. For
* service workers syntax, each binding shows up as a global variable.
*
*/
get bindings() {
return utils.getList(3, _Worker._Bindings, this);
}
_hasBindings() {
return !utils.isNull(utils.getPointer(3, this));
}
_initBindings(length) {
return utils.initList(3, _Worker._Bindings, length, this);
}
set bindings(value) {
utils.copyFrom(value, utils.getPointer(3, this));
}
_adoptGlobalOutbound(value) {
utils.adopt(value, utils.getPointer(4, this));
}
_disownGlobalOutbound() {
return utils.disown(this.globalOutbound);
}
/**
* Where should the global "fetch" go to? The default is the service called "internet", which
* should usually be configured to talk to the public internet.
*
*/
get globalOutbound() {
return utils.getStruct(
4,
ServiceDesignator,
this,
_Worker._capnp.defaultGlobalOutbound
);
}
_hasGlobalOutbound() {
return !utils.isNull(utils.getPointer(4, this));
}
_initGlobalOutbound() {
return utils.initStructAt(4, ServiceDesignator, this);
}
set globalOutbound(value) {
utils.copyFrom(value, utils.getPointer(4, this));
}
_adoptCacheApiOutbound(value) {
utils.adopt(value, utils.getPointer(7, this));
}
_disownCacheApiOutbound() {
return utils.disown(this.cacheApiOutbound);
}
/**
* Where should cache API (i.e. caches.default and caches.open(...)) requests go?
*
*/
get cacheApiOutbound() {
return utils.getStruct(7, ServiceDesignator, this);
}
_hasCacheApiOutbound() {
return !utils.isNull(utils.getPointer(7, this));
}
_initCacheApiOutbound() {
return utils.initStructAt(7, ServiceDesignator, this);
}
set cacheApiOutbound(value) {
utils.copyFrom(value, utils.getPointer(7, this));
}
_adoptDurableObjectNamespaces(value) {
utils.adopt(value, utils.getPointer(5, this));
}
_disownDurableObjectNamespaces() {
return utils.disown(this.durableObjectNamespaces);
}
/**
* List of durable object namespaces in this Worker.
*
*/
get durableObjectNamespaces() {
return utils.getList(5, _Worker._DurableObjectNamespaces, this);
}
_hasDurableObjectNamespaces() {
return !utils.isNull(utils.getPointer(5, this));
}
_initDurableObjectNamespaces(length) {
return utils.initList(5, _Worker._DurableObjectNamespaces, length, this);
}
set durableObjectNamespaces(value) {
utils.copyFrom(value, utils.getPointer(5, this));
}
/**
* Additional text which is hashed together with `DurableObjectNamespace.uniqueKey`. When using
* worker inheritance, each derived worker must specify a unique modifier to ensure that its
* Durable Object instances have unique IDs from all other workers inheriting the same parent.
*
* DO NOT LOSE this value, otherwise it may be difficult or impossible to recover stored data.
*
*/
get durableObjectUniqueKeyModifier() {
return utils.getText(6, this);
}
set durableObjectUniqueKeyModifier(value) {
utils.setText(6, value, this);
}
/**
* Specifies where this worker's Durable Objects are stored.
*
*/
get durableObjectStorage() {
return utils.getAs(Worker_DurableObjectStorage, this);
}
_initDurableObjectStorage() {
return utils.getAs(Worker_DurableObjectStorage, this);
}
get moduleFallback() {
return utils.getText(9, this);
}
set moduleFallback(value) {
utils.setText(9, value, this);
}
_adoptTails(value) {
utils.adopt(value, utils.getPointer(10, this));
}
_disownTails() {
return utils.disown(this.tails);
}
/**
* List of tail worker services that should receive tail events for this worker.
* See: https://developers.cloudflare.com/workers/observability/logs/tail-workers/
*
*/
get tails() {
return utils.getList(10, _Worker._Tails, this);
}
_hasTails() {
return !utils.isNull(utils.getPointer(10, this));
}
_initTails(length) {
return utils.initList(10, _Worker._Tails, length, this);
}
set tails(value) {
utils.copyFrom(value, utils.getPointer(10, this));
}
_adoptStreamingTails(value) {
utils.adopt(value, utils.getPointer(11, this));
}
_disownStreamingTails() {
return utils.disown(this.streamingTails);
}
/**
* List of streaming tail worker services that should receive tail events for this worker.
* NOTE: This will be deleted in a future refactor, do not depend on this.
*
*/
get streamingTails() {
return utils.getList(11, _Worker._StreamingTails, this);
}
_hasStreamingTails() {
return !utils.isNull(utils.getPointer(11, this));
}
_initStreamingTails(length) {
return utils.initList(11, _Worker._StreamingTails, length, this);
}
set streamingTails(value) {
utils.copyFrom(value, utils.getPointer(11, this));
}
get containerEngine() {
return utils.getAs(Worker_ContainerEngine, this);
}
_initContainerEngine() {
return utils.getAs(Worker_ContainerEngine, this);
}
toString() {
return "Worker_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
var Worker = _Worker;
__publicField(Worker, "MODULES", Worker_Which.MODULES);
__publicField(Worker, "SERVICE_WORKER_SCRIPT", Worker_Which.SERVICE_WORKER_SCRIPT);
__publicField(Worker, "INHERIT", Worker_Which.INHERIT);
__publicField(Worker, "Module", Worker_Module);
__publicField(Worker, "Binding", Worker_Binding);
__publicField(Worker, "DurableObjectNamespace", Worker_DurableObjectNamespace);
__publicField(Worker, "DockerConfiguration", Worker_DockerConfiguration);
__publicField(Worker, "_capnp", {
displayName: "Worker",
id: "acfa77e88fd97d1c",
size: new ObjectSize(8, 13),
defaultGlobalOutbound: readRawPointer(
new Uint8Array([
16,
7,
80,
1,
3,
0,
0,
17,
9,
74,
0,
1,
255,
105,
110,
116,
101,
114,
110,
101,
116,
0,
0,
0
]).buffer
)
});
__publicField(Worker, "_Modules");
__publicField(Worker, "_Bindings");
__publicField(Worker, "_DurableObjectNamespaces");
__publicField(Worker, "_Tails");
__publicField(Worker, "_StreamingTails");
var ExternalServer_Https = class extends Struct {
_adoptOptions(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownOptions() {
return utils.disown(this.options);
}
get options() {
return utils.getStruct(1, HttpOptions, this);
}
_hasOptions() {
return !utils.isNull(utils.getPointer(1, this));
}
_initOptions() {
return utils.initStructAt(1, HttpOptions, this);
}
set options(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptTlsOptions(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownTlsOptions() {
return utils.disown(this.tlsOptions);
}
get tlsOptions() {
return utils.getStruct(2, TlsOptions, this);
}
_hasTlsOptions() {
return !utils.isNull(utils.getPointer(2, this));
}
_initTlsOptions() {
return utils.initStructAt(2, TlsOptions, this);
}
set tlsOptions(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
/**
* If present, expect the host to present a certificate authenticating it as this hostname.
* If `certificateHost` is not provided, then the certificate is checked against `address`.
*
*/
get certificateHost() {
return utils.getText(3, this);
}
set certificateHost(value) {
utils.setText(3, value, this);
}
toString() {
return "ExternalServer_Https_" + super.toString();
}
};
__publicField(ExternalServer_Https, "_capnp", {
displayName: "https",
id: "ac37e02afd3dc6db",
size: new ObjectSize(8, 4)
});
var ExternalServer_Tcp = class extends Struct {
_adoptTlsOptions(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownTlsOptions() {
return utils.disown(this.tlsOptions);
}
get tlsOptions() {
return utils.getStruct(1, TlsOptions, this);
}
_hasTlsOptions() {
return !utils.isNull(utils.getPointer(1, this));
}
_initTlsOptions() {
return utils.initStructAt(1, TlsOptions, this);
}
set tlsOptions(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
get certificateHost() {
return utils.getText(2, this);
}
set certificateHost(value) {
utils.setText(2, value, this);
}
toString() {
return "ExternalServer_Tcp_" + super.toString();
}
};
__publicField(ExternalServer_Tcp, "_capnp", {
displayName: "tcp",
id: "d941637df0fb39f1",
size: new ObjectSize(8, 4)
});
var ExternalServer_Which = {
/**
* Address/port of the server. Optional; if not specified, then you will be required to specify
* the address on the command line with with `--external-addr <name>=<addr>`.
*
* Examples:
* - "1.2.3.4": Connect to the given IPv4 address on the protocol's default port.
* - "1.2.3.4:80": Connect to the given IPv4 address and port.
* - "1234:5678::abcd": Connect to the given IPv6 address on the protocol's default port.
* - "[1234:5678::abcd]:80": Connect to the given IPv6 address and port.
* - "unix:/path/to/socket": Connect to the given Unix Domain socket by path.
* - "unix-abstract:name": On Linux, connect to the given "abstract" Unix socket name.
* - "example.com:80": Perform a DNS lookup to determine the address, and then connect to it.
*
* (These are the formats supported by KJ's parseAddress().)
*
*/
HTTP: 0,
/**
* Talk to the server over unencrypted HTTP.
*
*/
HTTPS: 1,
/**
* Talk to the server over encrypted HTTPS.
*
*/
TCP: 2
};
var ExternalServer = class extends Struct {
/**
* Address/port of the server. Optional; if not specified, then you will be required to specify
* the address on the command line with with `--external-addr <name>=<addr>`.
*
* Examples:
* - "1.2.3.4": Connect to the given IPv4 address on the protocol's default port.
* - "1.2.3.4:80": Connect to the given IPv4 address and port.
* - "1234:5678::abcd": Connect to the given IPv6 address on the protocol's default port.
* - "[1234:5678::abcd]:80": Connect to the given IPv6 address and port.
* - "unix:/path/to/socket": Connect to the given Unix Domain socket by path.
* - "unix-abstract:name": On Linux, connect to the given "abstract" Unix socket name.
* - "example.com:80": Perform a DNS lookup to determine the address, and then connect to it.
*
* (These are the formats supported by KJ's parseAddress().)
*
*/
get address() {
return utils.getText(0, this);
}
set address(value) {
utils.setText(0, value, this);
}
_adoptHttp(value) {
utils.setUint16(0, 0, this);
utils.adopt(value, utils.getPointer(1, this));
}
_disownHttp() {
return utils.disown(this.http);
}
/**
* Talk to the server over unencrypted HTTP.
*
*/
get http() {
utils.testWhich("http", utils.getUint16(0, this), 0, this);
return utils.getStruct(1, HttpOptions, this);
}
_hasHttp() {
return !utils.isNull(utils.getPointer(1, this));
}
_initHttp() {
utils.setUint16(0, 0, this);
return utils.initStructAt(1, HttpOptions, this);
}
get _isHttp() {
return utils.getUint16(0, this) === 0;
}
set http(value) {
utils.setUint16(0, 0, this);
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* Talk to the server over encrypted HTTPS.
*
*/
get https() {
utils.testWhich("https", utils.getUint16(0, this), 1, this);
return utils.getAs(ExternalServer_Https, this);
}
_initHttps() {
utils.setUint16(0, 1, this);
return utils.getAs(ExternalServer_Https, this);
}
get _isHttps() {
return utils.getUint16(0, this) === 1;
}
set https(_) {
utils.setUint16(0, 1, this);
}
/**
* Connect to the server over raw TCP. Bindings to this service will only support the
* `connect()` method; `fetch()` will throw an exception.
*
*/
get tcp() {
utils.testWhich("tcp", utils.getUint16(0, this), 2, this);
return utils.getAs(ExternalServer_Tcp, this);
}
_initTcp() {
utils.setUint16(0, 2, this);
return utils.getAs(ExternalServer_Tcp, this);
}
get _isTcp() {
return utils.getUint16(0, this) === 2;
}
set tcp(_) {
utils.setUint16(0, 2, this);
}
toString() {
return "ExternalServer_" + super.toString();
}
which() {
return utils.getUint16(0, this);
}
};
__publicField(ExternalServer, "HTTP", ExternalServer_Which.HTTP);
__publicField(ExternalServer, "HTTPS", ExternalServer_Which.HTTPS);
__publicField(ExternalServer, "TCP", ExternalServer_Which.TCP);
__publicField(ExternalServer, "_capnp", {
displayName: "ExternalServer",
id: "ff209f9aa352f5a4",
size: new ObjectSize(8, 4)
});
var _Network = class extends Struct {
_adoptAllow(value) {
utils.adopt(value, utils.getPointer(0, this));
}
_disownAllow() {
return utils.disown(this.allow);
}
get allow() {
return utils.getList(0, TextList, this, _Network._capnp.defaultAllow);
}
_hasAllow() {
return !utils.isNull(utils.getPointer(0, this));
}
_initAllow(length) {
return utils.initList(0, TextList, length, this);
}
set allow(value) {
utils.copyFrom(value, utils.getPointer(0, this));
}
_adoptDeny(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownDeny() {
return utils.disown(this.deny);
}
/**
* Specifies which network addresses the Worker will be allowed to connect to, e.g. using fetch().
* The default allows publicly-routable IP addresses only, in order to prevent SSRF attacks.
*
* The allow and deny lists specify network blocks in CIDR notation (IPv4 and IPv6), such as
* "192.0.2.0/24" or "2001:db8::/32". Traffic will be permitted as long as the address
* matches at least one entry in the allow list and none in the deny list.
*
* In addition to IPv4 and IPv6 CIDR notation, several special strings may be specified:
* - "private": Matches network addresses that are reserved by standards for private networks,
* such as "10.0.0.0/8" or "192.168.0.0/16". This is a superset of "local".
* - "public": Opposite of "private".
* - "local": Matches network addresses that are defined by standards to only be accessible from
* the local machine, such as "127.0.0.0/8" or Unix domain addresses.
* - "network": Opposite of "local".
* - "unix": Matches all Unix domain socket addresses. (In the future, we may support specifying a
* glob to narrow this to specific paths.)
* - "unix-abstract": Matches Linux's "abstract unix domain" addresses. (In the future, we may
* support specifying a glob.)
*
* In the case that the Worker specifies a DNS hostname rather than a raw address, these rules are
* used to filter the addresses returned by the lookup. If none of the returned addresses turn
* out to be permitted, then the system will behave as if the DNS entry did not exist.
*
* (The above is exactly the format supported by kj::Network::restrictPeers().)
*
*/
get deny() {
return utils.getList(1, TextList, this);
}
_hasDeny() {
return !utils.isNull(utils.getPointer(1, this));
}
_initDeny(length) {
return utils.initList(1, TextList, length, this);
}
set deny(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
_adoptTlsOptions(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownTlsOptions() {
return utils.disown(this.tlsOptions);
}
get tlsOptions() {
return utils.getStruct(2, TlsOptions, this);
}
_hasTlsOptions() {
return !utils.isNull(utils.getPointer(2, this));
}
_initTlsOptions() {
return utils.initStructAt(2, TlsOptions, this);
}
set tlsOptions(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
toString() {
return "Network_" + super.toString();
}
};
var Network = _Network;
__publicField(Network, "_capnp", {
displayName: "Network",
id: "fa42244f950c9b9c",
size: new ObjectSize(0, 3),
defaultAllow: readRawPointer(
new Uint8Array([
16,
3,
17,
1,
14,
17,
1,
58,
63,
112,
117,
98,
108,
105,
99
]).buffer
)
});
var _DiskDirectory = class extends Struct {
/**
* The filesystem path of the directory. If not specified, then it must be specified on the
* command line with `--directory-path <service-name>=<path>`.
*
* Relative paths are interpreted relative to the current directory where the server is executed,
* NOT relative to the config file. So, you should usually use absolute paths in the config file.
*
*/
get path() {
return utils.getText(0, this);
}
set path(value) {
utils.setText(0, value, this);
}
/**
* Whether to support PUT requests for writing. A PUT will write to a temporary file which
* is atomically moved into place upon successful completion of the upload. Parent directories are
* created as needed.
*
*/
get writable() {
return utils.getBit(0, this, _DiskDirectory._capnp.defaultWritable);
}
set writable(value) {
utils.setBit(0, value, this, _DiskDirectory._capnp.defaultWritable);
}
/**
* Whether to allow access to files and directories whose name starts with '.'. These are made
* inaccessible by default since they very often store metadata that is not meant to be served,
* e.g. a git repository or an `.htaccess` file.
*
* Note that the special links "." and ".." will never be accessible regardless of this setting.
*
*/
get allowDotfiles() {
return utils.getBit(1, this, _DiskDirectory._capnp.defaultAllowDotfiles);
}
set allowDotfiles(value) {
utils.setBit(1, value, this, _DiskDirectory._capnp.defaultAllowDotfiles);
}
toString() {
return "DiskDirectory_" + super.toString();
}
};
var DiskDirectory = _DiskDirectory;
__publicField(DiskDirectory, "_capnp", {
displayName: "DiskDirectory",
id: "9048ab22835f51c3",
size: new ObjectSize(8, 1),
defaultWritable: getBitMask(false, 0),
defaultAllowDotfiles: getBitMask(false, 1)
});
var HttpOptions_Style = {
/**
* Normal HTTP. The request line contains only the path, and the separate `Host` header
* specifies the hostname.
*
*/
HOST: 0,
/**
* HTTP proxy protocol. The request line contains a full URL instead of a path. No `Host`
* header is required. This is the protocol used by HTTP forward proxies. This allows you to
* implement such a proxy as a Worker.
*
*/
PROXY: 1
};
var HttpOptions_Header = class extends Struct {
/**
* Case-insensitive.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
/**
* If null, the header will be removed.
*
*/
get value() {
return utils.getText(1, this);
}
set value(value) {
utils.setText(1, value, this);
}
toString() {
return "HttpOptions_Header_" + super.toString();
}
};
__publicField(HttpOptions_Header, "_capnp", {
displayName: "Header",
id: "dc0394b5a6f3417e",
size: new ObjectSize(0, 2)
});
var _HttpOptions = class extends Struct {
get style() {
return utils.getUint16(
0,
this,
_HttpOptions._capnp.defaultStyle
);
}
set style(value) {
utils.setUint16(0, value, this, _HttpOptions._capnp.defaultStyle);
}
/**
* If specified, then when the given header is present on a request, it specifies the protocol
* ("http" or "https") that was used by the original client. The request URL reported to the
* Worker will reflect this protocol. Otherwise, the URL will reflect the actual physical protocol
* used by the server in receiving the request.
*
* This option is useful when this server sits behind a reverse proxy that performs TLS
* termination. Typically such proxies forward the original protocol in a header named something
* like "X-Forwarded-Proto".
*
* This setting is ignored when `style` is `proxy`.
*
*/
get forwardedProtoHeader() {
return utils.getText(0, this);
}
set forwardedProtoHeader(value) {
utils.setText(0, value, this);
}
/**
* If set, then the `request.cf` object will be encoded (as JSON) into / parsed from the header
* with this name. Otherwise, it will be discarded on send / `undefined` on receipt.
*
*/
get cfBlobHeader() {
return utils.getText(1, this);
}
set cfBlobHeader(value) {
utils.setText(1, value, this);
}
_adoptInjectRequestHeaders(value) {
utils.adopt(value, utils.getPointer(2, this));
}
_disownInjectRequestHeaders() {
return utils.disown(this.injectRequestHeaders);
}
/**
* List of headers which will be automatically injected into all requests. This can be used
* e.g. to add an authorization token to all requests when using `ExternalServer`. It can also
* apply to incoming requests received on a `Socket` to modify the headers that will be delivered
* to the app. Any existing header with the same name is removed.
*
*/
get injectRequestHeaders() {
return utils.getList(2, _HttpOptions._InjectRequestHeaders, this);
}
_hasInjectRequestHeaders() {
return !utils.isNull(utils.getPointer(2, this));
}
_initInjectRequestHeaders(length) {
return utils.initList(2, _HttpOptions._InjectRequestHeaders, length, this);
}
set injectRequestHeaders(value) {
utils.copyFrom(value, utils.getPointer(2, this));
}
_adoptInjectResponseHeaders(value) {
utils.adopt(value, utils.getPointer(3, this));
}
_disownInjectResponseHeaders() {
return utils.disown(this.injectResponseHeaders);
}
/**
* Same as `injectRequestHeaders` but for responses.
*
*/
get injectResponseHeaders() {
return utils.getList(3, _HttpOptions._InjectResponseHeaders, this);
}
_hasInjectResponseHeaders() {
return !utils.isNull(utils.getPointer(3, this));
}
_initInjectResponseHeaders(length) {
return utils.initList(
3,
_HttpOptions._InjectResponseHeaders,
length,
this
);
}
set injectResponseHeaders(value) {
utils.copyFrom(value, utils.getPointer(3, this));
}
/**
* A CONNECT request for this host+port will be treated as a request to form a Cap'n Proto RPC
* connection. The server will expose a WorkerdBootstrap as the bootstrap interface, allowing
* events to be delivered to the target worker via capnp. Clients will use capnp for non-HTTP
* event types (especially JSRPC).
*
*/
get capnpConnectHost() {
return utils.getText(4, this);
}
set capnpConnectHost(value) {
utils.setText(4, value, this);
}
toString() {
return "HttpOptions_" + super.toString();
}
};
var HttpOptions = _HttpOptions;
__publicField(HttpOptions, "Style", HttpOptions_Style);
__publicField(HttpOptions, "Header", HttpOptions_Header);
__publicField(HttpOptions, "_capnp", {
displayName: "HttpOptions",
id: "aa8dc6885da78f19",
size: new ObjectSize(8, 5),
defaultStyle: getUint16Mask(0)
});
__publicField(HttpOptions, "_InjectRequestHeaders");
__publicField(HttpOptions, "_InjectResponseHeaders");
var TlsOptions_Keypair = class extends Struct {
/**
* Private key in PEM format. Supports PKCS8 keys as well as "traditional format" RSA and DSA
* keys.
*
* Remember that you can use Cap'n Proto's `embed` syntax to reference an external file.
*
*/
get privateKey() {
return utils.getText(0, this);
}
set privateKey(value) {
utils.setText(0, value, this);
}
/**
* Certificate chain in PEM format. A chain can be constructed by concatenating multiple
* PEM-encoded certificates, starting with the leaf certificate.
*
*/
get certificateChain() {
return utils.getText(1, this);
}
set certificateChain(value) {
utils.setText(1, value, this);
}
toString() {
return "TlsOptions_Keypair_" + super.toString();
}
};
__publicField(TlsOptions_Keypair, "_capnp", {
displayName: "Keypair",
id: "f546bf2d5d8bd13e",
size: new ObjectSize(0, 2)
});
var TlsOptions_Version = {
/**
* A good default chosen by the code maintainers. May change over time.
*
*/
GOOD_DEFAULT: 0,
SSL3: 1,
TLS1DOT0: 2,
TLS1DOT1: 3,
TLS1DOT2: 4,
TLS1DOT3: 5
};
var _TlsOptions = class extends Struct {
_adoptKeypair(value) {
utils.adopt(value, utils.getPointer(0, this));
}
_disownKeypair() {
return utils.disown(this.keypair);
}
/**
* The default private key and certificate to use. Optional when acting as a client.
*
*/
get keypair() {
return utils.getStruct(0, TlsOptions_Keypair, this);
}
_hasKeypair() {
return !utils.isNull(utils.getPointer(0, this));
}
_initKeypair() {
return utils.initStructAt(0, TlsOptions_Keypair, this);
}
set keypair(value) {
utils.copyFrom(value, utils.getPointer(0, this));
}
/**
* If true, then when acting as a server, incoming connections will be rejected unless they bear
* a certificate signed by one of the trusted CAs.
*
* Typically, when using this, you'd set `trustBrowserCas = false` and list a specific private CA
* in `trustedCertificates`.
*
*/
get requireClientCerts() {
return utils.getBit(0, this, _TlsOptions._capnp.defaultRequireClientCerts);
}
set requireClientCerts(value) {
utils.setBit(0, value, this, _TlsOptions._capnp.defaultRequireClientCerts);
}
/**
* If true, trust certificates which are signed by one of the CAs that browsers normally trust.
* You should typically set this true when talking to the public internet, but you may want to
* set it false when talking to servers on your internal network.
*
*/
get trustBrowserCas() {
return utils.getBit(1, this, _TlsOptions._capnp.defaultTrustBrowserCas);
}
set trustBrowserCas(value) {
utils.setBit(1, value, this, _TlsOptions._capnp.defaultTrustBrowserCas);
}
_adoptTrustedCertificates(value) {
utils.adopt(value, utils.getPointer(1, this));
}
_disownTrustedCertificates() {
return utils.disown(this.trustedCertificates);
}
/**
* Additional CA certificates to trust, in PEM format. Remember that you can use Cap'n Proto's
* `embed` syntax to read the certificates from other files.
*
*/
get trustedCertificates() {
return utils.getList(1, TextList, this);
}
_hasTrustedCertificates() {
return !utils.isNull(utils.getPointer(1, this));
}
_initTrustedCertificates(length) {
return utils.initList(1, TextList, length, this);
}
set trustedCertificates(value) {
utils.copyFrom(value, utils.getPointer(1, this));
}
/**
* Minimum TLS version that will be allowed. Generally you should not override this unless you
* have unusual backwards-compatibility needs.
*
*/
get minVersion() {
return utils.getUint16(
2,
this,
_TlsOptions._capnp.defaultMinVersion
);
}
set minVersion(value) {
utils.setUint16(2, value, this, _TlsOptions._capnp.defaultMinVersion);
}
/**
* OpenSSL cipher list string. The default is a curated list designed to be compatible with
* almost all software in current use (specifically, based on Mozilla's "intermediate"
* recommendations). The defaults will change in future versions of this software to account
* for the latest cryptanalysis.
*
* Generally you should only specify your own `cipherList` if:
* - You have extreme backwards-compatibility needs and wish to enable obsolete and/or broken
* algorithms.
* - You need quickly to disable an algorithm recently discovered to be broken.
*
*/
get cipherList() {
return utils.getText(2, this);
}
set cipherList(value) {
utils.setText(2, value, this);
}
toString() {
return "TlsOptions_" + super.toString();
}
};
var TlsOptions = _TlsOptions;
__publicField(TlsOptions, "Keypair", TlsOptions_Keypair);
__publicField(TlsOptions, "Version", TlsOptions_Version);
__publicField(TlsOptions, "_capnp", {
displayName: "TlsOptions",
id: "aabb3c3778ac4311",
size: new ObjectSize(8, 3),
defaultRequireClientCerts: getBitMask(false, 0),
defaultTrustBrowserCas: getBitMask(false, 1),
defaultMinVersion: getUint16Mask(0)
});
var _Extension_Module = class extends Struct {
/**
* Full js module name.
*
*/
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
/**
* Internal modules can be imported by other extension modules only and not the user code.
*
*/
get internal() {
return utils.getBit(0, this, _Extension_Module._capnp.defaultInternal);
}
set internal(value) {
utils.setBit(0, value, this, _Extension_Module._capnp.defaultInternal);
}
/**
* Raw source code of ES module.
*
*/
get esModule() {
return utils.getText(1, this);
}
set esModule(value) {
utils.setText(1, value, this);
}
toString() {
return "Extension_Module_" + super.toString();
}
};
var Extension_Module = _Extension_Module;
__publicField(Extension_Module, "_capnp", {
displayName: "Module",
id: "d5d16e76fdedc37d",
size: new ObjectSize(8, 2),
defaultInternal: getBitMask(false, 0)
});
var _Extension = class extends Struct {
_adoptModules(value) {
utils.adopt(value, utils.getPointer(0, this));
}
_disownModules() {
return utils.disown(this.modules);
}
/**
* List of javascript modules provided by the extension.
* These modules can either be imported directly as user-level api (if not marked internal)
* or used to define more complicated workerd constructs such as wrapped bindings and events.
*
*/
get modules() {
return utils.getList(0, _Extension._Modules, this);
}
_hasModules() {
return !utils.isNull(utils.getPointer(0, this));
}
_initModules(length) {
return utils.initList(0, _Extension._Modules, length, this);
}
set modules(value) {
utils.copyFrom(value, utils.getPointer(0, this));
}
toString() {
return "Extension_" + super.toString();
}
};
var Extension = _Extension;
__publicField(Extension, "Module", Extension_Module);
__publicField(Extension, "_capnp", {
displayName: "Extension",
id: "e390128a861973a6",
size: new ObjectSize(0, 1)
});
__publicField(Extension, "_Modules");
var FallbackServiceRequest_Attribute = class extends Struct {
get name() {
return utils.getText(0, this);
}
set name(value) {
utils.setText(0, value, this);
}
get value() {
return utils.getText(1, this);
}
set value(value) {
utils.setText(1, value, this);
}
toString() {
return "FallbackServiceRequest_Attribute_" + super.toString();
}
};
__publicField(FallbackServiceRequest_Attribute, "_capnp", {
displayName: "Attribute",
id: "ecfe563249c01f75",
size: new ObjectSize(0, 2)
});
var _FallbackServiceRequest = class extends Struct {
get type() {
return utils.getText(0, this);
}
set type(value) {
utils.setText(0, value, this);
}
get specifier() {
return utils.getText(1, this);
}
set specifier(value) {
utils.setText(1, value, this);
}
get rawSpecifier() {
return utils.getText(2, this);
}
set rawSpecifier(value) {
utils.setText(2, value, this);
}
get referrer() {
return utils.getText(3, this);
}
set referrer(value) {
utils.setText(3, value, this);
}
_adoptAttributes(value) {
utils.adopt(value, utils.getPointer(4, this));
}
_disownAttributes() {
return utils.disown(this.attributes);
}
get attributes() {
return utils.getList(4, _FallbackServiceRequest._Attributes, this);
}
_hasAttributes() {
return !utils.isNull(utils.getPointer(4, this));
}
_initAttributes(length) {
return utils.initList(
4,
_FallbackServiceRequest._Attributes,
length,
this
);
}
set attributes(value) {
utils.copyFrom(value, utils.getPointer(4, this));
}
toString() {
return "FallbackServiceRequest_" + super.toString();
}
};
var FallbackServiceRequest = _FallbackServiceRequest;
__publicField(FallbackServiceRequest, "Attribute", FallbackServiceRequest_Attribute);
__publicField(FallbackServiceRequest, "_capnp", {
displayName: "FallbackServiceRequest",
id: "daf79e36b3f32800",
size: new ObjectSize(0, 5)
});
__publicField(FallbackServiceRequest, "_Attributes");
Config._Services = CompositeList(Service);
Config._Sockets = CompositeList(Socket);
Config._Extensions = CompositeList(Extension);
Worker_Binding_WrappedBinding._InnerBindings = CompositeList(Worker_Binding);
Worker._Modules = CompositeList(Worker_Module);
Worker._Bindings = CompositeList(Worker_Binding);
Worker._DurableObjectNamespaces = CompositeList(
Worker_DurableObjectNamespace
);
Worker._Tails = CompositeList(ServiceDesignator);
Worker._StreamingTails = CompositeList(ServiceDesignator);
HttpOptions._InjectRequestHeaders = CompositeList(HttpOptions_Header);
HttpOptions._InjectResponseHeaders = CompositeList(HttpOptions_Header);
Extension._Modules = CompositeList(Extension_Module);
FallbackServiceRequest._Attributes = CompositeList(
FallbackServiceRequest_Attribute
);
// src/runtime/config/workerd.ts
var kVoid = Symbol("kVoid");
// src/runtime/config/index.ts
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);
const safeKey = key === "constructor" ? `$${key}` : 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[safeKey] = void 0;
} else if (value !== void 0) {
anyStruct[safeKey] = value;
}
}
}
function serializeConfig(config) {
const message = new Message();
const struct = message.initRoot(Config);
encodeCapnpStruct(config, struct);
return Buffer.from(message.toArrayBuffer());
}
// src/runtime/index.ts
var ControlMessageSchema = import_zod5.z.discriminatedUnion("event", [
import_zod5.z.object({
event: import_zod5.z.literal("listen"),
socket: import_zod5.z.string(),
port: import_zod5.z.number()
}),
import_zod5.z.object({
event: import_zod5.z.literal("listen-inspector"),
port: import_zod5.z.number()
})
]);
var kInspectorSocket = Symbol("kInspectorSocket");
async function waitForPorts(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 });
const requiredSockets = Array.from(options.requiredSockets);
const socketPorts = /* @__PURE__ */ new Map();
try {
for await (const line of lines) {
const message = ControlMessageSchema.safeParse(JSON.parse(line));
if (!message.success)
continue;
const data = message.data;
const socket = data.event === "listen-inspector" ? kInspectorSocket : data.socket;
const index = requiredSockets.indexOf(socket);
if (index === -1)
continue;
socketPorts.set(socket, data.port);
requiredSockets.splice(index, 1);
if (requiredSockets.length === 0)
return socketPorts;
}
} finally {
options?.signal?.removeEventListener("abort", abortListener);
}
}
function waitForExit(process3) {
return new Promise((resolve2) => {
process3.once("exit", () => resolve2());
});
}
function pipeOutput(stdout2, stderr2) {
import_readline.default.createInterface(stdout2).on("line", (data) => console.log(data));
import_readline.default.createInterface(stderr2).on("line", (data) => console.error(red2(data)));
}
function getRuntimeCommand() {
return process.env.MINIFLARE_WORKERD_PATH ?? import_workerd2.default;
}
function getRuntimeArgs(options) {
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}=${options.entryAddress}`,
`--external-addr=${SERVICE_LOOPBACK}=${options.loopbackAddress}`,
// Configure extra pipe for receiving control messages (e.g. when ready)
"--control-fd=3",
// Read config from stdin
"-"
];
if (options.inspectorAddress !== void 0) {
args.push(`--inspector-addr=${options.inspectorAddress}`);
}
if (options.verbose) {
args.push("--verbose");
}
return args;
}
var Runtime = class {
#process;
#processExitPromise;
async updateConfig(configBuffer, options) {
await this.dispose();
const command = getRuntimeCommand();
const args = getRuntimeArgs(options);
const FORCE_COLOR2 = $.enabled ? "1" : "0";
const runtimeProcess = import_child_process.default.spawn(command, args, {
stdio: ["pipe", "pipe", "pipe", "pipe"],
env: { ...process.env, FORCE_COLOR: FORCE_COLOR2 }
});
this.#process = runtimeProcess;
this.#processExitPromise = waitForExit(runtimeProcess);
const handleRuntimeStdio = options.handleRuntimeStdio ?? pipeOutput;
handleRuntimeStdio(runtimeProcess.stdout, runtimeProcess.stderr);
const controlPipe = runtimeProcess.stdio[3];
(0, import_assert4.default)(controlPipe instanceof import_stream.Readable);
runtimeProcess.stdin.write(configBuffer);
runtimeProcess.stdin.end();
await (0, import_events2.once)(runtimeProcess.stdin, "finish");
return waitForPorts(controlPipe, options);
}
dispose() {
this.#process?.kill("SIGKILL");
return this.#processExitPromise;
}
};
// src/plugins/assets/constants.ts
var ASSETS_PLUGIN_NAME = "assets";
var ASSETS_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:assets-service`;
var ROUTER_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:router`;
var RPC_PROXY_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:rpc-proxy`;
var ASSETS_KV_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:kv`;
// src/plugins/cache/index.ts
var import_promises4 = __toESM(require("fs/promises"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache.worker.ts
var import_fs9 = __toESM(require("fs"));
var import_path12 = __toESM(require("path"));
var import_url9 = __toESM(require("url"));
var contents9;
function cache_worker_default() {
if (contents9 !== void 0)
return contents9;
const filePath = import_path12.default.join(__dirname, "workers", "cache/cache.worker.js");
contents9 = import_fs9.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath);
return contents9;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry.worker.ts
var import_fs10 = __toESM(require("fs"));
var import_path13 = __toESM(require("path"));
var import_url10 = __toESM(require("url"));
var contents10;
function cache_entry_worker_default() {
if (contents10 !== void 0)
return contents10;
const filePath = import_path13.default.join(__dirname, "workers", "cache/cache-entry.worker.js");
contents10 = import_fs10.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url10.default.pathToFileURL(filePath);
return contents10;
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts
var import_fs11 = __toESM(require("fs"));
var import_path14 = __toESM(require("path"));
var import_url11 = __toESM(require("url"));
var contents11;
function cache_entry_noop_worker_default() {
if (contents11 !== void 0)
return contents11;
const filePath = import_path14.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js");
contents11 = import_fs11.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url11.default.pathToFileURL(filePath);
return contents11;
}
// src/plugins/cache/index.ts
var import_zod7 = require("zod");
// src/plugins/shared/index.ts
var import_crypto = __toESM(require("crypto"));
var import_fs13 = require("fs");
var import_promises3 = __toESM(require("fs/promises"));
var import_path16 = __toESM(require("path"));
var import_url14 = require("url");
var import_zod6 = require("zod");
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/object-entry.worker.ts
var import_fs12 = __toESM(require("fs"));
var import_path15 = __toESM(require("path"));
var import_url12 = __toESM(require("url"));
var contents12;
function object_entry_worker_default() {
if (contents12 !== void 0)
return contents12;
const filePath = import_path15.default.join(__dirname, "workers", "shared/object-entry.worker.js");
contents12 = import_fs12.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url12.default.pathToFileURL(filePath);
return contents12;
}
// src/plugins/shared/constants.ts
var SOCKET_ENTRY = "entry";
var SOCKET_ENTRY_LOCAL = "entry:local";
var SOCKET_DIRECT_PREFIX = "direct";
function getDirectSocketName(workerIndex, entrypoint) {
return `${SOCKET_DIRECT_PREFIX}:${workerIndex}:${entrypoint}`;
}
var SERVICE_LOOPBACK = "loopback";
var HOST_CAPNP_CONNECT = "miniflare-unsafe-internal-capnp-connect";
var WORKER_BINDING_SERVICE_LOOPBACK = {
name: CoreBindings.SERVICE_LOOPBACK,
service: { name: SERVICE_LOOPBACK }
};
var WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS = {
name: SharedBindings.MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS,
json: "true"
};
var WORKER_BINDING_ENABLE_STICKY_BLOBS = {
name: SharedBindings.MAYBE_JSON_ENABLE_STICKY_BLOBS,
json: "true"
};
var enableControlEndpoints = false;
function getMiniflareObjectBindings(unsafeStickyBlobs) {
const result = [];
if (enableControlEndpoints) {
result.push(WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS);
}
if (unsafeStickyBlobs) {
result.push(WORKER_BINDING_ENABLE_STICKY_BLOBS);
}
return result;
}
function _enableControlEndpoints() {
enableControlEndpoints = true;
}
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
}
]
};
}
var kUnsafeEphemeralUniqueKey = Symbol.for(
"miniflare.kUnsafeEphemeralUniqueKey"
);
// src/plugins/shared/routing.ts
var import_url13 = require("url");
var RouterError = class extends MiniflareError {
};
function routeSpecificity(url21) {
const hostParts = url21.host.split(".");
let hostScore = hostParts.length;
if (hostParts[0] === "*")
hostScore -= 2;
const pathParts = url21.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 url21 = new import_url13.URL(urlInput);
const specificity = routeSpecificity(url21);
const protocol = hasProtocol ? url21.protocol : void 0;
const internationalisedAllowHostnamePrefix = url21.hostname.startsWith("xn--*");
const allowHostnamePrefix = url21.hostname.startsWith("*") || internationalisedAllowHostnamePrefix;
const anyHostname = url21.hostname === "*";
if (allowHostnamePrefix && !anyHostname) {
let hostname = url21.hostname;
if (internationalisedAllowHostnamePrefix) {
hostname = (0, import_url13.domainToUnicode)(hostname);
}
url21.hostname = hostname.substring(1);
}
const allowPathSuffix = url21.pathname.endsWith("*");
if (allowPathSuffix) {
url21.pathname = url21.pathname.substring(0, url21.pathname.length - 1);
}
if (url21.search) {
throw new RouterError(
"ERR_QUERY_STRING",
`Route "${route}" for "${target}" contains a query string. This is not allowed.`
);
}
if (url21.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 ? "" : url21.hostname,
path: url21.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;
}
// src/plugins/shared/index.ts
var DEFAULT_PERSIST_ROOT = ".mf";
var PersistenceSchema = import_zod6.z.union([import_zod6.z.boolean(), import_zod6.z.string().url(), PathSchema]).optional();
var ProxyNodeBinding = class {
constructor(proxyOverrideHandler) {
this.proxyOverrideHandler = proxyOverrideHandler;
}
};
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(url21) {
if (typeof url21 !== "string" || import_path16.default.isAbsolute(url21))
return;
try {
return new URL(url21);
} catch {
}
}
function getPersistPath(pluginName, tmpPath, persist) {
const memoryishPath = import_path16.default.join(tmpPath, pluginName);
if (persist === void 0 || persist === false) {
return memoryishPath;
}
const url21 = maybeParseURL(persist);
if (url21 !== void 0) {
if (url21.protocol === "memory:") {
return memoryishPath;
} else if (url21.protocol === "file:") {
return (0, import_url14.fileURLToPath)(url21);
}
throw new MiniflareCoreError(
"ERR_PERSIST_UNSUPPORTED",
`Unsupported "${url21.protocol}" persistence protocol for storage: ${url21.href}`
);
}
return persist === true ? import_path16.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_path16.default.join(persistPath, sanitisedNamespace);
const previousPath = import_path16.default.join(previousDir, "db.sqlite");
const previousWalPath = import_path16.default.join(previousDir, "db.sqlite-wal");
if (!(0, import_fs13.existsSync)(previousPath))
return;
const id = durableObjectNamespaceIdFromName(uniqueKey, namespace);
const newDir = import_path16.default.join(persistPath, uniqueKey);
const newPath = import_path16.default.join(newDir, `${id}.sqlite`);
const newWalPath = import_path16.default.join(newDir, `${id}.sqlite-wal`);
if ((0, import_fs13.existsSync)(newPath)) {
log.debug(
`Not migrating ${previousPath} to ${newPath} as it already exists`
);
return;
}
log.debug(`Migrating ${previousPath} to ${newPath}...`);
await import_promises3.default.mkdir(newDir, { recursive: true });
try {
await import_promises3.default.copyFile(previousPath, newPath);
if ((0, import_fs13.existsSync)(previousWalPath)) {
await import_promises3.default.copyFile(previousWalPath, newWalPath);
}
await import_promises3.default.unlink(previousPath);
await import_promises3.default.unlink(previousWalPath);
} catch (e) {
log.warn(`Error migrating ${previousPath} to ${newPath}: ${e}`);
}
}
// src/plugins/cache/index.ts
var CacheOptionsSchema = import_zod7.z.object({
cache: import_zod7.z.boolean().optional(),
cacheWarnUsage: import_zod7.z.boolean().optional()
});
var CacheSharedOptionsSchema = import_zod7.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,
unsafeStickyBlobs
}) {
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 services = [
{ name: getCacheServiceName(workerIndex), worker: entryWorker }
];
if (cache) {
const uniqueKey = `miniflare-${CACHE_OBJECT_CLASS_NAME}`;
const persist = sharedOptions.cachePersist;
const persistPath = getPersistPath(CACHE_PLUGIN_NAME, tmpPath, persist);
await import_promises4.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 }
},
...getMiniflareObjectBindings(unsafeStickyBlobs)
]
}
};
services.push(storageService, objectService);
}
return services;
},
getPersistPath({ cachePersist }, tmpPath) {
return getPersistPath(CACHE_PLUGIN_NAME, tmpPath, cachePersist);
}
};
// src/plugins/do/index.ts
var import_promises5 = __toESM(require("fs/promises"));
var import_zod8 = require("zod");
var DurableObjectsOptionsSchema = import_zod8.z.object({
durableObjects: import_zod8.z.record(
import_zod8.z.union([
import_zod8.z.string(),
import_zod8.z.object({
className: import_zod8.z.string(),
scriptName: import_zod8.z.string().optional(),
useSQLite: import_zod8.z.boolean().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_zod8.z.union([import_zod8.z.string(), import_zod8.z.literal(kUnsafeEphemeralUniqueKey)]).optional(),
// Prevents the Durable Object being evicted.
unsafePreventEviction: import_zod8.z.boolean().optional()
})
])
).optional()
});
var DurableObjectsSharedOptionsSchema = import_zod8.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 enableSql = isObject ? designator.useSQLite : void 0;
const unsafeUniqueKey = isObject ? designator.unsafeUniqueKey : void 0;
const unsafePreventEviction = isObject ? designator.unsafePreventEviction : void 0;
return {
className,
serviceName,
enableSql,
unsafeUniqueKey,
unsafePreventEviction
};
}
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, new ProxyNodeBinding()])
);
},
async getServices({
sharedOptions,
tmpPath,
durableObjectClassNames,
unsafeEphemeralDurableObjects
}) {
let hasDurableObjects = false;
for (const classNames of durableObjectClassNames.values()) {
if (classNames.size > 0) {
hasDurableObjects = true;
break;
}
}
if (!hasDurableObjects)
return;
if (unsafeEphemeralDurableObjects)
return;
const storagePath = getPersistPath(
DURABLE_OBJECTS_PLUGIN_NAME,
tmpPath,
sharedOptions.durableObjectsPersist
);
await import_promises5.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 }
}
];
},
getPersistPath({ durableObjectsPersist }, tmpPath) {
return getPersistPath(
DURABLE_OBJECTS_PLUGIN_NAME,
tmpPath,
durableObjectsPersist
);
}
};
// 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}`;
}
// src/plugins/core/modules.ts
var import_assert5 = __toESM(require("assert"));
var import_fs14 = require("fs");
var import_module = require("module");
var import_path17 = __toESM(require("path"));
var import_url15 = require("url");
var import_util = require("util");
var import_acorn = require("acorn");
var import_acorn_walk = require("acorn-walk");
var import_zod9 = require("zod");
// src/plugins/core/node-compat.ts
function getNodeCompat(compatibilityDate = "2000-01-01", compatibilityFlags, opts) {
const { nodeCompat = false } = opts ?? {};
const {
hasNodejsAlsFlag,
hasNodejsCompatFlag,
hasNodejsCompatV2Flag,
hasNoNodejsCompatV2Flag,
hasExperimentalNodejsCompatV2Flag
} = parseNodeCompatibilityFlags(compatibilityFlags);
const nodeCompatSwitchOverDate = "2024-09-23";
const legacy = nodeCompat === true;
let mode = null;
if (hasNodejsCompatV2Flag || hasNodejsCompatFlag && compatibilityDate >= nodeCompatSwitchOverDate && !hasNoNodejsCompatV2Flag) {
mode = "v2";
} else if (hasNodejsCompatFlag) {
mode = "v1";
} else if (hasNodejsAlsFlag) {
mode = "als";
} else if (legacy) {
mode = "legacy";
}
return {
mode,
hasNodejsAlsFlag,
hasNodejsCompatFlag,
hasNodejsCompatV2Flag,
hasNoNodejsCompatV2Flag,
hasExperimentalNodejsCompatV2Flag
};
}
function parseNodeCompatibilityFlags(compatibilityFlags) {
return {
hasNodejsAlsFlag: compatibilityFlags.includes("nodejs_als"),
hasNodejsCompatFlag: compatibilityFlags.includes("nodejs_compat"),
hasNodejsCompatV2Flag: compatibilityFlags.includes("nodejs_compat_v2"),
hasNoNodejsCompatV2Flag: compatibilityFlags.includes("no_nodejs_compat_v2"),
hasExperimentalNodejsCompatV2Flag: compatibilityFlags.includes(
"experimental:nodejs_compat_v2"
)
};
}
// src/plugins/core/modules.ts
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\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_zod9.z.enum([
"ESModule",
"CommonJS",
"Text",
"Data",
"CompiledWasm",
"PythonModule",
"PythonRequirement"
]);
var ModuleRuleSchema = import_zod9.z.object({
type: ModuleRuleTypeSchema,
include: import_zod9.z.string().array(),
fallthrough: import_zod9.z.boolean().optional()
});
var ModuleDefinitionSchema = import_zod9.z.object({
type: ModuleRuleTypeSchema,
path: PathSchema,
contents: import_zod9.z.string().or(import_zod9.z.instanceof(Uint8Array)).optional()
});
var SourceOptionsSchema = import_zod9.z.union([
import_zod9.z.object({
// Manually defined modules
// (used by Wrangler which has its own module collection code)
modules: import_zod9.z.array(ModuleDefinitionSchema),
// `modules` "name"s will be their paths relative to this value.
// This ensures file paths in stack traces are correct.
modulesRoot: PathSchema.optional()
}),
import_zod9.z.object({
script: import_zod9.z.string(),
// Optional script path for resolving modules, and stack traces file names
scriptPath: PathSchema.optional(),
// Automatically collect modules by parsing `script` if `true`, or treat as
// service-worker if `false`
modules: import_zod9.z.boolean().optional(),
// How to interpret automatically collected modules
modulesRules: import_zod9.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: PathSchema.optional()
}),
import_zod9.z.object({
scriptPath: PathSchema,
// Automatically collect modules by parsing `scriptPath` if `true`, or treat
// as service-worker if `false`
modules: import_zod9.z.boolean().optional(),
// How to interpret automatically collected modules
modulesRules: import_zod9.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: PathSchema.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) {
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_path17.default.relative(modulesRoot, modulePath);
return import_path17.default.sep === "\\" ? name.replaceAll("\\", "/") : name;
}
function withSourceURL(script, scriptPath) {
if (script.lastIndexOf("//# sourceURL=") !== -1)
return script;
let scriptURL = scriptPath;
if (maybeGetStringScriptPathIndex(scriptPath) === void 0) {
scriptURL = (0, import_url15.pathToFileURL)(scriptPath);
}
const sourceURL = `
//# sourceURL=${scriptURL}
`;
return script + sourceURL;
}
function getResolveErrorPrefix(referencingPath) {
const relative2 = import_path17.default.relative("", referencingPath);
return `Unable to resolve "${relative2}" dependency`;
}
var ModuleLocator = class {
constructor(modulesRoot, additionalModuleNames, rules = [], compatibilityDate, compatibilityFlags) {
this.modulesRoot = modulesRoot;
this.additionalModuleNames = additionalModuleNames;
rules = rules.concat(DEFAULT_MODULE_RULES);
this.#compiledRules = compileModuleRules(rules);
this.#nodejsCompatMode = getNodeCompat(
compatibilityDate,
compatibilityFlags ?? []
).mode;
}
#compiledRules;
#nodejsCompatMode;
#visitedPaths = /* @__PURE__ */ new Set();
modules = [];
visitEntrypoint(code, 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 (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:
${dim2(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;
if (
// `cloudflare:` and `workerd:` imports don't need to be included explicitly
spec.startsWith("cloudflare:") || spec.startsWith("workerd:") || // Node.js compat v1 requires imports to be prefixed with `node:`
this.#nodejsCompatMode === "v1" && spec.startsWith("node:") || // Node.js compat modules and v2 can also handle non-prefixed imports
this.#nodejsCompatMode === "v2" && builtinModulesWithPrefix.includes(spec) || // Async Local Storage mode (node_als) only deals with `node:async_hooks` imports
this.#nodejsCompatMode === "als" && spec === "node:async_hooks" || // Any "additional" external modules can be ignored
this.additionalModuleNames.includes(spec)
) {
return;
}
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\``
);
}
const identifier = import_path17.default.resolve(import_path17.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_fs14.readFileSync)(identifier);
switch (rule.type) {
case "ESModule":
case "CommonJS":
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;
case "PythonModule":
this.modules.push({ name, pythonModule: data.toString("utf-8") });
break;
case "PythonRequirement":
this.modules.push({ name, pythonRequirement: data.toString("utf-8") });
break;
default:
const exhaustive = rule.type;
import_assert5.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 };
}
const exhaustive = type;
import_assert5.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`);
}
var encoder = new import_util.TextEncoder();
var decoder = new import_util.TextDecoder();
function contentsToString(contents21) {
return typeof contents21 === "string" ? contents21 : decoder.decode(contents21);
}
function contentsToArray(contents21) {
return typeof contents21 === "string" ? encoder.encode(contents21) : contents21;
}
function convertModuleDefinition(modulesRoot, def) {
const name = moduleName(modulesRoot, def.path);
const contents21 = def.contents ?? (0, import_fs14.readFileSync)(def.path);
switch (def.type) {
case "ESModule":
case "CommonJS":
return createJavaScriptModule(
contentsToString(contents21),
name,
import_path17.default.resolve(modulesRoot, def.path),
def.type
);
case "Text":
return { name, text: contentsToString(contents21) };
case "Data":
return { name, data: contentsToArray(contents21) };
case "CompiledWasm":
return { name, wasm: contentsToArray(contents21) };
case "PythonModule":
return { name, pythonModule: contentsToString(contents21) };
case "PythonRequirement":
return { name, pythonRequirement: contentsToString(contents21) };
default:
const exhaustive = def.type;
import_assert5.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
}
}
function convertWorkerModule(mod) {
const path31 = mod.name;
(0, import_assert5.default)(path31 !== void 0);
const m = mod;
if ("esModule" in m)
return { path: path31, type: "ESModule" };
else if ("commonJsModule" in m)
return { path: path31, type: "CommonJS" };
else if ("text" in m)
return { path: path31, type: "Text" };
else if ("data" in m)
return { path: path31, type: "Data" };
else if ("wasm" in m)
return { path: path31, type: "CompiledWasm" };
else if ("pythonModule" in m)
return { path: path31, type: "PythonModule" };
else if ("pythonRequirement" in m)
return { path: path31, type: "PythonRequirement" };
(0, import_assert5.default)(
!("json" in m || "fallbackService" in m),
"Unreachable: json or fallbackService modules aren't generated"
);
const exhaustive = m;
import_assert5.default.fail(
`Unreachable: [${Object.keys(exhaustive).join(
", "
)}] modules are unsupported`
);
}
// src/plugins/core/proxy/client.ts
var import_assert8 = __toESM(require("assert"));
var import_crypto2 = __toESM(require("crypto"));
var import_web4 = require("stream/web");
var import_util2 = __toESM(require("util"));
var import_undici6 = require("undici");
// src/plugins/core/proxy/fetch-sync.ts
var import_assert7 = __toESM(require("assert"));
var import_web2 = require("stream/web");
var import_worker_threads = require("worker_threads");
// src/plugins/core/errors/index.ts
var import_fs15 = __toESM(require("fs"));
var import_path18 = __toESM(require("path"));
var import_url16 = require("url");
var import_zod10 = require("zod");
// src/plugins/core/errors/sourcemap.ts
var import_assert6 = __toESM(require("assert"));
// 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 ?? void 0;
}
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;
}
};
// src/plugins/core/errors/sourcemap.ts
function getFreshSourceMapSupport() {
const resolvedSupportPath = require.resolve("@cspotcode/source-map-support");
const originalSymbolFor = Symbol.for;
const originalSupport = require.cache[resolvedSupportPath];
try {
Symbol.for = (key) => {
import_assert6.default.strictEqual(key, "source-map-support/sharedData");
return Symbol(key);
};
delete require.cache[resolvedSupportPath];
return require(resolvedSupportPath);
} finally {
Symbol.for = originalSymbolFor;
require.cache[resolvedSupportPath] = originalSupport;
}
}
var sourceMapInstallBaseOptions = {
environment: "node",
// Don't add Node `uncaughtException` handler
handleUncaughtExceptions: false,
// Don't hook Node `require` function
hookRequire: false,
redirectConflictingLibrary: 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 support = getFreshSourceMapSupport();
const originalPrepareStackTrace = Error.prepareStackTrace;
support.install(sourceMapInstallBaseOptions);
const prepareStackTrace = Error.prepareStackTrace;
(0, import_assert6.default)(prepareStackTrace !== void 0);
Error.prepareStackTrace = originalPrepareStackTrace;
sourceMapper = (retrieveSourceMap, error) => {
support.install({
...sourceMapInstallBaseOptions,
retrieveFile(_file) {
return "";
},
retrieveSourceMap
});
const callSites = parseStack(error.stack ?? "");
return prepareStackTrace(error, callSites);
};
return sourceMapper;
}
// src/plugins/core/errors/index.ts
function maybeGetDiskFile(filePath) {
try {
const contents21 = import_fs15.default.readFileSync(filePath, "utf8");
return { path: filePath, contents: contents21 };
} catch (e) {
if (e.code !== "ENOENT")
throw e;
}
}
function maybeGetFile2(workerSrcOpts, fileSpecifier) {
const maybeUrl = maybeParseURL(fileSpecifier);
if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") {
const filePath = (0, import_url16.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_path18.default.resolve(modulesRoot, module2.path) === filePath) {
const contents21 = contentsToString(module2.contents);
return { path: filePath, contents: contents21 };
}
}
} else if ("script" in srcOpts && "scriptPath" in srcOpts && srcOpts.script !== void 0 && srcOpts.scriptPath !== void 0) {
const modulesRoot = srcOpts.modules && srcOpts.modulesRoot || "";
if (import_path18.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 = maybeGetFile2(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_path18.default.dirname(sourceFile.path);
const sourceMapPath = import_path18.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.cf?.prettyErrorOriginalUrl ?? 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.cloudflare.com" 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" }
});
}
// src/plugins/core/proxy/fetch-sync.ts
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 { Pool, fetch } = actualRequire("undici");
let dispatcherUrl;
let dispatcher;
port.addEventListener("message", async (event) => {
const { id, method, url, headers, body } = event.data;
if (dispatcherUrl !== url) {
dispatcherUrl = url;
dispatcher = new Pool(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 });
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);
});
port.start();
`
);
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(url21, init2) {
this.#ensureWorker();
Atomics.store(
this.#notifyHandle,
/* index */
0,
/* value */
0
);
const id = this.#nextId++;
this.#channel.port1.postMessage({
id,
method: init2.method,
url: url21.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_assert7.default)(message?.id === id);
if ("response" in message) {
const { status: status2, headers: rawHeaders, body } = message.response;
const headers = new import_undici4.Headers(rawHeaders);
const stack = headers.get(CoreHeaders.ERROR_STACK);
if (status2 === 500 && stack !== null && body !== null) {
(0, import_assert7.default)(!(body instanceof import_web2.ReadableStream));
const caught = JsonErrorSchema.parse(JSON.parse(DECODER.decode(body)));
throw reviveError([], caught);
}
return { status: status2, headers, body };
} else {
throw message.error;
}
}
async dispose() {
await this.#worker?.terminate();
}
};
// 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();
}
};
// src/plugins/core/proxy/client.ts
var kAddress = Symbol("kAddress");
var kName = Symbol("kName");
var kIsFunction = Symbol("kIsFunction");
function isNativeTarget(value) {
return typeof value === "object" && value !== null && kAddress in value && kIsFunction in value;
}
var TARGET_GLOBAL = {
[kAddress]: ProxyAddresses.GLOBAL,
[kName]: "global",
[kIsFunction]: false
};
var TARGET_ENV = {
[kAddress]: ProxyAddresses.ENV,
[kName]: "env",
[kIsFunction]: false
};
var reducers = {
...structuredSerializableReducers,
...createHTTPReducers(NODE_PLATFORM_IMPL),
Native(value) {
if (isNativeTarget(value))
return [value[kAddress], value[kName], value[kIsFunction]];
}
};
var revivers = {
...structuredSerializableRevivers,
...createHTTPRevivers(NODE_PLATFORM_IMPL)
// `Native` reviver depends on `ProxyStubHandler` methods
};
var PROXY_SECRET = import_crypto2.default.randomBytes(16);
var PROXY_SECRET_HEX = PROXY_SECRET.toString("hex");
function isClientError(status2) {
return 400 <= status2 && status2 < 500;
}
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() {
this.#bridge.poisonProxies();
this.#globalProxy = void 0;
this.#envProxy = void 0;
}
setRuntimeEntryURL(runtimeEntryURL) {
this.#bridge.url = runtimeEntryURL;
}
dispose() {
return this.#bridge.dispose();
}
};
var ProxyClientBridge = class {
constructor(url21, dispatchFetch) {
this.url = url21;
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;
// Garbage collection passes will free lots of objects at once. Rather than
// sending a `DELETE` request for each address, we batch finalisations within
// 100ms of each other into one request. This ensures we don't create *lots*
// of TCP connections to `workerd` in `dispatchFetch()` for all the concurrent
// requests.
#finalizeBatch = [];
#finalizeBatchTimeout;
sync = new SynchronousFetcher();
get version() {
return this.#version;
}
#finalizeProxy = (held) => {
this.#finalizeBatch.push(held);
clearTimeout(this.#finalizeBatchTimeout);
this.#finalizeBatchTimeout = setTimeout(this.#finalizeProxyBatch, 100);
};
#finalizeProxyBatch = async () => {
const addresses = [];
for (const held of this.#finalizeBatch.splice(0)) {
if (held.version === this.#version)
addresses.push(held.address);
}
if (addresses.length === 0)
return;
try {
await this.dispatchFetch(this.url, {
method: "DELETE",
headers: {
[CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
[CoreHeaders.OP]: ProxyOps.FREE,
[CoreHeaders.OP_TARGET]: addresses.join(",")
}
});
} catch {
}
};
getProxy(target) {
const handler = new ProxyStubHandler(this, target);
let proxyTarget;
if (target[kIsFunction]) {
proxyTarget = new Function();
} else {
proxyTarget = {};
}
proxyTarget[import_util2.default.inspect.custom] = handler.inspect;
const proxy = new Proxy(proxyTarget, handler);
const held = {
address: target[kAddress],
version: this.#version
};
this.#finalizationRegistry.register(proxy, held, this);
return proxy;
}
poisonProxies() {
this.#version++;
this.#finalizationRegistry.unregister(this);
}
dispose() {
this.poisonProxies();
return this.sync.dispose();
}
};
var ProxyStubHandler = class extends Function {
constructor(bridge, target) {
super();
this.bridge = bridge;
this.target = target;
this.#version = bridge.version;
this.#stringifiedTarget = stringify(this.target, reducers);
}
#version;
#stringifiedTarget;
#knownValues = /* @__PURE__ */ new Map();
#knownDescriptors = /* @__PURE__ */ new Map();
#knownOwnKeys;
revivers = {
...revivers,
Native: (value) => {
(0, import_assert8.default)(Array.isArray(value));
const [address, name, isFunction] = value;
(0, import_assert8.default)(typeof address === "number");
(0, import_assert8.default)(typeof name === "string");
(0, import_assert8.default)(typeof isFunction === "boolean");
const target = {
[kAddress]: address,
[kName]: name,
[kIsFunction]: isFunction
};
if (name === "Promise") {
const resPromise = this.bridge.dispatchFetch(this.bridge.url, {
method: "POST",
headers: {
[CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
[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_assert8.default)(res.status === 200);
return result;
}
}
async #parseAsyncResponse(resPromise) {
const res = await resPromise;
(0, import_assert8.default)(!isClientError(res.status));
const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE);
if (typeHeader === "Promise, ReadableStream")
return res.body;
(0, import_assert8.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_assert8.default)(!Number.isNaN(stringifiedSize));
(0, import_assert8.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_assert8.default)(!isClientError(syncRes.status));
(0, import_assert8.default)(syncRes.body !== null);
(0, import_assert8.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);
}
#thisFnKnownAsync = false;
apply(_target, ...args) {
const result = this.#call(
"__miniflareWrappedFunction",
this.#thisFnKnownAsync,
args[1],
this
);
if (!this.#thisFnKnownAsync && result instanceof Promise) {
this.#thisFnKnownAsync = true;
}
return result;
}
get(_target, key, _receiver) {
this.#assertSafe();
if (key === kAddress)
return this.target[kAddress];
if (key === kName)
return this.target[kName];
if (key === kIsFunction)
return this.target[kIsFunction];
if (typeof key === "symbol" || key === "then")
return void 0;
const maybeKnown = this.#knownValues.get(key);
if (maybeKnown !== void 0)
return maybeKnown;
const syncRes = this.bridge.sync.fetch(this.bridge.url, {
method: "POST",
headers: {
[CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
[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.#knownValues.set(key, result);
}
return result;
}
has(target, key) {
return this.get(target, key, void 0) !== void 0;
}
getOwnPropertyDescriptor(target, key) {
this.#assertSafe();
if (typeof key === "symbol")
return void 0;
const maybeKnown = this.#knownDescriptors.get(key);
if (maybeKnown !== void 0)
return maybeKnown;
const syncRes = this.bridge.sync.fetch(this.bridge.url, {
method: "POST",
headers: {
[CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
[CoreHeaders.OP]: ProxyOps.GET_OWN_DESCRIPTOR,
[CoreHeaders.OP_KEY]: key,
[CoreHeaders.OP_TARGET]: this.#stringifiedTarget
}
});
const result = this.#parseSyncResponse(
syncRes,
this.getOwnPropertyDescriptor
);
this.#knownDescriptors.set(key, result);
return result;
}
ownKeys(_target) {
this.#assertSafe();
if (this.#knownOwnKeys !== void 0)
return this.#knownOwnKeys;
const syncRes = this.bridge.sync.fetch(this.bridge.url, {
method: "POST",
headers: {
[CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
[CoreHeaders.OP]: ProxyOps.GET_OWN_KEYS,
[CoreHeaders.OP_TARGET]: this.#stringifiedTarget
}
});
const result = this.#parseSyncResponse(syncRes, this.ownKeys);
this.#knownOwnKeys = result;
return result;
}
getPrototypeOf(_target) {
this.#assertSafe();
return null;
}
#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 || // Durable Object stub RPC calls should always be async to avoid blocking
// the Node.js event loop with `Atomics.wait()`. This allows Promise.race()
// and timeouts to work correctly when racing against DO method calls.
isDurableObjectStub(targetName) || // 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_assert8.default)(arg instanceof import_undici6.Headers);
(0, import_assert8.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_SECRET]: PROXY_SECRET_HEX,
[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_SECRET]: PROXY_SECRET_HEX,
[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_SECRET]: PROXY_SECRET_HEX,
[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_SECRET, PROXY_SECRET_HEX);
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);
}
};
// src/plugins/core/services.ts
var import_zod11 = require("zod");
var kCurrentWorker = Symbol.for("miniflare.kCurrentWorker");
var HttpOptionsHeaderSchema = import_zod11.z.object({
name: import_zod11.z.string(),
// name should be required
value: import_zod11.z.ostring()
// If omitted, the header will be removed
});
var HttpOptionsSchema = import_zod11.z.object({
style: import_zod11.z.nativeEnum(HttpOptions_Style).optional(),
forwardedProtoHeader: import_zod11.z.ostring(),
cfBlobHeader: import_zod11.z.ostring(),
injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(),
injectResponseHeaders: HttpOptionsHeaderSchema.array().optional()
}).transform((options) => ({
...options,
capnpConnectHost: HOST_CAPNP_CONNECT
}));
var TlsOptionsKeypairSchema = import_zod11.z.object({
privateKey: import_zod11.z.ostring(),
certificateChain: import_zod11.z.ostring()
});
var TlsOptionsSchema = import_zod11.z.object({
keypair: TlsOptionsKeypairSchema.optional(),
requireClientCerts: import_zod11.z.oboolean(),
trustBrowserCas: import_zod11.z.oboolean(),
trustedCertificates: import_zod11.z.string().array().optional(),
minVersion: import_zod11.z.nativeEnum(TlsOptions_Version).optional(),
cipherList: import_zod11.z.ostring()
});
var NetworkSchema = import_zod11.z.object({
allow: import_zod11.z.string().array().optional(),
deny: import_zod11.z.string().array().optional(),
tlsOptions: TlsOptionsSchema.optional()
});
var ExternalServerSchema = import_zod11.z.intersection(
import_zod11.z.object({ address: import_zod11.z.string() }),
// address should be required
import_zod11.z.union([
import_zod11.z.object({ http: import_zod11.z.optional(HttpOptionsSchema) }),
import_zod11.z.object({
https: import_zod11.z.optional(
import_zod11.z.object({
options: HttpOptionsSchema.optional(),
tlsOptions: TlsOptionsSchema.optional(),
certificateHost: import_zod11.z.ostring()
})
)
})
])
);
var DiskDirectorySchema = import_zod11.z.object({
path: import_zod11.z.string(),
// path should be required
writable: import_zod11.z.oboolean()
});
var ServiceFetchSchema = import_zod11.z.custom((v) => typeof v === "function");
var ServiceDesignatorSchema = import_zod11.z.union([
import_zod11.z.string(),
import_zod11.z.literal(kCurrentWorker),
import_zod11.z.object({
name: import_zod11.z.union([import_zod11.z.string(), import_zod11.z.literal(kCurrentWorker)]),
entrypoint: import_zod11.z.ostring()
}),
import_zod11.z.object({ network: NetworkSchema }),
import_zod11.z.object({ external: ExternalServerSchema }),
import_zod11.z.object({ disk: DiskDirectorySchema }),
ServiceFetchSchema
]);
// 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_fs16.readFileSync)(process.env.NODE_EXTRA_CA_CERTS, "utf8");
const certs = extra.match(
/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g
);
if (certs !== null) {
trustedCertificates.push(...certs);
}
} 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 WrappedBindingSchema = import_zod12.z.object({
scriptName: import_zod12.z.string(),
entrypoint: import_zod12.z.string().optional(),
bindings: import_zod12.z.record(JsonSchema).optional()
});
var UnusableStringSchema = import_zod12.z.string().transform(() => void 0);
var UnsafeDirectSocketSchema = import_zod12.z.object({
host: import_zod12.z.ostring(),
port: import_zod12.z.onumber(),
entrypoint: import_zod12.z.ostring(),
proxy: import_zod12.z.oboolean()
});
var CoreOptionsSchemaInput = import_zod12.z.intersection(
SourceOptionsSchema,
import_zod12.z.object({
name: import_zod12.z.string().optional(),
rootPath: UnusableStringSchema.optional(),
compatibilityDate: import_zod12.z.string().optional(),
compatibilityFlags: import_zod12.z.string().array().optional(),
routes: import_zod12.z.string().array().optional(),
bindings: import_zod12.z.record(JsonSchema).optional(),
wasmBindings: import_zod12.z.record(import_zod12.z.union([PathSchema, import_zod12.z.instanceof(Uint8Array)])).optional(),
textBlobBindings: import_zod12.z.record(PathSchema).optional(),
dataBlobBindings: import_zod12.z.record(import_zod12.z.union([PathSchema, import_zod12.z.instanceof(Uint8Array)])).optional(),
serviceBindings: import_zod12.z.record(ServiceDesignatorSchema).optional(),
wrappedBindings: import_zod12.z.record(import_zod12.z.union([import_zod12.z.string(), WrappedBindingSchema])).optional(),
outboundService: ServiceDesignatorSchema.optional(),
fetchMock: import_zod12.z.instanceof(import_undici7.MockAgent).optional(),
// TODO(soon): remove this in favour of per-object `unsafeUniqueKey: kEphemeralUniqueKey`
unsafeEphemeralDurableObjects: import_zod12.z.boolean().optional(),
unsafeDirectSockets: UnsafeDirectSocketSchema.array().optional(),
unsafeEvalBinding: import_zod12.z.string().optional(),
unsafeUseModuleFallbackService: import_zod12.z.boolean().optional(),
/** Used to set the vitest pool worker SELF binding to point to the Router Worker if there are assets.
(If there are assets but we're not using vitest, the miniflare entry worker can point directly to
Router Worker)
*/
hasAssetsAndIsVitest: import_zod12.z.boolean().optional(),
unsafeEnableAssetsRpc: import_zod12.z.boolean().optional(),
// Strip the CF-Connecting-IP header from outbound fetches
// There is an issue with the connect() API and the globalOutbound workerd setting that impacts TCP ingress
// We should default it to true once https://github.com/cloudflare/workerd/pull/4145 is resolved
stripCfConnectingIp: import_zod12.z.boolean().default(false)
})
);
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.fetchMock = void 0;
value.outboundService = (req) => fetch3(req, { dispatcher: fetchMock });
}
return value;
});
var CoreSharedOptionsSchema = import_zod12.z.object({
rootPath: UnusableStringSchema.optional(),
host: import_zod12.z.string().optional(),
port: import_zod12.z.number().optional(),
https: import_zod12.z.boolean().optional(),
httpsKey: import_zod12.z.string().optional(),
httpsKeyPath: import_zod12.z.string().optional(),
httpsCert: import_zod12.z.string().optional(),
httpsCertPath: import_zod12.z.string().optional(),
inspectorPort: import_zod12.z.number().optional(),
verbose: import_zod12.z.boolean().optional(),
log: import_zod12.z.instanceof(Log).optional(),
handleRuntimeStdio: import_zod12.z.function(import_zod12.z.tuple([import_zod12.z.instanceof(import_stream2.Readable), import_zod12.z.instanceof(import_stream2.Readable)])).optional(),
upstream: import_zod12.z.string().optional(),
// TODO: add back validation of cf object
cf: import_zod12.z.union([import_zod12.z.boolean(), import_zod12.z.string(), import_zod12.z.record(import_zod12.z.any())]).optional(),
liveReload: import_zod12.z.boolean().optional(),
// This is a shared secret between a proxy server and miniflare that can be
// passed in a header to prove that the request came from the proxy and not
// some malicious attacker.
unsafeProxySharedSecret: import_zod12.z.string().optional(),
unsafeModuleFallbackService: ServiceFetchSchema.optional(),
// Keep blobs when deleting/overwriting keys, required for stacked storage
unsafeStickyBlobs: import_zod12.z.boolean().optional(),
unsafeEnableAssetsRpc: import_zod12.z.boolean().optional(),
// Whether to get structured logs from workerd or not (default to `false`)
// This option is useful in combination with a custom handleRuntimeStdio.
structuredWorkerdLogs: import_zod12.z.boolean().default(false)
});
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(refererName, workerIndex, kind, name, service, hasAssetsAndIsVitest = false, unsafeEnableAssetsRpc = false) {
let serviceName;
let entrypoint;
if (typeof service === "function") {
serviceName = getCustomServiceName(workerIndex, kind, name);
} else if (typeof service === "object") {
if ("name" in service) {
if (service.name === kCurrentWorker) {
serviceName = getUserServiceName(refererName);
} else {
serviceName = getUserServiceName(service.name);
}
entrypoint = service.entrypoint;
} else {
serviceName = getBuiltinServiceName(workerIndex, kind, name);
}
} else if (service === kCurrentWorker) {
serviceName = hasAssetsAndIsVitest ? unsafeEnableAssetsRpc ? `${RPC_PROXY_SERVICE_NAME}:${refererName}` : `${ROUTER_SERVICE_NAME}:${refererName}` : getUserServiceName(refererName);
} else {
serviceName = getUserServiceName(service);
}
return { name: serviceName, entrypoint };
}
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" && !("name" in service)) {
return {
name: getBuiltinServiceName(workerIndex, kind, name),
...service
};
}
}
var FALLBACK_COMPATIBILITY_DATE = "2000-01-01";
function getCurrentCompatibilityDate() {
const now = (/* @__PURE__ */ 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 ",
bold2(`"${import_workerd2.compatibilityDate}"`),
",\nbut you've requested ",
bold2(`"${compatibilityDate}"`),
". Falling back to ",
bold2(`"${import_workerd2.compatibilityDate}"`),
"..."
].join("")
);
return import_workerd2.compatibilityDate;
}
return compatibilityDate;
}
function buildBindings(bindings) {
return Object.entries(bindings).map(([name, value]) => {
if (typeof value === "string") {
return {
name,
text: value
};
} else {
return {
name,
json: JSON.stringify(value)
};
}
});
}
var WRAPPED_MODULE_PREFIX = "miniflare-internal:wrapped:";
function workerNameToWrappedModule(workerName) {
return WRAPPED_MODULE_PREFIX + workerName;
}
function maybeWrappedModuleToWorkerName(name) {
if (name.startsWith(WRAPPED_MODULE_PREFIX)) {
return name.substring(WRAPPED_MODULE_PREFIX.length);
}
}
function getStripCfConnectingIpName(workerIndex) {
return `strip-cf-connecting-ip:${workerIndex}`;
}
function getGlobalOutbound(workerIndex, options) {
return options.outboundService === void 0 ? void 0 : getCustomServiceDesignator(
/* referrer */
options.name,
workerIndex,
"$" /* KNOWN */,
CUSTOM_SERVICE_KNOWN_OUTBOUND,
options.outboundService,
options.hasAssetsAndIsVitest,
options.unsafeEnableAssetsRpc
);
}
var CORE_PLUGIN = {
options: CoreOptionsSchema,
sharedOptions: CoreSharedOptionsSchema,
getBindings(options, workerIndex) {
const bindings = [];
if (options.bindings !== void 0) {
bindings.push(...buildBindings(options.bindings));
}
if (options.wasmBindings !== void 0) {
bindings.push(
...Object.entries(options.wasmBindings).map(
([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((wasmModule) => ({ name, wasmModule })) : { name, wasmModule: value }
)
);
}
if (options.textBlobBindings !== void 0) {
bindings.push(
...Object.entries(options.textBlobBindings).map(
([name, path31]) => import_promises6.default.readFile(path31, "utf8").then((text) => ({ name, text }))
)
);
}
if (options.dataBlobBindings !== void 0) {
bindings.push(
...Object.entries(options.dataBlobBindings).map(
([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((data) => ({ name, data })) : { name, data: value }
)
);
}
if (options.serviceBindings !== void 0) {
bindings.push(
...Object.entries(options.serviceBindings).map(([name, service]) => {
return {
name,
service: getCustomServiceDesignator(
/* referrer */
options.name,
workerIndex,
"#" /* UNKNOWN */,
name,
service,
options.hasAssetsAndIsVitest,
options.unsafeEnableAssetsRpc
)
};
})
);
}
if (options.wrappedBindings !== void 0) {
bindings.push(
...Object.entries(options.wrappedBindings).map(([name, designator]) => {
const isObject = typeof designator === "object";
const scriptName = isObject ? designator.scriptName : designator;
const entrypoint = isObject ? designator.entrypoint : void 0;
const bindings2 = isObject ? designator.bindings : void 0;
const moduleName2 = workerNameToWrappedModule(scriptName);
const innerBindings = bindings2 === void 0 ? [] : buildBindings(bindings2);
return {
name,
wrapped: { moduleName: moduleName2, entrypoint, innerBindings }
};
})
);
}
if (options.unsafeEvalBinding !== void 0) {
bindings.push({
name: options.unsafeEvalBinding,
unsafeEval: kVoid
});
}
return Promise.all(bindings);
},
async getNodeBindings(options) {
const bindingEntries3 = [];
if (options.bindings !== void 0) {
bindingEntries3.push(
...Object.entries(options.bindings).map(([name, value]) => [
name,
JSON.parse(JSON.stringify(value))
])
);
}
if (options.wasmBindings !== void 0) {
bindingEntries3.push(
...Object.entries(options.wasmBindings).map(
([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((buffer) => [name, new WebAssembly.Module(buffer)]) : [name, new WebAssembly.Module(value)]
)
);
}
if (options.textBlobBindings !== void 0) {
bindingEntries3.push(
...Object.entries(options.textBlobBindings).map(
([name, path31]) => import_promises6.default.readFile(path31, "utf8").then((text) => [name, text])
)
);
}
if (options.dataBlobBindings !== void 0) {
bindingEntries3.push(
...Object.entries(options.dataBlobBindings).map(
([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((buffer) => [name, viewToBuffer(buffer)]) : [name, viewToBuffer(value)]
)
);
}
if (options.serviceBindings !== void 0) {
bindingEntries3.push(
...Object.keys(options.serviceBindings).map((name) => [
name,
new ProxyNodeBinding()
])
);
}
if (options.wrappedBindings !== void 0) {
bindingEntries3.push(
...Object.keys(options.wrappedBindings).map((name) => [
name,
new ProxyNodeBinding()
])
);
}
return Object.fromEntries(await Promise.all(bindingEntries3));
},
async getServices({
log,
options,
sharedOptions,
workerBindings,
workerIndex,
wrappedBindingNames,
durableObjectClassNames,
additionalModules,
loopbackPort
}) {
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_path19.default.posix.dirname(name2))
);
subDirs.delete(".");
for (const module2 of additionalModules) {
workerScript.modules.push(module2);
for (const subDir of subDirs) {
const relativePath = import_path19.default.posix.relative(subDir, module2.name);
const relativePathString = JSON.stringify(relativePath);
workerScript.modules.push({
name: import_path19.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 = options.name ?? "";
const serviceName = getUserServiceName(options.name);
const classNames = durableObjectClassNames.get(serviceName);
const classNamesEntries = Array.from(classNames ?? []);
const compatibilityDate = validateCompatibilityDate(
log,
options.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE
);
const isWrappedBinding = wrappedBindingNames.has(name);
const services = [];
const extensions = [];
if (isWrappedBinding) {
let invalidWrapped2 = function(reason) {
const message = `Cannot use ${stringName} for wrapped binding because ${reason}`;
throw new MiniflareCoreError("ERR_INVALID_WRAPPED", message);
};
var invalidWrapped = invalidWrapped2;
const stringName = JSON.stringify(name);
if (workerIndex === 0) {
invalidWrapped2(
`it's the entrypoint.
Ensure ${stringName} isn't the first entry in the \`workers\` array.`
);
}
if (!("modules" in workerScript)) {
invalidWrapped2(
`it's a service worker.
Ensure ${stringName} sets \`modules\` to \`true\` or an array of modules`
);
}
if (workerScript.modules.length !== 1) {
invalidWrapped2(
`it isn't a single module.
Ensure ${stringName} doesn't include unbundled \`import\`s.`
);
}
const firstModule = workerScript.modules[0];
if (!("esModule" in firstModule)) {
invalidWrapped2("it isn't a single ES module");
}
if (options.compatibilityDate !== void 0) {
invalidWrapped2(
"it defines a compatibility date.\nWrapped bindings use the compatibility date of the worker with the binding."
);
}
if (options.compatibilityFlags?.length) {
invalidWrapped2(
"it defines compatibility flags.\nWrapped bindings use the compatibility flags of the worker with the binding."
);
}
if (options.outboundService !== void 0) {
invalidWrapped2(
"it defines an outbound service.\nWrapped bindings use the outbound service of the worker with the binding."
);
}
extensions.push({
modules: [
{
name: workerNameToWrappedModule(name),
esModule: firstModule.esModule,
internal: true
}
]
});
} else {
services.push({
name: serviceName,
worker: {
...workerScript,
compatibilityDate,
compatibilityFlags: options.compatibilityFlags,
bindings: workerBindings,
durableObjectNamespaces: classNamesEntries.map(
([
className,
{ enableSql, unsafeUniqueKey, unsafePreventEviction }
]) => {
if (unsafeUniqueKey === kUnsafeEphemeralUniqueKey) {
return {
className,
enableSql,
ephemeralLocal: kVoid,
preventEviction: unsafePreventEviction
};
} else {
return {
className,
enableSql,
// 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}`,
preventEviction: unsafePreventEviction
};
}
}
),
durableObjectStorage: classNamesEntries.length === 0 ? void 0 : options.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME },
globalOutbound: options.stripCfConnectingIp ? { name: getStripCfConnectingIpName(workerIndex) } : getGlobalOutbound(workerIndex, options),
cacheApiOutbound: { name: getCacheServiceName(workerIndex) },
moduleFallback: options.unsafeUseModuleFallbackService && sharedOptions.unsafeModuleFallbackService !== void 0 ? `localhost:${loopbackPort}` : void 0
}
});
}
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);
}
if (options.stripCfConnectingIp) {
services.push({
name: getStripCfConnectingIpName(workerIndex),
worker: {
modules: [
{
name: "index.js",
esModule: strip_cf_connecting_ip_worker_default()
}
],
compatibilityDate: "2025-01-01",
globalOutbound: getGlobalOutbound(workerIndex, options)
}
});
}
return { services, extensions };
}
};
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: fallbackWorkerName }
},
...workerNames.map((name) => ({
name: CoreBindings.SERVICE_USER_ROUTE_PREFIX + name,
service: { name: getUserServiceName(name) }
})),
{
name: CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
durableObjectNamespace: { className: "ProxyServer" }
},
{
name: CoreBindings.DATA_PROXY_SECRET,
data: PROXY_SECRET
},
// Add `proxyBindings` here, they'll be added to the `ProxyServer` `env`
...proxyBindings
];
if (sharedOptions.upstream !== void 0) {
serviceEntryBindings.push({
name: CoreBindings.TEXT_UPSTREAM_URL,
text: sharedOptions.upstream
});
}
if (sharedOptions.unsafeProxySharedSecret !== void 0) {
serviceEntryBindings.push({
name: CoreBindings.DATA_PROXY_SHARED_SECRET,
data: encoder2.encode(sharedOptions.unsafeProxySharedSecret)
});
}
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: CoreHeaders.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",
"brotli_content_encoding",
"rpc"
],
bindings: serviceEntryBindings,
durableObjectNamespaces: [
{
className: "ProxyServer",
uniqueKey: `${SERVICE_ENTRY}-ProxyServer`,
// `ProxyServer` relies on a singleton object containing of "heap"
// mapping addresses to native references. If the singleton object
// were evicted, addresses would be invalidated. Therefore, we
// prevent eviction to ensure heap addresses stay valid for the
// lifetime of the `workerd` process
preventEviction: true
}
],
// `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", "240.0.0.0/4"],
deny: [],
tlsOptions: {
trustBrowserCas: true,
trustedCertificates
}
}
}
];
}
function getWorkerScript(options, workerIndex, additionalModuleNames) {
const modulesRoot = import_path19.default.resolve(
("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_fs16.readFileSync)(options.scriptPath, "utf8");
} else {
import_assert9.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.compatibilityDate,
options.compatibilityFlags
);
locator.visitEntrypoint(code, scriptPath);
return { modules: locator.modules };
} else {
code = withSourceURL(code, scriptPath);
return { serviceWorkerScript: code };
}
}
// src/plugins/assets/schema.ts
var import_zod13 = require("zod");
var AssetsOptionsSchema = import_zod13.z.object({
assets: import_zod13.z.object({
// User Worker name or vitest runner - this is only ever set inside miniflare
// The assets plugin needs access to the worker name to create the router worker - user worker binding
workerName: import_zod13.z.string().optional(),
directory: PathSchema,
binding: import_zod13.z.string().optional(),
routerConfig: RouterConfigSchema.optional(),
assetConfig: AssetConfigSchema.optional()
}).optional()
});
// src/plugins/assets/index.ts
var ASSETS_PLUGIN = {
options: AssetsOptionsSchema,
async getBindings(options) {
if (!options.assets?.binding) {
return [];
}
return [
{
// binding between User Worker and Asset Worker
name: options.assets.binding,
service: {
name: `${ASSETS_SERVICE_NAME}:${options.assets.workerName}`
}
}
];
},
async getNodeBindings(options) {
if (!options.assets?.binding) {
return {};
}
return {
[options.assets.binding]: new ProxyNodeBinding()
};
},
async getServices({ options, unsafeEnableAssetsRpc }) {
if (!options.assets) {
return [];
}
const storageServiceName = `${ASSETS_PLUGIN_NAME}:storage`;
const storageService = {
name: storageServiceName,
disk: { path: options.assets.directory, writable: true }
};
const { encodedAssetManifest, assetsReverseMap } = await buildAssetManifest(
options.assets.directory
);
const redirectsFile = (0, import_node_path3.join)(options.assets.directory, REDIRECTS_FILENAME);
const headersFile = (0, import_node_path3.join)(options.assets.directory, HEADERS_FILENAME);
const redirectsContents = maybeGetFile(redirectsFile);
const headersContents = maybeGetFile(headersFile);
const logger = new Log();
const assetParserLogger = {
debug: (message) => logger.debug(message),
log: (message) => logger.info(message),
info: (message) => logger.info(message),
warn: (message) => logger.warn(message),
error: (error) => logger.error(error)
};
let parsedRedirects;
if (redirectsContents !== void 0) {
const redirects = parseRedirects(redirectsContents);
parsedRedirects = RedirectsSchema.parse(
constructRedirects({
redirects,
redirectsFile,
logger: assetParserLogger
}).redirects
);
}
let parsedHeaders;
if (headersContents !== void 0) {
const headers = parseHeaders(headersContents);
parsedHeaders = HeadersSchema.parse(
constructHeaders({
headers,
headersFile,
logger: assetParserLogger
}).headers
);
}
const assetConfig = {
...options.assets.assetConfig,
redirects: parsedRedirects,
headers: parsedHeaders
};
const id = options.assets.workerName;
const namespaceService = {
name: `${ASSETS_KV_SERVICE_NAME}:${id}`,
worker: {
compatibilityDate: "2023-07-24",
compatibilityFlags: ["nodejs_compat"],
modules: [
{
name: "assets-kv-worker.mjs",
esModule: assets_kv_worker_default()
}
],
bindings: [
{
name: SharedBindings.MAYBE_SERVICE_BLOBS,
service: { name: storageServiceName }
},
{
name: "ASSETS_REVERSE_MAP",
json: JSON.stringify(assetsReverseMap)
}
]
}
};
const assetService = {
name: `${ASSETS_SERVICE_NAME}:${id}`,
worker: {
// TODO: read these from the wrangler.toml
compatibilityDate: "2024-07-31",
compatibilityFlags: ["nodejs_compat"],
modules: [
{
name: "asset-worker.mjs",
esModule: assets_worker_default()
}
],
bindings: [
{
name: "ASSETS_KV_NAMESPACE",
kvNamespace: {
name: `${ASSETS_KV_SERVICE_NAME}:${id}`
}
},
{
name: "ASSETS_MANIFEST",
data: encodedAssetManifest
},
{
name: "CONFIG",
json: JSON.stringify(assetConfig)
}
]
}
};
const routerService = {
name: `${ROUTER_SERVICE_NAME}:${id}`,
worker: {
// TODO: read these from the wrangler.toml
compatibilityDate: "2024-07-31",
compatibilityFlags: ["nodejs_compat", "no_nodejs_compat_v2"],
modules: [
{
name: "router-worker.mjs",
esModule: router_worker_default()
}
],
bindings: [
{
name: "ASSET_WORKER",
service: {
name: `${ASSETS_SERVICE_NAME}:${id}`
}
},
{
name: "USER_WORKER",
service: { name: getUserServiceName(id) }
},
{
name: "CONFIG",
json: JSON.stringify(options.assets.routerConfig ?? {})
}
]
}
};
const services = [
storageService,
namespaceService,
assetService,
routerService
];
if (unsafeEnableAssetsRpc) {
const assetsProxyService = {
name: `${RPC_PROXY_SERVICE_NAME}:${id}`,
worker: {
compatibilityDate: "2024-08-01",
modules: [
{
name: "assets-proxy-worker.mjs",
esModule: rpc_proxy_worker_default()
}
],
bindings: [
{
name: "ROUTER_WORKER",
service: {
name: `${ROUTER_SERVICE_NAME}:${id}`
}
}
]
}
};
services.push(assetsProxyService);
}
return services;
}
};
var buildAssetManifest = async (dir) => {
const { manifest, assetsReverseMap } = await walk(dir);
const sortedAssetManifest = sortManifest(manifest);
const encodedAssetManifest = encodeManifest(sortedAssetManifest);
return { encodedAssetManifest, assetsReverseMap };
};
var walk = async (dir) => {
const files = await import_promises7.default.readdir(dir, { recursive: true });
const manifest = [];
const assetsReverseMap = {};
const { assetsIgnoreFunction } = await createAssetsIgnoreFunction(dir);
let counter = 0;
await Promise.all(
files.map(async (file) => {
if (assetsIgnoreFunction(file)) {
return;
}
const filepath = import_node_path3.default.join(dir, file);
const relativeFilepath = import_node_path3.default.relative(dir, filepath);
const filestat = await import_promises7.default.stat(filepath);
if (filestat.isSymbolicLink() || filestat.isDirectory()) {
return;
} else {
if (filestat.size > MAX_ASSET_SIZE) {
throw new Error(
`Asset too large.
Cloudflare Workers supports assets with sizes of up to ${prettyBytes(
MAX_ASSET_SIZE,
{
binary: true
}
)}. We found a file ${filepath} with a size of ${prettyBytes(
filestat.size,
{
binary: true
}
)}.
Ensure all assets in your assets directory "${dir}" conform with the Workers maximum size requirement.`
);
}
const [pathHash, contentHash] = await Promise.all([
hashPath(normalizeFilePath(relativeFilepath)),
// used absolute filepath here so that changes to the enclosing asset folder will be registered
hashPath(filepath + filestat.mtimeMs.toString())
]);
manifest.push({
pathHash,
contentHash
});
assetsReverseMap[bytesToHex(contentHash)] = {
filePath: relativeFilepath,
contentType: getContentType(filepath)
};
counter++;
}
})
);
if (counter > MAX_ASSET_COUNT) {
throw new Error(
`Maximum number of assets exceeded.
Cloudflare Workers supports up to ${MAX_ASSET_COUNT.toLocaleString()} assets in a version. We found ${counter.toLocaleString()} files in the specified assets directory "${dir}".
Ensure your assets directory contains a maximum of ${MAX_ASSET_COUNT.toLocaleString()} files, and that you have specified your assets directory correctly.`
);
}
return { manifest, assetsReverseMap };
};
var sortManifest = (manifest) => {
return manifest.sort(comparisonFn);
};
var comparisonFn = (a, b) => {
if (a.pathHash.length < b.pathHash.length) {
return -1;
}
if (a.pathHash.length > b.pathHash.length) {
return 1;
}
for (const [i, v] of a.pathHash.entries()) {
if (v < b.pathHash[i]) {
return -1;
}
if (v > b.pathHash[i]) {
return 1;
}
}
return 1;
};
var encodeManifest = (manifest) => {
const assetManifestBytes = new Uint8Array(
HEADER_SIZE + manifest.length * ENTRY_SIZE
);
for (const [i, entry] of manifest.entries()) {
const entryOffset = HEADER_SIZE + i * ENTRY_SIZE;
assetManifestBytes.set(entry.pathHash, entryOffset + PATH_HASH_OFFSET);
assetManifestBytes.set(
entry.contentHash,
entryOffset + CONTENT_HASH_OFFSET
);
}
return assetManifestBytes;
};
var bytesToHex = (buffer) => {
return [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
};
var hashPath = async (path31) => {
const encoder3 = new TextEncoder();
const data = encoder3.encode(path31);
const hashBuffer = await import_node_crypto.default.subtle.digest(
"SHA-256",
data.buffer
);
return new Uint8Array(hashBuffer, 0, PATH_HASH_SIZE);
};
// src/plugins/d1/index.ts
var import_promises8 = __toESM(require("fs/promises"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/d1/database.worker.ts
var import_fs17 = __toESM(require("fs"));
var import_path20 = __toESM(require("path"));
var import_url17 = __toESM(require("url"));
var contents13;
function database_worker_default() {
if (contents13 !== void 0)
return contents13;
const filePath = import_path20.default.join(__dirname, "workers", "d1/database.worker.js");
contents13 = import_fs17.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url17.default.pathToFileURL(filePath);
return contents13;
}
// src/plugins/d1/index.ts
var import_zod14 = require("zod");
var D1OptionsSchema = import_zod14.z.object({
d1Databases: import_zod14.z.union([import_zod14.z.record(import_zod14.z.string()), import_zod14.z.string().array()]).optional()
});
var D1SharedOptionsSchema = import_zod14.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, new ProxyNodeBinding()])
);
},
async getServices({
options,
sharedOptions,
tmpPath,
log,
unsafeStickyBlobs
}) {
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_promises8.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 }
},
...getMiniflareObjectBindings(unsafeStickyBlobs)
]
}
};
services.push(storageService, objectService);
for (const database of databases) {
await migrateDatabase(log, uniqueKey, persistPath, database[1]);
}
}
return services;
},
getPersistPath({ d1Persist }, tmpPath) {
return getPersistPath(D1_PLUGIN_NAME, tmpPath, d1Persist);
}
};
// src/plugins/hyperdrive/index.ts
var import_node_assert3 = __toESM(require("node:assert"));
var import_zod15 = require("zod");
var HYPERDRIVE_PLUGIN_NAME = "hyperdrive";
function hasPostgresProtocol(url21) {
return url21.protocol === "postgresql:" || url21.protocol === "postgres:";
}
function getPort(url21) {
if (url21.port !== "")
return url21.port;
if (hasPostgresProtocol(url21))
return "5432";
import_node_assert3.default.fail(`Expected known protocol, got ${url21.protocol}`);
}
var HyperdriveSchema = import_zod15.z.union([import_zod15.z.string().url(), import_zod15.z.instanceof(URL)]).transform((url21, ctx) => {
if (typeof url21 === "string")
url21 = new URL(url21);
if (url21.protocol === "") {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "You must specify the database protocol - e.g. 'postgresql'."
});
} else if (!hasPostgresProtocol(url21)) {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "Only PostgreSQL or PostgreSQL compatible databases are currently supported."
});
}
if (url21.host === "") {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "You must provide a hostname or IP address in your connection string - e.g. 'user:password@database-hostname.example.com:5432/databasename"
});
}
if (url21.pathname === "") {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "You must provide a database name as the path component - e.g. /postgres"
});
}
if (url21.username === "") {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "You must provide a username - e.g. 'user:password@database.example.com:port/databasename'"
});
}
if (url21.password === "") {
ctx.addIssue({
code: import_zod15.z.ZodIssueCode.custom,
message: "You must provide a password - e.g. 'user:password@database.example.com:port/databasename' "
});
}
return url21;
});
var HyperdriveInputOptionsSchema = import_zod15.z.object({
hyperdrives: import_zod15.z.record(import_zod15.z.string(), HyperdriveSchema).optional()
});
var HYPERDRIVE_PLUGIN = {
options: HyperdriveInputOptionsSchema,
getBindings(options) {
return Object.entries(options.hyperdrives ?? {}).map(
([name, url21]) => {
const database = url21.pathname.replace("/", "");
const scheme = url21.protocol.replace(":", "");
return {
name,
hyperdrive: {
designator: {
name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`
},
database: decodeURIComponent(database),
user: decodeURIComponent(url21.username),
password: decodeURIComponent(url21.password),
scheme
}
};
}
);
},
getNodeBindings(options) {
return Object.fromEntries(
Object.entries(options.hyperdrives ?? {}).map(([name, url21]) => {
const connectionOverrides = {
connectionString: `${url21}`,
port: Number.parseInt(url21.port),
host: url21.hostname
};
const proxyNodeBinding = new ProxyNodeBinding({
get(target, prop) {
return prop in connectionOverrides ? connectionOverrides[prop] : target[prop];
}
});
return [name, proxyNodeBinding];
})
);
},
async getServices({ options }) {
return Object.entries(options.hyperdrives ?? {}).map(
([name, url21]) => ({
name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`,
external: {
address: `${url21.hostname}:${getPort(url21)}`,
tcp: {}
}
})
);
}
};
// src/plugins/kv/index.ts
var import_promises10 = __toESM(require("fs/promises"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/namespace.worker.ts
var import_fs18 = __toESM(require("fs"));
var import_path21 = __toESM(require("path"));
var import_url18 = __toESM(require("url"));
var contents14;
function namespace_worker_default() {
if (contents14 !== void 0)
return contents14;
const filePath = import_path21.default.join(__dirname, "workers", "kv/namespace.worker.js");
contents14 = import_fs18.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url18.default.pathToFileURL(filePath);
return contents14;
}
// src/plugins/kv/index.ts
var import_zod16 = require("zod");
// src/plugins/kv/constants.ts
var KV_PLUGIN_NAME = "kv";
// src/plugins/kv/sites.ts
var import_assert10 = __toESM(require("assert"));
var import_promises9 = __toESM(require("fs/promises"));
var import_path23 = __toESM(require("path"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/sites.worker.ts
var import_fs19 = __toESM(require("fs"));
var import_path22 = __toESM(require("path"));
var import_url19 = __toESM(require("url"));
var contents15;
function sites_worker_default() {
if (contents15 !== void 0)
return contents15;
const filePath = import_path22.default.join(__dirname, "workers", "kv/sites.worker.js");
contents15 = import_fs19.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url19.default.pathToFileURL(filePath);
return contents15;
}
// src/plugins/kv/sites.ts
async function* listKeysInDirectoryInner(rootPath2, currentPath) {
const fileEntries = await import_promises9.default.readdir(currentPath, { withFileTypes: true });
for (const fileEntry of fileEntries) {
const filePath = import_path23.default.posix.join(currentPath, fileEntry.name);
if (fileEntry.isDirectory()) {
yield* listKeysInDirectoryInner(rootPath2, filePath);
} else {
yield filePath.substring(rootPath2.length + 1);
}
}
}
function listKeysInDirectory(rootPath2) {
rootPath2 = import_path23.default.resolve(rootPath2);
return listKeysInDirectoryInner(rootPath2, rootPath2);
}
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_assert10.default)(siteRegExps !== void 0);
const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
options.sitePath,
siteRegExps
);
return {
[SiteBindings.KV_NAMESPACE_SITE]: new ProxyNodeBinding(),
[SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST
};
}
function getSitesServices(options) {
const siteRegExps = sitesRegExpsCache.get(options);
(0, import_assert10.default)(siteRegExps !== void 0);
const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps);
const persist = import_path23.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];
}
// src/plugins/kv/index.ts
var KVOptionsSchema = import_zod16.z.object({
kvNamespaces: import_zod16.z.union([import_zod16.z.record(import_zod16.z.string()), import_zod16.z.string().array()]).optional(),
// Workers Sites
sitePath: PathSchema.optional(),
siteInclude: import_zod16.z.string().array().optional(),
siteExclude: import_zod16.z.string().array().optional()
});
var KVSharedOptionsSchema = import_zod16.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, new ProxyNodeBinding()])
);
if (isWorkersSitesEnabled(options)) {
Object.assign(bindings, await getSitesNodeBindings(options));
}
return bindings;
},
async getServices({
options,
sharedOptions,
tmpPath,
log,
unsafeStickyBlobs
}) {
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_promises10.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 }
},
...getMiniflareObjectBindings(unsafeStickyBlobs)
]
}
};
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;
},
getPersistPath({ kvPersist }, tmpPath) {
return getPersistPath(KV_PLUGIN_NAME, tmpPath, kvPersist);
}
};
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/pipelines/pipeline.worker.ts
var import_fs20 = __toESM(require("fs"));
var import_path24 = __toESM(require("path"));
var import_url20 = __toESM(require("url"));
var contents16;
function pipeline_worker_default() {
if (contents16 !== void 0)
return contents16;
const filePath = import_path24.default.join(__dirname, "workers", "pipelines/pipeline.worker.js");
contents16 = import_fs20.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url20.default.pathToFileURL(filePath);
return contents16;
}
// src/plugins/pipelines/index.ts
var import_zod17 = require("zod");
var PipelineOptionsSchema = import_zod17.z.object({
pipelines: import_zod17.z.union([import_zod17.z.record(import_zod17.z.string()), import_zod17.z.string().array()]).optional()
});
var PIPELINES_PLUGIN_NAME = "pipelines";
var SERVICE_PIPELINE_PREFIX = `${PIPELINES_PLUGIN_NAME}:pipeline`;
var PIPELINE_PLUGIN = {
options: PipelineOptionsSchema,
getBindings(options) {
const pipelines = bindingEntries(options.pipelines);
return pipelines.map(([name, id]) => ({
name,
service: { name: `${SERVICE_PIPELINE_PREFIX}:${id}` }
}));
},
getNodeBindings(options) {
const buckets = namespaceKeys(options.pipelines);
return Object.fromEntries(
buckets.map((name) => [name, new ProxyNodeBinding()])
);
},
async getServices({ options }) {
const pipelines = bindingEntries(options.pipelines);
const services = [];
for (const pipeline of pipelines) {
services.push({
name: `${SERVICE_PIPELINE_PREFIX}:${pipeline[1]}`,
worker: {
compatibilityDate: "2024-12-30",
modules: [
{
name: "pipeline.worker.js",
esModule: pipeline_worker_default()
}
]
}
});
}
return services;
}
};
function bindingEntries(namespaces) {
if (Array.isArray(namespaces)) {
return namespaces.map((bindingName) => [bindingName, bindingName]);
} else if (namespaces !== void 0) {
return Object.entries(namespaces).map(([name, opts]) => [
name,
typeof opts === "string" ? opts : opts.pipelineName
]);
} else {
return [];
}
}
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/queues/broker.worker.ts
var import_fs21 = __toESM(require("fs"));
var import_path25 = __toESM(require("path"));
var import_url21 = __toESM(require("url"));
var contents17;
function broker_worker_default() {
if (contents17 !== void 0)
return contents17;
const filePath = import_path25.default.join(__dirname, "workers", "queues/broker.worker.js");
contents17 = import_fs21.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url21.default.pathToFileURL(filePath);
return contents17;
}
// src/plugins/queues/index.ts
var import_zod18 = require("zod");
// src/plugins/queues/errors.ts
var QueuesError = class extends MiniflareError {
};
// src/plugins/queues/index.ts
var QueuesOptionsSchema = import_zod18.z.object({
queueProducers: import_zod18.z.union([
import_zod18.z.record(QueueProducerOptionsSchema),
import_zod18.z.string().array(),
import_zod18.z.record(import_zod18.z.string())
]).optional(),
queueConsumers: import_zod18.z.union([import_zod18.z.record(QueueConsumerOptionsSchema), import_zod18.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 = bindingEntries2(options.queueProducers);
return queues.map(([name, id]) => ({
name,
queue: { name: `${SERVICE_QUEUE_PREFIX}:${id}` }
}));
},
getNodeBindings(options) {
const queues = bindingKeys(options.queueProducers);
return Object.fromEntries(
queues.map((name) => [name, new ProxyNodeBinding()])
);
},
async getServices({
options,
workerNames,
queueProducers: allQueueProducers,
queueConsumers: allQueueConsumers,
unsafeStickyBlobs
}) {
const queues = bindingEntries2(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,
preventEviction: true
}
],
// Miniflare's Queue broker is in-memory only at the moment
durableObjectStorage: { inMemory: kVoid },
bindings: [
{
name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
service: { name: SERVICE_LOOPBACK }
},
...getMiniflareObjectBindings(unsafeStickyBlobs),
{
name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
durableObjectNamespace: {
className: QUEUE_BROKER_OBJECT_CLASS_NAME
}
},
{
name: QueueBindings.MAYBE_JSON_QUEUE_PRODUCERS,
json: JSON.stringify(Object.fromEntries(allQueueProducers))
},
{
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;
}
};
function bindingEntries2(namespaces) {
if (Array.isArray(namespaces)) {
return namespaces.map((bindingName) => [bindingName, bindingName]);
} else if (namespaces !== void 0) {
return Object.entries(namespaces).map(([name, opts]) => [
name,
typeof opts === "string" ? opts : opts.queueName
]);
} else {
return [];
}
}
function bindingKeys(namespaces) {
if (Array.isArray(namespaces)) {
return namespaces;
} else if (namespaces !== void 0) {
return Object.keys(namespaces);
} else {
return [];
}
}
// src/plugins/r2/index.ts
var import_promises11 = __toESM(require("fs/promises"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/bucket.worker.ts
var import_fs22 = __toESM(require("fs"));
var import_path26 = __toESM(require("path"));
var import_url22 = __toESM(require("url"));
var contents18;
function bucket_worker_default() {
if (contents18 !== void 0)
return contents18;
const filePath = import_path26.default.join(__dirname, "workers", "r2/bucket.worker.js");
contents18 = import_fs22.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url22.default.pathToFileURL(filePath);
return contents18;
}
// src/plugins/r2/index.ts
var import_zod19 = require("zod");
var R2OptionsSchema = import_zod19.z.object({
r2Buckets: import_zod19.z.union([import_zod19.z.record(import_zod19.z.string()), import_zod19.z.string().array()]).optional()
});
var R2SharedOptionsSchema = import_zod19.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, new ProxyNodeBinding()])
);
},
async getServices({
options,
sharedOptions,
tmpPath,
log,
unsafeStickyBlobs
}) {
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_promises11.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 }
},
...getMiniflareObjectBindings(unsafeStickyBlobs)
]
}
};
services.push(storageService, objectService);
for (const bucket of buckets) {
await migrateDatabase(log, uniqueKey, persistPath, bucket[1]);
}
}
return services;
},
getPersistPath({ r2Persist }, tmpPath) {
return getPersistPath(R2_PLUGIN_NAME, tmpPath, r2Persist);
}
};
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/ratelimit/ratelimit.worker.ts
var import_fs23 = __toESM(require("fs"));
var import_path27 = __toESM(require("path"));
var import_url23 = __toESM(require("url"));
var contents19;
function ratelimit_worker_default() {
if (contents19 !== void 0)
return contents19;
const filePath = import_path27.default.join(__dirname, "workers", "ratelimit/ratelimit.worker.js");
contents19 = import_fs23.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url23.default.pathToFileURL(filePath);
return contents19;
}
// src/plugins/ratelimit/index.ts
var import_zod20 = require("zod");
var PeriodType = /* @__PURE__ */ ((PeriodType2) => {
PeriodType2[PeriodType2["TENSECONDS"] = 10] = "TENSECONDS";
PeriodType2[PeriodType2["MINUTE"] = 60] = "MINUTE";
return PeriodType2;
})(PeriodType || {});
var RatelimitConfigSchema = import_zod20.z.object({
simple: import_zod20.z.object({
limit: import_zod20.z.number().gt(0),
// may relax this to be any number in the future
period: import_zod20.z.nativeEnum(PeriodType).optional()
})
});
var RatelimitOptionsSchema = import_zod20.z.object({
ratelimits: import_zod20.z.record(RatelimitConfigSchema).optional()
});
var RATELIMIT_PLUGIN_NAME = "ratelimit";
var SERVICE_RATELIMIT_PREFIX = `${RATELIMIT_PLUGIN_NAME}`;
var SERVICE_RATELIMIT_MODULE = `cloudflare-internal:${SERVICE_RATELIMIT_PREFIX}:module`;
function buildJsonBindings(bindings) {
return Object.entries(bindings).map(([name, value]) => ({
name,
json: JSON.stringify(value)
}));
}
var RATELIMIT_PLUGIN = {
options: RatelimitOptionsSchema,
getBindings(options) {
if (!options.ratelimits) {
return [];
}
const bindings = Object.entries(options.ratelimits).map(
([name, config]) => ({
name,
wrapped: {
moduleName: SERVICE_RATELIMIT_MODULE,
innerBindings: buildJsonBindings({
namespaceId: name,
limit: config.simple.limit,
period: config.simple.period
})
}
})
);
return bindings;
},
getNodeBindings(options) {
if (!options.ratelimits) {
return {};
}
return Object.fromEntries(
Object.keys(options.ratelimits).map((name) => [
name,
new ProxyNodeBinding()
])
);
},
async getServices({ options }) {
if (!options.ratelimits) {
return [];
}
return {
services: [],
extensions: [
{
modules: [
{
name: SERVICE_RATELIMIT_MODULE,
esModule: ratelimit_worker_default(),
internal: true
}
]
}
]
};
}
};
// src/plugins/workflows/index.ts
var import_promises12 = __toESM(require("fs/promises"));
// embed-worker:/home/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/workflows/binding.worker.ts
var import_fs24 = __toESM(require("fs"));
var import_path28 = __toESM(require("path"));
var import_url24 = __toESM(require("url"));
var contents20;
function binding_worker_default() {
if (contents20 !== void 0)
return contents20;
const filePath = import_path28.default.join(__dirname, "workers", "workflows/binding.worker.js");
contents20 = import_fs24.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url24.default.pathToFileURL(filePath);
return contents20;
}
// src/plugins/workflows/index.ts
var import_zod21 = require("zod");
var WorkflowsOptionsSchema = import_zod21.z.object({
workflows: import_zod21.z.record(
import_zod21.z.object({
name: import_zod21.z.string(),
className: import_zod21.z.string(),
scriptName: import_zod21.z.string().optional()
})
).optional()
});
var WorkflowsSharedOptionsSchema = import_zod21.z.object({
workflowsPersist: PersistenceSchema
});
var WORKFLOWS_PLUGIN_NAME = "workflows";
var WORKFLOWS_STORAGE_SERVICE_NAME = `${WORKFLOWS_PLUGIN_NAME}:storage`;
var WORKFLOWS_PLUGIN = {
options: WorkflowsOptionsSchema,
sharedOptions: WorkflowsSharedOptionsSchema,
async getBindings(options) {
return Object.entries(options.workflows ?? {}).map(
([bindingName, workflow]) => ({
name: bindingName,
service: {
name: `${WORKFLOWS_PLUGIN_NAME}:${workflow.name}`,
entrypoint: "WorkflowBinding"
}
})
);
},
async getNodeBindings(options) {
return Object.fromEntries(
Object.keys(options.workflows ?? {}).map((bindingName) => [
bindingName,
new ProxyNodeBinding()
])
);
},
async getServices({ options, sharedOptions, tmpPath }) {
const persistPath = getPersistPath(
WORKFLOWS_PLUGIN_NAME,
tmpPath,
sharedOptions.workflowsPersist
);
await import_promises12.default.mkdir(persistPath, { recursive: true });
const storageServices = Object.entries(
options.workflows ?? {}
).map(([_, workflow]) => ({
name: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${workflow.name}`,
disk: { path: persistPath, writable: true }
}));
const services = Object.entries(options.workflows ?? {}).map(
([_bindingName, workflow]) => {
const uniqueKey = `miniflare-workflows-${workflow.name}`;
const workflowsBinding = {
name: `${WORKFLOWS_PLUGIN_NAME}:${workflow.name}`,
worker: {
compatibilityDate: "2024-10-22",
modules: [
{
name: "workflows.mjs",
esModule: binding_worker_default()
}
],
durableObjectNamespaces: [
{
className: "Engine",
enableSql: true,
uniqueKey,
preventEviction: true
}
],
durableObjectStorage: {
localDisk: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${workflow.name}`
},
bindings: [
{
name: "ENGINE",
durableObjectNamespace: { className: "Engine" }
},
{
name: "USER_WORKFLOW",
service: {
name: getUserServiceName(workflow.scriptName),
entrypoint: workflow.className
}
}
]
}
};
return workflowsBinding;
}
);
if (services.length === 0) {
return [];
}
return [...storageServices, ...services];
},
getPersistPath({ workflowsPersist }, tmpPath) {
return getPersistPath(WORKFLOWS_PLUGIN_NAME, tmpPath, workflowsPersist);
}
};
// 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,
[HYPERDRIVE_PLUGIN_NAME]: HYPERDRIVE_PLUGIN,
[RATELIMIT_PLUGIN_NAME]: RATELIMIT_PLUGIN,
[ASSETS_PLUGIN_NAME]: ASSETS_PLUGIN,
[WORKFLOWS_PLUGIN_NAME]: WORKFLOWS_PLUGIN,
[PIPELINES_PLUGIN_NAME]: PIPELINE_PLUGIN
};
var PLUGIN_ENTRIES = Object.entries(PLUGINS);
// src/shared/mime-types.ts
var compressedByCloudflareFL = /* @__PURE__ */ new Set([
// list copied from https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/#:~:text=If%20supported%20by%20visitors%E2%80%99%20web%20browsers%2C%20Cloudflare%20will%20return%20Gzip%20or%20Brotli%2Dencoded%20responses%20for%20the%20following%20content%20types%3A
"text/html",
"text/richtext",
"text/plain",
"text/css",
"text/x-script",
"text/x-component",
"text/x-java-source",
"text/x-markdown",
"application/javascript",
"application/x-javascript",
"text/javascript",
"text/js",
"image/x-icon",
"image/vnd.microsoft.icon",
"application/x-perl",
"application/x-httpd-cgi",
"text/xml",
"application/xml",
"application/rss+xml",
"application/vnd.api+json",
"application/x-protobuf",
"application/json",
"multipart/bag",
"multipart/mixed",
"application/xhtml+xml",
"font/ttf",
"font/otf",
"font/x-woff",
"image/svg+xml",
"application/vnd.ms-fontobject",
"application/ttf",
"application/x-ttf",
"application/otf",
"application/x-otf",
"application/truetype",
"application/opentype",
"application/x-opentype",
"application/font-woff",
"application/eot",
"application/font",
"application/font-sfnt",
"application/wasm",
"application/javascript-binast",
"application/manifest+json",
"application/ld+json",
"application/graphql+json",
"application/geo+json"
]);
function isCompressedByCloudflareFL(contentTypeHeader) {
if (!contentTypeHeader)
return true;
const [contentType] = contentTypeHeader.split(";");
return compressedByCloudflareFL.has(contentType);
}
// src/zod-format.ts
var import_assert11 = __toESM(require("assert"));
var import_util4 = __toESM(require("util"));
var kMessages = Symbol("kMessages");
var kActual = Symbol("kActual");
var kGroupId = Symbol("kGroupId");
var groupColours = [
yellow2,
/* (green) */
cyan,
blue2,
magenta,
green2
];
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, path31, groupId) {
if (path31.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_assert11.default)(current !== void 0);
groupCounts.set(groupId, current + 1);
}
return {
[kMessages]: [message],
[kActual]: input,
[kGroupId]: groupId
};
}
const [head, ...tail] = path31;
(0, import_assert11.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_assert11.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 = red2;
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_assert11.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}${dim2(prefix)}${actualIndented}${dim2(suffix)}
${error}`;
} else if (Array.isArray(annotated)) {
let result = `${indent}${dim2(`${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}${dim2("...,")}
`;
}
if (value !== void 0) {
result += print(inspectOptions, groupCounts, value, arrayIndent, {
prefix: `/* [${i}] */ `,
suffix: ","
});
result += "\n";
}
}
result += `${indent}${dim2(`]${suffix}`)}`;
return result;
} else if (isRecord(annotated)) {
let result = `${indent}${dim2(`${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}${dim2("...,")}
`;
}
if (value !== void 0) {
result += print(inspectOptions, groupCounts, value, objectIndent, {
prefix: `${key}: `,
suffix: ","
});
result += "\n";
}
}
result += `${indent}${dim2(`}${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);
}
// src/merge.ts
var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function isPlainObject(value) {
const proto2 = Object.getPrototypeOf(value);
return proto2 === Object.prototype || proto2 === null || Object.getOwnPropertyNames(proto2).sort().join("\0") === objectProtoNames;
}
function convertWorkerOptionsArrayToObject(key, array) {
const _ = array;
if (key === "queueConsumers") {
const object = Object.fromEntries(
array.map((item) => [item, {}])
);
return object;
} else {
const object = Object.fromEntries(array.map((item) => [item, item]));
return object;
}
}
function mergeWorkerOptions(a, b) {
const aRecord = a;
for (const [key, bValue] of Object.entries(b)) {
const aValue = aRecord[key];
if (aValue === void 0) {
aRecord[key] = bValue;
continue;
}
const aIsArray = Array.isArray(aValue);
const bIsArray = Array.isArray(bValue);
const aIsObject = isPlainObject(aValue);
const bIsObject = isPlainObject(bValue);
if (aIsArray && bIsArray) {
aRecord[key] = Array.from(new Set(aValue.concat(bValue)));
} else if (aIsArray && bIsObject) {
const aNewValue = convertWorkerOptionsArrayToObject(
// Must be an array/record key if `aValue` & `bValue` are array/record
key,
aValue
);
Object.assign(aNewValue, bValue);
aRecord[key] = aNewValue;
} else if (aIsObject && bIsArray) {
const bNewValue = convertWorkerOptionsArrayToObject(
// Must be an array/record key if `aValue` & `bValue` are array/record
key,
bValue
);
Object.assign(aValue, bNewValue);
} else if (aIsObject && bIsObject) {
Object.assign(aValue, bValue);
} else {
aRecord[key] = bValue;
}
}
return a;
}
// src/index.ts
var DEFAULT_HOST = "127.0.0.1";
function getURLSafeHost(host) {
return import_net.default.isIPv6(host) ? `[${host}]` : host;
}
function maybeGetLocallyAccessibleHost(h) {
if (h === "localhost")
return "localhost";
if (h === "127.0.0.1" || h === "*" || h === "0.0.0.0" || h === "::") {
return "127.0.0.1";
}
if (h === "::1")
return "[::1]";
}
function getServerPort(server) {
const address = server.address();
(0, import_assert12.default)(address !== null && typeof address === "object");
return address.port;
}
function hasMultipleWorkers(opts) {
return typeof opts === "object" && opts !== null && "workers" in opts && Array.isArray(opts.workers);
}
function getRootPath(opts) {
if (typeof opts === "object" && opts !== null && "rootPath" in opts && typeof opts.rootPath === "string") {
return opts.rootPath;
} else {
return "";
}
}
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(
() => ({})
);
const sharedRootPath = multipleWorkers ? getRootPath(sharedOpts) : "";
const workerRootPaths = workerOpts.map(
(opts2) => import_path29.default.resolve(sharedRootPath, getRootPath(opts2))
);
try {
for (const [key, plugin] of PLUGIN_ENTRIES) {
pluginSharedOpts[key] = plugin.sharedOptions === void 0 ? void 0 : parseWithRootPath(sharedRootPath, plugin.sharedOptions, sharedOpts);
for (let i = 0; i < workerOpts.length; i++) {
const optionsPath = multipleWorkers ? ["workers", i] : void 0;
pluginWorkerOpts[i][key] = parseWithRootPath(
workerRootPaths[i],
plugin.options,
workerOpts[i],
{ path: optionsPath }
);
}
}
} catch (e) {
if (e instanceof import_zod23.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,
...doConfigs
} = normaliseDurableObject(designator);
let classNames = serviceClassNames.get(serviceName);
if (classNames === void 0) {
classNames = /* @__PURE__ */ new Map();
serviceClassNames.set(serviceName, classNames);
}
if (classNames.has(className)) {
const existingInfo = classNames.get(className);
const isDoUnacceptableDiff = (field) => {
if (!existingInfo) {
return false;
}
const same = existingInfo[field] === doConfigs[field];
if (same) {
return false;
}
const oneIsUndefined = existingInfo[field] === void 0 || doConfigs[field] === void 0;
if (oneIsUndefined) {
return false;
}
return true;
};
if (isDoUnacceptableDiff("enableSql")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_STORAGE_BACKEND",
`Different storage backends defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.enableSql
)} and ${JSON.stringify(existingInfo?.enableSql)}`
);
}
if (isDoUnacceptableDiff("unsafeUniqueKey")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_UNIQUE_KEYS",
`Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.unsafeUniqueKey
)} and ${JSON.stringify(existingInfo?.unsafeUniqueKey)}`
);
}
if (isDoUnacceptableDiff("unsafePreventEviction")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_PREVENT_EVICTION",
`Multiple unsafe prevent eviction values defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.unsafePreventEviction
)} and ${JSON.stringify(existingInfo?.unsafePreventEviction)}`
);
}
} else {
classNames.set(className, {
enableSql: doConfigs.enableSql,
unsafeUniqueKey: doConfigs.unsafeUniqueKey,
unsafePreventEviction: doConfigs.unsafePreventEviction
});
}
}
}
return serviceClassNames;
}
function invalidWrappedAsBound(name, bindingType) {
const stringName = JSON.stringify(name);
throw new MiniflareCoreError(
"ERR_INVALID_WRAPPED",
`Cannot use ${stringName} for wrapped binding because it is bound to with ${bindingType} bindings.
Ensure other workers don't define ${bindingType} bindings to ${stringName}.`
);
}
function getWrappedBindingNames(allWorkerOpts, durableObjectClassNames) {
const wrappedBindingWorkerNames = /* @__PURE__ */ new Set();
for (const workerOpts of allWorkerOpts) {
for (const designator of Object.values(
workerOpts.core.wrappedBindings ?? {}
)) {
const scriptName = typeof designator === "object" ? designator.scriptName : designator;
if (durableObjectClassNames.has(getUserServiceName(scriptName))) {
invalidWrappedAsBound(scriptName, "Durable Object");
}
wrappedBindingWorkerNames.add(scriptName);
}
}
for (const workerOpts of allWorkerOpts) {
for (const designator of Object.values(
workerOpts.core.serviceBindings ?? {}
)) {
if (typeof designator !== "string")
continue;
if (wrappedBindingWorkerNames.has(designator)) {
invalidWrappedAsBound(designator, "service");
}
}
}
return wrappedBindingWorkerNames;
}
function getQueueProducers(allWorkerOpts) {
const queueProducers = /* @__PURE__ */ new Map();
for (const workerOpts of allWorkerOpts) {
const workerName = workerOpts.core.name ?? "";
let workerProducers = workerOpts.queues.queueProducers;
if (workerProducers !== void 0) {
if (Array.isArray(workerProducers)) {
workerProducers = Object.fromEntries(
workerProducers.map((bindingName) => [
bindingName,
{ queueName: bindingName }
])
);
}
const producersIterable = Object.entries(
workerProducers
);
for (const [bindingName, opts] of producersIterable) {
if (typeof opts === "string") {
queueProducers.set(bindingName, { workerName, queueName: opts });
} else {
queueProducers.set(bindingName, { workerName, ...opts });
}
}
}
}
return queueProducers;
}
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, wrappedBindingNames) {
const allRoutes = /* @__PURE__ */ new Map();
for (const workerOpts of allWorkerOpts) {
const name = workerOpts.core.name ?? "";
if (wrappedBindingNames.has(name))
continue;
(0, import_assert12.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_assert12.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_assert12.default)(service.worker !== void 0);
const serviceName = service.name;
(0, import_assert12.default)(serviceName !== void 0);
return service.worker.durableObjectNamespaces?.map(({ className }) => {
(0, import_assert12.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 _transformsForContentEncodingAndContentType(encoding, type) {
const encoders = [];
if (!encoding)
return encoders;
if (!isCompressedByCloudflareFL(type))
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 type = headers["content-type"]?.toString();
const encoders = _transformsForContentEncodingAndContentType(encoding, type);
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?.();
}
});
}
var maybeInstanceRegistry;
function _initialiseInstanceRegistry() {
return maybeInstanceRegistry = /* @__PURE__ */ new Map();
}
var Miniflare2 = class {
#previousSharedOpts;
#previousWorkerOpts;
#sharedOpts;
#workerOpts;
#log;
#runtime;
#removeExitHook;
#runtimeEntryURL;
#socketPorts;
#runtimeDispatcher;
#proxyClient;
#structuredWorkerdLogs;
#cfObject = {};
// 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;
// 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;
#loopbackHost;
#liveReloadServer;
#webSocketServer;
#webSocketExtraHeaders;
constructor(opts) {
const [sharedOpts, workerOpts] = validateOptions(opts);
checkMacOSVersion({ shouldThrow: true });
this.#sharedOpts = sharedOpts;
this.#workerOpts = workerOpts;
if (maybeInstanceRegistry !== void 0) {
const object = { name: "Miniflare", stack: "" };
Error.captureStackTrace(object, Miniflare2);
maybeInstanceRegistry.set(this, object.stack);
}
this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
this.#structuredWorkerdLogs = this.#sharedOpts.core.structuredWorkerdLogs ?? false;
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_path29.default.join(
import_os2.default.tmpdir(),
`miniflare-${import_crypto3.default.randomBytes(16).toString("hex")}`
);
this.#runtime = new Runtime();
this.#removeExitHook = (0, import_exit_hook.default)(() => {
void this.#runtime?.dispose();
try {
import_fs25.default.rmSync(this.#tmpPath, { force: true, recursive: true });
} catch (e) {
this.#log.debug(`Unable to remove temporary directory: ${String(e)}`);
}
});
this.#disposeController = new AbortController();
this.#runtimeMutex = new Mutex();
this.#initPromise = this.#runtimeMutex.runWith(() => this.#assembleAndUpdateConfig()).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 #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_assert12.default)(typeof service === "function");
try {
let response = await service(request, this);
if (!(response instanceof Response)) {
response = new Response(response.body, response);
}
return import_zod23.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_undici4.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(CoreHeaders.CF_BLOB);
headers.delete(CoreHeaders.CF_BLOB);
(0, import_assert12.default)(!Array.isArray(cfBlob));
const cf = cfBlob ? JSON.parse(cfBlob) : void 0;
const originalUrl = headers.get(CoreHeaders.ORIGINAL_URL);
const url21 = new URL(originalUrl ?? 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(url21, {
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 (this.#sharedOpts.core.unsafeModuleFallbackService !== void 0 && request.headers.has("X-Resolve-Method") && originalUrl === null) {
response = await this.#sharedOpts.core.unsafeModuleFallbackService(
request,
this
);
} else if (url21.pathname === "/core/error") {
response = await handlePrettyErrorRequest(
this.#log,
this.#workerSrcOpts,
request
);
} else if (url21.pathname === "/core/log") {
const level = parseInt(request.headers.get(SharedHeaders.LOG_LEVEL));
(0, import_assert12.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_http6.default.ServerResponse(req);
(0, import_assert12.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);
};
async #getLoopbackPort() {
const loopbackHost = this.#sharedOpts.core.host ?? DEFAULT_HOST;
if (this.#loopbackServer !== void 0) {
if (this.#loopbackHost === loopbackHost) {
return getServerPort(this.#loopbackServer);
}
await this.#stopLoopbackServer();
}
this.#loopbackServer = await this.#startLoopbackServer(loopbackHost);
this.#loopbackHost = loopbackHost;
return getServerPort(this.#loopbackServer);
}
#startLoopbackServer(hostname) {
if (hostname === "*")
hostname = "::";
return new Promise((resolve2) => {
const server = (0, import_stoppable.default)(
import_http6.default.createServer(this.#handleLoopback),
/* grace */
0
);
server.on("upgrade", this.#handleLoopbackUpgrade);
server.listen(0, hostname, () => resolve2(server));
});
}
#stopLoopbackServer() {
return new Promise((resolve2, reject) => {
(0, import_assert12.default)(this.#loopbackServer !== void 0);
this.#loopbackServer.stop((err) => err ? reject(err) : resolve2());
});
}
#getSocketAddress(id, previousRequestedPort, host = DEFAULT_HOST, requestedPort) {
if (requestedPort === 0 && previousRequestedPort === 0) {
requestedPort = this.#socketPorts?.get(id);
}
return `${getURLSafeHost(host)}:${requestedPort ?? 0}`;
}
async #assembleConfig(loopbackPort) {
const allPreviousWorkerOpts = this.#previousWorkerOpts;
const allWorkerOpts = this.#workerOpts;
const sharedOpts = this.#sharedOpts;
sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf);
this.#cfObject = sharedOpts.core.cf;
const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts);
const wrappedBindingNames = getWrappedBindingNames(
allWorkerOpts,
durableObjectClassNames
);
const queueProducers = getQueueProducers(allWorkerOpts);
const queueConsumers = getQueueConsumers(allWorkerOpts);
const allWorkerRoutes = getWorkerRoutes(allWorkerOpts, wrappedBindingNames);
const workerNames = [...allWorkerRoutes.keys()];
const services = /* @__PURE__ */ new Map();
const extensions = [
{
modules: [
{ name: "miniflare:shared", esModule: index_worker_default() },
{ name: "miniflare:zod", esModule: zod_worker_default() }
]
}
];
const sockets = [
{
name: SOCKET_ENTRY,
service: { name: SERVICE_ENTRY },
...await getEntrySocketHttpOptions(sharedOpts.core)
}
];
const configuredHost = sharedOpts.core.host ?? DEFAULT_HOST;
if (maybeGetLocallyAccessibleHost(configuredHost) === void 0) {
sockets.push({
name: SOCKET_ENTRY_LOCAL,
service: { name: SERVICE_ENTRY },
http: {},
address: "127.0.0.1:0"
});
}
const proxyBindings = [];
const allWorkerBindings = /* @__PURE__ */ new Map();
const wrappedBindingsToPopulate = [];
for (let i = 0; i < allWorkerOpts.length; i++) {
const previousWorkerOpts = allPreviousWorkerOpts?.[i];
const workerOpts = allWorkerOpts[i];
const workerName = workerOpts.core.name ?? "";
const isModulesWorker = Boolean(workerOpts.core.modules);
if (workerOpts.workflows.workflows) {
for (const workflow of Object.values(workerOpts.workflows.workflows)) {
workflow.scriptName ??= workerOpts.core.name;
}
}
if (workerOpts.assets.assets) {
workerOpts.assets.assets.workerName = workerOpts.core.name;
}
const workerBindings = [];
allWorkerBindings.set(workerName, 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) {
if (key === "kv" && binding.name === SiteBindings.JSON_SITE_MANIFEST && isModulesWorker) {
(0, import_assert12.default)("json" in binding && binding.json !== void 0);
additionalModules.push({
name: SiteBindings.JSON_SITE_MANIFEST,
text: binding.json
});
} else {
workerBindings.push(binding);
}
if (isNativeTargetBinding(binding)) {
proxyBindings.push(buildProxyBinding(key, workerName, binding));
}
if ("wrapped" in binding && binding.wrapped?.moduleName !== void 0 && binding.wrapped.innerBindings !== void 0) {
const workerName2 = maybeWrappedModuleToWorkerName(
binding.wrapped.moduleName
);
if (workerName2 !== void 0) {
wrappedBindingsToPopulate.push({
workerName: workerName2,
innerBindings: binding.wrapped.innerBindings
});
}
}
if ("service" in binding) {
const targetWorkerName = binding.service?.name?.replace(
"core:user:",
""
);
const maybeAssetTargetService = allWorkerOpts.find(
(worker) => worker.core.name === targetWorkerName && worker.assets.assets
);
if (maybeAssetTargetService && !binding.service?.entrypoint) {
(0, import_assert12.default)(binding.service?.name);
binding.service.name = this.#sharedOpts.core.unsafeEnableAssetsRpc ? `${RPC_PROXY_SERVICE_NAME}:${targetWorkerName}` : `${ROUTER_SERVICE_NAME}:${targetWorkerName}`;
}
}
}
}
}
const unsafeStickyBlobs = sharedOpts.core.unsafeStickyBlobs ?? false;
const unsafeEnableAssetsRpc = sharedOpts.core.unsafeEnableAssetsRpc ?? false;
const unsafeEphemeralDurableObjects = workerOpts.core.unsafeEphemeralDurableObjects ?? false;
const pluginServicesOptionsBase = {
log: this.#log,
workerBindings,
workerIndex: i,
additionalModules,
tmpPath: this.#tmpPath,
workerNames,
loopbackPort,
unsafeStickyBlobs,
wrappedBindingNames,
durableObjectClassNames,
unsafeEphemeralDurableObjects,
queueProducers,
queueConsumers,
unsafeEnableAssetsRpc
};
for (const [key, plugin] of PLUGIN_ENTRIES) {
const pluginServicesExtensions = 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 (pluginServicesExtensions !== void 0) {
let pluginServices;
if (Array.isArray(pluginServicesExtensions)) {
pluginServices = pluginServicesExtensions;
} else {
pluginServices = pluginServicesExtensions.services;
extensions.push(...pluginServicesExtensions.extensions);
}
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 previousDirectSockets = previousWorkerOpts?.core.unsafeDirectSockets ?? [];
const directSockets = workerOpts.core.unsafeDirectSockets ?? [];
for (let j = 0; j < directSockets.length; j++) {
const previousDirectSocket = previousDirectSockets[j];
const directSocket = directSockets[j];
const entrypoint = directSocket.entrypoint ?? "default";
const name = getDirectSocketName(i, entrypoint);
const address = this.#getSocketAddress(
name,
previousDirectSocket?.port,
directSocket.host,
directSocket.port
);
sockets.push({
name,
address,
service: {
name: getUserServiceName(workerName),
entrypoint: entrypoint === "default" ? void 0 : entrypoint
},
http: {
style: directSocket.proxy ? HttpOptions_Style.PROXY : void 0,
cfBlobHeader: CoreHeaders.CF_BLOB,
capnpConnectHost: HOST_CAPNP_CONNECT
}
});
}
}
const globalServices = getGlobalServices({
sharedOptions: sharedOpts.core,
allWorkerRoutes,
/*
* - if Workers + Assets project but NOT Vitest, point to Router Worker or
* Proxy Worker depending on whether experimental flag `unsafeEnableAssetsRpc`
* was set
* - if Vitest with assets, the self binding on the test runner will point to
* Router Worker
*/
fallbackWorkerName: this.#workerOpts[0].assets.assets && !this.#workerOpts[0].core.name?.startsWith(
"vitest-pool-workers-runner-"
) ? this.#sharedOpts.core.unsafeEnableAssetsRpc ? `${RPC_PROXY_SERVICE_NAME}:${this.#workerOpts[0].core.name}` : `${ROUTER_SERVICE_NAME}:${this.#workerOpts[0].core.name}` : getUserServiceName(this.#workerOpts[0].core.name),
loopbackPort,
log: this.#log,
proxyBindings
});
for (const service of globalServices) {
(0, import_assert12.default)(service.name !== void 0 && !services.has(service.name));
services.set(service.name, service);
}
for (const toPopulate of wrappedBindingsToPopulate) {
const bindings = allWorkerBindings.get(toPopulate.workerName);
if (bindings === void 0)
continue;
const existingBindingNames = new Set(
toPopulate.innerBindings.map(({ name }) => name)
);
toPopulate.innerBindings.push(
...bindings.filter(({ name }) => !existingBindingNames.has(name))
);
}
const servicesArray = Array.from(services.values());
if (wrappedBindingsToPopulate.length > 0 && _isCyclic(servicesArray)) {
throw new MiniflareCoreError(
"ERR_CYCLIC",
"Generated workerd config contains cycles. Ensure wrapped bindings don't have bindings to themselves."
);
}
return {
services: servicesArray,
sockets,
extensions,
structuredLogging: this.#structuredWorkerdLogs
};
}
async #assembleAndUpdateConfig() {
const initial = !this.#runtimeEntryURL;
(0, import_assert12.default)(this.#runtime !== void 0);
const loopbackPort = await this.#getLoopbackPort();
const config = await this.#assembleConfig(loopbackPort);
const configBuffer = serializeConfig(config);
(0, import_assert12.default)(config.sockets !== void 0);
const requiredSockets = config.sockets.map(
({ name }) => {
(0, import_assert12.default)(name !== void 0);
return name;
}
);
if (this.#sharedOpts.core.inspectorPort !== void 0) {
requiredSockets.push(kInspectorSocket);
}
const configuredHost = this.#sharedOpts.core.host ?? DEFAULT_HOST;
const entryAddress = this.#getSocketAddress(
SOCKET_ENTRY,
this.#previousSharedOpts?.core.port,
configuredHost,
this.#sharedOpts.core.port
);
let inspectorAddress;
if (this.#sharedOpts.core.inspectorPort !== void 0) {
inspectorAddress = this.#getSocketAddress(
kInspectorSocket,
this.#previousSharedOpts?.core.inspectorPort,
"localhost",
this.#sharedOpts.core.inspectorPort
);
}
const loopbackAddress = `${maybeGetLocallyAccessibleHost(configuredHost) ?? getURLSafeHost(configuredHost)}:${loopbackPort}`;
const runtimeOpts = {
signal: this.#disposeController.signal,
entryAddress,
loopbackAddress,
requiredSockets,
inspectorAddress,
verbose: this.#sharedOpts.core.verbose,
handleRuntimeStdio: this.#sharedOpts.core.handleRuntimeStdio
};
const maybeSocketPorts = await this.#runtime.updateConfig(
configBuffer,
runtimeOpts
);
if (this.#disposeController.signal.aborted)
return;
if (maybeSocketPorts === void 0) {
throw new MiniflareCoreError(
"ERR_RUNTIME_FAILURE",
"The Workers runtime failed to start. There is likely additional logging output above."
);
}
this.#socketPorts = maybeSocketPorts;
const entrySocket = config.sockets?.[0];
const secure = entrySocket !== void 0 && "https" in entrySocket;
const previousEntryURL = this.#runtimeEntryURL;
const entryPort = maybeSocketPorts.get(SOCKET_ENTRY);
(0, import_assert12.default)(entryPort !== void 0);
const maybeAccessibleHost = maybeGetLocallyAccessibleHost(configuredHost);
if (maybeAccessibleHost === void 0) {
const localEntryPort = maybeSocketPorts.get(SOCKET_ENTRY_LOCAL);
(0, import_assert12.default)(localEntryPort !== void 0, "Expected local entry socket port");
this.#runtimeEntryURL = new URL(`http://127.0.0.1:${localEntryPort}`);
} else {
this.#runtimeEntryURL = new URL(
`${secure ? "https" : "http"}://${maybeAccessibleHost}:${entryPort}`
);
}
if (previousEntryURL?.toString() !== this.#runtimeEntryURL.toString()) {
this.#runtimeDispatcher = new import_undici8.Pool(this.#runtimeEntryURL, {
connect: { rejectUnauthorized: false }
});
}
if (this.#proxyClient === void 0) {
this.#proxyClient = new ProxyClient(
this.#runtimeEntryURL,
this.dispatchFetch
);
} else {
this.#proxyClient.setRuntimeEntryURL(this.#runtimeEntryURL);
}
if (!this.#runtimeMutex.hasWaiting) {
const ready = initial ? "Ready" : "Updated and ready";
const urlSafeHost = getURLSafeHost(configuredHost);
this.#log.info(
`${ready} on ${secure ? "https" : "http"}://${urlSafeHost}:${entryPort}`
);
if (initial) {
const hosts = [];
if (configuredHost === "::" || configuredHost === "*") {
hosts.push("localhost");
hosts.push("[::1]");
}
if (configuredHost === "::" || configuredHost === "*" || configuredHost === "0.0.0.0") {
hosts.push(...getAccessibleHosts(true));
}
for (const h of hosts) {
this.#log.info(`- ${secure ? "https" : "http"}://${h}:${entryPort}`);
}
}
this.#handleReload();
}
}
async #waitForReady(disposing = false) {
await this.#initPromise;
await this.#runtimeMutex.drained();
if (disposing)
return new URL("http://[100::]/");
this.#checkDisposed();
(0, import_assert12.default)(this.#runtimeEntryURL !== void 0);
return new URL(this.#runtimeEntryURL.toString());
}
get ready() {
return this.#waitForReady();
}
async getCf() {
this.#checkDisposed();
await this.ready;
return JSON.parse(JSON.stringify(this.#cfObject));
}
async getInspectorURL() {
this.#checkDisposed();
await this.ready;
(0, import_assert12.default)(this.#socketPorts !== void 0);
const maybePort = this.#socketPorts.get(kInspectorSocket);
if (maybePort === void 0) {
throw new TypeError(
"Inspector not enabled in Miniflare instance. Set the `inspectorPort` option to enable it."
);
}
return new URL(`ws://127.0.0.1:${maybePort}`);
}
async unsafeGetDirectURL(workerName, entrypoint = "default") {
this.#checkDisposed();
await this.ready;
const workerIndex = this.#findAndAssertWorkerIndex(workerName);
const workerOpts = this.#workerOpts[workerIndex];
const socketName = getDirectSocketName(workerIndex, entrypoint);
(0, import_assert12.default)(this.#socketPorts !== void 0);
const maybePort = this.#socketPorts.get(socketName);
if (maybePort === void 0) {
const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName);
const friendlyEntrypointName = entrypoint === "default" ? entrypoint : JSON.stringify(entrypoint);
throw new TypeError(
`Direct access disabled in ${friendlyWorkerName} worker for ${friendlyEntrypointName} entrypoint`
);
}
const directSocket = workerOpts.core.unsafeDirectSockets?.find(
(socket) => (socket.entrypoint ?? "default") === entrypoint
);
(0, import_assert12.default)(directSocket !== void 0);
const host = directSocket.host ?? DEFAULT_HOST;
const accessibleHost = maybeGetLocallyAccessibleHost(host) ?? getURLSafeHost(host);
return new URL(`http://${accessibleHost}:${maybePort}`);
}
#checkDisposed() {
if (this.#disposeController.signal.aborted) {
throw new MiniflareCoreError(
"ERR_DISPOSED",
"Cannot use disposed instance"
);
}
}
async #setOptions(opts) {
const [sharedOpts, workerOpts] = validateOptions(opts);
this.#previousSharedOpts = this.#sharedOpts;
this.#previousWorkerOpts = this.#workerOpts;
this.#sharedOpts = sharedOpts;
this.#workerOpts = workerOpts;
this.#log = this.#sharedOpts.core.log ?? this.#log;
this.#structuredWorkerdLogs = this.#sharedOpts.core.structuredWorkerdLogs ?? this.#structuredWorkerdLogs;
await this.#assembleAndUpdateConfig();
}
setOptions(opts) {
this.#checkDisposed();
this.#proxyClient?.poisonProxies();
return this.#runtimeMutex.runWith(() => this.#setOptions(opts));
}
dispatchFetch = async (input, init2) => {
this.#checkDisposed();
await this.ready;
(0, import_assert12.default)(this.#runtimeEntryURL !== void 0);
(0, import_assert12.default)(this.#runtimeDispatcher !== void 0);
const forward = new Request(input, init2);
const url21 = new URL(forward.url);
const actualRuntimeOrigin = this.#runtimeEntryURL.origin;
const userRuntimeOrigin = url21.origin;
url21.protocol = this.#runtimeEntryURL.protocol;
url21.host = this.#runtimeEntryURL.host;
if (forward.body !== null && forward.headers.get("Content-Length") === "0") {
forward.headers.delete("Content-Length");
}
const cfBlob = forward.cf ? { ...fallbackCf, ...forward.cf } : void 0;
const dispatcher = new DispatchFetchDispatcher(
(0, import_undici8.getGlobalDispatcher)(),
this.#runtimeDispatcher,
actualRuntimeOrigin,
userRuntimeOrigin,
cfBlob
);
const forwardInit = forward;
forwardInit.dispatcher = dispatcher;
const response = await fetch3(url21, 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);
}
const contentEncoding = response.headers.get("Content-Encoding");
if (contentEncoding)
response.headers.set("MF-Content-Encoding", contentEncoding);
response.headers.delete("Content-Encoding");
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_assert12.default)(this.#proxyClient !== void 0);
return this.#proxyClient;
}
#findAndAssertWorkerIndex(workerName) {
if (workerName === void 0) {
return 0;
} else {
const index = this.#workerOpts.findIndex(
({ core }) => (core.name ?? "") === workerName
);
if (index === -1) {
throw new TypeError(`${JSON.stringify(workerName)} worker not found`);
}
return index;
}
}
async getBindings(workerName) {
const bindings = {};
const proxyClient = await this._getProxyClient();
const workerIndex = this.#findAndAssertWorkerIndex(workerName);
const workerOpts = this.#workerOpts[workerIndex];
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 instanceof ProxyNodeBinding) {
const proxyBindingName = getProxyBindingName(key, workerName, name);
let proxy = proxyClient.env[proxyBindingName];
(0, import_assert12.default)(
proxy !== void 0,
`Expected ${proxyBindingName} to be bound`
);
if (binding.proxyOverrideHandler) {
proxy = new Proxy(proxy, binding.proxyOverrideHandler);
}
bindings[name] = proxy;
} else {
bindings[name] = binding;
}
}
}
return bindings;
}
async getWorker(workerName) {
const proxyClient = await this._getProxyClient();
const workerIndex = this.#findAndAssertWorkerIndex(workerName);
const workerOpts = this.#workerOpts[workerIndex];
workerName = workerOpts.core.name ?? "";
const bindingName = CoreBindings.SERVICE_USER_ROUTE_PREFIX + workerName;
const fetcher = proxyClient.env[bindingName];
if (fetcher === void 0) {
const stringName = JSON.stringify(workerName);
throw new TypeError(
`${stringName} is being used as a wrapped binding, and cannot be accessed as a worker`
);
}
return fetcher;
}
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);
}
unsafeGetPersistPaths() {
const result = /* @__PURE__ */ new Map();
for (const [key, plugin] of PLUGIN_ENTRIES) {
const sharedOpts = this.#sharedOpts[key];
const maybePath = plugin.getPersistPath?.(sharedOpts, this.#tmpPath);
if (maybePath !== void 0)
result.set(key, maybePath);
}
return result;
}
async dispose() {
this.#disposeController.abort();
this.#proxyClient?.poisonProxies();
try {
await this.#waitForReady(
/* disposing */
true
);
} finally {
this.#removeExitHook?.();
await this.#proxyClient?.dispose();
await this.#runtime?.dispose();
await this.#stopLoopbackServer();
await import_fs25.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 = {
ASSETS_PLUGIN,
AssetsOptionsSchema,
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,
DispatchFetchDispatcher,
DurableObjectsOptionsSchema,
DurableObjectsSharedOptionsSchema,
ErrorEvent,
File,
FormData,
HOST_CAPNP_CONNECT,
HYPERDRIVE_PLUGIN,
HYPERDRIVE_PLUGIN_NAME,
Headers,
HttpOptions_Style,
HyperdriveInputOptionsSchema,
HyperdriveSchema,
JsonSchema,
KVHeaders,
KVLimits,
KVOptionsSchema,
KVParams,
KVSharedOptionsSchema,
KV_PLUGIN,
KV_PLUGIN_NAME,
LiteralSchema,
Log,
LogLevel,
MessageEvent,
Miniflare,
MiniflareCoreError,
MiniflareError,
ModuleDefinitionSchema,
ModuleRuleSchema,
ModuleRuleTypeSchema,
Mutex,
NoOpLog,
PIPELINES_PLUGIN_NAME,
PIPELINE_PLUGIN,
PLUGINS,
PLUGIN_ENTRIES,
PathSchema,
PeriodType,
PersistenceSchema,
PipelineOptionsSchema,
ProxyAddresses,
ProxyClient,
ProxyNodeBinding,
ProxyOps,
QUEUES_PLUGIN,
QUEUES_PLUGIN_NAME,
QueueBindings,
QueueConsumerOptionsSchema,
QueueConsumerSchema,
QueueConsumersSchema,
QueueContentTypeSchema,
QueueIncomingMessageSchema,
QueueMessageDelaySchema,
QueueProducerOptionsSchema,
QueueProducerSchema,
QueueProducersSchema,
QueuesBatchRequestSchema,
QueuesError,
QueuesOptionsSchema,
R2OptionsSchema,
R2SharedOptionsSchema,
R2_PLUGIN,
R2_PLUGIN_NAME,
RATELIMIT_PLUGIN,
RATELIMIT_PLUGIN_NAME,
RatelimitConfigSchema,
RatelimitOptionsSchema,
Request,
Response,
RouterError,
Runtime,
SERVICE_ENTRY,
SERVICE_LOOPBACK,
SITES_NO_CACHE_PREFIX,
SOCKET_ENTRY,
SOCKET_ENTRY_LOCAL,
SharedBindings,
SharedHeaders,
SiteBindings,
SourceOptionsSchema,
TlsOptions_Version,
TypedEventTarget,
WORKER_BINDING_SERVICE_LOOPBACK,
WORKFLOWS_PLUGIN,
WORKFLOWS_PLUGIN_NAME,
WORKFLOWS_STORAGE_SERVICE_NAME,
WaitGroup,
WebSocket,
WebSocketPair,
Worker_Binding_CryptoKey_Usage,
WorkflowsOptionsSchema,
WorkflowsSharedOptionsSchema,
__MiniflareFunctionWrapper,
_enableControlEndpoints,
_forceColour,
_initialiseInstanceRegistry,
_isCyclic,
_transformsForContentEncodingAndContentType,
base64Decode,
base64Encode,
buildAssetManifest,
compileModuleRules,
coupleWebSocket,
createFetchMock,
createHTTPReducers,
createHTTPRevivers,
decodeSitesKey,
deserialiseRegExps,
deserialiseSiteRegExps,
encodeSitesKey,
fetch,
formatZodError,
getAccessibleHosts,
getAssetsBindingsNames,
getCacheServiceName,
getDirectSocketName,
getEntrySocketHttpOptions,
getFreshSourceMapSupport,
getGlobalServices,
getMiniflareObjectBindings,
getNodeCompat,
getPersistPath,
getRootPath,
globsToRegExps,
isDurableObjectStub,
isFetcherFetch,
isR2ObjectWriteHttpMetadata,
isSitesRequest,
kCurrentWorker,
kInspectorSocket,
kUnsafeEphemeralUniqueKey,
kVoid,
matchRoutes,
maybeApply,
maybeParseURL,
mergeWorkerOptions,
migrateDatabase,
namespaceEntries,
namespaceKeys,
normaliseDurableObject,
objectEntryWorker,
parseRanges,
parseRoutes,
parseWithReadableStreams,
parseWithRootPath,
prefixError,
prefixStream,
readPrefix,
reduceError,
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