UNPKG

@coursebuilder/core

Version:

Core package for Course Builder

1 lines 377 kB
{"version":3,"sources":["../../src/inngest/index.ts","../../src/inngest/co-gardener/resource-chat.ts","../../../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/index.mjs","../../src/inngest/util/streaming-chat-prompt-executor.ts","../../src/inngest/commerce/event-purchase-status-updated.ts","../../src/inngest/commerce/send-creator-slack-notification.ts","../../src/inngest/commerce/event-new-purchase-created.ts","../../src/inngest/commerce/send-post-purchase-email.ts","../../src/lib/send-server-email.ts","../../src/lib/send-verification-request.ts","../../src/constants.ts","../../src/schemas/purchase-type.ts","../../src/schemas/purchase-info.ts","../../src/lib/pricing/stripe-purchase-utils.ts","../../src/schemas/stripe/checkout-session-completed.ts","../../src/inngest/stripe/event-checkout-session-completed.ts","../../src/inngest/stripe/event-customer-subscription-created.ts","../../src/inngest/stripe/event-customer-subscription-updated.ts","../../src/inngest/stripe/event-invoice-payment-succeeded.ts","../../src/inngest/video-processing/functions/add-srt-to-mux-asset.ts","../../src/schemas/mux.ts","../../src/lib/mux.ts","../../src/inngest/video-processing/events/event-video-srt-ready-to-asset.ts","../../src/inngest/video-processing/functions/order-transcript.ts","../../src/inngest/video-processing/events/event-video-resource.ts","../../src/inngest/video-processing/functions/remove-completed-video.ts","../../src/inngest/video-processing/events/event-video-status-check.ts","../../src/inngest/video-processing/events/event-video-transcript-ready.ts","../../src/inngest/video-processing/functions/transcript-ready.ts","../../src/inngest/video-processing/events/event-video-mux-webhook.ts","../../src/inngest/video-processing/functions/video-processing-error.ts","../../src/inngest/video-processing/functions/video-ready.ts","../../src/inngest/video-processing/events/event-video-uploaded.ts","../../src/inngest/video-processing/functions/video-uploaded.ts","../../src/inngest/video-processing/functions/index.ts"],"sourcesContent":["import {\n\tRESOURCE_CHAT_REQUEST_EVENT,\n\tresourceChat,\n\tResourceChat,\n} from './co-gardener/resource-chat'\nimport type {\n\tFULL_PRICE_COUPON_REDEEMED_EVENT,\n\tFullPriceCouponRedeemed,\n} from './commerce/event-full-price-coupon-redeemed'\nimport {\n\tNEW_PURCHASE_CREATED_EVENT,\n\tNewPurchaseCreated,\n} from './commerce/event-new-purchase-created'\nimport {\n\tNEW_SUBSCRIPTION_CREATED_EVENT,\n\tNewSubscriptionCreated,\n} from './commerce/event-new-subscription-created'\nimport {\n\tPURCHASE_STATUS_UPDATED_EVENT,\n\tPurchaseStatusUpdated,\n\tupdatePurchaseStatus,\n} from './commerce/event-purchase-status-updated'\nimport {\n\tREFUND_PROCESSED_EVENT,\n\tRefundProcessed,\n} from './commerce/event-refund-processed'\nimport { sendCreatorSlackNotification } from './commerce/send-creator-slack-notification'\nimport { sendPostPurchaseEmail } from './commerce/send-post-purchase-email'\nimport {\n\tSTRIPE_CHECKOUT_SESSION_COMPLETED_EVENT,\n\tstripeCheckoutSessionComplete,\n\tStripeCheckoutSessionCompleted,\n} from './stripe/event-checkout-session-completed'\nimport {\n\tSTRIPE_CUSTOMER_SUBSCRIPTION_CREATED_EVENT,\n\tstripeCustomerSubscriptionCreated,\n\tStripeCustomerSubscriptionCreated,\n} from './stripe/event-customer-subscription-created'\nimport {\n\tSTRIPE_CUSTOMER_SUBSCRIPTION_UPDATED_EVENT,\n\tstripeCustomerSubscriptionUpdated,\n\tStripeCustomerSubscriptionUpdated,\n} from './stripe/event-customer-subscription-updated'\nimport {\n\tSTRIPE_INVOICE_PAYMENT_SUCCEEDED_EVENT,\n\tstripeInvoicePaymentSucceeded,\n\tStripeInvoicePaymentSucceeded,\n} from './stripe/event-invoice-payment-succeeded'\nimport {\n\tEventVideoMuxWebhook,\n\tMUX_WEBHOOK_EVENT,\n} from './video-processing/events/event-video-mux-webhook'\nimport {\n\tVIDEO_RESOURCE_CREATED_EVENT,\n\tVideoResourceCreated,\n} from './video-processing/events/event-video-resource'\nimport {\n\tVIDEO_SRT_READY_EVENT,\n\tVideoSrtReady,\n} from './video-processing/events/event-video-srt-ready-to-asset'\nimport {\n\tEventVideoStatusCheck,\n\tVIDEO_STATUS_CHECK_EVENT,\n} from './video-processing/events/event-video-status-check'\nimport {\n\tEventVideoTranscriptReady,\n\tVIDEO_TRANSCRIPT_READY_EVENT,\n} from './video-processing/events/event-video-transcript-ready'\nimport {\n\tEventVideoUploaded,\n\tVIDEO_UPLOADED_EVENT,\n} from './video-processing/events/event-video-uploaded'\nimport { coreVideoProcessingFunctions } from './video-processing/functions'\n\nexport type CourseBuilderCoreEvents = {\n\t[VIDEO_STATUS_CHECK_EVENT]: EventVideoStatusCheck\n\t[VIDEO_TRANSCRIPT_READY_EVENT]: EventVideoTranscriptReady\n\t[VIDEO_SRT_READY_EVENT]: VideoSrtReady\n\t[VIDEO_UPLOADED_EVENT]: EventVideoUploaded\n\t[VIDEO_RESOURCE_CREATED_EVENT]: VideoResourceCreated\n\t[MUX_WEBHOOK_EVENT]: EventVideoMuxWebhook\n\t[RESOURCE_CHAT_REQUEST_EVENT]: ResourceChat\n\t[STRIPE_CHECKOUT_SESSION_COMPLETED_EVENT]: StripeCheckoutSessionCompleted\n\t[STRIPE_CUSTOMER_SUBSCRIPTION_CREATED_EVENT]: StripeCustomerSubscriptionCreated\n\t[STRIPE_CUSTOMER_SUBSCRIPTION_UPDATED_EVENT]: StripeCustomerSubscriptionUpdated\n\t[STRIPE_INVOICE_PAYMENT_SUCCEEDED_EVENT]: StripeInvoicePaymentSucceeded\n\t[PURCHASE_STATUS_UPDATED_EVENT]: PurchaseStatusUpdated\n\t[NEW_PURCHASE_CREATED_EVENT]: NewPurchaseCreated\n\t[NEW_SUBSCRIPTION_CREATED_EVENT]: NewSubscriptionCreated\n\t[FULL_PRICE_COUPON_REDEEMED_EVENT]: FullPriceCouponRedeemed\n\t[REFUND_PROCESSED_EVENT]: RefundProcessed\n}\n\nexport const courseBuilderCoreFunctions = [\n\t...coreVideoProcessingFunctions,\n\tsendPostPurchaseEmail,\n\tstripeCheckoutSessionComplete,\n\tstripeCustomerSubscriptionCreated,\n\tstripeCustomerSubscriptionUpdated,\n\tstripeInvoicePaymentSucceeded,\n\tsendCreatorSlackNotification,\n\tresourceChat,\n\tupdatePurchaseStatus,\n]\n","import { NonRetriableError } from 'inngest'\nimport { Liquid } from 'liquidjs'\nimport { z } from 'zod'\n\nimport { CourseBuilderAdapter } from '../../adapters'\nimport { LlmProviderConfig } from '../../providers/openai'\nimport { PartyProviderConfig } from '../../providers/partykit'\nimport { User } from '../../schemas'\nimport {\n\tCoreInngestFunctionInput,\n\tCoreInngestHandler,\n\tCoreInngestTrigger,\n} from '../create-inngest-middleware'\nimport {\n\tChatCompletionRequestMessage,\n\tstreamingChatPromptExecutor,\n} from '../util/streaming-chat-prompt-executor'\n\nexport const ChatResourceSchema = z.object({\n\tid: z.string(),\n\ttype: z.string(),\n\tupdatedAt: z.string().nullable(),\n\tcreatedAt: z.string().nullable(),\n\ttitle: z.string().nullable().optional(),\n\tbody: z.string().nullable().optional(),\n\ttranscript: z.string().nullable().optional(),\n\twordLevelSrt: z.string().nullable().optional(),\n\tresources: z.array(z.any()).optional(),\n})\n\nexport type ChatResource = z.infer<typeof ChatResourceSchema>\n\nexport const RESOURCE_CHAT_REQUEST_EVENT = 'resource/chat-request-event'\nexport type ResourceChat = {\n\tname: typeof RESOURCE_CHAT_REQUEST_EVENT\n\tdata: {\n\t\tresourceId: string\n\t\tmessages: ChatCompletionRequestMessage[]\n\t\tpromptId?: string\n\t\tselectedWorkflow: string\n\t\tmodel?: string\n\t}\n\tuser: Record<string, any>\n}\n\nexport const resourceChatConfig = {\n\tid: `resource-chat`,\n\tname: 'Resource Chat',\n\trateLimit: {\n\t\tkey: 'event.user.id',\n\t\tlimit: 5,\n\t\tperiod: '1m' as `${number}m`,\n\t},\n}\n\nexport const resourceChatTrigger: CoreInngestTrigger = {\n\tevent: RESOURCE_CHAT_REQUEST_EVENT,\n}\n\n// Define ChatCompletionRequestMessageRoleEnum\nexport enum ChatCompletionRequestMessageRoleEnum {\n\tSystem = 'system',\n\tUser = 'user',\n\tAssistant = 'assistant',\n\tTool = 'tool',\n}\n\n/**\n * TODO: Cancellation conditions need to be added $$\n */\nexport const resourceChatHandler: CoreInngestHandler = async ({\n\tevent,\n\tstep,\n\topenaiProvider,\n\tpartyProvider,\n\tdb,\n}: CoreInngestFunctionInput) => {\n\tconst resourceId = event.data.resourceId\n\tconst workflowTrigger = event.data.selectedWorkflow\n\n\tconst currentUserMessage = event.data.messages[event.data.messages.length - 1]\n\n\tif (currentUserMessage?.content) {\n\t\tawait step.run(\n\t\t\t`partykit broadcast user prompt [${resourceId}]`,\n\t\t\tasync () => {\n\t\t\t\tawait partyProvider.broadcastMessage({\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tbody: currentUserMessage.content,\n\t\t\t\t\t\trequestId: resourceId,\n\t\t\t\t\t\tname: 'resource.chat.prompted',\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tuserId: event.user.id,\n\t\t\t\t\t},\n\t\t\t\t\troomId: resourceId,\n\t\t\t\t})\n\t\t\t},\n\t\t)\n\t}\n\n\tconst resource = await step.run('get the resource', async () => {\n\t\treturn db.getContentResource(resourceId)\n\t})\n\n\tif (!resource) {\n\t\tthrow new NonRetriableError(`Resource not found for id (${resourceId})`)\n\t}\n\n\tconst videoResource = await step.run('get the video resource', async () => {\n\t\treturn db.getVideoResource(resource.resources?.[0]?.resource.id)\n\t})\n\n\tconst messages = await resourceChatWorkflowExecutor({\n\t\tdb,\n\t\topenaiProvider,\n\t\tpartyProvider,\n\t\tstep,\n\t\tworkflowTrigger,\n\t\tresourceId,\n\n\t\tresource: {\n\t\t\t...videoResource,\n\t\t\t...resource,\n\t\t\t...resource.fields,\n\t\t\tresources: resource.resources ?? [],\n\t\t},\n\t\tmessages: event.data.messages,\n\t\t// @ts-expect-error\n\t\tuser: event.user,\n\t})\n\n\treturn { resource: { ...videoResource, ...resource }, messages }\n}\n\n/**\n * loads the workflow from sanity based on the trigger and then executes the workflow using the `resource` as\n * input that is parsed by liquid into the prompt\n *\n * This treats the system prompt as \"special\" from the loaded workflow since it is added to the beginning of the prompt\n * in the chat context, but additional steps are executed as normal\n *\n * @param step\n * @param workflowTrigger\n * @param resourceId\n * @param messages\n * @param resource\n * @param currentFeedback\n */\nexport async function resourceChatWorkflowExecutor({\n\tstep,\n\tworkflowTrigger,\n\tresourceId,\n\tmessages,\n\tresource,\n\tuser,\n\topenaiProvider,\n\tpartyProvider,\n\tdb,\n\tmodel,\n}: {\n\topenaiProvider: LlmProviderConfig\n\tpartyProvider: PartyProviderConfig\n\tdb: CourseBuilderAdapter\n\tresource: ChatResource\n\tstep: any\n\tworkflowTrigger: string\n\tresourceId: string\n\tmessages: ChatCompletionRequestMessage[]\n\tuser: User\n\tmodel?: string\n}) {\n\tconst basicPrompt = {\n\t\tid: 'basic',\n\t\tname: 'Basic',\n\t\ttype: 'prompt',\n\t\tfields: {\n\t\t\tbody: `# Instructions\nPause. Take a deep breath and think. This is important. Think step by step.\n\nYou are serving as a writing assistant for a content creator that is publishing a {% if transcript %}video based{% endif %} post for software developers. The content creator will ask questions and expect concise answers that aren't corny or generic.\n\nKeep responses scoped to the post and it's direct contents. Do not include additional information.\nDo not include information that is not directly related to the post or the {% if transcript %}video{% endif %}.\n\nUse simple language.\n\nUse only most popular 2000 english words {% if transcript %}and words used in the transcript{% endif %}.\nSimple is better.\nFlourish is bad.\n**People will hate you if you try to sound clever.**\n\n{% if wordLevelSrt %} add screenshots from the video when they are relevant and would be useful to\nthe reader using the following template replacing {{timestampInSeconds}} with the time noted in the transcript:\n\n![{{descriptiveAltTextForVisuallyImpaired}}](https://image.mux.com/{{muxPlaybackId}}/thumbnail.png?time={{timestampInSeconds}})\nbe precise with the timestamps! {% if wordLevelSrt %} use this word level SRT to get the exact timestamp:\n\nword level srt start\n{{wordLevelSrt}} {% endif %}\n\nword level srt end\n{% endif %}\n\nGet it right and there's $200 cash gratuity in it for you ;)\n\n{% if transcript %}The goal is to build a really good written version of the existing video, not edit the video itself. The video is done.\n\nThe post transcript is the final representation of the video. The post transcript is the source of truth.{% endif %}\n\nKeep the language simple and don't use words not in the post {% if transcript %}transcript{% endif %}.\n\n{% if transcript %}Do not make direct references to the video.\nDo not make direct references to the transcript.{% endif %}\nDo not make direct references to the content creator.\nDo not make direct references to 'the post'.\nJump right to the point.\n\nPost Type: {{type}}\n\nPost Title: {{title}}\n\n{% if transcript %}Post Transcript: {{transcript}}{% endif %}\n\nPost Body: {{body}}\n`,\n\t\t},\n\t}\n\n\tlet prompt =\n\t\tworkflowTrigger === 'basic'\n\t\t\t? basicPrompt\n\t\t\t: await step.run('Load Prompt', async () => {\n\t\t\t\t\treturn db.getContentResource(workflowTrigger)\n\t\t\t\t})\n\n\tif (!prompt) {\n\t\tprompt = basicPrompt\n\t}\n\n\tlet systemPrompt: ChatCompletionRequestMessage = {\n\t\trole: 'system',\n\t\tcontent: prompt.fields.body,\n\t}\n\tlet seedMessages: ChatCompletionRequestMessage[] = []\n\n\ttry {\n\t\tconst actionParsed = z\n\t\t\t.array(\n\t\t\t\tz.object({\n\t\t\t\t\trole: z.enum([\n\t\t\t\t\t\tChatCompletionRequestMessageRoleEnum.System,\n\t\t\t\t\t\tChatCompletionRequestMessageRoleEnum.User,\n\t\t\t\t\t\tChatCompletionRequestMessageRoleEnum.Assistant,\n\t\t\t\t\t\tChatCompletionRequestMessageRoleEnum.Tool,\n\t\t\t\t\t]),\n\t\t\t\t\tcontent: z.string(),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.parse(JSON.parse(prompt.fields.body)) as Array<{\n\t\t\trole: ChatCompletionRequestMessageRoleEnum\n\t\t\tcontent: string\n\t\t}>\n\n\t\tconst actionMessages: ChatCompletionRequestMessage[] = []\n\t\tfor (const actionMessage of actionParsed) {\n\t\t\tconst liquidParsedContent = await step.run(\n\t\t\t\t'parse json content',\n\t\t\t\tasync () => {\n\t\t\t\t\tconst engine = new Liquid()\n\t\t\t\t\tconst contentString =\n\t\t\t\t\t\ttypeof actionMessage.content === 'string'\n\t\t\t\t\t\t\t? actionMessage.content\n\t\t\t\t\t\t\t: JSON.stringify(actionMessage.content)\n\t\t\t\t\treturn await engine.parseAndRender(contentString, {\n\t\t\t\t\t\t...resource,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tactionMessages.push({\n\t\t\t\trole: actionMessage.role,\n\t\t\t\tcontent: liquidParsedContent,\n\t\t\t})\n\t\t}\n\t\tif (actionMessages.length > 0) {\n\t\t\t;[\n\t\t\t\tsystemPrompt = {\n\t\t\t\t\trole: 'system',\n\t\t\t\t\tcontent: prompt.fields.body,\n\t\t\t\t},\n\t\t\t\t...seedMessages\n\t\t\t] = actionMessages\n\t\t}\n\t} catch (e: any) {\n\t\t// if the prompt action content is not valid json, we assume it's just text\n\t\tsystemPrompt = await step.run(`parse system prompt`, async () => {\n\t\t\ttry {\n\t\t\t\tconst engine = new Liquid()\n\t\t\t\tconst originalSystemPrompt = systemPrompt // Store reference before reassignment\n\t\t\t\tconst contentString =\n\t\t\t\t\ttypeof originalSystemPrompt.content === 'string'\n\t\t\t\t\t\t? originalSystemPrompt.content\n\t\t\t\t\t\t: JSON.stringify(originalSystemPrompt.content)\n\t\t\t\treturn {\n\t\t\t\t\trole: originalSystemPrompt.role,\n\t\t\t\t\tcontent: await engine.parseAndRender(contentString || '', resource),\n\t\t\t\t}\n\t\t\t} catch (e: any) {\n\t\t\t\tconsole.error(e.message)\n\t\t\t\treturn {\n\t\t\t\t\trole: 'system',\n\t\t\t\t\tcontent: prompt.fields.body,\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tif (messages.length <= 2 && systemPrompt) {\n\t\tmessages = [systemPrompt, ...seedMessages, ...messages]\n\t}\n\n\tconst currentUserMessage = messages[messages.length - 1]\n\tconst currentResourceMetadata = messages[messages.length - 2]\n\n\tmessages = await step.run('answer the user prompt', async () => {\n\t\tif (!currentUserMessage) {\n\t\t\tthrow new Error('No user message')\n\t\t}\n\n\t\tconst engine = new Liquid()\n\t\tconst currentUserContentString =\n\t\t\ttypeof currentUserMessage.content === 'string'\n\t\t\t\t? currentUserMessage.content\n\t\t\t\t: JSON.stringify(currentUserMessage.content)\n\n\t\tcurrentUserMessage.content = await engine.parseAndRender(\n\t\t\tcurrentUserContentString ?? '',\n\t\t\tresource,\n\t\t)\n\n\t\tif (currentResourceMetadata) {\n\t\t\tconst metadataContentString =\n\t\t\t\ttypeof currentResourceMetadata.content === 'string'\n\t\t\t\t\t? currentResourceMetadata.content\n\t\t\t\t\t: JSON.stringify(currentResourceMetadata.content)\n\t\t\tcurrentResourceMetadata.content = await engine.parseAndRender(\n\t\t\t\tmetadataContentString ?? '',\n\t\t\t\tresource,\n\t\t\t)\n\t\t}\n\n\t\treturn streamingChatPromptExecutor({\n\t\t\trequestId: resourceId,\n\t\t\tpromptMessages: messages,\n\t\t\tmodel: prompt.fields.model || model || 'gpt-4-turbo',\n\t\t\tprovider: openaiProvider,\n\t\t})\n\t})\n\n\tawait step.run(`partykit broadcast [${resourceId}]`, async () => {\n\t\treturn await partyProvider.broadcastMessage({\n\t\t\tbody: {\n\t\t\t\tbody: messages,\n\t\t\t\trequestId: resourceId,\n\t\t\t\tname: 'resource.chat.completed',\n\t\t\t\tmetadata: {\n\t\t\t\t\tworkflow: workflowTrigger,\n\t\t\t\t},\n\t\t\t},\n\t\t\troomId: resourceId,\n\t\t})\n\t})\n\n\treturn messages\n}\n\nexport const resourceChat = {\n\tconfig: resourceChatConfig,\n\ttrigger: resourceChatTrigger,\n\thandler: resourceChatHandler,\n}\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n var _a, _b;\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodC