UNPKG

@coursebuilder/core

Version:

Core package for Course Builder

1 lines 346 kB
{"version":3,"sources":["../../src/providers/stripe.ts","../../src/lib/pricing/stripe-subscription-utils.ts","../../../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/index.mjs","../../src/schemas/stripe/checkout-session-metadata.ts","../../src/schemas/subscription-info.ts","../../src/errors.ts","../../src/lib/utils/logger.ts","../../src/lib/pricing/stripe-checkout.ts","../../src/lib/pricing/format-prices-for-product.ts","../../src/lib/pricing/determine-coupon-to-apply.ts","../../src/lib/pricing/get-calculated-price.ts","../../src/schemas/purchase-type.ts","../../src/schemas/purchase-info.ts","../../src/lib/pricing/stripe-purchase-utils.ts"],"sourcesContent":["import { parseSubscriptionInfoFromCheckoutSession } from 'src/lib/pricing/stripe-subscription-utils'\nimport Stripe from 'stripe'\n\nimport { CourseBuilderAdapter } from '../adapters'\nimport { CheckoutParams, stripeCheckout } from '../lib/pricing/stripe-checkout'\nimport { parsePurchaseInfoFromCheckoutSession } from '../lib/pricing/stripe-purchase-utils'\nimport { logger } from '../lib/utils/logger'\nimport {\n\tPaymentsAdapter,\n\tPaymentsProviderConfig,\n\tPaymentsProviderConsumerConfig,\n} from '../types'\n\nexport default function StripeProvider(\n\toptions: PaymentsProviderConsumerConfig,\n): PaymentsProviderConfig {\n\treturn {\n\t\tid: 'stripe',\n\t\tname: 'Stripe',\n\t\ttype: 'payment',\n\t\t...options,\n\t\toptions,\n\t\tgetSubscription: async (subscriptionId: string) => {\n\t\t\treturn options.paymentsAdapter.getSubscription(subscriptionId)\n\t\t},\n\t\tgetBillingPortalUrl: async (customerId: string, returnUrl: string) => {\n\t\t\treturn options.paymentsAdapter.getBillingPortalUrl(customerId, returnUrl)\n\t\t},\n\t\tgetSubscriptionInfo: async (\n\t\t\tcheckoutSessionId: string,\n\t\t\t_: CourseBuilderAdapter,\n\t\t) => {\n\t\t\tconst checkoutSession =\n\t\t\t\tawait options.paymentsAdapter.getCheckoutSession(checkoutSessionId)\n\t\t\tconsole.log('checkoutSession', checkoutSession)\n\n\t\t\treturn parseSubscriptionInfoFromCheckoutSession(checkoutSession)\n\t\t},\n\t\tgetPurchaseInfo: async (\n\t\t\tcheckoutSessionId: string,\n\t\t\tadapter: CourseBuilderAdapter,\n\t\t) => {\n\t\t\tconst checkoutSession =\n\t\t\t\tawait options.paymentsAdapter.getCheckoutSession(checkoutSessionId)\n\t\t\treturn parsePurchaseInfoFromCheckoutSession(checkoutSession, adapter)\n\t\t},\n\t\tcreateCheckoutSession: async (\n\t\t\tcheckoutParams: CheckoutParams,\n\t\t\tadapter?: CourseBuilderAdapter,\n\t\t) => {\n\t\t\treturn stripeCheckout({\n\t\t\t\tparams: checkoutParams,\n\t\t\t\tconfig: options,\n\t\t\t\tadapter,\n\t\t\t})\n\t\t},\n\t\tgetCustomer: async (customerId: string) => {\n\t\t\treturn options.paymentsAdapter.getCustomer(customerId)\n\t\t},\n\t\tupdateCustomer: async (\n\t\t\tcustomerId: string,\n\t\t\tcustomer: { name: string; email: string; metadata?: Record<string, any> },\n\t\t) => {\n\t\t\treturn options.paymentsAdapter.updateCustomer(customerId, customer)\n\t\t},\n\t\trefundCharge: async (chargeId: string) => {\n\t\t\treturn options.paymentsAdapter.refundCharge(chargeId)\n\t\t},\n\t\tgetProduct: async (productId: string) => {\n\t\t\treturn options.paymentsAdapter.getProduct(productId)\n\t\t},\n\t\tgetPrice: async (priceId: string) => {\n\t\t\treturn options.paymentsAdapter.getPrice(priceId)\n\t\t},\n\t\tupdateProduct: async (\n\t\t\tproductId: string,\n\t\t\tproduct: Partial<Stripe.Product>,\n\t\t) => {\n\t\t\treturn options.paymentsAdapter.updateProduct(productId, product)\n\t\t},\n\t\tupdatePrice: async (priceId: string, price: Partial<Stripe.Price>) => {\n\t\t\treturn options.paymentsAdapter.updatePrice(priceId, price)\n\t\t},\n\t\tcreatePrice: async (price: Stripe.PriceCreateParams) => {\n\t\t\treturn options.paymentsAdapter.createPrice(price)\n\t\t},\n\t\tcreateProduct: async (product: Stripe.ProductCreateParams) => {\n\t\t\treturn options.paymentsAdapter.createProduct(product)\n\t\t},\n\t}\n}\n\nexport const STRIPE_VERSION = '2024-06-20'\n\nexport class StripePaymentAdapter implements PaymentsAdapter {\n\twebhookSecret: string\n\tstripe: Stripe\n\n\tconstructor({\n\t\tstripeToken,\n\t\tstripeWebhookSecret,\n\t}: {\n\t\tstripeToken: string\n\t\tstripeWebhookSecret: string\n\t}) {\n\t\tconst stripe = this.createStripeClient(stripeToken)\n\n\t\tif (!stripeWebhookSecret) {\n\t\t\tthrow new Error('Stripe webhook secret not found')\n\t\t}\n\t\tthis.webhookSecret = stripeWebhookSecret\n\t\tthis.stripe = stripe\n\t}\n\n\tprivate createStripeClient(token: string) {\n\t\treturn new Stripe(token, {\n\t\t\tapiVersion: STRIPE_VERSION,\n\t\t})\n\t}\n\n\tasync verifyWebhookSignature(rawBody: string, sig: string) {\n\t\tconst event = this.stripe.webhooks.constructEvent(\n\t\t\trawBody,\n\t\t\tsig,\n\t\t\tthis.webhookSecret,\n\t\t)\n\t\treturn Boolean(event)\n\t}\n\n\tasync getCouponPercentOff(identifier: string) {\n\t\tconst coupon = await this.stripe.coupons.retrieve(identifier)\n\t\treturn coupon && coupon.percent_off ? coupon.percent_off / 100 : 0\n\t}\n\tasync createCoupon(params: Stripe.CouponCreateParams) {\n\t\tconst coupon = await this.stripe.coupons.create(params)\n\t\treturn coupon.id\n\t}\n\tasync createPromotionCode(params: Stripe.PromotionCodeCreateParams) {\n\t\tconst { id } = await this.stripe.promotionCodes.create(params)\n\t\treturn id\n\t}\n\tasync createCheckoutSession(params: Stripe.Checkout.SessionCreateParams) {\n\t\tconst session = await this.stripe.checkout.sessions.create(params)\n\t\treturn session.url\n\t}\n\n\tasync getCheckoutSession(checkoutSessionId: string) {\n\t\tlogger.debug('getCheckoutSession', { checkoutSessionId })\n\t\treturn await this.stripe.checkout.sessions.retrieve(checkoutSessionId, {\n\t\t\texpand: [\n\t\t\t\t'customer',\n\t\t\t\t'line_items.data.price.product',\n\t\t\t\t'line_items.data.discounts',\n\t\t\t\t'payment_intent.latest_charge',\n\t\t\t\t'subscription',\n\t\t\t\t'subscription.plan.product',\n\t\t\t],\n\t\t})\n\t}\n\tasync createCustomer(params: { email: string; userId: string }) {\n\t\tconst stripeCustomer = await this.stripe.customers.create({\n\t\t\temail: params.email,\n\t\t\tmetadata: {\n\t\t\t\tuserId: params.userId,\n\t\t\t},\n\t\t})\n\t\treturn stripeCustomer.id\n\t}\n\tasync getCustomer(customerId: string) {\n\t\treturn (await this.stripe.customers.retrieve(customerId)) as Stripe.Customer\n\t}\n\tasync updateCustomer(\n\t\tcustomerId: string,\n\t\tcustomer: { name: string; email: string; metadata: Record<string, string> },\n\t) {\n\t\tconst stripeCustomer = (await this.stripe.customers.retrieve(\n\t\t\tcustomerId,\n\t\t)) as Stripe.Customer\n\n\t\tawait this.stripe.customers.update(customerId, {\n\t\t\tname: customer.name || stripeCustomer.name || undefined,\n\t\t\temail: customer.email || stripeCustomer.email || undefined,\n\t\t\tmetadata: {\n\t\t\t\t...stripeCustomer.metadata,\n\t\t\t\t...customer.metadata,\n\t\t\t},\n\t\t})\n\t}\n\tasync refundCharge(chargeId: string) {\n\t\treturn await this.stripe.refunds.create({\n\t\t\tcharge: chargeId,\n\t\t})\n\t}\n\tasync getProduct(productId: string) {\n\t\treturn this.stripe.products.retrieve(productId)\n\t}\n\tasync getPrice(priceId: string) {\n\t\treturn this.stripe.prices.retrieve(priceId)\n\t}\n\n\tasync updateProduct<TProductUpdate = Stripe.ProductUpdateParams>(\n\t\tproductId: string,\n\t\tproduct: Partial<TProductUpdate>,\n\t) {\n\t\tawait this.stripe.products.update(productId, product)\n\t}\n\tasync updatePrice<TPriceUpdate = Stripe.PriceUpdateParams>(\n\t\tpriceId: string,\n\t\tprice: Partial<TPriceUpdate>,\n\t) {\n\t\tawait this.stripe.prices.update(priceId, price)\n\t}\n\tasync createPrice(price: Stripe.PriceCreateParams) {\n\t\treturn this.stripe.prices.create(price)\n\t}\n\tasync createProduct(product: Stripe.ProductCreateParams) {\n\t\treturn this.stripe.products.create(product)\n\t}\n\tasync getSubscription(subscriptionId: string) {\n\t\treturn this.stripe.subscriptions.retrieve(subscriptionId)\n\t}\n\tasync getBillingPortalUrl(customerId: string, returnUrl: string) {\n\t\treturn this.stripe.billingPortal.sessions\n\t\t\t.create({\n\t\t\t\tcustomer: customerId,\n\t\t\t\treturn_url: returnUrl,\n\t\t\t})\n\t\t\t.then((session) => session.url)\n\t}\n}\n\nexport const mockStripeAdapter: PaymentsAdapter = {\n\tgetCouponPercentOff: async () => 0,\n\tcreateCoupon: async () => 'mock-coupon-id',\n\tcreatePromotionCode: async () => 'mock-promotion-code-id',\n\tcreateCheckoutSession: async () => 'mock-checkout-session-id',\n\tcreateCustomer: async () => 'mock-customer-id',\n\tverifyWebhookSignature: async () => true,\n\tgetCheckoutSession: async () => ({ id: 'mock-checkout-session-id' }) as any,\n\tgetCustomer: async () => ({ id: 'mock-customer-id' }) as any,\n\tupdateCustomer: async () => {},\n\trefundCharge: async () => ({}) as any,\n\tupdateProduct: async () => {},\n\tupdatePrice: async () => {},\n\tgetProduct: async () => ({}) as any,\n\tgetPrice: async () => ({}) as any,\n\tcreatePrice: async () => ({}) as any,\n\tcreateProduct: async () => ({}) as any,\n\tgetSubscription: async () => ({}) as any,\n\tgetBillingPortalUrl: async () => 'mock-billing-portal-url',\n}\n\nexport const MockStripeProvider: PaymentsProviderConfig = {\n\tid: 'mock-stripe' as const,\n\tname: 'Mock Stripe',\n\ttype: 'payment',\n\toptions: {\n\t\terrorRedirectUrl: 'mock-error-redirect-url',\n\t\tcancelUrl: 'mock-cancel-url',\n\t\tbaseSuccessUrl: 'mock-base-success-url',\n\t\tpaymentsAdapter: mockStripeAdapter,\n\t},\n\tgetSubscriptionInfo: async () => ({}) as any,\n\tgetPurchaseInfo: async (\n\t\tcheckoutSessionId: string,\n\t\tadapter: CourseBuilderAdapter,\n\t) => {\n\t\treturn {} as any\n\t},\n\tcreateCheckoutSession: async () => {\n\t\treturn {\n\t\t\tredirect: 'mock-checkout-session-id',\n\t\t\tstatus: 303,\n\t\t}\n\t},\n\tgetCustomer: async () => ({ id: 'mock-customer-id' }) as any,\n\tupdateCustomer: async () => {},\n\trefundCharge: async () => ({}) as any,\n\tupdateProduct: async () => {},\n\tupdatePrice: async () => {},\n\tgetProduct: async () => ({}) as any,\n\tgetPrice: async () => ({}) as any,\n\tcreatePrice: async () => ({}) as any,\n\tcreateProduct: async () => ({}) as any,\n\tgetSubscription: async () => ({}) as any,\n\tgetBillingPortalUrl: async () => 'mock-billing-portal-url',\n}\n","import type Stripe from 'stripe'\n\nimport { first } from '@coursebuilder/nodash'\n\nimport {\n\tCheckoutSessionMetadata,\n\tCheckoutSessionMetadataSchema,\n} from '../../schemas/stripe/checkout-session-metadata'\nimport {\n\tSubscriptionInfo,\n\tSubscriptionInfoSchema,\n} from '../../schemas/subscription-info'\nimport { logger } from '../utils/logger'\n\nexport async function parseSubscriptionInfoFromCheckoutSession(\n\tcheckoutSession: Stripe.Checkout.Session,\n) {\n\tlogger.debug('Parsing subscription info from checkout session', {\n\t\tcheckoutSession,\n\t})\n\n\tconst { customer, subscription, metadata } = checkoutSession\n\tconst { email, name, id: stripeCustomerId } = customer as Stripe.Customer\n\tconst stripeSubscription = subscription as Stripe.Subscription\n\n\tconst subscriptionItem = first(stripeSubscription.items.data)\n\tif (!subscriptionItem) {\n\t\tlogger.error(new Error('No subscription item found in checkout session'))\n\t\tthrow new Error('No subscription item found')\n\t}\n\n\tconst stripePrice = subscriptionItem.price\n\tconst quantity = subscriptionItem.quantity || 1\n\tconst stripeProduct = (stripeSubscription as any).plan\n\t\t?.product as Stripe.Product\n\n\tlogger.debug('Found subscription details', {\n\t\tstripeCustomerId,\n\t\tsubscriptionId: stripeSubscription.id,\n\t\tproductId: stripeProduct.id,\n\t\tquantity,\n\t})\n\n\t// Add required fields to metadata before parsing\n\tconst enrichedMetadata = {\n\t\tbulk: quantity > 1 ? 'true' : 'false',\n\t\tcountry: 'US',\n\t\tip_address: '127.0.0.1',\n\t\tproductId: stripeProduct.id,\n\t\tproduct: stripeProduct.name,\n\t\tsiteName: 'default',\n\t\t...metadata,\n\t}\n\n\tconst parsedMetadata = enrichedMetadata\n\t\t? CheckoutSessionMetadataSchema.parse(enrichedMetadata)\n\t\t: undefined\n\n\tlogger.debug('Enriched metadata', { enrichedMetadata, parsedMetadata })\n\n\tconst info: SubscriptionInfo = {\n\t\tcustomerIdentifier: stripeCustomerId,\n\t\temail,\n\t\tname,\n\t\tproductIdentifier: stripeProduct.id,\n\t\tproduct: stripeProduct,\n\t\tsubscriptionIdentifier: stripeSubscription.id,\n\t\tpriceIdentifier: stripePrice.id,\n\t\tquantity,\n\t\tstatus: stripeSubscription.status,\n\t\tcurrentPeriodStart: new Date(\n\t\t\tstripeSubscription.current_period_start * 1000,\n\t\t),\n\t\tcurrentPeriodEnd: new Date(stripeSubscription.current_period_end * 1000),\n\t\tmetadata: parsedMetadata,\n\t}\n\n\tconst parsedInfo = SubscriptionInfoSchema.parse(info)\n\tlogger.debug('Successfully parsed subscription info', { parsedInfo })\n\treturn parsedInfo\n}\n\nexport interface SubscriptionPermissions {\n\torganizationId: string\n\tpurchasingMemberId: string\n\tisMultiUser: boolean\n\tassignToMember?: string // only for single-user subscriptions\n}\n\nexport function determineSubscriptionPermissions(\n\tmetadata: CheckoutSessionMetadata,\n\torganizationId: string,\n\tpurchasingMemberId: string,\n): SubscriptionPermissions {\n\tlogger.debug('Determining subscription permissions', {\n\t\tmetadata,\n\t\torganizationId,\n\t\tpurchasingMemberId,\n\t})\n\n\tconst isMultiUser = metadata.bulk === 'true'\n\n\tconst permissions = {\n\t\torganizationId,\n\t\tpurchasingMemberId,\n\t\tisMultiUser,\n\t\tassignToMember: !isMultiUser ? purchasingMemberId : undefined,\n\t}\n\n\tlogger.debug('Determined subscription permissions', { permissions })\n\treturn permissions\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 ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\