@stackframe/stack-shared 2.8.10 → 2.8.12
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/CHANGELOG.md +12 -0
- package/dist/config/{schema.d.cts → schema.d.mts} +38 -33
- package/dist/config/schema.d.ts +37 -32
- package/dist/config/schema.js +5 -3
- package/dist/config/schema.js.map +1 -1
- package/dist/{crud.d.cts → crud.d.mts} +1 -1
- package/dist/esm/config/schema.js +5 -3
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/interface/clientInterface.js +8 -6
- package/dist/esm/interface/clientInterface.js.map +1 -1
- package/dist/esm/interface/crud/project-api-keys.js +20 -15
- package/dist/esm/interface/crud/project-api-keys.js.map +1 -1
- package/dist/esm/interface/crud/projects.js +5 -12
- package/dist/esm/interface/crud/projects.js.map +1 -1
- package/dist/esm/interface/serverInterface.js +28 -2
- package/dist/esm/interface/serverInterface.js.map +1 -1
- package/dist/esm/known-errors.js +43 -1
- package/dist/esm/known-errors.js.map +1 -1
- package/dist/esm/schema-fields.js +2 -0
- package/dist/esm/schema-fields.js.map +1 -1
- package/dist/esm/utils/errors.js +4 -0
- package/dist/esm/utils/errors.js.map +1 -1
- package/dist/esm/utils/hashes.js +1 -1
- package/dist/esm/utils/hashes.js.map +1 -1
- package/dist/esm/utils/objects.js +24 -0
- package/dist/esm/utils/objects.js.map +1 -1
- package/dist/esm/utils/promises.js +1 -1
- package/dist/esm/utils/promises.js.map +1 -1
- package/dist/esm/utils/strings.js +1 -0
- package/dist/esm/utils/strings.js.map +1 -1
- package/dist/helpers/password.d.mts +11 -0
- package/dist/helpers/{production-mode.d.cts → production-mode.d.mts} +3 -3
- package/dist/hooks/use-async-callback.js +1 -1
- package/dist/hooks/{use-async-external-store.d.cts → use-async-external-store.d.mts} +1 -1
- package/dist/index.d.mts +30 -0
- package/dist/interface/{adminInterface.d.cts → adminInterface.d.mts} +26 -26
- package/dist/interface/{clientInterface.d.cts → clientInterface.d.mts} +18 -18
- package/dist/interface/clientInterface.js +8 -6
- package/dist/interface/clientInterface.js.map +1 -1
- package/dist/interface/crud/{contact-channels.d.cts → contact-channels.d.mts} +2 -2
- package/dist/interface/crud/{current-user.d.cts → current-user.d.mts} +2 -2
- package/dist/interface/crud/{email-templates.d.cts → email-templates.d.mts} +2 -2
- package/dist/interface/crud/{emails.d.cts → emails.d.mts} +2 -2
- package/dist/interface/crud/emails.js +1 -1
- package/dist/interface/crud/{internal-api-keys.d.cts → internal-api-keys.d.mts} +2 -2
- package/dist/interface/crud/{oauth.d.cts → oauth.d.mts} +2 -2
- package/dist/interface/crud/{project-api-keys.d.cts → project-api-keys.d.mts} +14 -4
- package/dist/interface/crud/project-api-keys.d.ts +12 -2
- package/dist/interface/crud/project-api-keys.js +20 -15
- package/dist/interface/crud/project-api-keys.js.map +1 -1
- package/dist/interface/crud/{project-permissions.d.cts → project-permissions.d.mts} +2 -2
- package/dist/interface/crud/project-permissions.js +1 -1
- package/dist/interface/crud/{projects.d.cts → projects.d.mts} +9 -22
- package/dist/interface/crud/projects.d.ts +7 -20
- package/dist/interface/crud/projects.js +6 -13
- package/dist/interface/crud/projects.js.map +1 -1
- package/dist/interface/crud/{sessions.d.cts → sessions.d.mts} +2 -2
- package/dist/interface/crud/{svix-token.d.cts → svix-token.d.mts} +2 -2
- package/dist/interface/crud/{team-invitation-details.d.cts → team-invitation-details.d.mts} +2 -2
- package/dist/interface/crud/team-invitation-details.js +1 -1
- package/dist/interface/crud/{team-invitation.d.cts → team-invitation.d.mts} +2 -2
- package/dist/interface/crud/team-invitation.js +1 -1
- package/dist/interface/crud/{team-member-profiles.d.cts → team-member-profiles.d.mts} +2 -2
- package/dist/interface/crud/team-member-profiles.js +1 -1
- package/dist/interface/crud/{team-memberships.d.cts → team-memberships.d.mts} +2 -2
- package/dist/interface/crud/{team-permissions.d.cts → team-permissions.d.mts} +2 -2
- package/dist/interface/crud/team-permissions.js +1 -1
- package/dist/interface/crud/{teams.d.cts → teams.d.mts} +2 -2
- package/dist/interface/crud/teams.js +1 -1
- package/dist/interface/crud/{users.d.cts → users.d.mts} +2 -2
- package/dist/interface/crud/users.js +1 -1
- package/dist/interface/{serverInterface.d.cts → serverInterface.d.mts} +23 -21
- package/dist/interface/serverInterface.d.ts +2 -0
- package/dist/interface/serverInterface.js +28 -2
- package/dist/interface/serverInterface.js.map +1 -1
- package/dist/{known-errors.d.cts → known-errors.d.mts} +14 -3
- package/dist/known-errors.d.ts +11 -0
- package/dist/known-errors.js +43 -1
- package/dist/known-errors.js.map +1 -1
- package/dist/{schema-fields.d.cts → schema-fields.d.mts} +2 -1
- package/dist/schema-fields.d.ts +2 -1
- package/dist/schema-fields.js +4 -1
- package/dist/schema-fields.js.map +1 -1
- package/dist/sessions.js +1 -1
- package/dist/utils/api-keys.js +1 -1
- package/dist/utils/{caches.d.cts → caches.d.mts} +2 -2
- package/dist/utils/{errors.d.cts → errors.d.mts} +4 -2
- package/dist/utils/errors.d.ts +2 -0
- package/dist/utils/errors.js +4 -0
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/fs.js +2 -2
- package/dist/utils/hashes.js +6 -6
- package/dist/utils/hashes.js.map +1 -1
- package/dist/utils/ips.js +1 -1
- package/dist/utils/{json.d.cts → json.d.mts} +1 -1
- package/dist/utils/jwt.js +3 -3
- package/dist/utils/{objects.d.cts → objects.d.mts} +9 -5
- package/dist/utils/objects.d.ts +9 -5
- package/dist/utils/objects.js +28 -0
- package/dist/utils/objects.js.map +1 -1
- package/dist/utils/{promises.d.cts → promises.d.mts} +1 -1
- package/dist/utils/promises.js +1 -1
- package/dist/utils/promises.js.map +1 -1
- package/dist/utils/react.js +1 -1
- package/dist/utils/{stores.d.cts → stores.d.mts} +3 -3
- package/dist/utils/strings.js +1 -0
- package/dist/utils/strings.js.map +1 -1
- package/package.json +9 -6
- package/dist/helpers/password.d.cts +0 -11
- package/dist/index.d.cts +0 -30
- /package/dist/config/{format.d.cts → format.d.mts} +0 -0
- /package/dist/{global.d.d.cts → global.d.d.mts} +0 -0
- /package/dist/hooks/{use-async-callback.d.cts → use-async-callback.d.mts} +0 -0
- /package/dist/hooks/{use-hash.d.cts → use-hash.d.mts} +0 -0
- /package/dist/hooks/{use-strict-memo.d.cts → use-strict-memo.d.mts} +0 -0
- /package/dist/interface/{webhooks.d.cts → webhooks.d.mts} +0 -0
- /package/dist/{sessions.d.cts → sessions.d.mts} +0 -0
- /package/dist/utils/{api-keys.d.cts → api-keys.d.mts} +0 -0
- /package/dist/utils/{arrays.d.cts → arrays.d.mts} +0 -0
- /package/dist/utils/{base64.d.cts → base64.d.mts} +0 -0
- /package/dist/utils/{booleans.d.cts → booleans.d.mts} +0 -0
- /package/dist/utils/{browser-compat.d.cts → browser-compat.d.mts} +0 -0
- /package/dist/utils/{bytes.d.cts → bytes.d.mts} +0 -0
- /package/dist/utils/{compile-time.d.cts → compile-time.d.mts} +0 -0
- /package/dist/utils/{crypto.d.cts → crypto.d.mts} +0 -0
- /package/dist/utils/{dates.d.cts → dates.d.mts} +0 -0
- /package/dist/utils/{dom.d.cts → dom.d.mts} +0 -0
- /package/dist/utils/{env.d.cts → env.d.mts} +0 -0
- /package/dist/utils/{fs.d.cts → fs.d.mts} +0 -0
- /package/dist/utils/{functions.d.cts → functions.d.mts} +0 -0
- /package/dist/utils/{geo.d.cts → geo.d.mts} +0 -0
- /package/dist/utils/{globals.d.cts → globals.d.mts} +0 -0
- /package/dist/utils/{hashes.d.cts → hashes.d.mts} +0 -0
- /package/dist/utils/{html.d.cts → html.d.mts} +0 -0
- /package/dist/utils/{http.d.cts → http.d.mts} +0 -0
- /package/dist/utils/{ips.d.cts → ips.d.mts} +0 -0
- /package/dist/utils/{jwt.d.cts → jwt.d.mts} +0 -0
- /package/dist/utils/{locks.d.cts → locks.d.mts} +0 -0
- /package/dist/utils/{maps.d.cts → maps.d.mts} +0 -0
- /package/dist/utils/{math.d.cts → math.d.mts} +0 -0
- /package/dist/utils/{node-http.d.cts → node-http.d.mts} +0 -0
- /package/dist/utils/{numbers.d.cts → numbers.d.mts} +0 -0
- /package/dist/utils/{oauth.d.cts → oauth.d.mts} +0 -0
- /package/dist/utils/{passkey.d.cts → passkey.d.mts} +0 -0
- /package/dist/utils/{proxies.d.cts → proxies.d.mts} +0 -0
- /package/dist/utils/{react.d.cts → react.d.mts} +0 -0
- /package/dist/utils/{results.d.cts → results.d.mts} +0 -0
- /package/dist/utils/{sentry.d.cts → sentry.d.mts} +0 -0
- /package/dist/utils/{strings.d.cts → strings.d.mts} +0 -0
- /package/dist/utils/{strings.nicify.test.d.cts → strings.nicify.test.d.mts} +0 -0
- /package/dist/utils/{types.d.cts → types.d.mts} +0 -0
- /package/dist/utils/{unicode.d.cts → unicode.d.mts} +0 -0
- /package/dist/utils/{urls.d.cts → urls.d.mts} +0 -0
- /package/dist/utils/{uuids.d.cts → uuids.d.mts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema-fields.ts"],"sourcesContent":["import * as yup from \"yup\";\nimport { KnownErrors } from \".\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit } from \"./utils/objects\";\nimport { isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, TDefault, TFlags>,\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys. Fix this in the future. Provided key: ${path}`);\n return yup.reach(this, path) as any;\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args);\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args);\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args);\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args);\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(...args: Parameters<typeof yup.tuple<T>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(...args);\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n );\n\n // we don't want to update the type of `object` to have a default flag\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return yupMixed().test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.ISchema<any>[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n const [first] = args;\n const firstDesc = first.describe();\n for (const schema of args) {\n const desc = schema.describe();\n if (desc.type !== firstDesc.type) throw new StackAssertionError(`yupUnion must have schemas of the same type (got: ${firstDesc.type} and ${desc.type})`, { first, schema, firstDesc, desc });\n }\n\n return yupMixed().test('is-one-of', 'Invalid value', async (value, context) => {\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: `${context.path} is not matched by any of the provided schemas:\\n${errors.map((e: any, i) => '\\tSchema ' + i + \": \\n\\t\\t\" + e.errors.join('\\n\\t\\t')).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<string, yup.InferType<T>>> {\n return yupObject().unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nundefined?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectUserCountSchema = yupNumber().meta({ openapiField: { description: 'The number of users in this project', exampleValue: 10 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-neon-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the Neon integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Neon authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_NEON_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined().nonEmpty(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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9N,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,UAAU,YAAY,QAAI,4CAA+B,KAAK,SAAK,wBAAS,+FAA+F,KAAK,EAAE;AACzL,aAAW,oBAAoB,KAAK,MAAM,QAAQ,IAAI,yCAAyC,IAAI,GAAG;AACpG,QAAI,aAAa,iBAAiB,aAAa,iBAAiB,iBAAiB,cAAe,QAAO;AAAA,EACzG;AACA,SAAO;AACT,CAAC;AAGM,SAAS,eACd,QACA,UACG;AACH,QAAM,UAAU,OAAO,QAAQ,QAAQ;AACvC,SAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,GAAG,GAAG;AAAA,IAC9C,IAAI,IAAI,WAAkB,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,UAAU,UAAU,OAAO,KAAK,CAAC;AAAA,IACxF,MAAM,CAACC,YAAcA,QAAO,QAAQ;AAAA,IACpC,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;AAEO,SAAS,0BACd,QACA,UACG;AACH,QAAM,UAAU,OAAO,QAAQ,QAAQ;AACvC,SAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,GAAG,GAAG;AAAA,IAC9C,IAAI,IAAI,WAAkB,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,UAAU,UAAU,OAAO,KAAK,CAAC;AAAA,IACxF,MAAM,CAACA,YAAcA,QAAO,QAAQ,EAAE,SAAS;AAAA,IAC/C,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;","names":["object","schema"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema-fields.ts"],"sourcesContent":["import * as yup from \"yup\";\nimport { KnownErrors } from \".\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit } from \"./utils/objects\";\nimport { isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, TDefault, TFlags>,\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys. Fix this in the future. Provided key: ${path}`);\n return yup.reach(this, path) as any;\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args);\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args);\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args);\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args);\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(...args: Parameters<typeof yup.tuple<T>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(...args);\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n );\n\n // we don't want to update the type of `object` to have a default flag\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return yupMixed().test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.ISchema<any>[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n const [first] = args;\n const firstDesc = first.describe();\n for (const schema of args) {\n const desc = schema.describe();\n if (desc.type !== firstDesc.type) throw new StackAssertionError(`yupUnion must have schemas of the same type (got: ${firstDesc.type} and ${desc.type})`, { first, schema, firstDesc, desc });\n }\n\n return yupMixed().test('is-one-of', 'Invalid value', async (value, context) => {\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: `${context.path} is not matched by any of the provided schemas:\\n${errors.map((e: any, i) => '\\tSchema ' + i + \": \\n\\t\\t\" + e.errors.join('\\n\\t\\t')).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<string, yup.InferType<T>>> {\n return yupObject().unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nundefined?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectBranchIdSchema = yupString().nonEmpty().max(255).meta({ openapiField: { description: _idDescription('project branch'), exampleValue: 'main' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectUserCountSchema = yupNumber().meta({ openapiField: { description: 'The number of users in this project', exampleValue: 10 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-neon-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the Neon integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Neon authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_NEON_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index)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IACpC,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;AAEO,SAAS,0BACd,QACA,UACG;AACH,QAAM,UAAU,OAAO,QAAQ,QAAQ;AACvC,SAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,GAAG,GAAG;AAAA,IAC9C,IAAI,IAAI,WAAkB,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,UAAU,UAAU,OAAO,KAAK,CAAC;AAAA,IACxF,MAAM,CAACA,YAAcA,QAAO,QAAQ,EAAE,SAAS;AAAA,IAC/C,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;","names":["object","schema"]}
|
package/dist/sessions.js
CHANGED
|
@@ -35,7 +35,7 @@ __export(sessions_exports, {
|
|
|
35
35
|
RefreshToken: () => RefreshToken
|
|
36
36
|
});
|
|
37
37
|
module.exports = __toCommonJS(sessions_exports);
|
|
38
|
-
var jose = __toESM(require("jose")
|
|
38
|
+
var jose = __toESM(require("jose"));
|
|
39
39
|
var import_errors = require("./utils/errors");
|
|
40
40
|
var import_stores = require("./utils/stores");
|
|
41
41
|
var AccessToken = class {
|
package/dist/utils/api-keys.js
CHANGED
|
@@ -35,7 +35,7 @@ __export(api_keys_exports, {
|
|
|
35
35
|
parseProjectApiKey: () => parseProjectApiKey
|
|
36
36
|
});
|
|
37
37
|
module.exports = __toCommonJS(api_keys_exports);
|
|
38
|
-
var import_crc32 = __toESM(require("crc/crc32")
|
|
38
|
+
var import_crc32 = __toESM(require("crc/crc32"));
|
|
39
39
|
var import_bytes = require("./bytes");
|
|
40
40
|
var import_crypto = require("./crypto");
|
|
41
41
|
var import_errors = require("./errors");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RateLimitOptions, ReactPromise } from './promises.
|
|
2
|
-
import './results.
|
|
1
|
+
import { RateLimitOptions, ReactPromise } from './promises.mjs';
|
|
2
|
+
import './results.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Can be used to cache the result of a function call, for example for the `use` hook in React.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Json } from './json.
|
|
2
|
-
import './results.
|
|
1
|
+
import { Json } from './json.mjs';
|
|
2
|
+
import './results.mjs';
|
|
3
3
|
|
|
4
4
|
declare function throwErr(errorMessage: string, extraData?: any): never;
|
|
5
5
|
declare function throwErr(error: Error): never;
|
|
@@ -45,6 +45,7 @@ type StatusErrorConstructorParameters = [
|
|
|
45
45
|
message: string
|
|
46
46
|
];
|
|
47
47
|
declare class StatusError extends Error {
|
|
48
|
+
private readonly __stackStatusErrorBrand;
|
|
48
49
|
name: string;
|
|
49
50
|
readonly statusCode: number;
|
|
50
51
|
static BadRequest: {
|
|
@@ -208,6 +209,7 @@ declare class StatusError extends Error {
|
|
|
208
209
|
message: string;
|
|
209
210
|
};
|
|
210
211
|
constructor(...args: StatusErrorConstructorParameters);
|
|
212
|
+
static isStatusError(error: unknown): error is StatusError;
|
|
211
213
|
isClientError(): boolean;
|
|
212
214
|
isServerError(): boolean;
|
|
213
215
|
getStatusCode(): number;
|
package/dist/utils/errors.d.ts
CHANGED
|
@@ -45,6 +45,7 @@ type StatusErrorConstructorParameters = [
|
|
|
45
45
|
message: string
|
|
46
46
|
];
|
|
47
47
|
declare class StatusError extends Error {
|
|
48
|
+
private readonly __stackStatusErrorBrand;
|
|
48
49
|
name: string;
|
|
49
50
|
readonly statusCode: number;
|
|
50
51
|
static BadRequest: {
|
|
@@ -208,6 +209,7 @@ declare class StatusError extends Error {
|
|
|
208
209
|
message: string;
|
|
209
210
|
};
|
|
210
211
|
constructor(...args: StatusErrorConstructorParameters);
|
|
212
|
+
static isStatusError(error: unknown): error is StatusError;
|
|
211
213
|
isClientError(): boolean;
|
|
212
214
|
isServerError(): boolean;
|
|
213
215
|
getStatusCode(): number;
|
package/dist/utils/errors.js
CHANGED
|
@@ -110,12 +110,16 @@ var StatusError = class extends Error {
|
|
|
110
110
|
status = status.statusCode;
|
|
111
111
|
}
|
|
112
112
|
super(message);
|
|
113
|
+
this.__stackStatusErrorBrand = "stack-status-error-brand-sentinel";
|
|
113
114
|
this.name = "StatusError";
|
|
114
115
|
this.statusCode = status;
|
|
115
116
|
if (!message) {
|
|
116
117
|
throw new StackAssertionError("StatusError always requires a message unless a Status object is passed", { cause: this });
|
|
117
118
|
}
|
|
118
119
|
}
|
|
120
|
+
static isStatusError(error) {
|
|
121
|
+
return typeof error === "object" && error !== null && "__stackStatusErrorBrand" in error && error.__stackStatusErrorBrand === "stack-status-error-brand-sentinel";
|
|
122
|
+
}
|
|
119
123
|
isClientError() {
|
|
120
124
|
return this.statusCode >= 400 && this.statusCode < 500;
|
|
121
125
|
}
|
package/dist/utils/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA0B;AAE1B,qBAAqB;AACrB,qBAAuB;AAMhB,SAAS,YAAY,MAAoB;AAC9C,MAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,UAAM,IAAI,oBAAoB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAAA,EAChD,WAAW,KAAK,CAAC,aAAa,OAAO;AACnC,UAAM,KAAK,CAAC;AAAA,EACd,OAAO;AAEL,UAAM,IAAI,YAAY,GAAG,IAAI;AAAA,EAC/B;AACF;AAEA,SAAS,yBAAyB,OAAuB;AAEvD,QAAM,eAAe,IAAI,MAAM,EAAE,OAAO,WAAW,SAAS;AAC5D,SAAO,MAAM,MAAM,IAAI,EAAE,MAAM,eAAe,IAAI,CAAC,EAAE,KAAK,IAAI;AAChE;AAwBO,SAAS,kBAAkB,UAAiB,QAAuB;AAExE,QAAM,qBAAqB,MAAM,OAAO,SAAS,IAAI;AAMrD,QAAM,YAAY,yBAAyB,IAAI,MAAM,EAAE,SAAS,EAAE,EAAE,MAAM,IAAI,EAA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AAmB;AA5BpE,YA6BG,uBAAuB,EAAE,YAAY,KAAK,SAAS,wBAAwB;AA7B9E,YA8BG,kBAAkB,EAAE,YAAY,KAAK,SAAS,oBAAoB;AA9BrE,YA+BG,8BAA8B,EAAE,YAAY,KAAK,SAAS,kCAAkC;AA/B/F,YAgCG,6BAA6B,EAAE,YAAY,KAAK,SAAS,gCAAgC;AAhC5F,YAkCG,sBAAsB,EAAE,YAAY,KAAK,SAAS,wBAAwB;AAlC7E,YAmCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AAnClE,YAoCG,aAAa,EAAE,YAAY,KAAK,SAAS,cAAc;AApC1D,YAqCG,qBAAqB,EAAE,YAAY,KAAK,SAAS,sBAAsB;AArC1E,YAsCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AAtClE,YAuCG,0BAA0B,EAAE,YAAY,KAAK,SAAS,6BAA6B;AAvCtF,YAwCG,wBAAwB,EAAE,YAAY,KAAK,SAAS,0BAA0B;AAxCjF,YAyCG,sBAAsB,EAAE,YAAY,KAAK,SAAS,uBAAuB;AAzC5E,YA0CG,eAAe,EAAE,YAAY,KAAK,SAAS,gBAAgB;AA1C9D,YA2CG,cAAc,EAAE,YAAY,KAAK,SAAS,eAAe;AA3C5D,YA4CG,gCAAgC,EAAE,YAAY,KAAK,SAAS,kCAAkC;AA4D9G,YAAY,UAAU,OAAO;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA0B;AAE1B,qBAAqB;AACrB,qBAAuB;AAMhB,SAAS,YAAY,MAAoB;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AwCG,0BAA0B,EAAE,YAAY,KAAK,SAAS,6BAA6B;AAxCtF,YAyCG,wBAAwB,EAAE,YAAY,KAAK,SAAS,0BAA0B;AAzCjF,YA0CG,sBAAsB,EAAE,YAAY,KAAK,SAAS,uBAAuB;AA1C5E,YA2CG,eAAe,EAAE,YAAY,KAAK,SAAS,gBAAgB;AA3C9D,YA4CG,cAAc,EAAE,YAAY,KAAK,SAAS,eAAe;AA5C5D,YA6CG,gCAAgC,EAAE,YAAY,KAAK,SAAS,kCAAkC;AAiE9G,YAAY,UAAU,OAAO;","names":[]}
|
package/dist/utils/fs.js
CHANGED
|
@@ -35,8 +35,8 @@ __export(fs_exports, {
|
|
|
35
35
|
writeFileSyncIfChanged: () => writeFileSyncIfChanged
|
|
36
36
|
});
|
|
37
37
|
module.exports = __toCommonJS(fs_exports);
|
|
38
|
-
var stackFs = __toESM(require("fs")
|
|
39
|
-
var path = __toESM(require("path")
|
|
38
|
+
var stackFs = __toESM(require("fs"));
|
|
39
|
+
var path = __toESM(require("path"));
|
|
40
40
|
async function list(path2) {
|
|
41
41
|
return await stackFs.promises.readdir(path2);
|
|
42
42
|
}
|
package/dist/utils/hashes.js
CHANGED
|
@@ -37,7 +37,7 @@ __export(hashes_exports, {
|
|
|
37
37
|
sha512: () => sha512
|
|
38
38
|
});
|
|
39
39
|
module.exports = __toCommonJS(hashes_exports);
|
|
40
|
-
var
|
|
40
|
+
var import_bcryptjs = __toESM(require("bcryptjs"));
|
|
41
41
|
var import_errors = require("./errors");
|
|
42
42
|
async function sha512(input) {
|
|
43
43
|
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
@@ -48,13 +48,13 @@ async function hashPassword(password) {
|
|
|
48
48
|
if (passwordBytes.length >= 72) {
|
|
49
49
|
throw new import_errors.StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });
|
|
50
50
|
}
|
|
51
|
-
const salt = await
|
|
52
|
-
return await
|
|
51
|
+
const salt = await import_bcryptjs.default.genSalt(10);
|
|
52
|
+
return await import_bcryptjs.default.hash(password, salt);
|
|
53
53
|
}
|
|
54
54
|
async function comparePassword(password, hash) {
|
|
55
55
|
switch (await getPasswordHashAlgorithm(hash)) {
|
|
56
56
|
case "bcrypt": {
|
|
57
|
-
return await
|
|
57
|
+
return await import_bcryptjs.default.compare(password, hash);
|
|
58
58
|
}
|
|
59
59
|
default: {
|
|
60
60
|
return false;
|
|
@@ -70,10 +70,10 @@ async function getPasswordHashAlgorithm(hash) {
|
|
|
70
70
|
}
|
|
71
71
|
if (hash.match(/^\$2[ayb]\$.{56}$/)) {
|
|
72
72
|
try {
|
|
73
|
-
if (
|
|
73
|
+
if (import_bcryptjs.default.getRounds(hash) > 16) {
|
|
74
74
|
return void 0;
|
|
75
75
|
}
|
|
76
|
-
await
|
|
76
|
+
await import_bcryptjs.default.compare("any string", hash);
|
|
77
77
|
return "bcrypt";
|
|
78
78
|
} catch (e) {
|
|
79
79
|
console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);
|
package/dist/utils/hashes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/hashes.tsx"],"sourcesContent":["import bcrypt from '
|
|
1
|
+
{"version":3,"sources":["../../src/utils/hashes.tsx"],"sourcesContent":["import bcrypt from 'bcryptjs';\nimport { StackAssertionError } from './errors';\n\nexport async function sha512(input: Uint8Array | string): Promise<Uint8Array> {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n return new Uint8Array(await crypto.subtle.digest(\"SHA-512\", bytes));\n}\n\nexport async function hashPassword(password: string) {\n const passwordBytes = new TextEncoder().encode(password);\n if (passwordBytes.length >= 72) {\n throw new StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });\n }\n const salt = await bcrypt.genSalt(10);\n return await bcrypt.hash(password, salt);\n}\n\nexport async function comparePassword(password: string, hash: string): Promise<boolean> {\n switch (await getPasswordHashAlgorithm(hash)) {\n case \"bcrypt\": {\n return await bcrypt.compare(password, hash);\n }\n default: {\n return false;\n }\n }\n}\n\nexport async function isPasswordHashValid(hash: string) {\n return !!(await getPasswordHashAlgorithm(hash));\n}\n\nexport async function getPasswordHashAlgorithm(hash: string): Promise<\"bcrypt\" | undefined> {\n if (typeof hash !== \"string\") {\n throw new StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });\n }\n if (hash.match(/^\\$2[ayb]\\$.{56}$/)) {\n try {\n if (bcrypt.getRounds(hash) > 16) {\n return undefined;\n }\n await bcrypt.compare(\"any string\", hash);\n return \"bcrypt\";\n } catch (e) {\n console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAmB;AACnB,oBAAoC;AAEpC,eAAsB,OAAO,OAAiD;AAC5E,QAAM,QAAQ,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC5E,SAAO,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;AACpE;AAEA,eAAsB,aAAa,UAAkB;AACnD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,QAAQ;AACvD,MAAI,cAAc,UAAU,IAAI;AAC9B,UAAM,IAAI,kCAAoB,mCAAmC,EAAE,KAAK,cAAc,OAAO,CAAC;AAAA,EAChG;AACA,QAAM,OAAO,MAAM,gBAAAA,QAAO,QAAQ,EAAE;AACpC,SAAO,MAAM,gBAAAA,QAAO,KAAK,UAAU,IAAI;AACzC;AAEA,eAAsB,gBAAgB,UAAkB,MAAgC;AACtF,UAAQ,MAAM,yBAAyB,IAAI,GAAG;AAAA,IAC5C,KAAK,UAAU;AACb,aAAO,MAAM,gBAAAA,QAAO,QAAQ,UAAU,IAAI;AAAA,IAC5C;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,eAAsB,oBAAoB,MAAc;AACtD,SAAO,CAAC,CAAE,MAAM,yBAAyB,IAAI;AAC/C;AAEA,eAAsB,yBAAyB,MAA6C;AAC1F,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI,kCAAoB,uDAAuD,EAAE,KAAK,CAAC;AAAA,EAC/F;AACA,MAAI,KAAK,MAAM,mBAAmB,GAAG;AACnC,QAAI;AACF,UAAI,gBAAAA,QAAO,UAAU,IAAI,IAAI,IAAI;AAC/B,eAAO;AAAA,MACT;AACA,YAAM,gBAAAA,QAAO,QAAQ,cAAc,IAAI;AACvC,aAAO;AAAA,IACT,SAAS,GAAG;AACV,cAAQ,KAAK,2EAA2E,CAAC;AACzF,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,WAAO;AAAA,EACT;AACF;","names":["bcrypt"]}
|
package/dist/utils/ips.js
CHANGED
|
@@ -34,7 +34,7 @@ __export(ips_exports, {
|
|
|
34
34
|
isIpAddress: () => isIpAddress
|
|
35
35
|
});
|
|
36
36
|
module.exports = __toCommonJS(ips_exports);
|
|
37
|
-
var import_ip_regex = __toESM(require("ip-regex")
|
|
37
|
+
var import_ip_regex = __toESM(require("ip-regex"));
|
|
38
38
|
function isIpAddress(ip) {
|
|
39
39
|
return (0, import_ip_regex.default)({ exact: true }).test(ip);
|
|
40
40
|
}
|
package/dist/utils/jwt.js
CHANGED
|
@@ -40,9 +40,9 @@ __export(jwt_exports, {
|
|
|
40
40
|
verifyJWT: () => verifyJWT
|
|
41
41
|
});
|
|
42
42
|
module.exports = __toCommonJS(jwt_exports);
|
|
43
|
-
var import_crypto = __toESM(require("crypto")
|
|
44
|
-
var import_elliptic = __toESM(require("elliptic")
|
|
45
|
-
var jose = __toESM(require("jose")
|
|
43
|
+
var import_crypto = __toESM(require("crypto"));
|
|
44
|
+
var import_elliptic = __toESM(require("elliptic"));
|
|
45
|
+
var jose = __toESM(require("jose"));
|
|
46
46
|
var import_errors = require("jose/errors");
|
|
47
47
|
var import_bytes = require("./bytes");
|
|
48
48
|
var import_errors2 = require("./errors");
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
declare function isNotNull<T>(value: T): value is NonNullable<T>;
|
|
2
|
-
type DeepPartial<T> = T extends object ? {
|
|
2
|
+
type DeepPartial<T> = T extends object ? (T extends (infer E)[] ? T : {
|
|
3
3
|
[P in keyof T]?: DeepPartial<T[P]>;
|
|
4
|
-
} : T;
|
|
5
|
-
type DeepRequired<T> = T extends object ? {
|
|
4
|
+
}) : T;
|
|
5
|
+
type DeepRequired<T> = T extends object ? (T extends (infer E)[] ? T : {
|
|
6
6
|
[P in keyof T]-?: DeepRequired<T[P]>;
|
|
7
|
-
} : T;
|
|
7
|
+
}) : T;
|
|
8
8
|
/**
|
|
9
9
|
* Assumes both objects are primitives, arrays, or non-function plain objects, and compares them deeply.
|
|
10
10
|
*
|
|
@@ -51,8 +51,12 @@ declare function deepFilterUndefined<T extends object>(obj: T): DeepFilterUndefi
|
|
|
51
51
|
declare function pick<T extends {}, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
|
|
52
52
|
declare function omit<T extends {}, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
53
53
|
declare function split<T extends {}, K extends keyof T>(obj: T, keys: K[]): [Pick<T, K>, Omit<T, K>];
|
|
54
|
+
declare function mapValues<T extends object, U>(obj: T, fn: (value: T extends (infer E)[] ? E : T[keyof T]) => U): Record<keyof T, U>;
|
|
55
|
+
declare function sortKeys<T extends object>(obj: T): T;
|
|
56
|
+
declare function deepSortKeys<T extends object>(obj: T): T;
|
|
54
57
|
declare function set<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]): void;
|
|
55
58
|
declare function get<T extends object, K extends keyof T>(obj: T, key: K): T[K];
|
|
59
|
+
declare function getOrUndefined<T extends object, K extends keyof T>(obj: T, key: K): T[K] | undefined;
|
|
56
60
|
declare function has<T extends object, K extends keyof T>(obj: T, key: K): obj is T & {
|
|
57
61
|
[k in K]: unknown;
|
|
58
62
|
};
|
|
@@ -62,4 +66,4 @@ declare function hasAndNotUndefined<T extends object, K extends keyof T>(obj: T,
|
|
|
62
66
|
declare function deleteKey<T extends object, K extends keyof T>(obj: T, key: K): void;
|
|
63
67
|
declare function isObjectLike(value: unknown): value is object;
|
|
64
68
|
|
|
65
|
-
export { type DeepFilterUndefined, type DeepMerge, type DeepPartial, type DeepRequired, type FilterUndefined, type FilterUndefinedOrNull, deepFilterUndefined, deepMerge, deepPlainClone, deepPlainEquals, deleteKey, filterUndefined, filterUndefinedOrNull, get, has, hasAndNotUndefined, isCloneable, isNotNull, isObjectLike, omit, pick, set, shallowClone, split, typedAssign, typedEntries, typedFromEntries, typedKeys, typedValues };
|
|
69
|
+
export { type DeepFilterUndefined, type DeepMerge, type DeepPartial, type DeepRequired, type FilterUndefined, type FilterUndefinedOrNull, deepFilterUndefined, deepMerge, deepPlainClone, deepPlainEquals, deepSortKeys, deleteKey, filterUndefined, filterUndefinedOrNull, get, getOrUndefined, has, hasAndNotUndefined, isCloneable, isNotNull, isObjectLike, mapValues, omit, pick, set, shallowClone, sortKeys, split, typedAssign, typedEntries, typedFromEntries, typedKeys, typedValues };
|
package/dist/utils/objects.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
declare function isNotNull<T>(value: T): value is NonNullable<T>;
|
|
2
|
-
type DeepPartial<T> = T extends object ? {
|
|
2
|
+
type DeepPartial<T> = T extends object ? (T extends (infer E)[] ? T : {
|
|
3
3
|
[P in keyof T]?: DeepPartial<T[P]>;
|
|
4
|
-
} : T;
|
|
5
|
-
type DeepRequired<T> = T extends object ? {
|
|
4
|
+
}) : T;
|
|
5
|
+
type DeepRequired<T> = T extends object ? (T extends (infer E)[] ? T : {
|
|
6
6
|
[P in keyof T]-?: DeepRequired<T[P]>;
|
|
7
|
-
} : T;
|
|
7
|
+
}) : T;
|
|
8
8
|
/**
|
|
9
9
|
* Assumes both objects are primitives, arrays, or non-function plain objects, and compares them deeply.
|
|
10
10
|
*
|
|
@@ -51,8 +51,12 @@ declare function deepFilterUndefined<T extends object>(obj: T): DeepFilterUndefi
|
|
|
51
51
|
declare function pick<T extends {}, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
|
|
52
52
|
declare function omit<T extends {}, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
53
53
|
declare function split<T extends {}, K extends keyof T>(obj: T, keys: K[]): [Pick<T, K>, Omit<T, K>];
|
|
54
|
+
declare function mapValues<T extends object, U>(obj: T, fn: (value: T extends (infer E)[] ? E : T[keyof T]) => U): Record<keyof T, U>;
|
|
55
|
+
declare function sortKeys<T extends object>(obj: T): T;
|
|
56
|
+
declare function deepSortKeys<T extends object>(obj: T): T;
|
|
54
57
|
declare function set<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]): void;
|
|
55
58
|
declare function get<T extends object, K extends keyof T>(obj: T, key: K): T[K];
|
|
59
|
+
declare function getOrUndefined<T extends object, K extends keyof T>(obj: T, key: K): T[K] | undefined;
|
|
56
60
|
declare function has<T extends object, K extends keyof T>(obj: T, key: K): obj is T & {
|
|
57
61
|
[k in K]: unknown;
|
|
58
62
|
};
|
|
@@ -62,4 +66,4 @@ declare function hasAndNotUndefined<T extends object, K extends keyof T>(obj: T,
|
|
|
62
66
|
declare function deleteKey<T extends object, K extends keyof T>(obj: T, key: K): void;
|
|
63
67
|
declare function isObjectLike(value: unknown): value is object;
|
|
64
68
|
|
|
65
|
-
export { type DeepFilterUndefined, type DeepMerge, type DeepPartial, type DeepRequired, type FilterUndefined, type FilterUndefinedOrNull, deepFilterUndefined, deepMerge, deepPlainClone, deepPlainEquals, deleteKey, filterUndefined, filterUndefinedOrNull, get, has, hasAndNotUndefined, isCloneable, isNotNull, isObjectLike, omit, pick, set, shallowClone, split, typedAssign, typedEntries, typedFromEntries, typedKeys, typedValues };
|
|
69
|
+
export { type DeepFilterUndefined, type DeepMerge, type DeepPartial, type DeepRequired, type FilterUndefined, type FilterUndefinedOrNull, deepFilterUndefined, deepMerge, deepPlainClone, deepPlainEquals, deepSortKeys, deleteKey, filterUndefined, filterUndefinedOrNull, get, getOrUndefined, has, hasAndNotUndefined, isCloneable, isNotNull, isObjectLike, mapValues, omit, pick, set, shallowClone, sortKeys, split, typedAssign, typedEntries, typedFromEntries, typedKeys, typedValues };
|