Open History to see the last commit
1/** Mechanically bind Cloudflare's per-model inputs to its own universal REST route. */
2import type { BundledEndpoint, ModelInfo, SpecSource } from './types.ts'
3
4export const GATEWAY_REST_DOCS =
5 'https://raw.githubusercontent.com/cloudflare/cloudflare-docs/production/src/content/docs/ai-gateway/usage/rest-api.mdx'
6export interface GatewayRunContract {
7 path: string
8 source: SpecSource
9}
10
11export function parseGatewayRunContract(
12 text: string,
13 source: SpecSource,
14): GatewayRunContract {
15 if (
16 !/`POST \/ai\/run`\s*\|\s*Envelope with `model`, `input`/.test(text) ||
17 !/Model-specific parameters go inside `input`/.test(text)
18 )
19 throw new Error(
20 'cloudflare-ai-gateway: native docs publish no model/input envelope',
21 )
22 const url = text.match(
23 /curl -X POST "(https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/\$[A-Z_]+\/ai\/run)"/,
24 )?.[1]
25 if (!url)
26 throw new Error(
27 'cloudflare-ai-gateway: native docs publish no universal POST path',
28 )
29 return {
30 path: url
31 .replace('https://api.cloudflare.com/client/v4', '')
32 .replace(/\$[A-Z_]+/, '{account_id}'),
33 source,
34 }
35}
36
37function record(value: unknown): value is Record<string, unknown> {
38 return typeof value === 'object' && value !== null && !Array.isArray(value)
39}
40
41/** A wrapped schema's root-relative refs must still address its original root. */
42function wrappedInput(value: unknown): unknown {
43 if (Array.isArray(value)) return value.map(wrappedInput)
44 if (!record(value)) return value
45 return Object.fromEntries(
46 Object.entries(value).map(([key, item]) => {
47 if (key === '$id')
48 throw new Error(
49 'cloudflare-ai-gateway: scoped input $id cannot be wrapped',
50 )
51 if (key === '$ref') {
52 if (typeof item !== 'string' || !item.startsWith('#'))
53 throw new Error(
54 'cloudflare-ai-gateway: input schema has an external reference',
55 )
56 if (item !== '#' && !item.startsWith('#/'))
57 throw new Error(
58 'cloudflare-ai-gateway: input schema has an unsupported anchor reference',
59 )
60 return [key, `#/properties/input${item.slice(1)}`]
61 }
62 return [key, wrappedInput(item)]
63 }),
64 )
65}
66
67/** A native input record containing only its dialect declares no body fields. */
68export function hasGatewayInputSchema(value: unknown): boolean {
69 return record(value) && Object.keys(value).some((key) => key !== '$schema')
70}
71
72export function catalogGatewayEndpoint(
73 catalog: unknown,
74 info: ModelInfo,
75 source: SpecSource,
76 contract: GatewayRunContract,
77): BundledEndpoint | null {
78 if (info.activity == null) return null
79 if (record(catalog) && catalog.schema == null) return null
80 if (!record(catalog) || !record(catalog.schema))
81 throw new Error(
82 `cloudflare-ai-gateway: ${info.rawId} has no native schema object`,
83 )
84 const input = catalog.schema.input
85 if (input == null || (record(input) && !hasGatewayInputSchema(input)))
86 return null
87 if (!record(input))
88 throw new Error(
89 `cloudflare-ai-gateway: ${info.rawId} input schema is not an object`,
90 )
91 return {
92 publicId: info.rawId,
93 path: contract.path,
94 activity: info.activity,
95 description: info.displayName ?? null,
96 source,
97 derivation: 'generated',
98 input: {
99 type: 'object',
100 properties: {
101 model: { type: 'string', const: info.rawId },
102 input: wrappedInput(input),
103 },
104 // Native docs name the envelope fields but do not publish their required list.
105 'x-modelschemas-envelope-source': contract.source,
106 },
107 // The catalog's intrinsic output does not establish the /ai/run HTTP envelope.
108 }
109}