Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

1.9 KB
Raw Blame
import { stderrDetailSuffix } from './clone-error-classify.ts';
import {
  LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,
  type LocalOpCliInvocation,
  runOkCliSubprocess,
} from './subprocess.ts';
import type { LocalOpSubprocessLifetime } from './subprocess-lifetime.ts';

export interface RunPatOptions extends LocalOpCliInvocation {
  lifetime?: LocalOpSubprocessLifetime;
  host?: string;
  token: string;
  timeoutMs?: number;
}

export type RunPatResult =
  | { ok: true; host: string; login: string }
  | { ok: false; host: string; error: string };

export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResult> {
  const host = opts.host ?? 'github.com';
  let terminal: RunPatResult | null = null;

  const proc = runOkCliSubprocess(opts.cli, {
    lifetime: opts.lifetime,
    cwd: opts.cwd,
    trailingArgs: ['auth', 'pat', '--json', '--host', host, '--token-stdin'],
    stdinData: opts.token,
    timeoutMs: opts.timeoutMs ?? LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,
    onLine: ({ parsed }) => {
      if (!parsed) return;
      if (parsed.type === 'complete') {
        terminal = {
          ok: true,
          host: typeof parsed.host === 'string' ? parsed.host : host,
          login: typeof parsed.login === 'string' ? parsed.login : '',
        };
      } else if (parsed.type === 'error') {
        terminal = {
          ok: false,
          host,
          error: typeof parsed.message === 'string' ? parsed.message : 'Token validation failed',
        };
      }
    },
  });

  const result = await proc.done;
  if ('refused' in result) return { ok: false, host, error: result.refused };
  if (terminal) return terminal;
  if (result.timedOut) return { ok: false, host, error: 'Token validation timed out.' };
  return {
    ok: false,
    host,
    error: `Token validation failed.${stderrDetailSuffix(result.stderr, [opts.token, opts.token.trim()])}`,
  };
}