@develit-io/backend-sdk 5.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
2
+ import { AnyPgTable } from 'drizzle-orm/pg-core';
3
+ import * as drizzle_orm from 'drizzle-orm';
4
+ import { ExtractTablesWithRelations, DBQueryConfig, BuildQueryResult } from 'drizzle-orm';
5
+ import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
6
+ import { AnySQLiteTable } from 'drizzle-orm/sqlite-core';
7
+ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
8
+ export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
9
+ import * as z from 'zod/v4/core';
10
+ import { Queue } from '@cloudflare/workers-types';
11
+ import * as drizzle_kit from 'drizzle-kit';
12
+ import { BatchItem } from 'drizzle-orm/batch';
13
+ import { DrizzleD1Database } from 'drizzle-orm/d1';
14
+
15
+ declare const base: {
16
+ id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
17
+ createdAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>;
18
+ modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"modified_at">>>;
19
+ };
20
+ declare const basePostgres: {
21
+ id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>;
22
+ createdAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
23
+ modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"modified_at">>>;
24
+ };
25
+
26
+ type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
27
+ interface InternalError {
28
+ status: InternalErrorResponseStatus;
29
+ code: string;
30
+ message: string;
31
+ }
32
+ interface IRPCResponse<T> {
33
+ status: StatusCodes;
34
+ message: string;
35
+ data: T | null | undefined;
36
+ error: boolean;
37
+ phrase?: ReasonPhrases;
38
+ }
39
+ interface GatewayResponse<T> {
40
+ status?: number;
41
+ message: string;
42
+ data?: T;
43
+ }
44
+
45
+ /**
46
+ * Utility type to infer possible relation includes (`with`) for a given table.
47
+ * This helps define which relations (one-to-many, many-to-one) can be included in a query.
48
+ *
49
+ * @template Tables - The Drizzle ORM schema object.
50
+ * @template TableName - The table for which relations should be inferred.
51
+ */
52
+ type IncludeRelation<Tables extends Record<string, unknown>, TableName extends keyof ExtractTablesWithRelations<Tables>> = DBQueryConfig<'one' | 'many', boolean, ExtractTablesWithRelations<Tables>, ExtractTablesWithRelations<Tables>[TableName]>['with'];
53
+ /**
54
+ * Infers the result type of Drizzle ORM select query with optional relations.
55
+ * This ensures correct TypeScript inference when querying tables and their relations.
56
+ *
57
+ * @template Tables - The Drizzle ORM schema object.
58
+ * @template TableName - The table for which the query result is being inferred.
59
+ * @template With - (Optional) Specifies which relations should be included in the result.
60
+ */
61
+ type InferResultType<Tables extends Record<string, unknown>, TableName extends keyof ExtractTablesWithRelations<Tables>, With extends IncludeRelation<Tables, TableName> | undefined = undefined> = BuildQueryResult<ExtractTablesWithRelations<Tables>, ExtractTablesWithRelations<Tables>[TableName], {
62
+ with: With;
63
+ }>;
64
+
65
+ declare const ibanZodSchema: z.$ZodString<unknown>;
66
+ declare const swiftZodSchema: z.$ZodString<unknown>;
67
+
68
+ interface CommandLogPayload<T = string> {
69
+ action: T;
70
+ actorId: string;
71
+ actorUsername?: string;
72
+ entityId?: string;
73
+ }
74
+
75
+ interface CommandItem<TAuditAction = string> {
76
+ command: BatchItem<'sqlite'>;
77
+ logPayload: CommandLogPayload<TAuditAction>;
78
+ id: string;
79
+ }
80
+
81
+ declare const handleActionResponse: <T>({ error, status, message, data, }: {
82
+ error: boolean;
83
+ status: number;
84
+ message: string;
85
+ data: T;
86
+ }) => T & {};
87
+
88
+ type Constructor<T = {}> = abstract new (...args: any[]) => T;
89
+ interface DevelitWorkerMethods {
90
+ name: string;
91
+ action: string;
92
+ fetch(): Promise<Response>;
93
+ log(data: object, identifier?: string): void;
94
+ logQueuePush(data: object): void;
95
+ logQueuePull(data: object): void;
96
+ logQueueRetries(data: object): void;
97
+ logInput(data: object): void;
98
+ logOutput(data: object): void;
99
+ logError(error: object): void;
100
+ pushToQueue<T>(queue: Queue, message: T | T[]): Promise<void>;
101
+ handleInput<T extends z.$ZodType>(args: {
102
+ input: z.infer<T>;
103
+ schema: T;
104
+ }): z.infer<T>;
105
+ handleAction<TInput, TOutput>(input: {
106
+ data: TInput;
107
+ schema: z.$ZodType<TInput>;
108
+ } | null, options: ActionHandlerOptions<TInput, TOutput>, actionExecution: (validatedInput: TInput | null) => Promise<TOutput>): Promise<IRPCResponse<TOutput>>;
109
+ }
110
+ declare function develitWorker<TWorker extends Constructor>(Worker: TWorker): TWorker & Constructor<DevelitWorkerMethods>;
111
+
112
+ interface ActionHandlerOptions<TInput, TOutput> {
113
+ /**
114
+ * Success message to return in the response
115
+ * @default "Operation completed successfully."
116
+ */
117
+ successMessage?: string;
118
+ /**
119
+ * Transform function to modify the input before logging
120
+ * Useful for removing sensitive data from logs
121
+ */
122
+ logInputTransform?: (input: TInput) => object;
123
+ /**
124
+ * Transform function to modify the output before logging
125
+ * Useful for removing sensitive data from logs
126
+ */
127
+ logOutputTransform?: (data: TOutput) => object;
128
+ /**
129
+ * Skip input validation if true
130
+ * @default false
131
+ */
132
+ skipValidation?: boolean;
133
+ /**
134
+ * Skip logging if true
135
+ * @default false
136
+ */
137
+ skipLogging?: boolean;
138
+ }
139
+ /**
140
+ * Generic action handler that eliminates boilerplate code for service actions
141
+ *
142
+ * @template TInput - The input type for the action
143
+ * @template TOutput - The output type for the action
144
+ * @param worker - The worker instance (this context)
145
+ * @param input - The input data for the action
146
+ * @param options - Configuration options for the handler
147
+ * @param actionExecution - The actual business logic function
148
+ * @returns Promise resolving to IRPCResponse<TOutput>
149
+ */
150
+ declare function handleAction<TInput, TOutput>(worker: DevelitWorkerMethods, input: {
151
+ data: TInput;
152
+ schema: z.$ZodType<TInput>;
153
+ } | null, options: ActionHandlerOptions<TInput, TOutput> | undefined, actionExecution: (validatedInput: TInput | null) => Promise<TOutput>): Promise<IRPCResponse<TOutput>>;
154
+ /**
155
+ * Utility type to extract the validated input type from a schema
156
+ */
157
+ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
158
+ /**
159
+ * Utility type for action execution functions
160
+ */
161
+ type ActionExecution<TInput, TOutput> = (input: TInput) => Promise<TOutput>;
162
+
163
+ declare const drizzleConfig: drizzle_kit.Config;
164
+ declare function first<T>(rows: T[]): T | undefined;
165
+ declare function firstOrError<T>(rows: T[]): T;
166
+ declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
167
+
168
+ declare const createInternalError: (error: unknown, details?: {
169
+ status?: InternalErrorResponseStatus;
170
+ code?: string;
171
+ message?: string;
172
+ }) => InternalError;
173
+ declare const isInternalError: (error: unknown) => error is InternalError;
174
+
175
+ declare const RPCResponse: {
176
+ /**
177
+ * ✅ Constructs a successful RPC response.
178
+ *
179
+ * This method wraps the provided data in a standardized response format,
180
+ * ensuring consistency across API responses.
181
+ *
182
+ * @template T - The type of the response data.
183
+ * @param message - Response message
184
+ * @param detail - Optional -> Contains data and status code
185
+ * @returns An `IRPCResponse<T>` with the provided data and no error.
186
+ */
187
+ ok<T>(message: string, detail?: {
188
+ data?: T;
189
+ status?: StatusCodes;
190
+ }): IRPCResponse<T>;
191
+ /**
192
+ * ❌ Constructs a generic service error response.
193
+ *
194
+ * This method logs the error and returns a standardized error response.
195
+ *
196
+ * @template T - The expected response type (typically ignored in errors).
197
+ * @param error - An `RPCError` containing error details.
198
+ * @returns An `IRPCResponse<T>` with `null` data and the provided error.
199
+ */
200
+ serviceError<T>(error: InternalError): IRPCResponse<T>;
201
+ /**
202
+ * ❌ Constructs a validation error response (HTTP 400).
203
+ *
204
+ * This is a convenience method for returning validation errors.
205
+ * It internally delegates to `serviceError()`.
206
+ *
207
+ * @template T - The expected response type (typically ignored in errors).
208
+ * @param error - An `RPCError` representing a validation failure.
209
+ * @returns An `IRPCResponse<T>` with `null` data and the provided error.
210
+ */
211
+ validationError<T>(error: InternalError): IRPCResponse<T>;
212
+ };
213
+
214
+ /**
215
+ * A utility function to handle operations and return a standardized result.
216
+ *
217
+ * This function wraps the call and ensures that both the resolved value
218
+ * and any potential errors are captured in a structured tuple format.
219
+ *
220
+ * @template T - The type of the expected result.
221
+ * @returns A call that resolves to a tuple containing:
222
+ * - The resolved data (`T | null`) if successful.
223
+ * - An `RPCError` object (`RPCError | null`) if an error occurs.
224
+ */
225
+ type Result<T> = [data: T | null, error: InternalError | null];
226
+ /**
227
+ * Executes a given promise and returns the result in a structured format.
228
+ *
229
+ * Instead of throwing errors, this function catches them and returns
230
+ * a standardized `RPCError` object, making error handling more predictable.
231
+ *
232
+ * @template T - The expected return type of the promise.
233
+ * @param promise - A promise representing an asynchronous operation.
234
+ * @returns A promise that resolves to a tuple:
235
+ * - `[data, null]` if the operation succeeds.
236
+ * - `[null, error]` if the operation fails.
237
+ */
238
+ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
239
+ /**
240
+ * Executes a given function and returns the result in a structured format.
241
+ *
242
+ * Instead of throwing errors, this function catches them and returns
243
+ * a standardized `RPCError` object, making error handling more predictable.
244
+ *
245
+ * @template T - The expected return type of the function.
246
+ * @param function - A function representing an synchronous operation.
247
+ * @returns A a tuple:
248
+ * - `[data, null]` if the operation succeeds.
249
+ * - `[null, error]` if the operation fails.
250
+ */
251
+ declare const useResultSync: <T>(fn: () => T) => Result<T>;
252
+
253
+ declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
254
+
255
+ interface AuditLogPayload<T> {
256
+ action: T;
257
+ actorId: string;
258
+ actorUsername?: string;
259
+ service: string;
260
+ entityId?: string;
261
+ }
262
+
263
+ interface Command<TAuditAction = string> {
264
+ handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
265
+ }
266
+ type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
267
+ declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
268
+ command: BatchItem<"sqlite">;
269
+ logPayload: CommandLogPayload<TAuditAction>;
270
+ id: string;
271
+ }) => CommandFactory<TParams, TAuditAction>;
272
+
273
+ declare class DatabaseTransaction<TAuditAction = string> {
274
+ private db;
275
+ private serviceName?;
276
+ private auditLogWriter?;
277
+ private commands;
278
+ private logs;
279
+ private ids;
280
+ constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
281
+ enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
282
+ execute(commandItem: Command<TAuditAction>): Promise<void>;
283
+ executeAll(): Promise<void>;
284
+ getLogs(): readonly AuditLogPayload<TAuditAction>[];
285
+ getIds(): readonly string[];
286
+ getCommandsCount(): number;
287
+ }
288
+
289
+ type AuditLogTable = AnySQLiteTable | AnyPgTable;
290
+ type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
291
+ /**
292
+ * Creates an audit log writer function that inserts audit logs into a specified table
293
+ *
294
+ * @param table - The Drizzle table definition for audit logs
295
+ * @returns A function that can be passed to DatabaseTransaction constructor
296
+ *
297
+ * @example
298
+ * ```typescript
299
+ * import { createAuditLogWriter } from '@develit-io/workers-sdk'
300
+ * import { auditLogsTable } from './schema'
301
+ *
302
+ * const auditWriter = createAuditLogWriter(auditLogsTable)
303
+ *
304
+ * // Use in initializeDB
305
+ * this.initializeDB(env.DB, schema, auditWriter)
306
+ * ```
307
+ */
308
+ declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
309
+
310
+ declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
311
+ new (...args: any[]): {
312
+ name: string;
313
+ };
314
+ } & T;
315
+
316
+ /**
317
+ * Method decorator that sets `this.action` to a specific name before method execution.
318
+ *
319
+ * This is used to enforce logging context and input validation via `handleActionInput`.
320
+ */
321
+ declare const action: (name: string) => MethodDecorator;
322
+
323
+ interface WithRetryCounterOptions {
324
+ baseDelay: number;
325
+ }
326
+ type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
327
+ declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
328
+
329
+ export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleConfig, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
330
+ export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };