{"version":3,"file":"server-BnX7U6mz.mjs","names":["pkg.version"],"sources":["../src/logger.ts","../src/schemas.ts","../src/npm-process.ts","../src/npm-client.ts","../package.json","../src/server.ts"],"sourcesContent":["import { styleText } from 'node:util'\nimport * as p from '@clack/prompts'\nimport { createDebug } from 'obug'\n\nlet isInitialized = false\n\n/**\n * Initialize the logger with intro message\n */\nexport function initLogger(): void {\n  if (isInitialized) return\n  isInitialized = true\n  p.intro(styleText(['bgCyan', 'black'], ' npmx connector '))\n}\n\n/**\n * Log when starting to execute a command\n */\nexport function logCommand(command: string): void {\n  p.log.step(`${styleText('dim', '$ ')}${styleText('cyan', command)}`)\n}\n\n/**\n * Log successful command completion\n */\nexport function logSuccess(message: string): void {\n  p.log.success(styleText('green', message))\n}\n\n/**\n * Log command failure\n */\nexport function logError(message: string): void {\n  p.log.error(styleText('red', message))\n}\n\n/**\n * Log warning\n */\nexport function logWarning(message: string): void {\n  p.log.warn(styleText('yellow', message))\n}\n\n/**\n * Log info message\n */\nexport function logInfo(message: string): void {\n  p.log.info(message)\n}\n\n/**\n * Log a debug message with `obug` (minimal fork of `debug`)\n */\nexport const logDebug = createDebug('npmx-connector')\n\n/**\n * Show the connection token in a nice box\n */\nexport function showToken(token: string, port: number, frontendUrl: string): void {\n  const connectUrl = `${frontendUrl}?token=${token}&port=${port}`\n\n  p.note(\n    [\n      `Open: ${styleText(['bold', 'underline', 'cyan'], connectUrl)}`,\n      '',\n      styleText('dim', `Or paste token manually: ${token}`),\n    ].join('\\n'),\n    'Click to connect',\n  )\n}\n","import * as v from 'valibot'\nimport validateNpmPackageName from 'validate-npm-package-name'\n\n// Validation pattern for npm usernames/org names\n// These follow similar rules: lowercase alphanumeric with hyphens, can't start/end with hyphen\nconst NPM_USERNAME_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i\n\n// ============================================================================\n// Base Schemas\n// ============================================================================\n\n/**\n * Validates an npm package name using the official npm validation package\n * Accepts both new and legacy package name formats\n */\nexport const PackageNameSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Package name is required'),\n  v.check(input => {\n    const result = validateNpmPackageName(input)\n    return result.validForNewPackages || result.validForOldPackages\n  }, 'Invalid package name format'),\n)\n\n/**\n * Validates an npm package name for new packages only\n * Stricter than PackageNameSchema - rejects legacy formats (uppercase, etc.)\n * @internal\n */\nexport const NewPackageNameSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Package name is required'),\n  v.check(input => {\n    const result = validateNpmPackageName(input)\n    return result.validForNewPackages === true\n  }, 'Invalid package name format. New packages must be lowercase and follow npm naming conventions.'),\n)\n\n/**\n * Validates an npm username\n * Must be alphanumeric with hyphens, max 50 chars, can't start/end with hyphen\n */\nexport const UsernameSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Username is required'),\n  v.maxLength(50, 'Username is too long'),\n  v.regex(NPM_USERNAME_RE, 'Invalid username format'),\n)\n\n/**\n * Validates an npm org name (without the @ prefix)\n * Same rules as username\n */\nexport const OrgNameSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Org name is required'),\n  v.maxLength(50, 'Org name is too long'),\n  v.regex(NPM_USERNAME_RE, 'Invalid org name format'),\n)\n\n/**\n * Validates a scope:team format (e.g., @myorg:developers)\n */\nexport const ScopeTeamSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Scope:team is required'),\n  v.maxLength(100, 'Scope:team is too long'),\n  v.check(input => {\n    const match = input.match(/^@([^:]+):(.+)$/)\n    if (!match) return false\n    const [, scope, team] = match\n    if (!scope || !NPM_USERNAME_RE.test(scope)) return false\n    if (!team || !NPM_USERNAME_RE.test(team)) return false\n    return true\n  }, 'Invalid scope:team format. Expected @scope:team'),\n)\n\n/**\n * Validates org roles\n * @internal\n */\nexport const OrgRoleSchema = v.picklist(\n  ['developer', 'admin', 'owner'],\n  'Invalid role. Must be developer, admin, or owner',\n)\n\n/**\n * Validates access permissions\n * @internal\n */\nexport const PermissionSchema = v.picklist(\n  ['read-only', 'read-write'],\n  'Invalid permission. Must be read-only or read-write',\n)\n\n/**\n * Validates operation types\n */\nexport const OperationTypeSchema = v.picklist([\n  'org:add-user',\n  'org:rm-user',\n  'org:set-role',\n  'team:create',\n  'team:destroy',\n  'team:add-user',\n  'team:rm-user',\n  'access:grant',\n  'access:revoke',\n  'owner:add',\n  'owner:rm',\n  'package:init',\n])\n\n/**\n * Validates OTP (6-digit code)\n * @internal\n */\nexport const OtpSchema = v.optional(\n  v.pipe(v.string(), v.regex(/^\\d{6}$/, 'OTP must be a 6-digit code')),\n)\n\n/**\n * Validates a hex token (like session tokens and operation IDs)\n * @internal\n */\nexport const HexTokenSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Token is required'),\n  v.regex(/^[a-f0-9]+$/i, 'Invalid token format'),\n)\n\n/**\n * Validates operation ID (16-char hex)\n */\nexport const OperationIdSchema = v.pipe(\n  v.string(),\n  v.nonEmpty('Operation ID is required'),\n  v.regex(/^[a-f0-9]{16}$/i, 'Invalid operation ID format'),\n)\n\n// ============================================================================\n// Request Body Schemas\n// ============================================================================\n\n/**\n * Schema for /connect request body\n */\nexport const ConnectBodySchema = v.object({\n  token: HexTokenSchema,\n})\n\n/**\n * Schema for /execute request body.\n * - `otp`: optional 6-digit OTP code for 2FA\n * - `interactive`: when true, commands run via a real PTY (node-pty) instead of execFile, so npm's OTP handler can activate.\n * - `openUrls`: when true (default), npm opens auth URLs in the user's browser automatically. When false, URLs are suppressed on the connector side and only returned in the response / exposed in /state\n */\nexport const ExecuteBodySchema = v.object({\n  otp: OtpSchema,\n  interactive: v.optional(v.boolean()),\n  openUrls: v.optional(v.boolean()),\n})\n\n/**\n * Schema for operation params based on type\n * Validates the params object for each operation type\n */\nconst OperationParamsSchema = v.record(v.string(), v.string())\n\n/**\n * Schema for single operation request body\n */\nexport const CreateOperationBodySchema = v.object({\n  type: OperationTypeSchema,\n  params: OperationParamsSchema,\n  description: v.pipe(v.string(), v.nonEmpty('Description is required'), v.maxLength(500)),\n  command: v.pipe(v.string(), v.nonEmpty('Command is required'), v.maxLength(1000)),\n})\n\n/**\n * Schema for batch operation request body\n */\nexport const BatchOperationsBodySchema = v.array(CreateOperationBodySchema)\n\n// ============================================================================\n// Type-specific Operation Params Schemas\n// ============================================================================\n\n/** @internal */\nexport const OrgAddUserParamsSchema = v.object({\n  org: OrgNameSchema,\n  user: UsernameSchema,\n  role: OrgRoleSchema,\n})\n\nconst OrgRemoveUserParamsSchema = v.object({\n  org: OrgNameSchema,\n  user: UsernameSchema,\n})\n\nconst TeamCreateParamsSchema = v.object({\n  scopeTeam: ScopeTeamSchema,\n})\n\nconst TeamDestroyParamsSchema = v.object({\n  scopeTeam: ScopeTeamSchema,\n})\n\nconst TeamAddUserParamsSchema = v.object({\n  scopeTeam: ScopeTeamSchema,\n  user: UsernameSchema,\n})\n\nconst TeamRemoveUserParamsSchema = v.object({\n  scopeTeam: ScopeTeamSchema,\n  user: UsernameSchema,\n})\n\n/** @internal */\nexport const AccessGrantParamsSchema = v.object({\n  permission: PermissionSchema,\n  scopeTeam: ScopeTeamSchema,\n  pkg: PackageNameSchema,\n})\n\nconst AccessRevokeParamsSchema = v.object({\n  scopeTeam: ScopeTeamSchema,\n  pkg: PackageNameSchema,\n})\n\nconst OwnerAddParamsSchema = v.object({\n  user: UsernameSchema,\n  pkg: PackageNameSchema,\n})\n\nconst OwnerRemoveParamsSchema = v.object({\n  user: UsernameSchema,\n  pkg: PackageNameSchema,\n})\n\n/** @internal */\nexport const PackageInitParamsSchema = v.object({\n  name: NewPackageNameSchema,\n  author: v.optional(UsernameSchema),\n})\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Validates operation params based on operation type\n * @throws ValiError if validation fails\n */\nexport function validateOperationParams(\n  type: v.InferOutput<typeof OperationTypeSchema>,\n  params: Record<string, string>,\n): void {\n  switch (type) {\n    case 'org:add-user':\n      v.parse(OrgAddUserParamsSchema, params)\n      break\n    case 'org:rm-user':\n      v.parse(OrgRemoveUserParamsSchema, params)\n      break\n    case 'org:set-role':\n      v.parse(OrgAddUserParamsSchema, params) // same params as add-user\n      break\n    case 'team:create':\n      v.parse(TeamCreateParamsSchema, params)\n      break\n    case 'team:destroy':\n      v.parse(TeamDestroyParamsSchema, params)\n      break\n    case 'team:add-user':\n      v.parse(TeamAddUserParamsSchema, params)\n      break\n    case 'team:rm-user':\n      v.parse(TeamRemoveUserParamsSchema, params)\n      break\n    case 'access:grant':\n      v.parse(AccessGrantParamsSchema, params)\n      break\n    case 'access:revoke':\n      v.parse(AccessRevokeParamsSchema, params)\n      break\n    case 'owner:add':\n      v.parse(OwnerAddParamsSchema, params)\n      break\n    case 'owner:rm':\n      v.parse(OwnerRemoveParamsSchema, params)\n      break\n    case 'package:init':\n      v.parse(PackageInitParamsSchema, params)\n      break\n  }\n}\n\n/**\n * Safe parse wrapper that returns a formatted error message\n */\nexport function safeParse<T extends v.GenericSchema>(\n  schema: T,\n  input: unknown,\n): { success: true; data: v.InferOutput<T> } | { success: false; error: string } {\n  const result = v.safeParse(schema, input)\n  if (result.success) {\n    return { success: true, data: result.output }\n  }\n  // Format the first error message\n  const firstIssue = result.issues[0]\n  const path = firstIssue?.path?.map(p => p.key).join('.') || ''\n  const message = firstIssue?.message || 'Validation failed'\n  return {\n    success: false,\n    error: path ? `${path}: ${message}` : message,\n  }\n}\n","import process from 'node:process'\n\ninterface NpmProcessCommand {\n  command: string\n  args: string[]\n}\n\nexport function resolveNpmProcessCommand(\n  npmArgs: string[],\n  platform = process.platform,\n  comSpec = process.env.ComSpec,\n): NpmProcessCommand {\n  if (platform === 'win32') {\n    return {\n      command: comSpec || 'cmd.exe',\n      args: ['/d', '/s', '/c', 'npm', ...npmArgs],\n    }\n  }\n\n  return {\n    command: 'npm',\n    args: npmArgs,\n  }\n}\n","import crypto from 'node:crypto'\nimport process from 'node:process'\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { mkdtempDisposable, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport * as v from 'valibot'\nimport { PackageNameSchema, UsernameSchema, OrgNameSchema, ScopeTeamSchema } from './schemas.ts'\nimport { logCommand, logSuccess, logError, logDebug } from './logger.ts'\nimport { resolveNpmProcessCommand } from './npm-process.ts'\n\nconst execFileAsync = promisify(execFile)\nexport const NPM_REGISTRY_URL = 'https://registry.npmjs.org/'\n\nfunction createNpmEnv(overrides: Record<string, string> = {}): Record<string, string> {\n  return {\n    ...process.env,\n    ...overrides,\n    FORCE_COLOR: '0',\n    npm_config_registry: NPM_REGISTRY_URL,\n  }\n}\n\n/**\n * Validates an npm package name using the official npm validation package\n * @throws Error if the name is invalid\n * @internal\n */\nexport function validatePackageName(name: string): void {\n  const result = v.safeParse(PackageNameSchema, name)\n  if (!result.success) {\n    const message = result.issues[0]?.message || 'Invalid package name'\n    throw new Error(`Invalid package name \"${name}\": ${message}`)\n  }\n}\n\n/**\n * Validates an npm username\n * @throws Error if the username is invalid\n * @internal\n */\nexport function validateUsername(name: string): void {\n  const result = v.safeParse(UsernameSchema, name)\n  if (!result.success) {\n    throw new Error(`Invalid username: ${name}`)\n  }\n}\n\n/**\n * Validates an npm org name (without the @ prefix)\n * @throws Error if the org name is invalid\n * @internal\n */\nexport function validateOrgName(name: string): void {\n  const result = v.safeParse(OrgNameSchema, name)\n  if (!result.success) {\n    throw new Error(`Invalid org name: ${name}`)\n  }\n}\n\n/**\n * Validates a scope:team format (e.g., @myorg:developers)\n * @throws Error if the scope:team is invalid\n * @internal\n */\nexport function validateScopeTeam(scopeTeam: string): void {\n  const result = v.safeParse(ScopeTeamSchema, scopeTeam)\n  if (!result.success) {\n    throw new Error(`Invalid scope:team format: ${scopeTeam}. Expected @scope:team`)\n  }\n}\n\nexport interface NpmExecResult {\n  stdout: string\n  stderr: string\n  exitCode: number\n  /** True if the operation failed due to missing/invalid OTP */\n  requiresOtp?: boolean\n  /** True if the operation failed due to authentication failure (not logged in or token expired) */\n  authFailure?: boolean\n  /** URLs detected in the command output (stdout + stderr) */\n  urls?: string[]\n}\n\nfunction detectOtpRequired(stderr: string): boolean {\n  const otpPatterns = [\n    'EOTP',\n    'one-time password',\n    'This operation requires a one-time password',\n    'OTP required for authentication',\n    '--otp=<code>',\n  ]\n  const lowerStderr = stderr.toLowerCase()\n  logDebug('Checking for OTP requirement in stderr:', stderr)\n  logDebug('OTP patterns:', otpPatterns)\n  const result = otpPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))\n  logDebug('OTP required:', result)\n  return result\n}\n\nfunction detectAuthFailure(stderr: string): boolean {\n  const authPatterns = [\n    'ENEEDAUTH',\n    'You must be logged in',\n    'authentication error',\n    'Unable to authenticate',\n    'code E401',\n    'code E403',\n    '401 Unauthorized',\n    '403 Forbidden',\n    'not logged in',\n    'npm login',\n    'npm adduser',\n  ]\n  const lowerStderr = stderr.toLowerCase()\n  logDebug('Checking for auth failure in stderr:', stderr)\n  logDebug('Auth patterns:', authPatterns)\n  const result = authPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))\n  logDebug('Auth failure:', result)\n  return result\n}\n\nfunction filterNpmWarnings(stderr: string): string {\n  return stderr\n    .split('\\n')\n    .filter(line => !line.startsWith('npm warn'))\n    .join('\\n')\n    .trim()\n}\n\nconst URL_RE = /https?:\\/\\/[^\\s<>\"{}|\\\\^`[\\]]+/g\n\nexport function extractUrls(text: string): string[] {\n  const matches = text.match(URL_RE)\n  if (!matches) return []\n\n  const cleaned = matches.map(url => url.replace(/[.,;:!?)]+$/, ''))\n  return [...new Set(cleaned)]\n}\n\n// Patterns to detect npm's OTP prompt in pty output\nconst OTP_PROMPT_RE = /Enter OTP:/i\n// Patterns to detect npm's web auth URL prompt in pty output\nconst AUTH_URL_PROMPT_RE = /Press ENTER to open in the browser/i\n// npm prints \"Authenticate your account at:\\n<url>\" — capture the URL on the next line\nconst AUTH_URL_TITLE_RE = /Authenticate your account at:\\s*(https?:\\/\\/\\S+)/\n\nfunction stripAnsi(text: string): string {\n  // eslint disabled because we need escape characters in regex\n  // eslint-disable-next-line no-control-regex, regexp/no-obscure-range\n  return text.replace(/\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g, '')\n}\n\nconst AUTH_URL_TIMEOUT_MS = 90_000\n\nexport interface ExecNpmOptions {\n  otp?: string\n  silent?: boolean\n  /** Working directory for the npm command. */\n  cwd?: string\n  /** When true, use PTY-based interactive execution instead of execFile. */\n  interactive?: boolean\n  /** When true, npm opens auth URLs in the user's browser.\n   *  When false, browser opening is suppressed via npm_config_browser=false.\n   *  Only relevant when `interactive` is true. */\n  openUrls?: boolean\n  /** Called when an auth URL is detected in the pty output, while npm is still running (polling doneUrl). Lets the caller expose the URL to the frontend via /state before the execute response comes back.\n   *  Only relevant when `interactive` is true. */\n  onAuthUrl?: (url: string) => void\n}\n\n/**\n * PTY-based npm execution for interactive commands (uses node-pty).\n *\n * - Web OTP - either open URL in browser if openUrls is true or passes the URL to frontend. If no auth happened within AUTH_URL_TIMEOUT_MS kills the process to unlock the connector.\n *\n * - CLI OTP - if we get a classic OTP prompt will either return OTP request to the frontend or will pass sent OTP if its provided\n */\nasync function execNpmInteractive(\n  args: string[],\n  options: ExecNpmOptions = {},\n): Promise<NpmExecResult> {\n  const openUrls = options.openUrls === true\n  const { promise, resolve } = Promise.withResolvers<NpmExecResult>()\n\n  // Lazy-load node-pty so the native addon is only required when interactive mode is actually used.\n  const pty = await import('@lydell/node-pty')\n\n  const npmArgs = options.otp ? [...args, '--otp', options.otp] : args\n\n  if (!options.silent) {\n    const displayCmd = options.otp\n      ? ['npm', ...args, '--otp', '******'].join(' ')\n      : ['npm', ...args].join(' ')\n    logCommand(`${displayCmd} (interactive/pty)`)\n  }\n\n  let output = ''\n  let resolved = false\n  let otpPromptSeen = false\n  let authUrlSeen = false\n  let enterSent = false\n  let authUrlTimeout: ReturnType<typeof setTimeout> | null = null\n  let authUrlTimedOut = false\n\n  const env = createNpmEnv()\n\n  // When openUrls is false, tell npm not to open the browser.\n  // npm still prints the auth URL and polls doneUrl\n  if (!openUrls) {\n    env.npm_config_browser = 'false'\n  }\n\n  const child = pty.spawn('npm', npmArgs, {\n    name: 'xterm-256color',\n    cols: 120,\n    rows: 30,\n    cwd: options.cwd,\n    env,\n  })\n\n  // General timeout: 5 minutes (covers non-auth interactive commands)\n  const timeout = setTimeout(() => {\n    if (resolved) return\n    logDebug('Interactive command timed out', { output })\n    child.kill()\n  }, 300000)\n\n  child.onData((data: string) => {\n    output += data\n    const clean = stripAnsi(data)\n    logDebug('pty data:', { text: clean.trim() })\n\n    const cleanAll = stripAnsi(output)\n\n    // Detect auth URL in output and notify the caller.\n    if (!authUrlSeen) {\n      const urlMatch = cleanAll.match(AUTH_URL_TITLE_RE)\n\n      if (urlMatch && urlMatch[1]) {\n        authUrlSeen = true\n        const authUrl = urlMatch[1].replace(/[.,;:!?)]+$/, '')\n        logDebug('Auth URL detected:', { authUrl, openUrls })\n        options.onAuthUrl?.(authUrl)\n\n        authUrlTimeout = setTimeout(() => {\n          if (resolved) return\n          authUrlTimedOut = true\n          logDebug('Auth URL timeout (90s) — killing process')\n          logError('Authentication timed out after 90 seconds')\n          child.kill()\n        }, AUTH_URL_TIMEOUT_MS)\n      }\n    }\n\n    if (authUrlSeen && openUrls && !enterSent && AUTH_URL_PROMPT_RE.test(cleanAll)) {\n      enterSent = true\n      logDebug('Web auth prompt detected, pressing ENTER')\n      child.write('\\r')\n    }\n\n    if (!otpPromptSeen && OTP_PROMPT_RE.test(cleanAll)) {\n      otpPromptSeen = true\n      if (options.otp) {\n        logDebug('OTP prompt detected, writing OTP')\n        child.write(options.otp + '\\r')\n      } else {\n        logDebug('OTP prompt detected but no OTP provided, killing process')\n        child.kill()\n      }\n    }\n  })\n\n  child.onExit(({ exitCode }) => {\n    if (resolved) return\n    resolved = true\n    clearTimeout(timeout)\n    if (authUrlTimeout) clearTimeout(authUrlTimeout)\n\n    const cleanOutput = stripAnsi(output)\n    logDebug('Interactive command exited:', { exitCode, output: cleanOutput })\n\n    const requiresOtp =\n      authUrlTimedOut || (otpPromptSeen && !options.otp) || detectOtpRequired(cleanOutput)\n    const authFailure = detectAuthFailure(cleanOutput)\n    const urls = extractUrls(cleanOutput)\n\n    if (!options.silent) {\n      if (exitCode === 0) {\n        logSuccess('Done')\n      } else if (requiresOtp) {\n        logError('OTP required')\n      } else if (authFailure) {\n        logError('Authentication required - please run \"npm login\" and restart the connector')\n      } else {\n        const firstLine = filterNpmWarnings(cleanOutput).split('\\n')[0] || 'Command failed'\n        logError(firstLine)\n      }\n    }\n\n    // If auth URL timed out, force a non-zero exit code so it's marked as failed\n    const finalExitCode = authUrlTimedOut ? 1 : exitCode\n\n    resolve({\n      stdout: cleanOutput.trim(),\n      stderr: requiresOtp\n        ? 'This operation requires a one-time password (OTP).'\n        : authFailure\n          ? 'Authentication failed. Please run \"npm login\" and restart the connector.'\n          : filterNpmWarnings(cleanOutput),\n      exitCode: finalExitCode,\n      requiresOtp,\n      authFailure,\n      urls: urls.length > 0 ? urls : undefined,\n    })\n  })\n\n  return promise\n}\n\nasync function execNpm(args: string[], options: ExecNpmOptions = {}): Promise<NpmExecResult> {\n  if (options.interactive) {\n    return execNpmInteractive(args, options)\n  }\n\n  // Build the full args array including OTP if provided\n  const npmArgs = options.otp ? [...args, '--otp', options.otp] : args\n\n  // Log the command being run (hide OTP value for security)\n  if (!options.silent) {\n    const displayCmd = options.otp\n      ? ['npm', ...args, '--otp', '******'].join(' ')\n      : ['npm', ...args].join(' ')\n    logCommand(displayCmd)\n  }\n\n  try {\n    logDebug('Executing npm command:', { command: 'npm', args: npmArgs })\n    const { command, args: processArgs } = resolveNpmProcessCommand(npmArgs)\n    const { stdout, stderr } = await execFileAsync(command, processArgs, {\n      timeout: 60000,\n      cwd: options.cwd,\n      env: createNpmEnv(),\n    })\n\n    logDebug('Command succeeded:', { stdout, stderr })\n\n    if (!options.silent) {\n      logSuccess('Done')\n    }\n\n    return {\n      stdout: stdout.trim(),\n      stderr: filterNpmWarnings(stderr),\n      exitCode: 0,\n    }\n  } catch (error) {\n    const err = error as { stdout?: string; stderr?: string; code?: number }\n    const stderr = err.stderr?.trim() ?? String(error)\n    logDebug('Command failed:', { error, stdout: err.stdout, stderr: err.stderr, code: err.code })\n    const requiresOtp = detectOtpRequired(stderr)\n    const authFailure = detectAuthFailure(stderr)\n\n    if (!options.silent) {\n      if (requiresOtp) {\n        logError('OTP required')\n      } else if (authFailure) {\n        logError('Authentication required - please run \"npm login\" and restart the connector')\n      } else {\n        logError(filterNpmWarnings(stderr).split('\\n')[0] || 'Command failed')\n      }\n    }\n\n    return {\n      stdout: err.stdout?.trim() ?? '',\n      stderr: requiresOtp\n        ? 'This operation requires a one-time password (OTP).'\n        : authFailure\n          ? 'Authentication failed. Please run \"npm login\" and restart the connector.'\n          : filterNpmWarnings(stderr),\n      exitCode: err.code ?? 1,\n      requiresOtp,\n      authFailure,\n    }\n  }\n}\n\nexport async function getNpmUser(): Promise<string | null> {\n  const result = await execNpm(['whoami'], { silent: true })\n  if (result.exitCode === 0 && result.stdout) {\n    return result.stdout\n  }\n  return null\n}\n\n/**\n * Gets the user's avatar as a base64 data URL from Gravatar.\n * Returns null if the user's email cannot be retrieved or avatar fetch fails.\n */\nexport async function getNpmAvatar(): Promise<string | null> {\n  const result = await execNpm(['profile', 'get', 'email', '--json'], { silent: true })\n  if (result.exitCode !== 0 || !result.stdout) {\n    return null\n  }\n\n  try {\n    const parsed = JSON.parse(result.stdout) as { email?: string }\n    if (!parsed.email) {\n      return null\n    }\n\n    const email = parsed.email.trim().toLowerCase()\n    const hash = crypto.createHash('md5').update(email).digest('hex')\n    const gravatarUrl = `https://www.gravatar.com/avatar/${hash}?s=64&d=retro`\n\n    const response = await fetch(gravatarUrl)\n    if (!response.ok) {\n      return null\n    }\n\n    const contentType = response.headers.get('content-type') || 'image/png'\n    const buffer = await response.arrayBuffer()\n    const base64 = Buffer.from(buffer).toString('base64')\n    return `data:${contentType};base64,${base64}`\n  } catch {\n    return null\n  }\n}\n\nexport async function orgAddUser(\n  org: string,\n  user: string,\n  role: 'developer' | 'admin' | 'owner',\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateOrgName(org)\n  validateUsername(user)\n  return execNpm(['org', 'set', org, user, role], options)\n}\n\nexport async function orgRemoveUser(\n  org: string,\n  user: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateOrgName(org)\n  validateUsername(user)\n  return execNpm(['org', 'rm', org, user], options)\n}\n\nexport async function teamCreate(\n  scopeTeam: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  return execNpm(['team', 'create', scopeTeam], options)\n}\n\nexport async function teamDestroy(\n  scopeTeam: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  return execNpm(['team', 'destroy', scopeTeam], options)\n}\n\nexport async function teamAddUser(\n  scopeTeam: string,\n  user: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  validateUsername(user)\n  return execNpm(['team', 'add', scopeTeam, user], options)\n}\n\nexport async function teamRemoveUser(\n  scopeTeam: string,\n  user: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  validateUsername(user)\n  return execNpm(['team', 'rm', scopeTeam, user], options)\n}\n\nexport async function accessGrant(\n  permission: 'read-only' | 'read-write',\n  scopeTeam: string,\n  pkg: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  validatePackageName(pkg)\n  return execNpm(['access', 'grant', permission, scopeTeam, pkg], options)\n}\n\nexport async function accessRevoke(\n  scopeTeam: string,\n  pkg: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  validatePackageName(pkg)\n  return execNpm(['access', 'revoke', scopeTeam, pkg], options)\n}\n\nexport async function ownerAdd(\n  user: string,\n  pkg: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateUsername(user)\n  validatePackageName(pkg)\n  return execNpm(['owner', 'add', user, pkg], options)\n}\n\nexport async function ownerRemove(\n  user: string,\n  pkg: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validateUsername(user)\n  validatePackageName(pkg)\n  return execNpm(['owner', 'rm', user, pkg], options)\n}\n\n// List functions (for reading data) - silent since they're not user-triggered operations\n\nexport async function orgListUsers(org: string): Promise<NpmExecResult> {\n  validateOrgName(org)\n  return execNpm(['org', 'ls', org, '--json'], { silent: true })\n}\n\nexport async function teamListTeams(org: string): Promise<NpmExecResult> {\n  validateOrgName(org)\n  return execNpm(['team', 'ls', org, '--json'], { silent: true })\n}\n\nexport async function teamListUsers(scopeTeam: string): Promise<NpmExecResult> {\n  validateScopeTeam(scopeTeam)\n  return execNpm(['team', 'ls', scopeTeam, '--json'], { silent: true })\n}\n\nexport async function accessListCollaborators(pkg: string): Promise<NpmExecResult> {\n  validatePackageName(pkg)\n  return execNpm(['access', 'list', 'collaborators', pkg, '--json'], { silent: true })\n}\n\n/**\n * Lists all packages that a user has access to publish.\n * Uses `npm access list packages @{user} --json`\n * Returns a map of package name to permission level\n */\nexport async function listUserPackages(user: string): Promise<NpmExecResult> {\n  validateUsername(user)\n  return execNpm(['access', 'list', 'packages', `@${user}`, '--json'], { silent: true })\n}\n\n/**\n * Initialize and publish a new package to claim the name.\n * Creates a minimal package.json in a temp directory and publishes it.\n * @param name Package name to claim\n * @param author npm username of the publisher (for author field)\n * @param options Execution options (otp, interactive, etc.)\n */\nexport async function packageInit(\n  name: string,\n  author?: string,\n  options?: ExecNpmOptions,\n): Promise<NpmExecResult> {\n  validatePackageName(name)\n\n  // Let Node clean up the temp directory automatically when this scope exits.\n  await using tempDir = await mkdtempDisposable(join(tmpdir(), 'npmx-init-'))\n\n  // Determine access type based on whether it's a scoped package\n  const isScoped = name.startsWith('@')\n  const access = isScoped ? 'public' : undefined\n\n  // Create minimal package.json\n  const packageJson = {\n    name,\n    version: '0.0.0',\n    description: `Placeholder for ${name}`,\n    main: 'index.js',\n    scripts: {},\n    keywords: [],\n    author: author ? `${author} (https://www.npmjs.com/~${author})` : '',\n    license: 'UNLICENSED',\n    private: false,\n    ...(access && { publishConfig: { access } }),\n  }\n\n  await writeFile(join(tempDir.path, 'package.json'), JSON.stringify(packageJson, null, 2))\n\n  // Create empty index.js\n  await writeFile(join(tempDir.path, 'index.js'), '// Placeholder\\n')\n\n  // Build npm publish args\n  const args = ['publish']\n  if (access) {\n    args.push('--access', access)\n  }\n\n  const displayCmd = options?.otp\n    ? ['npm', ...args, '--otp', '******'].join(' ')\n    : ['npm', ...args].join(' ')\n  logCommand(`${displayCmd} (in temp dir for ${name})`)\n\n  const result = await execNpm(args, { ...options, cwd: tempDir.path, silent: true })\n\n  if (result.exitCode === 0) {\n    logSuccess(`Published ${name}@0.0.0`)\n  } else if (result.requiresOtp) {\n    logError('OTP required')\n  } else if (result.authFailure) {\n    logError('Authentication required - please run \"npm login\" and restart the connector')\n  } else {\n    logError(result.stderr.split('\\n')[0] || 'Command failed')\n  }\n\n  return result\n}\n","","import crypto from 'node:crypto'\nimport { H3, HTTPError, handleCors, type H3Event } from 'h3-next'\nimport type { CorsOptions } from 'h3-next'\nimport * as v from 'valibot'\n\nimport type {\n  ConnectorState,\n  PendingOperation,\n  ApiResponse,\n  ConnectorEndpoints,\n  AssertEndpointsImplemented,\n} from './types.ts'\n\n// Endpoint completeness check — errors if this list diverges from ConnectorEndpoints.\nconst _endpointCheck: AssertEndpointsImplemented<\n  | 'POST /connect'\n  | 'GET /state'\n  | 'POST /operations'\n  | 'POST /operations/batch'\n  | 'DELETE /operations'\n  | 'DELETE /operations/all'\n  | 'POST /approve'\n  | 'POST /approve-all'\n  | 'POST /retry'\n  | 'POST /execute'\n  | 'GET /org/:org/users'\n  | 'GET /org/:org/teams'\n  | 'GET /team/:scopeTeam/users'\n  | 'GET /package/:pkg/collaborators'\n  | 'GET /user/packages'\n  | 'GET /user/orgs'\n> = true\nvoid _endpointCheck\nimport { logDebug, logError } from './logger.ts'\nimport {\n  getNpmUser,\n  getNpmAvatar,\n  orgAddUser,\n  orgRemoveUser,\n  orgListUsers,\n  teamCreate,\n  teamDestroy,\n  teamAddUser,\n  teamRemoveUser,\n  teamListTeams,\n  teamListUsers,\n  accessGrant,\n  accessRevoke,\n  accessListCollaborators,\n  ownerAdd,\n  ownerRemove,\n  packageInit,\n  listUserPackages,\n  extractUrls,\n  type ExecNpmOptions,\n  type NpmExecResult,\n} from './npm-client.ts'\nimport {\n  ConnectBodySchema,\n  ExecuteBodySchema,\n  CreateOperationBodySchema,\n  BatchOperationsBodySchema,\n  OrgNameSchema,\n  ScopeTeamSchema,\n  PackageNameSchema,\n  OperationIdSchema,\n  safeParse,\n  validateOperationParams,\n} from './schemas.ts'\n\n// Read version from package.json\nimport pkg from '../package.json' with { type: 'json' }\n\nexport const CONNECTOR_VERSION = pkg.version\n\nfunction generateToken(): string {\n  return crypto.randomBytes(16).toString('hex')\n}\n\nfunction generateOperationId(): string {\n  return crypto.randomBytes(8).toString('hex')\n}\n\nconst corsOptions: CorsOptions = {\n  origin: ['https://npmx.dev', /^http:\\/\\/localhost:\\d+$/, /^http:\\/\\/127.0.0.1:\\d+$/],\n  methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],\n  allowHeaders: ['Content-Type', 'Authorization'],\n}\n\nexport function createConnectorApp(expectedToken: string): H3 {\n  const state: ConnectorState = {\n    session: {\n      token: expectedToken,\n      connectedAt: 0,\n      npmUser: null,\n      avatar: null,\n    },\n    operations: [],\n  }\n\n  const app = new H3()\n\n  // Handle CORS for all requests (including preflight)\n  app.use((event: H3Event) => {\n    const corsResult = handleCors(event, corsOptions)\n    if (corsResult !== false) {\n      return corsResult\n    }\n  })\n\n  function validateToken(authHeader: string | null): boolean {\n    if (!authHeader) return false\n    const token = authHeader.replace('Bearer ', '')\n    return token === expectedToken\n  }\n\n  app.post('/connect', async (event: H3Event) => {\n    const rawBody = await event.req.json()\n    const parsed = safeParse(ConnectBodySchema, rawBody)\n    if (!parsed.success) {\n      throw new HTTPError({ statusCode: 400, message: parsed.error })\n    }\n\n    if (parsed.data.token !== expectedToken) {\n      throw new HTTPError({ statusCode: 401, message: 'Invalid token' })\n    }\n\n    const [npmUser, avatar] = await Promise.all([getNpmUser(), getNpmAvatar()])\n    state.session.connectedAt = Date.now()\n    state.session.npmUser = npmUser\n    state.session.avatar = avatar\n\n    return {\n      success: true,\n      data: {\n        npmUser,\n        avatar,\n        connectedAt: state.session.connectedAt,\n      },\n    } satisfies ApiResponse<ConnectorEndpoints['POST /connect']['data']>\n  })\n\n  app.get('/state', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    return {\n      success: true,\n      data: {\n        npmUser: state.session.npmUser,\n        avatar: state.session.avatar,\n        operations: state.operations,\n      },\n    } satisfies ApiResponse<ConnectorEndpoints['GET /state']['data']>\n  })\n\n  app.post('/operations', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const rawBody = await event.req.json()\n    const parsed = safeParse(CreateOperationBodySchema, rawBody)\n    if (!parsed.success) {\n      throw new HTTPError({ statusCode: 400, message: parsed.error })\n    }\n\n    const { type, params, description, command } = parsed.data\n\n    // Validate params based on operation type\n    try {\n      validateOperationParams(type, params)\n    } catch (err) {\n      const message = err instanceof v.ValiError ? err.issues[0]?.message : String(err)\n      throw new HTTPError({ statusCode: 400, message: `Invalid params: ${message}` })\n    }\n\n    const operation: PendingOperation = {\n      id: generateOperationId(),\n      type,\n      params,\n      description,\n      command,\n      status: 'pending',\n      createdAt: Date.now(),\n    }\n\n    state.operations.push(operation)\n\n    return {\n      success: true,\n      data: operation,\n    } satisfies ApiResponse<ConnectorEndpoints['POST /operations']['data']>\n  })\n\n  app.post('/operations/batch', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const rawBody = await event.req.json()\n    const parsed = safeParse(BatchOperationsBodySchema, rawBody)\n    if (!parsed.success) {\n      throw new HTTPError({ statusCode: 400, message: parsed.error })\n    }\n\n    // Validate each operation's params\n    for (let i = 0; i < parsed.data.length; i++) {\n      const op = parsed.data[i]\n      if (!op) continue\n      try {\n        validateOperationParams(op.type, op.params)\n      } catch (err) {\n        const message = err instanceof v.ValiError ? err.issues[0]?.message : String(err)\n        throw new HTTPError({\n          statusCode: 400,\n          message: `Operation ${i}: Invalid params: ${message}`,\n        })\n      }\n    }\n\n    const created: PendingOperation[] = []\n    for (const op of parsed.data) {\n      const operation: PendingOperation = {\n        id: generateOperationId(),\n        type: op.type,\n        params: op.params,\n        description: op.description,\n        command: op.command,\n        status: 'pending',\n        createdAt: Date.now(),\n      }\n      state.operations.push(operation)\n      created.push(operation)\n    }\n\n    return {\n      success: true,\n      data: created,\n    } satisfies ApiResponse<ConnectorEndpoints['POST /operations/batch']['data']>\n  })\n\n  app.post('/approve', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const url = new URL(event.req.url)\n    const id = url.searchParams.get('id')\n\n    const idValidation = safeParse(OperationIdSchema, id)\n    if (!idValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: idValidation.error })\n    }\n\n    const operation = state.operations.find(op => op.id === idValidation.data)\n    if (!operation) {\n      throw new HTTPError({ statusCode: 404, message: 'Operation not found' })\n    }\n\n    if (operation.status !== 'pending') {\n      throw new HTTPError({\n        statusCode: 400,\n        message: 'Operation is not pending',\n      })\n    }\n\n    operation.status = 'approved'\n\n    return {\n      success: true,\n      data: operation,\n    } satisfies ApiResponse<ConnectorEndpoints['POST /approve']['data']>\n  })\n\n  app.post('/approve-all', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const pendingOps = state.operations.filter(op => op.status === 'pending')\n    for (const op of pendingOps) {\n      op.status = 'approved'\n    }\n\n    return {\n      success: true,\n      data: { approved: pendingOps.length },\n    } satisfies ApiResponse<ConnectorEndpoints['POST /approve-all']['data']>\n  })\n\n  app.post('/retry', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const url = new URL(event.req.url)\n    const id = url.searchParams.get('id')\n\n    const idValidation = safeParse(OperationIdSchema, id)\n    if (!idValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: idValidation.error })\n    }\n\n    const operation = state.operations.find(op => op.id === idValidation.data)\n    if (!operation) {\n      throw new HTTPError({ statusCode: 404, message: 'Operation not found' })\n    }\n\n    if (operation.status !== 'failed') {\n      throw new HTTPError({\n        statusCode: 400,\n        message: 'Only failed operations can be retried',\n      })\n    }\n\n    // Reset the operation for retry\n    operation.status = 'approved'\n    operation.result = undefined\n\n    return {\n      success: true,\n      data: operation,\n    } satisfies ApiResponse<ConnectorEndpoints['POST /retry']['data']>\n  })\n\n  app.post('/execute', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    // OTP, interactive flag, and openUrls can be passed in the request body\n    let otp: string | undefined\n    let interactive = false\n    let openUrls = false\n    try {\n      const rawBody = await event.req.json()\n      if (rawBody) {\n        const parsed = safeParse(ExecuteBodySchema, rawBody)\n        if (!parsed.success) {\n          throw new HTTPError({ statusCode: 400, message: parsed.error })\n        }\n        otp = parsed.data.otp\n        interactive = parsed.data.interactive ?? false\n        openUrls = parsed.data.openUrls ?? false\n      }\n    } catch (err) {\n      // Re-throw HTTPError, ignore JSON parse errors (empty body is fine)\n      if (err instanceof HTTPError) throw err\n    }\n\n    const approvedOps = state.operations.filter(op => op.status === 'approved')\n    const results: Array<{ id: string; result: NpmExecResult }> = []\n    let otpRequired = false\n    const completedIds = new Set<string>()\n    const failedIds = new Set<string>()\n\n    // Collect all URLs across all operations in this execution batch\n    const allUrls: string[] = []\n\n    // Execute operations in waves, respecting dependencies\n    // Each wave contains operations whose dependencies are satisfied\n    while (true) {\n      // Find operations ready to run (no pending dependencies)\n      const readyOps = approvedOps.filter(op => {\n        // Already processed\n        if (completedIds.has(op.id) || failedIds.has(op.id)) return false\n        // No dependency - ready\n        if (!op.dependsOn) return true\n        // Dependency completed successfully - ready\n        if (completedIds.has(op.dependsOn)) return true\n        // Dependency failed - skip this one too\n        if (failedIds.has(op.dependsOn)) {\n          op.status = 'failed'\n          op.result = {\n            stdout: '',\n            stderr: 'Skipped: dependency failed',\n            exitCode: 1,\n          }\n          failedIds.add(op.id)\n          results.push({ id: op.id, result: op.result })\n          return false\n        }\n        // Dependency still pending - not ready\n        return false\n      })\n\n      // No more operations to run\n      if (readyOps.length === 0) break\n\n      // If we've hit an OTP error and no OTP was provided, stop\n      if (otpRequired && !otp) break\n\n      // Execute ready operations in parallel\n      const runningOps = readyOps.map(async op => {\n        op.status = 'running'\n        const result = await executeOperation(op, { otp, interactive, openUrls })\n        op.result = result\n        op.authUrl = undefined\n        op.status = result.exitCode === 0 ? 'completed' : 'failed'\n\n        if (result.exitCode === 0) {\n          completedIds.add(op.id)\n        } else {\n          failedIds.add(op.id)\n        }\n\n        // Track if OTP is needed\n        if (result.requiresOtp) {\n          otpRequired = true\n        }\n\n        // Collect URLs from this operation's output\n        if (result.urls && result.urls.length > 0) {\n          allUrls.push(...result.urls)\n        }\n\n        results.push({ id: op.id, result })\n      })\n\n      await Promise.all(runningOps)\n    }\n\n    // Check if any operation had an auth failure\n    const authFailure = results.some(r => r.result.authFailure)\n\n    const urls = [...new Set(allUrls)]\n\n    return {\n      success: true,\n      data: {\n        results,\n        otpRequired,\n        authFailure,\n        urls: urls.length > 0 ? urls : undefined,\n      },\n    } satisfies ApiResponse<ConnectorEndpoints['POST /execute']['data']>\n  })\n\n  app.delete('/operations', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const url = new URL(event.req.url)\n    const id = url.searchParams.get('id')\n\n    const idValidation = safeParse(OperationIdSchema, id)\n    if (!idValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: idValidation.error })\n    }\n\n    const index = state.operations.findIndex(op => op.id === idValidation.data)\n    if (index === -1) {\n      throw new HTTPError({ statusCode: 404, message: 'Operation not found' })\n    }\n\n    const operation = state.operations[index]\n    if (!operation || operation.status === 'running') {\n      throw new HTTPError({\n        statusCode: 400,\n        message: 'Cannot cancel running operation',\n      })\n    }\n\n    state.operations.splice(index, 1)\n\n    return { success: true } satisfies ApiResponse<ConnectorEndpoints['DELETE /operations']['data']>\n  })\n\n  app.delete('/operations/all', event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const removed = state.operations.filter(op => op.status !== 'running').length\n    state.operations = state.operations.filter(op => op.status === 'running')\n\n    return {\n      success: true,\n      data: { removed },\n    } satisfies ApiResponse<ConnectorEndpoints['DELETE /operations/all']['data']>\n  })\n\n  // List endpoints (read-only data fetching)\n\n  app.get('/org/:org/users', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const orgRaw = event.context.params?.org\n    const orgValidation = safeParse(OrgNameSchema, orgRaw)\n    if (!orgValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: orgValidation.error })\n    }\n\n    const result = await orgListUsers(orgValidation.data)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list org users',\n      } as ApiResponse\n    }\n\n    try {\n      const users = JSON.parse(result.stdout) as Record<string, 'developer' | 'admin' | 'owner'>\n      return {\n        success: true,\n        data: users,\n      } satisfies ApiResponse<ConnectorEndpoints['GET /org/:org/users']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse org users',\n      } as ApiResponse\n    }\n  })\n\n  app.get('/org/:org/teams', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const orgRaw = event.context.params?.org\n    const orgValidation = safeParse(OrgNameSchema, orgRaw)\n    if (!orgValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: orgValidation.error })\n    }\n\n    const result = await teamListTeams(orgValidation.data)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list teams',\n      } as ApiResponse\n    }\n\n    try {\n      const teams = JSON.parse(result.stdout) as string[]\n      return {\n        success: true,\n        data: teams,\n      } satisfies ApiResponse<ConnectorEndpoints['GET /org/:org/teams']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse teams',\n      } as ApiResponse\n    }\n  })\n\n  app.get('/team/:scopeTeam/users', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const scopeTeamRaw = event.context.params?.scopeTeam\n    if (!scopeTeamRaw) {\n      throw new HTTPError({ statusCode: 400, message: 'Team name required' })\n    }\n\n    // Decode the team name (handles encoded colons like nuxt%3Adevelopers)\n    const scopeTeam = decodeURIComponent(scopeTeamRaw)\n\n    const validationResult = safeParse(ScopeTeamSchema, scopeTeam)\n    if (!validationResult.success) {\n      logError('scope:team validation failed')\n      logDebug(validationResult.error, { scopeTeamRaw, scopeTeam })\n      throw new HTTPError({\n        statusCode: 400,\n        message: `Invalid scope:team format: ${scopeTeam}. Expected @scope:team`,\n      })\n    }\n\n    const result = await teamListUsers(scopeTeam)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list team users',\n      } as ApiResponse\n    }\n\n    try {\n      const users = JSON.parse(result.stdout) as string[]\n      return {\n        success: true,\n        data: users,\n      } satisfies ApiResponse<ConnectorEndpoints['GET /team/:scopeTeam/users']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse team users',\n      } as ApiResponse\n    }\n  })\n\n  app.get('/package/:pkg/collaborators', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const pkgRaw = event.context.params?.pkg\n    if (!pkgRaw) {\n      throw new HTTPError({ statusCode: 400, message: 'Package name required' })\n    }\n\n    // Decode the package name (handles scoped packages like @nuxt%2Fkit)\n    const decodedPkg = decodeURIComponent(pkgRaw)\n\n    const pkgValidation = safeParse(PackageNameSchema, decodedPkg)\n    if (!pkgValidation.success) {\n      throw new HTTPError({ statusCode: 400, message: pkgValidation.error })\n    }\n\n    const result = await accessListCollaborators(pkgValidation.data)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list collaborators',\n      } as ApiResponse\n    }\n\n    try {\n      const collaborators = JSON.parse(result.stdout) as Record<string, 'read-only' | 'read-write'>\n      return {\n        success: true,\n        data: collaborators,\n      } satisfies ApiResponse<ConnectorEndpoints['GET /package/:pkg/collaborators']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse collaborators',\n      } as ApiResponse\n    }\n  })\n\n  // User-specific endpoints\n\n  app.get('/user/packages', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const npmUser = state.session.npmUser\n    if (!npmUser) {\n      return {\n        success: false,\n        error: 'Not logged in to npm',\n      } as ApiResponse\n    }\n\n    const result = await listUserPackages(npmUser)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list user packages',\n      } as ApiResponse\n    }\n\n    try {\n      // npm access list packages returns { \"packageName\": \"read-write\" | \"read-only\" }\n      const packages = JSON.parse(result.stdout) as Record<string, 'read-write' | 'read-only'>\n      return {\n        success: true,\n        data: packages,\n      } satisfies ApiResponse<ConnectorEndpoints['GET /user/packages']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse user packages',\n      } as ApiResponse\n    }\n  })\n\n  app.get('/user/orgs', async event => {\n    const auth = event.req.headers.get('authorization')\n    if (!validateToken(auth)) {\n      throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })\n    }\n\n    const npmUser = state.session.npmUser\n    if (!npmUser) {\n      return {\n        success: false,\n        error: 'Not logged in to npm',\n      } as ApiResponse\n    }\n\n    // Get user's packages and extract org names from scoped packages\n    const result = await listUserPackages(npmUser)\n    if (result.exitCode !== 0) {\n      return {\n        success: false,\n        error: result.stderr || 'Failed to list user packages',\n      } as ApiResponse\n    }\n\n    try {\n      const packages = JSON.parse(result.stdout) as Record<string, string>\n      const orgs = new Set<string>()\n\n      // Extract org names from scoped packages (e.g., @myorg/mypackage -> myorg)\n      for (const pkgName of Object.keys(packages)) {\n        if (pkgName.startsWith('@')) {\n          const match = pkgName.match(/^@([^/]+)\\//)\n          if (match && match[1]) {\n            // Exclude the user's own scope (personal packages)\n            if (match[1].toLowerCase() !== npmUser.toLowerCase()) {\n              orgs.add(match[1])\n            }\n          }\n        }\n      }\n\n      return {\n        success: true,\n        data: Array.from(orgs).sort(),\n      } satisfies ApiResponse<ConnectorEndpoints['GET /user/orgs']['data']>\n    } catch {\n      return {\n        success: false,\n        error: 'Failed to parse user orgs',\n      } as ApiResponse\n    }\n  })\n\n  return app\n}\n\nasync function executeOperation(\n  op: PendingOperation,\n  options: { otp?: string; interactive?: boolean; openUrls?: boolean } = {},\n): Promise<NpmExecResult> {\n  const { type, params } = op\n\n  // Build exec options that get passed through to execNpm, which\n  // internally routes to either execFile or PTY-based execution.\n  const execOptions: ExecNpmOptions = {\n    otp: options.otp,\n    interactive: options.interactive,\n    openUrls: options.openUrls,\n    onAuthUrl: options.interactive\n      ? url => {\n          // Set authUrl on the operation so /state exposes it to the\n          // frontend while npm is still polling for authentication.\n          op.authUrl = url\n        }\n      : undefined,\n  }\n\n  let result: NpmExecResult\n\n  switch (type) {\n    case 'org:add-user':\n    case 'org:set-role':\n      result = await orgAddUser(\n        params.org,\n        params.user,\n        params.role as 'developer' | 'admin' | 'owner',\n        execOptions,\n      )\n      break\n    case 'org:rm-user':\n      result = await orgRemoveUser(params.org, params.user, execOptions)\n      break\n    case 'team:create':\n      result = await teamCreate(params.scopeTeam, execOptions)\n      break\n    case 'team:destroy':\n      result = await teamDestroy(params.scopeTeam, execOptions)\n      break\n    case 'team:add-user':\n      result = await teamAddUser(params.scopeTeam, params.user, execOptions)\n      break\n    case 'team:rm-user':\n      result = await teamRemoveUser(params.scopeTeam, params.user, execOptions)\n      break\n    case 'access:grant':\n      result = await accessGrant(\n        params.permission as 'read-only' | 'read-write',\n        params.scopeTeam,\n        params.pkg,\n        execOptions,\n      )\n      break\n    case 'access:revoke':\n      result = await accessRevoke(params.scopeTeam, params.pkg, execOptions)\n      break\n    case 'owner:add':\n      result = await ownerAdd(params.user, params.pkg, execOptions)\n      break\n    case 'owner:rm':\n      result = await ownerRemove(params.user, params.pkg, execOptions)\n      break\n    case 'package:init':\n      result = await packageInit(params.name, params.author, execOptions)\n      break\n    default:\n      return {\n        stdout: '',\n        stderr: `Unknown operation type: ${type}`,\n        exitCode: 1,\n      }\n  }\n\n  // Extract URLs from output if not already populated\n  if (!result.urls) {\n    const urls = extractUrls((result.stdout || '') + '\\n' + (result.stderr || ''))\n    if (urls.length > 0) result.urls = urls\n  }\n\n  return result\n}\n\nexport { generateToken }\n"],"mappings":";;;;;;;;;;;;;AAIA,IAAI,gBAAgB;;;;AAKpB,SAAgB,aAAmB;AACjC,KAAI,cAAe;AACnB,iBAAgB;AAChB,G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