wrangler
Version:
Command-line interface for all things Cloudflare Workers
1,589 lines (1,580 loc) • 18.2 MB
JavaScript
'use strict';
var assert32 = require('assert');
var fs6 = require('fs');
var os6 = require('os');
var path31 = require('path');
var process5 = require('process');
var Url = require('url');
var childProcess = require('child_process');
var fs$1 = require('fs/promises');
var util = require('util');
var buffer = require('buffer');
var crypto2 = require('crypto');
var timersPromises = require('timers/promises');
var console$1 = require('console');
var tty = require('tty');
var esbuild2 = require('esbuild');
var miniflare = require('miniflare');
var async_hooks = require('async_hooks');
var Stream = require('stream');
var http = require('http');
var https = require('https');
var zlib = require('zlib');
var web = require('stream/web');
var nodeModule = require('module');
var readline2 = require('readline');
var blake3Wasm = require('blake3-wasm');
var promises = require('stream/promises');
var events = require('events');
var net2 = require('net');
var workerd = require('workerd');
var domain5 = require('domain');
var consumers = require('stream/consumers');
var string_decoder = require('string_decoder');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var assert32__default = /*#__PURE__*/_interopDefault(assert32);
var fs6__namespace = /*#__PURE__*/_interopNamespace(fs6);
var os6__namespace = /*#__PURE__*/_interopNamespace(os6);
var path31__namespace = /*#__PURE__*/_interopNamespace(path31);
var process5__default = /*#__PURE__*/_interopDefault(process5);
var Url__default = /*#__PURE__*/_interopDefault(Url);
var childProcess__default = /*#__PURE__*/_interopDefault(childProcess);
var fs$1__namespace = /*#__PURE__*/_interopNamespace(fs$1);
var util__namespace = /*#__PURE__*/_interopNamespace(util);
var crypto2__default = /*#__PURE__*/_interopDefault(crypto2);
var timersPromises__namespace = /*#__PURE__*/_interopNamespace(timersPromises);
var tty__default = /*#__PURE__*/_interopDefault(tty);
var esbuild2__namespace = /*#__PURE__*/_interopNamespace(esbuild2);
var async_hooks__namespace = /*#__PURE__*/_interopNamespace(async_hooks);
var Stream__namespace = /*#__PURE__*/_interopNamespace(Stream);
var http__namespace = /*#__PURE__*/_interopNamespace(http);
var https__namespace = /*#__PURE__*/_interopNamespace(https);
var zlib__namespace = /*#__PURE__*/_interopNamespace(zlib);
var nodeModule__namespace = /*#__PURE__*/_interopNamespace(nodeModule);
var readline2__default = /*#__PURE__*/_interopDefault(readline2);
var events__default = /*#__PURE__*/_interopDefault(events);
var net2__default = /*#__PURE__*/_interopDefault(net2);
var domain5__namespace = /*#__PURE__*/_interopNamespace(domain5);
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x6) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x6, {
get: (a7, b9) => (typeof require !== "undefined" ? require : a7)[b9]
}) : x6)(function(x6) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x6 + '" is not supported');
});
var __esm = (fn3, res) => function __init() {
return fn3 && (res = (0, fn3[__getOwnPropNames(fn3)[0]])(fn3 = 0)), res;
};
var __commonJS = (cb2, mod2) => function __require6() {
return mod2 || (0, cb2[__getOwnPropNames(cb2)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all3) => {
for (var name2 in all3)
__defProp(target, name2, { get: all3[name2], 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 = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __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 || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
// import_meta_url.js
var import_meta_url;
var init_import_meta_url = __esm({
"import_meta_url.js"() {
import_meta_url = __require("url").pathToFileURL(__filename);
}
});
// ../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/registry.mjs
function setShims(shims, options = { auto: false }) {
if (auto) {
throw new Error(`you must \`import 'cloudflare/shims/${shims.kind}'\` before importing anything else from cloudflare`);
}
if (kind) {
throw new Error(`can't \`import 'cloudflare/shims/${shims.kind}'\` after \`import 'cloudflare/shims/${kind}'\``);
}
auto = options.auto;
kind = shims.kind;
fetch2 = shims.fetch;
shims.Request;
shims.Response;
shims.Headers;
FormData2 = shims.FormData;
shims.Blob;
File2 = shims.File;
shims.ReadableStream;
getMultipartRequestOptions = shims.getMultipartRequestOptions;
getDefaultAgent = shims.getDefaultAgent;
fileFromPath = shims.fileFromPath;
isFsReadStream = shims.isFsReadStream;
}
var auto, kind, fetch2, FormData2, File2, getMultipartRequestOptions, getDefaultAgent, fileFromPath, isFsReadStream;
var init_registry = __esm({
"../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/registry.mjs"() {
init_import_meta_url();
auto = false;
kind = void 0;
fetch2 = void 0;
FormData2 = void 0;
File2 = void 0;
getMultipartRequestOptions = void 0;
getDefaultAgent = void 0;
fileFromPath = void 0;
isFsReadStream = void 0;
__name(setShims, "setShims");
}
});
// ../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/MultipartBody.mjs
var MultipartBody;
var init_MultipartBody = __esm({
"../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/MultipartBody.mjs"() {
init_import_meta_url();
MultipartBody = class {
static {
__name(this, "MultipartBody");
}
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return "MultipartBody";
}
};
}
});
// ../workers-utils/dist/chunk-Q72B4Q5Z.mjs
var __create2, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __getProtoOf2, __hasOwnProp2, __name2, __require2, __commonJS2, __export2, __copyProps2, __toESM2;
var init_chunk_Q72B4Q5Z = __esm({
"../workers-utils/dist/chunk-Q72B4Q5Z.mjs"() {
init_import_meta_url();
__create2 = Object.create;
__defProp2 = Object.defineProperty;
__getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
__getOwnPropNames2 = Object.getOwnPropertyNames;
__getProtoOf2 = Object.getPrototypeOf;
__hasOwnProp2 = Object.prototype.hasOwnProperty;
__name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name");
__require2 = /* @__PURE__ */ ((x6) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x6, {
get: /* @__PURE__ */ __name((a7, b9) => (typeof __require !== "undefined" ? __require : a7)[b9], "get")
}) : x6)(function(x6) {
if (typeof __require !== "undefined") return __require.apply(this, arguments);
throw Error('Dynamic require of "' + x6 + '" is not supported');
});
__commonJS2 = /* @__PURE__ */ __name((cb2, mod2) => /* @__PURE__ */ __name(function __require22() {
return mod2 || (0, cb2[__getOwnPropNames2(cb2)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
}, "__require2"), "__commonJS");
__export2 = /* @__PURE__ */ __name((target, all3) => {
for (var name2 in all3)
__defProp2(target, name2, { get: all3[name2], enumerable: true });
}, "__export");
__copyProps2 = /* @__PURE__ */ __name((to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp2.call(to, key) && key !== except)
__defProp2(to, key, { get: /* @__PURE__ */ __name(() => from[key], "get"), enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
}, "__copyProps");
__toESM2 = /* @__PURE__ */ __name((mod2, isNodeMode, target) => (target = mod2 != null ? __create2(__getProtoOf2(mod2)) : {}, __copyProps2(
// 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 || !mod2 || !mod2.__esModule ? __defProp2(target, "default", { value: mod2, enumerable: true }) : target,
mod2
)), "__toESM");
}
});
function isCompatDate(str) {
return /^\d{4}-\d{2}-\d{2}$/.test(str);
}
function formatCompatibilityDate(date11) {
const compatDate = date11.toISOString().slice(0, 10);
assert32__default.default(isCompatDate(compatDate));
return compatDate;
}
function getTodaysCompatDate() {
return formatCompatibilityDate(/* @__PURE__ */ new Date());
}
function assertNever(_value) {
}
function mapWorkerMetadataBindings(bindings2) {
return bindings2.filter((binding) => binding.type !== "secret_text").reduce((configObj, binding) => {
switch (binding.type) {
case "plain_text":
{
configObj.vars = {
...configObj.vars ?? {},
[binding.name]: binding.text
};
}
break;
case "json":
{
configObj.vars = {
...configObj.vars ?? {},
[binding.name]: binding.json
};
}
break;
case "kv_namespace":
{
configObj.kv_namespaces = [
...configObj.kv_namespaces ?? [],
{ id: binding.namespace_id, binding: binding.name }
];
}
break;
case "durable_object_namespace":
{
configObj.durable_objects = {
bindings: [
...configObj.durable_objects?.bindings ?? [],
{
name: binding.name,
class_name: binding.class_name,
script_name: binding.script_name,
environment: binding.environment
}
]
};
}
break;
case "d1":
{
configObj.d1_databases = [
...configObj.d1_databases ?? [],
{
binding: binding.name,
database_id: binding.id
}
];
}
break;
case "browser":
{
configObj.browser = {
binding: binding.name
};
}
break;
case "ai":
{
configObj.ai = {
binding: binding.name
};
}
break;
case "images":
{
configObj.images = {
binding: binding.name
};
}
break;
case "stream":
{
configObj.stream = {
binding: binding.name
};
}
break;
case "media":
{
configObj.media = {
binding: binding.name
};
}
break;
case "r2_bucket":
{
configObj.r2_buckets = [
...configObj.r2_buckets ?? [],
{
binding: binding.name,
bucket_name: binding.bucket_name,
jurisdiction: binding.jurisdiction
}
];
}
break;
case "secrets_store_secret":
{
configObj.secrets_store_secrets = [
...configObj.secrets_store_secrets ?? [],
{
binding: binding.name,
store_id: binding.store_id,
secret_name: binding.secret_name
}
];
}
break;
case "artifacts":
{
configObj.artifacts = [
...configObj.artifacts ?? [],
{
binding: binding.name,
namespace: binding.namespace
}
];
}
break;
case "unsafe_hello_world": {
configObj.unsafe_hello_world = [
...configObj.unsafe_hello_world ?? [],
{
binding: binding.name,
enable_timer: binding.enable_timer
}
];
break;
}
case "flagship": {
configObj.flagship = [
...configObj.flagship ?? [],
{
binding: binding.name,
app_id: binding.app_id
}
];
break;
}
case "service":
{
configObj.services = [
...configObj.services ?? [],
{
binding: binding.name,
service: binding.service,
environment: binding.environment,
entrypoint: binding.entrypoint
}
];
}
break;
case "analytics_engine":
{
configObj.analytics_engine_datasets = [
...configObj.analytics_engine_datasets ?? [],
{ binding: binding.name, dataset: binding.dataset }
];
}
break;
case "dispatch_namespace":
{
configObj.dispatch_namespaces = [
...configObj.dispatch_namespaces ?? [],
{
binding: binding.name,
namespace: binding.namespace,
...binding.outbound && {
outbound: {
service: binding.outbound.worker.service,
environment: binding.outbound.worker.environment,
parameters: binding.outbound.params?.map((p7) => p7.name) ?? []
}
}
}
];
}
break;
case "logfwdr":
{
configObj.logfwdr = {
bindings: [
...configObj.logfwdr?.bindings ?? [],
{ name: binding.name, destination: binding.destination }
]
};
}
break;
case "wasm_module":
{
configObj.wasm_modules = {
...configObj.wasm_modules ?? {},
[binding.name]: binding.part
};
}
break;
case "text_blob":
{
configObj.text_blobs = {
...configObj.text_blobs ?? {},
[binding.name]: binding.part
};
}
break;
case "data_blob":
{
configObj.data_blobs = {
...configObj.data_blobs ?? {},
[binding.name]: binding.part
};
}
break;
case "secret_text":
break;
case "version_metadata": {
{
configObj.version_metadata = {
binding: binding.name
};
}
break;
}
case "send_email": {
configObj.send_email = [
...configObj.send_email ?? [],
{
name: binding.name,
destination_address: binding.destination_address,
allowed_destination_addresses: binding.allowed_destination_addresses,
allowed_sender_addresses: binding.allowed_sender_addresses
}
];
break;
}
case "queue":
configObj.queues ??= { producers: [] };
configObj.queues.producers = [
...configObj.queues.producers ?? [],
{
binding: binding.name,
queue: binding.queue_name,
delivery_delay: binding.delivery_delay
}
];
break;
case "vectorize":
configObj.vectorize = [
...configObj.vectorize ?? [],
{
binding: binding.name,
index_name: binding.index_name
}
];
break;
case "ai_search_namespace":
configObj.ai_search_namespaces = [
...configObj.ai_search_namespaces ?? [],
{
binding: binding.name,
namespace: binding.namespace
}
];
break;
case "ai_search":
configObj.ai_search = [
...configObj.ai_search ?? [],
{
binding: binding.name,
instance_name: binding.instance_name
}
];
break;
case "websearch":
{
configObj.websearch = {
binding: binding.name
};
}
break;
case "agent_memory": {
configObj.agent_memory = [
...configObj.agent_memory ?? [],
{
binding: binding.name,
namespace: binding.namespace
}
];
break;
}
case "hyperdrive":
configObj.hyperdrive = [
...configObj.hyperdrive ?? [],
{
binding: binding.name,
id: binding.id
}
];
break;
case "mtls_certificate":
configObj.mtls_certificates = [
...configObj.mtls_certificates ?? [],
{
binding: binding.name,
certificate_id: binding.certificate_id
}
];
break;
case "pipelines":
configObj.pipelines = [
...configObj.pipelines ?? [],
{
binding: binding.name,
// NOTE: stream is the primary field, but we also support pipeline for backward compatibility
...binding.stream && { stream: binding.stream },
...binding.pipeline && { pipeline: binding.pipeline }
}
];
break;
case "assets":
configObj.assets = {
binding: binding.name
// Note: we currently don't get all the assets information from the
// API, so here we are only able to set the name of the binding
// hopefully in the future we can properly fully support the binding
};
break;
case "inherit":
configObj.unsafe = {
bindings: [...configObj.unsafe?.bindings ?? [], binding],
metadata: configObj.unsafe?.metadata ?? void 0
};
break;
case "workflow":
{
configObj.workflows = [
...configObj.workflows ?? [],
{
binding: binding.name,
name: binding.workflow_name,
class_name: binding.class_name,
script_name: binding.script_name
}
];
}
break;
case "worker_loader":
{
configObj.worker_loaders = [
...configObj.worker_loaders ?? [],
{
binding: binding.name
}
];
}
break;
case "ratelimit":
{
configObj.ratelimits = [
...configObj.ratelimits ?? [],
{
name: binding.name,
namespace_id: binding.namespace_id,
simple: {
limit: binding.simple.limit,
period: binding.simple.period
}
}
];
}
break;
case "vpc_service":
{
configObj.vpc_services = [
...configObj.vpc_services ?? [],
{
binding: binding.name,
service_id: binding.service_id
}
];
}
break;
case "vpc_network":
{
if (binding.tunnel_id !== void 0) {
configObj.vpc_networks = [
...configObj.vpc_networks ?? [],
{ binding: binding.name, tunnel_id: binding.tunnel_id }
];
} else if (binding.network_id !== void 0) {
configObj.vpc_networks = [
...configObj.vpc_networks ?? [],
{ binding: binding.name, network_id: binding.network_id }
];
}
}
break;
default: {
configObj.unsafe = {
bindings: [...configObj.unsafe?.bindings ?? [], binding],
metadata: configObj.unsafe?.metadata ?? void 0
};
}
}
return configObj;
}, {});
}
function constructWranglerConfig(config5) {
const mappedBindings = mapWorkerMetadataBindings(config5.bindings);
const durableObjectClassNames = config5.bindings.filter(
(binding) => binding.type === "durable_object_namespace" && binding.script_name === config5.name
).map(
(durableObject) => durableObject.class_name
);
const allRoutes = [
...config5.routes.map((r8) => ({
pattern: r8.pattern,
zone_name: r8.zone_name
})),
...config5.domains.map((c8) => ({
pattern: c8.hostname,
zone_name: c8.zone_name,
custom_domain: true,
enabled: c8.enabled,
previews_enabled: c8.previews_enabled
}))
];
return {
name: config5.name,
main: config5.entrypoint,
workers_dev: config5.subdomain.enabled,
preview_urls: config5.subdomain.previews_enabled,
compatibility_date: config5.compatibility_date ?? getTodaysCompatDate(),
compatibility_flags: config5.compatibility_flags,
...allRoutes.length ? { routes: allRoutes } : {},
placement: config5.placement?.mode === "smart" ? { mode: "smart" } : void 0,
limits: config5.limits,
...durableObjectClassNames.length && config5.migration_tag ? {
migrations: [
{
tag: config5.migration_tag,
new_classes: durableObjectClassNames
}
]
} : {},
...config5.schedules.length ? {
triggers: {
crons: config5.schedules.map((scheduled) => scheduled.cron)
}
} : {},
tail_consumers: config5.tail_consumers ?? void 0,
observability: config5.observability,
...mappedBindings
};
}
var init_chunk_J6JRMPLM = __esm({
"../workers-utils/dist/chunk-J6JRMPLM.mjs"() {
init_import_meta_url();
init_chunk_Q72B4Q5Z();
__name(isCompatDate, "isCompatDate");
__name2(isCompatDate, "isCompatDate");
__name(formatCompatibilityDate, "formatCompatibilityDate");
__name2(formatCompatibilityDate, "formatCompatibilityDate");
__name(getTodaysCompatDate, "getTodaysCompatDate");
__name2(getTodaysCompatDate, "getTodaysCompatDate");
__name(assertNever, "assertNever");
__name2(assertNever, "assertNever");
__name(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
__name2(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
__name(constructWranglerConfig, "constructWranglerConfig");
__name2(constructWranglerConfig, "constructWranglerConfig");
}
});
function isDirectory(path89) {
return fs6__namespace.default.statSync(path89, { throwIfNoEntry: false })?.isDirectory() ?? false;
}
function removeDir(dirPath, { fireAndForget = false } = {}) {
const result = fs6__namespace.default.promises.rm(dirPath, {
recursive: true,
force: true,
maxRetries: 5,
retryDelay: 100
});
if (fireAndForget) {
void result.catch(() => {
});
} else {
return result;
}
}
function removeDirSync(dirPath) {
fs6__namespace.default.rmSync(dirPath, {
recursive: true,
force: true,
maxRetries: 5,
retryDelay: 100
});
}
var init_chunk_53IMCORZ = __esm({
"../workers-utils/dist/chunk-53IMCORZ.mjs"() {
init_import_meta_url();
init_chunk_Q72B4Q5Z();
__name(isDirectory, "isDirectory");
__name2(isDirectory, "isDirectory");
__name(removeDir, "removeDir");
__name2(removeDir, "removeDir");
__name(removeDirSync, "removeDirSync");
__name2(removeDirSync, "removeDirSync");
}
});
function isWindows() {
return /^win/i.test(process.platform);
}
function isMacOS() {
return /^darwin$/i.test(process.platform);
}
function isNonEmpty(value) {
return !!value;
}
function getEnv(name2) {
return process.env[name2];
}
function normalizePath(p7) {
return p7 ? path31__namespace.default.normalize(path31__namespace.default.join(p7, ".")) : void 0;
}
function homeDir() {
if (isWindows()) {
const priorityList = [
os6__namespace.default.homedir(),
getEnv("USERPROFILE"),
getEnv("HOME"),
// NOTE: `os-paths@7` uses `||` here (not `&&`), so a home directory is
// derived even when only one of HOMEDRIVE/HOMEPATH is set. This is
// preserved deliberately for byte-for-byte parity — see the parity
// tests, which compare this branch against the real package.
getEnv("HOMEDRIVE") || getEnv("HOMEPATH") ? path31__namespace.default.join(getEnv("HOMEDRIVE") ?? "", getEnv("HOMEPATH") ?? "") : void 0
];
return normalizePath(priorityList.find(isNonEmpty));
}
return normalizePath(os6__namespace.default.homedir() || getEnv("HOME"));
}
function joinToBase(base, segments) {
return base ? path31__namespace.default.join(base, ...segments) : void 0;
}
function tempDir() {
if (isWindows()) {
const fallback2 = "C:\\Temp";
const priorityListLazy = [
() => os6__namespace.default.tmpdir(),
() => getEnv("TEMP"),
() => getEnv("TMP"),
() => joinToBase(getEnv("LOCALAPPDATA"), ["Temp"]),
() => joinToBase(homeDir(), ["AppData", "Local", "Temp"]),
() => joinToBase(getEnv("ALLUSERSPROFILE"), ["Temp"]),
() => joinToBase(getEnv("SystemRoot"), ["Temp"]),
() => joinToBase(getEnv("windir"), ["Temp"]),
() => joinToBase(getEnv("SystemDrive"), ["\\", "Temp"])
];
const found = priorityListLazy.find((fn3) => isNonEmpty(fn3()));
return found && normalizePath(found()) || fallback2;
}
const fallback = "/tmp";
const priorityList = [
os6__namespace.default.tmpdir(),
getEnv("TMPDIR"),
getEnv("TEMP"),
getEnv("TMP")
];
return normalizePath(priorityList.find(isNonEmpty)) || fallback;
}
function baseDir() {
return homeDir() || tempDir();
}
function valOrPath(value, segments) {
return value || path31__namespace.default.join(...segments);
}
function windowsAppData() {
return valOrPath(getEnv("APPDATA"), [baseDir(), "AppData", "Roaming"]);
}
function windowsLocalAppData() {
return valOrPath(getEnv("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
}
function xdgConfig() {
if (isMacOS()) {
return valOrPath(getEnv("XDG_CONFIG_HOME"), [
baseDir(),
"Library",
"Preferences"
]);
}
if (isWindows()) {
return valOrPath(getEnv("XDG_CONFIG_HOME"), [
windowsAppData(),
"xdg.config"
]);
}
return valOrPath(getEnv("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
}
function xdgCache() {
if (isMacOS()) {
return valOrPath(getEnv("XDG_CACHE_HOME"), [
baseDir(),
"Library",
"Caches"
]);
}
if (isWindows()) {
return valOrPath(getEnv("XDG_CACHE_HOME"), [
windowsLocalAppData(),
"xdg.cache"
]);
}
return valOrPath(getEnv("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
}
function xdgAppPaths(name2) {
const segment = path31__namespace.default.parse(name2).name;
return {
config: /* @__PURE__ */ __name2(() => path31__namespace.default.join(xdgConfig(), segment), "config"),
cache: /* @__PURE__ */ __name2(() => path31__namespace.default.join(xdgCache(), segment), "cache")
};
}
function getGlobalConfigPath({
appName = "wrangler",
leadingDot = true,
useLegacyHomeDir = true
} = {}) {
const dirName = `${leadingDot ? "." : ""}${appName}`;
const configDir = xdgAppPaths(dirName).config();
if (useLegacyHomeDir) {
const legacyConfigDir = path31__namespace.default.join(os6__namespace.default.homedir(), dirName);
if (isDirectory(legacyConfigDir)) {
return legacyConfigDir;
}
}
return configDir;
}
function getGlobalWranglerCachePath() {
return xdgAppPaths(".wrangler").cache();
}
var init_chunk_34VZWBGB = __esm({
"../workers-utils/dist/chunk-34VZWBGB.mjs"() {
init_import_meta_url();
init_chunk_53IMCORZ();
init_chunk_Q72B4Q5Z();
__name(isWindows, "isWindows");
__name2(isWindows, "isWindows");
__name(isMacOS, "isMacOS");
__name2(isMacOS, "isMacOS");
__name(isNonEmpty, "isNonEmpty");
__name2(isNonEmpty, "isNonEmpty");
__name(getEnv, "getEnv");
__name2(getEnv, "getEnv");
__name(normalizePath, "normalizePath");
__name2(normalizePath, "normalizePath");
__name(homeDir, "homeDir");
__name2(homeDir, "homeDir");
__name(joinToBase, "joinToBase");
__name2(joinToBase, "joinToBase");
__name(tempDir, "tempDir");
__name2(tempDir, "tempDir");
__name(baseDir, "baseDir");
__name2(baseDir, "baseDir");
__name(valOrPath, "valOrPath");
__name2(valOrPath, "valOrPath");
__name(windowsAppData, "windowsAppData");
__name2(windowsAppData, "windowsAppData");
__name(windowsLocalAppData, "windowsLocalAppData");
__name2(windowsLocalAppData, "windowsLocalAppData");
__name(xdgConfig, "xdgConfig");
__name2(xdgConfig, "xdgConfig");
__name(xdgCache, "xdgCache");
__name2(xdgCache, "xdgCache");
__name(xdgAppPaths, "xdgAppPaths");
__name2(xdgAppPaths, "xdgAppPaths");
__name(getGlobalConfigPath, "getGlobalConfigPath");
__name2(getGlobalConfigPath, "getGlobalConfigPath");
__name(getGlobalWranglerCachePath, "getGlobalWranglerCachePath");
__name2(getGlobalWranglerCachePath, "getGlobalWranglerCachePath");
}
});
function partitionExports(exports2) {
const partitioned = {
"durable-object": {},
worker: {}
};
if (exports2 === void 0) {
return partitioned;
}
for (const [name2, entry] of Object.entries(exports2)) {
partitioned[entry.type][name2] = entry;
}
return partitioned;
}
function createFatalError(message, isJson, options) {
if (isJson) {
return new JsonFriendlyFatalError(JSON.stringify(message), options);
}
return new FatalError(`${message}`, options);
}
function createScanner(text, ignoreTrivia = false) {
const len = text.length;
let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
function scanHexDigits(count, exact) {
let digits2 = 0;
let value2 = 0;
while (digits2 < count || !exact) {
let ch2 = text.charCodeAt(pos);
if (ch2 >= 48 && ch2 <= 57) {
value2 = value2 * 16 + ch2 - 48;
} else if (ch2 >= 65 && ch2 <= 70) {
value2 = value2 * 16 + ch2 - 65 + 10;
} else if (ch2 >= 97 && ch2 <= 102) {
value2 = value2 * 16 + ch2 - 97 + 10;
} else {
break;
}
pos++;
digits2++;
}
if (digits2 < count) {
value2 = -1;
}
return value2;
}
__name(scanHexDigits, "scanHexDigits");
__name2(scanHexDigits, "scanHexDigits");
function setPosition(newPosition) {
pos = newPosition;
value = "";
tokenOffset = 0;
token = 16;
scanError = 0;
}
__name(setPosition, "setPosition");
__name2(setPosition, "setPosition");
function scanNumber() {
let start = pos;
if (text.charCodeAt(pos) === 48) {
pos++;
} else {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
}
if (pos < text.length && text.charCodeAt(pos) === 46) {
pos++;
if (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
} else {
scanError = 3;
return text.substring(start, pos);
}
}
let end = pos;
if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
pos++;
if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
pos++;
}
if (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
end = pos;
} else {
scanError = 3;
}
}
return text.substring(start, end);
}
__name(scanNumber, "scanNumber");
__name2(scanNumber, "scanNumber");
function scanString() {
let result = "", start = pos;
while (true) {
if (pos >= len) {
result += text.substring(start, pos);
scanError = 2;
break;
}
const ch2 = text.charCodeAt(pos);
if (ch2 === 34) {
result += text.substring(start, pos);
pos++;
break;
}
if (ch2 === 92) {
result += text.substring(start, pos);
pos++;
if (pos >= len) {
scanError = 2;
break;
}
const ch22 = text.charCodeAt(pos++);
switch (ch22) {
case 34:
result += '"';
break;
case 92:
result += "\\";
break;
case 47:
result += "/";
break;
case 98:
result += "\b";
break;
case 102:
result += "\f";
break;
case 110:
result += "\n";
break;
case 114:
result += "\r";
break;
case 116:
result += " ";
break;
case 117:
const ch3 = scanHexDigits(4, true);
if (ch3 >= 0) {
result += String.fromCharCode(ch3);
} else {
scanError = 4;
}
break;
default:
scanError = 5;
}
start = pos;
continue;
}
if (ch2 >= 0 && ch2 <= 31) {
if (isLineBreak(ch2)) {
result += text.substring(start, pos);
scanError = 2;
break;
} else {
scanError = 6;
}
}
pos++;
}
return result;
}
__name(scanString, "scanString");
__name2(scanString, "scanString");
function scanNext() {
value = "";
scanError = 0;
tokenOffset = pos;
lineStartOffset = lineNumber;
prevTokenLineStartOffset = tokenLineStartOffset;
if (pos >= len) {
tokenOffset = len;
return token = 17;
}
let code = text.charCodeAt(pos);
if (isWhiteSpace(code)) {
do {
pos++;
value += String.fromCharCode(code);
code = text.charCodeAt(pos);
} while (isWhiteSpace(code));
return token = 15;
}
if (isLineBreak(code)) {
pos++;
value += String.fromCharCode(code);
if (code === 13 && text.charCodeAt(pos) === 10) {
pos++;
value += "\n";
}
lineNumber++;
tokenLineStartOffset = pos;
return token = 14;
}
switch (code) {
// tokens: []{}:,
case 123:
pos++;
return token = 1;
case 125:
pos++;
return token = 2;
case 91:
pos++;
return token = 3;
case 93:
pos++;
return token = 4;
case 58:
pos++;
return token = 6;
case 44:
pos++;
return token = 5;
// strings
case 34:
pos++;
value = scanString();
return token = 10;
// comments
case 47:
const start = pos - 1;
if (text.charCodeAt(pos + 1) === 47) {
pos += 2;
while (pos < len) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
value = text.substring(start, pos);
return token = 12;
}
if (text.charCodeAt(pos + 1) === 42) {
pos += 2;
const safeLength = len - 1;
let commentClosed = false;
while (pos < safeLength) {
const ch2 = text.charCodeAt(pos);
if (ch2 === 42 && text.charCodeAt(pos + 1) === 47) {
pos += 2;
commentClosed = true;
break;
}
pos++;
if (isLineBreak(ch2)) {
if (ch2 === 13 && text.charCodeAt(pos) === 10) {
pos++;
}
lineNumber++;
tokenLineStartOffset = pos;
}
}
if (!commentClosed) {
pos++;
scanError = 1;
}
value = text.substring(start, pos);
return token = 13;
}
value += String.fromCharCode(code);
pos++;
return token = 16;
// numbers
case 45:
value += String.fromCharCode(code);
pos++;
if (pos === len || !isDigit(text.charCodeAt(pos))) {
return token = 16;
}
// found a minus, followed by a number so
// we fall through to proceed with scanning
// numbers
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
value += scanNumber();
return token = 11;
// literals and unknown symbols
default:
while (pos < len && isUnknownContentCharacter(code)) {
pos++;
code = text.charCodeAt(pos);
}
if (tokenOffset !== pos) {
value = text.substring(tokenOffset, pos);
switch (value) {
case "true":
return token = 8;
case "false":
return token = 9;
case "null":
return token = 7;
}
return token = 16;
}
value += String.fromCharCode(code);
pos++;
return token = 16;
}
}
__name(scanNext, "scanNext");
__name2(scanNext, "scanNext");
function isUnknownContentCharacter(code) {
if (isWhiteSpace(code) || isLineBreak(code)) {
return false;
}
switch (code) {
case 125:
case 93:
case 123:
case 91:
case 34:
case 58:
case 44:
case 47:
return false;
}
return true;
}
__name(isUnknownContentCharacter, "isUnknownContentCharacter");
__name2(isUnknownContentCharacter, "isUnknownContentCharacter");
function scanNextNonTrivia() {
let result;
do {
result = scanNext();
} while (result >= 12 && result <= 15);
return result;
}
__name(scanNextNonTrivia, "scanNextNonTrivia");
__name2(scanNextNonTrivia, "scanNextNonTrivia");
return {
setPosition,
getPosition: /* @__PURE__ */ __name2(() => pos, "getPosition"),
scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
getToken: /* @__PURE__ */ __name2(() => token, "getToken"),
getTokenValue: /* @__PURE__ */ __name2(() => value, "getTokenValue"),
getTokenOffset: /* @__PURE__ */ __name2(() => tokenOffset, "getTokenOffset"),
getTokenLength: /* @__PURE__ */ __name2(() => pos - tokenOffset, "getTokenLength"),
getTokenStartLine: /* @__PURE__ */ __name2(() => lineStartOffset, "getTokenStartLine"),
getTokenStartCharacter: /* @__PURE__ */ __name2(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"),
getTokenError: /* @__PURE__ */ __name2(() => scanError, "getTokenError")
};
}
function isWhiteSpace(ch2) {
return ch2 === 32 || ch2 === 9;
}
function isLineBreak(ch2) {
return ch2 === 10 || ch2 === 13;
}
function isDigit(ch2) {
return ch2 >= 48 && ch2 <= 57;
}
function format(documentText, range2, options) {
let initialIndentLevel;
let formatText;
let formatTextStart;
let rangeStart;
let rangeEnd;
if (range2) {
rangeStart = range2.offset;
rangeEnd = rangeStart + range2.length;
formatTextStart = rangeStart;
while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
formatTextStart--;
}
let endOffset = rangeEnd;
while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
endOffset++;
}
formatText = documentText.substring(formatTextStart, endOffset);
initialIndentLevel = computeIndentLevel(formatText, options);
} else {
formatText = documentText;
initialIndentLevel = 0;
formatTextStart = 0;
rangeStart = 0;
rangeEnd = documentText.length;
}
const eol = getEOL(options, documentText);
let numberLineBreaks = 0;
let indentLevel = 0;
let indentValue;
if (options.insertSpaces) {
indentValue = repeat(" ", options.tabSize || 4);
} else {
indentValue = " ";
}
let scanner = createScanner(formatText, false);
let hasError = false;
function newLinesAndIndent() {
if (numberLineBreaks > 1) {
return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
} else {
return eol + repeat(indentValue, initialIndentLevel + indentLevel);
}
}
__name(newLinesAndIndent, "newLinesAndIndent");
__name2(newLinesAndIndent, "newLinesAndIndent");
function scanNext() {
let token = scanner.scan();
numberLineBreaks = 0;
while (token === 15 || token === 14) {
if (token === 14 && options.keepLines) {
numberLineBreaks += 1;
} else if (token === 14) {
numberLineBreaks = 1;
}
token = scanner.scan();
}
hasError = token === 16 || scanner.getTokenError() !== 0;
return token;
}
__name(scanNext, "scanNext");
__name2(scanNext, "scanNext");
const editOperations = [];
function addEdit(text, startOffset, endOffset) {
if (!hasError && (!range2 || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
}
}
__name(addEdit, "addEdit");
__name2(addEdit, "addEdit");
let firstToken = scanNext();
if (options.keepLines && numberLineBreaks > 0) {
addEdit(repeat(eol, numberLineBreaks), 0, 0);
}
if (firstToken !== 17) {
let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
let initialIndent = repeat(indentValue, initialIndentLevel);
addEdit(initialIndent, formatTextStart, firstTokenStart);
}
while (firstToken !== 17) {
let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
let secondToken = scanNext();
let replaceContent = "";
let needsLineBreak = false;
while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(" ", firstTokenEnd, commentTokenStart);
firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
needsLineBreak = secondToken === 12;
replaceContent = needsLineBreak ? newLinesAndIndent() : "";
secondToken = scanNext();
}
if (secondToken === 2) {
if (firstToken !== 1) {
indentLevel--;
}
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
replaceContent = newLinesAndIndent();
} else if (options.keepLines) {
replaceContent = " ";
}
} else if (secondToken === 4) {
if (firstToken !== 3) {
indentLevel--;
}
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
replaceContent = newLinesAndIndent();
} else if (options.keepLines) {
replaceContent = " ";
}
} else {
switch (firstToken) {
case 3:
case 1:
indentLevel++;
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = " ";
}
break;
case 5:
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = " ";
}
break;
case 12:
replaceContent = newLinesAndIndent();
break;
case 13:
if (numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (!needsLineBreak) {
replaceContent = " ";
}
break;
case 6:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (!needsLineBreak) {
replaceContent = " ";
}
break;
case 10:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (secondToken === 6 && !needsLineBreak) {
replaceContent = "";
}
break;
case 7:
case 8:
case 9:
case 11:
case 2:
case 4:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else {
if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
replaceContent = " ";
} else if (secondToken !== 5 && secondToken !== 17) {
hasError = true;
}
}
break;
case 16:
hasError = true;
break;
}
if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
replaceContent = newLinesAndIndent();
}
}
if (secondToken === 17) {
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = options.insertFinalNewline ? eol : "";
}
}
const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(replaceContent, firstTokenEnd, secondTokenStart);
firstToken = secondToken;
}
return editOperations;
}
function repeat(s7, count) {
let result = "";
for (let i7 = 0; i7 < count; i7++) {
result += s7;
}
return result;
}
function computeIndentLevel(content, options) {
let i7 = 0;
let nChars = 0;
const tabSize = options.tabSize || 4;
while (i7 < content.length) {
let ch2 = content.charAt(i7);
if (ch2 === " ") {
nChars++;
} else if (ch2 === " ") {
nChars += tabSize;
} else {
break;
}
i7++;
}
return Math.floor(nChars / tabSize);
}
function getEOL(options, text) {
for (let i7 = 0; i7 < text.length; i7++) {
const ch2 = text.charAt(i7);
if (ch2 === "\r") {
if (i7 + 1 < text.length && text.charAt(i7 + 1) === "\n") {
return "\r\n";
}
return "\r";
} else if (ch2 === "\n") {
return "\n";
}
}
return options && options.eol || "\n";
}
function isEOL(text, offset) {
return "\r\n".indexOf(text.charAt(offset)) !== -1;
}
function parse(text, errors = [], options = ParseOptions.DEFAULT) {
let currentProperty = null;
let currentParent = [];
const previousParents = [];
function onValue(value) {
if (Array.isArray(currentParent)) {
currentParent.push(value);
} else if (currentProperty !== null) {
currentParent[currentProperty] = value;
}
}
__name(onValue, "onValue");
__name2(onValue, "onValue");
const visitor = {
onObjectBegin: /* @__PURE__ */ __name2(() => {
const object5 = {};
onValue(object5);
previousParents.push(currentParent);
currentParent = object5;
currentProperty = null;
}, "onObjectBegin"),
onObjectProperty: /* @__PURE__ */ __name2((name2) => {
currentProperty = name2;
}, "onObjectProperty"),
onObjectEnd: /* @__PURE__ */ __name2(() => {
currentParent = previousParents.pop();
}, "onObjectEnd"),
onArrayBegin: /* @__PURE__ */ __name2(() => {
const array5 = [];
onValue(array5);
previousParents.push(currentParent);
currentParent = array5;
currentProperty = null;
}, "onArrayBegin"),
onArrayEnd: /* @__PURE__ */ __name2(() => {
currentParent = previousParents.pop();
}, "onArrayEnd"),
onLiteralValue: onValue,
onError: /* @__PURE__ */ __name2((error111, offset, length) => {
errors.push({ error: error111, offset, length });
}, "onError")
};
visit(text, visitor, options);
return currentParent[0];
}
function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
function ensurePropertyComplete(endOffset) {
if (currentParent.type === "property") {
currentParent.length = endOffset - currentParent.offset;
currentParent = currentParent.parent;
}
}
__name(ensurePropertyComplete, "ensurePropertyComplete");
__name2(ensurePropertyComplete, "ensurePropertyComplete");
function onValue(valueNode) {
currentParent.children.push(valueNode);
return valueNode;
}
__name(onValue, "onValue");
__name2(onValue, "onValue");
const visitor = {
onObjectBegin: /* @__PURE__ */ __name2((offset) => {
currentParent = onValue({ type: "object", offset, length: -1, parent: curre