"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// loaders/InjectBackgroundRuntimeLoader.ts
var InjectBackgroundRuntimeLoader_exports = {};
__export(InjectBackgroundRuntimeLoader_exports, {
  default: () => InjectBackgroundRuntimeLoader_default
});
module.exports = __toCommonJS(InjectBackgroundRuntimeLoader_exports);
var import_path = __toESM(require("path"));
var import_loader_utils = require("loader-utils");
var import_schema_utils = require("schema-utils");
var schema = {
  type: "object",
  properties: {
    test: {
      type: "string"
    },
    manifestPath: {
      type: "string"
    }
  }
};
var defaultBgEmitted = false;
function InjectBackgroundRuntimeLoader_default(source) {
  const options = this.getOptions();
  const manifestPath = options.manifestPath;
  const projectPath = import_path.default.dirname(manifestPath);
  const manifest = require(manifestPath);
  (0, import_schema_utils.validate)(schema, options, {
    name: "Inject Reload (background.scripts and background.service_worker) Script",
    baseDataPath: "options"
  });
  const url = (0, import_loader_utils.urlToRequest)(this.resourcePath);
  const generalReloadCode = `
  ;chrome.runtime.onMessageExternal.addListener(
    async (request, _sender, sendResponse) => {
      const managementInfo = await new Promise((resolve) => {
        chrome.management.getSelf(resolve);
      });
 
      // Ping-pong between the user extension background page(this)
      // and the middleware socket client (reloadService.ts),
      // which will then send a message to the server
      // (startServer.ts) so it can display the extension info.
      if (request.initialLoadData) {
        sendResponse({
          id: chrome.runtime.id,
          manifest: chrome.runtime.getManifest(),
          management: managementInfo,
        })
        return true
      }
  
      // Reload the extension runtime if the manifest or
      // service worker changes. 
      if (
        request.changedFile === 'manifest.json' ||
        request.changedFile === 'service_worker' ||
        request.changedFile === '_locales'
      ) {
        setTimeout(() => {
          sendResponse({reloaded: true})
          chrome.runtime.reload()
        }, 750)
      }

      // Reload all tabs if the contextMenus code changes.
      if (request.changedFile === 'contextMenus') {
        sendResponse({reloaded: true})
        chrome.tabs.query({}, (tabs) => {
          if (!tabs) return
          tabs.forEach((tab) => chrome.tabs.reload(tab.id))
        })
      }

      // Reload all tabs if the declarative_net_request code changes.
      if (request.changedFile === 'declarative_net_request') {
        sendResponse({reloaded: true})
        chrome.runtime.reload()
      }

      // Reload the active tab and the extension
      if (request.changedFile === 'USER_REQUEST') {
        sendResponse({reloaded: true})
        chrome.runtime.reload()

        chrome.tabs.query({}, (tabs) => {
          if (!tabs) return
          tabs.forEach((tab) => chrome.tabs.reload(tab.id))
        })
      }
  
      return true
    }
  );
  `;
  if (manifest.background) {
    if (manifest.background.scripts) {
      for (const bgScript of [manifest.background.scripts[0]]) {
        const absoluteUrl = import_path.default.resolve(projectPath, bgScript);
        if (url.includes(absoluteUrl)) {
          return `${generalReloadCode}${source}`;
        }
      }
    }
    if (manifest.background.service_worker) {
      const absoluteUrl = import_path.default.resolve(
        projectPath,
        manifest.background.service_worker
      );
      if (url.includes(absoluteUrl)) {
        return `${generalReloadCode}${source}`;
      }
    }
  }
  if (!manifest.background) {
    if (manifest.manifest_version === 2) {
      if (!defaultBgEmitted) {
        this.emitFile("background/script.js", generalReloadCode);
        defaultBgEmitted = true;
      }
    }
    if (manifest.manifest_version === 3) {
      if (!defaultBgEmitted) {
        this.emitFile("background/service_worker.js", generalReloadCode);
        defaultBgEmitted = true;
      }
    }
  }
  return source;
}
