"use strict";
/**
 * npmrc — safely manage the GitHub Packages credential for @openlife-business
 * inside the user's ~/.npmrc.
 *
 * `openlife upgrade` writes two lines so `npm i -g @openlife-business/cli` can
 * authenticate against the private registry:
 *
 *   @openlife-business:registry=https://npm.pkg.github.com
 *   //npm.pkg.github.com/:_authToken=<token>
 *
 * SECURITY / open-core boundary:
 *   - We ALWAYS write to ~/.npmrc (os.homedir()), NEVER process.cwd(), so the
 *     token can never land inside the repository.
 *   - The file is written with mode 0o600 (owner read/write only) — a registry
 *     token is a secret.
 *   - Edits are idempotent and surgical: re-running upsert replaces the two
 *     lines in place (token rotation) instead of duplicating them, and remove
 *     deletes only those two lines, preserving every other entry the user has.
 */
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.upsertBusinessRegistry = upsertBusinessRegistry;
exports.removeBusinessRegistry = removeBusinessRegistry;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
function defaultNpmrcPath() {
    return path.join(os.homedir(), '.npmrc');
}
/**
 * npm's per-registry auth key: protocol stripped, leading `//`, trailing slash.
 * `https://npm.pkg.github.com` → `//npm.pkg.github.com/`.
 */
function authKeyFromRegistry(registry) {
    const noProto = registry.replace(/^https?:/i, '').replace(/\/+$/, '');
    return `${noProto}/`;
}
function readLines(npmrcPath) {
    if (!fs.existsSync(npmrcPath))
        return [];
    const raw = fs.readFileSync(npmrcPath, 'utf-8');
    if (raw === '')
        return [];
    // Split on \n, dropping a single trailing empty element from a final newline.
    const lines = raw.split('\n');
    if (lines.length > 0 && lines[lines.length - 1] === '')
        lines.pop();
    return lines;
}
function writeLines(npmrcPath, lines) {
    const content = lines.length > 0 ? lines.join('\n') + '\n' : '';
    fs.writeFileSync(npmrcPath, content, { mode: 0o600 });
    try {
        fs.chmodSync(npmrcPath, 0o600); // enforce 0o600 even if the file pre-existed
    }
    catch {
        /* best-effort on platforms without chmod semantics */
    }
}
/**
 * Ensure the scope registry + auth token lines exist (replacing any prior
 * pair). Returns whether the file content actually changed.
 */
function upsertBusinessRegistry(opts, npmrcPath = defaultNpmrcPath()) {
    const registryKey = `${opts.scope}:registry=`;
    const authKey = `${authKeyFromRegistry(opts.registry)}:_authToken=`;
    const existing = readLines(npmrcPath);
    // Drop any prior version of our two lines, keep everything else verbatim.
    const kept = existing.filter((line) => !line.startsWith(registryKey) && !line.startsWith(authKey));
    kept.push(`${registryKey}${opts.registry}`);
    kept.push(`${authKey}${opts.token}`);
    const before = existing.join('\n');
    const after = kept.join('\n');
    if (before === after)
        return { changed: false, path: npmrcPath };
    writeLines(npmrcPath, kept);
    return { changed: true, path: npmrcPath };
}
/**
 * Remove the @openlife-business registry + its matching auth token line. The
 * host is derived from the existing registry line, so this works for any
 * registry/proxy the upgrade flow may have configured. Other entries are left
 * untouched; the file is never deleted.
 */
function removeBusinessRegistry(scope = '@openlife-business', npmrcPath = defaultNpmrcPath()) {
    const existing = readLines(npmrcPath);
    if (existing.length === 0)
        return { changed: false, path: npmrcPath };
    const registryKey = `${scope}:registry=`;
    const registryLine = existing.find((line) => line.startsWith(registryKey));
    const authKey = registryLine
        ? `${authKeyFromRegistry(registryLine.slice(registryKey.length))}:_authToken=`
        : null;
    const kept = existing.filter((line) => {
        if (line.startsWith(registryKey))
            return false;
        if (authKey && line.startsWith(authKey))
            return false;
        return true;
    });
    if (kept.length === existing.length)
        return { changed: false, path: npmrcPath };
    writeLines(npmrcPath, kept);
    return { changed: true, path: npmrcPath };
}
