#!/usr/bin/env node
import "../chunk-DhYkiPYI.mjs";
import "../config-CtRi0Lgg.mjs";
import { $ as jsonArgs, A as printData, B as loadAccessToken, D as tokenCommand, G as fetchUserInfo, H as readPlatformConfig, I as loadConfig, J as readPackageJson, K as initOAuth2Client, M as generateCommand, O as listCommand$5, P as applyCommand, Q as deploymentArgs, R as apiCommand, S as listCommand$6, U as writePlatformConfig, V as loadWorkspaceId, W as fetchAll, X as commonArgs, Y as PATScope, Z as confirmationArgs, a as createCommand$3, d as listCommand$7, et as withCommonArgs, h as executionsCommand, l as startCommand, nt as logger, p as getCommand$2, q as initOperatorClient, r as deleteCommand$3, s as resumeCommand, t as listCommand$8, tt as workspaceArgs, w as getCommand$1, x as removeCommand, y as showCommand, z as fetchLatestToken } from "../list-C0wNbdbP.mjs";
import { register } from "node:module";
import { defineCommand, runCommand, runMain } from "citty";
import { generateCodeVerifier } from "@badgateway/oauth2-client";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Code, ConnectError } from "@connectrpc/connect";
import ml from "multiline-ts";
import * as path from "path";
import * as fs from "fs";
import pLimit from "p-limit";
import { spawnSync } from "node:child_process";
import * as crypto from "node:crypto";
import * as http from "node:http";
import open from "open";
import { lookup } from "mime-types";
import { setTimeout as setTimeout$1 } from "node:timers/promises";

//#region src/cli/init.ts
const detectPackageManager = () => {
	const availablePMs = [
		"npm",
		"yarn",
		"pnpm"
	];
	const userAgent = process.env.npm_config_user_agent;
	if (!userAgent) return;
	const [name] = userAgent.split("/");
	if (!availablePMs.includes(name)) return;
	return name;
};
const initCommand = defineCommand({
	meta: {
		name: "init",
		description: "Initialize a new project using create-sdk"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Project name",
			required: false
		},
		template: {
			type: "string",
			description: "Template name",
			required: false,
			alias: "t"
		}
	},
	run: withCommonArgs(async (args) => {
		const packageJson$1 = await readPackageJson();
		const version = packageJson$1.version && packageJson$1.version !== "0.0.0" ? packageJson$1.version : "latest";
		let packageManager = detectPackageManager();
		if (!packageManager) {
			logger.warn("⚠️ Could not detect package manager, defaulting to npm");
			packageManager = "npm";
		}
		const initArgs = [
			"create",
			`@tailor-platform/sdk@${version}`,
			...args.name ? [args.name] : [],
			...packageManager === "npm" ? ["--"] : [],
			...args.template ? ["--template", args.template] : []
		];
		logger.log(`Running: ${packageManager} ${initArgs.join(" ")}`);
		spawnSync(packageManager, initArgs, { stdio: "inherit" });
	})
});

//#endregion
//#region src/cli/login.ts
const redirectPort = 8085;
const redirectUri = `http://localhost:${redirectPort}/callback`;
function randomState() {
	return crypto.randomBytes(32).toString("base64url");
}
const startAuthServer = async () => {
	const client = initOAuth2Client();
	const state = randomState();
	const codeVerifier = await generateCodeVerifier();
	return new Promise((resolve, reject) => {
		const server = http.createServer(async (req, res) => {
			try {
				if (!req.url?.startsWith("/callback")) throw new Error("Invalid callback URL");
				const tokens = await client.authorizationCode.getTokenFromCodeRedirect(`http://${req.headers.host}${req.url}`, {
					redirectUri,
					state,
					codeVerifier
				});
				const userInfo = await fetchUserInfo(tokens.accessToken);
				const pfConfig = readPlatformConfig();
				pfConfig.users = {
					...pfConfig.users,
					[userInfo.email]: {
						access_token: tokens.accessToken,
						refresh_token: tokens.refreshToken,
						token_expires_at: new Date(tokens.expiresAt).toISOString()
					}
				};
				pfConfig.current_user = userInfo.email;
				writePlatformConfig(pfConfig);
				res.writeHead(200, { "Content-Type": "application/json" });
				res.end(JSON.stringify({
					status: "ok",
					message: "Successfully authenticated. Please close this window."
				}));
				resolve();
			} catch (error) {
				res.writeHead(401);
				res.end("Authentication failed");
				reject(error);
			} finally {
				server.close();
			}
		});
		const timeout = setTimeout(() => {
			server.close();
			reject(/* @__PURE__ */ new Error("Login timeout exceeded"));
		}, 300 * 1e3);
		server.on("close", () => {
			clearTimeout(timeout);
		});
		server.on("error", (error) => {
			reject(error);
		});
		server.listen(redirectPort, async () => {
			const authorizeUri = await client.authorizationCode.getAuthorizeUri({
				redirectUri,
				state,
				codeVerifier
			});
			logger.info(`Opening browser for login:\n\n${authorizeUri}\n`);
			try {
				await open(authorizeUri);
			} catch {
				logger.warn("Failed to open browser automatically. Please open the URL above manually.");
			}
		});
	});
};
const loginCommand = defineCommand({
	meta: {
		name: "login",
		description: "Login to Tailor Platform"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		await startAuthServer();
		logger.success("Successfully logged in to Tailor Platform.");
	})
});

//#endregion
//#region src/cli/logout.ts
const logoutCommand = defineCommand({
	meta: {
		name: "logout",
		description: "Logout from Tailor Platform"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		const pfConfig = readPlatformConfig();
		const tokens = pfConfig.current_user ? pfConfig.users[pfConfig.current_user] : void 0;
		if (!tokens) {
			logger.info("You are not logged in.");
			return;
		}
		initOAuth2Client().revoke({
			accessToken: tokens.access_token,
			refreshToken: tokens.refresh_token,
			expiresAt: Date.parse(tokens.token_expires_at)
		}, "refresh_token");
		delete pfConfig.users[pfConfig.current_user];
		pfConfig.current_user = null;
		writePlatformConfig(pfConfig);
		logger.success("Successfully logged out from Tailor Platform.");
	})
});

//#endregion
//#region src/cli/machineuser/index.ts
const machineuserCommand = defineCommand({
	meta: {
		name: "machineuser",
		description: "Manage machine users"
	},
	subCommands: {
		list: listCommand$5,
		token: tokenCommand
	},
	async run() {
		await runCommand(listCommand$5, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/oauth2client/index.ts
const oauth2clientCommand = defineCommand({
	meta: {
		name: "oauth2client",
		description: "Manage OAuth2 clients"
	},
	subCommands: {
		get: getCommand$1,
		list: listCommand$6
	},
	async run() {
		await runCommand(listCommand$6, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/profile/create.ts
const createCommand$2 = defineCommand({
	meta: {
		name: "create",
		description: "Create new profile"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		},
		user: {
			type: "string",
			description: "User email",
			required: true,
			alias: "u"
		},
		"workspace-id": {
			type: "string",
			description: "Workspace ID",
			required: true,
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (config.profiles[args.name]) throw new Error(`Profile "${args.name}" already exists.`);
		const client = await initOperatorClient(await fetchLatestToken(config, args.user));
		if (!(await fetchAll(async (pageToken) => {
			const { workspaces, nextPageToken } = await client.listWorkspaces({ pageToken });
			return [workspaces, nextPageToken];
		})).find((ws) => ws.id === args["workspace-id"])) throw new Error(`Workspace "${args["workspace-id"]}" not found.`);
		config.profiles[args.name] = {
			user: args.user,
			workspace_id: args["workspace-id"]
		};
		writePlatformConfig(config);
		if (!args.json) logger.success(`Profile "${args.name}" created successfully.`);
		printData({
			name: args.name,
			user: args.user,
			workspaceId: args["workspace-id"]
		}, args.json);
	})
});

//#endregion
//#region src/cli/profile/delete.ts
const deleteCommand$2 = defineCommand({
	meta: {
		name: "delete",
		description: "Delete profile"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.profiles[args.name]) throw new Error(`Profile "${args.name}" not found.`);
		delete config.profiles[args.name];
		writePlatformConfig(config);
		logger.success(`Profile "${args.name}" deleted successfully.`);
	})
});

//#endregion
//#region src/cli/profile/list.ts
const listCommand$4 = defineCommand({
	meta: {
		name: "list",
		description: "List all profiles"
	},
	args: {
		...commonArgs,
		...jsonArgs
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		const profiles = Object.entries(config.profiles);
		if (profiles.length === 0) {
			logger.info(ml`
        No profiles found.
        Please create a profile first using 'tailor-sdk profile create' command.
      `);
			return;
		}
		printData(profiles.map(([name, profile]) => ({
			name,
			user: profile.user,
			workspaceId: profile.workspace_id
		})), args.json);
	})
});

//#endregion
//#region src/cli/profile/update.ts
const updateCommand$1 = defineCommand({
	meta: {
		name: "update",
		description: "Update profile properties"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		name: {
			type: "positional",
			description: "Profile name",
			required: true
		},
		user: {
			type: "string",
			description: "New user email",
			alias: "u"
		},
		"workspace-id": {
			type: "string",
			description: "New workspace ID",
			alias: "w"
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.profiles[args.name]) throw new Error(`Profile "${args.name}" not found.`);
		if (!args.user && !args["workspace-id"]) throw new Error("Please provide at least one property to update.");
		const profile = config.profiles[args.name];
		const oldUser = profile.user;
		const newUser = args.user || oldUser;
		const oldWorkspaceId = profile.workspace_id;
		const newWorkspaceId = args["workspace-id"] || oldWorkspaceId;
		const client = await initOperatorClient(await fetchLatestToken(config, newUser));
		if (!(await fetchAll(async (pageToken) => {
			const { workspaces, nextPageToken } = await client.listWorkspaces({ pageToken });
			return [workspaces, nextPageToken];
		})).find((ws) => ws.id === newWorkspaceId)) throw new Error(`Workspace "${newWorkspaceId}" not found.`);
		profile.user = newUser;
		profile.workspace_id = newWorkspaceId;
		writePlatformConfig(config);
		if (!args.json) logger.success(`Profile "${args.name}" updated successfully`);
		printData({
			name: args.name,
			user: newUser,
			workspaceId: newWorkspaceId
		}, args.json);
	})
});

//#endregion
//#region src/cli/profile/index.ts
const profileCommand = defineCommand({
	meta: {
		name: "profile",
		description: "Manage workspace profiles (user + workspace combinations)"
	},
	subCommands: {
		create: createCommand$2,
		delete: deleteCommand$2,
		list: listCommand$4,
		update: updateCommand$1
	},
	async run() {
		await runCommand(listCommand$4, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/secret/args.ts
/**
* Arguments for specify secret key
*/
const vaultArgs = { "vault-name": {
	type: "string",
	description: "Vault name",
	alias: "V",
	required: true
} };
/**
* Arguments for specify secret key
*/
const secretIdentifyArgs = {
	...vaultArgs,
	name: {
		type: "string",
		description: "Secret name",
		alias: "n",
		required: true
	}
};
/**
* Arguments for specify secret key
*/
const secretValueArgs = {
	...secretIdentifyArgs,
	value: {
		type: "string",
		description: "Secret value",
		alias: "v",
		required: true
	}
};

//#endregion
//#region src/cli/secret/create.ts
const createSecretCommand = defineCommand({
	meta: {
		name: "create",
		description: "Create a secret in a vault"
	},
	args: {
		...commonArgs,
		...workspaceArgs,
		...secretValueArgs
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.createSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name,
				secretmanagerSecretValue: args.value
			});
		} catch (error) {
			if (error instanceof ConnectError) {
				if (error.code === Code.NotFound) throw new Error(`Vault "${args["vault-name"]}" not found.`);
				if (error.code === Code.AlreadyExists) throw new Error(`Secret "${args.name}" already exists.`);
			}
			throw error;
		}
		logger.success(`Secret: ${args.name} created in vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/delete.ts
const deleteSecretCommand = defineCommand({
	meta: {
		name: "delete",
		description: "Delete a secret in a vault"
	},
	args: {
		...commonArgs,
		...workspaceArgs,
		...secretIdentifyArgs,
		...confirmationArgs
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		if (!args.yes) {
			if (await logger.prompt(`Enter the secret name to confirm deletion ("${args.name}"): `, { type: "text" }) !== args.name) {
				logger.info("Secret deletion cancelled.");
				return;
			}
		}
		try {
			await client.deleteSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Secret "${args.name}" not found in vault "${args["vault-name"]}".`);
			throw error;
		}
		logger.success(`Secret: ${args.name} deleted from vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/list.ts
function secretInfo(secret) {
	return {
		name: secret.name,
		createdAt: secret.createTime ? timestampDate(secret.createTime).toISOString() : "N/A",
		updatedAt: secret.updateTime ? timestampDate(secret.updateTime).toISOString() : "N/A"
	};
}
async function secretList(options) {
	const client = await initOperatorClient(await loadAccessToken({
		useProfile: true,
		profile: options.profile
	}));
	const workspaceId = loadWorkspaceId({
		workspaceId: options.workspaceId,
		profile: options.profile
	});
	return (await fetchAll(async (pageToken) => {
		const { secrets, nextPageToken } = await client.listSecretManagerSecrets({
			workspaceId,
			secretmanagerVaultName: options.vaultName,
			pageToken
		});
		return [secrets, nextPageToken];
	})).map(secretInfo);
}
const listSecretCommand = defineCommand({
	meta: {
		name: "list",
		description: "List secrets in a vault"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		...workspaceArgs,
		...vaultArgs
	},
	run: withCommonArgs(async (args) => {
		try {
			printData(await secretList({
				workspaceId: args["workspace-id"],
				profile: args.profile,
				vaultName: args["vault-name"]
			}), args.json);
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Vault "${args["vault-name"]}" not found.`);
			throw error;
		}
	})
});

//#endregion
//#region src/cli/secret/update.ts
const updateSecretCommand = defineCommand({
	meta: {
		name: "update",
		description: "Update a secret in a vault"
	},
	args: {
		...commonArgs,
		...workspaceArgs,
		...secretValueArgs
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.updateSecretManagerSecret({
				workspaceId,
				secretmanagerVaultName: args["vault-name"],
				secretmanagerSecretName: args.name,
				secretmanagerSecretValue: args.value
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Secret "${args.name}" not found in vault "${args["vault-name"]}".`);
			throw error;
		}
		logger.success(`Secret: ${args.name} updated in vault: ${args["vault-name"]}`);
	})
});

//#endregion
//#region src/cli/secret/vault/args.ts
const nameArgs = { name: {
	type: "positional",
	description: "Vault name",
	required: true
} };

//#endregion
//#region src/cli/secret/vault/create.ts
const createCommand$1 = defineCommand({
	meta: {
		name: "create",
		description: "Create a Secret Manager vault"
	},
	args: {
		...commonArgs,
		...workspaceArgs,
		...nameArgs
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		try {
			await client.createSecretManagerVault({
				workspaceId,
				secretmanagerVaultName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.AlreadyExists) throw new Error(`Vault "${args.name}" already exists.`);
			throw error;
		}
		logger.success(`Vault: ${args.name} created`);
	})
});

//#endregion
//#region src/cli/secret/vault/delete.ts
const deleteCommand$1 = defineCommand({
	meta: {
		name: "delete",
		description: "Delete a Secret Manager vault"
	},
	args: {
		...commonArgs,
		...workspaceArgs,
		...nameArgs,
		...confirmationArgs
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		if (!args.yes) {
			if (await logger.prompt(`Enter the vault name to confirm deletion ("${args.name}"): `, { type: "text" }) !== args.name) {
				logger.info("Vault deletion cancelled.");
				return;
			}
		}
		try {
			await client.deleteSecretManagerVault({
				workspaceId,
				secretmanagerVaultName: args.name
			});
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(`Vault "${args.name}" not found.`);
			throw error;
		}
		logger.success(`Vault: ${args.name} deleted`);
	})
});

//#endregion
//#region src/cli/secret/vault/list.ts
function vaultInfo(vault) {
	return {
		name: vault.name,
		createdAt: vault.createTime ? timestampDate(vault.createTime).toISOString() : "N/A",
		updatedAt: vault.updateTime ? timestampDate(vault.updateTime).toISOString() : "N/A"
	};
}
async function vaultList(options) {
	const client = await initOperatorClient(await loadAccessToken({
		useProfile: true,
		profile: options?.profile
	}));
	const workspaceId = loadWorkspaceId({
		workspaceId: options?.workspaceId,
		profile: options?.profile
	});
	return (await fetchAll(async (pageToken) => {
		const { vaults, nextPageToken } = await client.listSecretManagerVaults({
			workspaceId,
			pageToken
		});
		return [vaults, nextPageToken];
	})).map(vaultInfo);
}
const listCommand$3 = defineCommand({
	meta: {
		name: "list",
		description: "List Secret Manager vaults"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		...workspaceArgs
	},
	run: withCommonArgs(async (args) => {
		printData(await vaultList({
			workspaceId: args["workspace-id"],
			profile: args.profile
		}), args.json);
	})
});

//#endregion
//#region src/cli/secret/vault/index.ts
const vaultCommand = defineCommand({
	meta: {
		name: "vault",
		description: "Manage Secret Manager vaults"
	},
	subCommands: {
		create: createCommand$1,
		delete: deleteCommand$1,
		list: listCommand$3
	},
	async run() {
		await runCommand(listCommand$3, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/secret/index.ts
const secretCommand = defineCommand({
	meta: {
		name: "secret",
		description: "Manage secrets and vaults"
	},
	subCommands: {
		create: createSecretCommand,
		delete: deleteSecretCommand,
		list: listSecretCommand,
		update: updateSecretCommand,
		vault: vaultCommand
	},
	async run() {
		await runCommand(vaultCommand, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/utils/progress.ts
function createProgress(label, total) {
	let current = 0;
	const update = () => {
		current += 1;
		const percent = Math.round(current / total * 100);
		process.stdout.write(`\r${label} ${current}/${total} (${percent}%)`);
	};
	const finish = () => {
		process.stdout.write("\n");
	};
	return {
		update,
		finish
	};
}
async function withTimeout(p, ms, message) {
	return await Promise.race([p, setTimeout$1(ms).then(() => {
		throw new Error(message);
	})]);
}

//#endregion
//#region src/cli/staticwebsite/deploy.ts
const CHUNK_SIZE = 64 * 1024;
const IGNORED_FILES = new Set([
	".DS_Store",
	"thumbs.db",
	"desktop.ini"
]);
function shouldIgnoreFile(filePath) {
	const fileName = path.basename(filePath).toLowerCase();
	return IGNORED_FILES.has(fileName);
}
async function deployStaticWebsite(client, workspaceId, name, distDir, showProgress = true) {
	const { deploymentId } = await client.createDeployment({
		workspaceId,
		name
	});
	if (!deploymentId) throw new Error("createDeployment returned empty deploymentId");
	const skippedFiles = await uploadDirectory(client, workspaceId, deploymentId, distDir, showProgress);
	const { url } = await client.publishDeployment({
		workspaceId,
		deploymentId
	});
	if (!url) throw new Error("publishDeployment returned empty url");
	return {
		url,
		skippedFiles
	};
}
async function uploadDirectory(client, workspaceId, deploymentId, rootDir, showProgress) {
	const files = await collectFiles(rootDir);
	if (files.length === 0) {
		logger.warn(`No files found under ${rootDir}`);
		return [];
	}
	const limit = pLimit(5);
	const total = files.length;
	const progress = showProgress ? createProgress("Uploading files", total) : void 0;
	const skippedFiles = [];
	await Promise.all(files.map((relativePath) => limit(async () => {
		await uploadSingleFile(client, workspaceId, deploymentId, rootDir, relativePath, skippedFiles);
		if (progress) progress.update();
	})));
	if (progress) progress.finish();
	return skippedFiles;
}
async function collectFiles(rootDir, currentDir = "") {
	const dirPath = path.join(rootDir, currentDir);
	const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
	const files = [];
	for (const entry of entries) {
		const rel = path.join(currentDir, entry.name);
		if (entry.isDirectory()) {
			const sub = await collectFiles(rootDir, rel);
			files.push(...sub);
		} else if (entry.isFile() && !entry.isSymbolicLink() && !shouldIgnoreFile(rel)) files.push(rel);
	}
	return files;
}
async function uploadSingleFile(client, workspaceId, deploymentId, rootDir, relativePath, skippedFiles) {
	const absPath = path.join(rootDir, relativePath);
	const filePath = relativePath.split(path.sep).join("/");
	const mime = lookup(filePath);
	if (!mime) {
		skippedFiles.push(`${filePath} (unsupported content type; no MIME mapping found)`);
		return;
	}
	const contentType = mime;
	const readStream = fs.createReadStream(absPath, { highWaterMark: CHUNK_SIZE });
	async function* requestStream() {
		yield { payload: {
			case: "initialMetadata",
			value: {
				workspaceId,
				deploymentId,
				filePath,
				contentType
			}
		} };
		for await (const chunk of readStream) yield { payload: {
			case: "chunkData",
			value: chunk
		} };
	}
	async function uploadWithLogging() {
		try {
			await client.uploadFile(requestStream());
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.InvalidArgument) {
				skippedFiles.push(`${filePath} (server rejected file as invalid: ${error.message})`);
				return;
			}
			throw error;
		}
	}
	await withTimeout(uploadWithLogging(), 2 * 6e4, `Upload timed out for "${filePath}"`);
}
function logSkippedFiles(skippedFiles) {
	if (skippedFiles.length === 0) return;
	logger.warn("Deployment completed, but some files failed to upload. These files may have unsupported content types or other validation issues. Please review the list below:");
	for (const file of skippedFiles) logger.log(`  - ${file}`);
}
const deployCommand = defineCommand({
	meta: {
		name: "deploy",
		description: "Deploy a static website"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		...workspaceArgs,
		name: {
			type: "string",
			description: "Static website name",
			alias: "n",
			required: true
		},
		dir: {
			type: "string",
			description: "Path to the static website files",
			alias: "d",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		logger.info(`Deploying static website "${args.name}" from directory: ${args.dir}`);
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const name = args.name;
		const dir = path.resolve(process.cwd(), args.dir);
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`Directory not found or not a directory: ${dir}`);
		const { url, skippedFiles } = await withTimeout(deployStaticWebsite(client, workspaceId, name, dir, !args.json), 10 * 6e4, "Deployment timed out after 10 minutes.");
		if (args.json) printData({
			name,
			workspaceId,
			url,
			skippedFiles
		}, true);
		else {
			logger.success(`Static website "${name}" deployed successfully. URL: ${url}`);
			logSkippedFiles(skippedFiles);
		}
	})
});

//#endregion
//#region src/cli/staticwebsite/get.ts
const getCommand = defineCommand({
	meta: {
		name: "get",
		description: "Get static website details"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		...workspaceArgs,
		name: {
			type: "positional",
			description: "Static website name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const client = await initOperatorClient(await loadAccessToken({
			useProfile: true,
			profile: args.profile
		}));
		const workspaceId = loadWorkspaceId({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		const notFoundErrorMessage = `Static website "${args.name}" not found.`;
		try {
			const { staticwebsite } = await client.getStaticWebsite({
				workspaceId,
				name: args.name
			});
			if (!staticwebsite) throw new Error(notFoundErrorMessage);
			printData({
				workspaceId,
				name: staticwebsite.name,
				description: staticwebsite.description,
				url: staticwebsite.url,
				allowedIpAddresses: args.json ? staticwebsite.allowedIpAddresses : staticwebsite.allowedIpAddresses.join("\n")
			}, args.json);
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(notFoundErrorMessage);
			throw error;
		}
	})
});

//#endregion
//#region src/cli/staticwebsite/list.ts
async function listStaticWebsites(options) {
	const client = await initOperatorClient(await loadAccessToken({
		useProfile: true,
		profile: options?.profile
	}));
	const workspaceId = loadWorkspaceId({
		workspaceId: options?.workspaceId,
		profile: options?.profile
	});
	return (await fetchAll(async (pageToken) => {
		const { staticwebsites, nextPageToken } = await client.listStaticWebsites({
			workspaceId,
			pageToken
		});
		return [staticwebsites, nextPageToken];
	})).map((site) => ({
		workspaceId,
		name: site.name,
		description: site.description,
		url: site.url ?? "",
		allowedIpAddresses: site.allowedIpAddresses
	}));
}
const listCommand$2 = defineCommand({
	meta: {
		name: "list",
		description: "List static websites"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		...workspaceArgs
	},
	run: withCommonArgs(async (args) => {
		const websites = await listStaticWebsites({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		printData(args.json ? websites : websites.map(({ allowedIpAddresses, ...rest }) => {
			if (allowedIpAddresses.length === 0) return {
				...rest,
				allowedIpAddresses: "No allowed IP addresses"
			};
			const count = allowedIpAddresses.length;
			const label = count === 1 ? "1 IP address" : `${count} IP addresses`;
			return {
				...rest,
				allowedIpAddresses: label
			};
		}), args.json);
	})
});

//#endregion
//#region src/cli/staticwebsite/index.ts
const staticwebsiteCommand = defineCommand({
	meta: {
		name: "staticwebsite",
		description: "Manage static websites"
	},
	subCommands: {
		deploy: deployCommand,
		get: getCommand,
		list: listCommand$2
	},
	async run() {
		await runCommand(listCommand$2, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/tailordb/truncate.ts
async function truncateSingleType(options, client) {
	await client.truncateTailorDBType({
		workspaceId: options.workspaceId,
		namespaceName: options.namespaceName,
		tailordbTypeName: options.typeName
	});
	logger.success(`Truncated type "${options.typeName}" in namespace "${options.namespaceName}"`);
}
async function truncateNamespace(workspaceId, namespaceName, client) {
	await client.truncateTailorDBTypes({
		workspaceId,
		namespaceName
	});
	logger.success(`Truncated all types in namespace "${namespaceName}"`);
}
async function getAllNamespaces(configPath) {
	const { config } = await loadConfig(configPath);
	const namespaces = /* @__PURE__ */ new Set();
	if (config.db) for (const [namespaceName] of Object.entries(config.db)) namespaces.add(namespaceName);
	return Array.from(namespaces);
}
async function getTypeNamespace(workspaceId, typeName, client, configPath) {
	const namespaces = await getAllNamespaces(configPath);
	for (const namespace of namespaces) try {
		const { tailordbTypes } = await client.listTailorDBTypes({
			workspaceId,
			namespaceName: namespace
		});
		if (tailordbTypes.some((type) => type.name === typeName)) return namespace;
	} catch {
		continue;
	}
	return null;
}
async function truncate(options) {
	const client = await initOperatorClient(await loadAccessToken({
		useProfile: true,
		profile: options?.profile
	}));
	const workspaceId = loadWorkspaceId({
		workspaceId: options?.workspaceId,
		profile: options?.profile
	});
	const hasTypes = options?.types && options.types.length > 0;
	const hasNamespace = !!options?.namespace;
	const hasAll = !!options?.all;
	const optionCount = [
		hasAll,
		hasNamespace,
		hasTypes
	].filter(Boolean).length;
	if (optionCount === 0) throw new Error("Please specify one of: --all, --namespace <name>, or type names");
	if (optionCount > 1) throw new Error("Options --all, --namespace, and type names are mutually exclusive. Please specify only one.");
	const namespaces = await getAllNamespaces(options?.configPath);
	if (hasAll) {
		if (namespaces.length === 0) {
			logger.warn("No namespaces found in config file.");
			return;
		}
		if (!options?.yes) {
			const namespaceList = namespaces.join(", ");
			if (!await logger.prompt(`This will truncate ALL tables in the following namespaces: ${namespaceList}. Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				logger.info("Truncate cancelled.");
				return;
			}
		}
		for (const namespace of namespaces) await truncateNamespace(workspaceId, namespace, client);
		logger.success("Truncated all tables in all namespaces");
		return;
	}
	if (hasNamespace && options?.namespace) {
		const namespace = options.namespace;
		if (!namespaces.includes(namespace)) throw new Error(`Namespace "${namespace}" not found in config. Available namespaces: ${namespaces.join(", ")}`);
		if (!options.yes) {
			if (!await logger.prompt(`This will truncate ALL tables in namespace "${namespace}". Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				logger.info("Truncate cancelled.");
				return;
			}
		}
		await truncateNamespace(workspaceId, namespace, client);
		return;
	}
	if (hasTypes && options?.types) {
		const typeNames = options.types;
		const typeNamespaceMap = /* @__PURE__ */ new Map();
		const notFoundTypes = [];
		for (const typeName of typeNames) {
			const namespace = await getTypeNamespace(workspaceId, typeName, client, options.configPath);
			if (namespace) typeNamespaceMap.set(typeName, namespace);
			else notFoundTypes.push(typeName);
		}
		if (notFoundTypes.length > 0) throw new Error(`The following types were not found in any namespace: ${notFoundTypes.join(", ")}`);
		if (!options.yes) {
			const typeList = typeNames.join(", ");
			if (!await logger.prompt(`This will truncate the following types: ${typeList}. Continue? (yes/no)`, {
				type: "confirm",
				initial: false
			})) {
				logger.info("Truncate cancelled.");
				return;
			}
		}
		for (const typeName of typeNames) {
			const namespace = typeNamespaceMap.get(typeName);
			if (!namespace) continue;
			await truncateSingleType({
				workspaceId,
				namespaceName: namespace,
				typeName
			}, client);
		}
	}
}
const truncateCommand = defineCommand({
	meta: {
		name: "truncate",
		description: "Truncate TailorDB tables"
	},
	args: {
		...commonArgs,
		types: {
			type: "positional",
			description: "Type names to truncate",
			required: false
		},
		all: {
			type: "boolean",
			description: "Truncate all tables in all namespaces",
			default: false,
			alias: "a"
		},
		namespace: {
			type: "string",
			description: "Truncate all tables in specified namespace",
			alias: "n"
		},
		yes: {
			type: "boolean",
			description: "Skip confirmation prompt",
			alias: "y",
			default: false
		},
		...deploymentArgs
	},
	run: withCommonArgs(async (args) => {
		const types = args._.length > 0 ? args._.map((arg) => String(arg)).filter(Boolean) : void 0;
		await truncate({
			workspaceId: args["workspace-id"],
			profile: args.profile,
			configPath: args.config,
			all: args.all,
			namespace: args.namespace,
			types,
			yes: args.yes
		});
	})
});

//#endregion
//#region src/cli/tailordb/index.ts
const tailordbCommand = defineCommand({
	meta: {
		name: "tailordb",
		description: "Manage TailorDB tables and data"
	},
	subCommands: { truncate: truncateCommand }
});

//#endregion
//#region src/cli/user/current.ts
const currentCommand = defineCommand({
	meta: {
		name: "current",
		description: "Show current user"
	},
	args: commonArgs,
	run: withCommonArgs(async () => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        Current user not set.
        Please login first using 'tailor-sdk login' command to register a user.
      `);
		if (!config.users[config.current_user]) throw new Error(ml`
        Current user '${config.current_user}' not found in registered users.
        Please login again using 'tailor-sdk login' command to register the user.
      `);
		logger.log(config.current_user);
	})
});

//#endregion
//#region src/cli/user/list.ts
const listCommand$1 = defineCommand({
	meta: {
		name: "list",
		description: "List all users"
	},
	args: {
		...commonArgs,
		...jsonArgs
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		const users = Object.keys(config.users);
		if (users.length === 0) {
			logger.info(ml`
        No users found.
        Please login first using 'tailor-sdk login' command to register a user.
      `);
			return;
		}
		if (args.json) {
			printData(users, args.json);
			return;
		}
		users.forEach((user) => {
			if (user === config.current_user) logger.success(`${user} (current)`, { mode: "plain" });
			else logger.log(user);
		});
	})
});

//#endregion
//#region src/cli/user/pat/transform.ts
function patScopeToString(scope) {
	switch (scope) {
		case PATScope.PAT_SCOPE_READ: return "read";
		case PATScope.PAT_SCOPE_WRITE: return "write";
		default: return "unknown";
	}
}
function transformPersonalAccessToken(pat) {
	return {
		name: pat.name,
		scopes: pat.scopes.map(patScopeToString)
	};
}
function getScopesFromWriteFlag(write) {
	return write ? [PATScope.PAT_SCOPE_READ, PATScope.PAT_SCOPE_WRITE] : [PATScope.PAT_SCOPE_READ];
}
function getScopeStringsFromWriteFlag(write) {
	return write ? ["read", "write"] : ["read"];
}
function printCreatedToken(name, token, write, action, json) {
	const scopes = getScopeStringsFromWriteFlag(write);
	if (json) printData({
		name,
		scopes,
		token
	}, json);
	else logger.log(ml`
      Personal access token ${action} successfully.

        name: ${name}
      scopes: ${scopes.join("/")}
       token: ${token}

      Please save this token in a secure location. You won't be able to see it again.
    `);
}

//#endregion
//#region src/cli/user/pat/create.ts
const createCommand = defineCommand({
	meta: {
		name: "create",
		description: "Create new personal access token"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		},
		write: {
			type: "boolean",
			description: "Grant write permission (default: read-only)",
			alias: "W",
			default: false
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const client = await initOperatorClient(await fetchLatestToken(config, config.current_user));
		const scopes = getScopesFromWriteFlag(args.write);
		const result = await client.createPersonalAccessToken({
			name: args.name,
			scopes
		});
		if (!result.accessToken) throw new Error("Failed to create personal access token");
		printCreatedToken(args.name, result.accessToken, args.write, "created", args.json);
	})
});

//#endregion
//#region src/cli/user/pat/delete.ts
const deleteCommand = defineCommand({
	meta: {
		name: "delete",
		description: "Delete personal access token"
	},
	args: {
		...commonArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		await (await initOperatorClient(await fetchLatestToken(config, config.current_user))).deletePersonalAccessToken({ name: args.name });
		logger.success(`Personal access token "${args.name}" deleted successfully.`);
	})
});

//#endregion
//#region src/cli/user/pat/list.ts
const listCommand = defineCommand({
	meta: {
		name: "list",
		description: "List all personal access tokens"
	},
	args: {
		...commonArgs,
		...jsonArgs
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const client = await initOperatorClient(await fetchLatestToken(config, config.current_user));
		const pats = await fetchAll(async (pageToken) => {
			const { personalAccessTokens, nextPageToken } = await client.listPersonalAccessTokens({ pageToken });
			return [personalAccessTokens, nextPageToken];
		});
		if (pats.length === 0) {
			logger.info(ml`
        No personal access tokens found.
        Please create a token using 'tailor-sdk user pat create' command.
      `);
			return;
		}
		if (args.json) {
			printData(pats.map(transformPersonalAccessToken), args.json);
			return;
		}
		const maxNameLength = Math.max(...pats.map((pat) => pat.name.length));
		pats.forEach((pat) => {
			const info = transformPersonalAccessToken(pat);
			const paddedName = info.name.padStart(maxNameLength);
			logger.log(`${paddedName}: ${info.scopes.join("/")}`);
		});
	})
});

//#endregion
//#region src/cli/user/pat/update.ts
const updateCommand = defineCommand({
	meta: {
		name: "update",
		description: "Update personal access token (delete and recreate)"
	},
	args: {
		...commonArgs,
		...jsonArgs,
		name: {
			type: "positional",
			description: "Token name",
			required: true
		},
		write: {
			type: "boolean",
			description: "Grant write permission (if not specified, keeps read-only)",
			alias: "W",
			default: false
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.current_user) throw new Error(ml`
        No user logged in.
        Please login first using 'tailor-sdk login' command.
      `);
		const client = await initOperatorClient(await fetchLatestToken(config, config.current_user));
		await client.deletePersonalAccessToken({ name: args.name });
		const scopes = getScopesFromWriteFlag(args.write);
		const result = await client.createPersonalAccessToken({
			name: args.name,
			scopes
		});
		if (!result.accessToken) throw new Error("Failed to create personal access token");
		printCreatedToken(args.name, result.accessToken, args.write, "updated", args.json);
	})
});

//#endregion
//#region src/cli/user/pat/index.ts
const patCommand = defineCommand({
	meta: {
		name: "pat",
		description: "Manage personal access tokens"
	},
	subCommands: {
		create: createCommand,
		delete: deleteCommand,
		list: listCommand,
		update: updateCommand
	},
	async run(context) {
		await runCommand(listCommand, { rawArgs: context.rawArgs || [] });
	}
});

//#endregion
//#region src/cli/user/switch.ts
const switchCommand = defineCommand({
	meta: {
		name: "switch",
		description: "Set current user"
	},
	args: {
		...commonArgs,
		user: {
			type: "positional",
			description: "User email",
			required: true
		}
	},
	run: withCommonArgs(async (args) => {
		const config = readPlatformConfig();
		if (!config.users[args.user]) throw new Error(ml`
        User "${args.user}" not found.
        Please login first using 'tailor-sdk login' command to register this user.
      `);
		config.current_user = args.user;
		writePlatformConfig(config);
		logger.success(`Current user set to "${args.user}" successfully.`);
	})
});

//#endregion
//#region src/cli/user/index.ts
const userCommand = defineCommand({
	meta: {
		name: "user",
		description: "Manage Tailor Platform users"
	},
	subCommands: {
		current: currentCommand,
		list: listCommand$1,
		pat: patCommand,
		switch: switchCommand
	},
	async run() {
		await runCommand(listCommand$1, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/workflow/index.ts
const workflowCommand = defineCommand({
	meta: {
		name: "workflow",
		description: "Manage workflows"
	},
	subCommands: {
		list: listCommand$7,
		get: getCommand$2,
		start: startCommand,
		executions: executionsCommand,
		resume: resumeCommand
	},
	async run() {
		await runCommand(listCommand$7, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/workspace/index.ts
const workspaceCommand = defineCommand({
	meta: {
		name: "workspace",
		description: "Manage Tailor Platform workspaces"
	},
	subCommands: {
		create: createCommand$3,
		delete: deleteCommand$3,
		list: listCommand$8
	},
	async run() {
		await runCommand(listCommand$8, { rawArgs: [] });
	}
});

//#endregion
//#region src/cli/index.ts
register("tsx", import.meta.url, { data: {} });
const packageJson = await readPackageJson();
const mainCommand = defineCommand({
	meta: {
		name: Object.keys(packageJson.bin ?? {})[0] || "tailor-sdk",
		version: packageJson.version,
		description: packageJson.description || "Tailor CLI for managing Tailor Platform SDK applications"
	},
	subCommands: {
		api: apiCommand,
		apply: applyCommand,
		generate: generateCommand,
		init: initCommand,
		login: loginCommand,
		logout: logoutCommand,
		machineuser: machineuserCommand,
		oauth2client: oauth2clientCommand,
		profile: profileCommand,
		remove: removeCommand,
		secret: secretCommand,
		show: showCommand,
		staticwebsite: staticwebsiteCommand,
		tailordb: tailordbCommand,
		user: userCommand,
		workflow: workflowCommand,
		workspace: workspaceCommand
	}
});
runMain(mainCommand);

//#endregion
export { mainCommand };
//# sourceMappingURL=index.mjs.map