diff --git a/polylan_submitter/src/api/client.gen.ts b/polylan_submitter/src/api/client.gen.ts new file mode 100644 index 0000000..cab3c70 --- /dev/null +++ b/polylan_submitter/src/api/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig()); diff --git a/polylan_submitter/src/api/client/client.gen.ts b/polylan_submitter/src/api/client/client.gen.ts new file mode 100644 index 0000000..fc3f037 --- /dev/null +++ b/polylan_submitter/src/api/client/client.gen.ts @@ -0,0 +1,277 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors(); + + const beforeRequest = async < + TData = unknown, + TResponseStyle extends 'data' | 'fields' = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, + >( + options: RequestOptions, + ) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined as string | undefined, + }; + + if (opts.security) { + await setAuthParams(opts); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined; + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const resolvedOpts = opts as typeof opts & + ResolvedRequestOptions; + const url = buildUrl(resolvedOpts); + + return { opts: resolvedOpts, url }; + }; + + const request: Client['request'] = async (options) => { + const throwOnError = options.throwOnError ?? _config.throwOnError; + const responseStyle = options.responseStyle ?? _config.responseStyle; + + let request: Request | undefined; + let response: Response | undefined; + + try { + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + + response = await _fetch(request); + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if (response.status === 204 || response.headers.get('Content-Length') === '0') { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'text': + data = await response[parseAs](); + break; + case 'json': { + // Some servers return 200 with no Content-Length and empty body. + // response.json() would throw; read as text and parse if non-empty. + const text = await response.text(); + data = text ? JSON.parse(text) : {}; + break; + } + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + throw jsonError ?? textError; + } catch (error) { + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = await fn(finalError, response, request, options as ResolvedRequestOptions); + } + } + + finalError = finalError || {}; + + if (throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response, + }; + } + }; + + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; + + const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options }); + + return { + buildUrl: _buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/polylan_submitter/src/api/client/index.ts b/polylan_submitter/src/api/client/index.ts new file mode 100644 index 0000000..b295ede --- /dev/null +++ b/polylan_submitter/src/api/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/polylan_submitter/src/api/client/types.gen.ts b/polylan_submitter/src/api/client/types.gen.ts new file mode 100644 index 0000000..4b288a5 --- /dev/null +++ b/polylan_submitter/src/api/client/types.gen.ts @@ -0,0 +1,217 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> + extends + Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onRequest' + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + headers: Headers; + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record ? TData[keyof TData] : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? (TData extends Record ? TData[keyof TData] : TData) | undefined + : ( + | { + data: TData extends Record ? TData[keyof TData] : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record ? TError[keyof TError] : TError; + } + ) & { + /** request may be undefined, because error may be from building the request object itself */ + request?: Request; + /** response may be undefined, because error may be from building the request object itself or from a network error */ + response?: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick>, 'method'>, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/polylan_submitter/src/api/client/utils.gen.ts b/polylan_submitter/src/api/client/utils.gen.ts new file mode 100644 index 0000000..7800fe4 --- /dev/null +++ b/polylan_submitter/src/api/client/utils.gen.ts @@ -0,0 +1,316 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = (contentType: string | null): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export async function setAuthParams( + options: Pick & { + headers: Headers; + }, +): Promise { + for (const auth of options.security ?? []) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +} + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e., their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + /** response may be undefined due to a network error where no response object is produced */ + response: Res | undefined, + /** request may be undefined, because error may be from building the request object itself */ + request: Req | undefined, + options: Options, +) => Err | Promise; + +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/polylan_submitter/src/api/core/auth.gen.ts b/polylan_submitter/src/api/core/auth.gen.ts new file mode 100644 index 0000000..3ebf994 --- /dev/null +++ b/polylan_submitter/src/api/core/auth.gen.ts @@ -0,0 +1,41 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/polylan_submitter/src/api/core/bodySerializer.gen.ts b/polylan_submitter/src/api/core/bodySerializer.gen.ts new file mode 100644 index 0000000..67daca6 --- /dev/null +++ b/polylan_submitter/src/api/core/bodySerializer.gen.ts @@ -0,0 +1,82 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: unknown) => unknown; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: (body: unknown): FormData => { + const data = new FormData(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: unknown): string => + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: (body: unknown): string => { + const data = new URLSearchParams(); + + Object.entries(body as Record).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/polylan_submitter/src/api/core/params.gen.ts b/polylan_submitter/src/api/core/params.gen.ts new file mode 100644 index 0000000..7955601 --- /dev/null +++ b/polylan_submitter/src/api/core/params.gen.ts @@ -0,0 +1,169 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[key.slice(prefix.length)] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/polylan_submitter/src/api/core/pathSerializer.gen.ts b/polylan_submitter/src/api/core/pathSerializer.gen.ts new file mode 100644 index 0000000..994b284 --- /dev/null +++ b/polylan_submitter/src/api/core/pathSerializer.gen.ts @@ -0,0 +1,171 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; +}; diff --git a/polylan_submitter/src/api/core/queryKeySerializer.gen.ts b/polylan_submitter/src/api/core/queryKeySerializer.gen.ts new file mode 100644 index 0000000..5000df6 --- /dev/null +++ b/polylan_submitter/src/api/core/queryKeySerializer.gen.ts @@ -0,0 +1,117 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { + if (value === null) { + return null; + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/polylan_submitter/src/api/core/serverSentEvents.gen.ts b/polylan_submitter/src/api/core/serverSentEvents.gen.ts new file mode 100644 index 0000000..ddf3c4d --- /dev/null +++ b/polylan_submitter/src/api/core/serverSentEvents.gen.ts @@ -0,0 +1,242 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * Callback invoked when a network or parsing error occurs during streaming. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param error The error that occurred. + */ + onSseError?: (error: unknown) => void; + /** + * Callback invoked when an event is streamed from the server. + * + * This option applies only if the endpoint returns a stream of events. + * + * @param event Event streamed from the server. + * @returns Nothing (void). + */ + onSseEvent?: (event: StreamEvent) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export function createSseClient({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult { + let lastEventId: string | undefined; + + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + const createStream = async function* () { + let retryDelay: number = sseDefaultRetryDelay ?? 3000; + let attempt = 0; + const signal = options.signal ?? new AbortController().signal; + + while (true) { + if (signal.aborted) break; + + attempt++; + + const headers = + options.headers instanceof Headers + ? options.headers + : new Headers(options.headers as Record | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + let eventName: string | undefined; + + for (const line of lines) { + if (line.startsWith('data:')) { + dataLines.push(line.replace(/^data:\s*/, '')); + } else if (line.startsWith('event:')) { + eventName = line.replace(/^event:\s*/, ''); + } else if (line.startsWith('id:')) { + lastEventId = line.replace(/^id:\s*/, ''); + } else if (line.startsWith('retry:')) { + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); + if (!Number.isNaN(parsed)) { + retryDelay = parsed; + } + } + } + + let data: unknown; + let parsedJson = false; + + if (dataLines.length) { + const rawData = dataLines.join('\n'); + try { + data = JSON.parse(rawData); + parsedJson = true; + } catch { + data = rawData; + } + } + + if (parsedJson) { + if (responseValidator) { + await responseValidator(data); + } + + if (responseTransformer) { + data = await responseTransformer(data); + } + } + + onSseEvent?.({ + data, + event: eventName, + id: lastEventId, + retry: retryDelay, + }); + + if (dataLines.length) { + yield data as any; + } + } + } + } finally { + signal.removeEventListener('abort', abortHandler); + reader.releaseLock(); + } + + break; // exit loop on normal completion + } catch (error) { + // connection failed or aborted; retry after delay + onSseError?.(error); + + if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) { + break; // stop after firing error + } + + // exponential backoff: double retry each attempt, cap at 30s + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); + await sleep(backoff); + } + } + }; + + const stream = createStream(); + + return { stream }; +} diff --git a/polylan_submitter/src/api/core/types.gen.ts b/polylan_submitter/src/api/core/types.gen.ts new file mode 100644 index 0000000..9efe71d --- /dev/null +++ b/polylan_submitter/src/api/core/types.gen.ts @@ -0,0 +1,104 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g., converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; +}; diff --git a/polylan_submitter/src/api/core/utils.gen.ts b/polylan_submitter/src/api/core/utils.gen.ts new file mode 100644 index 0000000..9a4fec7 --- /dev/null +++ b/polylan_submitter/src/api/core/utils.gen.ts @@ -0,0 +1,140 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + url: string; +} + +export const PATH_PARAM_RE = /\{[^{}]+\}/g; + +export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { + let url = _url; + const matches = _url.match(PATH_PARAM_RE); + if (matches) { + for (const match of matches) { + let explode = false; + let name = match.substring(1, match.length - 1); + let style: ArraySeparatorStyle = 'simple'; + + if (name.endsWith('*')) { + explode = true; + name = name.substring(0, name.length - 1); + } + + if (name.startsWith('.')) { + name = name.substring(1); + style = 'label'; + } else if (name.startsWith(';')) { + name = name.substring(1); + style = 'matrix'; + } + + const value = path[name]; + + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); + continue; + } + + if (typeof value === 'object') { + url = url.replace( + match, + serializeObjectParam({ + explode, + name, + style, + value: value as Record, + valueOnly: true, + }), + ); + continue; + } + + if (style === 'matrix') { + url = url.replace( + match, + `;${serializePrimitiveParam({ + name, + value: value as string, + })}`, + ); + continue; + } + + const replaceValue = encodeURIComponent( + style === 'label' ? `.${value as string}` : (value as string), + ); + url = url.replace(match, replaceValue); + } + } + return url; +}; + +export const getUrl = ({ + baseUrl, + path, + query, + querySerializer, + url: _url, +}: { + baseUrl?: string; + path?: Record; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e., client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/polylan_submitter/src/api/index.ts b/polylan_submitter/src/api/index.ts new file mode 100644 index 0000000..057793f --- /dev/null +++ b/polylan_submitter/src/api/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export { animationsApiPuzzleResults, animationsApiResults, animationsApiTopSubmissions, gamesApiListGames, marketApiCloseMarket, marketApiCreateBet, marketApiListMarkets, marketApiListUserBets, marketApiResolveMarket, noitaApiGetLeaderboard, noitaApiGetResults, noitaApiSubmitLogFile, type Options, polylanSubmitterApiClearCache, polylanSubmitterApiGetUserInfo, polylanSubmitterApiHealthCheck, submissionsApiCreateSubmission, submissionsApiDeleteSubmission, submissionsApiGetCollection, submissionsApiGetStats, submissionsApiGetSubmission, submissionsApiListPuzzles, submissionsApiListResponsesNeedingValidation, submissionsApiListSubmissions, submissionsApiValidateAuto, submissionsApiValidateResponse, submissionsApiValidateSubmission } from './sdk.gen'; +export type { AnimationsApiPuzzleResultsData, AnimationsApiPuzzleResultsResponse, AnimationsApiPuzzleResultsResponses, AnimationsApiResultsData, AnimationsApiResultsResponse, AnimationsApiResultsResponses, AnimationsApiTopSubmissionsData, AnimationsApiTopSubmissionsResponse, AnimationsApiTopSubmissionsResponses, ClientOptions, GameOut, GamesApiListGamesData, GamesApiListGamesResponse, GamesApiListGamesResponses, Input, LeaderboardEntryOut, LeaderboardOut, MarketApiCloseMarketData, MarketApiCloseMarketResponses, MarketApiCreateBetData, MarketApiCreateBetResponse, MarketApiCreateBetResponses, MarketApiListMarketsData, MarketApiListMarketsResponse, MarketApiListMarketsResponses, MarketApiListUserBetsData, MarketApiListUserBetsResponse, MarketApiListUserBetsResponses, MarketApiResolveMarketData, MarketApiResolveMarketResponse, MarketApiResolveMarketResponses, MarketListSchema, MarketOptionSchema, NoitaApiGetLeaderboardData, NoitaApiGetLeaderboardResponse, NoitaApiGetLeaderboardResponses, NoitaApiGetResultsData, NoitaApiGetResultsResponse, NoitaApiGetResultsResponses, NoitaApiSubmitLogFileData, NoitaApiSubmitLogFileError, NoitaApiSubmitLogFileErrors, NoitaApiSubmitLogFileResponse, NoitaApiSubmitLogFileResponses, NoitaSubmissionOut, ObjectivResultOut, PagedSubmissionOut, PolylanSubmitterApiClearCacheData, PolylanSubmitterApiClearCacheResponses, PolylanSubmitterApiGetUserInfoData, PolylanSubmitterApiGetUserInfoResponse, PolylanSubmitterApiGetUserInfoResponses, PolylanSubmitterApiHealthCheckData, PolylanSubmitterApiHealthCheckResponses, PuzzlePointsFactorOut, PuzzleResponseIn, PuzzleResponseOut, PuzzleResponseRankingOut, PuzzleResultsOut, PuzzleSubmissionsOut, PuzzleSubmissionWithRankOut, RankingSchema, ResolveMarketSchema, ResultsOut, SteamCollectionItemOut, SteamCollectionOut, SubmissionFileOut, SubmissionIn, SubmissionOut, SubmissionsApiCreateSubmissionData, SubmissionsApiCreateSubmissionResponse, SubmissionsApiCreateSubmissionResponses, SubmissionsApiDeleteSubmissionData, SubmissionsApiDeleteSubmissionResponses, SubmissionsApiGetCollectionData, SubmissionsApiGetCollectionResponse, SubmissionsApiGetCollectionResponses, SubmissionsApiGetStatsData, SubmissionsApiGetStatsResponses, SubmissionsApiGetSubmissionData, SubmissionsApiGetSubmissionResponse, SubmissionsApiGetSubmissionResponses, SubmissionsApiListPuzzlesData, SubmissionsApiListPuzzlesResponse, SubmissionsApiListPuzzlesResponses, SubmissionsApiListResponsesNeedingValidationData, SubmissionsApiListResponsesNeedingValidationResponse, SubmissionsApiListResponsesNeedingValidationResponses, SubmissionsApiListSubmissionsData, SubmissionsApiListSubmissionsResponse, SubmissionsApiListSubmissionsResponses, SubmissionsApiValidateAutoData, SubmissionsApiValidateAutoResponse, SubmissionsApiValidateAutoResponses, SubmissionsApiValidateResponseData, SubmissionsApiValidateResponseResponse, SubmissionsApiValidateResponseResponses, SubmissionsApiValidateSubmissionData, SubmissionsApiValidateSubmissionResponse, SubmissionsApiValidateSubmissionResponses, TournamentPuzzleResultsOut, TournamentSubmissionsOut, UserBetCreateSchema, UserBetSchema, UserDisplayOut, UserInfoOut, ValidationIn, WinnerFileOut, WinnerResponseOut } from './types.gen'; diff --git a/polylan_submitter/src/api/sdk.gen.ts b/polylan_submitter/src/api/sdk.gen.ts new file mode 100644 index 0000000..a5ef664 --- /dev/null +++ b/polylan_submitter/src/api/sdk.gen.ts @@ -0,0 +1,241 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client'; +import { client } from './client.gen'; +import type { AnimationsApiPuzzleResultsData, AnimationsApiPuzzleResultsResponses, AnimationsApiResultsData, AnimationsApiResultsResponses, AnimationsApiTopSubmissionsData, AnimationsApiTopSubmissionsResponses, GamesApiListGamesData, GamesApiListGamesResponses, MarketApiCloseMarketData, MarketApiCloseMarketResponses, MarketApiCreateBetData, MarketApiCreateBetResponses, MarketApiListMarketsData, MarketApiListMarketsResponses, MarketApiListUserBetsData, MarketApiListUserBetsResponses, MarketApiResolveMarketData, MarketApiResolveMarketResponses, NoitaApiGetLeaderboardData, NoitaApiGetLeaderboardResponses, NoitaApiGetResultsData, NoitaApiGetResultsResponses, NoitaApiSubmitLogFileData, NoitaApiSubmitLogFileErrors, NoitaApiSubmitLogFileResponses, PolylanSubmitterApiClearCacheData, PolylanSubmitterApiClearCacheResponses, PolylanSubmitterApiGetUserInfoData, PolylanSubmitterApiGetUserInfoResponses, PolylanSubmitterApiHealthCheckData, PolylanSubmitterApiHealthCheckResponses, SubmissionsApiCreateSubmissionData, SubmissionsApiCreateSubmissionResponses, SubmissionsApiDeleteSubmissionData, SubmissionsApiDeleteSubmissionResponses, SubmissionsApiGetCollectionData, SubmissionsApiGetCollectionResponses, SubmissionsApiGetStatsData, SubmissionsApiGetStatsResponses, SubmissionsApiGetSubmissionData, SubmissionsApiGetSubmissionResponses, SubmissionsApiListPuzzlesData, SubmissionsApiListPuzzlesResponses, SubmissionsApiListResponsesNeedingValidationData, SubmissionsApiListResponsesNeedingValidationResponses, SubmissionsApiListSubmissionsData, SubmissionsApiListSubmissionsResponses, SubmissionsApiValidateAutoData, SubmissionsApiValidateAutoResponses, SubmissionsApiValidateResponseData, SubmissionsApiValidateResponseResponses, SubmissionsApiValidateSubmissionData, SubmissionsApiValidateSubmissionResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * You can pass arbitrary values through the `meta` object. This can be + * used to access values that aren't defined as part of the SDK function. + */ + meta?: Record; +}; + +/** + * Health Check + * + * Health check endpoint + */ +export const polylanSubmitterApiHealthCheck = (options?: Options) => (options?.client ?? client).get({ url: '/api/health', ...options }); + +/** + * Clear Cache + * + * Clear all API caches (admin only) + */ +export const polylanSubmitterApiClearCache = (options?: Options) => (options?.client ?? client).post({ url: '/api/cache/clear', ...options }); + +/** + * Get User Info + * + * Get current user information + */ +export const polylanSubmitterApiGetUserInfo = (options?: Options) => (options?.client ?? client).get({ url: '/api/user', ...options }); + +/** + * List Puzzles + * + * Get list of available puzzles + */ +export const submissionsApiListPuzzles = (options?: Options) => (options?.client ?? client).get({ url: '/api/submissions/puzzles', ...options }); + +/** + * Get Collection + * + * Get the active collection details + */ +export const submissionsApiGetCollection = (options?: Options) => (options?.client ?? client).get({ url: '/api/submissions/collection', ...options }); + +/** + * List Submissions + * + * Get paginated list of submissions + */ +export const submissionsApiListSubmissions = (options?: Options) => (options?.client ?? client).get({ url: '/api/submissions/submissions', ...options }); + +/** + * Create Submission + * + * Create a new submission with multiple puzzle responses + */ +export const submissionsApiCreateSubmission = (options: Options) => (options.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/submissions/submissions', + ...options, + headers: { + 'Content-Type': null, + ...options.headers + } +}); + +/** + * Delete Submission + * + * Delete a submission (admin only) + */ +export const submissionsApiDeleteSubmission = (options: Options) => (options.client ?? client).delete({ url: '/api/submissions/submissions/{submission_id}', ...options }); + +/** + * Get Submission + * + * Get detailed submission by ID + */ +export const submissionsApiGetSubmission = (options: Options) => (options.client ?? client).get({ url: '/api/submissions/submissions/{submission_id}', ...options }); + +/** + * Validate Response + * + * Manually validate a puzzle response + */ +export const submissionsApiValidateResponse = (options: Options) => (options.client ?? client).put({ + url: '/api/submissions/responses/{response_id}/validate', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * Validate Auto + * + * Try to auto validate a puzzle response + */ +export const submissionsApiValidateAuto = (options: Options) => (options.client ?? client).put({ url: '/api/submissions/responses/{response_id}/validate/auto', ...options }); + +/** + * List Responses Needing Validation + * + * Get all responses that need manual validation + */ +export const submissionsApiListResponsesNeedingValidation = (options?: Options) => (options?.client ?? client).get({ url: '/api/submissions/responses/needs-validation', ...options }); + +/** + * Validate Submission + * + * Mark entire submission as validated + */ +export const submissionsApiValidateSubmission = (options: Options) => (options.client ?? client).post({ url: '/api/submissions/submissions/{submission_id}/validate', ...options }); + +/** + * Get Stats + * + * Get submission statistics + */ +export const submissionsApiGetStats = (options?: Options) => (options?.client ?? client).get({ url: '/api/submissions/stats', ...options }); + +/** + * Results + */ +export const animationsApiResults = (options?: Options) => (options?.client ?? client).get({ url: '/api/results/results', ...options }); + +/** + * Top Submissions + * + * Get tournament top submissions for each puzzle. Only available when tournament is closed. + */ +export const animationsApiTopSubmissions = (options?: Options) => (options?.client ?? client).get({ url: '/api/results/top-submissions', ...options }); + +/** + * Puzzle Results + * + * Get tournament results organized by puzzle with coefficients. Only available when tournament is closed. + */ +export const animationsApiPuzzleResults = (options?: Options) => (options?.client ?? client).get({ url: '/api/results/puzzle-results', ...options }); + +/** + * Get Results + */ +export const noitaApiGetResults = (options?: Options) => (options?.client ?? client).get({ url: '/api/noita/results', ...options }); + +/** + * Get Leaderboard + * + * Get the global leaderboard for all users ranked by total score. + * + * Uses Window functions to rank users by their total score in descending order. + */ +export const noitaApiGetLeaderboard = (options?: Options) => (options?.client ?? client).get({ url: '/api/noita/leaderboard', ...options }); + +/** + * Submit Log File + * + * Submit a Noita run file (log file, screenshot, or video). + * + * Accepts: + * - Text files (.txt) for polylan_mod_log.txt + * - Images (.png, .jpg, .gif) + * - Videos (.mp4, .webm) + * + * Max file size: 256 MB + */ +export const noitaApiSubmitLogFile = (options: Options) => (options.client ?? client).post({ + ...formDataBodySerializer, + url: '/api/noita/submit', + ...options, + headers: { + 'Content-Type': null, + ...options.headers + } +}); + +/** + * List Games + */ +export const gamesApiListGames = (options?: Options) => (options?.client ?? client).get({ url: '/api/games/', ...options }); + +/** + * List Markets + * + * List all markets. + */ +export const marketApiListMarkets = (options?: Options) => (options?.client ?? client).get({ url: '/api/market/', ...options }); + +/** + * List User Bets + * + * List all bets placed by the current user. + */ +export const marketApiListUserBets = (options?: Options) => (options?.client ?? client).get({ url: '/api/market/user/bets', ...options }); + +/** + * Close Market + * + * Close a market. Admin only. + */ +export const marketApiCloseMarket = (options: Options) => (options.client ?? client).post({ url: '/api/market/{market_uuid}/actions/close', ...options }); + +/** + * Resolve Market + * + * Resolve a market with a winning option. Admin only. + */ +export const marketApiResolveMarket = (options: Options) => (options.client ?? client).post({ + url: '/api/market/{market_uuid}/actions/resolve', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * Create Bet + * + * Place a bet on a market option. + */ +export const marketApiCreateBet = (options: Options) => (options.client ?? client).post({ + url: '/api/market/{market_uuid}/bets', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); diff --git a/polylan_submitter/src/api/types.gen.ts b/polylan_submitter/src/api/types.gen.ts new file mode 100644 index 0000000..20afd50 --- /dev/null +++ b/polylan_submitter/src/api/types.gen.ts @@ -0,0 +1,1569 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: string; +}; + +/** + * UserInfoOut + * + * Schema for user information output + */ +export type UserInfoOut = { + /** + * Id + */ + id?: number | null; + /** + * Username + */ + username?: string | null; + /** + * First Name + */ + first_name?: string | null; + /** + * Last Name + */ + last_name?: string | null; + /** + * Email + */ + email?: string | null; + /** + * Is Authenticated + */ + is_authenticated: boolean; + /** + * Is Staff + */ + is_staff: boolean; + /** + * Is Superuser + */ + is_superuser: boolean; + /** + * Cas Groups + */ + cas_groups?: Array | null; +}; + +/** + * PuzzlePointsFactorOut + * + * Schema for puzzle points factor + */ +export type PuzzlePointsFactorOut = { + /** + * Cost + */ + cost: number; + /** + * Cycles + */ + cycles: number; + /** + * Area + */ + area: number; +}; + +/** + * SteamCollectionItemOut + * + * Schema for Steam collection item output + */ +export type SteamCollectionItemOut = { + /** + * Steam Url + */ + steam_url: string; + points_factor?: PuzzlePointsFactorOut | null; + /** + * ID + */ + id: number; + /** + * Steam Item Id + * + * Steam Workshop item ID + */ + steam_item_id: string; + /** + * Title + * + * Item title + */ + title: string; + /** + * Author Name + * + * Steam username of item creator + */ + author_name: string; + /** + * Description + * + * Item description + */ + description: string; + /** + * Tags + * + * Item tags as JSON array + */ + tags?: { + [key: string]: unknown; + }; + /** + * Order Index + * + * Order of item in collection + */ + order_index?: number; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * SteamCollectionOut + * + * Schema for Steam collection output + */ +export type SteamCollectionOut = { + /** + * ID + */ + id: number; + /** + * Steam Id + * + * Steam collection ID from URL + */ + steam_id: string; + /** + * Title + * + * Collection title + */ + title: string; + /** + * Description + * + * Collection description + */ + description: string; + /** + * Author Name + * + * Steam username of collection creator + */ + author_name: string; + /** + * Total Items + * + * Number of items in collection + */ + total_items?: number; + /** + * Unique Visitors + * + * Number of unique visitors + */ + unique_visitors?: number; + /** + * Current Favorites + * + * Current number of favorites + */ + current_favorites?: number; + /** + * Accepting Submissions + * + * Whether the tournament is accepting new submissions + */ + accepting_submissions?: boolean; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * Input + */ +export type Input = { + /** + * Limit + */ + limit?: number; + /** + * Offset + */ + offset?: number; +}; + +/** + * PagedSubmissionOut + */ +export type PagedSubmissionOut = { + /** + * Items + */ + items: Array; + /** + * Count + */ + count: number; +}; + +/** + * PuzzleResponseOut + * + * Schema for puzzle response output + */ +export type PuzzleResponseOut = { + /** + * Files + */ + files: Array; + /** + * Final Cost + */ + final_cost: number | null; + /** + * Final Cycles + */ + final_cycles: number | null; + /** + * Final Area + */ + final_area: number | null; + /** + * ID + */ + id: number; + /** + * Puzzle + * + * The puzzle this response is for + */ + puzzle_id: number; + /** + * Puzzle Name + * + * Puzzle name as detected by OCR + */ + puzzle_name: string; + /** + * Cost + * + * Cost value from OCR + */ + cost: number; + /** + * Cycles + * + * Cycles value from OCR + */ + cycles: number; + /** + * Area + * + * Area value from OCR + */ + area: number; + /** + * Needs Manual Validation + * + * Whether OCR failed and manual validation is needed + */ + needs_manual_validation?: boolean; + /** + * Ocr Confidence Cost + * + * OCR confidence score for cost (0.0 to 1.0) + */ + ocr_confidence_cost?: number | null; + /** + * Ocr Confidence Cycles + * + * OCR confidence score for cycles (0.0 to 1.0) + */ + ocr_confidence_cycles?: number | null; + /** + * Ocr Confidence Area + * + * OCR confidence score for area (0.0 to 1.0) + */ + ocr_confidence_area?: number | null; + /** + * Validated Cost + * + * Manually validated cost value + */ + validated_cost?: number | null; + /** + * Validated Cycles + * + * Manually validated cycles value + */ + validated_cycles?: number | null; + /** + * Validated Area + * + * Manually validated area value + */ + validated_area?: number | null; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * SubmissionFileOut + * + * Schema for submission file output + */ +export type SubmissionFileOut = { + /** + * File Url + */ + file_url: string | null; + /** + * ID + */ + id: number; + /** + * Original Filename + * + * Original filename as uploaded by user + */ + original_filename: string; + /** + * File Size + * + * File size in bytes + */ + file_size: number; + /** + * Content Type + * + * MIME type of the file + */ + content_type: string; + /** + * Ocr Processed + * + * Whether OCR has been processed for this file + */ + ocr_processed?: boolean; + /** + * Ocr Raw Data + * + * Raw OCR data as JSON + */ + ocr_raw_data?: { + [key: string]: unknown; + } | null; + /** + * Ocr Error + * + * OCR processing error message + */ + ocr_error: string; + /** + * Created At + */ + created_at: string; +}; + +/** + * SubmissionOut + * + * Schema for submission output + */ +export type SubmissionOut = { + /** + * Responses + */ + responses: Array; + /** + * Total Responses + */ + total_responses: number; + /** + * Needs Validation + */ + needs_validation: boolean; + /** + * Id + */ + id?: string; + /** + * User + * + * User who made the submission (null for anonymous) + */ + user_id?: number | null; + /** + * Notes + * + * Optional notes about the submission + */ + notes?: string | null; + /** + * Is Validated + * + * Whether this submission has been manually validated + */ + is_validated?: boolean; + /** + * Validated By + * + * Admin user who validated this submission + */ + validated_by_id?: number | null; + /** + * Validated At + * + * When this submission was validated + */ + validated_at?: string | null; + /** + * Manual Validation Requested + * + * Whether the user specifically requested manual validation + */ + manual_validation_requested?: boolean; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * PuzzleResponseIn + * + * Schema for creating a puzzle response + */ +export type PuzzleResponseIn = { + /** + * Puzzle Id + */ + puzzle_id: number; + /** + * Puzzle Name + */ + puzzle_name: string; + /** + * Cost + */ + cost?: number | null; + /** + * Cycles + */ + cycles?: number | null; + /** + * Area + */ + area?: number | null; + /** + * Needs Manual Validation + */ + needs_manual_validation?: boolean; + /** + * Ocr Confidence Cost + */ + ocr_confidence_cost?: number | null; + /** + * Ocr Confidence Cycles + */ + ocr_confidence_cycles?: number | null; + /** + * Ocr Confidence Area + */ + ocr_confidence_area?: number | null; +}; + +/** + * SubmissionIn + * + * Schema for creating a submission + */ +export type SubmissionIn = { + /** + * Notes + */ + notes?: string | null; + /** + * Manual Validation Requested + */ + manual_validation_requested?: boolean; + /** + * Responses + */ + responses: Array; +}; + +/** + * ValidationIn + * + * Schema for manual validation input + */ +export type ValidationIn = { + /** + * Puzzle + */ + puzzle?: number | null; + /** + * Validated Cost + */ + validated_cost?: number | null; + /** + * Validated Cycles + */ + validated_cycles?: number | null; + /** + * Validated Area + */ + validated_area?: number | null; +}; + +/** + * PuzzleResponseRankingOut + */ +export type PuzzleResponseRankingOut = { + /** + * Points + */ + points?: number | null; + /** + * Rank Points + */ + rank_points?: number | null; + /** + * Puzzle User Rank + */ + puzzle_user_rank: number; + /** + * User Response Rank + */ + user_response_rank: number; + /** + * User Id + */ + user_id: number; + /** + * Final Cost + */ + final_cost: number | null; + /** + * Final Cycles + */ + final_cycles: number | null; + /** + * Final Area + */ + final_area: number | null; + /** + * ID + */ + id: number; + /** + * Puzzle Name + * + * Puzzle name as detected by OCR + */ + puzzle_name: string; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * RankingSchema + */ +export type RankingSchema = { + /** + * Users + */ + users: Array; + /** + * Puzzles + */ + puzzles: Array; + /** + * Responses By Userid + */ + responses_by_userid: { + [key: string]: Array; + }; + /** + * Ranking By Puzzle + */ + ranking_by_puzzle: { + [key: string]: Array; + }; +}; + +/** + * UserDisplayOut + */ +export type UserDisplayOut = { + /** + * Id + */ + id: number; + /** + * Username + */ + username: string; + /** + * Is Staff + */ + is_staff: boolean; +}; + +/** + * PuzzleSubmissionsOut + * + * Schema for puzzle with all top submissions + */ +export type PuzzleSubmissionsOut = { + /** + * Puzzle Id + */ + puzzle_id: number; + /** + * Puzzle Title + */ + puzzle_title: string; + /** + * Submissions + */ + submissions: Array; +}; + +/** + * TournamentSubmissionsOut + * + * Schema for tournament top submissions results + */ +export type TournamentSubmissionsOut = { + /** + * Submissions + */ + submissions: Array; +}; + +/** + * WinnerFileOut + * + * Schema for winner submission file + */ +export type WinnerFileOut = { + /** + * File Url + */ + file_url: string; + /** + * Original Filename + */ + original_filename: string; +}; + +/** + * WinnerResponseOut + * + * Schema for winner response with files + */ +export type WinnerResponseOut = { + /** + * User Id + */ + user_id: number; + /** + * Username + */ + username: string; + /** + * Final Cost + */ + final_cost: number | null; + /** + * Final Cycles + */ + final_cycles: number | null; + /** + * Final Area + */ + final_area: number | null; + /** + * Rank Points + */ + rank_points: number | null; + /** + * Total Coef + */ + total_coef: number | null; + /** + * Files + */ + files: Array; +}; + +/** + * PuzzleResultsOut + * + * Schema for puzzle-specific results with coefficients + */ +export type PuzzleResultsOut = { + /** + * Puzzle Id + */ + puzzle_id: number; + /** + * Puzzle Title + */ + puzzle_title: string; + points_factor: PuzzlePointsFactorOut | null; + /** + * Submissions + */ + submissions: Array; +}; + +/** + * PuzzleSubmissionWithRankOut + * + * Schema for puzzle submission with rank + */ +export type PuzzleSubmissionWithRankOut = { + /** + * Rank + */ + rank: number; + /** + * User Id + */ + user_id: number; + /** + * Username + */ + username: string; + /** + * Final Cost + */ + final_cost: number | null; + /** + * Final Cycles + */ + final_cycles: number | null; + /** + * Final Area + */ + final_area: number | null; + /** + * Rank Points + */ + rank_points: number | null; + /** + * Total Coef + */ + total_coef: number | null; + /** + * Files + */ + files: Array; +}; + +/** + * TournamentPuzzleResultsOut + * + * Schema for tournament puzzle-specific results + */ +export type TournamentPuzzleResultsOut = { + /** + * Results + */ + results: Array; +}; + +/** + * ObjectivResultOut + */ +export type ObjectivResultOut = { + /** + * Objectiv Id + */ + objectiv_id: string; + /** + * Display String + */ + display_string: string; + /** + * First Seen At + */ + first_seen_at: string | null; + /** + * Count + */ + count: number; + /** + * Max Count + */ + max_count: number; + /** + * Seed + */ + seed: string | null; + /** + * Points Per Objectiv + */ + points_per_objectiv: number; + /** + * Total Points + */ + total_points: number | null; +}; + +/** + * ResultsOut + */ +export type ResultsOut = { + /** + * Total Score + */ + total_score: number; + /** + * Deaths Count + */ + deaths_count: number; + /** + * Objectives + */ + objectives: Array; +}; + +/** + * LeaderboardEntryOut + */ +export type LeaderboardEntryOut = { + /** + * Rank + */ + rank: number; + /** + * Username + */ + username: string; + /** + * Is Staff + */ + is_staff: boolean; + /** + * Total Score + */ + total_score: number; + /** + * Objectives Count + */ + objectives_count: number; + /** + * Deaths Count + */ + deaths_count: number; +}; + +/** + * LeaderboardOut + */ +export type LeaderboardOut = { + /** + * Leaderboard + */ + leaderboard: Array; +}; + +/** + * NoitaSubmissionOut + */ +export type NoitaSubmissionOut = { + /** + * Id + */ + id: string; + /** + * User Id + */ + user_id: number | null; + /** + * Username + */ + username: string | null; + /** + * File Size + */ + file_size: number; + /** + * Content Type + */ + content_type: string; + /** + * Created At + */ + created_at: string; + /** + * Processed + */ + processed: boolean; +}; + +/** + * GameOut + */ +export type GameOut = { + /** + * Steam App Id + */ + steam_app_id: number; + /** + * Name + */ + name: string; + /** + * Path + */ + path: string; +}; + +/** + * MarketListSchema + */ +export type MarketListSchema = { + /** + * Uuid + */ + uuid: string; + /** + * Title + */ + title: string; + /** + * Description + */ + description: string; + /** + * Type + */ + type: string; + /** + * Status + */ + status: string; + /** + * End Date + */ + end_date: string; + /** + * Created At + */ + created_at: string; + /** + * Options + */ + options: Array; + winning_option?: MarketOptionSchema | null; +}; + +/** + * MarketOptionSchema + */ +export type MarketOptionSchema = { + /** + * Uuid + */ + uuid: string; + /** + * Text + */ + text: string; + /** + * Position + */ + position: number; +}; + +/** + * UserBetSchema + */ +export type UserBetSchema = { + /** + * Uuid + */ + uuid: string; + /** + * Amount + */ + amount: number; + /** + * Created At + */ + created_at: string; + option: MarketOptionSchema; + market?: MarketListSchema | null; +}; + +/** + * ResolveMarketSchema + */ +export type ResolveMarketSchema = { + /** + * Winning Option Uuid + */ + winning_option_uuid: string; +}; + +/** + * UserBetCreateSchema + */ +export type UserBetCreateSchema = { + /** + * Option Uuid + */ + option_uuid: string; + /** + * Amount + */ + amount: number; +}; + +export type PolylanSubmitterApiHealthCheckData = { + body?: never; + path?: never; + query?: never; + url: '/api/health'; +}; + +export type PolylanSubmitterApiHealthCheckResponses = { + /** + * OK + */ + 200: unknown; +}; + +export type PolylanSubmitterApiClearCacheData = { + body?: never; + path?: never; + query?: never; + url: '/api/cache/clear'; +}; + +export type PolylanSubmitterApiClearCacheResponses = { + /** + * OK + */ + 200: unknown; +}; + +export type PolylanSubmitterApiGetUserInfoData = { + body?: never; + path?: never; + query?: never; + url: '/api/user'; +}; + +export type PolylanSubmitterApiGetUserInfoResponses = { + /** + * OK + */ + 200: UserInfoOut; +}; + +export type PolylanSubmitterApiGetUserInfoResponse = PolylanSubmitterApiGetUserInfoResponses[keyof PolylanSubmitterApiGetUserInfoResponses]; + +export type SubmissionsApiListPuzzlesData = { + body?: never; + path?: never; + query?: never; + url: '/api/submissions/puzzles'; +}; + +export type SubmissionsApiListPuzzlesResponses = { + /** + * Response + * + * OK + */ + 200: Array; +}; + +export type SubmissionsApiListPuzzlesResponse = SubmissionsApiListPuzzlesResponses[keyof SubmissionsApiListPuzzlesResponses]; + +export type SubmissionsApiGetCollectionData = { + body?: never; + path?: never; + query?: never; + url: '/api/submissions/collection'; +}; + +export type SubmissionsApiGetCollectionResponses = { + /** + * OK + */ + 200: SteamCollectionOut; +}; + +export type SubmissionsApiGetCollectionResponse = SubmissionsApiGetCollectionResponses[keyof SubmissionsApiGetCollectionResponses]; + +export type SubmissionsApiListSubmissionsData = { + body?: never; + path?: never; + query?: { + /** + * Limit + */ + limit?: number; + /** + * Offset + */ + offset?: number; + }; + url: '/api/submissions/submissions'; +}; + +export type SubmissionsApiListSubmissionsResponses = { + /** + * OK + */ + 200: PagedSubmissionOut; +}; + +export type SubmissionsApiListSubmissionsResponse = SubmissionsApiListSubmissionsResponses[keyof SubmissionsApiListSubmissionsResponses]; + +export type SubmissionsApiCreateSubmissionData = { + /** + * MultiPartBodyParams + */ + body: { + /** + * Files + */ + files: Array; + data: SubmissionIn; + }; + path?: never; + query?: never; + url: '/api/submissions/submissions'; +}; + +export type SubmissionsApiCreateSubmissionResponses = { + /** + * OK + */ + 200: SubmissionOut; +}; + +export type SubmissionsApiCreateSubmissionResponse = SubmissionsApiCreateSubmissionResponses[keyof SubmissionsApiCreateSubmissionResponses]; + +export type SubmissionsApiDeleteSubmissionData = { + body?: never; + path: { + /** + * Submission Id + */ + submission_id: string; + }; + query?: never; + url: '/api/submissions/submissions/{submission_id}'; +}; + +export type SubmissionsApiDeleteSubmissionResponses = { + /** + * OK + */ + 200: unknown; +}; + +export type SubmissionsApiGetSubmissionData = { + body?: never; + path: { + /** + * Submission Id + */ + submission_id: string; + }; + query?: never; + url: '/api/submissions/submissions/{submission_id}'; +}; + +export type SubmissionsApiGetSubmissionResponses = { + /** + * OK + */ + 200: SubmissionOut; +}; + +export type SubmissionsApiGetSubmissionResponse = SubmissionsApiGetSubmissionResponses[keyof SubmissionsApiGetSubmissionResponses]; + +export type SubmissionsApiValidateResponseData = { + body: ValidationIn; + path: { + /** + * Response Id + */ + response_id: number; + }; + query?: never; + url: '/api/submissions/responses/{response_id}/validate'; +}; + +export type SubmissionsApiValidateResponseResponses = { + /** + * OK + */ + 200: PuzzleResponseOut; +}; + +export type SubmissionsApiValidateResponseResponse = SubmissionsApiValidateResponseResponses[keyof SubmissionsApiValidateResponseResponses]; + +export type SubmissionsApiValidateAutoData = { + body?: never; + path: { + /** + * Response Id + */ + response_id: number; + }; + query?: never; + url: '/api/submissions/responses/{response_id}/validate/auto'; +}; + +export type SubmissionsApiValidateAutoResponses = { + /** + * OK + */ + 200: PuzzleResponseOut; +}; + +export type SubmissionsApiValidateAutoResponse = SubmissionsApiValidateAutoResponses[keyof SubmissionsApiValidateAutoResponses]; + +export type SubmissionsApiListResponsesNeedingValidationData = { + body?: never; + path?: never; + query?: never; + url: '/api/submissions/responses/needs-validation'; +}; + +export type SubmissionsApiListResponsesNeedingValidationResponses = { + /** + * Response + * + * OK + */ + 200: Array; +}; + +export type SubmissionsApiListResponsesNeedingValidationResponse = SubmissionsApiListResponsesNeedingValidationResponses[keyof SubmissionsApiListResponsesNeedingValidationResponses]; + +export type SubmissionsApiValidateSubmissionData = { + body?: never; + path: { + /** + * Submission Id + */ + submission_id: string; + }; + query?: never; + url: '/api/submissions/submissions/{submission_id}/validate'; +}; + +export type SubmissionsApiValidateSubmissionResponses = { + /** + * OK + */ + 200: SubmissionOut; +}; + +export type SubmissionsApiValidateSubmissionResponse = SubmissionsApiValidateSubmissionResponses[keyof SubmissionsApiValidateSubmissionResponses]; + +export type SubmissionsApiGetStatsData = { + body?: never; + path?: never; + query?: never; + url: '/api/submissions/stats'; +}; + +export type SubmissionsApiGetStatsResponses = { + /** + * OK + */ + 200: unknown; +}; + +export type AnimationsApiResultsData = { + body?: never; + path?: never; + query?: never; + url: '/api/results/results'; +}; + +export type AnimationsApiResultsResponses = { + /** + * OK + */ + 200: RankingSchema; +}; + +export type AnimationsApiResultsResponse = AnimationsApiResultsResponses[keyof AnimationsApiResultsResponses]; + +export type AnimationsApiTopSubmissionsData = { + body?: never; + path?: never; + query?: { + /** + * Limit + */ + limit?: number; + }; + url: '/api/results/top-submissions'; +}; + +export type AnimationsApiTopSubmissionsResponses = { + /** + * OK + */ + 200: TournamentSubmissionsOut; +}; + +export type AnimationsApiTopSubmissionsResponse = AnimationsApiTopSubmissionsResponses[keyof AnimationsApiTopSubmissionsResponses]; + +export type AnimationsApiPuzzleResultsData = { + body?: never; + path?: never; + query?: { + /** + * Limit + */ + limit?: number; + }; + url: '/api/results/puzzle-results'; +}; + +export type AnimationsApiPuzzleResultsResponses = { + /** + * OK + */ + 200: TournamentPuzzleResultsOut; +}; + +export type AnimationsApiPuzzleResultsResponse = AnimationsApiPuzzleResultsResponses[keyof AnimationsApiPuzzleResultsResponses]; + +export type NoitaApiGetResultsData = { + body?: never; + path?: never; + query?: never; + url: '/api/noita/results'; +}; + +export type NoitaApiGetResultsResponses = { + /** + * OK + */ + 200: ResultsOut; +}; + +export type NoitaApiGetResultsResponse = NoitaApiGetResultsResponses[keyof NoitaApiGetResultsResponses]; + +export type NoitaApiGetLeaderboardData = { + body?: never; + path?: never; + query?: never; + url: '/api/noita/leaderboard'; +}; + +export type NoitaApiGetLeaderboardResponses = { + /** + * OK + */ + 200: LeaderboardOut; +}; + +export type NoitaApiGetLeaderboardResponse = NoitaApiGetLeaderboardResponses[keyof NoitaApiGetLeaderboardResponses]; + +export type NoitaApiSubmitLogFileData = { + /** + * FileParams + */ + body: { + /** + * File + */ + file: Blob | File; + }; + path?: never; + query?: never; + url: '/api/noita/submit'; +}; + +export type NoitaApiSubmitLogFileErrors = { + /** + * Response + * + * Bad Request + */ + 400: { + [key: string]: unknown; + }; +}; + +export type NoitaApiSubmitLogFileError = NoitaApiSubmitLogFileErrors[keyof NoitaApiSubmitLogFileErrors]; + +export type NoitaApiSubmitLogFileResponses = { + /** + * OK + */ + 200: NoitaSubmissionOut; +}; + +export type NoitaApiSubmitLogFileResponse = NoitaApiSubmitLogFileResponses[keyof NoitaApiSubmitLogFileResponses]; + +export type GamesApiListGamesData = { + body?: never; + path?: never; + query?: never; + url: '/api/games/'; +}; + +export type GamesApiListGamesResponses = { + /** + * Response + * + * OK + */ + 200: Array; +}; + +export type GamesApiListGamesResponse = GamesApiListGamesResponses[keyof GamesApiListGamesResponses]; + +export type MarketApiListMarketsData = { + body?: never; + path?: never; + query?: never; + url: '/api/market/'; +}; + +export type MarketApiListMarketsResponses = { + /** + * Response + * + * OK + */ + 200: Array; +}; + +export type MarketApiListMarketsResponse = MarketApiListMarketsResponses[keyof MarketApiListMarketsResponses]; + +export type MarketApiListUserBetsData = { + body?: never; + path?: never; + query?: never; + url: '/api/market/user/bets'; +}; + +export type MarketApiListUserBetsResponses = { + /** + * Response + * + * OK + */ + 200: Array; +}; + +export type MarketApiListUserBetsResponse = MarketApiListUserBetsResponses[keyof MarketApiListUserBetsResponses]; + +export type MarketApiCloseMarketData = { + body?: never; + path: { + /** + * Market Uuid + */ + market_uuid: string; + }; + query?: never; + url: '/api/market/{market_uuid}/actions/close'; +}; + +export type MarketApiCloseMarketResponses = { + /** + * OK + */ + 200: unknown; +}; + +export type MarketApiResolveMarketData = { + body: ResolveMarketSchema; + path: { + /** + * Market Uuid + */ + market_uuid: string; + }; + query?: never; + url: '/api/market/{market_uuid}/actions/resolve'; +}; + +export type MarketApiResolveMarketResponses = { + /** + * OK + */ + 200: MarketListSchema; +}; + +export type MarketApiResolveMarketResponse = MarketApiResolveMarketResponses[keyof MarketApiResolveMarketResponses]; + +export type MarketApiCreateBetData = { + body: UserBetCreateSchema; + path: { + /** + * Market Uuid + */ + market_uuid: string; + }; + query?: never; + url: '/api/market/{market_uuid}/bets'; +}; + +export type MarketApiCreateBetResponses = { + /** + * OK + */ + 200: UserBetSchema; +}; + +export type MarketApiCreateBetResponse = MarketApiCreateBetResponses[keyof MarketApiCreateBetResponses];