#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// package.json
var require_package = __commonJS({
  "package.json"(exports, module) {
    module.exports = {
      name: "@openfin/here-zero",
      version: "0.1.2",
      description: "CLI packager for HERE Web",
      types: "dist/main.d.ts",
      type: "module",
      license: "SEE LICENSE IN LICENSE.md",
      bin: {
        "here-zero": "./dist/bin/cli.cjs"
      },
      files: [
        "assets",
        "dist"
      ],
      exports: {
        ".": {
          import: {
            types: "./dist/main.d.ts",
            default: "./dist/main.mjs"
          },
          require: {
            types: "./dist/main.d.cts",
            default: "./dist/main.cjs"
          },
          default: "./dist/main.mjs"
        }
      },
      scripts: {
        "build:ts": "tsc --noEmit && tsup --dts-resolve",
        postbuild: "node --experimental-strip-types ./scripts/load-assets.ts",
        build: "npm run build:ts"
      },
      dependencies: {
        "@openfin/core": "42.100.99",
        "@rollup/plugin-commonjs": "^25.0.7",
        "@rollup/plugin-node-resolve": "^15.2.3",
        "@rollup/plugin-typescript": "^11.1.6",
        commander: "^13.1.0",
        cosmiconfig: "^9.0.0",
        "cosmiconfig-typescript-loader": "^6.1.0",
        rollup: "^4.9.1",
        "rollup-plugin-copy": "^3.5.0",
        "ts-node": "^10.9.2",
        typescript: "^5.3.3",
        zod: "^3.25.63"
      },
      devDependencies: {
        "@openfin/here-web-lib": "0.0.1",
        "@openfin/here-web-ui": "0.1.0",
        "@rollup/plugin-commonjs": "^25.0.7",
        "@rollup/plugin-node-resolve": "^15.2.3",
        "@rollup/plugin-typescript": "^11.1.6",
        rollup: "^4.9.1",
        tsup: "^8.4.0",
        typescript: "^5.2.0"
      }
    };
  }
});

// src/bin/cli.ts
import { program } from "commander";
import path3 from "path";

// src/internal/config.ts
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";

// src/internal/validation.ts
import { z } from "zod";
var contextGroupStrategySchema = z.union([z.literal("window"), z.literal("supertab"), z.literal("global")]);
var iconSchema = z.object({
  src: z.string(),
  sizes: z.string(),
  type: z.string().optional(),
  purpose: z.union([z.literal("any"), z.literal("maskable"), z.literal("monochrome"), z.string()]).optional()
});
var hereConfigSchema = z.object({
  overrides: z.object({
    file: z.string()
  }),
  outputDir: z.string(),
  logo: z.object({
    searchCommandBar: z.string().optional(),
    newTab: z.string().optional()
  }).optional(),
  title: z.string().optional(),
  favicon: z.string().optional(),
  interop: z.object({
    contextGroupStrategy: contextGroupStrategySchema
  }).optional(),
  base: z.string().optional(),
  pwa: z.union([
    z.boolean(),
    z.object({
      icons: z.array(iconSchema).length(2).optional()
    })
  ]).optional()
});
function validate(config) {
  try {
    hereConfigSchema.parse(config);
  } catch (err) {
    if (err instanceof z.ZodError) {
      console.error(err.issues);
    }
  }
}
__name(validate, "validate");

// src/internal/config.ts
async function loadConfig(searchPath) {
  const explorer = cosmiconfig("here-zero", {
    searchPlaces: ["here.config.js", "here.config.mjs", "here.config.ts"],
    loaders: {
      ".ts": TypeScriptLoader()
    }
  });
  try {
    const result = searchPath ? await explorer.load(searchPath) : await explorer.search();
    if (!result) {
      return {
        config: {},
        filepath: null,
        message: "No configuration file found"
      };
    }
    const config = await result.config;
    validate(config);
    return {
      config,
      filepath: result.filepath,
      message: `Configuration loaded from: ${result.filepath}`
    };
  } catch (error) {
    const message = `Error loading configuration: ${error.message}`;
    console.error(message);
    return {
      config: {},
      filepath: null,
      message
    };
  }
}
__name(loadConfig, "loadConfig");

// src/internal/copyAssets.ts
import fs2 from "fs";
import { cp } from "fs/promises";
import path2 from "path";

// src/internal/pwaManifest.ts
import fs from "fs";
import path from "path";
function writePWAManifest(config) {
  if (config.pwa === false) {
    return "";
  }
  let basePath = config.base || "";
  if (config.base && !basePath.endsWith("/")) {
    basePath += "/";
  }
  const defaultManifest = {
    name: "Here",
    short_name: "Here",
    start_url: ".",
    display: "standalone",
    background_color: "#ffffff",
    theme_color: "#ffffff",
    icons: [
      {
        src: `${basePath}icons/icon-192x192.png`,
        sizes: "192x192",
        type: "image/png"
      },
      {
        src: `${basePath}icons/icon-512x512.png`,
        sizes: "512x512",
        type: "image/png"
      }
    ]
  };
  const manifest = {
    ...defaultManifest,
    name: config.title,
    short_name: config.title?.replaceAll(" ", ""),
    start_url: config.base ? config.base : ".",
    icons: config.pwa?.icons?.length == 2 ? config.pwa.icons : defaultManifest.icons
  };
  const manifestPath = path.join(config.outputDir, "manifest.json");
  fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
  console.log(`Generated PWA manifest ${manifestPath}`);
  const manifestHref = `${basePath}manifest.json`;
  return manifestHref;
}
__name(writePWAManifest, "writePWAManifest");

// src/internal/injectIntoHead.ts
function injectIntoHead(html, headContent) {
  console.log(`Injecting ${headContent} into <head> of index.html`);
  return html.replace(/<\/head>/i, `${headContent}</head>`);
}
__name(injectIntoHead, "injectIntoHead");

// src/internal/copyAssets.ts
async function copyAssetsToOutput(config) {
  const { overrides, outputDir: outputPath, logo, title, favicon } = config;
  const workingDir = process.cwd();
  const outputDir = path2.join(workingDir, outputPath);
  if (!fs2.existsSync(outputDir)) {
    fs2.mkdirSync(outputDir, { recursive: true });
  }
  const overridesFile = path2.basename(overrides.file);
  const overridesJsSrc = path2.join(workingDir, overrides.file);
  const overridesJsPath = path2.join(outputDir, path2.basename(overrides.file));
  if (fs2.existsSync(overridesJsSrc)) {
    fs2.copyFileSync(overridesJsSrc, overridesJsPath);
  } else {
    console.warn(`Warning: Failed to find: ${overridesJsSrc}`);
  }
  try {
    const cliPackagerAssetsDir = path2.join(__dirname, "../../dist/assets");
    await cp(cliPackagerAssetsDir, outputDir, { recursive: true, force: true });
    const indexHtmlDest = path2.join(outputDir, "index.html");
    let html = fs2.readFileSync(indexHtmlDest, "utf8");
    if (fs2.existsSync(overridesJsPath)) {
      html = injectIntoHead(html, `<script src="${overridesFile}"></script>`);
    }
    const configScript = `<script>window.__HERE_CONFIG__ = ${JSON.stringify(config)};</script>`;
    html = injectIntoHead(html, configScript);
    const manifestHref = writePWAManifest(config);
    if (!!manifestHref) {
      html = injectIntoHead(html, `<link rel="manifest" href="${manifestHref}" />`);
    }
    fs2.writeFileSync(indexHtmlDest, html, "utf8");
    console.log(`Here Web entrypoint: ${indexHtmlDest}`);
  } catch (error) {
    console.error("Failed to copy assets folder:", error);
    process.exit(1);
  }
}
__name(copyAssetsToOutput, "copyAssetsToOutput");

// src/bin/cli.ts
var version = require_package().version;
program.name("here-zero").description("CLI packager for here-web").version(version).option("-c, --config <path>", "specify the config path").option("-p, --print", "print the loaded configuration").action(async (options) => {
  const searchPath = options.config ? path3.resolve(options.config) : void 0;
  const { config, filepath, message } = await loadConfig(searchPath);
  if (filepath) {
    await copyAssetsToOutput(config);
  }
  if (options.print && filepath) {
    console.log(`Configuration content:
${JSON.stringify(config, null, 2)}`);
  }
});
program.parse(process.argv);
