'use strict';

var fs = require('fs');
var path = require('path');
var process = require('process');
var url = require('url');
var deployer = require('@mastra/deployer');
var build = require('@mastra/deployer/build');
var esm = require('fs-extra/esm');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var process__default = /*#__PURE__*/_interopDefault(process);

// src/index.ts
var VercelDeployer = class extends deployer.Deployer {
  vcConfigOverrides = {};
  studio;
  constructor(options = {}) {
    super({ name: "VERCEL" });
    this.outputDir = path.join(".vercel", "output", "functions", "index.func");
    this.studio = options.studio ?? false;
    const { studio, ...overrides } = options;
    this.vcConfigOverrides = { ...overrides };
  }
  async prepare(outputDirectory) {
    await super.prepare(outputDirectory);
    this.writeVercelJSON(path.join(outputDirectory, this.outputDir, "..", ".."));
    if (this.studio) {
      const __filename = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
      const __dirname = path.dirname(__filename);
      const studioSource = path.join(path.dirname(__dirname), "dist", "studio");
      const staticDir = path.join(outputDirectory, ".vercel", "output", "static");
      try {
        await esm.copy(studioSource, staticDir, { overwrite: true });
      } catch (err) {
        throw new Error(
          `Failed to copy studio assets from "${studioSource}" to "${staticDir}": ${err instanceof Error ? err.message : err}`
        );
      }
      this.injectStudioConfig(staticDir);
    }
  }
  getEntry() {
    return `
import { handle } from 'hono/vercel'
import { mastra } from '#mastra';
import { createHonoServer, getToolExports } from '#server';
import { tools } from '#tools';
import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';

if (mastra.getStorage()) {
  mastra.__registerInternalWorkflow(scoreTracesWorkflow);
}

const app = await createHonoServer(mastra, { tools: getToolExports(tools) });

export const GET = handle(app);
export const POST = handle(app);
export const PUT = handle(app);
export const DELETE = handle(app);
export const PATCH = handle(app);
export const OPTIONS = handle(app);
export const HEAD = handle(app);
`;
  }
  injectStudioConfig(staticDir) {
    const indexPath = path.join(staticDir, "index.html");
    let html = fs.readFileSync(indexPath, "utf-8");
    html = build.injectStudioHtmlConfig(html, {
      host: `window.location.hostname`,
      port: `(window.location.port || (window.location.protocol === 'https:' ? '443' : '80'))`,
      protocol: `window.location.protocol.replace(':', '')`,
      apiPrefix: `'/api'`,
      basePath: "",
      hideCloudCta: `'true'`,
      templates: `'false'`,
      cloudApiEndpoint: `''`,
      experimentalFeatures: `'false'`,
      telemetryDisabled: `''`,
      requestContextPresets: `''`,
      experimentalUI: `'false'`
    });
    fs.writeFileSync(indexPath, html);
  }
  writeVercelJSON(outputDirectory) {
    const routes = this.studio ? [
      { src: "/api/(.*)", dest: "/" },
      { src: "/health", dest: "/" },
      { handle: "filesystem" },
      { src: "/(.*)", dest: "/index.html", check: true }
    ] : [{ src: "/(.*)", dest: "/" }];
    fs.writeFileSync(path.join(outputDirectory, "config.json"), JSON.stringify({ version: 3, routes }));
  }
  async bundle(entryFile, outputDirectory, { toolsPaths, projectRoot }) {
    const result = await this._bundle(
      this.getEntry(),
      entryFile,
      { outputDirectory, projectRoot },
      toolsPaths,
      path.join(outputDirectory, this.outputDir)
    );
    const nodeVersion = process__default.default.version?.split(".")?.[0]?.replace("v", "") ?? "22";
    const vcConfig = {
      handler: "index.mjs",
      launcherType: "Nodejs",
      runtime: `nodejs${nodeVersion}.x`,
      shouldAddHelpers: true
    };
    const { maxDuration, memory, regions } = this.vcConfigOverrides;
    if (typeof maxDuration === "number") vcConfig.maxDuration = maxDuration;
    if (typeof memory === "number") vcConfig.memory = memory;
    if (Array.isArray(regions) && regions.length > 0) vcConfig.regions = regions;
    fs.writeFileSync(path.join(outputDirectory, this.outputDir, ".vc-config.json"), JSON.stringify(vcConfig, null, 2));
    await esm.move(path.join(outputDirectory, ".vercel", "output"), path.join(process__default.default.cwd(), ".vercel", "output"), {
      overwrite: true
    });
    return result;
  }
  async deploy() {
    this.logger?.info("Deploying to Vercel is deprecated. Please use the Vercel dashboard to deploy.");
  }
  async lint(entryFile, outputDirectory, toolsPaths) {
    await super.lint(entryFile, outputDirectory, toolsPaths);
    const hasLibsql = await this.deps.checkDependencies(["@mastra/libsql"]) === `ok`;
    if (hasLibsql) {
      this.logger.error(
        `Vercel Deployer does not support @libsql/client(which may have been installed by @mastra/libsql) as a dependency. 
				Use other Mastra Storage options instead e.g @mastra/pg`
      );
      process__default.default.exit(1);
    }
  }
};

exports.VercelDeployer = VercelDeployer;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map