@sqrzro/server 4.0.0-alpha.3 → 4.0.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.d.ts +13 -11
- package/dist/auth/index.js +1 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/chunk-3A4JSFVE.js +2 -0
- package/dist/chunk-3A4JSFVE.js.map +1 -0
- package/dist/{chunk-AGS5PPG2.js → chunk-3JA7XHAG.js} +2 -2
- package/dist/chunk-3JA7XHAG.js.map +1 -0
- package/dist/chunk-C2XLUXVN.js +2 -0
- package/dist/chunk-C2XLUXVN.js.map +1 -0
- package/dist/chunk-CESWDV42.js +2 -0
- package/dist/chunk-CESWDV42.js.map +1 -0
- package/dist/chunk-DOBAUBXG.js +2 -0
- package/dist/chunk-DOBAUBXG.js.map +1 -0
- package/dist/chunk-KC7SPWBL.js +2 -0
- package/dist/chunk-KC7SPWBL.js.map +1 -0
- package/dist/chunk-U27WABYY.js +2 -0
- package/dist/chunk-U27WABYY.js.map +1 -0
- package/dist/chunk-UCMLSO7F.js +3 -0
- package/dist/chunk-UCMLSO7F.js.map +1 -0
- package/dist/cli/scripts/db-generate.ts +1 -1
- package/dist/cli/static/{drizzle.config.js → drizzle.config.cjs} +3 -3
- package/dist/csv/index.d.ts +7 -0
- package/dist/csv/index.js +2 -0
- package/dist/csv/index.js.map +1 -0
- package/dist/database/index.d.ts +92 -33
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.d.ts +33 -4
- package/dist/forms/index.js +1 -1
- package/dist/forms/index.js.map +1 -1
- package/dist/{interfaces-BheedaEI.d.ts → interfaces-DTUqy5Oj.d.ts} +4 -3
- package/dist/interfaces-Gqu85VTW.d.ts +7 -0
- package/dist/json/index.d.ts +3 -1
- package/dist/json/index.js +1 -1
- package/dist/json/index.js.map +1 -1
- package/dist/mail/index.d.ts +20 -0
- package/dist/mail/index.js +3 -0
- package/dist/mail/index.js.map +1 -0
- package/dist/proxy/index.d.ts +14 -0
- package/dist/proxy/index.js +2 -0
- package/dist/proxy/index.js.map +1 -0
- package/dist/storage/index.d.ts +30 -0
- package/dist/storage/index.js +2 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/utility/index.d.ts +8 -5
- package/dist/utility/index.js +1 -1
- package/package.json +34 -15
- package/dist/chunk-37TYQL5Y.js +0 -2
- package/dist/chunk-37TYQL5Y.js.map +0 -1
- package/dist/chunk-AGS5PPG2.js.map +0 -1
- package/dist/chunk-QE347FVL.js +0 -2
- package/dist/chunk-QE347FVL.js.map +0 -1
- package/dist/chunk-XSJ4OEIH.js +0 -2
- package/dist/chunk-XSJ4OEIH.js.map +0 -1
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,15 +1,23 @@
|
|
|
1
|
+
import { A as AuthSession } from '../interfaces-Gqu85VTW.js';
|
|
1
2
|
import { ResetType, AuthUserTable } from './utility/schema.js';
|
|
2
3
|
import { NextRequest } from 'next/server';
|
|
3
|
-
import { M as MakeNullOptional } from '../interfaces-
|
|
4
|
+
import { M as MakeNullOptional } from '../interfaces-DTUqy5Oj.js';
|
|
4
5
|
import 'drizzle-orm/pg-core';
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
interface MFAObject {
|
|
8
|
+
key: string;
|
|
9
|
+
url: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
declare function createMFA(name: string, email: string): Promise<MFAObject>;
|
|
13
|
+
|
|
14
|
+
declare function validateMFA(code: string): Promise<boolean>;
|
|
7
15
|
|
|
8
16
|
declare function updatePasswordWithPassword(): Promise<void>;
|
|
9
17
|
|
|
10
|
-
declare function updatePasswordWithToken(token: string, newPassword: string): Promise<
|
|
18
|
+
declare function updatePasswordWithToken(type: ResetType, token: string, newPassword: string): Promise<string>;
|
|
11
19
|
|
|
12
|
-
declare function createReset(type: ResetType, email: string): Promise<string | null>;
|
|
20
|
+
declare function createReset(type: ResetType, email: string, role?: number): Promise<string | null>;
|
|
13
21
|
|
|
14
22
|
declare function validateReset(type: ResetType, token: string): Promise<boolean>;
|
|
15
23
|
|
|
@@ -19,12 +27,6 @@ declare function deleteSession(): Promise<void>;
|
|
|
19
27
|
|
|
20
28
|
declare function deleteUserSessions(): Promise<void>;
|
|
21
29
|
|
|
22
|
-
interface AuthSession {
|
|
23
|
-
expires: Date;
|
|
24
|
-
secret: string;
|
|
25
|
-
userID: string;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
30
|
declare function uncached_validateSession(cookies?: NextRequest['cookies']): Promise<AuthSession | null>;
|
|
29
31
|
declare const validateSession: typeof uncached_validateSession;
|
|
30
32
|
|
|
@@ -46,4 +48,4 @@ declare function getSessionUser(): ReturnType<typeof uncached_getSessionUser>;
|
|
|
46
48
|
|
|
47
49
|
declare function validateUser(email: string, password: string): Promise<string>;
|
|
48
50
|
|
|
49
|
-
export { createMFA, createReset, createSession, createUser, deleteSession, deleteUser, deleteUserSessions, ensureSessionUser, getSessionUser, updatePasswordWithPassword, updatePasswordWithToken, validateReset, validateSession, validateUser };
|
|
51
|
+
export { AuthSession, createMFA, createReset, createSession, createUser, deleteSession, deleteUser, deleteUserSessions, ensureSessionUser, getSessionUser, updatePasswordWithPassword, updatePasswordWithToken, validateMFA, validateReset, validateSession, validateUser };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export{a as createMFA,e as createReset,g as createSession,j as createUser,h as deleteSession,k as deleteUser,i as deleteUserSessions,c as updatePasswordWithPassword,d as updatePasswordWithToken,b as validateMFA,f as validateReset,l as validateUser}from'../chunk-U27WABYY.js';import'../chunk-CESWDV42.js';export{j as ensureSessionUser,i as getSessionUser,h as validateSession}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import'../chunk-3JA7XHAG.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/auth/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/mfas/create-mfa.ts","../../src/auth/passwords/update-password-with-password.ts","../../src/auth/resets/utility/delete-user-resets.ts","../../src/auth/resets/utility/get-reset-by-id.ts","../../src/auth/utility/hash-secret.ts","../../src/auth/passwords/update-password-with-token.ts","../../src/auth/users/utility/get-user-by-email.ts","../../src/auth/resets/create-reset.ts","../../src/auth/resets/validate-reset.ts","../../src/auth/utility/create-secure-random-string.ts","../../src/auth/sessions/create-session.ts","../../src/auth/sessions/delete-session.ts","../../src/auth/sessions/delete-user-sessions.ts","../../src/auth/users/create-user.ts","../../src/auth/users/delete-user.ts","../../src/auth/users/validate-user.ts"],"names":["createMFA","create_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","db_default","authResetTable","and","eq","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","role","ensure_role_default","expiry","results","authUserTable","isNull","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","getUserByEmail","email","get_user_by_default","get_user_by_email_default","TOKEN_LENGTH","createReset","user","generate_id_default","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","expires","storage_default","cookies","AUTH_COOKIE_NAME","create_session_default","deleteSession","cookie","get_session_cookie_default","delete_session_default","deleteUserSessions","delete_user_sessions_default","createUser","data","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"obAAA,SAASA,CAAAA,EAA2B,CAChC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECJf,SAASE,CAAAA,EAA4C,CACj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QH,GChBf,SAASI,EAAAA,EAA4B,CACjC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,GAAQD,GCEf,eAAeE,EAAAA,CAAapC,CAAAA,CAAeqC,CAAAA,CAAmC,CAC1E,IAAMhC,CAAAA,CAAO,MAAMH,CAAAA,CAAeF,CAAK,CAAA,CAEvC,GAAI,CAACK,CAAAA,EAAM,QAAA,EAAY,CAAE,MAAMb,CAAAA,CAAO,QAAQ6C,CAAAA,CAAUhC,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIiC,GAAAA,CAAgB,CAAE,MAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,EAGzD,OAAOjC,CAAAA,CAAK,EAChB,KAEOkC,EAAAA,CAAQH","file":"index.js","sourcesContent":["function createMFA(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default createMFA;\n","function updatePasswordWithPassword(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default updatePasswordWithPassword;\n","import { and, eq } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { authResetTable } from '../../utility/schema';\n\nimport type { ResetType } from './interfaces';\n\nasync function deleteUserResets(type: ResetType, userID: string): Promise<void> {\n await db\n .delete(authResetTable)\n .where(and(eq(authResetTable.userID, userID), eq(authResetTable.type, type)));\n}\n\nexport default deleteUserResets;\n","import { and, eq, gte, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { AuthUser } from '../../users/utility/interfaces';\nimport { AUTH_INVITE_EXPIRY_HOURS, AUTH_RESET_EXPIRY_HOURS } from '../../utility/config';\nimport ensureRole from '../../utility/ensure-role';\nimport { authResetTable, authUserTable } from '../../utility/schema';\n\nimport type { AuthReset, ResetType } from './interfaces';\n\nconst EXPIRIES: Record<ResetType, number> = {\n INVITE: AUTH_INVITE_EXPIRY_HOURS,\n MFA: AUTH_RESET_EXPIRY_HOURS,\n PASSWORD: AUTH_RESET_EXPIRY_HOURS,\n};\n\nasync function getResetByID(\n type: ResetType,\n id: string\n): Promise<(AuthReset & { user: AuthUser }) | null> {\n const role = ensureRole();\n\n const expiry = new Date();\n expiry.setHours(expiry.getHours() - EXPIRIES[type]);\n\n const results = await db\n .select()\n .from(authResetTable)\n .innerJoin(\n authUserTable,\n and(\n eq(authUserTable.id, authResetTable.userID),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .where(\n and(\n eq(authResetTable.id, id),\n eq(authResetTable.type, type),\n gte(authResetTable.createdAt, expiry)\n )\n )\n .limit(1);\n\n return results[0] ? { ...results[0].resets, user: results[0].user_credentials } : null;\n}\n\nexport default getResetByID;\n","import bcrypt from 'bcryptjs';\n\nconst PW_SALT_ROUNDS = 12;\n\nasync function hashSecret(secret: string): Promise<string> {\n return bcrypt.hash(secret, PW_SALT_ROUNDS);\n}\n\nexport default hashSecret;\n","import { eq } from 'drizzle-orm';\n\nimport db from '../../utility/db';\n\nimport deleteUserResets from '../resets/utility/delete-user-resets';\nimport getResetByID from '../resets/utility/get-reset-by-id';\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nasync function updatePasswordWithToken(token: string, newPassword: string): Promise<void> {\n const reset = await getResetByID('PASSWORD', token);\n\n if (!reset) {\n throw new Error('RESET_TOKEN_INVALID');\n }\n\n await db\n .update(authUserTable)\n .set({\n password: await hashSecret(newPassword),\n })\n .where(eq(authUserTable.id, reset.userID));\n\n await deleteUserResets('PASSWORD', reset.userID);\n}\n\nexport default updatePasswordWithToken;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string): Promise<AuthUser | null> {\n return getUserBy('email', email);\n}\n\nexport default getUserByEmail;\n","import db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authResetTable } from '../utility/schema';\n\nimport deleteUserResets from './utility/delete-user-resets';\nimport type { ResetType } from './utility/interfaces';\n\nconst TOKEN_LENGTH = 48;\n\nasync function createReset(type: ResetType, email: string): Promise<string | null> {\n const user = await getUserByEmail(email);\n\n if (!user) {\n return null;\n }\n\n await deleteUserResets(type, user.id);\n\n const id = generateID(null, TOKEN_LENGTH);\n\n await db.insert(authResetTable).values({\n createdAt: new Date(),\n id,\n type,\n userID: user.id,\n });\n\n return id;\n}\n\nexport default createReset;\n","import type { ResetType } from '../utility/schema';\n\nimport getResetByID from './utility/get-reset-by-id';\n\nasync function validateReset(type: ResetType, token: string): Promise<boolean> {\n return Boolean(await getResetByID(type, token));\n}\n\nexport default validateReset;\n","function createSecureRandomString(): string {\n\t// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)\n\tconst alphabet = \"abcdefghijkmnpqrstuvwxyz23456789\";\n\n\t// Generate 24 bytes = 192 bits of entropy.\n\t// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits\n\tconst bytes = new Uint8Array(24);\n\tcrypto.getRandomValues(bytes);\n\n\tlet id = \"\";\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\t// >> 3 \"removes\" the right-most 3 bits of the byte\n\t\tid += alphabet[bytes[i] >> 3];\n\t}\n\treturn id;\n}\n\nexport default createSecureRandomString;","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport createSecureRandomString from '../utility/create-secure-random-string';\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport ensureRole from '../utility/ensure-role';\nimport hashSecret from '../utility/hash-secret';\n\nconst DEFAULT_EXPIRES = 24;\nconst HOUR_IN_MS = 60 * 60 * 1000;\n\nasync function createSession(userID: string, expiresIn = DEFAULT_EXPIRES): Promise<void> {\n const role = ensureRole();\n\n const id = createSecureRandomString();\n const secret = createSecureRandomString();\n const token = `${id}.${secret}`;\n\n const expires = new Date(Date.now() + expiresIn * HOUR_IN_MS);\n\n await serverStorage.setItem('session', id, {\n expires,\n role,\n secret: await hashSecret(secret),\n userID,\n });\n\n (await cookies()).set(AUTH_COOKIE_NAME, token, {\n expires,\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: true,\n });\n}\n\nexport default createSession;\n","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\n\nimport getSessionCookie from './utility/get-session-cookie';\n\nasync function deleteSession(): Promise<void> {\n const cookie = await getSessionCookie();\n\n if (!cookie) {\n return;\n }\n\n await serverStorage.removeItem('session', cookie.id);\n (await cookies()).delete(AUTH_COOKIE_NAME);\n}\n\nexport default deleteSession;\n","function deleteUserSessions(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUserSessions;\n","import db from '../../utility/db';\n\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nimport type { AuthUser, AuthUserDataWithID } from './utility/interfaces';\n\nasync function createUser(data: AuthUserDataWithID): Promise<AuthUser | null> {\n const [result] = await db\n .insert(authUserTable)\n .values({ ...data, password: data.password ? await hashSecret(data.password) : null })\n .returning();\n\n return result ?? null;\n}\n\nexport default createUser;\n","function deleteUser(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUser;\n","import bcrypt from 'bcryptjs';\n\nimport ValidationError from '../../forms/utility/ValidationError';\n\nimport getUserByEmail from './utility/get-user-by-email';\n\nasync function validateUser(email: string, password: string): Promise<string> {\n const user = await getUserByEmail(email);\n\n if (!user?.password || !(await bcrypt.compare(password, user.password))) {\n throw new ValidationError({ email: '', password: '' });\n }\n\n return user.id;\n}\n\nexport default validateUser;\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {filterNull}from'@sqrzro/utility';function i(n,t){return Array.isArray(n)?filterNull(n.map(r=>i(r,t))):n?.startsWith(t)?n:null}var e=i;function l(n,t){let r=e(n,t);if(!r)throw new Error(`Could not ensure ID. '${n}' is not a valid ID with prefix '${t}'.`);return r}var a=l;async function d(n,t,r){if(!r)return null;let u=r instanceof Promise?await r:r;return e(u[n],t)}var m=d;export{e as a,a as b,m as c};//# sourceMappingURL=chunk-3A4JSFVE.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-3A4JSFVE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utility/guard-id.ts","../src/utility/ensure-id.ts","../src/utility/get-id-from-params.ts"],"names":["guardID","id","prefix","filterNull","item","guard_id_default","ensureID","guardedID","ensure_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default"],"mappings":"yCAKA,SAASA,CAAAA,CACLC,CAAAA,CACAC,EACc,CACd,OAAI,MAAM,OAAA,CAAQD,CAAE,EACTE,UAAAA,CAAWF,CAAAA,CAAG,IAAKG,CAAAA,EAASJ,CAAAA,CAAWI,EAAMF,CAAM,CAAC,CAAC,CAAA,CAG3DD,GAAI,UAAA,CAAWC,CAAM,EAInBD,CAAAA,CAHI,IAIf,CAEA,IAAOI,CAAAA,CAAQL,EClBf,SAASM,CAAAA,CAA2BL,EAA+BC,CAAAA,CAAmB,CAClF,IAAMK,CAAAA,CAAYF,CAAAA,CAAWJ,EAAIC,CAAM,CAAA,CAEvC,GAAI,CAACK,EACD,MAAM,IAAI,MAAM,CAAA,sBAAA,EAAyBN,CAAE,oCAAoCC,CAAM,CAAA,EAAA,CAAI,EAG7F,OAAOK,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECVf,eAAeG,CAAAA,CACXC,EACAR,CAAAA,CACAS,CAAAA,CACiB,CACjB,GAAI,CAACA,EACD,OAAO,IAAA,CAGX,IAAMC,CAAAA,CAAgBD,CAAAA,YAAkB,QAAU,MAAMA,CAAAA,CAASA,EACjE,OAAON,CAAAA,CAAWO,EAAcF,CAAG,CAAA,CAAGR,CAAM,CAChD,KAEOW,CAAAA,CAAQJ","file":"chunk-3A4JSFVE.js","sourcesContent":["import { filterNull } from '@sqrzro/utility';\n\nfunction guardID<T extends string>(id: (string | null | undefined)[], prefix: string): T[];\nfunction guardID<T extends string>(id: string | null | undefined, prefix: string): T | null;\n\nfunction guardID<T extends string>(\n id: (string | null | undefined)[] | string | null | undefined,\n prefix: string\n): T[] | T | null {\n if (Array.isArray(id)) {\n return filterNull(id.map((item) => guardID<T>(item, prefix)));\n }\n\n if (!id?.startsWith(prefix)) {\n return null;\n }\n\n return id as T;\n}\n\nexport default guardID;\n","import guardID from './guard-id';\n\nfunction ensureID<T extends string>(id: string | null | undefined, prefix: string): T {\n const guardedID = guardID<T>(id, prefix);\n\n if (!guardedID) {\n throw new Error(`Could not ensure ID. '${id}' is not a valid ID with prefix '${prefix}'.`);\n }\n\n return guardedID;\n}\n\nexport default ensureID;\n","import guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T | null> {\n if (!params) {\n return null;\n }\n\n const awaitedParams = params instanceof Promise ? await params : params;\n return guardID<T>(awaitedParams[key], prefix);\n}\n\nexport default getIDFromParams;\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var s=class extends Error{messages;constructor(r){super(JSON.stringify(r)),this.messages=r,this.name="ValidationError";}},e=s;export{e as a};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var s=class extends Error{messages;constructor(r){super(JSON.stringify(r)),this.messages=r,this.name="ValidationError";}},e=s;export{e as a};//# sourceMappingURL=chunk-3JA7XHAG.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-3JA7XHAG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/forms/ValidationError.ts"],"names":["ValidationError","messages","ValidationError_default"],"mappings":"AAMA,IAAMA,CAAAA,CAAN,cAA8B,KAAM,CACzB,SAEA,WAAA,CAAYC,CAAAA,CAAkC,CACjD,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC,CAAA,CAE9B,KAAK,QAAA,CAAWA,CAAAA,CAChB,KAAK,IAAA,CAAO,kBAChB,CACJ,CAAA,CAEOC,CAAAA,CAAQF","file":"chunk-3JA7XHAG.js","sourcesContent":["/**\n * Custom error class to represent validation errors in form processing.\n * \n * It extends the built-in Error class and includes a messages property\n * that holds a record of validation error messages.\n */\nclass ValidationError extends Error {\n public messages: Record<string, string>;\n\n public constructor(messages: Record<string, string>) {\n super(JSON.stringify(messages));\n\n this.messages = messages;\n this.name = 'ValidationError';\n }\n}\n\nexport default ValidationError;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-KC7SPWBL.js';import {createClient}from'redis';var i=null;async function o(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return i||(i=createClient({url:process.env.REDIS_URL}),await i.connect(),i)}var n=o;var c={async getItem(t,r){let e=await(await n()).get(`[${t}]:${r}`);if(!e)return null;try{return JSON.parse(e)}catch{return null}},async getArray(t,r){return await(await n()).sMembers(`[${t}]:${r}`)},async addToArray(t,r,e){await(await n()).sAdd(`[${t}]:${r}`,e);},async removeFromArray(t,r,e){await(await n()).sRem(`[${t}]:${r}`,e);},async setItem(t,r,e){a("[storage]","setItem",`[${t}]:${r} - {${JSON.stringify(e)}}`),await(await n()).set(`[${t}]:${r}`,JSON.stringify(e));},async removeItem(t,r){a("[storage]","removeItem",`[${t}]:${r}`),await(await n()).del(`[${t}]:${r}`);}},w=c;export{w as a};//# sourceMappingURL=chunk-C2XLUXVN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-C2XLUXVN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/utility/get-client.ts","../src/storage/index.ts"],"names":["client","getClient","createClient","get_client_default","serverStorage","prefix","key","value","log_default","storage_default"],"mappings":"qEAIA,IAAIA,EAAiD,IAAA,CAQrD,eAAeC,GAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,UACb,MAAM,IAA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CAAA,EAAA,EAAKC,CAAG,CAAA,IAAA,EAAO,KAAK,SAAA,CAAUC,CAAK,CAAC,CAAA,CAAA,CAAG,CAAA,CAC7E,MAAO,MAAMJ,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,GAAI,IAAA,CAAK,SAAA,CAAUC,CAAK,CAAC,EAC7E,CAAA,CAOA,MAAM,UAAA,CAAWF,CAAAA,CAAgBC,EAA4B,CACzDE,CAAAA,CAAI,YAAa,YAAA,CAAc,CAAA,CAAA,EAAIH,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CACnD,KAAA,CAAO,MAAMH,GAAU,EAAG,GAAA,CAAI,IAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,EACtD,CACJ,CAAA,CAEOG,CAAAA,CAAQL","file":"chunk-C2XLUXVN.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import log from '../utility/log';\n\nimport getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n log('[storage]', 'setItem', `[${prefix}]:${key} - {${JSON.stringify(value)}}`);\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n log('[storage]', 'removeItem', `[${prefix}]:${key}`);\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {randomBytes}from'crypto';var f=16;function l(e,r=f){let o="abcdefghijklmnopqrstuvwxyz0123456789",s=randomBytes(r),a="";for(let t=0;t<r;t++)a+=o[s[t]%o.length];return `${e?e+"_":""}${a}`}var u=l;export{u as a};//# sourceMappingURL=chunk-CESWDV42.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-CESWDV42.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utility/generate-id.ts"],"names":["ID_LENGTH","generateID","prefix","length","chars","bytes","randomBytes","result","i","generate_id_default"],"mappings":"iCAEA,IAAMA,EAAY,EAAA,CAElB,SAASC,EAAsCC,CAAAA,CAAwBC,CAAAA,CAASH,EAAc,CAC1F,IAAMI,EAAQ,sCAAA,CACRC,CAAAA,CAAQC,YAAYH,CAAM,CAAA,CAE5BI,CAAAA,CAAS,EAAA,CAEb,IAAA,IAASC,CAAAA,CAAI,EAAGA,CAAAA,CAAIL,CAAAA,CAAQK,IACxBD,CAAAA,EAAUH,CAAAA,CAAMC,EAAMG,CAAC,CAAA,CAAIJ,EAAM,MAAM,CAAA,CAG3C,OAAO,CAAA,EAAGF,CAAAA,CAASA,EAAS,GAAA,CAAM,EAAE,GAAGK,CAAM,CAAA,CACjD,CAEA,IAAOE,CAAAA,CAAQR","file":"chunk-CESWDV42.js","sourcesContent":["import { randomBytes } from 'crypto';\n\nconst ID_LENGTH = 16;\n\nfunction generateID<T extends string = string>(prefix?: string | null, length = ID_LENGTH): T {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';\n const bytes = randomBytes(length);\n\n let result = '';\n\n for (let i = 0; i < length; i++) {\n result += chars[bytes[i] % chars.length];\n }\n\n return `${prefix ? prefix + '_' : ''}${result}` as T;\n}\n\nexport default generateID;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-C2XLUXVN.js';import {a}from'./chunk-KC7SPWBL.js';import {e}from'./chunk-JI2U2EMD.js';import R from'bcryptjs';import {cache}from'react';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';function g(){let s=process.env.AUTH_ROLE;if(!s)throw new Error("AUTH_ROLE environment variable is not set.");let e=parseInt(s,10);if(isNaN(e))throw new Error("AUTH_ROLE environment variable is not a valid number.");return e}var u=g;var l=process.env.AUTH_COOKIE_NAME??"session",C=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,X=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function y(s){let e=(s??await cookies()).get(l)?.value;if(!e)return null;let o=e.split(".");if(o.length!==2)return null;let[t,n]=o;return {id:t,secret:n}}var m=y;function _(s){let{expires:e,secret:o,userID:t}=s;if(typeof e!="string"||typeof o!="string"||typeof t!="string")return null;let n=new Date(e);return isNaN(n.getTime())?null:{expires:n,secret:o,userID:t}}var f=_;async function I(s){a("[auth:session]","validateSession","Validating session...");let e=await m(s);if(!e)return a("[auth:session]","validateSession","No session cookie found"),null;a("[auth:session]","validateSession",`Session cookie found with ID: ${e.id}`);let o=u(),t=await a$1.getItem("session",e.id);return t?.role!==o?(a("[auth:session]","validateSession",`Session role ${t?.role} does not match expected role ${o}`),null):typeof t?.secret!="string"?(a("[auth:session]","validateSession","Session secret is not a string"),null):await R.compare(e.secret,t.secret)?f(t):(a("[auth:session]","validateSession","Session secret does not match"),null)}var v=cache(I),c=v;var p=drizzle(process.env.DATABASE_URL??"");async function w(s,e$1,o){let t=o??u();return (await p.select().from(e).where(and(eq(e[s],e$1),eq(e.role,t),isNull(e.deletedAt))).limit(1))[0]??null}var U=w;async function H(s,e){return U("id",s,e)}var S=H;async function b(){a("[auth:users]","getSessionUser","Attempting to retrieve session user...");let s=await c();if(!s)return a("[auth:users]","getSessionUser","No valid session found"),null;a("[auth:users]","getSessionUser",`Valid session found for user ID: ${s.userID}`);let e=await S(s.userID);return e?(a("[auth:users]","getSessionUser",`User found for session user ID: ${e.id}`),{email:e.email,id:e.id}):(a("[auth:users]","getSessionUser",`No user found for session user ID: ${s.userID}`),null)}async function k(){return cache(b)()}var h=k;async function D(){let s=await h();if(!s)throw new Error("Could not ensure session user. No session user found.");return s}var ce=D;export{p as a,u as b,U as c,l as d,C as e,X as f,m as g,c as h,h as i,ce as j};//# sourceMappingURL=chunk-DOBAUBXG.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-DOBAUBXG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/utility/ensure-role.ts","../src/auth/utility/config.ts","../src/auth/sessions/utility/get-session-cookie.ts","../src/auth/sessions/utility/parse-session.ts","../src/auth/sessions/validate-session.ts","../src/utility/db.ts","../src/auth/users/utility/get-user-by.ts","../src/auth/users/utility/get-user-by-id.ts","../src/auth/users/get-session-user.ts","../src/auth/users/ensure-session-user.ts"],"names":["ensureRole","role","roleNumber","ensure_role_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getSessionCookie","cookies","cookie","cookieFn","parts","id","secret","get_session_cookie_default","parseSession","session","expires","userID","expiresDate","parse_session_default","uncached_validateSession","log_default","storage_default","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","key","value","userRole","authUserTable","and","eq","isNull","get_user_by_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","ensureSessionUser","user","ensure_session_user_default"],"mappings":"gSAAA,SAASA,CAAAA,EAAqB,CAC1B,IAAMC,CAAAA,CAAO,OAAA,CAAQ,IAAI,SAAA,CAEzB,GAAI,CAACA,CAAAA,CACD,MAAM,IAAI,MAAM,4CAA4C,CAAA,CAGhE,IAAMC,CAAAA,CAAa,QAAA,CAASD,CAAAA,CAAM,EAAE,CAAA,CAEpC,GAAI,KAAA,CAAMC,CAAU,CAAA,CAChB,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,KAEOC,CAAAA,CAAQH,EChBR,IAAMI,CAAAA,CAAmB,OAAA,CAAQ,GAAA,CAAI,gBAAA,EAAoB,SAAA,CAEnDC,CAAAA,CAA2B,OAAA,CAAQ,IAAI,wBAAA,CAC9C,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,wBAAwB,CAAA,CAC3C,GAEOC,CAAAA,CAA0B,OAAA,CAAQ,GAAA,CAAI,uBAAA,CAC7C,MAAA,CAAO,OAAA,CAAQ,IAAI,uBAAuB,CAAA,CAC1C,ECDN,eAAeC,CAAAA,CACXC,CAAAA,CACiC,CACjC,IAAMC,CAAAA,CAAAA,CAAUD,CAAAA,EAAY,MAAME,OAAAA,EAAS,EAAI,IAAIN,CAAg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UTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\nimport log from '../../utility/log';\n\nimport ensureRole from '../utility/ensure-role';\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n log('[auth:session]', 'validateSession', 'Validating session...');\n\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n log('[auth:session]', 'validateSession', 'No session cookie found');\n return null;\n }\n\n log('[auth:session]', 'validateSession', `Session cookie found with ID: ${cookie.id}`);\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if (session?.role !== role) {\n log(\n '[auth:session]',\n 'validateSession',\n `Session role ${session?.role} does not match expected role ${role}`\n );\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n log('[auth:session]', 'validateSession', 'Session secret is not a string');\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n log('[auth:session]', 'validateSession', 'Session secret does not match');\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(\n key: keyof AuthUserTable,\n value: string,\n role?: number\n): Promise<AuthUser | null> {\n const userRole = role ?? ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, userRole),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string, role?: number): Promise<AuthUser | null> {\n return getUserBy('id', id, role);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport log from '../../utility/log';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n log('[auth:users]', 'getSessionUser', 'Attempting to retrieve session user...');\n\n const session = await validateSession();\n\n if (!session) {\n log('[auth:users]', 'getSessionUser', 'No valid session found');\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `Valid session found for user ID: ${session.userID}`);\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n log(\n '[auth:users]',\n 'getSessionUser',\n `No user found for session user ID: ${session.userID}`\n );\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `User found for session user ID: ${authUser.id}`);\n\n return {\n email: authUser.email,\n id: authUser.id,\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import getSessionUser from './get-session-user';\nimport type { User } from './utility/interfaces';\n\nasync function ensureSessionUser(): Promise<User> {\n const user = await getSessionUser();\n\n if (!user) {\n throw new Error('Could not ensure session user. No session user found.');\n }\n\n return user;\n}\n\nexport default ensureSessionUser;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function o(e){return process.env.SZ_LOG==="true"?true:typeof process.env.SZ_LOG=="string"?process.env.SZ_LOG.split(",").includes(e):false}function r(e,s,n){o(e)&&console.log(`[${e}] ${s}: ${n}`);}var t=r;export{t as a};//# sourceMappingURL=chunk-KC7SPWBL.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-KC7SPWBL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utility/log.ts"],"names":["shouldLog","alias","log","fnName","message","log_default"],"mappings":"AAAA,SAASA,CAAAA,CAAUC,EAAwB,CACvC,OAAI,QAAQ,GAAA,CAAI,MAAA,GAAW,OAChB,IAAA,CAGP,OAAO,QAAQ,GAAA,CAAI,MAAA,EAAW,SACX,OAAA,CAAQ,GAAA,CAAI,OAAO,KAAA,CAAM,GAAG,CAAA,CAC7B,QAAA,CAASA,CAAK,CAAA,CAG7B,KACX,CAEA,SAASC,EAAID,CAAAA,CAAeE,CAAAA,CAAgBC,EAAuB,CAC3DJ,CAAAA,CAAUC,CAAK,CAAA,EACf,OAAA,CAAQ,IAAI,CAAA,CAAA,EAAIA,CAAK,KAAKE,CAAM,CAAA,EAAA,EAAKC,CAAO,CAAA,CAAE,EAEtD,CAEA,IAAOC,CAAAA,CAAQH","file":"chunk-KC7SPWBL.js","sourcesContent":["function shouldLog(alias: string): boolean {\n if (process.env.SZ_LOG === 'true') {\n return true;\n }\n\n if (typeof process.env.SZ_LOG === 'string') {\n const logAliases = process.env.SZ_LOG.split(',');\n return logAliases.includes(alias);\n }\n\n return false;\n}\n\nfunction log(alias: string, fnName: string, message: string): void {\n if (shouldLog(alias)) {\n console.log(`[${alias}] ${fnName}: ${message}`); // eslint-disable-line no-console\n }\n}\n\nexport default log;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-CESWDV42.js';import {a,j,b,d,g as g$1,c,f as f$2,e as e$1}from'./chunk-DOBAUBXG.js';import {a as a$3}from'./chunk-C2XLUXVN.js';import {a as a$2}from'./chunk-KC7SPWBL.js';import {g,e,f as f$1}from'./chunk-JI2U2EMD.js';import {a as a$4}from'./chunk-3JA7XHAG.js';import {and,eq,isNull,gte}from'drizzle-orm';import N from'qrcode';import {Totp}from'time2fa';import Z from'bcryptjs';import {cookies}from'next/headers';async function M(e,t){return c("email",e,t)}var f=M;async function q(e,t){if(!t)throw new Error("Email is required to generate MFA secret.");let o=await f(t);if(!o)throw new Error("User not found. Cannot generate MFA secret.");let r=Totp.generateKey({issuer:e,user:t});return await a.delete(g).where(and(eq(g.userID,o.id),isNull(g.verifiedAt))),await a.insert(g).values({id:a$1(),name:"Default",secret:r.secret,userID:o.id}),new Promise((a,c)=>{N.toDataURL(r.url,{rendererOpts:{quality:1},margin:0,scale:6},(u,F)=>{u&&c(u),a({key:r.secret,url:F});});})}var B=q;async function K(e){let t=await j(),[o]=await a.select().from(g).where(eq(g.userID,t.id)).limit(1);return o?Totp.validate({passcode:e,secret:o.secret}):false}var L=K;function V(){throw new Error("Function not implemented.")}var X=V;async function Y(e,t){await a.delete(f$1).where(and(eq(f$1.userID,t),eq(f$1.type,e)));}var R=Y;var J={INVITE:e$1,MFA:f$2,PASSWORD:f$2};async function Q(e$1,t){let o=b(),r=new Date;r.setHours(r.getHours()-J[e$1]);let a$1=await a.select().from(f$1).innerJoin(e,and(eq(e.id,f$1.userID),eq(e.role,o),isNull(e.deletedAt))).where(and(eq(f$1.id,t),eq(f$1.type,e$1),gte(f$1.createdAt,r))).limit(1);return a$1[0]?{...a$1[0].resets,user:a$1[0].user_credentials}:null}var A=Q;var ee=12;async function te(e){return Z.hash(e,ee)}var p=te;async function oe(e$1,t,o){let r=await A(e$1,t);if(!r)throw new Error("RESET_TOKEN_INVALID");return await a.update(e).set({password:await p(o)}).where(eq(e.id,r.userID)),await R(e$1,r.userID),r.userID}var se=oe;var ie=48;async function ae(e,t,o){let r=await f(t,o);if(!r)return null;await R(e,r.id);let a$2=a$1(null,ie);return await a.insert(f$1).values({createdAt:new Date,id:a$2,type:e,userID:r.id}),a$2}var ne=ae;async function me(e,t){return !!await A(e,t)}var ue=me;function fe(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let o="";for(let r=0;r<t.length;r++)o+=e[t[r]>>3];return o}var E=fe;var le=24,de=3600*1e3;async function ce(e,t=le){a$2("auth:session","createSession",`Creating session for user ${e} with expiration of ${t} hours`);let o=b();a$2("auth:session","createSession",`Assigned role ${o} to session for user ${e}`);let r=E(),a=E(),c=`${r}.${a}`,u=new Date(Date.now()+t*de);await a$3.setItem("session",r,{expires:u,role:o,secret:await p(a),userID:e}),a$2("auth:session","createSession",`Set session ID ${r} and secret for user ${e} (role ${o}) in storage with expiration at ${u.toISOString()}`),(await cookies()).set(d,c,{expires:u,httpOnly:true,path:"/",sameSite:"lax",secure:true}),a$2("auth:session","createSession",`Set cookie '${d}' for user ${e} with token ${c} and expiration at ${u.toISOString()}`);}var we=ce;async function ye(){let e=await g$1();e&&(await a$3.removeItem("session",e.id),(await cookies()).delete(d));}var ge=ye;function Re(){throw new Error("Function not implemented.")}var Se=Re;async function Ae(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await p(e$1.password):null}).returning();return t??null}var Ue=Ae;function xe(){throw new Error("Function not implemented.")}var Ee=xe;async function be(e,t){let o=await f(e);if(!o?.password||!await Z.compare(t,o.password))throw new a$4({email:"",password:""});return o.id}var Ie=be;export{B as a,L as b,X as c,se as d,ne as e,ue as f,we as g,ge as h,Se as i,Ue as j,Ee as k,Ie as l};//# sourceMappingURL=chunk-U27WABYY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-U27WABYY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/users/utility/get-user-by-email.ts","../src/auth/mfas/create-mfa.ts","../src/auth/mfas/validate-mfa.ts","../src/auth/passwords/update-password-with-password.ts","../src/auth/resets/utility/delete-user-resets.ts","../src/auth/resets/utility/get-reset-by-id.ts","../src/auth/utility/hash-secret.ts","../src/auth/passwords/update-password-with-token.ts","../src/auth/resets/create-reset.ts","../src/auth/resets/validate-reset.ts","../src/auth/utility/create-secure-random-string.ts","../src/auth/sessions/create-session.ts","../src/auth/sessions/delete-session.ts","../src/auth/sessions/delete-user-sessions.ts","../src/auth/users/create-user.ts","../src/auth/users/delete-user.ts","../src/auth/users/validate-user.ts"],"names":["getUserByEmail","email","role","get_user_by_default","get_user_by_email_default","createMFA","name","user","key","Totp","db_default","authMFATable","and","eq","isNull","generate_id_default","resolve","reject","qrcode","err","data","create_mfa_default","validateMFA","code","ensure_session_user_default","mfa","validate_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","authResetTable","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","ensure_role_default","expiry","results","authUserTable","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","TOKEN_LENGTH","createReset","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","log_default","expires","storage_default","cookies","AUTH_COOKIE_NAME","create_session_default","deleteSession","cookie","get_session_cookie_default","delete_session_default","deleteUserSessions","delete_user_sessions_default","createUser","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"0bAGA,eAAeA,CAAAA,CAAeC,CAAAA,CAAeC,EAAyC,CAClF,OAAOC,CAAAA,CAAU,OAAA,CAASF,CAAAA,CAAOC,CAAI,CACzC,CAEA,IAAOE,EAAQJ,CAAAA,CCMf,eAAeK,CAAAA,CAAUC,CAAAA,CAAcL,CAAAA,CAAmC,CAKtE,GAAI,CAACA,EACD,MAAM,IAAI,MAAM,2CAA2C,CAAA,CAG/D,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAeH,CAAK,CAAA,CAEvC,GAAI,CAACM,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAAA,CAGjE,IAAMC,CAAAA,CAAMC,IAAAA,CAAK,YAAY,CAAE,MAAA,CAAQH,EAAM,IAAA,CAAML,CAAM,CAAC,CAAA,CAI1D,OAAA,MAAMS,CAAAA,CACD,MAAA,CAAOC,CAAY,CAAA,CACnB,MAAMC,GAAAA,CAAIC,EAAAA,CAAGF,CAAAA,CAAa,MAAA,CAAQJ,CAAAA,CAAK,EAAE,EAAGO,MAAAA,CAAOH,CAAAA,CAAa,UAAU,CAAC,CAAC,CAAA,CAIjF,MAAMD,CAAAA,CAAG,MAAA,CAAOC,CAAY,CAAA,CAAE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AA,CAAM,QAAA,CAAUA,IAAK,QAAA,CAAW,MAAM6B,CAAAA,CAAW7B,GAAAA,CAAK,QAAQ,CAAA,CAAI,IAAK,CAAC,CAAA,CACpF,SAAA,EAAU,CAEf,OAAO8D,CAAAA,EAAU,IACrB,CAEA,IAAOC,EAAAA,CAAQF,GChBf,SAASG,EAAAA,EAA4B,CACjC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,EAAAA,CAAQD,GCEf,eAAeE,EAAAA,CAAarF,CAAAA,CAAesF,EAAmC,CAC1E,IAAMhF,EAAO,MAAMH,CAAAA,CAAeH,CAAK,CAAA,CAEvC,GAAI,CAACM,GAAM,QAAA,EAAY,CAAE,MAAMyC,CAAAA,CAAO,OAAA,CAAQuC,EAAUhF,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIiF,GAAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,CAAA,CAGzD,OAAOjF,CAAAA,CAAK,EAChB,CAEA,IAAOkF,EAAAA,CAAQH","file":"chunk-U27WABYY.js","sourcesContent":["import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string, role?: number): Promise<AuthUser | null> {\n return getUserBy('email', email, role);\n}\n\nexport default getUserByEmail;\n","import { and, eq, isNull } from 'drizzle-orm';\nimport qrcode from 'qrcode';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authMFATable } from '../utility/schema';\n\nimport checkMFAEnabled from './check-mfa-enabled';\nimport type { MFAObject } from './utility/interfaces';\n\nasync function createMFA(name: string, email: string): Promise<MFAObject> {\n if (!checkMFAEnabled()) {\n throw new Error('MFA is not enabled. Cannot generate MFA secret.');\n }\n\n if (!email) {\n throw new Error('Email is required to generate MFA secret.');\n }\n\n const user = await getUserByEmail(email);\n\n if (!user) {\n throw new Error('User not found. Cannot generate MFA secret.');\n }\n\n const key = Totp.generateKey({ issuer: name, user: email });\n\n // Delete all the unverified MFA entries for this user\n\n await db\n .delete(authMFATable)\n .where(and(eq(authMFATable.userID, user.id), isNull(authMFATable.verifiedAt)));\n\n // Add the new MFA entry\n\n await db.insert(authMFATable).values({\n id: generateID(),\n name: 'Default',\n secret: key.secret,\n userID: user.id,\n });\n\n return new Promise((resolve, reject) => {\n qrcode.toDataURL(\n key.url,\n { rendererOpts: { quality: 1 }, margin: 0, scale: 6 },\n (err, data) => {\n if (err) {\n reject(err);\n }\n resolve({ key: key.secret, url: data });\n }\n );\n });\n}\n\nexport default createMFA;\n","import { eq } from 'drizzle-orm';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { authMFATable } from '../utility/schema';\n\nimport ensureSessionUser from '../users/ensure-session-user';\n\nimport checkMFAEnabled from './check-mfa-enabled';\n\nasync function validateMFA(code: string): Promise<boolean> {\n if (!checkMFAEnabled()) {\n return false;\n }\n\n const user = await ensureSessionUser();\n\n const [mfa] = await db\n .select()\n .from(authMFATable)\n .where(eq(authMFATable.userID, user.id))\n .limit(1);\n\n if (!mfa) {\n return false;\n }\n\n return Totp.validate({ passcode: code, secret: mfa.secret });\n}\n\nexport default validateMFA;\n","function updatePasswordWithPassword(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default updatePasswordWithPassword;\n","import { and, eq } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { authResetTable } from '../../utility/schema';\n\nimport type { ResetType } from './interfaces';\n\nasync function deleteUserResets(type: ResetType, userID: string): Promise<void> {\n await db\n .delete(authResetTable)\n .where(and(eq(authResetTable.userID, userID), eq(authResetTable.type, type)));\n}\n\nexport default deleteUserResets;\n","import { and, eq, gte, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { AuthUser } from '../../users/utility/interfaces';\nimport { AUTH_INVITE_EXPIRY_HOURS, AUTH_RESET_EXPIRY_HOURS } from '../../utility/config';\nimport ensureRole from '../../utility/ensure-role';\nimport { authResetTable, authUserTable } from '../../utility/schema';\n\nimport type { AuthReset, ResetType } from './interfaces';\n\nconst EXPIRIES: Record<ResetType, number> = {\n INVITE: AUTH_INVITE_EXPIRY_HOURS,\n MFA: AUTH_RESET_EXPIRY_HOURS,\n PASSWORD: AUTH_RESET_EXPIRY_HOURS,\n};\n\nasync function getResetByID(\n type: ResetType,\n id: string\n): Promise<(AuthReset & { user: AuthUser }) | null> {\n const role = ensureRole();\n\n const expiry = new Date();\n expiry.setHours(expiry.getHours() - EXPIRIES[type]);\n\n const results = await db\n .select()\n .from(authResetTable)\n .innerJoin(\n authUserTable,\n and(\n eq(authUserTable.id, authResetTable.userID),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .where(\n and(\n eq(authResetTable.id, id),\n eq(authResetTable.type, type),\n gte(authResetTable.createdAt, expiry)\n )\n )\n .limit(1);\n\n return results[0] ? { ...results[0].resets, user: results[0].user_credentials } : null;\n}\n\nexport default getResetByID;\n","import bcrypt from 'bcryptjs';\n\nconst PW_SALT_ROUNDS = 12;\n\nasync function hashSecret(secret: string): Promise<string> {\n return bcrypt.hash(secret, PW_SALT_ROUNDS);\n}\n\nexport default hashSecret;\n","import { eq } from 'drizzle-orm';\n\nimport db from '../../utility/db';\n\nimport deleteUserResets from '../resets/utility/delete-user-resets';\nimport getResetByID from '../resets/utility/get-reset-by-id';\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable, ResetType } from '../utility/schema';\n\nasync function updatePasswordWithToken(\n type: ResetType,\n token: string,\n newPassword: string\n): Promise<string> {\n const reset = await getResetByID(type, token);\n\n if (!reset) {\n throw new Error('RESET_TOKEN_INVALID');\n }\n\n await db\n .update(authUserTable)\n .set({\n password: await hashSecret(newPassword),\n })\n .where(eq(authUserTable.id, reset.userID));\n\n await deleteUserResets(type, reset.userID);\n\n return reset.userID;\n}\n\nexport default updatePasswordWithToken;\n","import db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authResetTable } from '../utility/schema';\n\nimport deleteUserResets from './utility/delete-user-resets';\nimport type { ResetType } from './utility/interfaces';\n\nconst TOKEN_LENGTH = 48;\n\nasync function createReset(type: ResetType, email: string, role?: number): Promise<string | null> {\n const user = await getUserByEmail(email, role);\n\n if (!user) {\n return null;\n }\n\n await deleteUserResets(type, user.id);\n\n const id = generateID(null, TOKEN_LENGTH);\n\n await db.insert(authResetTable).values({\n createdAt: new Date(),\n id,\n type,\n userID: user.id,\n });\n\n return id;\n}\n\nexport default createReset;\n","import type { ResetType } from '../utility/schema';\n\nimport getResetByID from './utility/get-reset-by-id';\n\nasync function validateReset(type: ResetType, token: string): Promise<boolean> {\n return Boolean(await getResetByID(type, token));\n}\n\nexport default validateReset;\n","function createSecureRandomString(): string {\n\t// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)\n\tconst alphabet = \"abcdefghijkmnpqrstuvwxyz23456789\";\n\n\t// Generate 24 bytes = 192 bits of entropy.\n\t// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits\n\tconst bytes = new Uint8Array(24);\n\tcrypto.getRandomValues(bytes);\n\n\tlet id = \"\";\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\t// >> 3 \"removes\" the right-most 3 bits of the byte\n\t\tid += alphabet[bytes[i] >> 3];\n\t}\n\treturn id;\n}\n\nexport default createSecureRandomString;","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\nimport log from '../../utility/log';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport createSecureRandomString from '../utility/create-secure-random-string';\nimport ensureRole from '../utility/ensure-role';\nimport hashSecret from '../utility/hash-secret';\n\nconst DEFAULT_EXPIRES = 24;\nconst HOUR_IN_MS = 60 * 60 * 1000;\n\nasync function createSession(userID: string, expiresIn = DEFAULT_EXPIRES): Promise<void> {\n log(\n 'auth:session',\n 'createSession',\n `Creating session for user ${userID} with expiration of ${expiresIn} hours`\n );\n\n const role = ensureRole();\n\n log('auth:session', 'createSession', `Assigned role ${role} to session for user ${userID}`);\n\n const id = createSecureRandomString();\n const secret = createSecureRandomString();\n const token = `${id}.${secret}`;\n\n const expires = new Date(Date.now() + expiresIn * HOUR_IN_MS);\n\n await serverStorage.setItem('session', id, {\n expires,\n role,\n secret: await hashSecret(secret),\n userID,\n });\n\n log(\n 'auth:session',\n 'createSession',\n `Set session ID ${id} and secret for user ${userID} (role ${role}) in storage with expiration at ${expires.toISOString()}`\n );\n\n (await cookies()).set(AUTH_COOKIE_NAME, token, {\n expires,\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: true,\n });\n\n log(\n 'auth:session',\n 'createSession',\n `Set cookie '${AUTH_COOKIE_NAME}' for user ${userID} with token ${token} and expiration at ${expires.toISOString()}`\n );\n}\n\nexport default createSession;\n","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\n\nimport getSessionCookie from './utility/get-session-cookie';\n\nasync function deleteSession(): Promise<void> {\n const cookie = await getSessionCookie();\n\n if (!cookie) {\n return;\n }\n\n await serverStorage.removeItem('session', cookie.id);\n (await cookies()).delete(AUTH_COOKIE_NAME);\n}\n\nexport default deleteSession;\n","function deleteUserSessions(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUserSessions;\n","import db from '../../utility/db';\n\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nimport type { AuthUser, AuthUserDataWithID } from './utility/interfaces';\n\nasync function createUser(data: AuthUserDataWithID): Promise<AuthUser | null> {\n const [result] = await db\n .insert(authUserTable)\n .values({ ...data, password: data.password ? await hashSecret(data.password) : null })\n .returning();\n\n return result ?? null;\n}\n\nexport default createUser;\n","function deleteUser(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUser;\n","import bcrypt from 'bcryptjs';\n\nimport ValidationError from '../../forms/ValidationError';\n\nimport getUserByEmail from './utility/get-user-by-email';\n\nasync function validateUser(email: string, password: string): Promise<string> {\n const user = await getUserByEmail(email);\n\n if (!user?.password || !(await bcrypt.compare(password, user.password))) {\n throw new ValidationError({ email: '', password: '' });\n }\n\n return user.id;\n}\n\nexport default validateUser;\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {parse}from'csv/sync';function p(s){let t=[],n=s.split(`
|
|
2
|
+
`).filter(r=>r.trim()!=="");for(let r of n){let i=parse(r,{skip_empty_lines:true});t.push(i[0].map(e=>e.trim()));}return t}var f=p;export{f as a};//# sourceMappingURL=chunk-UCMLSO7F.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-UCMLSO7F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/csv/parse-csv.ts"],"names":["parseCSV","csv","records","lines","item","line","record","parse","parse_csv_default"],"mappings":"6BAEA,SAASA,CAAAA,CAASC,CAAAA,CAAyB,CACvC,IAAMC,CAAAA,CAAsB,EAAC,CACvBC,CAAAA,CAAQF,EAAI,KAAA,CAAM;AAAA,CAAI,EAAE,MAAA,CAAQG,CAAAA,EAASA,CAAAA,CAAK,IAAA,KAAW,EAAE,CAAA,CAEjE,IAAA,IAAWC,CAAAA,IAAQF,EAAO,CACtB,IAAMG,EAASC,KAAAA,CAAMF,CAAAA,CAAM,CACvB,gBAAA,CAAkB,IACtB,CAAC,CAAA,CAEDH,EAAQ,IAAA,CAAKI,CAAAA,CAAO,CAAC,CAAA,CAAE,IAAKF,CAAAA,EAASA,CAAAA,CAAK,IAAA,EAAM,CAAC,EACrD,CAEA,OAAOF,CACX,KAEOM,CAAAA,CAAQR","file":"chunk-UCMLSO7F.js","sourcesContent":["import { parse } from 'csv/sync';\n\nfunction parseCSV(csv: string): string[][] {\n const records: string[][] = [];\n const lines = csv.split('\\n').filter((item) => item.trim() !== '');\n\n for (const line of lines) {\n const record = parse(line, {\n skip_empty_lines: true,\n }) as string[][];\n\n records.push(record[0].map((item) => item.trim()));\n }\n\n return records;\n}\n\nexport default parseCSV;\n"]}
|
|
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
5
5
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
6
6
|
|
|
7
7
|
const binPath = resolve(__dirname, '../../../node_modules/.bin/drizzle-kit');
|
|
8
|
-
const configPath = resolve(__dirname, '../static/drizzle.config.
|
|
8
|
+
const configPath = resolve(__dirname, '../static/drizzle.config.cjs');
|
|
9
9
|
|
|
10
10
|
async function main() {
|
|
11
11
|
const ls = spawn(binPath, ['generate', `--config=${configPath}`], { stdio: 'inherit' });
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
require('dotenv/config');
|
|
2
|
+
const { defineConfig } = require('drizzle-kit');
|
|
3
3
|
|
|
4
4
|
if (!process.env.DATABASE_URL) {
|
|
5
5
|
throw new Error('DATABASE_URL is not defined. Database migration cannot be generated.');
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
module.exports = defineConfig({
|
|
9
9
|
dbCredentials: {
|
|
10
10
|
url: process.env.DATABASE_URL,
|
|
11
11
|
},
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{a as parseCSV}from'../chunk-UCMLSO7F.js';import {stringify}from'csv/sync';function n(e){return stringify(e)}var t=n;function a(e){return new Blob([t(e)],{type:"text/csv"})}var f=a;export{t as generateCSV,f as generateCSVBlob};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/csv/generate-csv.ts","../../src/csv/generate-csv-blob.ts"],"names":["generateCSV","data","stringify","generate_csv_default","generateCSVBlob","generate_csv_blob_default"],"mappings":"iFAEA,SAASA,EAAYC,CAAAA,CAA0B,CAC3C,OAAOC,SAAAA,CAAUD,CAAI,CACzB,CAEA,IAAOE,CAAAA,CAAQH,ECJf,SAASI,CAAAA,CAAgBH,CAAAA,CAAwB,CAC7C,OAAO,IAAI,IAAA,CAAK,CAACE,EAAYF,CAAI,CAAC,CAAA,CAAG,CAAE,KAAM,UAAW,CAAC,CAC7D,KAEOI,CAAAA,CAAQD","file":"index.js","sourcesContent":["import { stringify } from 'csv/sync';\n\nfunction generateCSV(data: string[][]): string {\n return stringify(data);\n}\n\nexport default generateCSV;\n","import generateCSV from './generate-csv';\n\nfunction generateCSVBlob(data: string[][]): Blob {\n return new Blob([generateCSV(data)], { type: 'text/csv' });\n}\n\nexport default generateCSVBlob;\n"]}
|
package/dist/database/index.d.ts
CHANGED
|
@@ -1,50 +1,109 @@
|
|
|
1
|
-
import { SQL } from 'drizzle-orm';
|
|
2
1
|
import { PgColumn } from 'drizzle-orm/pg-core';
|
|
3
|
-
import {
|
|
2
|
+
import { SQL } from 'drizzle-orm';
|
|
3
|
+
import { P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
4
4
|
|
|
5
|
+
type QueryConditions = (SQL | undefined)[];
|
|
5
6
|
interface QueryConfig {
|
|
6
7
|
limit: number;
|
|
7
8
|
offset: number;
|
|
8
9
|
}
|
|
9
|
-
interface SelectFunctionConfig<Filters
|
|
10
|
-
filters?:
|
|
11
|
-
guards?:
|
|
10
|
+
interface SelectFunctionConfig<Filters, Guards> extends Partial<QueryConfig> {
|
|
11
|
+
filters?: Filters;
|
|
12
|
+
guards?: Guards;
|
|
12
13
|
}
|
|
13
|
-
interface PaginatedSelectFunctionConfig<Filters
|
|
14
|
+
interface PaginatedSelectFunctionConfig<Filters, Guards> extends SelectFunctionConfig<Filters, Guards> {
|
|
14
15
|
page?: number | null;
|
|
15
16
|
}
|
|
16
|
-
interface RepositoryConfig<
|
|
17
|
-
applyFilters?: (filters:
|
|
18
|
-
applyGuards?: (guards:
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}>;
|
|
23
|
-
makeCreateMutation?: (values: Data & {
|
|
24
|
-
id: ID;
|
|
25
|
-
}) => Promise<Model>;
|
|
26
|
-
makeMetaQuery?: (conditions: SQL[]) => Promise<{
|
|
17
|
+
interface RepositoryConfig<Indexes = Record<string, PgColumn<any, any, any>>> {
|
|
18
|
+
applyFilters?: (filters: any) => Promise<QueryConditions>;
|
|
19
|
+
applyGuards?: (guards: any) => Promise<QueryConditions>;
|
|
20
|
+
indexes?: Indexes;
|
|
21
|
+
makeCreateMutation?: (values: any) => Promise<any>;
|
|
22
|
+
makeMetaQuery?: (conditions: QueryConditions) => Promise<{
|
|
27
23
|
count: number;
|
|
28
24
|
}>;
|
|
29
|
-
makeQuery?: (conditions:
|
|
30
|
-
makeUpdateMutation?: (values:
|
|
31
|
-
id: ID;
|
|
32
|
-
}) => Promise<Model>;
|
|
25
|
+
makeQuery?: (conditions: QueryConditions, config: QueryConfig) => Promise<any[]>;
|
|
26
|
+
makeUpdateMutation?: (values: any) => Promise<any>;
|
|
33
27
|
paramKey?: string;
|
|
34
28
|
prefix?: string;
|
|
35
29
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
30
|
+
type InferColumnType<T> = T extends PgColumn<infer C, any, any> ? C['data'] : never;
|
|
31
|
+
type InferFilters<C> = C extends {
|
|
32
|
+
applyFilters: (filters: infer F) => Promise<QueryConditions>;
|
|
33
|
+
} ? F : never;
|
|
34
|
+
type InferGuards<C> = C extends {
|
|
35
|
+
applyGuards: (guards: infer G) => Promise<QueryConditions>;
|
|
36
|
+
} ? G : never;
|
|
37
|
+
type InferID<C> = C extends {
|
|
38
|
+
indexes: {
|
|
39
|
+
id: infer IDColumn;
|
|
40
|
+
};
|
|
41
|
+
} ? InferColumnType<IDColumn> : never;
|
|
42
|
+
type InferQueryModel<C> = C extends {
|
|
43
|
+
makeQuery: (conditions: QueryConditions, config: QueryConfig) => Promise<(infer M)[]>;
|
|
44
|
+
} ? M : never;
|
|
45
|
+
type InferCreate<C> = C extends {
|
|
46
|
+
makeCreateMutation: (values: infer D) => Promise<infer M>;
|
|
47
|
+
} ? {
|
|
48
|
+
data: D;
|
|
49
|
+
model: M;
|
|
50
|
+
} : never;
|
|
51
|
+
type InferUpdate<C> = C extends {
|
|
52
|
+
makeUpdateMutation: (values: infer D) => Promise<infer M>;
|
|
53
|
+
} ? {
|
|
54
|
+
data: D;
|
|
55
|
+
model: M;
|
|
56
|
+
} : never;
|
|
57
|
+
interface GuardID<T extends string> {
|
|
58
|
+
(id: (string | null | undefined)[]): T[];
|
|
59
|
+
(id: string | null | undefined): T | null;
|
|
46
60
|
}
|
|
61
|
+
type InferRepository<I extends Record<string, PgColumn<any, any, any>>, C extends RepositoryConfig> = (C extends {
|
|
62
|
+
makeCreateMutation: any;
|
|
63
|
+
} ? {
|
|
64
|
+
create: (data: InferCreate<C>['data']) => Promise<InferCreate<C>['model']>;
|
|
65
|
+
} : {}) & (C extends {
|
|
66
|
+
makeQuery: any;
|
|
67
|
+
} ? {
|
|
68
|
+
getAll: (config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>> | undefined) => Promise<InferQueryModel<C>[]>;
|
|
69
|
+
} & (C extends {
|
|
70
|
+
indexes: any;
|
|
71
|
+
} ? {
|
|
72
|
+
ensureByID: (id: InferID<C>) => Promise<InferQueryModel<C>>;
|
|
73
|
+
ensureByIndex: <K extends keyof I>(key: K, value: InferColumnType<I[K]>, config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<InferQueryModel<C>>;
|
|
74
|
+
getByID: (id: InferID<C>) => Promise<InferQueryModel<C> | null>;
|
|
75
|
+
getByIndex: <K extends keyof I>(key: K, value: InferColumnType<I[K]>, config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<InferQueryModel<C> | null>;
|
|
76
|
+
} & (C extends {
|
|
77
|
+
prefix: any;
|
|
78
|
+
} ? {
|
|
79
|
+
ensureFromSession: () => Promise<InferQueryModel<C>>;
|
|
80
|
+
} & (C extends {
|
|
81
|
+
paramKey: any;
|
|
82
|
+
} ? {
|
|
83
|
+
ensureFromParams: (params?: Record<string, string> | Promise<Record<string, string>> | null | undefined) => Promise<InferQueryModel<C>>;
|
|
84
|
+
getFromParams: (params?: Record<string, string> | Promise<Record<string, string>> | null | undefined) => Promise<InferQueryModel<C> | null>;
|
|
85
|
+
} : {}) : {}) : {}) & (C extends {
|
|
86
|
+
makeMetaQuery: any;
|
|
87
|
+
} ? {
|
|
88
|
+
getPaginated: (config?: PaginatedSelectFunctionConfig<InferFilters<C>, InferGuards<C>> | undefined) => Promise<Paginated<InferQueryModel<C>>>;
|
|
89
|
+
} : {}) : {}) & (C extends {
|
|
90
|
+
prefix: any;
|
|
91
|
+
} ? {
|
|
92
|
+
ensureID: (id: string | null | undefined) => InferID<C>;
|
|
93
|
+
guardID: GuardID<InferID<C>>;
|
|
94
|
+
} & (C extends {
|
|
95
|
+
paramKey: any;
|
|
96
|
+
} ? {
|
|
97
|
+
ensureIDFromParams: (params?: Record<string, string> | Promise<Record<string, string>> | null | undefined) => Promise<InferID<C>>;
|
|
98
|
+
getIDFromParams: (params?: Record<string, string> | Promise<Record<string, string>> | null | undefined) => Promise<InferID<C> | null>;
|
|
99
|
+
} : {}) : {}) & (C extends {
|
|
100
|
+
makeUpdateMutation: any;
|
|
101
|
+
} ? {
|
|
102
|
+
update: (data: InferUpdate<C>['data']) => Promise<InferUpdate<C>['model']>;
|
|
103
|
+
} : {});
|
|
47
104
|
|
|
48
|
-
declare function createRepository<
|
|
105
|
+
declare function createRepository<I extends Record<string, PgColumn<any, any, any>>, C extends RepositoryConfig>(repoConfig: C & {
|
|
106
|
+
indexes?: I;
|
|
107
|
+
}): InferRepository<I, C>;
|
|
49
108
|
|
|
50
|
-
export { type QueryConfig, createRepository };
|
|
109
|
+
export { type QueryConditions, type QueryConfig, createRepository };
|
package/dist/database/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {j}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import {a,b,c}from'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import {cache}from'react';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';async function E(e,u,o){let d=await c(e,u,o);return b(d,u)}var g=E;function S(e){function u(r){if(!e.prefix)throw new Error("Could not `guardID`. `prefix` is not defined.");return Array.isArray(r)?a(r,e.prefix):a(r,e.prefix)}function o(r){if(!e.prefix)throw new Error("Could not `ensureID`. `prefix` is not defined.");return b(r,e.prefix)}async function d(r){if(!e.paramKey)throw new Error("Could not `getIDFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getIDFromParams`. `prefix` is not defined.");return c(e.paramKey,e.prefix,r)}async function p(r){if(!e.paramKey)throw new Error("Could not `getIDFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getIDFromParams`. `prefix` is not defined.");return g(e.paramKey,e.prefix,r)}async function x(r){if(!e.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let n=[],s=await e.applyFilters?.(r?.filters??null);n.push(...s||[]);let a=await e.applyGuards?.(r?.guards??null);return n.push(...a||[]),e.makeQuery(n,{limit:r?.limit??-1,offset:r?.offset??0})}async function C(r){if(!e.makeMetaQuery)throw new Error("Could not `getPaginated`. `makeMetaQuery` function is not defined.");if(!e.makeQuery)throw new Error("Could not `getPaginated`. `makeQuery` function is not defined.");let n=[],s=await e.applyFilters?.(r?.filters??null);n.push(...s||[]);let a=await e.applyGuards?.(r?.guards??null);n.push(...a||[]);let y=await e.makeMetaQuery(n);return {data:await e.makeQuery(n,{limit:r?.limit??10,offset:((r?.page??1)-1)*(r?.limit??10)}),meta:{limit:r?.limit??10,page:r?.page??1,total:y.count}}}async function f(r,n,s){if(!e.makeQuery)throw new Error("Could not `getByIndex`. `makeQuery` function is not defined.");if(!e.indexes?.[r])throw new Error(`'Could not \`getByIndex\`. Index ${String(r)} is not defined in the repository configuration.`);let a=[],y=await e.applyFilters?.(s?.filters??null);a.push(...y||[]);let D=await e.applyGuards?.(s?.guards??null);a.push(...D||[]),a.push(eq(e.indexes[r],n));let[K]=await e.makeQuery(a,{limit:1,offset:0});return K??null}async function P(r,n,s){let a=await f(r,n,s);return a||notFound()}async function w(r){return f("id",r)}async function c$1(r){return P("id",r)}async function F(r){let n=await d(r);return n?w(n):null}async function Q(r){let n=await p(r);return c$1(n)}async function k(){let r=await j(),n=o(r.id);return c$1(n)}async function M(r){if(!e.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");return e.makeCreateMutation(r)}async function R(r){if(!e.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return e.makeUpdateMutation(r)}let t={};return "makeCreateMutation"in e&&(t.create=M),"makeQuery"in e&&(t.getAll=cache(x),"indexes"in e&&(t.ensureByID=cache(c$1),t.ensureByIndex=cache(P),t.getByID=cache(w),t.getByIndex=cache(f),"prefix"in e&&(t.ensureFromSession=cache(k),"paramKey"in e&&(t.ensureFromParams=cache(Q),t.getFromParams=cache(F)))),"makeMetaQuery"in e&&(t.getPaginated=cache(C))),"prefix"in e&&(t.ensureID=o,t.guardID=u,"paramKey"in e&&(t.ensureIDFromParams=p,t.getIDFromParams=d)),"makeUpdateMutation"in e&&(t.update=R),t}var G=S;export{G as createRepository};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/database/create-repository.ts"],"names":["createRepository","repoConfig","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByID","id","eq","results","uncached_getFromParams","params","get_id_from_params_default","result","notFound","uncached_getFromSession","user","ensure_session_user_default","ensure_id_default","create","data","values","generate_id_default","pick","update","args","cache","create_repository_default"],"mappings":"mPAqBO,SAASA,CAAAA,CAOZC,CAAAA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A,CACZ,MAAM,IAAI,KAAA,CAAM,0DAA0D,CAAA,CAG9E,OAAOA,CAAAA,CAAW,kBAAA,CAAmBsB,CAAI,CAC7C,CAEA,OAAO,CACH,MAAA,CAAAD,CAAAA,CACA,OAAQ,CAAA,GACDM,CAAAA,GAEIC,KAAAA,CAAM3B,CAAe,CAAA,CAAE,GAAG0B,CAAI,CAAA,CAEzC,OAAA,CAAS,CAAA,GACFA,CAAAA,GAEIC,KAAAA,CAAMpB,CAAgB,CAAA,CAAE,GAAGmB,CAAI,CAAA,CAE1C,aAAA,CAAe,CAAA,GACRA,CAAAA,GAEIC,KAAAA,CAAMhB,CAAsB,CAAA,CAAE,GAAGe,CAAI,CAAA,CAEhD,cAAA,CAAgB,CAAA,GACTA,CAAAA,GAEIC,KAAAA,CAAMX,CAAuB,CAAA,CAAE,GAAGU,CAAI,CAAA,CAEjD,YAAA,CAAc,IACPA,CAAAA,GAEIC,KAAAA,CAAMtB,CAAqB,CAAA,CAAE,GAAGqB,CAAI,CAAA,CAE/C,MAAA,CAAAD,CACJ,CACJ,CAEA,IAAOG,CAAAA,CAAQ9B","file":"index.js","sourcesContent":["import { cache } from 'react';\n\nimport { pick } from '@sqrzro/utility';\nimport { eq } from 'drizzle-orm';\nimport type { SQL } from 'drizzle-orm';\nimport { notFound } from 'next/navigation';\n\nimport ensureSessionUser from '../auth/users/ensure-session-user';\n\nimport ensureID from '../utility/ensure-id';\nimport generateID from '../utility/generate-id';\nimport getIDFromParams from '../utility/get-id-from-params';\nimport type { Paginated } from '../utility/interfaces';\n\nimport type {\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n RepositoryObject,\n SelectFunctionConfig,\n} from './utility/interfaces';\n\nexport function createRepository<\n ID extends string,\n Model,\n Filters = null,\n Guards = null,\n Data extends object = {},\n>(\n repoConfig: RepositoryConfig<ID, Model, Filters, Guards, Data>\n): RepositoryObject<ID, Model, Filters, Guards, Data> {\n async function uncached_getAll(\n config?: SelectFunctionConfig<Filters, Guards>\n ): Promise<Model[]> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getAll`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n return repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? -1,\n offset: config?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n config?: PaginatedSelectFunctionConfig<Filters, Guards>\n ): Promise<Paginated<Model>> {\n if (!repoConfig.makeMetaQuery) {\n throw new Error('Could not `getPaginated`. `makeMetaQuery` function is not defined.');\n }\n\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getPaginated`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n const meta = await repoConfig.makeMetaQuery(conditions);\n const data = await repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? 10,\n offset: ((config?.page ?? 1) - 1) * (config?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: config?.limit ?? 10, page: config?.page ?? 1, total: meta.count },\n };\n }\n\n async function uncached_getByID(\n id: ID,\n config?: SelectFunctionConfig<Filters, Guards>\n ): Promise<Model | null> {\n if (!repoConfig.idColumn) {\n throw new Error('Could not `getByID`. `idColumn` is not defined.');\n }\n\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getByID`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n conditions.push(eq(repoConfig.idColumn, id));\n\n const [results] = await repoConfig.makeQuery(conditions, { limit: 1, offset: 0 });\n return results || null;\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | null\n ): Promise<Model> {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromParams`. `prefix` is not defined.');\n }\n\n const id = await getIDFromParams<ID>(repoConfig.paramKey, repoConfig.prefix, params);\n const result = await uncached_getByID(id);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getFromSession(): Promise<Model> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromSession`. `prefix` is not defined.');\n }\n\n const user = await ensureSessionUser();\n const id = ensureID<ID>(user.id, repoConfig.prefix);\n const result = await uncached_getByID(id);\n\n if (!result) {\n throw new Error(`Could not \\`getFromSession\\`. No record with ID '${id}' found.`);\n }\n\n return result;\n }\n\n async function create(data: Data): Promise<Model> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\n }\n\n const values: Data & { id: ID } = {\n id: generateID<ID>(repoConfig.prefix),\n ...pick(data, repoConfig.fillable || []),\n };\n\n return repoConfig.makeCreateMutation(values);\n }\n\n async function update(data: Partial<Data> & { id: ID }): Promise<Model> {\n if (!repoConfig.makeUpdateMutation) {\n throw new Error('Could not `update`. `makeUpdateMutation` is not defined.');\n }\n\n return repoConfig.makeUpdateMutation(data);\n }\n\n return {\n create,\n getAll: (\n ...args: Parameters<typeof uncached_getAll>\n ): ReturnType<typeof uncached_getAll> => {\n return cache(uncached_getAll)(...args);\n },\n getByID: (\n ...args: Parameters<typeof uncached_getByID>\n ): ReturnType<typeof uncached_getByID> => {\n return cache(uncached_getByID)(...args);\n },\n getFromParams: (\n ...args: Parameters<typeof uncached_getFromParams>\n ): ReturnType<typeof uncached_getFromParams> => {\n return cache(uncached_getFromParams)(...args);\n },\n getFromSession: (\n ...args: Parameters<typeof uncached_getFromSession>\n ): ReturnType<typeof uncached_getFromSession> => {\n return cache(uncached_getFromSession)(...args);\n },\n getPaginated: (\n ...args: Parameters<typeof uncached_getPaginated>\n ): ReturnType<typeof uncached_getPaginated> => {\n return cache(uncached_getPaginated)(...args);\n },\n update,\n };\n}\n\nexport default createRepository;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","createRepository","repoConfig","uncached_guardID","guard_id_default","uncached_ensureID","uncached_getIDFromParams","uncached_ensureIDFromParams","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","notFound","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","uncached_ensureFromSession","user","ensure_session_user_default","create","data","update","repository","cache","create_repository_default"],"mappings":"mQAGA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,EACAC,CAAAA,CACU,CACV,IAAMC,CAAAA,CAAK,MAAMC,CAAAA,CAAmBJ,CAAAA,CAAKC,CAAAA,CAAQC,CAAM,EACvD,OAAOG,CAAAA,CAAYF,CAAAA,CAAIF,CAAM,CACjC,CAEA,IAAOK,CAAAA,CAAQP,CAAAA,CCiBf,SAASQ,CAAAA,CAGPC,CAAAA,CAAwD,CAKtD,SAASC,CAAAA,CACLN,CAAAA,CACgC,CAChC,GAAI,CAACK,CAAAA,CAAW,MAAA,CACZ,MAAM,IAAI,MAAM,+CAA+C,CAAA,CAGnE,OAAI,KAAA,CAAM,QAAQL,CAAE,CAAA,CACTO,CAAAA,CAAoBP,CAAAA,CAAIK,EAAW,MAAM,CAAA,CAG7CE,CAAAA,CAAoBP,CAAAA,CAAIK,EAAW,MAAM,CACpD,CAEA,SAASG,EAAkBR,CAAAA,CAA2C,CAClE,GAAI,CAACK,EAAW,MAAA,CACZ,MAAM,IAAI,KAAA,CAAM,gDAAgD,CAAA,CAGpE,OAAOH,CAAA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AAA,CAAgBC,KAAAA,CAAMT,CAAsB,CAAA,CAAA,CAAA,CAAA,CAKxE,kBAAmBrB,CAAAA,GAClB6B,CAAAA,CAAmB,YAAA,CAAeC,KAAAA,CAAMnB,CAAqB,CAAA,CAAA,CAAA,CAIlE,QAAA,GAAYX,CAAAA,GACX6B,CAAAA,CAAmB,SAAW1B,CAAAA,CAC9B0B,CAAAA,CAAmB,OAAA,CAAU5B,CAAAA,CAE1B,aAAcD,CAAAA,GACb6B,CAAAA,CAAmB,kBAAA,CAAqBxB,CAAAA,CACxCwB,EAAmB,eAAA,CAAkBzB,CAAAA,CAAAA,CAAAA,CAI1C,oBAAA,GAAwBJ,CAAAA,GACvB6B,EAAmB,MAAA,CAASD,CAAAA,CAAAA,CAG1BC,CACX,KAEOE,CAAAA,CAAQhC","file":"index.js","sourcesContent":["import ensureID from './ensure-id';\nimport getIDFromParams from './get-id-from-params';\n\nasync function ensureIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T> {\n const id = await getIDFromParams<T>(key, prefix, params);\n return ensureID<T>(id, prefix);\n}\n\nexport default ensureIDFromParams;\n","import { cache } from 'react';\n\nimport { eq } from 'drizzle-orm';\nimport type { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\n\nimport ensureSessionUser from '../auth/users/ensure-session-user';\n\nimport ensureID from '../utility/ensure-id';\nimport getIDFromParams from '../utility/get-id-from-params';\nimport guardID from '../utility/guard-id';\nimport type { Paginated } from '../utility/interfaces';\n\nimport type {\n InferColumnType,\n InferCreate,\n InferFilters,\n InferGuards,\n InferID,\n InferQueryModel,\n InferRepository,\n InferUpdate,\n QueryConditions,\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n} from './utility/interfaces';\nimport ensureIDFromParams from '../utility/ensure-id-from-params';\n\nfunction createRepository<\n I extends Record<string, PgColumn<any, any, any>>,\n C extends RepositoryConfig,\n>(repoConfig: C & { indexes?: I }): InferRepository<I, C> {\n // ----------------------------------------------------------------------------------\n // Guard Functions\n // ----------------------------------------------------------------------------------\n\n function uncached_guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): InferID<C>[] | InferID<C> | null {\n if (!repoConfig.prefix) {\n throw new Error('Could not `guardID`. `prefix` is not defined.');\n }\n\n if (Array.isArray(id)) {\n return guardID<InferID<C>>(id, repoConfig.prefix);\n }\n\n return guardID<InferID<C>>(id, repoConfig.prefix);\n }\n\n function uncached_ensureID(id: string | null | undefined): InferID<C> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `ensureID`. `prefix` is not defined.');\n }\n\n return ensureID<InferID<C>>(id, repoConfig.prefix);\n }\n\n async function uncached_getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return getIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n async function uncached_ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return ensureIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n // ----------------------------------------------------------------------------------\n // List Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getAll(\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>[]> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getAll`. `makeQuery` function is not defined.');\n }\n\n const conditions: QueryConditions = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n return repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? -1,\n offset: config?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n config?: PaginatedSelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<Paginated<InferQueryModel<C>>> {\n if (!repoConfig.makeMetaQuery) {\n throw new Error('Could not `getPaginated`. `makeMetaQuery` function is not defined.');\n }\n\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getPaginated`. `makeQuery` function is not defined.');\n }\n\n const conditions: QueryConditions = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n const meta = await repoConfig.makeMetaQuery(conditions);\n const data = await repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? 10,\n offset: ((config?.page ?? 1) - 1) * (config?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: config?.limit ?? 10, page: config?.page ?? 1, total: meta.count },\n };\n }\n\n // ----------------------------------------------------------------------------------\n // Index Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C> | null> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getByIndex`. `makeQuery` function is not defined.');\n }\n\n if (!repoConfig.indexes?.[key]) {\n throw new Error(\n `'Could not \\`getByIndex\\`. Index ${String(key)} is not defined in the repository configuration.`\n );\n }\n\n const conditions: QueryConditions = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n conditions.push(eq(repoConfig.indexes[key], value));\n\n const [result] = await repoConfig.makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>> {\n const result = await uncached_getByIndex(key, value, config);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: InferID<C>): Promise<InferQueryModel<C> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: InferID<C>): Promise<InferQueryModel<C>> {\n return uncached_ensureByIndex('id', id);\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C> | null> {\n const id = await uncached_getIDFromParams(params);\n return id ? uncached_getByID(id) : null;\n }\n\n async function uncached_ensureFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C>> {\n const id = await uncached_ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function uncached_ensureFromSession(): Promise<InferQueryModel<C>> {\n const user = await ensureSessionUser();\n const id = uncached_ensureID(user.id);\n\n return uncached_ensureByID(id);\n }\n\n // ----------------------------------------------------------------------------------\n // Mutation Functions\n // ----------------------------------------------------------------------------------\n\n async function create(data: InferCreate<C>['data']): Promise<InferCreate<C>['model']> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\n }\n\n return repoConfig.makeCreateMutation(data);\n }\n\n async function update(data: InferUpdate<C>['data']): Promise<InferUpdate<C>['model']> {\n if (!repoConfig.makeUpdateMutation) {\n throw new Error('Could not `update`. `makeUpdateMutation` is not defined.');\n }\n\n return repoConfig.makeUpdateMutation(data);\n }\n\n const repository = {} as InferRepository<I, C>;\n\n if ('makeCreateMutation' in repoConfig) {\n (repository as any).create = create;\n }\n\n if ('makeQuery' in repoConfig) {\n (repository as any).getAll = cache(uncached_getAll);\n\n if ('indexes' in repoConfig) {\n (repository as any).ensureByID = cache(uncached_ensureByID);\n (repository as any).ensureByIndex = cache(uncached_ensureByIndex);\n (repository as any).getByID = cache(uncached_getByID);\n (repository as any).getByIndex = cache(uncached_getByIndex);\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureFromSession = cache(uncached_ensureFromSession);\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureFromParams = cache(uncached_ensureFromParams);\n (repository as any).getFromParams = cache(uncached_getFromParams);\n }\n }\n }\n\n if ('makeMetaQuery' in repoConfig) {\n (repository as any).getPaginated = cache(uncached_getPaginated);\n }\n }\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureID = uncached_ensureID;\n (repository as any).guardID = uncached_guardID;\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureIDFromParams = uncached_ensureIDFromParams;\n (repository as any).getIDFromParams = uncached_getIDFromParams;\n }\n }\n\n if ('makeUpdateMutation' in repoConfig) {\n (repository as any).update = update;\n }\n\n return repository;\n}\n\nexport default createRepository;\n"]}
|
package/dist/forms/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
1
|
+
import z$1, { z } from 'zod';
|
|
2
2
|
|
|
3
3
|
interface AwaitedFormResponse<M> {
|
|
4
4
|
data: M | null;
|
|
@@ -6,6 +6,19 @@ interface AwaitedFormResponse<M> {
|
|
|
6
6
|
validation: Record<string, string> | null;
|
|
7
7
|
}
|
|
8
8
|
type FormResponse<M> = Promise<AwaitedFormResponse<M>>;
|
|
9
|
+
type ValidationRule<V, T = undefined> = T extends undefined ? {
|
|
10
|
+
validator: V;
|
|
11
|
+
} : {
|
|
12
|
+
validator: V;
|
|
13
|
+
transformer: T;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare function createRule<V, T = undefined>(config: {
|
|
17
|
+
validator: V;
|
|
18
|
+
} | {
|
|
19
|
+
validator: V;
|
|
20
|
+
transformer: T;
|
|
21
|
+
}): ValidationRule<V, T>;
|
|
9
22
|
|
|
10
23
|
/**
|
|
11
24
|
* Custom error class to represent validation errors in form processing.
|
|
@@ -18,7 +31,7 @@ declare class ValidationError extends Error {
|
|
|
18
31
|
constructor(messages: Record<string, string>);
|
|
19
32
|
}
|
|
20
33
|
|
|
21
|
-
interface SubmitFormArgs<Schema extends z.
|
|
34
|
+
interface SubmitFormArgs<Schema extends z.ZodTypeAny, Response> {
|
|
22
35
|
fn: (data: z.infer<Schema>) => Promise<Response>;
|
|
23
36
|
formData: object;
|
|
24
37
|
onSuccess?: (model: Response) => Promise<void> | void;
|
|
@@ -31,6 +44,22 @@ interface SubmitFormArgs<Schema extends z.ZodType, Response> {
|
|
|
31
44
|
* @param args The arguments for submitting the form.
|
|
32
45
|
* @returns A promise that resolves to either the submitted model or an error.
|
|
33
46
|
*/
|
|
34
|
-
declare function submitForm<Schema extends z.
|
|
47
|
+
declare function submitForm<Schema extends z.ZodTypeAny, Response>(args: SubmitFormArgs<Schema, Response>): Promise<FormResponse<Response>>;
|
|
48
|
+
|
|
49
|
+
declare function validateSchema<T extends z.ZodTypeAny>(data: object, schema: T): Promise<z.infer<T>>;
|
|
50
|
+
|
|
51
|
+
declare function getCSVRule(): {
|
|
52
|
+
validator: z$1.ZodPipe<z$1.ZodString, z$1.ZodTransform<string[][], string>>;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
declare function getExistsTransformer<T, ID>(key: string, value: ID, fn: (value: ID) => Promise<T>): Promise<NonNullable<T>>;
|
|
56
|
+
|
|
57
|
+
declare function getExistsValidator<T, ID>(fn: (value: ID) => Promise<T>): [(value: ID) => Promise<boolean>, {
|
|
58
|
+
message: string;
|
|
59
|
+
}];
|
|
60
|
+
|
|
61
|
+
declare function getNotExistsValidator<T, ID>(fn: (value: ID) => Promise<T>): [(value: ID) => Promise<boolean>, {
|
|
62
|
+
message: string;
|
|
63
|
+
}];
|
|
35
64
|
|
|
36
|
-
export { type FormResponse, submitForm };
|
|
65
|
+
export { type FormResponse, ValidationError, type ValidationRule, createRule, getCSVRule, getExistsTransformer, getExistsValidator, getNotExistsValidator, submitForm, validateSchema };
|
package/dist/forms/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-UCMLSO7F.js';import {a as a$1}from'../chunk-3JA7XHAG.js';export{a as ValidationError}from'../chunk-3JA7XHAG.js';import {redirect}from'next/navigation';import v,{z as z$1}from'zod';function c(e){return e}var s=c;function R(e){let[,,t]=e.split(";");redirect(`${t.startsWith("/")?"":"/"}${t}`);}var m=R;function l(e){let t={};for(let r in e)typeof e[r]=="string"?t[r]=e[r].trim():typeof e[r]=="object"&&e[r]!==null?t[r]=l(e[r]):t[r]=e[r];return t}var u=l;function g(e){return e.issues.reduce((t,r)=>({...t,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var f=g;function x(e){return typeof e.input>"u"&&(e.code==="invalid_type"||e.code==="invalid_value")||!e.input&&(e.code==="invalid_format"||e.code==="too_small")}function T(e){return x(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var d=T;async function E(e,t){try{return await t.parseAsync(u(e),{error:o=>d(o)})}catch(r){throw r instanceof z$1.ZodError?new a$1(f(r)):r}}var n=E;async function I(e){let t={data:null,error:null,validation:null};try{let r=await n(e.formData,e.schema),o=await e.fn(r);return await e.onSuccess?.(o),{...t,data:o}}catch(r){if(r instanceof a$1)return e.onValidationError?.(r),{...t,validation:r.messages};if(r instanceof Error)throw r.message==="NEXT_REDIRECT"&&"digest"in r&&m(String(r.digest)),r;return {...t,error:"submitForm encountered an unknown error"}}}var V=I;var h=v.string().transform(a);function D(){return s({validator:h})}var w=D;async function S(e,t,r){let o=await r(t);if(!o)throw new a$1({[e]:"NOT_FOUND"});return o}var b=S;function Z(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var F=Z;function z(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var $=z;export{s as createRule,w as getCSVRule,b as getExistsTransformer,F as getExistsValidator,$ as getNotExistsValidator,V as submitForm,n as validateSchema};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/forms/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/validate-schema.ts","../../src/forms/submit-form.ts"],"names":["handleRedirect","digest","path","redirect","handle_redirect_default","transformErrors","error","acc","cur","transform_errors_default","validateSchema","data","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default"],"mappings":"uGAEA,SAASA,EAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,EAAO,KAAA,CAAM,GAAG,EACnCE,QAAAA,CAAS,CAAA,EAAGD,EAAK,UAAA,CAAW,GAAG,EAAI,EAAA,CAAK,GAAG,GAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,EAAQJ,CAAAA,CCLf,SAASK,CAAAA,CAAgBC,CAAAA,CAA2C,CAChE,OAAOA,CAAAA,CAAM,OAAO,MAAA,CAChB,CAACC,EAAKC,CAAAA,IAAS,CACX,GAAGD,CAAAA,CACH,CAACC,EAAI,IAAA,CAAK,IAAA,CAAK,GAAG,CAAC,EAAGA,EAAI,OAAA,CAAQ,OAAA,CAAQ,MAAO,EAAE,CACvD,GACA,EACJ,CACJ,CAEA,IAAOC,EAAQJ,CAAAA,CCPf,eAAeK,EAAoCC,CAAAA,CAAcC,CAAAA,CAAgC,CAC7F,GAAI,CAEA,OADe,MAAMA,CAAAA,CAAO,WAAWD,CAAI,CAE/C,OAASL,CAAAA,CAAO,CACZ,MAAIA,CAAAA,YAAiBO,CAAAA,CAAE,QAAA,CACb,IAAIC,GAAAA,CAAgBL,CAAAA,CAAgBH,CAAK,CAAC,CAAA,CAE9CA,CACV,CACJ,CAEA,IAAOS,CAAAA,CAAQL,CAAAA,CCIf,eAAeM,CAAAA,CACXC,CAAAA,CAC+B,CAC/B,IAAIC,CAAAA,CAA0C,CAAE,IAAA,CAAM,IAAA,CAAM,MAAO,IAAA,CAAM,UAAA,CAAY,IAAK,CAAA,CAE1F,GAAI,CACA,IAAMP,CAAAA,CAAO,MAAMI,CAAAA,CAAeE,CAAAA,CAAK,SAAUA,CAAAA,CAAK,MAAM,EACtDE,CAAAA,CAAQ,MAAMF,EAAK,EAAA,CAAGN,CAAI,EAEhC,OAAA,MAAMM,CAAAA,CAAK,YAAYE,CAAK,CAAA,CAErB,CAAE,GAAGD,CAAAA,CAAU,KAAMC,CAAM,CACtC,OAASb,CAAAA,CAAO,CACZ,GAAIA,CAAAA,YAAiBQ,GAAAA,CACjB,OAAAG,CAAAA,CAAK,iBAAA,GAAoBX,CAAK,CAAA,CACvB,CAAE,GAAGY,CAAAA,CAAU,UAAA,CAAYZ,EAAM,QAAS,CAAA,CAErD,GAAIA,CAAAA,YAAiB,KAAA,CACjB,MAAIA,CAAAA,CAAM,OAAA,GAAY,iBAAmB,QAAA,GAAYA,CAAAA,EACjDF,EAAe,MAAA,CAAOE,CAAAA,CAAM,MAAM,CAAC,CAAA,CAEjCA,EAGV,OAAO,CAAE,GAAGY,CAAAA,CAAU,KAAA,CAAO,yCAA0C,CAC3E,CACJ,CAEA,IAAOE,CAAAA,CAAQJ","file":"index.js","sourcesContent":["import { redirect } from 'next/navigation';\n\nfunction handleRedirect(digest: string): void {\n const [, , path] = digest.split(';');\n redirect(`${path.startsWith('/') ? '' : '/'}${path}`);\n}\n\nexport default handleRedirect;\n","import { z } from 'zod';\n\nfunction transformErrors(error: z.ZodError): Record<string, string> {\n return error.issues.reduce(\n (acc, cur) => ({\n ...acc,\n [cur.path.join('.')]: cur.message.replace(/\"/gu, ''),\n }),\n {}\n );\n}\n\nexport default transformErrors;\n","import { z } from 'zod';\n\nimport ValidationError from './ValidationError';\nimport transformErrors from './transform-errors';\n\nasync function validateSchema<T extends z.ZodType>(data: object, schema: T): Promise<z.infer<T>> {\n try {\n const result = await schema.parseAsync(data);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new ValidationError(transformErrors(error));\n }\n throw error;\n }\n}\n\nexport default validateSchema;\n","import { z } from 'zod';\n\nimport handleRedirect from './utility/handle-redirect';\nimport type { AwaitedFormResponse, FormResponse } from './utility/interfaces';\nimport ValidationError from './utility/ValidationError';\nimport validateSchema from './utility/validate-schema';\n\ninterface SubmitFormArgs<Schema extends z.ZodType, Response> {\n fn: (data: z.infer<Schema>) => Promise<Response>;\n formData: object;\n onSuccess?: (model: Response) => Promise<void> | void;\n onValidationError?: (error: ValidationError) => void;\n schema: Schema;\n}\n\n/**\n * Submit a form and handle validation and submission errors.\n *\n * @param args The arguments for submitting the form.\n * @returns A promise that resolves to either the submitted model or an error.\n */\nasync function submitForm<Schema extends z.ZodType, Response>(\n args: SubmitFormArgs<Schema, Response>\n): Promise<FormResponse<Response>> {\n let response: AwaitedFormResponse<Response> = { data: null, error: null, validation: null };\n\n try {\n const data = await validateSchema(args.formData, args.schema);\n const model = await args.fn(data);\n\n await args.onSuccess?.(model);\n\n return { ...response, data: model };\n } catch (error) {\n if (error instanceof ValidationError) {\n args.onValidationError?.(error);\n return { ...response, validation: error.messages };\n }\n if (error instanceof Error) {\n if (error.message === 'NEXT_REDIRECT' && 'digest' in error) {\n handleRedirect(String(error.digest));\n }\n throw error;\n // return { ...response, error: error.message };\n }\n return { ...response, error: 'submitForm encountered an unknown error' };\n }\n}\n\nexport default submitForm;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/forms/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/clean-data.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/transform-issue.ts","../../src/forms/validate-schema.ts","../../src/forms/submit-form.ts","../../src/forms/rules/get-csv-rule.ts","../../src/forms/transformers/get-exists-transformer.ts","../../src/forms/validators/get-exists-validator.ts","../../src/forms/validators/get-not-exists-validator.ts"],"names":["createRule","config","create_rule_default","handleRedirect","digest","path","redirect","handle_redirect_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default","validator","parse_csv_default","getCSVRule","get_csv_rule_default","getExistsTransformer","value","fn","result","get_exists_transformer_default","getExistsValidator","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],"mappings":"4MAEA,SAASA,CAAAA,CACLC,EACoB,CACpB,OAAOA,CACX,CAEA,IAAOC,EAAQF,ECNf,SAASG,CAAAA,CAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,EAAO,KAAA,CAAM,GAAG,EACnCE,QAAAA,CAAS,CAAA,EAAGD,EAAK,UAAA,CAAW,GAAG,CAAA,CAAI,EAAA,CAAK,GAAG,CAAA,EAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,CAAAA,CAAQJ,ECPf,SAASK,CAAAA,CAAUC,EAAsB,CACrC,IAAMC,EAAuC,EAAC,CAE9C,QAAWC,CAAAA,IAAOF,CAAAA,CACV,OAAOA,CAAAA,CAAKE,CAAG,CAAA,EAAM,SACrBD,CAAAA,CAAYC,CAAG,EAAIF,CAAAA,CAAKE,CAAG,EAAE,IAAA,EAAK,CAC3B,OAAOF,CAAAA,CAAKE,CAAG,CAAA,EAAM,UAAYF,CAAAA,CAAKE,CAAG,IAAM,IAAA,CACtDD,CAAAA,CAAYC,CAAG,CAAA,CAAIH,CAAAA,CAAUC,CAAAA,CAAKE,CAAG,CAAW,CAAA,CAEhDD,EAAYC,CAAG,CAAA,CAAIF,EAAKE,CAAG,CAAA,CAInC,OAAOD,CACX,CAEA,IAAOE,CAAAA,CAAQJ,CAAAA,CCdf,SAASK,EAAgBC,CAAAA,CAA2C,CAChE,OAAOA,CAAAA,CAAM,MAAA,CAAO,OAChB,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CACX,GAAGD,CAAAA,C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A,CAAS,WAAY,CAC3B,CACJ,CAEA,IAAOK,CAAAA,CAAQD,ECZf,SAASE,CAAAA,CACLL,EACsD,CACtD,OAAO,CACH,MAAOD,CAAAA,EAEI,CADQ,MAAMC,CAAAA,CAAGD,CAAK,EAGjC,CAAE,OAAA,CAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOO,CAAAA,CAAQD","file":"index.js","sourcesContent":["import type { ValidationRule } from './utility/interfaces';\n\nfunction createRule<V, T = undefined>(\n config: { validator: V } | { validator: V; transformer: T }\n): ValidationRule<V, T> {\n return config as ValidationRule<V, T>;\n}\n\nexport default createRule;\n","import { redirect } from 'next/navigation';\n\nfunction handleRedirect(digest: string): void {\n const [, , path] = digest.split(';');\n redirect(`${path.startsWith('/') ? '' : '/'}${path}`);\n}\n\nexport default handleRedirect;\n","function cleanData(data: object): object {\n const cleanedData: Record<string, unknown> = {};\n\n for (const key in data) {\n if (typeof data[key] === 'string') {\n cleanedData[key] = data[key].trim();\n } else if (typeof data[key] === 'object' && data[key] !== null) {\n cleanedData[key] = cleanData(data[key] as object);\n } else {\n cleanedData[key] = data[key];\n }\n }\n\n return cleanedData;\n}\n\nexport default cleanData;\n","import { z } from 'zod';\n\nfunction transformErrors(error: z.ZodError): Record<string, string> {\n return error.issues.reduce(\n (acc, cur) => ({\n ...acc,\n [cur.path.join('.')]: cur.message.replace(/\"/gu, ''),\n }),\n {}\n );\n}\n\nexport default transformErrors;\n","import type { $ZodIssue, $ZodIssueBase, $ZodRawIssue } from 'zod/v4/core';\n\nfunction isRequired<T extends $ZodIssueBase = $ZodIssue>(issue: $ZodRawIssue<T>): boolean {\n if (\n typeof issue.input === 'undefined' &&\n (issue.code === 'invalid_type' || issue.code === 'invalid_value')\n ) {\n return true;\n }\n\n if (!issue.input && (issue.code === 'invalid_format' || issue.code === 'too_small')) {\n return true;\n }\n\n return false;\n}\n\nfunction transformIssue<T extends $ZodIssueBase = $ZodIssue>(\n issue: $ZodRawIssue<T>\n): { message: string } | null {\n if (isRequired(issue)) {\n return { message: 'REQUIRED' };\n }\n\n return issue.message ? { message: issue.message } : null;\n}\n\nexport default transformIssue;\n","import { z } from 'zod';\n\nimport cleanData from './utility/clean-data';\nimport transformErrors from './utility/transform-errors';\nimport transformIssue from './utility/transform-issue';\n\nimport ValidationError from './ValidationError';\n\nasync function validateSchema<T extends z.ZodTypeAny>(\n data: object,\n schema: T\n): Promise<z.infer<T>> {\n try {\n const result = await schema.parseAsync(cleanData(data), {\n error: (issue) => transformIssue(issue),\n });\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new ValidationError(transformErrors(error));\n }\n throw error;\n }\n}\n\nexport default validateSchema;\n","import { z } from 'zod';\n\nimport handleRedirect from './utility/handle-redirect';\nimport type { AwaitedFormResponse, FormResponse } from './utility/interfaces';\n\nimport ValidationError from './ValidationError';\nimport validateSchema from './validate-schema';\n\ninterface SubmitFormArgs<Schema extends z.ZodTypeAny, Response> {\n fn: (data: z.infer<Schema>) => Promise<Response>;\n formData: object;\n onSuccess?: (model: Response) => Promise<void> | void;\n onValidationError?: (error: ValidationError) => void;\n schema: Schema;\n}\n\n/**\n * Submit a form and handle validation and submission errors.\n *\n * @param args The arguments for submitting the form.\n * @returns A promise that resolves to either the submitted model or an error.\n */\nasync function submitForm<Schema extends z.ZodTypeAny, Response>(\n args: SubmitFormArgs<Schema, Response>\n): Promise<FormResponse<Response>> {\n let response: AwaitedFormResponse<Response> = { data: null, error: null, validation: null };\n\n try {\n const data = await validateSchema(args.formData, args.schema);\n const model = await args.fn(data);\n\n await args.onSuccess?.(model);\n\n return { ...response, data: model };\n } catch (error) {\n if (error instanceof ValidationError) {\n args.onValidationError?.(error);\n return { ...response, validation: error.messages };\n }\n if (error instanceof Error) {\n if (error.message === 'NEXT_REDIRECT' && 'digest' in error) {\n handleRedirect(String(error.digest));\n }\n throw error;\n // return { ...response, error: error.message };\n }\n return { ...response, error: 'submitForm encountered an unknown error' };\n }\n}\n\nexport default submitForm;\n","import z from 'zod';\n\nimport parseCSV from '../../csv/parse-csv';\n\nimport createRule from '../create-rule';\n\nconst validator = z.string().transform(parseCSV);\n\nfunction getCSVRule() {\n return createRule({ validator });\n}\n\nexport default getCSVRule;\n","import ValidationError from '../ValidationError';\n\nasync function getExistsTransformer<T, ID>(\n key: string,\n value: ID,\n fn: (value: ID) => Promise<T>\n): Promise<NonNullable<T>> {\n const result = await fn(value);\n\n if (!result) {\n throw new ValidationError({ [key]: 'NOT_FOUND' });\n }\n\n return result;\n}\n\nexport default getExistsTransformer;\n","function getExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return Boolean(result);\n },\n { message: 'NOT_FOUND' },\n ];\n}\n\nexport default getExistsValidator;\n","function getNotExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return !result;\n },\n { message: 'ALREADY_EXISTS' },\n ];\n}\n\nexport default getNotExistsValidator;\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
filters?: Partial<Filters> | null;
|
|
1
|
+
type ListFunctionConfig<Filters = undefined> = {
|
|
3
2
|
params?: Record<string, string> | null;
|
|
4
3
|
page?: number | null;
|
|
5
|
-
}
|
|
4
|
+
} & (Filters extends undefined ? {} : {
|
|
5
|
+
filters?: Partial<Filters> | null;
|
|
6
|
+
});
|
|
6
7
|
type MakeNullOptional<T> = {
|
|
7
8
|
[K in keyof T as null extends T[K] ? K : never]?: T[K];
|
|
8
9
|
} & {
|
package/dist/json/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
+
declare function validateJsonResponse<T extends z.ZodType>(query: Promise<Response>, schema: T): Promise<z.infer<T>>;
|
|
4
|
+
|
|
3
5
|
declare function validateJson<T extends z.ZodType>(data: unknown, schema: T): z.infer<T>;
|
|
4
6
|
|
|
5
|
-
export { validateJson };
|
|
7
|
+
export { validateJson, validateJsonResponse };
|
package/dist/json/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function s(e,o){return o.parse(e)}var t=s;async function a(e,o){let n=await(await e).json();return t(n,o)}var r=a;export{t as validateJson,r as validateJsonResponse};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/json/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/json/validate-json.ts"],"names":["validateJson","data","schema","validate_json_default"],"mappings":"AAEA,SAASA,CAAAA,CAAkCC,CAAAA,CAAeC,CAAAA,CAAuB,CAC7E,OAAOA,CAAAA,CAAO,KAAA,CAAMD,CAAI,CAC5B,CAEA,IAAOE,CAAAA,CAAQH","file":"index.js","sourcesContent":["import type { z } from 'zod';\n\nfunction validateJson<T extends z.ZodType>(data: unknown, schema: T): z.infer<T> {\n return schema.parse(data);\n}\n\nexport default validateJson;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/json/validate-json.ts","../../src/json/validate-json-response.ts"],"names":["validateJson","data","schema","validate_json_default","validateJsonResponse","query","validate_json_response_default"],"mappings":"AAEA,SAASA,CAAAA,CAAkCC,CAAAA,CAAeC,CAAAA,CAAuB,CAC7E,OAAOA,CAAAA,CAAO,KAAA,CAAMD,CAAI,CAC5B,CAEA,IAAOE,CAAAA,CAAQH,ECFf,eAAeI,CAAAA,CACXC,CAAAA,CACAH,CAAAA,CACmB,CAEnB,IAAMD,CAAAA,CAAO,KAAA,CADI,MAAMI,GACK,IAAA,EAAK,CAEjC,OAAOF,CAAAA,CAAaF,CAAAA,CAAMC,CAAM,CACpC,KAEOI,CAAAA,CAAQF","file":"index.js","sourcesContent":["import type { z } from 'zod';\n\nfunction validateJson<T extends z.ZodType>(data: unknown, schema: T): z.infer<T> {\n return schema.parse(data);\n}\n\nexport default validateJson;\n","import type { z } from 'zod';\n\nimport validateJson from './validate-json';\n\nasync function validateJsonResponse<T extends z.ZodType>(\n query: Promise<Response>,\n schema: T\n): Promise<z.infer<T>> {\n const response = await query;\n const data = await response.json();\n\n return validateJson(data, schema);\n}\n\nexport default validateJsonResponse;\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
interface MailObject<T extends object> {
|
|
2
|
+
subject: string | ((data: T) => Promise<string> | string);
|
|
3
|
+
template: (data: T) => Promise<React.ReactElement> | React.ReactElement;
|
|
4
|
+
}
|
|
5
|
+
interface MailOptions {
|
|
6
|
+
attachments?: {
|
|
7
|
+
content: string;
|
|
8
|
+
filename: string;
|
|
9
|
+
type: string;
|
|
10
|
+
}[];
|
|
11
|
+
bcc?: string[] | string;
|
|
12
|
+
cc?: string[] | string;
|
|
13
|
+
from?: string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
declare function createMail<T extends object>(subject: string | ((data: T) => Promise<string> | string), template: (data: T) => Promise<React.ReactElement> | React.ReactElement): MailObject<T>;
|
|
17
|
+
|
|
18
|
+
declare function sendMail<T extends object>(to: string[] | string, mail: MailObject<T>, data?: T, options?: MailOptions): Promise<boolean>;
|
|
19
|
+
|
|
20
|
+
export { type MailObject, createMail, sendMail };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import y from'@sendgrid/mail';import x from'stream';function v(t,e){return {subject:t,template:e}}var w=v;function P(t){return t?Array.isArray(t)?t.map(e=>({email:e})):[{email:t}]:[]}var c=P;async function S(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Mailtrap. Mail API key has not been set.");let[e,r]=process.env.MAIL_API_KEY.split("."),i=await(await fetch(`https://sandbox.api.mailtrap.io/api/send/${e}`,{method:"POST",headers:{"Api-Token":r,"Content-Type":"application/json"},body:JSON.stringify({attachments:t.attachments,bcc:c(t.bcc),cc:c(t.cc),from:t.from,html:t.html,subject:t.subject,to:c(t.to)})})).json();if(i.errors)throw new Error(`Could not send mail via Mailtrap. ${i.errors[0]}.`);return true}var M=S;function f(t,e){return Array.isArray(t)?t.map(r=>({email:r,type:e})):[{email:t,type:e}]}function _(t,e,r){return [...f(t,"to"),...f(e||[],"cc"),...f(r||[],"bcc")]}var g=_;async function T(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Mandrill. Mail API key has not been set.");let r={attachments:t.attachments?.map(o=>({content:o.content,name:o.filename,type:o.type})),from_email:t.from.email,from_name:t.from.name,html:t.html,subject:t.subject,preserve_recipients:true,to:g(t.to,t.cc,t.bcc)},i=await(await fetch("https://mandrillapp.com/api/1.0/messages/send",{method:"POST",body:JSON.stringify({key:process.env.MAIL_API_KEY,message:r})})).json();return Array.isArray(i)?i.every(o=>o.status==="sent"):i.status==="sent"}var A=T;function D(t){return t?Array.isArray(t)?t.map(e=>({email:e})):[{email:t}]:[]}var l=D;async function L(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Sendgrid. Mail API key has not been set.");y.setApiKey(process.env.MAIL_API_KEY);let e=await y.send({attachments:t.attachments,bcc:l(t.bcc),cc:l(t.cc),from:t.from,html:t.html,to:l(t.to),subject:t.subject});if(!e[0].statusCode.toString().startsWith("2"))throw new Error(`Could not send mail via Sendgrid. ${JSON.stringify(e)}`);return true}var R=L;async function N(t){let e=(await import('react-dom/server')).default;return new Promise(r=>{let n=new x.Writable,i="";function o(m,d,p){i+=m.toString(),p();}n._write=o;let{pipe:s}=e.renderToPipeableStream(t,{onShellReady:()=>{s(n),r(i);}});})}var b=N;async function O(t,e){let{subject:r,template:n}=t,i=typeof r=="function"?await r(e):r,o=await n(e);return {html:await b(o),subject:i}}var h=O;function j(t){if(!t&&!process.env.MAIL_FROM)throw new Error("Mail from address has not been set as an environment variable, or provided in options.");let e=/^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(t||process.env.MAIL_FROM||"");if(!e?.groups?.name||!e?.groups?.email)throw new Error('Mail from address is not the correct format. It should be "Name <email>".');return {email:e.groups.email.trim(),name:e.groups.name.trim()}}var I=j;var C=["MAILTRAP"],U=["MAILTRAP","MANDRILL","SENDGRID"],V="MAILTRAP",K="SENDGRID",E={MAILTRAP:M,MANDRILL:A,SENDGRID:R};async function k(t,e,r,n){let i=I(n?.from),{subject:o,html:s}=await h(e,r||{}),m={attachments:n?.attachments,bcc:n?.bcc,cc:n?.cc,from:i,html:s,subject:o,to:t},d=process.env.MAIL_ENABLE_PRODUCTION==="true"?U:C,p=process.env.MAIL_ENABLE_PRODUCTION==="true"?K:V,a=process.env.MAIL_DRIVER?process.env.MAIL_DRIVER.toUpperCase():p;if(!d.includes(a)||!E[a])throw new Error(`Mail driver ${a} is not supported. If you're in a production environment, you might need to set the MAIL_ENABLE_PRODUCTION environment variable to access this driver.`);let u=E[a];if(!u)throw new Error(`Mail driver ${a} is not supported.`);return u(m)}var Y=k;
|
|
2
|
+
export{w as createMail,Y as sendMail};//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mail/create-mail.ts","../../src/mail/drivers/mailtrap/transform-mailtrap-recipients.ts","../../src/mail/drivers/mailtrap/index.ts","../../src/mail/drivers/mandrill/transform-mandrill-recipients.ts","../../src/mail/drivers/mandrill/index.ts","../../src/mail/drivers/sendgrid/transform-sendgrid-recipients.ts","../../src/mail/drivers/sendgrid/index.ts","../../src/mail/utility/render-mail.ts","../../src/mail/utility/get-mail.ts","../../src/mail/utility/get-sender-details.ts","../../src/mail/send-mail.ts"],"names":["createMail","subject","template","create_mail_default","transformMailtrapRecipients","emails","email","transform_mailtrap_recipients_default","sendMailtrapMail","sendObject","id","key","json","mailtrap_default","transformMandrillRecipientGroup","group","type","transformMandrillRecipients","to","cc","bcc","transform_mandrill_recipients_default","sendMandrillMail","message","attachment","item","mandrill_default","transformSendgridRecipients","transform_sendgrid_recipients_default","sendSendgridMail","sgMail","response","sendgrid_default","renderMail","element","ReactDOMServer","resolve","ws","stream","content","write","chunk","enc","next","pipe","render_mail_default","getMail","mail","data","subjectText","get_mail_default","getSenderDetails","from","matches","get_sender_details_default","DEVELOPMENT_DRIVERS","PRODUCTION_DRIVERS","DEFAULT_DEVELOPMENT_DRIVER","DEFAULT_PRODUCTION_DRIVER","driverMap","sendMail","options","html","allowedDriverAliases","defaultDriverAlias","driverAlias","driver","send_mail_default"],"mappings":"oDAEA,SAASA,EACLC,CAAAA,CACAC,CAAAA,CACa,CACb,OAAO,CAAE,QAAAD,CAAAA,CAAS,QAAA,CAAAC,CAAS,CAC/B,CAEA,IAAOC,CAAAA,CAAQH,ECTf,SAASI,CAAAA,CAA4BC,EAAiD,CAClF,OAAKA,CAAAA,CAGE,KAAA,CAAM,QAAQA,CAAM,CAAA,CAAIA,EAAO,GAAA,CAAKC,CAAAA,GAAW,CAAE,KAAA,CAAAA,CAAM,EAAE,CAAA,CAAI,CAAC,CAAE,KAAA,CAAOD,CAAO,CAAC,CAAA,CAF3E,EAGf,CAEA,IAAOE,CAAAA,CAAQH,CAAAA,CCHf,eAAeI,CAAAA,CAAiBC,CAAAA,CAAkD,CAC9E,GAAI,CAAC,QAAQ,GAAA,CAAI,YAAA,CACb,MAAM,IAAI,MAAM,kEAAkE,CAAA,CAQtF,GAAM,CAACC,CAAAA,CAAIC,CAAG,CAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,MAAM,GAAG,CAAA,CAgB9CC,EAAQ,KAAA,CAdG,MAAM,MAAM,CAAA,yCAAA,EAA4CF,CAAE,GAAI,CAC3E,MAAA,CAAQ,OACR,OAAA,CAAS,CAAE,YAAaC,CAAAA,CAAK,cAAA,CAAgB,kBAAmB,CAAA,CAChE,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACjB,WAAA,CAAaF,CAAAA,CAAW,YACxB,GAAA,CAAKF,CAAAA,CAA4BE,EAAW,GAAG,CAAA,CAC/C,EAAA,CAAIF,CAAAA,CAA4BE,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,MAAMZ,CAAAA,CAAQH,EAAMC,CAAAA,EAAQ,EAAE,CAAA,CAElDvC,CAAAA,CAAiC,CACnC,WAAA,CAAaoD,CAAAA,EAAS,WAAA,CACtB,GAAA,CAAKA,GAAS,GAAA,CACd,EAAA,CAAIA,GAAS,EAAA,CACb,IAAA,CAAAT,EACA,IAAA,CAAAU,CAAAA,CACA,OAAA,CAAA7D,CAAAA,CACA,GAAAiB,CACJ,CAAA,CAEM6C,EACF,OAAA,CAAQ,GAAA,CAAI,yBAA2B,MAAA,CAASP,CAAAA,CAAqBD,EAEnES,CAAAA,CACF,OAAA,CAAQ,IAAI,sBAAA,GAA2B,MAAA,CACjCN,EACAD,CAAAA,CAEJQ,CAAAA,CAAc,QAAQ,GAAA,CAAI,WAAA,CAC1B,OAAA,CAAQ,GAAA,CAAI,YAAY,WAAA,EAAY,CACpCD,EAEN,GAAI,CAACD,EAAqB,QAAA,CAASE,CAAW,GAAK,CAACN,CAAAA,CAAUM,CAAW,CAAA,CACrE,MAAM,IAAI,KAAA,CACN,CAAA,YAAA,EAAeA,CAAW,CAAA,sJAAA,CAC9B,CAAA,CAGJ,IAAMC,CAAAA,CAASP,EAAUM,CAAW,CAAA,CAEpC,GAAI,CAACC,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,eAAeD,CAAW,CAAA,kBAAA,CAAoB,EAGlE,OAAOC,CAAAA,CAAOzD,CAAU,CAC5B,KAEO0D,CAAAA,CAAQP","file":"index.js","sourcesContent":["import type { MailObject } from './utility/interfaces';\n\nfunction createMail<T extends object>(\n subject: string | ((data: T) => Promise<string> | string),\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement\n): MailObject<T> {\n return { subject, template };\n}\n\nexport default createMail;\n","function transformMailtrapRecipients(emails?: string[] | string): { email: string }[] {\n if (!emails) {\n return [];\n }\n return Array.isArray(emails) ? emails.map((email) => ({ email })) : [{ email: emails }];\n}\n\nexport default transformMailtrapRecipients;\n","import type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformMailtrapRecipients from './transform-mailtrap-recipients';\n\nasync function sendMailtrapMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Mailtrap. Mail API key has not been set.');\n }\n\n /*\n * The account id and api key are both in the MAIL_API_KEY variable, separated by a `.`. We need\n * to split them.\n */\n\n const [id, key] = process.env.MAIL_API_KEY.split('.');\n\n const response = await fetch(`https://sandbox.api.mailtrap.io/api/send/${id}`, {\n method: 'POST',\n headers: { 'Api-Token': key, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n attachments: sendObject.attachments,\n bcc: transformMailtrapRecipients(sendObject.bcc),\n cc: transformMailtrapRecipients(sendObject.cc),\n from: sendObject.from,\n html: sendObject.html,\n subject: sendObject.subject,\n to: transformMailtrapRecipients(sendObject.to),\n }),\n });\n\n const json = (await response.json()) as { errors?: string[] };\n\n if (json.errors) {\n throw new Error(`Could not send mail via Mailtrap. ${json.errors[0]}.`);\n }\n\n return true;\n}\n\nexport default sendMailtrapMail;\n","function transformMandrillRecipientGroup(\n group: string[] | string,\n type: 'bcc' | 'cc' | 'to'\n): { email: string; type: 'bcc' | 'cc' | 'to' }[] {\n if (Array.isArray(group)) {\n return group.map((email) => ({ email, type }));\n }\n return [{ email: group, type }];\n}\n\nfunction transformMandrillRecipients(\n to: string[] | string,\n cc?: string[] | string,\n bcc?: string[] | string\n): { email: string; type: 'bcc' | 'cc' | 'to' }[] {\n return [\n ...transformMandrillRecipientGroup(to, 'to'),\n ...transformMandrillRecipientGroup(cc || [], 'cc'),\n ...transformMandrillRecipientGroup(bcc || [], 'bcc'),\n ];\n}\n\nexport default transformMandrillRecipients;\n","import type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformMandrillRecipients from './transform-mandrill-recipients';\n\ninterface MandrillResponse {\n status: string;\n}\n\nasync function sendMandrillMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Mandrill. Mail API key has not been set.');\n }\n\n const attachments = sendObject.attachments?.map((attachment) => ({\n content: attachment.content,\n name: attachment.filename,\n type: attachment.type,\n }));\n\n /* eslint-disable camelcase */\n const message = {\n attachments,\n from_email: sendObject.from.email,\n from_name: sendObject.from.name,\n html: sendObject.html,\n subject: sendObject.subject,\n preserve_recipients: true,\n to: transformMandrillRecipients(sendObject.to, sendObject.cc, sendObject.bcc),\n };\n /* eslint-enable camelcase */\n\n const response = await fetch('https://mandrillapp.com/api/1.0/messages/send', {\n method: 'POST',\n body: JSON.stringify({\n key: process.env.MAIL_API_KEY,\n message,\n }),\n });\n\n const json = (await response.json()) as MandrillResponse | [MandrillResponse];\n\n return Array.isArray(json)\n ? json.every((item) => item.status === 'sent')\n : json.status === 'sent';\n}\n\nexport default sendMandrillMail;\n","function transformSendgridRecipients(emails?: string[] | string): { email: string }[] {\n if (!emails) {\n return [];\n }\n return Array.isArray(emails) ? emails.map((email) => ({ email })) : [{ email: emails }];\n}\n\nexport default transformSendgridRecipients;\n","import sgMail from '@sendgrid/mail';\n\nimport type { SendableMailObject } from '../../utility/interfaces';\n\nimport transformSendgridRecipients from './transform-sendgrid-recipients';\n\nasync function sendSendgridMail(sendObject: SendableMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Could not send mail via Sendgrid. Mail API key has not been set.');\n }\n\n sgMail.setApiKey(process.env.MAIL_API_KEY);\n\n const response = await sgMail.send({\n attachments: sendObject.attachments,\n bcc: transformSendgridRecipients(sendObject.bcc),\n cc: transformSendgridRecipients(sendObject.cc),\n from: sendObject.from,\n html: sendObject.html,\n to: transformSendgridRecipients(sendObject.to),\n subject: sendObject.subject,\n });\n\n if (!response[0].statusCode.toString().startsWith('2')) {\n throw new Error(`Could not send mail via Sendgrid. ${JSON.stringify(response)}`);\n }\n\n return true;\n}\n\nexport default sendSendgridMail;\n","import stream from 'node:stream';\n\nasync function renderMail(element: React.ReactElement): Promise<string> {\n const ReactDOMServer = (await import('react-dom/server')).default;\n\n return new Promise((resolve) => {\n const ws = new stream.Writable();\n let content = '';\n\n function write<T extends { toString: () => string }>(\n chunk: T,\n enc: BufferEncoding,\n next: (error?: Error | null) => void\n ): void {\n content += chunk.toString();\n next();\n }\n\n ws._write = write; // eslint-disable-line no-underscore-dangle\n\n const { pipe } = ReactDOMServer.renderToPipeableStream(element, {\n onShellReady: () => {\n pipe(ws);\n resolve(content);\n },\n });\n });\n}\n\nexport default renderMail;\n","import renderMail from './render-mail';\nimport type { MailObject } from './interfaces';\n\nasync function getMail<T extends object>(\n mail: MailObject<T>,\n data: T\n): Promise<{ subject: string; html: string }> {\n const { subject, template } = mail;\n\n const subjectText = typeof subject === 'function' ? await subject(data) : subject;\n\n const element = await template(data);\n const html = await renderMail(element);\n\n return {\n html,\n subject: subjectText,\n };\n}\n\nexport default getMail;\n","function getSenderDetails(from?: string | null): { email: string; name: string } {\n if (!from && !process.env.MAIL_FROM) {\n throw new Error(\n 'Mail from address has not been set as an environment variable, or provided in options.'\n );\n }\n\n const matches = /^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(from || process.env.MAIL_FROM || '');\n\n if (!matches?.groups?.name || !matches?.groups?.email) {\n throw new Error(\n 'Mail from address is not the correct format. It should be \"Name <email>\".'\n );\n }\n\n return {\n email: matches.groups.email.trim(),\n name: matches.groups.name.trim(),\n };\n}\n\nexport default getSenderDetails;\n","import sendMailtrapMail from './drivers/mailtrap';\nimport sendMandrillMail from './drivers/mandrill';\nimport sendSendgridMail from './drivers/sendgrid';\n\nimport getMail from './utility/get-mail';\nimport getSenderDetails from './utility/get-sender-details';\nimport type { MailDriver, MailObject, MailOptions, SendableMailObject } from './utility/interfaces';\n\nconst DEVELOPMENT_DRIVERS = ['MAILTRAP'];\nconst PRODUCTION_DRIVERS = ['MAILTRAP', 'MANDRILL', 'SENDGRID'];\n\nconst DEFAULT_DEVELOPMENT_DRIVER = 'MAILTRAP';\nconst DEFAULT_PRODUCTION_DRIVER = 'SENDGRID';\n\nconst driverMap: Record<string, MailDriver> = {\n MAILTRAP: sendMailtrapMail,\n MANDRILL: sendMandrillMail,\n SENDGRID: sendSendgridMail,\n};\n\nasync function sendMail<T extends object>(\n to: string[] | string,\n mail: MailObject<T>,\n data?: T,\n options?: MailOptions\n): Promise<boolean> {\n const from = getSenderDetails(options?.from);\n const { subject, html } = await getMail(mail, data || {});\n\n const sendObject: SendableMailObject = {\n attachments: options?.attachments,\n bcc: options?.bcc,\n cc: options?.cc,\n from,\n html,\n subject,\n to,\n };\n\n const allowedDriverAliases =\n process.env.MAIL_ENABLE_PRODUCTION === 'true' ? PRODUCTION_DRIVERS : DEVELOPMENT_DRIVERS;\n\n const defaultDriverAlias =\n process.env.MAIL_ENABLE_PRODUCTION === 'true'\n ? DEFAULT_PRODUCTION_DRIVER\n : DEFAULT_DEVELOPMENT_DRIVER;\n\n const driverAlias = process.env.MAIL_DRIVER\n ? process.env.MAIL_DRIVER.toUpperCase()\n : defaultDriverAlias;\n\n if (!allowedDriverAliases.includes(driverAlias) || !driverMap[driverAlias]) {\n throw new Error(\n `Mail driver ${driverAlias} is not supported. If you're in a production environment, you might need to set the MAIL_ENABLE_PRODUCTION environment variable to access this driver.`\n );\n }\n\n const driver = driverMap[driverAlias];\n\n if (!driver) {\n throw new Error(`Mail driver ${driverAlias} is not supported.`);\n }\n\n return driver(sendObject);\n}\n\nexport default sendMail;\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { A as AuthSession } from '../interfaces-Gqu85VTW.js';
|
|
3
|
+
|
|
4
|
+
interface ProxyRedirect {
|
|
5
|
+
redirect: string;
|
|
6
|
+
}
|
|
7
|
+
type ProxyFunction = (request: NextRequest) => Promise<ProxyRedirect | null>;
|
|
8
|
+
type SessionProxyFunction = (session: AuthSession | null, request: NextRequest) => Promise<ProxyRedirect | null>;
|
|
9
|
+
|
|
10
|
+
declare function handleProxy(request: NextRequest, functions: ProxyFunction[]): Promise<NextResponse>;
|
|
11
|
+
|
|
12
|
+
declare function handleSessionProxy(request: NextRequest, functions: SessionProxyFunction[]): Promise<NextResponse>;
|
|
13
|
+
|
|
14
|
+
export { type ProxyFunction, type ProxyRedirect, type SessionProxyFunction, handleProxy, handleSessionProxy };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import'../chunk-U27WABYY.js';import'../chunk-CESWDV42.js';import {h}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import'../chunk-3JA7XHAG.js';import {NextResponse}from'next/server';async function x(e,o){for(let r of o){let t=await r(e);if(t)return NextResponse.redirect(new URL(t.redirect,e.url))}return NextResponse.next()}var u=x;async function a(e,o){let r=await h(e.cookies);for(let t of o){let n=await t(r,e);if(n)return NextResponse.redirect(new URL(n.redirect,e.url))}return NextResponse.next()}var c=a;export{u as handleProxy,c as handleSessionProxy};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/proxy/handle-proxy.ts","../../src/proxy/handle-session-proxy.ts"],"names":["handleProxy","request","functions","func","result","NextResponse","handle_proxy_default","handleSessionProxy","session","validate_session_default","handle_session_proxy_default"],"mappings":"uRAKA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,EACqB,CACrB,IAAA,IAAWC,CAAAA,IAAQD,CAAAA,CAAW,CAC1B,IAAME,CAAAA,CAAS,MAAMD,CAAAA,CAAKF,CAAO,EAEjC,GAAIG,CAAAA,CACA,OAAOC,YAAAA,CAAa,SAAS,IAAI,GAAA,CAAID,EAAO,QAAA,CAAUH,CAAAA,CAAQ,GAAG,CAAC,CAE1E,CAEA,OAAOI,YAAAA,CAAa,MACxB,KAEOC,CAAAA,CAAQN,ECbf,eAAeO,EACXN,CAAAA,CACAC,CAAAA,CACqB,CACrB,IAAMM,CAAAA,CAAU,MAAMC,CAAAA,CAAgBR,CAAAA,CAAQ,OAAO,CAAA,CAErD,IAAA,IAAWE,KAAQD,CAAAA,CAAW,CAC1B,IAAME,CAAAA,CAAS,MAAMD,EAAKK,CAAAA,CAASP,CAAO,CAAA,CAE1C,GAAIG,EACA,OAAOC,YAAAA,CAAa,SAAS,IAAI,GAAA,CAAID,EAAO,QAAA,CAAUH,CAAAA,CAAQ,GAAG,CAAC,CAE1E,CAEA,OAAOI,YAAAA,CAAa,MACxB,KAEOK,CAAAA,CAAQH","file":"index.js","sourcesContent":["import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\n\nimport type { ProxyFunction } from './utility/interfaces';\n\nasync function handleProxy(\n request: NextRequest,\n functions: ProxyFunction[]\n): Promise<NextResponse> {\n for (const func of functions) {\n const result = await func(request);\n\n if (result) {\n return NextResponse.redirect(new URL(result.redirect, request.url));\n }\n }\n\n return NextResponse.next();\n}\n\nexport default handleProxy;\n","import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\n\nimport { validateSession } from '../auth';\n\nimport type { SessionProxyFunction } from './utility/interfaces';\n\nasync function handleSessionProxy(\n request: NextRequest,\n functions: SessionProxyFunction[]\n): Promise<NextResponse> {\n const session = await validateSession(request.cookies);\n\n for (const func of functions) {\n const result = await func(session, request);\n\n if (result) {\n return NextResponse.redirect(new URL(result.redirect, request.url));\n }\n }\n\n return NextResponse.next();\n}\n\nexport default handleSessionProxy;\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.
|
|
3
|
+
*/
|
|
4
|
+
declare const serverStorage: {
|
|
5
|
+
/**
|
|
6
|
+
* Get an item from the cache.
|
|
7
|
+
* @param prefix The prefix to use for the cache key.
|
|
8
|
+
* @param key The key of the item to retrieve.
|
|
9
|
+
* @returns The cached item, or null if not found.
|
|
10
|
+
*/
|
|
11
|
+
getItem(prefix: string, key: string): Promise<Record<string, unknown> | null>;
|
|
12
|
+
getArray(prefix: string, key: string): Promise<string[]>;
|
|
13
|
+
addToArray(prefix: string, key: string, value: string): Promise<void>;
|
|
14
|
+
removeFromArray(prefix: string, key: string, value: string): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Set an item in the cache.
|
|
17
|
+
* @param prefix The prefix to use for the cache key.
|
|
18
|
+
* @param key The key of the item to set.
|
|
19
|
+
* @param value The value of the item to set.
|
|
20
|
+
*/
|
|
21
|
+
setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Remove an item from the cache.
|
|
24
|
+
* @param prefix The prefix to use for the cache key.
|
|
25
|
+
* @param key The key of the item to remove.
|
|
26
|
+
*/
|
|
27
|
+
removeItem(prefix: string, key: string): Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export { serverStorage as default };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
|
package/dist/utility/index.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-
|
|
1
|
+
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
2
2
|
|
|
3
|
-
declare function ensureID<T extends string>(id: string
|
|
3
|
+
declare function ensureID<T extends string>(id: string | null | undefined, prefix: string): T;
|
|
4
4
|
|
|
5
5
|
declare function generateID<T extends string = string>(prefix?: string | null, length?: number): T;
|
|
6
6
|
|
|
7
|
-
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string>> | null): Promise<T>;
|
|
7
|
+
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string>> | Record<string, string> | null): Promise<T | null>;
|
|
8
8
|
|
|
9
|
-
declare function guardID<T extends string>(id: string
|
|
9
|
+
declare function guardID<T extends string>(id: (string | null | undefined)[], prefix: string): T[];
|
|
10
|
+
declare function guardID<T extends string>(id: string | null | undefined, prefix: string): T | null;
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
declare function log(alias: string, fnName: string, message: string): void;
|
|
13
|
+
|
|
14
|
+
export { ensureID, generateID, getIDFromParams, guardID, log };
|
package/dist/utility/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export{a as generateID}from'../chunk-CESWDV42.js';export{b as ensureID,c as getIDFromParams,a as guardID}from'../chunk-3A4JSFVE.js';export{a as log}from'../chunk-KC7SPWBL.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqrzro/server",
|
|
3
|
-
"version": "4.0.0-alpha.
|
|
3
|
+
"version": "4.0.0-alpha.30",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -21,6 +21,10 @@
|
|
|
21
21
|
"types": "./dist/cli/index.d.ts",
|
|
22
22
|
"default": "./dist/cli/index.js"
|
|
23
23
|
},
|
|
24
|
+
"./csv": {
|
|
25
|
+
"types": "./dist/csv/index.d.ts",
|
|
26
|
+
"default": "./dist/csv/index.js"
|
|
27
|
+
},
|
|
24
28
|
"./database": {
|
|
25
29
|
"types": "./dist/database/index.d.ts",
|
|
26
30
|
"default": "./dist/database/index.js"
|
|
@@ -33,6 +37,18 @@
|
|
|
33
37
|
"types": "./dist/json/index.d.ts",
|
|
34
38
|
"default": "./dist/json/index.js"
|
|
35
39
|
},
|
|
40
|
+
"./mail": {
|
|
41
|
+
"types": "./dist/mail/index.d.ts",
|
|
42
|
+
"default": "./dist/mail/index.js"
|
|
43
|
+
},
|
|
44
|
+
"./proxy": {
|
|
45
|
+
"types": "./dist/proxy/index.d.ts",
|
|
46
|
+
"default": "./dist/proxy/index.js"
|
|
47
|
+
},
|
|
48
|
+
"./storage": {
|
|
49
|
+
"types": "./dist/storage/index.d.ts",
|
|
50
|
+
"default": "./dist/storage/index.js"
|
|
51
|
+
},
|
|
36
52
|
"./utility": {
|
|
37
53
|
"types": "./dist/utility/index.d.ts",
|
|
38
54
|
"default": "./dist/utility/index.js"
|
|
@@ -44,31 +60,34 @@
|
|
|
44
60
|
"dependencies": {
|
|
45
61
|
"@sendgrid/mail": "^8.1.6",
|
|
46
62
|
"bcryptjs": "^3.0.3",
|
|
47
|
-
"commander": "^14.0.
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"drizzle-
|
|
63
|
+
"commander": "^14.0.3",
|
|
64
|
+
"csv": "^6.4.1",
|
|
65
|
+
"dotenv": "^17.3.1",
|
|
66
|
+
"drizzle-kit": "^0.31.9",
|
|
67
|
+
"drizzle-orm": "^0.45.1",
|
|
51
68
|
"joi": "^18.0.2",
|
|
52
|
-
"pg": "^8.
|
|
53
|
-
"
|
|
54
|
-
"
|
|
69
|
+
"pg": "^8.19.0",
|
|
70
|
+
"qrcode": "^1.5.4",
|
|
71
|
+
"react-dom": "^19.2.4",
|
|
72
|
+
"redis": "^5.11.0",
|
|
73
|
+
"time2fa": "^1.4.2",
|
|
55
74
|
"tsx": "^4.21.0",
|
|
56
|
-
"zod": "^4.
|
|
57
|
-
"@sqrzro/utility": "^4.0.0-alpha.
|
|
75
|
+
"zod": "^4.3.6",
|
|
76
|
+
"@sqrzro/utility": "^4.0.0-alpha.10"
|
|
58
77
|
},
|
|
59
78
|
"devDependencies": {
|
|
60
79
|
"@types/jest": "^29.5.14",
|
|
61
|
-
"@types/node": "^24.
|
|
62
|
-
"@types/pg": "^8.
|
|
63
|
-
"@types/react": "^19.2.
|
|
80
|
+
"@types/node": "^24.11.0",
|
|
81
|
+
"@types/pg": "^8.18.0",
|
|
82
|
+
"@types/react": "^19.2.14",
|
|
64
83
|
"@types/react-dom": "^19.2.3",
|
|
65
84
|
"jest": "^29.7.0",
|
|
66
|
-
"prettier": "^3.
|
|
85
|
+
"prettier": "^3.8.1",
|
|
67
86
|
"rimraf": "^4.4.1",
|
|
68
87
|
"ts-jest": "^29.4.6",
|
|
69
88
|
"tsup": "^8.5.1",
|
|
70
89
|
"typescript": "^5.9.3",
|
|
71
|
-
"@sqrzro/prettier-config": "^4.0.0-alpha.
|
|
90
|
+
"@sqrzro/prettier-config": "^4.0.0-alpha.2"
|
|
72
91
|
},
|
|
73
92
|
"peerDependencies": {
|
|
74
93
|
"next": "^16.1.6",
|
package/dist/chunk-37TYQL5Y.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-37TYQL5Y.js"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/forms/utility/ValidationError.ts"],"names":["ValidationError","messages","ValidationError_default"],"mappings":"AAMA,IAAMA,CAAAA,CAAN,cAA8B,KAAM,CACzB,SAEA,WAAA,CAAYC,CAAAA,CAAkC,CACjD,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC,CAAA,CAE9B,KAAK,QAAA,CAAWA,CAAAA,CAChB,KAAK,IAAA,CAAO,kBAChB,CACJ,CAAA,CAEOC,CAAAA,CAAQF","file":"chunk-AGS5PPG2.js","sourcesContent":["/**\n * Custom error class to represent validation errors in form processing.\n * \n * It extends the built-in Error class and includes a messages property\n * that holds a record of validation error messages.\n */\nclass ValidationError extends Error {\n public messages: Record<string, string>;\n\n public constructor(messages: Record<string, string>) {\n super(JSON.stringify(messages));\n\n this.messages = messages;\n this.name = 'ValidationError';\n }\n}\n\nexport default ValidationError;\n"]}
|
package/dist/chunk-QE347FVL.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {e}from'./chunk-JI2U2EMD.js';import I from'bcryptjs';import {cache}from'react';import {createClient}from'redis';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';var i=null;async function S(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return i||(i=createClient({url:process.env.REDIS_URL}),await i.connect(),i)}var o=S;var w={async getItem(e,r){let t=await(await o()).get(`[${e}]:${r}`);if(!t)return null;try{return JSON.parse(t)}catch{return null}},async getArray(e,r){return await(await o()).sMembers(`[${e}]:${r}`)},async addToArray(e,r,t){await(await o()).sAdd(`[${e}]:${r}`,t);},async removeFromArray(e,r,t){await(await o()).sRem(`[${e}]:${r}`,t);},async setItem(e,r,t){await(await o()).set(`[${e}]:${r}`,JSON.stringify(t));},async removeItem(e,r){await(await o()).del(`[${e}]:${r}`);}},l=w;function _(){let e=process.env.AUTH_ROLE;if(!e)throw new Error("AUTH_ROLE environment variable is not set.");let r=parseInt(e,10);if(isNaN(r))throw new Error("AUTH_ROLE environment variable is not a valid number.");return r}var u=_;var c=process.env.AUTH_COOKIE_NAME??"session",K=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,V=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function h(e){let r=(e??await cookies()).get(c)?.value;if(!r)return null;let t=r.split(".");if(t.length!==2)return null;let[s,a]=t;return {id:s,secret:a}}var m=h;function v(e){let{expires:r,secret:t,userID:s}=e;if(typeof r!="string"||typeof t!="string"||typeof s!="string")return null;let a=new Date(r);return isNaN(a.getTime())?null:{expires:a,secret:t,userID:s}}var f=v;async function x(e){let r=await m(e);if(!r)return null;let t=u(),s=await l.getItem("session",r.id);return s?.role!==t||typeof s?.secret!="string"||!await I.compare(r.secret,s.secret)?null:f(s)}var N=cache(x),p=N;var y=drizzle(process.env.DATABASE_URL??"");async function b(e$1,r){let t=u();return (await y.select().from(e).where(and(eq(e[e$1],r),eq(e.role,t),isNull(e.deletedAt))).limit(1))[0]??null}var d=b;async function k(e){return d("id",e)}var U=k;async function $(){let e=await p();if(!e)return null;let r=await U(e.userID);return r?{email:r.email,id:r.id}:null}async function D(){return cache($)()}var R=D;async function L(){let e=await R();if(!e)throw new Error("Could not ensure session user. No session user found.");return e}var Re=L;export{y as a,c as b,K as c,V as d,u as e,d as f,l as g,m as h,p as i,R as j,Re as k};//# sourceMappingURL=chunk-QE347FVL.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-QE347FVL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/utility/get-client.ts","../src/storage/index.ts","../src/auth/utility/ensure-role.ts","../src/auth/utility/config.ts","../src/auth/sessions/utility/get-session-cookie.ts","../src/auth/sessions/utility/parse-session.ts","../src/auth/sessions/validate-session.ts","../src/utility/db.ts","../src/auth/users/utility/get-user-by.ts","../src/auth/users/utility/get-user-by-id.ts","../src/auth/users/get-session-user.ts","../src/auth/users/ensure-session-user.ts"],"names":["client","getClient","createClient","get_client_default","serverStorage","prefix","key","value","storage_default","ensureRole","role","roleNumber","ensure_role_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getSessionCookie","cookies","cookie","cookieFn","parts","id","secret","get_session_cookie_default","parseSession","session","expires","userID","expiresDate","parse_session_default","uncached_validateSession","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","authUserTable","and","eq","isNull","get_user_by_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","ensureSessionUser","user","ensure_session_user_default"],"mappings":"kPAIA,IAAIA,CAAAA,CAAiD,KAQrD,eAAeC,CAAAA,EAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,SAAA,CACb,MAAM,IAAI,KAAA,CAAM,gEAAgE,CAAA,CAGpF,OAAID,CAAAA,GAIJA,CAAAA,CAASE,aAAa,CAClB,GAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,SACrB,CAAC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,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,KAEOC,EAAAA,CAAQF","file":"chunk-QE347FVL.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n","function ensureRole(): number {\n const role = process.env.AUTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\n\nimport ensureRole from '../utility/ensure-role';\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n return null;\n }\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if(session?.role !== role) {\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(key: keyof AuthUserTable, value: string): Promise<AuthUser | null> {\n const role = ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string): Promise<AuthUser | null> {\n return getUserBy('id', id);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n const session = await validateSession();\n\n if (!session) {\n return null;\n }\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n return null;\n }\n\n return {\n email: authUser.email,\n id: authUser.id,\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import getSessionUser from './get-session-user';\nimport type { User } from './utility/interfaces';\n\nasync function ensureSessionUser(): Promise<User> {\n const user = await getSessionUser();\n\n if (!user) {\n throw new Error('Could not ensure session user. No session user found.');\n }\n\n return user;\n}\n\nexport default ensureSessionUser;\n"]}
|
package/dist/chunk-XSJ4OEIH.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';function u(r,n){let t=Array.isArray(r)?r[0]:r;return t?.startsWith(n)?t:null}var s=u;function a(r,n){let t=s(r,n);if(!t)throw new Error(`Could not ensure ID. '${r}' is not a valid ID with prefix '${n}'.`);return t}var m=a;var l=16;function d(r,n=l){let t="abcdefghijklmnopqrstuvwxyz0123456789",i=randomBytes(n),e="";for(let o=0;o<n;o++)e+=t[i[o]%t.length];return `${r?r+"_":""}${e}`}var I=d;async function f(r,n,t){if(!t)throw new Error("");let i=await t,e=s(i[r],n);if(!e)throw new Error("");return e}var p=f;export{s as a,m as b,I as c,p as d};//# sourceMappingURL=chunk-XSJ4OEIH.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-XSJ4OEIH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utility/guard-id.ts","../src/utility/ensure-id.ts","../src/utility/generate-id.ts","../src/utility/get-id-from-params.ts"],"names":["guardID","id","prefix","value","guard_id_default","ensureID","guardedID","ensure_id_default","ID_LENGTH","generateID","length","chars","bytes","randomBytes","result","i","generate_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default"],"mappings":"iCAAA,SAASA,CAAAA,CACLC,CAAAA,CACAC,CAAAA,CACQ,CACR,IAAMC,CAAAA,CAAQ,KAAA,CAAM,OAAA,CAAQF,CAAE,CAAA,CAAI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D,MAAM,IAAI,KAAA,CAAM,EAAE,CAAA,CAGtB,OAAOA,CACX,KAEOoB,CAAAA,CAAQJ","file":"chunk-XSJ4OEIH.js","sourcesContent":["function guardID<T extends string>(\n id: string[] | string | null | undefined,\n prefix: string\n): T | null {\n const value = Array.isArray(id) ? id[0] : id;\n\n if (!value?.startsWith(prefix)) {\n return null;\n }\n\n return value as T;\n}\n\nexport default guardID;\n","import guardID from './guard-id';\n\nfunction ensureID<T extends string>(id: string[] | string | null | undefined, prefix: string): T {\n const guardedID = guardID<T>(id, prefix);\n\n if (!guardedID) {\n throw new Error(`Could not ensure ID. '${id}' is not a valid ID with prefix '${prefix}'.`);\n }\n\n return guardedID;\n}\n\nexport default ensureID;\n","import { randomBytes } from 'crypto';\n\nconst ID_LENGTH = 16;\n\nfunction generateID<T extends string = string>(prefix?: string | null, length = ID_LENGTH): T {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';\n const bytes = randomBytes(length);\n\n let result = '';\n\n for (let i = 0; i < length; i++) {\n result += chars[bytes[i] % chars.length];\n }\n\n return `${prefix ? prefix + '_' : ''}${result}` as T;\n}\n\nexport default generateID;\n","import guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | null\n): Promise<T> {\n if (!params) {\n throw new Error('');\n }\n\n const awaitedParams = await params;\n const id = guardID<T>(awaitedParams[key], prefix);\n\n if (!id) {\n throw new Error('');\n }\n\n return id;\n}\n\nexport default getIDFromParams;\n"]}
|