@kalutskii/foundation 2.0.0 → 2.0.6

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.
Files changed (4) hide show
  1. package/README.md +13 -347
  2. package/dist/index.d.ts +939 -737
  3. package/dist/index.js +1009 -678
  4. package/package.json +5 -5
package/dist/index.d.ts CHANGED
@@ -1,86 +1,284 @@
1
- import { SQL } from "drizzle-orm";
2
1
  import { Locale } from "date-fns";
3
- import z, { ZodObject, ZodRawShape, z as z$1 } from "zod";
2
+ import { InferSelectModel, SQL, Table } from "drizzle-orm";
3
+ import { HTTPException } from "hono/http-exception";
4
+ import { z } from "zod";
4
5
  import { Context, ErrorHandler, MiddlewareHandler, TypedResponse } from "hono";
5
6
  import { SymmetricAlgorithm } from "hono/utils/jwt/jwa";
7
+ import { JWTPayload, JWTPayload as JWTPayload$1 } from "hono/utils/jwt/types";
8
+ //#region src/base64/base64.utilities.d.ts
9
+ /**
10
+ * Encodes arbitrary binary bytes into their canonical Base64 representation.
11
+ * Chunked conversion avoids the argument limit imposed by `String.fromCharCode`.
12
+ */
13
+ declare function encodeBase64(bytes: Uint8Array): string;
14
+ /**
15
+ * Decodes Base64 text accepted by native `atob` into its original binary bytes.
16
+ * Unsupported input preserves the platform failure instead of returning partial data.
17
+ */
18
+ declare function decodeBase64(value: string): Uint8Array<ArrayBuffer>;
19
+ //#endregion
20
+ //#region src/datetime/datetime.types.d.ts
21
+ /**
22
+ * Options selecting the timezone used by current-time datetime operations.
23
+ * An omitted timezone preserves the shared London-based default behavior.
24
+ */
25
+ type DateTimeZoneOptions = {
26
+ /**
27
+ * IANA timezone used to project and format the current instant.
28
+ * The shared London timezone applies when this option is omitted.
29
+ */
30
+ tz?: string;
31
+ };
32
+ /**
33
+ * Options controlling current-date formatting and optional time inclusion.
34
+ * Time output includes its UTC offset and remains enabled unless explicitly disabled.
35
+ */
36
+ type FormattedDateOptions = DateTimeZoneOptions & {
37
+ /**
38
+ * Controls whether wall-clock time and its UTC offset are included.
39
+ * Time information remains enabled unless this option is explicitly `false`.
40
+ */
41
+ withTime?: boolean;
42
+ };
43
+ /**
44
+ * Options controlling localized formatting for one explicit instant.
45
+ * Russian localization and the shared timezone default apply when omitted.
46
+ */
47
+ type FormatTimeOptions = DateTimeZoneOptions & {
48
+ /**
49
+ * date-fns locale used for the textual calendar representation.
50
+ * The Russian locale remains the default when this option is omitted.
51
+ */
52
+ locale?: Locale;
53
+ };
54
+ //#endregion
55
+ //#region src/datetime/datetime.utilities.d.ts
56
+ /**
57
+ * Projects the current instant onto the wall-clock fields of another timezone.
58
+ * The timezone defaults to `Europe/London` when no option is provided.
59
+ *
60
+ * @example
61
+ * const londonTime = getZonedTime({ tz: 'Europe/London' });
62
+ */
63
+ declare function getZonedTime({ tz }?: DateTimeZoneOptions): Date;
64
+ /**
65
+ * Formats the UTC offset of a timezone at the supplied date.
66
+ * An explicit date preserves daylight-saving and historical offset rules.
67
+ *
68
+ * @example
69
+ * getUTCOffset(date, 'Europe/Moscow'); // `(+3 UTC)`
70
+ */
71
+ declare function getUTCOffset(date: Date, tz: string): string;
72
+ /**
73
+ * Formats the current time and UTC offset in the selected timezone.
74
+ * The timezone defaults to `Europe/London` when no option is provided.
75
+ *
76
+ * @example
77
+ * getFormattedTime({ tz: 'Europe/Moscow' }); // `03:04:05 (+3 UTC)`
78
+ */
79
+ declare function getFormattedTime({ tz }?: DateTimeZoneOptions): string;
80
+ /**
81
+ * Formats the current date with optional time and UTC offset components.
82
+ * Time is included by default and uses the selected timezone for display.
83
+ *
84
+ * @example
85
+ * getFormattedDate({ tz: 'UTC', withTime: false }); // `02.01.2024`
86
+ */
87
+ declare function getFormattedDate({ tz, withTime }?: FormattedDateOptions): string;
88
+ /**
89
+ * Formats an explicit instant in another timezone using the selected locale.
90
+ * The result includes localized date text, wall-clock time, and UTC offset.
91
+ *
92
+ * @example
93
+ * formatTime(date, { locale: ru, tz: 'Europe/Moscow' });
94
+ */
95
+ declare function formatTime(time: Date, options?: FormatTimeOptions): string;
96
+ //#endregion
97
+ //#region src/datetime/datetime.constants.d.ts
98
+ /**
99
+ * Default timezone applied by datetime utilities when no explicit zone is provided.
100
+ * The value preserves the package's historical London-based formatting behavior.
101
+ */
102
+ declare const DEFAULT_DATETIME_TIMEZONE = "Europe/London";
103
+ //#endregion
104
+ //#region src/drizzle/drizzle.errors.d.ts
105
+ declare const drizzleErrors: {
106
+ whereConditionsRequired: () => Error;
107
+ whereColumnNotFound: () => Error;
108
+ };
109
+ type DrizzleErrorCode = keyof typeof drizzleErrors;
110
+ //#endregion
111
+ //#region src/drizzle/drizzle.types.d.ts
112
+ /**
113
+ * Defined equality conditions accepted by `sqlWhere` for one Drizzle table.
114
+ * Keys and values remain aligned with the table's inferred selected row model.
115
+ */
116
+ type SQLWhereConditions<TTable extends Table> = Partial<InferSelectModel<TTable>>;
117
+ //#endregion
6
118
  //#region src/drizzle/drizzle.refiners.d.ts
7
119
  /**
8
120
  * Builds a Drizzle `WHERE` clause by combining defined object entries with `and`.
9
- * Expects the supplied keys to be validated against the table beforehand.
121
+ * Keys and values follow the table model while empty conditions remain forbidden.
10
122
  *
11
123
  * @example
12
124
  * await db.update(usersTable).set(values).where(sqlWhere(usersTable, { id: 1 })).returning();
13
125
  */
14
- declare function sqlWhere(table: unknown, where: Record<string, unknown>): SQL;
126
+ declare function sqlWhere<TTable extends Table>(table: TTable, where: SQLWhereConditions<NoInfer<TTable>>): SQL;
15
127
  //#endregion
16
- //#region src/hono/hono.execution.d.ts
128
+ //#region src/execution/execution.constants.d.ts
17
129
  /**
18
- * Converts expected `HTTPException` values into shared API error envelopes.
19
- * Unexpected failures are logged and represented by a traceable generic response.
130
+ * Default total attempt count applied when `retryExecution` receives no override.
131
+ * The value includes the initial operation and every subsequent retry attempt.
20
132
  */
21
- declare const onHandlerError: ErrorHandler;
133
+ declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
22
134
  //#endregion
23
- //#region src/http/http.constants.d.ts
24
- declare const SUCCESS_STATUS_CODES: readonly [200, 201, 202, 307];
25
- declare const EXCEPTION_STATUS_CODES: readonly [400, 401, 403, 404, 405, 409, 500];
26
- //#endregion
27
- //#region src/http/http.types.d.ts
28
- type SuccessStatusCode = (typeof SUCCESS_STATUS_CODES)[number];
29
- type ExceptionStatusCode = (typeof EXCEPTION_STATUS_CODES)[number];
30
- type APISuccess<TData = void> = {
31
- kind: 'data';
32
- status: SuccessStatusCode;
33
- data: TData;
135
+ //#region src/execution/execution.errors.d.ts
136
+ declare const executionErrors: {
137
+ invalidMaxAttempts: () => RangeError;
138
+ invalidRetryDelay: () => RangeError;
139
+ invalidTimeout: () => RangeError;
140
+ executionTimedOut: () => DOMException;
34
141
  };
35
- type APIError<TErrorCode extends string = string> = {
36
- kind: 'error';
37
- status: ExceptionStatusCode;
38
- error: TErrorCode;
39
- };
40
- type APIContractResult<TData = void, TErrorCode extends string = string> = APISuccess<TData> | APIError<TErrorCode>;
41
- type APIContractData<TResult extends APIContractResult<unknown>> = TResult extends APISuccess<infer TData> ? TData : never;
42
- type APIContractError<TResult extends APIContractResult<unknown>> = Extract<TResult, APIError>;
43
- type APIContractErrorCode<TResult extends APIContractResult<unknown>> = APIContractError<TResult>['error'];
44
- type ErrorCodeOf<TErrorFactories extends Record<string, unknown>> = keyof TErrorFactories & string;
45
- type FetchResult<TData, TErrorCode extends string = string> = {
46
- error: null;
142
+ type ExecutionErrorCode = keyof typeof executionErrors;
143
+ //#endregion
144
+ //#region src/execution/execution.types.d.ts
145
+ /**
146
+ * Synchronous or asynchronous operation consumed by execution utilities.
147
+ * The resolved value remains inferred from its callback without widening.
148
+ */
149
+ type Execution<TData> = () => TData | Promise<TData>;
150
+ /**
151
+ * Mutually exclusive result produced after capturing an operation outcome.
152
+ * Successful data and unknown failures are distinguished by `success`.
153
+ */
154
+ type ExecutionResult<TData> = {
155
+ success: true;
47
156
  data: TData;
48
157
  } | {
49
- error: TErrorCode;
50
- data: null;
158
+ success: false;
159
+ error: unknown;
51
160
  };
161
+ /**
162
+ * Context supplied to every operation attempt executed by `retryExecution`.
163
+ * Attempts are one-based and share an optional caller cancellation signal.
164
+ */
165
+ type RetryExecutionContext = Readonly<{
166
+ /**
167
+ * One-based number of the attempt currently being executed.
168
+ * The initial operation always receives the `attempt` value `1`.
169
+ */
170
+ attempt: number;
171
+ /**
172
+ * Optional signal allowing the operation to observe caller cancellation.
173
+ * The same signal remains available across every execution attempt.
174
+ */
175
+ signal?: AbortSignal;
176
+ }>;
177
+ /**
178
+ * Configuration controlling retry limits, delays, filtering, and cancellation.
179
+ * Three immediate attempts run by default when every failure remains retryable.
180
+ */
181
+ type RetryExecutionOptions = Readonly<{
182
+ /**
183
+ * Positive total attempt count including the initial execution.
184
+ * Omitting this option applies the default of three attempts.
185
+ */
186
+ maxAttempts?: number;
187
+ /**
188
+ * Delay before the next attempt, or a resolver returning it in milliseconds.
189
+ * The resolver receives the failure and completed one-based attempt number.
190
+ */
191
+ delayMilliseconds?: number | ((error: unknown, attempt: number) => number | Promise<number>);
192
+ /**
193
+ * Decides whether another attempt may follow the latest operation failure.
194
+ * Returning `false` preserves and immediately rethrows the original failure.
195
+ */
196
+ shouldRetry?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
197
+ /**
198
+ * Cancels pending delays and prevents subsequent attempts when aborted.
199
+ * Active operations must observe the signal to stop their own work.
200
+ */
201
+ signal?: AbortSignal;
202
+ }>;
203
+ /**
204
+ * Configuration for one cooperatively cancellable time-bounded execution.
205
+ * Caller cancellation and timeout expiration retain their original reasons.
206
+ */
207
+ type ExecuteWithTimeoutOptions = Readonly<{
208
+ /**
209
+ * Non-negative finite execution duration expressed in milliseconds.
210
+ * Expiration aborts with a standard `TimeoutError` DOM exception.
211
+ */
212
+ timeoutMilliseconds: number;
213
+ /**
214
+ * Optional caller signal combined with the internally managed timeout signal.
215
+ * Its cancellation reason takes precedence when the signal is already aborted.
216
+ */
217
+ signal?: AbortSignal;
218
+ }>;
52
219
  //#endregion
53
- //#region src/hono/hono.types.d.ts
220
+ //#region src/execution/execution.measurements.d.ts
54
221
  /**
55
- * Options for a typed JSON response wrapped in the shared API success envelope.
56
- * The status generic preserves the literal code inferred by the route contract.
222
+ * Result returned after measuring a successful synchronous or asynchronous execution.
223
+ * The resolved value remains available beside its rounded millisecond duration.
57
224
  */
58
- type HonoRespondOptions<TData extends object, TStatus extends SuccessStatusCode> = {
59
- status: TStatus;
60
- data?: TData;
225
+ type MeasuredExecution<TData> = {
226
+ /**
227
+ * Value resolved by the measured execution without cloning or transformation.
228
+ * Its generic type remains identical to the original operation result.
229
+ */
230
+ result: TData;
231
+ /**
232
+ * Rounded wall-clock duration of the measured execution in milliseconds.
233
+ * The value is collected only after the supplied operation resolves.
234
+ */
235
+ executionTime: number;
61
236
  };
62
237
  /**
63
- * Options for a downloadable binary response with attachment metadata.
64
- * The content type remains optional and falls back to a generic binary type.
238
+ * Measures a synchronous or asynchronous execution while preserving its resolved result.
239
+ * Rejected operations propagate unchanged and never produce a measurement result.
240
+ *
241
+ * @example
242
+ * const { result, executionTime } = await measureExecutionTime(async () => {
243
+ * return await fetchData();
244
+ * });
245
+ * console.log(`Execution time: ${executionTime}ms`);
65
246
  */
66
- type HonoFileRespondOptions<TStatus extends SuccessStatusCode> = {
67
- status: TStatus;
68
- content: Uint8Array<ArrayBuffer>;
69
- filename: string;
70
- contentType?: string;
71
- };
247
+ declare function measureExecutionTime<TData>(execution: Execution<TData>): Promise<MeasuredExecution<TData>>;
72
248
  //#endregion
73
- //#region src/hono/hono.respond.d.ts
249
+ //#region src/execution/execution.retry.d.ts
74
250
  /**
75
- * Wraps `c.json` in the shared success envelope while preserving its literal status.
76
- * Missing response data is represented by an empty object for contract consistency.
251
+ * Waits for a retry delay while preserving cooperative caller cancellation.
252
+ * Zero-duration delays resolve immediately without allocating a timer.
77
253
  */
78
- declare function respond<T extends object = Record<string, never>, S extends SuccessStatusCode = SuccessStatusCode>(c: Context, options: HonoRespondOptions<T, S>): Response & TypedResponse<APISuccess<T> | APIError, S, 'json'>;
254
+ declare function waitForRetry(delayMilliseconds: number, signal?: AbortSignal): Promise<void>;
79
255
  /**
80
- * Responds with downloadable binary content and its attachment headers.
81
- * Unknown/undefined content types default to `application/octet-stream`.
256
+ * Repeats a failed operation under explicit attempt, delay, and filtering policies.
257
+ * Exhaustion, rejected filtering, and cancellation preserve the original failure.
258
+ */
259
+ declare function retryExecution<TData>(execution: (context: RetryExecutionContext) => TData | Promise<TData>, options?: RetryExecutionOptions): Promise<TData>;
260
+ //#endregion
261
+ //#region src/execution/execution.timeout.d.ts
262
+ /**
263
+ * Runs an operation with a signal controlled by timeout and caller cancellation.
264
+ * The promise rejects promptly even when the operation ignores its abort signal.
82
265
  */
83
- declare function fileRespond<S extends SuccessStatusCode>(c: Context, options: HonoFileRespondOptions<S>): Response;
266
+ declare function executeWithTimeout<TData>(execution: (signal: AbortSignal) => TData | Promise<TData>, options: ExecuteWithTimeoutOptions): Promise<TData>;
267
+ //#endregion
268
+ //#region src/execution/execution.utilities.d.ts
269
+ /**
270
+ * Resolves synchronous and asynchronous operations through one promise-based contract.
271
+ * Failures use the supplied fallback or propagate unchanged when none is available.
272
+ *
273
+ * @example
274
+ * await safeExecute(() => fetchData(), (error) => console.error(error));
275
+ */
276
+ declare function safeExecute<TData, TErrorResult = never>(fn: Execution<TData>, onError?: (error: unknown) => TErrorResult | Promise<TErrorResult>): Promise<TData | TErrorResult>;
277
+ /**
278
+ * Captures a synchronous or asynchronous operation in a discriminated result.
279
+ * Successful values and original unknown failures remain available unchanged.
280
+ */
281
+ declare function captureExecution<TData>(execution: Execution<TData>): Promise<ExecutionResult<TData>>;
84
282
  //#endregion
85
283
  //#region src/hmac/hmac.constants.d.ts
86
284
  /**
@@ -120,12 +318,26 @@ declare const hmacEncoding: Readonly<{
120
318
  HEX: "hex";
121
319
  }>;
122
320
  //#endregion
321
+ //#region src/hmac/hmac.errors.d.ts
322
+ declare const hmacErrors: {
323
+ invalidHexSignature: () => TypeError;
324
+ invalidBase64Signature: () => TypeError;
325
+ invalidBase64UrlSignature: () => TypeError;
326
+ incompatibleCryptoKey: () => TypeError;
327
+ };
328
+ type HMACErrorCode = keyof typeof hmacErrors;
329
+ //#endregion
123
330
  //#region src/hmac/hmac.types.d.ts
124
331
  /**
125
332
  * Binary-safe input accepted as either an HMAC payload or a secret key.
126
333
  * Strings use UTF-8 encoding while byte arrays preserve their exact contents.
127
334
  */
128
335
  type HMACInput = string | Uint8Array;
336
+ /**
337
+ * Secret material accepted directly or as a previously imported Web Crypto key.
338
+ * Imported keys avoid repeated key imports across high-frequency operations.
339
+ */
340
+ type HMACSecret = HMACInput | CryptoKey;
129
341
  /**
130
342
  * Configures the digest algorithm and textual signature encoding for one service.
131
343
  * Omitted values select SHA-256 and lowercase hexadecimal output by default.
@@ -152,23 +364,28 @@ declare class HMACService {
152
364
  readonly algorithm: HMACAlgorithm;
153
365
  readonly encoding: HMACEncoding;
154
366
  constructor(options?: HMACServiceOptions);
367
+ /**
368
+ * Imports raw secret material as a non-extractable Web Crypto HMAC key.
369
+ * The resulting key supports repeated signing and verification without reimporting.
370
+ */
371
+ importKey(secret: HMACInput): Promise<CryptoKey>;
155
372
  /**
156
373
  * Authenticates a payload with a secret and returns the encoded signature.
157
- * String inputs use UTF-8 while byte arrays preserve their exact byte sequence.
374
+ * Imported keys bypass repeated key creation while preserving service policy.
158
375
  *
159
376
  * @example
160
377
  * const signature = await hmacService.sign('payload', 'shared-secret');
161
378
  */
162
- sign(payload: HMACInput, secret: HMACInput): Promise<string>;
379
+ sign(payload: HMACInput, secret: HMACSecret): Promise<string>;
163
380
  /**
164
381
  * Verifies an encoded signature without requiring a manual equality comparison.
165
- * Invalid encodings, incorrect secrets, and altered payloads all resolve to `false`.
382
+ * Invalid signatures resolve to `false`; incompatible imported keys reject explicitly.
166
383
  *
167
384
  * @example
168
385
  * const verified = await hmacService.verify('payload', signature, 'shared-secret');
169
386
  */
170
- verify(payload: HMACInput, signature: string, secret: HMACInput): Promise<boolean>;
171
- private importSecret;
387
+ verify(payload: HMACInput, signature: string, secret: HMACSecret): Promise<boolean>;
388
+ private resolveKey;
172
389
  }
173
390
  //#endregion
174
391
  //#region src/hmac/hmac.utilities.d.ts
@@ -188,502 +405,612 @@ declare function encodeHMACSignature(signature: Uint8Array, encoding: HMACEncodi
188
405
  */
189
406
  declare function decodeHMACSignature(signature: string, encoding: HMACEncoding): Uint8Array<ArrayBuffer>;
190
407
  //#endregion
191
- //#region src/http/http.errors.d.ts
408
+ //#region src/hono/hono.constants.d.ts
192
409
  /**
193
- * Represents an error envelope rejected by an API request resolver.
194
- * The original status and typed code remain available for client handling.
410
+ * Default HTTP header carrying one request identifier across service boundaries.
411
+ * Incoming non-empty values are preserved while missing identifiers are generated.
195
412
  */
196
- declare class APIRequestError<TErrorCode extends string = string> extends Error {
197
- readonly code: TErrorCode;
198
- readonly status: ExceptionStatusCode;
199
- constructor(status: ExceptionStatusCode, code: TErrorCode);
200
- }
201
- //#endregion
202
- //#region src/http/http.factory.d.ts
413
+ declare const HONO_REQUEST_ID_HEADER = "X-Request-ID";
203
414
  /**
204
- * Creates a successful API envelope without cloning its data.
205
- * Generic inference preserves the exact supplied payload type.
415
+ * Default service label applied to request lines emitted by Hono logging middleware.
416
+ * Configured middleware may replace the label without changing message formatting.
206
417
  */
207
- declare function success<T = unknown>({ status, data }: {
208
- status: SuccessStatusCode;
209
- data: T;
210
- }): APISuccess<T>;
418
+ declare const HONO_LOGGING_SERVICE = "hono";
419
+ //#endregion
420
+ //#region src/hono/hono.errors.d.ts
421
+ declare const honoErrors: {
422
+ internalServerError: () => HTTPException;
423
+ invalidRequestId: () => TypeError;
424
+ };
425
+ type HonoErrorCode = keyof typeof honoErrors;
426
+ //#endregion
427
+ //#region src/response/response.enums.d.ts
428
+ declare const responseKindsArray: readonly ['success', 'error'];
429
+ type ResponseKind = (typeof responseKindsArray)[number];
430
+ declare const responseKindsRecord: Readonly<{
431
+ ERROR: "error";
432
+ SUCCESS: "success";
433
+ }>;
434
+ declare const responseKind: Readonly<{
435
+ ERROR: "error";
436
+ SUCCESS: "success";
437
+ }>;
438
+ declare const SUCCESS_RESPONSE_STATUSES: readonly [200, 201, 202, 206];
439
+ type SuccessResponseStatus = (typeof SUCCESS_RESPONSE_STATUSES)[number];
440
+ declare const ERROR_RESPONSE_STATUSES: readonly [400, 401, 403, 404, 405, 406, 408, 409, 410, 413, 414, 415, 422, 425, 429, 440, 498, 500, 501, 502, 503, 504];
441
+ type ErrorResponseStatus = (typeof ERROR_RESPONSE_STATUSES)[number];
442
+ //#endregion
443
+ //#region src/response/response.errors.d.ts
444
+ declare const responseErrors: {
445
+ invalidResponseErrorCode: () => TypeError;
446
+ invalidSuccessResponseStatus: () => RangeError;
447
+ invalidErrorResponseStatus: () => RangeError;
448
+ };
449
+ type ResponseErrorCode = keyof typeof responseErrors;
211
450
  /**
212
- * Creates a failed API envelope with one supported exception status.
213
- * The supplied error code remains unchanged for downstream resolution.
451
+ * Represents a failed response rejected while unwrapping a remote operation.
452
+ * The original machine-readable code and response status remain available.
214
453
  */
215
- declare function failure<const TErrorCode extends string>({ status, error }: {
216
- status: ExceptionStatusCode;
454
+ declare class ResponseError<TErrorCode extends string = string> extends Error {
455
+ readonly code: TErrorCode;
456
+ readonly status: ErrorResponseStatus;
457
+ constructor(status: ErrorResponseStatus, code: TErrorCode);
458
+ }
459
+ //#endregion
460
+ //#region src/response/response.types.d.ts
461
+ type SuccessResponse<TData = void> = {
462
+ kind: typeof responseKind.SUCCESS;
463
+ status: SuccessResponseStatus;
464
+ data: TData;
465
+ };
466
+ type ErrorResponse<TErrorCode extends string = string> = {
467
+ kind: typeof responseKind.ERROR;
468
+ status: ErrorResponseStatus;
217
469
  error: TErrorCode;
218
- }): APIError<TErrorCode>;
470
+ };
471
+ type ResponseResult<TData = void, TErrorCode extends string = string> = SuccessResponse<TData> | ErrorResponse<TErrorCode>;
472
+ type ResponseData<TResult extends ResponseResult<unknown>> = TResult extends SuccessResponse<infer TData> ? TData : never;
473
+ type ResponseFailure<TResult extends ResponseResult<unknown>> = Extract<TResult, ErrorResponse>;
474
+ type ResponseFailureCode<TResult extends ResponseResult<unknown>> = ResponseFailure<TResult>['error'];
475
+ type ErrorCodeOf<TErrorFactories extends Record<string, unknown>> = keyof TErrorFactories & string;
476
+ type ResolvedResponse<TData, TErrorCode extends string = string> = {
477
+ success: true;
478
+ status: SuccessResponseStatus;
479
+ data: TData;
480
+ error: null;
481
+ } | {
482
+ success: false;
483
+ status: ErrorResponseStatus;
484
+ data: null;
485
+ error: TErrorCode;
486
+ };
219
487
  //#endregion
220
- //#region src/http/http.resolvers.d.ts
488
+ //#region src/response/response.factories.d.ts
221
489
  /**
222
- * Converts an API contract envelope into a mutually exclusive safe result.
223
- * Only `APIError` values are normalized; rejected fetchers still reject.
490
+ * Creates a successful response envelope without cloning its supplied data.
491
+ * Generic inference preserves the exact payload type for downstream contracts.
224
492
  */
225
- declare function fetchSafely<TResult extends APIContractResult<unknown>>(fetcher: () => Promise<TResult>): Promise<FetchResult<APIContractData<TResult>, APIContractErrorCode<TResult>>>;
493
+ declare function createSuccessResponse<TData>(status: SuccessResponseStatus, data: TData): SuccessResponse<TData>;
226
494
  /**
227
- * Returns successful API data and throws `APIRequestError` for a failed envelope.
228
- * Transport and programming rejections propagate without replacement.
495
+ * Creates a failed response envelope from one stable machine-readable error code.
496
+ * Human-readable or malformed values reject before crossing the response boundary.
229
497
  */
230
- declare function fetchAndThrow<TResult extends APIContractResult<unknown>>(fetcher: () => Promise<TResult>): Promise<APIContractData<TResult>>;
498
+ declare function createErrorResponse<const TErrorCode extends string>(status: ErrorResponseStatus, error: TErrorCode): ErrorResponse<TErrorCode>;
231
499
  //#endregion
232
- //#region src/logging/logging.constants.d.ts
500
+ //#region src/response/response.resolvers.d.ts
233
501
  /**
234
- * Terminal color configuration for every supported logging level.
235
- * The `LogLevel` contract prevents missing or unsupported level entries.
502
+ * Resolves a response envelope into a status-preserving discriminated result.
503
+ * Transport and programming failures remain observable promise rejections.
236
504
  */
237
- declare const logLevelColors: {
238
- readonly info: typeof import("kleur/colors").print;
239
- readonly warn: typeof import("kleur/colors").print;
240
- readonly error: typeof import("kleur/colors").print;
241
- };
505
+ declare function resolveResponse<TResult extends ResponseResult<unknown>>(operation: () => Promise<TResult>): Promise<ResolvedResponse<ResponseData<TResult>, ResponseFailureCode<TResult>>>;
242
506
  /**
243
- * Public placeholder written instead of sensitive query and JSON values.
244
- * One stable marker keeps redacted output recognizable across log consumers.
507
+ * Unwraps successful response data and throws `ResponseError` for a failed envelope.
508
+ * Transport and programming failures propagate without replacement or normalization.
245
509
  */
246
- declare const REDACTED_LOG_VALUE = "[redacted]";
510
+ declare function unwrapResponse<TResult extends ResponseResult<unknown>>(operation: () => Promise<TResult>): Promise<ResponseData<TResult>>;
511
+ //#endregion
512
+ //#region src/response/response.validation.d.ts
247
513
  /**
248
- * Normalized key fragments treated as sensitive by logging redaction.
249
- * Matching ignores case and separators so compound field names remain covered.
514
+ * Determines whether a value is a stable camelCase response error code.
515
+ * Human-readable text and punctuation remain excluded from public envelopes.
250
516
  */
251
- declare const sensitiveLogKeyParts: readonly ['password', 'passwd', 'token', 'secret', 'authorization', 'apikey', 'credential'];
517
+ declare function isResponseErrorCode(value: unknown): value is string;
252
518
  /**
253
- * Terminal colors assigned to the supported HTTP response status ranges.
254
- * Unlisted ranges intentionally retain the terminal's default text appearance.
519
+ * Determines whether a value belongs to the supported success-status catalog.
520
+ * Runtime membership mirrors the exact union exposed by `SuccessResponseStatus`.
255
521
  */
256
- declare const httpStatusColors: readonly [{
257
- readonly range: readonly [200, 299];
258
- readonly color: typeof import("kleur/colors").print;
259
- }, {
260
- readonly range: readonly [400, 499];
261
- readonly color: typeof import("kleur/colors").print;
262
- }, {
263
- readonly range: readonly [500, 599];
264
- readonly color: typeof import("kleur/colors").print;
265
- }];
266
- //#endregion
267
- //#region src/logging/logging.enums.d.ts
268
- declare const logLevelsArray: readonly ['info', 'warn', 'error'];
269
- type LogLevel = (typeof logLevelsArray)[number];
270
- declare const logLevelsRecord: Readonly<{
271
- ERROR: "error";
272
- INFO: "info";
273
- WARN: "warn";
274
- }>;
275
- declare const logLevel: Readonly<{
276
- ERROR: "error";
277
- INFO: "info";
278
- WARN: "warn";
279
- }>;
280
- //#endregion
281
- //#region src/logging/logging.middleware.d.ts
522
+ declare function isSuccessResponseStatus(value: unknown): value is SuccessResponseStatus;
282
523
  /**
283
- * Logs Hono request metadata with query parameters and a normalized body preview.
284
- * Sensitive values are redacted by partial key match before output is written.
524
+ * Determines whether a value belongs to the supported error-status catalog.
525
+ * Runtime membership mirrors the exact union exposed by `ErrorResponseStatus`.
285
526
  */
286
- declare const loggingMiddleware: MiddlewareHandler;
287
- //#endregion
288
- //#region src/logging/logging.security.d.ts
527
+ declare function isErrorResponseStatus(value: unknown): value is ErrorResponseStatus;
289
528
  /**
290
- * Replaces sensitive query values using partial, case-insensitive key matching.
291
- * A new collection is returned so the caller's search parameters remain unchanged.
529
+ * Narrows a response result to its successful branch through the shared discriminator.
530
+ * Payload and error-code generics remain unchanged for downstream control-flow analysis.
292
531
  */
293
- declare function redactSensitiveSearchParams(searchParams: URLSearchParams): URLSearchParams;
532
+ declare function isSuccessResponse<TData, TErrorCode extends string>(response: ResponseResult<TData, TErrorCode>): response is SuccessResponse<TData>;
294
533
  /**
295
- * Replaces values under sensitive keys throughout a serialized JSON structure.
296
- * Invalid JSON and payloads without matching keys are returned byte-for-byte unchanged.
534
+ * Narrows a response result to its failed branch through the shared discriminator.
535
+ * Payload and error-code generics remain unchanged for downstream control-flow analysis.
297
536
  */
298
- declare function redactSensitiveJSON(json: string): string;
537
+ declare function isErrorResponse<TData, TErrorCode extends string>(response: ResponseResult<TData, TErrorCode>): response is ErrorResponse<TErrorCode>;
299
538
  //#endregion
300
- //#region src/logging/logging.services.d.ts
539
+ //#region src/hono/hono.types.d.ts
301
540
  /**
302
- * Writes timestamped and colorized messages using a stable service column.
303
- * Error messages may include a stack trace on a subordinate second line.
541
+ * Options controlling the application-owned side effect for unexpected Hono failures.
542
+ * Expected client exceptions bypass the callback and retain their machine-readable code.
304
543
  */
305
- declare const log: {
544
+ type HonoErrorHandlerOptions = {
306
545
  /**
307
- * Writes an informational message with an optional service label.
308
- * Missing service names use the shared `log` fallback label.
546
+ * Receives an unexpected failure, request context, and optional correlation identifier.
547
+ * Applications may report original context without changing the public response envelope.
309
548
  */
310
- info(message: string, service?: string): void;
549
+ onUnexpectedError: (error: unknown, context: Context, requestId?: string) => void;
550
+ };
551
+ /**
552
+ * Options controlling request metadata and body previews emitted by Hono middleware.
553
+ * Defaults preserve the existing service label, body capture, and shared preview limit.
554
+ */
555
+ type HonoLoggingMiddlewareOptions = {
311
556
  /**
312
- * Writes a warning message with an optional service label.
313
- * Missing service names use the shared `log` fallback label.
557
+ * Service label passed to the configured writer beside every completed request.
558
+ * Omission uses the stable `hono` label shared by the default middleware.
314
559
  */
315
- warn(message: string, service?: string): void;
560
+ service?: string;
561
+ /**
562
+ * Destination receiving each formatted request line and its resolved service label.
563
+ * Omission delegates output to the shared logging service at informational level.
564
+ */
565
+ write?: (message: string, service: string) => void;
566
+ /**
567
+ * Determines whether request bodies are cloned, normalized, and included in logs.
568
+ * Omission enables previews to preserve the established middleware behavior.
569
+ */
570
+ includeBody?: boolean;
571
+ /**
572
+ * Number of characters retained from each edge of an oversized body preview.
573
+ * Omission uses the shared logging limit and invalid values reject immediately.
574
+ */
575
+ bodyPreviewEdgeLength?: number;
316
576
  /**
317
- * Writes an error message with optional service and stack trace context.
318
- * Provided stack traces are rendered beneath the primary message.
577
+ * Header inspected for request correlation after downstream middleware completes.
578
+ * Omission uses the same default header as request identifier middleware.
319
579
  */
320
- error(message: string, service?: string, stack?: string): void;
580
+ requestIdHeader?: string;
321
581
  };
322
- //#endregion
323
- //#region src/logging/logging.utilities.d.ts
324
582
  /**
325
- * Selects a terminal color function for one HTTP response status.
326
- * Successes are green, client errors yellow, and server errors red.
583
+ * Options controlling acceptance and creation of request identifiers in Hono.
584
+ * Existing non-empty identifiers take precedence over locally generated values.
327
585
  */
328
- declare function getColoredHTTPStatus(status: number): (text: string) => string;
329
- //#endregion
330
- //#region src/upload/upload.constants.d.ts
586
+ type HonoRequestIdMiddlewareOptions = {
587
+ /**
588
+ * Header read from incoming requests and written to every outgoing response.
589
+ * Omission uses the shared `X-Request-ID` header name.
590
+ */
591
+ header?: string;
592
+ /**
593
+ * Factory invoked only when the incoming request does not carry an identifier.
594
+ * Omission generates a standards-based random UUID through the Web Crypto API.
595
+ */
596
+ createRequestId?: () => string;
597
+ };
331
598
  /**
332
- * Canonical metadata shared by upload controls and runtime validation.
333
- * Every supported format defines display, MIME, and extension values.
599
+ * Options for a typed JSON response wrapped in the shared success envelope.
600
+ * The status generic preserves the literal code inferred by the route contract.
334
601
  */
335
- declare const fileFormatsConfig: {
336
- readonly png: {
337
- readonly name: 'PNG';
338
- readonly mimeTypes: readonly ["image/png"];
339
- readonly extensions: readonly [".png"];
340
- };
341
- readonly jpg: {
342
- readonly name: 'JPG';
343
- readonly mimeTypes: readonly ["image/jpeg"];
344
- readonly extensions: readonly [".jpg", ".jpeg"];
345
- };
346
- readonly svg: {
347
- readonly name: 'SVG';
348
- readonly mimeTypes: readonly ["image/svg+xml"];
349
- readonly extensions: readonly [".svg"];
350
- };
351
- readonly webp: {
352
- readonly name: 'WEBP';
353
- readonly mimeTypes: readonly ["image/webp"];
354
- readonly extensions: readonly [".webp"];
355
- };
356
- readonly avif: {
357
- readonly name: 'AVIF';
358
- readonly mimeTypes: readonly ["image/avif"];
359
- readonly extensions: readonly [".avif"];
360
- };
361
- readonly heic: {
362
- readonly name: 'HEIC';
363
- readonly mimeTypes: readonly ["image/heic", "image/heif"];
364
- readonly extensions: readonly [".heic", ".heif"];
365
- };
366
- readonly pdf: {
367
- readonly name: 'PDF';
368
- readonly mimeTypes: readonly ["application/pdf"];
369
- readonly extensions: readonly [".pdf"];
370
- };
371
- readonly rtf: {
372
- readonly name: 'RTF';
373
- readonly mimeTypes: readonly ["application/rtf"];
374
- readonly extensions: readonly [".rtf"];
375
- };
376
- readonly txt: {
377
- readonly name: 'TXT';
378
- readonly mimeTypes: readonly ["text/plain"];
379
- readonly extensions: readonly [".txt"];
380
- };
602
+ type HonoRespondOptions<TData extends object, TStatus extends SuccessResponseStatus> = {
603
+ status: TStatus;
604
+ data?: TData;
605
+ };
606
+ /**
607
+ * Options for a downloadable binary response with attachment metadata.
608
+ * The content type remains optional and falls back to a generic binary type.
609
+ */
610
+ type HonoFileRespondOptions<TStatus extends SuccessResponseStatus> = {
611
+ status: TStatus;
612
+ content: Uint8Array<ArrayBuffer>;
613
+ filename: string;
614
+ contentType?: string;
381
615
  };
382
616
  //#endregion
383
- //#region src/upload/upload.enums.d.ts
384
- declare const fileFormatsArray: readonly ["png", "jpg", "webp", "avif", "heic", "svg", "pdf", "rtf", "txt"];
385
- type FileFormat = (typeof fileFormatsArray)[number];
386
- declare const fileFormatsRecord: Readonly<{
387
- AVIF: "avif";
388
- HEIC: "heic";
389
- JPG: "jpg";
390
- PDF: "pdf";
391
- PNG: "png";
392
- RTF: "rtf";
393
- SVG: "svg";
394
- TXT: "txt";
395
- WEBP: "webp";
396
- }>;
397
- declare const fileFormat: Readonly<{
398
- AVIF: "avif";
399
- HEIC: "heic";
400
- JPG: "jpg";
401
- PDF: "pdf";
402
- PNG: "png";
403
- RTF: "rtf";
404
- SVG: "svg";
405
- TXT: "txt";
406
- WEBP: "webp";
407
- }>;
408
- declare const uploadValidationErrorsArray: readonly ['empty_file', 'unsupported_file_format', 'file_size_exceeded', 'files_count_exceeded'];
409
- type UploadValidationError = (typeof uploadValidationErrorsArray)[number];
410
- declare const uploadValidationErrorsRecord: Readonly<{
411
- EMPTY_FILE: "empty_file";
412
- FILES_COUNT_EXCEEDED: "files_count_exceeded";
413
- FILE_SIZE_EXCEEDED: "file_size_exceeded";
414
- UNSUPPORTED_FILE_FORMAT: "unsupported_file_format";
415
- }>;
416
- declare const uploadValidationError: Readonly<{
417
- EMPTY_FILE: "empty_file";
418
- FILES_COUNT_EXCEEDED: "files_count_exceeded";
419
- FILE_SIZE_EXCEEDED: "file_size_exceeded";
420
- UNSUPPORTED_FILE_FORMAT: "unsupported_file_format";
421
- }>;
617
+ //#region src/hono/hono.execution.d.ts
618
+ /**
619
+ * Creates a Hono error handler that preserves expected machine-readable exceptions.
620
+ * Unexpected failures invoke application reporting before returning a stable fallback.
621
+ */
622
+ declare function createHonoErrorHandler(options: HonoErrorHandlerOptions): ErrorHandler;
422
623
  //#endregion
423
- //#region src/upload/upload.types.d.ts
424
- type FileFormatConfig = (typeof fileFormatsConfig)[FileFormat];
624
+ //#region src/hono/hono.logging.d.ts
425
625
  /**
426
- * Shared upload policy consumed by browser controls and backend validation.
427
- * One preset keeps format, size, capacity, and fallback rules synchronized.
626
+ * Creates Hono middleware with configurable body capture, correlation, and output.
627
+ * Sensitive values are redacted before the completed request line reaches its writer.
428
628
  */
429
- type UploadPreset<TFormats extends readonly FileFormat[] = readonly FileFormat[]> = Readonly<{
430
- /**
431
- * Supported formats accepted by every consumer of the preset.
432
- * Const inference preserves the supplied format tuple without widening.
433
- */
434
- formats: TFormats;
435
- /**
436
- * Maximum accepted size of one uploaded file measured in bytes.
437
- * Schema and client validation can share this exact numeric boundary.
438
- */
439
- maxFileSize: number;
440
- /**
441
- * Optional maximum number of files retained by one upload collection.
442
- * Single-file controls can set this value to `1` for shared capacity rules.
443
- */
444
- maxFilesCount?: number;
445
- /**
446
- * Allows extensions to compensate for absent or unreliable MIME metadata.
447
- * The fallback remains disabled when this option is omitted.
448
- */
449
- extensionFallback?: boolean;
450
- }>;
629
+ declare function createLoggingMiddleware(options?: HonoLoggingMiddlewareOptions): MiddlewareHandler;
451
630
  /**
452
- * Constraints used to validate an incoming collection of browser files.
453
- * Existing and incoming counts are combined when enforcing capacity.
631
+ * Ready-to-use Hono request logger backed by the shared default logging policy.
632
+ * Applications may use the factory when request capture or output needs configuration.
454
633
  */
455
- type UploadFilesValidationOptions = Readonly<{
456
- /**
457
- * Number of files already retained before the incoming batch is validated.
458
- * Existing entries reduce the remaining capacity without being revalidated.
459
- */
460
- currentFilesCount: number;
461
- /**
462
- * Supported formats used to validate every file in the incoming batch.
463
- * MIME and extension metadata are resolved through the canonical catalog.
464
- */
465
- formats: readonly FileFormat[];
634
+ declare const loggingMiddleware: MiddlewareHandler;
635
+ //#endregion
636
+ //#region src/hono/hono.request-id.d.ts
637
+ /**
638
+ * Resolves a request identifier from response metadata before its incoming header.
639
+ * This ordering exposes identifiers generated by the request middleware downstream.
640
+ */
641
+ declare function getHonoRequestId(context: Context, header?: string): string | undefined;
642
+ /**
643
+ * Creates middleware that preserves or generates one request correlation identifier.
644
+ * The resolved value is returned on the response and remains available to Hono adapters.
645
+ */
646
+ declare function createRequestIdMiddleware(options?: HonoRequestIdMiddlewareOptions): MiddlewareHandler;
647
+ /**
648
+ * Ready-to-use request identifier middleware backed by the shared default policy.
649
+ * Applications may use the factory when a custom header or generator is required.
650
+ */
651
+ declare const requestIdMiddleware: MiddlewareHandler;
652
+ //#endregion
653
+ //#region src/hono/hono.respond.d.ts
654
+ /**
655
+ * Wraps `c.json` in the shared success envelope while preserving its literal status.
656
+ * Missing response data is represented by an empty object for contract consistency.
657
+ */
658
+ declare function respond<TData extends object = Record<string, never>, TStatus extends SuccessResponseStatus = SuccessResponseStatus>(c: Context, options: HonoRespondOptions<TData, TStatus>): Response & TypedResponse<SuccessResponse<TData>, TStatus, 'json'>;
659
+ /**
660
+ * Responds with downloadable binary content and its attachment headers.
661
+ * Unknown/undefined content types default to `application/octet-stream`.
662
+ */
663
+ declare function fileRespond<TStatus extends SuccessResponseStatus>(c: Context, options: HonoFileRespondOptions<TStatus>): Response;
664
+ //#endregion
665
+ //#region src/jwt/jwt.constants.d.ts
666
+ /**
667
+ * Default symmetric algorithm applied to JWT signing and verification operations.
668
+ * The policy uses `HS256` unless a service instance explicitly selects another value.
669
+ */
670
+ declare const DEFAULT_JWT_ALGORITHM: SymmetricAlgorithm;
671
+ /**
672
+ * Default token lifetime applied when a signing operation supplies no override.
673
+ * The duration is expressed in seconds and represents exactly fifteen minutes.
674
+ */
675
+ declare const DEFAULT_JWT_EXPIRATION_SECONDS: number;
676
+ //#endregion
677
+ //#region src/jwt/jwt.errors.d.ts
678
+ declare const jwtErrors: {
679
+ invalidExpirationSeconds: () => RangeError;
680
+ };
681
+ type JWTErrorCode = keyof typeof jwtErrors;
682
+ //#endregion
683
+ //#region src/jwt/jwt.types.d.ts
684
+ /**
685
+ * Configures the algorithm and default expiration used by `JWTService`.
686
+ * Omitted values fall back to `HS256` and fifteen minutes respectively.
687
+ */
688
+ type JWTServiceOptions = {
466
689
  /**
467
- * Maximum accepted size of one uploaded file measured in bytes.
468
- * Files exceeding this boundary receive the stable size error key.
690
+ * Symmetric algorithm used to sign and verify every token handled by the service.
691
+ * Defaults to `HS256` when the configuration does not provide another value.
469
692
  */
470
- maxFileSize: number;
693
+ algorithm?: SymmetricAlgorithm;
471
694
  /**
472
- * Optional maximum number of retained files after accepting the batch.
473
- * Omitting this value leaves collection capacity unrestricted.
695
+ * Default lifetime assigned to signed tokens, expressed in whole seconds.
696
+ * Negative values intentionally create tokens that are already expired.
474
697
  */
475
- maxFilesCount?: number;
476
- }>;
698
+ defaultExpirationSeconds?: number;
699
+ };
477
700
  /**
478
- * Accepted files and the final rejection encountered in one batch.
479
- * Valid entries remain available when another entry fails validation.
701
+ * Configures one JWT signing operation without changing service defaults.
702
+ * A supplied expiration takes precedence over `defaultExpirationSeconds`.
480
703
  */
481
- type UploadFilesValidationResult = Readonly<{
482
- /**
483
- * Valid incoming files that fit the remaining collection capacity.
484
- * Accepted file objects preserve their original identity and ordering.
485
- */
486
- acceptedFiles: File[];
704
+ type JWTSignOptions = {
487
705
  /**
488
- * Final stable rejection encountered while processing the incoming batch.
489
- * The field remains absent when every supplied file is accepted.
706
+ * Lifetime assigned to the token created by this signing operation.
707
+ * The value overrides the service default and uses whole seconds.
490
708
  */
491
- validationError?: UploadValidationError;
492
- }>;
709
+ expiresInSeconds?: number;
710
+ };
493
711
  /**
494
- * Options used to construct one reusable Zod file schema.
495
- * Extension fallback is disabled by default to preserve strict MIME checks.
712
+ * Parses an untrusted JWT payload into the payload returned by `JWTService`.
713
+ * Zod transformations and asynchronous refinements remain part of the contract.
496
714
  */
497
- type ZodUploadFileSchemaOptions = Readonly<{
715
+ type JWTPayloadSchema<TPayload extends JWTPayload> = z.ZodType<TPayload>;
716
+ //#endregion
717
+ //#region src/jwt/jwt.services.d.ts
718
+ /**
719
+ * Signs, decodes, and verifies JWTs with optional payload schema validation.
720
+ * A supplied schema parses payloads returned by decoding and verification.
721
+ */
722
+ declare class JWTService<TPayload extends JWTPayload$1 = JWTPayload$1> {
723
+ readonly payloadSchema: JWTPayloadSchema<TPayload> | undefined;
724
+ protected readonly algorithm: SymmetricAlgorithm;
725
+ protected readonly defaultExpirationSeconds: number;
726
+ constructor(payloadSchema?: JWTPayloadSchema<TPayload>, options?: JWTServiceOptions);
498
727
  /**
499
- * Supported formats accepted by the generated file schema.
500
- * Strict MIME validation uses metadata from the canonical format catalog.
728
+ * Signs a payload using the configured algorithm and expiration settings.
729
+ * Per-operation expiration overrides the default configured by the service.
730
+ *
731
+ * @example
732
+ * const token = await jwtService.sign({ userId: '123' }, secret, { expiresInSeconds: 300 });
501
733
  */
502
- formats: readonly FileFormat[];
734
+ sign(payload: TPayload, secret: string, options?: JWTSignOptions): Promise<string>;
503
735
  /**
504
- * Maximum accepted file size measured in bytes for the generated file schema.
505
- * Empty files remain invalid independently of this configured boundary.
736
+ * Decodes a token without authentication and parses its payload when configured.
737
+ * Schema failures return `null`, while malformed token failures remain unchanged.
738
+ *
739
+ * @example
740
+ * const payload = await jwtService.decode(token);
506
741
  */
507
- maxFileSize: number;
742
+ decode(token: string): Promise<TPayload | null>;
508
743
  /**
509
- * Allows a supported extension to compensate for missing MIME metadata.
510
- * The fallback remains disabled by default to preserve strict validation.
744
+ * Verifies a token using the configured algorithm and parses its payload.
745
+ * Authentication, expiration, and schema failures reject the operation.
746
+ *
747
+ * @example
748
+ * const payload = await jwtService.verifyOrThrow(token, secret);
511
749
  */
512
- extensionFallback?: boolean;
513
- }>;
750
+ verifyOrThrow(token: string, secret: string): Promise<TPayload>;
751
+ }
514
752
  //#endregion
515
- //#region src/upload/upload.factory.d.ts
753
+ //#region src/jwt/jwt.validation.d.ts
516
754
  /**
517
- * Defines one shared upload policy while preserving its literal format tuple.
518
- * The resulting preset can drive schemas, picker hints, and batch validation.
519
- *
520
- * @example
521
- * const imageUploadPreset = defineUploadPreset({
522
- * formats: [fileFormat.JPG, fileFormat.PNG, fileFormat.WEBP],
523
- * maxFileSize: 8 * 1024 * 1024,
524
- * maxFilesCount: 1,
525
- * });
755
+ * Validates a JWT lifetime before it participates in expiration calculation.
756
+ * Whole positive, zero, and negative seconds are accepted within the safe range.
526
757
  */
527
- declare function defineUploadPreset<const TFormats extends readonly FileFormat[]>(preset: UploadPreset<TFormats>): UploadPreset<TFormats>;
758
+ declare function validateJWTExpirationSeconds(expirationSeconds: number): void;
528
759
  //#endregion
529
- //#region src/upload/upload.presets.d.ts
760
+ //#region src/logging/logging.constants.d.ts
530
761
  /**
531
- * Default maximum size of one file accepted by the built-in upload presets.
532
- * The 20 MiB boundary matches the existing upload component policy.
762
+ * Terminal color configuration for every supported logging level.
763
+ * The `LogLevel` contract prevents missing or unsupported level entries.
533
764
  */
534
- declare const DEFAULT_UPLOAD_MAX_FILE_SIZE: number;
765
+ declare const logLevelColors: {
766
+ readonly info: typeof import("kleur/colors").print;
767
+ readonly warn: typeof import("kleur/colors").print;
768
+ readonly error: typeof import("kleur/colors").print;
769
+ };
535
770
  /**
536
- * Ready-to-use policy for every image format supported by the upload catalog.
537
- * Each image may occupy up to 20 MiB while collection capacity remains unrestricted.
771
+ * Public placeholder written instead of sensitive query and JSON values.
772
+ * One stable marker keeps redacted output recognizable across log consumers.
538
773
  */
539
- declare const imageUploadPreset: Readonly<{
540
- formats: readonly ["png", "jpg", "webp", "avif", "heic"];
541
- maxFileSize: number;
542
- maxFilesCount?: number;
543
- extensionFallback?: boolean;
544
- }>;
774
+ declare const REDACTED_LOG_VALUE = "[redacted]";
545
775
  /**
546
- * Ready-to-use policy for every image format supporting transparency (alpha channel).
547
- * Each image may occupy up to 20 MiB while collection capacity remains unrestricted.
776
+ * Number of characters retained from each edge of an oversized request body.
777
+ * The complete preview includes both edges separated by one explicit ellipsis.
548
778
  */
549
- declare const imageTransparentUploadPreset: Readonly<{
550
- formats: readonly ["png", "webp", "svg"];
551
- maxFileSize: number;
552
- maxFilesCount?: number;
553
- extensionFallback?: boolean;
554
- }>;
779
+ declare const LOG_BODY_PREVIEW_EDGE_LENGTH = 30;
555
780
  /**
556
- * Ready-to-use policy for every document format supported by the upload catalog.
557
- * Each document may occupy up to 20 MiB while collection capacity remains unrestricted.
781
+ * Safe request-body placeholder emitted instead of reading multipart content.
782
+ * Avoiding multipart reads prevents file payloads from entering logs or memory copies.
558
783
  */
559
- declare const documentUploadPreset: Readonly<{
560
- formats: readonly ["pdf", "rtf", "txt"];
561
- maxFileSize: number;
562
- maxFilesCount?: number;
563
- extensionFallback?: boolean;
564
- }>;
565
- //#endregion
566
- //#region src/upload/upload.schemas.d.ts
784
+ declare const MULTIPART_LOG_BODY = "[multipart]";
567
785
  /**
568
- * Builds a reusable Zod schema for one uploaded file with format and size.
569
- * MIME matching is strict unless extension fallback is explicitly enabled.
786
+ * Normalized key fragments treated as sensitive by logging redaction.
787
+ * Matching ignores case and separators so compound field names remain covered.
570
788
  */
571
- declare function zodUploadFileSchema(options: ZodUploadFileSchemaOptions): z$1.ZodFile;
789
+ declare const sensitiveLogKeyParts: readonly ['password', 'passwd', 'token', 'secret', 'authorization', 'apikey', 'credential'];
790
+ /**
791
+ * Terminal colors assigned to the supported HTTP response status ranges.
792
+ * Unlisted ranges intentionally retain the terminal's default text appearance.
793
+ */
794
+ declare const httpStatusColors: readonly [{
795
+ readonly range: readonly [200, 299];
796
+ readonly color: typeof import("kleur/colors").print;
797
+ }, {
798
+ readonly range: readonly [400, 499];
799
+ readonly color: typeof import("kleur/colors").print;
800
+ }, {
801
+ readonly range: readonly [500, 599];
802
+ readonly color: typeof import("kleur/colors").print;
803
+ }];
572
804
  //#endregion
573
- //#region src/upload/upload.utilities.d.ts
805
+ //#region src/logging/logging.enums.d.ts
806
+ declare const logLevelsArray: readonly ['info', 'warn', 'error'];
807
+ type LogLevel = (typeof logLevelsArray)[number];
808
+ declare const logLevelsRecord: Readonly<{
809
+ ERROR: "error";
810
+ INFO: "info";
811
+ WARN: "warn";
812
+ }>;
813
+ declare const logLevel: Readonly<{
814
+ ERROR: "error";
815
+ INFO: "info";
816
+ WARN: "warn";
817
+ }>;
818
+ //#endregion
819
+ //#region src/logging/logging.errors.d.ts
820
+ declare const loggingErrors: {
821
+ invalidBodyPreviewEdgeLength: () => RangeError;
822
+ };
823
+ type LoggingErrorCode = keyof typeof loggingErrors;
824
+ //#endregion
825
+ //#region src/logging/logging.security.d.ts
574
826
  /**
575
- * Extracts a normalized trailing extension from a complete file name.
576
- * Returns an empty string when no valid dot-delimited suffix exists.
827
+ * Recursively replaces values owned by sensitive keys in an arbitrary structure.
828
+ * Arrays and safe values retain their original ordering and primitive identity.
577
829
  */
578
- declare function getFileExtension(fileName: string): string;
830
+ declare function redactSensitiveValue(value: unknown): unknown;
579
831
  /**
580
- * Normalizes a configured extension to a lowercase dot-prefixed value.
581
- * Existing prefixes remain intact so repeated normalization is stable.
832
+ * Replaces sensitive query values using partial, case-insensitive key matching.
833
+ * A new collection is returned so the caller's search parameters remain unchanged.
582
834
  */
583
- declare function normalizeFileExtension(extension: string): string;
835
+ declare function redactSensitiveSearchParams(searchParams: URLSearchParams): URLSearchParams;
584
836
  /**
585
- * Compares a concrete MIME type with an exact or wildcard configuration.
586
- * Wildcards match every subtype belonging to the configured media group.
837
+ * Replaces values under sensitive keys throughout a serialized JSON structure.
838
+ * Invalid JSON and payloads without matching keys are returned byte-for-byte unchanged.
587
839
  */
588
- declare function matchesMimeType(fileMimeType: string, configuredMimeType: string): boolean;
840
+ declare function redactSensitiveJSON(json: string): string;
841
+ //#endregion
842
+ //#region src/logging/logging.types.d.ts
589
843
  /**
590
- * Checks whether a file MIME type belongs to one selected format.
591
- * File names and extensions cannot make an unsupported MIME type valid.
844
+ * Receives one completely formatted logging line for final output or collection.
845
+ * Implementations control the destination without changing formatting behavior.
592
846
  */
593
- declare function isFileMimeTypeSupported(file: File, formats: readonly FileFormat[]): boolean;
847
+ type LogSink = (line: string) => void;
594
848
  /**
595
- * Checks whether a file extension belongs to one selected format.
596
- * The comparison is case-insensitive and requires a complete suffix.
849
+ * Logger bound to one service label and one configured output destination.
850
+ * Every method preserves the shared timestamp, level, and trace formatting.
597
851
  */
598
- declare function isFileExtensionSupported(file: File, formats: readonly FileFormat[]): boolean;
852
+ type ScopedLogger = {
853
+ info: (message: string) => void;
854
+ warn: (message: string) => void;
855
+ error: (message: string, error?: unknown) => void;
856
+ };
599
857
  /**
600
- * Checks whether a file matches one configured MIME type or extension.
601
- * This permissive predicate supports clients where MIME metadata is absent.
858
+ * Options used to bind a logger to one service and output destination.
859
+ * The default sink writes every fully formatted line through `console.log`.
602
860
  */
603
- declare function isFileFormatSupported(file: File, formats: readonly FileFormat[]): boolean;
861
+ type CreateLoggerOptions = {
862
+ /**
863
+ * Stable service label displayed beside every message from the logger.
864
+ * Short labels retain the shared terminal column alignment automatically.
865
+ */
866
+ service: string;
867
+ /**
868
+ * Optional destination receiving each completely formatted output line.
869
+ * Omission preserves the standard console-backed logging behavior.
870
+ */
871
+ sink?: LogSink;
872
+ };
604
873
  /**
605
- * Builds a native file-picker hint from configured MIME types and extensions.
606
- * Duplicate values are removed while their configuration order is retained.
874
+ * Structured values required to format one completed HTTP request log entry.
875
+ * Optional query and body previews disappear when their normalized values are empty.
607
876
  */
608
- declare function createUploadAccept(formats: readonly FileFormat[]): string;
877
+ type HTTPRequestLogOptions = {
878
+ /**
879
+ * HTTP method associated with the completed request.
880
+ * Formatting reserves a stable terminal column for its value.
881
+ */
882
+ method: string;
883
+ /**
884
+ * Final HTTP status observed after downstream request handling.
885
+ * Its numeric range determines the terminal color applied to the value.
886
+ */
887
+ status: number;
888
+ /**
889
+ * Completed request-processing duration expressed in milliseconds.
890
+ * Formatting expects the value to be rounded before it reaches this boundary.
891
+ */
892
+ duration: number;
893
+ /**
894
+ * Request pathname displayed without serialized query parameters.
895
+ * Formatting reserves a stable terminal column for its value.
896
+ */
897
+ path: string;
898
+ /**
899
+ * Optional redacted query representation without the leading question mark.
900
+ * Empty and omitted values do not produce a suffix in the formatted line.
901
+ */
902
+ searchParams?: string;
903
+ /**
904
+ * Optional normalized, redacted, and length-limited request body preview.
905
+ * Empty and omitted values do not produce a suffix in the formatted line.
906
+ */
907
+ bodyPreview?: string;
908
+ /**
909
+ * Optional identifier correlating this request with downstream logs and reports.
910
+ * Empty and omitted values do not produce a suffix in the formatted line.
911
+ */
912
+ requestId?: string;
913
+ };
609
914
  //#endregion
610
- //#region src/upload/upload.validation.d.ts
915
+ //#region src/logging/logging.services.d.ts
611
916
  /**
612
- * Validates one file against configured format and size constraints.
613
- * Returns the first stable error key or nothing for a valid file.
917
+ * Creates a logger permanently bound to one service label and output destination.
918
+ * Calls retain the shared formatting while avoiding repeated service arguments.
614
919
  */
615
- declare function validateUploadFile(file: File, formats: readonly FileFormat[], maxFileSize: number): UploadValidationError | undefined;
920
+ declare function createLogger(options: CreateLoggerOptions): ScopedLogger;
616
921
  /**
617
- * Validates an incoming collection while preserving every accepted file.
618
- * Returns accepted entries and the final rejection key from the batch.
922
+ * Writes timestamped and colorized messages using a stable service column.
923
+ * Error messages may include a stack trace on a subordinate second line.
619
924
  */
620
- declare function validateUploadFiles(incomingFiles: readonly File[], options: UploadFilesValidationOptions): UploadFilesValidationResult;
925
+ declare const log: {
926
+ /**
927
+ * Writes an informational message with an optional service label.
928
+ * Missing service names use the shared `log` fallback label.
929
+ */
930
+ info(message: string, service?: string): void;
931
+ /**
932
+ * Writes a warning message with an optional service label.
933
+ * Missing service names use the shared `log` fallback label.
934
+ */
935
+ warn(message: string, service?: string): void;
936
+ /**
937
+ * Writes an error message with optional service and unknown failure context.
938
+ * Native errors and strings render a normalized subordinate trace line.
939
+ */
940
+ error(message: string, service?: string, error?: unknown): void;
941
+ };
621
942
  //#endregion
622
- //#region src/utilities/datetime.utilities.d.ts
943
+ //#region src/logging/logging.utilities.d.ts
623
944
  /**
624
- * Projects the current instant onto the wall-clock fields of another timezone.
625
- * The timezone defaults to `Europe/London` when no option is provided.
626
- *
627
- * @example
628
- * const londonTime = getZonedTime({ tz: 'Europe/London' });
945
+ * Extracts useful trace context from an unknown failure without inventing a message.
946
+ * Strings pass through directly, while native errors prefer their complete stack.
629
947
  */
630
- declare function getZonedTime({ tz }?: {
631
- tz?: string;
632
- }): Date;
948
+ declare function normalizeLogError(error: unknown): string | undefined;
633
949
  /**
634
- * Formats the UTC offset of a timezone at the supplied date.
635
- * An explicit date preserves daylight-saving and historical offset rules.
636
- *
637
- * @example
638
- * getUTCOffset(date, 'Europe/Moscow'); // `(+3 UTC)`
950
+ * Selects a terminal color function for one HTTP response status.
951
+ * Successes are green, client errors yellow, and server errors red.
639
952
  */
640
- declare function getUTCOffset(date: Date, tz: string): string;
953
+ declare function getColoredHTTPStatus(status: number): (text: string) => string;
641
954
  /**
642
- * Formats the current time and UTC offset in the selected timezone.
643
- * The timezone defaults to `Europe/London` when no option is provided.
644
- *
645
- * @example
646
- * getFormattedTime({ tz: 'Europe/Moscow' }); // `03:04:05 (+3 UTC)`
955
+ * Formats one completed HTTP request as a compact colorized terminal line.
956
+ * Empty query and body values are omitted without disturbing column alignment.
647
957
  */
648
- declare function getFormattedTime({ tz }?: {
649
- tz?: string;
650
- }): string;
958
+ declare function formatHTTPRequestLog(options: HTTPRequestLogOptions): string;
651
959
  /**
652
- * Formats the current date with optional time and UTC offset components.
653
- * Time is included by default and uses the selected timezone for display.
654
- *
655
- * @example
656
- * getFormattedDate({ tz: 'UTC', withTime: false }); // `02.01.2024`
960
+ * Reads one request clone and returns a normalized, redacted, and bounded body preview.
961
+ * Multipart requests return a safe marker without reading or retaining uploaded content.
657
962
  */
658
- declare function getFormattedDate({ tz, withTime }?: {
659
- tz?: string;
660
- withTime?: boolean;
661
- }): string;
963
+ declare function createHTTPRequestBodyPreview(request: Request, contentType?: string, edgeLength?: number): Promise<string>;
964
+ //#endregion
965
+ //#region src/object/object.utilities.d.ts
662
966
  /**
663
- * Formats an explicit instant in another timezone using the selected locale.
664
- * The result includes localized date text, wall-clock time, and UTC offset.
967
+ * Recognizes ordinary records whose direct prototype is `Object.prototype`.
968
+ * Arrays, null, native objects, and custom class instances remain excluded.
969
+ */
970
+ declare function isPlainObject(value: unknown): value is Record<string, unknown>;
971
+ //#endregion
972
+ //#region src/random/random.errors.d.ts
973
+ declare const randomErrors: {
974
+ invalidRandomStringLength: () => RangeError;
975
+ };
976
+ type RandomErrorCode = keyof typeof randomErrors;
977
+ //#endregion
978
+ //#region src/random/random.utilities.d.ts
979
+ /**
980
+ * Creates a cryptographically sourced string from the alphanumeric collection.
981
+ * Rejection sampling prevents modulo bias while bounded batches support long output.
665
982
  *
666
983
  * @example
667
- * formatTime(date, { locale: ru, tz: 'Europe/Moscow' });
984
+ * generateRandomString(5); // `aZ3fG`
985
+ * generateRandomString(); // `G5kLm2P9sQ`
668
986
  */
669
- declare function formatTime(time: Date, { locale, tz }?: {
670
- locale?: Locale;
671
- tz?: string;
672
- }): string;
987
+ declare function generateRandomString(length?: number): string;
673
988
  //#endregion
674
- //#region src/utilities/encoding.utilities.d.ts
989
+ //#region src/random/random.validation.d.ts
675
990
  /**
676
- * Encodes arbitrary binary bytes into their canonical Base64 representation.
677
- * Chunked conversion avoids the argument limit imposed by `String.fromCharCode`.
991
+ * Validates the requested random-string length before allocating random bytes.
992
+ * Only non-negative safe integers can represent a complete output character count.
678
993
  */
679
- declare function encodeBase64(bytes: Uint8Array): string;
994
+ declare function assertRandomStringLength(length: number): void;
995
+ //#endregion
996
+ //#region src/random/random.constants.d.ts
680
997
  /**
681
- * Decodes a canonical or padded Base64 string into its original binary bytes.
682
- * Invalid input preserves the native `atob` failure instead of returning partial data.
998
+ * Alphanumeric character collection used by the default random-string generator.
999
+ * Its fixed ordering keeps byte-to-character translation stable across runtimes.
683
1000
  */
684
- declare function decodeBase64(value: string): Uint8Array<ArrayBuffer>;
1001
+ declare const RANDOM_ALPHANUMERIC_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1002
+ /**
1003
+ * Default output length used when `generateRandomString` receives no override.
1004
+ * Ten characters preserve the historical package contract for existing consumers.
1005
+ */
1006
+ declare const DEFAULT_RANDOM_STRING_LENGTH = 10;
1007
+ /**
1008
+ * Maximum random-byte count requested from Web Crypto in one operation.
1009
+ * The boundary follows the platform limit enforced by `crypto.getRandomValues`.
1010
+ */
1011
+ declare const RANDOM_BYTE_BATCH_SIZE = 65536;
685
1012
  //#endregion
686
- //#region src/utilities/enums.utilities.d.ts
1013
+ //#region src/string-enum/string-enum.types.d.ts
687
1014
  /**
688
1015
  * Recursively replaces dots in a string literal with underscores.
689
1016
  * Every other character remains unchanged in the resulting literal type.
@@ -691,7 +1018,7 @@ declare function decodeBase64(value: string): Uint8Array<ArrayBuffer>;
691
1018
  * @example
692
1019
  * type Key = ReplaceDotsWithUnderscores<'foo.bar.baz'>; // `foo_bar_baz`
693
1020
  */
694
- type ReplaceDotsWithUnderscores<TValue extends string> = TValue extends `${infer Head}.${infer Tail}` ? `${ReplaceDotsWithUnderscores<Head>}_${ReplaceDotsWithUnderscores<Tail>}` : TValue;
1021
+ type ReplaceDotsWithUnderscores<TValue extends string> = TValue extends `${infer THead}.${infer TTail}` ? `${ReplaceDotsWithUnderscores<THead>}_${ReplaceDotsWithUnderscores<TTail>}` : TValue;
695
1022
  /**
696
1023
  * Recursively replaces hyphens in a string literal with underscores.
697
1024
  * Every other character remains unchanged in the resulting literal type.
@@ -699,387 +1026,262 @@ type ReplaceDotsWithUnderscores<TValue extends string> = TValue extends `${infer
699
1026
  * @example
700
1027
  * type Key = ReplaceHyphensWithUnderscores<'foo-bar-baz'>; // `foo_bar_baz`
701
1028
  */
702
- type ReplaceHyphensWithUnderscores<TValue extends string> = TValue extends `${infer Head}-${infer Tail}` ? `${ReplaceHyphensWithUnderscores<Head>}_${ReplaceHyphensWithUnderscores<Tail>}` : TValue;
1029
+ type ReplaceHyphensWithUnderscores<TValue extends string> = TValue extends `${infer THead}-${infer TTail}` ? `${ReplaceHyphensWithUnderscores<THead>}_${ReplaceHyphensWithUnderscores<TTail>}` : TValue;
1030
+ /**
1031
+ * Inserts underscores at lowercase-to-uppercase boundaries in a string literal.
1032
+ * Existing separators reset boundary tracking while consecutive capitals remain grouped.
1033
+ */
1034
+ type SeparateCamelCase<TValue extends string, TPreviousWasLowercase extends boolean = false> = TValue extends `${infer TCharacter}${infer TRest}` ? TCharacter extends '.' | '-' ? `${TCharacter}${SeparateCamelCase<TRest>}` : TCharacter extends Lowercase<TCharacter> ? `${TCharacter}${SeparateCamelCase<TRest, true>}` : TPreviousWasLowercase extends true ? `_${TCharacter}${SeparateCamelCase<TRest>}` : `${TCharacter}${SeparateCamelCase<TRest>}` : TValue;
1035
+ /**
1036
+ * Converts one supported string literal into its uppercase enum-record key.
1037
+ * CamelCase boundaries, dots, and hyphens consistently become underscores.
1038
+ */
1039
+ type StringEnumKey<TValue extends string> = Uppercase<ReplaceHyphensWithUnderscores<ReplaceDotsWithUnderscores<SeparateCamelCase<TValue>>>>;
703
1040
  /**
704
- * Maps string literals to immutable uppercase enum-like keys.
705
- * Dots and hyphens become underscores while values preserve their original literals.
1041
+ * Maps a readonly string-literal collection into an immutable enum-like record.
1042
+ * Normalized uppercase keys retain their original source literals as record values.
706
1043
  *
707
1044
  * @example
708
1045
  * type Statuses = StringEnumRecord<readonly ['review.pending', 'published']>;
709
1046
  */
710
- type StringEnumRecord<TValues extends readonly string[]> = Readonly<{ [Value in TValues[number] as Uppercase<ReplaceHyphensWithUnderscores<ReplaceDotsWithUnderscores<Value>>>]: Value; }>;
1047
+ type StringEnumRecord<TValues extends readonly string[]> = Readonly<{ [TValue in TValues[number] as StringEnumKey<TValue>]: TValue; }>;
1048
+ //#endregion
1049
+ //#region src/string-enum/string-enum.utilities.d.ts
711
1050
  /**
712
1051
  * Creates an immutable enum-like record from a readonly string array.
713
- * Keys are uppercased and every dot or hyphen is replaced with an underscore.
1052
+ * Keys become upper snake case across camelCase, dotted, and hyphenated values.
714
1053
  *
715
1054
  * @example
716
1055
  * createStringEnumRecord(['foo-bar.s', 'baz'] as const); // `{ FOO_BAR_S: 'foo-bar.s', BAZ: 'baz' }`
717
1056
  */
718
- declare function createStringEnumRecord<const T extends readonly string[]>(values: T): StringEnumRecord<T>;
1057
+ declare function createStringEnumRecord<const TValues extends readonly string[]>(values: TValues): StringEnumRecord<TValues>;
719
1058
  //#endregion
720
- //#region src/utilities/execution.utilities.d.ts
1059
+ //#region src/type/type.utilities.d.ts
721
1060
  /**
722
- * Resolves synchronous and asynchronous executions through one promise-based contract.
723
- * Failures use the supplied fallback or propagate unchanged when none is available.
1061
+ * Flattens an intersection or mapped type into one readable object shape.
1062
+ * Property modifiers remain unchanged while editor output becomes easier to inspect.
724
1063
  *
725
1064
  * @example
726
- * await safeExecute(() => fetchData(), (error) => console.error(error));
1065
+ * type User = Simplify<{ id: string } & { email: string }>;
727
1066
  */
728
- declare function safeExecute<T, E = never>(fn: () => Promise<T> | T, onError?: (error: unknown) => E | Promise<E>): Promise<T | E>;
729
- /**
730
- * Result returned after measuring one successful asynchronous execution.
731
- * The original value is preserved beside its rounded millisecond duration.
732
- */
733
- type MeasuredExecution<T> = {
734
- /**
735
- * Value resolved by the measured execution without cloning or transformation.
736
- * Its generic type remains identical to the original asynchronous result.
737
- */
738
- result: T;
739
- /**
740
- * Rounded wall-clock duration of the measured execution in milliseconds.
741
- * The value is always collected after the supplied promise resolves.
742
- */
743
- executionTime: number;
744
- };
1067
+ type Simplify<TValue> = { [TKey in keyof TValue]: TValue[TKey]; } & {};
745
1068
  /**
746
- * Measures an asynchronous execution while preserving its resolved result.
747
- * Rejected executions propagate unchanged and do not produce a measurement.
1069
+ * Builds a union whose branches retain one selected property and forbid every other selected key.
1070
+ * Each flattened branch preserves the selected property's original value type and optionality.
748
1071
  *
749
1072
  * @example
750
- * const { result, executionTime } = await measureExecutionTime(async () => {
751
- * return await fetchData();
752
- * });
753
- * console.log(`Execution time: ${executionTime}ms`);
1073
+ * type UserSelector = ExactlyOne<{ id: string; email: string }, 'id' | 'email'>;
754
1074
  */
755
- declare function measureExecutionTime<T>(execution: () => Promise<T>): Promise<MeasuredExecution<T>>;
756
- //#endregion
757
- //#region src/utilities/generation.utilities.d.ts
1075
+ type ExactlyOne<TEntity, TKeys extends keyof TEntity> = { [TKey in TKeys]: Simplify<Pick<TEntity, TKey> & Partial<Record<Exclude<TKeys, TKey>, never>>>; }[TKeys];
758
1076
  /**
759
- * Creates a cryptographically sourced string from the alphanumeric set.
760
- * Requested length defaults to `10` characters when omitted.
1077
+ * Builds a union whose branches require one selected property while preserving every remaining property.
1078
+ * Additional selected properties may coexist, but at least one must hold its concrete declared value.
761
1079
  *
762
1080
  * @example
763
- * generateRandomString(5); // `aZ3fG`
764
- * generateRandomString(); // `G5kLm2P9sQ`
1081
+ * type UserPatch = AtLeastOne<{ email?: string; fullName?: string }>;
765
1082
  */
766
- declare function generateRandomString(length?: number): string;
1083
+ type AtLeastOne<TEntity, TKeys extends keyof TEntity = keyof TEntity> = TKeys extends keyof TEntity ? Simplify<Required<Pick<TEntity, TKeys>> & Partial<Omit<TEntity, TKeys>>> : never;
767
1084
  //#endregion
768
- //#region src/utilities/type.utilities.d.ts
769
- /**
770
- * Utility type that simplifies a given type T by flattening its structure.
771
- * This is particularly useful for improving the readability of complex types.
772
- */
773
- type Simplify<T> = { [K in keyof T]: T[K]; } & {};
1085
+ //#region src/upload/upload.enums.d.ts
1086
+ declare const uploadValidationErrorsArray: readonly ['emptyFile', 'unsupportedFileFormat', 'fileSizeExceeded', 'filesCountExceeded'];
1087
+ type UploadValidationError = (typeof uploadValidationErrorsArray)[number];
1088
+ declare const uploadValidationErrorsRecord: Readonly<{
1089
+ EMPTY_FILE: "emptyFile";
1090
+ FILES_COUNT_EXCEEDED: "filesCountExceeded";
1091
+ FILE_SIZE_EXCEEDED: "fileSizeExceeded";
1092
+ UNSUPPORTED_FILE_FORMAT: "unsupportedFileFormat";
1093
+ }>;
1094
+ declare const uploadValidationError: Readonly<{
1095
+ EMPTY_FILE: "emptyFile";
1096
+ FILES_COUNT_EXCEEDED: "filesCountExceeded";
1097
+ FILE_SIZE_EXCEEDED: "fileSizeExceeded";
1098
+ UNSUPPORTED_FILE_FORMAT: "unsupportedFileFormat";
1099
+ }>;
1100
+ //#endregion
1101
+ //#region src/upload/upload.errors.d.ts
1102
+ declare const uploadErrors: {
1103
+ uploadFormatRequired: () => TypeError;
1104
+ invalidMimeType: () => TypeError;
1105
+ invalidFileExtension: () => TypeError;
1106
+ invalidMaxFileSize: () => RangeError;
1107
+ invalidMaxFilesCount: () => RangeError;
1108
+ invalidCurrentFilesCount: () => RangeError;
1109
+ };
1110
+ type UploadErrorCode = keyof typeof uploadErrors;
774
1111
  //#endregion
775
- //#region src/zod-bulk/zod-bulk.schemas.d.ts
1112
+ //#region src/upload/upload.types.d.ts
776
1113
  /**
777
- * Builds a strict selection contract for bulk operations across paginated data.
778
- * The identifier schema is shared by explicit and all-matching selection modes.
779
- *
780
- * `include` targets only identifiers listed by the client. `exclude` targets every
781
- * item matching the accompanying search snapshot except excluded identifiers.
782
- *
783
- * @example
784
- * const assetBulkSelectionSchema = zodBulkSelectionSchema({
785
- * identifierSchema: z.string().min(1),
786
- * });
1114
+ * Transport metadata describing one file format accepted by an upload policy.
1115
+ * MIME types and extension collections remain application-owned literal values.
787
1116
  */
788
- declare function zodBulkSelectionSchema<const TIdentifierSchema extends z$1.ZodType<string | number>>({ identifierSchema }: {
1117
+ type UploadFormat = Readonly<{
789
1118
  /**
790
- * Schema used to validate every included or excluded entity identifier.
791
- * Its transforms and exact inferred output are preserved in both branches.
1119
+ * MIME types accepted for files belonging to this format.
1120
+ * Exact values and complete media wildcards such as `image/*` are supported.
792
1121
  */
793
- identifierSchema: TIdentifierSchema;
794
- }): z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
795
- mode: z$1.ZodLiteral<"include">;
796
- identifiers: z$1.ZodArray<TIdentifierSchema>;
797
- }, z$1.core.$strict>, z$1.ZodObject<{
798
- mode: z$1.ZodLiteral<"exclude">;
799
- excludedIdentifiers: z$1.ZodArray<TIdentifierSchema>;
800
- }, z$1.core.$strict>], "mode">;
801
- //#endregion
802
- //#region src/zod-bulk/zod-bulk.types.d.ts
803
- /**
804
- * Shared bulk-selection payload produced by `zodBulkSelectionSchema`.
805
- * String identifiers are used by default for frontend table integrations.
806
- */
807
- type ZodBulkSelection<TIdentifier extends string | number = string> = z.infer<ReturnType<typeof zodBulkSelectionSchema<z.ZodType<TIdentifier>>>>;
808
- /**
809
- * Explicit bulk selection containing only identifiers chosen by the client.
810
- * This branch does not require resolving an all-matching search snapshot.
811
- */
812
- type ZodBulkIncludeSelection<TIdentifier extends string | number = string> = Extract<ZodBulkSelection<TIdentifier>, {
813
- mode: 'include';
1122
+ mimeTypes: readonly string[];
1123
+ /**
1124
+ * File extensions accepted when an upload policy enables extension fallback.
1125
+ * Values may include or omit their dot prefix and are matched case-insensitively.
1126
+ */
1127
+ extensions: readonly string[];
814
1128
  }>;
815
1129
  /**
816
- * All-matching bulk selection containing identifiers excluded by the client.
817
- * Backend handlers must resolve targets from the same search snapshot.
1130
+ * Format matching policy shared by predicates and complete file validation.
1131
+ * Extension fallback remains disabled so MIME metadata is authoritative by default.
818
1132
  */
819
- type ZodBulkExcludeSelection<TIdentifier extends string | number = string> = Extract<ZodBulkSelection<TIdentifier>, {
820
- mode: 'exclude';
821
- }>;
822
- //#endregion
823
- //#region src/zod-jwt/zod-jwt.types.d.ts
824
- /**
825
- * Configures the algorithm and default expiration used by `ZodJWTService`.
826
- * Omitted values fall back to `HS256` and fifteen minutes respectively.
827
- */
828
- type JWTServiceOptions = {
1133
+ type UploadFormatValidationOptions<TFormats extends readonly UploadFormat[] = readonly UploadFormat[]> = Readonly<{
829
1134
  /**
830
- * Symmetric algorithm used to sign and verify every token handled by the service.
831
- * Defaults to `HS256` when the configuration does not provide another value.
1135
+ * Format definitions accepted by this validation boundary.
1136
+ * Literal tuples remain available to consumers that define narrower policies.
832
1137
  */
833
- algorithm?: SymmetricAlgorithm;
1138
+ formats: TFormats;
834
1139
  /**
835
- * Default lifetime assigned to signed tokens, expressed in seconds.
836
- * Defaults to `900` seconds, which is equivalent to fifteen minutes.
1140
+ * Allows extensions to compensate for absent or unreliable MIME metadata.
1141
+ * Omission preserves strict MIME validation across every adapter.
837
1142
  */
838
- defaultExpirationSeconds?: number;
839
- };
1143
+ extensionFallback?: boolean;
1144
+ }>;
840
1145
  /**
841
- * Configures one JWT signing operation without changing service defaults.
842
- * A supplied expiration takes precedence over `defaultExpirationSeconds`.
1146
+ * Constraints used to validate one browser file independently of collection capacity.
1147
+ * Empty files remain invalid independently of the configured maximum size boundary.
843
1148
  */
844
- type JWTSignOptions = {
1149
+ type UploadFileValidationOptions<TFormats extends readonly UploadFormat[] = readonly UploadFormat[]> = Simplify<UploadFormatValidationOptions<TFormats> & Readonly<{
845
1150
  /**
846
- * Lifetime assigned to the token created by this signing operation.
847
- * Overrides the service default and remains expressed in seconds.
1151
+ * Maximum accepted size of one uploaded file measured in bytes.
1152
+ * The boundary must be a non-negative integer number of bytes.
848
1153
  */
849
- expiresInSeconds?: number;
850
- };
851
- /**
852
- * Resolves the parsed payload of a Zod schema or preserves a direct payload type.
853
- * Schema transforms are reflected in the resulting inferred payload.
854
- */
855
- type Payload<T> = T extends z.ZodType ? z.infer<T> : T;
1154
+ maxFileSize: number;
1155
+ }>>;
856
1156
  /**
857
- * Preserves a Zod payload schema and rejects direct payload types with `never`.
858
- * The result controls whether runtime payload validation is available.
1157
+ * Shared upload policy consumed by browser controls and backend validation.
1158
+ * One preset keeps format, size, capacity, and fallback rules synchronized.
859
1159
  */
860
- type PayloadSchema<T> = T extends z.ZodType ? T : never;
861
- //#endregion
862
- //#region src/zod-jwt/zod-jwt.services.d.ts
1160
+ type UploadPreset<TFormats extends readonly UploadFormat[] = readonly UploadFormat[]> = Simplify<UploadFileValidationOptions<TFormats> & Readonly<{
1161
+ /**
1162
+ * Optional maximum number of files retained by one upload collection.
1163
+ * Single-file controls can set this value to `1` for shared capacity rules.
1164
+ */
1165
+ maxFilesCount?: number;
1166
+ }>>;
863
1167
  /**
864
- * Signs, decodes, and verifies JWTs with optional Zod payload validation.
865
- * A supplied schema parses payloads returned by decoding and verification.
1168
+ * Constraints used to validate an incoming collection of browser files.
1169
+ * Existing and incoming counts are combined when enforcing capacity.
866
1170
  */
867
- declare class ZodJWTService<TPayloadOrSchema> {
868
- readonly payloadSchema: PayloadSchema<TPayloadOrSchema> | undefined;
869
- protected readonly algorithm: SymmetricAlgorithm;
870
- protected readonly defaultExpirationSeconds: number;
871
- constructor(payloadSchema?: PayloadSchema<TPayloadOrSchema>, options?: JWTServiceOptions);
1171
+ type UploadFilesValidationOptions = Simplify<UploadPreset & Readonly<{
872
1172
  /**
873
- * Signs a payload using the configured algorithm and expiration settings.
874
- * Per-call expiration overrides the default configured by the service.
875
- *
876
- * @example
877
- * const token = await jwtService.sign({ userId: '123' }, secret, { expiresInSeconds: 300 });
1173
+ * Number of files already retained before the incoming batch is validated.
1174
+ * Existing entries reduce the remaining capacity without being revalidated.
878
1175
  */
879
- sign(payload: Payload<TPayloadOrSchema>, secret: string, options?: JWTSignOptions): Promise<string>;
1176
+ currentFilesCount: number;
1177
+ }>>;
1178
+ /**
1179
+ * Accepted files and the first rejection encountered in one batch.
1180
+ * Valid entries remain available when another entry fails validation.
1181
+ */
1182
+ type UploadFilesValidationResult = Readonly<{
880
1183
  /**
881
- * Decodes without authenticating it and parses its payload when a schema exists.
882
- * Schema validation failures return `null`, while malformed tokens still reject.
883
- *
884
- * @example
885
- * const payload = await jwtService.decode(token);
1184
+ * Valid incoming files that fit the remaining collection capacity.
1185
+ * File objects preserve their identity and ordering through a readonly view.
886
1186
  */
887
- decode(token: string): Promise<Payload<TPayloadOrSchema> | null>;
1187
+ acceptedFiles: readonly File[];
888
1188
  /**
889
- * Verifies a token using the configured algorithm and parses its payload.
890
- * Signature, expiration, and schema validation failures reject the operation.
891
- *
892
- * @example
893
- * const payload = await jwtService.verifyOrThrow(token, secret);
1189
+ * First stable rejection encountered while processing the incoming batch.
1190
+ * The field remains absent when every supplied file is accepted.
894
1191
  */
895
- verifyOrThrow(token: string, secret: string): Promise<Payload<TPayloadOrSchema>>;
896
- }
1192
+ validationError?: UploadValidationError;
1193
+ }>;
897
1194
  //#endregion
898
- //#region src/zod-search/zod-search.pagination.schemas.d.ts
1195
+ //#region src/upload/upload.factory.d.ts
899
1196
  /**
900
- * Validates offset-based pagination shared by search request contracts.
901
- * Missing fields inside the required object receive predictable defaults.
1197
+ * Validates one upload format before it becomes part of a reusable policy.
1198
+ * Accepts MIME-only and extension-only definitions while rejecting malformed values.
902
1199
  */
903
- declare const zodPaginationSchema: z$1.ZodObject<{
904
- offset: z$1.ZodDefault<z$1.ZodCoercedNumber<unknown>>;
905
- limit: z$1.ZodDefault<z$1.ZodCoercedNumber<unknown>>;
906
- }, z$1.core.$strip>;
1200
+ declare function assertUploadFormat(format: UploadFormat): void;
907
1201
  /**
908
- * Exposes pagination fields for composition into other object schemas.
909
- * The shape stays derived from the schema to prevent contract divergence.
1202
+ * Defines one upload format while preserving its literal MIME and extension tuples.
1203
+ * Applications may enrich the returned object with their own display metadata.
910
1204
  */
911
- declare const zodPaginationShape: {
912
- offset: z$1.ZodDefault<z$1.ZodCoercedNumber<unknown>>;
913
- limit: z$1.ZodDefault<z$1.ZodCoercedNumber<unknown>>;
914
- };
915
- //#endregion
916
- //#region src/zod-search/zod-search.types.d.ts
1205
+ declare function defineUploadFormat<const TFormat extends UploadFormat>(format: TFormat): TFormat;
917
1206
  /**
918
- * TypeScript output produced after successful pagination validation.
919
- * Defaulted fields are represented as required numeric properties.
1207
+ * Defines one shared upload policy while preserving its literal format tuple.
1208
+ * The resulting preset can drive schemas, picker hints, and batch validation.
920
1209
  */
921
- type ZodPaginationOptions = z.infer<typeof zodPaginationSchema>;
1210
+ declare function defineUploadPreset<const TFormats extends readonly UploadFormat[]>(preset: UploadPreset<TFormats>): UploadPreset<TFormats>;
1211
+ //#endregion
1212
+ //#region src/upload/upload.schemas.d.ts
922
1213
  /**
923
- * Feature flags shared by both supported search schema composition modes.
924
- * Literal values are preserved in the resulting runtime and static shapes.
1214
+ * Builds a reusable Zod schema for one uploaded file with format and size.
1215
+ * MIME matching is strict unless extension fallback is explicitly enabled.
925
1216
  */
926
- type ZodSearchFeatureOptions<TQueryEnabled extends boolean, TPaginationEnabled extends boolean> = {
927
- /**
928
- * Controls whether an optional non-empty `query` field is generated.
929
- * The field is enabled when this option is omitted from the call.
930
- */
931
- queryEnabled?: TQueryEnabled;
932
- /**
933
- * Controls whether a required `pagination` object is generated.
934
- * The field is enabled when this option is omitted from the call.
935
- */
936
- paginationEnabled?: TPaginationEnabled;
937
- };
1217
+ declare function zodUploadFileSchema(options: UploadFileValidationOptions): z.ZodFile;
1218
+ //#endregion
1219
+ //#region src/upload/upload.utilities.d.ts
938
1220
  /**
939
- * Configuration used to compose a reusable search request schema.
940
- * Exactly one source must be provided for the resulting `where` field.
941
- *
942
- * `filters` is the concise mode that applies partial and non-empty rules.
943
- * `whereSchema` accepts a fully prepared schema with custom Zod effects.
1221
+ * Extracts a normalized trailing extension from a complete file name.
1222
+ * Returns an empty string when no valid dot-delimited suffix exists.
944
1223
  */
945
- type ZodSearchSchemaOptions<TShape extends z.ZodRawShape = never, TWhereSchema extends z.ZodType<Record<string, unknown>> = never, TQueryEnabled extends boolean = true, TPaginationEnabled extends boolean = true> = ZodSearchFeatureOptions<TQueryEnabled, TPaginationEnabled> & ({
946
- /**
947
- * Object schema whose fields become optional filters inside `where`.
948
- * The factory requires one defined value whenever `where` is present.
949
- */
950
- filters: z.ZodObject<TShape>;
951
- /** Prevents combining automatic filters with a prepared schema. */
952
- whereSchema?: never;
953
- } | {
954
- /** Prevents combining a prepared schema with automatic filters. */
955
- filters?: never;
956
- /**
957
- * Prepared schema used directly to validate the `where` object.
958
- * Its refinements, transforms, and inferred output are preserved.
959
- */
960
- whereSchema: TWhereSchema;
961
- });
962
- //#endregion
963
- //#region src/zod-search/zod-search.schemas.d.ts
1224
+ declare function getFileExtension(fileName: string): string;
964
1225
  /**
965
- * Optional text query shared by search request contracts.
966
- * Provided values are trimmed and must contain visible text.
1226
+ * Normalizes a configured extension to a lowercase dot-prefixed value.
1227
+ * Existing prefixes remain intact so repeated normalization is stable.
967
1228
  */
968
- declare const zodSearchQuerySchema: z$1.ZodOptional<z$1.ZodString>;
1229
+ declare function normalizeFileExtension(extension: string): string;
969
1230
  /**
970
- * Makes every supplied filter optional while requiring one defined value.
971
- * Top-level optionality is added later for both composition modes equally.
1231
+ * Compares a concrete MIME type with an exact or wildcard configuration.
1232
+ * Wildcards match every subtype belonging to the configured media group.
972
1233
  */
973
- declare const createZodSearchWhereSchema: <TShape extends z$1.ZodRawShape>(filters: z$1.ZodObject<TShape>) => z$1.ZodPipe<z$1.ZodObject<{ -readonly [k in keyof TShape]: z$1.ZodOptional<TShape[k]>; }, z$1.core.$strip>, z$1.ZodTransform<Awaited<AtLeastOne<z$1.core.$InferObjectOutput<{ -readonly [k in keyof TShape]: z$1.ZodOptional<TShape[k]>; }, {}>, keyof z$1.core.$InferObjectOutput<{ -readonly [k in keyof TShape]: z$1.ZodOptional<TShape[k]>; }, {}>>>, z$1.core.$InferObjectOutput<{ -readonly [k in keyof TShape]: z$1.ZodOptional<TShape[k]>; }, {}>>>;
1234
+ declare function matchesMimeType(fileMimeType: string, configuredMimeType: string): boolean;
974
1235
  /**
975
- * Empty schema shape used when a search feature is explicitly disabled.
976
- * Intersections remove disabled fields without widening enabled branches.
1236
+ * Checks whether a file MIME type belongs to one selected format.
1237
+ * File names and extensions cannot make an unsupported MIME type valid.
977
1238
  */
978
- type ZodDisabledSearchShape = Record<never, never>;
1239
+ declare function isFileMimeTypeSupported(file: File, formats: readonly UploadFormat[]): boolean;
979
1240
  /**
980
- * Resolves the schema used by `where` from the selected composition mode.
981
- * Prepared schemas remain untouched, including their effects and output.
1241
+ * Checks whether a file extension belongs to one selected format.
1242
+ * The comparison is case-insensitive and requires a complete suffix.
982
1243
  */
983
- type ZodSearchWhereSchema<TShape extends z$1.ZodRawShape, TWhereSchema extends z$1.ZodType<Record<string, unknown>>> = [TWhereSchema] extends [never] ? ReturnType<typeof createZodSearchWhereSchema<TShape>> : TWhereSchema;
1244
+ declare function isFileExtensionSupported(file: File, formats: readonly UploadFormat[]): boolean;
984
1245
  /**
985
- * Schema-level shape assembled from the selected source and feature flags.
986
- * Keeping Zod schemas here makes runtime composition the contract source.
1246
+ * Checks whether a file satisfies the format policy selected by one validation boundary.
1247
+ * MIME matching remains strict unless the caller explicitly enables extension fallback.
987
1248
  */
988
- type ZodSearchShape<TShape extends z$1.ZodRawShape, TWhereSchema extends z$1.ZodType<Record<string, unknown>>, TQueryEnabled extends boolean, TPaginationEnabled extends boolean> = {
989
- where: z$1.ZodOptional<ZodSearchWhereSchema<TShape, TWhereSchema>>;
990
- } & (TQueryEnabled extends false ? ZodDisabledSearchShape : {
991
- query: typeof zodSearchQuerySchema;
992
- }) & (TPaginationEnabled extends false ? ZodDisabledSearchShape : {
993
- pagination: typeof zodPaginationSchema;
994
- });
1249
+ declare function isFileFormatSupported(file: File, options: UploadFormatValidationOptions): boolean;
995
1250
  /**
996
- * Builds a strict schema for reusable search request contracts.
997
- * The optional `where` object must contain one defined filter.
998
- *
999
- * Query is optional and non-empty; pagination is required by default.
1000
- * Literal feature flags update both runtime and inferred static shapes.
1001
- *
1002
- * Pass `filters` for automatic partial and non-empty validation, or use
1003
- * `whereSchema` to preserve a prepared schema with custom Zod effects.
1004
- *
1005
- * @example
1006
- * const assetSearchSchema = zodSearchSchema({
1007
- * filters: assetSchema.pick({ status: true }),
1008
- * });
1009
- *
1010
- * const refinedAssetSearchSchema = zodSearchSchema({
1011
- * whereSchema: zodAtLeastOne(assetSchema.pick({ status: true }).partial()),
1012
- * });
1251
+ * Builds a native file-picker hint from configured MIME types and extensions.
1252
+ * Duplicate values are removed while their configuration order is retained.
1013
1253
  */
1014
- declare const zodSearchSchema: <const TShape extends z$1.ZodRawShape = never, const TWhereSchema extends z$1.ZodType<Record<string, unknown>> = never, const TQueryEnabled extends boolean = true, const TPaginationEnabled extends boolean = true>(options: ZodSearchSchemaOptions<TShape, TWhereSchema, TQueryEnabled, TPaginationEnabled>) => z$1.ZodObject<ZodSearchShape<TShape, TWhereSchema, TQueryEnabled, TPaginationEnabled> extends (infer T) ? { -readonly [P in keyof T]: T[P]; } : never, z$1.core.$strict>;
1254
+ declare function createUploadAccept(formats: readonly UploadFormat[]): string;
1015
1255
  //#endregion
1016
- //#region src/zod-validation/zod-validation.types.d.ts
1017
- type StringifiablePayloadValue = string | number | boolean | bigint | Date;
1256
+ //#region src/upload/upload.validation.d.ts
1018
1257
  /**
1019
- * Recursively transforms payload values to strings while preserving container structure.
1020
- * Nullable and omitted members remain unchanged for transport-layer omission handling.
1258
+ * Validates one file against configured format and size constraints.
1259
+ * Returns the first stable error key or nothing for a valid file.
1021
1260
  */
1022
- type StringifiedPayload<TValue> = TValue extends null | undefined ? TValue : TValue extends StringifiablePayloadValue ? string : TValue extends readonly (infer TItem)[] ? StringifiedPayload<TItem>[] : TValue extends object ? { [TKey in keyof TValue]: StringifiedPayload<TValue[TKey]>; } : string;
1261
+ declare function validateUploadFile(file: File, options: UploadFileValidationOptions): UploadValidationError | undefined;
1023
1262
  /**
1024
- * Utility type that ensures at least one property from the specified
1025
- * keys of a given type T is required, while the rest remain optional.
1026
- *
1027
- * This is useful for scenarios where you want to enforce that at least one
1028
- * of several optional (nullable) properties must be provided in an object.
1029
- *
1030
- * @example
1031
- * type Example = AtLeastOne<{ a?: string; b?: number; c?: boolean }>;
1032
- * // Valid: { a: "hello" }, { b: 42 }, { c: true }, { a: "hello", b: 42 }
1033
- * // Invalid: {}, { a: undefined, b: undefined, c: undefined }
1263
+ * Validates an incoming collection while preserving every accepted file.
1264
+ * Returns accepted entries and the first rejection key from the batch.
1034
1265
  */
1035
- type AtLeastOne<T, Keys extends keyof T = keyof T> = Keys extends keyof T ? Simplify<Required<Pick<T, Keys>> & Partial<Omit<T, Keys>>> : never;
1266
+ declare function validateUploadFiles(incomingFiles: readonly File[], options: UploadFilesValidationOptions): UploadFilesValidationResult;
1036
1267
  //#endregion
1037
- //#region src/zod-validation/zod-validation.refiners.d.ts
1038
- /**
1039
- * Wraps a partial Zod object schema with:
1040
- * 1. A runtime check ensuring at least one field is non-undefined.
1041
- * 2. A `.transform()` that narrows the output type to `AtLeastOne<T>`,
1042
- * making it directly assignable to domain `*Select` and `*Update` types without casting.
1043
- *
1044
- * @example
1045
- * zQuery(zodAtLeastOne(userSelectSchema)) // result: UserSelect ✓
1046
- */
1047
- declare const zodAtLeastOne: <T extends ZodObject<ZodRawShape>>(schema: T) => z$1.ZodPipe<T, z$1.ZodTransform<Awaited<AtLeastOne<z$1.TypeOf<T>>>, z$1.TypeOf<T>>>;
1268
+ //#region src/zod/zod.errors.d.ts
1269
+ declare const zodErrors: {
1270
+ atLeastOneRequired: () => {
1271
+ code: 'custom';
1272
+ message: string;
1273
+ };
1274
+ };
1275
+ type ZodErrorCode = keyof typeof zodErrors;
1048
1276
  //#endregion
1049
- //#region src/zod-validation/zod-validation.parsing.d.ts
1050
- declare const parseQueryValue: (value: unknown) => unknown;
1277
+ //#region src/zod/zod.refiners.d.ts
1051
1278
  /**
1052
- * Preprocesses query-like values before Zod validation.
1053
- *
1054
- * Query parameters are string-based by nature, even when they semantically represent
1055
- * numbers or booleans. This helper converts only clear primitive values, allowing
1056
- * regular schemas like `z.number()` and `z.boolean()` to validate query input directly.
1279
+ * Requires one defined property while preserving the supplied Zod object validation.
1280
+ * The output type reflects semantic presence and retains valid falsy or nullable values.
1057
1281
  *
1058
1282
  * @example
1059
- * const schema = asQuery(z.object({
1060
- * page: z.number().int().positive(),
1061
- * isActive: z.boolean(),
1062
- * }));
1063
- *
1064
- * schema.parse({ page: '2', isActive: 'true' });
1065
- * // { page: 2, isActive: true }
1066
- */
1067
- declare const asQuery: <T extends z$1.ZodTypeAny>(schema: T) => z$1.ZodPreprocess<T>;
1068
- /**
1069
- * Recursively converts payload values to strings without changing container structure.
1070
- * Objects and arrays are copied while `null` and `undefined` retain omission semantics.
1071
- *
1072
- * @example
1073
- * stringifyPayloadValues({ page: 2, enabled: true });
1074
- * // { page: '2', enabled: 'true' }
1075
- */
1076
- declare function stringifyPayloadValues<TValue>(value: TValue): StringifiedPayload<TValue>;
1077
- //#endregion
1078
- //#region src/zod-validation/zod-validation.utilities.d.ts
1079
- /**
1080
- * Checks whether a value is a plain record backed by `Object.prototype`.
1081
- * Arrays, null, dates, collections, and custom class instances are rejected.
1283
+ * const patchSchema = zodAtLeastOne(z.object({ name: z.string().optional() }));
1082
1284
  */
1083
- declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
1285
+ declare function zodAtLeastOne<TSchema extends z.ZodObject<z.ZodRawShape>>(schema: TSchema): z.ZodPipe<TSchema, z.ZodTransform<Awaited<AtLeastOne<z.TypeOf<TSchema>>>, z.TypeOf<TSchema>>>;
1084
1286
  //#endregion
1085
- export { APIContractData, APIContractError, APIContractErrorCode, APIContractResult, APIError, APIRequestError, APISuccess, AtLeastOne, DEFAULT_HMAC_ALGORITHM, DEFAULT_HMAC_ENCODING, DEFAULT_UPLOAD_MAX_FILE_SIZE, EXCEPTION_STATUS_CODES, ErrorCodeOf, ExceptionStatusCode, FetchResult, FileFormat, FileFormatConfig, HMACAlgorithm, HMACEncoding, HMACInput, HMACService, HMACServiceOptions, HonoFileRespondOptions, HonoRespondOptions, JWTServiceOptions, JWTSignOptions, LogLevel, MeasuredExecution, Payload, PayloadSchema, REDACTED_LOG_VALUE, ReplaceDotsWithUnderscores, ReplaceHyphensWithUnderscores, SUCCESS_STATUS_CODES, Simplify, StringEnumRecord, StringifiedPayload, SuccessStatusCode, UploadFilesValidationOptions, UploadFilesValidationResult, UploadPreset, UploadValidationError, ZodBulkExcludeSelection, ZodBulkIncludeSelection, ZodBulkSelection, ZodJWTService, ZodPaginationOptions, ZodSearchSchemaOptions, ZodUploadFileSchemaOptions, asQuery, createStringEnumRecord, createUploadAccept, createZodSearchWhereSchema, decodeBase64, decodeHMACSignature, defineUploadPreset, documentUploadPreset, encodeBase64, encodeHMACSignature, failure, fetchAndThrow, fetchSafely, fileFormat, fileFormatsArray, fileFormatsConfig, fileFormatsRecord, fileRespond, formatTime, generateRandomString, getColoredHTTPStatus, getFileExtension, getFormattedDate, getFormattedTime, getUTCOffset, getZonedTime, hmacAlgorithm, hmacAlgorithmsArray, hmacAlgorithmsRecord, hmacEncoding, hmacEncodingsArray, hmacEncodingsRecord, httpStatusColors, imageTransparentUploadPreset, imageUploadPreset, isFileExtensionSupported, isFileFormatSupported, isFileMimeTypeSupported, isPlainObject, log, logLevel, logLevelColors, logLevelsArray, logLevelsRecord, loggingMiddleware, matchesMimeType, measureExecutionTime, normalizeFileExtension, onHandlerError, parseQueryValue, redactSensitiveJSON, redactSensitiveSearchParams, respond, safeExecute, sensitiveLogKeyParts, sqlWhere, stringifyPayloadValues, success, toHMACBytes, uploadValidationError, uploadValidationErrorsArray, uploadValidationErrorsRecord, validateUploadFile, validateUploadFiles, zodAtLeastOne, zodBulkSelectionSchema, zodPaginationSchema, zodPaginationShape, zodSearchQuerySchema, zodSearchSchema, zodUploadFileSchema };
1287
+ export { AtLeastOne, CreateLoggerOptions, DEFAULT_DATETIME_TIMEZONE, DEFAULT_HMAC_ALGORITHM, DEFAULT_HMAC_ENCODING, DEFAULT_JWT_ALGORITHM, DEFAULT_JWT_EXPIRATION_SECONDS, DEFAULT_RANDOM_STRING_LENGTH, DEFAULT_RETRY_MAX_ATTEMPTS, DateTimeZoneOptions, DrizzleErrorCode, ERROR_RESPONSE_STATUSES, ErrorCodeOf, ErrorResponse, ErrorResponseStatus, ExactlyOne, ExecuteWithTimeoutOptions, Execution, ExecutionErrorCode, ExecutionResult, FormatTimeOptions, FormattedDateOptions, HMACAlgorithm, HMACEncoding, HMACErrorCode, HMACInput, HMACSecret, HMACService, HMACServiceOptions, HONO_LOGGING_SERVICE, HONO_REQUEST_ID_HEADER, HTTPRequestLogOptions, HonoErrorCode, HonoErrorHandlerOptions, HonoFileRespondOptions, HonoLoggingMiddlewareOptions, HonoRequestIdMiddlewareOptions, HonoRespondOptions, JWTErrorCode, type JWTPayload, JWTPayloadSchema, JWTService, JWTServiceOptions, JWTSignOptions, LOG_BODY_PREVIEW_EDGE_LENGTH, LogLevel, LogSink, LoggingErrorCode, MULTIPART_LOG_BODY, MeasuredExecution, RANDOM_ALPHANUMERIC_CHARACTERS, RANDOM_BYTE_BATCH_SIZE, REDACTED_LOG_VALUE, RandomErrorCode, ReplaceDotsWithUnderscores, ReplaceHyphensWithUnderscores, ResolvedResponse, ResponseData, ResponseError, ResponseErrorCode, ResponseFailure, ResponseFailureCode, ResponseKind, ResponseResult, RetryExecutionContext, RetryExecutionOptions, SQLWhereConditions, SUCCESS_RESPONSE_STATUSES, ScopedLogger, SeparateCamelCase, Simplify, StringEnumKey, StringEnumRecord, SuccessResponse, SuccessResponseStatus, UploadErrorCode, UploadFileValidationOptions, UploadFilesValidationOptions, UploadFilesValidationResult, UploadFormat, UploadFormatValidationOptions, UploadPreset, UploadValidationError, ZodErrorCode, assertRandomStringLength, assertUploadFormat, captureExecution, createErrorResponse, createHTTPRequestBodyPreview, createHonoErrorHandler, createLogger, createLoggingMiddleware, createRequestIdMiddleware, createStringEnumRecord, createSuccessResponse, createUploadAccept, decodeBase64, decodeHMACSignature, defineUploadFormat, defineUploadPreset, drizzleErrors, encodeBase64, encodeHMACSignature, executeWithTimeout, executionErrors, fileRespond, formatHTTPRequestLog, formatTime, generateRandomString, getColoredHTTPStatus, getFileExtension, getFormattedDate, getFormattedTime, getHonoRequestId, getUTCOffset, getZonedTime, hmacAlgorithm, hmacAlgorithmsArray, hmacAlgorithmsRecord, hmacEncoding, hmacEncodingsArray, hmacEncodingsRecord, hmacErrors, honoErrors, httpStatusColors, isErrorResponse, isErrorResponseStatus, isFileExtensionSupported, isFileFormatSupported, isFileMimeTypeSupported, isPlainObject, isResponseErrorCode, isSuccessResponse, isSuccessResponseStatus, jwtErrors, log, logLevel, logLevelColors, logLevelsArray, logLevelsRecord, loggingErrors, loggingMiddleware, matchesMimeType, measureExecutionTime, normalizeFileExtension, normalizeLogError, randomErrors, redactSensitiveJSON, redactSensitiveSearchParams, redactSensitiveValue, requestIdMiddleware, resolveResponse, respond, responseErrors, responseKind, responseKindsArray, responseKindsRecord, retryExecution, safeExecute, sensitiveLogKeyParts, sqlWhere, toHMACBytes, unwrapResponse, uploadErrors, uploadValidationError, uploadValidationErrorsArray, uploadValidationErrorsRecord, validateJWTExpirationSeconds, validateUploadFile, validateUploadFiles, waitForRetry, zodAtLeastOne, zodErrors, zodUploadFileSchema };