@sqrzro/server 4.0.0-alpha.41 → 4.0.0-alpha.43
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/chunk-2ZLU4AUD.js +2 -0
- package/dist/chunk-2ZLU4AUD.js.map +1 -0
- package/dist/database/index.d.ts +13 -9
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.d.ts +2 -13
- package/dist/forms/index.js +1 -1
- package/dist/forms/index.js.map +1 -1
- package/dist/interfaces-cnzok1wV.d.ts +13 -0
- package/package.json +3 -3
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function s(r){return r}var l=s;var t=class extends Error{messages;constructor(e){super(JSON.stringify(e)),this.messages=e,this.name="ValidationError";}},n=t;async function a(r,e,o){let i=await o(e);if(!i)throw new n({[r]:"NOT_FOUND"});return i}var c=a;export{l as a,n as b,c};//# sourceMappingURL=chunk-2ZLU4AUD.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-2ZLU4AUD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/forms/create-rule.ts","../src/forms/ValidationError.ts","../src/forms/transformers/get-exists-transformer.ts"],"names":["createRule","config","create_rule_default","ValidationError","messages","ValidationError_default","getExistsTransformer","key","value","fn","result","get_exists_transformer_default"],"mappings":"AAEA,SAASA,CAAAA,CAA4CC,CAAAA,CAIzB,CACxB,OAAOA,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECJf,IAAMG,CAAAA,CAAN,cAA8B,KAAM,CACzB,QAAA,CAEA,WAAA,CAAYC,CAAAA,CAAkC,CACjD,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC,CAAA,CAE9B,IAAA,CAAK,QAAA,CAAWA,CAAAA,CAChB,IAAA,CAAK,KAAO,kBAChB,CACJ,CAAA,CAEOC,CAAAA,CAAQF,ECff,eAAeG,CAAAA,CACXC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACuB,CACvB,IAAMC,CAAAA,CAAS,MAAMD,CAAAA,CAAGD,CAAK,EAE7B,GAAI,CAACE,CAAAA,CACD,MAAM,IAAIL,CAAAA,CAAgB,CAAE,CAACE,CAAG,EAAG,WAAY,CAAC,CAAA,CAGpD,OAAOG,CACX,KAEOC,CAAAA,CAAQL","file":"chunk-2ZLU4AUD.js","sourcesContent":["import type { ValidationRule } from './utility/interfaces';\n\nfunction createRule<V, T = undefined, R = undefined>(config: {\n validator: V;\n transformer?: T;\n refiner?: R;\n}): ValidationRule<V, T, R> {\n return config as ValidationRule<V, T, R>;\n}\n\nexport default createRule;\n","/**\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","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"]}
|
package/dist/database/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { SQL } from 'drizzle-orm';
|
|
2
2
|
import { PgColumn } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { V as ValidationRule } from '../interfaces-cnzok1wV.js';
|
|
4
|
+
import z from 'zod';
|
|
3
5
|
import { P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
4
6
|
import * as drizzle_orm_node_postgres from 'drizzle-orm/node-postgres';
|
|
5
7
|
import { Pool } from 'pg';
|
|
@@ -21,6 +23,7 @@ type UnwrapID<TConfig extends RepositoryConfig> = TConfig extends {
|
|
|
21
23
|
};
|
|
22
24
|
} ? UnwrapColumnType<IDColumn> : never;
|
|
23
25
|
type UnwrapModel<TConfig extends RepositoryConfig> = TConfig['makeQuery'] extends (...args: any) => Promise<(infer U)[]> ? U : never;
|
|
26
|
+
type UnwrapParamKey<TConfig extends RepositoryConfig> = TConfig['paramKey'] extends infer U ? U extends string ? U : never : never;
|
|
24
27
|
type UnwrapUpdate<TConfig> = TConfig extends {
|
|
25
28
|
makeUpdateMutation: (values: infer Data) => Promise<infer Model>;
|
|
26
29
|
} ? {
|
|
@@ -38,7 +41,7 @@ interface SelectFunctionConfig<TFilters, TGuards> extends Partial<QueryConfig> {
|
|
|
38
41
|
interface PaginatedFunctionConfig<TFilters, TGuards> extends SelectFunctionConfig<TFilters, TGuards> {
|
|
39
42
|
page?: number | null;
|
|
40
43
|
}
|
|
41
|
-
type RepositoryConfig<TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>, TFilters = never, TGuards = never> = {
|
|
44
|
+
type RepositoryConfig<TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>, TFilters = never, TGuards = never, TParamKey extends string = string> = {
|
|
42
45
|
indexes?: TIndexes;
|
|
43
46
|
makeCountQuery?: (conditions: QueryConditions) => Promise<number>;
|
|
44
47
|
makeDeleteMutation?: (id: any) => Promise<void>;
|
|
@@ -48,7 +51,7 @@ type RepositoryConfig<TIndexes extends Record<string, PgColumn<any>> = Record<st
|
|
|
48
51
|
makeUpdateMutation?: (values: any) => Promise<any>;
|
|
49
52
|
applyFilters?: (filters: TFilters) => Promise<QueryConditions>;
|
|
50
53
|
applyGuards?: (guards: TGuards) => Promise<QueryConditions>;
|
|
51
|
-
paramKey?:
|
|
54
|
+
paramKey?: TParamKey;
|
|
52
55
|
prefix?: string;
|
|
53
56
|
transformDropdown?: (value: any) => any;
|
|
54
57
|
};
|
|
@@ -56,25 +59,26 @@ type RepositoryConfig<TIndexes extends Record<string, PgColumn<any>> = Record<st
|
|
|
56
59
|
declare function createRepository<TConfig extends RepositoryConfig<TIndexes, any, any>, TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>>(config: TConfig): {
|
|
57
60
|
create: (data: UnwrapInsert<TConfig>["data"]) => Promise<UnwrapInsert<TConfig>["model"]>;
|
|
58
61
|
delete: (id: UnwrapID<TConfig>) => Promise<void>;
|
|
59
|
-
ensureByID: (id: UnwrapID<TConfig
|
|
62
|
+
ensureByID: (id: UnwrapID<TConfig>, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig>>;
|
|
60
63
|
ensureByIndex: <K extends keyof TIndexes>(key: K, value: UnwrapColumnType<TIndexes[K]>, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>> | undefined) => Promise<UnwrapModel<TConfig>>;
|
|
61
|
-
ensureFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null) => Promise<UnwrapModel<TConfig>>;
|
|
64
|
+
ensureFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig>>;
|
|
62
65
|
ensureID: (id: string | null | undefined) => UnwrapID<TConfig>;
|
|
63
66
|
ensureIDFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null) => Promise<UnwrapID<TConfig>>;
|
|
64
67
|
getAll: (fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig>[]>;
|
|
65
68
|
getAutocomplete: {
|
|
66
69
|
({ id, }: {
|
|
67
70
|
id?: UnwrapID<TConfig>;
|
|
68
|
-
}): Promise<UnwrapDropdown<TConfig> | null>;
|
|
71
|
+
}, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>): Promise<UnwrapDropdown<TConfig> | null>;
|
|
69
72
|
({ search, }: {
|
|
70
73
|
search?: string;
|
|
71
|
-
}): Promise<UnwrapDropdown<TConfig>[]>;
|
|
74
|
+
}, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>): Promise<UnwrapDropdown<TConfig>[]>;
|
|
72
75
|
};
|
|
73
|
-
getByID: (id: UnwrapID<TConfig
|
|
76
|
+
getByID: (id: UnwrapID<TConfig>, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig> | null>;
|
|
74
77
|
getByIndex: <K extends keyof TIndexes>(key: K, value: UnwrapColumnType<TIndexes[K]>, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig> | null>;
|
|
75
78
|
getDropdown: (fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapDropdown<TConfig>[]>;
|
|
76
|
-
getFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null) => Promise<UnwrapModel<TConfig> | null>;
|
|
79
|
+
getFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null, fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<UnwrapModel<TConfig> | null>;
|
|
77
80
|
getIDFromParams: (params?: Promise<Record<string, string>> | Record<string, string> | null) => Promise<UnwrapID<TConfig> | null>;
|
|
81
|
+
getIDRule: (idKey: string) => ValidationRule<z.ZodTemplateLiteral<UnwrapID<TConfig>>, <T>(data: T) => Promise<T & Record<UnwrapParamKey<TConfig>, UnwrapModel<TConfig>>>, undefined>;
|
|
78
82
|
getPaginated: (fnConfig?: PaginatedFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>) => Promise<Paginated<UnwrapModel<TConfig>>>;
|
|
79
83
|
guardID: {
|
|
80
84
|
(id: (string | null | undefined)[]): UnwrapID<TConfig>[];
|
|
@@ -88,4 +92,4 @@ declare const db: drizzle_orm_node_postgres.NodePgDatabase<Record<string, never>
|
|
|
88
92
|
$client: Pool;
|
|
89
93
|
};
|
|
90
94
|
|
|
91
|
-
export { type PaginatedFunctionConfig, type QueryConditions, type QueryConfig, type RepositoryConfig, type SelectFunctionConfig, type UnwrapColumnType, type UnwrapDropdown, type UnwrapFilters, type UnwrapGuards, type UnwrapID, type UnwrapInsert, type UnwrapModel, type UnwrapUpdate, createRepository, db };
|
|
95
|
+
export { type PaginatedFunctionConfig, type QueryConditions, type QueryConfig, type RepositoryConfig, type SelectFunctionConfig, type UnwrapColumnType, type UnwrapDropdown, type UnwrapFilters, type UnwrapGuards, type UnwrapID, type UnwrapInsert, type UnwrapModel, type UnwrapParamKey, type UnwrapUpdate, ValidationRule, createRepository, db };
|
package/dist/database/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,
|
|
1
|
+
import {a as a$1,c as c$1}from'../chunk-2ZLU4AUD.js';import {a,b,c}from'../chunk-BA3BC4CD.js';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';import {cache}from'react';import R from'zod';import {drizzle}from'drizzle-orm/node-postgres';import {Pool}from'pg';async function z(e,l,u){let p=await c(e,l,u);return b(p,l)}var x=z;function i(e,l){for(let u of l)if(e[u]===void 0||e[u]===null)throw new Error(`Repository config is missing required field: "${String(u)}"`);return e}function N(e){function l(n){let{prefix:r}=i(e,["prefix"]);return Array.isArray(n)?a(n,r):a(n,r)}function u(n){let{prefix:r}=i(e,["prefix"]);return b(n,r)}async function p(n){let{paramKey:r,prefix:t}=i(e,["paramKey","prefix"]);return c(r,t,n)}async function y(n){let{paramKey:r,prefix:t}=i(e,["paramKey","prefix"]);try{return await x(r,t,n)}catch{notFound();}}async function c$2(n){let{makeQuery:r}=i(e,["makeQuery"]),t=[],o=await e.applyFilters?.(n?.filters??null);t.push(...o||[]);let s=await e.applyGuards?.(n?.guards??null);return t.push(...s||[]),r(t,{limit:n?.limit??-1,offset:n?.offset??0})}async function k(n){let{makeCountQuery:r,makeQuery:t}=i(e,["makeCountQuery","makeQuery"]),o=[],s=await e.applyFilters?.(n?.filters??null);o.push(...s||[]);let w=await e.applyGuards?.(n?.guards??null);o.push(...w||[]);let T=await r(o);return {data:await t(o,{limit:n?.limit??10,offset:((n?.page??1)-1)*(n?.limit??10)}),meta:{limit:n?.limit??10,page:n?.page??1,total:T}}}async function g(n,r,t){let{makeQuery:o}=i(e,["makeQuery"]);if(!e.indexes?.[n])throw new Error(`'Could not \`getByIndex\`. Index ${String(n)} is not defined in the repository configuration.`);let s=[],w=await e.applyFilters?.(t?.filters??null);s.push(...w||[]);let T=await e.applyGuards?.(t?.guards??null);s.push(...T||[]),s.push(eq(e.indexes[n],r));let[D]=await o(s,{limit:1,offset:0});return D??null}async function U(...n){let r=await g(...n);return r||notFound()}async function d(n,r){return g("id",n,r)}async function I(n,r){return U("id",n,r)}async function K(n,r){let t=await p(n);return t?d(t,r):null}async function M(n,r){let t=await y(n);return I(t,r)}async function G({id:n,search:r},t){if(i(e,["makeQuery","transformDropdown"]),n){let o=await d(n,t);return o?e.transformDropdown(o):null}if(r){let o=await c$2({...t,filters:{...t?.filters||{},search:r},limit:4});return Promise.all(o.map(e.transformDropdown))}return null}async function S(n){i(e,["makeQuery","transformDropdown"]);let r=await c$2(n);return Promise.all(r.map(e.transformDropdown))}async function _(n){let{makeInsertMutation:r}=i(e,["makeInsertMutation"]);return r(n)}async function Q(n){let{makeUpdateMutation:r}=i(e,["makeUpdateMutation"]);return r(n)}async function A(n){let{makeDeleteMutation:r}=i(e,["makeDeleteMutation"]);return r(n)}async function B(n){let{makeUndeleteMutation:r}=i(e,["makeUndeleteMutation"]);return r(n)}function b$1(n){return async r=>{let{paramKey:t}=i(e,["paramKey"]),o=await c$1(n,r[n],cache(d));return {...r,[t]:o}}}function v(n){let{prefix:r}=i(e,["paramKey","prefix"]),t=R.templateLiteral([r,"_",R.string()]);return a$1({validator:t,transformer:b$1(n)})}return {create:_,delete:A,ensureByID:cache(I),ensureByIndex:cache(U),ensureFromParams:cache(M),ensureID:u,ensureIDFromParams:y,getAll:cache(c$2),getAutocomplete:cache(G),getByID:cache(d),getByIndex:cache(g),getDropdown:cache(S),getFromParams:cache(K),getIDFromParams:p,getIDRule:v,getPaginated:cache(k),guardID:l,undelete:B,update:Q}}var L=N;var V=new Pool({connectionString:process.env.DATABASE_URL}),Z=drizzle(V),j=Z;export{L as createRepository,j as db};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts","../../src/database/db.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","ensureConfig","config","keys","createRepository","guardID","guard_id_default","ensureID","getIDFromParams","paramKey","notFound","uncached_getAll","fnConfig","makeQuery","conditions","filters","guards","uncached_getPaginated","makeCountQuery","total","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","args","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","uncached_getAutocomplete","search","results","uncached_getDropdown","create","data","makeInsertMutation","update","makeUpdateMutation","$delete","makeDeleteMutation","undelete","makeUndeleteMutation","cache","create_repository_default","pool","Pool","db","drizzle","db_default"],"mappings":"oNAGA,eAAeA,EACXC,CAAAA,CACAC,CAAAA,CACAC,EACU,CACV,IAAMC,EAAK,MAAMC,CAAAA,CAAmBJ,EAAKC,CAAAA,CAAQC,CAAM,EACvD,OAAOG,GAAAA,CAAYF,EAAIF,CAAM,CACjC,CAEA,IAAOK,CAAAA,CAAQP,ECcf,SAASQ,CAAAA,CACLC,EACAC,CAAAA,CAC2C,CAC3C,QAAWT,CAAAA,IAAOS,CAAAA,CACd,GAAID,CAAAA,CAAOR,CAAG,CAAA,GAAM,MAAA,EAAaQ,EAAOR,CAAG,CAAA,GAAM,KAC7C,MAAM,IAAI,MAAM,CAAA,8CAAA,EAA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AA,CAAAJ,CACJ,CACJ,CAEA,IAAOO,EAAQxC,ECtRf,IAAMyC,CAAAA,CAAO,IAAIC,IAAAA,CAAK,CAClB,iBAAkB,OAAA,CAAQ,GAAA,CAAI,YAClC,CAAC,CAAA,CAEKC,EAAKC,OAAAA,CAAQH,CAAI,EAEhBI,CAAAA,CAAQF","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 { eq } from 'drizzle-orm';\nimport { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\nimport { cache } from 'react';\n\nimport ensureIDFn from '../utility/ensure-id';\nimport ensureIDFromParamsFn from '../utility/ensure-id-from-params';\nimport getIDFromParamsFn from '../utility/get-id-from-params';\nimport guardIDFn from '../utility/guard-id';\nimport { Paginated } from '../utility/interfaces';\n\nimport {\n QueryConditions,\n PaginatedFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n UnwrapColumnType,\n UnwrapDropdown,\n UnwrapFilters,\n UnwrapGuards,\n UnwrapID,\n UnwrapInsert,\n UnwrapModel,\n UnwrapUpdate,\n} from './interfaces';\n\nfunction ensureConfig<TConfig extends RepositoryConfig, TKeys extends keyof TConfig>(\n config: TConfig,\n keys: TKeys[]\n): { [K in TKeys]-?: NonNullable<TConfig[K]> } {\n for (const key of keys) {\n if (config[key] === undefined || config[key] === null) {\n throw new Error(`Repository config is missing required field: \"${String(key)}\"`);\n }\n }\n return config as unknown as { [K in TKeys]-?: NonNullable<TConfig[K]> };\n}\n\nfunction createRepository<\n TConfig extends RepositoryConfig<TIndexes, any, any>,\n TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>,\n>(config: TConfig) {\n function guardID(id: (string | null | undefined)[]): UnwrapID<TConfig>[];\n function guardID(id: string | null | undefined): UnwrapID<TConfig> | null;\n\n function guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): UnwrapID<TConfig> | UnwrapID<TConfig>[] | null {\n const { prefix } = ensureConfig(config, ['prefix']);\n\n if (Array.isArray(id)) {\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n function ensureID(id: string | null | undefined): UnwrapID<TConfig> {\n const { prefix } = ensureConfig(config, ['prefix']);\n return ensureIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n async function getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig> | null> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n return getIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n }\n\n async function ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig>> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n\n try {\n const id = await ensureIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n return id;\n } catch (err) {\n notFound();\n }\n }\n\n async function uncached_getAll(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>[]> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n return makeQuery(conditions, {\n limit: fnConfig?.limit ?? -1,\n offset: fnConfig?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n fnConfig?: PaginatedFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<Paginated<UnwrapModel<TConfig>>> {\n const { makeCountQuery, makeQuery } = ensureConfig(config, ['makeCountQuery', 'makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n const total = await makeCountQuery(conditions);\n\n const data = await makeQuery(conditions, {\n limit: fnConfig?.limit ?? 10,\n offset: ((fnConfig?.page ?? 1) - 1) * (fnConfig?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: fnConfig?.limit ?? 10, page: fnConfig?.page ?? 1, total },\n };\n }\n\n async function uncached_getByIndex<K extends keyof TIndexes>(\n key: K,\n value: UnwrapColumnType<TIndexes[K]>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n if (!config.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 config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n conditions.push(eq(config.indexes[key], value));\n\n const [result] = await makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof TIndexes>(\n ...args: Parameters<typeof uncached_getByIndex<K>>\n ): Promise<UnwrapModel<TConfig>> {\n const result = await uncached_getByIndex(...args);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig>> {\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<UnwrapModel<TConfig> | null> {\n const id = await 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<UnwrapModel<TConfig>> {\n const id = await ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function uncached_getAutocomplete({\n id,\n }: {\n id?: UnwrapID<TConfig>;\n }): Promise<UnwrapDropdown<TConfig> | null>;\n\n async function uncached_getAutocomplete({\n search,\n }: {\n search?: string;\n }): Promise<UnwrapDropdown<TConfig>[]>;\n\n async function uncached_getAutocomplete({\n id,\n search,\n }: {\n id?: UnwrapID<TConfig>;\n search?: string;\n }): Promise<UnwrapDropdown<TConfig> | UnwrapDropdown<TConfig>[] | null> {\n ensureConfig(config, ['makeQuery', 'transformDropdown']);\n\n if (id) {\n const result = await uncached_getByID(id);\n return result ? config.transformDropdown!(result) : null;\n }\n\n if (search) {\n const results = await uncached_getAll({\n filters: { search } as UnwrapFilters<TConfig>,\n limit: 4,\n });\n return Promise.all(results.map(config.transformDropdown!));\n }\n\n return null;\n }\n\n async function uncached_getDropdown(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapDropdown<TConfig>[]> {\n ensureConfig(config, ['makeQuery', 'transformDropdown']);\n\n const results = await uncached_getAll(fnConfig);\n return Promise.all(results.map(config.transformDropdown!));\n }\n\n async function create(\n data: UnwrapInsert<TConfig>['data']\n ): Promise<UnwrapInsert<TConfig>['model']> {\n const { makeInsertMutation } = ensureConfig(config, ['makeInsertMutation']);\n return makeInsertMutation(data);\n }\n\n async function update(\n data: UnwrapUpdate<TConfig>['data']\n ): Promise<UnwrapUpdate<TConfig>['model']> {\n const { makeUpdateMutation } = ensureConfig(config, ['makeUpdateMutation']);\n return makeUpdateMutation(data);\n }\n\n async function $delete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeDeleteMutation } = ensureConfig(config, ['makeDeleteMutation']);\n return makeDeleteMutation(id);\n }\n\n async function undelete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeUndeleteMutation } = ensureConfig(config, ['makeUndeleteMutation']);\n return makeUndeleteMutation(id);\n }\n\n return {\n create,\n delete: $delete,\n ensureByID: cache(uncached_ensureByID),\n ensureByIndex: cache(uncached_ensureByIndex),\n ensureFromParams: cache(uncached_ensureFromParams),\n ensureID,\n ensureIDFromParams,\n getAll: cache(uncached_getAll),\n getAutocomplete: cache(uncached_getAutocomplete),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getDropdown: cache(uncached_getDropdown),\n getFromParams: cache(uncached_getFromParams),\n getIDFromParams,\n getPaginated: cache(uncached_getPaginated),\n guardID,\n undelete,\n update,\n };\n}\n\nexport default createRepository;\n","import { drizzle } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\n\nconst pool = new Pool({\n connectionString: process.env.DATABASE_URL,\n});\n\nconst db = drizzle(pool);\n\nexport default db;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts","../../src/database/db.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","ensureConfig","config","keys","createRepository","guardID","guard_id_default","ensureID","getIDFromParams","paramKey","notFound","uncached_getAll","fnConfig","makeQuery","conditions","filters","guards","uncached_getPaginated","makeCountQuery","total","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","args","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","uncached_getAutocomplete","search","results","uncached_getDropdown","create","data","makeInsertMutation","update","makeUpdateMutation","$delete","makeDeleteMutation","undelete","makeUndeleteMutation","makeTransformer","idKey","model","get_exists_transformer_default","cache","getIDRule","validator","z","create_rule_default","create_repository_default","pool","Pool","db","drizzle","db_default"],"mappings":"qRAGA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AA,CACA,kBAAA,CAAAd,CAAAA,CACA,OAAQsD,KAAAA,CAAMpC,GAAe,CAAA,CAC7B,eAAA,CAAiBoC,KAAAA,CAAMjB,CAAwB,EAC/C,OAAA,CAASiB,KAAAA,CAAMrB,CAAgB,CAAA,CAC/B,UAAA,CAAYqB,KAAAA,CAAM3B,CAAmB,CAAA,CACrC,WAAA,CAAa2B,MAAMd,CAAoB,CAAA,CACvC,cAAec,KAAAA,CAAMnB,CAAsB,CAAA,CAC3C,eAAA,CAAApB,CAAAA,CACA,SAAA,CAAAwC,EACA,YAAA,CAAcD,KAAAA,CAAM9B,CAAqB,CAAA,CACzC,OAAA,CAAAZ,CAAAA,CACA,SAAAoC,CAAAA,CACA,MAAA,CAAAJ,CACJ,CACJ,CAEA,IAAOe,EAAQhD,ECpUf,IAAMiD,CAAAA,CAAO,IAAIC,KAAK,CAClB,gBAAA,CAAkB,OAAA,CAAQ,GAAA,CAAI,YAClC,CAAC,EAEKC,CAAAA,CAAKC,OAAAA,CAAQH,CAAI,CAAA,CAEhBI,CAAAA,CAAQF","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 { eq } from 'drizzle-orm';\nimport { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\nimport { cache } from 'react';\nimport z from 'zod';\n\nimport createRule from '../forms/create-rule';\nimport getExistsTransformer from '../forms/transformers/get-exists-transformer';\n\nimport ensureIDFn from '../utility/ensure-id';\nimport ensureIDFromParamsFn from '../utility/ensure-id-from-params';\nimport getIDFromParamsFn from '../utility/get-id-from-params';\nimport guardIDFn from '../utility/guard-id';\nimport { Paginated } from '../utility/interfaces';\n\nimport {\n QueryConditions,\n PaginatedFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n UnwrapColumnType,\n UnwrapDropdown,\n UnwrapFilters,\n UnwrapGuards,\n UnwrapID,\n UnwrapInsert,\n UnwrapModel,\n UnwrapParamKey,\n UnwrapUpdate,\n} from './interfaces';\n\nfunction ensureConfig<TConfig extends RepositoryConfig, TKeys extends keyof TConfig>(\n config: TConfig,\n keys: TKeys[]\n): { [K in TKeys]-?: NonNullable<TConfig[K]> } {\n for (const key of keys) {\n if (config[key] === undefined || config[key] === null) {\n throw new Error(`Repository config is missing required field: \"${String(key)}\"`);\n }\n }\n return config as unknown as { [K in TKeys]-?: NonNullable<TConfig[K]> };\n}\n\nfunction createRepository<\n TConfig extends RepositoryConfig<TIndexes, any, any>,\n TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>,\n>(config: TConfig) {\n function guardID(id: (string | null | undefined)[]): UnwrapID<TConfig>[];\n function guardID(id: string | null | undefined): UnwrapID<TConfig> | null;\n\n function guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): UnwrapID<TConfig> | UnwrapID<TConfig>[] | null {\n const { prefix } = ensureConfig(config, ['prefix']);\n\n if (Array.isArray(id)) {\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n function ensureID(id: string | null | undefined): UnwrapID<TConfig> {\n const { prefix } = ensureConfig(config, ['prefix']);\n return ensureIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n async function getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig> | null> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n return getIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n }\n\n async function ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig>> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n\n try {\n const id = await ensureIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n return id;\n } catch (err) {\n notFound();\n }\n }\n\n async function uncached_getAll(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>[]> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n return makeQuery(conditions, {\n limit: fnConfig?.limit ?? -1,\n offset: fnConfig?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n fnConfig?: PaginatedFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<Paginated<UnwrapModel<TConfig>>> {\n const { makeCountQuery, makeQuery } = ensureConfig(config, ['makeCountQuery', 'makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n const total = await makeCountQuery(conditions);\n\n const data = await makeQuery(conditions, {\n limit: fnConfig?.limit ?? 10,\n offset: ((fnConfig?.page ?? 1) - 1) * (fnConfig?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: fnConfig?.limit ?? 10, page: fnConfig?.page ?? 1, total },\n };\n }\n\n async function uncached_getByIndex<K extends keyof TIndexes>(\n key: K,\n value: UnwrapColumnType<TIndexes[K]>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n if (!config.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 config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n conditions.push(eq(config.indexes[key], value));\n\n const [result] = await makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof TIndexes>(\n ...args: Parameters<typeof uncached_getByIndex<K>>\n ): Promise<UnwrapModel<TConfig>> {\n const result = await uncached_getByIndex(...args);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(\n id: UnwrapID<TConfig>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n return uncached_getByIndex('id', id, fnConfig);\n }\n\n async function uncached_ensureByID(\n id: UnwrapID<TConfig>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>> {\n return uncached_ensureByIndex('id', id, fnConfig);\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n const id = await getIDFromParams(params);\n return id ? uncached_getByID(id, fnConfig) : null;\n }\n\n async function uncached_ensureFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>> {\n const id = await ensureIDFromParams(params);\n return uncached_ensureByID(id, fnConfig);\n }\n\n async function uncached_getAutocomplete(\n {\n id,\n }: {\n id?: UnwrapID<TConfig>;\n },\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapDropdown<TConfig> | null>;\n\n async function uncached_getAutocomplete(\n {\n search,\n }: {\n search?: string;\n },\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapDropdown<TConfig>[]>;\n\n async function uncached_getAutocomplete(\n {\n id,\n search,\n }: {\n id?: UnwrapID<TConfig>;\n search?: string;\n },\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapDropdown<TConfig> | UnwrapDropdown<TConfig>[] | null> {\n ensureConfig(config, ['makeQuery', 'transformDropdown']);\n\n if (id) {\n const result = await uncached_getByID(id, fnConfig);\n return result ? config.transformDropdown!(result) : null;\n }\n\n if (search) {\n const results = await uncached_getAll({\n ...fnConfig,\n filters: { ...(fnConfig?.filters || {}), search } as UnwrapFilters<TConfig>,\n limit: 4,\n });\n return Promise.all(results.map(config.transformDropdown!));\n }\n\n return null;\n }\n\n async function uncached_getDropdown(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapDropdown<TConfig>[]> {\n ensureConfig(config, ['makeQuery', 'transformDropdown']);\n\n const results = await uncached_getAll(fnConfig);\n return Promise.all(results.map(config.transformDropdown!));\n }\n\n async function create(\n data: UnwrapInsert<TConfig>['data']\n ): Promise<UnwrapInsert<TConfig>['model']> {\n const { makeInsertMutation } = ensureConfig(config, ['makeInsertMutation']);\n return makeInsertMutation(data);\n }\n\n async function update(\n data: UnwrapUpdate<TConfig>['data']\n ): Promise<UnwrapUpdate<TConfig>['model']> {\n const { makeUpdateMutation } = ensureConfig(config, ['makeUpdateMutation']);\n return makeUpdateMutation(data);\n }\n\n async function $delete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeDeleteMutation } = ensureConfig(config, ['makeDeleteMutation']);\n return makeDeleteMutation(id);\n }\n\n async function undelete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeUndeleteMutation } = ensureConfig(config, ['makeUndeleteMutation']);\n return makeUndeleteMutation(id);\n }\n\n function makeTransformer(idKey: string) {\n return async <T>(\n data: T\n ): Promise<T & Record<UnwrapParamKey<TConfig>, UnwrapModel<TConfig>>> => {\n const { paramKey } = ensureConfig(config, ['paramKey']);\n\n const model = await getExistsTransformer(idKey, data[idKey], cache(uncached_getByID));\n\n return { ...data, [paramKey]: model };\n };\n }\n\n function getIDRule(idKey: string) {\n const { prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n\n const validator = z.templateLiteral([prefix, '_', z.string()]) as z.ZodTemplateLiteral<\n UnwrapID<TConfig>\n >;\n\n return createRule({ validator, transformer: makeTransformer(idKey) });\n }\n\n return {\n create,\n delete: $delete,\n ensureByID: cache(uncached_ensureByID),\n ensureByIndex: cache(uncached_ensureByIndex),\n ensureFromParams: cache(uncached_ensureFromParams),\n ensureID,\n ensureIDFromParams,\n getAll: cache(uncached_getAll),\n getAutocomplete: cache(uncached_getAutocomplete),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getDropdown: cache(uncached_getDropdown),\n getFromParams: cache(uncached_getFromParams),\n getIDFromParams,\n getIDRule,\n getPaginated: cache(uncached_getPaginated),\n guardID,\n undelete,\n update,\n };\n}\n\nexport default createRepository;\n","import { drizzle } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\n\nconst pool = new Pool({\n connectionString: process.env.DATABASE_URL,\n});\n\nconst db = drizzle(pool);\n\nexport default db;\n"]}
|
package/dist/forms/index.d.ts
CHANGED
|
@@ -1,17 +1,6 @@
|
|
|
1
|
+
import { V as ValidationRule, F as FormResponse } from '../interfaces-cnzok1wV.js';
|
|
1
2
|
import z$1, { z } from 'zod';
|
|
2
3
|
|
|
3
|
-
interface AwaitedFormResponse<M> {
|
|
4
|
-
data: M | null;
|
|
5
|
-
error: string | null;
|
|
6
|
-
validation: Record<string, string> | null;
|
|
7
|
-
}
|
|
8
|
-
type FormResponse<M> = Promise<AwaitedFormResponse<M>>;
|
|
9
|
-
type ValidationRule<V, T = undefined, R = undefined> = {
|
|
10
|
-
refiner: R;
|
|
11
|
-
transformer: T;
|
|
12
|
-
validator: V;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
4
|
declare function createRule<V, T = undefined, R = undefined>(config: {
|
|
16
5
|
validator: V;
|
|
17
6
|
transformer?: T;
|
|
@@ -66,4 +55,4 @@ declare function getNotExistsValidator<ID>(fn: (value: ID) => Promise<any>): [(v
|
|
|
66
55
|
message: string;
|
|
67
56
|
}];
|
|
68
57
|
|
|
69
|
-
export {
|
|
58
|
+
export { FormResponse, ValidationError, ValidationRule, createRule, getCSVRule, getExistsTransformer, getExistsValidator, getNotExistsRefiner, 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 {b as b$1,a as a$1}from'../chunk-2ZLU4AUD.js';export{b as ValidationError,a as createRule,c as getExistsTransformer}from'../chunk-2ZLU4AUD.js';import {redirect}from'next/navigation';import D,{z as z$1}from'zod';function g(e){let[,,t]=e.split(";");redirect(`${t.startsWith("/")?"":"/"}${t}`);}var m=g;function u(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]=u(e[r]):t[r]=e[r];return t}var f=u;function R(e){return e.issues.reduce((t,r)=>({...t,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var l=R;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 y(e){return x(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var d=y;async function I(e,t){try{return await t.parseAsync(f(e),{error:o=>d(o)})}catch(r){throw r instanceof z$1.ZodError?new b$1(l(r)):r}}var n=I;async function h(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 b$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=h;function S(e,t){return [async function(r){let o=await t(r[e]);return o?o.id===r.id:true},{message:"ALREADY_EXISTS",path:[e]}]}var w=S;var T=D.string().transform(a);function b(){return a$1({validator:T})}var V=b;function Z(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var A=Z;function z(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var F=z;export{V as getCSVRule,A as getExistsValidator,w as getNotExistsRefiner,F 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/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/ValidationError.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/refiner/get-not-exists-refiner.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","ValidationError","messages","ValidationError_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","validate_schema_default","submitForm","args","response","model","submit_form_default","getNotExistsRefiner","field","fn","result","get_not_exists_refiner_default","validator","parse_csv_default","getCSVRule","get_csv_rule_default","getExistsTransformer","value","get_exists_transformer_default","getExistsValidator","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],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AAA,CAAE,MAAA,EAAO,CAAE,SAAA,CAAUa,GAAQ,EAE/C,SAASC,CAAAA,EAAa,CAClB,OAAOvC,CAAAA,CAAW,CAAE,SAAA,CAAAqC,CAAU,CAAC,CACnC,CAEA,IAAOG,CAAAA,CAAQD,ECVf,eAAeE,CAAAA,CACX7B,CAAAA,CACA8B,CAAAA,CACAR,CAAAA,CACuB,CACvB,IAAMC,CAAAA,CAAS,MAAMD,CAAAA,CAAGQ,CAAK,CAAA,CAE7B,GAAI,CAACP,CAAAA,CACD,MAAM,IAAI3B,CAAAA,CAAgB,CAAE,CAACI,CAAG,EAAG,WAAY,CAAC,CAAA,CAGpD,OAAOuB,CACX,CAEA,IAAOQ,CAAAA,CAAQF,EChBf,SAASG,CAAAA,CACLV,CAAAA,CACsD,CACtD,OAAO,CACH,MAAOQ,CAAAA,EAEI,CAAA,CADQ,MAAMR,CAAAA,CAAGQ,CAAK,CAAA,CAGjC,CAAE,QAAS,WAAY,CAC3B,CACJ,CAEA,IAAOG,CAAAA,CAAQD,ECZf,SAASE,CAAAA,CACLZ,CAAAA,CACsD,CACtD,OAAO,CACH,MAAOQ,GAEI,CADQ,MAAMR,CAAAA,CAAGQ,CAAK,CAAA,CAGjC,CAAE,OAAA,CAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOK,CAAAA,CAAQD","file":"index.js","sourcesContent":["import type { ValidationRule } from './utility/interfaces';\n\nfunction createRule<V, T = undefined, R = undefined>(config: {\n validator: V;\n transformer?: T;\n refiner?: R;\n}): ValidationRule<V, T, R> {\n return config as ValidationRule<V, T, R>;\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","/**\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","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","function getNotExistsRefiner(\n field: string,\n fn: (value: any) => Promise<any>\n): [\n (data: any) => Promise<boolean>,\n {\n message: string;\n path: string[];\n },\n] {\n return [\n async function (data: any) {\n const result = await fn(data[field]);\n\n if (!result) {\n return true;\n }\n\n return result.id === data.id;\n },\n { message: 'ALREADY_EXISTS', path: [field] },\n ];\n}\n\nexport default getNotExistsRefiner;\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<ID>(\n fn: (value: ID) => Promise<any>\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
|
+
{"version":3,"sources":["../../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/refiner/get-not-exists-refiner.ts","../../src/forms/rules/get-csv-rule.ts","../../src/forms/validators/get-exists-validator.ts","../../src/forms/validators/get-not-exists-validator.ts"],"names":["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","getNotExistsRefiner","field","fn","result","get_not_exists_refiner_default","validator","parse_csv_default","getCSVRule","create_rule_default","get_csv_rule_default","getExistsValidator","value","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],"mappings":"+PAEA,SAASA,EAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,EAAO,KAAA,CAAM,GAAG,EACnCE,QAAAA,CAAS,CAAA,EAAGD,CAAAA,CAAK,UAAA,CAAW,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AC,CAAA,CAEjCA,CAAAA,CAGV,OAAO,CAAE,GAAGe,EAAU,KAAA,CAAO,yCAA0C,CAC3E,CACJ,KAEOE,CAAAA,CAAQJ,EClDf,SAASK,CAAAA,CACLC,CAAAA,CACAC,CAAAA,CAOF,CACE,OAAO,CACH,eAAgBzB,CAAAA,CAAW,CACvB,IAAM0B,CAAAA,CAAS,MAAMD,CAAAA,CAAGzB,CAAAA,CAAKwB,CAAK,CAAC,EAEnC,OAAKE,CAAAA,CAIEA,EAAO,EAAA,GAAO1B,CAAAA,CAAK,GAHf,IAIf,CAAA,CACA,CAAE,OAAA,CAAS,gBAAA,CAAkB,IAAA,CAAM,CAACwB,CAAK,CAAE,CAC/C,CACJ,KAEOG,CAAAA,CAAQJ,EClBf,IAAMK,EAAYb,CAAAA,CAAE,MAAA,GAAS,SAAA,CAAUc,CAAQ,EAE/C,SAASC,CAAAA,EAAa,CAClB,OAAOC,GAAAA,CAAW,CAAE,UAAAH,CAAU,CAAC,CACnC,CAEA,IAAOI,EAAQF,ECZf,SAASG,CAAAA,CACLR,CAAAA,CACsD,CACtD,OAAO,CACH,MAAOS,CAAAA,EAEI,EADQ,MAAMT,CAAAA,CAAGS,CAAK,CAAA,CAGjC,CAAE,OAAA,CAAS,WAAY,CAC3B,CACJ,CAEA,IAAOC,CAAAA,CAAQF,ECZf,SAASG,CAAAA,CACLX,EACsD,CACtD,OAAO,CACH,MAAOS,CAAAA,EAEI,CADQ,MAAMT,CAAAA,CAAGS,CAAK,EAGjC,CAAE,OAAA,CAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOG,CAAAA,CAAQD","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","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","function getNotExistsRefiner(\n field: string,\n fn: (value: any) => Promise<any>\n): [\n (data: any) => Promise<boolean>,\n {\n message: string;\n path: string[];\n },\n] {\n return [\n async function (data: any) {\n const result = await fn(data[field]);\n\n if (!result) {\n return true;\n }\n\n return result.id === data.id;\n },\n { message: 'ALREADY_EXISTS', path: [field] },\n ];\n}\n\nexport default getNotExistsRefiner;\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","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<ID>(\n fn: (value: ID) => Promise<any>\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"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
interface AwaitedFormResponse<M> {
|
|
2
|
+
data: M | null;
|
|
3
|
+
error: string | null;
|
|
4
|
+
validation: Record<string, string> | null;
|
|
5
|
+
}
|
|
6
|
+
type FormResponse<M> = Promise<AwaitedFormResponse<M>>;
|
|
7
|
+
type ValidationRule<V, T = undefined, R = undefined> = {
|
|
8
|
+
refiner: R;
|
|
9
|
+
transformer: T;
|
|
10
|
+
validator: V;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type { FormResponse as F, ValidationRule as V };
|
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.43",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -44,9 +44,9 @@
|
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@sendgrid/mail": "^8.1.6",
|
|
47
|
-
"csv": "^6.
|
|
47
|
+
"csv": "^6.5.0",
|
|
48
48
|
"drizzle-orm": "^0.45.1",
|
|
49
|
-
"pg": "^8.
|
|
49
|
+
"pg": "^8.20.0",
|
|
50
50
|
"react-dom": "^19.2.4",
|
|
51
51
|
"redis": "^5.11.0",
|
|
52
52
|
"zod": "^4.3.6",
|