@kalutskii/foundation 0.4.3 → 0.4.5

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
@@ -30,20 +30,33 @@ type FetchResult<T> = {
30
30
  data: null;
31
31
  };
32
32
 
33
- /** Factory for creating successful API responses with serializable data. */
33
+ /**
34
+ * Factory for creating successful API responses with serializable data.
35
+ * Example usage: `success({ status: 200, data: { message: 'Operation successful' } })`
36
+ */
34
37
  declare function success<T = unknown>({ status, data }: {
35
38
  status: SuccessStatusCode;
36
39
  data: T;
37
40
  }): APISuccess<T>;
38
- /** Factory for creating API error responses, including the error message. */
41
+ /**
42
+ * Factory for creating API error responses, including the error message.
43
+ * Example usage: `failure({ status: 404, error: 'User not found' })`
44
+ */
39
45
  declare function failure({ status, error }: {
40
46
  status: ExceptionStatusCode;
41
47
  error: string;
42
48
  }): APIError;
43
49
 
44
- /** Resolves an APIContractResult fetcher into a FetchResult discriminated union. */
50
+ /**
51
+ * Resolves an APIContractResult fetcher into a FetchResult discriminated union.
52
+ * Does not throw errors, instead returning them in the error property of the FetchResult.
53
+ * Example usage: const result = await fetchSafely(() => api.fetchUser(userId));
54
+ */
45
55
  declare function fetchSafely<TResult extends APIContractResult<unknown>>(fetcher: () => Promise<TResult>): Promise<FetchResult<APIContractData<TResult>>>;
46
- /** Resolves an APIContractResult fetcher, throwing an error if the result is an APIError. */
56
+ /**
57
+ * Resolves an APIContractResult fetcher, throwing an error if the result is an APIError.
58
+ * Example usage: const data = await fetchAndThrow(() => api.fetchUser(userId));
59
+ */
47
60
  declare function fetchAndThrow<TResult extends APIContractResult<unknown>>(fetcher: () => Promise<TResult>): Promise<APIContractData<TResult>>;
48
61
 
49
62
  /**
@@ -53,7 +66,7 @@ declare function fetchAndThrow<TResult extends APIContractResult<unknown>>(fetch
53
66
  declare const onHandlerError: ErrorHandler;
54
67
 
55
68
  /**
56
- * Request logging middleware for Hono, providing detailed logs for each incoming request.
69
+ * Request logging middleware for Hono, providing deeply detailed logs for each incoming request.
57
70
  * Example log output: [12:12:12 (+4 UTC)] hono | POST 200 123ms /api/v1/users (search=term)
58
71
  */
59
72
  declare const honoLoggingHandler: MiddlewareHandler;
@@ -61,15 +74,24 @@ declare const honoLoggingHandler: MiddlewareHandler;
61
74
  /**
62
75
  * Type utility that recursively transforms all Date fields to string, as well as handling arrays and objects.
63
76
  * This is necessary for proper typing when working with RPC, as JSON does not support the Date type directly.
64
- * Example: SerializeDates<{ createdAt: Date; nested: { updatedAt: Date }; tags: Date[] }> \
65
- * = { createdAt: string; nested: { updatedAt: string }; tags: string[] }
77
+ * Example usage: `SerializeDates<{ createdAt: Date; nested: { updatedAt: Date }; tags: Date[] }>` \
78
+ * = `{ createdAt: string; nested: { updatedAt: string }; tags: string[] }`
66
79
  */
67
80
  type SerializeDates<T> = T extends Date ? string : T extends (infer U)[] ? SerializeDates<U>[] : T extends readonly (infer U)[] ? readonly SerializeDates<U>[] : T extends object ? {
68
81
  [K in keyof T]: SerializeDates<T[K]>;
69
82
  } : T;
83
+ type QueryPrimitive = string | number | boolean | bigint | Date | null | undefined;
84
+ /**
85
+ * Type utility that recursively transforms all fields to string, as well as handling arrays and objects.
86
+ * This is useful for serializing complex data structures into query parameters, which must be strings.
87
+ * Example usage: `AsQuery<{ id: number; name: string; tags: string[] }>` = `{ id: string; name: string; tags: string[] }`
88
+ */
89
+ type AsQuery<T> = T extends QueryPrimitive ? string : T extends readonly (infer Item)[] ? AsQuery<Item>[] : T extends object ? {
90
+ [Key in keyof T]: AsQuery<T[Key]>;
91
+ } : string;
70
92
  /**
71
93
  * Transforms a string to a number (when passing query parameters).
72
- * Example: asQueryNumber(z.number())('123') = 123
94
+ * Example usage: `asQueryNumber(z.number())('123') = 123`
73
95
  */
74
96
  declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess<T>;
75
97
  /**
@@ -79,8 +101,8 @@ declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess
79
101
  declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPreprocess<T>;
80
102
 
81
103
  /**
82
- * Wraps c.json with a typed success payload & possible APIError.
83
- * When no data is provided, responds with an empty object {}.
104
+ * Wraps c.json with a typed success payload / (or void data) & possible APIError response.
105
+ * When no data is provided, responds with an empty object {} (purely for type consistency).
84
106
  */
85
107
  declare function respond<T extends object = Record<string, never>, S extends SuccessStatusCode = SuccessStatusCode>(c: Context, options: {
86
108
  status: S;
@@ -89,19 +111,19 @@ declare function respond<T extends object = Record<string, never>, S extends Suc
89
111
 
90
112
  /**
91
113
  * Returns the current time in the specified timezone.
92
- * Example: getZonedTime({ tz: 'America/New_York' }) = new Date('2026-03-15T12:00:00Z')
114
+ * Example usage: `getZonedTime({ tz: 'America/New_York' }) = new Date('2026-03-15T12:00:00Z')`
93
115
  */
94
116
  declare const getZonedTime: ({ tz }?: {
95
117
  tz?: string;
96
118
  }) => Date;
97
119
  /**
98
120
  * Returns the timezone offset in the format (+4 UTC) / (-5 UTC).
99
- * Example: getUTCOffset(new Date('2026-03-15T12:00:00Z'), 'America/New_York') = '(-4 UTC)'
121
+ * Example usage: `getUTCOffset(new Date('2026-03-15T12:00:00Z'), 'America/New_York') = '(-4 UTC)'`
100
122
  */
101
123
  declare const getUTCOffset: (date: Date, tz: string) => string;
102
124
  /**
103
125
  * Returns the current time in the specified timezone, formatted as HH:mm:ss (+X UTC).
104
- * Example: getFormattedTime({ tz: 'America/New_York' }) = '12:00:00 (-4 UTC)'
126
+ * Example usage: `getFormattedTime({ tz: 'America/New_York' }) = '12:00:00 (-4 UTC)'`
105
127
  */
106
128
  declare const getFormattedTime: ({ tz }?: {
107
129
  tz?: string;
@@ -109,7 +131,7 @@ declare const getFormattedTime: ({ tz }?: {
109
131
  /**
110
132
  * Returns the current date in the specified timezone, formatted as dd.MM.yyyy.
111
133
  * By default, it also includes time (HH:mm:ss) and timezone offset.
112
- * Example: getFormattedDate({ tz: 'America/New_York' }) = '03.15.2026 12:00:00 (-4 UTC)'
134
+ * Example usage: `getFormattedDate({ tz: 'America/New_York' }) = '03.15.2026 12:00:00 (-4 UTC)'`
113
135
  */
114
136
  declare const getFormattedDate: ({ tz, withTime, }?: {
115
137
  tz?: string;
@@ -117,7 +139,7 @@ declare const getFormattedDate: ({ tz, withTime, }?: {
117
139
  }) => string;
118
140
  /**
119
141
  * Formats the given time in the specified timezone, using the provided locale for date formatting.
120
- * Example: formatTime(new Date('2026-03-15T12:00:00Z'), { tz: 'America/New_York' }) = '12:00:00, March 15, 2026 (-4 UTC)'
142
+ * Example usage: `formatTime(new Date('2026-03-15T12:00:00Z'), { tz: 'America/New_York' }) = '12:00:00, March 15, 2026 (-4 UTC)'`
121
143
  */
122
144
  declare const formatTime: (time: Date, { locale, tz }?: {
123
145
  locale?: Locale;
@@ -126,13 +148,31 @@ declare const formatTime: (time: Date, { locale, tz }?: {
126
148
 
127
149
  /**
128
150
  * Safely executes functions and handles errors without using try/catch in the calling code.
129
- * Example: safeExecute(() => fetchData(), (error) => console.error(error));
151
+ * Example usage: `safeExecute(() => fetchData(), (error) => console.error(error))`
130
152
  */
131
153
  declare function safeExecute<T, E = never>(fn: () => Promise<T> | T, onError?: (error?: unknown) => E | Promise<E>): Promise<T | E>;
154
+ type MeasuredExecution<T> = {
155
+ /** The result of the executed function. */
156
+ result: T;
157
+ /** The time taken to execute the function, in milliseconds. */
158
+ executionTime: number;
159
+ };
160
+ /**
161
+ * Utility function to measure the execution time of an asynchronous function.
162
+ * @returns An object containing the result of the execution and the time taken in milliseconds.
163
+ *
164
+ * ```ts
165
+ * const { result, executionTime } = await measureExecutionTime(async () => {
166
+ * return await fetchData();
167
+ * });
168
+ * console.log(`Execution time: ${executionTime}ms`);
169
+ * ```
170
+ */
171
+ declare function measureExecutionTime<T>(execution: () => Promise<T>): Promise<MeasuredExecution<T>>;
132
172
 
133
173
  /**
134
174
  * Creates a random string of the specified length using characters from DEFAULT_CHARACTERS.
135
- * Example: generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ' (default 10 characters)
175
+ * Example usage: `generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ'`
136
176
  */
137
177
  declare function generateRandomString(length?: number): string;
138
178
 
@@ -143,7 +183,7 @@ declare function generateRandomString(length?: number): string;
143
183
  declare function getColoredHTTPStatus(status: number): (text: string) => string;
144
184
  /**
145
185
  * Unified logging interface for different levels (info, warn, error)
146
- * with optional service name and stack trace for errors.
186
+ * with optional service name and stack trace for errors (error level).
147
187
  */
148
188
  declare const log: {
149
189
  info: (message: string, service?: string) => void;
@@ -212,4 +252,4 @@ declare class ZodJWTService<TPayloadOrSchema> {
212
252
  verifyOrThrow(token: string, secret: string): Promise<Payload<TPayloadOrSchema>>;
213
253
  }
214
254
 
215
- export { type APIContractData, type APIContractError, type APIContractResult, type APIError, type APISuccess, EXCEPTION_STATUS_CODES, type ExceptionStatusCode, type FetchResult, type JWTServiceOptions, type JWTSignOptions, type Payload, type PayloadSchema, SUCCESS_STATUS_CODES, type SerializeDates, type SuccessStatusCode, type XOR, ZodJWTService, asQueryBoolean, asQueryNumber, failure, fetchAndThrow, fetchSafely, formatTime, generateRandomString, getColoredHTTPStatus, getFormattedDate, getFormattedTime, getUTCOffset, getZonedTime, honoLoggingHandler, log, onHandlerError, respond, safeExecute, success };
255
+ export { type APIContractData, type APIContractError, type APIContractResult, type APIError, type APISuccess, type AsQuery, EXCEPTION_STATUS_CODES, type ExceptionStatusCode, type FetchResult, type JWTServiceOptions, type JWTSignOptions, type MeasuredExecution, type Payload, type PayloadSchema, SUCCESS_STATUS_CODES, type SerializeDates, type SuccessStatusCode, type XOR, ZodJWTService, asQueryBoolean, asQueryNumber, failure, fetchAndThrow, fetchSafely, formatTime, generateRandomString, getColoredHTTPStatus, getFormattedDate, getFormattedTime, getUTCOffset, getZonedTime, honoLoggingHandler, log, measureExecutionTime, onHandlerError, respond, safeExecute, success };
package/dist/index.js CHANGED
@@ -140,6 +140,12 @@ async function safeExecute(fn, onError) {
140
140
  throw err;
141
141
  }
142
142
  }
143
+ async function measureExecutionTime(execution) {
144
+ const startedAt = performance.now();
145
+ const result = await execution();
146
+ const executionTime = performance.now() - startedAt;
147
+ return { result, executionTime: Math.round(executionTime) };
148
+ }
143
149
 
144
150
  // src/utilities/serialization.utilities.ts
145
151
  import { z } from "zod";
@@ -224,6 +230,7 @@ export {
224
230
  getZonedTime,
225
231
  honoLoggingHandler,
226
232
  log,
233
+ measureExecutionTime,
227
234
  onHandlerError,
228
235
  respond,
229
236
  safeExecute,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kalutskii/foundation",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "description": "Typescript collection of most common utilities, schemas and functions among private projects.",
5
5
  "type": "module",
6
6
  "repository": {