@kalutskii/foundation 0.4.2 → 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 -21
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -30,23 +30,34 @@ 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
|
-
/** Pure type guard to check if a response is an APIContractResult. */
|
|
49
|
-
declare function isAPIResponse<TResponseData extends object>(responseData: TResponseData): responseData is TResponseData & APIContractResult<unknown>;
|
|
50
61
|
|
|
51
62
|
/**
|
|
52
63
|
* Global error handler for Hono framework. Catches all exceptions thrown in route handlers and middlewares.
|
|
@@ -55,7 +66,7 @@ declare function isAPIResponse<TResponseData extends object>(responseData: TResp
|
|
|
55
66
|
declare const onHandlerError: ErrorHandler;
|
|
56
67
|
|
|
57
68
|
/**
|
|
58
|
-
* 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.
|
|
59
70
|
* Example log output: [12:12:12 (+4 UTC)] hono | POST 200 123ms /api/v1/users (search=term)
|
|
60
71
|
*/
|
|
61
72
|
declare const honoLoggingHandler: MiddlewareHandler;
|
|
@@ -63,15 +74,15 @@ declare const honoLoggingHandler: MiddlewareHandler;
|
|
|
63
74
|
/**
|
|
64
75
|
* Type utility that recursively transforms all Date fields to string, as well as handling arrays and objects.
|
|
65
76
|
* This is necessary for proper typing when working with RPC, as JSON does not support the Date type directly.
|
|
66
|
-
* Example: SerializeDates<{ createdAt: Date; nested: { updatedAt: Date }; tags: Date[] }
|
|
67
|
-
* = { 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[] }`
|
|
68
79
|
*/
|
|
69
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 ? {
|
|
70
81
|
[K in keyof T]: SerializeDates<T[K]>;
|
|
71
82
|
} : T;
|
|
72
83
|
/**
|
|
73
84
|
* Transforms a string to a number (when passing query parameters).
|
|
74
|
-
* Example: asQueryNumber(z.number())('123') = 123
|
|
85
|
+
* Example usage: `asQueryNumber(z.number())('123') = 123`
|
|
75
86
|
*/
|
|
76
87
|
declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess<T>;
|
|
77
88
|
/**
|
|
@@ -81,8 +92,8 @@ declare const asQueryNumber: <T extends ZodNumber>(schema: T) => z.ZodPreprocess
|
|
|
81
92
|
declare const asQueryBoolean: <T extends z.ZodTypeAny>(schema: T) => z.ZodPreprocess<T>;
|
|
82
93
|
|
|
83
94
|
/**
|
|
84
|
-
* Wraps c.json with a typed success payload & possible APIError.
|
|
85
|
-
* 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).
|
|
86
97
|
*/
|
|
87
98
|
declare function respond<T extends object = Record<string, never>, S extends SuccessStatusCode = SuccessStatusCode>(c: Context, options: {
|
|
88
99
|
status: S;
|
|
@@ -91,19 +102,19 @@ declare function respond<T extends object = Record<string, never>, S extends Suc
|
|
|
91
102
|
|
|
92
103
|
/**
|
|
93
104
|
* Returns the current time in the specified timezone.
|
|
94
|
-
* 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')`
|
|
95
106
|
*/
|
|
96
107
|
declare const getZonedTime: ({ tz }?: {
|
|
97
108
|
tz?: string;
|
|
98
109
|
}) => Date;
|
|
99
110
|
/**
|
|
100
111
|
* Returns the timezone offset in the format (+4 UTC) / (-5 UTC).
|
|
101
|
-
* 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)'`
|
|
102
113
|
*/
|
|
103
114
|
declare const getUTCOffset: (date: Date, tz: string) => string;
|
|
104
115
|
/**
|
|
105
116
|
* Returns the current time in the specified timezone, formatted as HH:mm:ss (+X UTC).
|
|
106
|
-
* Example: getFormattedTime({ tz: 'America/New_York' }) = '12:00:00 (-4 UTC)'
|
|
117
|
+
* Example usage: `getFormattedTime({ tz: 'America/New_York' }) = '12:00:00 (-4 UTC)'`
|
|
107
118
|
*/
|
|
108
119
|
declare const getFormattedTime: ({ tz }?: {
|
|
109
120
|
tz?: string;
|
|
@@ -111,7 +122,7 @@ declare const getFormattedTime: ({ tz }?: {
|
|
|
111
122
|
/**
|
|
112
123
|
* Returns the current date in the specified timezone, formatted as dd.MM.yyyy.
|
|
113
124
|
* By default, it also includes time (HH:mm:ss) and timezone offset.
|
|
114
|
-
* 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)'`
|
|
115
126
|
*/
|
|
116
127
|
declare const getFormattedDate: ({ tz, withTime, }?: {
|
|
117
128
|
tz?: string;
|
|
@@ -119,7 +130,7 @@ declare const getFormattedDate: ({ tz, withTime, }?: {
|
|
|
119
130
|
}) => string;
|
|
120
131
|
/**
|
|
121
132
|
* Formats the given time in the specified timezone, using the provided locale for date formatting.
|
|
122
|
-
* 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)'`
|
|
123
134
|
*/
|
|
124
135
|
declare const formatTime: (time: Date, { locale, tz }?: {
|
|
125
136
|
locale?: Locale;
|
|
@@ -128,13 +139,31 @@ declare const formatTime: (time: Date, { locale, tz }?: {
|
|
|
128
139
|
|
|
129
140
|
/**
|
|
130
141
|
* Safely executes functions and handles errors without using try/catch in the calling code.
|
|
131
|
-
* Example: safeExecute(() => fetchData(), (error) => console.error(error))
|
|
142
|
+
* Example usage: `safeExecute(() => fetchData(), (error) => console.error(error))`
|
|
132
143
|
*/
|
|
133
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>>;
|
|
134
163
|
|
|
135
164
|
/**
|
|
136
165
|
* Creates a random string of the specified length using characters from DEFAULT_CHARACTERS.
|
|
137
|
-
* Example: generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ'
|
|
166
|
+
* Example usage: `generateRandomString(5) = 'aZ3fG' / generateRandomString() = 'G5kLm2P9sQ'`
|
|
138
167
|
*/
|
|
139
168
|
declare function generateRandomString(length?: number): string;
|
|
140
169
|
|
|
@@ -145,7 +174,7 @@ declare function generateRandomString(length?: number): string;
|
|
|
145
174
|
declare function getColoredHTTPStatus(status: number): (text: string) => string;
|
|
146
175
|
/**
|
|
147
176
|
* Unified logging interface for different levels (info, warn, error)
|
|
148
|
-
* with optional service name and stack trace for errors.
|
|
177
|
+
* with optional service name and stack trace for errors (error level).
|
|
149
178
|
*/
|
|
150
179
|
declare const log: {
|
|
151
180
|
info: (message: string, service?: string) => void;
|
|
@@ -214,4 +243,4 @@ declare class ZodJWTService<TPayloadOrSchema> {
|
|
|
214
243
|
verifyOrThrow(token: string, secret: string): Promise<Payload<TPayloadOrSchema>>;
|
|
215
244
|
}
|
|
216
245
|
|
|
217
|
-
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,
|
|
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
|
@@ -23,12 +23,6 @@ async function fetchAndThrow(fetcher) {
|
|
|
23
23
|
throw new Error(response.error);
|
|
24
24
|
return response.data;
|
|
25
25
|
}
|
|
26
|
-
function isAPIResponse(responseData) {
|
|
27
|
-
if (!("kind" in responseData) || !("status" in responseData))
|
|
28
|
-
return false;
|
|
29
|
-
const { kind, status } = responseData;
|
|
30
|
-
return (kind === "data" || kind === "error") && (typeof status === "number" || typeof status === "string");
|
|
31
|
-
}
|
|
32
26
|
|
|
33
27
|
// src/hono/hono.execution.ts
|
|
34
28
|
import { HTTPException } from "hono/http-exception";
|
|
@@ -146,6 +140,12 @@ async function safeExecute(fn, onError) {
|
|
|
146
140
|
throw err;
|
|
147
141
|
}
|
|
148
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
|
+
}
|
|
149
149
|
|
|
150
150
|
// src/utilities/serialization.utilities.ts
|
|
151
151
|
import { z } from "zod";
|
|
@@ -229,8 +229,8 @@ export {
|
|
|
229
229
|
getUTCOffset,
|
|
230
230
|
getZonedTime,
|
|
231
231
|
honoLoggingHandler,
|
|
232
|
-
isAPIResponse,
|
|
233
232
|
log,
|
|
233
|
+
measureExecutionTime,
|
|
234
234
|
onHandlerError,
|
|
235
235
|
respond,
|
|
236
236
|
safeExecute,
|