package builder import ( "encoding/json" "os" "path/filepath" "strings" ) // ImportMap represents a browser importmap. type ImportMap struct { Imports map[string]string `json:"imports"` } // GenerateImportMap scans libDir for .js files and produces an importmap JSON string. // // Naming rules: // - lib/chart.js → "chart" // - lib/icons/index.js → "icons" // - lib/utils/helpers.js → "utils/helpers" func GenerateImportMap(libDir string) (string, error) { imports := make(map[string]string) if _, err := os.Stat(libDir); os.IsNotExist(err) { b, _ := json.MarshalIndent(ImportMap{Imports: imports}, "", " ") return string(b), nil } err := filepath.WalkDir(libDir, func(path string, d os.DirEntry, err error) error { if err != nil || d.IsDir() || !strings.HasSuffix(path, ".js") { return err } rel, _ := filepath.Rel(libDir, path) rel = filepath.ToSlash(rel) dir := filepath.ToSlash(filepath.Dir(rel)) base := strings.TrimSuffix(filepath.Base(rel), ".js") var importName string switch { case dir == ".": importName = base case base == "index": importName = dir default: importName = dir + "/" + base } imports[importName] = "/lib/" + rel return nil }) if err != nil { return "", err } b, err := json.MarshalIndent(ImportMap{Imports: imports}, "", " ") return string(b), err }