Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/microsoft

src/accounts.ts

79 lines · 2.7 KB · TypeScript
export const DEFAULT_MICROSOFT_INTEGRATION = 'microsoft'

export type MicrosoftAccountParams = {
  /** Exact Kody OAuth integration name. Wins over `account`. */
  integration?: string
  /**
   * Convenience alias. `default` / `microsoft` / omitted → `microsoft`.
   * `work` → `microsoft-work`. Values that already start with `microsoft-`
   * are used as-is.
   */
  account?: string
}

export type MicrosoftAccountInfo = {
  account: string
  integrationName: string
  useWhen: string
}

/**
 * Resolve which saved Microsoft OAuth integration to use.
 *
 * - `integration` wins when set (exact name, e.g. `microsoft-work`)
 * - `account: 'work'` → `microsoft-work`
 * - `account: 'default'` / `'microsoft'` / omitted → `microsoft`
 * - bare values that already start with `microsoft-` are used as-is
 */
export function resolveMicrosoftIntegration(input: MicrosoftAccountParams | string = {}): string {
  if (typeof input === 'string') {
    return resolveMicrosoftIntegration({ account: input })
  }
  const explicit = input.integration?.trim()
  if (explicit) return explicit

  const account = input.account?.trim()
  if (!account || account === 'default' || account === 'microsoft') {
    return DEFAULT_MICROSOFT_INTEGRATION
  }
  if (account.startsWith('microsoft-') || account === DEFAULT_MICROSOFT_INTEGRATION) {
    return account
  }
  return 'microsoft-' + account
}

export function describeMicrosoftAccount(input: MicrosoftAccountParams | string = {}): MicrosoftAccountInfo {
  const integrationName = resolveMicrosoftIntegration(input)
  const account =
    typeof input === 'string'
      ? input || 'default'
      : input.account?.trim() || (input.integration ? input.integration : 'default')
  return {
    account,
    integrationName,
    useWhen:
      integrationName === DEFAULT_MICROSOFT_INTEGRATION
        ? 'Default Microsoft Graph connection. Connect at /connect/oauth?provider=microsoft.'
        : 'Additional Microsoft account. Connect at /connect/oauth?provider=' + integrationName + '.',
  }
}

/**
 * Return how this package maps `account` / `integration` to a Kody OAuth connection.
 * @example
 * import accounts from 'kody:@kody/microsoft/accounts'
 * const { defaultIntegration } = accounts()
 * // => 'microsoft'
 */
export default function accounts() {
  return {
    defaultIntegration: DEFAULT_MICROSOFT_INTEGRATION,
    naming:
      'Pass integration for an exact Kody OAuth name, or account as a short alias (`work` → microsoft-work).',
    examples: [
      { account: 'default', integrationName: 'microsoft' },
      { account: 'work', integrationName: 'microsoft-work' },
      { integration: 'microsoft-personal', integrationName: 'microsoft-personal' },
    ],
  }
}