{"version":3,"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Import Map Devtools Loader\n *\n * This script is designed to be loaded early in the page lifecycle, before import maps\n * are processed by the browser. It applies overrides from localStorage to any import maps\n * in the page, and sets up a MutationObserver to handle dynamically added import maps.\n */\n\nconst LOCAL_STORAGE_KEY = \"import-map-overrides\";\nconst ORIGINALS_STORAGE_KEY = \"import-map-originals\";\n\n// Log with a consistent prefix\nfunction log(...args: any[]) {\n  console.log(\"[Import Map Devtools]\", ...args);\n}\n\nfunction logError(...args: any[]) {\n  console.error(\"[Import Map Devtools]\", ...args);\n}\n\nfunction logWarning(...args: any[]) {\n  console.warn(\"[Import Map Devtools]\", ...args);\n}\n\n// Log function that shows the current import map in the DOM\nfunction logCurrentImportMap() {\n  const importMaps = document.querySelectorAll('script[type=\"importmap\"]');\n  if (importMaps.length === 0) {\n    log(\"No import maps found in document\");\n    return;\n  }\n\n  log(`Current import map(s) in DOM (${importMaps.length} found):`);\n  importMaps.forEach((importMap, index) => {\n    try {\n      const content = JSON.parse(importMap.textContent || \"{}\");\n      log(`Import map #${index + 1}:`, content);\n    } catch (e) {\n      logError(\n        `Failed to parse import map #${index + 1}:`,\n        importMap.textContent\n      );\n    }\n  });\n}\n\n/**\n * Get all overrides from local storage\n */\nfunction getOverrides(): Record<string, string> {\n  try {\n    const overrides = JSON.parse(\n      localStorage.getItem(LOCAL_STORAGE_KEY) || \"{}\"\n    );\n    if (Object.keys(overrides).length > 0) {\n      log(\"Loaded overrides from localStorage:\", overrides);\n    }\n    return overrides;\n  } catch (e) {\n    logError(\"Error retrieving import map overrides from localStorage\", e);\n    return {};\n  }\n}\n\n/**\n * Get original import map URLs from local storage\n */\nfunction getOriginals(): Record<string, string> {\n  try {\n    return JSON.parse(localStorage.getItem(ORIGINALS_STORAGE_KEY) || \"{}\");\n  } catch (e) {\n    logError(\"Error retrieving original import map URLs from localStorage\", e);\n    return {};\n  }\n}\n\n/**\n * Save original import map URLs to local storage\n */\nfunction saveOriginals(originals: Record<string, string>): void {\n  try {\n    const existingOriginals = getOriginals();\n    const mergedOriginals = { ...existingOriginals, ...originals };\n    localStorage.setItem(\n      ORIGINALS_STORAGE_KEY,\n      JSON.stringify(mergedOriginals)\n    );\n    log(\"Saved original import map URLs to localStorage:\", mergedOriginals);\n  } catch (e) {\n    logError(\"Error saving original import map URLs to localStorage\", e);\n  }\n}\n\n/**\n * Save original URLs from an import map\n */\nfunction saveOriginalUrls(importMapEl: HTMLScriptElement): void {\n  try {\n    let currentMap = JSON.parse(importMapEl.textContent || '{\"imports\":{}}');\n    if (currentMap.imports && Object.keys(currentMap.imports).length > 0) {\n      const overrides = getOverrides();\n      const originals: Record<string, string> = {};\n\n      // Only save URLs that aren't already overridden\n      for (const [moduleName, url] of Object.entries(currentMap.imports)) {\n        if (!overrides[moduleName]) {\n          originals[moduleName] = url as string;\n        }\n      }\n\n      if (Object.keys(originals).length > 0) {\n        log(\"Saving original URLs for modules:\", Object.keys(originals));\n        saveOriginals(originals);\n      }\n    }\n  } catch (error) {\n    logError(\"Error saving original import map URLs:\", error);\n  }\n}\n\n/**\n * Get all import maps combined into a single object\n * This merges all import maps in the document\n */\nfunction getCombinedImportMap(): { imports: Record<string, string> } {\n  const importMaps = document.querySelectorAll('script[type=\"importmap\"]');\n  const combined = { imports: {} as Record<string, string> };\n\n  importMaps.forEach((importMapEl) => {\n    try {\n      const content = JSON.parse(importMapEl.textContent || '{\"imports\":{}}');\n      if (content.imports) {\n        Object.assign(combined.imports, content.imports);\n      }\n    } catch (e) {\n      logError(\"Error parsing import map while combining:\", e);\n    }\n  });\n\n  return combined;\n}\n\n/**\n * Apply overrides to an import map element\n */\nfunction applyOverridesToImportMap(importMapEl: HTMLScriptElement): void {\n  const overrides = getOverrides();\n\n  if (Object.keys(overrides).length === 0) {\n    log(\"No overrides to apply\");\n    return; // No overrides to apply\n  }\n\n  log(\"Starting to apply overrides to import map:\", importMapEl);\n\n  // First log the content before changes\n  try {\n    log(\"Import map content before overrides:\", importMapEl.textContent);\n  } catch (e) {\n    logError(\"Couldn't log import map content:\", e);\n  }\n\n  try {\n    // Get the current import map content\n    let currentMap;\n    try {\n      currentMap = JSON.parse(importMapEl.textContent || '{\"imports\":{}}');\n\n      // Save original URLs before applying overrides\n      saveOriginalUrls(importMapEl);\n    } catch (error) {\n      logError(\"Invalid import map JSON, creating new one:\", error);\n      currentMap = { imports: {} };\n    }\n\n    // Apply overrides\n    if (!currentMap.imports) {\n      currentMap.imports = {};\n    }\n\n    // Check if we're actually changing anything\n    let changes = 0;\n    for (const [moduleName, url] of Object.entries(overrides)) {\n      if (currentMap.imports[moduleName] !== url) {\n        log(\n          `Overriding \"${moduleName}\" from \"${\n            currentMap.imports[moduleName] || \"undefined\"\n          }\" to \"${url}\"`\n        );\n        currentMap.imports[moduleName] = url;\n        changes++;\n      }\n    }\n\n    if (changes > 0) {\n      // Update the import map element with the new content\n      const newContent = JSON.stringify(currentMap, null, 2);\n      log(\"Setting new import map content:\", newContent);\n      importMapEl.textContent = newContent;\n\n      // Force a re-parse of the import map by removing and re-adding it to the DOM\n      const parent = importMapEl.parentNode;\n      if (parent) {\n        const newImportMap = document.createElement(\"script\");\n        newImportMap.setAttribute(\"type\", \"importmap\");\n        newImportMap.textContent = newContent;\n\n        // Replace the old import map with the new one\n        parent.replaceChild(newImportMap, importMapEl);\n        log(\"Replaced import map in DOM to ensure browser recognizes changes\");\n      } else {\n        logWarning(\"Couldn't replace import map in DOM, parent node not found\");\n      }\n\n      log(`Updated import map with ${changes} override(s)`);\n\n      // Log the full import map after changes to verify\n      logCurrentImportMap();\n    } else {\n      log(\"No changes needed to import map, overrides already applied\");\n    }\n  } catch (error) {\n    logError(\"Error applying import map overrides:\", error);\n  }\n}\n\n/**\n * Create a merged import map and ensure it's the only one in the document\n */\nfunction createMergedImportMap(): HTMLScriptElement | null {\n  const overrides = getOverrides();\n\n  // Get all existing import maps\n  const importMaps = document.querySelectorAll('script[type=\"importmap\"]');\n  const combinedMap = getCombinedImportMap();\n\n  // Apply overrides to the combined map\n  for (const [moduleName, url] of Object.entries(overrides)) {\n    combinedMap.imports[moduleName] = url;\n  }\n\n  // Create the single merged import map\n  const newImportMap = document.createElement(\"script\");\n  newImportMap.setAttribute(\"type\", \"importmap\");\n  const content = JSON.stringify(combinedMap, null, 2);\n  newImportMap.textContent = content;\n\n  // Remove all existing import maps\n  importMaps.forEach((map) => {\n    if (map.parentNode) {\n      log(\"Removing existing import map:\", map.textContent);\n      map.parentNode.removeChild(map);\n    }\n  });\n\n  // Insert the merged import map\n  document.head.insertBefore(newImportMap, document.head.firstChild);\n  log(\"Created merged import map with all modules:\", content);\n\n  return newImportMap;\n}\n\n/**\n * Apply overrides to all import maps in the document\n */\nfunction applyOverridesToAllImportMaps(): void {\n  log(\"Starting to apply overrides to all import maps\");\n  logCurrentImportMap();\n\n  const importMaps = document.querySelectorAll('script[type=\"importmap\"]');\n\n  if (importMaps.length === 0) {\n    log(\"No import maps found in document\");\n    // Create a new import map if needed\n    createMergedImportMap();\n    return;\n  }\n\n  if (importMaps.length > 1) {\n    log(`Found ${importMaps.length} import maps - merging them into one`);\n    // Merge all import maps into one\n    createMergedImportMap();\n    return;\n  }\n\n  log(`Found 1 import map in document`);\n  // Apply overrides to the single import map\n  applyOverridesToImportMap(importMaps[0] as HTMLScriptElement);\n\n  log(\"Finished applying overrides to all import maps\");\n  logCurrentImportMap();\n}\n\n/**\n * Initialize the loader\n */\nfunction init(): void {\n  log(\"Loader initializing...\");\n\n  // Apply overrides to existing import maps\n  applyOverridesToAllImportMaps();\n\n  // Set up a MutationObserver to watch for new import maps\n  log(\"Setting up MutationObserver to watch for new import maps\");\n  const observer = new MutationObserver((mutations) => {\n    for (const mutation of mutations) {\n      if (mutation.type !== \"childList\") continue;\n\n      let importMapAdded = false;\n\n      mutation.addedNodes.forEach((node) => {\n        if (node.nodeType === Node.ELEMENT_NODE) {\n          const el = node as Element;\n\n          // Check if the added node is an import map\n          if (\n            el.tagName === \"SCRIPT\" &&\n            el.getAttribute(\"type\") === \"importmap\"\n          ) {\n            importMapAdded = true;\n          }\n\n          // Check for import maps within the added node\n          const importMaps = el.querySelectorAll('script[type=\"importmap\"]');\n          if (importMaps.length > 0) {\n            importMapAdded = true;\n          }\n        }\n      });\n\n      // If any import map was added, merge them all\n      if (importMapAdded) {\n        log(\"New import map detected, merging all import maps\");\n        setTimeout(() => applyOverridesToAllImportMaps(), 0);\n      }\n    }\n  });\n\n  // Observe changes to the document\n  observer.observe(document, { childList: true, subtree: true });\n\n  // Listen for storage events to update when overrides change in other tabs\n  window.addEventListener(\"storage\", (event) => {\n    if (event.key === LOCAL_STORAGE_KEY) {\n      log(\"Overrides changed in another tab, applying updates\");\n      applyOverridesToAllImportMaps();\n    }\n  });\n\n  // Listen for custom events from the import-map-devtools library\n  window.addEventListener(\"import-map-overrides:change\", () => {\n    log(\"Detected change event, re-applying overrides\");\n    applyOverridesToAllImportMaps();\n  });\n\n  // Create a custom event for the main library to know the loader is active\n  window.dispatchEvent(new CustomEvent(\"import-map-devtools:loader-ready\"));\n\n  log(\"Loader initialization complete\");\n\n  // Periodically check and reapply import maps in case things change\n  setInterval(() => {\n    log(\"Periodic check and reapply of import maps\");\n    applyOverridesToAllImportMaps();\n  }, 5000);\n}\n\n// Run the initialization\ninit();\n"],"mappings":";;;AAQA,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB;AAG9B,SAAS,OAAO,MAAa;AAC3B,UAAQ,IAAI,yBAAyB,GAAG,IAAI;AAC9C;AAEA,SAAS,YAAY,MAAa;AAChC,UAAQ,MAAM,yBAAyB,GAAG,IAAI;AAChD;AAEA,SAAS,cAAc,MAAa;AAClC,UAAQ,KAAK,yBAAyB,GAAG,IAAI;AAC/C;AAGA,SAAS,sBAAsB;AAC7B,QAAM,aAAa,SAAS,iBAAiB,0BAA0B;AACvE,MAAI,WAAW,WAAW,GAAG;AAC3B,QAAI,kCAAkC;AACtC;AAAA,EACF;AAEA,MAAI,iCAAiC,WAAW,MAA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