@develit-io/backend-sdk 5.6.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +142 -31
- package/dist/index.d.cts +96 -61
- package/dist/index.d.mts +96 -61
- package/dist/index.d.ts +96 -61
- package/dist/index.mjs +137 -31
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,9 @@ require('http-status-codes');
|
|
|
7
7
|
const z = require('zod/v4/core');
|
|
8
8
|
const h3 = require('h3');
|
|
9
9
|
const consola = require('consola');
|
|
10
|
-
const
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const crypto$1 = require('node:crypto');
|
|
12
|
+
const path = require('path');
|
|
11
13
|
const superjson = require('superjson');
|
|
12
14
|
|
|
13
15
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
@@ -25,6 +27,9 @@ function _interopNamespaceCompat(e) {
|
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
const z__namespace = /*#__PURE__*/_interopNamespaceCompat(z);
|
|
30
|
+
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
|
|
31
|
+
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto$1);
|
|
32
|
+
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
|
|
28
33
|
const superjson__default = /*#__PURE__*/_interopDefaultCompat(superjson);
|
|
29
34
|
|
|
30
35
|
const base = {
|
|
@@ -210,28 +215,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
210
215
|
}
|
|
211
216
|
}
|
|
212
217
|
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
218
|
+
const asNonEmpty = (arr) => {
|
|
219
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
function createAuditLogWriter(table) {
|
|
223
|
+
return (logs, db) => {
|
|
224
|
+
if (logs.length === 0) return [];
|
|
225
|
+
const auditRecords = logs.map((log) => ({
|
|
226
|
+
...log,
|
|
227
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
228
|
+
id: crypto.randomUUID()
|
|
229
|
+
}));
|
|
230
|
+
return [db.insert(table).values(auditRecords)];
|
|
231
|
+
};
|
|
226
232
|
}
|
|
227
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
228
233
|
|
|
229
|
-
|
|
230
|
-
|
|
234
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
235
|
+
const key = crypto__default.createHash("sha256").update(uniqueKey).digest();
|
|
236
|
+
const nameHmac = crypto__default.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
237
|
+
const hmac = crypto__default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
238
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
239
|
+
}
|
|
240
|
+
const getDatabaseIdFromWrangler = () => {
|
|
241
|
+
try {
|
|
242
|
+
const wranglerPath = path__default.resolve("./wrangler.jsonc");
|
|
243
|
+
const wranglerContent = fs__default.readFileSync(wranglerPath, "utf-8");
|
|
244
|
+
const cleanContent = wranglerContent.replace(
|
|
245
|
+
/\/\*[\s\S]*?\*\/|\/\/.*$/gm,
|
|
246
|
+
""
|
|
247
|
+
);
|
|
248
|
+
const config = JSON.parse(cleanContent);
|
|
249
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
250
|
+
let databaseId;
|
|
251
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
252
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
253
|
+
console.log(
|
|
254
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
if (!databaseId) {
|
|
258
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
259
|
+
console.log(
|
|
260
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (!databaseId) {
|
|
264
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
265
|
+
}
|
|
266
|
+
return databaseId;
|
|
267
|
+
} catch (err) {
|
|
268
|
+
console.warn(
|
|
269
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
270
|
+
);
|
|
271
|
+
}
|
|
231
272
|
};
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
return
|
|
273
|
+
const isRemoteEnvironment = () => {
|
|
274
|
+
const environment = process.env.ENVIRONMENT;
|
|
275
|
+
return environment && environment !== "localhost";
|
|
276
|
+
};
|
|
277
|
+
const getLocalD1 = (databaseId) => {
|
|
278
|
+
const name = durableObjectNamespaceIdFromName(
|
|
279
|
+
"miniflare-D1DatabaseObject",
|
|
280
|
+
databaseId
|
|
281
|
+
);
|
|
282
|
+
const searchPaths = [
|
|
283
|
+
path__default.resolve("../../.wrangler"),
|
|
284
|
+
// Root of monorepo
|
|
285
|
+
path__default.resolve("./.wrangler")
|
|
286
|
+
// Current directory
|
|
287
|
+
];
|
|
288
|
+
for (const basePath of searchPaths) {
|
|
289
|
+
try {
|
|
290
|
+
const dbFile = fs__default.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
291
|
+
if (dbFile) {
|
|
292
|
+
const url = path__default.resolve(basePath, dbFile);
|
|
293
|
+
console.log(`Found D1 database at: ${url}`);
|
|
294
|
+
return url;
|
|
295
|
+
} else {
|
|
296
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
297
|
+
}
|
|
298
|
+
} catch {
|
|
299
|
+
console.warn(`Could not search in ${basePath}`);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
const getCredentials = () => {
|
|
305
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
306
|
+
if (isRemoteEnvironment()) {
|
|
307
|
+
return {
|
|
308
|
+
driver: "d1-http",
|
|
309
|
+
dbCredentials: {
|
|
310
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
311
|
+
databaseId,
|
|
312
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
} else {
|
|
316
|
+
return {
|
|
317
|
+
dbCredentials: {
|
|
318
|
+
url: getLocalD1(databaseId)
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const drizzleD1Config = {
|
|
324
|
+
schema: "./src/database/schema/",
|
|
325
|
+
out: "./src/database/migrations/",
|
|
326
|
+
dialect: "sqlite",
|
|
327
|
+
...getCredentials()
|
|
235
328
|
};
|
|
236
329
|
|
|
237
330
|
class DatabaseTransaction {
|
|
@@ -296,17 +389,33 @@ const defineCommand = (handler) => {
|
|
|
296
389
|
});
|
|
297
390
|
};
|
|
298
391
|
|
|
299
|
-
function
|
|
300
|
-
return
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
return [db.insert(table).values(auditRecords)];
|
|
308
|
-
};
|
|
392
|
+
function first(rows) {
|
|
393
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
394
|
+
}
|
|
395
|
+
function firstOrError(rows) {
|
|
396
|
+
if (rows.length === 0) {
|
|
397
|
+
throw new Error("Query did not return any data.");
|
|
398
|
+
}
|
|
399
|
+
return rows[0];
|
|
309
400
|
}
|
|
401
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
402
|
+
|
|
403
|
+
const drizzlePgConfig = {
|
|
404
|
+
schema: "./src/database/schema/",
|
|
405
|
+
out: "./src/database/migrations/",
|
|
406
|
+
dialect: "postgresql",
|
|
407
|
+
dbCredentials: {
|
|
408
|
+
url: process.env.DATABASE_URL
|
|
409
|
+
},
|
|
410
|
+
migrations: {
|
|
411
|
+
table: "__drizzle_migrations",
|
|
412
|
+
schema: "public"
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
417
|
+
return baseDelaySeconds ** attempts;
|
|
418
|
+
};
|
|
310
419
|
|
|
311
420
|
const service = (serviceName) => {
|
|
312
421
|
return function(constructor) {
|
|
@@ -455,7 +564,9 @@ exports.createAuditLogWriter = createAuditLogWriter;
|
|
|
455
564
|
exports.createInternalError = createInternalError;
|
|
456
565
|
exports.defineCommand = defineCommand;
|
|
457
566
|
exports.develitWorker = develitWorker;
|
|
458
|
-
exports.
|
|
567
|
+
exports.drizzleD1Config = drizzleD1Config;
|
|
568
|
+
exports.drizzlePgConfig = drizzlePgConfig;
|
|
569
|
+
exports.durableObjectNamespaceIdFromName = durableObjectNamespaceIdFromName;
|
|
459
570
|
exports.first = first;
|
|
460
571
|
exports.firstOrError = firstOrError;
|
|
461
572
|
exports.handleAction = handleAction;
|
package/dist/index.d.cts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.d.mts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.mjs
CHANGED
|
@@ -5,7 +5,9 @@ import 'http-status-codes';
|
|
|
5
5
|
import * as z from 'zod/v4/core';
|
|
6
6
|
import { createError } from 'h3';
|
|
7
7
|
import { consola } from 'consola';
|
|
8
|
-
import
|
|
8
|
+
import fs from 'fs';
|
|
9
|
+
import crypto$1 from 'node:crypto';
|
|
10
|
+
import path from 'path';
|
|
9
11
|
import superjson from 'superjson';
|
|
10
12
|
|
|
11
13
|
const base = {
|
|
@@ -191,28 +193,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
191
193
|
}
|
|
192
194
|
}
|
|
193
195
|
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
196
|
+
const asNonEmpty = (arr) => {
|
|
197
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
function createAuditLogWriter(table) {
|
|
201
|
+
return (logs, db) => {
|
|
202
|
+
if (logs.length === 0) return [];
|
|
203
|
+
const auditRecords = logs.map((log) => ({
|
|
204
|
+
...log,
|
|
205
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
206
|
+
id: crypto.randomUUID()
|
|
207
|
+
}));
|
|
208
|
+
return [db.insert(table).values(auditRecords)];
|
|
209
|
+
};
|
|
207
210
|
}
|
|
208
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
209
211
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
213
|
+
const key = crypto$1.createHash("sha256").update(uniqueKey).digest();
|
|
214
|
+
const nameHmac = crypto$1.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
215
|
+
const hmac = crypto$1.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
216
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
217
|
+
}
|
|
218
|
+
const getDatabaseIdFromWrangler = () => {
|
|
219
|
+
try {
|
|
220
|
+
const wranglerPath = path.resolve("./wrangler.jsonc");
|
|
221
|
+
const wranglerContent = fs.readFileSync(wranglerPath, "utf-8");
|
|
222
|
+
const cleanContent = wranglerContent.replace(
|
|
223
|
+
/\/\*[\s\S]*?\*\/|\/\/.*$/gm,
|
|
224
|
+
""
|
|
225
|
+
);
|
|
226
|
+
const config = JSON.parse(cleanContent);
|
|
227
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
228
|
+
let databaseId;
|
|
229
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
230
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
231
|
+
console.log(
|
|
232
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
if (!databaseId) {
|
|
236
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
237
|
+
console.log(
|
|
238
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if (!databaseId) {
|
|
242
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
243
|
+
}
|
|
244
|
+
return databaseId;
|
|
245
|
+
} catch (err) {
|
|
246
|
+
console.warn(
|
|
247
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
212
250
|
};
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
return
|
|
251
|
+
const isRemoteEnvironment = () => {
|
|
252
|
+
const environment = process.env.ENVIRONMENT;
|
|
253
|
+
return environment && environment !== "localhost";
|
|
254
|
+
};
|
|
255
|
+
const getLocalD1 = (databaseId) => {
|
|
256
|
+
const name = durableObjectNamespaceIdFromName(
|
|
257
|
+
"miniflare-D1DatabaseObject",
|
|
258
|
+
databaseId
|
|
259
|
+
);
|
|
260
|
+
const searchPaths = [
|
|
261
|
+
path.resolve("../../.wrangler"),
|
|
262
|
+
// Root of monorepo
|
|
263
|
+
path.resolve("./.wrangler")
|
|
264
|
+
// Current directory
|
|
265
|
+
];
|
|
266
|
+
for (const basePath of searchPaths) {
|
|
267
|
+
try {
|
|
268
|
+
const dbFile = fs.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
269
|
+
if (dbFile) {
|
|
270
|
+
const url = path.resolve(basePath, dbFile);
|
|
271
|
+
console.log(`Found D1 database at: ${url}`);
|
|
272
|
+
return url;
|
|
273
|
+
} else {
|
|
274
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
275
|
+
}
|
|
276
|
+
} catch {
|
|
277
|
+
console.warn(`Could not search in ${basePath}`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const getCredentials = () => {
|
|
283
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
284
|
+
if (isRemoteEnvironment()) {
|
|
285
|
+
return {
|
|
286
|
+
driver: "d1-http",
|
|
287
|
+
dbCredentials: {
|
|
288
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
289
|
+
databaseId,
|
|
290
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
} else {
|
|
294
|
+
return {
|
|
295
|
+
dbCredentials: {
|
|
296
|
+
url: getLocalD1(databaseId)
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
const drizzleD1Config = {
|
|
302
|
+
schema: "./src/database/schema/",
|
|
303
|
+
out: "./src/database/migrations/",
|
|
304
|
+
dialect: "sqlite",
|
|
305
|
+
...getCredentials()
|
|
216
306
|
};
|
|
217
307
|
|
|
218
308
|
class DatabaseTransaction {
|
|
@@ -277,17 +367,33 @@ const defineCommand = (handler) => {
|
|
|
277
367
|
});
|
|
278
368
|
};
|
|
279
369
|
|
|
280
|
-
function
|
|
281
|
-
return
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return [db.insert(table).values(auditRecords)];
|
|
289
|
-
};
|
|
370
|
+
function first(rows) {
|
|
371
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
372
|
+
}
|
|
373
|
+
function firstOrError(rows) {
|
|
374
|
+
if (rows.length === 0) {
|
|
375
|
+
throw new Error("Query did not return any data.");
|
|
376
|
+
}
|
|
377
|
+
return rows[0];
|
|
290
378
|
}
|
|
379
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
380
|
+
|
|
381
|
+
const drizzlePgConfig = {
|
|
382
|
+
schema: "./src/database/schema/",
|
|
383
|
+
out: "./src/database/migrations/",
|
|
384
|
+
dialect: "postgresql",
|
|
385
|
+
dbCredentials: {
|
|
386
|
+
url: process.env.DATABASE_URL
|
|
387
|
+
},
|
|
388
|
+
migrations: {
|
|
389
|
+
table: "__drizzle_migrations",
|
|
390
|
+
schema: "public"
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
395
|
+
return baseDelaySeconds ** attempts;
|
|
396
|
+
};
|
|
291
397
|
|
|
292
398
|
const service = (serviceName) => {
|
|
293
399
|
return function(constructor) {
|
|
@@ -425,4 +531,4 @@ function develitWorker(Worker) {
|
|
|
425
531
|
return DevelitWorker;
|
|
426
532
|
}
|
|
427
533
|
|
|
428
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
534
|
+
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|