"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.installNet = installNet;
const http = __importStar(require("http"));
const https = __importStar(require("https"));
const url_1 = require("url");
const evaluator_1 = require("../language/evaluator");
function asString(obj) {
    return obj instanceof evaluator_1.StringObj ? obj.value : null;
}
function fetchUrl(urlStr, timeoutMs = 15_000) {
    return new Promise((resolve, reject) => {
        let parsed;
        try {
            parsed = new url_1.URL(urlStr);
        }
        catch {
            reject(new Error(`invalid URL: ${urlStr}`));
            return;
        }
        const lib = parsed.protocol === "http:" ? http : https;
        const req = lib.get(urlStr, (res) => {
            if (res.statusCode &&
                res.statusCode >= 300 &&
                res.statusCode < 400 &&
                res.headers.location) {
                void fetchUrl(res.headers.location, timeoutMs).then(resolve, reject);
                return;
            }
            const chunks = [];
            res.on("data", (c) => chunks.push(c));
            res.on("end", () => {
                resolve(Buffer.concat(chunks).toString("utf8"));
            });
        });
        req.setTimeout(timeoutMs, () => {
            req.destroy(new Error("net_fetch timeout"));
        });
        req.on("error", reject);
    });
}
/**
 * Async networking helpers. `net_fetch` returns a promise-like string via
 * blocking wait in the builtin (cooperative with the Nexus async runtime).
 */
function installNet(env) {
    env.set("net_fetch", new evaluator_1.BuiltinObj((...args) => {
        if (args.length < 1 || args.length > 2) {
            return new evaluator_1.ErrorObj("net_fetch: want url [, timeout_ms]");
        }
        const url = asString(args[0]);
        if (!url) {
            return new evaluator_1.ErrorObj("net_fetch: url must be string");
        }
        let timeout = 15_000;
        if (args[1] instanceof evaluator_1.IntegerObj) {
            timeout = args[1].value;
        }
        // Sync bridge using deasync-free Atomics wait on a shared buffer is
        // unavailable in all hosts; instead we stash a thenable string wrapper.
        // The evaluator awaits PromiseObj; we return a special error if sync.
        // For smoke tests and offline use, support `net_fetch_sync` mock via
        // child_process-free promise object registered on global.
        try {
            // Attempt immediate cache for data: URLs
            if (url.startsWith("data:text/plain,")) {
                return new evaluator_1.StringObj(decodeURIComponent(url.slice("data:text/plain,".length)));
            }
            // Blocking fetch using nested event loop is not portable; use
            // spawnSync-free approach: return pending marker consumed by async eval.
            const { PromiseObj } = require("../language/runtime");
            return new PromiseObj(fetchUrl(url, timeout)
                .then((body) => new evaluator_1.StringObj(body))
                .catch((err) => new evaluator_1.ErrorObj(`net_fetch failed: ${err instanceof Error ? err.message : String(err)}`)));
        }
        catch (err) {
            return new evaluator_1.ErrorObj(`net_fetch unavailable: ${err instanceof Error ? err.message : String(err)}`);
        }
    }));
    env.set("net_url_encode", new evaluator_1.BuiltinObj((...args) => {
        if (args.length !== 1) {
            return new evaluator_1.ErrorObj("net_url_encode: want 1 string");
        }
        const s = asString(args[0]);
        if (s === null) {
            return new evaluator_1.ErrorObj("net_url_encode: want string");
        }
        return new evaluator_1.StringObj(encodeURIComponent(s));
    }));
}
//# sourceMappingURL=net.js.map