@danylohotvianskyi/bobra-framework 0.1.3 → 0.1.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 (48) hide show
  1. package/batteries/auth/hash.ts +5 -5
  2. package/batteries/auth/token-metadata.ts +6 -6
  3. package/batteries/auth/token-validation.ts +5 -6
  4. package/core/config.ts +9 -1
  5. package/core/discovery.ts +4 -0
  6. package/core/factory.ts +292 -15
  7. package/db/migrate.ts +2 -2
  8. package/dist/batteries/auth/hash.d.ts +2 -1
  9. package/dist/batteries/auth/hash.js +5 -4
  10. package/dist/batteries/auth/hash.js.map +1 -1
  11. package/dist/batteries/auth/token-metadata.d.ts +3 -3
  12. package/dist/batteries/auth/token-metadata.js +5 -4
  13. package/dist/batteries/auth/token-metadata.js.map +1 -1
  14. package/dist/batteries/auth/token-validation.d.ts +2 -2
  15. package/dist/batteries/auth/token-validation.js +3 -4
  16. package/dist/batteries/auth/token-validation.js.map +1 -1
  17. package/dist/core/config.d.ts +3 -0
  18. package/dist/core/config.js +6 -1
  19. package/dist/core/config.js.map +1 -1
  20. package/dist/core/discovery.d.ts +3 -0
  21. package/dist/core/discovery.js.map +1 -1
  22. package/dist/core/factory.d.ts +23 -3
  23. package/dist/core/factory.js +241 -15
  24. package/dist/core/factory.js.map +1 -1
  25. package/dist/db/migrate.js +2 -2
  26. package/dist/db/migrate.js.map +1 -1
  27. package/dist/middleware/ensure-api-token.d.ts +1 -1
  28. package/dist/middleware/ensure-api-token.js +1 -1
  29. package/dist/middleware/ensure-api-token.js.map +1 -1
  30. package/dist/node/generate-wrangler-config.d.ts +4 -1
  31. package/dist/node/generate-wrangler-config.js +5 -1
  32. package/dist/node/generate-wrangler-config.js.map +1 -1
  33. package/dist/node/index.d.ts +1 -1
  34. package/dist/node/index.js +2 -2
  35. package/dist/node/index.js.map +1 -1
  36. package/middleware/ensure-api-token.ts +2 -2
  37. package/node/generate-wrangler-config.ts +9 -1
  38. package/node/index.ts +2 -2
  39. package/package.json +9 -8
  40. package/dist/core/env-files.d.ts +0 -17
  41. package/dist/core/env-files.js +0 -39
  42. package/dist/core/env-files.js.map +0 -1
  43. package/dist/db/schema.d.ts +0 -8
  44. package/dist/db/schema.js +0 -10
  45. package/dist/db/schema.js.map +0 -1
  46. package/dist/scripts/generate-wrangler-config.d.ts +0 -94
  47. package/dist/scripts/generate-wrangler-config.js +0 -370
  48. package/dist/scripts/generate-wrangler-config.js.map +0 -1
@@ -1,4 +1,5 @@
1
1
  import { getLogger } from '../../logging/logger';
2
+ import { isSQLite, type DatabaseContext } from '../../db/client';
2
3
 
3
4
  // Token hash algorithm configuration
4
5
  const HASH_CONFIG = {
@@ -17,15 +18,14 @@ export async function hashToken(token: string, salt: string): Promise<string> {
17
18
 
18
19
  // Find a token record by computing hash against all stored records
19
20
  export async function findTokenByHash(
20
- db: any,
21
+ ctx: DatabaseContext<any>,
21
22
  token: string,
22
23
  schema: any,
23
- useSqlite?: boolean
24
24
  ) {
25
25
  try {
26
- const t = useSqlite ? schema.tokensSqlite : schema.tokens;
27
- const tokenRecords = await db.select({
28
- id: (t as any).uid,
26
+ const t = isSQLite(ctx) ? schema.tokensSqlite : schema.tokens;
27
+ const tokenRecords = await (ctx.db as any).select({
28
+ uid: (t as any).uid,
29
29
  tokenHash: t.tokenHash,
30
30
  tokenSalt: t.tokenSalt,
31
31
  expiresAt: t.expiresAt,
@@ -1,20 +1,20 @@
1
1
  import { eq } from 'drizzle-orm';
2
+ import { isSQLite, type DatabaseContext } from '../../db/client';
2
3
 
3
4
  // Database client interface for token metadata update
4
5
  export interface TokenMetadataUpdateClient {
5
- db: any;
6
+ ctx: DatabaseContext<any>;
6
7
  schema: any;
7
- sql: any;
8
8
  }
9
9
 
10
10
  // Update the lastUsedAt timestamp for a token
11
11
  export async function updateTokenLastUsed(
12
12
  client: TokenMetadataUpdateClient,
13
- tokenId: string
13
+ tokenUid: string
14
14
  ): Promise<void> {
15
- const useSqlite = !!(client as any).useSqlite;
15
+ const useSqlite = isSQLite(client.ctx);
16
16
  const table = useSqlite ? client.schema.tokensSqlite : client.schema.tokens;
17
- await client.db.update(table)
17
+ await (client.ctx.db as any).update(table)
18
18
  .set({ lastUsedAt: useSqlite ? new Date().toISOString() : new Date() })
19
- .where(eq((table as any).uid, tokenId));
19
+ .where(eq((table as any).uid, tokenUid));
20
20
  }
@@ -2,7 +2,7 @@ import { TokenMetadataUpdateClient, updateTokenLastUsed } from './token-metadata
2
2
  import { hashToken, findTokenByHash } from './hash';
3
3
 
4
4
  export interface TokenRecord {
5
- id: string;
5
+ uid: string;
6
6
  tokenHash: string;
7
7
  tokenSalt: string;
8
8
  expiresAt: Date;
@@ -18,7 +18,7 @@ export interface TokenValidationResult {
18
18
  valid: boolean;
19
19
  reason?: string;
20
20
  tokenInfo?: {
21
- id: string;
21
+ uid: string;
22
22
  expiresAt: Date;
23
23
  lastUsedAt?: Date;
24
24
  ipAddresses?: string[];
@@ -32,8 +32,7 @@ export async function validateToken(
32
32
  provider: TokenValidationProvider
33
33
  ): Promise<TokenValidationResult> {
34
34
  try {
35
- const useSqlite = !!(provider as any).useSqlite;
36
- const tokenRecord = await findTokenByHash(provider.db, token, provider.schema, useSqlite);
35
+ const tokenRecord = await findTokenByHash(provider.ctx, token, provider.schema);
37
36
 
38
37
  if (!tokenRecord) {
39
38
  return {
@@ -62,12 +61,12 @@ export async function validateToken(
62
61
  const isValid = computedHash === tokenRecord.tokenHash;
63
62
 
64
63
  if (isValid) {
65
- await updateTokenLastUsed(provider, tokenRecord.id);
64
+ await updateTokenLastUsed(provider, tokenRecord.uid);
66
65
  const isInit = tokenRecord.initToken === true || tokenRecord.initToken === 1;
67
66
  return {
68
67
  valid: true,
69
68
  tokenInfo: {
70
- id: tokenRecord.id,
69
+ uid: tokenRecord.uid,
71
70
  expiresAt: tokenRecord.expiresAt,
72
71
  lastUsedAt: tokenRecord.lastUsedAt,
73
72
  ipAddresses: tokenRecord.ipAddresses,
package/core/config.ts CHANGED
@@ -98,6 +98,9 @@ export interface WorkerConfig {
98
98
  external_url?: string;
99
99
  }>;
100
100
  kv_namespaces?: WorkerKvNamespaceConfig[];
101
+ triggers?: {
102
+ crons?: string[];
103
+ };
101
104
  vars?: Record<string, string | number | boolean | JSONValue>;
102
105
  cf_routes?: CloudflareRoute[];
103
106
  observability?: {
@@ -157,7 +160,7 @@ export interface AppConfig {
157
160
  // Default configuration — apps should override these via their config.yml
158
161
  export const defaultConfig: AppConfig = {
159
162
  cors: {
160
- origin: ['http://localhost:3000', 'http://localhost:8700'],
163
+ origin: ['*'],
161
164
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
162
165
  allowHeaders: ['Content-Type', 'Authorization'],
163
166
  },
@@ -179,6 +182,11 @@ export const defaultConfig: AppConfig = {
179
182
  description: 'Central routing worker',
180
183
  main: 'src/index.ts',
181
184
  routes: [],
185
+ observability: {
186
+ logs: {
187
+ enabled: false
188
+ }
189
+ }
182
190
  },
183
191
  };
184
192
 
package/core/discovery.ts CHANGED
@@ -10,6 +10,8 @@ export interface AppHandler {
10
10
  version: string;
11
11
  routes: Hono<any>;
12
12
  componentSchemas?: Record<string, any>;
13
+ /** Additional security schemes to declare in the handler's OpenAPI spec */
14
+ securitySchemes?: Record<string, any>;
13
15
  // Allow handlers to initialize their own logger with the worker's config
14
16
  initLogger?: (config: Partial<LoggerConfig>, context?: string, worker?: string, handler?: string) => void;
15
17
  // Allow handlers to perform async initialization (e.g., database connections)
@@ -20,6 +22,8 @@ export interface AppHandler {
20
22
  handlesQueue?: (queueName: string, configuredQueues: string[]) => boolean;
21
23
  // Let the handler mount directly on root path
22
24
  ignoreWorkerBasePath?: boolean;
25
+ // Optional scheduled handler
26
+ scheduled?: (event: any, env: any, ctx: any) => Promise<void> | void;
23
27
  }
24
28
 
25
29
  /**
package/core/factory.ts CHANGED
@@ -16,7 +16,87 @@ import {
16
16
  getServiceDiscovery,
17
17
  } from './config';
18
18
  import { serviceDiscoveryMiddleware } from '../network/service-discovery';
19
- import { openAPISpecs } from 'hono-openapi';
19
+ import { generateSpecs } from 'hono-openapi';
20
+
21
+ // Helper: collect schema $ref names referenced anywhere in the OpenAPI spec
22
+ function collectReferencedSchemaNames(obj: any): Set<string> {
23
+ const set = new Set<string>();
24
+ function scan(val: any) {
25
+ if (typeof val === 'object' && val !== null) {
26
+ for (const k in val) {
27
+ if (k === '$ref' && typeof val[k] === 'string') {
28
+ const m = val[k].match(/^#\/components\/schemas\/([A-Za-z0-9_.-]+)/);
29
+ if (m && m[1]) set.add(m[1]);
30
+ } else {
31
+ scan(val[k]);
32
+ }
33
+ }
34
+ }
35
+ }
36
+ scan(obj);
37
+ return set;
38
+ }
39
+
40
+ function pruneComponents(full: any, paths: any, keepAlways: string[] = []) {
41
+ const result: any = { ...(full.components || {}) };
42
+ const schemas = (full.components && full.components.schemas) || {};
43
+
44
+ // Start with schemas referenced directly from paths
45
+ const refs = collectReferencedSchemaNames(paths);
46
+
47
+ // Always-keep schemas should be included in the starting set as well
48
+ for (const name of keepAlways) {
49
+ refs.add(name);
50
+ }
51
+
52
+ const kept: Record<string, any> = {};
53
+
54
+ // Traverse schema references transitively using a work queue to ensure
55
+ // nested dependencies are not pruned.
56
+ const toVisit: string[] = Array.from(refs);
57
+ while (toVisit.length > 0) {
58
+ const name = toVisit.pop() as string;
59
+ const schema = schemas[name];
60
+
61
+ if (!schema || kept[name]) {
62
+ continue;
63
+ }
64
+
65
+ // Keep this schema
66
+ kept[name] = schema;
67
+
68
+ // Find any schemas it references and add them to the queue if not already seen
69
+ const nestedRefs = collectReferencedSchemaNames(schema);
70
+ for (const dep of nestedRefs) {
71
+ if (!refs.has(dep)) {
72
+ refs.add(dep);
73
+ toVisit.push(dep);
74
+ }
75
+ }
76
+ }
77
+
78
+ result.schemas = kept;
79
+ return result;
80
+ }
81
+
82
+ export interface OpenAPISpecOptions {
83
+ /** The path where the OpenAPI spec will be served (e.g. '/openapi', '/internal/openapi') */
84
+ path?: string;
85
+ /** Return true to exclude an operation from the generated OpenAPI spec */
86
+ excludeEndpoint?: (path: string, method: string, operation: any) => boolean;
87
+ /** Exclude operations that have any of these tags (e.g. ['internal']) */
88
+ excludeTags?: string[];
89
+ /** Whether or not to prune unreferenced OpenAPI component schemas (defaults to true if exclusions are used) */
90
+ pruneComponents?: boolean;
91
+ /** An array of schema names to always keep in the OpenAPI spec if pruneComponents is true */
92
+ pruneComponentsKeepAlways?: string[];
93
+ /** Additional security schemes to add to the OpenAPI spec */
94
+ securitySchemes?: Record<string, any>;
95
+ }
96
+
97
+ export interface WorkerOptions {
98
+ openapi?: OpenAPISpecOptions | OpenAPISpecOptions[];
99
+ }
20
100
 
21
101
  // Worker environment interface
22
102
  export interface WorkerEnv {
@@ -26,7 +106,7 @@ export interface WorkerEnv {
26
106
  }
27
107
 
28
108
  // Create a new worker instance with common middleware
29
- export async function createWorker(env?: WorkerEnv): Promise<AppWorker> {
109
+ export async function createWorker(env?: WorkerEnv, options?: WorkerOptions): Promise<AppWorker> {
30
110
  const app = new Hono<{ Bindings: WorkerEnv }>();
31
111
 
32
112
  const config = await loadConfig(env || {});
@@ -68,12 +148,13 @@ export async function createWorker(env?: WorkerEnv): Promise<AppWorker> {
68
148
  });
69
149
 
70
150
  // Worker-level OpenAPI with router base path prefixing
71
- app.get('/openapi', (() => {
151
+ (() => {
72
152
  const specApp = new Hono<{ Bindings: WorkerEnv }>();
73
153
  const routerBase = getRouterBasePath(config);
74
154
  // Mount the worker app under router base path so generated paths include router base
75
155
  specApp.route(routerBase === '/' ? '/' : routerBase, app);
76
- return openAPISpecs(specApp, {
156
+
157
+ const specOptions = {
77
158
  documentation: {
78
159
  info: {
79
160
  title: config.server.name,
@@ -81,10 +162,71 @@ export async function createWorker(env?: WorkerEnv): Promise<AppWorker> {
81
162
  description: config.server.description,
82
163
  },
83
164
  },
84
- });
85
- })());
165
+ } as any;
166
+
167
+ const specDefs = options?.openapi
168
+ ? (Array.isArray(options.openapi) ? options.openapi : [options.openapi])
169
+ : [{ path: '/openapi' }];
170
+
171
+ for (const specDef of specDefs) {
172
+ const specPath = specDef.path || '/openapi';
173
+ app.get(specPath, async (c) => {
174
+ const full = await generateSpecs(specApp, specOptions, undefined, c);
175
+ const { excludeEndpoint, excludeTags, pruneComponents: specPrune, securitySchemes } = specDef;
176
+ const hasExclusions = !!excludeEndpoint || (!!excludeTags && excludeTags.length > 0);
177
+
178
+ let finalSpec = full;
179
+
180
+ if (hasExclusions) {
181
+ const filtered: any = { ...full, paths: {} };
182
+ for (const [path, ops] of Object.entries(full.paths || {})) {
183
+ const keepOps: any = {};
184
+ for (const [method, op] of Object.entries(ops as any)) {
185
+ let shouldExclude = false;
186
+ if (excludeEndpoint && excludeEndpoint(path, method, op)) {
187
+ shouldExclude = true;
188
+ }
189
+ if (!shouldExclude && excludeTags && Array.isArray((op as any).tags)) {
190
+ if ((op as any).tags.some((tag: string) => excludeTags.includes(tag))) {
191
+ shouldExclude = true;
192
+ }
193
+ }
194
+
195
+ if (!shouldExclude) {
196
+ keepOps[method] = op;
197
+ }
198
+ }
199
+ if (Object.keys(keepOps).length > 0) filtered.paths[path] = keepOps;
200
+ }
201
+
202
+ const shouldPrune = specPrune ?? true;
203
+ if (shouldPrune) {
204
+ filtered.components = pruneComponents(full, filtered.paths, specDef.pruneComponentsKeepAlways || []);
205
+ } else {
206
+ filtered.components = full.components;
207
+ }
208
+ finalSpec = filtered;
209
+ }
210
+
211
+ if (securitySchemes) {
212
+ finalSpec = {
213
+ ...finalSpec,
214
+ components: {
215
+ ...(finalSpec.components || {}),
216
+ securitySchemes: {
217
+ ...(finalSpec.components?.securitySchemes || {}),
218
+ ...securitySchemes
219
+ }
220
+ }
221
+ };
222
+ }
223
+
224
+ return c.json(finalSpec, 200);
225
+ });
226
+ }
227
+ })();
86
228
 
87
- return new AppWorker(app, config, workerName, basePath);
229
+ return new AppWorker(app, config, workerName, basePath, options);
88
230
  }
89
231
 
90
232
  // Core worker class that manages handlers and their lifecycle
@@ -94,14 +236,16 @@ export class AppWorker {
94
236
  private config: AppConfig;
95
237
  private workerName: string;
96
238
  private basePath: string;
239
+ private options?: WorkerOptions;
97
240
  private initialized = false;
98
241
  private startupStack = new LogStack();
99
242
 
100
- constructor(app: Hono<{ Bindings: WorkerEnv }>, config: AppConfig, workerName: string, basePath: string) {
243
+ constructor(app: Hono<{ Bindings: WorkerEnv }>, config: AppConfig, workerName: string, basePath: string, options?: WorkerOptions) {
101
244
  this.app = app;
102
245
  this.config = config;
103
246
  this.workerName = workerName;
104
247
  this.basePath = basePath;
248
+ this.options = options;
105
249
 
106
250
  // Register this worker's main app in the unified registry
107
251
  appWorkerRegistry.registerMainApp(workerName, app);
@@ -222,6 +366,34 @@ export class AppWorker {
222
366
  };
223
367
  }
224
368
 
369
+ getScheduledFunction(): ((event: any, env: WorkerEnv, ctx: any) => Promise<void>) | undefined {
370
+ const scheduledHandlers = this.handlers.filter(h => typeof h.scheduled === 'function');
371
+
372
+ if (scheduledHandlers.length === 0) {
373
+ return undefined;
374
+ }
375
+
376
+ return async (event: any, env: WorkerEnv, ctx: any) => {
377
+ await this.initialize(env);
378
+
379
+ const promises = scheduledHandlers.map(async (handler) => {
380
+ try {
381
+ const logger = getLogger();
382
+ try {
383
+ logger.setHandler?.(handler.name);
384
+ await handler.scheduled!(event, env, ctx);
385
+ } finally {
386
+ logger.setHandler?.('');
387
+ }
388
+ } catch (error) {
389
+ getLogger().error(`Scheduled task error in handler ${handler.name}`, error instanceof Error ? error : new Error(String(error)));
390
+ }
391
+ });
392
+
393
+ await Promise.all(promises);
394
+ };
395
+ }
396
+
225
397
  // Add a handler to the worker
226
398
  async add(handlerModule: Promise<{ default: AppHandler }> | { default: AppHandler }): Promise<this> {
227
399
  try {
@@ -258,7 +430,7 @@ export class AppWorker {
258
430
  }
259
431
 
260
432
  if (handler.name !== 'api-docs') {
261
- this.app.get(`${handlerPath}/openapi`, (() => {
433
+ (() => {
262
434
  const specApp = new Hono<{ Bindings: WorkerEnv }>();
263
435
  const routerBase = getRouterBasePath(this.config);
264
436
  const prefix = routerBase === '/' ? handlerPath : `${routerBase}${handlerPath}`;
@@ -269,7 +441,12 @@ export class AppWorker {
269
441
  componentSchemas = handler.componentSchemas;
270
442
  }
271
443
 
272
- return openAPISpecs(specApp, {
444
+ let handlerSecuritySchemes = {};
445
+ if (handler.securitySchemes) {
446
+ handlerSecuritySchemes = handler.securitySchemes;
447
+ }
448
+
449
+ const specOptions = {
273
450
  documentation: {
274
451
  info: {
275
452
  title: `${this.config.server.name} - ${handler.name}`,
@@ -278,10 +455,72 @@ export class AppWorker {
278
455
  },
279
456
  components: {
280
457
  schemas: componentSchemas,
458
+ securitySchemes: handlerSecuritySchemes,
281
459
  },
282
460
  },
283
- });
284
- })());
461
+ } as any;
462
+
463
+ const specDefs = this.options?.openapi
464
+ ? (Array.isArray(this.options.openapi) ? this.options.openapi : [this.options.openapi])
465
+ : [{ path: '/openapi' }];
466
+
467
+ for (const specDef of specDefs) {
468
+ const specPath = specDef.path || '/openapi';
469
+ this.app.get(`${handlerPath}${specPath}`, async (c) => {
470
+ const full = await generateSpecs(specApp, specOptions, undefined, c);
471
+ const { excludeEndpoint, excludeTags, pruneComponents: specPrune, securitySchemes } = specDef;
472
+ const hasExclusions = !!excludeEndpoint || (!!excludeTags && excludeTags.length > 0);
473
+
474
+ let finalSpec = full;
475
+
476
+ if (hasExclusions) {
477
+ const filtered: any = { ...full, paths: {} };
478
+ for (const [path, ops] of Object.entries(full.paths || {})) {
479
+ const keepOps: any = {};
480
+ for (const [method, op] of Object.entries(ops as any)) {
481
+ let shouldExclude = false;
482
+ if (excludeEndpoint && excludeEndpoint(path, method, op)) {
483
+ shouldExclude = true;
484
+ }
485
+ if (!shouldExclude && excludeTags && Array.isArray((op as any).tags)) {
486
+ if ((op as any).tags.some((tag: string) => excludeTags.includes(tag))) {
487
+ shouldExclude = true;
488
+ }
489
+ }
490
+
491
+ if (!shouldExclude) {
492
+ keepOps[method] = op;
493
+ }
494
+ }
495
+ if (Object.keys(keepOps).length > 0) filtered.paths[path] = keepOps;
496
+ }
497
+
498
+ const shouldPrune = specPrune ?? true;
499
+ if (shouldPrune) {
500
+ filtered.components = pruneComponents(full, filtered.paths, specDef.pruneComponentsKeepAlways || []);
501
+ } else {
502
+ filtered.components = full.components;
503
+ }
504
+ finalSpec = filtered;
505
+ }
506
+
507
+ if (securitySchemes) {
508
+ finalSpec = {
509
+ ...finalSpec,
510
+ components: {
511
+ ...(finalSpec.components || {}),
512
+ securitySchemes: {
513
+ ...(finalSpec.components?.securitySchemes || {}),
514
+ ...securitySchemes
515
+ }
516
+ }
517
+ };
518
+ }
519
+
520
+ return c.json(finalSpec, 200);
521
+ });
522
+ }
523
+ })();
285
524
  }
286
525
 
287
526
  // Mount handler routes with base path
@@ -355,6 +594,7 @@ export class AppWorker {
355
594
  export() {
356
595
  const self = this;
357
596
  const queueFunction = this.getQueueFunction();
597
+ const scheduledFunction = this.getScheduledFunction();
358
598
 
359
599
  const workerExport: any = {
360
600
  async fetch(request: any, env: WorkerEnv, ctx: any) {
@@ -396,6 +636,15 @@ export class AppWorker {
396
636
  };
397
637
  }
398
638
 
639
+ if (scheduledFunction) {
640
+ workerExport.scheduled = async (event: any, env: WorkerEnv, ctx: any) => {
641
+ const globalVars = (self.config as any).vars || {};
642
+ const workerVars = (self.config.workers?.[self.workerName]?.vars) || {};
643
+ const mergedEnv = { ...env, ...globalVars, ...workerVars } as WorkerEnv;
644
+ await scheduledFunction(event, mergedEnv, ctx);
645
+ };
646
+ }
647
+
399
648
  return workerExport;
400
649
  }
401
650
  }
@@ -408,7 +657,8 @@ export function createHandlerArray(...handlers: AppHandler[]): Array<Promise<{ d
408
657
  // Convenience function to create a Cloudflare Worker from handler imports
409
658
  export function createCloudflareWorker(
410
659
  workerName: string,
411
- handlers: Array<Promise<{ default: AppHandler }> | { default: AppHandler }>
660
+ handlers: Array<Promise<{ default: AppHandler }> | { default: AppHandler }>,
661
+ options?: WorkerOptions
412
662
  ) {
413
663
  return {
414
664
  async fetch(request: Request, env: WorkerEnv, ctx: any): Promise<Response> {
@@ -423,7 +673,7 @@ export function createCloudflareWorker(
423
673
  const cfContinent = request.headers?.get?.('X-CF-Continent') || (request as any).cf?.continent;
424
674
  if (cfContinent) (workerEnv as any).__cfContinent = cfContinent;
425
675
 
426
- const worker = await createWorker(workerEnv);
676
+ const worker = await createWorker(workerEnv, options);
427
677
 
428
678
  for (const handler of handlers) {
429
679
  await worker.add(handler);
@@ -452,7 +702,7 @@ export function createCloudflareWorker(
452
702
  WORKER_NAME: workerName
453
703
  };
454
704
 
455
- const worker = await createWorker(workerEnv);
705
+ const worker = await createWorker(workerEnv, options);
456
706
 
457
707
  for (const handler of handlers) {
458
708
  await worker.add(handler);
@@ -471,6 +721,33 @@ export function createCloudflareWorker(
471
721
  getLogger().error(`${workerName} queue processing error`, error instanceof Error ? error : new Error(String(error)));
472
722
  throw error;
473
723
  }
724
+ },
725
+
726
+ async scheduled(event: any, env: WorkerEnv, ctx: any): Promise<void> {
727
+ try {
728
+ const workerEnv = {
729
+ ...env,
730
+ WORKER_NAME: workerName
731
+ };
732
+
733
+ const worker = await createWorker(workerEnv);
734
+
735
+ for (const handler of handlers) {
736
+ await worker.add(handler);
737
+ }
738
+ const scheduledFunction = worker.getScheduledFunction();
739
+
740
+ if (!scheduledFunction) {
741
+ getLogger().warn(`No scheduled function found in handlers for worker ${workerName}`);
742
+ return;
743
+ }
744
+
745
+ await scheduledFunction(event, workerEnv, ctx);
746
+
747
+ } catch (error) {
748
+ getLogger().error(`${workerName} scheduled task error`, error instanceof Error ? error : new Error(String(error)));
749
+ throw error;
750
+ }
474
751
  }
475
752
  };
476
753
  }
package/db/migrate.ts CHANGED
@@ -31,7 +31,7 @@
31
31
 
32
32
  import 'dotenv/config';
33
33
  import * as path from 'path';
34
- import { loadEnvFiles } from '../node';
34
+ import { loadEnvFiles } from '../node/index.js';
35
35
 
36
36
  // Load .dev.vars and .env files (Node.js only)
37
37
  if (typeof process !== 'undefined' && process.versions && process.versions.node) {
@@ -62,7 +62,7 @@ if (isNode) {
62
62
  import { drizzle } from 'drizzle-orm/postgres-js';
63
63
  import { migrate as pgMigrate } from 'drizzle-orm/postgres-js/migrator';
64
64
  import postgres from 'postgres';
65
- import { createPublicApiToken } from '../batteries/auth/token';
65
+ import { createPublicApiToken } from '../batteries/auth/token.js';
66
66
 
67
67
  // Configuration based on database engine
68
68
  const getConfig = () => {
@@ -1,2 +1,3 @@
1
+ import { type DatabaseContext } from '../../db/client';
1
2
  export declare function hashToken(token: string, salt: string): Promise<string>;
2
- export declare function findTokenByHash(db: any, token: string, schema: any, useSqlite?: boolean): Promise<any>;
3
+ export declare function findTokenByHash(ctx: DatabaseContext<any>, token: string, schema: any): Promise<any>;
@@ -1,4 +1,5 @@
1
1
  import { getLogger } from '../../logging/logger';
2
+ import { isSQLite } from '../../db/client';
2
3
  // Token hash algorithm configuration
3
4
  const HASH_CONFIG = {
4
5
  ALGORITHM: 'SHA-256'
@@ -12,11 +13,11 @@ export async function hashToken(token, salt) {
12
13
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
13
14
  }
14
15
  // Find a token record by computing hash against all stored records
15
- export async function findTokenByHash(db, token, schema, useSqlite) {
16
+ export async function findTokenByHash(ctx, token, schema) {
16
17
  try {
17
- const t = useSqlite ? schema.tokensSqlite : schema.tokens;
18
- const tokenRecords = await db.select({
19
- id: t.uid,
18
+ const t = isSQLite(ctx) ? schema.tokensSqlite : schema.tokens;
19
+ const tokenRecords = await ctx.db.select({
20
+ uid: t.uid,
20
21
  tokenHash: t.tokenHash,
21
22
  tokenSalt: t.tokenSalt,
22
23
  expiresAt: t.expiresAt,
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../batteries/auth/hash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,qCAAqC;AACrC,MAAM,WA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C,CAAC,CAAC,CAAC;gBAC3H,SAAS;YACX,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,SAAS,EAAE,CAAC,KAAK,CAAC,8BAA8B,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7G,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -1,6 +1,6 @@
1
+ import { type DatabaseContext } from '../../db/client';
1
2
  export interface TokenMetadataUpdateClient {
2
- db: any;
3
+ ctx: DatabaseContext<any>;
3
4
  schema: any;
4
- sql: any;
5
5
  }
6
- export declare function updateTokenLastUsed(client: TokenMetadataUpdateClient, tokenId: string): Promise<void>;
6
+ export declare function updateTokenLastUsed(client: TokenMetadataUpdateClient, tokenUid: string): Promise<void>;
@@ -1,10 +1,11 @@
1
1
  import { eq } from 'drizzle-orm';
2
+ import { isSQLite } from '../../db/client';
2
3
  // Update the lastUsedAt timestamp for a token
3
- export async function updateTokenLastUsed(client, tokenId) {
4
- const useSqlite = !!client.useSqlite;
4
+ export async function updateTokenLastUsed(client, tokenUid) {
5
+ const useSqlite = isSQLite(client.ctx);
5
6
  const table = useSqlite ? client.schema.tokensSqlite : client.schema.tokens;
6
- await client.db.update(table)
7
+ await client.ctx.db.update(table)
7
8
  .set({ lastUsedAt: useSqlite ? new Date().toISOString() : new Date() })
8
- .where(eq(table.uid, tokenId));
9
+ .where(eq(table.uid, tokenUid));
9
10
  }
10
11
  //# sourceMappingURL=token-metadata.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"token-metadata.js","sourceRoot":"","sources":["../../../batteries/auth/token-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AASjC,8CAA8C;AAC9C,MAAM,CAAC,KAAK,UAAU,mBA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