import {z} from 'zod' export type GetApiScriptByNameModeNameArgs = {name: string, mode: 'json' | 'raw', withoutText?: boolean | undefined}; export type GetApiScriptByNameModeNameOptions = {baseUrl?: string | undefined, internalApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiScriptByNameModeNameResponse = z.object({status: z.string().optional(), data: z.object({id: z.number().optional(), name: z.string().optional(), source: z.string().optional(), url: z.object({}).optional(), text: z.string().optional(), httpHeaders: z.object({}).optional(), lastSaveDate: z.number().optional(), nonce: z.number().optional()}).optional()}); 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 }; /** * Get a script record by its name. * * GET /script/by-name/{mode}/{name} */ export const getApiScriptByNameModeName = async (args: GetApiScriptByNameModeNameArgs, options?: GetApiScriptByNameModeNameOptions) => { const {baseUrl = "https://api.phantombuster.com/api/v2", fetch: fetchFn = fetch, internalApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.withoutText != null) query.append("withoutText", String(args.withoutText)) if (internalApiKey !== undefined) headers.set("X-Phantombuster-Key-1", internalApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/script/by-name/${encodeURIComponent(String(args.mode))}/${encodeURIComponent(String(args.name))}${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(getApiScriptByNameModeNameResponse, await res.json()) };