"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.JAVASCRIPT_WEB_AGENT_CONFIG = void 0;
const constants_1 = require("../../lib/constants");
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const package_json_light_1 = require("../../utils/package-json-light");
const utils_1 = require("./utils");
const package_manager_detection_light_1 = require("../../lib/package-manager-detection-light");
const browser_sdk_prompt_1 = require("../_shared/browser-sdk-prompt");
const javascript_web_blocking_policy_1 = require("../_shared/javascript-web-blocking-policy");
const vue_powered_docs_site_1 = require("../_shared/vue-powered-docs-site");
exports.JAVASCRIPT_WEB_AGENT_CONFIG = {
    metadata: {
        name: 'JavaScript (Web)',
        glyph: '🌐',
        glyphColor: '#F7DF1E',
        integration: constants_1.Integration.javascript_web,
        targetsBrowser: true,
        beta: true,
        docsUrl: 'https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2',
        gatherContext: async (options) => {
            const packageManagerName = await (0, utils_1.detectJsPackageManager)(options);
            const hasTypeScript = fs.existsSync(path.join(options.installDir, 'tsconfig.json'));
            const hasBundler = (0, utils_1.detectBundler)(options);
            const packageJson = await (0, package_json_light_1.tryGetPackageJson)(options);
            return {
                packageManagerName,
                hasTypeScript,
                hasBundler,
                vuePoweredDocsSite: packageJson
                    ? (0, vue_powered_docs_site_1.isVuePoweredDocsSite)(packageJson)
                    : false,
            };
        },
    },
    detection: {
        packageName: '@amplitude/analytics-browser',
        packageDisplayName: 'JavaScript (Web)',
        usesPackageJson: false,
        getVersion: () => undefined,
        detectPackageManager: package_manager_detection_light_1.detectNodePackageManagersLight,
        detect: async (options) => {
            const packageJson = await (0, package_json_light_1.tryGetPackageJson)(options);
            if (!packageJson) {
                return false;
            }
            // A "bin" field means this is a Node.js CLI tool, not a web app
            if (packageJson.bin) {
                return false;
            }
            if ((0, javascript_web_blocking_policy_1.javascriptWebBlockedByFrameworkPackage)(packageJson)) {
                return false;
            }
            const { installDir } = options;
            // Has (index.html OR has a bundler) AND is a JavaScript project
            const hasIndexHtmlFlag = (0, utils_1.hasIndexHtml)(options);
            const bundler = (0, utils_1.detectBundler)(options);
            const hasBundler = !!bundler;
            const hasLockfile = [
                'package-lock.json',
                'yarn.lock',
                'pnpm-lock.yaml',
                'bun.lockb',
                'bun.lock',
                'deno.lock',
            ].some((lockfile) => fs.existsSync(path.join(installDir, lockfile)));
            // We only treat this as JS Web if there's BOTH:
            // - a lockfile, and
            // - at least one frontend signal (index.html or bundler)
            if (hasLockfile && (hasIndexHtmlFlag || hasBundler)) {
                return true;
            }
            // Otherwise → Node/Backend (handled by javascriptNode fallback)
            return false;
        },
    },
    environment: {
        uploadToHosting: false,
        getEnvVars: (apiKey, _host) => ({
            AMPLITUDE_API_KEY: apiKey,
        }),
    },
    analytics: {
        getTags: (context) => {
            const tags = {
                packageManager: context.packageManagerName ?? 'unknown',
            };
            if (context.hasBundler) {
                tags.bundler = context.hasBundler;
            }
            return tags;
        },
    },
    prompts: {
        projectTypeDetection: 'This is a JavaScript/TypeScript project. Look for package.json and lockfiles (package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lockb) to confirm.',
        packageInstallation: 'Look for lockfiles to determine the package manager (npm, yarn, pnpm, bun). Do not manually edit package.json.',
        getAdditionalContextLines: (context) => {
            const projectTypeLine = context.vuePoweredDocsSite
                ? `Project type: Vue-powered documentation or presentation tooling (VitePress, VuePress, Slidev, etc.) — not a product Vue SPA; wire the browser SDK via that tool's supported client, theme, or layout extension entrypoints.`
                : `Project type: Generic JavaScript/TypeScript application (no specific framework detected)`;
            const lines = [
                `Package manager: ${context.packageManagerName ?? 'unknown'}`,
                `Has TypeScript: ${context.hasTypeScript ? 'yes' : 'no'}`,
                `Framework docs ID: js (use amplitude://docs/frameworks/js for documentation if available)`,
                projectTypeLine,
                browser_sdk_prompt_1.BROWSER_UNIFIED_SDK_PROMPT_LINE,
                `Initialize from the project's main entry point (e.g. src/main.ts, src/index.ts, or wherever the app boots) before any tracked user code runs. For static-HTML / no-bundler projects, the CDN <script> tag flow is appropriate instead — but the npm path is preferred whenever a build pipeline exists.`,
            ];
            if (context.hasBundler) {
                lines.unshift(`Bundler: ${context.hasBundler}`);
            }
            return lines;
        },
    },
    ui: {
        successMessage: 'Amplitude integration complete',
        estimatedDurationMinutes: 5,
        getOutroChanges: (context) => {
            const packageManagerName = context.packageManagerName ?? 'package manager';
            return [
                `Analyzed your JavaScript project structure`,
                `Installed the @amplitude/unified package using ${packageManagerName}`,
                `Created Amplitude initialization code`,
                `Configured autocapture and event tracking`,
            ];
        },
        getOutroNextSteps: () => [
            'Ensure amplitude.init() is called before any track calls',
            'Autocapture tracks clicks, form submissions, and pageviews automatically',
            'Use amplitude.track() for custom events and amplitude.setUserId() for users',
            'NEVER send PII in event properties (no emails, names, or user content)',
            'Visit your Amplitude dashboard to see incoming events',
        ],
    },
};
