@kalutskii/foundation 0.5.1 → 0.6.2

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/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ErrorHandler, MiddlewareHandler, Context, TypedResponse } from 'hono';
2
- import z$1, { z, ZodNumber } from 'zod';
2
+ import z from 'zod';
3
3
  import { Locale } from 'date-fns';
4
4
  import { SymmetricAlgorithm } from 'hono/utils/jwt/jwa';
5
5
 
@@ -42,15 +42,6 @@ type FetchResult<T> = {
42
42
  data: null;
43
43
  };
44
44
 
45
- /**
46
- * Type utility that recursively transforms all Date fields to string, as well as handling arrays and objects.
47
- * This is necessary for proper typing when working with RPC, as JSON does not support the Date type directly.
48
- * Example usage: `SerializeDates<{ createdAt: Date; nested: { updatedAt: Date }; tags: Date[] }>` \
49
- * = `{ createdAt: string; nested: { updatedAt: string }; tags: string[] }`
50
- */
51
- type SerializeDates<T> = T extends Date ? string : T extends (infer U)[] ? SerializeDates<U>[] : T extends readonly (infer U)[] ? readonly SerializeDates<U>[] : T extends object ? {
52
- [K in keyof T]: SerializeDates<T[K]>;
53
- } : T;
54
45
  type QueryPrimitive = string | number | boolean | bigint | Date | null | undefined;
55
46
  /**
56
47
  * Type utility that recursively transforms all fields to string, as well as handling arrays and objects.
@@ -60,16 +51,6 @@ type QueryPrimitive = string | number | boolean | bigint | Date | null | undefin
60
51
  type AsQuery<T> = T extends QueryPrimitive ? string : T extends readonly (infer Item)[] ? AsQuery<Item>[] : T extends object ? {
61
52
  [Key in keyof T]: AsQuery<T[Key]>;
62
53
  } : string;
63
- /**
64
- * Transforms a string to a number (when passing query parameters).
65
- * Example usage: `asQueryNumber(z.number())('123') = 123`
66
- */
67
- declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess<T>;
68
- /**
69
- * Transforms various string representations of boolean values into actual booleans.
70
- * See POSITIVE_VALUES and NEGATIVE_VALUES arrays below for supported inputs.
71
- */
72
- declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPreprocess<T>;
73
54
 
74
55
  /**
75
56
  * Wraps c.json with a typed success payload / (or void data) & possible APIError response.
@@ -78,7 +59,7 @@ declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPrepro
78
59
  declare function respond<T extends object = Record<string, never>, S extends SuccessStatusCode = SuccessStatusCode>(c: Context, options: {
79
60
  status: S;
80
61
  data?: T;
81
- }): Response & TypedResponse<APISuccess<SerializeDates<T>> | APIError, S, 'json'>;
62
+ }): Response & TypedResponse<APISuccess<AsQuery<T>> | APIError, S, 'json'>;
82
63
 
83
64
  /**
84
65
  * Factory for creating successful API responses with serializable data.
@@ -122,15 +103,15 @@ declare function fetchAndThrow<TResult extends APIContractResult<unknown>>(fetch
122
103
  * });
123
104
  * ```
124
105
  */
125
- declare const paginationSchema: z$1.ZodObject<{
126
- offset: z$1.ZodOptional<z$1.ZodNumber>;
127
- limit: z$1.ZodOptional<z$1.ZodNumber>;
128
- }, z$1.core.$strip>;
106
+ declare const paginationSchema: z.ZodObject<{
107
+ offset: z.ZodOptional<z.ZodNumber>;
108
+ limit: z.ZodOptional<z.ZodNumber>;
109
+ }, z.core.$strip>;
129
110
  /**
130
111
  * A TypeScript type representing the pagination options validated by the `paginationSchema`.
131
112
  * Read documentation for `paginationSchema` for more details on the structure and usage of this type.
132
113
  */
133
- type PaginationOptions = z$1.infer<typeof paginationSchema>;
114
+ type PaginationOptions = z.infer<typeof paginationSchema>;
134
115
 
135
116
  /**
136
117
  * A utility function that extracts pagination options from the provided input.
@@ -139,11 +120,11 @@ type PaginationOptions = z$1.infer<typeof paginationSchema>;
139
120
  *
140
121
  * ```ts
141
122
  * await db.query.someTable.findMany({
142
- * ...getPagination(options),
123
+ * ...refinePagination(options),
143
124
  * });
144
125
  * ```
145
126
  */
146
- declare const getPagination: (options?: PaginationOptions) => {
127
+ declare const refinePagination: (options?: PaginationOptions) => {
147
128
  offset?: number | undefined;
148
129
  limit?: number | undefined;
149
130
  };
@@ -237,6 +218,7 @@ declare const log: {
237
218
  type Simplify<T> = {
238
219
  [K in keyof T]: T[K];
239
220
  } & {};
221
+
240
222
  /**
241
223
  * A utility type that represents a value that can be of type T or null.
242
224
  * Commonly used for optional fields in data models or function return types.
@@ -267,6 +249,29 @@ type XOR<T, U> = Simplify<T & {
267
249
  */
268
250
  type AtLeastOne<T, Keys extends keyof T = keyof T> = Keys extends keyof T ? Simplify<Required<Pick<T, Keys>> & Partial<Omit<T, Keys>>> : never;
269
251
 
252
+ /**
253
+ * Refines a Zod object schema to ensure that at least one of its keys is defined.
254
+ * This is useful for validating objects where at least one property must be present.
255
+ *
256
+ * ```ts
257
+ * const mySchema = z.object({
258
+ * a: z.string()
259
+ * b: z.number()
260
+ * }).refine(atLeastOneDefined);
261
+ * ```
262
+ */
263
+ declare const atLeastOneDefined: <T extends z.ZodRawShape>(schema: z.ZodObject<T>) => z.ZodType<AtLeastOne<z.infer<z.ZodObject<T>>>>;
264
+ /**
265
+ * Transforms a string to a number (when passing query parameters).
266
+ * Example usage: `asQueryNumber(z.number())('123') = 123`
267
+ */
268
+ declare const asQueryNumber: <T extends z.ZodNumber>(schema: T) => z.ZodPreprocess<T>;
269
+ /**
270
+ * Transforms various string representations of boolean values into actual booleans.
271
+ * See POSITIVE_VALUES and NEGATIVE_VALUES arrays below for supported inputs.
272
+ */
273
+ declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPreprocess<T>;
274
+
270
275
  /** Options for configuring the JWT service. */
271
276
  type JWTServiceOptions = {
272
277
  /** The algorithm to use for signing and verifying JWTs. Defaults to 'HS256'. */
@@ -280,9 +285,9 @@ type JWTSignOptions = {
280
285
  expiresInSeconds?: number;
281
286
  };
282
287
  /** Utility types for inferring payload types from Zod schemas. */
283
- type Payload<T> = T extends z$1.ZodType ? z$1.infer<T> : T;
288
+ type Payload<T> = T extends z.ZodType ? z.infer<T> : T;
284
289
  /** Utility type to extract the payload schema type from a Zod schema. */
285
- type PayloadSchema<T> = T extends z$1.ZodType ? T : never;
290
+ type PayloadSchema<T> = T extends z.ZodType ? T : never;
286
291
 
287
292
  /**
288
293
  * A service class for handling JWT operations with optional Zod schema validation for the payload.
@@ -315,4 +320,4 @@ declare class ZodJWTService<TPayloadOrSchema> {
315
320
  verifyOrThrow(token: string, secret: string): Promise<Payload<TPayloadOrSchema>>;
316
321
  }
317
322
 
318
- export { type APIContractData, type APIContractError, type APIContractResult, type APIError, type APISuccess, type AsQuery, type AtLeastOne, EXCEPTION_STATUS_CODES, type ExceptionStatusCode, type FetchResult, type JWTServiceOptions, type JWTSignOptions, type MeasuredExecution, type PaginationOptions, type Payload, type PayloadSchema, SUCCESS_STATUS_CODES, type SerializeDates, type Simplify, type SuccessStatusCode, type XOR, ZodJWTService, asQueryBoolean, asQueryNumber, failure, fetchAndThrow, fetchSafely, formatTime, generateRandomString, getColoredHTTPStatus, getFormattedDate, getFormattedTime, getPagination, getUTCOffset, getZonedTime, honoLoggingHandler, log, measureExecutionTime, onHandlerError, paginationSchema, respond, safeExecute, success };
323
+ export { type APIContractData, type APIContractError, type APIContractResult, type APIError, type APISuccess, type AsQuery, type AtLeastOne, EXCEPTION_STATUS_CODES, type ExceptionStatusCode, type FetchResult, type JWTServiceOptions, type JWTSignOptions, type MeasuredExecution, type PaginationOptions, type Payload, type PayloadSchema, SUCCESS_STATUS_CODES, type Simplify, type SuccessStatusCode, type XOR, ZodJWTService, asQueryBoolean, asQueryNumber, atLeastOneDefined, failure, fetchAndThrow, fetchSafely, formatTime, generateRandomString, getColoredHTTPStatus, getFormattedDate, getFormattedTime, getUTCOffset, getZonedTime, honoLoggingHandler, log, measureExecutionTime, onHandlerError, paginationSchema, refinePagination, respond, safeExecute, success };
package/dist/index.js CHANGED
@@ -137,8 +137,8 @@ var paginationSchema = z.object({
137
137
  limit: z.number().int().positive().optional()
138
138
  });
139
139
 
140
- // src/pagination/pagination.utilities.ts
141
- var getPagination = (options) => {
140
+ // src/pagination/pagination.refiners.ts
141
+ var refinePagination = (options) => {
142
142
  const pagination = {};
143
143
  if (options?.offset !== void 0) {
144
144
  pagination.offset = options.offset;
@@ -166,8 +166,19 @@ async function measureExecutionTime(execution) {
166
166
  return { result, executionTime: Math.round(executionTime) };
167
167
  }
168
168
 
169
- // src/utilities/serialization.utilities.ts
170
- import { z as z2 } from "zod";
169
+ // src/validation/validation.refiners.ts
170
+ import z2 from "zod";
171
+
172
+ // src/validation/validation.messages.ts
173
+ var AT_LEAST_ONE_DEFINED_ERROR = (keys) => `At least one of the specified keys must be defined: ${keys.join(", ")}`;
174
+
175
+ // src/validation/validation.refiners.ts
176
+ var atLeastOneDefined = (schema) => {
177
+ const keys = Object.keys(schema.shape);
178
+ return schema.partial().refine((value) => keys.some((key) => value[key] != null), {
179
+ message: AT_LEAST_ONE_DEFINED_ERROR(keys)
180
+ });
181
+ };
171
182
  var asQueryNumber = (schema) => z2.preprocess((v) => typeof v === "string" ? Number(v) : v, schema);
172
183
  var asQueryBoolean = (schema) => {
173
184
  const POSITIVE_VALUES = ["1", "true", "yes", "y", "on"];
@@ -240,6 +251,7 @@ export {
240
251
  ZodJWTService,
241
252
  asQueryBoolean,
242
253
  asQueryNumber,
254
+ atLeastOneDefined,
243
255
  failure,
244
256
  fetchAndThrow,
245
257
  fetchSafely,
@@ -248,7 +260,6 @@ export {
248
260
  getColoredHTTPStatus,
249
261
  getFormattedDate,
250
262
  getFormattedTime,
251
- getPagination,
252
263
  getUTCOffset,
253
264
  getZonedTime,
254
265
  honoLoggingHandler,
@@ -256,6 +267,7 @@ export {
256
267
  measureExecutionTime,
257
268
  onHandlerError,
258
269
  paginationSchema,
270
+ refinePagination,
259
271
  respond,
260
272
  safeExecute,
261
273
  success
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kalutskii/foundation",
3
- "version": "0.5.1",
3
+ "version": "0.6.2",
4
4
  "description": "Typescript collection of most common utilities, schemas and functions among private projects.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -40,6 +40,7 @@
40
40
  "esbuild-plugin-tsconfig-paths": "^1.0.2",
41
41
  "eslint": "^10.2.1",
42
42
  "eslint-config-prettier": "^10.1.8",
43
+ "jiti": "^2.7.0",
43
44
  "prettier": "^3.8.1",
44
45
  "tsup": "^8.5.1",
45
46
  "typescript-eslint": "^8.58.2"