import { r as __exportAll, t as __commonJSMin } from "./chunk-BSw8zbkd.mjs";
import { n as require_graphql, t as require_main } from "./main-BY-64ifo.mjs";
import { createPrivateKey, subtle } from "node:crypto";
import { BaseSubgraph } from "@powerhousedao/reactor-api";
const schema = require_main().gql`
  """
  A GitHub connection for one studio environment: the repo created in the
  caller's account for that environment.
  """
  type GithubConnection {
    environmentId: String!
    repoFullName: String!
    repoUrl: String!
    createdAt: String!
  }

  """
  Whether the caller has connected GitHub for an environment, and the details.
  """
  type GithubConnectionStatus {
    connected: Boolean!
    connection: GithubConnection
  }

  """
  A short-lived installation access token for Git push/pull. ~1h lifetime;
  re-fetch on expiry. Never persisted server-side beyond its in-process cache.
  """
  type GithubPushToken {
    token: String!
    expiresAt: String!
  }

  """
  A pending GitHub App device authorization. Display userCode at
  verificationUri, then poll connectGithub with deviceCode until the user
  authorizes. About 15m lifetime; interval is the minimum seconds between polls.
  """
  type GithubDeviceFlow {
    deviceCode: String!
    userCode: String!
    verificationUri: String!
    expiresIn: Int!
    interval: Int!
  }

  type VetraGithubAuthQueries {
    "The caller's GitHub connection for the given environment."
    myGithubConnection(environmentId: String!): GithubConnectionStatus!
    """
    Mint a push token for the repo bound to environmentId. The app installation
    on the repo is resolved at call time. Errors: NOT_CONNECTED if no connection
    exists for the environment; APP_NOT_INSTALLED if the app is not installed on
    the repo yet; UNAUTHENTICATED if no caller.
    """
    getPushToken(environmentId: String!): GithubPushToken!
  }

  type VetraGithubAuthMutations {
    """
    Begin GitHub App device authorization for the authenticated caller. The
    backend calls GitHub with the app's public client_id (no secret) and returns
    the user_code and URL to display plus the device_code to poll connectGithub
    with. Errors: UNAUTHENTICATED if no caller.
    """
    startGithubDeviceFlow: GithubDeviceFlow!
    """
    Complete onboarding for the authenticated caller from a deviceCode obtained
    via startGithubDeviceFlow, binding the result to environmentId (one repo per
    environment). The backend exchanges the code for a user access token
    server-side (never exposed to the client or stored) and creates a blank
    private repo in the caller's account. The app does not need to be installed
    yet — that is required later, before pushing. Poll until it returns connected.
    Errors: AUTHORIZATION_PENDING or SLOW_DOWN while the user has not authorized
    yet (keep polling); DEVICE_CODE_EXPIRED if the code timed out; ACCESS_DENIED
    if the user declined; REPO_ALREADY_EXISTS if the name is taken;
    UNAUTHENTICATED if no caller.
    """
    connectGithub(
      deviceCode: String!
      repoName: String!
      environmentId: String!
    ): GithubConnectionStatus!
  }

  type Query {
    VetraGithubAuth: VetraGithubAuthQueries!
  }

  type Mutation {
    VetraGithubAuth: VetraGithubAuthMutations!
  }
`;
//#endregion
//#region subgraphs/vetra-github-auth/db/installations.ts
function nowIso() {
	return (/* @__PURE__ */ new Date()).toISOString();
}
function toConnection(row) {
	return {
		userDid: row.user_did,
		environmentId: row.environment_id,
		repoFullName: row.repo_full_name,
		createdAt: row.created_at
	};
}
/**
* The caller's GitHub connection for one environment, or null if they have not
* connected that environment. Keyed on (DID, environment) so a caller only ever
* sees their own environments' connections.
*/
async function getConnection(db, did, environmentId) {
	const row = await db.selectFrom("github_installations").selectAll().where("user_did", "=", did).where("environment_id", "=", environmentId).executeTakeFirst();
	return row ? toConnection(row) : null;
}
/**
* Save (or replace) a connection for a (DID, environment). One row per
* environment: re-connecting the same environment replaces its installation/repo,
* and a user can hold a separate repo for each environment they own.
*/
async function saveConnection(db, did, environmentId, repoFullName) {
	const createdAt = nowIso();
	await db.insertInto("github_installations").values({
		user_did: did,
		environment_id: environmentId,
		repo_full_name: repoFullName,
		created_at: createdAt
	}).onConflict((oc) => oc.columns(["user_did", "environment_id"]).doUpdateSet({
		repo_full_name: repoFullName,
		created_at: createdAt
	})).execute();
	return {
		userDid: did,
		environmentId,
		repoFullName,
		createdAt
	};
}
//#endregion
//#region node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js
function getUserAgent() {
	if (typeof navigator === "object" && "userAgent" in navigator) return navigator.userAgent;
	if (typeof process === "object" && process.version !== void 0) return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
	return "<environment undetectable>";
}
//#endregion
//#region node_modules/.pnpm/@octokit+endpoint@11.0.3/node_modules/@octokit/endpoint/dist-bundle/index.js
var userAgent = `octokit-endpoint.js/0.0.0-development ${getUserAgent()}`;
var DEFAULTS = {
	method: "GET",
	baseUrl: "https://api.github.com",
	headers: {
		accept: "application/vnd.github.v3+json",
		"user-agent": userAgent
	},
	mediaType: { format: "" }
};
function lowercaseKeys(object) {
	if (!object) return {};
	return Object.keys(object).reduce((newObj, key) => {
		newObj[key.toLowerCase()] = object[key];
		return newObj;
	}, {});
}
function isPlainObject$1(value) {
	if (typeof value !== "object" || value === null) return false;
	if (Object.prototype.toString.call(value) !== "[object Object]") return false;
	const proto = Object.getPrototypeOf(value);
	if (proto === null) return true;
	const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
	return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
}
function mergeDeep(defaults, options) {
	const result = Object.assign({}, defaults);
	Object.keys(options).forEach((key) => {
		if (isPlainObject$1(options[key])) if (!(key in defaults)) Object.assign(result, { [key]: options[key] });
		else result[key] = mergeDeep(defaults[key], options[key]);
		else Object.assign(result, { [key]: options[key] });
	});
	return result;
}
function removeUndefinedProperties(obj) {
	for (const key in obj) if (obj[key] === void 0) delete obj[key];
	return obj;
}
function merge(defaults, route, options) {
	if (typeof route === "string") {
		let [method, url] = route.split(" ");
		options = Object.assign(url ? {
			method,
			url
		} : { url: method }, options);
	} else options = Object.assign({}, route);
	options.headers = lowercaseKeys(options.headers);
	removeUndefinedProperties(options);
	removeUndefinedProperties(options.headers);
	const mergedOptions = mergeDeep(defaults || {}, options);
	if (options.url === "/graphql") {
		if (defaults && defaults.mediaType.previews?.length) mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
		mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
	}
	return mergedOptions;
}
function addQueryParameters(url, parameters) {
	const separator = /\?/.test(url) ? "&" : "?";
	const names = Object.keys(parameters);
	if (names.length === 0) return url;
	return url + separator + names.map((name) => {
		if (name === "q") return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
		return `${name}=${encodeURIComponent(parameters[name])}`;
	}).join("&");
}
var urlVariableRegex = /\{[^{}}]+\}/g;
function removeNonChars(variableName) {
	return variableName.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
	const matches = url.match(urlVariableRegex);
	if (!matches) return [];
	return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
function omit(object, keysToOmit) {
	const result = { __proto__: null };
	for (const key of Object.keys(object)) if (keysToOmit.indexOf(key) === -1) result[key] = object[key];
	return result;
}
function encodeReserved(str) {
	return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
		if (!/%[0-9A-Fa-f]/.test(part)) part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
		return part;
	}).join("");
}
function encodeUnreserved(str) {
	return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
		return "%" + c.charCodeAt(0).toString(16).toUpperCase();
	});
}
function encodeValue(operator, value, key) {
	value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
	if (key) return encodeUnreserved(key) + "=" + value;
	else return value;
}
function isDefined(value) {
	return value !== void 0 && value !== null;
}
function isKeyOperator(operator) {
	return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
	var value = context[key], result = [];
	if (isDefined(value) && value !== "") if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
		value = value.toString();
		if (modifier && modifier !== "*") value = value.substring(0, parseInt(modifier, 10));
		result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
	} else if (modifier === "*") if (Array.isArray(value)) value.filter(isDefined).forEach(function(value2) {
		result.push(encodeValue(operator, value2, isKeyOperator(operator) ? key : ""));
	});
	else Object.keys(value).forEach(function(k) {
		if (isDefined(value[k])) result.push(encodeValue(operator, value[k], k));
	});
	else {
		const tmp = [];
		if (Array.isArray(value)) value.filter(isDefined).forEach(function(value2) {
			tmp.push(encodeValue(operator, value2));
		});
		else Object.keys(value).forEach(function(k) {
			if (isDefined(value[k])) {
				tmp.push(encodeUnreserved(k));
				tmp.push(encodeValue(operator, value[k].toString()));
			}
		});
		if (isKeyOperator(operator)) result.push(encodeUnreserved(key) + "=" + tmp.join(","));
		else if (tmp.length !== 0) result.push(tmp.join(","));
	}
	else if (operator === ";") {
		if (isDefined(value)) result.push(encodeUnreserved(key));
	} else if (value === "" && (operator === "&" || operator === "?")) result.push(encodeUnreserved(key) + "=");
	else if (value === "") result.push("");
	return result;
}
function parseUrl(template) {
	return { expand: expand.bind(null, template) };
}
function expand(template, context) {
	var operators = [
		"+",
		"#",
		".",
		"/",
		";",
		"?",
		"&"
	];
	template = template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) {
		if (expression) {
			let operator = "";
			const values = [];
			if (operators.indexOf(expression.charAt(0)) !== -1) {
				operator = expression.charAt(0);
				expression = expression.substr(1);
			}
			expression.split(/,/g).forEach(function(variable) {
				var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
				values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
			});
			if (operator && operator !== "+") {
				var separator = ",";
				if (operator === "?") separator = "&";
				else if (operator !== "#") separator = operator;
				return (values.length !== 0 ? operator : "") + values.join(separator);
			} else return values.join(",");
		} else return encodeReserved(literal);
	});
	if (template === "/") return template;
	else return template.replace(/\/$/, "");
}
function parse$1(options) {
	let method = options.method.toUpperCase();
	let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
	let headers = Object.assign({}, options.headers);
	let body;
	let parameters = omit(options, [
		"method",
		"baseUrl",
		"url",
		"headers",
		"request",
		"mediaType"
	]);
	const urlVariableNames = extractUrlVariableNames(url);
	url = parseUrl(url).expand(parameters);
	if (!/^http/.test(url)) url = options.baseUrl + url;
	const remainingParameters = omit(parameters, Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"));
	if (!/application\/octet-stream/i.test(headers.accept)) {
		if (options.mediaType.format) headers.accept = headers.accept.split(/,/).map((format) => format.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
		if (url.endsWith("/graphql")) {
			if (options.mediaType.previews?.length) headers.accept = (headers.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g) || []).concat(options.mediaType.previews).map((preview) => {
				return `application/vnd.github.${preview}-preview${options.mediaType.format ? `.${options.mediaType.format}` : "+json"}`;
			}).join(",");
		}
	}
	if (["GET", "HEAD"].includes(method)) url = addQueryParameters(url, remainingParameters);
	else if ("data" in remainingParameters) body = remainingParameters.data;
	else if (Object.keys(remainingParameters).length) body = remainingParameters;
	if (!headers["content-type"] && typeof body !== "undefined") headers["content-type"] = "application/json; charset=utf-8";
	if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") body = "";
	return Object.assign({
		method,
		url,
		headers
	}, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null);
}
function endpointWithDefaults(defaults, route, options) {
	return parse$1(merge(defaults, route, options));
}
function withDefaults$1(oldDefaults, newDefaults) {
	const DEFAULTS2 = merge(oldDefaults, newDefaults);
	const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
	return Object.assign(endpoint2, {
		DEFAULTS: DEFAULTS2,
		defaults: withDefaults$1.bind(null, DEFAULTS2),
		merge: merge.bind(null, DEFAULTS2),
		parse: parse$1
	});
}
var endpoint = withDefaults$1(null, DEFAULTS);
//#endregion
//#region node_modules/.pnpm/content-type@2.0.0/node_modules/content-type/dist/index.js
var require_dist = /* @__PURE__ */ __commonJSMin(((exports) => {
	/*!
	* content-type
	* Copyright(c) 2015 Douglas Christopher Wilson
	* MIT Licensed
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.parse = parse;
	/**
	* Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`.
	*/
	const NullObject = /* @__PURE__ */ (() => {
		const C = function() {};
		C.prototype = Object.create(null);
		return C;
	})();
	/**
	* Parse a `Content-Type` header.
	*/
	function parse(header, options) {
		const len = header.length;
		let index = skipOWS(header, 0, len);
		const valueStart = index;
		index = skipValue(header, index, len);
		const valueEnd = trailingOWS(header, valueStart, index);
		return {
			type: header.slice(valueStart, valueEnd).toLowerCase(),
			parameters: options?.parameters === false ? new NullObject() : parseParameters(header, index, len)
		};
	}
	const SP = 32;
	const HTAB = 9;
	const SEMI = 59;
	const EQ = 61;
	const DQUOTE = 34;
	const BSLASH = 92;
	/**
	* Parses the parameters of a `Content-Type` header starting at the given index.
	*/
	function parseParameters(header, index, len) {
		const parameters = new NullObject();
		parameter: while (index < len) {
			index = skipOWS(header, index + 1, len);
			const keyStart = index;
			while (index < len) {
				const code = header.charCodeAt(index);
				if (code === SEMI) continue parameter;
				if (code === EQ) {
					const keyEnd = trailingOWS(header, keyStart, index);
					const key = header.slice(keyStart, keyEnd).toLowerCase();
					index = skipOWS(header, index + 1, len);
					if (index < len && header.charCodeAt(index) === DQUOTE) {
						index++;
						let value = "";
						while (index < len) {
							const code = header.charCodeAt(index++);
							if (code === DQUOTE) {
								index = skipValue(header, index, len);
								if (parameters[key] === void 0) parameters[key] = value;
								break;
							}
							if (code === BSLASH && index < len) {
								value += header[index++];
								continue;
							}
							value += String.fromCharCode(code);
						}
						continue parameter;
					}
					const valueStart = index;
					index = skipValue(header, index, len);
					if (parameters[key] === void 0) {
						const valueEnd = trailingOWS(header, valueStart, index);
						parameters[key] = header.slice(valueStart, valueEnd);
					}
					continue parameter;
				}
				index++;
			}
		}
		return parameters;
	}
	/**
	* Skip over characters until a semicolon.
	*/
	function skipValue(str, index, len) {
		while (index < len) {
			if (str.charCodeAt(index) === SEMI) break;
			index++;
		}
		return index;
	}
	/**
	* Skip optional whitespace (OWS) in an HTTP header value.
	*
	* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
	*/
	function skipOWS(header, index, len) {
		while (index < len) {
			const char = header.charCodeAt(index);
			if (char !== SP && char !== HTAB) break;
			index++;
		}
		return index;
	}
	/**
	* Trim optional whitespace (OWS) from the end of a substring.
	*
	* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
	*/
	function trailingOWS(header, start, end) {
		while (end > start) {
			const char = header.charCodeAt(end - 1);
			if (char !== SP && char !== HTAB) break;
			end--;
		}
		return end;
	}
}));
//#endregion
//#region node_modules/.pnpm/json-with-bigint@3.5.8/node_modules/json-with-bigint/json-with-bigint.js
const intRegex = /^-?\d+$/;
const noiseValue = /^-?\d+n+$/;
const originalStringify = JSON.stringify;
const originalParse = JSON.parse;
const customFormat = /^-?\d+n$/;
const bigIntsStringify = /([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g;
const noiseStringify = /([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g;
/**
* @typedef {(this: any, key: string | number | undefined, value: any) => any} Replacer
* @typedef {(key: string | number | undefined, value: any, context?: { source: string }) => any} Reviver
*/
/**
* Converts a JavaScript value to a JSON string.
*
* Supports serialization of BigInt values using two strategies:
* 1. Custom format "123n" → "123" (universal fallback)
* 2. Native JSON.rawJSON() (Node.js 22+, fastest) when available
*
* All other values are serialized exactly like native JSON.stringify().
*
* @param {*} value The value to convert to a JSON string.
* @param {Replacer | Array<string | number> | null} [replacer]
*   A function that alters the behavior of the stringification process,
*   or an array of strings/numbers to indicate properties to exclude.
* @param {string | number} [space]
*   A string or number to specify indentation or pretty-printing.
* @returns {string} The JSON string representation.
*/
const JSONStringify = (value, replacer, space) => {
	if ("rawJSON" in JSON) return originalStringify(value, (key, value) => {
		if (typeof value === "bigint") return JSON.rawJSON(value.toString());
		if (typeof replacer === "function") return replacer(key, value);
		if (Array.isArray(replacer) && replacer.includes(key)) return value;
		return value;
	}, space);
	if (!value) return originalStringify(value, replacer, space);
	return originalStringify(value, (key, value) => {
		if (typeof value === "string" && noiseValue.test(value)) return value.toString() + "n";
		if (typeof value === "bigint") return value.toString() + "n";
		if (typeof replacer === "function") return replacer(key, value);
		if (Array.isArray(replacer) && replacer.includes(key)) return value;
		return value;
	}, space).replace(bigIntsStringify, "$1$2$3").replace(noiseStringify, "$1$2$3");
};
const featureCache = /* @__PURE__ */ new Map();
/**
* Detects if the current JSON.parse implementation supports the context.source feature.
*
* Uses toString() fingerprinting to cache results and automatically detect runtime
* replacements of JSON.parse (polyfills, mocks, etc.).
*
* @returns {boolean} true if context.source is supported, false otherwise.
*/
const isContextSourceSupported = () => {
	const parseFingerprint = JSON.parse.toString();
	if (featureCache.has(parseFingerprint)) return featureCache.get(parseFingerprint);
	try {
		const result = JSON.parse("1", (_, __, context) => !!context?.source && context.source === "1");
		featureCache.set(parseFingerprint, result);
		return result;
	} catch {
		featureCache.set(parseFingerprint, false);
		return false;
	}
};
/**
* Reviver function that converts custom-format BigInt strings back to BigInt values.
* Also handles "noise" strings that accidentally match the BigInt format.
*
* @param {string | number | undefined} key The object key.
* @param {*} value The value being parsed.
* @param {object} [context] Parse context (if supported by JSON.parse).
* @param {Reviver} [userReviver] User's custom reviver function.
* @returns {any} The transformed value.
*/
const convertMarkedBigIntsReviver = (key, value, context, userReviver) => {
	if (typeof value === "string" && customFormat.test(value)) return BigInt(value.slice(0, -1));
	if (typeof value === "string" && noiseValue.test(value)) return value.slice(0, -1);
	if (typeof userReviver !== "function") return value;
	return userReviver(key, value, context);
};
/**
* Fast JSON.parse implementation (~2x faster than classic fallback).
* Uses JSON.parse's context.source feature to detect integers and convert
* large numbers directly to BigInt without string manipulation.
*
* Does not support legacy custom format from v1 of this library.
*
* @param {string} text JSON string to parse.
* @param {Reviver} [reviver] Transform function to apply to each value.
* @returns {any} Parsed JavaScript value.
*/
const JSONParseV2 = (text, reviver) => {
	return JSON.parse(text, (key, value, context) => {
		const isBigNumber = typeof value === "number" && (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER);
		const isInt = context && intRegex.test(context.source);
		if (isBigNumber && isInt) return BigInt(context.source);
		if (typeof reviver !== "function") return value;
		return reviver(key, value, context);
	});
};
const MAX_INT = Number.MAX_SAFE_INTEGER.toString();
const MAX_DIGITS = MAX_INT.length;
const stringsOrLargeNumbers = /"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g;
const noiseValueWithQuotes = /^"-?\d+n+"$/;
/**
* Converts a JSON string into a JavaScript value.
*
* Supports parsing of large integers using two strategies:
* 1. Classic fallback: Marks large numbers with "123n" format, then converts to BigInt
* 2. Fast path (JSONParseV2): Uses context.source feature (~2x faster) when available
*
* All other JSON values are parsed exactly like native JSON.parse().
*
* @param {string} text A valid JSON string.
* @param {Reviver} [reviver]
*   A function that transforms the results. This function is called for each member
*   of the object. If a member contains nested objects, the nested objects are
*   transformed before the parent object is.
* @returns {any} The parsed JavaScript value.
* @throws {SyntaxError} If text is not valid JSON.
*/
const JSONParse = (text, reviver) => {
	if (!text) return originalParse(text, reviver);
	if (isContextSourceSupported()) return JSONParseV2(text, reviver);
	return originalParse(text.replace(stringsOrLargeNumbers, (text, digits, fractional, exponential) => {
		const isString = text[0] === "\"";
		if (isString && noiseValueWithQuotes.test(text)) return text.substring(0, text.length - 1) + "n\"";
		const isFractionalOrExponential = fractional || exponential;
		const isLessThanMaxSafeInt = digits && (digits.length < MAX_DIGITS || digits.length === MAX_DIGITS && digits <= MAX_INT);
		if (isString || isFractionalOrExponential || isLessThanMaxSafeInt) return text;
		return "\"" + text + "n\"";
	}), (key, value, context) => convertMarkedBigIntsReviver(key, value, context, reviver));
};
//#endregion
//#region node_modules/.pnpm/@octokit+request-error@7.1.0/node_modules/@octokit/request-error/dist-src/index.js
var RequestError = class extends Error {
	name;
	/**
	* http status code
	*/
	status;
	/**
	* Request options that lead to the error.
	*/
	request;
	/**
	* Response object if a response was received
	*/
	response;
	constructor(message, statusCode, options) {
		super(message, { cause: options.cause });
		this.name = "HttpError";
		this.status = Number.parseInt(statusCode);
		if (Number.isNaN(this.status)) this.status = 0;
		/* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */
		if ("response" in options) this.response = options.response;
		const requestCopy = Object.assign({}, options.request);
		if (options.request.headers.authorization) requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace(/(?<! ) .*$/, " [REDACTED]") });
		requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
		this.request = requestCopy;
	}
};
//#endregion
//#region node_modules/.pnpm/@octokit+request@10.0.10/node_modules/@octokit/request/dist-bundle/index.js
var import_dist = require_dist();
var VERSION$4 = "10.0.10";
var defaults_default = { headers: { "user-agent": `octokit-request.js/${VERSION$4} ${getUserAgent()}` } };
function isPlainObject(value) {
	if (typeof value !== "object" || value === null) return false;
	if (Object.prototype.toString.call(value) !== "[object Object]") return false;
	const proto = Object.getPrototypeOf(value);
	if (proto === null) return true;
	const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
	return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
}
var noop = () => "";
async function fetchWrapper(requestOptions) {
	const fetch = requestOptions.request?.fetch || globalThis.fetch;
	if (!fetch) throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");
	const log = requestOptions.request?.log || console;
	const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;
	const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body;
	const requestHeaders = Object.fromEntries(Object.entries(requestOptions.headers).map(([name, value]) => [name, String(value)]));
	let fetchResponse;
	try {
		fetchResponse = await fetch(requestOptions.url, {
			method: requestOptions.method,
			body,
			redirect: requestOptions.request?.redirect,
			headers: requestHeaders,
			signal: requestOptions.request?.signal,
			...requestOptions.body && { duplex: "half" }
		});
	} catch (error) {
		let message = "Unknown Error";
		if (error instanceof Error) {
			if (error.name === "AbortError") {
				error.status = 500;
				throw error;
			}
			message = error.message;
			if (error.name === "TypeError" && "cause" in error) {
				if (error.cause instanceof Error) message = error.cause.message;
				else if (typeof error.cause === "string") message = error.cause;
			}
		}
		const requestError = new RequestError(message, 500, { request: requestOptions });
		requestError.cause = error;
		throw requestError;
	}
	const status = fetchResponse.status;
	const url = fetchResponse.url;
	const responseHeaders = {};
	for (const [key, value] of fetchResponse.headers) responseHeaders[key] = value;
	const octokitResponse = {
		url,
		status,
		headers: responseHeaders,
		data: ""
	};
	if ("deprecation" in responseHeaders) {
		const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/);
		const deprecationLink = matches && matches.pop();
		log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
	}
	if (status === 204 || status === 205) return octokitResponse;
	if (requestOptions.method === "HEAD") {
		if (status < 400) return octokitResponse;
		throw new RequestError(fetchResponse.statusText, status, {
			response: octokitResponse,
			request: requestOptions
		});
	}
	if (status === 304) {
		octokitResponse.data = await getResponseData(fetchResponse);
		throw new RequestError("Not modified", status, {
			response: octokitResponse,
			request: requestOptions
		});
	}
	if (status >= 400) {
		octokitResponse.data = await getResponseData(fetchResponse);
		throw new RequestError(toErrorMessage(octokitResponse.data), status, {
			response: octokitResponse,
			request: requestOptions
		});
	}
	octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;
	return octokitResponse;
}
async function getResponseData(response) {
	const contentType = response.headers.get("content-type");
	if (!contentType) return response.text().catch(noop);
	const mimetype = (0, import_dist.parse)(contentType);
	if (isJSONResponse(mimetype)) {
		let text = "";
		try {
			text = await response.text();
			return JSONParse(text);
		} catch (err) {
			return text;
		}
	} else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") return response.text().catch(noop);
	else return response.arrayBuffer().catch(
		/* v8 ignore next -- @preserve */
		() => /* @__PURE__ */ new ArrayBuffer(0)
	);
}
function isJSONResponse(mimetype) {
	return mimetype.type === "application/json" || mimetype.type === "application/scim+json";
}
function toErrorMessage(data) {
	if (typeof data === "string") return data;
	if (data instanceof ArrayBuffer) return "Unknown error";
	if ("message" in data) {
		const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : "";
		return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`;
	}
	return `Unknown error: ${JSON.stringify(data)}`;
}
function withDefaults(oldEndpoint, newDefaults) {
	const endpoint2 = oldEndpoint.defaults(newDefaults);
	const newApi = function(route, parameters) {
		const endpointOptions = endpoint2.merge(route, parameters);
		if (!endpointOptions.request || !endpointOptions.request.hook) return fetchWrapper(endpoint2.parse(endpointOptions));
		const request2 = (route2, parameters2) => {
			return fetchWrapper(endpoint2.parse(endpoint2.merge(route2, parameters2)));
		};
		Object.assign(request2, {
			endpoint: endpoint2,
			defaults: withDefaults.bind(null, endpoint2)
		});
		return endpointOptions.request.hook(request2, endpointOptions);
	};
	return Object.assign(newApi, {
		endpoint: endpoint2,
		defaults: withDefaults.bind(null, endpoint2)
	});
}
var request = withDefaults(endpoint, defaults_default);
/* v8 ignore next -- @preserve */
/* v8 ignore else -- @preserve */
//#endregion
//#region node_modules/.pnpm/@octokit+oauth-methods@6.0.2/node_modules/@octokit/oauth-methods/dist-bundle/index.js
function requestToOAuthBaseUrl(request) {
	const endpointDefaults = request.endpoint.DEFAULTS;
	return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
}
async function oauthRequest(request, route, parameters) {
	const withOAuthParameters = {
		baseUrl: requestToOAuthBaseUrl(request),
		headers: { accept: "application/json" },
		...parameters
	};
	const response = await request(route, withOAuthParameters);
	if ("error" in response.data) {
		const error = new RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { request: request.endpoint.merge(route, withOAuthParameters) });
		error.response = response;
		throw error;
	}
	return response;
}
async function exchangeWebFlowCode(options) {
	const response = await oauthRequest(options.request || request, "POST /login/oauth/access_token", {
		client_id: options.clientId,
		client_secret: options.clientSecret,
		code: options.code,
		redirect_uri: options.redirectUrl
	});
	const authentication = {
		clientType: options.clientType,
		clientId: options.clientId,
		clientSecret: options.clientSecret,
		token: response.data.access_token,
		scopes: response.data.scope.split(/\s+/).filter(Boolean)
	};
	if (options.clientType === "github-app") {
		if ("refresh_token" in response.data) {
			const apiTimeInMs = new Date(response.headers.date).getTime();
			authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in);
		}
		delete authentication.scopes;
	}
	return {
		...response,
		authentication
	};
}
function toTimestamp(apiTimeInMs, expirationInSeconds) {
	return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
}
async function createDeviceCode(options) {
	const request$5 = options.request || request;
	const parameters = { client_id: options.clientId };
	if ("scopes" in options && Array.isArray(options.scopes)) parameters.scope = options.scopes.join(" ");
	return oauthRequest(request$5, "POST /login/device/code", parameters);
}
async function exchangeDeviceCode$1(options) {
	const response = await oauthRequest(options.request || request, "POST /login/oauth/access_token", {
		client_id: options.clientId,
		device_code: options.code,
		grant_type: "urn:ietf:params:oauth:grant-type:device_code"
	});
	const authentication = {
		clientType: options.clientType,
		clientId: options.clientId,
		token: response.data.access_token,
		scopes: response.data.scope.split(/\s+/).filter(Boolean)
	};
	if ("clientSecret" in options) authentication.clientSecret = options.clientSecret;
	if (options.clientType === "github-app") {
		if ("refresh_token" in response.data) {
			const apiTimeInMs = new Date(response.headers.date).getTime();
			authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp2(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp2(apiTimeInMs, response.data.refresh_token_expires_in);
		}
		delete authentication.scopes;
	}
	return {
		...response,
		authentication
	};
}
function toTimestamp2(apiTimeInMs, expirationInSeconds) {
	return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
}
async function checkToken(options) {
	const response = await (options.request || request)("POST /applications/{client_id}/token", {
		headers: { authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` },
		client_id: options.clientId,
		access_token: options.token
	});
	const authentication = {
		clientType: options.clientType,
		clientId: options.clientId,
		clientSecret: options.clientSecret,
		token: options.token,
		scopes: response.data.scopes
	};
	if (response.data.expires_at) authentication.expiresAt = response.data.expires_at;
	if (options.clientType === "github-app") delete authentication.scopes;
	return {
		...response,
		authentication
	};
}
async function refreshToken(options) {
	const response = await oauthRequest(options.request || request, "POST /login/oauth/access_token", {
		client_id: options.clientId,
		client_secret: options.clientSecret,
		grant_type: "refresh_token",
		refresh_token: options.refreshToken
	});
	const apiTimeInMs = new Date(response.headers.date).getTime();
	const authentication = {
		clientType: "github-app",
		clientId: options.clientId,
		clientSecret: options.clientSecret,
		token: response.data.access_token,
		refreshToken: response.data.refresh_token,
		expiresAt: toTimestamp3(apiTimeInMs, response.data.expires_in),
		refreshTokenExpiresAt: toTimestamp3(apiTimeInMs, response.data.refresh_token_expires_in)
	};
	return {
		...response,
		authentication
	};
}
function toTimestamp3(apiTimeInMs, expirationInSeconds) {
	return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
}
async function resetToken(options) {
	const response = await (options.request || request)("PATCH /applications/{client_id}/token", {
		headers: { authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` },
		client_id: options.clientId,
		access_token: options.token
	});
	const authentication = {
		clientType: options.clientType,
		clientId: options.clientId,
		clientSecret: options.clientSecret,
		token: response.data.token,
		scopes: response.data.scopes
	};
	if (response.data.expires_at) authentication.expiresAt = response.data.expires_at;
	if (options.clientType === "github-app") delete authentication.scopes;
	return {
		...response,
		authentication
	};
}
async function deleteToken(options) {
	return (options.request || request)("DELETE /applications/{client_id}/token", {
		headers: { authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` },
		client_id: options.clientId,
		access_token: options.token
	});
}
async function deleteAuthorization(options) {
	return (options.request || request)("DELETE /applications/{client_id}/grant", {
		headers: { authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` },
		client_id: options.clientId,
		access_token: options.token
	});
}
//#endregion
//#region node_modules/.pnpm/@octokit+auth-oauth-device@8.0.3/node_modules/@octokit/auth-oauth-device/dist-bundle/index.js
async function getOAuthAccessToken(state, options) {
	const cachedAuthentication = getCachedAuthentication(state, options.auth);
	if (cachedAuthentication) return cachedAuthentication;
	const { data: verification } = await createDeviceCode({
		clientType: state.clientType,
		clientId: state.clientId,
		request: options.request || state.request,
		scopes: options.auth.scopes || state.scopes
	});
	await state.onVerification(verification);
	const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification);
	state.authentication = authentication;
	return authentication;
}
function getCachedAuthentication(state, auth2) {
	if (auth2.refresh === true) return false;
	if (!state.authentication) return false;
	if (state.clientType === "github-app") return state.authentication;
	const authentication = state.authentication;
	return ("scopes" in auth2 && auth2.scopes || state.scopes).join(" ") === authentication.scopes.join(" ") ? authentication : false;
}
async function wait(seconds) {
	await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
}
async function waitForAccessToken(request, clientId, clientType, verification) {
	try {
		const options = {
			clientId,
			request,
			code: verification.device_code
		};
		const { authentication } = clientType === "oauth-app" ? await exchangeDeviceCode$1({
			...options,
			clientType: "oauth-app"
		}) : await exchangeDeviceCode$1({
			...options,
			clientType: "github-app"
		});
		return {
			type: "token",
			tokenType: "oauth",
			...authentication
		};
	} catch (error) {
		if (!error.response) throw error;
		const errorType = error.response.data.error;
		if (errorType === "authorization_pending") {
			await wait(verification.interval);
			return waitForAccessToken(request, clientId, clientType, verification);
		}
		if (errorType === "slow_down") {
			await wait(verification.interval + 7);
			return waitForAccessToken(request, clientId, clientType, verification);
		}
		throw error;
	}
}
async function auth$3(state, authOptions) {
	return getOAuthAccessToken(state, { auth: authOptions });
}
async function hook$3(state, request, route, parameters) {
	let endpoint = request.endpoint.merge(route, parameters);
	if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) return request(endpoint);
	const { token } = await getOAuthAccessToken(state, {
		request,
		auth: { type: "oauth" }
	});
	endpoint.headers.authorization = `token ${token}`;
	return request(endpoint);
}
var VERSION$3 = "0.0.0-development";
function createOAuthDeviceAuth(options) {
	const requestWithDefaults = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-oauth-device.js/${VERSION$3} ${getUserAgent()}` } });
	const { request: request$3 = requestWithDefaults, ...otherOptions } = options;
	const state = options.clientType === "github-app" ? {
		...otherOptions,
		clientType: "github-app",
		request: request$3
	} : {
		...otherOptions,
		clientType: "oauth-app",
		request: request$3,
		scopes: options.scopes || []
	};
	if (!options.clientId) throw new Error("[@octokit/auth-oauth-device] \"clientId\" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)");
	if (!options.onVerification) throw new Error("[@octokit/auth-oauth-device] \"onVerification\" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)");
	return Object.assign(auth$3.bind(null, state), { hook: hook$3.bind(null, state) });
}
//#endregion
//#region node_modules/.pnpm/@octokit+auth-oauth-user@6.0.2/node_modules/@octokit/auth-oauth-user/dist-bundle/index.js
var VERSION$2 = "0.0.0-development";
async function getAuthentication(state) {
	if ("code" in state.strategyOptions) {
		const { authentication } = await exchangeWebFlowCode({
			clientId: state.clientId,
			clientSecret: state.clientSecret,
			clientType: state.clientType,
			onTokenCreated: state.onTokenCreated,
			...state.strategyOptions,
			request: state.request
		});
		return {
			type: "token",
			tokenType: "oauth",
			...authentication
		};
	}
	if ("onVerification" in state.strategyOptions) {
		const authentication = await createOAuthDeviceAuth({
			clientType: state.clientType,
			clientId: state.clientId,
			onTokenCreated: state.onTokenCreated,
			...state.strategyOptions,
			request: state.request
		})({ type: "oauth" });
		return {
			clientSecret: state.clientSecret,
			...authentication
		};
	}
	if ("token" in state.strategyOptions) return {
		type: "token",
		tokenType: "oauth",
		clientId: state.clientId,
		clientSecret: state.clientSecret,
		clientType: state.clientType,
		onTokenCreated: state.onTokenCreated,
		...state.strategyOptions
	};
	throw new Error("[@octokit/auth-oauth-user] Invalid strategy options");
}
async function auth$2(state, options = {}) {
	if (!state.authentication) state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state);
	if (state.authentication.invalid) throw new Error("[@octokit/auth-oauth-user] Token is invalid");
	const currentAuthentication = state.authentication;
	if ("expiresAt" in currentAuthentication) {
		if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < /* @__PURE__ */ new Date()) {
			const { authentication } = await refreshToken({
				clientType: "github-app",
				clientId: state.clientId,
				clientSecret: state.clientSecret,
				refreshToken: currentAuthentication.refreshToken,
				request: state.request
			});
			state.authentication = {
				tokenType: "oauth",
				type: "token",
				...authentication
			};
		}
	}
	if (options.type === "refresh") {
		if (state.clientType === "oauth-app") throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens");
		if (!currentAuthentication.hasOwnProperty("expiresAt")) throw new Error("[@octokit/auth-oauth-user] Refresh token missing");
		await state.onTokenCreated?.(state.authentication, { type: options.type });
	}
	if (options.type === "check" || options.type === "reset") {
		const method = options.type === "check" ? checkToken : resetToken;
		try {
			const { authentication } = await method({
				clientType: state.clientType,
				clientId: state.clientId,
				clientSecret: state.clientSecret,
				token: state.authentication.token,
				request: state.request
			});
			state.authentication = {
				tokenType: "oauth",
				type: "token",
				...authentication
			};
			if (options.type === "reset") await state.onTokenCreated?.(state.authentication, { type: options.type });
			return state.authentication;
		} catch (error) {
			if (error.status === 404) {
				error.message = "[@octokit/auth-oauth-user] Token is invalid";
				state.authentication.invalid = true;
			}
			throw error;
		}
	}
	if (options.type === "delete" || options.type === "deleteAuthorization") {
		const method = options.type === "delete" ? deleteToken : deleteAuthorization;
		try {
			await method({
				clientType: state.clientType,
				clientId: state.clientId,
				clientSecret: state.clientSecret,
				token: state.authentication.token,
				request: state.request
			});
		} catch (error) {
			if (error.status !== 404) throw error;
		}
		state.authentication.invalid = true;
		return state.authentication;
	}
	return state.authentication;
}
var ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/;
function requiresBasicAuth(url) {
	return url && ROUTES_REQUIRING_BASIC_AUTH.test(url);
}
async function hook$2(state, request, route, parameters = {}) {
	const endpoint = request.endpoint.merge(route, parameters);
	if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) return request(endpoint);
	if (requiresBasicAuth(endpoint.url)) {
		const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
		endpoint.headers.authorization = `basic ${credentials}`;
		return request(endpoint);
	}
	const { token } = state.clientType === "oauth-app" ? await auth$2({
		...state,
		request
	}) : await auth$2({
		...state,
		request
	});
	endpoint.headers.authorization = "token " + token;
	return request(endpoint);
}
function createOAuthUserAuth({ clientId, clientSecret, clientType = "oauth-app", request: request$2 = request.defaults({ headers: { "user-agent": `octokit-auth-oauth-app.js/${VERSION$2} ${getUserAgent()}` } }), onTokenCreated, ...strategyOptions }) {
	const state = Object.assign({
		clientType,
		clientId,
		clientSecret,
		onTokenCreated,
		strategyOptions,
		request: request$2
	});
	return Object.assign(auth$2.bind(null, state), { hook: hook$2.bind(null, state) });
}
createOAuthUserAuth.VERSION = VERSION$2;
//#endregion
//#region node_modules/.pnpm/@octokit+auth-oauth-app@9.0.3/node_modules/@octokit/auth-oauth-app/dist-bundle/index.js
async function auth$1(state, authOptions) {
	if (authOptions.type === "oauth-app") return {
		type: "oauth-app",
		clientId: state.clientId,
		clientSecret: state.clientSecret,
		clientType: state.clientType,
		headers: { authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` }
	};
	if ("factory" in authOptions) {
		const { type, ...options } = {
			...authOptions,
			...state
		};
		return authOptions.factory(options);
	}
	const common = {
		clientId: state.clientId,
		clientSecret: state.clientSecret,
		request: state.request,
		...authOptions
	};
	return (state.clientType === "oauth-app" ? await createOAuthUserAuth({
		...common,
		clientType: state.clientType
	}) : await createOAuthUserAuth({
		...common,
		clientType: state.clientType
	}))();
}
async function hook$1(state, request2, route, parameters) {
	let endpoint = request2.endpoint.merge(route, parameters);
	if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) return request2(endpoint);
	if (state.clientType === "github-app" && !requiresBasicAuth(endpoint.url)) throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`);
	const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
	endpoint.headers.authorization = `basic ${credentials}`;
	try {
		return await request2(endpoint);
	} catch (error) {
		if (error.status !== 401) throw error;
		error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`;
		throw error;
	}
}
var VERSION$1 = "0.0.0-development";
function createOAuthAppAuth(options) {
	const state = Object.assign({
		request: request.defaults({ headers: { "user-agent": `octokit-auth-oauth-app.js/${VERSION$1} ${getUserAgent()}` } }),
		clientType: "oauth-app"
	}, options);
	return Object.assign(auth$1.bind(null, state), { hook: hook$1.bind(null, state) });
}
//#endregion
//#region node_modules/.pnpm/universal-github-app-jwt@2.2.2/node_modules/universal-github-app-jwt/lib/utils.js
/**
* @param {string} privateKey
* @returns {boolean}
*/
function isPkcs1(privateKey) {
	return privateKey.includes("-----BEGIN RSA PRIVATE KEY-----");
}
/**
* @param {string} privateKey
* @returns {boolean}
*/
function isOpenSsh(privateKey) {
	return privateKey.includes("-----BEGIN OPENSSH PRIVATE KEY-----");
}
/**
* @param {string} str
* @returns {ArrayBuffer}
*/
function string2ArrayBuffer(str) {
	const buf = new ArrayBuffer(str.length);
	const bufView = new Uint8Array(buf);
	for (let i = 0, strLen = str.length; i < strLen; i++) bufView[i] = str.charCodeAt(i);
	return buf;
}
/**
* @param {string} pem
* @returns {ArrayBuffer}
*/
function getDERfromPEM(pem) {
	const pemB64 = pem.trim().split("\n").slice(1, -1).join("");
	return string2ArrayBuffer(atob(pemB64));
}
/**
* @param {import('../internals').Header} header
* @param {import('../internals').Payload} payload
* @returns {string}
*/
function getEncodedMessage(header, payload) {
	return `${base64encodeJSON(header)}.${base64encodeJSON(payload)}`;
}
/**
* @param {ArrayBuffer} buffer
* @returns {string}
*/
function base64encode(buffer) {
	var binary = "";
	var bytes = new Uint8Array(buffer);
	var len = bytes.byteLength;
	for (var i = 0; i < len; i++) binary += String.fromCharCode(bytes[i]);
	return fromBase64(btoa(binary));
}
/**
* @param {string} base64
* @returns {string}
*/
function fromBase64(base64) {
	return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}
/**
* @param {Record<string,unknown>} obj
* @returns {string}
*/
function base64encodeJSON(obj) {
	return fromBase64(btoa(JSON.stringify(obj)));
}
//#endregion
//#region node_modules/.pnpm/universal-github-app-jwt@2.2.2/node_modules/universal-github-app-jwt/lib/crypto-node.js
function convertPrivateKey(privateKey) {
	if (!isPkcs1(privateKey)) return privateKey;
	return createPrivateKey(privateKey).export({
		type: "pkcs8",
		format: "pem"
	});
}
//#endregion
//#region node_modules/.pnpm/universal-github-app-jwt@2.2.2/node_modules/universal-github-app-jwt/lib/get-token.js
/**
* @param {import('../internals').GetTokenOptions} options
* @returns {Promise<string>}
*/
async function getToken({ privateKey, payload }) {
	const convertedPrivateKey = convertPrivateKey(privateKey);
	/* c8 ignore start */
	if (isPkcs1(convertedPrivateKey)) throw new Error("[universal-github-app-jwt] Private Key is in PKCS#1 format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats");
	/* c8 ignore stop */
	if (isOpenSsh(convertedPrivateKey)) throw new Error("[universal-github-app-jwt] Private Key is in OpenSSH format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats");
	const algorithm = {
		name: "RSASSA-PKCS1-v1_5",
		hash: { name: "SHA-256" }
	};
	/** @type {import('../internals').Header} */
	const header = {
		alg: "RS256",
		typ: "JWT"
	};
	const privateKeyDER = getDERfromPEM(convertedPrivateKey);
	const importedKey = await subtle.importKey("pkcs8", privateKeyDER, algorithm, false, ["sign"]);
	const encodedMessage = getEncodedMessage(header, payload);
	const encodedMessageArrBuf = string2ArrayBuffer(encodedMessage);
	return `${encodedMessage}.${base64encode(await subtle.sign(algorithm.name, importedKey, encodedMessageArrBuf))}`;
}
//#endregion
//#region node_modules/.pnpm/universal-github-app-jwt@2.2.2/node_modules/universal-github-app-jwt/index.js
/**
* @param {import(".").Options} options
* @returns {Promise<import(".").Result>}
*/
async function githubAppJwt({ id, privateKey, now = Math.floor(Date.now() / 1e3) }) {
	const privateKeyWithNewlines = privateKey.replace(/\\n/g, "\n");
	const nowWithSafetyMargin = now - 30;
	const expiration = nowWithSafetyMargin + 600;
	return {
		appId: id,
		expiration,
		token: await getToken({
			privateKey: privateKeyWithNewlines,
			payload: {
				iat: nowWithSafetyMargin,
				exp: expiration,
				iss: id
			}
		})
	};
}
//#endregion
//#region node_modules/.pnpm/toad-cache@3.7.0/node_modules/toad-cache/dist/toad-cache.mjs
var LruObject = class {
	constructor(max = 1e3, ttlInMsecs = 0) {
		if (isNaN(max) || max < 0) throw new Error("Invalid max value");
		if (isNaN(ttlInMsecs) || ttlInMsecs < 0) throw new Error("Invalid ttl value");
		this.first = null;
		this.items = Object.create(null);
		this.last = null;
		this.size = 0;
		this.max = max;
		this.ttl = ttlInMsecs;
	}
	bumpLru(item) {
		if (this.last === item) return;
		const last = this.last;
		const next = item.next;
		const prev = item.prev;
		if (this.first === item) this.first = next;
		item.next = null;
		item.prev = last;
		last.next = item;
		if (prev !== null) prev.next = next;
		if (next !== null) next.prev = prev;
		this.last = item;
	}
	clear() {
		this.items = Object.create(null);
		this.first = null;
		this.last = null;
		this.size = 0;
	}
	delete(key) {
		if (Object.prototype.hasOwnProperty.call(this.items, key)) {
			const item = this.items[key];
			delete this.items[key];
			this.size--;
			if (item.prev !== null) item.prev.next = item.next;
			if (item.next !== null) item.next.prev = item.prev;
			if (this.first === item) this.first = item.next;
			if (this.last === item) this.last = item.prev;
		}
	}
	deleteMany(keys) {
		for (var i = 0; i < keys.length; i++) this.delete(keys[i]);
	}
	evict() {
		if (this.size > 0) {
			const item = this.first;
			delete this.items[item.key];
			if (--this.size === 0) {
				this.first = null;
				this.last = null;
			} else {
				this.first = item.next;
				this.first.prev = null;
			}
		}
	}
	expiresAt(key) {
		if (Object.prototype.hasOwnProperty.call(this.items, key)) return this.items[key].expiry;
	}
	get(key) {
		if (Object.prototype.hasOwnProperty.call(this.items, key)) {
			const item = this.items[key];
			if (this.ttl > 0 && item.expiry <= Date.now()) {
				this.delete(key);
				return;
			}
			this.bumpLru(item);
			return item.value;
		}
	}
	getMany(keys) {
		const result = [];
		for (var i = 0; i < keys.length; i++) result.push(this.get(keys[i]));
		return result;
	}
	keys() {
		return Object.keys(this.items);
	}
	set(key, value) {
		if (Object.prototype.hasOwnProperty.call(this.items, key)) {
			const item = this.items[key];
			item.value = value;
			item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
			if (this.last !== item) this.bumpLru(item);
			return;
		}
		if (this.max > 0 && this.size === this.max) this.evict();
		const item = {
			expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
			key,
			prev: this.last,
			next: null,
			value
		};
		this.items[key] = item;
		if (++this.size === 1) this.first = item;
		else this.last.next = item;
		this.last = item;
	}
};
//#endregion
//#region node_modules/.pnpm/@octokit+auth-app@8.2.0/node_modules/@octokit/auth-app/dist-node/index.js
async function getAppAuthentication({ appId, privateKey, timeDifference, createJwt }) {
	try {
		if (createJwt) {
			const { jwt, expiresAt } = await createJwt(appId, timeDifference);
			return {
				type: "app",
				token: jwt,
				appId,
				expiresAt
			};
		}
		const authOptions = {
			id: appId,
			privateKey
		};
		if (timeDifference) Object.assign(authOptions, { now: Math.floor(Date.now() / 1e3) + timeDifference });
		const appAuthentication = await githubAppJwt(authOptions);
		return {
			type: "app",
			token: appAuthentication.token,
			appId: appAuthentication.appId,
			expiresAt: (/* @__PURE__ */ new Date(appAuthentication.expiration * 1e3)).toISOString()
		};
	} catch (error) {
		if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'");
		else throw error;
	}
}
function getCache() {
	return new LruObject(15e3, 1e3 * 60 * 59);
}
async function get(cache, options) {
	const cacheKey = optionsToCacheKey(options);
	const result = await cache.get(cacheKey);
	if (!result) return;
	const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|");
	return {
		token,
		createdAt,
		expiresAt,
		permissions: options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => {
			if (/!$/.test(string)) permissions2[string.slice(0, -1)] = "write";
			else permissions2[string] = "read";
			return permissions2;
		}, {}),
		repositoryIds: options.repositoryIds,
		repositoryNames: options.repositoryNames,
		singleFileName,
		repositorySelection
	};
}
async function set(cache, options, data) {
	const key = optionsToCacheKey(options);
	const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map((name) => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(",");
	const value = [
		data.token,
		data.createdAt,
		data.expiresAt,
		data.repositorySelection,
		permissionsString,
		data.singleFileName
	].join("|");
	await cache.set(key, value);
}
function optionsToCacheKey({ installationId, permissions = {}, repositoryIds = [], repositoryNames = [] }) {
	const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(",");
	return [
		installationId,
		repositoryIds.sort().join(","),
		repositoryNames.join(","),
		permissionsString
	].filter(Boolean).join("|");
}
function toTokenAuthentication({ installationId, token, createdAt, expiresAt, repositorySelection, permissions, repositoryIds, repositoryNames, singleFileName }) {
	return Object.assign({
		type: "token",
		tokenType: "installation",
		token,
		installationId,
		permissions,
		createdAt,
		expiresAt,
		repositorySelection
	}, repositoryIds ? { repositoryIds } : null, repositoryNames ? { repositoryNames } : null, singleFileName ? { singleFileName } : null);
}
async function getInstallationAuthentication(state, options, customRequest) {
	const installationId = Number(options.installationId || state.installationId);
	if (!installationId) throw new Error("[@octokit/auth-app] installationId option is required for installation authentication.");
	if (options.factory) {
		const { type, factory, oauthApp, ...factoryAuthOptions } = {
			...state,
			...options
		};
		return factory(factoryAuthOptions);
	}
	const request = customRequest || state.request;
	return getInstallationAuthenticationConcurrently(state, {
		...options,
		installationId
	}, request);
}
var pendingPromises = /* @__PURE__ */ new Map();
function getInstallationAuthenticationConcurrently(state, options, request) {
	const cacheKey = optionsToCacheKey(options);
	if (pendingPromises.has(cacheKey)) return pendingPromises.get(cacheKey);
	const promise = getInstallationAuthenticationImpl(state, options, request).finally(() => pendingPromises.delete(cacheKey));
	pendingPromises.set(cacheKey, promise);
	return promise;
}
async function getInstallationAuthenticationImpl(state, options, request) {
	if (!options.refresh) {
		const result = await get(state.cache, options);
		if (result) {
			const { token: token2, createdAt: createdAt2, expiresAt: expiresAt2, permissions: permissions2, repositoryIds: repositoryIds2, repositoryNames: repositoryNames2, singleFileName: singleFileName2, repositorySelection: repositorySelection2 } = result;
			return toTokenAuthentication({
				installationId: options.installationId,
				token: token2,
				createdAt: createdAt2,
				expiresAt: expiresAt2,
				permissions: permissions2,
				repositorySelection: repositorySelection2,
				repositoryIds: repositoryIds2,
				repositoryNames: repositoryNames2,
				singleFileName: singleFileName2
			});
		}
	}
	const appAuthentication = await getAppAuthentication(state);
	const payload = {
		installation_id: options.installationId,
		mediaType: { previews: ["machine-man"] },
		headers: { authorization: `bearer ${appAuthentication.token}` }
	};
	if (options.repositoryIds) Object.assign(payload, { repository_ids: options.repositoryIds });
	if (options.repositoryNames) Object.assign(payload, { repositories: options.repositoryNames });
	if (options.permissions) Object.assign(payload, { permissions: options.permissions });
	const { data: { token, expires_at: expiresAt, repositories, permissions: permissionsOptional, repository_selection: repositorySelectionOptional, single_file: singleFileName } } = await request("POST /app/installations/{installation_id}/access_tokens", payload);
	const permissions = permissionsOptional || {};
	const repositorySelection = repositorySelectionOptional || "all";
	const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0;
	const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0;
	const createdAt = (/* @__PURE__ */ new Date()).toISOString();
	const cacheOptions = {
		token,
		createdAt,
		expiresAt,
		repositorySelection,
		permissions,
		repositoryIds,
		repositoryNames
	};
	if (singleFileName) Object.assign(payload, { singleFileName });
	await set(state.cache, options, cacheOptions);
	const cacheData = {
		installationId: options.installationId,
		token,
		createdAt,
		expiresAt,
		repositorySelection,
		permissions,
		repositoryIds,
		repositoryNames
	};
	if (singleFileName) Object.assign(cacheData, { singleFileName });
	return toTokenAuthentication(cacheData);
}
async function auth(state, authOptions) {
	switch (authOptions.type) {
		case "app": return getAppAuthentication(state);
		case "oauth-app": return state.oauthApp({ type: "oauth-app" });
		case "installation": return getInstallationAuthentication(state, {
			...authOptions,
			type: "installation"
		});
		case "oauth-user": return state.oauthApp(authOptions);
		default: throw new Error(`Invalid auth type: ${authOptions.type}`);
	}
}
var PATHS = [
	"/app",
	"/app/hook/config",
	"/app/hook/deliveries",
	"/app/hook/deliveries/{delivery_id}",
	"/app/hook/deliveries/{delivery_id}/attempts",
	"/app/installations",
	"/app/installations/{installation_id}",
	"/app/installations/{installation_id}/access_tokens",
	"/app/installations/{installation_id}/suspended",
	"/app/installation-requests",
	"/marketplace_listing/accounts/{account_id}",
	"/marketplace_listing/plan",
	"/marketplace_listing/plans",
	"/marketplace_listing/plans/{plan_id}/accounts",
	"/marketplace_listing/stubbed/accounts/{account_id}",
	"/marketplace_listing/stubbed/plan",
	"/marketplace_listing/stubbed/plans",
	"/marketplace_listing/stubbed/plans/{plan_id}/accounts",
	"/orgs/{org}/installation",
	"/repos/{owner}/{repo}/installation",
	"/users/{username}/installation",
	"/enterprises/{enterprise}/installation"
];
function routeMatcher(paths) {
	const regex = `^(?:${paths.map((p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/")).map((r) => `(?:${r})`).join("|")})$`;
	return new RegExp(regex, "i");
}
var REGEX = routeMatcher(PATHS);
function requiresAppAuth(url) {
	return !!url && REGEX.test(url.split("?")[0]);
}
var FIVE_SECONDS_IN_MS = 5 * 1e3;
function isNotTimeSkewError(error) {
	return !(error.message.match(/'Expiration time' claim \('exp'\) is too far in the future/) || error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/));
}
async function hook(state, request, route, parameters) {
	const endpoint = request.endpoint.merge(route, parameters);
	const url = endpoint.url;
	if (/\/login\/oauth\/access_token$/.test(url)) return request(endpoint);
	if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
		const { token: token2 } = await getAppAuthentication(state);
		endpoint.headers.authorization = `bearer ${token2}`;
		let response;
		try {
			response = await request(endpoint);
		} catch (error) {
			if (isNotTimeSkewError(error)) throw error;
			if (typeof error.response.headers.date === "undefined") throw error;
			const diff = Math.floor((Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3);
			state.log.warn(error.message);
			state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`);
			const { token: token3 } = await getAppAuthentication({
				...state,
				timeDifference: diff
			});
			endpoint.headers.authorization = `bearer ${token3}`;
			return request(endpoint);
		}
		return response;
	}
	if (requiresBasicAuth(url)) {
		const authentication = await state.oauthApp({ type: "oauth-app" });
		endpoint.headers.authorization = authentication.headers.authorization;
		return request(endpoint);
	}
	const { token, createdAt } = await getInstallationAuthentication(state, {}, request.defaults({ baseUrl: endpoint.baseUrl }));
	endpoint.headers.authorization = `token ${token}`;
	return sendRequestWithRetries(state, request, endpoint, createdAt);
}
async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
	const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt);
	try {
		return await request(options);
	} catch (error) {
		if (error.status !== 401) throw error;
		if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
			if (retries > 0) error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`;
			throw error;
		}
		++retries;
		const awaitTime = retries * 1e3;
		state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)`);
		await new Promise((resolve) => setTimeout(resolve, awaitTime));
		return sendRequestWithRetries(state, request, options, createdAt, retries);
	}
}
var VERSION = "8.2.0";
function createAppAuth(options) {
	if (!options.appId) throw new Error("[@octokit/auth-app] appId option is required");
	if (!options.privateKey && !options.createJwt) throw new Error("[@octokit/auth-app] privateKey option is required");
	else if (options.privateKey && options.createJwt) throw new Error("[@octokit/auth-app] privateKey and createJwt options are mutually exclusive");
	if ("installationId" in options && !options.installationId) throw new Error("[@octokit/auth-app] installationId is set to a falsy value");
	const log = options.log || {};
	if (typeof log.warn !== "function") log.warn = console.warn.bind(console);
	const request$1 = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-app.js/${VERSION} ${getUserAgent()}` } });
	const state = Object.assign({
		request: request$1,
		cache: getCache()
	}, options, options.installationId ? { installationId: Number(options.installationId) } : {}, {
		log,
		oauthApp: createOAuthAppAuth({
			clientType: "github-app",
			clientId: options.clientId || "",
			clientSecret: options.clientSecret || "",
			request: request$1
		})
	});
	return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) });
}
//#endregion
//#region subgraphs/vetra-github-auth/github-app.ts
/** Backend GitHub App helpers: installation discovery, repo creation, and
* short-lived installation tokens. */
/** Raised when the GITHUB_APP_* environment is missing or incomplete. */
var GithubAppConfigError = class extends Error {
	constructor(message) {
		super(message);
		this.name = "GithubAppConfigError";
	}
};
/** Raised when minting an installation token fails because the app is no longer
* installed (GitHub 401/404). */
var ReinstallRequiredError = class extends Error {
	constructor(message) {
		super(message);
		this.name = "ReinstallRequiredError";
	}
};
/** Raised when repo creation fails because the name is already taken (422). */
var RepoAlreadyExistsError = class extends Error {
	constructor(message) {
		super(message);
		this.name = "RepoAlreadyExistsError";
	}
};
let cachedAuth = null;
/** Lazily build (and cache) the app auth interface. Un-escapes `\n` so a
* single-line `GITHUB_APP_PRIVATE_KEY` env value works. */
function appAuth() {
	if (cachedAuth) return cachedAuth;
	const appId = process.env.GITHUB_APP_ID;
	const privateKey = process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g, "\n");
	if (!appId || !privateKey) throw new GithubAppConfigError("Missing GitHub App config: GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY must be set");
	cachedAuth = createAppAuth({
		appId,
		privateKey
	});
	return cachedAuth;
}
function isUninstalled(error) {
	const status = error?.status;
	return status === 401 || status === 404;
}
/**
* Mint a ~1h installation access token. When `repoName` is given, the token is
* scoped to that single repository with Contents access only. Throws
* {@link ReinstallRequiredError} if the app has been uninstalled.
*/
async function mintInstallationToken(installationId, repoName) {
	try {
		const result = await appAuth()(repoName ? {
			type: "installation",
			installationId: Number(installationId),
			repositoryNames: [repoName],
			permissions: { contents: "write" }
		} : {
			type: "installation",
			installationId: Number(installationId)
		});
		return {
			token: result.token,
			expiresAt: result.expiresAt
		};
	} catch (error) {
		if (isUninstalled(error)) throw new ReinstallRequiredError(`Installation ${installationId} is no longer accessible; the app was likely uninstalled`);
		throw error;
	}
}
const GITHUB_API = "https://api.github.com";
function userHeaders(userAccessToken) {
	return {
		Authorization: `token ${userAccessToken}`,
		Accept: "application/vnd.github+json",
		"X-GitHub-Api-Version": "2022-11-28",
		"User-Agent": "vetra-cloud"
	};
}
/** Create a blank private repo in the user's account with their access token. */
async function createRepo(userAccessToken, name) {
	const response = await fetch(`${GITHUB_API}/user/repos`, {
		method: "POST",
		headers: {
			...userHeaders(userAccessToken),
			"Content-Type": "application/json"
		},
		body: JSON.stringify({
			name,
			private: true,
			auto_init: false
		})
	});
	if (response.status === 422) throw new RepoAlreadyExistsError(`A repository named "${name}" already exists`);
	if (!response.ok) throw new Error(`Failed to create repository: ${response.status} ${response.statusText}`);
	const body = await response.json();
	return {
		fullName: body.full_name,
		url: body.html_url
	};
}
/**
* The id of this app's installation on `repoFullName` (`owner/repo`), or null if
* the app is not installed on that repo. Resolved from the app's own JWT, so it
* needs no user token.
*/
async function findRepoInstallationId(repoFullName) {
	const { token: jwt } = await appAuth()({ type: "app" });
	const response = await fetch(`${GITHUB_API}/repos/${repoFullName}/installation`, { headers: {
		Authorization: `Bearer ${jwt}`,
		Accept: "application/vnd.github+json",
		"X-GitHub-Api-Version": "2022-11-28",
		"User-Agent": "vetra-cloud"
	} });
	if (response.status === 404) return null;
	if (!response.ok) throw new Error(`Failed to look up repo installation: ${response.status} ${response.statusText}`);
	const body = await response.json();
	return String(body.id);
}
/**
* Find a repo named `name` in the authenticated user's account, returning its
* full name and URL, or null if they have no such repo.
*/
async function findUserRepo(userAccessToken, name) {
	const userResponse = await fetch(`${GITHUB_API}/user`, { headers: userHeaders(userAccessToken) });
	if (!userResponse.ok) throw new Error(`Failed to resolve the authenticated user: ${userResponse.status} ${userResponse.statusText}`);
	const { login } = await userResponse.json();
	const repoResponse = await fetch(`${GITHUB_API}/repos/${login}/${name}`, { headers: userHeaders(userAccessToken) });
	if (repoResponse.status === 404) return null;
	if (!repoResponse.ok) throw new Error(`Failed to look up repository: ${repoResponse.status} ${repoResponse.statusText}`);
	const body = await repoResponse.json();
	return {
		fullName: body.full_name,
		url: body.html_url
	};
}
const GITHUB_OAUTH_HOST = "https://github.com";
function githubClientId() {
	const clientId = process.env.GITHUB_APP_CLIENT_ID;
	if (!clientId) throw new GithubAppConfigError("Missing GitHub App config: GITHUB_APP_CLIENT_ID must be set");
	return clientId;
}
/**
* Begin GitHub App device authorization (`POST /login/device/code`); returns the
* `user_code`, verification URL, and `device_code`.
*/
async function startDeviceFlow() {
	const response = await fetch(`${GITHUB_OAUTH_HOST}/login/device/code`, {
		method: "POST",
		headers: {
			Accept: "application/json",
			"Content-Type": "application/json",
			"User-Agent": "vetra-cloud"
		},
		body: JSON.stringify({ client_id: githubClientId() })
	});
	if (!response.ok) throw new Error(`Failed to start device flow: ${response.status} ${response.statusText}`);
	const body = await response.json();
	return {
		deviceCode: body.device_code,
		userCode: body.user_code,
		verificationUri: body.verification_uri,
		expiresIn: body.expires_in,
		interval: body.interval
	};
}
/**
* Exchange a device_code for a user access token, mapping GitHub's polling
* responses to a discriminated status.
*/
async function exchangeDeviceCode(deviceCode) {
	const response = await fetch(`${GITHUB_OAUTH_HOST}/login/oauth/access_token`, {
		method: "POST",
		headers: {
			Accept: "application/json",
			"Content-Type": "application/json",
			"User-Agent": "vetra-cloud"
		},
		body: JSON.stringify({
			client_id: githubClientId(),
			device_code: deviceCode,
			grant_type: "urn:ietf:params:oauth:grant-type:device_code"
		})
	});
	if (!response.ok) throw new Error(`Failed to exchange device code: ${response.status} ${response.statusText}`);
	const body = await response.json();
	if (body.access_token) return {
		status: "authorized",
		accessToken: body.access_token
	};
	switch (body.error) {
		case "authorization_pending": return { status: "pending" };
		case "slow_down": return { status: "slowDown" };
		case "expired_token": return { status: "expired" };
		case "access_denied": return { status: "denied" };
		default: throw new Error(`Device flow exchange failed: ${body.error ?? "unknown error"}`);
	}
}
//#endregion
//#region subgraphs/vetra-github-auth/resolvers.ts
var import_graphql = require_graphql();
/** A GraphQLError carrying the error code in `extensions.code` and `message`. */
function ghError(code) {
	return new import_graphql.GraphQLError(code, { extensions: { code } });
}
/** Canonical did:pkh for the authenticated caller, or null if unauthenticated. */
function callerDid(ctx) {
	const u = ctx.user;
	if (!u) return null;
	return `did:pkh:${u.networkId}:${u.chainId}:${u.address.toLowerCase()}`;
}
function requireDid(ctx) {
	const did = callerDid(ctx);
	if (!did) throw ghError("UNAUTHENTICATED");
	return did;
}
function toStatus(connection) {
	return {
		connected: !!connection,
		connection: connection ? {
			environmentId: connection.environmentId,
			repoFullName: connection.repoFullName,
			repoUrl: `https://github.com/${connection.repoFullName}`,
			createdAt: connection.createdAt
		} : null
	};
}
function createResolvers(db) {
	return {
		Query: { VetraGithubAuth: () => ({}) },
		Mutation: { VetraGithubAuth: () => ({}) },
		VetraGithubAuthQueries: {
			myGithubConnection: async (_p, { environmentId }, ctx) => {
				return toStatus(await getConnection(db, requireDid(ctx), environmentId));
			},
			getPushToken: async (_p, { environmentId }, ctx) => {
				const connection = await getConnection(db, requireDid(ctx), environmentId);
				if (!connection) throw ghError("NOT_CONNECTED");
				const installationId = await findRepoInstallationId(connection.repoFullName);
				if (!installationId) throw ghError("APP_NOT_INSTALLED");
				const repoName = connection.repoFullName.split("/").pop();
				try {
					return await mintInstallationToken(installationId, repoName);
				} catch (error) {
					if (error instanceof ReinstallRequiredError) throw ghError("APP_NOT_INSTALLED");
					throw error;
				}
			}
		},
		VetraGithubAuthMutations: {
			startGithubDeviceFlow: async (_p, _a, ctx) => {
				requireDid(ctx);
				return startDeviceFlow();
			},
			connectGithub: async (_p, { deviceCode, repoName, environmentId }, ctx) => {
				const did = requireDid(ctx);
				const exchange = await exchangeDeviceCode(deviceCode);
				if (exchange.status !== "authorized") throw ghError({
					pending: "AUTHORIZATION_PENDING",
					slowDown: "SLOW_DOWN",
					expired: "DEVICE_CODE_EXPIRED",
					denied: "ACCESS_DENIED"
				}[exchange.status]);
				const userAccessToken = exchange.accessToken;
				let repo;
				try {
					repo = await createRepo(userAccessToken, repoName);
				} catch (error) {
					if (error instanceof RepoAlreadyExistsError) {
						const existing = await findUserRepo(userAccessToken, repoName);
						if (!existing) throw ghError("REPO_ALREADY_EXISTS");
						repo = existing;
					} else throw error;
				}
				return toStatus(await saveConnection(db, did, environmentId, repo.fullName));
			}
		}
	};
}
//#endregion
//#region subgraphs/vetra-github-auth/db/migrations.ts
async function up(db) {
	await db.schema.createTable("github_installations").addColumn("user_did", "varchar(255)", (col) => col.notNull()).addColumn("environment_id", "varchar(255)", (col) => col.notNull()).addColumn("repo_full_name", "varchar(255)", (col) => col.notNull()).addColumn("created_at", "varchar(255)", (col) => col.notNull()).addPrimaryKeyConstraint("github_installations_pkey", ["user_did", "environment_id"]).ifNotExists().execute();
}
//#endregion
//#region subgraphs/vetra-github-auth/index.ts
var vetra_github_auth_exports = /* @__PURE__ */ __exportAll({ VetraGithubAuthSubgraph: () => VetraGithubAuthSubgraph });
/**
* Binds a user's Renown identity to the GitHub App installation they own, and
* brokers short-lived installation push tokens for the agent. Owns its own
* relational table in an isolated namespace; every resolver is keyed off the
* gateway-verified caller DID. App secrets (private key, client secret) are
* read from the environment by `github-app.ts`, never stored here.
*/
var VetraGithubAuthSubgraph = class extends BaseSubgraph {
	name = "vetra-github-auth";
	typeDefs = schema;
	resolvers = {};
	additionalContextFields = {};
	async onSetup() {
		const db = await this.relationalDb.createNamespace("vetra-github-auth");
		await up(db);
		this.resolvers = createResolvers(db);
	}
};
//#endregion
export { vetra_github_auth_exports as n, VetraGithubAuthSubgraph as t };

//# sourceMappingURL=vetra-github-auth-qcV69ESb.mjs.map