import { n as __exportAll, r as __require, t as __commonJSMin } from "./chunk-YKewjYmz.js";
import { b as generateId } from "./dist-CdWSQzOH.js";
import { t as GrantApplication } from "./module-Bj-tanSV.js";
import { t as Project } from "./module-Cpz1JYVM.js";
import { i as driveCreateDocument, n as addFolder, t as addFile, u as gql } from "./document-drive-DwMcPeeu.js";
import { BaseSubgraph } from "@powerhousedao/reactor-api";
//#region (ignored) node_modules/dotenv/lib
var require_lib = /* @__PURE__ */ __commonJSMin((() => {}));
//#endregion
//#region node_modules/dotenv/lib/main.js
var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fs = require_lib();
	const path = __require("path");
	const os = __require("os");
	const crypto = __require("crypto");
	const TIPS = [
		"◈ encrypted .env [www.dotenvx.com]",
		"◈ secrets for agents [www.dotenvx.com]",
		"⌁ auth for agents [www.vestauth.com]",
		"⌘ custom filepath { path: '/custom/path/.env' }",
		"⌘ enable debugging { debug: true }",
		"⌘ override existing { override: true }",
		"⌘ suppress logs { quiet: true }",
		"⌘ multiple files { path: ['.env.local', '.env'] }"
	];
	function _getRandomTip() {
		return TIPS[Math.floor(Math.random() * TIPS.length)];
	}
	function parseBoolean(value) {
		if (typeof value === "string") return ![
			"false",
			"0",
			"no",
			"off",
			""
		].includes(value.toLowerCase());
		return Boolean(value);
	}
	function supportsAnsi() {
		return process.stdout.isTTY;
	}
	function dim(text) {
		return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
	}
	const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
	function parse(src) {
		const obj = {};
		let lines = src.toString();
		lines = lines.replace(/\r\n?/gm, "\n");
		let match;
		while ((match = LINE.exec(lines)) != null) {
			const key = match[1];
			let value = match[2] || "";
			value = value.trim();
			const maybeQuote = value[0];
			value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
			if (maybeQuote === "\"") {
				value = value.replace(/\\n/g, "\n");
				value = value.replace(/\\r/g, "\r");
			}
			obj[key] = value;
		}
		return obj;
	}
	function _parseVault(options) {
		options = options || {};
		const vaultPath = _vaultPath(options);
		options.path = vaultPath;
		const result = DotenvModule.configDotenv(options);
		if (!result.parsed) {
			const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
			err.code = "MISSING_DATA";
			throw err;
		}
		const keys = _dotenvKey(options).split(",");
		const length = keys.length;
		let decrypted;
		for (let i = 0; i < length; i++) try {
			const attrs = _instructions(result, keys[i].trim());
			decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
			break;
		} catch (error) {
			if (i + 1 >= length) throw error;
		}
		return DotenvModule.parse(decrypted);
	}
	function _warn(message) {
		console.error(`⚠ ${message}`);
	}
	function _debug(message) {
		console.log(`┆ ${message}`);
	}
	function _log(message) {
		console.log(`◇ ${message}`);
	}
	function _dotenvKey(options) {
		if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
		if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
		return "";
	}
	function _instructions(result, dotenvKey) {
		let uri;
		try {
			uri = new URL(dotenvKey);
		} catch (error) {
			if (error.code === "ERR_INVALID_URL") {
				const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
				err.code = "INVALID_DOTENV_KEY";
				throw err;
			}
			throw error;
		}
		const key = uri.password;
		if (!key) {
			const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
			err.code = "INVALID_DOTENV_KEY";
			throw err;
		}
		const environment = uri.searchParams.get("environment");
		if (!environment) {
			const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
			err.code = "INVALID_DOTENV_KEY";
			throw err;
		}
		const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
		const ciphertext = result.parsed[environmentKey];
		if (!ciphertext) {
			const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
			err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
			throw err;
		}
		return {
			ciphertext,
			key
		};
	}
	function _vaultPath(options) {
		let possibleVaultPath = null;
		if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
			for (const filepath of options.path) if (fs.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
		} else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
		else possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
		if (fs.existsSync(possibleVaultPath)) return possibleVaultPath;
		return null;
	}
	function _resolveHome(envPath) {
		return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
	}
	function _configVault(options) {
		const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
		const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
		if (debug || !quiet) _log("loading env from encrypted .env.vault");
		const parsed = DotenvModule._parseVault(options);
		let processEnv = process.env;
		if (options && options.processEnv != null) processEnv = options.processEnv;
		DotenvModule.populate(processEnv, parsed, options);
		return { parsed };
	}
	function configDotenv(options) {
		const dotenvPath = path.resolve(process.cwd(), ".env");
		let encoding = "utf8";
		let processEnv = process.env;
		if (options && options.processEnv != null) processEnv = options.processEnv;
		let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
		let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
		if (options && options.encoding) encoding = options.encoding;
		else if (debug) _debug("no encoding is specified (UTF-8 is used by default)");
		let optionPaths = [dotenvPath];
		if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
		else {
			optionPaths = [];
			for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
		}
		let lastError;
		const parsedAll = {};
		for (const path of optionPaths) try {
			const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
			DotenvModule.populate(parsedAll, parsed, options);
		} catch (e) {
			if (debug) _debug(`failed to load ${path} ${e.message}`);
			lastError = e;
		}
		const populated = DotenvModule.populate(processEnv, parsedAll, options);
		debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
		quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
		if (debug || !quiet) {
			const keysCount = Object.keys(populated).length;
			const shortPaths = [];
			for (const filePath of optionPaths) try {
				const relative = path.relative(process.cwd(), filePath);
				shortPaths.push(relative);
			} catch (e) {
				if (debug) _debug(`failed to load ${filePath} ${e.message}`);
				lastError = e;
			}
			_log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`);
		}
		if (lastError) return {
			parsed: parsedAll,
			error: lastError
		};
		else return { parsed: parsedAll };
	}
	function config(options) {
		if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
		const vaultPath = _vaultPath(options);
		if (!vaultPath) {
			_warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`);
			return DotenvModule.configDotenv(options);
		}
		return DotenvModule._configVault(options);
	}
	function decrypt(encrypted, keyStr) {
		const key = Buffer.from(keyStr.slice(-64), "hex");
		let ciphertext = Buffer.from(encrypted, "base64");
		const nonce = ciphertext.subarray(0, 12);
		const authTag = ciphertext.subarray(-16);
		ciphertext = ciphertext.subarray(12, -16);
		try {
			const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
			aesgcm.setAuthTag(authTag);
			return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
		} catch (error) {
			const isRange = error instanceof RangeError;
			const invalidKeyLength = error.message === "Invalid key length";
			const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
			if (isRange || invalidKeyLength) {
				const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
				err.code = "INVALID_DOTENV_KEY";
				throw err;
			} else if (decryptionFailed) {
				const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
				err.code = "DECRYPTION_FAILED";
				throw err;
			} else throw error;
		}
	}
	function populate(processEnv, parsed, options = {}) {
		const debug = Boolean(options && options.debug);
		const override = Boolean(options && options.override);
		const populated = {};
		if (typeof parsed !== "object") {
			const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
			err.code = "OBJECT_REQUIRED";
			throw err;
		}
		for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
			if (override === true) {
				processEnv[key] = parsed[key];
				populated[key] = parsed[key];
			}
			if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
			else _debug(`"${key}" is already defined and was NOT overwritten`);
		} else {
			processEnv[key] = parsed[key];
			populated[key] = parsed[key];
		}
		return populated;
	}
	const DotenvModule = {
		configDotenv,
		_configVault,
		_parseVault,
		config,
		decrypt,
		parse,
		populate
	};
	module.exports.configDotenv = DotenvModule.configDotenv;
	module.exports._configVault = DotenvModule._configVault;
	module.exports._parseVault = DotenvModule._parseVault;
	module.exports.config = DotenvModule.config;
	module.exports.decrypt = DotenvModule.decrypt;
	module.exports.parse = DotenvModule.parse;
	module.exports.populate = DotenvModule.populate;
	module.exports = DotenvModule;
}));
//#endregion
//#region node_modules/dotenv/lib/env-options.js
var require_env_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const options = {};
	if (process.env.DOTENV_CONFIG_ENCODING != null) options.encoding = process.env.DOTENV_CONFIG_ENCODING;
	if (process.env.DOTENV_CONFIG_PATH != null) options.path = process.env.DOTENV_CONFIG_PATH;
	if (process.env.DOTENV_CONFIG_QUIET != null) options.quiet = process.env.DOTENV_CONFIG_QUIET;
	if (process.env.DOTENV_CONFIG_DEBUG != null) options.debug = process.env.DOTENV_CONFIG_DEBUG;
	if (process.env.DOTENV_CONFIG_OVERRIDE != null) options.override = process.env.DOTENV_CONFIG_OVERRIDE;
	if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
	module.exports = options;
}));
//#endregion
//#region node_modules/dotenv/lib/cli-options.js
var require_cli_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;
	module.exports = function optionMatcher(args) {
		const options = args.reduce(function(acc, cur) {
			const matches = cur.match(re);
			if (matches) acc[matches[1]] = matches[2];
			return acc;
		}, {});
		if (!("quiet" in options)) options.quiet = "true";
		return options;
	};
}));
//#endregion
//#region node_modules/dotenv/config.js
(function() {
	require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
})();
//#endregion
//#region subgraphs/apply-to/schema.ts
const schema = gql`
  type ApplyToQueries {
    example(driveId: String!): String
  }

  type Query {
    applyTo: ApplyToQueries!
  }

  type Mutation {
    """
    Fusion "Apply" entry point: loads the grant pool, provisions an
    applicant-workspace drive (project + new grant-application), pre-fills the
    application with pool and project refs, links the application to the
    funder drive when the pool is found there, and returns deep-link fields.

    Each call creates a new, distinctly-named applicant drive so multiple
    applicants can apply to the same grant pool without collision.
    """
    applyToPool(input: ApplyToPoolInput!): ApplyToPoolOutput!
  }

  input ApplyToPoolInput {
    """Grant pool PHID the applicant is applying to."""
    grantPoolId: PHID!
    """
    Applicant display name. Required — used as the primary differentiator
    in drive and project naming so funders can tell applicants apart at a glance.
    """
    applicantName: String!
    """
    Optional applicant contact email. When provided, stored on the applicant's
    project document so reviewers can reach out.
    """
    applicantEmail: String
  }

  type ApplyToPoolOutput {
    success: Boolean!
    data: ApplyToPoolData
    errors: [String!]!
  }

  type ApplyToPoolData {
    driveId: PHID!
    applicationId: PHID!
    projectId: PHID!
    driveSlug: String!
    """
    Local Connect open URL; includes document id for opening the new application when supported.
    """
    redirectUrl: String!
  }
`;
//#endregion
//#region subgraphs/apply-to/resolvers.ts
/** Placeholder URIs; DAOIP-5 fields require valid URLs. Replace when Fusion/Connect expose canonical registries. */
const GRANT_POOLS_REGISTRY_URI = "https://local.invalid/grant-pools";
const PROJECTS_REGISTRY_URI = "https://local.invalid/projects";
/** Stopwords dropped from pool-name acronym (keeps acronym compact and readable). */
const ACRONYM_STOPWORDS = new Set([
	"the",
	"a",
	"an",
	"of",
	"and",
	"or",
	"for",
	"to",
	"in",
	"on",
	"at",
	"with",
	"by",
	"from",
	"as"
]);
/**
* Connect + Switchboard URLs are environment-specific. Preference order:
*   1. `CONNECT_URL` / `SWITCHBOARD_URL` — injected by the Vetra deployment
*      platform via manifest `config`, or set locally in `.env`.
*   2. `NEXT_PUBLIC_*` aliases — same var, alt prefix some deployments use.
*   3. Hardcoded `light-fawn-92` deployment fallback, so a misconfigured
*      deploy still produces a working production redirect rather than a
*      dead `localhost` link.
* Trailing slashes and `/graphql` suffixes are stripped so we can append
* `/d/<slug>` reliably.
*/
const FALLBACK_CONNECT_URL = "https://connect.light-fawn-92.vetra.io";
const FALLBACK_SWITCHBOARD_URL = "https://switchboard.light-fawn-92.vetra.io/graphql";
function stripTrailingSlash(url) {
	return url.replace(/\/+$/, "");
}
function getConnectUrl() {
	return stripTrailingSlash(process.env.CONNECT_URL ?? process.env.NEXT_PUBLIC_CONNECT_URL ?? FALLBACK_CONNECT_URL);
}
function getSwitchboardBaseUrl() {
	return stripTrailingSlash(process.env.SWITCHBOARD_URL ?? process.env.NEXT_PUBLIC_SWITCHBOARD_URL ?? FALLBACK_SWITCHBOARD_URL).replace(/\/graphql$/, "");
}
function getRedirectUrl(driveSlug, applicationId) {
	const connectUrl = getConnectUrl();
	const driveUrl = `${getSwitchboardBaseUrl()}/d/${encodeURIComponent(driveSlug)}`;
	return `${connectUrl}/?driveUrl=${encodeURIComponent(driveUrl)}&docId=${encodeURIComponent(applicationId)}`;
}
/** Lowercase, hyphenate, strip non-url-safe chars, clamp length. Returns "" if nothing usable. */
function slugifyName(name, max = 24) {
	return name.trim().toLowerCase().normalize("NFKD").replace(/\p{Diacritic}/gu, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max).replace(/-+$/g, "");
}
/**
* Turn a multi-word pool name into a short uppercase acronym of first letters.
* "RFP Hub: Standard RFP Object and Public Aggregation API" → "RHSROPAA"
* "Web3 Community Round" → "WCR"
* Drops common stopwords. Clamped to `max` letters.
*/
function poolAcronym(name, max = 10) {
	return name.replace(/[^a-zA-Z0-9\s]/g, " ").split(/\s+/).map((w) => w.trim()).filter((w) => w.length > 0 && !ACRONYM_STOPWORDS.has(w.toLowerCase())).map((w) => w[0].toUpperCase()).slice(0, max).join("") || "RFP";
}
/**
* Build a drive slug that is unique across applicants AND across repeat
* applications from the same applicant. Shape:
*   apply-<poolShortId>-<applicantSlug>-<rand4>
* Falls back to a sensible default if applicantName has no url-safe chars.
*/
function slugForDrive(grantPoolId, applicantName) {
	const poolShort = grantPoolId.replace(/[^a-zA-Z0-9]/g, "").slice(0, 12);
	const applicantSlug = slugifyName(applicantName) || "applicant";
	const rand = generateId().slice(0, 4);
	return `apply-${poolShort || "pool"}-${applicantSlug}-${rand}`;
}
function truncateName(name, max) {
	const t = name.trim();
	return t.length <= max ? t : t.slice(0, max);
}
/**
* Drive node names are validated by the node reducer in
* `@powerhousedao/shared/document-drive` against `/^[a-zA-Z0-9-_.\s()]+$/`.
* Drop anything outside that set so the reducer accepts the file; otherwise
* `reactor.execute` silently skips the ADD_FILE op.
*/
function sanitizeNodeName(raw) {
	return raw.replace(/[^a-zA-Z0-9-_.\s()]+/g, " ").replace(/\s{2,}/g, " ").trim();
}
/** Very lenient email sanity check. Falsy if obviously invalid. */
function normalizeEmail(raw) {
	if (!raw) return null;
	const v = raw.trim();
	if (!v) return null;
	if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return null;
	return v;
}
/** Document IDs on drives that are themselves soft-deleted. */
async function getDeletedDriveDocIds(reactorClient) {
	const { results: drives } = await reactorClient.find({ type: "powerhouse/document-drive" });
	const ids = /* @__PURE__ */ new Set();
	for (const drive of drives) {
		if (!drive.state.document.isDeleted) continue;
		const driveDoc = drive;
		for (const node of driveDoc.state.global.nodes) if (node.kind === "file") ids.add(node.id);
	}
	return ids;
}
const getResolvers = (subgraph) => {
	const reactor = subgraph.reactorClient;
	return {
		Query: { applyTo: () => ({}) },
		ApplyToQueries: { example: (_parent, args) => {
			return `example: ${args.driveId}`;
		} },
		Mutation: { applyToPool: async (_parent, args) => {
			const { input } = args;
			const grantPoolId = input.grantPoolId?.trim();
			const applicantName = input.applicantName?.trim() ?? "";
			const applicantEmail = normalizeEmail(input.applicantEmail);
			if (!grantPoolId) return {
				success: false,
				data: null,
				errors: ["Grant pool id is required"]
			};
			if (!applicantName) return {
				success: false,
				data: null,
				errors: ["Applicant name is required"]
			};
			if (input.applicantEmail && input.applicantEmail.trim() && !applicantEmail) return {
				success: false,
				data: null,
				errors: ["Applicant email format is invalid"]
			};
			try {
				const deletedDriveDocIds = await getDeletedDriveDocIds(reactor);
				let grantPoolDoc;
				try {
					grantPoolDoc = await reactor.get(grantPoolId);
				} catch {
					return {
						success: false,
						data: null,
						errors: ["Grant pool not found"]
					};
				}
				if (grantPoolDoc.header.documentType !== "rfp-hub/grant-pool" || grantPoolDoc.state.document.isDeleted || deletedDriveDocIds.has(grantPoolId)) return {
					success: false,
					data: null,
					errors: ["Grant pool not found"]
				};
				const poolState = grantPoolDoc.state.global;
				const poolName = poolState.name?.trim() || "Grant pool";
				const acronym = poolAcronym(poolName);
				const driveDisplayName = truncateName(`${applicantName} — ${acronym}`, 64);
				const driveSlug = slugForDrive(grantPoolId, applicantName);
				const driveDoc = driveCreateDocument();
				driveDoc.header.name = driveDisplayName;
				driveDoc.state.global.name = driveDisplayName;
				driveDoc.state.global.icon = "https://cdn-icons-png.flaticon.com/512/3135/3135715.png";
				driveDoc.header.slug = driveSlug;
				if (!driveDoc.header.meta) driveDoc.header.meta = {};
				driveDoc.header.meta.preferredEditor = "applicant-workspace";
				const driveId = (await reactor.create(driveDoc)).header.id;
				const projectDoc = await reactor.createEmpty("rfp-hub/project", { parentIdentifier: driveId });
				const grantApplicationDoc = await reactor.createEmpty("rfp-hub/grant-application", { parentIdentifier: driveId });
				const projectFileName = truncateName(sanitizeNodeName(`${applicantName} Project`), 64);
				const applicationFileName = truncateName(sanitizeNodeName(`${acronym} Application`), 64);
				const projectFolderId = generateId();
				const applicationsFolderId = generateId();
				await reactor.execute(driveId, "main", [
					addFolder({
						id: projectFolderId,
						name: "My Project"
					}),
					addFolder({
						id: applicationsFolderId,
						name: "Applications"
					}),
					addFile({
						documentType: "rfp-hub/project",
						id: projectDoc.header.id,
						name: projectFileName,
						parentFolder: projectFolderId
					}),
					addFile({
						documentType: "rfp-hub/grant-application",
						id: grantApplicationDoc.header.id,
						name: applicationFileName,
						parentFolder: applicationsFolderId
					})
				]);
				const projectLabel = truncateName(applicantName, 120);
				const projectActions = [Project.actions.setProjectName({ name: projectLabel }), Project.actions.addRelevantPool({
					id: generateId(),
					poolId: grantPoolId,
					poolName
				})];
				if (applicantEmail) projectActions.push(Project.actions.setProjectEmail({ email: applicantEmail }));
				await reactor.execute(projectDoc.header.id, "main", projectActions);
				const now = (/* @__PURE__ */ new Date()).toISOString();
				const appActions = [
					GrantApplication.actions.setPoolRef({
						grantPoolId,
						grantPoolName: poolName,
						grantPoolsURI: GRANT_POOLS_REGISTRY_URI
					}),
					GrantApplication.actions.setProjectRef({
						projectId: projectDoc.header.id,
						projectName: projectLabel,
						projectsURI: PROJECTS_REGISTRY_URI
					}),
					GrantApplication.actions.setCreatedAt({ createdAt: now })
				];
				const minGrantAmount = poolState.minGrant?.[0]?.amount;
				if (minGrantAmount && typeof minGrantAmount.value === "number" && typeof minGrantAmount.unit === "string" && minGrantAmount.unit.trim()) appActions.push(GrantApplication.actions.addFundsAsked({
					id: generateId(),
					amount: {
						value: minGrantAmount.value,
						unit: minGrantAmount.unit
					}
				}));
				const minUsdRaw = minGrantAmount;
				if (minUsdRaw && typeof minUsdRaw.value === "number" && (minUsdRaw.unit === "USD" || minUsdRaw.unit === "USDC")) appActions.push(GrantApplication.actions.setFundsAskedUsd({ fundsAskedInUSD: {
					value: minUsdRaw.value,
					unit: "USD"
				} }));
				await reactor.execute(grantApplicationDoc.header.id, "main", appActions);
				return {
					success: true,
					data: {
						driveId,
						applicationId: grantApplicationDoc.header.id,
						projectId: projectDoc.header.id,
						driveSlug,
						redirectUrl: getRedirectUrl(driveSlug, grantApplicationDoc.header.id)
					},
					errors: []
				};
			} catch (error) {
				console.error("applyToPool failed:", error);
				return {
					success: false,
					data: null,
					errors: [error instanceof Error ? error.message : "An unexpected error occurred"]
				};
			}
		} }
	};
};
//#endregion
//#region subgraphs/apply-to/index.ts
var apply_to_exports = /* @__PURE__ */ __exportAll({ ApplyToSubgraph: () => ApplyToSubgraph });
var ApplyToSubgraph = class extends BaseSubgraph {
	name = "apply-to";
	typeDefs = schema;
	resolvers = getResolvers(this);
	additionalContextFields = {};
	async onSetup() {}
	async onDisconnect() {}
};
//#endregion
export { apply_to_exports as n, ApplyToSubgraph as t };

//# sourceMappingURL=apply-to-of3FkzIu.js.map