#!/usr/bin/env node
"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 __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;
};
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
));

// package.json
var require_package = __commonJS({
  "package.json"(exports2, module2) {
    module2.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
var import_commander = require("commander");
var import_node_path = __toESM(require("path"), 1);

// src/internal/config.ts
var import_cosmiconfig = require("cosmiconfig");
var import_cosmiconfig_typescript_loader = require("cosmiconfig-typescript-loader");

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

// src/internal/config.ts
async function loadConfig(searchPath) {
  const explorer = (0, import_cosmiconfig.cosmiconfig)("here-zero", {
    searchPlaces: ["here.config.js", "here.config.mjs", "here.config.ts"],
    loaders: {
      ".ts": (0, import_cosmiconfig_typescript_loader.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
var import_fs2 = __toESM(require("fs"), 1);
var import_promises = require("fs/promises");
var import_path2 = __toESM(require("path"), 1);

// src/internal/pwaManifest.ts
var import_fs = __toESM(require("fs"), 1);
var import_path = __toESM(require("path"), 1);
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 = import_path.default.join(config.outputDir, "manifest.json");
  import_fs.default.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 = import_path2.default.join(workingDir, outputPath);
  if (!import_fs2.default.existsSync(outputDir)) {
    import_fs2.default.mkdirSync(outputDir, { recursive: true });
  }
  const overridesFile = import_path2.default.basename(overrides.file);
  const overridesJsSrc = import_path2.default.join(workingDir, overrides.file);
  const overridesJsPath = import_path2.default.join(outputDir, import_path2.default.basename(overrides.file));
  if (import_fs2.default.existsSync(overridesJsSrc)) {
    import_fs2.default.copyFileSync(overridesJsSrc, overridesJsPath);
  } else {
    console.warn(`Warning: Failed to find: ${overridesJsSrc}`);
  }
  try {
    const cliPackagerAssetsDir = import_path2.default.join(__dirname, "../../dist/assets");
    await (0, import_promises.cp)(cliPackagerAssetsDir, outputDir, { recursive: true, force: true });
    const indexHtmlDest = import_path2.default.join(outputDir, "index.html");
    let html = import_fs2.default.readFileSync(indexHtmlDest, "utf8");
    if (import_fs2.default.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}" />`);
    }
    import_fs2.default.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;
import_commander.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 ? import_node_path.default.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)}`);
  }
});
import_commander.program.parse(process.argv);
