All files robots.ts

92.56% Statements 137/148
61.42% Branches 86/140
100% Functions 23/23
93.7% Lines 134/143

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                                                          42x 10x   42x 3238x       42x 2844x   42x 194x 194x     194x 392x     42x 298x   42x 12x   42x 1398x 1398x   1398x 1872x 1872x 1872x                   474x 474x 474x 474x 438x   474x     1398x     1398x     42x 972x 972x 972x   972x     51x                       14x 14x       39x 39x                   10x     31x     321x 321x 750x   321x         506x       42x 222x 220x   2x 2x     42x 202x 202x 202x       202x 202x         42x     10x 10x 10x   10x 232x 222x 222x           222x 218x   4x       10x     42x       2x 2x   2x 192x 192x     2x     42x 2x 2x 192x 192x 192x 192x 192x 192x 192x     2x     42x 42x   42x 15x 2x   15x     42x 12x 2x   12x     42x 3x 3x 3x   288x             3x   288x     288x 288x 288x   101x   3x 3x 3x 3x   3x   3x           42x 10x 10x 10x   10x 10x 10x 10x 10x   10x             10x 10x 10x               10x     42x 2x 2x   2x 2x    
import type { z } from 'zod'
 
import { getRobotSchemaOptions, robotsMeta } from './alphalib/types/robots/_index.ts'
 
export type RobotListOptions = {
  category?: string
  search?: string
  limit?: number
  cursor?: string
}
 
export type RobotListItem = {
  name: string
  title?: string
  summary: string
  category?: string
}
 
export type RobotListResult = {
  robots: RobotListItem[]
  nextCursor?: string
}
 
export type RobotParamHelp = {
  name: string
  type: string
  description?: string
}
 
export type RobotHelp = {
  name: string
  summary: string
  requiredParams: RobotParamHelp[]
  optionalParams: RobotParamHelp[]
  examples?: Array<{ description: string; snippet: Record<string, unknown> }>
}
 
export type RobotHelpOptions = {
  robotName: string
  detailLevel?: 'summary' | 'params' | 'examples' | 'full'
}
 
type RobotsMetaMap = typeof robotsMeta
type RobotMeta = RobotsMetaMap[keyof RobotsMetaMap]
 
const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null
 
const getDef = (schema: z.ZodTypeAny): Record<string, unknown> =>
  (schema as unknown as { _def?: Record<string, unknown>; def?: Record<string, unknown> })._def ??
  (schema as unknown as { def?: Record<string, unknown> }).def ??
  {}
 
const getDefType = (def: Record<string, unknown>): string | undefined =>
  (def.type as string | undefined) ?? (def.typeName as string | undefined)
 
const robotNameToPath = (name: string): string => {
  const base = name.replace(/Robot$/, '')
  const spaced = base
    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
    .replace(/([A-Z]+)([A-Z][a-z0-9])/g, '$1 $2')
  const parts = spaced.split(/\s+/).filter(Boolean)
  return `/${parts.map((part) => part.toLowerCase()).join('/')}`
}
 
const selectSummary = (meta: RobotMeta): string =>
  meta.purpose_sentence ?? meta.purpose_words ?? meta.purpose_word ?? meta.title ?? meta.name
 
const resolveRobotPath = (robotName: string): string =>
  robotName.startsWith('/') ? robotName : robotNameToPath(robotName)
 
const unwrapSchema = (schema: z.ZodTypeAny): { base: z.ZodTypeAny; optional: boolean } => {
  let base = schema
  let optional = typeof base.isOptional === 'function' ? base.isOptional() : false
 
  while (true) {
    const def = getDef(base)
    const defType = getDefType(def)
    if (
      defType === 'optional' ||
      defType === 'default' ||
      defType === 'nullable' ||
      defType === 'catch' ||
      defType === 'ZodOptional' ||
      defType === 'ZodDefault' ||
      defType === 'ZodNullable' ||
      defType === 'ZodCatch'
    ) {
      const inner = def.innerType as z.ZodTypeAny | undefined
      Eif (inner) {
        base = inner
        if (defType !== 'nullable' && defType !== 'ZodNullable') {
          optional = true
        }
        continue
      }
    }
    break
  }
 
  return { base, optional }
}
 
const describeSchemaType = (schema: z.ZodTypeAny): string => {
  const { base } = unwrapSchema(schema)
  const def = getDef(base)
  const defType = getDefType(def)
 
  switch (defType) {
    case 'string':
    case 'ZodString':
      return 'string'
    case 'number':
    case 'ZodNumber':
      return 'number'
    case 'boolean':
    case 'ZodBoolean':
      return 'boolean'
    case 'bigint':
    case 'ZodBigInt':
      return 'bigint'
    case 'literal':
    case 'ZodLiteral': {
      const value = (def.values as unknown[] | undefined)?.[0] ?? def.value
      return value === undefined ? 'literal' : JSON.stringify(value)
    }
    case 'enum':
    case 'ZodEnum': {
      const values = Array.isArray(def.values) ? def.values : []
      return values.length ? `enum(${values.join(' | ')})` : 'enum'
    }
    case 'array':
    case 'ZodArray': {
      const element = def.element as z.ZodTypeAny | undefined
      const inner = element ? describeSchemaType(element) : 'unknown'
      return `array<${inner}>`
    }
    case 'object':
    case 'ZodObject':
      return 'object'
    case 'record':
    case 'ZodRecord':
      return 'record'
    case 'union':
    case 'ZodUnion': {
      const options = Array.isArray(def.options) ? def.options : []
      const rendered = options
        .map((option) => describeSchemaType(option as z.ZodTypeAny))
        .join(' | ')
      return rendered ? `union<${rendered}>` : 'union'
    }
    case 'ZodDiscriminatedUnion':
      return 'object'
    default:
      return defType ?? 'unknown'
  }
}
 
const getParamDescription = (schema: z.ZodTypeAny): string | undefined => {
  if (schema.description?.trim()) {
    return schema.description.trim()
  }
  const inner = unwrapSchema(schema).base
  return inner.description?.trim()
}
 
const getShape = (schema: z.ZodTypeAny): Record<string, z.ZodTypeAny> => {
  const { base } = unwrapSchema(schema)
  const def = getDef(base)
  const shape = def.shape as
    | Record<string, z.ZodTypeAny>
    | (() => Record<string, z.ZodTypeAny>)
    | undefined
  Eif (typeof shape === 'function') {
    return shape()
  }
  return shape ?? {}
}
 
const getRobotParams = (
  schema: z.ZodTypeAny,
): { required: RobotParamHelp[]; optional: RobotParamHelp[] } => {
  const shape = getShape(schema)
  const required: RobotParamHelp[] = []
  const optional: RobotParamHelp[] = []
 
  for (const [key, value] of Object.entries(shape)) {
    if (key === 'robot') continue
    const { optional: isOptional } = unwrapSchema(value)
    const param: RobotParamHelp = {
      name: key,
      type: describeSchemaType(value),
      description: getParamDescription(value),
    }
 
    if (isOptional) {
      optional.push(param)
    } else {
      required.push(param)
    }
  }
 
  return { required, optional }
}
 
const getRobotsMetaIndex = (): {
  byName: Map<string, RobotMeta>
  byPath: Map<string, RobotMeta>
} => {
  const byName = new Map<string, RobotMeta>()
  const byPath = new Map<string, RobotMeta>()
 
  for (const meta of Object.values(robotsMeta)) {
    byName.set(meta.name, meta)
    byPath.set(robotNameToPath(meta.name), meta)
  }
 
  return { byName, byPath }
}
 
const getRobotSchemaIndex = (): Map<string, z.ZodTypeAny> => {
  const index = new Map<string, z.ZodTypeAny>()
  for (const option of getRobotSchemaOptions()) {
    const shape = getShape(option)
    const robotSchema = shape.robot
    Iif (!robotSchema) continue
    const robotDef = getDef(robotSchema)
    const robotLiteral = (robotDef.values as unknown[] | undefined)?.[0] ?? robotDef.value
    Eif (typeof robotLiteral === 'string') {
      index.set(robotLiteral, option)
    }
  }
  return index
}
 
let cachedMetaIndex: ReturnType<typeof getRobotsMetaIndex> | null = null
let cachedSchemaIndex: ReturnType<typeof getRobotSchemaIndex> | null = null
 
const getMetaIndex = (): ReturnType<typeof getRobotsMetaIndex> => {
  if (!cachedMetaIndex) {
    cachedMetaIndex = getRobotsMetaIndex()
  }
  return cachedMetaIndex
}
 
const getSchemaIndex = (): ReturnType<typeof getRobotSchemaIndex> => {
  if (!cachedSchemaIndex) {
    cachedSchemaIndex = getRobotSchemaIndex()
  }
  return cachedSchemaIndex
}
 
export const listRobots = (options: RobotListOptions = {}): RobotListResult => {
  const normalizedSearch = options.search?.toLowerCase()
  const normalizedCategory = options.category?.toLowerCase()
  const { byPath } = getMetaIndex()
 
  const allRobots: RobotListItem[] = Array.from(byPath.entries()).map(([path, meta]) => ({
    name: path,
    title: meta.title,
    summary: selectSummary(meta),
    category: meta.service_slug,
  }))
 
  const filtered = allRobots
    .filter((robot) => {
      Iif (normalizedCategory && robot.category?.toLowerCase() !== normalizedCategory) {
        return false
      }
      Iif (!normalizedSearch) return true
      const haystack = `${robot.name} ${robot.title ?? ''} ${robot.summary}`.toLowerCase()
      return haystack.includes(normalizedSearch)
    })
    .sort((a, b) => a.name.localeCompare(b.name))
 
  const start = options.cursor ? Number.parseInt(options.cursor, 10) : 0
  const safeStart = Number.isFinite(start) && start > 0 ? start : 0
  const safeLimit = options.limit && options.limit > 0 ? options.limit : 200
  const page = filtered.slice(safeStart, safeStart + safeLimit)
  const nextCursor =
    safeStart + safeLimit < filtered.length ? String(safeStart + safeLimit) : undefined
 
  return {
    robots: page,
    nextCursor,
  }
}
 
export const getRobotHelp = (options: RobotHelpOptions): RobotHelp => {
  const detailLevel = options.detailLevel ?? 'summary'
  const { byPath, byName } = getMetaIndex()
  const schemaIndex = getSchemaIndex()
 
  const path = resolveRobotPath(options.robotName)
  const meta = byPath.get(path) ?? byName.get(options.robotName) ?? null
  const summary = meta ? selectSummary(meta) : `Robot ${path}`
  const schema = schemaIndex.get(path)
  const params = schema ? getRobotParams(schema) : { required: [], optional: [] }
 
  const help: RobotHelp = {
    name: path,
    summary,
    requiredParams: detailLevel === 'params' || detailLevel === 'full' ? params.required : [],
    optionalParams: detailLevel === 'params' || detailLevel === 'full' ? params.optional : [],
  }
 
  Eif ((detailLevel === 'examples' || detailLevel === 'full') && meta?.example_code) {
    const snippet = isRecord(meta.example_code) ? meta.example_code : {}
    help.examples = [
      {
        description: meta.example_code_description ?? 'Example',
        snippet,
      },
    ]
  }
 
  return help
}
 
export const isKnownRobot = (robotName: string): boolean => {
  const { byPath, byName } = getMetaIndex()
  const schemaIndex = getSchemaIndex()
 
  const path = resolveRobotPath(robotName)
  return byPath.has(path) || byName.has(robotName) || schemaIndex.has(path)
}