#!/usr/bin/env node
import "../chunk-CIV_ash9.mjs";
import "../config-CBpYlVa-.mjs";
import { $ as deploymentArgs, A as listCommand$5, B as fetchLatestToken, C as removeCommand, E as getCommand$1, F as applyCommand, G as fetchAll, H as loadWorkspaceId, J as initOperatorClient, K as fetchUserInfo, L as loadConfig, N as generateCommand, Q as confirmationArgs, U as readPlatformConfig, V as loadAccessToken, W as writePlatformConfig, X as PATScope, Y as readPackageJson, Z as commonArgs, a as createCommand$3, d as listCommand$7, et as jsonArgs, h as executionsCommand, k as tokenCommand, l as startCommand, nt as workspaceArgs, p as getCommand$2, q as initOAuth2Client, r as deleteCommand$3, rt as logger, s as resumeCommand, t as listCommand$8, tt as withCommonArgs, w as listCommand$6, x as showCommand, y as truncateCommand, z as apiCommand } from "../list-1cs_CGF8.mjs";
import { createRequire, register } from "node:module";
import { defineCommand, runCommand, runMain } from "citty";
import * as fs$1 from "node:fs";
import * as path from "pathe";
import { generateCodeVerifier } from "@badgateway/oauth2-client";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Code, ConnectError } from "@connectrpc/connect";
import { findUpSync } from "find-up-simple";
import ml from "multiline-ts";
import * as fs$2 from "fs";
import pLimit from "p-limit";
import { spawn, 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.`);
		const profileInfo = {
			name: args.name,
			user: args.user,
			workspaceId: args["workspace-id"]
		};
		logger.out(profileInfo);
	})
});

//#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 () => {
		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;
		}
		const profileInfos = profiles.map(([name, profile]) => ({
			name,
			user: profile.user,
			workspaceId: profile.workspace_id
		}));
		logger.out(profileInfos);
	})
});

//#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`);
		const profileInfo = {
			name: args.name,
			user: newUser,
			workspaceId: newWorkspaceId
		};
		logger.out(profileInfo);
	})
});

//#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"
	};
}
/**
* List secrets in a Secret Manager vault.
* @param options - Secret listing options
* @returns List of secrets
*/
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 {
			const secrets = await secretList({
				workspaceId: args["workspace-id"],
				profile: args.profile,
				vaultName: args["vault-name"]
			});
			logger.out(secrets);
		} 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"
	};
}
/**
* List Secret Manager vaults in the workspace.
* @param options - Vault listing options
* @returns List of vaults
*/
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) => {
		const vaults = await vaultList({
			workspaceId: args["workspace-id"],
			profile: args.profile
		});
		logger.out(vaults);
	})
});

//#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
/**
* Create a simple progress reporter that writes updates to stderr.
* @param label - Label to prefix progress output
* @param total - Total number of steps
* @returns Progress helpers
*/
function createProgress(label, total) {
	let current = 0;
	const update = () => {
		current += 1;
		const percent = Math.round(current / total * 100);
		process.stderr.write(`\r${label} ${current}/${total} (${percent}%)`);
	};
	const finish = () => {
		process.stderr.write("\n");
	};
	return {
		update,
		finish
	};
}
/**
* Wrap a promise with a timeout, rejecting if the timeout elapses first.
* @template T
* @param p - Promise to await
* @param ms - Timeout in milliseconds
* @param message - Error message on timeout
* @returns Result of the original promise if it completes in time
*/
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);
}
/**
* Deploy a static website by creating a deployment, uploading files, and publishing it.
* @param client - Operator client instance
* @param workspaceId - Workspace ID
* @param name - Static website name
* @param distDir - Directory containing static site files
* @param showProgress - Whether to show upload progress
* @returns Deployment result with URL and skipped files
*/
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;
}
/**
* Recursively collect all deployable files under the given directory.
* @param rootDir - Root directory to scan
* @param currentDir - Current relative directory (for recursion)
* @returns List of file paths relative to rootDir
*/
async function collectFiles(rootDir, currentDir = "") {
	const dirPath = path.join(rootDir, currentDir);
	const entries = await fs$2.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, filePath, skippedFiles) {
	const absPath = path.join(rootDir, filePath);
	const mime = lookup(filePath);
	if (!mime) {
		skippedFiles.push(`${filePath} (unsupported content type; no MIME mapping found)`);
		return;
	}
	const contentType = mime;
	const readStream = fs$2.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}"`);
}
/**
* Log skipped files after a deployment, including reasons for skipping.
* @param skippedFiles - List of skipped file descriptions
*/
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$2.existsSync(dir) || !fs$2.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) logger.out({
			name,
			workspaceId,
			url,
			skippedFiles
		});
		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);
			const info = {
				workspaceId,
				name: staticwebsite.name,
				description: staticwebsite.description,
				url: staticwebsite.url,
				allowedIpAddresses: args.json ? staticwebsite.allowedIpAddresses : staticwebsite.allowedIpAddresses.join("\n")
			};
			logger.out(info);
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) throw new Error(notFoundErrorMessage);
			throw error;
		}
	})
});

//#endregion
//#region src/cli/staticwebsite/list.ts
/**
* List static websites in the workspace.
* @param options - Static website listing options
* @returns List of static websites
*/
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
		});
		const formatted = 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
			};
		});
		logger.out(formatted);
	})
});

//#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/utils/resolve-cli-bin.ts
/**
* Resolve a CLI binary path from the caller's project dependencies.
* @param options - Resolution options for locating the CLI binary.
* @returns Absolute path to the CLI binary entry.
*/
function resolveCliBinPath(options) {
	const { cwd, packageName, binName, installHint } = options;
	const projectPackageJsonPath = findUpSync("package.json", { cwd });
	if (!projectPackageJsonPath) throw new Error(`Failed to locate package.json from ${cwd}.`);
	const requireFromProject = createRequire(projectPackageJsonPath);
	let pkgJsonPath;
	try {
		pkgJsonPath = requireFromProject.resolve(`${packageName}/package.json`);
	} catch {
		throw new Error(`Missing optional dependency \`${packageName}\`. Install it in your project (e.g. \`${installHint}\`).`);
	}
	const binRelativePath = JSON.parse(fs$1.readFileSync(pkgJsonPath, "utf8")).bin?.[binName];
	if (!binRelativePath) throw new Error(`\`${packageName}\` does not expose a \`${binName}\` binary entry.`);
	return path.resolve(path.dirname(pkgJsonPath), binRelativePath);
}

//#endregion
//#region src/cli/tailordb/erd/schema.ts
/**
* Convert TailorDB field config to tbls column definition.
* @param fieldName - Field name
* @param fieldConfig - TailorDB field configuration
* @returns tbls column definition
*/
function toTblsColumn(fieldName, fieldConfig) {
	const baseType = fieldConfig.type || "string";
	return {
		name: fieldName,
		type: fieldConfig.array ? `${baseType}[]` : baseType,
		nullable: !fieldConfig.required,
		comment: fieldConfig.description ?? ""
	};
}
/**
* Build tbls schema JSON from TailorDB types.
* @param types - TailorDB types fetched from platform
* @param namespace - TailorDB namespace
* @returns tbls-compatible schema representation
*/
function buildTblsSchema(types, namespace) {
	const tables = [];
	const relations = [];
	const referencedByTable = {};
	const constraintsByTable = {};
	const enumsMap = /* @__PURE__ */ new Map();
	for (const type of types) {
		const tableName = type.name;
		const schema = type.schema;
		const columns = [];
		const tableConstraints = [];
		columns.push({
			name: "id",
			type: "uuid",
			nullable: false,
			comment: ""
		});
		tableConstraints.push({
			name: `pk_${tableName}`,
			type: "PRIMARY KEY",
			def: "",
			table: tableName,
			columns: ["id"]
		});
		if (schema) for (const [fieldName, fieldConfig] of Object.entries(schema.fields ?? {})) {
			columns.push(toTblsColumn(fieldName, fieldConfig));
			if (fieldConfig.type === "enum" && fieldConfig.allowedValues.length > 0) {
				const enumName = `${tableName}_${fieldName}`;
				let values = enumsMap.get(enumName);
				if (!values) {
					values = /* @__PURE__ */ new Set();
					enumsMap.set(enumName, values);
				}
				for (const value of fieldConfig.allowedValues) values.add(value.value);
			}
			if (fieldConfig.foreignKey && fieldConfig.foreignKeyType) {
				const foreignTable = fieldConfig.foreignKeyType;
				const foreignColumn = fieldConfig.foreignKeyField || "id";
				const childCardinality = fieldConfig.required ? "exactly_one" : "zero_or_one";
				relations.push({
					table: tableName,
					columns: [fieldName],
					parent_table: foreignTable,
					parent_columns: [foreignColumn],
					cardinality: childCardinality,
					parent_cardinality: "zero_or_more",
					def: ""
				});
				tableConstraints.push({
					name: `fk_${tableName}_${fieldName}`,
					type: "FOREIGN KEY",
					def: "",
					table: tableName,
					columns: [fieldName],
					referenced_table: foreignTable,
					referenced_columns: [foreignColumn]
				});
				if (!referencedByTable[tableName]) referencedByTable[tableName] = /* @__PURE__ */ new Set();
				referencedByTable[tableName].add(foreignTable);
			}
		}
		constraintsByTable[tableName] = tableConstraints;
		tables.push({
			name: tableName,
			type: "table",
			comment: schema?.description ?? "",
			columns,
			indexes: [],
			constraints: constraintsByTable[tableName] ?? [],
			triggers: [],
			def: "",
			referenced_tables: []
		});
	}
	for (const table of tables) {
		const referenced = referencedByTable[table.name];
		table.referenced_tables = referenced ? Array.from(referenced) : [];
	}
	const enums = [];
	for (const [name, values] of enumsMap.entries()) enums.push({
		name,
		values: Array.from(values)
	});
	return {
		name: namespace,
		tables,
		relations,
		enums
	};
}
/**
* Export apply-applied TailorDB schema for a namespace as tbls-compatible JSON.
* @param options - Export options
* @returns tbls schema representation
*/
async function exportTailorDBSchema(options) {
	const { client, workspaceId, namespace } = options;
	const types = await fetchAll(async (pageToken) => {
		try {
			const { tailordbTypes, nextPageToken } = await client.listTailorDBTypes({
				workspaceId,
				namespaceName: namespace,
				pageToken
			});
			return [tailordbTypes, nextPageToken];
		} catch (error) {
			if (error instanceof ConnectError && error.code === Code.NotFound) return [[], ""];
			throw error;
		}
	});
	if (types.length === 0) logger.warn(`No TailorDB types found in namespace "${namespace}". Returning empty schema.`);
	return buildTblsSchema(types, namespace);
}
/**
* Writes the TailorDB schema to a file in tbls-compatible JSON format.
* @param options - The options for writing the schema file.
*/
async function writeTblsSchemaToFile(options) {
	const schema = await exportTailorDBSchema(options);
	const json = JSON.stringify(schema, null, 2);
	fs$1.mkdirSync(path.dirname(options.outputPath), { recursive: true });
	fs$1.writeFileSync(options.outputPath, json, "utf8");
	const relativePath = path.relative(process.cwd(), options.outputPath);
	logger.success(`Wrote ERD schema to ${relativePath}`);
}

//#endregion
//#region src/cli/utils/beta.ts
/**
* Warn that the ERD CLI is a beta feature.
*/
function logErdBetaWarning() {
	logger.warn("The ERD command is a beta feature and may introduce breaking changes in future releases.");
	logger.newline();
}

//#endregion
//#region src/cli/tailordb/erd/utils.ts
/**
* Initialize shared ERD command context.
* @param args - CLI arguments.
* @returns Initialized context.
*/
async function initErdContext(args) {
	logErdBetaWarning();
	const client = await initOperatorClient(await loadAccessToken({
		useProfile: true,
		profile: args.profile
	}));
	const workspaceId = loadWorkspaceId({
		workspaceId: args.workspaceId,
		profile: args.profile
	});
	const { config } = await loadConfig(args.config);
	return {
		client,
		workspaceId,
		config
	};
}

//#endregion
//#region src/cli/tailordb/erd/export.ts
const DEFAULT_ERD_BASE_DIR = ".tailor-sdk/erd";
/**
* Resolve TailorDB config and namespace.
* @param config - Loaded Tailor SDK config.
* @param explicitNamespace - Namespace override.
* @returns Resolved namespace and erdSite.
*/
function resolveDbConfig(config, explicitNamespace) {
	const namespace = explicitNamespace ?? Object.keys(config.db ?? {})[0];
	if (!namespace) throw new Error("No TailorDB namespaces found in config. Please define db services in tailor.config.ts or pass --namespace.");
	const dbConfig = config.db?.[namespace];
	if (!dbConfig || typeof dbConfig !== "object" || "external" in dbConfig) throw new Error(`TailorDB namespace "${namespace}" not found in config.db.`);
	return {
		namespace,
		erdSite: dbConfig.erdSite
	};
}
/**
* Get all namespaces with erdSite configured.
* @param config - Loaded Tailor SDK config.
* @returns Namespaces with erdSite.
*/
function resolveAllErdSites(config) {
	const results = [];
	for (const [namespace, dbConfig] of Object.entries(config.db ?? {})) if (dbConfig && typeof dbConfig === "object" && !("external" in dbConfig) && dbConfig.erdSite) results.push({
		namespace,
		erdSite: dbConfig.erdSite
	});
	return results;
}
/**
* Run the liam CLI to build an ERD static site from a schema file.
* @param schemaPath - Path to the ERD schema JSON file
* @param cwd - Working directory where liam will run (dist is created here)
* @returns Resolves when the build completes successfully
*/
async function runLiamBuild(schemaPath, cwd) {
	fs$1.mkdirSync(cwd, { recursive: true });
	return await new Promise((resolve, reject) => {
		let liamBinPath;
		try {
			liamBinPath = resolveCliBinPath({
				cwd,
				packageName: "@liam-hq/cli",
				binName: "liam",
				installHint: "npm i -D @liam-hq/cli"
			});
		} catch (error) {
			logger.error(String(error));
			reject(error);
			return;
		}
		const child = spawn(process.execPath, [
			liamBinPath,
			"erd",
			"build",
			"--format",
			"tbls",
			"--input",
			schemaPath
		], {
			stdio: "inherit",
			cwd
		});
		child.on("error", (error) => {
			logger.error("Failed to run `@liam-hq/cli`. Ensure it is installed in your project.");
			reject(error);
		});
		child.on("exit", (code) => {
			if (code === 0) resolve();
			else {
				logger.error("liam CLI exited with a non-zero code. Ensure `@liam-hq/cli erd build --format tbls --input schema.json` works in your project.");
				reject(/* @__PURE__ */ new Error(`liam CLI exited with code ${code ?? 1}`));
			}
		});
	});
}
/**
* Export TailorDB schema and build ERD artifacts via liam.
* @param options - Build options.
*/
async function prepareErdBuild(options) {
	await writeTblsSchemaToFile(options);
	await runLiamBuild(options.outputPath, options.erdDir);
}
/**
* Prepare ERD builds for one or more namespaces.
* @param options - Build options.
* @returns Build results by namespace.
*/
async function prepareErdBuilds(options) {
	const { client, workspaceId, config } = options;
	const baseDir = options.outputDir ?? path.resolve(process.cwd(), DEFAULT_ERD_BASE_DIR);
	let targets;
	if (options.namespace) {
		const { namespace, erdSite } = resolveDbConfig(config, options.namespace);
		const erdDir = path.join(baseDir, namespace);
		targets = [{
			namespace,
			erdSite,
			schemaOutputPath: path.join(erdDir, "schema.json"),
			distDir: path.join(erdDir, "dist"),
			erdDir
		}];
	} else {
		const erdSites = resolveAllErdSites(config);
		if (erdSites.length === 0) throw new Error("No namespaces with erdSite configured found. Add erdSite: \"<static-website-name>\" to db.<namespace> in tailor.config.ts.");
		logger.info(`Found ${erdSites.length} namespace(s) with erdSite configured.`);
		targets = erdSites.map(({ namespace, erdSite }) => {
			const erdDir = path.join(baseDir, namespace);
			return {
				namespace,
				erdSite,
				schemaOutputPath: path.join(erdDir, "schema.json"),
				distDir: path.join(erdDir, "dist"),
				erdDir
			};
		});
	}
	await Promise.all(targets.map((target) => prepareErdBuild({
		namespace: target.namespace,
		client,
		workspaceId,
		outputPath: target.schemaOutputPath,
		erdDir: target.erdDir
	})));
	return targets;
}
const erdExportCommand = defineCommand({
	meta: {
		name: "export",
		description: "Export Liam ERD dist from applied TailorDB schema (beta)"
	},
	args: {
		...commonArgs,
		...deploymentArgs,
		...jsonArgs,
		namespace: {
			type: "string",
			description: "TailorDB namespace name (optional if only one namespace is defined in config)",
			alias: "n"
		},
		output: {
			type: "string",
			description: "Output directory path for tbls-compatible ERD JSON (writes to <outputDir>/<namespace>/schema.json)",
			alias: "o",
			default: DEFAULT_ERD_BASE_DIR
		}
	},
	run: withCommonArgs(async (args) => {
		const { client, workspaceId, config } = await initErdContext(args);
		const outputDir = path.resolve(process.cwd(), String(args.output));
		const results = await prepareErdBuilds({
			client,
			workspaceId,
			config,
			namespace: args.namespace,
			outputDir
		});
		if (args.json) logger.out(results.map((result) => ({
			namespace: result.namespace,
			distDir: result.distDir,
			schemaOutputPath: result.schemaOutputPath
		})));
		else for (const result of results) {
			logger.out(`Exported ERD for namespace "${result.namespace}"`);
			logger.out(`  - Liam ERD dist: ${result.distDir}`);
			logger.out(`  - tbls schema.json: ${result.schemaOutputPath}`);
		}
	})
});

//#endregion
//#region src/cli/tailordb/erd/deploy.ts
const erdDeployCommand = defineCommand({
	meta: {
		name: "deploy",
		description: "Deploy ERD static website for TailorDB namespace(s) (beta)"
	},
	args: {
		...commonArgs,
		...deploymentArgs,
		...jsonArgs,
		namespace: {
			type: "string",
			description: "TailorDB namespace name (optional - deploys all namespaces with erdSite if omitted)",
			alias: "n"
		}
	},
	run: withCommonArgs(async (args) => {
		const { client, workspaceId, config } = await initErdContext(args);
		const buildResults = await prepareErdBuilds({
			client,
			workspaceId,
			config,
			namespace: args.namespace
		});
		const deployResults = await Promise.all(buildResults.map(async (result) => {
			if (!result.erdSite) throw new Error(`No erdSite configured for namespace "${result.namespace}". Add erdSite: "<static-website-name>" to db.${result.namespace} in tailor.config.ts.`);
			if (!args.json) logger.info(`Deploying ERD for namespace "${result.namespace}" to site "${result.erdSite}"...`);
			const { url, skippedFiles } = await deployStaticWebsite(client, workspaceId, result.erdSite, result.distDir, !args.json);
			return {
				namespace: result.namespace,
				erdSite: result.erdSite,
				url,
				skippedFiles
			};
		}));
		if (args.json) logger.out(deployResults);
		else for (const result of deployResults) {
			logger.success(`ERD site "${result.erdSite}" deployed successfully.`);
			logger.out(result.url);
			logSkippedFiles(result.skippedFiles);
		}
	})
});

//#endregion
//#region src/cli/tailordb/erd/serve.ts
function formatServeCommand(namespace) {
	return `tailor-sdk tailordb erd serve --namespace ${namespace}`;
}
async function runServeDist(results) {
	if (results.length === 0) throw new Error("No ERD build results found.");
	const [primary, ...rest] = results;
	logger.info(`Serving ERD for namespace "${primary.namespace}".`);
	if (rest.length > 0) {
		const commands = rest.map((result) => `  - ${formatServeCommand(result.namespace)}`).join("\n");
		logger.warn(`Multiple namespaces found. To serve another namespace, run:\n${commands}`);
	}
	fs$1.mkdirSync(primary.erdDir, { recursive: true });
	return await new Promise((resolve, reject) => {
		let serveBinPath;
		try {
			serveBinPath = resolveCliBinPath({
				cwd: primary.erdDir,
				packageName: "serve",
				binName: "serve",
				installHint: "npm i -D serve"
			});
		} catch (error) {
			logger.error(String(error));
			reject(error);
			return;
		}
		const child = spawn(process.execPath, [serveBinPath, "dist"], {
			stdio: "inherit",
			cwd: primary.erdDir
		});
		child.on("error", (error) => {
			logger.error("Failed to run `serve dist`. Ensure `serve` is installed in your project.");
			reject(error);
		});
		child.on("exit", (code) => {
			if (code === 0) resolve();
			else {
				logger.error("serve CLI exited with a non-zero code. Ensure `serve dist` works in your project.");
				reject(/* @__PURE__ */ new Error(`serve CLI exited with code ${code ?? 1}`));
			}
		});
	});
}
const erdServeCommand = defineCommand({
	meta: {
		name: "serve",
		description: "Generate and serve ERD (liam build + `serve dist`) (beta)"
	},
	args: {
		...commonArgs,
		...deploymentArgs,
		namespace: {
			type: "string",
			description: "TailorDB namespace name (uses first namespace in config if not specified)",
			alias: "n"
		}
	},
	run: withCommonArgs(async (args) => {
		const { client, workspaceId, config } = await initErdContext(args);
		await runServeDist(await prepareErdBuilds({
			client,
			workspaceId,
			config,
			namespace: args.namespace
		}));
	})
});

//#endregion
//#region src/cli/tailordb/erd/index.ts
const erdCommand = defineCommand({
	meta: {
		name: "erd",
		description: "ERD utilities for TailorDB (beta)"
	},
	subCommands: {
		export: erdExportCommand,
		serve: erdServeCommand,
		deploy: erdDeployCommand
	}
});

//#endregion
//#region src/cli/tailordb/index.ts
const tailordbCommand = defineCommand({
	meta: {
		name: "tailordb",
		description: "Manage TailorDB tables and data"
	},
	subCommands: {
		erd: erdCommand,
		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) {
			logger.out(users);
			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";
	}
}
/**
* Transform a PersonalAccessToken into CLI-friendly info.
* @param pat - Personal access token resource
* @returns Flattened token info
*/
function transformPersonalAccessToken(pat) {
	return {
		name: pat.name,
		scopes: pat.scopes.map(patScopeToString)
	};
}
/**
* Get PAT scopes from a write flag.
* @param write - Whether write access is required
* @returns Scopes to apply to the token
*/
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"];
}
/**
* Print the created or updated personal access token to the logger.
* @param name - Token name
* @param token - Token value
* @param write - Whether the token has write scope
* @param action - Action performed
*/
function printCreatedToken(name, token, write, action) {
	const scopes = getScopeStringsFromWriteFlag(write);
	if (logger.jsonMode) logger.out({
		name,
		scopes,
		token
	});
	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");
	})
});

//#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) {
			const patInfos = pats.map(transformPersonalAccessToken);
			logger.out(patInfos);
			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");
	})
});

//#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