var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { D as DevServer } from "./dev-server-nWWQHf5q.js";
import { ay as dirname, ak as join, at as simpleHash, R as Runtime, C as BufferPolyfill } from "./fetch-virtual-server-BZi6n2Qk.js";
let typescriptModulePromise = null;
class ExecutionContext {
  constructor() {
    __publicField(this, "pending", /* @__PURE__ */ new Set());
  }
  waitUntil(promise) {
    this.pending.add(promise);
    promise.finally(() => {
      this.pending.delete(promise);
    }).catch(() => {
    });
  }
  passThroughOnException() {
  }
  flush() {
    if (this.pending.size === 0) {
      return;
    }
    void Promise.allSettled(Array.from(this.pending)).catch(() => {
    });
  }
}
function toRuntimeEnv(runtimeEnv, bindings) {
  const next = { ...runtimeEnv ?? {} };
  for (const [key, value] of Object.entries(bindings)) {
    if (typeof value === "string") {
      next[key] = value;
    } else if (typeof value === "number" || typeof value === "boolean") {
      next[key] = String(value);
    }
  }
  return next;
}
function getFetchHandler(namespace) {
  if (typeof namespace.fetch === "function") {
    return namespace.fetch.bind(namespace);
  }
  const defaultExport = namespace.default;
  if (typeof defaultExport === "function") {
    return defaultExport.bind(namespace);
  }
  if (defaultExport && typeof defaultExport === "object" && typeof defaultExport.fetch === "function") {
    return defaultExport.fetch.bind(defaultExport);
  }
  return null;
}
function headersToRecord(headers) {
  const output = {};
  headers.forEach((value, key) => {
    output[key] = value;
  });
  return output;
}
async function getTypeScriptModule() {
  if (!typescriptModulePromise) {
    typescriptModulePromise = import("./typescript-CNlebi2Q.js").then((n) => n.t);
  }
  return typescriptModulePromise;
}
async function transpileWorkerSource(sourcePath, sourceText) {
  const typescript = await getTypeScriptModule();
  const result = typescript.transpileModule(sourceText, {
    compilerOptions: {
      allowJs: true,
      esModuleInterop: true,
      isolatedModules: true,
      jsx: typescript.JsxEmit.Preserve,
      module: typescript.ModuleKind.CommonJS,
      target: typescript.ScriptTarget.ES2022
    },
    fileName: sourcePath,
    reportDiagnostics: false
  });
  return result.outputText || sourceText;
}
class CloudflareWorkerDevServer extends DevServer {
  constructor(vfs, options) {
    super(vfs, options);
    __publicField(this, "entry");
    __publicField(this, "envBindings");
    __publicField(this, "localProtocol");
    __publicField(this, "runtimeEnv");
    this.entry = options.entry;
    this.envBindings = { ...options.envBindings ?? {} };
    this.localProtocol = options.localProtocol ?? "http";
    this.runtimeEnv = toRuntimeEnv(options.runtimeEnv, this.envBindings);
  }
  getCompiledModulePath() {
    const directory = dirname(this.entry);
    return join(directory, `.almostnode-wrangler-${simpleHash(this.entry)}.cjs`);
  }
  startWatching() {
  }
  async handleRequest(method, url, headers, body) {
    try {
      const runtime = new Runtime(this.vfs, {
        cwd: this.root,
        env: this.runtimeEnv
      });
      try {
        const sourceText = String(this.vfs.readFileSync(this.entry, "utf8"));
        const compiledPath = this.getCompiledModulePath();
        const compiledSource = await transpileWorkerSource(this.entry, sourceText);
        this.vfs.writeFileSync(compiledPath, compiledSource);
        const imported = await runtime.execute(compiledSource, compiledPath);
        const namespace = imported.namespace;
        const fetchHandler = getFetchHandler(namespace);
        if (!fetchHandler) {
          throw new Error(
            `Wrangler worker entry ${this.entry} does not export a fetch handler.`
          );
        }
        const request = new Request(
          new URL(url, `${this.localProtocol}://localhost:${this.port}`).toString(),
          {
            method,
            headers,
            body: method === "GET" || method === "HEAD" ? void 0 : body
          }
        );
        const ctx = new ExecutionContext();
        const response = await fetchHandler(request, { ...this.envBindings }, ctx);
        ctx.flush();
        if (!(response instanceof Response)) {
          throw new Error("Cloudflare fetch handlers must return a Response.");
        }
        const responseBody = BufferPolyfill.from(await response.arrayBuffer());
        return {
          statusCode: response.status,
          statusMessage: response.statusText || "OK",
          headers: headersToRecord(response.headers),
          body: responseBody
        };
      } finally {
        runtime.clearCache();
      }
    } catch (error) {
      return this.serverError(error);
    }
  }
}
export {
  CloudflareWorkerDevServer
};
//# sourceMappingURL=cloudflare-worker-dev-server-BA2RWMwL.js.map
