"use strict";
const __rslib_import_meta_url__ = /*#__PURE__*/ function() {
    return "u" < typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
}();
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    default: ()=>warn_no_default_export
});
const external_fs_namespaceObject = require("fs");
var external_fs_default = /*#__PURE__*/ __webpack_require__.n(external_fs_namespaceObject);
const external_path_namespaceObject = require("path");
var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
function findUpLocalSync(filename, options) {
    const root = external_path_namespaceObject.parse(options.cwd).root;
    let currentDir = options.cwd;
    while(true){
        const candidate = external_path_namespaceObject.join(currentDir, filename);
        try {
            const stat = external_fs_namespaceObject.statSync(candidate);
            if (stat.isFile()) return candidate;
        } catch  {}
        if (currentDir === root) return;
        currentDir = external_path_namespaceObject.dirname(currentDir);
    }
}
function findNearestPackageJsonSync(manifestPath) {
    try {
        const manifestDir = external_path_namespaceObject.dirname(manifestPath);
        const packageJsonPath = findUpLocalSync('package.json', {
            cwd: manifestDir
        });
        return packageJsonPath || null;
    } catch (error) {
        console.warn('Failed to find package.json:', error);
        return null;
    }
}
require("pintor");
require("crypto");
require("child_process");
const external_module_namespaceObject = require("module");
(0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
require("os");
(0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
function runtime_context_parseJsonSafe(text) {
    const raw = 'string' == typeof text ? text : String(text || '');
    const s = raw && 0xfeff === raw.charCodeAt(0) ? raw.slice(1) : raw;
    return JSON.parse(s || '{}');
}
function hasDependency(projectPath, dependency) {
    const findNearestPackageJsonDirectory = (startPath)=>{
        let currentDirectory = startPath;
        const maxDepth = 4;
        for(let i = 0; i < maxDepth; i++){
            const candidate = external_path_namespaceObject.join(currentDirectory, 'package.json');
            if (external_fs_namespaceObject.existsSync(candidate)) return currentDirectory;
            const parentDirectory = external_path_namespaceObject.dirname(currentDirectory);
            if (parentDirectory === currentDirectory) break;
            currentDirectory = parentDirectory;
        }
    };
    const packageJsonDirectory = findNearestPackageJsonDirectory(projectPath);
    if (!packageJsonDirectory) return false;
    const packageJsonPath = external_path_namespaceObject.join(packageJsonDirectory, 'package.json');
    if (!external_fs_namespaceObject.existsSync(packageJsonPath)) return false;
    const parsed = runtime_context_parseJsonSafe(external_fs_namespaceObject.readFileSync(packageJsonPath, 'utf8'));
    const dependencies = parsed.dependencies || {};
    const devDependencies = parsed.devDependencies || {};
    return !!dependencies[dependency] || !!devDependencies[dependency];
}
const core_namespaceObject = require("@swc/core");
const external_schema_utils_namespaceObject = require("schema-utils");
const schema = {
    type: 'object',
    properties: {
        test: {
            type: 'string'
        },
        manifestPath: {
            type: 'string'
        },
        mode: {
            type: 'string'
        }
    }
};
const EXAMPLES_BASE = 'https://github.com/extension-js/examples/blob/main';
function getContentScriptSampleInfo(packageJsonDir, resourcePath) {
    if (hasDependency(packageJsonDir, 'react')) return {
        phrase: 'See React sample',
        url: `${EXAMPLES_BASE}/react/src/content/scripts.tsx`
    };
    if (hasDependency(packageJsonDir, 'preact')) return {
        phrase: 'See Preact sample',
        url: `${EXAMPLES_BASE}/preact/src/content/scripts.tsx`
    };
    if (hasDependency(packageJsonDir, 'vue')) return {
        phrase: 'See Vue sample',
        url: `${EXAMPLES_BASE}/vue/src/content/scripts.ts`
    };
    if (hasDependency(packageJsonDir, 'svelte')) return {
        phrase: 'See Svelte sample',
        url: `${EXAMPLES_BASE}/svelte/src/content/scripts.ts`
    };
    const ext = external_path_default().extname(resourcePath).toLowerCase();
    if ('.ts' === ext || '.tsx' === ext || '.mts' === ext || '.mtsx' === ext) return {
        phrase: 'See TypeScript sample',
        url: `${EXAMPLES_BASE}/typescript/src/content/scripts.ts`
    };
    return {
        phrase: 'See vanilla JS sample',
        url: `${EXAMPLES_BASE}/content/src/content/scripts.js`
    };
}
function getSourceSignature(source) {
    const head = source.slice(0, 64);
    const tail = source.slice(-64);
    return `${source.length}:${head}:${tail}`;
}
function analyzeDefaultExport(source, resourcePath, compilation) {
    const abs = external_path_default().normalize(resourcePath);
    const sig = getSourceSignature(source);
    const cacheKey = `${abs}|${sig}`;
    try {
        const compilationAny = compilation;
        if (compilationAny) {
            compilationAny.__extjsDefaultExportAnalysisCache ??= new Map();
            const cached = compilationAny.__extjsDefaultExportAnalysisCache.get(cacheKey);
            if (cached) return cached;
        }
        const ext = external_path_default().extname(resourcePath).toLowerCase();
        const isTS = '.ts' === ext || '.tsx' === ext || '.mts' === ext || '.mtsx' === ext;
        const isJSX = '.jsx' === ext || '.tsx' === ext || '.mjsx' === ext || '.mtsx' === ext;
        const ast = (0, core_namespaceObject.parseSync)(source, {
            syntax: isTS ? "typescript" : "ecmascript",
            tsx: isTS && isJSX,
            jsx: !isTS && isJSX,
            decorators: true,
            dynamicImport: true,
            importAssertions: true,
            topLevelAwait: true
        });
        const body = Array.isArray(ast?.body) ? ast.body : [];
        const bindings = new Map();
        const recordBinding = (name, kind)=>{
            if ('string' == typeof name && name) bindings.set(name, kind);
        };
        const inspectDecl = (node)=>{
            if ('FunctionDeclaration' === node.type) {
                const id = node.identifier;
                recordBinding(id?.value, 'function');
            } else if ('ClassDeclaration' === node.type) {
                const id = node.identifier;
                recordBinding(id?.value, 'class');
            } else if ('VariableDeclaration' === node.type) {
                const decls = node.declarations;
                if (!Array.isArray(decls)) return;
                for (const d of decls){
                    if (!d || 'object' != typeof d) continue;
                    const dd = d;
                    const id = dd.id;
                    const init = dd.init;
                    if (id?.type !== 'Identifier') continue;
                    const name = id.value;
                    const initType = init?.type;
                    if ('FunctionExpression' === initType || 'ArrowFunctionExpression' === initType) recordBinding(name, 'function');
                    else if ('ClassExpression' === initType) recordBinding(name, 'class');
                    else if (initType) recordBinding(name, 'other');
                }
            }
        };
        for (const item of body){
            if (!item || 'object' != typeof item) continue;
            const it = item;
            if ('FunctionDeclaration' === it.type || 'ClassDeclaration' === it.type || 'VariableDeclaration' === it.type) inspectDecl(it);
            if ('ExportNamedDeclaration' === it.type) {
                const decl = it.declaration;
                if (decl && 'object' == typeof decl) inspectDecl(decl);
            }
        }
        const resolveIdentifierKind = (name)=>bindings.get(name) ?? 'unknown';
        const analysis = {
            hasDefaultExport: false,
            kind: 'none'
        };
        for (const item of body){
            if (!item || 'object' != typeof item) continue;
            const it = item;
            if ('ExportDefaultDeclaration' === it.type) {
                analysis.hasDefaultExport = true;
                const decl = it.decl;
                const declType = decl?.type;
                if ('FunctionDeclaration' === declType || 'FunctionExpression' === declType) analysis.kind = 'function';
                else if ('ClassDeclaration' === declType || 'ClassExpression' === declType) analysis.kind = 'class';
                else analysis.kind = 'other';
                break;
            }
            if ('ExportDefaultExpression' === it.type) {
                analysis.hasDefaultExport = true;
                const expr = it.expression;
                const exprType = expr?.type;
                if ('FunctionExpression' === exprType || 'ArrowFunctionExpression' === exprType) analysis.kind = 'function';
                else if ('ClassExpression' === exprType) analysis.kind = 'class';
                else if ('Identifier' === exprType && 'string' == typeof expr?.value) analysis.kind = resolveIdentifierKind(expr.value);
                else analysis.kind = 'other';
                break;
            }
            if ('ExportNamedDeclaration' === it.type && Array.isArray(it.specifiers)) {
                for (const specifier of it.specifiers){
                    if (!specifier || 'object' != typeof specifier) continue;
                    const spec = specifier;
                    if ('ExportSpecifier' !== spec.type) continue;
                    const exported = spec.exported;
                    const orig = spec.orig;
                    const exportedType = exported?.type;
                    const exportedValue = exported?.value;
                    const isDefault = 'Identifier' === exportedType ? 'default' === exportedValue : 'Ident' === exportedType ? 'default' === exportedValue : 'Str' === exportedType ? 'default' === exportedValue : false;
                    if (isDefault) {
                        analysis.hasDefaultExport = true;
                        if (orig?.type === 'Identifier' && 'string' == typeof orig?.value) analysis.kind = resolveIdentifierKind(orig.value);
                        else analysis.kind = 'unknown';
                        break;
                    }
                }
                if (analysis.hasDefaultExport) break;
            }
        }
        if (compilationAny) compilationAny.__extjsDefaultExportAnalysisCache.set(cacheKey, analysis);
        return analysis;
    } catch  {
        const fallback = source.includes('export default') ? {
            hasDefaultExport: true,
            kind: 'unknown'
        } : {
            hasDefaultExport: false,
            kind: 'none'
        };
        try {
            const compilationAny = compilation;
            if (compilationAny?.__extjsDefaultExportAnalysisCache) compilationAny.__extjsDefaultExportAnalysisCache.set(cacheKey, fallback);
        } catch  {}
        return fallback;
    }
}
function warn_no_default_export(source) {
    const options = this.getOptions();
    const manifestPath = options.manifestPath;
    const manifest = JSON.parse(external_fs_default().readFileSync(manifestPath, 'utf-8'));
    const resourceQuery = this.resourceQuery;
    if ('string' == typeof resourceQuery && resourceQuery.includes('__extjs_inner=1')) return source;
    (0, external_schema_utils_namespaceObject.validate)(schema, options, {
        name: "scripts:warn-no-default-export",
        baseDataPath: 'options'
    });
    try {
        const resourceAbsPath = external_path_default().normalize(this.resourcePath);
        const manifestDir = external_path_default().dirname(manifestPath);
        const packageJsonPath = findNearestPackageJsonSync(manifestPath);
        const packageJsonDir = packageJsonPath ? external_path_default().dirname(packageJsonPath) : manifestDir;
        const compilation = this._compilation;
        const dedupeKey = `no-default:${resourceAbsPath}`;
        if (compilation) {
            compilation.__extjsWarnedDefaultExport ??= new Set();
            if (compilation.__extjsWarnedDefaultExport.has(dedupeKey)) return source;
        }
        const declaredContentJsAbsPaths = [];
        const contentScripts = Array.isArray(manifest.content_scripts) ? manifest.content_scripts : [];
        for (const contentScript of contentScripts){
            const contentScriptJsList = Array.isArray(contentScript?.js) ? contentScript.js : [];
            for (const contentScriptJs of contentScriptJsList)declaredContentJsAbsPaths.push(external_path_default().resolve(manifestDir, contentScriptJs));
        }
        const isDeclaredContentScript = declaredContentJsAbsPaths.some((abs)=>resourceAbsPath === external_path_default().normalize(abs));
        const scriptsDir = external_path_default().resolve(packageJsonDir, "scripts");
        const relToScripts = external_path_default().relative(scriptsDir, resourceAbsPath);
        const isScriptsFolderScript = relToScripts && !relToScripts.startsWith('..') && !external_path_default().isAbsolute(relToScripts);
        const isContentScriptLike = isDeclaredContentScript || isScriptsFolderScript;
        if (isContentScriptLike) {
            const analysis = analyzeDefaultExport(source, this.resourcePath, compilation);
            if (analysis.hasDefaultExport) {
                if ('class' === analysis.kind || 'other' === analysis.kind) {
                    const dedupeKindKey = `default-not-callable:${resourceAbsPath}`;
                    if (compilation) {
                        compilation.__extjsWarnedDefaultExportKinds ??= new Set();
                        if (compilation.__extjsWarnedDefaultExportKinds.has(dedupeKindKey)) return source;
                    }
                    const relativeFile = external_path_default().relative(packageJsonDir, resourceAbsPath);
                    const found = 'class' === analysis.kind ? 'class' : 'non-callable value';
                    const sample = getContentScriptSampleInfo(packageJsonDir, this.resourcePath);
                    const message = [
                        "Content script default export must be a function.",
                        `  │ File: ${relativeFile}`,
                        "  │",
                        `  │ Found: ${found}. Export a default function that sets up your script and returns optional cleanup.`,
                        "  │ Without it: duplicate UI mounts, memory leaks, and inconsistent state during HMR.",
                        `  │ ${sample.phrase} ${sample.url}`
                    ].join('\n');
                    compilation?.warnings.push(message);
                    compilation?.__extjsWarnedDefaultExportKinds?.add(dedupeKindKey);
                }
            } else {
                const relativeFile = external_path_default().relative(packageJsonDir, resourceAbsPath);
                const sample = getContentScriptSampleInfo(packageJsonDir, this.resourcePath);
                const message = [
                    "Content script requires a default export.",
                    ` File: ${relativeFile}`,
                    "",
                    " Export a default function so Extension.js can mount and cleanup safely.",
                    " Without it: duplicate UI mounts and inconsistent state during HMR.",
                    ` ${sample.phrase}: ${sample.url}`
                ].join('\n');
                compilation?.warnings.push(message);
                compilation?.__extjsWarnedDefaultExport?.add(dedupeKey);
            }
        }
    } catch  {}
    return source;
}
exports["default"] = __webpack_exports__["default"];
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "default"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
