var __defineProperty = Object.defineProperty;
var __hasOwnProperty = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => {
  return __defineProperty(target, "__esModule", {value: true});
};
var __exportStar = (target, module2) => {
  __markAsModule(target);
  if (typeof module2 === "object" || typeof module2 === "function") {
    for (let key in module2)
      if (__hasOwnProperty.call(module2, key) && !__hasOwnProperty.call(target, key) && key !== "default")
        __defineProperty(target, key, {get: () => module2[key], enumerable: true});
  }
  return target;
};
var __toModule = (module2) => {
  if (module2 && module2.__esModule)
    return module2;
  return __exportStar(__defineProperty({}, "default", {value: module2, enumerable: true}), module2);
};

// lib/stdio_protocol.ts
function encodePacket(packet) {
  let visit = (value) => {
    if (value === null) {
      bb.write8(0);
    } else if (typeof value === "boolean") {
      bb.write8(1);
      bb.write8(+value);
    } else if (typeof value === "number") {
      bb.write8(2);
      bb.write32(value);
    } else if (typeof value === "string") {
      bb.write8(3);
      bb.write(encodeUTF8(value));
    } else if (value instanceof Uint8Array) {
      bb.write8(4);
      bb.write(value);
    } else if (value instanceof Array) {
      bb.write8(5);
      bb.write32(value.length);
      for (let item of value) {
        visit(item);
      }
    } else {
      let keys = Object.keys(value);
      bb.write8(6);
      bb.write32(keys.length);
      for (let key of keys) {
        bb.write(encodeUTF8(key));
        visit(value[key]);
      }
    }
  };
  let bb = new ByteBuffer();
  bb.write32(0);
  bb.write32(packet.id << 1 | +!packet.isRequest);
  visit(packet.value);
  writeUInt32LE(bb.buf, bb.len - 4, 0);
  return bb.buf.subarray(0, bb.len);
}
function decodePacket(bytes) {
  let visit = () => {
    switch (bb.read8()) {
      case 0:
        return null;
      case 1:
        return !!bb.read8();
      case 2:
        return bb.read32();
      case 3:
        return decodeUTF8(bb.read());
      case 4:
        return bb.read();
      case 5: {
        let count = bb.read32();
        let value2 = [];
        for (let i = 0; i < count; i++) {
          value2.push(visit());
        }
        return value2;
      }
      case 6: {
        let count = bb.read32();
        let value2 = {};
        for (let i = 0; i < count; i++) {
          value2[decodeUTF8(bb.read())] = visit();
        }
        return value2;
      }
      default:
        throw new Error("Invalid packet");
    }
  };
  let bb = new ByteBuffer(bytes);
  let id = bb.read32();
  let isRequest = (id & 1) === 0;
  id >>>= 1;
  let value = visit();
  if (bb.ptr !== bytes.length) {
    throw new Error("Invalid packet");
  }
  return {id, isRequest, value};
}
class ByteBuffer {
  constructor(buf = new Uint8Array(1024)) {
    this.buf = buf;
    this.len = 0;
    this.ptr = 0;
  }
  _write(delta) {
    if (this.len + delta > this.buf.length) {
      let clone = new Uint8Array((this.len + delta) * 2);
      clone.set(this.buf);
      this.buf = clone;
    }
    this.len += delta;
    return this.len - delta;
  }
  write8(value) {
    let offset = this._write(1);
    this.buf[offset] = value;
  }
  write32(value) {
    let offset = this._write(4);
    writeUInt32LE(this.buf, value, offset);
  }
  write(bytes) {
    let offset = this._write(4 + bytes.length);
    writeUInt32LE(this.buf, bytes.length, offset);
    this.buf.set(bytes, offset + 4);
  }
  _read(delta) {
    if (this.ptr + delta > this.buf.length) {
      throw new Error("Invalid packet");
    }
    this.ptr += delta;
    return this.ptr - delta;
  }
  read8() {
    return this.buf[this._read(1)];
  }
  read32() {
    return readUInt32LE(this.buf, this._read(4));
  }
  read() {
    let length = this.read32();
    let bytes = new Uint8Array(length);
    let ptr = this._read(bytes.length);
    bytes.set(this.buf.subarray(ptr, ptr + length));
    return bytes;
  }
}
let encodeUTF8;
let decodeUTF8;
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
  let encoder = new TextEncoder();
  let decoder = new TextDecoder();
  encodeUTF8 = (text) => encoder.encode(text);
  decodeUTF8 = (bytes) => decoder.decode(bytes);
} else if (typeof Buffer !== "undefined") {
  encodeUTF8 = (text) => Buffer.from(text);
  decodeUTF8 = (bytes) => Buffer.from(bytes).toString();
} else {
  throw new Error("No UTF-8 codec found");
}
function readUInt32LE(buffer, offset) {
  return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
}
function writeUInt32LE(buffer, value, offset) {
  buffer[offset++] = value;
  buffer[offset++] = value >> 8;
  buffer[offset++] = value >> 16;
  buffer[offset++] = value >> 24;
}

// lib/common.ts
function validateTarget(target) {
  target += "";
  if (target.indexOf(",") >= 0)
    throw new Error(`Invalid target: ${target}`);
  return target;
}
function pushCommonFlags(flags, options, isTTY2, logLevelDefault) {
  if (options.target) {
    if (options.target instanceof Array)
      flags.push(`--target=${Array.from(options.target).map(validateTarget).join(",")}`);
    else
      flags.push(`--target=${validateTarget(options.target)}`);
  }
  if (options.strict === true)
    flags.push(`--strict`);
  else if (options.strict)
    for (let key of options.strict)
      flags.push(`--strict:${key}`);
  if (options.minify)
    flags.push("--minify");
  if (options.minifySyntax)
    flags.push("--minify-syntax");
  if (options.minifyWhitespace)
    flags.push("--minify-whitespace");
  if (options.minifyIdentifiers)
    flags.push("--minify-identifiers");
  if (options.jsxFactory)
    flags.push(`--jsx-factory=${options.jsxFactory}`);
  if (options.jsxFragment)
    flags.push(`--jsx-fragment=${options.jsxFragment}`);
  if (options.define)
    for (let key in options.define)
      flags.push(`--define:${key}=${options.define[key]}`);
  if (options.pure)
    for (let fn of options.pure)
      flags.push(`--pure:${fn}`);
  if (options.color)
    flags.push(`--color=${options.color}`);
  else if (isTTY2)
    flags.push(`--color=true`);
  flags.push(`--log-level=${options.logLevel || logLevelDefault}`);
  flags.push(`--error-limit=${options.errorLimit || 0}`);
}
function flagsForBuildOptions(options, isTTY2) {
  let flags = [];
  let stdinContents = null;
  let stdinResolveDir = null;
  pushCommonFlags(flags, options, isTTY2, "info");
  if (options.sourcemap)
    flags.push(`--sourcemap${options.sourcemap === true ? "" : `=${options.sourcemap}`}`);
  if (options.globalName)
    flags.push(`--global-name=${options.globalName}`);
  if (options.bundle)
    flags.push("--bundle");
  if (options.splitting)
    flags.push("--splitting");
  if (options.metafile)
    flags.push(`--metafile=${options.metafile}`);
  if (options.outfile)
    flags.push(`--outfile=${options.outfile}`);
  if (options.outdir)
    flags.push(`--outdir=${options.outdir}`);
  if (options.platform)
    flags.push(`--platform=${options.platform}`);
  if (options.format)
    flags.push(`--format=${options.format}`);
  if (options.tsconfig)
    flags.push(`--tsconfig=${options.tsconfig}`);
  if (options.resolveExtensions)
    flags.push(`--resolve-extensions=${options.resolveExtensions.join(",")}`);
  if (options.external)
    for (let name of options.external)
      flags.push(`--external:${name}`);
  if (options.loader)
    for (let ext in options.loader)
      flags.push(`--loader:${ext}=${options.loader[ext]}`);
  if (options.entryPoints) {
    for (let entryPoint of options.entryPoints) {
      if (entryPoint.startsWith("-"))
        throw new Error(`Invalid entry point: ${entryPoint}`);
      flags.push(entryPoint);
    }
  }
  if (options.stdin) {
    let {contents, resolveDir, sourcefile, loader} = options.stdin;
    if (sourcefile)
      flags.push(`--sourcefile=${sourcefile}`);
    if (loader)
      flags.push(`--loader=${loader}`);
    if (resolveDir)
      stdinResolveDir = resolveDir + "";
    stdinContents = contents ? contents + "" : "";
  }
  return [flags, stdinContents, stdinResolveDir];
}
function flagsForTransformOptions(options, isTTY2) {
  let flags = [];
  pushCommonFlags(flags, options, isTTY2, "silent");
  if (options.sourcemap)
    flags.push(`--sourcemap=${options.sourcemap === true ? "external" : options.sourcemap}`);
  if (options.sourcefile)
    flags.push(`--sourcefile=${options.sourcefile}`);
  if (options.loader)
    flags.push(`--loader=${options.loader}`);
  return flags;
}
function createChannel(options) {
  let callbacks = new Map();
  let isClosed = false;
  let nextID = 0;
  let stdout = new Uint8Array(4096);
  let stdoutUsed = 0;
  let readFromStdout = (chunk) => {
    let limit = stdoutUsed + chunk.length;
    if (limit > stdout.length) {
      let swap = new Uint8Array(limit * 2);
      swap.set(stdout);
      stdout = swap;
    }
    stdout.set(chunk, stdoutUsed);
    stdoutUsed += chunk.length;
    let offset = 0;
    while (offset + 4 <= stdoutUsed) {
      let length = readUInt32LE(stdout, offset);
      if (offset + 4 + length > stdoutUsed) {
        break;
      }
      offset += 4;
      handleIncomingPacket(stdout.slice(offset, offset + length));
      offset += length;
    }
    if (offset > 0) {
      stdout.set(stdout.slice(offset));
      stdoutUsed -= offset;
    }
  };
  let afterClose = () => {
    isClosed = true;
    for (let callback of callbacks.values()) {
      callback("The service was stopped", null);
    }
    callbacks.clear();
  };
  let sendRequest = (value, callback) => {
    if (isClosed)
      return callback("The service is no longer running", null);
    let id = nextID++;
    callbacks.set(id, callback);
    options.writeToStdin(encodePacket({id, isRequest: true, value}));
  };
  let sendResponse = (id, value) => {
    if (isClosed)
      throw new Error("The service is no longer running");
    options.writeToStdin(encodePacket({id, isRequest: false, value}));
  };
  let handleRequest = (id, command, request) => {
    try {
      switch (command) {
        default:
          throw new Error(`Invalid command: ` + command);
      }
    } catch (e) {
      let error = "Internal error";
      try {
        error = e + "";
      } catch {
      }
      sendResponse(id, {error});
    }
  };
  let handleIncomingPacket = (bytes) => {
    let packet = decodePacket(bytes);
    if (packet.isRequest) {
      handleRequest(packet.id, packet.value[0], packet.value[1]);
    } else {
      let callback = callbacks.get(packet.id);
      callbacks.delete(packet.id);
      if (packet.value.error)
        callback(packet.value.error, {});
      else
        callback(null, packet.value);
    }
  };
  return {
    readFromStdout,
    afterClose,
    service: {
      build(options2, isTTY2, callback) {
        let [flags, stdin, resolveDir] = flagsForBuildOptions(options2, isTTY2);
        let write = options2.write !== false;
        sendRequest(["build", {flags, write, stdin, resolveDir}], (error, response) => {
          if (error)
            return callback(new Error(error), null);
          let errors = response.errors;
          let warnings = response.warnings;
          if (errors.length > 0)
            return callback(failureErrorWithLog("Build failed", errors, warnings), null);
          let result = {warnings};
          if (!write)
            result.outputFiles = response.outputFiles;
          callback(null, result);
        });
      },
      transform(input, options2, isTTY2, callback) {
        let flags = flagsForTransformOptions(options2, isTTY2);
        sendRequest(["transform", {flags, input}], (error, response) => {
          if (error)
            return callback(new Error(error), null);
          let errors = response.errors;
          let warnings = response.warnings;
          if (errors.length > 0)
            return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
          callback(null, {warnings, js: response.js, jsSourceMap: response.jsSourceMap});
        });
      }
    }
  };
}
function failureErrorWithLog(text, errors, warnings) {
  let limit = 5;
  let summary = errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
    if (i === limit)
      return "\n...";
    if (!e.location)
      return `
error: ${e.text}`;
    let {file, line, column} = e.location;
    return `
${file}:${line}:${column}: error: ${e.text}`;
  }).join("");
  let error = new Error(`${text}${summary}`);
  error.errors = errors;
  error.warnings = warnings;
  return error;
}

// lib/node.ts
const child_process = __toModule(require("child_process"));
const path = __toModule(require("path"));
const tty = __toModule(require("tty"));
let esbuildCommandAndArgs = () => {
  if (true) {
    return ["node", [path.join(__dirname, "..", "bin", "esbuild")]];
  }
  if (process.platform === "win32") {
    return [path.join(__dirname, "..", "esbuild.exe"), []];
  }
  return [path.join(__dirname, "..", "bin", "esbuild"), []];
};
let isTTY = () => tty.isatty(2);
let build = (options) => {
  return startService().then((service) => {
    let promise = service.build(options);
    promise.then(service.stop, service.stop);
    return promise;
  });
};
let transform = (input, options) => {
  return startService().then((service) => {
    let promise = service.transform(input, options);
    promise.then(service.stop, service.stop);
    return promise;
  });
};
let buildSync = (options) => {
  let result;
  runServiceSync((service) => service.build(options, isTTY(), (err, res) => {
    if (err)
      throw err;
    result = res;
  }));
  return result;
};
let transformSync = (input, options) => {
  let result;
  runServiceSync((service) => service.transform(input, options, isTTY(), (err, res) => {
    if (err)
      throw err;
    result = res;
  }));
  return result;
};
let startService = (options) => {
  if (options) {
    if (options.wasmURL)
      throw new Error(`The "wasmURL" option only works in the browser`);
    if (options.worker)
      throw new Error(`The "worker" option only works in the browser`);
  }
  let [command, args] = esbuildCommandAndArgs();
  let child = child_process.spawn(command, args.concat("--service"), {
    cwd: process.cwd(),
    windowsHide: true,
    stdio: ["pipe", "pipe", "inherit"]
  });
  let {readFromStdout, afterClose, service} = createChannel({
    writeToStdin(bytes) {
      child.stdin.write(bytes);
    }
  });
  child.stdout.on("data", readFromStdout);
  child.stdout.on("end", afterClose);
  return Promise.resolve({
    build: (options2) => new Promise((resolve, reject) => service.build(options2, isTTY(), (err, res) => err ? reject(err) : resolve(res))),
    transform: (input, options2) => new Promise((resolve, reject) => service.transform(input, options2, isTTY(), (err, res) => err ? reject(err) : resolve(res))),
    stop() {
      child.kill();
    }
  });
};
let runServiceSync = (callback) => {
  let [command, args] = esbuildCommandAndArgs();
  let stdin = new Uint8Array();
  let {readFromStdout, afterClose, service} = createChannel({
    writeToStdin(bytes) {
      if (stdin.length !== 0)
        throw new Error("Must run at most one command");
      stdin = bytes;
    }
  });
  callback(service);
  let stdout = child_process.execFileSync(command, args.concat("--service"), {
    cwd: process.cwd(),
    windowsHide: true,
    input: stdin,
    maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
  });
  readFromStdout(stdout);
  afterClose();
};
let api = {
  build,
  buildSync,
  transform,
  transformSync,
  startService
};
module.exports = api;
