@trigger.dev/core 0.0.0-prerelease-20240418145424 → 0.0.0-prerelease-20240528152213
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog-BUwiuDbt.d.mts +202 -0
- package/dist/catalog-eKgqBHUA.d.ts +202 -0
- package/dist/index.d.mts +60 -1
- package/dist/index.d.ts +60 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -1
- package/dist/index.mjs.map +1 -1
- package/dist/manager-uPyMRN8k.d.mts +1159 -0
- package/dist/manager-uPyMRN8k.d.ts +1159 -0
- package/dist/messages-l9PdIyKF.d.mts +16741 -0
- package/dist/messages-l9PdIyKF.d.ts +16741 -0
- package/dist/schemas-b8tRw8dX.d.mts +2331 -0
- package/dist/schemas-b8tRw8dX.d.ts +2331 -0
- package/dist/v3/dev/index.d.mts +28 -0
- package/dist/v3/dev/index.d.ts +28 -0
- package/dist/v3/dev/index.js +93 -0
- package/dist/v3/dev/index.js.map +1 -0
- package/dist/v3/dev/index.mjs +91 -0
- package/dist/v3/dev/index.mjs.map +1 -0
- package/dist/v3/index.d.mts +517 -17166
- package/dist/v3/index.d.ts +517 -17166
- package/dist/v3/index.js +1591 -2828
- package/dist/v3/index.js.map +1 -1
- package/dist/v3/index.mjs +1580 -2802
- package/dist/v3/index.mjs.map +1 -1
- package/dist/v3/otel/index.js +85 -44
- package/dist/v3/otel/index.js.map +1 -1
- package/dist/v3/otel/index.mjs +85 -44
- package/dist/v3/otel/index.mjs.map +1 -1
- package/dist/v3/prod/index.d.mts +45 -0
- package/dist/v3/prod/index.d.ts +45 -0
- package/dist/v3/prod/index.js +304 -0
- package/dist/v3/prod/index.js.map +1 -0
- package/dist/v3/prod/index.mjs +302 -0
- package/dist/v3/prod/index.mjs.map +1 -0
- package/dist/v3/utils/structuredLogger.d.mts +31 -0
- package/dist/v3/utils/structuredLogger.d.ts +31 -0
- package/dist/v3/utils/structuredLogger.js +88 -0
- package/dist/v3/utils/structuredLogger.js.map +1 -0
- package/dist/v3/utils/structuredLogger.mjs +86 -0
- package/dist/v3/utils/structuredLogger.mjs.map +1 -0
- package/dist/v3/workers/index.d.mts +96 -0
- package/dist/v3/workers/index.d.ts +96 -0
- package/dist/v3/workers/index.js +2831 -0
- package/dist/v3/workers/index.js.map +1 -0
- package/dist/v3/workers/index.mjs +2815 -0
- package/dist/v3/workers/index.mjs.map +1 -0
- package/dist/v3/zodIpc.d.mts +32 -0
- package/dist/v3/zodIpc.d.ts +32 -0
- package/dist/v3/zodIpc.js +268 -0
- package/dist/v3/zodIpc.js.map +1 -0
- package/dist/v3/zodIpc.mjs +266 -0
- package/dist/v3/zodIpc.mjs.map +1 -0
- package/dist/v3/zodMessageHandler.d.mts +69 -0
- package/dist/v3/zodMessageHandler.d.ts +69 -0
- package/dist/v3/zodMessageHandler.js +168 -0
- package/dist/v3/zodMessageHandler.js.map +1 -0
- package/dist/v3/zodMessageHandler.mjs +163 -0
- package/dist/v3/zodMessageHandler.mjs.map +1 -0
- package/dist/v3/zodNamespace.d.mts +3663 -0
- package/dist/v3/zodNamespace.d.ts +3663 -0
- package/dist/v3/zodNamespace.js +366 -0
- package/dist/v3/zodNamespace.js.map +1 -0
- package/dist/v3/zodNamespace.mjs +364 -0
- package/dist/v3/zodNamespace.mjs.map +1 -0
- package/dist/v3/zodSocket.d.mts +88 -0
- package/dist/v3/zodSocket.d.ts +88 -0
- package/dist/v3/zodSocket.js +319 -0
- package/dist/v3/zodSocket.js.map +1 -0
- package/dist/v3/zodSocket.mjs +315 -0
- package/dist/v3/zodSocket.mjs.map +1 -0
- package/dist/v3/zodfetch.d.mts +78 -0
- package/dist/v3/zodfetch.d.ts +78 -0
- package/dist/v3/zodfetch.js +446 -0
- package/dist/v3/zodfetch.js.map +1 -0
- package/dist/v3/zodfetch.mjs +433 -0
- package/dist/v3/zodfetch.mjs.map +1 -0
- package/package.json +77 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/v3/zodSocket.ts","../../src/v3/utils/structuredLogger.ts"],"names":["io","ZodError","z","LogLevel","SimpleStructuredLogger","constructor","name","level","includes","process","env","DEBUG","debug","info","fields","child","log","message","args","console","error","warn","loggerFunction","structuredLog","length","timestamp","Date","JSON","stringify","fromZodError","messageSchema","object","version","string","type","payload","unknown","ZodSocketMessageHandler","options","schema","handlers","handleMessage","parsedMessage","parseMessage","Error","handler","String","ack","safeParse","success","data","messageWithVersion","parsedPayload","registerHandlers","emitter","logger","eventName","Object","keys","on","callback","hasCallback","stack","_schema","ZodSocketMessageSender","socket","send","emit","sendWithAck","callbackResult","emitWithAck","ZodSocketConnection","opts","uri","secure","host","port","namespace","transports","auth","token","authToken","extraHeaders","reconnectionDelay","reconnectionDelayMax","socketId","id","serverMessages","clientMessages","onError","onConnection","reason","description","onDisconnect","close","connect","bind"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,UAAU;AACnB,SAASC,UAAUC,SAAS;;;ICSrB;UAAKC,WAAQ;AAARA,EAAAA,UAAAA,UACV,KAAA,IAAA,CAAA,IAAA;AADUA,EAAAA,UAAAA,UAEV,OAAA,IAAA,CAAA,IAAA;AAFUA,EAAAA,UAAAA,UAGV,MAAA,IAAA,CAAA,IAAA;AAHUA,EAAAA,UAAAA,UAIV,MAAA,IAAA,CAAA,IAAA;AAJUA,EAAAA,UAAAA,UAKV,OAAA,IAAA,CAAA,IAAA;GALUA,aAAAA,WAAAA,CAAAA,EAAAA;;AAQL,IAAMC,0BAAN,MAAMA,wBAAAA;EACXC,YACUC,MACAC,QAAkB;IAAC;IAAK;IAAQC,SAASC,QAAQC,IAAIC,SAAS,EAAA,IAClER,SAASS,QACTT,SAASU,MACLC,QACR;AAoCF;gBAzCUR;iBACAC;kBAGAO;EACP;EAEHC,MAAMD,QAAiCP,OAAkB;AACvD,WAAO,IAAIH,wBAAuB,KAAKE,MAAMC,OAAO;MAAE,GAAG,KA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EA,IAAI5B,cAAc;AAChB,WAAO,mBAAK,SAAQA,YAAY4B,KAAK,mBAAK,QAAO;EACnD;AACF;AA/EE;AAGA;AACA;AARWzB;AAAN,IAAMA,sBAAN","sourcesContent":["import type { Socket } from \"socket.io-client\";\nimport { io } from \"socket.io-client\";\nimport { ZodError, z } from \"zod\";\nimport { EventEmitterLike, ZodMessageValueSchema } from \"./zodMessageHandler\";\nimport { LogLevel, SimpleStructuredLogger, StructuredLogger } from \"./utils/structuredLogger\";\nimport { fromZodError } from \"zod-validation-error\";\n\nexport interface ZodSocketMessageCatalogSchema {\n [key: string]:\n | {\n message: ZodMessageValueSchema<any>;\n }\n | {\n message: ZodMessageValueSchema<any>;\n callback?: ZodMessageValueSchema<any>;\n };\n}\n\nexport type ZodMessageCatalogToSocketIoEvents<TCatalog extends ZodSocketMessageCatalogSchema> = {\n [K in keyof TCatalog]: SocketMessageHasCallback<TCatalog, K> extends true\n ? (\n message: z.infer<GetSocketMessageSchema<TCatalog, K>>,\n callback: (ack: z.infer<GetSocketCallbackSchema<TCatalog, K>>) => void\n ) => void\n : (message: z.infer<GetSocketMessageSchema<TCatalog, K>>) => void;\n};\n\nexport type GetSocketMessageSchema<\n TRPCCatalog extends ZodSocketMessageCatalogSchema,\n TMessageType extends keyof TRPCCatalog,\n> = TRPCCatalog[TMessageType][\"message\"];\n\nexport type InferSocketMessageSchema<\n TRPCCatalog extends ZodSocketMessageCatalogSchema,\n TMessageType extends keyof TRPCCatalog,\n> = z.infer<GetSocketMessageSchema<TRPCCatalog, TMessageType>>;\n\nexport type GetSocketCallbackSchema<\n TRPCCatalog extends ZodSocketMessageCatalogSchema,\n TMessageType extends keyof TRPCCatalog,\n> = TRPCCatalog[TMessageType] extends { callback: any }\n ? TRPCCatalog[TMessageType][\"callback\"]\n : never;\n\nexport type InferSocketCallbackSchema<\n TRPCCatalog extends ZodSocketMessageCatalogSchema,\n TMessageType extends keyof TRPCCatalog,\n> = z.infer<GetSocketCallbackSchema<TRPCCatalog, TMessageType>>;\n\nexport type SocketMessageHasCallback<\n TRPCCatalog extends ZodSocketMessageCatalogSchema,\n TMessageType extends keyof TRPCCatalog,\n> = GetSocketCallbackSchema<TRPCCatalog, TMessageType> extends never ? false : true;\n\nexport type ZodSocketMessageHandlers<TCatalogSchema extends ZodSocketMessageCatalogSchema> =\n Partial<{\n [K in keyof TCatalogSchema]: (\n payload: z.infer<GetSocketMessageSchema<TCatalogSchema, K>>\n ) => Promise<\n SocketMessageHasCallback<TCatalogSchema, K> extends true\n ? z.input<GetSocketCallbackSchema<TCatalogSchema, K>>\n : void\n >;\n }>;\n\nexport type ZodSocketMessageHandlerOptions<TMessageCatalog extends ZodSocketMessageCatalogSchema> =\n {\n schema: TMessageCatalog;\n handlers?: ZodSocketMessageHandlers<TMessageCatalog>;\n };\n\ntype MessageFromSocketSchema<\n K extends keyof TMessageCatalog,\n TMessageCatalog extends ZodSocketMessageCatalogSchema,\n> = {\n type: K;\n payload: z.input<GetSocketMessageSchema<TMessageCatalog, K>>;\n};\n\nexport type MessagesFromSocketCatalog<TMessageCatalog extends ZodSocketMessageCatalogSchema> = {\n [K in keyof TMessageCatalog]: MessageFromSocketSchema<K, TMessageCatalog>;\n}[keyof TMessageCatalog];\n\nconst messageSchema = z.object({\n version: z.string(),\n type: z.string(),\n payload: z.unknown(),\n});\n\nexport class ZodSocketMessageHandler<TRPCCatalog extends ZodSocketMessageCatalogSchema> {\n #schema: TRPCCatalog;\n #handlers: ZodSocketMessageHandlers<TRPCCatalog> | undefined;\n\n constructor(options: ZodSocketMessageHandlerOptions<TRPCCatalog>) {\n this.#schema = options.schema;\n this.#handlers = options.handlers;\n }\n\n public async handleMessage(message: unknown) {\n const parsedMessage = this.parseMessage(message);\n\n if (!this.#handlers) {\n throw new Error(\"No handlers provided\");\n }\n\n const handler = this.#handlers[parsedMessage.type];\n\n if (!handler) {\n console.error(`No handler for message type: ${String(parsedMessage.type)}`);\n return;\n }\n\n const ack = await handler(parsedMessage.payload);\n\n return ack;\n }\n\n public parseMessage(message: unknown): MessagesFromSocketCatalog<TRPCCatalog> {\n const parsedMessage = messageSchema.safeParse(message);\n\n if (!parsedMessage.success) {\n throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);\n }\n\n const schema = this.#schema[parsedMessage.data.type][\"message\"];\n\n if (!schema) {\n throw new Error(`Unknown message type: ${parsedMessage.data.type}`);\n }\n\n const messageWithVersion = {\n version: parsedMessage.data.version,\n ...(typeof parsedMessage.data.payload === \"object\" ? parsedMessage.data.payload : {}),\n };\n\n const parsedPayload = schema.safeParse(messageWithVersion);\n\n if (!parsedPayload.success) {\n console.error(\"Failed to parse message payload\", {\n message,\n payload: messageWithVersion,\n });\n\n throw parsedPayload.error instanceof ZodError\n ? fromZodError(parsedPayload.error)\n : parsedPayload.error;\n }\n\n return {\n type: parsedMessage.data.type,\n payload: parsedPayload.data,\n };\n }\n\n public registerHandlers(emitter: EventEmitterLike, logger?: StructuredLogger) {\n const log = logger ?? console;\n\n if (!this.#handlers) {\n log.info(\"No handlers provided\");\n return;\n }\n\n for (const eventName of Object.keys(this.#handlers)) {\n emitter.on(eventName, async (message: any, callback?: any): Promise<void> => {\n log.info(`handling ${eventName}`, {\n payload: message,\n hasCallback: !!callback,\n });\n\n let ack;\n\n try {\n // FIXME: this only works if the message doesn't have genuine payload prop\n if (\"payload\" in message) {\n ack = await this.handleMessage({ type: eventName, ...message });\n } else {\n // Handle messages not sent by ZodMessageSender\n const { version, ...payload } = message;\n ack = await this.handleMessage({ type: eventName, version, payload });\n }\n } catch (error) {\n log.error(\"Error while handling message\", {\n error:\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n }\n : error,\n });\n return;\n }\n\n if (callback && typeof callback === \"function\") {\n callback(ack);\n }\n });\n }\n }\n}\n\nexport type ZodSocketMessageSenderOptions<TMessageCatalog extends ZodSocketMessageCatalogSchema> = {\n schema: TMessageCatalog;\n socket: ZodSocket<any, TMessageCatalog>;\n};\n\nexport type GetSocketMessagesWithCallback<TMessageCatalog extends ZodSocketMessageCatalogSchema> = {\n [K in keyof TMessageCatalog]: SocketMessageHasCallback<TMessageCatalog, K> extends true\n ? K\n : never;\n}[keyof TMessageCatalog];\n\nexport type GetSocketMessagesWithoutCallback<\n TMessageCatalog extends ZodSocketMessageCatalogSchema,\n> = {\n [K in keyof TMessageCatalog]: SocketMessageHasCallback<TMessageCatalog, K> extends true\n ? never\n : K;\n}[keyof TMessageCatalog];\n\nexport class ZodSocketMessageSender<TMessageCatalog extends ZodSocketMessageCatalogSchema> {\n #schema: TMessageCatalog;\n #socket: ZodSocket<any, TMessageCatalog>;\n\n constructor(options: ZodSocketMessageSenderOptions<TMessageCatalog>) {\n this.#schema = options.schema;\n this.#socket = options.socket;\n }\n\n public send<K extends GetSocketMessagesWithoutCallback<TMessageCatalog>>(\n type: K,\n payload: z.input<GetSocketMessageSchema<TMessageCatalog, K>>\n ): void {\n const schema = this.#schema[type][\"message\"];\n\n if (!schema) {\n throw new Error(`Unknown message type: ${type as string}`);\n }\n\n const parsedPayload = schema.safeParse(payload);\n\n if (!parsedPayload.success) {\n throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);\n }\n\n // @ts-expect-error\n this.#socket.emit(type, { payload, version: \"v1\" });\n\n return;\n }\n\n public async sendWithAck<K extends GetSocketMessagesWithCallback<TMessageCatalog>>(\n type: K,\n payload: z.input<GetSocketMessageSchema<TMessageCatalog, K>>\n ): Promise<z.infer<GetSocketCallbackSchema<TMessageCatalog, K>>> {\n const schema = this.#schema[type][\"message\"];\n\n if (!schema) {\n throw new Error(`Unknown message type: ${type as string}`);\n }\n\n const parsedPayload = schema.safeParse(payload);\n\n if (!parsedPayload.success) {\n throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);\n }\n\n // @ts-expect-error\n const callbackResult = await this.#socket.emitWithAck(type, { payload, version: \"v1\" });\n\n return callbackResult;\n }\n}\n\nexport type ZodSocket<\n TListenEvents extends ZodSocketMessageCatalogSchema,\n TEmitEvents extends ZodSocketMessageCatalogSchema,\n> = Socket<\n ZodMessageCatalogToSocketIoEvents<TListenEvents>,\n ZodMessageCatalogToSocketIoEvents<TEmitEvents>\n>;\n\ninterface ZodSocketConnectionOptions<\n TClientMessages extends ZodSocketMessageCatalogSchema,\n TServerMessages extends ZodSocketMessageCatalogSchema,\n> {\n host: string;\n port?: number;\n secure?: boolean;\n namespace: string;\n clientMessages: TClientMessages;\n serverMessages: TServerMessages;\n extraHeaders?: {\n [header: string]: string;\n };\n handlers?: ZodSocketMessageHandlers<TServerMessages>;\n authToken?: string;\n onConnection?: (\n socket: ZodSocket<TServerMessages, TClientMessages>,\n handler: ZodSocketMessageHandler<TServerMessages>,\n sender: ZodSocketMessageSender<TClientMessages>,\n logger: StructuredLogger\n ) => Promise<void>;\n onDisconnect?: (\n socket: ZodSocket<TServerMessages, TClientMessages>,\n reason: Socket.DisconnectReason,\n description: any,\n logger: StructuredLogger\n ) => Promise<void>;\n onError?: (\n socket: ZodSocket<TServerMessages, TClientMessages>,\n err: Error,\n logger: StructuredLogger\n ) => Promise<void>;\n}\n\nexport class ZodSocketConnection<\n TClientMessages extends ZodSocketMessageCatalogSchema,\n TServerMessages extends ZodSocketMessageCatalogSchema,\n> {\n #sender: ZodSocketMessageSender<TClientMessages>;\n socket: ZodSocket<TServerMessages, TClientMessages>;\n\n #handler: ZodSocketMessageHandler<TServerMessages>;\n #logger: StructuredLogger;\n\n constructor(opts: ZodSocketConnectionOptions<TClientMessages, TServerMessages>) {\n const uri = `${opts.secure ? \"wss\" : \"ws\"}://${opts.host}:${\n opts.port ?? (opts.secure ? \"443\" : \"80\")\n }/${opts.namespace}`;\n\n const logger = new SimpleStructuredLogger(opts.namespace, LogLevel.info);\n logger.log(\"new zod socket\", { uri });\n\n this.socket = io(uri, {\n transports: [\"websocket\"],\n auth: {\n token: opts.authToken,\n },\n extraHeaders: opts.extraHeaders,\n reconnectionDelay: 500,\n reconnectionDelayMax: 1000,\n });\n\n this.#logger = logger.child({\n socketId: this.socket.id,\n });\n\n this.#handler = new ZodSocketMessageHandler({\n schema: opts.serverMessages,\n handlers: opts.handlers,\n });\n this.#handler.registerHandlers(this.socket, this.#logger);\n\n this.#sender = new ZodSocketMessageSender({\n schema: opts.clientMessages,\n socket: this.socket,\n });\n\n this.socket.on(\"connect_error\", async (error) => {\n this.#logger.error(`connect_error: ${error}`);\n\n if (opts.onError) {\n await opts.onError(this.socket, error, this.#logger);\n }\n });\n\n this.socket.on(\"connect\", async () => {\n this.#logger.info(\"connect\");\n\n if (opts.onConnection) {\n await opts.onConnection(this.socket, this.#handler, this.#sender, this.#logger);\n }\n });\n\n this.socket.on(\"disconnect\", async (reason, description) => {\n this.#logger.info(\"disconnect\", { reason, description });\n\n if (opts.onDisconnect) {\n await opts.onDisconnect(this.socket, reason, description, this.#logger);\n }\n });\n }\n\n close() {\n this.socket.close();\n }\n\n connect() {\n this.socket.connect();\n }\n\n get send() {\n return this.#sender.send.bind(this.#sender);\n }\n\n get sendWithAck() {\n return this.#sender.sendWithAck.bind(this.#sender);\n }\n}\n\nfunction createLogger(prefix: string) {\n return (...args: any[]) => console.log(prefix, ...args);\n}\n","type StructuredArgs = (Record<string, unknown> | undefined)[];\n\nexport interface StructuredLogger {\n log: (message: string, ...args: StructuredArgs) => any;\n error: (message: string, ...args: StructuredArgs) => any;\n warn: (message: string, ...args: StructuredArgs) => any;\n info: (message: string, ...args: StructuredArgs) => any;\n debug: (message: string, ...args: StructuredArgs) => any;\n child: (fields: Record<string, unknown>) => StructuredLogger;\n}\n\nexport enum LogLevel {\n \"log\",\n \"error\",\n \"warn\",\n \"info\",\n \"debug\",\n}\n\nexport class SimpleStructuredLogger implements StructuredLogger {\n constructor(\n private name: string,\n private level: LogLevel = [\"1\", \"true\"].includes(process.env.DEBUG ?? \"\")\n ? LogLevel.debug\n : LogLevel.info,\n private fields?: Record<string, unknown>\n ) {}\n\n child(fields: Record<string, unknown>, level?: LogLevel) {\n return new SimpleStructuredLogger(this.name, level, { ...this.fields, ...fields });\n }\n\n log(message: string, ...args: StructuredArgs) {\n if (this.level < LogLevel.log) return;\n\n this.#structuredLog(console.log, message, \"log\", ...args);\n }\n\n error(message: string, ...args: StructuredArgs) {\n if (this.level < LogLevel.error) return;\n\n this.#structuredLog(console.error, message, \"error\", ...args);\n }\n\n warn(message: string, ...args: StructuredArgs) {\n if (this.level < LogLevel.warn) return;\n\n this.#structuredLog(console.warn, message, \"warn\", ...args);\n }\n\n info(message: string, ...args: StructuredArgs) {\n if (this.level < LogLevel.info) return;\n\n this.#structuredLog(console.info, message, \"info\", ...args);\n }\n\n debug(message: string, ...args: StructuredArgs) {\n if (this.level < LogLevel.debug) return;\n\n this.#structuredLog(console.debug, message, \"debug\", ...args);\n }\n\n #structuredLog(\n loggerFunction: (message: string, ...args: any[]) => void,\n message: string,\n level: string,\n ...args: StructuredArgs\n ) {\n const structuredLog = {\n ...(args.length === 1 ? args[0] : args),\n ...this.fields,\n timestamp: new Date(),\n name: this.name,\n message,\n level,\n };\n\n loggerFunction(JSON.stringify(structuredLog));\n }\n}\n"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { R as RetryOptions } from '../schemas-b8tRw8dX.mjs';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
|
|
5
|
+
declare const defaultRetryOptions: {
|
|
6
|
+
maxAttempts: number;
|
|
7
|
+
factor: number;
|
|
8
|
+
minTimeoutInMs: number;
|
|
9
|
+
maxTimeoutInMs: number;
|
|
10
|
+
randomize: false;
|
|
11
|
+
};
|
|
12
|
+
type ZodFetchOptions = {
|
|
13
|
+
retry?: RetryOptions;
|
|
14
|
+
};
|
|
15
|
+
declare function zodfetch<TResponseBodySchema extends z.ZodTypeAny>(schema: TResponseBodySchema, url: string, requestInit?: RequestInit, options?: ZodFetchOptions): Promise<z.output<TResponseBodySchema>>;
|
|
16
|
+
declare class MultipartBody {
|
|
17
|
+
body: any;
|
|
18
|
+
constructor(body: any);
|
|
19
|
+
get [Symbol.toStringTag](): string;
|
|
20
|
+
}
|
|
21
|
+
declare function zodupload<TResponseBodySchema extends z.ZodTypeAny, TBody = Record<string, unknown>>(schema: TResponseBodySchema, url: string, body: TBody, requestInit?: RequestInit, options?: ZodFetchOptions): Promise<z.output<TResponseBodySchema>>;
|
|
22
|
+
declare const createForm: <T = Record<string, unknown>>(body: T | undefined) => Promise<FormData>;
|
|
23
|
+
type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;
|
|
24
|
+
/**
|
|
25
|
+
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
26
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s
|
|
27
|
+
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
28
|
+
* @param {Object=} options additional properties
|
|
29
|
+
* @param {string=} options.type the MIME type of the content
|
|
30
|
+
* @param {number=} options.lastModified the last modified timestamp
|
|
31
|
+
* @returns a {@link File} with the given properties
|
|
32
|
+
*/
|
|
33
|
+
declare function toFile(value: ToFileInput | PromiseLike<ToFileInput>, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise<FileLike>;
|
|
34
|
+
/**
|
|
35
|
+
* Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.
|
|
36
|
+
*/
|
|
37
|
+
interface BlobLike {
|
|
38
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */
|
|
39
|
+
readonly size: number;
|
|
40
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */
|
|
41
|
+
readonly type: string;
|
|
42
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */
|
|
43
|
+
text(): Promise<string>;
|
|
44
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */
|
|
45
|
+
slice(start?: number, end?: number): BlobLike;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Intended to match web.File, node.File, node-fetch.File, etc.
|
|
49
|
+
*/
|
|
50
|
+
interface FileLike extends BlobLike {
|
|
51
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */
|
|
52
|
+
readonly lastModified: number;
|
|
53
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */
|
|
54
|
+
readonly name: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Intended to match web.Response, node.Response, node-fetch.Response, etc.
|
|
58
|
+
*/
|
|
59
|
+
interface ResponseLike {
|
|
60
|
+
url: string;
|
|
61
|
+
blob(): Promise<BlobLike>;
|
|
62
|
+
}
|
|
63
|
+
type Uploadable = FileLike | ResponseLike | Readable;
|
|
64
|
+
declare const isResponseLike: (value: any) => value is ResponseLike;
|
|
65
|
+
declare const isFileLike: (value: any) => value is FileLike;
|
|
66
|
+
/**
|
|
67
|
+
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
|
|
68
|
+
* adds the arrayBuffer() method type because it is available and used at runtime
|
|
69
|
+
*/
|
|
70
|
+
declare const isBlobLike: (value: any) => value is BlobLike & {
|
|
71
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
72
|
+
};
|
|
73
|
+
declare const isFsReadStream: (value: any) => value is Readable;
|
|
74
|
+
declare const isUploadable: (value: any) => value is Uploadable;
|
|
75
|
+
type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;
|
|
76
|
+
declare const isRecordLike: (value: any) => value is Record<string, string>;
|
|
77
|
+
|
|
78
|
+
export { type BlobLike, type BlobLikePart, type FileLike, MultipartBody, type ResponseLike, type ToFileInput, type Uploadable, type ZodFetchOptions, createForm, defaultRetryOptions, isBlobLike, isFileLike, isFsReadStream, isRecordLike, isResponseLike, isUploadable, toFile, zodfetch, zodupload };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { R as RetryOptions } from '../schemas-b8tRw8dX.js';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
|
|
5
|
+
declare const defaultRetryOptions: {
|
|
6
|
+
maxAttempts: number;
|
|
7
|
+
factor: number;
|
|
8
|
+
minTimeoutInMs: number;
|
|
9
|
+
maxTimeoutInMs: number;
|
|
10
|
+
randomize: false;
|
|
11
|
+
};
|
|
12
|
+
type ZodFetchOptions = {
|
|
13
|
+
retry?: RetryOptions;
|
|
14
|
+
};
|
|
15
|
+
declare function zodfetch<TResponseBodySchema extends z.ZodTypeAny>(schema: TResponseBodySchema, url: string, requestInit?: RequestInit, options?: ZodFetchOptions): Promise<z.output<TResponseBodySchema>>;
|
|
16
|
+
declare class MultipartBody {
|
|
17
|
+
body: any;
|
|
18
|
+
constructor(body: any);
|
|
19
|
+
get [Symbol.toStringTag](): string;
|
|
20
|
+
}
|
|
21
|
+
declare function zodupload<TResponseBodySchema extends z.ZodTypeAny, TBody = Record<string, unknown>>(schema: TResponseBodySchema, url: string, body: TBody, requestInit?: RequestInit, options?: ZodFetchOptions): Promise<z.output<TResponseBodySchema>>;
|
|
22
|
+
declare const createForm: <T = Record<string, unknown>>(body: T | undefined) => Promise<FormData>;
|
|
23
|
+
type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;
|
|
24
|
+
/**
|
|
25
|
+
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
26
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s
|
|
27
|
+
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
28
|
+
* @param {Object=} options additional properties
|
|
29
|
+
* @param {string=} options.type the MIME type of the content
|
|
30
|
+
* @param {number=} options.lastModified the last modified timestamp
|
|
31
|
+
* @returns a {@link File} with the given properties
|
|
32
|
+
*/
|
|
33
|
+
declare function toFile(value: ToFileInput | PromiseLike<ToFileInput>, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise<FileLike>;
|
|
34
|
+
/**
|
|
35
|
+
* Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.
|
|
36
|
+
*/
|
|
37
|
+
interface BlobLike {
|
|
38
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */
|
|
39
|
+
readonly size: number;
|
|
40
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */
|
|
41
|
+
readonly type: string;
|
|
42
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */
|
|
43
|
+
text(): Promise<string>;
|
|
44
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */
|
|
45
|
+
slice(start?: number, end?: number): BlobLike;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Intended to match web.File, node.File, node-fetch.File, etc.
|
|
49
|
+
*/
|
|
50
|
+
interface FileLike extends BlobLike {
|
|
51
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */
|
|
52
|
+
readonly lastModified: number;
|
|
53
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */
|
|
54
|
+
readonly name: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Intended to match web.Response, node.Response, node-fetch.Response, etc.
|
|
58
|
+
*/
|
|
59
|
+
interface ResponseLike {
|
|
60
|
+
url: string;
|
|
61
|
+
blob(): Promise<BlobLike>;
|
|
62
|
+
}
|
|
63
|
+
type Uploadable = FileLike | ResponseLike | Readable;
|
|
64
|
+
declare const isResponseLike: (value: any) => value is ResponseLike;
|
|
65
|
+
declare const isFileLike: (value: any) => value is FileLike;
|
|
66
|
+
/**
|
|
67
|
+
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
|
|
68
|
+
* adds the arrayBuffer() method type because it is available and used at runtime
|
|
69
|
+
*/
|
|
70
|
+
declare const isBlobLike: (value: any) => value is BlobLike & {
|
|
71
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
72
|
+
};
|
|
73
|
+
declare const isFsReadStream: (value: any) => value is Readable;
|
|
74
|
+
declare const isUploadable: (value: any) => value is Uploadable;
|
|
75
|
+
type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;
|
|
76
|
+
declare const isRecordLike: (value: any) => value is Record<string, string>;
|
|
77
|
+
|
|
78
|
+
export { type BlobLike, type BlobLikePart, type FileLike, MultipartBody, type ResponseLike, type ToFileInput, type Uploadable, type ZodFetchOptions, createForm, defaultRetryOptions, isBlobLike, isFileLike, isFsReadStream, isRecordLike, isResponseLike, isUploadable, toFile, zodfetch, zodupload };
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zodValidationError = require('zod-validation-error');
|
|
4
|
+
var formDataEncoder = require('form-data-encoder');
|
|
5
|
+
var stream = require('stream');
|
|
6
|
+
|
|
7
|
+
var __defProp = Object.defineProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
+
var __publicField = (obj, key, value) => {
|
|
11
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// src/v3/apiErrors.ts
|
|
16
|
+
var _APIError = class _APIError extends Error {
|
|
17
|
+
constructor(status, error, message, headers) {
|
|
18
|
+
super(`${_APIError.makeMessage(status, error, message)}`);
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.headers = headers;
|
|
21
|
+
const data = error;
|
|
22
|
+
this.error = data;
|
|
23
|
+
this.code = data?.["code"];
|
|
24
|
+
this.param = data?.["param"];
|
|
25
|
+
this.type = data?.["type"];
|
|
26
|
+
}
|
|
27
|
+
static makeMessage(status, error, message) {
|
|
28
|
+
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
|
|
29
|
+
if (status && msg) {
|
|
30
|
+
return `${status} ${msg}`;
|
|
31
|
+
}
|
|
32
|
+
if (status) {
|
|
33
|
+
return `${status} status code (no body)`;
|
|
34
|
+
}
|
|
35
|
+
if (msg) {
|
|
36
|
+
return msg;
|
|
37
|
+
}
|
|
38
|
+
return "(no status code or body)";
|
|
39
|
+
}
|
|
40
|
+
static generate(status, errorResponse, message, headers) {
|
|
41
|
+
if (!status) {
|
|
42
|
+
return new APIConnectionError({
|
|
43
|
+
cause: castToError(errorResponse)
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const error = errorResponse?.["error"];
|
|
47
|
+
if (status === 400) {
|
|
48
|
+
return new BadRequestError(status, error, message, headers);
|
|
49
|
+
}
|
|
50
|
+
if (status === 401) {
|
|
51
|
+
return new AuthenticationError(status, error, message, headers);
|
|
52
|
+
}
|
|
53
|
+
if (status === 403) {
|
|
54
|
+
return new PermissionDeniedError(status, error, message, headers);
|
|
55
|
+
}
|
|
56
|
+
if (status === 404) {
|
|
57
|
+
return new NotFoundError(status, error, message, headers);
|
|
58
|
+
}
|
|
59
|
+
if (status === 409) {
|
|
60
|
+
return new ConflictError(status, error, message, headers);
|
|
61
|
+
}
|
|
62
|
+
if (status === 422) {
|
|
63
|
+
return new UnprocessableEntityError(status, error, message, headers);
|
|
64
|
+
}
|
|
65
|
+
if (status === 429) {
|
|
66
|
+
return new RateLimitError(status, error, message, headers);
|
|
67
|
+
}
|
|
68
|
+
if (status >= 500) {
|
|
69
|
+
return new InternalServerError(status, error, message, headers);
|
|
70
|
+
}
|
|
71
|
+
return new _APIError(status, error, message, headers);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
__name(_APIError, "APIError");
|
|
75
|
+
var APIError = _APIError;
|
|
76
|
+
var _APIConnectionError = class _APIConnectionError extends APIError {
|
|
77
|
+
constructor({ message, cause }) {
|
|
78
|
+
super(void 0, void 0, message || "Connection error.", void 0);
|
|
79
|
+
__publicField(this, "status");
|
|
80
|
+
if (cause)
|
|
81
|
+
this.cause = cause;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
__name(_APIConnectionError, "APIConnectionError");
|
|
85
|
+
var APIConnectionError = _APIConnectionError;
|
|
86
|
+
var _BadRequestError = class _BadRequestError extends APIError {
|
|
87
|
+
constructor() {
|
|
88
|
+
super(...arguments);
|
|
89
|
+
__publicField(this, "status", 400);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
__name(_BadRequestError, "BadRequestError");
|
|
93
|
+
var BadRequestError = _BadRequestError;
|
|
94
|
+
var _AuthenticationError = class _AuthenticationError extends APIError {
|
|
95
|
+
constructor() {
|
|
96
|
+
super(...arguments);
|
|
97
|
+
__publicField(this, "status", 401);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
__name(_AuthenticationError, "AuthenticationError");
|
|
101
|
+
var AuthenticationError = _AuthenticationError;
|
|
102
|
+
var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
|
|
103
|
+
constructor() {
|
|
104
|
+
super(...arguments);
|
|
105
|
+
__publicField(this, "status", 403);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
__name(_PermissionDeniedError, "PermissionDeniedError");
|
|
109
|
+
var PermissionDeniedError = _PermissionDeniedError;
|
|
110
|
+
var _NotFoundError = class _NotFoundError extends APIError {
|
|
111
|
+
constructor() {
|
|
112
|
+
super(...arguments);
|
|
113
|
+
__publicField(this, "status", 404);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
__name(_NotFoundError, "NotFoundError");
|
|
117
|
+
var NotFoundError = _NotFoundError;
|
|
118
|
+
var _ConflictError = class _ConflictError extends APIError {
|
|
119
|
+
constructor() {
|
|
120
|
+
super(...arguments);
|
|
121
|
+
__publicField(this, "status", 409);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
__name(_ConflictError, "ConflictError");
|
|
125
|
+
var ConflictError = _ConflictError;
|
|
126
|
+
var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
|
|
127
|
+
constructor() {
|
|
128
|
+
super(...arguments);
|
|
129
|
+
__publicField(this, "status", 422);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
__name(_UnprocessableEntityError, "UnprocessableEntityError");
|
|
133
|
+
var UnprocessableEntityError = _UnprocessableEntityError;
|
|
134
|
+
var _RateLimitError = class _RateLimitError extends APIError {
|
|
135
|
+
constructor() {
|
|
136
|
+
super(...arguments);
|
|
137
|
+
__publicField(this, "status", 429);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
__name(_RateLimitError, "RateLimitError");
|
|
141
|
+
var RateLimitError = _RateLimitError;
|
|
142
|
+
var _InternalServerError = class _InternalServerError extends APIError {
|
|
143
|
+
};
|
|
144
|
+
__name(_InternalServerError, "InternalServerError");
|
|
145
|
+
var InternalServerError = _InternalServerError;
|
|
146
|
+
function castToError(err) {
|
|
147
|
+
if (err instanceof Error)
|
|
148
|
+
return err;
|
|
149
|
+
return new Error(err);
|
|
150
|
+
}
|
|
151
|
+
__name(castToError, "castToError");
|
|
152
|
+
|
|
153
|
+
// src/v3/utils/retries.ts
|
|
154
|
+
var defaultRetryOptions = {
|
|
155
|
+
maxAttempts: 3,
|
|
156
|
+
factor: 2,
|
|
157
|
+
minTimeoutInMs: 1e3,
|
|
158
|
+
maxTimeoutInMs: 6e4,
|
|
159
|
+
randomize: true
|
|
160
|
+
};
|
|
161
|
+
function calculateNextRetryDelay(options, attempt) {
|
|
162
|
+
const opts = {
|
|
163
|
+
...defaultRetryOptions,
|
|
164
|
+
...options
|
|
165
|
+
};
|
|
166
|
+
if (attempt >= opts.maxAttempts) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
|
|
170
|
+
const random = randomize ? Math.random() + 1 : 1;
|
|
171
|
+
const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
|
|
172
|
+
return Math.round(timeout);
|
|
173
|
+
}
|
|
174
|
+
__name(calculateNextRetryDelay, "calculateNextRetryDelay");
|
|
175
|
+
var defaultRetryOptions2 = {
|
|
176
|
+
maxAttempts: 3,
|
|
177
|
+
factor: 2,
|
|
178
|
+
minTimeoutInMs: 1e3,
|
|
179
|
+
maxTimeoutInMs: 6e4,
|
|
180
|
+
randomize: false
|
|
181
|
+
};
|
|
182
|
+
async function zodfetch(schema, url, requestInit, options) {
|
|
183
|
+
return await _doZodFetch(schema, url, requestInit, options);
|
|
184
|
+
}
|
|
185
|
+
__name(zodfetch, "zodfetch");
|
|
186
|
+
var _MultipartBody = class _MultipartBody {
|
|
187
|
+
constructor(body) {
|
|
188
|
+
this.body = body;
|
|
189
|
+
}
|
|
190
|
+
get [Symbol.toStringTag]() {
|
|
191
|
+
return "MultipartBody";
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
__name(_MultipartBody, "MultipartBody");
|
|
195
|
+
var MultipartBody = _MultipartBody;
|
|
196
|
+
async function zodupload(schema, url, body, requestInit, options) {
|
|
197
|
+
const form = await createForm(body);
|
|
198
|
+
const encoder = new formDataEncoder.FormDataEncoder(form);
|
|
199
|
+
const finalHeaders = {};
|
|
200
|
+
for (const [key, value] of Object.entries(requestInit?.headers || {})) {
|
|
201
|
+
finalHeaders[key] = value;
|
|
202
|
+
}
|
|
203
|
+
for (const [key, value] of Object.entries(encoder.headers)) {
|
|
204
|
+
finalHeaders[key] = value;
|
|
205
|
+
}
|
|
206
|
+
finalHeaders["Content-Length"] = String(encoder.contentLength);
|
|
207
|
+
const finalRequestInit = {
|
|
208
|
+
...requestInit,
|
|
209
|
+
headers: finalHeaders,
|
|
210
|
+
body: stream.Readable.from(encoder),
|
|
211
|
+
// @ts-expect-error
|
|
212
|
+
duplex: "half"
|
|
213
|
+
};
|
|
214
|
+
return await _doZodFetch(schema, url, finalRequestInit, options);
|
|
215
|
+
}
|
|
216
|
+
__name(zodupload, "zodupload");
|
|
217
|
+
var createForm = /* @__PURE__ */ __name(async (body) => {
|
|
218
|
+
const form = new FormData();
|
|
219
|
+
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
|
|
220
|
+
return form;
|
|
221
|
+
}, "createForm");
|
|
222
|
+
async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
|
|
223
|
+
try {
|
|
224
|
+
const response = await fetch(url, requestInitWithCache(requestInit));
|
|
225
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
|
226
|
+
if (!response.ok) {
|
|
227
|
+
const retryResult = shouldRetry(response, attempt, options?.retry);
|
|
228
|
+
if (retryResult.retry) {
|
|
229
|
+
await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
|
|
230
|
+
return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
|
|
231
|
+
} else {
|
|
232
|
+
const errText = await response.text().catch((e) => castToError2(e).message);
|
|
233
|
+
const errJSON = safeJsonParse(errText);
|
|
234
|
+
const errMessage = errJSON ? void 0 : errText;
|
|
235
|
+
throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
const jsonBody = await response.json();
|
|
239
|
+
const parsedResult = schema.safeParse(jsonBody);
|
|
240
|
+
if (parsedResult.success) {
|
|
241
|
+
return parsedResult.data;
|
|
242
|
+
}
|
|
243
|
+
throw zodValidationError.fromZodError(parsedResult.error);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (error instanceof APIError) {
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
if (options?.retry) {
|
|
249
|
+
const retry = {
|
|
250
|
+
...defaultRetryOptions2,
|
|
251
|
+
...options.retry
|
|
252
|
+
};
|
|
253
|
+
const delay = calculateNextRetryDelay(retry, attempt);
|
|
254
|
+
if (delay) {
|
|
255
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
256
|
+
return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
throw new APIConnectionError({
|
|
260
|
+
cause: castToError2(error)
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
__name(_doZodFetch, "_doZodFetch");
|
|
265
|
+
function castToError2(err) {
|
|
266
|
+
if (err instanceof Error)
|
|
267
|
+
return err;
|
|
268
|
+
return new Error(err);
|
|
269
|
+
}
|
|
270
|
+
__name(castToError2, "castToError");
|
|
271
|
+
function shouldRetry(response, attempt, retryOptions) {
|
|
272
|
+
function shouldRetryForOptions() {
|
|
273
|
+
const retry = {
|
|
274
|
+
...defaultRetryOptions2,
|
|
275
|
+
...retryOptions
|
|
276
|
+
};
|
|
277
|
+
const delay = calculateNextRetryDelay(retry, attempt);
|
|
278
|
+
if (delay) {
|
|
279
|
+
return {
|
|
280
|
+
retry: true,
|
|
281
|
+
delay
|
|
282
|
+
};
|
|
283
|
+
} else {
|
|
284
|
+
return {
|
|
285
|
+
retry: false
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
__name(shouldRetryForOptions, "shouldRetryForOptions");
|
|
290
|
+
const shouldRetryHeader = response.headers.get("x-should-retry");
|
|
291
|
+
if (shouldRetryHeader === "true")
|
|
292
|
+
return shouldRetryForOptions();
|
|
293
|
+
if (shouldRetryHeader === "false")
|
|
294
|
+
return {
|
|
295
|
+
retry: false
|
|
296
|
+
};
|
|
297
|
+
if (response.status === 408)
|
|
298
|
+
return shouldRetryForOptions();
|
|
299
|
+
if (response.status === 409)
|
|
300
|
+
return shouldRetryForOptions();
|
|
301
|
+
if (response.status === 429)
|
|
302
|
+
return shouldRetryForOptions();
|
|
303
|
+
if (response.status >= 500)
|
|
304
|
+
return shouldRetryForOptions();
|
|
305
|
+
return {
|
|
306
|
+
retry: false
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
__name(shouldRetry, "shouldRetry");
|
|
310
|
+
function safeJsonParse(text) {
|
|
311
|
+
try {
|
|
312
|
+
return JSON.parse(text);
|
|
313
|
+
} catch (e) {
|
|
314
|
+
return void 0;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
__name(safeJsonParse, "safeJsonParse");
|
|
318
|
+
function createResponseHeaders(headers) {
|
|
319
|
+
return new Proxy(Object.fromEntries(
|
|
320
|
+
// @ts-ignore
|
|
321
|
+
headers.entries()
|
|
322
|
+
), {
|
|
323
|
+
get(target, name) {
|
|
324
|
+
const key = name.toString();
|
|
325
|
+
return target[key.toLowerCase()] || target[key];
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
__name(createResponseHeaders, "createResponseHeaders");
|
|
330
|
+
function requestInitWithCache(requestInit) {
|
|
331
|
+
try {
|
|
332
|
+
const withCache = {
|
|
333
|
+
...requestInit,
|
|
334
|
+
cache: "no-cache"
|
|
335
|
+
};
|
|
336
|
+
const _ = new Request("http://localhost", withCache);
|
|
337
|
+
return withCache;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return requestInit ?? {};
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
__name(requestInitWithCache, "requestInitWithCache");
|
|
343
|
+
var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
|
|
344
|
+
if (value === void 0)
|
|
345
|
+
return;
|
|
346
|
+
if (value == null) {
|
|
347
|
+
throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
|
|
348
|
+
}
|
|
349
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
350
|
+
form.append(key, String(value));
|
|
351
|
+
} else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
|
|
352
|
+
const file = await toFile(value);
|
|
353
|
+
form.append(key, file);
|
|
354
|
+
} else if (Array.isArray(value)) {
|
|
355
|
+
await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
|
|
356
|
+
} else if (typeof value === "object") {
|
|
357
|
+
await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
|
|
358
|
+
} else {
|
|
359
|
+
throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
|
|
360
|
+
}
|
|
361
|
+
}, "addFormValue");
|
|
362
|
+
async function toFile(value, name, options) {
|
|
363
|
+
value = await value;
|
|
364
|
+
options ??= isFileLike(value) ? {
|
|
365
|
+
lastModified: value.lastModified,
|
|
366
|
+
type: value.type
|
|
367
|
+
} : {};
|
|
368
|
+
if (isResponseLike(value)) {
|
|
369
|
+
const blob = await value.blob();
|
|
370
|
+
name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
|
|
371
|
+
return new File([
|
|
372
|
+
blob
|
|
373
|
+
], name, options);
|
|
374
|
+
}
|
|
375
|
+
const bits = await getBytes(value);
|
|
376
|
+
name ||= getName(value) ?? "unknown_file";
|
|
377
|
+
if (!options.type) {
|
|
378
|
+
const type = bits[0]?.type;
|
|
379
|
+
if (typeof type === "string") {
|
|
380
|
+
options = {
|
|
381
|
+
...options,
|
|
382
|
+
type
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return new File(bits, name, options);
|
|
387
|
+
}
|
|
388
|
+
__name(toFile, "toFile");
|
|
389
|
+
function getName(value) {
|
|
390
|
+
return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
|
|
391
|
+
getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
|
|
392
|
+
}
|
|
393
|
+
__name(getName, "getName");
|
|
394
|
+
var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
|
|
395
|
+
if (typeof x === "string")
|
|
396
|
+
return x;
|
|
397
|
+
if (typeof Buffer !== "undefined" && x instanceof Buffer)
|
|
398
|
+
return String(x);
|
|
399
|
+
return void 0;
|
|
400
|
+
}, "getStringFromMaybeBuffer");
|
|
401
|
+
async function getBytes(value) {
|
|
402
|
+
let parts = [];
|
|
403
|
+
if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
404
|
+
value instanceof ArrayBuffer) {
|
|
405
|
+
parts.push(value);
|
|
406
|
+
} else if (isBlobLike(value)) {
|
|
407
|
+
parts.push(await value.arrayBuffer());
|
|
408
|
+
} else if (isAsyncIterableIterator(value)) {
|
|
409
|
+
for await (const chunk of value) {
|
|
410
|
+
parts.push(chunk);
|
|
411
|
+
}
|
|
412
|
+
} else {
|
|
413
|
+
throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
|
|
414
|
+
}
|
|
415
|
+
return parts;
|
|
416
|
+
}
|
|
417
|
+
__name(getBytes, "getBytes");
|
|
418
|
+
function propsForError(value) {
|
|
419
|
+
const props = Object.getOwnPropertyNames(value);
|
|
420
|
+
return `[${props.map((p) => `"${p}"`).join(", ")}]`;
|
|
421
|
+
}
|
|
422
|
+
__name(propsForError, "propsForError");
|
|
423
|
+
var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
|
|
424
|
+
var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
|
|
425
|
+
var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
|
|
426
|
+
var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
|
|
427
|
+
var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof stream.Readable, "isFsReadStream");
|
|
428
|
+
var isUploadable = /* @__PURE__ */ __name((value) => {
|
|
429
|
+
return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
|
|
430
|
+
}, "isUploadable");
|
|
431
|
+
var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
|
|
432
|
+
|
|
433
|
+
exports.MultipartBody = MultipartBody;
|
|
434
|
+
exports.createForm = createForm;
|
|
435
|
+
exports.defaultRetryOptions = defaultRetryOptions2;
|
|
436
|
+
exports.isBlobLike = isBlobLike;
|
|
437
|
+
exports.isFileLike = isFileLike;
|
|
438
|
+
exports.isFsReadStream = isFsReadStream;
|
|
439
|
+
exports.isRecordLike = isRecordLike;
|
|
440
|
+
exports.isResponseLike = isResponseLike;
|
|
441
|
+
exports.isUploadable = isUploadable;
|
|
442
|
+
exports.toFile = toFile;
|
|
443
|
+
exports.zodfetch = zodfetch;
|
|
444
|
+
exports.zodupload = zodupload;
|
|
445
|
+
//# sourceMappingURL=out.js.map
|
|
446
|
+
//# sourceMappingURL=zodfetch.js.map
|