Skip to content
Myr

types.ts

This file

Path

src/client/types.ts

393 lines · 12.2 KiB · TypeScript

Last changed by

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–14why, one step back
1import type { Hono } from '../hono'
2import type { HonoBase } from '../hono-base'3import type { METHODS, METHOD_NAME_ALL_LOWERCASE } from '../router'4import type { Endpoint, ExtractSchema, KnownResponseFormat, ResponseFormat, Schema } from '../types'5import type { StatusCode, SuccessStatusCode } from '../utils/http-status'6import type { HasRequiredKeys } from '../utils/types'78/**9 * Type representing the '$all' method name10 */11type MethodNameAll = `$${typeof METHOD_NAME_ALL_LOWERCASE}`1213/**14 * Type representing all standard HTTP methods prefixed with '$'

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 15why, one step back
15 * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch' | '$query'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 16–393why, one step back
16 */
17type StandardMethods = `$${(typeof METHODS)[number]}`1819/**20 * Expands '$all' into all standard HTTP methods.21 * If the schema contains '$all', it creates a type where all standard HTTP methods22 * point to the same endpoint definition as '$all', while removing '$all' itself.23 */24type ExpandAllMethod<S> = MethodNameAll extends keyof S25 ? { [M in StandardMethods]: S[MethodNameAll] } & Omit<S, MethodNameAll>26 : S2728type HonoRequest = (typeof Hono.prototype)['request']2930export type BuildSearchParamsFn = (query: Record<string, string | string[]>) => URLSearchParams3132export type ClientRequestOptions<T = unknown> = {33 fetch?: typeof fetch | HonoRequest34 webSocket?: (...args: ConstructorParameters<typeof WebSocket>) => WebSocket35 /**36 * Standard `RequestInit`, caution that this take highest priority37 * and could be used to overwrite things that Hono sets for you, like `body | method | headers`.38 *39 * If you want to add some headers, use in `headers` instead of `init`40 */41 init?: RequestInit42 /**43 * Custom function to serialize query parameters into URLSearchParams.44 * By default, arrays are serialized as multiple parameters with the same key (e.g., `key=a&key=b`).45 * You can provide a custom function to change this behavior, for example to use bracket notation (e.g., `key[]=a&key[]=b`).46 *47 * @example48 * ```ts49 * const client = hc('http://localhost', {50 * buildSearchParams: (query) => {51 * return new URLSearchParams(qs.stringify(query))52 * }53 * })54 * ```55 */56 buildSearchParams?: BuildSearchParamsFn57} & (keyof T extends never58 ? {59 headers?:60 | Record<string, string>61 | (() => Record<string, string> | Promise<Record<string, string>>)62 }63 : {64 headers: T | (() => T | Promise<T>)65 })6667export type ClientRequest<Prefix extends string, Path extends string, S extends Schema> = {68 [M in keyof ExpandAllMethod<S>]: ExpandAllMethod<S>[M] extends Endpoint & { input: infer R }69 ? R extends object70 ? HasRequiredKeys<R> extends true71 ? (72 args: R,73 options?: ClientRequestOptions74 ) => Promise<ClientResponseOfEndpoint<ExpandAllMethod<S>[M]>>75 : (76 args?: R,77 options?: ClientRequestOptions78 ) => Promise<ClientResponseOfEndpoint<ExpandAllMethod<S>[M]>>79 : never80 : never81} & {82 $url: <83 const Arg extends84 | (S[keyof S] extends { input: infer R }85 ? R extends { param: infer P }86 ? R extends { query: infer Q }87 ? { param: P; query: Q }88 : { param: P }89 : R extends { query: infer Q }90 ? { query: Q }91 : {}92 : {})93 | undefined = undefined,94 >(95 arg?: Arg96 ) => HonoURL<Prefix, Path, Arg>97 $path: <98 const Arg extends99 | (S[keyof S] extends { input: infer R }100 ? R extends { param: infer P }101 ? R extends { query: infer Q }102 ? { param: P; query: Q }103 : { param: P }104 : R extends { query: infer Q }105 ? { query: Q }106 : {}107 : {})108 | undefined = undefined,109 >(110 arg?: Arg111 ) => BuildPath<Path, Arg>112} & (S['$get'] extends { outputFormat: 'ws' }113 ? S['$get'] extends { input: infer I }114 ? {115 $ws: (args?: I) => WebSocket116 }117 : {}118 : {})119120type ClientResponseOfEndpoint<T extends Endpoint = Endpoint> = T extends {121 output: infer O122 outputFormat: infer F123 status: infer S124}125 ? ClientResponse<O, S extends number ? S : never, F extends ResponseFormat ? F : never>126 : never127128export interface ClientResponse<129 T,130 U extends number = StatusCode,131 F extends ResponseFormat = ResponseFormat,132> {133 readonly body: ReadableStream | null134 readonly bodyUsed: boolean135 ok: U extends SuccessStatusCode136 ? true137 : U extends Exclude<StatusCode, SuccessStatusCode>138 ? false139 : boolean140 redirected: boolean141 status: U142 statusText: string143 type: 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'144 headers: Headers145 url: string146 redirect(url: string, status: number): Response147 clone(): Response148 bytes(): Promise<Uint8Array<ArrayBuffer>>149 json(): F extends 'text' ? Promise<never> : F extends 'json' ? Promise<T> : Promise<unknown>150 text(): F extends 'text' ? (T extends string ? Promise<T> : Promise<never>) : Promise<string>151 blob(): Promise<Blob>152 formData(): Promise<FormData>153 arrayBuffer(): Promise<ArrayBuffer>154}155156type BuildSearch<Arg, Key extends 'query'> = Arg extends { [K in Key]: infer Query }157 ? IsEmptyObject<Query> extends true158 ? ''159 : `?${string}`160 : ''161162type BuildPathname<P extends string, Arg> = Arg extends { param: infer Param }163 ? `${ApplyParam<TrimStartSlash<P>, Param>}`164 : `/${TrimStartSlash<P>}`165166type BuildPath<P extends string, Arg> = `${BuildPathname<P, Arg>}${BuildSearch<Arg, 'query'>}`167168type BuildTypedURL<169 Protocol extends string,170 Host extends string,171 Port extends string,172 P extends string,173 Arg,174> = TypedURL<`${Protocol}:`, Host, Port, BuildPathname<P, Arg>, BuildSearch<Arg, 'query'>>175176type HonoURL<Prefix extends string, Path extends string, Arg> =177 IsLiteral<Prefix> extends true178 ? TrimEndSlash<Prefix> extends `${infer Protocol}://${infer Rest}`179 ? Rest extends `${infer Hostname}/${infer P}`180 ? ParseHostName<Hostname> extends [infer Host extends string, infer Port extends string]181 ? BuildTypedURL<Protocol, Host, Port, P, Arg>182 : never183 : ParseHostName<Rest> extends [infer Host extends string, infer Port extends string]184 ? BuildTypedURL<Protocol, Host, Port, Path, Arg>185 : never186 : URL187 : URL188type ParseHostName<T extends string> = T extends `${infer Host}:${infer Port}`189 ? [Host, Port]190 : [T, '']191type TrimStartSlash<T extends string> = T extends `/${infer R}` ? TrimStartSlash<R> : T192type TrimEndSlash<T extends string> = T extends `${infer R}/` ? TrimEndSlash<R> : T193type IsLiteral<T extends string> = [T] extends [never] ? false : string extends T ? false : true194type ApplyParam<195 Path extends string,196 P,197 Result extends string = '',198> = Path extends `${infer Head}/${infer Rest}`199 ? Head extends `:${infer Param}`200 ? P extends Record<Param, infer Value extends string>201 ? IsLiteral<Value> extends true202 ? ApplyParam<Rest, P, `${Result}/${Value & string}`>203 : ApplyParam<Rest, P, `${Result}/${Head}`>204 : ApplyParam<Rest, P, `${Result}/${Head}`>205 : ApplyParam<Rest, P, `${Result}/${Head}`>206 : Path extends `:${infer Param}`207 ? P extends Record<Param, infer Value extends string>208 ? IsLiteral<Value> extends true209 ? `${Result}/${Value & string}`210 : `${Result}/${Path}`211 : `${Result}/${Path}`212 : `${Result}/${Path}`213type IsEmptyObject<T> = keyof T extends never ? true : false214215export interface TypedURL<216 Protocol extends string,217 Hostname extends string,218 Port extends string,219 Pathname extends string,220 Search extends string,221> extends URL {222 protocol: Protocol223 hostname: Hostname224 port: Port225 host: Port extends '' ? Hostname : `${Hostname}:${Port}`226 origin: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}`227 pathname: Pathname228 search: Search229 href: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}${Pathname}${Search}`230}231232export interface Response extends ClientResponse<unknown> {}233234export type Fetch<T> = (235 args?: InferRequestType<T>,236 opt?: ClientRequestOptions237) => Promise<ClientResponseOfEndpoint<InferEndpointType<T>>>238239type InferEndpointType<T> = T extends (240 args: infer R,241 // eslint-disable-next-line @typescript-eslint/no-explicit-any242 options: any | undefined243) => Promise<infer U>244 ? U extends ClientResponse<infer O, infer S, infer F>245 ? { input: NonNullable<R>; output: O; outputFormat: F; status: S } extends Endpoint246 ? { input: NonNullable<R>; output: O; outputFormat: F; status: S }247 : never248 : never249 : never250251export type InferResponseType<T, U extends StatusCode = StatusCode> = InferResponseTypeFromEndpoint<252 InferEndpointType<T>,253 U254>255256type InferResponseTypeFromEndpoint<T extends Endpoint, U extends StatusCode> = T extends {257 output: infer O258 status: infer S259}260 ? S extends U261 ? O262 : never263 : never264265export type InferRequestType<T> = T extends (266 args: infer R,267 // eslint-disable-next-line @typescript-eslint/no-explicit-any268 options: any | undefined269) => Promise<ClientResponse<unknown>>270 ? NonNullable<R>271 : never272273export type InferRequestOptionsType<T> = T extends (274 // eslint-disable-next-line @typescript-eslint/no-explicit-any275 args: any,276 options: infer R277) => Promise<ClientResponse<unknown>>278 ? NonNullable<R>279 : never280281/**282 * Filter a ClientResponse type so it only includes responses of specific status codes.283 */284export type FilterClientResponseByStatusCode<285 T extends ClientResponse<any, any, any>,286 U extends number = StatusCode,287> =288 T extends ClientResponse<infer RT, infer RC, infer RF>289 ? RC extends U290 ? ClientResponse<RT, RC, RF>291 : never292 : never293294type PathToChain<295 Prefix extends string,296 Path extends string,297 E extends Schema,298 Original extends string = Path,299> = Path extends `/${infer P}`300 ? PathToChain<Prefix, P, E, Path>301 : Path extends `${infer P}/${infer R}`302 ? { [K in P]: PathToChain<Prefix, R, E, Original> }303 : {304 [K in Path extends '' ? 'index' : Path]: ClientRequest<305 Prefix,306 Original,307 E extends Record<string, unknown> ? E[Original] : never308 >309 }310311export type Client<T, Prefix extends string> =312 T extends HonoBase<any, infer S, any>313 ? S extends Record<infer K, Schema>314 ? K extends string315 ? PathToChain<Prefix, K, S>316 : never317 : never318 : never319320export type Callback = (opts: CallbackOptions) => unknown321322interface CallbackOptions {323 path: string[]324 // eslint-disable-next-line @typescript-eslint/no-explicit-any325 args: any[]326}327328export type ObjectType<T = unknown> = {329 [key: string]: T330}331332type GlobalResponseDefinition = {333 [S in StatusCode]?: {334 [F in KnownResponseFormat]?: unknown335 }336}337338type ToEndpoints<Def extends GlobalResponseDefinition, R> = {339 [S in keyof Def & StatusCode]: {340 [F in keyof Def[S] & KnownResponseFormat]: Omit<R, 'output' | 'status' | 'outputFormat'> & {341 output: Def[S][F]342 status: S343 outputFormat: F344 }345 }[keyof Def[S] & KnownResponseFormat]346}[keyof Def & StatusCode]347348type ModRoute<R, Def extends GlobalResponseDefinition> = R extends Endpoint349 ? R | ToEndpoints<Def, R>350 : R351352type ModSchema<D, Def extends GlobalResponseDefinition> = {353 [K in keyof D]: {354 [M in keyof D[K]]: ModRoute<D[K][M], Def>355 }356}357358export type ApplyGlobalResponse<App, Def extends GlobalResponseDefinition> =359 App extends HonoBase<infer E, infer _ extends Schema, infer B>360 ? ModSchema<ExtractSchema<App>, Def> extends infer S extends Schema361 ? Hono<E, S, B>362 : never363 : never364365type PickRoute<R, U extends StatusCode> = R extends Endpoint366 ? R extends { status: U }367 ? R368 : never369 : R370371type PickSchema<D, U extends StatusCode> = {372 [K in keyof D]: {373 [M in keyof D[K]]: PickRoute<D[K][M], U>374 }375}376377/**378 * Keep only specific status code responses from all routes of an app.379 * Useful when error responses are handled centrally (e.g., via custom fetch)380 * and you want the client to only expose success response types.381 *382 * @example383 * ```ts384 * type AppSuccessOnly = PickResponseByStatusCode<typeof app, 200>385 * const client = hc<AppSuccessOnly>('http://localhost')386 * ```387 */388export type PickResponseByStatusCode<App, U extends StatusCode> =389 App extends HonoBase<infer E, infer _ extends Schema, infer B>390 ? PickSchema<ExtractSchema<App>, U> extends infer S extends Schema391 ? Hono<E, S, B>392 : never393 : never