import {z} from 'zod' export type Region = 'JP' | 'NA' | 'CN' | 'KR' | 'TW'; export type GetApiRawRegionScriptSearchArgs = {region: Region, query: string, scriptFileName?: (string | null) | undefined, rawScript?: (boolean | null) | undefined, warId?: Array | undefined, limit?: (number | null) | undefined}; export type GetApiRawRegionScriptSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const scriptSearchResult = z.object({scriptId: z.string(), score: z.number(), snippets: z.array(z.string())}); export const getApiRawRegionScriptSearchResponse = z.array(scriptSearchResult); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Find and get script data * * GET /raw/{region}/script/search */ export const getApiRawRegionScriptSearch = async (args: GetApiRawRegionScriptSearchArgs, options?: GetApiRawRegionScriptSearchOptions) => { const {baseUrl = "https://api.atlasacademy.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (args.scriptFileName != null) query.append("scriptFileName", String(args.scriptFileName)) if (args.rawScript != null) query.append("rawScript", String(args.rawScript)) for (const item of args.warId ?? []) query.append("warId", String(item)) if (args.limit != null) query.append("limit", String(args.limit)) const url = `${baseUrl.replace(/\/+$/, '')}/raw/${encodeURIComponent(String(args.region))}/script/search${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiRawRegionScriptSearchResponse, await res.json()) };