func prettyPrintPath(fs fs.FS, path string) string {
	if relPath, ok := fs.Rel(fs.Cwd(), path); ok {
		return strings.ReplaceAll(relPath, "\\", "/")
	}
	return path
}
This is used to make error messages platform-independent
package api
import (
	"fmt"
	"net"
	"net/http"
	"path"
	"sort"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
	"github.com/evanw/esbuild/internal/config"
	"github.com/evanw/esbuild/internal/fs"
	"github.com/evanw/esbuild/internal/helpers"
	"github.com/evanw/esbuild/internal/logger"
)
type apiHandler struct {
	mutex            sync.Mutex
	outdirPathPrefix string
	servedir         string
	options          *config.Options
	onRequest        func(ServeOnRequestArgs)
	rebuild          func() BuildResult
	currentBuild     *runningBuild
	fs               fs.FS
	serveWaitGroup   sync.WaitGroup
	serveError       error
}
type runningBuild struct {
	waitGroup sync.WaitGroup
	result    BuildResult
}
func (h *apiHandler) build() BuildResult {
	build := func() *runningBuild {
		h.mutex.Lock()
		defer h.mutex.Unlock()
		if h.currentBuild == nil {
			build := &runningBuild{}
			build.waitGroup.Add(1)
			h.currentBuild = build
			go func() {
				result := h.rebuild()
				h.rebuild = result.Rebuild
				build.result = result
				build.waitGroup.Done()
				time.Sleep(250 * time.Millisecond)
				h.mutex.Lock()
				defer h.mutex.Unlock()
				h.currentBuild = nil
			}()
		}
		return h.currentBuild
	}()
	build.waitGroup.Wait()
	return build.result
}
func escapeForHTML(text string) string {
	text = strings.ReplaceAll(text, "&", "&amp;")
	text = strings.ReplaceAll(text, "<", "&lt;")
	text = strings.ReplaceAll(text, ">", "&gt;")
	return text
}
func escapeForAttribute(text string) string {
	text = escapeForHTML(text)
	text = strings.ReplaceAll(text, "\"", "&quot;")
	text = strings.ReplaceAll(text, "'", "&apos;")
	return text
}
func (h *apiHandler) notifyRequest(duration time.Duration, req *http.Request, status int) {
	if h.onRequest != nil {
		h.onRequest(ServeOnRequestArgs{
			RemoteAddress: req.RemoteAddr,
			Method:        req.Method,
			Path:          req.URL.Path,
			Status:        status,
			TimeInMS:      int(duration.Milliseconds()),
		})
	}
}
func errorsToString(errors []Message) string {
	stderrOptions := logger.OutputOptions{IncludeSource: true}
	terminalOptions := logger.TerminalInfo{}
	sb := strings.Builder{}
	limit := 5
	for i, msg := range convertMessagesToInternal(nil, logger.Error, errors) {
		if i == limit {
			sb.WriteString(fmt.Sprintf("%d out of %d errors shown\n", limit, len(errors)))
			break
		}
		sb.WriteString(msg.String(stderrOptions, terminalOptions))
	}
	return sb.String()
}
func (h *apiHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	start := time.Now()
	if req.Method == "GET" && strings.HasPrefix(req.URL.Path, "/") {
		res.Header().Set("Access-Control-Allow-Origin", "*")
		queryPath := path.Clean(req.URL.Path)[1:]
		result := h.build()
		if len(result.Errors) > 0 {
			go h.notifyRequest(time.Since(start), req, http.StatusServiceUnavailable)
			res.Header().Set("Content-Type", "text/plain; charset=utf-8")
			res.WriteHeader(http.StatusServiceUnavailable)
			res.Write([]byte(errorsToString(result.Errors)))
			return
		}
		var kind fs.EntryKind
		var fileContents fs.OpenedFile
		dirEntries := make(map[string]bool)
		fileEntries := make(map[string]bool)
		if strings.HasPrefix(queryPath, h.outdirPathPrefix) {
			outdirQueryPath := queryPath[len(h.outdirPathPrefix):]
			if strings.HasPrefix(outdirQueryPath, "/") {
				outdirQueryPath = outdirQueryPath[1:]
			}
			resultKind, inMemoryBytes := h.matchQueryPathToResult(outdirQueryPath, &result, dirEntries, fileEntries)
			kind = resultKind
			fileContents = &fs.InMemoryOpenedFile{Contents: inMemoryBytes}
		} else {
			p := h.outdirPathPrefix
			for p != "" {
				var dir string
				var base string
				if slash := strings.IndexByte(p, '/'); slash == -1 {
					base = p
				} else {
					dir = p[:slash]
					base = p[slash+1:]
				}
				if dir == queryPath {
					kind = fs.DirEntry
					dirEntries[base] = true
					break
				}
				p = dir
			}
		}
		if h.servedir != "" && kind != fs.FileEntry {
			absPath := h.fs.Join(h.servedir, queryPath)
			if absDir := h.fs.Dir(absPath); absDir != absPath {
				if entries, err, _ := h.fs.ReadDirectory(absDir); err == nil {
					if entry, _ := entries.Get(h.fs.Base(absPath)); entry != nil && entry.Kind(h.fs) == fs.FileEntry {
						if contents, err, _ := h.fs.OpenFile(absPath); err == nil {
							defer contents.Close()
							fileContents = contents
							kind = fs.FileEntry
						} else if err != syscall.ENOENT {
							go h.notifyRequest(time.Since(start), req, http.StatusInternalServerError)
							res.WriteHeader(http.StatusInternalServerError)
							res.Write([]byte(fmt.Sprintf("500 - Internal server error: %s", err.Error())))
							return
						}
					}
				}
			}
		}
		var fallbackIndexName string
		if h.servedir != "" && kind != fs.FileEntry {
			if entries, err, _ := h.fs.ReadDirectory(h.fs.Join(h.servedir, queryPath)); err == nil {
				kind = fs.DirEntry
				for _, name := range entries.SortedKeys() {
					entry, _ := entries.Get(name)
					switch entry.Kind(h.fs) {
					case fs.DirEntry:
						dirEntries[name] = true
					case fs.FileEntry:
						fileEntries[name] = true
						if name == "index.html" {
							fallbackIndexName = name
						}
					}
				}
			} else if err != syscall.ENOENT {
				go h.notifyRequest(time.Since(start), req, http.StatusInternalServerError)
				res.WriteHeader(http.StatusInternalServerError)
				res.Write([]byte(fmt.Sprintf("500 - Internal server error: %s", err.Error())))
				return
			}
		}
		if kind == fs.DirEntry && !strings.HasSuffix(req.URL.Path, "/") {
			res.Header().Set("Location", req.URL.Path+"/")
			go h.notifyRequest(time.Since(start), req, http.StatusFound)
			res.WriteHeader(http.StatusFound)
			res.Write(nil)
			return
		}
		if kind == fs.DirEntry && fallbackIndexName != "" {
			queryPath += "/" + fallbackIndexName
			if contents, err, _ := h.fs.OpenFile(h.fs.Join(h.servedir, queryPath)); err == nil {
				defer contents.Close()
				fileContents = contents
				kind = fs.FileEntry
			} else if err != syscall.ENOENT {
				go h.notifyRequest(time.Since(start), req, http.StatusInternalServerError)
				res.WriteHeader(http.StatusInternalServerError)
				res.Write([]byte(fmt.Sprintf("500 - Internal server error: %s", err.Error())))
				return
			}
		}
		if kind == fs.FileEntry {
			status := http.StatusOK
			fileContentsLen := fileContents.Len()
			begin := 0
			end := fileContentsLen
			isRange := false
			if rangeBegin, rangeEnd, ok := parseRangeHeader(req.Header.Get("Range"), fileContentsLen); ok && rangeBegin < rangeEnd {
				isRange = true
				begin = rangeBegin
				end = rangeEnd
				status = http.StatusPartialContent
			}
			fileBytes, err := fileContents.Read(begin, end)
			if err != nil {
				go h.notifyRequest(time.Since(start), req, http.StatusInternalServerError)
				res.WriteHeader(http.StatusInternalServerError)
				res.Write([]byte(fmt.Sprintf("500 - Internal server error: %s", err.Error())))
				return
			}
			if contentType := helpers.MimeTypeByExtension(path.Ext(queryPath)); contentType != "" {
				res.Header().Set("Content-Type", contentType)
			} else {
				res.Header().Set("Content-Type", "application/octet-stream")
			}
			if isRange {
				res.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", begin, end-1, fileContentsLen))
			}
			res.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileBytes)))
			go h.notifyRequest(time.Since(start), req, status)
			res.WriteHeader(status)
			res.Write(fileBytes)
			return
		}
		if kind == fs.DirEntry {
			html := respondWithDirList(queryPath, dirEntries, fileEntries)
			res.Header().Set("Content-Type", "text/html; charset=utf-8")
			res.Header().Set("Content-Length", fmt.Sprintf("%d", len(html)))
			go h.notifyRequest(time.Since(start), req, http.StatusOK)
			res.Write(html)
			return
		}
	}
	res.Header().Set("Content-Type", "text/plain; charset=utf-8")
	go h.notifyRequest(time.Since(start), req, http.StatusNotFound)
	res.WriteHeader(http.StatusNotFound)
	res.Write([]byte("404 - Not Found"))
}
func parseRangeHeader(r string, contentLength int) (int, int, bool) {
	if strings.HasPrefix(r, "bytes=") {
		r = r[len("bytes="):]
		if dash := strings.IndexByte(r, '-'); dash != -1 {
			if begin, ok := parseRangeInt(r[:dash], contentLength-1); ok {
				if end, ok := parseRangeInt(r[dash+1:], contentLength-1); ok {
					return begin, end + 1, true
				}
			}
		}
	}
	return 0, 0, false
}
func parseRangeInt(text string, maxValue int) (int, bool) {
	if text == "" {
		return 0, false
	}
	value := 0
	for _, c := range text {
		if c < '0' || c > '9' {
			return 0, false
		}
		value = value*10 + int(c-'0')
		if value > maxValue {
			return 0, false
		}
	}
	return value, true
}
func (h *apiHandler) matchQueryPathToResult(
	queryPath string,
	result *BuildResult,
	dirEntries map[string]bool,
	fileEntries map[string]bool,
) (fs.EntryKind, []byte) {
	queryIsDir := false
	queryDir := queryPath
	if queryDir != "" {
		queryDir += "/"
	}
	for _, file := range result.OutputFiles {
		if relPath, ok := h.fs.Rel(h.options.AbsOutputDir, file.Path); ok {
			relPath = strings.ReplaceAll(relPath, "\\", "/")
			if relPath == queryPath {
				return fs.FileEntry, file.Contents
			}
			if strings.HasPrefix(relPath, queryDir) {
				entry := relPath[len(queryDir):]
				queryIsDir = true
				if slash := strings.IndexByte(entry, '/'); slash == -1 {
					fileEntries[entry] = true
				} else if dir := entry[:slash]; !dirEntries[dir] {
					dirEntries[dir] = true
				}
			}
		}
	}
	if queryIsDir {
		return fs.DirEntry, nil
	}
	return 0, nil
}
func respondWithDirList(queryPath string, dirEntries map[string]bool, fileEntries map[string]bool) []byte {
	queryPath = "/" + queryPath
	queryDir := queryPath
	if queryDir != "/" {
		queryDir += "/"
	}
	html := strings.Builder{}
	html.WriteString(`<!doctype html>`)
	html.WriteString(`<meta charset="utf8">`)
	html.WriteString(`<title>Directory: `)
	html.WriteString(escapeForHTML(queryDir))
	html.WriteString(`</title>`)
	html.WriteString(`<h1>Directory: `)
	html.WriteString(escapeForHTML(queryDir))
	html.WriteString(`</h1>`)
	html.WriteString(`<ul>`)
	if queryPath != "/" {
		parentDir := path.Dir(queryPath)
		if parentDir != "/" {
			parentDir += "/"
		}
		html.WriteString(fmt.Sprintf(`<li><a href="%s">../</a></li>`, escapeForAttribute(parentDir)))
	}
	strings := make([]string, 0, len(dirEntries)+len(fileEntries))
	for entry := range dirEntries {
		strings = append(strings, entry)
	}
	sort.Strings(strings)
	for _, entry := range strings {
		html.WriteString(fmt.Sprintf(`<li><a href="%s/">%s/</a></li>`, escapeForAttribute(path.Join(queryPath, entry)), escapeForHTML(entry)))
	}
	strings = strings[:0]
	for entry := range fileEntries {
		strings = append(strings, entry)
	}
	sort.Strings(strings)
	for _, entry := range strings {
		html.WriteString(fmt.Sprintf(`<li><a href="%s">%s</a></li>`, escapeForAttribute(path.Join(queryPath, entry)), escapeForHTML(entry)))
	}
	html.WriteString(`</ul>`)
	return []byte(html.String())
}