@kalutskii/foundation 0.4.3 → 0.4.4
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 +50 -19
- package/dist/index.js +7 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -30,20 +30,33 @@ type FetchResult<T> = {
|
|
|
30
30
|
data: null;
|
|
31
31
|
};
|
|
32
32
|
|
|
33
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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,15 @@ 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;
|
|
70
83
|
/**
|
|
71
84
|
* Transforms a string to a number (when passing query parameters).
|
|
72
|
-
* Example: asQueryNumber(z.number())('123') = 123
|
|
85
|
+
* Example usage: `asQueryNumber(z.number())('123') = 123`
|
|
73
86
|
*/
|
|
74
87
|
declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess<T>;
|
|
75
88
|
/**
|
|
@@ -79,8 +92,8 @@ declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess
|
|
|
79
92
|
declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPreprocess<T>;
|
|
80
93
|
|
|
81
94
|
/**
|
|
82
|
-
* Wraps c.json with a typed success payload & possible APIError.
|
|
83
|
-
* When no data is provided, responds with an empty object {}.
|
|
95
|
+
* Wraps c.json with a typed success payload / (or void data) & possible APIError response.
|
|
96
|
+
* When no data is provided, responds with an empty object {} (purely for type consistency).
|
|
84
97
|
*/
|
|
85
98
|
declare function respond<T extends object = Record<string, never>, S extends SuccessStatusCode = SuccessStatusCode>(c: Context, options: {
|
|
86
99
|
status: S;
|
|
@@ -89,19 +102,19 @@ declare function respond<T extends object = Record<string, never>, S extends Suc
|
|
|
89
102
|
|
|
90
103
|
/**
|
|
91
104
|
* Returns the current time in the specified timezone.
|
|
92
|
-
* Example: getZonedTime({ tz: 'America/New_York' }) = new Date('2026-03-15T12:00:00Z')
|
|
105
|
+
* Example usage: `getZonedTime({ tz: 'America/New_York' }) = new Date('2026-03-15T12:00:00Z')`
|
|
93
106
|
*/
|
|
94
107
|
declare const getZonedTime: ({ tz }?: {
|
|
95
108
|
tz?: string;
|
|
96
109
|
}) => Date;
|
|
97
110
|
/**
|
|
98
111
|
* 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)'
|
|
112
|
+
* Example usage: `getUTCOffset(new Date('2026-03-15T12:00:00Z'), 'America/New_York') = '(-4 UTC)'`
|
|
100
113
|
*/
|
|
101
114
|
declare const getUTCOffset: (date: Date, tz: string) => string;
|
|
102
115
|
/**
|
|
103
116
|
* 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)'
|
|
117
|
+
* Example usage: `getFormattedTime({ tz: 'America/New_York' }) = '12:00:00 (-4 UTC)'`
|
|
105
118
|
*/
|
|
106
119
|
declare const getFormattedTime: ({ tz }?: {
|
|
107
120
|
tz?: string;
|
|
@@ -109,7 +122,7 @@ declare const getFormattedTime: ({ tz }?: {
|
|
|
109
122
|
/**
|
|
110
123
|
* Returns the current date in the specified timezone, formatted as dd.MM.yyyy.
|
|
111
124
|
* 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)'
|
|
125
|
+
* Example usage: `getFormattedDate({ tz: 'America/New_York' }) = '03.15.2026 12:00:00 (-4 UTC)'`
|
|
113
126
|
*/
|
|
114
127
|
declare const getFormattedDate: ({ tz, withTime, }?: {
|
|
115
128
|
tz?: string;
|
|
@@ -117,7 +130,7 @@ declare const getFormattedDate: ({ tz, withTime, }?: {
|
|
|
117
130
|
}) => string;
|
|
118
131
|
/**
|
|
119
132
|
* 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)'
|
|
133
|
+
* Example usage: `formatTime(new Date('2026-03-15T12:00:00Z'), { tz: 'America/New_York' }) = '12:00:00, March 15, 2026 (-4 UTC)'`
|
|
121
134
|
*/
|
|
122
135
|
declare const formatTime: (time: Date, { locale, tz }?: {
|
|
123
136
|
locale?: Locale;
|
|
@@ -126,13 +139,31 @@ declare const formatTime: (time: Date, { locale, tz }?: {
|
|
|
126
139
|
|
|
127
140
|
/**
|
|
128
141
|
* Safely executes functions and handles errors without using try/catch in the calling code.
|
|
129
|
-
* Example: safeExecute(() => fetchData(), (error) => console.error(error))
|
|
142
|
+
* Example usage: `safeExecute(() => fetchData(), (error) => console.error(error))`
|
|
130
143
|
*/
|
|
131
144
|
declare function safeExecute<T, E = never>(fn: () => Promise<T> | T, onError?: (error?: unknown) => E | Promise<E>): Promise<T | E>;
|
|
145
|
+
type MeasuredExecution<T> = {
|
|
146
|
+
/** The result of the executed function. */
|
|
147
|
+
result: T;
|
|
148
|
+
/** The time taken to execute the function, in milliseconds. */
|
|
149
|
+
executionTime: number;
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Utility function to measure the execution time of an asynchronous function.
|
|
153
|
+
* @returns An object containing the result of the execution and the time taken in milliseconds.
|
|
154
|
+
*
|
|
155
|
+
* ```ts
|
|
156
|
+
* const { result, executionTime } = await measureExecutionTime(async () => {
|
|
157
|
+
* return await fetchData();
|
|
158
|
+
* });
|
|
159
|
+
* console.log(`Execution time: ${executionTime}ms`);
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
declare function measureExecutionTime<T>(execution: () => Promise<T>): Promise<MeasuredExecution<T>>;
|
|
132
163
|
|
|
133
164
|
/**
|
|
134
165
|
* Creates a random string of the specified length using characters from DEFAULT_CHARACTERS.
|
|
135
|
-
* Example: generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ'
|
|
166
|
+
* Example usage: `generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ'`
|
|
136
167
|
*/
|
|
137
168
|
declare function generateRandomString(length?: number): string;
|
|
138
169
|
|
|
@@ -143,7 +174,7 @@ declare function generateRandomString(length?: number): string;
|
|
|
143
174
|
declare function getColoredHTTPStatus(status: number): (text: string) => string;
|
|
144
175
|
/**
|
|
145
176
|
* Unified logging interface for different levels (info, warn, error)
|
|
146
|
-
* with optional service name and stack trace for errors.
|
|
177
|
+
* with optional service name and stack trace for errors (error level).
|
|
147
178
|
*/
|
|
148
179
|
declare const log: {
|
|
149
180
|
info: (message: string, service?: string) => void;
|
|
@@ -212,4 +243,4 @@ declare class ZodJWTService<TPayloadOrSchema> {
|
|
|
212
243
|
verifyOrThrow(token: string, secret: string): Promise<Payload<TPayloadOrSchema>>;
|
|
213
244
|
}
|
|
214
245
|
|
|
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 };
|
|
246
|
+
export { type APIContractData, type APIContractError, type APIContractResult, type APIError, type APISuccess, 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,
|